From a6013720e5d2222a08956a09be6b60668862687f Mon Sep 17 00:00:00 2001
From: Matthijs Kooijman
Date: Mon, 7 Jul 2014 15:22:49 +0200
Subject: [PATCH 01/73] Explicitely store a layout type for a library
Previously, the useRecursion and srcFolders were filled on library
creation, based on the existence of the src folder. Now, a layout
variable is set, and the useRecursion() and getSrcFolder() methods
change their return value based on the layout in use.
---
app/src/processing/app/packages/Library.java | 29 ++++++++++++--------
1 file changed, 17 insertions(+), 12 deletions(-)
diff --git a/app/src/processing/app/packages/Library.java b/app/src/processing/app/packages/Library.java
index 9c505fe4e41..bf69c4edd72 100644
--- a/app/src/processing/app/packages/Library.java
+++ b/app/src/processing/app/packages/Library.java
@@ -23,10 +23,11 @@ public class Library {
private String license;
private List architectures;
private File folder;
- private File srcFolder;
- private boolean useRecursion;
private boolean isLegacy;
+ private enum LibraryLayout { FLAT, RECURSIVE };
+ private LibraryLayout layout;
+
private static final List MANDATORY_PROPERTIES = Arrays
.asList(new String[] { "name", "version", "author", "maintainer",
"sentence", "paragraph", "url" });
@@ -82,12 +83,12 @@ private static Library createLibrary(File libFolder) throws IOException {
throw new IOException("Missing '" + p + "' from library");
// Check layout
- boolean useRecursion;
+ LibraryLayout layout;
File srcFolder = new File(libFolder, "src");
if (srcFolder.exists() && srcFolder.isDirectory()) {
// Layout with a single "src" folder and recursive compilation
- useRecursion = true;
+ layout = LibraryLayout.RECURSIVE;
File utilFolder = new File(libFolder, "utility");
if (utilFolder.exists() && utilFolder.isDirectory()) {
@@ -96,8 +97,7 @@ private static Library createLibrary(File libFolder) throws IOException {
}
} else {
// Layout with source code on library's root and "utility" folders
- srcFolder = libFolder;
- useRecursion = false;
+ layout = LibraryLayout.FLAT;
}
// Warn if root folder contains development leftovers
@@ -134,7 +134,6 @@ private static Library createLibrary(File libFolder) throws IOException {
Library res = new Library();
res.folder = libFolder;
- res.srcFolder = srcFolder;
res.name = properties.get("name").trim();
res.version = properties.get("version").trim();
res.author = properties.get("author").trim();
@@ -145,8 +144,8 @@ private static Library createLibrary(File libFolder) throws IOException {
res.category = category.trim();
res.license = license.trim();
res.architectures = archs;
- res.useRecursion = useRecursion;
res.isLegacy = false;
+ res.layout = layout;
return res;
}
@@ -154,8 +153,7 @@ private static Library createLegacyLibrary(File libFolder) {
// construct an old style library
Library res = new Library();
res.folder = libFolder;
- res.srcFolder = libFolder;
- res.useRecursion = false;
+ res.layout = LibraryLayout.FLAT;
res.name = libFolder.getName();
res.architectures = Arrays.asList("*");
res.isLegacy = true;
@@ -246,11 +244,18 @@ public String getMaintainer() {
}
public boolean useRecursion() {
- return useRecursion;
+ return (layout == LibraryLayout.RECURSIVE);
}
public File getSrcFolder() {
- return srcFolder;
+ switch (layout) {
+ case FLAT:
+ return folder;
+ case RECURSIVE:
+ return new File(folder, "src");
+ default:
+ return null; // Keep compiler happy :-(
+ }
}
public boolean isLegacy() {
From af0d8c7f5c258e7a6b4d2e9bf839958464d362c6 Mon Sep 17 00:00:00 2001
From: Matthijs Kooijman
Date: Tue, 8 Jul 2014 14:32:29 +0200
Subject: [PATCH 02/73] Let Sketch.getExtensions() return a List
This simplifies upcoming changes.
---
app/src/processing/app/Sketch.java | 12 ++++--------
1 file changed, 4 insertions(+), 8 deletions(-)
diff --git a/app/src/processing/app/Sketch.java b/app/src/processing/app/Sketch.java
index 4b2c6b44b4c..35109ab8072 100644
--- a/app/src/processing/app/Sketch.java
+++ b/app/src/processing/app/Sketch.java
@@ -170,7 +170,7 @@ protected void load() throws IOException {
code = new SketchCode[list.length];
- String[] extensions = getExtensions();
+ List extensions = getExtensions();
for (String filename : list) {
// Ignoring the dot prefix files is especially important to avoid files
@@ -1849,11 +1849,7 @@ public boolean isDefaultExtension(String what) {
* extensions.
*/
public boolean validExtension(String what) {
- String[] ext = getExtensions();
- for (int i = 0; i < ext.length; i++) {
- if (ext[i].equals(what)) return true;
- }
- return false;
+ return getExtensions().contains(what);
}
@@ -1873,8 +1869,8 @@ public List getHiddenExtensions() {
/**
* Returns a String[] array of proper extensions.
*/
- public String[] getExtensions() {
- return new String[] { "ino", "pde", "c", "cpp", "h" };
+ public List getExtensions() {
+ return Arrays.asList("ino", "pde", "c", "cpp", "h");
}
From 43dac3a902810784133cdfc190aab2ecbb90391c Mon Sep 17 00:00:00 2001
From: Matthijs Kooijman
Date: Tue, 8 Jul 2014 15:26:59 +0200
Subject: [PATCH 03/73] Use SketchCode.isExtension in more places
---
app/src/processing/app/EditorHeader.java | 2 +-
app/src/processing/app/Sketch.java | 16 +++-------------
2 files changed, 4 insertions(+), 14 deletions(-)
diff --git a/app/src/processing/app/EditorHeader.java b/app/src/processing/app/EditorHeader.java
index eef679f2ac9..f21228984f4 100644
--- a/app/src/processing/app/EditorHeader.java
+++ b/app/src/processing/app/EditorHeader.java
@@ -176,7 +176,7 @@ public void paintComponent(Graphics screen) {
for (int i = 0; i < sketch.getCodeCount(); i++) {
SketchCode code = sketch.getCode(i);
- String codeName = sketch.hideExtension(code.getExtension()) ?
+ String codeName = code.isExtension(sketch.getHiddenExtensions()) ?
code.getPrettyName() : code.getFileName();
// if modified, add the li'l glyph next to the name
diff --git a/app/src/processing/app/Sketch.java b/app/src/processing/app/Sketch.java
index 35109ab8072..bf31873bd02 100644
--- a/app/src/processing/app/Sketch.java
+++ b/app/src/processing/app/Sketch.java
@@ -425,7 +425,7 @@ protected void nameCode(String newName) {
if (renamingCode && currentIndex == 0) {
for (int i = 1; i < codeCount; i++) {
if (sanitaryName.equalsIgnoreCase(code[i].getPrettyName()) &&
- code[i].getExtension().equalsIgnoreCase("cpp")) {
+ code[i].isExtension("cpp")) {
Base.showMessage(_("Nope"),
I18n.format(
_("You can't rename the sketch to \"{0}\"\n" +
@@ -835,7 +835,7 @@ protected boolean saveAs() throws IOException {
// resaved (with the same name) to another location/folder.
for (int i = 1; i < codeCount; i++) {
if (newName.equalsIgnoreCase(code[i].getPrettyName()) &&
- code[i].getExtension().equalsIgnoreCase("cpp")) {
+ code[i].isExtension("cpp")) {
Base.showMessage(_("Nope"),
I18n.format(
_("You can't save the sketch as \"{0}\"\n" +
@@ -1818,21 +1818,11 @@ public boolean isReadOnly() {
// Breaking out extension types in order to clean up the code, and make it
// easier for other environments (like Arduino) to incorporate changes.
-
- /**
- * True if the specified extension should be hidden when shown on a tab.
- * For Processing, this is true for .pde files. (Broken out for subclasses.)
- */
- public boolean hideExtension(String what) {
- return getHiddenExtensions().contains(what);
- }
-
-
/**
* True if the specified code has the default file extension.
*/
public boolean hasDefaultExtension(SketchCode code) {
- return code.getExtension().equals(getDefaultExtension());
+ return code.isExtension(getDefaultExtension());
}
From e994c527294359b19fafbfa00f14585d80f7ef90 Mon Sep 17 00:00:00 2001
From: Matthijs Kooijman
Date: Tue, 8 Jul 2014 15:35:38 +0200
Subject: [PATCH 04/73] Don't store the extension in SketchCode
Nobody was using it anymore, except for checking against specific
extensions, which is easily done against the filename itself. This
prepares for some simplification of Sketch.load next.
---
app/src/processing/app/Sketch.java | 12 ++++++------
app/src/processing/app/SketchCode.java | 23 ++++++++++-------------
2 files changed, 16 insertions(+), 19 deletions(-)
diff --git a/app/src/processing/app/Sketch.java b/app/src/processing/app/Sketch.java
index bf31873bd02..3663e7322ca 100644
--- a/app/src/processing/app/Sketch.java
+++ b/app/src/processing/app/Sketch.java
@@ -192,7 +192,7 @@ protected void load() throws IOException {
// it would be otherwise possible to sneak in nasty filenames. [0116]
if (Sketch.isSanitaryName(base)) {
code[codeCount++] =
- new SketchCode(new File(folder, filename), extension);
+ new SketchCode(new File(folder, filename));
} else {
editor.console.message(I18n.format("File name {0} is invalid: ignored", filename), true, false);
}
@@ -487,7 +487,7 @@ protected void nameCode(String newName) {
}
}
- if (!current.renameTo(newFile, newExtension)) {
+ if (!current.renameTo(newFile)) {
Base.showWarning(_("Error"),
I18n.format(
_("Could not rename \"{0}\" to \"{1}\""),
@@ -531,7 +531,7 @@ protected void nameCode(String newName) {
editor.base.rebuildSketchbookMenus();
} else { // else if something besides code[0]
- if (!current.renameTo(newFile, newExtension)) {
+ if (!current.renameTo(newFile)) {
Base.showWarning(_("Error"),
I18n.format(
_("Could not rename \"{0}\" to \"{1}\""),
@@ -557,7 +557,7 @@ protected void nameCode(String newName) {
), e);
return;
}
- SketchCode newCode = new SketchCode(newFile, newExtension);
+ SketchCode newCode = new SketchCode(newFile);
//System.out.println("new code is named " + newCode.getPrettyName() + " " + newCode.getFile());
insertCode(newCode);
}
@@ -788,7 +788,7 @@ protected boolean renameCodeToInoExtension(File pdeFile) {
String pdeName = pdeFile.getPath();
pdeName = pdeName.substring(0, pdeName.length() - 4) + ".ino";
- return c.renameTo(new File(pdeName), "ino");
+ return c.renameTo(new File(pdeName));
}
return false;
}
@@ -1075,7 +1075,7 @@ public boolean addFile(File sourceFile) {
}
if (codeExtension != null) {
- SketchCode newCode = new SketchCode(destFile, codeExtension);
+ SketchCode newCode = new SketchCode(destFile);
if (replacement) {
replaceCode(newCode);
diff --git a/app/src/processing/app/SketchCode.java b/app/src/processing/app/SketchCode.java
index 096d37875eb..91a8232e8d3 100644
--- a/app/src/processing/app/SketchCode.java
+++ b/app/src/processing/app/SketchCode.java
@@ -25,10 +25,13 @@
package processing.app;
import java.io.*;
+import java.util.List;
+import java.util.Arrays;
import javax.swing.text.Document;
import static processing.app.I18n._;
+import processing.app.helpers.FileUtils;
/**
@@ -41,9 +44,6 @@ public class SketchCode {
/** File object for where this code is located */
private File file;
- /** Extension for this file (no dots, and in lowercase). */
- private String extension;
-
/** Text of the program text for this tab */
private String program;
@@ -70,9 +70,8 @@ public class SketchCode {
private int preprocOffset;
- public SketchCode(File file, String extension) {
+ public SketchCode(File file) {
this.file = file;
- this.extension = extension;
makePrettyName();
@@ -125,11 +124,10 @@ public boolean accept(File pathname) {
}
- protected boolean renameTo(File what, String ext) {
+ protected boolean renameTo(File what) {
boolean success = file.renameTo(what);
if (success) {
file = what;
- extension = ext;
makePrettyName();
}
return success;
@@ -151,13 +149,12 @@ public String getPrettyName() {
}
- public String getExtension() {
- return extension;
+ public boolean isExtension(String... extensions) {
+ return isExtension(Arrays.asList(extensions));
}
-
-
- public boolean isExtension(String what) {
- return extension.equals(what);
+
+ public boolean isExtension(List extensions) {
+ return FileUtils.hasExtension(file, extensions);
}
From 9bc1824b96468050c590e980327a079c6c8d7e59 Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Tue, 26 Aug 2014 16:31:06 +0200
Subject: [PATCH 05/73] Removed unused Base.getBoardsViaNetwork() and related
member.
---
app/src/processing/app/Base.java | 7 -------
1 file changed, 7 deletions(-)
diff --git a/app/src/processing/app/Base.java b/app/src/processing/app/Base.java
index dee3103de6d..fb7b302cff3 100644
--- a/app/src/processing/app/Base.java
+++ b/app/src/processing/app/Base.java
@@ -127,7 +127,6 @@ public class Base {
// int editorCount;
List editors = Collections.synchronizedList(new ArrayList());
Editor activeEditor;
- private final Map> boardsViaNetwork;
static File portableFolder = null;
static final String portableSketchbookFolder = "sketchbook";
@@ -310,8 +309,6 @@ protected static enum ACTION { GUI, NOOP, VERIFY, UPLOAD, GET_PREF };
public Base(String[] args) throws Exception {
platform.init(this);
- this.boardsViaNetwork = new ConcurrentHashMap>();
-
// Get the sketchbook path, and make sure it's set properly
String sketchbookPath = Preferences.get("sketchbook.path");
@@ -616,10 +613,6 @@ protected void processPrefArgument(String arg) {
Preferences.set(split[0], split[1]);
}
- public Map> getBoardsViaNetwork() {
- return new HashMap>(boardsViaNetwork);
- }
-
/**
* Post-constructor setup for the editor area. Loads the last
* sketch that was used (if any), and restores other Editor settings.
From dd911bc79d0511b40366228bc9ea1cba617966e0 Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Sun, 26 Jan 2014 23:13:01 +0100
Subject: [PATCH 06/73] Removed some trivial warnings
---
app/src/processing/app/AbstractMonitor.java | 1 +
app/src/processing/app/LastUndoableEditAwareUndoManager.java | 1 +
app/src/processing/app/NetworkMonitor.java | 3 +--
app/src/processing/app/SerialException.java | 1 +
app/src/processing/app/SerialMonitor.java | 1 +
app/src/processing/app/SerialNotFoundException.java | 3 +--
6 files changed, 6 insertions(+), 4 deletions(-)
diff --git a/app/src/processing/app/AbstractMonitor.java b/app/src/processing/app/AbstractMonitor.java
index 4394ca96401..9a3de6043b3 100644
--- a/app/src/processing/app/AbstractMonitor.java
+++ b/app/src/processing/app/AbstractMonitor.java
@@ -14,6 +14,7 @@
import static processing.app.I18n._;
+@SuppressWarnings("serial")
public abstract class AbstractMonitor extends JFrame implements MessageConsumer {
protected final JLabel noLineEndingAlert;
diff --git a/app/src/processing/app/LastUndoableEditAwareUndoManager.java b/app/src/processing/app/LastUndoableEditAwareUndoManager.java
index 336cfe15fff..0cd678a935b 100644
--- a/app/src/processing/app/LastUndoableEditAwareUndoManager.java
+++ b/app/src/processing/app/LastUndoableEditAwareUndoManager.java
@@ -5,6 +5,7 @@
import javax.swing.undo.UndoManager;
import javax.swing.undo.UndoableEdit;
+@SuppressWarnings("serial")
public class LastUndoableEditAwareUndoManager extends UndoManager {
private UndoableEdit lastUndoableEdit;
diff --git a/app/src/processing/app/NetworkMonitor.java b/app/src/processing/app/NetworkMonitor.java
index 73a973aad78..5f89382acf7 100644
--- a/app/src/processing/app/NetworkMonitor.java
+++ b/app/src/processing/app/NetworkMonitor.java
@@ -28,7 +28,6 @@ public class NetworkMonitor extends AbstractMonitor {
private MessageSiphon inputConsumer;
private Session session;
private Channel channel;
- private MessageSiphon errorConsumer;
private int connectionAttempts;
public NetworkMonitor(BoardPort port, Base base) {
@@ -98,7 +97,7 @@ private void tryConnect() throws JSchException, IOException {
channel.connect();
inputConsumer = new MessageSiphon(inputStream, this);
- errorConsumer = new MessageSiphon(errStream, this);
+ new MessageSiphon(errStream, this);
if (connectionAttempts > 1) {
SwingUtilities.invokeLater(new Runnable() {
diff --git a/app/src/processing/app/SerialException.java b/app/src/processing/app/SerialException.java
index d47e6018942..7fbc3e7ad03 100644
--- a/app/src/processing/app/SerialException.java
+++ b/app/src/processing/app/SerialException.java
@@ -22,6 +22,7 @@
import java.io.IOException;
+@SuppressWarnings("serial")
public class SerialException extends IOException {
public SerialException() {
super();
diff --git a/app/src/processing/app/SerialMonitor.java b/app/src/processing/app/SerialMonitor.java
index 49e7006a3a3..0be575ed262 100644
--- a/app/src/processing/app/SerialMonitor.java
+++ b/app/src/processing/app/SerialMonitor.java
@@ -27,6 +27,7 @@
import static processing.app.I18n._;
+@SuppressWarnings("serial")
public class SerialMonitor extends AbstractMonitor {
private final String port;
diff --git a/app/src/processing/app/SerialNotFoundException.java b/app/src/processing/app/SerialNotFoundException.java
index a3ab755b8a6..d8660c11000 100644
--- a/app/src/processing/app/SerialNotFoundException.java
+++ b/app/src/processing/app/SerialNotFoundException.java
@@ -1,5 +1,3 @@
-/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
/*
Copyright (c) 2007 David A. Mellis
@@ -20,6 +18,7 @@
package processing.app;
+@SuppressWarnings("serial")
public class SerialNotFoundException extends SerialException {
public SerialNotFoundException() {
super();
From 026dd50d8762beed458df945c2920cf8000dad8e Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Sun, 26 Jan 2014 22:03:01 +0100
Subject: [PATCH 07/73] Removed some warning from Editor class
---
app/src/processing/app/Editor.java | 19 ++++++++++++-------
1 file changed, 12 insertions(+), 7 deletions(-)
diff --git a/app/src/processing/app/Editor.java b/app/src/processing/app/Editor.java
index 0e83ec62d65..ee7fafc36ef 100644
--- a/app/src/processing/app/Editor.java
+++ b/app/src/processing/app/Editor.java
@@ -339,10 +339,9 @@ public boolean importData(JComponent src, Transferable transferable) {
new DataFlavor("text/uri-list;class=java.lang.String");
if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
- java.util.List list = (java.util.List)
+ List list = (List)
transferable.getTransferData(DataFlavor.javaFileListFlavor);
- for (int i = 0; i < list.size(); i++) {
- File file = (File) list.get(i);
+ for (File file : list) {
if (sketch.addFile(file)) {
successful++;
}
@@ -853,8 +852,9 @@ protected String findClassInZipFile(String base, File file) {
// Class file to search for
String classFileName = "/" + base + ".class";
+ ZipFile zipFile = null;
try {
- ZipFile zipFile = new ZipFile(file);
+ zipFile = new ZipFile(file);
Enumeration> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
@@ -874,6 +874,12 @@ protected String findClassInZipFile(String base, File file) {
} catch (IOException e) {
//System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")");
e.printStackTrace();
+ } finally {
+ if (zipFile != null)
+ try {
+ zipFile.close();
+ } catch (IOException e) {
+ }
}
return null;
}
@@ -1861,9 +1867,8 @@ protected String getCurrentKeyword() {
} catch (BadLocationException bl) {
bl.printStackTrace();
- } finally {
- return text;
- }
+ }
+ return text;
}
protected void handleFindReference() {
From 479b974fe1d65ab55d01f9d5b331456f8f9d76a3 Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Sun, 26 Jan 2014 19:24:11 +0100
Subject: [PATCH 08/73] Refactoring of Theme class
---
app/src/processing/app/Theme.java | 149 +++++++++---------------------
1 file changed, 46 insertions(+), 103 deletions(-)
diff --git a/app/src/processing/app/Theme.java b/app/src/processing/app/Theme.java
index b6c8ae4f0f7..9ee02ef5fd2 100644
--- a/app/src/processing/app/Theme.java
+++ b/app/src/processing/app/Theme.java
@@ -1,5 +1,3 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
/*
Part of the Processing project - http://processing.org
@@ -23,14 +21,14 @@
package processing.app;
-import java.awt.*;
-import java.io.*;
-import java.util.*;
-
-import processing.app.syntax.*;
-import processing.core.*;
import static processing.app.I18n._;
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.SystemColor;
+
+import processing.app.helpers.PreferencesMap;
+import processing.app.syntax.SyntaxStyle;
/**
* Storage class for theme settings. This was separated from the Preferences
@@ -40,165 +38,110 @@
public class Theme {
/** Copy of the defaults in case the user mangles a preference. */
- static HashMap defaults;
+ static PreferencesMap defaults;
/** Table of attributes/values for the theme. */
- static HashMap table = new HashMap();;
-
+ static PreferencesMap table = new PreferencesMap();
static protected void init() {
try {
- load(Base.getLibStream("theme/theme.txt"));
+ table.load(Base.getLibStream("theme/theme.txt"));
} catch (Exception te) {
Base.showError(null, _("Could not read color theme settings.\n" +
"You'll need to reinstall Arduino."), te);
}
- // check for platform-specific properties in the defaults
- String platformExt = "." + Base.getPlatformName();
- int platformExtLength = platformExt.length();
- for (String key : table.keySet()) {
- if (key.endsWith(platformExt)) {
- // this is a key specific to a particular platform
- String actualKey = key.substring(0, key.length() - platformExtLength);
- String value = get(key);
- table.put(actualKey, value);
- }
- }
-
// other things that have to be set explicitly for the defaults
setColor("run.window.bgcolor", SystemColor.control);
// clone the hash table
- defaults = (HashMap) table.clone();
- }
-
-
- static protected void load(InputStream input) throws IOException {
- String[] lines = PApplet.loadStrings(input);
- for (String line : lines) {
- if ((line.length() == 0) ||
- (line.charAt(0) == '#')) continue;
-
- // this won't properly handle = signs being in the text
- int equals = line.indexOf('=');
- if (equals != -1) {
- String key = line.substring(0, equals).trim();
- String value = line.substring(equals + 1).trim();
- table.put(key, value);
- }
- }
+ defaults = new PreferencesMap(table);
}
-
static public String get(String attribute) {
- return (String) table.get(attribute);
+ return table.get(attribute);
}
-
static public String getDefault(String attribute) {
- return (String) defaults.get(attribute);
+ return defaults.get(attribute);
}
-
static public void set(String attribute, String value) {
table.put(attribute, value);
}
-
static public boolean getBoolean(String attribute) {
- String value = get(attribute);
- return (new Boolean(value)).booleanValue();
+ return new Boolean(get(attribute));
}
-
static public void setBoolean(String attribute, boolean value) {
set(attribute, value ? "true" : "false");
}
-
static public int getInteger(String attribute) {
return Integer.parseInt(get(attribute));
}
-
static public void setInteger(String key, int value) {
set(key, String.valueOf(value));
}
-
static public Color getColor(String name) {
- Color parsed = null;
- String s = get(name);
- if ((s != null) && (s.indexOf("#") == 0)) {
- try {
- int v = Integer.parseInt(s.substring(1), 16);
- parsed = new Color(v);
- } catch (Exception e) {
- }
- }
- return parsed;
+ return parseColor(get(name));
}
-
static public void setColor(String attr, Color what) {
- set(attr, "#" + PApplet.hex(what.getRGB() & 0xffffff, 6));
+ set(attr, "#" + String.format("%06x", what.getRGB() & 0xffffff));
}
-
static public Font getFont(String attr) {
- boolean replace = false;
String value = get(attr);
if (value == null) {
- //System.out.println("reset 1");
value = getDefault(attr);
- replace = true;
+ set(attr, value);
}
- String[] pieces = PApplet.split(value, ',');
- if (pieces.length != 3) {
+ String[] split = value.split(",");
+ if (split.length != 3) {
value = getDefault(attr);
- //System.out.println("reset 2 for " + attr);
- pieces = PApplet.split(value, ',');
- //PApplet.println(pieces);
- replace = true;
+ set(attr, value);
+ split = value.split(",");
}
- String name = pieces[0];
- int style = Font.PLAIN; // equals zero
- if (pieces[1].indexOf("bold") != -1) {
+ String name = split[0];
+ int style = Font.PLAIN;
+ if (split[1].contains("bold"))
style |= Font.BOLD;
- }
- if (pieces[1].indexOf("italic") != -1) {
+ if (split[1].contains("italic"))
style |= Font.ITALIC;
+ int size = 12; // Default
+ try {
+ // (parseDouble handle numbers with decimals too)
+ size = (int) Double.parseDouble(split[2]);
+ } catch (NumberFormatException e) {
}
- int size = PApplet.parseInt(pieces[2], 12);
- Font font = new Font(name, style, size);
-
- // replace bad font with the default
- if (replace) {
- //System.out.println(attr + " > " + value);
- //setString(attr, font.getName() + ",plain," + font.getSize());
- set(attr, value);
- }
-
- return font;
+ return new Font(name, style, size);
}
-
static public SyntaxStyle getStyle(String what) {
- String str = get("editor." + what + ".style");
-
- StringTokenizer st = new StringTokenizer(str, ",");
+ String split[] = get("editor." + what + ".style").split(",");
- String s = st.nextToken();
- if (s.indexOf("#") == 0) s = s.substring(1);
- Color color = new Color(Integer.parseInt(s, 16));
+ Color color = parseColor(split[0]);
- s = st.nextToken();
- boolean bold = (s.indexOf("bold") != -1);
- boolean italic = (s.indexOf("italic") != -1);
- boolean underlined = (s.indexOf("underlined") != -1);
+ String style = split[1];
+ boolean bold = style.contains("bold");
+ boolean italic = style.contains("italic");
+ boolean underlined = style.contains("underlined");
return new SyntaxStyle(color, italic, bold, underlined);
}
+
+ private static Color parseColor(String v) {
+ try {
+ if (v.indexOf("#") == 0)
+ v = v.substring(1);
+ return new Color(Integer.parseInt(v, 16));
+ } catch (Exception e) {
+ return null;
+ }
+ }
}
From 93562a7800f010d38b2149f24e13fa5225178689 Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Sun, 26 Jan 2014 22:05:57 +0100
Subject: [PATCH 09/73] Refactored and simplified EditorConsole class.
---
app/src/processing/app/EditorConsole.java | 259 ++++++++++------------
1 file changed, 113 insertions(+), 146 deletions(-)
diff --git a/app/src/processing/app/EditorConsole.java b/app/src/processing/app/EditorConsole.java
index bfd20e152ae..c29222c93fe 100644
--- a/app/src/processing/app/EditorConsole.java
+++ b/app/src/processing/app/EditorConsole.java
@@ -1,5 +1,3 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
/*
Part of the Processing project - http://processing.org
@@ -22,15 +20,32 @@
*/
package processing.app;
-import static processing.app.I18n._;
-import java.awt.*;
-import java.awt.event.*;
-import java.io.*;
-import javax.swing.*;
-import javax.swing.text.*;
+import static processing.app.I18n._;
-import java.util.*;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.swing.JScrollPane;
+import javax.swing.JTextPane;
+import javax.swing.SwingUtilities;
+import javax.swing.text.AttributeSet;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.DefaultStyledDocument;
+import javax.swing.text.Element;
+import javax.swing.text.SimpleAttributeSet;
+import javax.swing.text.StyleConstants;
/**
@@ -40,16 +55,15 @@
* don't take over System.err, and debug while watching just System.out
* or just write println() or whatever directly to systemOut or systemErr.
*/
+@SuppressWarnings("serial")
public class EditorConsole extends JScrollPane {
Editor editor;
JTextPane consoleTextPane;
BufferedStyledDocument consoleDoc;
- MutableAttributeSet stdStyle;
- MutableAttributeSet errStyle;
-
- int maxLineCount;
+ SimpleAttributeSet stdStyle;
+ SimpleAttributeSet errStyle;
static File errFile;
static File outFile;
@@ -70,20 +84,19 @@ public class EditorConsole extends JScrollPane {
static EditorConsole currentConsole;
+ public EditorConsole(Editor _editor) {
+ editor = _editor;
- public EditorConsole(Editor editor) {
- this.editor = editor;
+ int maxLineCount = Preferences.getInteger("console.length");
- maxLineCount = Preferences.getInteger("console.length");
-
- consoleDoc = new BufferedStyledDocument(10000, maxLineCount);
+ consoleDoc = new BufferedStyledDocument(4000, maxLineCount);
consoleTextPane = new JTextPane(consoleDoc);
consoleTextPane.setEditable(false);
// necessary?
- MutableAttributeSet standard = new SimpleAttributeSet();
- StyleConstants.setAlignment(standard, StyleConstants.ALIGN_LEFT);
- consoleDoc.setParagraphAttributes(0, 0, standard, true);
+ SimpleAttributeSet leftAlignAttr = new SimpleAttributeSet();
+ StyleConstants.setAlignment(leftAlignAttr, StyleConstants.ALIGN_LEFT);
+ consoleDoc.setParagraphAttributes(0, 0, leftAlignAttr, true);
// build styles for different types of console output
Color bgColor = Theme.getColor("console.color");
@@ -112,13 +125,13 @@ public EditorConsole(Editor editor) {
consoleTextPane.setBackground(bgColor);
// add the jtextpane to this scrollpane
- this.setViewportView(consoleTextPane);
+ setViewportView(consoleTextPane);
// calculate height of a line of text in pixels
// and size window accordingly
- FontMetrics metrics = this.getFontMetrics(font);
+ FontMetrics metrics = getFontMetrics(font);
int height = metrics.getAscent() + metrics.getDescent();
- int lines = Preferences.getInteger("console.lines"); //, 4);
+ int lines = Preferences.getInteger("console.lines");
int sizeFudge = 6; //10; // unclear why this is necessary, but it is
setPreferredSize(new Dimension(1024, (height * lines) + sizeFudge));
setMinimumSize(new Dimension(1024, (height * 4) + sizeFudge));
@@ -127,10 +140,10 @@ public EditorConsole(Editor editor) {
systemOut = System.out;
systemErr = System.err;
- // Create a temporary folder which will have a randomized name. Has to
- // be randomized otherwise another instance of Processing (or one of its
- // sister IDEs) might collide with the file causing permissions problems.
- // The files and folders are not deleted on exit because they may be
+ // Create a temporary folder which will have a randomized name. Has to
+ // be randomized otherwise another instance of Processing (or one of its
+ // sister IDEs) might collide with the file causing permissions problems.
+ // The files and folders are not deleted on exit because they may be
// needed for debugging or bug reporting.
tempFolder = Base.createTempFolder("console");
tempFolder.deleteOnExit();
@@ -154,7 +167,7 @@ public EditorConsole(Editor editor) {
}
consoleOut = new PrintStream(new EditorConsoleStream(false));
consoleErr = new PrintStream(new EditorConsoleStream(true));
-
+
if (Preferences.getBoolean("console")) {
try {
System.setOut(consoleOut);
@@ -179,7 +192,7 @@ public void actionPerformed(ActionEvent evt) {
@Override
public void run() {
// only if new text has been added
- if (consoleDoc.hasAppendage) {
+ if (consoleDoc.isChanged()) {
// insert the text that's been added in the meantime
consoleDoc.insertAll();
// always move to the end of the text as it's added
@@ -220,7 +233,7 @@ public void handleQuit() {
stdoutFile.close();
stderrFile.close();
} catch (IOException e) {
- e.printStackTrace(systemOut);
+ e.printStackTrace();
}
outFile.delete();
@@ -240,23 +253,18 @@ public void write(byte b[], int offset, int length, boolean err) {
synchronized public void message(String what, boolean err, boolean advance) {
if (err) {
systemErr.print(what);
- //systemErr.print("CE" + what);
+ if (advance)
+ systemErr.println();
} else {
systemOut.print(what);
- //systemOut.print("CO" + what);
- }
-
- if (advance) {
- appendText("\n", err);
- if (err) {
- systemErr.println();
- } else {
+ if (advance)
systemOut.println();
- }
}
- // to console display
+ // to console display
appendText(what, err);
+ if (advance)
+ appendText("\n", err);
// moved down here since something is punting
}
@@ -292,83 +300,47 @@ public void clear() {
private static class EditorConsoleStream extends OutputStream {
- //static EditorConsole current;
final boolean err; // whether stderr or stdout
- final byte single[] = new byte[1];
-
- public EditorConsoleStream(boolean err) {
- this.err = err;
+ PrintStream system;
+ OutputStream file;
+
+ public EditorConsoleStream(boolean _err) {
+ err = _err;
+ if (err) {
+ system = systemErr;
+ file = stderrFile;
+ } else {
+ system = systemOut;
+ file = stdoutFile;
+ }
}
public void close() { }
public void flush() { }
- public void write(byte b[]) { // appears never to be used
- if (currentConsole != null) {
- currentConsole.write(b, 0, b.length, err);
- } else {
- try {
- if (err) {
- systemErr.write(b);
- } else {
- systemOut.write(b);
- }
- } catch (IOException e) { } // just ignore, where would we write?
- }
+ public void write(int b) {
+ write(new byte[] { (byte) b });
+ }
- OutputStream echo = err ? stderrFile : stdoutFile;
- if (echo != null) {
- try {
- echo.write(b);
- echo.flush();
- } catch (IOException e) {
- e.printStackTrace();
- echo = null;
- }
- }
+ public void write(byte b[]) { // appears never to be used
+ write(b, 0, b.length);
}
public void write(byte b[], int offset, int length) {
if (currentConsole != null) {
currentConsole.write(b, offset, length, err);
} else {
- if (err) {
- systemErr.write(b, offset, length);
- } else {
- systemOut.write(b, offset, length);
- }
- }
-
- OutputStream echo = err ? stderrFile : stdoutFile;
- if (echo != null) {
- try {
- echo.write(b, offset, length);
- echo.flush();
- } catch (IOException e) {
- e.printStackTrace();
- echo = null;
- }
- }
- }
-
- public void write(int b) {
- single[0] = (byte)b;
- if (currentConsole != null) {
- currentConsole.write(single, 0, 1, err);
- } else {
- // redirect for all the extra handling above
- write(new byte[] { (byte) b }, 0, 1);
+ system.write(b, offset, length);
}
- OutputStream echo = err ? stderrFile : stdoutFile;
- if (echo != null) {
+ if (file != null) {
try {
- echo.write(b);
- echo.flush();
+ file.write(b, offset, length);
+ file.flush();
} catch (IOException e) {
e.printStackTrace();
- echo = null;
+ file = null;
}
}
}
@@ -386,78 +358,73 @@ public void write(int b) {
* appendString() is called from multiple threads, and insertAll from the
* swing event thread, so they need to be synchronized
*/
+@SuppressWarnings("serial")
class BufferedStyledDocument extends DefaultStyledDocument {
- ArrayList elements = new ArrayList();
- int maxLineLength, maxLineCount;
- int currentLineLength = 0;
- boolean needLineBreak = false;
- boolean hasAppendage = false;
-
- public BufferedStyledDocument(int maxLineLength, int maxLineCount) {
- this.maxLineLength = maxLineLength;
- this.maxLineCount = maxLineCount;
+ private List elements = new ArrayList();
+ private int maxLineLength, maxLineCount;
+ private int currentLineLength = 0;
+ private boolean changed = false;
+
+ public BufferedStyledDocument(int _maxLineLength, int _maxLineCount) {
+ maxLineLength = _maxLineLength;
+ maxLineCount = _maxLineCount;
}
/** buffer a string for insertion at the end of the DefaultStyledDocument */
- public synchronized void appendString(String str, AttributeSet a) {
- // do this so that it's only updated when needed (otherwise console
- // updates every 250 ms when an app isn't even running.. see bug 180)
- hasAppendage = true;
-
- // process each line of the string
- while (str.length() > 0) {
- // newlines within an element have (almost) no effect, so we need to
- // replace them with proper paragraph breaks (start and end tags)
- if (needLineBreak || currentLineLength > maxLineLength) {
+ public synchronized void appendString(String text, AttributeSet a) {
+ changed = true;
+ char[] chars = text.toCharArray();
+ int start = 0;
+ int stop = 0;
+ while (stop < chars.length) {
+ char c = chars[stop];
+ stop++;
+ currentLineLength++;
+ if (c == '\n' || currentLineLength > maxLineLength) {
+ elements.add(new ElementSpec(a, ElementSpec.ContentType, chars, start,
+ stop - start));
elements.add(new ElementSpec(a, ElementSpec.EndTagType));
elements.add(new ElementSpec(a, ElementSpec.StartTagType));
currentLineLength = 0;
- }
-
- if (str.indexOf('\n') == -1) {
- elements.add(new ElementSpec(a, ElementSpec.ContentType,
- str.toCharArray(), 0, str.length()));
- currentLineLength += str.length();
- needLineBreak = false;
- str = str.substring(str.length()); // eat the string
- } else {
- elements.add(new ElementSpec(a, ElementSpec.ContentType,
- str.toCharArray(), 0, str.indexOf('\n') + 1));
- needLineBreak = true;
- str = str.substring(str.indexOf('\n') + 1); // eat the line
+ start = stop;
}
}
+ elements.add(new ElementSpec(a, ElementSpec.ContentType, chars, start,
+ stop - start));
}
/** insert the buffered strings */
public synchronized void insertAll() {
- ElementSpec[] elementArray = new ElementSpec[elements.size()];
- elements.toArray(elementArray);
-
try {
- // check how many lines have been used so far
+ // Insert new elements at the bottom
+ ElementSpec[] elementArray = elements.toArray(new ElementSpec[0]);
+ insert(getLength(), elementArray);
+
+ // check how many lines have been used
// if too many, shave off a few lines from the beginning
- Element element = super.getDefaultRootElement();
- int lineCount = element.getElementCount();
+ Element root = getDefaultRootElement();
+ int lineCount = root.getElementCount();
int overage = lineCount - maxLineCount;
if (overage > 0) {
// if 1200 lines, and 1000 lines is max,
// find the position of the end of the 200th line
- //systemOut.println("overage is " + overage);
- Element lineElement = element.getElement(overage);
- if (lineElement == null) return; // do nuthin
+ Element lineElement = root.getElement(overage);
+ if (lineElement == null)
+ return; // do nuthin
- int endOffset = lineElement.getEndOffset();
// remove to the end of the 200th line
- super.remove(0, endOffset);
+ int endOffset = lineElement.getEndOffset();
+ remove(0, endOffset);
}
- super.insert(super.getLength(), elementArray);
-
} catch (BadLocationException e) {
// ignore the error otherwise this will cause an infinite loop
// maybe not a good idea in the long run?
}
elements.clear();
- hasAppendage = false;
+ changed = false;
+ }
+
+ public boolean isChanged() {
+ return changed;
}
}
From 872897d6ad9b49e3adccbc39feaf19881923142c Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Sun, 26 Jan 2014 22:56:06 +0100
Subject: [PATCH 10/73] Splitted GUI and Streams in EditorConsole
---
app/src/processing/app/Base.java | 2 +-
app/src/processing/app/EditorConsole.java | 181 +-----------------
.../processing/app/EditorConsoleStream.java | 150 +++++++++++++++
app/src/processing/app/Sketch.java | 2 +-
4 files changed, 154 insertions(+), 181 deletions(-)
create mode 100644 app/src/processing/app/EditorConsoleStream.java
diff --git a/app/src/processing/app/Base.java b/app/src/processing/app/Base.java
index fb7b302cff3..9132571b117 100644
--- a/app/src/processing/app/Base.java
+++ b/app/src/processing/app/Base.java
@@ -764,7 +764,7 @@ protected void handleActivated(Editor whichEditor) {
activeEditor = whichEditor;
// set the current window to be the console that's getting output
- EditorConsole.setEditor(activeEditor);
+ EditorConsoleStream.setCurrent(activeEditor.console);
}
diff --git a/app/src/processing/app/EditorConsole.java b/app/src/processing/app/EditorConsole.java
index c29222c93fe..93d8eaf9deb 100644
--- a/app/src/processing/app/EditorConsole.java
+++ b/app/src/processing/app/EditorConsole.java
@@ -21,19 +21,12 @@
package processing.app;
-import static processing.app.I18n._;
-
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
@@ -65,25 +58,10 @@ public class EditorConsole extends JScrollPane {
SimpleAttributeSet stdStyle;
SimpleAttributeSet errStyle;
- static File errFile;
- static File outFile;
- static File tempFolder;
-
// Single static instance shared because there's only one real System.out.
// Within the input handlers, the currentConsole variable will be used to
// echo things to the correct location.
- static public PrintStream systemOut;
- static public PrintStream systemErr;
-
- static PrintStream consoleOut;
- static PrintStream consoleErr;
-
- static OutputStream stdoutFile;
- static OutputStream stderrFile;
-
- static EditorConsole currentConsole;
-
public EditorConsole(Editor _editor) {
editor = _editor;
@@ -136,47 +114,7 @@ public EditorConsole(Editor _editor) {
setPreferredSize(new Dimension(1024, (height * lines) + sizeFudge));
setMinimumSize(new Dimension(1024, (height * 4) + sizeFudge));
- if (systemOut == null) {
- systemOut = System.out;
- systemErr = System.err;
-
- // Create a temporary folder which will have a randomized name. Has to
- // be randomized otherwise another instance of Processing (or one of its
- // sister IDEs) might collide with the file causing permissions problems.
- // The files and folders are not deleted on exit because they may be
- // needed for debugging or bug reporting.
- tempFolder = Base.createTempFolder("console");
- tempFolder.deleteOnExit();
- try {
- String outFileName = Preferences.get("console.output.file");
- if (outFileName != null) {
- outFile = new File(tempFolder, outFileName);
- outFile.deleteOnExit();
- stdoutFile = new FileOutputStream(outFile);
- }
-
- String errFileName = Preferences.get("console.error.file");
- if (errFileName != null) {
- errFile = new File(tempFolder, errFileName);
- errFile.deleteOnExit();
- stderrFile = new FileOutputStream(errFile);
- }
- } catch (IOException e) {
- Base.showWarning(_("Console Error"),
- _("A problem occurred while trying to open the\nfiles used to store the console output."), e);
- }
- consoleOut = new PrintStream(new EditorConsoleStream(false));
- consoleErr = new PrintStream(new EditorConsoleStream(true));
-
- if (Preferences.getBoolean("console")) {
- try {
- System.setOut(consoleOut);
- System.setErr(consoleErr);
- } catch (Exception e) {
- e.printStackTrace(systemOut);
- }
- }
- }
+ EditorConsoleStream.init();
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
@@ -204,70 +142,6 @@ public void run() {
}).start();
}
-
- static public void setEditor(Editor editor) {
- currentConsole = editor.console;
- }
-
-
- /**
- * Close the streams so that the temporary files can be deleted.
- *
- * File.deleteOnExit() cannot be used because the stdout and stderr
- * files are inside a folder, and have to be deleted before the
- * folder itself is deleted, which can't be guaranteed when using
- * the deleteOnExit() method.
- */
- public void handleQuit() {
- // replace original streams to remove references to console's streams
- System.setOut(systemOut);
- System.setErr(systemErr);
-
- // close the PrintStream
- consoleOut.close();
- consoleErr.close();
-
- // also have to close the original FileOutputStream
- // otherwise it won't be shut down completely
- try {
- stdoutFile.close();
- stderrFile.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- outFile.delete();
- errFile.delete();
- tempFolder.delete();
- }
-
-
- public void write(byte b[], int offset, int length, boolean err) {
- // we could do some cross platform CR/LF mangling here before outputting
- // add text to output document
- message(new String(b, offset, length), err, false);
- }
-
-
- // added sync for 0091.. not sure if it helps or hinders
- synchronized public void message(String what, boolean err, boolean advance) {
- if (err) {
- systemErr.print(what);
- if (advance)
- systemErr.println();
- } else {
- systemOut.print(what);
- if (advance)
- systemOut.println();
- }
-
- // to console display
- appendText(what, err);
- if (advance)
- appendText("\n", err);
- // moved down here since something is punting
- }
-
/**
* Append a piece of text to the console.
@@ -281,7 +155,7 @@ synchronized public void message(String what, boolean err, boolean advance) {
* Updates are buffered to the console and displayed at regular
* intervals on Swing's event-dispatching thread. (patch by David Mellis)
*/
- synchronized private void appendText(String txt, boolean e) {
+ synchronized void appendText(String txt, boolean e) {
consoleDoc.appendString(txt, e ? errStyle : stdStyle);
}
@@ -294,57 +168,6 @@ public void clear() {
// maybe not a good idea in the long run?
}
}
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- private static class EditorConsoleStream extends OutputStream {
- final boolean err; // whether stderr or stdout
- PrintStream system;
- OutputStream file;
-
- public EditorConsoleStream(boolean _err) {
- err = _err;
- if (err) {
- system = systemErr;
- file = stderrFile;
- } else {
- system = systemOut;
- file = stdoutFile;
- }
- }
-
- public void close() { }
-
- public void flush() { }
-
- public void write(int b) {
- write(new byte[] { (byte) b });
- }
-
- public void write(byte b[]) { // appears never to be used
- write(b, 0, b.length);
- }
-
- public void write(byte b[], int offset, int length) {
- if (currentConsole != null) {
- currentConsole.write(b, offset, length, err);
- } else {
- system.write(b, offset, length);
- }
-
- if (file != null) {
- try {
- file.write(b, offset, length);
- file.flush();
- } catch (IOException e) {
- e.printStackTrace();
- file = null;
- }
- }
- }
- }
}
diff --git a/app/src/processing/app/EditorConsoleStream.java b/app/src/processing/app/EditorConsoleStream.java
new file mode 100644
index 00000000000..06e23267388
--- /dev/null
+++ b/app/src/processing/app/EditorConsoleStream.java
@@ -0,0 +1,150 @@
+package processing.app;
+
+import static processing.app.I18n._;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+
+class EditorConsoleStream extends OutputStream {
+ static File tempFolder;
+ static File outFile;
+ static File errFile;
+
+ static EditorConsole currentConsole;
+
+ static OutputStream stderrFile;
+ static OutputStream stdoutFile;
+ static PrintStream consoleErr;
+ static PrintStream consoleOut;
+ static public PrintStream systemErr;
+ static public PrintStream systemOut;
+
+ public static void init() {
+ if (systemOut == null) {
+ systemOut = System.out;
+ systemErr = System.err;
+
+ // Create a temporary folder which will have a randomized name. Has to
+ // be randomized otherwise another instance of Processing (or one of its
+ // sister IDEs) might collide with the file causing permissions problems.
+ // The files and folders are not deleted on exit because they may be
+ // needed for debugging or bug reporting.
+ tempFolder = Base.createTempFolder("console");
+ tempFolder.deleteOnExit();
+ try {
+ String outFileName = Preferences.get("console.output.file");
+ if (outFileName != null) {
+ outFile = new File(tempFolder, outFileName);
+ outFile.deleteOnExit();
+ stdoutFile = new FileOutputStream(outFile);
+ }
+
+ String errFileName = Preferences.get("console.error.file");
+ if (errFileName != null) {
+ errFile = new File(tempFolder, errFileName);
+ errFile.deleteOnExit();
+ stderrFile = new FileOutputStream(errFile);
+ }
+ } catch (IOException e) {
+ Base.showWarning(_("Console Error"),
+ _("A problem occurred while trying to open the\nfiles used to store the console output."),
+ e);
+ }
+ consoleOut = new PrintStream(new EditorConsoleStream(false));
+ consoleErr = new PrintStream(new EditorConsoleStream(true));
+
+ if (Preferences.getBoolean("console")) {
+ try {
+ System.setOut(consoleOut);
+ System.setErr(consoleErr);
+ } catch (Exception e) {
+ e.printStackTrace(systemOut);
+ }
+ }
+ }
+ }
+
+ /**
+ * Close the streams so that the temporary files can be deleted.
+ *
+ * File.deleteOnExit() cannot be used because the stdout and stderr files are
+ * inside a folder, and have to be deleted before the folder itself is
+ * deleted, which can't be guaranteed when using the deleteOnExit() method.
+ */
+ public static void quit() {
+ // replace original streams to remove references to console's streams
+ System.setOut(systemOut);
+ System.setErr(systemErr);
+
+ // close the PrintStream
+ consoleOut.close();
+ consoleErr.close();
+
+ // also have to close the original FileOutputStream
+ // otherwise it won't be shut down completely
+ try {
+ stdoutFile.close();
+ stderrFile.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ outFile.delete();
+ errFile.delete();
+ tempFolder.delete();
+ }
+
+ final boolean err; // whether stderr or stdout
+ PrintStream system;
+ OutputStream file;
+
+ public EditorConsoleStream(boolean _err) {
+ err = _err;
+ if (err) {
+ system = systemErr;
+ file = stderrFile;
+ } else {
+ system = systemOut;
+ file = stdoutFile;
+ }
+ }
+
+ public void close() {
+ }
+
+ public void flush() {
+ }
+
+ public void write(int b) {
+ write(new byte[] { (byte) b });
+ }
+
+ public void write(byte b[]) { // appears never to be used
+ write(b, 0, b.length);
+ }
+
+ public void write(byte b[], int offset, int length) {
+ if (currentConsole != null)
+ currentConsole.appendText(new String(b, offset, length), err);
+
+ system.write(b, offset, length);
+
+ if (file != null) {
+ try {
+ file.write(b, offset, length);
+ file.flush();
+ } catch (IOException e) {
+ e.printStackTrace();
+ file = null;
+ }
+ }
+ }
+
+ static public void setCurrent(EditorConsole console) {
+ currentConsole = console;
+ }
+
+}
\ No newline at end of file
diff --git a/app/src/processing/app/Sketch.java b/app/src/processing/app/Sketch.java
index 3663e7322ca..b487a6b2aac 100644
--- a/app/src/processing/app/Sketch.java
+++ b/app/src/processing/app/Sketch.java
@@ -194,7 +194,7 @@ protected void load() throws IOException {
code[codeCount++] =
new SketchCode(new File(folder, filename));
} else {
- editor.console.message(I18n.format("File name {0} is invalid: ignored", filename), true, false);
+ System.err.println(I18n.format("File name {0} is invalid: ignored", filename));
}
}
}
From af19257fbd6993bade147dab0f67267af6dce2e7 Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Fri, 31 Jan 2014 22:54:45 +0100
Subject: [PATCH 11/73] Rationalized Preferences and Theme classes.
Removed a lot of duplicate/unused code. Preferences un-marshalling
is now handled in PreferencesMap class.
---
app/src/processing/app/Preferences.java | 234 ++++++------------
app/src/processing/app/Theme.java | 51 +---
.../app/helpers/PreferencesMap.java | 87 ++++++-
3 files changed, 169 insertions(+), 203 deletions(-)
diff --git a/app/src/processing/app/Preferences.java b/app/src/processing/app/Preferences.java
index 8e89ba62b25..b8b8471f824 100644
--- a/app/src/processing/app/Preferences.java
+++ b/app/src/processing/app/Preferences.java
@@ -1,5 +1,3 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
/*
Part of the Processing project - http://processing.org
@@ -23,22 +21,48 @@
package processing.app;
+import static processing.app.I18n._;
+
+import java.awt.Color;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.Insets;
+import java.awt.SystemColor;
+import java.awt.Toolkit;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.util.Arrays;
+import java.util.MissingResourceException;
+import java.util.StringTokenizer;
+
+import javax.swing.Box;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JComboBox;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JTextField;
+import javax.swing.KeyStroke;
+
import processing.app.helpers.FileUtils;
+import processing.app.helpers.PreferencesMap;
import processing.app.syntax.SyntaxStyle;
import processing.core.PApplet;
import processing.core.PConstants;
-import javax.swing.*;
-import java.awt.*;
-import java.awt.event.*;
-import java.io.*;
-import java.util.*;
-
-import processing.app.helpers.PreferencesMap;
-import static processing.app.I18n._;
-
-
-
/**
* Storage class for user preferences and environment settings.
@@ -69,8 +93,6 @@
*/
public class Preferences {
- // what to call the feller
-
static final String PREFS_FILE = "preferences.txt";
class Language {
@@ -218,8 +240,8 @@ public String toString() {
// data model
- static Hashtable defaults;
- static Hashtable table = new Hashtable();
+ static PreferencesMap defaults;
+ static PreferencesMap prefs = new PreferencesMap();
static File preferencesFile;
static boolean doSave = true;
@@ -233,38 +255,25 @@ static protected void init(File file) {
// start by loading the defaults, in case something
// important was deleted from the user prefs
try {
- load(Base.getLibStream("preferences.txt"));
- } catch (Exception e) {
+ prefs.load(Base.getLibStream("preferences.txt"));
+ } catch (IOException e) {
Base.showError(null, _("Could not read default settings.\n" +
"You'll need to reinstall Arduino."), e);
}
// set some runtime constants (not saved on preferences file)
File hardwareFolder = Base.getHardwareFolder();
- table.put("runtime.ide.path", hardwareFolder.getParentFile().getAbsolutePath());
- table.put("runtime.ide.version", "" + Base.REVISION);
+ prefs.put("runtime.ide.path", hardwareFolder.getParentFile().getAbsolutePath());
+ prefs.put("runtime.ide.version", "" + Base.REVISION);
- // check for platform-specific properties in the defaults
- String platformExt = "." + Base.platform.getName();
- int platformExtLength = platformExt.length();
- Set keySet = new HashSet(table.keySet());
- for (String key : keySet) {
- if (key.endsWith(platformExt)) {
- // this is a key specific to a particular platform
- String actualKey = key.substring(0, key.length() - platformExtLength);
- String value = get(key);
- table.put(actualKey, value);
- }
- }
-
// clone the hash table
- defaults = new Hashtable(table);
+ defaults = new PreferencesMap(prefs);
if (preferencesFile.exists()) {
// load the previous preferences file
try {
- load(new FileInputStream(preferencesFile));
- } catch (Exception ex) {
+ prefs.load(preferencesFile);
+ } catch (IOException ex) {
Base.showError(_("Error reading preferences"),
I18n.format(_("Error reading the preferences file. "
+ "Please delete (or move)\n"
@@ -275,14 +284,14 @@ static protected void init(File file) {
// load the I18n module for internationalization
try {
- I18n.init(Preferences.get("editor.languages.current"));
+ I18n.init(get("editor.languages.current"));
} catch (MissingResourceException e) {
I18n.init("en");
- Preferences.set("editor.languages.current", "en");
+ set("editor.languages.current", "en");
}
// set some other runtime constants (not saved on preferences file)
- table.put("runtime.os", PConstants.platformNames[PApplet.platform]);
+ set("runtime.os", PConstants.platformNames[PApplet.platform]);
// other things that have to be set explicitly for the defaults
setColor("run.window.bgcolor", SystemColor.control);
@@ -604,11 +613,6 @@ public void keyPressed(KeyEvent e) {
}
- public Dimension getPreferredSize() {
- return new Dimension(wide, high);
- }
-
-
// .................................................................
@@ -733,26 +737,6 @@ protected void showFrame(Editor editor) {
// .................................................................
- static protected void load(InputStream input) throws IOException {
- load(input, table);
- }
-
- static public void load(InputStream input, Map table) throws IOException {
- String[] lines = loadStrings(input); // Reads as UTF-8
- for (String line : lines) {
- if ((line.length() == 0) ||
- (line.charAt(0) == '#')) continue;
-
- // this won't properly handle = signs being in the text
- int equals = line.indexOf('=');
- if (equals != -1) {
- String key = line.substring(0, equals).trim();
- String value = line.substring(equals + 1).trim();
- table.put(key, value);
- }
- }
- }
-
static public String[] loadStrings(InputStream input) {
try {
BufferedReader reader =
@@ -803,48 +787,36 @@ static protected void save() {
// Fix for 0163 to properly use Unicode when writing preferences.txt
PrintWriter writer = PApplet.createWriter(preferencesFile);
- String[] keys = table.keySet().toArray(new String[0]);
+ String[] keys = prefs.keySet().toArray(new String[0]);
Arrays.sort(keys);
for (String key: keys) {
if (key.startsWith("runtime."))
continue;
- writer.println(key + "=" + table.get(key));
+ writer.println(key + "=" + prefs.get(key));
}
writer.flush();
writer.close();
-
-// } catch (Exception ex) {
-// Base.showWarning(null, "Error while saving the settings file", ex);
-// }
}
// .................................................................
-
- // all the information from preferences.txt
-
- //static public String get(String attribute) {
- //return get(attribute, null);
- //}
-
static public String get(String attribute) {
- return table.get(attribute);
+ return prefs.get(attribute);
}
static public String get(String attribute, String defaultValue) {
String value = get(attribute);
-
return (value == null) ? defaultValue : value;
}
public static boolean has(String key) {
- return table.containsKey(key);
+ return prefs.containsKey(key);
}
public static void remove(String key) {
- table.remove(key);
+ prefs.remove(key);
}
static public String getDefault(String attribute) {
@@ -853,57 +825,27 @@ static public String getDefault(String attribute) {
static public void set(String attribute, String value) {
- table.put(attribute, value);
+ prefs.put(attribute, value);
}
static public void unset(String attribute) {
- table.remove(attribute);
+ prefs.remove(attribute);
}
static public boolean getBoolean(String attribute) {
- String value = get(attribute); //, null);
- return (new Boolean(value)).booleanValue();
-
- /*
- supposedly not needed, because anything besides 'true'
- (ignoring case) will just be false.. so if malformed -> false
- if (value == null) return defaultValue;
-
- try {
- return (new Boolean(value)).booleanValue();
- } catch (NumberFormatException e) {
- System.err.println("expecting an integer: " + attribute + " = " + value);
- }
- return defaultValue;
- */
+ return prefs.getBoolean(attribute);
}
static public void setBoolean(String attribute, boolean value) {
- set(attribute, value ? "true" : "false");
+ prefs.putBoolean(attribute, value);
}
- static public int getInteger(String attribute /*, int defaultValue*/) {
+ static public int getInteger(String attribute) {
return Integer.parseInt(get(attribute));
-
- /*
- String value = get(attribute, null);
- if (value == null) return defaultValue;
-
- try {
- return Integer.parseInt(value);
- } catch (NumberFormatException e) {
- // ignored will just fall through to returning the default
- System.err.println("expecting an integer: " + attribute + " = " + value);
- }
- return defaultValue;
- //if (value == null) return defaultValue;
- //return (value == null) ? defaultValue :
- //Integer.parseInt(value);
- */
}
@@ -913,62 +855,31 @@ static public void setInteger(String key, int value) {
static public Color getColor(String name) {
- Color parsed = Color.GRAY; // set a default
- String s = get(name);
- if ((s != null) && (s.indexOf("#") == 0)) {
- try {
- parsed = new Color(Integer.parseInt(s.substring(1), 16));
- } catch (Exception e) { }
- }
- return parsed;
+ Color parsed = prefs.getColor(name);
+ if (parsed != null)
+ return parsed;
+ return Color.GRAY; // set a default
}
static public void setColor(String attr, Color what) {
- set(attr, "#" + PApplet.hex(what.getRGB() & 0xffffff, 6));
+ prefs.putColor(attr, what);
}
static public Font getFont(String attr) {
- boolean replace = false;
- String value = get(attr);
- if (value == null) {
- //System.out.println("reset 1");
- value = getDefault(attr);
- replace = true;
- }
-
- String[] pieces = PApplet.split(value, ',');
- if (pieces.length != 3) {
- value = getDefault(attr);
- //System.out.println("reset 2 for " + attr);
- pieces = PApplet.split(value, ',');
- //PApplet.println(pieces);
- replace = true;
+ Font font = prefs.getFont(attr);
+ if (font == null) {
+ String value = defaults.get(attr);
+ prefs.put(attr, value);
+ font = prefs.getFont(attr);
}
-
- String name = pieces[0];
- int style = Font.PLAIN; // equals zero
- if (pieces[1].indexOf("bold") != -1) {
- style |= Font.BOLD;
- }
- if (pieces[1].indexOf("italic") != -1) {
- style |= Font.ITALIC;
- }
- int size = PApplet.parseInt(pieces[2], 12);
- Font font = new Font(name, style, size);
-
- // replace bad font with the default
- if (replace) {
- set(attr, value);
- }
-
return font;
}
- static public SyntaxStyle getStyle(String what /*, String dflt*/) {
- String str = get("editor." + what + ".style"); //, dflt);
+ static public SyntaxStyle getStyle(String what) {
+ String str = get("editor." + what + ".style");
StringTokenizer st = new StringTokenizer(str, ",");
@@ -983,7 +894,6 @@ static public SyntaxStyle getStyle(String what /*, String dflt*/) {
boolean bold = (s.indexOf("bold") != -1);
boolean italic = (s.indexOf("italic") != -1);
boolean underlined = (s.indexOf("underlined") != -1);
- //System.out.println(what + " = " + str + " " + bold + " " + italic);
return new SyntaxStyle(color, italic, bold, underlined);
}
@@ -991,7 +901,7 @@ static public SyntaxStyle getStyle(String what /*, String dflt*/) {
// get a copy of the Preferences
static public PreferencesMap getMap()
{
- return new PreferencesMap(table);
+ return new PreferencesMap(prefs);
}
// Decide wether changed preferences will be saved. When value is
diff --git a/app/src/processing/app/Theme.java b/app/src/processing/app/Theme.java
index 9ee02ef5fd2..96ac78b4336 100644
--- a/app/src/processing/app/Theme.java
+++ b/app/src/processing/app/Theme.java
@@ -70,11 +70,11 @@ static public void set(String attribute, String value) {
}
static public boolean getBoolean(String attribute) {
- return new Boolean(get(attribute));
+ return table.getBoolean(attribute);
}
static public void setBoolean(String attribute, boolean value) {
- set(attribute, value ? "true" : "false");
+ table.putBoolean(attribute, value);
}
static public int getInteger(String attribute) {
@@ -86,46 +86,27 @@ static public void setInteger(String key, int value) {
}
static public Color getColor(String name) {
- return parseColor(get(name));
+ return PreferencesMap.parseColor(get(name));
}
- static public void setColor(String attr, Color what) {
- set(attr, "#" + String.format("%06x", what.getRGB() & 0xffffff));
+ static public void setColor(String attr, Color color) {
+ table.putColor(attr, color);
}
static public Font getFont(String attr) {
- String value = get(attr);
- if (value == null) {
- value = getDefault(attr);
+ Font font = table.getFont(attr);
+ if (font == null) {
+ String value = getDefault(attr);
set(attr, value);
+ font = table.getFont(attr);
}
-
- String[] split = value.split(",");
- if (split.length != 3) {
- value = getDefault(attr);
- set(attr, value);
- split = value.split(",");
- }
-
- String name = split[0];
- int style = Font.PLAIN;
- if (split[1].contains("bold"))
- style |= Font.BOLD;
- if (split[1].contains("italic"))
- style |= Font.ITALIC;
- int size = 12; // Default
- try {
- // (parseDouble handle numbers with decimals too)
- size = (int) Double.parseDouble(split[2]);
- } catch (NumberFormatException e) {
- }
- return new Font(name, style, size);
+ return font;
}
static public SyntaxStyle getStyle(String what) {
String split[] = get("editor." + what + ".style").split(",");
- Color color = parseColor(split[0]);
+ Color color = PreferencesMap.parseColor(split[0]);
String style = split[1];
boolean bold = style.contains("bold");
@@ -134,14 +115,4 @@ static public SyntaxStyle getStyle(String what) {
return new SyntaxStyle(color, italic, bold, underlined);
}
-
- private static Color parseColor(String v) {
- try {
- if (v.indexOf("#") == 0)
- v = v.substring(1);
- return new Color(Integer.parseInt(v, 16));
- } catch (Exception e) {
- return null;
- }
- }
}
diff --git a/app/src/processing/app/helpers/PreferencesMap.java b/app/src/processing/app/helpers/PreferencesMap.java
index b4f60848a83..3f2b264ef5d 100644
--- a/app/src/processing/app/helpers/PreferencesMap.java
+++ b/app/src/processing/app/helpers/PreferencesMap.java
@@ -3,7 +3,7 @@
to handle preferences.
Part of the Arduino project - http://www.arduino.cc/
- Copyright (c) 2011 Cristian Maglie
+ Copyright (c) 2014 Cristian Maglie
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -21,6 +21,8 @@
*/
package processing.app.helpers;
+import java.awt.Color;
+import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -296,4 +298,87 @@ public File getFile(String key, String subFolder) {
return null;
return new File(file, subFolder);
}
+
+ /**
+ * Return the value of the specified key as boolean.
+ *
+ * @param key
+ * @return true if the value of the key is the string "true" (case
+ * insensitive compared), false in any other case
+ */
+ public boolean getBoolean(String key) {
+ return new Boolean(get(key));
+ }
+
+ /**
+ * Sets the value of the specified key to the string "true" or
+ * "false" based on value of the boolean parameter
+ *
+ * @param key
+ * @param value
+ * @return true if the previous value of the key was the string "true"
+ * (case insensitive compared), false in any other case
+ */
+ public boolean putBoolean(String key, boolean value) {
+ String prev = put(key, value ? "true" : "false");
+ return new Boolean(prev);
+ }
+
+ /**
+ * Create a Color with the value of the specified key. The format of the color
+ * should be an hexadecimal number of 6 digit, eventually prefixed with a '#'.
+ *
+ * @param name
+ * @return A Color object or null if the key is not found or the format
+ * is wrong
+ */
+ public Color getColor(String name) {
+ return parseColor(get(name));
+ }
+
+ /**
+ * Set the value of the specified key based on the Color passed as parameter.
+ *
+ * @param attr
+ * @param color
+ */
+ public void putColor(String attr, Color color) {
+ put(attr, "#" + String.format("%06x", color.getRGB() & 0xffffff));
+ }
+
+ public static Color parseColor(String v) {
+ try {
+ if (v.indexOf("#") == 0)
+ v = v.substring(1);
+ return new Color(Integer.parseInt(v, 16));
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ public Font getFont(String key) {
+ String value = get(key);
+ if (value == null)
+ return null;
+ String[] split = value.split(",");
+ if (split.length != 3)
+ return null;
+
+ String name = split[0];
+ int style = Font.PLAIN;
+ if (split[1].contains("bold"))
+ style |= Font.BOLD;
+ if (split[1].contains("italic"))
+ style |= Font.ITALIC;
+ int size;
+ try {
+ // ParseDouble handle numbers with decimals too
+ size = (int) Double.parseDouble(split[2]);
+ } catch (NumberFormatException e) {
+ // for wrong formatted size pick the default
+ size = 12;
+ }
+ return new Font(name, style, size);
+ }
+
}
From e6563cfebf4b71fc1e2b9a43ebbbb04871a1ff08 Mon Sep 17 00:00:00 2001
From: Claudio Indellicati
Date: Thu, 30 Jan 2014 13:48:07 +0100
Subject: [PATCH 12/73] Removed GUI dependencies from SketchCode class.
Moved GUI fields into a SketchCodeDocument container class.
---
app/src/processing/app/Editor.java | 16 +--
app/src/processing/app/EditorHeader.java | 3 +-
app/src/processing/app/Sketch.java | 119 +++++++++---------
app/src/processing/app/SketchCode.java | 72 -----------
.../processing/app/SketchCodeDocument.java | 83 ++++++++++++
5 files changed, 155 insertions(+), 138 deletions(-)
create mode 100644 app/src/processing/app/SketchCodeDocument.java
diff --git a/app/src/processing/app/Editor.java b/app/src/processing/app/Editor.java
index ee7fafc36ef..2a2c6fe4da3 100644
--- a/app/src/processing/app/Editor.java
+++ b/app/src/processing/app/Editor.java
@@ -1637,19 +1637,19 @@ public int getScrollPosition() {
* Switch between tabs, this swaps out the Document object
* that's currently being manipulated.
*/
- protected void setCode(SketchCode code) {
- SyntaxDocument document = (SyntaxDocument) code.getDocument();
+ protected void setCode(SketchCodeDocument codeDoc) {
+ SyntaxDocument document = (SyntaxDocument) codeDoc.getDocument();
if (document == null) { // this document not yet inited
document = new SyntaxDocument();
- code.setDocument(document);
-
+ codeDoc.setDocument(document);
+
// turn on syntax highlighting
document.setTokenMarker(new PdeKeywords());
// insert the program text into the document object
try {
- document.insertString(0, code.getProgram(), null);
+ document.insertString(0, codeDoc.getCode().getProgram(), null);
} catch (BadLocationException bl) {
bl.printStackTrace();
}
@@ -1674,12 +1674,12 @@ public void undoableEditHappened(UndoableEditEvent e) {
// update the document object that's in use
textarea.setDocument(document,
- code.getSelectionStart(), code.getSelectionStop(),
- code.getScrollPosition());
+ codeDoc.getSelectionStart(), codeDoc.getSelectionStop(),
+ codeDoc.getScrollPosition());
textarea.requestFocus(); // get the caret blinking
- this.undo = code.getUndo();
+ this.undo = codeDoc.getUndo();
undoAction.updateUndoState();
redoAction.updateRedoState();
}
diff --git a/app/src/processing/app/EditorHeader.java b/app/src/processing/app/EditorHeader.java
index f21228984f4..dfa76f02af6 100644
--- a/app/src/processing/app/EditorHeader.java
+++ b/app/src/processing/app/EditorHeader.java
@@ -361,7 +361,8 @@ public void actionPerformed(ActionEvent e) {
editor.getSketch().setCurrentCode(e.getActionCommand());
}
};
- for (SketchCode code : sketch.getCode()) {
+ for (SketchCodeDocument codeDoc : sketch.getCodeDocs()) {
+ SketchCode code = codeDoc.getCode();
item = new JMenuItem(code.isExtension(sketch.getDefaultExtension()) ?
code.getPrettyName() : code.getFileName());
item.setActionCommand(code.getFileName());
diff --git a/app/src/processing/app/Sketch.java b/app/src/processing/app/Sketch.java
index b487a6b2aac..9d7690a4aa0 100644
--- a/app/src/processing/app/Sketch.java
+++ b/app/src/processing/app/Sketch.java
@@ -40,7 +40,6 @@
import java.io.*;
import java.util.*;
-import java.util.List;
import javax.swing.*;
@@ -75,7 +74,9 @@ public class Sketch {
private File codeFolder;
private SketchCode current;
+ private SketchCodeDocument currentCodeDoc;
private int currentIndex;
+
/**
* Number of sketchCode objects (tabs) in the current sketch. Note that this
* will be the same as code.length, because the getCode() method returns
@@ -84,8 +85,8 @@ public class Sketch {
* http://dev.processing.org/bugs/show_bug.cgi?id=940
*/
private int codeCount;
- private SketchCode[] code;
-
+ private SketchCodeDocument[] codeDocs;
+
/** Class name for the PApplet, as determined by the preprocessor. */
private String appletClassName;
/** Class path determined during build. */
@@ -168,7 +169,7 @@ protected void load() throws IOException {
// external editor event. (fix for 0099)
codeCount = 0;
- code = new SketchCode[list.length];
+ codeDocs = new SketchCodeDocument[list.length];
List extensions = getExtensions();
@@ -191,8 +192,8 @@ protected void load() throws IOException {
// Don't allow people to use files with invalid names, since on load,
// it would be otherwise possible to sneak in nasty filenames. [0116]
if (Sketch.isSanitaryName(base)) {
- code[codeCount++] =
- new SketchCode(new File(folder, filename));
+ codeDocs[codeCount++] =
+ new SketchCodeDocument(new File(folder, filename));
} else {
System.err.println(I18n.format("File name {0} is invalid: ignored", filename));
}
@@ -204,16 +205,16 @@ protected void load() throws IOException {
throw new IOException(_("No valid code files found"));
// Remove any code that wasn't proper
- code = (SketchCode[]) PApplet.subset(code, 0, codeCount);
+ codeDocs = (SketchCodeDocument[]) PApplet.subset(codeDocs, 0, codeCount);
// move the main class to the first tab
// start at 1, if it's at zero, don't bother
for (int i = 1; i < codeCount; i++) {
//if (code[i].file.getName().equals(mainFilename)) {
- if (code[i].getFile().equals(primaryFile)) {
- SketchCode temp = code[0];
- code[0] = code[i];
- code[i] = temp;
+ if (codeDocs[i].getCode().getFile().equals(primaryFile)) {
+ SketchCodeDocument temp = codeDocs[0];
+ codeDocs[0] = codeDocs[i];
+ codeDocs[i] = temp;
break;
}
}
@@ -230,8 +231,8 @@ protected void load() throws IOException {
protected void replaceCode(SketchCode newCode) {
for (int i = 0; i < codeCount; i++) {
- if (code[i].getFileName().equals(newCode.getFileName())) {
- code[i] = newCode;
+ if (codeDocs[i].getCode().getFileName().equals(newCode.getFileName())) {
+ codeDocs[i].setCode(newCode);
break;
}
}
@@ -244,7 +245,7 @@ protected void insertCode(SketchCode newCode) {
// add file to the code/codeCount list, resort the list
//if (codeCount == code.length) {
- code = (SketchCode[]) PApplet.append(code, newCode);
+ codeDocs = (SketchCodeDocument[]) PApplet.append(codeDocs, newCode);
codeCount++;
//}
//code[codeCount++] = newCode;
@@ -257,14 +258,14 @@ protected void sortCode() {
for (int i = 1; i < codeCount; i++) {
int who = i;
for (int j = i + 1; j < codeCount; j++) {
- if (code[j].getFileName().compareTo(code[who].getFileName()) < 0) {
+ if (codeDocs[j].getCode().getFileName().compareTo(codeDocs[who].getCode().getFileName()) < 0) {
who = j; // this guy is earlier in the alphabet
}
}
if (who != i) { // swap with someone if changes made
- SketchCode temp = code[who];
- code[who] = code[i];
- code[i] = temp;
+ SketchCodeDocument temp = codeDocs[who];
+ codeDocs[who] = codeDocs[i];
+ codeDocs[i] = temp;
}
}
}
@@ -379,7 +380,7 @@ protected void nameCode(String newName) {
// Don't let the user create the main tab as a .java file instead of .pde
if (!isDefaultExtension(newExtension)) {
if (renamingCode) { // If creating a new tab, don't show this error
- if (current == code[0]) { // If this is the main tab, disallow
+ if (current == codeDocs[0].getCode()) { // If this is the main tab, disallow
Base.showWarning(_("Problem with rename"),
_("The main file can't use an extension.\n" +
"(It may be time for your to graduate to a\n" +
@@ -401,12 +402,12 @@ protected void nameCode(String newName) {
// In Arduino, we want to allow files with the same name but different
// extensions, so compare the full names (including extensions). This
// might cause problems: http://dev.processing.org/bugs/show_bug.cgi?id=543
- for (SketchCode c : code) {
- if (newName.equalsIgnoreCase(c.getFileName())) {
+ for (SketchCodeDocument c : codeDocs) {
+ if (newName.equalsIgnoreCase(c.getCode().getFileName())) {
Base.showMessage(_("Nope"),
I18n.format(
_("A file named \"{0}\" already exists in \"{1}\""),
- c.getFileName(),
+ c.getCode().getFileName(),
folder.getAbsolutePath()
));
return;
@@ -424,8 +425,8 @@ protected void nameCode(String newName) {
if (renamingCode && currentIndex == 0) {
for (int i = 1; i < codeCount; i++) {
- if (sanitaryName.equalsIgnoreCase(code[i].getPrettyName()) &&
- code[i].isExtension("cpp")) {
+ if (sanitaryName.equalsIgnoreCase(codeDocs[i].getCode().getPrettyName()) &&
+ codeDocs[i].getCode().isExtension("cpp")) {
Base.showMessage(_("Nope"),
I18n.format(
_("You can't rename the sketch to \"{0}\"\n" +
@@ -500,7 +501,7 @@ protected void nameCode(String newName) {
// save each of the other tabs because this is gonna be re-opened
try {
for (int i = 1; i < codeCount; i++) {
- code[i].save();
+ codeDocs[i].getCode().save();
}
} catch (Exception e) {
Base.showWarning(_("Error"), _("Could not rename the sketch. (1)"), e);
@@ -644,12 +645,12 @@ protected void removeCode(SketchCode which) {
// remove it from the internal list of files
// resort internal list of files
for (int i = 0; i < codeCount; i++) {
- if (code[i] == which) {
+ if (codeDocs[i].getCode() == which) {
for (int j = i; j < codeCount-1; j++) {
- code[j] = code[j+1];
+ codeDocs[j] = codeDocs[j+1];
}
codeCount--;
- code = (SketchCode[]) PApplet.shorten(code);
+ codeDocs = (SketchCodeDocument[]) PApplet.shorten(codeDocs);
return;
}
}
@@ -689,7 +690,7 @@ public void setModified(boolean state) {
protected void calcModified() {
modified = false;
for (int i = 0; i < codeCount; i++) {
- if (code[i].isModified()) {
+ if (codeDocs[i].getCode().isModified()) {
modified = true;
break;
}
@@ -773,8 +774,8 @@ public boolean accept(File dir, String name) {
}
for (int i = 0; i < codeCount; i++) {
- if (code[i].isModified())
- code[i].save();
+ if (codeDocs[i].getCode().isModified())
+ codeDocs[i].getCode().save();
}
calcModified();
return true;
@@ -782,13 +783,13 @@ public boolean accept(File dir, String name) {
protected boolean renameCodeToInoExtension(File pdeFile) {
- for (SketchCode c : code) {
- if (!c.getFile().equals(pdeFile))
+ for (SketchCodeDocument c : codeDocs) {
+ if (!c.getCode().getFile().equals(pdeFile))
continue;
String pdeName = pdeFile.getPath();
pdeName = pdeName.substring(0, pdeName.length() - 4) + ".ino";
- return c.renameTo(new File(pdeName));
+ return c.getCode().renameTo(new File(pdeName));
}
return false;
}
@@ -834,8 +835,8 @@ protected boolean saveAs() throws IOException {
// but ignore this situation for the first tab, since it's probably being
// resaved (with the same name) to another location/folder.
for (int i = 1; i < codeCount; i++) {
- if (newName.equalsIgnoreCase(code[i].getPrettyName()) &&
- code[i].isExtension("cpp")) {
+ if (newName.equalsIgnoreCase(codeDocs[i].getCode().getPrettyName()) &&
+ codeDocs[i].getCode().isExtension("cpp")) {
Base.showMessage(_("Nope"),
I18n.format(
_("You can't save the sketch as \"{0}\"\n" +
@@ -886,8 +887,8 @@ protected boolean saveAs() throws IOException {
// save the other tabs to their new location
for (int i = 1; i < codeCount; i++) {
- File newFile = new File(newFolder, code[i].getFileName());
- code[i].saveAs(newFile);
+ File newFile = new File(newFolder, codeDocs[i].getCode().getFileName());
+ codeDocs[i].getCode().saveAs(newFile);
}
// re-copy the data folder (this may take a while.. add progress bar?)
@@ -912,7 +913,7 @@ protected boolean saveAs() throws IOException {
// save the main tab with its new name
File newFile = new File(newFolder, newName + ".ino");
- code[0].saveAs(newFile);
+ codeDocs[0].getCode().saveAs(newFile);
editor.handleOpenUnchecked(newFile,
currentIndex,
@@ -1095,7 +1096,7 @@ public boolean addFile(File sourceFile) {
if (editor.untitled) { // TODO probably not necessary? problematic?
// If a file has been added, mark the main code as modified so
// that the sketch is properly saved.
- code[0].setModified(true);
+ codeDocs[0].getCode().setModified(true);
}
}
return true;
@@ -1155,16 +1156,18 @@ public void setCurrentCode(int which) {
// get the text currently being edited
if (current != null) {
- current.setState(editor.getText(),
- editor.getSelectionStart(),
- editor.getSelectionStop(),
- editor.getScrollPosition());
+ current.setProgram(editor.getText());
+ currentCodeDoc.setSelectionStart(editor.getSelectionStart());
+ currentCodeDoc.setSelectionStop(editor.getSelectionStop());
+ currentCodeDoc.setScrollPosition(editor.getScrollPosition());
}
- current = code[which];
+ currentCodeDoc = codeDocs[which];
+ current = currentCodeDoc.getCode();
currentIndex = which;
- editor.setCode(current);
+ editor.setCode(currentCodeDoc);
+
editor.header.rebuild();
}
@@ -1175,8 +1178,8 @@ public void setCurrentCode(int which) {
*/
protected void setCurrentCode(String findName) {
for (int i = 0; i < codeCount; i++) {
- if (findName.equals(code[i].getFileName()) ||
- findName.equals(code[i].getPrettyName())) {
+ if (findName.equals(codeDocs[i].getCode().getFileName()) ||
+ findName.equals(codeDocs[i].getCode().getPrettyName())) {
setCurrentCode(i);
return;
}
@@ -1336,7 +1339,8 @@ public void preprocess(String buildPath, PdePreprocessor preprocessor) throws Ru
StringBuffer bigCode = new StringBuffer();
int bigCount = 0;
- for (SketchCode sc : code) {
+ for (SketchCodeDocument scd : codeDocs) {
+ SketchCode sc = scd.getCode();
if (sc.isExtension("ino") || sc.isExtension("pde")) {
sc.setPreprocOffset(bigCount);
// These #line directives help the compiler report errors with
@@ -1396,7 +1400,8 @@ public void preprocess(String buildPath, PdePreprocessor preprocessor) throws Ru
// 3. then loop over the code[] and save each .java file
- for (SketchCode sc : code) {
+ for (SketchCodeDocument scd : codeDocs) {
+ SketchCode sc = scd.getCode();
if (sc.isExtension("c") || sc.isExtension("cpp") || sc.isExtension("h")) {
// no pre-processing services necessary for java files
// just write the the contents of 'program' to a .java file
@@ -1769,7 +1774,7 @@ protected void ensureExistence() {
modified = true;
for (int i = 0; i < codeCount; i++) {
- code[i].save(); // this will force a save
+ codeDocs[i].getCode().save(); // this will force a save
}
calcModified();
@@ -1804,8 +1809,8 @@ public boolean isReadOnly() {
// check to see if each modified code file can be written to
for (int i = 0; i < codeCount; i++) {
- if (code[i].isModified() && code[i].fileReadOnly() &&
- code[i].fileExists()) {
+ if (codeDocs[i].getCode().isModified() && codeDocs[i].getCode().fileReadOnly() &&
+ codeDocs[i].getCode().fileExists()) {
// System.err.println("found a read-only file " + code[i].file);
return true;
}
@@ -1948,8 +1953,8 @@ public String getClassPath() {
}
- public SketchCode[] getCode() {
- return code;
+ public SketchCodeDocument[] getCodeDocs() {
+ return codeDocs;
}
@@ -1959,13 +1964,13 @@ public int getCodeCount() {
public SketchCode getCode(int index) {
- return code[index];
+ return codeDocs[index].getCode();
}
public int getCodeIndex(SketchCode who) {
for (int i = 0; i < codeCount; i++) {
- if (who == code[i]) {
+ if (who == codeDocs[i].getCode()) {
return i;
}
}
diff --git a/app/src/processing/app/SketchCode.java b/app/src/processing/app/SketchCode.java
index 91a8232e8d3..f7116735ffb 100644
--- a/app/src/processing/app/SketchCode.java
+++ b/app/src/processing/app/SketchCode.java
@@ -28,8 +28,6 @@
import java.util.List;
import java.util.Arrays;
-import javax.swing.text.Document;
-
import static processing.app.I18n._;
import processing.app.helpers.FileUtils;
@@ -47,21 +45,6 @@ public class SketchCode {
/** Text of the program text for this tab */
private String program;
- /** Document object for this tab. Currently this is a SyntaxDocument. */
- private Document document;
-
- /**
- * Undo Manager for this tab, each tab keeps track of their own
- * Editor.undo will be set to this object when this code is the tab
- * that's currently the front.
- */
- private LastUndoableEditAwareUndoManager undo = new LastUndoableEditAwareUndoManager();
-
- // saved positions from last time this tab was used
- private int selectionStart;
- private int selectionStop;
- private int scrollPosition;
-
private boolean modified;
/** name of .java file after preproc */
@@ -183,16 +166,6 @@ public boolean isModified() {
}
-// public void setPreprocName(String preprocName) {
-// this.preprocName = preprocName;
-// }
-//
-//
-// public String getPreprocName() {
-// return preprocName;
-// }
-
-
public void setPreprocOffset(int preprocOffset) {
this.preprocOffset = preprocOffset;
}
@@ -208,51 +181,6 @@ public void addPreprocOffset(int extra) {
}
- public Document getDocument() {
- return document;
- }
-
-
- public void setDocument(Document d) {
- document = d;
- }
-
-
- public LastUndoableEditAwareUndoManager getUndo() {
- return undo;
- }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- // TODO these could probably be handled better, since it's a general state
- // issue that's read/write from only one location in Editor (on tab switch.)
-
-
- public int getSelectionStart() {
- return selectionStart;
- }
-
-
- public int getSelectionStop() {
- return selectionStop;
- }
-
-
- public int getScrollPosition() {
- return scrollPosition;
- }
-
-
- protected void setState(String p, int start, int stop, int pos) {
- program = p;
- selectionStart = start;
- selectionStop = stop;
- scrollPosition = pos;
- }
-
-
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
diff --git a/app/src/processing/app/SketchCodeDocument.java b/app/src/processing/app/SketchCodeDocument.java
new file mode 100644
index 00000000000..3310e247990
--- /dev/null
+++ b/app/src/processing/app/SketchCodeDocument.java
@@ -0,0 +1,83 @@
+package processing.app;
+
+import java.io.File;
+
+import javax.swing.text.Document;
+
+public class SketchCodeDocument {
+
+ SketchCode code;
+
+ private Document document;
+
+ /**
+ * Undo Manager for this tab, each tab keeps track of their own
+ * Editor.undo will be set to this object when this code is the tab
+ * that's currently the front.
+ */
+ private LastUndoableEditAwareUndoManager undo = new LastUndoableEditAwareUndoManager();
+
+ public LastUndoableEditAwareUndoManager getUndo() {
+ return undo;
+ }
+
+ public void setUndo(LastUndoableEditAwareUndoManager undo) {
+ this.undo = undo;
+ }
+
+ public int getSelectionStart() {
+ return selectionStart;
+ }
+
+ public void setSelectionStart(int selectionStart) {
+ this.selectionStart = selectionStart;
+ }
+
+ public int getSelectionStop() {
+ return selectionStop;
+ }
+
+ public void setSelectionStop(int selectionStop) {
+ this.selectionStop = selectionStop;
+ }
+
+ public int getScrollPosition() {
+ return scrollPosition;
+ }
+
+ public void setScrollPosition(int scrollPosition) {
+ this.scrollPosition = scrollPosition;
+ }
+
+ // saved positions from last time this tab was used
+ private int selectionStart;
+ private int selectionStop;
+ private int scrollPosition;
+
+
+ public SketchCodeDocument(SketchCode sketchCode, Document doc) {
+ code = sketchCode;
+ document = doc;
+ }
+
+ public SketchCodeDocument(File file) {
+ code = new SketchCode(file);
+ }
+
+ public SketchCode getCode() {
+ return code;
+ }
+
+ public void setCode(SketchCode code) {
+ this.code = code;
+ }
+
+ public Document getDocument() {
+ return document;
+ }
+
+ public void setDocument(Document document) {
+ this.document = document;
+ }
+
+}
From 79ab98fef9cd45e3515a13877c818e7df1e9f3ff Mon Sep 17 00:00:00 2001
From: Claudio Indellicati
Date: Thu, 30 Jan 2014 15:50:09 +0100
Subject: [PATCH 13/73] Make Compiler independent from Sketch.
Create a class SketchData to store all relevant data for a sketch
(trying to keep GUI stuff out of the way).
Moved preprocessing code from Sketch to Compiler.
---
app/src/processing/app/Base.java | 2 +-
app/src/processing/app/Sketch.java | 398 ++++-----------------
app/src/processing/app/SketchCode.java | 6 +-
app/src/processing/app/SketchData.java | 108 ++++++
app/src/processing/app/debug/Compiler.java | 211 +++++++++--
5 files changed, 367 insertions(+), 358 deletions(-)
create mode 100644 app/src/processing/app/SketchData.java
diff --git a/app/src/processing/app/Base.java b/app/src/processing/app/Base.java
index 9132571b117..2821625528a 100644
--- a/app/src/processing/app/Base.java
+++ b/app/src/processing/app/Base.java
@@ -105,7 +105,7 @@ public class Base {
static private LibraryList libraries;
// maps #included files to their library folder
- static Map importToLibraryTable;
+ public static Map importToLibraryTable;
// classpath for all known libraries for p5
// (both those in the p5/libs folder and those with lib subfolders
diff --git a/app/src/processing/app/Sketch.java b/app/src/processing/app/Sketch.java
index 9d7690a4aa0..970685485ce 100644
--- a/app/src/processing/app/Sketch.java
+++ b/app/src/processing/app/Sketch.java
@@ -29,13 +29,11 @@
import cc.arduino.packages.Uploader;
import processing.app.debug.*;
import processing.app.debug.Compiler;
+import processing.app.debug.Compiler.ProgressListener;
import processing.app.forms.PasswordAuthorizationDialog;
import processing.app.helpers.PreferencesMap;
import processing.app.helpers.FileUtils;
import processing.app.packages.Library;
-import processing.app.packages.LibraryList;
-import processing.app.preproc.*;
-import processing.core.*;
import static processing.app.I18n._;
import java.io.*;
@@ -55,12 +53,6 @@ public class Sketch {
/** main pde file for this sketch. */
private File primaryFile;
- /**
- * Name of sketch, which is the name of main file
- * (without .pde or .java extension)
- */
- private String name;
-
/** true if any of the files have been modified. */
private boolean modified;
@@ -77,25 +69,10 @@ public class Sketch {
private SketchCodeDocument currentCodeDoc;
private int currentIndex;
- /**
- * Number of sketchCode objects (tabs) in the current sketch. Note that this
- * will be the same as code.length, because the getCode() method returns
- * just the code[] array, rather than a copy of it, or an array that's been
- * resized to just the relevant files themselves.
- * http://dev.processing.org/bugs/show_bug.cgi?id=940
- */
- private int codeCount;
- private SketchCodeDocument[] codeDocs;
+ private SketchData data;
/** Class name for the PApplet, as determined by the preprocessor. */
private String appletClassName;
- /** Class path determined during build. */
- private String classPath;
-
- /**
- * List of library folders.
- */
- private LibraryList importedLibraries;
/**
* File inside the build directory that contains the build options
@@ -107,16 +84,16 @@ public class Sketch {
* path is location of the main .pde file, because this is also
* simplest to use when opening the file from the finder/explorer.
*/
- public Sketch(Editor editor, File file) throws IOException {
- this.editor = editor;
-
+ public Sketch(Editor _editor, File file) throws IOException {
+ editor = _editor;
+ data = new SketchData();
primaryFile = file;
// get the name of the sketch by chopping .pde or .java
// off of the main file name
String mainFilename = primaryFile.getName();
int suffixLength = getDefaultExtension().length() + 1;
- name = mainFilename.substring(0, mainFilename.length() - suffixLength);
+ data.setName(mainFilename.substring(0, mainFilename.length() - suffixLength));
// lib/build must exist when the application is started
// it is added to the CLASSPATH by default, but if it doesn't
@@ -167,9 +144,7 @@ protected void load() throws IOException {
// reset these because load() may be called after an
// external editor event. (fix for 0099)
- codeCount = 0;
-
- codeDocs = new SketchCodeDocument[list.length];
+ data.clearCodeDocs();
List extensions = getExtensions();
@@ -192,8 +167,7 @@ protected void load() throws IOException {
// Don't allow people to use files with invalid names, since on load,
// it would be otherwise possible to sneak in nasty filenames. [0116]
if (Sketch.isSanitaryName(base)) {
- codeDocs[codeCount++] =
- new SketchCodeDocument(new File(folder, filename));
+ data.addCodeDoc(new SketchCodeDocument(new File(folder, filename)));
} else {
System.err.println(I18n.format("File name {0} is invalid: ignored", filename));
}
@@ -201,26 +175,21 @@ protected void load() throws IOException {
}
}
- if (codeCount == 0)
+ if (data.getCodeCount() == 0)
throw new IOException(_("No valid code files found"));
- // Remove any code that wasn't proper
- codeDocs = (SketchCodeDocument[]) PApplet.subset(codeDocs, 0, codeCount);
-
// move the main class to the first tab
// start at 1, if it's at zero, don't bother
- for (int i = 1; i < codeCount; i++) {
+ for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
//if (code[i].file.getName().equals(mainFilename)) {
- if (codeDocs[i].getCode().getFile().equals(primaryFile)) {
- SketchCodeDocument temp = codeDocs[0];
- codeDocs[0] = codeDocs[i];
- codeDocs[i] = temp;
+ if (codeDoc.getCode().getFile().equals(primaryFile)) {
+ data.moveCodeDocToFront(codeDoc);
break;
}
}
// sort the entries at the top
- sortCode();
+ data.sortCode();
// set the main file to be the current tab
if (editor != null) {
@@ -229,47 +198,6 @@ protected void load() throws IOException {
}
- protected void replaceCode(SketchCode newCode) {
- for (int i = 0; i < codeCount; i++) {
- if (codeDocs[i].getCode().getFileName().equals(newCode.getFileName())) {
- codeDocs[i].setCode(newCode);
- break;
- }
- }
- }
-
-
- protected void insertCode(SketchCode newCode) {
- // make sure the user didn't hide the sketch folder
- ensureExistence();
-
- // add file to the code/codeCount list, resort the list
- //if (codeCount == code.length) {
- codeDocs = (SketchCodeDocument[]) PApplet.append(codeDocs, newCode);
- codeCount++;
- //}
- //code[codeCount++] = newCode;
- }
-
-
- protected void sortCode() {
- // cheap-ass sort of the rest of the files
- // it's a dumb, slow sort, but there shouldn't be more than ~5 files
- for (int i = 1; i < codeCount; i++) {
- int who = i;
- for (int j = i + 1; j < codeCount; j++) {
- if (codeDocs[j].getCode().getFileName().compareTo(codeDocs[who].getCode().getFileName()) < 0) {
- who = j; // this guy is earlier in the alphabet
- }
- }
- if (who != i) { // swap with someone if changes made
- SketchCodeDocument temp = codeDocs[who];
- codeDocs[who] = codeDocs[i];
- codeDocs[i] = temp;
- }
- }
- }
-
boolean renamingCode;
/**
@@ -380,7 +308,7 @@ protected void nameCode(String newName) {
// Don't let the user create the main tab as a .java file instead of .pde
if (!isDefaultExtension(newExtension)) {
if (renamingCode) { // If creating a new tab, don't show this error
- if (current == codeDocs[0].getCode()) { // If this is the main tab, disallow
+ if (current == data.getCodeDoc(0).getCode()) { // If this is the main tab, disallow
Base.showWarning(_("Problem with rename"),
_("The main file can't use an extension.\n" +
"(It may be time for your to graduate to a\n" +
@@ -402,7 +330,7 @@ protected void nameCode(String newName) {
// In Arduino, we want to allow files with the same name but different
// extensions, so compare the full names (including extensions). This
// might cause problems: http://dev.processing.org/bugs/show_bug.cgi?id=543
- for (SketchCodeDocument c : codeDocs) {
+ for (SketchCodeDocument c : data.getCodeDocs()) {
if (newName.equalsIgnoreCase(c.getCode().getFileName())) {
Base.showMessage(_("Nope"),
I18n.format(
@@ -424,9 +352,9 @@ protected void nameCode(String newName) {
}
if (renamingCode && currentIndex == 0) {
- for (int i = 1; i < codeCount; i++) {
- if (sanitaryName.equalsIgnoreCase(codeDocs[i].getCode().getPrettyName()) &&
- codeDocs[i].getCode().isExtension("cpp")) {
+ for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
+ if (sanitaryName.equalsIgnoreCase(codeDoc.getCode().getPrettyName()) &&
+ codeDoc.getCode().isExtension("cpp")) {
Base.showMessage(_("Nope"),
I18n.format(
_("You can't rename the sketch to \"{0}\"\n" +
@@ -500,8 +428,8 @@ protected void nameCode(String newName) {
// save each of the other tabs because this is gonna be re-opened
try {
- for (int i = 1; i < codeCount; i++) {
- codeDocs[i].getCode().save();
+ for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
+ codeDoc.getCode().save();
}
} catch (Exception e) {
Base.showWarning(_("Error"), _("Could not rename the sketch. (1)"), e);
@@ -560,11 +488,12 @@ protected void nameCode(String newName) {
}
SketchCode newCode = new SketchCode(newFile);
//System.out.println("new code is named " + newCode.getPrettyName() + " " + newCode.getFile());
- insertCode(newCode);
+ ensureExistence();
+ data.insertCode(newCode);
}
// sort the entries
- sortCode();
+ data.sortCode();
// set the new guy as current
setCurrentCode(newName);
@@ -629,7 +558,7 @@ public void handleDeleteCode() {
}
// remove code from the list
- removeCode(current);
+ data.removeCode(current);
// just set current tab to the main tab
setCurrentCode(0);
@@ -641,29 +570,12 @@ public void handleDeleteCode() {
}
- protected void removeCode(SketchCode which) {
- // remove it from the internal list of files
- // resort internal list of files
- for (int i = 0; i < codeCount; i++) {
- if (codeDocs[i].getCode() == which) {
- for (int j = i; j < codeCount-1; j++) {
- codeDocs[j] = codeDocs[j+1];
- }
- codeCount--;
- codeDocs = (SketchCodeDocument[]) PApplet.shorten(codeDocs);
- return;
- }
- }
- System.err.println(_("removeCode: internal error.. could not find code"));
- }
-
-
/**
* Move to the previous tab.
*/
public void handlePrevCode() {
int prev = currentIndex - 1;
- if (prev < 0) prev = codeCount-1;
+ if (prev < 0) prev = data.getCodeCount()-1;
setCurrentCode(prev);
}
@@ -672,7 +584,7 @@ public void handlePrevCode() {
* Move to the next tab.
*/
public void handleNextCode() {
- setCurrentCode((currentIndex + 1) % codeCount);
+ setCurrentCode((currentIndex + 1) % data.getCodeCount());
}
@@ -689,8 +601,8 @@ public void setModified(boolean state) {
protected void calcModified() {
modified = false;
- for (int i = 0; i < codeCount; i++) {
- if (codeDocs[i].getCode().isModified()) {
+ for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
+ if (codeDoc.getCode().isModified()) {
modified = true;
break;
}
@@ -773,9 +685,9 @@ public boolean accept(File dir, String name) {
}
}
- for (int i = 0; i < codeCount; i++) {
- if (codeDocs[i].getCode().isModified())
- codeDocs[i].getCode().save();
+ for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
+ if (codeDoc.getCode().isModified())
+ codeDoc.getCode().save();
}
calcModified();
return true;
@@ -783,7 +695,7 @@ public boolean accept(File dir, String name) {
protected boolean renameCodeToInoExtension(File pdeFile) {
- for (SketchCodeDocument c : codeDocs) {
+ for (SketchCodeDocument c : data.getCodeDocs()) {
if (!c.getCode().getFile().equals(pdeFile))
continue;
@@ -834,9 +746,9 @@ protected boolean saveAs() throws IOException {
// make sure there doesn't exist a .cpp file with that name already
// but ignore this situation for the first tab, since it's probably being
// resaved (with the same name) to another location/folder.
- for (int i = 1; i < codeCount; i++) {
- if (newName.equalsIgnoreCase(codeDocs[i].getCode().getPrettyName()) &&
- codeDocs[i].getCode().isExtension("cpp")) {
+ for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
+ if (newName.equalsIgnoreCase(codeDoc.getCode().getPrettyName()) &&
+ codeDoc.getCode().isExtension("cpp")) {
Base.showMessage(_("Nope"),
I18n.format(
_("You can't save the sketch as \"{0}\"\n" +
@@ -886,9 +798,10 @@ protected boolean saveAs() throws IOException {
}
// save the other tabs to their new location
- for (int i = 1; i < codeCount; i++) {
- File newFile = new File(newFolder, codeDocs[i].getCode().getFileName());
- codeDocs[i].getCode().saveAs(newFile);
+ for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
+ if (data.indexOfCodeDoc(codeDoc) == 0) continue;
+ File newFile = new File(newFolder, codeDoc.getCode().getFileName());
+ codeDoc.getCode().saveAs(newFile);
}
// re-copy the data folder (this may take a while.. add progress bar?)
@@ -913,7 +826,7 @@ protected boolean saveAs() throws IOException {
// save the main tab with its new name
File newFile = new File(newFolder, newName + ".ino");
- codeDocs[0].getCode().saveAs(newFile);
+ data.getCodeDoc(0).getCode().saveAs(newFile);
editor.handleOpenUnchecked(newFile,
currentIndex,
@@ -1079,11 +992,12 @@ public boolean addFile(File sourceFile) {
SketchCode newCode = new SketchCode(destFile);
if (replacement) {
- replaceCode(newCode);
+ data.replaceCode(newCode);
} else {
- insertCode(newCode);
- sortCode();
+ ensureExistence();
+ data.insertCode(newCode);
+ data.sortCode();
}
setCurrentCode(filename);
editor.header.repaint();
@@ -1096,7 +1010,7 @@ public boolean addFile(File sourceFile) {
if (editor.untitled) { // TODO probably not necessary? problematic?
// If a file has been added, mark the main code as modified so
// that the sketch is properly saved.
- codeDocs[0].getCode().setModified(true);
+ data.getCodeDoc(0).getCode().setModified(true);
}
}
return true;
@@ -1162,7 +1076,7 @@ public void setCurrentCode(int which) {
currentCodeDoc.setScrollPosition(editor.getScrollPosition());
}
- currentCodeDoc = codeDocs[which];
+ currentCodeDoc = data.getCodeDoc(which);
current = currentCodeDoc.getCode();
currentIndex = which;
@@ -1177,10 +1091,10 @@ public void setCurrentCode(int which) {
* @param findName the file name (not pretty name) to be shown
*/
protected void setCurrentCode(String findName) {
- for (int i = 0; i < codeCount; i++) {
- if (findName.equals(codeDocs[i].getCode().getFileName()) ||
- findName.equals(codeDocs[i].getCode().getPrettyName())) {
- setCurrentCode(i);
+ for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
+ if (findName.equals(codeDoc.getCode().getFileName()) ||
+ findName.equals(codeDoc.getCode().getPrettyName())) {
+ setCurrentCode(data.indexOfCodeDoc(codeDoc));
return;
}
}
@@ -1290,144 +1204,6 @@ public void prepare() throws IOException {
}
- /**
- * Build all the code for this sketch.
- *
- * In an advanced program, the returned class name could be different,
- * which is why the className is set based on the return value.
- * A compilation error will burp up a RunnerException.
- *
- * Setting purty to 'true' will cause exception line numbers to be incorrect.
- * Unless you know the code compiles, you should first run the preprocessor
- * with purty set to false to make sure there are no errors, then once
- * successful, re-export with purty set to true.
- *
- * @param buildPath Location to copy all the .java files
- * @return null if compilation failed, main class name if not
- */
- public void preprocess(String buildPath) throws RunnerException {
- preprocess(buildPath, new PdePreprocessor());
- }
-
- public void preprocess(String buildPath, PdePreprocessor preprocessor) throws RunnerException {
- // make sure the user didn't hide the sketch folder
- ensureExistence();
-
- classPath = buildPath;
-
-// // figure out the contents of the code folder to see if there
-// // are files that need to be added to the imports
-// if (codeFolder.exists()) {
-// libraryPath = codeFolder.getAbsolutePath();
-//
-// // get a list of .jar files in the "code" folder
-// // (class files in subfolders should also be picked up)
-// String codeFolderClassPath =
-// Compiler.contentsToClassPath(codeFolder);
-// // append the jar files in the code folder to the class path
-// classPath += File.pathSeparator + codeFolderClassPath;
-// // get list of packages found in those jars
-// codeFolderPackages =
-// Compiler.packageListFromClassPath(codeFolderClassPath);
-//
-// } else {
-// libraryPath = "";
-// }
-
- // 1. concatenate all .pde files to the 'main' pde
- // store line number for starting point of each code bit
-
- StringBuffer bigCode = new StringBuffer();
- int bigCount = 0;
- for (SketchCodeDocument scd : codeDocs) {
- SketchCode sc = scd.getCode();
- if (sc.isExtension("ino") || sc.isExtension("pde")) {
- sc.setPreprocOffset(bigCount);
- // These #line directives help the compiler report errors with
- // correct the filename and line number (issue 281 & 907)
- bigCode.append("#line 1 \"" + sc.getFileName() + "\"\n");
- bigCode.append(sc.getProgram());
- bigCode.append('\n');
- bigCount += sc.getLineCount();
- }
- }
-
- // Note that the headerOffset isn't applied until compile and run, because
- // it only applies to the code after it's been written to the .java file.
- int headerOffset = 0;
- try {
- headerOffset = preprocessor.writePrefix(bigCode.toString());
- } catch (FileNotFoundException fnfe) {
- fnfe.printStackTrace();
- String msg = _("Build folder disappeared or could not be written");
- throw new RunnerException(msg);
- }
-
- // 2. run preproc on that code using the sugg class name
- // to create a single .java file and write to buildpath
-
- try {
- // Output file
- File streamFile = new File(buildPath, name + ".cpp");
- FileOutputStream outputStream = new FileOutputStream(streamFile);
- preprocessor.write(outputStream);
- outputStream.close();
- } catch (FileNotFoundException fnfe) {
- fnfe.printStackTrace();
- String msg = _("Build folder disappeared or could not be written");
- throw new RunnerException(msg);
- } catch (RunnerException pe) {
- // RunnerExceptions are caught here and re-thrown, so that they don't
- // get lost in the more general "Exception" handler below.
- throw pe;
-
- } catch (Exception ex) {
- // TODO better method for handling this?
- System.err.println(I18n.format(_("Uncaught exception type: {0}"), ex.getClass()));
- ex.printStackTrace();
- throw new RunnerException(ex.toString());
- }
-
- // grab the imports from the code just preproc'd
-
- importedLibraries = new LibraryList();
- for (String item : preprocessor.getExtraImports()) {
- Library lib = Base.importToLibraryTable.get(item);
- if (lib != null && !importedLibraries.contains(lib)) {
- importedLibraries.add(lib);
- }
- }
-
- // 3. then loop over the code[] and save each .java file
-
- for (SketchCodeDocument scd : codeDocs) {
- SketchCode sc = scd.getCode();
- if (sc.isExtension("c") || sc.isExtension("cpp") || sc.isExtension("h")) {
- // no pre-processing services necessary for java files
- // just write the the contents of 'program' to a .java file
- // into the build directory. uses byte stream and reader/writer
- // shtuff so that unicode bunk is properly handled
- String filename = sc.getFileName(); //code[i].name + ".java";
- try {
- Base.saveFile(sc.getProgram(), new File(buildPath, filename));
- } catch (IOException e) {
- e.printStackTrace();
- throw new RunnerException(I18n.format(_("Problem moving {0} to the build folder"), filename));
- }
-// sc.setPreprocName(filename);
-
- } else if (sc.isExtension("ino") || sc.isExtension("pde")) {
- // The compiler and runner will need this to have a proper offset
- sc.addPreprocOffset(headerOffset);
- }
- }
- }
-
-
- public LibraryList getImportedLibraries() {
- return importedLibraries;
- }
-
/**
* Map an error from a set of processed .java files back to its location
@@ -1479,31 +1255,6 @@ public LibraryList getImportedLibraries() {
// }
- /**
- * Map an error from a set of processed .java files back to its location
- * in the actual sketch.
- * @param message The error message.
- * @param dotJavaFilename The .java file where the exception was found.
- * @param dotJavaLine Line number of the .java file for the exception (0-indexed!)
- * @return A RunnerException to be sent to the editor, or null if it wasn't
- * possible to place the exception to the sketch code.
- */
- public RunnerException placeException(String message,
- String dotJavaFilename,
- int dotJavaLine) {
- // Placing errors is simple, because we inserted #line directives
- // into the preprocessed source. The compiler gives us correct
- // the file name and line number. :-)
- for (int codeIndex = 0; codeIndex < getCodeCount(); codeIndex++) {
- SketchCode code = getCode(codeIndex);
- if (dotJavaFilename.equals(code.getFileName())) {
- return new RunnerException(message, codeIndex, dotJavaLine);
- }
- }
- return null;
- }
-
-
/**
* Run the build inside the temporary build folder.
* @return null if compilation failed, main class name if not
@@ -1564,8 +1315,8 @@ protected String buildPrefsString(Compiler compiler) {
* @return null if compilation failed, main class name if not
*/
public String build(String buildPath, boolean verbose) throws RunnerException {
- String primaryClassName = name + ".cpp";
- Compiler compiler = new Compiler(this, buildPath, primaryClassName);
+ String primaryClassName = data.getName() + ".cpp";
+ Compiler compiler = new Compiler(data, buildPath, primaryClassName);
File buildPrefsFile = new File(buildPath, BUILD_PREFS_FILE);
String newBuildPrefs = buildPrefsString(compiler);
@@ -1586,8 +1337,16 @@ public String build(String buildPath, boolean verbose) throws RunnerException {
// run the preprocessor
editor.status.progressUpdate(20);
- preprocess(buildPath);
+ ensureExistence();
+
+ compiler.setProgressListener(new ProgressListener() {
+ @Override
+ public void progress(int percent) {
+ editor.status.progressUpdate(percent);
+ }
+ });
+
// compile the program. errors will happen as a RunnerException
// that will bubble up to whomever called build().
if (compiler.compile(verbose)) {
@@ -1632,11 +1391,6 @@ public boolean exportApplet(String appletPath, boolean usingProgrammer)
}
- public void setCompilingProgress(int percent) {
- editor.status.progressUpdate(percent);
- }
-
-
protected void size(PreferencesMap prefs) throws RunnerException {
String maxTextSizeString = prefs.get("upload.maximum_size");
String maxDataSizeString = prefs.get("upload.maximum_data_size");
@@ -1773,8 +1527,8 @@ protected void ensureExistence() {
folder.mkdirs();
modified = true;
- for (int i = 0; i < codeCount; i++) {
- codeDocs[i].getCode().save(); // this will force a save
+ for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
+ codeDoc.getCode().save(); // this will force a save
}
calcModified();
@@ -1808,9 +1562,9 @@ public boolean isReadOnly() {
// } else if (!folder.canWrite()) {
// check to see if each modified code file can be written to
- for (int i = 0; i < codeCount; i++) {
- if (codeDocs[i].getCode().isModified() && codeDocs[i].getCode().fileReadOnly() &&
- codeDocs[i].getCode().fileExists()) {
+ for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
+ if (codeDoc.getCode().isModified() && codeDoc.getCode().fileReadOnly() &&
+ codeDoc.getCode().fileExists()) {
// System.err.println("found a read-only file " + code[i].file);
return true;
}
@@ -1879,7 +1633,7 @@ public List getExtensions() {
* Returns the name of this sketch. (The pretty name of the main tab.)
*/
public String getName() {
- return name;
+ return data.getName();
}
@@ -1948,33 +1702,23 @@ public File prepareCodeFolder() {
}
- public String getClassPath() {
- return classPath;
- }
-
-
public SketchCodeDocument[] getCodeDocs() {
- return codeDocs;
+ return data.getCodeDocs();
}
public int getCodeCount() {
- return codeCount;
+ return data.getCodeCount();
}
public SketchCode getCode(int index) {
- return codeDocs[index].getCode();
+ return data.getCodeDoc(index).getCode();
}
public int getCodeIndex(SketchCode who) {
- for (int i = 0; i < codeCount; i++) {
- if (who == codeDocs[i].getCode()) {
- return i;
- }
- }
- return -1;
+ return data.indexOfCode(who);
}
diff --git a/app/src/processing/app/SketchCode.java b/app/src/processing/app/SketchCode.java
index f7116735ffb..a2e0bb77287 100644
--- a/app/src/processing/app/SketchCode.java
+++ b/app/src/processing/app/SketchCode.java
@@ -1,5 +1,3 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
/*
SketchCode - data class for a single file inside a sketch
Part of the Processing project - http://processing.org
@@ -31,11 +29,11 @@
import static processing.app.I18n._;
import processing.app.helpers.FileUtils;
-
/**
* Represents a single tab of a sketch.
*/
public class SketchCode {
+
/** Pretty name (no extension), not the full file name */
private String prettyName;
@@ -47,8 +45,6 @@ public class SketchCode {
private boolean modified;
- /** name of .java file after preproc */
-// private String preprocName;
/** where this code starts relative to the concat'd code */
private int preprocOffset;
diff --git a/app/src/processing/app/SketchData.java b/app/src/processing/app/SketchData.java
new file mode 100644
index 00000000000..81471d62aff
--- /dev/null
+++ b/app/src/processing/app/SketchData.java
@@ -0,0 +1,108 @@
+package processing.app;
+
+import static processing.app.I18n._;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+public class SketchData {
+
+ /**
+ * Name of sketch, which is the name of main file (without .pde or .java
+ * extension)
+ */
+ private String name;
+
+ private List codeDocs = new ArrayList();
+
+ private static final Comparator CODE_DOCS_COMPARATOR = new Comparator() {
+ @Override
+ public int compare(SketchCodeDocument cd1, SketchCodeDocument cd2) {
+ return cd1.getCode().getFileName().compareTo(cd2.getCode().getFileName());
+ }
+ };
+
+
+ public int getCodeCount() {
+ return codeDocs.size();
+ }
+
+ public SketchCodeDocument[] getCodeDocs() {
+ return codeDocs.toArray(new SketchCodeDocument[0]);
+ }
+
+ public void addCodeDoc(SketchCodeDocument sketchCodeDoc) {
+ codeDocs.add(sketchCodeDoc);
+ }
+
+ public void moveCodeDocToFront(SketchCodeDocument codeDoc) {
+ codeDocs.remove(codeDoc);
+ codeDocs.add(0, codeDoc);
+ }
+
+ protected void replaceCode(SketchCode newCode) {
+ for (SketchCodeDocument codeDoc : codeDocs) {
+ if (codeDoc.getCode().getFileName().equals(newCode.getFileName())) {
+ codeDoc.setCode(newCode);
+ return;
+ }
+ }
+ }
+
+ protected void insertCode(SketchCode sketchCode) {
+ addCodeDoc(new SketchCodeDocument(sketchCode, null));
+ }
+
+ protected void sortCode() {
+ if (codeDocs.size() < 2)
+ return;
+ SketchCodeDocument first = codeDocs.remove(0);
+ Collections.sort(codeDocs, CODE_DOCS_COMPARATOR);
+ codeDocs.add(0, first);
+ }
+
+ public SketchCodeDocument getCodeDoc(int i) {
+ return codeDocs.get(i);
+ }
+
+ public SketchCode getCode(int i) {
+ return codeDocs.get(i).getCode();
+ }
+
+ protected void removeCode(SketchCode which) {
+ for (SketchCodeDocument codeDoc : codeDocs) {
+ if (codeDoc.getCode() == which) {
+ codeDocs.remove(codeDoc);
+ return;
+ }
+ }
+ System.err.println(_("removeCode: internal error.. could not find code"));
+ }
+
+ public int indexOfCodeDoc(SketchCodeDocument codeDoc) {
+ return codeDocs.indexOf(codeDoc);
+ }
+
+ public int indexOfCode(SketchCode who) {
+ for (SketchCodeDocument codeDoc : codeDocs) {
+ if (codeDoc.getCode() == who) {
+ return codeDocs.indexOf(codeDoc);
+ }
+ }
+ return -1;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void clearCodeDocs() {
+ codeDocs.clear();
+ }
+}
diff --git a/app/src/processing/app/debug/Compiler.java b/app/src/processing/app/debug/Compiler.java
index 0f43840a303..da601f56304 100644
--- a/app/src/processing/app/debug/Compiler.java
+++ b/app/src/processing/app/debug/Compiler.java
@@ -27,6 +27,8 @@
import java.io.BufferedReader;
import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
@@ -37,59 +39,84 @@
import processing.app.Base;
import processing.app.I18n;
import processing.app.Preferences;
-import processing.app.Sketch;
import processing.app.SketchCode;
+import processing.app.SketchCodeDocument;
+import processing.app.SketchData;
import processing.app.helpers.FileUtils;
import processing.app.helpers.PreferencesMap;
import processing.app.helpers.ProcessUtils;
import processing.app.helpers.StringReplacer;
import processing.app.helpers.filefilters.OnlyDirs;
import processing.app.packages.Library;
+import processing.app.packages.LibraryList;
+import processing.app.preproc.PdePreprocessor;
import processing.core.PApplet;
public class Compiler implements MessageConsumer {
- private Sketch sketch;
+ private SketchData sketch;
+ private PreferencesMap prefs;
+ private boolean verbose;
private List objectFiles;
- private PreferencesMap prefs;
- private boolean verbose;
private boolean sketchIsCompiled;
- private String targetArch;
private RunnerException exception;
+ /**
+ * Listener interface for progress update on the GUI
+ */
+ public interface ProgressListener {
+ public void progress(int percent);
+ }
+
+ private ProgressListener progressListener;
+
/**
* Create a new Compiler
* @param _sketch Sketch object to be compiled.
* @param _buildPath Where the temporary files live and will be built from.
* @param _primaryClassName the name of the combined sketch file w/ extension
*/
- public Compiler(Sketch _sketch, String _buildPath, String _primaryClassName)
+ public Compiler(SketchData _sketch, String _buildPath, String _primaryClassName)
throws RunnerException {
sketch = _sketch;
prefs = createBuildPreferences(_buildPath, _primaryClassName);
+
+ // Start with an empty progress listener
+ progressListener = new ProgressListener() {
+ @Override
+ public void progress(int percent) {
+ }
+ };
}
+ public void setProgressListener(ProgressListener _progressListener) {
+ progressListener = _progressListener;
+ }
+
/**
* Compile sketch.
+ * @param buildPath
*
* @return true if successful.
* @throws RunnerException Only if there's a problem. Only then.
*/
public boolean compile(boolean _verbose) throws RunnerException {
+ preprocess(prefs.get("build.path"));
+
verbose = _verbose || Preferences.getBoolean("build.verbose");
sketchIsCompiled = false;
objectFiles = new ArrayList();
// 0. include paths for core + all libraries
- sketch.setCompilingProgress(20);
+ progressListener.progress(20);
List includeFolders = new ArrayList();
includeFolders.add(prefs.getFile("build.core.path"));
if (prefs.getFile("build.variant.path") != null)
includeFolders.add(prefs.getFile("build.variant.path"));
- for (Library lib : sketch.getImportedLibraries()) {
+ for (Library lib : importedLibraries) {
if (verbose)
System.out.println(I18n
.format(_("Using library {0} in folder: {1} {2}"), lib.getName(),
@@ -105,7 +132,7 @@ public boolean compile(boolean _verbose) throws RunnerException {
String[] overrides = prefs.get("architecture.override_check").split(",");
archs.addAll(Arrays.asList(overrides));
}
- for (Library lib : sketch.getImportedLibraries()) {
+ for (Library lib : importedLibraries) {
if (!lib.supportsArchitecture(archs)) {
System.err.println(I18n
.format(_("WARNING: library {0} claims to run on {1} "
@@ -117,33 +144,33 @@ public boolean compile(boolean _verbose) throws RunnerException {
}
// 1. compile the sketch (already in the buildPath)
- sketch.setCompilingProgress(30);
+ progressListener.progress(30);
compileSketch(includeFolders);
sketchIsCompiled = true;
// 2. compile the libraries, outputting .o files to: //
// Doesn't really use configPreferences
- sketch.setCompilingProgress(40);
+ progressListener.progress(40);
compileLibraries(includeFolders);
// 3. compile the core, outputting .o files to and then
// collecting them into the core.a library file.
- sketch.setCompilingProgress(50);
+ progressListener.progress(50);
compileCore();
// 4. link it all together into the .elf file
- sketch.setCompilingProgress(60);
+ progressListener.progress(60);
compileLink();
// 5. extract EEPROM data (from EEMEM directive) to .eep file.
- sketch.setCompilingProgress(70);
+ progressListener.progress(70);
compileEep();
// 6. build the .hex file
- sketch.setCompilingProgress(80);
+ progressListener.progress(80);
compileHex();
- sketch.setCompilingProgress(90);
+ progressListener.progress(90);
return true;
}
@@ -190,8 +217,7 @@ private PreferencesMap createBuildPreferences(String _buildPath,
p.put("build.path", _buildPath);
p.put("build.project_name", _primaryClassName);
- targetArch = targetPlatform.getId();
- p.put("build.arch", targetArch.toUpperCase());
+ p.put("build.arch", targetPlatform.getId().toUpperCase());
// Platform.txt should define its own compiler.path. For
// compatibility with earlier 1.5 versions, we define a (ugly,
@@ -356,8 +382,6 @@ private boolean isAlreadyCompiled(File src, File obj, File dep, Map includeFolders) throws RunnerException {
// 2. compile the libraries, outputting .o files to:
// //
void compileLibraries(List includeFolders) throws RunnerException {
- for (Library lib : sketch.getImportedLibraries()) {
+ for (Library lib : importedLibraries) {
compileLibrary(lib, includeFolders);
}
}
@@ -853,4 +874,144 @@ private static String prepareIncludes(List includeFolders) {
public PreferencesMap getBuildPreferences() {
return prefs;
}
+
+ /**
+ * Build all the code for this sketch.
+ *
+ * In an advanced program, the returned class name could be different,
+ * which is why the className is set based on the return value.
+ * A compilation error will burp up a RunnerException.
+ *
+ * Setting purty to 'true' will cause exception line numbers to be incorrect.
+ * Unless you know the code compiles, you should first run the preprocessor
+ * with purty set to false to make sure there are no errors, then once
+ * successful, re-export with purty set to true.
+ *
+ * @param buildPath Location to copy all the .java files
+ * @return null if compilation failed, main class name if not
+ */
+ public void preprocess(String buildPath) throws RunnerException {
+ preprocess(buildPath, new PdePreprocessor());
+ }
+
+ public void preprocess(String buildPath, PdePreprocessor preprocessor) throws RunnerException {
+
+ // 1. concatenate all .pde files to the 'main' pde
+ // store line number for starting point of each code bit
+
+ StringBuffer bigCode = new StringBuffer();
+ int bigCount = 0;
+ for (SketchCodeDocument scd : sketch.getCodeDocs()) {
+ SketchCode sc = scd.getCode();
+ if (sc.isExtension("ino") || sc.isExtension("pde")) {
+ sc.setPreprocOffset(bigCount);
+ // These #line directives help the compiler report errors with
+ // correct the filename and line number (issue 281 & 907)
+ bigCode.append("#line 1 \"" + sc.getFileName() + "\"\n");
+ bigCode.append(sc.getProgram());
+ bigCode.append('\n');
+ bigCount += sc.getLineCount();
+ }
+ }
+
+ // Note that the headerOffset isn't applied until compile and run, because
+ // it only applies to the code after it's been written to the .java file.
+ int headerOffset = 0;
+ try {
+ headerOffset = preprocessor.writePrefix(bigCode.toString());
+ } catch (FileNotFoundException fnfe) {
+ fnfe.printStackTrace();
+ String msg = _("Build folder disappeared or could not be written");
+ throw new RunnerException(msg);
+ }
+
+ // 2. run preproc on that code using the sugg class name
+ // to create a single .java file and write to buildpath
+
+ try {
+ // Output file
+ File streamFile = new File(buildPath, sketch.getName() + ".cpp");
+ FileOutputStream outputStream = new FileOutputStream(streamFile);
+ preprocessor.write(outputStream);
+ outputStream.close();
+ } catch (FileNotFoundException fnfe) {
+ fnfe.printStackTrace();
+ String msg = _("Build folder disappeared or could not be written");
+ throw new RunnerException(msg);
+ } catch (RunnerException pe) {
+ // RunnerExceptions are caught here and re-thrown, so that they don't
+ // get lost in the more general "Exception" handler below.
+ throw pe;
+
+ } catch (Exception ex) {
+ // TODO better method for handling this?
+ System.err.println(I18n.format(_("Uncaught exception type: {0}"), ex.getClass()));
+ ex.printStackTrace();
+ throw new RunnerException(ex.toString());
+ }
+
+ // grab the imports from the code just preproc'd
+
+ importedLibraries = new LibraryList();
+ for (String item : preprocessor.getExtraImports()) {
+ Library lib = Base.importToLibraryTable.get(item);
+ if (lib != null && !importedLibraries.contains(lib)) {
+ importedLibraries.add(lib);
+ }
+ }
+
+ // 3. then loop over the code[] and save each .java file
+
+ for (SketchCodeDocument scd : sketch.getCodeDocs()) {
+ SketchCode sc = scd.getCode();
+ if (sc.isExtension("c") || sc.isExtension("cpp") || sc.isExtension("h")) {
+ // no pre-processing services necessary for java files
+ // just write the the contents of 'program' to a .java file
+ // into the build directory. uses byte stream and reader/writer
+ // shtuff so that unicode bunk is properly handled
+ String filename = sc.getFileName(); //code[i].name + ".java";
+ try {
+ Base.saveFile(sc.getProgram(), new File(buildPath, filename));
+ } catch (IOException e) {
+ e.printStackTrace();
+ throw new RunnerException(I18n.format(_("Problem moving {0} to the build folder"), filename));
+ }
+
+ } else if (sc.isExtension("ino") || sc.isExtension("pde")) {
+ // The compiler and runner will need this to have a proper offset
+ sc.addPreprocOffset(headerOffset);
+ }
+ }
+ }
+
+
+ /**
+ * List of library folders.
+ */
+ private LibraryList importedLibraries;
+
+ /**
+ * Map an error from a set of processed .java files back to its location
+ * in the actual sketch.
+ * @param message The error message.
+ * @param dotJavaFilename The .java file where the exception was found.
+ * @param dotJavaLine Line number of the .java file for the exception (0-indexed!)
+ * @return A RunnerException to be sent to the editor, or null if it wasn't
+ * possible to place the exception to the sketch code.
+ */
+ public RunnerException placeException(String message,
+ String dotJavaFilename,
+ int dotJavaLine) {
+ // Placing errors is simple, because we inserted #line directives
+ // into the preprocessed source. The compiler gives us correct
+ // the file name and line number. :-)
+ for (SketchCodeDocument codeDoc : sketch.getCodeDocs()) {
+ SketchCode code = codeDoc.getCode();
+ if (dotJavaFilename.equals(code.getFileName())) {
+ return new RunnerException(message, sketch.indexOfCode(code), dotJavaLine);
+ }
+ }
+ return null;
+ }
+
}
From bbd3782a9c3b6234ec8cc5aef8dea84533ad37f7 Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Sat, 1 Feb 2014 19:30:52 +0100
Subject: [PATCH 14/73] Reintroduced 'Next Tab' and 'Prev Tab' click actions
---
app/src/processing/app/EditorHeader.java | 32 +++++++++++-------------
1 file changed, 15 insertions(+), 17 deletions(-)
diff --git a/app/src/processing/app/EditorHeader.java b/app/src/processing/app/EditorHeader.java
index dfa76f02af6..956f4531ff7 100644
--- a/app/src/processing/app/EditorHeader.java
+++ b/app/src/processing/app/EditorHeader.java
@@ -34,6 +34,7 @@
/**
* Sketch tabs at the top of the editor window.
*/
+@SuppressWarnings("serial")
public class EditorHeader extends JComponent {
static Color backgroundColor;
static Color textColor[] = new Color[2];
@@ -326,30 +327,27 @@ public void actionPerformed(ActionEvent e) {
// KeyEvent.VK_LEFT and VK_RIGHT will make Windows beep
item = new JMenuItem(_("Previous Tab"));
- KeyStroke ctrlAltLeft =
- KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Editor.SHORTCUT_ALT_KEY_MASK);
+ KeyStroke ctrlAltLeft = KeyStroke
+ .getKeyStroke(KeyEvent.VK_LEFT, Editor.SHORTCUT_ALT_KEY_MASK);
item.setAccelerator(ctrlAltLeft);
- // this didn't want to work consistently
- /*
item.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- editor.sketch.prevCode();
- }
- });
- */
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ editor.sketch.handlePrevCode();
+ }
+ });
menu.add(item);
item = new JMenuItem(_("Next Tab"));
- KeyStroke ctrlAltRight =
- KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Editor.SHORTCUT_ALT_KEY_MASK);
+ KeyStroke ctrlAltRight = KeyStroke
+ .getKeyStroke(KeyEvent.VK_RIGHT, Editor.SHORTCUT_ALT_KEY_MASK);
item.setAccelerator(ctrlAltRight);
- /*
item.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- editor.sketch.nextCode();
- }
- });
- */
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ editor.sketch.handleNextCode();
+ }
+ });
menu.add(item);
Sketch sketch = editor.getSketch();
From 54f3f538f20cd05b7be7446a79b63230e443f74d Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Sat, 1 Feb 2014 20:47:00 +0100
Subject: [PATCH 15/73] Applied (a sort of) decorator pattern to SketchCodeDoc.
SketchCodeDoc renamed to SketchCodeDocument.
Compiler is now independent from SketchCodeDocument.
---
app/src/processing/app/Editor.java | 22 ++--
app/src/processing/app/EditorHeader.java | 3 +-
app/src/processing/app/Sketch.java | 113 ++++++++----------
.../processing/app/SketchCodeDocument.java | 44 ++-----
app/src/processing/app/SketchData.java | 74 +++++-------
app/src/processing/app/debug/Compiler.java | 11 +-
6 files changed, 110 insertions(+), 157 deletions(-)
diff --git a/app/src/processing/app/Editor.java b/app/src/processing/app/Editor.java
index 2a2c6fe4da3..35cfc45532a 100644
--- a/app/src/processing/app/Editor.java
+++ b/app/src/processing/app/Editor.java
@@ -1649,7 +1649,7 @@ protected void setCode(SketchCodeDocument codeDoc) {
// insert the program text into the document object
try {
- document.insertString(0, codeDoc.getCode().getProgram(), null);
+ document.insertString(0, codeDoc.getProgram(), null);
} catch (BadLocationException bl) {
bl.printStackTrace();
}
@@ -1659,17 +1659,17 @@ protected void setCode(SketchCodeDocument codeDoc) {
// connect the undo listener to the editor
document.addUndoableEditListener(new UndoableEditListener() {
- public void undoableEditHappened(UndoableEditEvent e) {
- if (compoundEdit != null) {
- compoundEdit.addEdit(e.getEdit());
-
- } else if (undo != null) {
- undo.addEdit(new CaretAwareUndoableEdit(e.getEdit(), textarea));
- undoAction.updateUndoState();
- redoAction.updateRedoState();
- }
+ public void undoableEditHappened(UndoableEditEvent e) {
+ if (compoundEdit != null) {
+ compoundEdit.addEdit(e.getEdit());
+
+ } else if (undo != null) {
+ undo.addEdit(new CaretAwareUndoableEdit(e.getEdit(), textarea));
+ undoAction.updateUndoState();
+ redoAction.updateRedoState();
}
- });
+ }
+ });
}
// update the document object that's in use
diff --git a/app/src/processing/app/EditorHeader.java b/app/src/processing/app/EditorHeader.java
index 956f4531ff7..0efd8668567 100644
--- a/app/src/processing/app/EditorHeader.java
+++ b/app/src/processing/app/EditorHeader.java
@@ -359,8 +359,7 @@ public void actionPerformed(ActionEvent e) {
editor.getSketch().setCurrentCode(e.getActionCommand());
}
};
- for (SketchCodeDocument codeDoc : sketch.getCodeDocs()) {
- SketchCode code = codeDoc.getCode();
+ for (SketchCode code : sketch.getCodes()) {
item = new JMenuItem(code.isExtension(sketch.getDefaultExtension()) ?
code.getPrettyName() : code.getFileName());
item.setActionCommand(code.getFileName());
diff --git a/app/src/processing/app/Sketch.java b/app/src/processing/app/Sketch.java
index 970685485ce..fcc3e915b89 100644
--- a/app/src/processing/app/Sketch.java
+++ b/app/src/processing/app/Sketch.java
@@ -65,8 +65,7 @@ public class Sketch {
/** code folder location for this sketch (may not exist yet) */
private File codeFolder;
- private SketchCode current;
- private SketchCodeDocument currentCodeDoc;
+ private SketchCodeDocument current;
private int currentIndex;
private SketchData data;
@@ -167,7 +166,7 @@ protected void load() throws IOException {
// Don't allow people to use files with invalid names, since on load,
// it would be otherwise possible to sneak in nasty filenames. [0116]
if (Sketch.isSanitaryName(base)) {
- data.addCodeDoc(new SketchCodeDocument(new File(folder, filename)));
+ data.addCode(new SketchCodeDocument(new File(folder, filename)));
} else {
System.err.println(I18n.format("File name {0} is invalid: ignored", filename));
}
@@ -180,10 +179,10 @@ protected void load() throws IOException {
// move the main class to the first tab
// start at 1, if it's at zero, don't bother
- for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
+ for (SketchCode code : data.getCodes()) {
//if (code[i].file.getName().equals(mainFilename)) {
- if (codeDoc.getCode().getFile().equals(primaryFile)) {
- data.moveCodeDocToFront(codeDoc);
+ if (code.getFile().equals(primaryFile)) {
+ data.moveCodeToFront(code);
break;
}
}
@@ -308,7 +307,7 @@ protected void nameCode(String newName) {
// Don't let the user create the main tab as a .java file instead of .pde
if (!isDefaultExtension(newExtension)) {
if (renamingCode) { // If creating a new tab, don't show this error
- if (current == data.getCodeDoc(0).getCode()) { // If this is the main tab, disallow
+ if (current == data.getCode(0)) { // If this is the main tab, disallow
Base.showWarning(_("Problem with rename"),
_("The main file can't use an extension.\n" +
"(It may be time for your to graduate to a\n" +
@@ -330,12 +329,12 @@ protected void nameCode(String newName) {
// In Arduino, we want to allow files with the same name but different
// extensions, so compare the full names (including extensions). This
// might cause problems: http://dev.processing.org/bugs/show_bug.cgi?id=543
- for (SketchCodeDocument c : data.getCodeDocs()) {
- if (newName.equalsIgnoreCase(c.getCode().getFileName())) {
+ for (SketchCode c : data.getCodes()) {
+ if (newName.equalsIgnoreCase(c.getFileName())) {
Base.showMessage(_("Nope"),
I18n.format(
_("A file named \"{0}\" already exists in \"{1}\""),
- c.getCode().getFileName(),
+ c.getFileName(),
folder.getAbsolutePath()
));
return;
@@ -352,15 +351,13 @@ protected void nameCode(String newName) {
}
if (renamingCode && currentIndex == 0) {
- for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
- if (sanitaryName.equalsIgnoreCase(codeDoc.getCode().getPrettyName()) &&
- codeDoc.getCode().isExtension("cpp")) {
+ for (SketchCode code : data.getCodes()) {
+ if (sanitaryName.equalsIgnoreCase(code.getPrettyName()) &&
+ code.isExtension("cpp")) {
Base.showMessage(_("Nope"),
- I18n.format(
- _("You can't rename the sketch to \"{0}\"\n" +
- "because the sketch already has a .cpp file with that name."),
- sanitaryName
- ));
+ I18n.format(_("You can't rename the sketch to \"{0}\"\n"
+ + "because the sketch already has a .cpp file with that name."),
+ sanitaryName));
return;
}
}
@@ -428,8 +425,8 @@ protected void nameCode(String newName) {
// save each of the other tabs because this is gonna be re-opened
try {
- for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
- codeDoc.getCode().save();
+ for (SketchCode code : data.getCodes()) {
+ code.save();
}
} catch (Exception e) {
Base.showWarning(_("Error"), _("Could not rename the sketch. (1)"), e);
@@ -486,10 +483,8 @@ protected void nameCode(String newName) {
), e);
return;
}
- SketchCode newCode = new SketchCode(newFile);
- //System.out.println("new code is named " + newCode.getPrettyName() + " " + newCode.getFile());
ensureExistence();
- data.insertCode(newCode);
+ data.addCode(new SketchCodeDocument(newFile));
}
// sort the entries
@@ -601,8 +596,8 @@ public void setModified(boolean state) {
protected void calcModified() {
modified = false;
- for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
- if (codeDoc.getCode().isModified()) {
+ for (SketchCode code : data.getCodes()) {
+ if (code.isModified()) {
modified = true;
break;
}
@@ -685,9 +680,9 @@ public boolean accept(File dir, String name) {
}
}
- for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
- if (codeDoc.getCode().isModified())
- codeDoc.getCode().save();
+ for (SketchCode code : data.getCodes()) {
+ if (code.isModified())
+ code.save();
}
calcModified();
return true;
@@ -695,13 +690,13 @@ public boolean accept(File dir, String name) {
protected boolean renameCodeToInoExtension(File pdeFile) {
- for (SketchCodeDocument c : data.getCodeDocs()) {
- if (!c.getCode().getFile().equals(pdeFile))
+ for (SketchCode c : data.getCodes()) {
+ if (!c.getFile().equals(pdeFile))
continue;
String pdeName = pdeFile.getPath();
pdeName = pdeName.substring(0, pdeName.length() - 4) + ".ino";
- return c.getCode().renameTo(new File(pdeName));
+ return c.renameTo(new File(pdeName));
}
return false;
}
@@ -746,9 +741,9 @@ protected boolean saveAs() throws IOException {
// make sure there doesn't exist a .cpp file with that name already
// but ignore this situation for the first tab, since it's probably being
// resaved (with the same name) to another location/folder.
- for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
- if (newName.equalsIgnoreCase(codeDoc.getCode().getPrettyName()) &&
- codeDoc.getCode().isExtension("cpp")) {
+ for (SketchCode code : data.getCodes()) {
+ if (newName.equalsIgnoreCase(code.getPrettyName()) &&
+ code.isExtension("cpp")) {
Base.showMessage(_("Nope"),
I18n.format(
_("You can't save the sketch as \"{0}\"\n" +
@@ -798,10 +793,10 @@ protected boolean saveAs() throws IOException {
}
// save the other tabs to their new location
- for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
- if (data.indexOfCodeDoc(codeDoc) == 0) continue;
- File newFile = new File(newFolder, codeDoc.getCode().getFileName());
- codeDoc.getCode().saveAs(newFile);
+ for (SketchCode code : data.getCodes()) {
+ if (data.indexOfCode(code) == 0) continue;
+ File newFile = new File(newFolder, code.getFileName());
+ code.saveAs(newFile);
}
// re-copy the data folder (this may take a while.. add progress bar?)
@@ -826,7 +821,7 @@ protected boolean saveAs() throws IOException {
// save the main tab with its new name
File newFile = new File(newFolder, newName + ".ino");
- data.getCodeDoc(0).getCode().saveAs(newFile);
+ data.getCode(0).saveAs(newFile);
editor.handleOpenUnchecked(newFile,
currentIndex,
@@ -989,14 +984,14 @@ public boolean addFile(File sourceFile) {
}
if (codeExtension != null) {
- SketchCode newCode = new SketchCode(destFile);
+ SketchCode newCode = new SketchCodeDocument(destFile);
if (replacement) {
data.replaceCode(newCode);
} else {
ensureExistence();
- data.insertCode(newCode);
+ data.addCode(newCode);
data.sortCode();
}
setCurrentCode(filename);
@@ -1010,7 +1005,7 @@ public boolean addFile(File sourceFile) {
if (editor.untitled) { // TODO probably not necessary? problematic?
// If a file has been added, mark the main code as modified so
// that the sketch is properly saved.
- data.getCodeDoc(0).getCode().setModified(true);
+ data.getCode(0).setModified(true);
}
}
return true;
@@ -1071,16 +1066,15 @@ public void setCurrentCode(int which) {
// get the text currently being edited
if (current != null) {
current.setProgram(editor.getText());
- currentCodeDoc.setSelectionStart(editor.getSelectionStart());
- currentCodeDoc.setSelectionStop(editor.getSelectionStop());
- currentCodeDoc.setScrollPosition(editor.getScrollPosition());
+ current.setSelectionStart(editor.getSelectionStart());
+ current.setSelectionStop(editor.getSelectionStop());
+ current.setScrollPosition(editor.getScrollPosition());
}
- currentCodeDoc = data.getCodeDoc(which);
- current = currentCodeDoc.getCode();
+ current = (SketchCodeDocument) data.getCode(which);
currentIndex = which;
- editor.setCode(currentCodeDoc);
+ editor.setCode(current);
editor.header.rebuild();
}
@@ -1091,10 +1085,10 @@ public void setCurrentCode(int which) {
* @param findName the file name (not pretty name) to be shown
*/
protected void setCurrentCode(String findName) {
- for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
- if (findName.equals(codeDoc.getCode().getFileName()) ||
- findName.equals(codeDoc.getCode().getPrettyName())) {
- setCurrentCode(data.indexOfCodeDoc(codeDoc));
+ for (SketchCode code : data.getCodes()) {
+ if (findName.equals(code.getFileName()) ||
+ findName.equals(code.getPrettyName())) {
+ setCurrentCode(data.indexOfCode(code));
return;
}
}
@@ -1527,8 +1521,8 @@ protected void ensureExistence() {
folder.mkdirs();
modified = true;
- for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
- codeDoc.getCode().save(); // this will force a save
+ for (SketchCode code : data.getCodes()) {
+ code.save(); // this will force a save
}
calcModified();
@@ -1562,9 +1556,8 @@ public boolean isReadOnly() {
// } else if (!folder.canWrite()) {
// check to see if each modified code file can be written to
- for (SketchCodeDocument codeDoc : data.getCodeDocs()) {
- if (codeDoc.getCode().isModified() && codeDoc.getCode().fileReadOnly() &&
- codeDoc.getCode().fileExists()) {
+ for (SketchCode code : data.getCodes()) {
+ if (code.isModified() && code.fileReadOnly() && code.fileExists()) {
// System.err.println("found a read-only file " + code[i].file);
return true;
}
@@ -1702,8 +1695,8 @@ public File prepareCodeFolder() {
}
- public SketchCodeDocument[] getCodeDocs() {
- return data.getCodeDocs();
+ public SketchCode[] getCodes() {
+ return data.getCodes();
}
@@ -1713,7 +1706,7 @@ public int getCodeCount() {
public SketchCode getCode(int index) {
- return data.getCodeDoc(index).getCode();
+ return data.getCode(index);
}
diff --git a/app/src/processing/app/SketchCodeDocument.java b/app/src/processing/app/SketchCodeDocument.java
index 3310e247990..ddb02646846 100644
--- a/app/src/processing/app/SketchCodeDocument.java
+++ b/app/src/processing/app/SketchCodeDocument.java
@@ -4,19 +4,24 @@
import javax.swing.text.Document;
-public class SketchCodeDocument {
+public class SketchCodeDocument extends SketchCode {
- SketchCode code;
-
private Document document;
- /**
- * Undo Manager for this tab, each tab keeps track of their own
- * Editor.undo will be set to this object when this code is the tab
- * that's currently the front.
- */
+ // Undo Manager for this tab, each tab keeps track of their own Editor.undo
+ // will be set to this object when this code is the tab that's currently the
+ // front.
private LastUndoableEditAwareUndoManager undo = new LastUndoableEditAwareUndoManager();
+ // saved positions from last time this tab was used
+ private int selectionStart;
+ private int selectionStop;
+ private int scrollPosition;
+
+ public SketchCodeDocument(File file) {
+ super(file);
+ }
+
public LastUndoableEditAwareUndoManager getUndo() {
return undo;
}
@@ -49,29 +54,6 @@ public void setScrollPosition(int scrollPosition) {
this.scrollPosition = scrollPosition;
}
- // saved positions from last time this tab was used
- private int selectionStart;
- private int selectionStop;
- private int scrollPosition;
-
-
- public SketchCodeDocument(SketchCode sketchCode, Document doc) {
- code = sketchCode;
- document = doc;
- }
-
- public SketchCodeDocument(File file) {
- code = new SketchCode(file);
- }
-
- public SketchCode getCode() {
- return code;
- }
-
- public void setCode(SketchCode code) {
- this.code = code;
- }
-
public Document getDocument() {
return document;
}
diff --git a/app/src/processing/app/SketchData.java b/app/src/processing/app/SketchData.java
index 81471d62aff..4f4a16c0e4f 100644
--- a/app/src/processing/app/SketchData.java
+++ b/app/src/processing/app/SketchData.java
@@ -1,7 +1,5 @@
package processing.app;
-import static processing.app.I18n._;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
@@ -14,82 +12,68 @@ public class SketchData {
* extension)
*/
private String name;
-
- private List codeDocs = new ArrayList();
- private static final Comparator CODE_DOCS_COMPARATOR = new Comparator() {
+ private List codes = new ArrayList();
+
+ private static final Comparator CODE_DOCS_COMPARATOR = new Comparator() {
@Override
- public int compare(SketchCodeDocument cd1, SketchCodeDocument cd2) {
- return cd1.getCode().getFileName().compareTo(cd2.getCode().getFileName());
+ public int compare(SketchCode x, SketchCode y) {
+ return x.getFileName().compareTo(y.getFileName());
}
};
-
public int getCodeCount() {
- return codeDocs.size();
+ return codes.size();
}
- public SketchCodeDocument[] getCodeDocs() {
- return codeDocs.toArray(new SketchCodeDocument[0]);
+ public SketchCode[] getCodes() {
+ return codes.toArray(new SketchCode[0]);
}
- public void addCodeDoc(SketchCodeDocument sketchCodeDoc) {
- codeDocs.add(sketchCodeDoc);
+ public void addCode(SketchCode sketchCode) {
+ codes.add(sketchCode);
}
- public void moveCodeDocToFront(SketchCodeDocument codeDoc) {
- codeDocs.remove(codeDoc);
- codeDocs.add(0, codeDoc);
+ public void moveCodeToFront(SketchCode codeDoc) {
+ codes.remove(codeDoc);
+ codes.add(0, codeDoc);
}
protected void replaceCode(SketchCode newCode) {
- for (SketchCodeDocument codeDoc : codeDocs) {
- if (codeDoc.getCode().getFileName().equals(newCode.getFileName())) {
- codeDoc.setCode(newCode);
+ for (SketchCode code : codes) {
+ if (code.getFileName().equals(newCode.getFileName())) {
+ codes.set(codes.indexOf(code), newCode);
return;
}
}
}
- protected void insertCode(SketchCode sketchCode) {
- addCodeDoc(new SketchCodeDocument(sketchCode, null));
- }
-
protected void sortCode() {
- if (codeDocs.size() < 2)
+ if (codes.size() < 2)
return;
- SketchCodeDocument first = codeDocs.remove(0);
- Collections.sort(codeDocs, CODE_DOCS_COMPARATOR);
- codeDocs.add(0, first);
- }
-
- public SketchCodeDocument getCodeDoc(int i) {
- return codeDocs.get(i);
+ SketchCode first = codes.remove(0);
+ Collections.sort(codes, CODE_DOCS_COMPARATOR);
+ codes.add(0, first);
}
public SketchCode getCode(int i) {
- return codeDocs.get(i).getCode();
+ return codes.get(i);
}
protected void removeCode(SketchCode which) {
- for (SketchCodeDocument codeDoc : codeDocs) {
- if (codeDoc.getCode() == which) {
- codeDocs.remove(codeDoc);
+ for (SketchCode code : codes) {
+ if (code == which) {
+ codes.remove(code);
return;
}
}
- System.err.println(_("removeCode: internal error.. could not find code"));
- }
-
- public int indexOfCodeDoc(SketchCodeDocument codeDoc) {
- return codeDocs.indexOf(codeDoc);
+ System.err.println("removeCode: internal error.. could not find code");
}
public int indexOfCode(SketchCode who) {
- for (SketchCodeDocument codeDoc : codeDocs) {
- if (codeDoc.getCode() == who) {
- return codeDocs.indexOf(codeDoc);
- }
+ for (SketchCode code : codes) {
+ if (code == who)
+ return codes.indexOf(code);
}
return -1;
}
@@ -103,6 +87,6 @@ public void setName(String name) {
}
public void clearCodeDocs() {
- codeDocs.clear();
+ codes.clear();
}
}
diff --git a/app/src/processing/app/debug/Compiler.java b/app/src/processing/app/debug/Compiler.java
index da601f56304..fd10947570f 100644
--- a/app/src/processing/app/debug/Compiler.java
+++ b/app/src/processing/app/debug/Compiler.java
@@ -40,7 +40,6 @@
import processing.app.I18n;
import processing.app.Preferences;
import processing.app.SketchCode;
-import processing.app.SketchCodeDocument;
import processing.app.SketchData;
import processing.app.helpers.FileUtils;
import processing.app.helpers.PreferencesMap;
@@ -50,7 +49,6 @@
import processing.app.packages.Library;
import processing.app.packages.LibraryList;
import processing.app.preproc.PdePreprocessor;
-import processing.core.PApplet;
public class Compiler implements MessageConsumer {
@@ -901,8 +899,7 @@ public void preprocess(String buildPath, PdePreprocessor preprocessor) throws Ru
StringBuffer bigCode = new StringBuffer();
int bigCount = 0;
- for (SketchCodeDocument scd : sketch.getCodeDocs()) {
- SketchCode sc = scd.getCode();
+ for (SketchCode sc : sketch.getCodes()) {
if (sc.isExtension("ino") || sc.isExtension("pde")) {
sc.setPreprocOffset(bigCount);
// These #line directives help the compiler report errors with
@@ -962,8 +959,7 @@ public void preprocess(String buildPath, PdePreprocessor preprocessor) throws Ru
// 3. then loop over the code[] and save each .java file
- for (SketchCodeDocument scd : sketch.getCodeDocs()) {
- SketchCode sc = scd.getCode();
+ for (SketchCode sc : sketch.getCodes()) {
if (sc.isExtension("c") || sc.isExtension("cpp") || sc.isExtension("h")) {
// no pre-processing services necessary for java files
// just write the the contents of 'program' to a .java file
@@ -1005,8 +1001,7 @@ public RunnerException placeException(String message,
// Placing errors is simple, because we inserted #line directives
// into the preprocessed source. The compiler gives us correct
// the file name and line number. :-)
- for (SketchCodeDocument codeDoc : sketch.getCodeDocs()) {
- SketchCode code = codeDoc.getCode();
+ for (SketchCode code : sketch.getCodes()) {
if (dotJavaFilename.equals(code.getFileName())) {
return new RunnerException(message, sketch.indexOfCode(code), dotJavaLine);
}
From b61f2a419f238afa22fb31e19179db25394faf60 Mon Sep 17 00:00:00 2001
From: Claudio Indellicati
Date: Sun, 6 Apr 2014 00:29:20 +0200
Subject: [PATCH 16/73] Made Compiler and PdePreprocessor independent from
Preferences.
Created a class PreferencesData to manage all parameters except the ones for the GUI.
Removed GUI parameters management from ParametersMap.
Created ParametersHelper class to help with GUI parameters management.
Used ParametersHelper in Themes.
---
app/src/processing/app/Preferences.java | 274 ++++--------------
app/src/processing/app/PreferencesData.java | 214 ++++++++++++++
app/src/processing/app/Theme.java | 11 +-
app/src/processing/app/debug/Compiler.java | 7 +-
.../app/helpers/PreferencesHelper.java | 103 +++++++
.../app/helpers/PreferencesMap.java | 59 ----
.../app/preproc/PdePreprocessor.java | 2 +-
7 files changed, 378 insertions(+), 292 deletions(-)
create mode 100644 app/src/processing/app/PreferencesData.java
create mode 100644 app/src/processing/app/helpers/PreferencesHelper.java
diff --git a/app/src/processing/app/Preferences.java b/app/src/processing/app/Preferences.java
index b8b8471f824..46008c962f6 100644
--- a/app/src/processing/app/Preferences.java
+++ b/app/src/processing/app/Preferences.java
@@ -38,15 +38,7 @@
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
-import java.io.BufferedReader;
import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
-import java.util.Arrays;
-import java.util.MissingResourceException;
-import java.util.StringTokenizer;
import javax.swing.Box;
import javax.swing.JButton;
@@ -58,10 +50,9 @@
import javax.swing.KeyStroke;
import processing.app.helpers.FileUtils;
+import processing.app.helpers.PreferencesHelper;
import processing.app.helpers.PreferencesMap;
-import processing.app.syntax.SyntaxStyle;
import processing.core.PApplet;
-import processing.core.PConstants;
/**
@@ -93,7 +84,7 @@
*/
public class Preferences {
- static final String PREFS_FILE = "preferences.txt";
+ static final String PREFS_FILE = PreferencesData.PREFS_FILE;
class Language {
Language(String _name, String _originalName, String _isoCode) {
@@ -238,72 +229,12 @@ public String toString() {
Editor editor;
- // data model
-
- static PreferencesMap defaults;
- static PreferencesMap prefs = new PreferencesMap();
- static File preferencesFile;
- static boolean doSave = true;
-
-
static protected void init(File file) {
- if (file != null)
- preferencesFile = file;
- else
- preferencesFile = Base.getSettingsFile(Preferences.PREFS_FILE);
- // start by loading the defaults, in case something
- // important was deleted from the user prefs
- try {
- prefs.load(Base.getLibStream("preferences.txt"));
- } catch (IOException e) {
- Base.showError(null, _("Could not read default settings.\n" +
- "You'll need to reinstall Arduino."), e);
- }
-
- // set some runtime constants (not saved on preferences file)
- File hardwareFolder = Base.getHardwareFolder();
- prefs.put("runtime.ide.path", hardwareFolder.getParentFile().getAbsolutePath());
- prefs.put("runtime.ide.version", "" + Base.REVISION);
-
- // clone the hash table
- defaults = new PreferencesMap(prefs);
-
- if (preferencesFile.exists()) {
- // load the previous preferences file
- try {
- prefs.load(preferencesFile);
- } catch (IOException ex) {
- Base.showError(_("Error reading preferences"),
- I18n.format(_("Error reading the preferences file. "
- + "Please delete (or move)\n"
- + "{0} and restart Arduino."),
- preferencesFile.getAbsolutePath()), ex);
- }
- }
-
- // load the I18n module for internationalization
- try {
- I18n.init(get("editor.languages.current"));
- } catch (MissingResourceException e) {
- I18n.init("en");
- set("editor.languages.current", "en");
- }
-
- // set some other runtime constants (not saved on preferences file)
- set("runtime.os", PConstants.platformNames[PApplet.platform]);
+ PreferencesData.init(file);
// other things that have to be set explicitly for the defaults
- setColor("run.window.bgcolor", SystemColor.control);
-
- fixPreferences();
- }
-
- private static void fixPreferences() {
- String baud = get("serial.debug_rate");
- if ("14400".equals(baud) || "28800".equals(baud) || "38400".equals(baud)) {
- set("serial.debug_rate", "9600");
- }
+ PreferencesHelper.putColor(PreferencesData.prefs, "run.window.bgcolor", SystemColor.control);
}
@@ -380,7 +311,7 @@ public void actionPerformed(ActionEvent e) {
label = new JLabel(_("Editor language: "));
box.add(label);
comboLanguage = new JComboBox(languages);
- String currentLanguage = Preferences.get("editor.languages.current");
+ String currentLanguage = PreferencesData.get("editor.languages.current");
for (Language language : languages) {
if (language.isoCode.equals(currentLanguage))
comboLanguage.setSelectedItem(language);
@@ -507,11 +438,11 @@ public void actionPerformed(ActionEvent e) {
right = Math.max(right, left + d.width);
top += d.height; // + GUI_SMALL;
- label = new JLabel(preferencesFile.getAbsolutePath());
+ label = new JLabel(PreferencesData.preferencesFile.getAbsolutePath());
final JLabel clickable = label;
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
- Base.openFolder(preferencesFile.getParentFile());
+ Base.openFolder(PreferencesData.preferencesFile.getParentFile());
}
public void mouseEntered(MouseEvent e) {
@@ -630,19 +561,19 @@ protected void disposeFrame() {
*/
protected void applyFrame() {
// put each of the settings into the table
- setBoolean("build.verbose", verboseCompilationBox.isSelected());
- setBoolean("upload.verbose", verboseUploadBox.isSelected());
- setBoolean("editor.linenumbers", displayLineNumbersBox.isSelected());
- setBoolean("upload.verify", verifyUploadBox.isSelected());
- setBoolean("editor.save_on_verify", saveVerifyUploadBox.isSelected());
-
+ PreferencesData.setBoolean("build.verbose", verboseCompilationBox.isSelected());
+ PreferencesData.setBoolean("upload.verbose", verboseUploadBox.isSelected());
+ PreferencesData.setBoolean("editor.linenumbers", displayLineNumbersBox.isSelected());
+ PreferencesData.setBoolean("upload.verify", verifyUploadBox.isSelected());
+ PreferencesData.setBoolean("editor.save_on_verify", saveVerifyUploadBox.isSelected());
+
// setBoolean("sketchbook.closing_last_window_quits",
// closingLastQuitsBox.isSelected());
//setBoolean("sketchbook.prompt", sketchPromptBox.isSelected());
//setBoolean("sketchbook.auto_clean", sketchCleanBox.isSelected());
// if the sketchbook path has changed, rebuild the menus
- String oldPath = get("sketchbook.path");
+ String oldPath = PreferencesData.get("sketchbook.path");
String newPath = sketchbookLocationField.getText();
if (newPath.isEmpty()) {
if (Base.getPortableFolder() == null)
@@ -652,12 +583,12 @@ protected void applyFrame() {
}
if (!newPath.equals(oldPath)) {
editor.base.rebuildSketchbookMenus();
- set("sketchbook.path", newPath);
+ PreferencesData.set("sketchbook.path", newPath);
}
- setBoolean("editor.external", externalEditorBox.isSelected());
- setBoolean("update.check", checkUpdatesBox.isSelected());
- setBoolean("editor.save_on_verify", saveVerifyUploadBox.isSelected());
+ PreferencesData.setBoolean("editor.external", externalEditorBox.isSelected());
+ PreferencesData.setBoolean("update.check", checkUpdatesBox.isSelected());
+ PreferencesData.setBoolean("editor.save_on_verify", saveVerifyUploadBox.isSelected());
/*
// was gonna use this to check memory settings,
@@ -674,24 +605,24 @@ protected void applyFrame() {
String newSizeText = fontSizeField.getText();
try {
int newSize = Integer.parseInt(newSizeText.trim());
- String pieces[] = PApplet.split(get("editor.font"), ',');
+ String pieces[] = PApplet.split(PreferencesData.get("editor.font"), ',');
pieces[2] = String.valueOf(newSize);
- set("editor.font", PApplet.join(pieces, ','));
+ PreferencesData.set("editor.font", PApplet.join(pieces, ','));
} catch (Exception e) {
System.err.println(I18n.format(_("ignoring invalid font size {0}"), newSizeText));
}
if (autoAssociateBox != null) {
- setBoolean("platform.auto_file_type_associations",
+ PreferencesData.setBoolean("platform.auto_file_type_associations",
autoAssociateBox.isSelected());
}
- setBoolean("editor.update_extension", updateExtensionBox.isSelected());
+ PreferencesData.setBoolean("editor.update_extension", updateExtensionBox.isSelected());
// adds the selected language to the preferences file
Language newLanguage = (Language) comboLanguage.getSelectedItem();
- set("editor.languages.current", newLanguage.isoCode);
+ PreferencesData.set("editor.languages.current", newLanguage.isoCode);
editor.applyPreferences();
}
@@ -701,10 +632,10 @@ protected void showFrame(Editor editor) {
this.editor = editor;
// set all settings entry boxes to their actual status
- verboseCompilationBox.setSelected(getBoolean("build.verbose"));
- verboseUploadBox.setSelected(getBoolean("upload.verbose"));
- displayLineNumbersBox.setSelected(getBoolean("editor.linenumbers"));
- verifyUploadBox.setSelected(getBoolean("upload.verify"));
+ verboseCompilationBox.setSelected(PreferencesData.getBoolean("build.verbose"));
+ verboseUploadBox.setSelected(PreferencesData.getBoolean("upload.verbose"));
+ displayLineNumbersBox.setSelected(PreferencesData.getBoolean("editor.linenumbers"));
+ verifyUploadBox.setSelected(PreferencesData.getBoolean("upload.verify"));
//closingLastQuitsBox.
// setSelected(getBoolean("sketchbook.closing_last_window_quits"));
@@ -714,200 +645,95 @@ protected void showFrame(Editor editor) {
// setSelected(getBoolean("sketchbook.auto_clean"));
sketchbookLocationField.
- setText(get("sketchbook.path"));
+ setText(PreferencesData.get("sketchbook.path"));
externalEditorBox.
- setSelected(getBoolean("editor.external"));
+ setSelected(PreferencesData.getBoolean("editor.external"));
checkUpdatesBox.
- setSelected(getBoolean("update.check"));
+ setSelected(PreferencesData.getBoolean("update.check"));
saveVerifyUploadBox.
- setSelected(getBoolean("editor.save_on_verify"));
+ setSelected(PreferencesData.getBoolean("editor.save_on_verify"));
if (autoAssociateBox != null) {
autoAssociateBox.
- setSelected(getBoolean("platform.auto_file_type_associations"));
+ setSelected(PreferencesData.getBoolean("platform.auto_file_type_associations"));
}
- updateExtensionBox.setSelected(get("editor.update_extension") == null ||
- getBoolean("editor.update_extension"));
+ updateExtensionBox.setSelected(PreferencesData.get("editor.update_extension") == null ||
+ PreferencesData.getBoolean("editor.update_extension"));
dialog.setVisible(true);
}
- // .................................................................
-
-
- 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;
- }
-
-
-
- // .................................................................
-
-
static protected void save() {
- if (!doSave) return;
-// try {
- // on startup, don't worry about it
- // this is trying to update the prefs for who is open
- // before Preferences.init() has been called.
- if (preferencesFile == null) return;
-
- // Fix for 0163 to properly use Unicode when writing preferences.txt
- PrintWriter writer = PApplet.createWriter(preferencesFile);
-
- String[] keys = prefs.keySet().toArray(new String[0]);
- Arrays.sort(keys);
- for (String key: keys) {
- if (key.startsWith("runtime."))
- continue;
- writer.println(key + "=" + prefs.get(key));
- }
-
- writer.flush();
- writer.close();
+ PreferencesData.save();
}
// .................................................................
static public String get(String attribute) {
- return prefs.get(attribute);
+ return PreferencesData.get(attribute);
}
static public String get(String attribute, String defaultValue) {
- String value = get(attribute);
- return (value == null) ? defaultValue : value;
+ return PreferencesData.get(attribute, defaultValue);
}
public static boolean has(String key) {
- return prefs.containsKey(key);
+ return PreferencesData.has(key);
}
public static void remove(String key) {
- prefs.remove(key);
- }
-
- static public String getDefault(String attribute) {
- return defaults.get(attribute);
+ PreferencesData.remove(key);
}
static public void set(String attribute, String value) {
- prefs.put(attribute, value);
- }
-
-
- static public void unset(String attribute) {
- prefs.remove(attribute);
+ PreferencesData.set(attribute, value);
}
static public boolean getBoolean(String attribute) {
- return prefs.getBoolean(attribute);
+ return PreferencesData.getBoolean(attribute);
}
static public void setBoolean(String attribute, boolean value) {
- prefs.putBoolean(attribute, value);
+ PreferencesData.setBoolean(attribute, value);
}
static public int getInteger(String attribute) {
- return Integer.parseInt(get(attribute));
+ return PreferencesData.getInteger(attribute);
}
static public void setInteger(String key, int value) {
- set(key, String.valueOf(value));
- }
-
-
- static public Color getColor(String name) {
- Color parsed = prefs.getColor(name);
- if (parsed != null)
- return parsed;
- return Color.GRAY; // set a default
- }
-
-
- static public void setColor(String attr, Color what) {
- prefs.putColor(attr, what);
+ PreferencesData.setInteger(key, value);
}
static public Font getFont(String attr) {
- Font font = prefs.getFont(attr);
+ Font font = PreferencesHelper.getFont(PreferencesData.prefs, attr);
if (font == null) {
- String value = defaults.get(attr);
- prefs.put(attr, value);
- font = prefs.getFont(attr);
+ String value = PreferencesData.defaults.get(attr);
+ PreferencesData.prefs.put(attr, value);
+ font = PreferencesHelper.getFont(PreferencesData.prefs, attr);
}
return font;
}
-
- static public SyntaxStyle getStyle(String what) {
- String str = get("editor." + what + ".style");
-
- StringTokenizer st = new StringTokenizer(str, ",");
-
- String s = st.nextToken();
- if (s.indexOf("#") == 0) s = s.substring(1);
- Color color = Color.DARK_GRAY;
- try {
- color = new Color(Integer.parseInt(s, 16));
- } catch (Exception e) { }
-
- s = st.nextToken();
- boolean bold = (s.indexOf("bold") != -1);
- boolean italic = (s.indexOf("italic") != -1);
- boolean underlined = (s.indexOf("underlined") != -1);
-
- return new SyntaxStyle(color, italic, bold, underlined);
- }
-
// get a copy of the Preferences
static public PreferencesMap getMap()
{
- return new PreferencesMap(prefs);
+ return PreferencesData.getMap();
}
// Decide wether changed preferences will be saved. When value is
// false, Preferences.save becomes a no-op.
static public void setDoSave(boolean value)
{
- doSave = value;
+ PreferencesData.setDoSave(value);
}
}
diff --git a/app/src/processing/app/PreferencesData.java b/app/src/processing/app/PreferencesData.java
new file mode 100644
index 00000000000..2b4af0118dd
--- /dev/null
+++ b/app/src/processing/app/PreferencesData.java
@@ -0,0 +1,214 @@
+package processing.app;
+
+import static processing.app.I18n._;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.util.Arrays;
+import java.util.MissingResourceException;
+
+import processing.app.helpers.PreferencesMap;
+import processing.core.PApplet;
+import processing.core.PConstants;
+
+
+public class PreferencesData {
+
+ static final String PREFS_FILE = "preferences.txt";
+
+ // data model
+
+ static PreferencesMap defaults;
+ static PreferencesMap prefs = new PreferencesMap();
+ static File preferencesFile;
+ static boolean doSave = true;
+
+
+ static public void init(File file) {
+ if (file != null)
+ preferencesFile = file;
+ else
+ preferencesFile = Base.getSettingsFile(Preferences.PREFS_FILE);
+
+ // start by loading the defaults, in case something
+ // important was deleted from the user prefs
+ try {
+ prefs.load(Base.getLibStream("preferences.txt"));
+ } catch (IOException e) {
+ Base.showError(null, _("Could not read default settings.\n" +
+ "You'll need to reinstall Arduino."), e);
+ }
+
+ // set some runtime constants (not saved on preferences file)
+ File hardwareFolder = Base.getHardwareFolder();
+ prefs.put("runtime.ide.path", hardwareFolder.getParentFile().getAbsolutePath());
+ prefs.put("runtime.ide.version", "" + Base.REVISION);
+
+ // clone the hash table
+ defaults = new PreferencesMap(prefs);
+
+ if (preferencesFile.exists()) {
+ // load the previous preferences file
+ try {
+ prefs.load(preferencesFile);
+ } catch (IOException ex) {
+ Base.showError(_("Error reading preferences"),
+ I18n.format(_("Error reading the preferences file. "
+ + "Please delete (or move)\n"
+ + "{0} and restart Arduino."),
+ preferencesFile.getAbsolutePath()), ex);
+ }
+ }
+
+ // load the I18n module for internationalization
+ try {
+ I18n.init(get("editor.languages.current"));
+ } catch (MissingResourceException e) {
+ I18n.init("en");
+ set("editor.languages.current", "en");
+ }
+
+ // set some other runtime constants (not saved on preferences file)
+ set("runtime.os", PConstants.platformNames[PApplet.platform]);
+
+ fixPreferences();
+ }
+
+ private static void fixPreferences() {
+ String baud = get("serial.debug_rate");
+ if ("14400".equals(baud) || "28800".equals(baud) || "38400".equals(baud)) {
+ set("serial.debug_rate", "9600");
+ }
+ }
+
+
+ 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;
+ }
+
+
+ static protected void save() {
+ if (!doSave)
+ return;
+
+ // on startup, don't worry about it
+ // this is trying to update the prefs for who is open
+ // before Preferences.init() has been called.
+ if (preferencesFile == null) return;
+
+ // Fix for 0163 to properly use Unicode when writing preferences.txt
+ PrintWriter writer = PApplet.createWriter(preferencesFile);
+
+ String[] keys = prefs.keySet().toArray(new String[0]);
+ Arrays.sort(keys);
+ for (String key: keys) {
+ if (key.startsWith("runtime."))
+ continue;
+ writer.println(key + "=" + prefs.get(key));
+ }
+
+ writer.flush();
+ writer.close();
+ }
+
+
+ // .................................................................
+
+ static public String get(String attribute) {
+ return prefs.get(attribute);
+ }
+
+ static public String get(String attribute, String defaultValue) {
+ String value = get(attribute);
+ return (value == null) ? defaultValue : value;
+ }
+
+ public static boolean has(String key) {
+ return prefs.containsKey(key);
+ }
+
+ public static void remove(String key) {
+ prefs.remove(key);
+ }
+
+ static public String getDefault(String attribute) {
+ return defaults.get(attribute);
+ }
+
+
+ static public void set(String attribute, String value) {
+ prefs.put(attribute, value);
+ }
+
+
+ static public void unset(String attribute) {
+ prefs.remove(attribute);
+ }
+
+
+ static public boolean getBoolean(String attribute) {
+ return prefs.getBoolean(attribute);
+ }
+
+
+ static public void setBoolean(String attribute, boolean value) {
+ prefs.putBoolean(attribute, value);
+ }
+
+
+ static public int getInteger(String attribute) {
+ return Integer.parseInt(get(attribute));
+ }
+
+
+ static public void setInteger(String key, int value) {
+ set(key, String.valueOf(value));
+ }
+
+ // get a copy of the Preferences
+ static public PreferencesMap getMap()
+ {
+ return new PreferencesMap(prefs);
+ }
+
+ // Decide wether changed preferences will be saved. When value is
+ // false, Preferences.save becomes a no-op.
+ static public void setDoSave(boolean value)
+ {
+ doSave = value;
+ }
+}
diff --git a/app/src/processing/app/Theme.java b/app/src/processing/app/Theme.java
index 96ac78b4336..7f23d3c4602 100644
--- a/app/src/processing/app/Theme.java
+++ b/app/src/processing/app/Theme.java
@@ -27,6 +27,7 @@
import java.awt.Font;
import java.awt.SystemColor;
+import processing.app.helpers.PreferencesHelper;
import processing.app.helpers.PreferencesMap;
import processing.app.syntax.SyntaxStyle;
@@ -86,19 +87,19 @@ static public void setInteger(String key, int value) {
}
static public Color getColor(String name) {
- return PreferencesMap.parseColor(get(name));
+ return PreferencesHelper.parseColor(get(name));
}
static public void setColor(String attr, Color color) {
- table.putColor(attr, color);
+ PreferencesHelper.putColor(table, attr, color);
}
static public Font getFont(String attr) {
- Font font = table.getFont(attr);
+ Font font = PreferencesHelper.getFont(table, attr);
if (font == null) {
String value = getDefault(attr);
set(attr, value);
- font = table.getFont(attr);
+ font = PreferencesHelper.getFont(table, attr);
}
return font;
}
@@ -106,7 +107,7 @@ static public Font getFont(String attr) {
static public SyntaxStyle getStyle(String what) {
String split[] = get("editor." + what + ".style").split(",");
- Color color = PreferencesMap.parseColor(split[0]);
+ Color color = PreferencesHelper.parseColor(split[0]);
String style = split[1];
boolean bold = style.contains("bold");
diff --git a/app/src/processing/app/debug/Compiler.java b/app/src/processing/app/debug/Compiler.java
index fd10947570f..232b5ac7ccb 100644
--- a/app/src/processing/app/debug/Compiler.java
+++ b/app/src/processing/app/debug/Compiler.java
@@ -38,7 +38,7 @@
import processing.app.Base;
import processing.app.I18n;
-import processing.app.Preferences;
+import processing.app.PreferencesData;
import processing.app.SketchCode;
import processing.app.SketchData;
import processing.app.helpers.FileUtils;
@@ -49,6 +49,7 @@
import processing.app.packages.Library;
import processing.app.packages.LibraryList;
import processing.app.preproc.PdePreprocessor;
+import processing.core.PApplet;
public class Compiler implements MessageConsumer {
@@ -104,7 +105,7 @@ public void setProgressListener(ProgressListener _progressListener) {
public boolean compile(boolean _verbose) throws RunnerException {
preprocess(prefs.get("build.path"));
- verbose = _verbose || Preferences.getBoolean("build.verbose");
+ verbose = _verbose || PreferencesData.getBoolean("build.verbose");
sketchIsCompiled = false;
objectFiles = new ArrayList();
@@ -203,7 +204,7 @@ private PreferencesMap createBuildPreferences(String _buildPath,
// Merge all the global preference configuration in order of priority
PreferencesMap p = new PreferencesMap();
- p.putAll(Preferences.getMap());
+ p.putAll(PreferencesData.getMap());
if (corePlatform != null)
p.putAll(corePlatform.getPreferences());
p.putAll(targetPlatform.getPreferences());
diff --git a/app/src/processing/app/helpers/PreferencesHelper.java b/app/src/processing/app/helpers/PreferencesHelper.java
new file mode 100644
index 00000000000..0e096e7f665
--- /dev/null
+++ b/app/src/processing/app/helpers/PreferencesHelper.java
@@ -0,0 +1,103 @@
+package processing.app.helpers;
+
+import java.awt.Color;
+import java.awt.Font;
+
+public abstract class PreferencesHelper {
+
+// /**
+// * Create a Color with the value of the specified key. The format of the color
+// * should be an hexadecimal number of 6 digit, eventually prefixed with a '#'.
+// *
+// * @param name
+// * @return A Color object or null if the key is not found or the format
+// * is wrong
+// */
+// static public Color getColor(PreferencesMap prefs, String name) {
+// Color parsed = parseColor(prefs.get(name));
+// if (parsed != null)
+// return parsed;
+// return Color.GRAY; // set a default
+// }
+//
+//
+// static public void setColor(PreferencesMap prefs, String attr, Color what) {
+// putColor(prefs, attr, what);
+// }
+//
+//
+// static public Font getFontWithDefault(PreferencesMap prefs, PreferencesMap defaults, String attr) {
+// Font font = getFont(prefs, attr);
+// if (font == null) {
+// String value = defaults.get(attr);
+// prefs.put(attr, value);
+// font = getFont(prefs, attr);
+// }
+// return font;
+// }
+//
+// static public SyntaxStyle getStyle(PreferencesMap prefs, String what) {
+// String str = prefs.get("editor." + what + ".style");
+//
+// StringTokenizer st = new StringTokenizer(str, ",");
+//
+// String s = st.nextToken();
+// if (s.indexOf("#") == 0) s = s.substring(1);
+// Color color = Color.DARK_GRAY;
+// try {
+// color = new Color(Integer.parseInt(s, 16));
+// } catch (Exception e) { }
+//
+// s = st.nextToken();
+// boolean bold = (s.indexOf("bold") != -1);
+// boolean italic = (s.indexOf("italic") != -1);
+// boolean underlined = (s.indexOf("underlined") != -1);
+//
+// return new SyntaxStyle(color, italic, bold, underlined);
+// }
+
+ /**
+ * Set the value of the specified key based on the Color passed as parameter.
+ *
+ * @param attr
+ * @param color
+ */
+ public static void putColor(PreferencesMap prefs, String attr, Color color) {
+ prefs.put(attr, "#" + String.format("%06x", color.getRGB() & 0xffffff));
+ }
+
+ public static Color parseColor(String v) {
+ try {
+ if (v.indexOf("#") == 0)
+ v = v.substring(1);
+ return new Color(Integer.parseInt(v, 16));
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ public static Font getFont(PreferencesMap prefs, String key) {
+ String value = prefs.get(key);
+ if (value == null)
+ return null;
+ String[] split = value.split(",");
+ if (split.length != 3)
+ return null;
+
+ String name = split[0];
+ int style = Font.PLAIN;
+ if (split[1].contains("bold"))
+ style |= Font.BOLD;
+ if (split[1].contains("italic"))
+ style |= Font.ITALIC;
+ int size;
+ try {
+ // ParseDouble handle numbers with decimals too
+ size = (int) Double.parseDouble(split[2]);
+ } catch (NumberFormatException e) {
+ // for wrong formatted size pick the default
+ size = 12;
+ }
+ return new Font(name, style, size);
+ }
+}
diff --git a/app/src/processing/app/helpers/PreferencesMap.java b/app/src/processing/app/helpers/PreferencesMap.java
index 3f2b264ef5d..d374fd8507f 100644
--- a/app/src/processing/app/helpers/PreferencesMap.java
+++ b/app/src/processing/app/helpers/PreferencesMap.java
@@ -21,8 +21,6 @@
*/
package processing.app.helpers;
-import java.awt.Color;
-import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -324,61 +322,4 @@ public boolean putBoolean(String key, boolean value) {
return new Boolean(prev);
}
- /**
- * Create a Color with the value of the specified key. The format of the color
- * should be an hexadecimal number of 6 digit, eventually prefixed with a '#'.
- *
- * @param name
- * @return A Color object or null if the key is not found or the format
- * is wrong
- */
- public Color getColor(String name) {
- return parseColor(get(name));
- }
-
- /**
- * Set the value of the specified key based on the Color passed as parameter.
- *
- * @param attr
- * @param color
- */
- public void putColor(String attr, Color color) {
- put(attr, "#" + String.format("%06x", color.getRGB() & 0xffffff));
- }
-
- public static Color parseColor(String v) {
- try {
- if (v.indexOf("#") == 0)
- v = v.substring(1);
- return new Color(Integer.parseInt(v, 16));
- } catch (Exception e) {
- return null;
- }
- }
-
- public Font getFont(String key) {
- String value = get(key);
- if (value == null)
- return null;
- String[] split = value.split(",");
- if (split.length != 3)
- return null;
-
- String name = split[0];
- int style = Font.PLAIN;
- if (split[1].contains("bold"))
- style |= Font.BOLD;
- if (split[1].contains("italic"))
- style |= Font.ITALIC;
- int size;
- try {
- // ParseDouble handle numbers with decimals too
- size = (int) Double.parseDouble(split[2]);
- } catch (NumberFormatException e) {
- // for wrong formatted size pick the default
- size = 12;
- }
- return new Font(name, style, size);
- }
-
}
diff --git a/app/src/processing/app/preproc/PdePreprocessor.java b/app/src/processing/app/preproc/PdePreprocessor.java
index 10e4b3dd592..e468cfd281d 100644
--- a/app/src/processing/app/preproc/PdePreprocessor.java
+++ b/app/src/processing/app/preproc/PdePreprocessor.java
@@ -90,7 +90,7 @@ public int writePrefix(String program)
program = scrubComments(program);
// If there are errors, an exception is thrown and this fxn exits.
- if (Preferences.getBoolean("preproc.substitute_unicode")) {
+ if (PreferencesData.getBoolean("preproc.substitute_unicode")) {
program = substituteUnicode(program);
}
From 21de7bdea389f5e3f3d9d9d97bd6f1b18a31acc0 Mon Sep 17 00:00:00 2001
From: Claudio Indellicati
Date: Mon, 7 Apr 2014 18:20:17 +0200
Subject: [PATCH 17/73] Moved some code from Sketch to SketchData.
---
app/src/processing/app/Sketch.java | 180 +++++--------------------
app/src/processing/app/SketchData.java | 151 +++++++++++++++++++++
2 files changed, 186 insertions(+), 145 deletions(-)
diff --git a/app/src/processing/app/Sketch.java b/app/src/processing/app/Sketch.java
index fcc3e915b89..b9e93e67785 100644
--- a/app/src/processing/app/Sketch.java
+++ b/app/src/processing/app/Sketch.java
@@ -50,21 +50,9 @@ public class Sketch {
private Editor editor;
- /** main pde file for this sketch. */
- private File primaryFile;
-
/** true if any of the files have been modified. */
private boolean modified;
- /** folder that contains this sketch */
- private File folder;
-
- /** data folder location for this sketch (may not exist yet) */
- private File dataFolder;
-
- /** code folder location for this sketch (may not exist yet) */
- private File codeFolder;
-
private SketchCodeDocument current;
private int currentIndex;
@@ -85,14 +73,7 @@ public class Sketch {
*/
public Sketch(Editor _editor, File file) throws IOException {
editor = _editor;
- data = new SketchData();
- primaryFile = file;
-
- // get the name of the sketch by chopping .pde or .java
- // off of the main file name
- String mainFilename = primaryFile.getName();
- int suffixLength = getDefaultExtension().length() + 1;
- data.setName(mainFilename.substring(0, mainFilename.length() - suffixLength));
+ data = new SketchData(file);
// lib/build must exist when the application is started
// it is added to the CLASSPATH by default, but if it doesn't
@@ -113,9 +94,6 @@ public Sketch(Editor _editor, File file) throws IOException {
tempBuildFolder = Base.getBuildFolder();
//Base.addBuildFolderToClassPath();
- folder = new File(file.getParent());
- //System.out.println("sketch dir is " + folder);
-
load();
}
@@ -135,60 +113,7 @@ public Sketch(Editor _editor, File file) throws IOException {
* in which case the load happens each time "run" is hit.
*/
protected void load() throws IOException {
- codeFolder = new File(folder, "code");
- dataFolder = new File(folder, "data");
-
- // get list of files in the sketch folder
- String list[] = folder.list();
-
- // reset these because load() may be called after an
- // external editor event. (fix for 0099)
- data.clearCodeDocs();
-
- List extensions = getExtensions();
-
- for (String filename : list) {
- // Ignoring the dot prefix files is especially important to avoid files
- // with the ._ prefix on Mac OS X. (You'll see this with Mac files on
- // non-HFS drives, i.e. a thumb drive formatted FAT32.)
- if (filename.startsWith(".")) continue;
-
- // Don't let some wacko name a directory blah.pde or bling.java.
- if (new File(folder, filename).isDirectory()) continue;
-
- // figure out the name without any extension
- String base = filename;
- // now strip off the .pde and .java extensions
- for (String extension : extensions) {
- if (base.toLowerCase().endsWith("." + extension)) {
- base = base.substring(0, base.length() - (extension.length() + 1));
-
- // Don't allow people to use files with invalid names, since on load,
- // it would be otherwise possible to sneak in nasty filenames. [0116]
- if (Sketch.isSanitaryName(base)) {
- data.addCode(new SketchCodeDocument(new File(folder, filename)));
- } else {
- System.err.println(I18n.format("File name {0} is invalid: ignored", filename));
- }
- }
- }
- }
-
- if (data.getCodeCount() == 0)
- throw new IOException(_("No valid code files found"));
-
- // move the main class to the first tab
- // start at 1, if it's at zero, don't bother
- for (SketchCode code : data.getCodes()) {
- //if (code[i].file.getName().equals(mainFilename)) {
- if (code.getFile().equals(primaryFile)) {
- data.moveCodeToFront(code);
- break;
- }
- }
-
- // sort the entries at the top
- data.sortCode();
+ data.load();
// set the main file to be the current tab
if (editor != null) {
@@ -335,7 +260,7 @@ protected void nameCode(String newName) {
I18n.format(
_("A file named \"{0}\" already exists in \"{1}\""),
c.getFileName(),
- folder.getAbsolutePath()
+ data.getFolder().getAbsolutePath()
));
return;
}
@@ -364,7 +289,7 @@ protected void nameCode(String newName) {
}
- File newFile = new File(folder, newName);
+ File newFile = new File(data.getFolder(), newName);
// if (newFile.exists()) { // yay! users will try anything
// Base.showMessage("Nope",
// "A file named \"" + newFile + "\" already exists\n" +
@@ -386,7 +311,7 @@ protected void nameCode(String newName) {
if (currentIndex == 0) {
// get the new folder name/location
String folderName = newName.substring(0, newName.indexOf('.'));
- File newFolder = new File(folder.getParentFile(), folderName);
+ File newFolder = new File(data.getFolder().getParentFile(), folderName);
if (newFolder.exists()) {
Base.showWarning(_("Cannot Rename"),
I18n.format(
@@ -434,7 +359,7 @@ protected void nameCode(String newName) {
}
// now rename the sketch folder and re-open
- boolean success = folder.renameTo(newFolder);
+ boolean success = data.getFolder().renameTo(newFolder);
if (!success) {
Base.showWarning(_("Error"), _("Could not rename the sketch. (2)"), null);
return;
@@ -479,7 +404,7 @@ protected void nameCode(String newName) {
I18n.format(
"Could not create the file \"{0}\" in \"{1}\"",
newFile,
- folder.getAbsolutePath()
+ data.getFolder().getAbsolutePath()
), e);
return;
}
@@ -534,7 +459,7 @@ public void handleDeleteCode() {
// to do a save on the handleNew()
// delete the entire sketch
- Base.removeDir(folder);
+ Base.removeDir(data.getFolder());
// get the changes into the sketchbook menu
//sketchbook.rebuildMenus();
@@ -680,10 +605,7 @@ public boolean accept(File dir, String name) {
}
}
- for (SketchCode code : data.getCodes()) {
- if (code.isModified())
- code.save();
- }
+ data.save();
calcModified();
return true;
}
@@ -720,10 +642,10 @@ protected boolean saveAs() throws IOException {
if (isReadOnly() || isUntitled()) {
// default to the sketchbook folder
- fd.setSelectedFile(new File(Base.getSketchbookFolder().getAbsolutePath(), folder.getName()));
+ fd.setSelectedFile(new File(Base.getSketchbookFolder().getAbsolutePath(), data.getFolder().getName()));
} else {
// default to the parent folder of where this was
- fd.setSelectedFile(folder);
+ fd.setSelectedFile(data.getFolder());
}
int returnVal = fd.showSaveDialog(editor);
@@ -755,7 +677,7 @@ protected boolean saveAs() throws IOException {
}
// check if the paths are identical
- if (newFolder.equals(folder)) {
+ if (newFolder.equals(data.getFolder())) {
// just use "save" here instead, because the user will have received a
// message (from the operating system) about "do you want to replace?"
return save();
@@ -764,7 +686,7 @@ protected boolean saveAs() throws IOException {
// check to see if the user is trying to save this sketch inside itself
try {
String newPath = newFolder.getCanonicalPath() + File.separator;
- String oldPath = folder.getCanonicalPath() + File.separator;
+ String oldPath = data.getFolder().getCanonicalPath() + File.separator;
if (newPath.indexOf(oldPath) == 0) {
Base.showWarning(_("How very Borges of you"),
@@ -800,20 +722,20 @@ protected boolean saveAs() throws IOException {
}
// re-copy the data folder (this may take a while.. add progress bar?)
- if (dataFolder.exists()) {
+ if (data.getDataFolder().exists()) {
File newDataFolder = new File(newFolder, "data");
- Base.copyDir(dataFolder, newDataFolder);
+ Base.copyDir(data.getDataFolder(), newDataFolder);
}
// re-copy the code folder
- if (codeFolder.exists()) {
+ if (data.getCodeFolder().exists()) {
File newCodeFolder = new File(newFolder, "code");
- Base.copyDir(codeFolder, newCodeFolder);
+ Base.copyDir(data.getCodeFolder(), newCodeFolder);
}
// copy custom applet.html file if one exists
// http://dev.processing.org/bugs/show_bug.cgi?id=485
- File customHtml = new File(folder, "applet.html");
+ File customHtml = new File(data.getFolder(), "applet.html");
if (customHtml.exists()) {
File newHtml = new File(newFolder, "applet.html");
Base.copyFile(customHtml, newHtml);
@@ -912,19 +834,19 @@ public boolean addFile(File sourceFile) {
//if (!codeFolder.exists()) codeFolder.mkdirs();
prepareCodeFolder();
- destFile = new File(codeFolder, filename);
+ destFile = new File(data.getCodeFolder(), filename);
} else {
- for (String extension : getExtensions()) {
+ for (String extension : data.getExtensions()) {
String lower = filename.toLowerCase();
if (lower.endsWith("." + extension)) {
- destFile = new File(this.folder, filename);
+ destFile = new File(data.getFolder(), filename);
codeExtension = extension;
}
}
if (codeExtension == null) {
prepareDataFolder();
- destFile = new File(dataFolder, filename);
+ destFile = new File(data.getDataFolder(), filename);
}
}
@@ -1511,14 +1433,14 @@ public boolean exportApplication(String destPath,
* but not its contents.
*/
protected void ensureExistence() {
- if (folder.exists()) return;
+ if (data.getFolder().exists()) return;
Base.showWarning(_("Sketch Disappeared"),
_("The sketch folder has disappeared.\n " +
"Will attempt to re-save in the same location,\n" +
"but anything besides the code will be lost."), null);
try {
- folder.mkdirs();
+ data.getFolder().mkdirs();
modified = true;
for (SketchCode code : data.getCodes()) {
@@ -1542,7 +1464,7 @@ protected void ensureExistence() {
* volumes or folders without appropriate permissions.
*/
public boolean isReadOnly() {
- String apath = folder.getAbsolutePath();
+ String apath = data.getFolder().getAbsolutePath();
for (File folder : Base.getLibrariesPath()) {
if (apath.startsWith(folder.getAbsolutePath()))
return true;
@@ -1591,7 +1513,7 @@ public boolean isDefaultExtension(String what) {
* extensions.
*/
public boolean validExtension(String what) {
- return getExtensions().contains(what);
+ return data.getExtensions().contains(what);
}
@@ -1599,7 +1521,7 @@ public boolean validExtension(String what) {
* Returns the default extension for this editor setup.
*/
public String getDefaultExtension() {
- return "ino";
+ return data.getDefaultExtension();
}
static private List hiddenExtensions = Arrays.asList("ino", "pde");
@@ -1608,13 +1530,6 @@ public List getHiddenExtensions() {
return hiddenExtensions;
}
- /**
- * Returns a String[] array of proper extensions.
- */
- public List getExtensions() {
- return Arrays.asList("ino", "pde", "c", "cpp", "h");
- }
-
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
@@ -1630,20 +1545,11 @@ public String getName() {
}
- /**
- * Returns a file object for the primary .pde of this sketch.
- */
- public File getPrimaryFile() {
- return primaryFile;
- }
-
-
/**
* Returns path to the main .pde file for this sketch.
*/
public String getMainFilePath() {
- return primaryFile.getAbsolutePath();
- //return code[0].file.getAbsolutePath();
+ return data.getMainFilePath();
}
@@ -1651,15 +1557,7 @@ public String getMainFilePath() {
* Returns the sketch folder.
*/
public File getFolder() {
- return folder;
- }
-
-
- /**
- * Returns the location of the sketch's data folder. (It may not exist yet.)
- */
- public File getDataFolder() {
- return dataFolder;
+ return data.getFolder();
}
@@ -1668,18 +1566,10 @@ public File getDataFolder() {
* it also returns the data folder, since it's likely about to be used.
*/
public File prepareDataFolder() {
- if (!dataFolder.exists()) {
- dataFolder.mkdirs();
+ if (!data.getDataFolder().exists()) {
+ data.getDataFolder().mkdirs();
}
- return dataFolder;
- }
-
-
- /**
- * Returns the location of the sketch's code folder. (It may not exist yet.)
- */
- public File getCodeFolder() {
- return codeFolder;
+ return data.getDataFolder();
}
@@ -1688,10 +1578,10 @@ public File getCodeFolder() {
* it also returns the code folder, since it's likely about to be used.
*/
public File prepareCodeFolder() {
- if (!codeFolder.exists()) {
- codeFolder.mkdirs();
+ if (!data.getCodeFolder().exists()) {
+ data.getCodeFolder().mkdirs();
}
- return codeFolder;
+ return data.getCodeFolder();
}
diff --git a/app/src/processing/app/SketchData.java b/app/src/processing/app/SketchData.java
index 4f4a16c0e4f..25b9d9c17e5 100644
--- a/app/src/processing/app/SketchData.java
+++ b/app/src/processing/app/SketchData.java
@@ -1,12 +1,29 @@
package processing.app;
+import static processing.app.I18n._;
+
+import java.io.File;
+import java.io.IOException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SketchData {
+ /** main pde file for this sketch. */
+ private File primaryFile;
+
+ /** folder that contains this sketch */
+ private File folder;
+
+ /** data folder location for this sketch (may not exist yet) */
+ private File dataFolder;
+
+ /** code folder location for this sketch (may not exist yet) */
+ private File codeFolder;
+
/**
* Name of sketch, which is the name of main file (without .pde or .java
* extension)
@@ -22,6 +39,99 @@ public int compare(SketchCode x, SketchCode y) {
}
};
+ SketchData(File file) {
+ primaryFile = file;
+
+ // get the name of the sketch by chopping .pde or .java
+ // off of the main file name
+ String mainFilename = primaryFile.getName();
+ int suffixLength = getDefaultExtension().length() + 1;
+ name = mainFilename.substring(0, mainFilename.length() - suffixLength);
+
+ folder = new File(file.getParent());
+ //System.out.println("sketch dir is " + folder);
+ }
+
+ /**
+ * Build the list of files.
+ *
+ * Generally this is only done once, rather than
+ * each time a change is made, because otherwise it gets to be
+ * a nightmare to keep track of what files went where, because
+ * not all the data will be saved to disk.
+ *
+ * This also gets called when the main sketch file is renamed,
+ * because the sketch has to be reloaded from a different folder.
+ *
+ * Another exception is when an external editor is in use,
+ * in which case the load happens each time "run" is hit.
+ */
+ protected void load() throws IOException {
+ codeFolder = new File(folder, "code");
+ dataFolder = new File(folder, "data");
+
+ // get list of files in the sketch folder
+ String list[] = folder.list();
+
+ // reset these because load() may be called after an
+ // external editor event. (fix for 0099)
+// codeDocs = new SketchCodeDoc[list.length];
+ clearCodeDocs();
+// data.setCodeDocs(codeDocs);
+
+ List extensions = getExtensions();
+
+ for (String filename : list) {
+ // Ignoring the dot prefix files is especially important to avoid files
+ // with the ._ prefix on Mac OS X. (You'll see this with Mac files on
+ // non-HFS drives, i.e. a thumb drive formatted FAT32.)
+ if (filename.startsWith(".")) continue;
+
+ // Don't let some wacko name a directory blah.pde or bling.java.
+ if (new File(folder, filename).isDirectory()) continue;
+
+ // figure out the name without any extension
+ String base = filename;
+ // now strip off the .pde and .java extensions
+ for (String extension : extensions) {
+ if (base.toLowerCase().endsWith("." + extension)) {
+ base = base.substring(0, base.length() - (extension.length() + 1));
+
+ // Don't allow people to use files with invalid names, since on load,
+ // it would be otherwise possible to sneak in nasty filenames. [0116]
+ if (Sketch.isSanitaryName(base)) {
+ addCode(new SketchCodeDocument(new File(folder, filename)));
+ } else {
+ System.err.println(I18n.format("File name {0} is invalid: ignored", filename));
+ }
+ }
+ }
+ }
+
+ if (getCodeCount() == 0)
+ throw new IOException(_("No valid code files found"));
+
+ // move the main class to the first tab
+ // start at 1, if it's at zero, don't bother
+ for (SketchCode code : getCodes()) {
+ //if (code[i].file.getName().equals(mainFilename)) {
+ if (code.getFile().equals(primaryFile)) {
+ moveCodeToFront(code);
+ break;
+ }
+ }
+
+ // sort the entries at the top
+ sortCode();
+ }
+
+ public void save() throws IOException {
+ for (SketchCode code : getCodes()) {
+ if (code.isModified())
+ code.save();
+ }
+ }
+
public int getCodeCount() {
return codes.size();
}
@@ -30,6 +140,35 @@ public SketchCode[] getCodes() {
return codes.toArray(new SketchCode[0]);
}
+ /**
+ * Returns the default extension for this editor setup.
+ */
+ public String getDefaultExtension() {
+ return "ino";
+ }
+
+ /**
+ * Returns a String[] array of proper extensions.
+ */
+ public List getExtensions() {
+ return Arrays.asList("ino", "pde", "c", "cpp", "h");
+ }
+
+ /**
+ * Returns a file object for the primary .pde of this sketch.
+ */
+ public File getPrimaryFile() {
+ return primaryFile;
+ }
+
+ /**
+ * Returns path to the main .pde file for this sketch.
+ */
+ public String getMainFilePath() {
+ return primaryFile.getAbsolutePath();
+ //return code[0].file.getAbsolutePath();
+ }
+
public void addCode(SketchCode sketchCode) {
codes.add(sketchCode);
}
@@ -89,4 +228,16 @@ public void setName(String name) {
public void clearCodeDocs() {
codes.clear();
}
+
+ public File getFolder() {
+ return folder;
+ }
+
+ public File getDataFolder() {
+ return dataFolder;
+ }
+
+ public File getCodeFolder() {
+ return codeFolder;
+ }
}
From 18a8d4d627a6c7c9d7f6255052eff11c727b249b Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Tue, 19 Aug 2014 11:50:51 +0200
Subject: [PATCH 18/73] Created PApplet and PConstants wrapper classes.
Also removed unused ColorSelector and CreateFont to reduce wrappers
size to the minimum.
This commit is preparatory for dropping dependency on processing-core.
---
app/src/processing/app/legacy/PApplet.java | 729 ++++++++++++++++
app/src/processing/app/legacy/PConstants.java | 22 +
.../processing/app/tools/ColorSelector.java | 609 -------------
app/src/processing/app/tools/CreateFont.java | 813 ------------------
4 files changed, 751 insertions(+), 1422 deletions(-)
create mode 100644 app/src/processing/app/legacy/PApplet.java
create mode 100644 app/src/processing/app/legacy/PConstants.java
delete mode 100644 app/src/processing/app/tools/ColorSelector.java
delete mode 100644 app/src/processing/app/tools/CreateFont.java
diff --git a/app/src/processing/app/legacy/PApplet.java b/app/src/processing/app/legacy/PApplet.java
new file mode 100644
index 00000000000..c444a3b2f5f
--- /dev/null
+++ b/app/src/processing/app/legacy/PApplet.java
@@ -0,0 +1,729 @@
+package processing.app.legacy;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.io.UnsupportedEncodingException;
+import java.text.NumberFormat;
+import java.util.ArrayList;
+import java.util.StringTokenizer;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
+public class PApplet {
+
+ /** Path to sketch folder */
+ public String sketchPath; //folder;
+
+ /**
+ * 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, 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 = PConstants.MACOSX;
+
+ } else if (osname.indexOf("Windows") != -1) {
+ platform = PConstants.WINDOWS;
+
+ } else if (osname.equals("Linux")) { // true for the ibm vm
+ platform = PConstants.LINUX;
+
+ } else {
+ platform = PConstants.OTHER;
+ }
+ }
+
+ /**
+ * GIF image of the Processing logo.
+ */
+ static public final byte[] ICON_IMAGE = {
+ 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -60, 0, 0, 0, 0, 0,
+ 0, 0, -127, 0, -127, 0, 0, -127, -127, -127, 0, 0, -127, 0, -127, -127,
+ -127, 0, -127, -127, -127, -63, -63, -63, 0, 0, -1, 0, -1, 0, 0, -1,
+ -1, -1, 0, 0, -1, 0, -1, -1, -1, 0, -1, -1, -1, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, -7, 4,
+ 9, 0, 0, 16, 0, 44, 0, 0, 0, 0, 16, 0, 16, 0, 0, 5,
+ 75, 32, 36, -118, -57, 96, 14, -57, -88, 66, -27, -23, -90, -86, 43, -97,
+ 99, 59, -65, -30, 125, -77, 3, -14, -4, 8, -109, 15, -120, -22, 61, 78,
+ 15, -124, 15, 25, 28, 28, 93, 63, -45, 115, -22, -116, 90, -83, 82, 89,
+ -44, -103, 61, 44, -91, -54, -89, 19, -111, 50, 18, -51, -55, 1, 73, -121,
+ -53, -79, 77, 43, -101, 12, -74, -30, -99, -24, -94, 16, 0, 59,
+ };
+
+ /**
+ * Split the provided String at wherever whitespace occurs. Multiple
+ * whitespace (extra spaces or tabs or whatever) between items will count as a
+ * single break.
+ *
+ * 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).
+ *
+ *
+ */
+ static public String[] splitTokens(String what) {
+ return splitTokens(what, PConstants.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.
+ *
+ *
+ */
+ 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.
+ *
+ * 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;
+
+ char chars[] = what.toCharArray();
+ int splitCount = 0; // 1;
+ for (int i = 0; i < chars.length; i++) {
+ if (chars[i] == delim)
+ splitCount++;
+ }
+ if (splitCount == 0) {
+ String splits[] = new String[1];
+ splits[0] = new String(what);
+ return splits;
+ }
+ 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;
+ }
+ }
+ splits[splitIndex] = new String(chars, startIndex, chars.length
+ - startIndex);
+ return splits;
+ }
+
+ static public String[] subset(String list[], int start, int count) {
+ String output[] = new String[count];
+ System.arraycopy(list, start, output, 0, count);
+ return output;
+ }
+
+
+ /**
+ * 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.
+ *
+ * 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.
+ *
+ * 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();
+ }
+
+ /**
+ * Parse a String into an int value. Returns 0 if the value is bad.
+ */
+ static final public int parseInt(String what) {
+ return parseInt(what, 0);
+ }
+
+ /**
+ * Parse a String to an int, and provide an alternate value that
+ * should be used when the number is invalid.
+ */
+ static final public int parseInt(String what, int otherwise) {
+ try {
+ int offset = what.indexOf('.');
+ if (offset == -1) {
+ return Integer.parseInt(what);
+ } else {
+ return Integer.parseInt(what.substring(0, offset));
+ }
+ } catch (NumberFormatException e) { }
+ return otherwise;
+ }
+
+ /**
+ * Make an array of int elements from an array of String objects.
+ * If the String can't be parsed as a number, it will be set to zero.
+ *
+ * String s[] = { "1", "300", "44" };
+ * int numbers[] = parseInt(s);
+ *
+ * numbers will contain { 1, 300, 44 }
+ */
+ static public int[] parseInt(String what[]) {
+ return parseInt(what, 0);
+ }
+
+ /**
+ * Make an array of int elements from an array of String objects.
+ * If the String can't be parsed as a number, its entry in the
+ * array will be set to the value of the "missing" parameter.
+ *
+ * String s[] = { "1", "300", "apple", "44" };
+ * int numbers[] = parseInt(s, 9999);
+ *
+ * numbers will contain { 1, 300, 9999, 44 }
+ */
+ static public int[] parseInt(String what[], int missing) {
+ int output[] = new int[what.length];
+ for (int i = 0; i < what.length; i++) {
+ try {
+ output[i] = Integer.parseInt(what[i]);
+ } catch (NumberFormatException e) {
+ output[i] = missing;
+ }
+ }
+ return output;
+ }
+
+ static public String[] loadStrings(File file) {
+ InputStream is = createInput(file);
+ if (is != null) return loadStrings(is);
+ 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;
+ }
+
+ public void saveStrings(String filename, String strings[]) {
+ saveStrings(saveFile(filename), strings);
+ }
+
+
+ static public void saveStrings(File file, String strings[]) {
+ saveStrings(createOutput(file), strings);
+ }
+
+
+ static public void saveStrings(OutputStream output, String strings[]) {
+ PrintWriter writer = createWriter(output);
+ for (int i = 0; i < strings.length; i++) {
+ writer.println(strings[i]);
+ }
+ writer.flush();
+ writer.close();
+ }
+
+
+ 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 final public String hex(int what, int digits) {
+ String stuff = Integer.toHexString(what).toUpperCase();
+
+ int length = stuff.length();
+ if (length > digits) {
+ return stuff.substring(length - digits);
+
+ } else if (length < digits) {
+ return "00000000".substring(8 - (digits-length)) + stuff;
+ }
+ return stuff;
+ }
+
+ 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);
+ }
+
+ /**
+ * 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).
+ *
+ * The args parameter is a String or String array which is passed to the command line. If you have multiple parameters, e.g. an application and a document, or a command with multiple switches, use the version that takes a String array, and place each individual item in a separate element.
+ *
+ * If args is a String (not an array), then it can only be a single file or application with no parameters. It's not the same as executing that String using a shell. For instance, open("jikes -help") will not work properly.
+ *
+ * This function behaves differently on each platform. On Windows, the parameters are sent to the Windows shell via "cmd /c". On Mac OS X, the "open" command is used (type "man open" in Terminal.app for documentation). On Linux, it first tries gnome-open, then kde-open, but if neither are available, it sends the command to the shell without any alterations.
+ *
+ * For users familiar with Java, this is not quite the same as Runtime.exec(), because the launcher command is prepended. Instead, the exec(String[]) function is a shortcut for Runtime.getRuntime.exec(String[]).
+ *
+ * @webref input:files
+ * @param filename name of the file
+ * @usage Application
+ */
+ static public void open(String filename) {
+ open(new String[] { filename });
+ }
+
+ static String openLauncher;
+
+ /**
+ * Launch a process using a platforms shell. This version uses an array
+ * to make it easier to deal with spaces in the individual elements.
+ * (This avoids the situation of trying to put single or double quotes
+ * around different bits).
+ *
+ * @param list of commands passed to the command line
+ */
+ static public Process open(String argv[]) {
+ String[] params = null;
+
+ if (platform == PConstants.WINDOWS) {
+ // just launching the .html file via the shell works
+ // but make sure to chmod +x the .html files first
+ // also place quotes around it in case there's a space
+ // in the user.dir part of the url
+ params = new String[] { "cmd", "/c" };
+
+ } else if (platform == PConstants.MACOSX) {
+ params = new String[] { "open" };
+
+ } else if (platform == PConstants.LINUX) {
+ if (openLauncher == null) {
+ // Attempt to use gnome-open
+ try {
+ Process p = Runtime.getRuntime().exec(new String[] { "gnome-open" });
+ /*int result =*/ p.waitFor();
+ // Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04)
+ openLauncher = "gnome-open";
+ } catch (Exception e) { }
+ }
+ if (openLauncher == null) {
+ // Attempt with kde-open
+ try {
+ Process p = Runtime.getRuntime().exec(new String[] { "kde-open" });
+ /*int result =*/ p.waitFor();
+ openLauncher = "kde-open";
+ } catch (Exception e) { }
+ }
+ if (openLauncher == null) {
+ System.err.println("Could not find gnome-open or kde-open, " +
+ "the open() command may not work.");
+ }
+ if (openLauncher != null) {
+ params = new String[] { openLauncher };
+ }
+ //} else { // give up and just pass it to Runtime.exec()
+ //open(new String[] { filename });
+ //params = new String[] { filename };
+ }
+ if (params != null) {
+ // If the 'open', 'gnome-open' or 'cmd' are already included
+ if (params[0].equals(argv[0])) {
+ // then don't prepend those params again
+ return exec(argv);
+ } else {
+ params = concat(params, argv);
+ return exec(params);
+ }
+ } else {
+ return exec(argv);
+ }
+ }
+
+ static public Process exec(String[] argv) {
+ try {
+ return Runtime.getRuntime().exec(argv);
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new RuntimeException("Could not open " + join(argv, ' '));
+ }
+ }
+
+ 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;
+ }
+
+ /**
+ * Identical to match(), except that it returns an array of all matches in
+ * the specified String, rather than just the first.
+ */
+ static public String[][] matchAll(String what, String regexp) {
+ Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
+ Matcher m = p.matcher(what);
+ ArrayList results = new ArrayList();
+ int count = m.groupCount() + 1;
+ while (m.find()) {
+ String[] groups = new String[count];
+ for (int i = 0; i < count; i++) {
+ groups[i] = m.group(i);
+ }
+ results.add(groups);
+ }
+ if (results.isEmpty()) {
+ return null;
+ }
+ String[][] matches = new String[results.size()][count];
+ for (int i = 0; i < matches.length; i++) {
+ matches[i] = (String[]) results.get(i);
+ }
+ return matches;
+ }
+
+ /**
+ * Match a string with a regular expression, and returns the match as an
+ * array. The first index is the matching expression, and array elements
+ * [1] and higher represent each of the groups (sequences found in parens).
+ *
+ * This uses multiline matching (Pattern.MULTILINE) and dotall mode
+ * (Pattern.DOTALL) by default, so that ^ and $ match the beginning and
+ * end of any lines found in the source, and the . operator will also
+ * pick up newline characters.
+ */
+ static public String[] match(String what, String regexp) {
+ Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
+ Matcher m = p.matcher(what);
+ if (m.find()) {
+ int count = m.groupCount() + 1;
+ String[] groups = new String[count];
+ for (int i = 0; i < count; i++) {
+ groups[i] = m.group(i);
+ }
+ return groups;
+ }
+ return null;
+ }
+
+ /**
+ * Integer number formatter.
+ */
+ static private NumberFormat int_nf;
+ static private int int_nf_digits;
+ static private boolean int_nf_commas;
+
+ static public String[] nf(int num[], int digits) {
+ String formatted[] = new String[num.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nf(num[i], digits);
+ }
+ return formatted;
+ }
+
+ static public String nf(int num, int digits) {
+ if ((int_nf != null) &&
+ (int_nf_digits == digits) &&
+ !int_nf_commas) {
+ return int_nf.format(num);
+ }
+
+ int_nf = NumberFormat.getInstance();
+ int_nf.setGroupingUsed(false); // no commas
+ int_nf_commas = false;
+ int_nf.setMinimumIntegerDigits(digits);
+ int_nf_digits = digits;
+ return int_nf.format(num);
+ }
+
+ static final public String[] str(int x[]) {
+ String s[] = new String[x.length];
+ for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
+ return s;
+ }
+
+ /**
+ * I want to print lines to a file. I have RSI from typing these
+ * eight lines of code so many times.
+ */
+ static public PrintWriter createWriter(File file) {
+ try {
+ createPath(file); // make sure in-between folders exist
+ OutputStream output = new FileOutputStream(file);
+ if (file.getName().toLowerCase().endsWith(".gz")) {
+ output = new GZIPOutputStream(output);
+ }
+ return createWriter(output);
+
+ } catch (Exception e) {
+ if (file == null) {
+ throw new RuntimeException("File passed to createWriter() was null");
+ } else {
+ e.printStackTrace();
+ throw new RuntimeException("Couldn't create a writer for " +
+ file.getAbsolutePath());
+ }
+ }
+ //return null;
+ }
+
+
+ /**
+ * I want to print lines to a file. Why am I always explaining myself?
+ * It's the JavaSoft API engineers who need to explain themselves.
+ */
+ static public PrintWriter createWriter(OutputStream output) {
+ try {
+ OutputStreamWriter osw = new OutputStreamWriter(output, "UTF-8");
+ return new PrintWriter(osw);
+ } catch (UnsupportedEncodingException e) { } // not gonna happen
+ 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;
+ }
+ }
+
+ /**
+ * Returns a path inside the applet folder to save to. Like sketchPath(),
+ * but creates any in-between folders so that things save properly.
+ *
+ * All saveXxxx() functions use the path to the sketch folder, rather than
+ * its data folder. Once exported, the data folder will be found inside the
+ * jar file of the exported application or applet. In this case, it's not
+ * possible to save data into the jar file, because it will often be running
+ * from a server, or marked in-use if running from a local file system.
+ * With this in mind, saving to the data path doesn't make sense anyway.
+ * If you know you're running locally, and want to save to the data folder,
+ * use saveXxxx("data/blah.dat").
+ */
+ public String savePath(String where) {
+ if (where == null) return null;
+ String filename = sketchPath(where);
+ createPath(filename);
+ return filename;
+ }
+
+
+ /**
+ * Identical to savePath(), but returns a File object.
+ */
+ public File saveFile(String where) {
+ return new File(savePath(where));
+ }
+
+ /**
+ * 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.
+ *
+ * If the path does not exist, intermediate folders will be created. If an
+ * exception occurs, it will be printed to the console, and null will be
+ * returned.
+ *
+ * Future releases may also add support for handling HTTP POST via this
+ * method (for better symmetry with createInput), however that's maybe a
+ * little too clever (and then we'd have to add the same features to the
+ * other file functions like createWriter). Who you callin' bloated?
+ */
+ public OutputStream createOutput(String filename) {
+ return createOutput(saveFile(filename));
+ }
+
+
+ static public OutputStream createOutput(File file) {
+ try {
+ createPath(file); // make sure the path exists
+ FileOutputStream fos = new FileOutputStream(file);
+ if (file.getName().toLowerCase().endsWith(".gz")) {
+ return new GZIPOutputStream(fos);
+ }
+ return fos;
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ /**
+ * Prepend the sketch folder path to the filename (or path) that is
+ * passed in. External libraries should use this function to save to
+ * the sketch folder.
+ *
+ * Note that when running as an applet inside a web browser,
+ * the sketchPath will be set to null, because security restrictions
+ * prevent applets from accessing that information.
+ *
+ * This will also cause an error if the sketch is not inited properly,
+ * meaning that init() was never called on the PApplet when hosted
+ * my some other main() or by other code. For proper use of init(),
+ * see the examples in the main description text for PApplet.
+ */
+ public String sketchPath(String where) {
+ if (sketchPath == null) {
+ return where;
+// throw new RuntimeException("The applet was not inited properly, " +
+// "or security restrictions prevented " +
+// "it from determining its path.");
+ }
+ // isAbsolute() could throw an access exception, but so will writing
+ // to the local disk using the sketch path, so this is safe here.
+ // for 0120, added a try/catch anyways.
+ try {
+ if (new File(where).isAbsolute()) return where;
+ } catch (Exception e) { }
+
+ return sketchPath + File.separator + 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());
+ }
+ }
+
+
+}
diff --git a/app/src/processing/app/legacy/PConstants.java b/app/src/processing/app/legacy/PConstants.java
new file mode 100644
index 00000000000..3b1d491d559
--- /dev/null
+++ b/app/src/processing/app/legacy/PConstants.java
@@ -0,0 +1,22 @@
+package processing.app.legacy;
+
+public class PConstants {
+
+ // platform IDs for PApplet.platform
+
+ public static final int OTHER = 0;
+ public static final int WINDOWS = 1;
+ public static final int MACOSX = 2;
+ public static final int LINUX = 3;
+
+ public static final String[] platformNames = {
+ "other", "windows", "macosx", "linux"
+ };
+
+
+ // used by split, all the standard whitespace chars
+ // (also includes unicode nbsp, that little bostage)
+
+ static final String WHITESPACE = " \t\n\r\f\u00A0";
+
+}
diff --git a/app/src/processing/app/tools/ColorSelector.java b/app/src/processing/app/tools/ColorSelector.java
deleted file mode 100644
index de14022398c..00000000000
--- a/app/src/processing/app/tools/ColorSelector.java
+++ /dev/null
@@ -1,609 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2006-08 Ben Fry and Casey Reas
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software Foundation,
- Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-*/
-
-package processing.app.tools;
-
-import processing.app.*;
-import processing.core.*;
-
-import java.awt.*;
-import java.awt.event.*;
-import javax.swing.*;
-import javax.swing.border.*;
-import javax.swing.event.*;
-import javax.swing.text.*;
-
-
-/**
- * Color selector tool for the Tools menu.
- *
- * Using the keyboard shortcuts, you can copy/paste the values for the
- * colors and paste them into your program. We didn't do any sort of
- * auto-insert of colorMode() or fill() or stroke() code cuz we couldn't
- * decide on a good way to do this.. your contributions welcome).
- */
-public class ColorSelector implements Tool, DocumentListener {
-
- Editor editor;
- JFrame frame;
-
- int hue, saturation, brightness; // range 360, 100, 100
- int red, green, blue; // range 256, 256, 256
-
- ColorRange range;
- ColorSlider slider;
-
- JTextField hueField, saturationField, brightnessField;
- JTextField redField, greenField, blueField;
-
- JTextField hexField;
-
- JPanel colorPanel;
-
-
- public String getMenuTitle() {
- return "Color Selector";
- }
-
-
- public void init(Editor editor) {
- this.editor = editor;
-
- frame = new JFrame("Color Selector");
- frame.getContentPane().setLayout(new BorderLayout());
-
- Box box = Box.createHorizontalBox();
- box.setBorder(new EmptyBorder(12, 12, 12, 12));
-
- range = new ColorRange();
- range.init();
- Box rangeBox = new Box(BoxLayout.Y_AXIS);
- rangeBox.setAlignmentY(0);
- rangeBox.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
- rangeBox.add(range);
- box.add(rangeBox);
- box.add(Box.createHorizontalStrut(10));
-
- slider = new ColorSlider();
- slider.init();
- Box sliderBox = new Box(BoxLayout.Y_AXIS);
- sliderBox.setAlignmentY(0);
- sliderBox.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
- sliderBox.add(slider);
- box.add(sliderBox);
- box.add(Box.createHorizontalStrut(10));
-
- box.add(createColorFields());
- box.add(Box.createHorizontalStrut(10));
-
- frame.getContentPane().add(box, BorderLayout.CENTER);
- frame.pack();
- frame.setResizable(false);
-
- // these don't help either.. they fix the component size but
- // leave a gap where the component is located
- //range.setSize(256, 256);
- //slider.setSize(256, 20);
-
- Dimension size = frame.getSize();
- Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
- frame.setLocation((screen.width - size.width) / 2,
- (screen.height - size.height) / 2);
-
- frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
- frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- frame.setVisible(false);
- }
- });
- Base.registerWindowCloseKeys(frame.getRootPane(), new ActionListener() {
- public void actionPerformed(ActionEvent actionEvent) {
- frame.setVisible(false);
- }
- });
-
- Base.setIcon(frame);
-
- hueField.getDocument().addDocumentListener(this);
- saturationField.getDocument().addDocumentListener(this);
- brightnessField.getDocument().addDocumentListener(this);
- redField.getDocument().addDocumentListener(this);
- greenField.getDocument().addDocumentListener(this);
- blueField.getDocument().addDocumentListener(this);
- hexField.getDocument().addDocumentListener(this);
-
- hexField.setText("FFFFFF");
- }
-
-
- public void run() {
- frame.setVisible(true);
- // You've got to be f--ing kidding me.. why did the following line
- // get deprecated for the pile of s-- that follows it?
- //frame.setCursor(Cursor.CROSSHAIR_CURSOR);
- frame.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
- }
-
-
- public void changedUpdate(DocumentEvent e) {
- //System.out.println("changed");
- }
-
- public void removeUpdate(DocumentEvent e) {
- //System.out.println("remove");
- }
-
-
- boolean updating;
-
- public void insertUpdate(DocumentEvent e) {
- if (updating) return; // don't update forever recursively
- updating = true;
-
- Document doc = e.getDocument();
- if (doc == hueField.getDocument()) {
- hue = bounded(hue, hueField, 359);
- updateRGB();
- updateHex();
-
- } else if (doc == saturationField.getDocument()) {
- saturation = bounded(saturation, saturationField, 99);
- updateRGB();
- updateHex();
-
- } else if (doc == brightnessField.getDocument()) {
- brightness = bounded(brightness, brightnessField, 99);
- updateRGB();
- updateHex();
-
- } else if (doc == redField.getDocument()) {
- red = bounded(red, redField, 255);
- updateHSB();
- updateHex();
-
- } else if (doc == greenField.getDocument()) {
- green = bounded(green, greenField, 255);
- updateHSB();
- updateHex();
-
- } else if (doc == blueField.getDocument()) {
- blue = bounded(blue, blueField, 255);
- updateHSB();
- updateHex();
-
- } else if (doc == hexField.getDocument()) {
- String str = hexField.getText();
- while (str.length() < 6) {
- str += "0";
- }
- if (str.length() > 6) {
- str = str.substring(0, 6);
- }
- updateRGB2(Integer.parseInt(str, 16));
- updateHSB();
- }
- range.redraw();
- slider.redraw();
- colorPanel.repaint();
- updating = false;
- }
-
-
- /**
- * Set the RGB values based on the current HSB values.
- */
- protected void updateRGB() {
- int rgb = Color.HSBtoRGB((float)hue / 359f,
- (float)saturation / 99f,
- (float)brightness / 99f);
- updateRGB2(rgb);
- }
-
-
- /**
- * Set the RGB values based on a calculated ARGB int.
- * Used by both updateRGB() to set the color from the HSB values,
- * and by updateHex(), to unpack the hex colors and assign them.
- */
- protected void updateRGB2(int rgb) {
- red = (rgb >> 16) & 0xff;
- green = (rgb >> 8) & 0xff;
- blue = rgb & 0xff;
-
- redField.setText(String.valueOf(red));
- greenField.setText(String.valueOf(green));
- blueField.setText(String.valueOf(blue));
- }
-
-
- /**
- * Set the HSB values based on the current RGB values.
- */
- protected void updateHSB() {
- float hsb[] = new float[3];
- Color.RGBtoHSB(red, green, blue, hsb);
-
- hue = (int) (hsb[0] * 359.0f);
- saturation = (int) (hsb[1] * 99.0f);
- brightness = (int) (hsb[2] * 99.0f);
-
- hueField.setText(String.valueOf(hue));
- saturationField.setText(String.valueOf(saturation));
- brightnessField.setText(String.valueOf(brightness));
- }
-
-
- protected void updateHex() {
- hexField.setText(PApplet.hex(red, 2) +
- PApplet.hex(green, 2) +
- PApplet.hex(blue, 2));
- }
-
-
- /**
- * Get the bounded value for a specific range. If the value is outside
- * the max, you can't edit right away, so just act as if it's already
- * been bounded and return the bounded value, then fire an event to set
- * it to the value that was just returned.
- */
- protected int bounded(int current, final JTextField field, final int max) {
- String text = field.getText();
- if (text.length() == 0) {
- return 0;
- }
- try {
- int value = Integer.parseInt(text);
- if (value > max) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- field.setText(String.valueOf(max));
- }
- });
- return max;
- }
- return value;
-
- } catch (NumberFormatException e) {
- return current; // should not be reachable
- }
- }
-
-
- protected Container createColorFields() {
- Box box = Box.createVerticalBox();
- box.setAlignmentY(0);
-
- colorPanel = new JPanel() {
- public void paintComponent(Graphics g) {
- g.setColor(new Color(red, green, blue));
- Dimension size = getSize();
- g.fillRect(0, 0, size.width, size.height);
- }
- };
- colorPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
- Dimension dim = new Dimension(60, 40);
- colorPanel.setMinimumSize(dim);
- //colorPanel.setMaximumSize(dim);
- //colorPanel.setPreferredSize(dim);
- box.add(colorPanel);
- box.add(Box.createVerticalStrut(10));
-
- Box row;
-
- row = Box.createHorizontalBox();
- row.add(createFixedLabel("H:"));
- row.add(hueField = new NumberField(4, false));
- row.add(new JLabel(" \u00B0")); // degree symbol
- row.add(Box.createHorizontalGlue());
- box.add(row);
- box.add(Box.createVerticalStrut(5));
-
- row = Box.createHorizontalBox();
- row.add(createFixedLabel("S:"));
- row.add(saturationField = new NumberField(4, false));
- row.add(new JLabel(" %"));
- row.add(Box.createHorizontalGlue());
- box.add(row);
- box.add(Box.createVerticalStrut(5));
-
- row = Box.createHorizontalBox();
- row.add(createFixedLabel("B:"));
- row.add(brightnessField = new NumberField(4, false));
- row.add(new JLabel(" %"));
- row.add(Box.createHorizontalGlue());
- box.add(row);
- box.add(Box.createVerticalStrut(10));
-
- //
-
- row = Box.createHorizontalBox();
- row.add(createFixedLabel("R:"));
- row.add(redField = new NumberField(4, false));
- row.add(Box.createHorizontalGlue());
- box.add(row);
- box.add(Box.createVerticalStrut(5));
-
- row = Box.createHorizontalBox();
- row.add(createFixedLabel("G:"));
- row.add(greenField = new NumberField(4, false));
- row.add(Box.createHorizontalGlue());
- box.add(row);
- box.add(Box.createVerticalStrut(5));
-
- row = Box.createHorizontalBox();
- row.add(createFixedLabel("B:"));
- row.add(blueField = new NumberField(4, false));
- row.add(Box.createHorizontalGlue());
- box.add(row);
- box.add(Box.createVerticalStrut(10));
-
- //
-
- row = Box.createHorizontalBox();
- row.add(createFixedLabel("#"));
- row.add(hexField = new NumberField(5, true));
- row.add(Box.createHorizontalGlue());
- box.add(row);
- box.add(Box.createVerticalStrut(10));
-
- box.add(Box.createVerticalGlue());
- return box;
- }
-
-
- int labelH;
-
- /**
- * return a label of a fixed width
- */
- protected JLabel createFixedLabel(String title) {
- JLabel label = new JLabel(title);
- if (labelH == 0) {
- labelH = label.getPreferredSize().height;
- }
- Dimension dim = new Dimension(20, labelH);
- label.setPreferredSize(dim);
- label.setMinimumSize(dim);
- label.setMaximumSize(dim);
- return label;
- }
-
-
- public class ColorRange extends PApplet {
-
- static final int WIDE = 256;
- static final int HIGH = 256;
-
- int lastX, lastY;
-
-
- public void setup() {
- size(WIDE, HIGH, P3D);
- noLoop();
-
- colorMode(HSB, 360, 256, 256);
- noFill();
- rectMode(CENTER);
- }
-
- public void draw() {
- if ((g == null) || (g.pixels == null)) return;
- if ((width != WIDE) || (height < HIGH)) {
- //System.out.println("bad size " + width + " " + height);
- return;
- }
-
- int index = 0;
- for (int j = 0; j < 256; j++) {
- for (int i = 0; i < 256; i++) {
- g.pixels[index++] = color(hue, i, 255 - j);
- }
- }
-
- stroke((brightness > 50) ? 0 : 255);
- rect(lastX, lastY, 9, 9);
- }
-
- public void mousePressed() {
- updateMouse();
- }
-
- public void mouseDragged() {
- updateMouse();
- }
-
- public void updateMouse() {
- if ((mouseX >= 0) && (mouseX < 256) &&
- (mouseY >= 0) && (mouseY < 256)) {
- int nsaturation = (int) (100 * (mouseX / 255.0f));
- int nbrightness = 100 - ((int) (100 * (mouseY / 255.0f)));
- saturationField.setText(String.valueOf(nsaturation));
- brightnessField.setText(String.valueOf(nbrightness));
-
- lastX = mouseX;
- lastY = mouseY;
- }
- }
-
- public Dimension getPreferredSize() {
- return new Dimension(WIDE, HIGH);
- }
-
- public Dimension getMinimumSize() {
- return new Dimension(WIDE, HIGH);
- }
-
- public Dimension getMaximumSize() {
- return new Dimension(WIDE, HIGH);
- }
-
- public void keyPressed() {
- if (key == ESC) {
- ColorSelector.this.frame.setVisible(false);
- // don't quit out of processing
- // http://dev.processing.org/bugs/show_bug.cgi?id=1006
- key = 0;
- }
- }
- }
-
-
- public class ColorSlider extends PApplet {
-
- static final int WIDE = 20;
- static final int HIGH = 256;
-
- public void setup() {
- size(WIDE, HIGH, P3D);
- colorMode(HSB, 255, 100, 100);
- noLoop();
- }
-
- public void draw() {
- if ((g == null) || (g.pixels == null)) return;
- if ((width != WIDE) || (height < HIGH)) {
- //System.out.println("bad size " + width + " " + height);
- return;
- }
-
- int index = 0;
- int sel = 255 - (int) (255 * (hue / 359f));
- for (int j = 0; j < 256; j++) {
- int c = color(255 - j, 100, 100);
- if (j == sel) c = 0xFF000000;
- for (int i = 0; i < WIDE; i++) {
- g.pixels[index++] = c;
- }
- }
- }
-
- public void mousePressed() {
- updateMouse();
- }
-
- public void mouseDragged() {
- updateMouse();
- }
-
- public void updateMouse() {
- if ((mouseX >= 0) && (mouseX < 256) &&
- (mouseY >= 0) && (mouseY < 256)) {
- int nhue = 359 - (int) (359 * (mouseY / 255.0f));
- hueField.setText(String.valueOf(nhue));
- }
- }
-
- public Dimension getPreferredSize() {
- return new Dimension(WIDE, HIGH);
- }
-
- public Dimension getMinimumSize() {
- return new Dimension(WIDE, HIGH);
- }
-
- public Dimension getMaximumSize() {
- return new Dimension(WIDE, HIGH);
- }
-
- public void keyPressed() {
- if (key == ESC) {
- ColorSelector.this.frame.setVisible(false);
- // don't quit out of processing
- // http://dev.processing.org/bugs/show_bug.cgi?id=1006
- key = 0;
- }
- }
- }
-
-
- /**
- * Extension of JTextField that only allows numbers
- */
- class NumberField extends JTextField {
-
- public boolean allowHex;
-
- public NumberField(int cols, boolean allowHex) {
- super(cols);
- this.allowHex = allowHex;
- }
-
- protected Document createDefaultModel() {
- return new NumberDocument(this);
- }
-
- public Dimension getPreferredSize() {
- if (!allowHex) {
- return new Dimension(45, super.getPreferredSize().height);
- }
- return super.getPreferredSize();
- }
-
- public Dimension getMinimumSize() {
- return getPreferredSize();
- }
-
- public Dimension getMaximumSize() {
- return getPreferredSize();
- }
- }
-
-
- /**
- * Document model to go with JTextField that only allows numbers.
- */
- class NumberDocument extends PlainDocument {
-
- NumberField parentField;
-
- public NumberDocument(NumberField parentField) {
- this.parentField = parentField;
- //System.out.println("setting parent to " + parentSelector);
- }
-
- public void insertString(int offs, String str, AttributeSet a)
- throws BadLocationException {
-
- if (str == null) return;
-
- char chars[] = str.toCharArray();
- int charCount = 0;
- // remove any non-digit chars
- for (int i = 0; i < chars.length; i++) {
- boolean ok = Character.isDigit(chars[i]);
- if (parentField.allowHex) {
- if ((chars[i] >= 'A') && (chars[i] <= 'F')) ok = true;
- if ((chars[i] >= 'a') && (chars[i] <= 'f')) ok = true;
- }
- if (ok) {
- if (charCount != i) { // shift if necessary
- chars[charCount] = chars[i];
- }
- charCount++;
- }
- }
- super.insertString(offs, new String(chars, 0, charCount), a);
- // can't call any sort of methods on the enclosing class here
- // seems to have something to do with how Document objects are set up
- }
- }
-}
diff --git a/app/src/processing/app/tools/CreateFont.java b/app/src/processing/app/tools/CreateFont.java
deleted file mode 100644
index 62d2ce4c076..00000000000
--- a/app/src/processing/app/tools/CreateFont.java
+++ /dev/null
@@ -1,813 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2004-10 Ben Fry and Casey Reas
- Copyright (c) 2001-04 Massachusetts Institute of Technology
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software Foundation,
- Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-*/
-
-package processing.app.tools;
-
-import processing.app.*;
-import processing.core.*;
-
-import java.awt.*;
-import java.awt.event.*;
-import java.io.*;
-import java.util.*;
-
-import javax.swing.*;
-import javax.swing.border.*;
-import javax.swing.event.*;
-
-
-/**
- * GUI tool for font creation heaven/hell.
- */
-public class CreateFont extends JFrame implements Tool {
- Editor editor;
- //Sketch sketch;
-
- Dimension windowSize;
-
- JList fontSelector;
- JTextField sizeSelector;
- JButton charsetButton;
- JCheckBox smoothBox;
- JComponent sample;
- JButton okButton;
- JTextField filenameField;
-
- HashMap table;
- boolean smooth = true;
-
- Font font;
-
- String[] list;
- int selection = -1;
-
- CharacterSelector charSelector;
-
-
- public CreateFont() {
- super("Create Font");
- }
-
-
- public String getMenuTitle() {
- return "Create Font...";
- }
-
-
- public void init(Editor editor) {
- this.editor = editor;
-
- Container paine = getContentPane();
- paine.setLayout(new BorderLayout()); //10, 10));
-
- JPanel pain = new JPanel();
- pain.setBorder(new EmptyBorder(13, 13, 13, 13));
- paine.add(pain, BorderLayout.CENTER);
-
- pain.setLayout(new BoxLayout(pain, BoxLayout.Y_AXIS));
-
- String labelText =
- "Use this tool to create bitmap fonts for your program.\n" +
- "Select a font and size, and click 'OK' to generate the font.\n" +
- "It will be added to the data folder of the current sketch.";
-
- JTextArea textarea = new JTextArea(labelText);
- textarea.setBorder(new EmptyBorder(10, 10, 20, 10));
- textarea.setBackground(null);
- textarea.setEditable(false);
- textarea.setHighlighter(null);
- textarea.setFont(new Font("Dialog", Font.PLAIN, 12));
- pain.add(textarea);
-
- // don't care about families starting with . or #
- // also ignore dialog, dialoginput, monospaced, serif, sansserif
-
- // getFontList is deprecated in 1.4, so this has to be used
- GraphicsEnvironment ge =
- GraphicsEnvironment.getLocalGraphicsEnvironment();
-
- Font fonts[] = ge.getAllFonts();
-
- String flist[] = new String[fonts.length];
- table = new HashMap();
-
- int index = 0;
- for (int i = 0; i < fonts.length; i++) {
- //String psname = fonts[i].getPSName();
- //if (psname == null) System.err.println("ps name is null");
-
- flist[index++] = fonts[i].getPSName();
- table.put(fonts[i].getPSName(), fonts[i]);
- }
-
- list = new String[index];
- System.arraycopy(flist, 0, list, 0, index);
-
- fontSelector = new JList(list);
- fontSelector.addListSelectionListener(new ListSelectionListener() {
- public void valueChanged(ListSelectionEvent e) {
- if (e.getValueIsAdjusting() == false) {
- selection = fontSelector.getSelectedIndex();
- okButton.setEnabled(true);
- update();
- }
- }
- });
-
- fontSelector.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- fontSelector.setVisibleRowCount(12);
- JScrollPane fontScroller = new JScrollPane(fontSelector);
- pain.add(fontScroller);
-
- Dimension d1 = new Dimension(13, 13);
- pain.add(new Box.Filler(d1, d1, d1));
-
- sample = new SampleComponent(this);
-
- // Seems that in some instances, no default font is set
- // http://dev.processing.org/bugs/show_bug.cgi?id=777
- sample.setFont(new Font("Dialog", Font.PLAIN, 12));
-
- pain.add(sample);
-
- Dimension d2 = new Dimension(6, 6);
- pain.add(new Box.Filler(d2, d2, d2));
-
- JPanel panel = new JPanel();
- panel.add(new JLabel("Size:"));
- sizeSelector = new JTextField(" 48 ");
- sizeSelector.getDocument().addDocumentListener(new DocumentListener() {
- public void insertUpdate(DocumentEvent e) { update(); }
- public void removeUpdate(DocumentEvent e) { update(); }
- public void changedUpdate(DocumentEvent e) { }
- });
- panel.add(sizeSelector);
-
- smoothBox = new JCheckBox("Smooth");
- smoothBox.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- smooth = smoothBox.isSelected();
- update();
- }
- });
- smoothBox.setSelected(smooth);
- panel.add(smoothBox);
-
-// allBox = new JCheckBox("All Characters");
-// allBox.addActionListener(new ActionListener() {
-// public void actionPerformed(ActionEvent e) {
-// all = allBox.isSelected();
-// }
-// });
-// allBox.setSelected(all);
-// panel.add(allBox);
- charsetButton = new JButton("Characters...");
- charsetButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- //showCharacterList();
- charSelector.setVisible(true);
- }
- });
- panel.add(charsetButton);
-
- pain.add(panel);
-
- JPanel filestuff = new JPanel();
- filestuff.add(new JLabel("Filename:"));
- filestuff.add(filenameField = new JTextField(20));
- filestuff.add(new JLabel(".vlw"));
- pain.add(filestuff);
-
- JPanel buttons = new JPanel();
- JButton cancelButton = new JButton("Cancel");
- cancelButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- setVisible(false);
- }
- });
- okButton = new JButton("OK");
- okButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- build();
- }
- });
- okButton.setEnabled(false);
-
- buttons.add(cancelButton);
- buttons.add(okButton);
- pain.add(buttons);
-
- JRootPane root = getRootPane();
- root.setDefaultButton(okButton);
- ActionListener disposer = new ActionListener() {
- public void actionPerformed(ActionEvent actionEvent) {
- setVisible(false);
- }
- };
- Base.registerWindowCloseKeys(root, disposer);
- Base.setIcon(this);
-
- setResizable(false);
- pack();
-
- // do this after pack so it doesn't affect layout
- sample.setFont(new Font(list[0], Font.PLAIN, 48));
-
- fontSelector.setSelectedIndex(0);
-
- Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
- windowSize = getSize();
-
- setLocation((screen.width - windowSize.width) / 2,
- (screen.height - windowSize.height) / 2);
-
- // create this behind the scenes
- charSelector = new CharacterSelector();
- }
-
-
- public void run() {
- setVisible(true);
- }
-
-
- public void update() {
- int fontsize = 0;
- try {
- fontsize = Integer.parseInt(sizeSelector.getText().trim());
- //System.out.println("'" + sizeSelector.getText() + "'");
- } catch (NumberFormatException e2) { }
-
- // if a deselect occurred, selection will be -1
- if ((fontsize > 0) && (fontsize < 256) && (selection != -1)) {
- //font = new Font(list[selection], Font.PLAIN, fontsize);
- Font instance = (Font) table.get(list[selection]);
- font = instance.deriveFont(Font.PLAIN, fontsize);
- //System.out.println("setting font to " + font);
- sample.setFont(font);
-
- String filenameSuggestion = list[selection].replace(' ', '_');
- filenameSuggestion += "-" + fontsize;
- filenameField.setText(filenameSuggestion);
- }
- }
-
-
- public void build() {
- int fontsize = 0;
- try {
- fontsize = Integer.parseInt(sizeSelector.getText().trim());
- } catch (NumberFormatException e) { }
-
- if (fontsize <= 0) {
- JOptionPane.showMessageDialog(this, "Bad font size, try again.",
- "Badness", JOptionPane.WARNING_MESSAGE);
- return;
- }
-
- String filename = filenameField.getText().trim();
- if (filename.length() == 0) {
- JOptionPane.showMessageDialog(this, "Enter a file name for the font.",
- "Lameness", JOptionPane.WARNING_MESSAGE);
- return;
- }
- if (!filename.endsWith(".vlw")) {
- filename += ".vlw";
- }
-
- // Please implement me properly. The schematic is below, but not debugged.
- // http://dev.processing.org/bugs/show_bug.cgi?id=1464
-
-// final String filename2 = filename;
-// final int fontsize2 = fontsize;
-// SwingUtilities.invokeLater(new Runnable() {
-// public void run() {
- try {
- Font instance = (Font) table.get(list[selection]);
- font = instance.deriveFont(Font.PLAIN, fontsize);
- //PFont f = new PFont(font, smooth, all ? null : PFont.CHARSET);
- PFont f = new PFont(font, smooth, charSelector.getCharacters());
-
-// PFont f = new PFont(font, smooth, null);
-// char[] charset = charSelector.getCharacters();
-// ProgressMonitor progressMonitor = new ProgressMonitor(CreateFont.this,
-// "Creating font", "", 0, charset.length);
-// progressMonitor.setProgress(0);
-// for (int i = 0; i < charset.length; i++) {
-// System.out.println(charset[i]);
-// f.index(charset[i]); // load this char
-// progressMonitor.setProgress(i+1);
-// }
-
- // make sure the 'data' folder exists
- File folder = editor.getSketch().prepareDataFolder();
- f.save(new FileOutputStream(new File(folder, filename)));
-
- } catch (IOException e) {
- JOptionPane.showMessageDialog(CreateFont.this,
- "An error occurred while creating font.",
- "No font for you",
- JOptionPane.WARNING_MESSAGE);
- e.printStackTrace();
- }
-// }
-// });
-
- setVisible(false);
- }
-
-
- /**
- * make the window vertically resizable
- */
- public Dimension getMaximumSize() {
- return new Dimension(windowSize.width, 2000);
-}
-
-
- public Dimension getMinimumSize() {
- return windowSize;
- }
-
-
- /*
- public void show(File targetFolder) {
- this.targetFolder = targetFolder;
- show();
- }
- */
-}
-
-
-/**
- * Component that draws the sample text. This is its own subclassed component
- * because Mac OS X controls seem to reset the RenderingHints for smoothing
- * so that they cannot be overridden properly for JLabel or JTextArea.
- * @author fry
- */
-class SampleComponent extends JComponent {
- // see http://rinkworks.com/words/pangrams.shtml
- String text =
- "Forsaking monastic tradition, twelve jovial friars gave up their " +
- "vocation for a questionable existence on the flying trapeze.";
- int high = 80;
-
- CreateFont parent;
-
- public SampleComponent(CreateFont p) {
- this.parent = p;
-
- // and yet, we still need an inner class to handle the basics.
- // or no, maybe i'll refactor this as a separate class!
- // maybe a few getters and setters? mmm?
- addMouseListener(new MouseAdapter() {
- public void mousePressed(MouseEvent e) {
- String input =
- (String) JOptionPane.showInputDialog(parent,
- "Enter new sample text:",
- "Sample Text",
- JOptionPane.PLAIN_MESSAGE,
- null, // icon
- null, // choices
- text);
- if (input != null) {
- text = input;
- parent.repaint();
- }
- }
- });
- }
-
- public void paintComponent(Graphics g) {
-// System.out.println("smoothing set to " + smooth);
- Graphics2D g2 = (Graphics2D) g;
- g2.setColor(Color.WHITE);
- Dimension dim = getSize();
- g2.fillRect(0, 0, dim.width, dim.height);
- g2.setColor(Color.BLACK);
-
- g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
- parent.smooth ?
- RenderingHints.VALUE_TEXT_ANTIALIAS_ON :
- RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
- // add this one as well (after 1.0.9)
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
- parent.smooth ?
- RenderingHints.VALUE_ANTIALIAS_ON :
- RenderingHints.VALUE_ANTIALIAS_OFF);
- //super.paintComponent(g2);
- Font font = getFont();
- int ascent = g2.getFontMetrics().getAscent();
-// System.out.println(f.getName());
- g2.setFont(font);
- g2.drawString(text, 5, dim.height - (dim.height - ascent) / 2);
- }
-
- public Dimension getPreferredSize() {
- return new Dimension(400, high);
- }
-
- public Dimension getMaximumSize() {
- return new Dimension(10000, high);
- }
-
- public Dimension getMinimumSize() {
- return new Dimension(100, high);
- }
-}
-
-
-/**
- * Frame for selecting which characters will be included with the font.
- */
-class CharacterSelector extends JFrame {
- JRadioButton defaultCharsButton;
- JRadioButton allCharsButton;
- JRadioButton unicodeCharsButton;
- JScrollPane unicodeBlockScroller;
- JList charsetList;
-
-
- public CharacterSelector() {
- super("Character Selector");
-
- charsetList = new CheckBoxList();
- DefaultListModel model = new DefaultListModel();
- charsetList.setModel(model);
- for (String item : blockNames) {
- model.addElement(new JCheckBox(item));
- }
-
- unicodeBlockScroller =
- new JScrollPane(charsetList,
- ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
- ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
-
- Container outer = getContentPane();
- outer.setLayout(new BorderLayout());
-
- JPanel pain = new JPanel();
- pain.setBorder(new EmptyBorder(13, 13, 13, 13));
- outer.add(pain, BorderLayout.CENTER);
-
- pain.setLayout(new BoxLayout(pain, BoxLayout.Y_AXIS));
-
- String labelText =
- "Default characters will include most bitmaps for Mac OS\n" +
- "and Windows Latin scripts. Including all characters may\n" +
- "require large amounts of memory for all of the bitmaps.\n" +
- "For greater control, you can select specific Unicode blocks.";
- JTextArea textarea = new JTextArea(labelText);
- textarea.setBorder(new EmptyBorder(13, 8, 13, 8));
- textarea.setBackground(null);
- textarea.setEditable(false);
- textarea.setHighlighter(null);
- textarea.setFont(new Font("Dialog", Font.PLAIN, 12));
- pain.add(textarea);
-
- ActionListener listener = new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- //System.out.println("action " + unicodeCharsButton.isSelected());
- //unicodeBlockScroller.setEnabled(unicodeCharsButton.isSelected());
- charsetList.setEnabled(unicodeCharsButton.isSelected());
- }
- };
- defaultCharsButton = new JRadioButton("Default Characters");
- allCharsButton = new JRadioButton("All Characters");
- unicodeCharsButton = new JRadioButton("Specific Unicode Blocks");
-
- defaultCharsButton.addActionListener(listener);
- allCharsButton.addActionListener(listener);
- unicodeCharsButton.addActionListener(listener);
-
- ButtonGroup group = new ButtonGroup();
- group.add(defaultCharsButton);
- group.add(allCharsButton);
- group.add(unicodeCharsButton);
-
- JPanel radioPanel = new JPanel();
- //radioPanel.setBackground(Color.red);
- radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
- radioPanel.add(defaultCharsButton);
- radioPanel.add(allCharsButton);
- radioPanel.add(unicodeCharsButton);
-
- JPanel rightStuff = new JPanel();
- rightStuff.setLayout(new BoxLayout(rightStuff, BoxLayout.X_AXIS));
- rightStuff.add(radioPanel);
- rightStuff.add(Box.createHorizontalGlue());
- pain.add(rightStuff);
- pain.add(Box.createVerticalStrut(13));
-
-// pain.add(radioPanel);
-
-// pain.add(defaultCharsButton);
-// pain.add(allCharsButton);
-// pain.add(unicodeCharsButton);
-
- defaultCharsButton.setSelected(true);
- charsetList.setEnabled(false);
-
- //frame.getContentPane().add(scroller);
- pain.add(unicodeBlockScroller);
- pain.add(Box.createVerticalStrut(8));
-
- JPanel buttons = new JPanel();
- JButton okButton = new JButton("OK");
- okButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- setVisible(false);
- }
- });
- okButton.setEnabled(true);
- buttons.add(okButton);
- pain.add(buttons);
-
- JRootPane root = getRootPane();
- root.setDefaultButton(okButton);
- ActionListener disposer = new ActionListener() {
- public void actionPerformed(ActionEvent actionEvent) {
- setVisible(false);
- }
- };
- Base.registerWindowCloseKeys(root, disposer);
- Base.setIcon(this);
-
- pack();
-
- Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
- Dimension windowSize = getSize();
-
- setLocation((screen.width - windowSize.width) / 2,
- (screen.height - windowSize.height) / 2);
- }
-
-
- protected char[] getCharacters() {
- if (defaultCharsButton.isSelected()) {
- return PFont.CHARSET;
- }
-
- char[] charset = new char[65536];
- if (allCharsButton.isSelected()) {
- for (int i = 0; i < 0xFFFF; i++) {
- charset[i] = (char) i;
- }
- } else {
- DefaultListModel model = (DefaultListModel) charsetList.getModel();
- int index = 0;
- for (int i = 0; i < BLOCKS.length; i++) {
- if (((JCheckBox) model.get(i)).isSelected()) {
- for (int j = blockStart[i]; j <= blockStop[i]; j++) {
- charset[index++] = (char) j;
- }
- }
- }
- charset = PApplet.subset(charset, 0, index);
- }
- //System.out.println("Creating font with " + charset.length + " characters.");
- return charset;
- }
-
-
- // http://www.unicode.org/Public/UNIDATA/Blocks.txt
- static final String[] BLOCKS = {
- "0000..007F; Basic Latin",
- "0080..00FF; Latin-1 Supplement",
- "0100..017F; Latin Extended-A",
- "0180..024F; Latin Extended-B",
- "0250..02AF; IPA Extensions",
- "02B0..02FF; Spacing Modifier Letters",
- "0300..036F; Combining Diacritical Marks",
- "0370..03FF; Greek and Coptic",
- "0400..04FF; Cyrillic",
- "0500..052F; Cyrillic Supplement",
- "0530..058F; Armenian",
- "0590..05FF; Hebrew",
- "0600..06FF; Arabic",
- "0700..074F; Syriac",
- "0750..077F; Arabic Supplement",
- "0780..07BF; Thaana",
- "07C0..07FF; NKo",
- "0800..083F; Samaritan",
- "0900..097F; Devanagari",
- "0980..09FF; Bengali",
- "0A00..0A7F; Gurmukhi",
- "0A80..0AFF; Gujarati",
- "0B00..0B7F; Oriya",
- "0B80..0BFF; Tamil",
- "0C00..0C7F; Telugu",
- "0C80..0CFF; Kannada",
- "0D00..0D7F; Malayalam",
- "0D80..0DFF; Sinhala",
- "0E00..0E7F; Thai",
- "0E80..0EFF; Lao",
- "0F00..0FFF; Tibetan",
- "1000..109F; Myanmar",
- "10A0..10FF; Georgian",
- "1100..11FF; Hangul Jamo",
- "1200..137F; Ethiopic",
- "1380..139F; Ethiopic Supplement",
- "13A0..13FF; Cherokee",
- "1400..167F; Unified Canadian Aboriginal Syllabics",
- "1680..169F; Ogham",
- "16A0..16FF; Runic",
- "1700..171F; Tagalog",
- "1720..173F; Hanunoo",
- "1740..175F; Buhid",
- "1760..177F; Tagbanwa",
- "1780..17FF; Khmer",
- "1800..18AF; Mongolian",
- "18B0..18FF; Unified Canadian Aboriginal Syllabics Extended",
- "1900..194F; Limbu",
- "1950..197F; Tai Le",
- "1980..19DF; New Tai Lue",
- "19E0..19FF; Khmer Symbols",
- "1A00..1A1F; Buginese",
- "1A20..1AAF; Tai Tham",
- "1B00..1B7F; Balinese",
- "1B80..1BBF; Sundanese",
- "1C00..1C4F; Lepcha",
- "1C50..1C7F; Ol Chiki",
- "1CD0..1CFF; Vedic Extensions",
- "1D00..1D7F; Phonetic Extensions",
- "1D80..1DBF; Phonetic Extensions Supplement",
- "1DC0..1DFF; Combining Diacritical Marks Supplement",
- "1E00..1EFF; Latin Extended Additional",
- "1F00..1FFF; Greek Extended",
- "2000..206F; General Punctuation",
- "2070..209F; Superscripts and Subscripts",
- "20A0..20CF; Currency Symbols",
- "20D0..20FF; Combining Diacritical Marks for Symbols",
- "2100..214F; Letterlike Symbols",
- "2150..218F; Number Forms",
- "2190..21FF; Arrows",
- "2200..22FF; Mathematical Operators",
- "2300..23FF; Miscellaneous Technical",
- "2400..243F; Control Pictures",
- "2440..245F; Optical Character Recognition",
- "2460..24FF; Enclosed Alphanumerics",
- "2500..257F; Box Drawing",
- "2580..259F; Block Elements",
- "25A0..25FF; Geometric Shapes",
- "2600..26FF; Miscellaneous Symbols",
- "2700..27BF; Dingbats",
- "27C0..27EF; Miscellaneous Mathematical Symbols-A",
- "27F0..27FF; Supplemental Arrows-A",
- "2800..28FF; Braille Patterns",
- "2900..297F; Supplemental Arrows-B",
- "2980..29FF; Miscellaneous Mathematical Symbols-B",
- "2A00..2AFF; Supplemental Mathematical Operators",
- "2B00..2BFF; Miscellaneous Symbols and Arrows",
- "2C00..2C5F; Glagolitic",
- "2C60..2C7F; Latin Extended-C",
- "2C80..2CFF; Coptic",
- "2D00..2D2F; Georgian Supplement",
- "2D30..2D7F; Tifinagh",
- "2D80..2DDF; Ethiopic Extended",
- "2DE0..2DFF; Cyrillic Extended-A",
- "2E00..2E7F; Supplemental Punctuation",
- "2E80..2EFF; CJK Radicals Supplement",
- "2F00..2FDF; Kangxi Radicals",
- "2FF0..2FFF; Ideographic Description Characters",
- "3000..303F; CJK Symbols and Punctuation",
- "3040..309F; Hiragana",
- "30A0..30FF; Katakana",
- "3100..312F; Bopomofo",
- "3130..318F; Hangul Compatibility Jamo",
- "3190..319F; Kanbun",
- "31A0..31BF; Bopomofo Extended",
- "31C0..31EF; CJK Strokes",
- "31F0..31FF; Katakana Phonetic Extensions",
- "3200..32FF; Enclosed CJK Letters and Months",
- "3300..33FF; CJK Compatibility",
- "3400..4DBF; CJK Unified Ideographs Extension A",
- "4DC0..4DFF; Yijing Hexagram Symbols",
- "4E00..9FFF; CJK Unified Ideographs",
- "A000..A48F; Yi Syllables",
- "A490..A4CF; Yi Radicals",
- "A4D0..A4FF; Lisu",
- "A500..A63F; Vai",
- "A640..A69F; Cyrillic Extended-B",
- "A6A0..A6FF; Bamum",
- "A700..A71F; Modifier Tone Letters",
- "A720..A7FF; Latin Extended-D",
- "A800..A82F; Syloti Nagri",
- "A830..A83F; Common Indic Number Forms",
- "A840..A87F; Phags-pa",
- "A880..A8DF; Saurashtra",
- "A8E0..A8FF; Devanagari Extended",
- "A900..A92F; Kayah Li",
- "A930..A95F; Rejang",
- "A960..A97F; Hangul Jamo Extended-A",
- "A980..A9DF; Javanese",
- "AA00..AA5F; Cham",
- "AA60..AA7F; Myanmar Extended-A",
- "AA80..AADF; Tai Viet",
- "ABC0..ABFF; Meetei Mayek",
- "AC00..D7AF; Hangul Syllables",
- "D7B0..D7FF; Hangul Jamo Extended-B",
- "D800..DB7F; High Surrogates",
- "DB80..DBFF; High Private Use Surrogates",
- "DC00..DFFF; Low Surrogates",
- "E000..F8FF; Private Use Area",
- "F900..FAFF; CJK Compatibility Ideographs",
- "FB00..FB4F; Alphabetic Presentation Forms",
- "FB50..FDFF; Arabic Presentation Forms-A",
- "FE00..FE0F; Variation Selectors",
- "FE10..FE1F; Vertical Forms",
- "FE20..FE2F; Combining Half Marks",
- "FE30..FE4F; CJK Compatibility Forms",
- "FE50..FE6F; Small Form Variants",
- "FE70..FEFF; Arabic Presentation Forms-B",
- "FF00..FFEF; Halfwidth and Fullwidth Forms",
- "FFF0..FFFF; Specials"
- };
-
- static String[] blockNames;
- static int[] blockStart;
- static int[] blockStop;
- static {
- int count = BLOCKS.length;
- blockNames = new String[count];
- blockStart = new int[count];
- blockStop = new int[count];
- for (int i = 0; i < count; i++) {
- String line = BLOCKS[i];
- blockStart[i] = PApplet.unhex(line.substring(0, 4));
- blockStop[i] = PApplet.unhex(line.substring(6, 10));
- blockNames[i] = line.substring(12);
- }
-// PApplet.println(codePointStop);
-// PApplet.println(codePoints);
- }
-}
-
-
-// Code for this CheckBoxList class found on the net, though I've lost the
-// link. If you run across the original version, please let me know so that
-// the original author can be credited properly. It was from a snippet
-// collection, but it seems to have been picked up so many places with others
-// placing their copyright on it, that I haven't been able to determine the
-// original author. [fry 20100216]
-class CheckBoxList extends JList {
- protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
-
- public CheckBoxList() {
- setCellRenderer(new CellRenderer());
-
- addMouseListener(new MouseAdapter() {
- public void mousePressed(MouseEvent e) {
- if (isEnabled()) {
- int index = locationToIndex(e.getPoint());
-
- if (index != -1) {
- JCheckBox checkbox = (JCheckBox)
- getModel().getElementAt(index);
- checkbox.setSelected(!checkbox.isSelected());
- repaint();
- }
- }
- }
- });
- setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- }
-
-
- protected class CellRenderer implements ListCellRenderer {
- public Component getListCellRendererComponent(JList list, Object value,
- int index, boolean isSelected,
- boolean cellHasFocus) {
- JCheckBox checkbox = (JCheckBox) value;
- checkbox.setBackground(isSelected ? getSelectionBackground() : getBackground());
- checkbox.setForeground(isSelected ? getSelectionForeground() : getForeground());
- //checkbox.setEnabled(isEnabled());
- checkbox.setEnabled(list.isEnabled());
- checkbox.setFont(getFont());
- checkbox.setFocusPainted(false);
- checkbox.setBorderPainted(true);
- checkbox.setBorder(isSelected ? UIManager.getBorder("List.focusCellHighlightBorder") : noFocusBorder);
- return checkbox;
- }
- }
-}
\ No newline at end of file
From e0f680be5bedeeb4e1125b808033e1f9478c4f07 Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Tue, 19 Aug 2014 11:53:44 +0200
Subject: [PATCH 19/73] Drop dependency from processing-core project.
---
app/.classpath | 1 -
app/src/processing/app/AbstractMonitor.java | 2 +-
app/src/processing/app/Base.java | 3 ++-
app/src/processing/app/Editor.java | 4 +++-
app/src/processing/app/Platform.java | 2 +-
app/src/processing/app/Preferences.java | 2 +-
app/src/processing/app/PreferencesData.java | 4 ++--
app/src/processing/app/SerialMonitor.java | 2 +-
app/src/processing/app/UpdateCheck.java | 2 +-
app/src/processing/app/debug/Compiler.java | 2 +-
app/src/processing/app/helpers/PreferencesMap.java | 4 +---
app/src/processing/app/linux/Platform.java | 2 +-
app/src/processing/app/macosx/Platform.java | 8 ++++----
app/src/processing/app/preproc/PdePreprocessor.java | 3 +--
app/src/processing/app/syntax/PdeKeywords.java | 3 ++-
app/src/processing/app/tools/AutoFormat.java | 2 +-
app/src/processing/app/tools/DiscourseFormat.java | 2 +-
app/src/processing/app/windows/Platform.java | 6 ++++--
18 files changed, 28 insertions(+), 26 deletions(-)
diff --git a/app/.classpath b/app/.classpath
index 32030b38e57..a37f05e66de 100644
--- a/app/.classpath
+++ b/app/.classpath
@@ -5,7 +5,6 @@
-
diff --git a/app/src/processing/app/AbstractMonitor.java b/app/src/processing/app/AbstractMonitor.java
index 9a3de6043b3..027601c5780 100644
--- a/app/src/processing/app/AbstractMonitor.java
+++ b/app/src/processing/app/AbstractMonitor.java
@@ -1,7 +1,7 @@
package processing.app;
import processing.app.debug.MessageConsumer;
-import processing.core.PApplet;
+import processing.app.legacy.PApplet;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
diff --git a/app/src/processing/app/Base.java b/app/src/processing/app/Base.java
index 2821625528a..574b8a4fac9 100644
--- a/app/src/processing/app/Base.java
+++ b/app/src/processing/app/Base.java
@@ -46,11 +46,12 @@
import processing.app.helpers.filefilters.OnlyDirs;
import processing.app.helpers.filefilters.OnlyFilesWithExtension;
import processing.app.javax.swing.filechooser.FileNameExtensionFilter;
+import processing.app.legacy.PApplet;
+import processing.app.legacy.PConstants;
import processing.app.packages.Library;
import processing.app.packages.LibraryList;
import processing.app.tools.MenuScroller;
import processing.app.tools.ZipDeflater;
-import processing.core.*;
import static processing.app.I18n._;
diff --git a/app/src/processing/app/Editor.java b/app/src/processing/app/Editor.java
index 35cfc45532a..0a9280063c7 100644
--- a/app/src/processing/app/Editor.java
+++ b/app/src/processing/app/Editor.java
@@ -23,13 +23,15 @@
package processing.app;
import cc.arduino.packages.UploaderAndMonitorFactory;
+
import com.jcraft.jsch.JSchException;
+
import processing.app.debug.*;
import processing.app.forms.PasswordAuthorizationDialog;
import processing.app.helpers.PreferencesMapException;
+import processing.app.legacy.PApplet;
import processing.app.syntax.*;
import processing.app.tools.*;
-import processing.core.*;
import static processing.app.I18n._;
import java.awt.*;
diff --git a/app/src/processing/app/Platform.java b/app/src/processing/app/Platform.java
index 59ce7f8819e..bf0f8ddd5db 100644
--- a/app/src/processing/app/Platform.java
+++ b/app/src/processing/app/Platform.java
@@ -35,7 +35,7 @@
import processing.app.debug.TargetBoard;
import processing.app.debug.TargetPackage;
import processing.app.debug.TargetPlatform;
-import processing.core.PConstants;
+import processing.app.legacy.PConstants;
/**
diff --git a/app/src/processing/app/Preferences.java b/app/src/processing/app/Preferences.java
index 46008c962f6..5b07f693398 100644
--- a/app/src/processing/app/Preferences.java
+++ b/app/src/processing/app/Preferences.java
@@ -52,7 +52,7 @@
import processing.app.helpers.FileUtils;
import processing.app.helpers.PreferencesHelper;
import processing.app.helpers.PreferencesMap;
-import processing.core.PApplet;
+import processing.app.legacy.PApplet;
/**
diff --git a/app/src/processing/app/PreferencesData.java b/app/src/processing/app/PreferencesData.java
index 2b4af0118dd..52e3ad87dc3 100644
--- a/app/src/processing/app/PreferencesData.java
+++ b/app/src/processing/app/PreferencesData.java
@@ -12,8 +12,8 @@
import java.util.MissingResourceException;
import processing.app.helpers.PreferencesMap;
-import processing.core.PApplet;
-import processing.core.PConstants;
+import processing.app.legacy.PApplet;
+import processing.app.legacy.PConstants;
public class PreferencesData {
diff --git a/app/src/processing/app/SerialMonitor.java b/app/src/processing/app/SerialMonitor.java
index 0be575ed262..67e90d5bbed 100644
--- a/app/src/processing/app/SerialMonitor.java
+++ b/app/src/processing/app/SerialMonitor.java
@@ -19,7 +19,7 @@
package processing.app;
import cc.arduino.packages.BoardPort;
-import processing.core.PApplet;
+import processing.app.legacy.PApplet;
import java.awt.*;
import java.awt.event.ActionEvent;
diff --git a/app/src/processing/app/UpdateCheck.java b/app/src/processing/app/UpdateCheck.java
index 21db25b5ce0..0e94366e92a 100644
--- a/app/src/processing/app/UpdateCheck.java
+++ b/app/src/processing/app/UpdateCheck.java
@@ -31,7 +31,7 @@
import javax.swing.JOptionPane;
-import processing.core.PApplet;
+import processing.app.legacy.PApplet;
import static processing.app.I18n._;
diff --git a/app/src/processing/app/debug/Compiler.java b/app/src/processing/app/debug/Compiler.java
index 232b5ac7ccb..1f7540e9c1b 100644
--- a/app/src/processing/app/debug/Compiler.java
+++ b/app/src/processing/app/debug/Compiler.java
@@ -49,7 +49,7 @@
import processing.app.packages.Library;
import processing.app.packages.LibraryList;
import processing.app.preproc.PdePreprocessor;
-import processing.core.PApplet;
+import processing.app.legacy.PApplet;
public class Compiler implements MessageConsumer {
diff --git a/app/src/processing/app/helpers/PreferencesMap.java b/app/src/processing/app/helpers/PreferencesMap.java
index d374fd8507f..a48617a62c7 100644
--- a/app/src/processing/app/helpers/PreferencesMap.java
+++ b/app/src/processing/app/helpers/PreferencesMap.java
@@ -27,14 +27,12 @@
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
import java.util.Map;
-import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import processing.app.Base;
-import processing.core.PApplet;
+import processing.app.legacy.PApplet;
@SuppressWarnings("serial")
public class PreferencesMap extends LinkedHashMap {
diff --git a/app/src/processing/app/linux/Platform.java b/app/src/processing/app/linux/Platform.java
index 7f4afefd52b..3c4fa59dd0a 100644
--- a/app/src/processing/app/linux/Platform.java
+++ b/app/src/processing/app/linux/Platform.java
@@ -27,7 +27,7 @@
import processing.app.Preferences;
import processing.app.debug.TargetPackage;
import processing.app.tools.ExternalProcessExecutor;
-import processing.core.PConstants;
+import processing.app.legacy.PConstants;
import java.io.*;
import java.util.Map;
diff --git a/app/src/processing/app/macosx/Platform.java b/app/src/processing/app/macosx/Platform.java
index 7bbe749846d..1d1a2305afd 100644
--- a/app/src/processing/app/macosx/Platform.java
+++ b/app/src/processing/app/macosx/Platform.java
@@ -28,8 +28,8 @@
import processing.app.Base;
import processing.app.debug.TargetPackage;
import processing.app.tools.ExternalProcessExecutor;
-import processing.core.PApplet;
-import processing.core.PConstants;
+import processing.app.legacy.PApplet;
+import processing.app.legacy.PConstants;
import javax.swing.*;
import java.awt.*;
@@ -129,7 +129,7 @@ public void openURL(String url) throws Exception {
} else {
// Assume this is a file instead, and just open it.
// Extension of http://dev.processing.org/bugs/show_bug.cgi?id=1010
- processing.core.PApplet.open(url);
+ PApplet.open(url);
}
} else {
try {
@@ -162,7 +162,7 @@ public boolean openFolderAvailable() {
public void openFolder(File file) throws Exception {
//openURL(file.getAbsolutePath()); // handles char replacement, etc
- processing.core.PApplet.open(file.getAbsolutePath());
+ PApplet.open(file.getAbsolutePath());
}
diff --git a/app/src/processing/app/preproc/PdePreprocessor.java b/app/src/processing/app/preproc/PdePreprocessor.java
index e468cfd281d..576f7468b9d 100644
--- a/app/src/processing/app/preproc/PdePreprocessor.java
+++ b/app/src/processing/app/preproc/PdePreprocessor.java
@@ -31,11 +31,10 @@ Processing version Copyright (c) 2004-05 Ben Fry and Casey Reas
import static processing.app.I18n._;
import processing.app.*;
-import processing.core.*;
+import processing.app.legacy.PApplet;
import java.io.*;
import java.util.*;
-
import java.util.regex.*;
diff --git a/app/src/processing/app/syntax/PdeKeywords.java b/app/src/processing/app/syntax/PdeKeywords.java
index d8e48f8e87d..ccf52531cfd 100644
--- a/app/src/processing/app/syntax/PdeKeywords.java
+++ b/app/src/processing/app/syntax/PdeKeywords.java
@@ -25,6 +25,7 @@
package processing.app.syntax;
import processing.app.*;
+import processing.app.legacy.PApplet;
import processing.app.packages.Library;
import java.io.*;
@@ -84,7 +85,7 @@ static private void getKeywords(InputStream input) throws Exception {
// in case there's any garbage on the line
//if (line.trim().length() == 0) continue;
- String pieces[] = processing.core.PApplet.split(line, '\t');
+ String pieces[] = PApplet.split(line, '\t');
if (pieces.length >= 2) {
//int tab = line.indexOf('\t');
// any line with no tab is ignored
diff --git a/app/src/processing/app/tools/AutoFormat.java b/app/src/processing/app/tools/AutoFormat.java
index 8cad91385a9..c2c109c061a 100644
--- a/app/src/processing/app/tools/AutoFormat.java
+++ b/app/src/processing/app/tools/AutoFormat.java
@@ -25,7 +25,7 @@ Bug fixes Copyright (c) 2005-09 Ben Fry and Casey Reas
package processing.app.tools;
import processing.app.*;
-import processing.core.PApplet;
+import processing.app.legacy.PApplet;
import static processing.app.I18n._;
import java.io.*;
diff --git a/app/src/processing/app/tools/DiscourseFormat.java b/app/src/processing/app/tools/DiscourseFormat.java
index ab5ef22fc89..a4a381c5a22 100644
--- a/app/src/processing/app/tools/DiscourseFormat.java
+++ b/app/src/processing/app/tools/DiscourseFormat.java
@@ -29,7 +29,7 @@
import processing.app.*;
import processing.app.syntax.*;
-import processing.core.PApplet;
+import processing.app.legacy.PApplet;
/**
* Format for Discourse Tool
diff --git a/app/src/processing/app/windows/Platform.java b/app/src/processing/app/windows/Platform.java
index e340da4176e..6d4653d9462 100644
--- a/app/src/processing/app/windows/Platform.java
+++ b/app/src/processing/app/windows/Platform.java
@@ -24,15 +24,17 @@
import com.sun.jna.Library;
import com.sun.jna.Native;
+
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.Executor;
+
import processing.app.Base;
import processing.app.Preferences;
import processing.app.debug.TargetPackage;
+import processing.app.legacy.PApplet;
+import processing.app.legacy.PConstants;
import processing.app.tools.ExternalProcessExecutor;
import processing.app.windows.Registry.REGISTRY_ROOT_KEY;
-import processing.core.PApplet;
-import processing.core.PConstants;
import java.io.ByteArrayOutputStream;
import java.io.File;
From 50f89d9665d554c97f3fa6bd424bb3e8f183eefb Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Tue, 19 Aug 2014 16:48:34 +0200
Subject: [PATCH 20/73] Refactored OS detection subroutine.
Moved from Base into a specific utility class OSUtils.
Removed unused platform constants.
---
.../packages/uploaders/SerialUploader.java | 3 +-
app/src/processing/app/Base.java | 89 +++----------------
app/src/processing/app/Editor.java | 9 +-
app/src/processing/app/EditorConsole.java | 4 +-
app/src/processing/app/EditorHeader.java | 5 +-
app/src/processing/app/EditorLineStatus.java | 5 +-
app/src/processing/app/EditorStatus.java | 8 +-
app/src/processing/app/FindReplace.java | 9 +-
app/src/processing/app/Preferences.java | 3 +-
app/src/processing/app/Sketch.java | 4 +-
app/src/processing/app/helpers/OSUtils.java | 29 ++++++
.../app/helpers/PreferencesMap.java | 7 +-
.../processing/app/helpers/ProcessUtils.java | 4 +-
.../app/syntax/PdeTextAreaDefaults.java | 5 +-
14 files changed, 82 insertions(+), 102 deletions(-)
create mode 100644 app/src/processing/app/helpers/OSUtils.java
diff --git a/app/src/cc/arduino/packages/uploaders/SerialUploader.java b/app/src/cc/arduino/packages/uploaders/SerialUploader.java
index 059fc587006..f216ec3a372 100644
--- a/app/src/cc/arduino/packages/uploaders/SerialUploader.java
+++ b/app/src/cc/arduino/packages/uploaders/SerialUploader.java
@@ -39,6 +39,7 @@
import processing.app.SerialException;
import processing.app.debug.RunnerException;
import processing.app.debug.TargetPlatform;
+import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesMap;
import processing.app.helpers.StringReplacer;
import cc.arduino.packages.Uploader;
@@ -188,7 +189,7 @@ private String waitForUploadPort(String uploadPort, List before) throws
// come back, so use a longer time out before assuming that the
// selected
// port is the bootloader (not the sketch).
- if (((!Base.isWindows() && elapsed >= 500) || elapsed >= 5000) && now.contains(uploadPort)) {
+ if (((!OSUtils.isWindows() && elapsed >= 500) || elapsed >= 5000) && now.contains(uploadPort)) {
if (verbose)
System.out.println("Uploading using selected port: " + uploadPort);
return uploadPort;
diff --git a/app/src/processing/app/Base.java b/app/src/processing/app/Base.java
index 574b8a4fac9..e8715dbb5d4 100644
--- a/app/src/processing/app/Base.java
+++ b/app/src/processing/app/Base.java
@@ -42,12 +42,12 @@
import processing.app.debug.TargetPlatform;
import processing.app.debug.TargetPlatformException;
import processing.app.helpers.FileUtils;
+import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesMap;
import processing.app.helpers.filefilters.OnlyDirs;
import processing.app.helpers.filefilters.OnlyFilesWithExtension;
import processing.app.javax.swing.filechooser.FileNameExtensionFilter;
import processing.app.legacy.PApplet;
-import processing.app.legacy.PConstants;
import processing.app.packages.Library;
import processing.app.packages.LibraryList;
import processing.app.tools.MenuScroller;
@@ -68,19 +68,6 @@ public class Base {
/** Set true if this a proper release rather than a numbered revision. */
static public boolean RELEASE = false;
- static Map platformNames = new HashMap();
- static {
- platformNames.put(PConstants.WINDOWS, "windows");
- platformNames.put(PConstants.MACOSX, "macosx");
- platformNames.put(PConstants.LINUX, "linux");
- }
-
- static HashMap platformIndices = new HashMap();
- static {
- platformIndices.put("windows", PConstants.WINDOWS);
- platformIndices.put("macosx", PConstants.MACOSX);
- platformIndices.put("linux", PConstants.LINUX);
- }
static Platform platform;
private static DiscoveryManager discoveryManager = new DiscoveryManager();
@@ -263,11 +250,11 @@ static protected boolean isCommandLine() {
static protected void initPlatform() {
try {
Class> platformClass = Class.forName("processing.app.Platform");
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
platformClass = Class.forName("processing.app.macosx.Platform");
- } else if (Base.isWindows()) {
+ } else if (OSUtils.isWindows()) {
platformClass = Class.forName("processing.app.windows.Platform");
- } else if (Base.isLinux()) {
+ } else if (OSUtils.isLinux()) {
platformClass = Class.forName("processing.app.linux.Platform");
}
platform = (Platform) platformClass.newInstance();
@@ -473,7 +460,7 @@ public Base(String[] args) throws Exception {
// being passed in with 8.3 syntax, which makes the sketch loader code
// unhappy, since the sketch folder naming doesn't match up correctly.
// http://dev.processing.org/bugs/show_bug.cgi?id=1089
- if (isWindows()) {
+ if (OSUtils.isWindows()) {
try {
file = file.getCanonicalFile();
} catch (IOException e) {
@@ -1087,7 +1074,7 @@ public boolean handleClose(Editor editor) {
// untitled sketch, just give up and let the user quit.
// if (Preferences.getBoolean("sketchbook.closing_last_window_quits") ||
// (editor.untitled && !editor.getSketch().isModified())) {
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
Object[] options = { "OK", "Cancel" };
String prompt =
_(" " +
@@ -1170,7 +1157,7 @@ public boolean handleQuit() {
// Save out the current prefs state
Preferences.save();
- if (!Base.isMacOS()) {
+ if (!OSUtils.isMacOS()) {
// If this was fired from the menu or an AppleEvent (the Finder),
// then Mac OS X will send the terminate signal itself.
System.exit(0);
@@ -1996,54 +1983,6 @@ static public String getPlatformName() {
}
- /**
- * Map a platform constant to its name.
- * @param which PConstants.WINDOWS, PConstants.MACOSX, PConstants.LINUX
- * @return one of "windows", "macosx", or "linux"
- */
- static public String getPlatformName(int which) {
- return platformNames.get(which);
- }
-
-
- static public int getPlatformIndex(String what) {
- Integer entry = platformIndices.get(what);
- return (entry == null) ? -1 : entry.intValue();
- }
-
-
- // These were changed to no longer rely on PApplet and PConstants because
- // of conflicts that could happen with older versions of core.jar, where
- // the MACOSX constant would instead read as the LINUX constant.
-
-
- /**
- * returns true if Processing is running on a Mac OS X machine.
- */
- static public boolean isMacOS() {
- //return PApplet.platform == PConstants.MACOSX;
- return System.getProperty("os.name").indexOf("Mac") != -1;
- }
-
-
- /**
- * returns true if running on windows.
- */
- static public boolean isWindows() {
- //return PApplet.platform == PConstants.WINDOWS;
- return System.getProperty("os.name").indexOf("Windows") != -1;
- }
-
-
- /**
- * true if running on linux.
- */
- static public boolean isLinux() {
- //return PApplet.platform == PConstants.LINUX;
- return System.getProperty("os.name").indexOf("Linux") != -1;
- }
-
-
// .................................................................
@@ -2176,7 +2115,7 @@ static public String getHardwarePath() {
static public String getAvrBasePath() {
String path = getHardwarePath() + File.separator + "tools" +
File.separator + "avr" + File.separator + "bin" + File.separator;
- if (Base.isLinux() && !(new File(path)).exists()) {
+ if (OSUtils.isLinux() && !(new File(path)).exists()) {
return ""; // use distribution provided avr tools if bundled tools missing
}
return path;
@@ -2411,7 +2350,7 @@ static public File selectFolder(String prompt, File folder, Frame frame) {
static public void setIcon(Frame frame) {
// don't use the low-res icon on Mac OS X; the window should
// already have the right icon from the .app file.
- if (Base.isMacOS()) return;
+ if (OSUtils.isMacOS()) return;
Image image = Toolkit.getDefaultToolkit().createImage(PApplet.ICON_IMAGE);
frame.setIconImage(image);
@@ -2464,9 +2403,9 @@ static public void showReference(String filename) {
}
static public void showGettingStarted() {
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
Base.showReference(_("Guide_MacOSX.html"));
- } else if (Base.isWindows()) {
+ } else if (OSUtils.isWindows()) {
Base.showReference(_("Guide_Windows.html"));
} else {
Base.openURL(_("http://www.arduino.cc/playground/Learning/Linux"));
@@ -2570,7 +2509,7 @@ static public void showError(String title, String message, Throwable e, int exit
// incomplete
static public int showYesNoCancelQuestion(Editor editor, String title,
String primary, String secondary) {
- if (!Base.isMacOS()) {
+ if (!OSUtils.isMacOS()) {
int result =
JOptionPane.showConfirmDialog(null, primary + "\n" + secondary, title,
JOptionPane.YES_NO_CANCEL_OPTION,
@@ -2646,7 +2585,7 @@ static public int showYesNoCancelQuestion(Editor editor, String title,
static public int showYesNoQuestion(Frame editor, String title,
String primary, String secondary) {
- if (!Base.isMacOS()) {
+ if (!OSUtils.isMacOS()) {
return JOptionPane.showConfirmDialog(editor,
"" +
"" + primary + "" +
@@ -2730,7 +2669,7 @@ static public File getContentFile(String name) {
String path = System.getProperty("user.dir");
// Get a path to somewhere inside the .app folder
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
// javaroot
// $JAVAROOT
String javaroot = System.getProperty("javaroot");
diff --git a/app/src/processing/app/Editor.java b/app/src/processing/app/Editor.java
index 0a9280063c7..b449820dcd4 100644
--- a/app/src/processing/app/Editor.java
+++ b/app/src/processing/app/Editor.java
@@ -28,6 +28,7 @@
import processing.app.debug.*;
import processing.app.forms.PasswordAuthorizationDialog;
+import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesMapException;
import processing.app.legacy.PApplet;
import processing.app.syntax.*;
@@ -591,7 +592,7 @@ public void actionPerformed(ActionEvent e) {
fileMenu.add(item);
// macosx already has its own preferences and quit menu
- if (!Base.isMacOS()) {
+ if (!OSUtils.isMacOS()) {
fileMenu.addSeparator();
item = newJMenuItem(_("Preferences"), ',');
@@ -1110,7 +1111,7 @@ public void actionPerformed(ActionEvent e) {
menu.add(item);
// macosx already has its own about menu
- if (!Base.isMacOS()) {
+ if (!OSUtils.isMacOS()) {
menu.addSeparator();
item = new JMenuItem(_("About Arduino"));
item.addActionListener(new ActionListener() {
@@ -1135,7 +1136,7 @@ protected JMenu buildEditMenu() {
undoItem.addActionListener(undoAction = new UndoAction());
menu.add(undoItem);
- if (!Base.isMacOS()) {
+ if (!OSUtils.isMacOS()) {
redoItem = newJMenuItem(_("Redo"), 'Y');
} else {
redoItem = newJMenuItemShift(_("Redo"), 'Z');
@@ -2031,7 +2032,7 @@ protected boolean checkModified() {
String prompt = I18n.format(_("Save changes to \"{0}\"? "), sketch.getName());
- if (!Base.isMacOS()) {
+ if (!OSUtils.isMacOS()) {
int result =
JOptionPane.showConfirmDialog(this, prompt, _("Close"),
JOptionPane.YES_NO_CANCEL_OPTION,
diff --git a/app/src/processing/app/EditorConsole.java b/app/src/processing/app/EditorConsole.java
index 93d8eaf9deb..6ee8e86c87a 100644
--- a/app/src/processing/app/EditorConsole.java
+++ b/app/src/processing/app/EditorConsole.java
@@ -40,6 +40,8 @@
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
+import processing.app.helpers.OSUtils;
+
/**
* Message console that sits below the editing area.
@@ -118,7 +120,7 @@ public EditorConsole(Editor _editor) {
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
setBorder(null);
}
diff --git a/app/src/processing/app/EditorHeader.java b/app/src/processing/app/EditorHeader.java
index 0efd8668567..ba96382a55f 100644
--- a/app/src/processing/app/EditorHeader.java
+++ b/app/src/processing/app/EditorHeader.java
@@ -22,6 +22,7 @@
*/
package processing.app;
+import processing.app.helpers.OSUtils;
import processing.app.tools.MenuScroller;
import static processing.app.I18n._;
@@ -381,7 +382,7 @@ public Dimension getPreferredSize() {
public Dimension getMinimumSize() {
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
return new Dimension(300, Preferences.GRID_SIZE);
}
return new Dimension(300, Preferences.GRID_SIZE - 1);
@@ -389,7 +390,7 @@ public Dimension getMinimumSize() {
public Dimension getMaximumSize() {
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
return new Dimension(3000, Preferences.GRID_SIZE);
}
return new Dimension(3000, Preferences.GRID_SIZE - 1);
diff --git a/app/src/processing/app/EditorLineStatus.java b/app/src/processing/app/EditorLineStatus.java
index e29fa0c2d38..2ef4e8edbca 100644
--- a/app/src/processing/app/EditorLineStatus.java
+++ b/app/src/processing/app/EditorLineStatus.java
@@ -22,6 +22,7 @@
package processing.app;
+import processing.app.helpers.OSUtils;
import processing.app.syntax.*;
import java.awt.*;
@@ -61,7 +62,7 @@ public EditorLineStatus(JEditTextArea textarea) {
foreground = Theme.getColor("linestatus.color");
high = Theme.getInteger("linestatus.height");
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
resize = Base.getThemeImage("resize.gif", this);
}
//linestatus.bgcolor = #000000
@@ -118,7 +119,7 @@ public void paintComponent(Graphics g) {
g.drawString(tmp, size.width - (int) bounds.getWidth() -20 , baseline);
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
g.drawImage(resize, size.width - 20, 0, this);
}
}
diff --git a/app/src/processing/app/EditorStatus.java b/app/src/processing/app/EditorStatus.java
index e09b5b0f975..7cb4b1ee1a2 100644
--- a/app/src/processing/app/EditorStatus.java
+++ b/app/src/processing/app/EditorStatus.java
@@ -25,9 +25,13 @@
import java.awt.*;
import java.awt.event.*;
+
import javax.swing.*;
+import processing.app.helpers.OSUtils;
+
import java.awt.datatransfer.*;
+
import static processing.app.I18n._;
@@ -331,7 +335,7 @@ public void actionPerformed(ActionEvent e) {
// !@#(* aqua ui #($*(( that turtle-neck wearing #(** (#$@)(
// os9 seems to work if bg of component is set, but x still a bastard
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
//yesButton.setBackground(bgcolor[EDIT]);
//noButton.setBackground(bgcolor[EDIT]);
cancelButton.setBackground(bgcolor[EDIT]);
@@ -444,7 +448,7 @@ public void keyTyped(KeyEvent event) {
progressBar = new JProgressBar(JScrollBar.HORIZONTAL);
progressBar.setIndeterminate(false);
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
//progressBar.setBackground(bgcolor[PROGRESS]);
//progressBar.putClientProperty("JProgressBar.style", "circular");
}
diff --git a/app/src/processing/app/FindReplace.java b/app/src/processing/app/FindReplace.java
index 66bbb5a229a..26e7a754920 100644
--- a/app/src/processing/app/FindReplace.java
+++ b/app/src/processing/app/FindReplace.java
@@ -26,8 +26,11 @@
import java.awt.*;
import java.awt.event.*;
+
import javax.swing.*;
+import processing.app.helpers.OSUtils;
+
/**
* Find & Replace window for the Processing editor.
@@ -47,7 +50,7 @@
@SuppressWarnings("serial")
public class FindReplace extends JFrame implements ActionListener {
- static final int EDGE = Base.isMacOS() ? 20 : 13;
+ static final int EDGE = OSUtils.isMacOS() ? 20 : 13;
static final int SMALL = 6;
static final int BUTTONGAP = 12; // 12 is correct for Mac, other numbers may be required for other platofrms
@@ -143,7 +146,7 @@ public void actionPerformed(ActionEvent e) {
buttons.setLayout(new FlowLayout(FlowLayout.CENTER, BUTTONGAP, 0));
// ordering is different on mac versus pc
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
buttons.add(replaceAllButton = new JButton(_("Replace All")));
buttons.add(replaceButton = new JButton(_("Replace")));
buttons.add(replaceFindButton = new JButton(_("Replace & Find")));
@@ -161,7 +164,7 @@ public void actionPerformed(ActionEvent e) {
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
buttons.setBorder(null);
}
diff --git a/app/src/processing/app/Preferences.java b/app/src/processing/app/Preferences.java
index 5b07f693398..e6c6925680a 100644
--- a/app/src/processing/app/Preferences.java
+++ b/app/src/processing/app/Preferences.java
@@ -50,6 +50,7 @@
import javax.swing.KeyStroke;
import processing.app.helpers.FileUtils;
+import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesHelper;
import processing.app.helpers.PreferencesMap;
import processing.app.legacy.PApplet;
@@ -405,7 +406,7 @@ public void actionPerformed(ActionEvent e) {
// [ ] Automatically associate .pde files with Processing
- if (Base.isWindows()) {
+ if (OSUtils.isWindows()) {
autoAssociateBox =
new JCheckBox(_("Automatically associate .ino files with Arduino"));
pain.add(autoAssociateBox);
diff --git a/app/src/processing/app/Sketch.java b/app/src/processing/app/Sketch.java
index b9e93e67785..aa1d375e459 100644
--- a/app/src/processing/app/Sketch.java
+++ b/app/src/processing/app/Sketch.java
@@ -25,12 +25,12 @@
import cc.arduino.packages.BoardPort;
import cc.arduino.packages.UploaderAndMonitorFactory;
-
import cc.arduino.packages.Uploader;
import processing.app.debug.*;
import processing.app.debug.Compiler;
import processing.app.debug.Compiler.ProgressListener;
import processing.app.forms.PasswordAuthorizationDialog;
+import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesMap;
import processing.app.helpers.FileUtils;
import processing.app.packages.Library;
@@ -529,7 +529,7 @@ protected void calcModified() {
}
editor.header.repaint();
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
// http://developer.apple.com/qa/qa2001/qa1146.html
Object modifiedParam = modified ? Boolean.TRUE : Boolean.FALSE;
editor.getRootPane().putClientProperty("windowModified", modifiedParam);
diff --git a/app/src/processing/app/helpers/OSUtils.java b/app/src/processing/app/helpers/OSUtils.java
new file mode 100644
index 00000000000..5efb77e29b3
--- /dev/null
+++ b/app/src/processing/app/helpers/OSUtils.java
@@ -0,0 +1,29 @@
+package processing.app.helpers;
+
+public class OSUtils {
+
+ /**
+ * returns true if running on windows.
+ */
+ static public boolean isWindows() {
+ //return PApplet.platform == PConstants.WINDOWS;
+ return System.getProperty("os.name").indexOf("Windows") != -1;
+ }
+
+ /**
+ * true if running on linux.
+ */
+ static public boolean isLinux() {
+ //return PApplet.platform == PConstants.LINUX;
+ return System.getProperty("os.name").indexOf("Linux") != -1;
+ }
+
+ /**
+ * returns true if Processing is running on a Mac OS X machine.
+ */
+ static public boolean isMacOS() {
+ //return PApplet.platform == PConstants.MACOSX;
+ return System.getProperty("os.name").indexOf("Mac") != -1;
+ }
+
+}
diff --git a/app/src/processing/app/helpers/PreferencesMap.java b/app/src/processing/app/helpers/PreferencesMap.java
index a48617a62c7..b40b8c97a59 100644
--- a/app/src/processing/app/helpers/PreferencesMap.java
+++ b/app/src/processing/app/helpers/PreferencesMap.java
@@ -31,7 +31,6 @@
import java.util.SortedSet;
import java.util.TreeSet;
-import processing.app.Base;
import processing.app.legacy.PApplet;
@SuppressWarnings("serial")
@@ -105,9 +104,9 @@ public void load(InputStream input) throws IOException {
String key = line.substring(0, equals).trim();
String value = line.substring(equals + 1).trim();
- key = processPlatformSuffix(key, ".linux", Base.isLinux());
- key = processPlatformSuffix(key, ".windows", Base.isWindows());
- key = processPlatformSuffix(key, ".macosx", Base.isMacOS());
+ key = processPlatformSuffix(key, ".linux", OSUtils.isLinux());
+ key = processPlatformSuffix(key, ".windows", OSUtils.isWindows());
+ key = processPlatformSuffix(key, ".macosx", OSUtils.isMacOS());
if (key != null)
put(key, value);
diff --git a/app/src/processing/app/helpers/ProcessUtils.java b/app/src/processing/app/helpers/ProcessUtils.java
index d378f991d4b..1fb74cc7994 100644
--- a/app/src/processing/app/helpers/ProcessUtils.java
+++ b/app/src/processing/app/helpers/ProcessUtils.java
@@ -1,7 +1,5 @@
package processing.app.helpers;
-import processing.app.Base;
-
import java.io.IOException;
import java.util.Map;
@@ -9,7 +7,7 @@ public class ProcessUtils {
public static Process exec(String[] command) throws IOException {
// No problems on linux and mac
- if (!Base.isWindows()) {
+ if (!OSUtils.isWindows()) {
return Runtime.getRuntime().exec(command);
}
diff --git a/app/src/processing/app/syntax/PdeTextAreaDefaults.java b/app/src/processing/app/syntax/PdeTextAreaDefaults.java
index 382c69aaff8..2ff65afa8bc 100644
--- a/app/src/processing/app/syntax/PdeTextAreaDefaults.java
+++ b/app/src/processing/app/syntax/PdeTextAreaDefaults.java
@@ -25,6 +25,7 @@
package processing.app.syntax;
import processing.app.*;
+import processing.app.helpers.OSUtils;
public class PdeTextAreaDefaults extends TextAreaDefaults {
@@ -35,7 +36,7 @@ public PdeTextAreaDefaults() {
//inputHandler.addDefaultKeyBindings(); // 0122
// use option on mac for text edit controls that are ctrl on windows/linux
- String mod = Base.isMacOS() ? "A" : "C";
+ String mod = OSUtils.isMacOS() ? "A" : "C";
// right now, ctrl-up/down is select up/down, but mod should be
// used instead, because the mac expects it to be option(alt)
@@ -94,7 +95,7 @@ public PdeTextAreaDefaults() {
inputHandler.addKeyBinding("CS+END", InputHandler.SELECT_DOC_END);
}
- if (Base.isMacOS()) {
+ if (OSUtils.isMacOS()) {
inputHandler.addKeyBinding("M+LEFT", InputHandler.HOME);
inputHandler.addKeyBinding("M+RIGHT", InputHandler.END);
inputHandler.addKeyBinding("MS+LEFT", InputHandler.SELECT_HOME); // 0122
From be96ae3a6a3c3ffb0667eae0d8fc444c3c20f64f Mon Sep 17 00:00:00 2001
From: Cristian Maglie
Date: Wed, 24 Sep 2014 11:36:02 +0200
Subject: [PATCH 21/73] Removed no more used 'core' project
---
app/build.xml | 5 -
build/build.xml | 3 -
build/macosx/template.app/Contents/Info.plist | 2 +-
build/windows/launcher/config.xml | 1 -
build/windows/launcher/config_debug.xml | 1 -
core/.classpath | 6 -
core/.project | 17 -
core/.settings/org.eclipse.jdt.core.prefs | 271 -
core/.settings/org.eclipse.jdt.ui.prefs | 5 -
core/api.txt | 413 -
core/build.xml | 26 -
core/done.txt | 3009 -----
core/license.txt | 456 -
core/make.sh | 7 -
core/methods/.classpath | 7 -
core/methods/.project | 17 -
core/methods/build.xml | 28 -
core/methods/demo/PApplet.java | 9483 --------------
core/methods/demo/PGraphics.java | 5075 --------
core/methods/demo/PImage.java | 2862 -----
core/methods/methods.jar | Bin 3725 -> 0 bytes
core/methods/src/PAppletMethods.java | 272 -
core/preproc.pl | 186 -
core/preproc/.classpath | 7 -
core/preproc/.project | 17 -
core/preproc/build.xml | 22 -
core/preproc/demo/PApplet.java | 8155 -------------
core/preproc/demo/PGraphics.java | 5043 --------
core/preproc/demo/PImage.java | 2713 ----
core/preproc/preproc.jar | Bin 3943 -> 0 bytes
.../src/processing/build/PAppletMethods.java | 236 -
core/src/processing/core/PApplet.java | 10184 ----------------
core/src/processing/core/PConstants.java | 504 -
core/src/processing/core/PFont.java | 877 --
core/src/processing/core/PGraphics.java | 5707 ---------
core/src/processing/core/PGraphics2D.java | 2144 ----
core/src/processing/core/PGraphics3D.java | 4379 -------
core/src/processing/core/PGraphicsJava2D.java | 1847 ---
core/src/processing/core/PImage.java | 2862 -----
core/src/processing/core/PLine.java | 1278 --
core/src/processing/core/PMatrix.java | 150 -
core/src/processing/core/PMatrix2D.java | 450 -
core/src/processing/core/PMatrix3D.java | 782 --
core/src/processing/core/PPolygon.java | 701 --
core/src/processing/core/PShape.java | 955 --
core/src/processing/core/PShapeSVG.java | 1473 ---
core/src/processing/core/PSmoothTriangle.java | 968 --
core/src/processing/core/PStyle.java | 61 -
core/src/processing/core/PTriangle.java | 3850 ------
core/src/processing/core/PVector.java | 565 -
core/src/processing/xml/CDATAReader.java | 193 -
core/src/processing/xml/ContentReader.java | 212 -
core/src/processing/xml/PIReader.java | 157 -
core/src/processing/xml/StdXMLBuilder.java | 356 -
core/src/processing/xml/StdXMLParser.java | 684 --
core/src/processing/xml/StdXMLReader.java | 626 -
core/src/processing/xml/XMLAttribute.java | 153 -
core/src/processing/xml/XMLElement.java | 1418 ---
.../src/processing/xml/XMLEntityResolver.java | 173 -
core/src/processing/xml/XMLException.java | 286 -
.../src/processing/xml/XMLParseException.java | 69 -
core/src/processing/xml/XMLUtil.java | 758 --
.../xml/XMLValidationException.java | 190 -
core/src/processing/xml/XMLValidator.java | 631 -
core/src/processing/xml/XMLWriter.java | 307 -
core/todo.txt | 782 --
66 files changed, 1 insertion(+), 85076 deletions(-)
delete mode 100644 core/.classpath
delete mode 100644 core/.project
delete mode 100644 core/.settings/org.eclipse.jdt.core.prefs
delete mode 100644 core/.settings/org.eclipse.jdt.ui.prefs
delete mode 100644 core/api.txt
delete mode 100644 core/build.xml
delete mode 100644 core/done.txt
delete mode 100644 core/license.txt
delete mode 100755 core/make.sh
delete mode 100644 core/methods/.classpath
delete mode 100644 core/methods/.project
delete mode 100644 core/methods/build.xml
delete mode 100644 core/methods/demo/PApplet.java
delete mode 100644 core/methods/demo/PGraphics.java
delete mode 100644 core/methods/demo/PImage.java
delete mode 100644 core/methods/methods.jar
delete mode 100644 core/methods/src/PAppletMethods.java
delete mode 100755 core/preproc.pl
delete mode 100644 core/preproc/.classpath
delete mode 100644 core/preproc/.project
delete mode 100644 core/preproc/build.xml
delete mode 100644 core/preproc/demo/PApplet.java
delete mode 100644 core/preproc/demo/PGraphics.java
delete mode 100644 core/preproc/demo/PImage.java
delete mode 100644 core/preproc/preproc.jar
delete mode 100644 core/preproc/src/processing/build/PAppletMethods.java
delete mode 100644 core/src/processing/core/PApplet.java
delete mode 100644 core/src/processing/core/PConstants.java
delete mode 100644 core/src/processing/core/PFont.java
delete mode 100644 core/src/processing/core/PGraphics.java
delete mode 100644 core/src/processing/core/PGraphics2D.java
delete mode 100644 core/src/processing/core/PGraphics3D.java
delete mode 100644 core/src/processing/core/PGraphicsJava2D.java
delete mode 100644 core/src/processing/core/PImage.java
delete mode 100644 core/src/processing/core/PLine.java
delete mode 100644 core/src/processing/core/PMatrix.java
delete mode 100644 core/src/processing/core/PMatrix2D.java
delete mode 100644 core/src/processing/core/PMatrix3D.java
delete mode 100644 core/src/processing/core/PPolygon.java
delete mode 100644 core/src/processing/core/PShape.java
delete mode 100644 core/src/processing/core/PShapeSVG.java
delete mode 100644 core/src/processing/core/PSmoothTriangle.java
delete mode 100644 core/src/processing/core/PStyle.java
delete mode 100644 core/src/processing/core/PTriangle.java
delete mode 100644 core/src/processing/core/PVector.java
delete mode 100644 core/src/processing/xml/CDATAReader.java
delete mode 100644 core/src/processing/xml/ContentReader.java
delete mode 100644 core/src/processing/xml/PIReader.java
delete mode 100644 core/src/processing/xml/StdXMLBuilder.java
delete mode 100644 core/src/processing/xml/StdXMLParser.java
delete mode 100644 core/src/processing/xml/StdXMLReader.java
delete mode 100644 core/src/processing/xml/XMLAttribute.java
delete mode 100644 core/src/processing/xml/XMLElement.java
delete mode 100644 core/src/processing/xml/XMLEntityResolver.java
delete mode 100644 core/src/processing/xml/XMLException.java
delete mode 100644 core/src/processing/xml/XMLParseException.java
delete mode 100644 core/src/processing/xml/XMLUtil.java
delete mode 100644 core/src/processing/xml/XMLValidationException.java
delete mode 100644 core/src/processing/xml/XMLValidator.java
delete mode 100644 core/src/processing/xml/XMLWriter.java
delete mode 100644 core/todo.txt
diff --git a/app/build.xml b/app/build.xml
index 5b41f02636d..0fbcfeea22f 100644
--- a/app/build.xml
+++ b/app/build.xml
@@ -24,11 +24,6 @@
-
-
-
-
-
-
@@ -84,12 +83,10 @@
-
-
diff --git a/build/macosx/template.app/Contents/Info.plist b/build/macosx/template.app/Contents/Info.plist
index 73267a3b83d..fe985281f29 100755
--- a/build/macosx/template.app/Contents/Info.plist
+++ b/build/macosx/template.app/Contents/Info.plist
@@ -94,7 +94,7 @@
- $JAVAROOT/pde.jar:$JAVAROOT/core.jar:$JAVAROOT/antlr.jar:$JAVAROOT/apple.jar:$JAVAROOT/ecj.jar:$JAVAROOT/registry.jar:$JAVAROOT/quaqua.jar:$JAVAROOT/jssc-2.8.0.jar:$JAVAROOT/commons-codec-1.7.jar:$JAVAROOT/commons-exec-1.1.jar:$JAVAROOT/commons-httpclient-3.1.jar:$JAVAROOT/commons-logging-1.0.4.jar:$JAVAROOT/jmdns-3.4.1.jar:$JAVAROOT/jsch-0.1.50.jar:$JAVAROOT/jna.jar
+ $JAVAROOT/pde.jar:$JAVAROOT/antlr.jar:$JAVAROOT/apple.jar:$JAVAROOT/ecj.jar:$JAVAROOT/registry.jar:$JAVAROOT/quaqua.jar:$JAVAROOT/jssc-2.8.0.jar:$JAVAROOT/commons-codec-1.7.jar:$JAVAROOT/commons-exec-1.1.jar:$JAVAROOT/commons-httpclient-3.1.jar:$JAVAROOT/commons-logging-1.0.4.jar:$JAVAROOT/jmdns-3.4.1.jar:$JAVAROOT/jsch-0.1.50.jar:$JAVAROOT/jna.jarJVMArchs
diff --git a/build/windows/launcher/config.xml b/build/windows/launcher/config.xml
index bb19308dd42..dbce4974b4c 100644
--- a/build/windows/launcher/config.xml
+++ b/build/windows/launcher/config.xml
@@ -16,7 +16,6 @@
processing.app.Baselib/pde.jar
- lib/core.jarlib/jna.jarlib/ecj.jarlib/jssc-2.8.0.jar
diff --git a/build/windows/launcher/config_debug.xml b/build/windows/launcher/config_debug.xml
index d2366827d99..2d1daea26d5 100644
--- a/build/windows/launcher/config_debug.xml
+++ b/build/windows/launcher/config_debug.xml
@@ -16,7 +16,6 @@
processing.app.Baselib/pde.jar
- lib/core.jarlib/jna.jarlib/ecj.jarlib/jssc-2.8.0.jar
diff --git a/core/.classpath b/core/.classpath
deleted file mode 100644
index fb5011632c0..00000000000
--- a/core/.classpath
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
diff --git a/core/.project b/core/.project
deleted file mode 100644
index e791e6fcde9..00000000000
--- a/core/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
- processing-core
-
-
-
-
-
- org.eclipse.jdt.core.javabuilder
-
-
-
-
-
- org.eclipse.jdt.core.javanature
-
-
diff --git a/core/.settings/org.eclipse.jdt.core.prefs b/core/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index d01f908ca29..00000000000
--- a/core/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,271 +0,0 @@
-#Sat Dec 31 13:42:35 CET 2011
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.5
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.5
-org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
-org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
-org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16
-org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=18
-org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=18
-org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16
-org.eclipse.jdt.core.formatter.alignment_for_assignment=0
-org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
-org.eclipse.jdt.core.formatter.alignment_for_compact_if=16
-org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80
-org.eclipse.jdt.core.formatter.alignment_for_enum_constants=16
-org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16
-org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16
-org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=18
-org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=18
-org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16
-org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16
-org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16
-org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16
-org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16
-org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16
-org.eclipse.jdt.core.formatter.blank_lines_after_imports=1
-org.eclipse.jdt.core.formatter.blank_lines_after_package=1
-org.eclipse.jdt.core.formatter.blank_lines_before_field=0
-org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0
-org.eclipse.jdt.core.formatter.blank_lines_before_imports=1
-org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1
-org.eclipse.jdt.core.formatter.blank_lines_before_method=1
-org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1
-org.eclipse.jdt.core.formatter.blank_lines_before_package=0
-org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1
-org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1
-org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line
-org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false
-org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false
-org.eclipse.jdt.core.formatter.comment.format_block_comments=true
-org.eclipse.jdt.core.formatter.comment.format_header=false
-org.eclipse.jdt.core.formatter.comment.format_html=true
-org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true
-org.eclipse.jdt.core.formatter.comment.format_line_comments=true
-org.eclipse.jdt.core.formatter.comment.format_source_code=true
-org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true
-org.eclipse.jdt.core.formatter.comment.indent_root_tags=true
-org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert
-org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert
-org.eclipse.jdt.core.formatter.comment.line_length=80
-org.eclipse.jdt.core.formatter.compact_else_if=true
-org.eclipse.jdt.core.formatter.continuation_indentation=2
-org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2
-org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false
-org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true
-org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true
-org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true
-org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true
-org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true
-org.eclipse.jdt.core.formatter.indent_empty_lines=false
-org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true
-org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true
-org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
-org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false
-org.eclipse.jdt.core.formatter.indentation.size=4
-org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert
-org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert
-org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert
-org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert
-org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert
-org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert
-org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert
-org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert
-org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert
-org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert
-org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert
-org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert
-org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert
-org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert
-org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert
-org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert
-org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert
-org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert
-org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert
-org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert
-org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert
-org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert
-org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert
-org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert
-org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert
-org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert
-org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
-org.eclipse.jdt.core.formatter.join_lines_in_comments=true
-org.eclipse.jdt.core.formatter.join_wrapped_lines=true
-org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false
-org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false
-org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false
-org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false
-org.eclipse.jdt.core.formatter.lineSplit=80
-org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false
-org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false
-org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
-org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1
-org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
-org.eclipse.jdt.core.formatter.tabulation.char=space
-org.eclipse.jdt.core.formatter.tabulation.size=2
-org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false
-org.eclipse.jdt.core.formatter.wrap_before_binary_operator=false
diff --git a/core/.settings/org.eclipse.jdt.ui.prefs b/core/.settings/org.eclipse.jdt.ui.prefs
deleted file mode 100644
index 7834a86e6b6..00000000000
--- a/core/.settings/org.eclipse.jdt.ui.prefs
+++ /dev/null
@@ -1,5 +0,0 @@
-#Fri Dec 30 18:14:57 CET 2011
-eclipse.preferences.version=1
-formatter_profile=_Arduino
-formatter_settings_version=11
-org.eclipse.jdt.ui.text.custom_code_templates=
diff --git a/core/api.txt b/core/api.txt
deleted file mode 100644
index 4b2746f8bb6..00000000000
--- a/core/api.txt
+++ /dev/null
@@ -1,413 +0,0 @@
-
- public void setParent(PApplet parent)
- public void setPrimary(boolean primary)
- public void setPath(String path)
- public void setSize(int iwidth, int iheight)
- protected void allocate()
- public void dispose()
-
- public boolean canDraw()
- public void beginDraw()
- public void endDraw()
-
- protected void checkSettings()
- protected void defaultSettings()
- protected void reapplySettings()
-
- public void hint(int which)
-
- public void beginShape()
- public void beginShape(int kind)
- public void edge(boolean e)
- public void normal(float nx, float ny, float nz)
- public void textureMode(int mode)
- public void texture(PImage image)
- public void vertex(float x, float y)
- public void vertex(float x, float y, float z)
- public void vertex(float x, float y, float u, float v)
- public void vertex(float x, float y, float z, float u, float v)
- protected void vertexTexture(float u, float v);
- public void breakShape()
- public void endShape()
- public void endShape(int mode)
-
- protected void bezierVertexCheck();
- 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)
-
- protected void curveVertexCheck();
- public void curveVertex(float x, float y)
- public void curveVertex(float x, float y, float z)
- protected void curveVertexSegment(float x1, float y1,
- float x2, float y2,
- float x3, float y3,
- float x4, float y4)
- protected void curveVertexSegment(float x1, float y1, float z1,
- float x2, float y2, float z2,
- float x3, float y3, float z3,
- float x4, float y4, float z4)
-
- protected void renderPoints(int start, int stop) // P3D
- protected void rawPoints(int start, int stop) // P3D
-
- protected void renderLines(int start, int stop) // P3D
- protected void rawLines(int start, int stop) // P3D
-
- protected void renderTriangles(int start, int stop) // P3D
- protected void rawTriangles(int start, int stop) // P3D
-
- public void flush()
- protected void render()
- proected void sort()
-
- 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)
-
- 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)
-
- 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)
-
- 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)
-
- public void box(float size)
- public void box(float w, float h, float d)
-
- public void sphereDetail(int res)
- public void sphereDetail(int ures, int vres)
- public void sphere(float r)
-
- 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)
- protected void bezierInitCheck()
- protected void bezierInit()
- 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)
-
- 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)
- protected void curveInitCheck()
- protected void curveInit()
- 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)
-
- protected void splineForward(int segments, PMatrix3D matrix)
-
- public void smooth()
- public void noSmooth()
-
- 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)
-
- 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)
-
- public void textAlign(int align)
- public void textAlign(int alignX, int alignY)
- public float textAscent()
- public float textDescent()
- public void textFont(PFont which)
- public void textFont(PFont which, float size)
- public void textLeading(float leading)
- public void textMode(int mode)
- protected boolean textModeCheck(int mode)
- public void textSize(float size)
- public float textWidth(char c)
- public float textWidth(String str)
- protected float textWidthImpl(char buffer[], int start, int stop)
-
- public void text(char c)
- public void text(char c, float x, float y)
- public void text(char c, float x, float y, float z)
- public void text(String str)
- public void text(String str, float x, float y)
- public void text(String str, float x, float y, float z)
- public void text(String str, float x1, float y1, float x2, float y2)
- public void text(String s, float x1, float y1, float x2, float y2, float z)
- public void text(int num, float x, float y)
- public void text(int num, float x, float y, float z)
- public void text(float num, float x, float y)
- public void text(float num, float x, float y, float z)
-
- protected void textLineAlignImpl(char buffer[], int start, int stop,
- float x, float y)
- protected void textLineImpl(char buffer[], int start, int stop,
- float x, float y)
- protected void textCharImpl(char ch, float x, float y)
- protected void textCharModelImpl(PImage glyph,
- float x1, float y1, //float z1,
- float x2, float y2, //float z2,
- int u2, int v2)
- protected void textCharScreenImpl(PImage glyph,
- int xx, int yy,
- int w0, int h0)
-
- public void pushMatrix()
- public void popMatrix()
-
- public void translate(float tx, float ty)
- public void translate(float tx, float ty, float tz)
- public void rotate(float angle)
- public void rotateX(float angle)
- public void rotateY(float angle)
- public void rotateZ(float angle)
- public void rotate(float angle, float vx, float vy, float vz)
- public void scale(float s)
- public void scale(float sx, float sy)
- public void scale(float x, float y, float z)
-
- public void resetMatrix()
- public void applyMatrix(PMatrix2D source)
- public void applyMatrix(float n00, float n01, float n02,
- float n10, float n11, float n12)
- public void applyMatrix(PMatrix3D source)
- 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)
-
- public getMatrix(PMatrix2D target)
- public getMatrix(PMatrix3D target)
- public void setMatrix(PMatrix2D source)
- public void setMatrix(PMatrix3D source)
- public void printMatrix()
-
- public void beginCamera()
- public void endCamera()
- public void camera()
- public void camera(float eyeX, float eyeY, float eyeZ,
- float centerX, float centerY, float centerZ,
- float upX, float upY, float upZ)
- public void printCamera()
-
- public void ortho()
- public void ortho(float left, float right,
- float bottom, float top,
- float near, float far)
- public void perspective()
- public void perspective(float fov, float aspect, float near, float far)
- public void frustum(float left, float right,
- float bottom, float top,
- float near, float far)
- public void printProjection()
-
- public float screenX(float x, float y)
- public float screenY(float x, float y)
- public float screenX(float x, float y, float z)
- public float screenY(float x, float y, float z)
- public float screenZ(float x, float y, float z)
- public float modelX(float x, float y, float z)
- public float modelY(float x, float y, float z)
- public float modelZ(float x, float y, float z)
-
- public void pushStyle()
- public void popStyle()
- public void style(PStyle)
- public PStyle getStyle()
- public void getStyle(PStyle)
-
- public void strokeCap(int cap)
- public void strokeJoin(int join)
- public void strokeWeight(float weight)
-
- public void noStroke()
- public void stroke(int rgb)
- public void stroke(int rgb, float alpha)
- public void stroke(float gray)
- public void stroke(float gray, float alpha)
- public void stroke(float x, float y, float z)
- public void stroke(float x, float y, float z, float a)
- protected void strokeFromCalc()
-
- public void noTint()
- public void tint(int rgb)
- public void tint(int rgb, float alpha)
- public void tint(float gray)
- public void tint(float gray, float alpha)
- public void tint(float x, float y, float z)
- public void tint(float x, float y, float z, float a)
- protected void tintFromCalc()
-
- public void noFill()
- public void fill(int rgb)
- public void fill(int rgb, float alpha)
- public void fill(float gray)
- public void fill(float gray, float alpha)
- public void fill(float x, float y, float z)
- public void fill(float x, float y, float z, float a)
- protected void fillFromCalc()
-
- public void ambient(int rgb)
- public void ambient(float gray)
- public void ambient(float x, float y, float z)
- protected void ambientFromCalc()
- public void specular(int rgb)
- public void specular(float gray)
- public void specular(float x, float y, float z)
- protected void specularFromCalc()
- public void shininess(float shine)
- public void emissive(int rgb)
- public void emissive(float gray)
- public void emissive(float x, float y, float z )
- protected void emissiveFromCalc()
-
- public void lights()
- public void noLights()
- public void ambientLight(float red, float green, float blue)
- public void ambientLight(float red, float green, float blue,
- float x, float y, float z)
- public void directionalLight(float red, float green, float blue,
- float nx, float ny, float nz)
- public void pointLight(float red, float green, float blue,
- float x, float y, float 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)
- public void lightFalloff(float constant, float linear, float quadratic)
- public void lightSpecular(float x, float y, float z)
- protected void lightPosition(int num, float x, float y, float z)
- protected void lightDirection(int num, float x, float y, float z)
-
- public void background(int rgb)
- public void background(int rgb, float alpha)
- public void background(float gray)
- public void background(float gray, float alpha)
- public void background(float x, float y, float z)
- public void background(float x, float y, float z, float a)
- public void background(PImage image)
- protected void backgroundFromCalc()
- protected void backgroundImpl(PImage image)
- protected void backgroundImpl()
-
- public void colorMode(int mode)
- public void colorMode(int mode, float max)
- public void colorMode(int mode, float maxX, float maxY, float maxZ)
- public void colorMode(int mode, float maxX, float maxY, float maxZ, float maxA)
-
- protected void colorCalc(int rgb)
- protected void colorCalc(int rgb, float alpha)
- protected void colorCalc(float gray)
- protected void colorCalc(float gray, float alpha)
- protected void colorCalc(float x, float y, float z)
- protected void colorCalc(float x, float y, float z, float a)
- protected void colorCalcARGB(int argb, float alpha)
-
- public final int color(int gray)
- public final int color(int gray, int alpha)
- public final int color(int rgb, float alpha)
- public final int color(int x, int y, int z)
-
- public final float alpha(int what)
- public final float red(int what)
- public final float green(int what)
- public final float blue(int what)
- public final float hue(int what)
- public final float saturation(int what)
- public final float brightness(int what)
-
- public int lerpColor(int c1, int c2, float amt)
- static public int lerpColor(int c1, int c2, float amt, int mode)
-
- public void beginRaw(PGraphics rawGraphics)
- public void endRaw()
-
- static public void showWarning(String msg)
- static public void showException(String msg)
-
- public boolean displayable()
- public boolean is2D()
- public boolean is3D()
-
-//
-
-These are the methods found in PImage, which are inherited by PGraphics.
-
- public PImage(Image)
- public Image getImage()
-
- public void setCache(Object parent, Object storage)
- public void getCache(Object parent)
- public void removeCache(Object parent)
-
- public boolean isModified();
- public void setModified();
- public void setModified(boolean state);
-
- public void loadPixels()
- public void updatePixels()
- public void updatePixels(int x, int y, int w, int h)
-
- public void resize(int wide, int high)
-
- public int get(int x, int y)
- public PImage get(int x, int y, int w, int h)
- protected PImage getImpl(int x, int y, int w, int h)
- public PImage get()
- public void set(int x, int y, int c)
- public void set(int x, int y, PImage src)
- protected void setImpl(int dx, int dy, int sx, int sy, int sw, int sh,
- PImage src)
-
- public void mask(int alpha[])
- public void mask(PImage alpha)
-
- public void filter(int kind)
- public void filter(int kind, float param)
-
- public void copy(int sx, int sy, int sw, int sh,
- int dx, int dy, int dw, int dh)
- public void copy(PImage src,
- int sx, int sy, int sw, int sh,
- int dx, int dy, int dw, int dh)
-
- static public int blendColor(int c1, int c2, int mode)
- public void blend(int sx, int sy, int sw, int sh,
- int dx, int dy, int dw, int dh, int mode)
- public void blend(PImage src,
- int sx, int sy, int sw, int sh,
- int dx, int dy, int dw, int dh, int mode)
-
- public void save(String path)
diff --git a/core/build.xml b/core/build.xml
deleted file mode 100644
index 1798a55c1c3..00000000000
--- a/core/build.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/core/done.txt b/core/done.txt
deleted file mode 100644
index e09233a1509..00000000000
--- a/core/done.txt
+++ /dev/null
@@ -1,3009 +0,0 @@
-0178 core (private)
-X filter(DILATE/ERODE)
-X dilate(boolean) has bug in clamping of top kernel coordinate
-X http://dev.processing.org/bugs/show_bug.cgi?id=1477
-X deprecated 'screen', adding screenW and screenH
-X write implementation for get/set methods inside PImage (w/o pixels[])
-
-
-0177 core (private)
-X no changes
-
-
-0176 core (private)
-X opengl sketches run at 30fps in present mode on OS X
-o still having problems w/ full screen non-FSEM
-X http://dev.processing.org/bugs/show_bug.cgi?id=1425
-X PFont not working well with lots of characters
-X only create bitmap chars on the fly when needed (in createFont)
-X Implement better caching mechanism when creating large fonts
-X http://dev.processing.org/bugs/show_bug.cgi?id=1111
-X fix problem with "create font" still showing anti-aliased text
-X don't make fonts power of 2
-X PGraphics3D: beginDraw does not release old textures
-X http://dev.processing.org/bugs/show_bug.cgi?id=1423
-X fix from taifun_browser
-X removing camera() and perspective() from setSize() trashes resize
-X probably regression b/c camera/perspective can't be called then
-X http://dev.processing.org/bugs/show_bug.cgi?id=1391
-
-
-0175 core (private)
-X changed createInputRaw() to only bother checking URLs if : present
-
-
-0174 core (private)
-X svg paths that use 'e' (exponent) not handled properly
-X http://dev.processing.org/bugs/show_bug.cgi?id=1408
-
-
-0173 core (private)
-X Re-enabled hack for temporary clipping.
-X Clipping still needs to be implemented properly, however. Please help!
-X http://dev.processing.org/bugs/show_bug.cgi?id=1393
-
-
-0172 core (private)
-X no changes to the core (or were there?)
-
-
-0171 core (1.0.9)
-X Blurred PImages in OPENGL sketches
-X removed NPOT texture support (for further testing)
-X http://dev.processing.org/bugs/show_bug.cgi?id=1352
-
-
-0170 core (1.0.8)
-X added some min/max functions that work with doubles
-X not sure if those are staying in or not
-X filter(RGB) supposed to be filter(OPAQUE)
-X http://dev.processing.org/bugs/show_bug.cgi?id=1346
-X implement non-power-of-2 textures
-X fix get() when used with save() in OpenGL mode
-X immediately update projection with OpenGL
-X in the past, projection updates required a new frame
-X also prevents camera/project from being reset with setSize() (regression?)
-X which was a problem anyway because it made GL calls outside draw()
-X partial fix for texture edge problems with opengl
-o http://dev.processing.org/bugs/show_bug.cgi?id=602
-X some camera problems may be coming from "cameraNear = -8" line
-X this may cause other problems with drawing/clipping however
-X opengl camera does not update on current frame (has to do a second frame)
-X remove methods from PApplet that use doubles
-
-
-0169 core (1.0.7)
-X remove major try/catch block from PApplet.main()
-X hopefully will allow some exception stuff to come through properly
-X PVector.angleDistance() returns NaN
-X http://dev.processing.org/bugs/show_bug.cgi?id=1316
-
-
-0168 core (1.0.6)
-X getImage() setting the wrong image type
-X http://dev.processing.org/bugs/show_bug.cgi?id=1282
-X strokeWeight() makes lines 2x too thick with P2D
-X http://dev.processing.org/bugs/show_bug.cgi?id=1283
-X image() doesn't work with P2D, P3D, and OPENGL with noFill()
-X http://dev.processing.org/bugs/show_bug.cgi?id=1299
-o maybe using rgb instead of tint inside drawing loops?
-X http://dev.processing.org/bugs/show_bug.cgi?id=1222
-
-
-0167 core (1.0.5)
-X changed text layout methods from private to protected
-
-
-0166 core (1.0.4)
-X disable point() going to set() from PGraphicsJava2D
-X set() doesn't honor alpha consistently
-X also causes problems with PDF
-X preliminary thread() implementation
-X double param version of map()
-X PImage cacheMap problem when using PImage.get()
-X http://dev.processing.org/bugs/show_bug.cgi?id=1245
-X problems with > 512 points and P3D/OPENGL (thx DopeShow)
-X http://dev.processing.org/bugs/show_bug.cgi?id=1255
-X imageMode(CENTER) doesn't work properly with P2D
-X http://dev.processing.org/bugs/show_bug.cgi?id=1232
-X reset matrices when using beginRecord() with PDF
-X http://dev.processing.org/bugs/show_bug.cgi?id=1227
-X resizing window distorts gl graphics
-X patch from Pablo Funes
-X http://dev.processing.org/bugs/show_bug.cgi?id=1176
-X significant point() and set() slowdown on OS X
-X http://dev.processing.org/bugs/show_bug.cgi?id=1094
-
-
-0165 core (1.0.3)
-X update to itext 2.1.4
-X endRecord or endRaw produces RuntimeException with PDF library
-X http://dev.processing.org/bugs/show_bug.cgi?id=1169
-X problem with beginRaw/endRaw and OpenGL
-X http://dev.processing.org/bugs/show_bug.cgi?id=1171
-X set strokeWeight with begin/endRaw
-X http://dev.processing.org/bugs/show_bug.cgi?id=1172
-X fix strokeWeight with P3D (better version of line hack)
-X make P3D use proper weights
-X ArrayIndexOutOfBoundsException with point()
-X http://dev.processing.org/bugs/show_bug.cgi?id=1168
-
-
-0164 core (1.0.2)
-X requestImage() causing problems with JAVA2D
-X fix minor strokeWeight bug with OpenGL
-X text() with char array
-o add documentation
-o add this for text in a rectangle?
-X minor bug fix to svg files that weren't being resized properly
-X OpenGL is rendering darker in 0149+
-X http://dev.processing.org/bugs/show_bug.cgi?id=958
-X the fix has been found, just incorporate it
-X thanks to dave bollinger
-X OutOfMemoryError with ellipse() in P3D and OPENGL
-X http://dev.processing.org/bugs/show_bug.cgi?id=1086
-X should also fix problem with AIOOBE
-X http://dev.processing.org/bugs/show_bug.cgi?id=1117
-X point(x,y) ignores noStroke() (in some renderers)
-X http://dev.processing.org/bugs/show_bug.cgi?id=1090
-X fix startup problem when scheme coloring was odd
-X http://dev.processing.org/bugs/show_bug.cgi?id=1109
-X fix several point() problems with P3D
-X http://dev.processing.org/bugs/show_bug.cgi?id=1110
-X nextPage() not working properly with PDF as the renderer
-X http://dev.processing.org/bugs/show_bug.cgi?id=1131
-X save styles when nextPage() is called
-X beginRaw() broken (no DXF, etc working)
-X http://dev.processing.org/bugs/show_bug.cgi?id=1099
-X http://dev.processing.org/bugs/show_bug.cgi?id=1144
-X Fix algorithm for quadratic to cubic curve conversion
-X wrong algorithm in PGraphicsOpenGL and PShapeSVG
-X (thanks to user 'shambles')
-X http://dev.processing.org/bugs/show_bug.cgi?id=1122
-X tint() not working in P2D
-X http://dev.processing.org/bugs/show_bug.cgi?id=1132
-X blend() y coordinates inverted when using OpenGL
-X http://dev.processing.org/bugs/show_bug.cgi?id=1137
-
-invalid/wontfix/dupe
-X Processing will not start with non-standard disk partitioning on OS X
-X http://dev.processing.org/bugs/show_bug.cgi?id=1127
-X Got NoClassDefFoundError exception when accessing quicktime API
-X http://dev.processing.org/bugs/show_bug.cgi?id=1128
-X http://dev.processing.org/bugs/show_bug.cgi?id=1129
-X http://dev.processing.org/bugs/show_bug.cgi?id=1130
-X not using present mode correctly
-X http://dev.processing.org/bugs/show_bug.cgi?id=1138
-X apparent graphics driver conflict on vista
-X http://dev.processing.org/bugs/show_bug.cgi?id=1140
-X PImage.save() does not create parent directories
-X http://dev.processing.org/bugs/show_bug.cgi?id=1124
-X sketch turning blue and not working on osx
-X http://dev.processing.org/bugs/show_bug.cgi?id=1164
-X dupe: blend() inaccurary
-X http://dev.processing.org/bugs/show_bug.cgi?id=1008
-X glPushAttrib style function
-X http://dev.processing.org/bugs/show_bug.cgi?id=1150
-X calling saveFrame() in noLoop() (update reference)
-X http://dev.processing.org/bugs/show_bug.cgi?id=1155
-
-xml
-X fix for xml elements that have null names
-X added listChildren() method
-X added optional toString(boolean) parameter to enable/disable indents
-
-
-0163 core (1.0.1)
-X do not parse split() with regexp
-X http://dev.processing.org/bugs/show_bug.cgi?id=1060
-X ArrayIndexOutOfBoundsException in ellipseImpl() with 1.0
-X http://dev.processing.org/bugs/show_bug.cgi?id=1068
-
-
-0162 core (1.0)
-X no additional changes for 1.0
-
-
-0161 core
-X present on macosx causing strange flicker/jump while window opens
-X using validate() for present mode, pack() otherwise
-X http://dev.processing.org/bugs/show_bug.cgi?id=1051
-
-
-0160 core
-X stroked lines drawing on top of everything else in P3D
-X http://dev.processing.org/bugs/show_bug.cgi?id=1032
-X 100x100 sketches not working
-
-
-0159 core
-o disable present mode? (weirdness with placements on mac)
-X deal with some present mode issues
-X use FSE on mac within the PDE
-X when exporting, never use FSE
-_ document changes re: can specify --exclusive on command line
-X do we need to do glEnable for multisample with gl?
-o just need to test this on a few platforms
-X doesn't seem to be the case
-X Present mode and OPENGL not working in 0156 with Windows Vista
-X http://dev.processing.org/bugs/show_bug.cgi?id=1009
-X Seems to be limited to Java 6u10 (but verify)
-o -Dsun.java2d.d3d=false seems to fix the problem
-o can probably add that to PApplet.main()
-X does not work
-
-
-0158 core
-X beginShape(TRIANGLE_FAN), and therefore arc(), broken in P2D
-X also a typo in the ColorWheel example
-X http://dev.processing.org/bugs/show_bug.cgi?id=1019
-X P2D - null pointer exception drawing line with alpha stroke
-X http://dev.processing.org/bugs/show_bug.cgi?id=1023
-X P2D endShape() is working like endShape(CLOSE)
-X http://dev.processing.org/bugs/show_bug.cgi?id=1021
-X http://dev.processing.org/bugs/show_bug.cgi?id=1028 (mark as dupe)
-X arc() center transparent
-X http://dev.processing.org/bugs/show_bug.cgi?id=1027
-X mark as dupe of bug #200
-X but fixed for the P2D case, still afflicts P2D
-X P2D - alpha stroke rendered at full opacity
-X http://dev.processing.org/bugs/show_bug.cgi?id=1024
-X smooth() on single line ellipses not coming out smooth
-X sort of works, just not great
-X improve (slightly) the quality of ellipse() and arc() with P2D
-X don't use TRIANGLE_FAN on ellipseImpl() and arcImpl() with P2D
-X split out ellipseImpl and arcImpl from PGraphics into P2D and P3D
-X figure out better model for adaptive sizing of circles
-X also goes for arcs, though will be weighted based on arc size
-X Bring back CENTER_RADIUS but deprecate it
-X http://dev.processing.org/bugs/show_bug.cgi?id=1035
-X enable smoothing by default in opengl
-X change hints to instead only be able to DISABLE 2X or 4X
-X bring back .width and .height fields for PShape
-o need to update the examples to reflect
-X no examples to update
-X change reference re: smoothing in opengl
-X hint(), smooth(), and size()
-X rev the version number
-
-
-0157 core
-X SVG polygon shapes not drawing since loadShape() and PShape changes
-X http://dev.processing.org/bugs/show_bug.cgi?id=1005
-X image(a, x, y) not honoring imageMode(CENTER)
-X need to just pass image(a, x, y) to image(a, x, y, a.width, a.height)
-X rather than passing it directly to imageImpl()
-X http://dev.processing.org/bugs/show_bug.cgi?id=1013
-o disable P2D before releasing (unless implementation is finished)
-
-
-0156 core
-X clarify the "no variables in size() command" rule
-X http://dev.processing.org/bugs/show_bug.cgi?id=992
-X present mode broken in general?
-X placement of elements in present mode is messed up
-X "stop" button hops around, window not centered on screen
-X http://dev.processing.org/bugs/show_bug.cgi?id=923
-X disable P2D for size() and createGraphics() before releasing
-X already was disabled, just a bug in detecting it
-
-
-0155 core
-X hint(DISABLE_DEPTH_TEST) throws null pointer exception with OpenGL
-X http://dev.processing.org/bugs/show_bug.cgi?id=984
-
-
-0154 core
-X only set apple.awt.graphics.UseQuartz on osx, otherwise security error
-X http://dev.processing.org/bugs/show_bug.cgi?id=976
-X add skewX() and skewY() to PMatrix
-X Add support style attribute for path tag to Candy SVG (ricard)
-X http://dev.processing.org/bugs/show_bug.cgi?id=771
-X remove setX/Y/Z from PVector, copy() (use get() instead), add mult/div
-X remove copy() from PVector?
-X add mult() and div() with vector inputs?
-
-
-0153 core
-X make PImage.init() public again
-
-
-0152 core
-X no changes to 0152 core
-
-
-0151 core
-X NullPointerException on curveVertex() when using more than 128 vertices
-X http://dev.processing.org/bugs/show_bug.cgi?id=952
-X Text not bounding correctly with x, y, w, h
-X http://dev.processing.org/bugs/show_bug.cgi?id=954
-o dataFolder() might be flawed b/c it's referring to contents of jar file
-o for input, better to use openStream
-X clear up the javadoc on this
-X odd-size height will make blue line across image in saveFrame()
-X http://dev.processing.org/bugs/show_bug.cgi?id=944
-X probably the pixel flipping code (and endian sorting) not happening
-X because the blue comes from the byte order flip
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=OpenGL;action=post;num=1219196429
-X ArrayIndexOutOfBoundsException in PLine
-X http://dev.processing.org/bugs/show_bug.cgi?id=246
-X http://dev.processing.org/bugs/show_bug.cgi?id=462
-X random AIOOBE with P3D and points
-X http://dev.processing.org/bugs/show_bug.cgi?id=937
-
-cleanup
-X alter bezier and curve matrices to use PMatrix
-X float array stuff is redundant with code that's in PMatrix
-X and PMatrix has to be included even w/o P3D so...
-X add texture support to begin/endRaw
-X should we do joins when alpha is turned off?
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=OpenGL;action=display;num=1210007450
-X no, because it's too processor intensive to draw a lotta ellipses
-X but added a note about it to the reference for 0151
-X strokeWeight() doesn't work in opengl or p3d
-o gl smoothing.. how to disable polygon but keep line enabled
-o or at least make a note of this?
-o leave smooth off, get the gl object, then enable line smooth
-X don't bother, this is a workaround for another bug
-o PPolygon no longer in use and PLine is a mess
-o make a version of PGraphics3 that uses it for more accurate rendering?
-
-
-0150 core
-X no changes to processing.core in 0150
-
-
-0149 core
-X remove MACOS9 constant from processing.core.*
-X because code no longer runs on os9 since dropping 1.1 support
-X specular() with alpha has been removed
-X GLDrawableFactory.chooseGraphicsConfiguration() error with OpenGL
-X http://dev.processing.org/bugs/show_bug.cgi?id=891
-X http://dev.processing.org/bugs/show_bug.cgi?id=908
-X fix problem with unregisterXxxx()
-X http://dev.processing.org/bugs/show_bug.cgi?id=910
-X make parseFloat() with String[] array return NaN for missing values
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Syntax;action=display;num=1220880375
-X fix problems with text in a rectangle
-X http://dev.processing.org/bugs/show_bug.cgi?id=893
-X http://dev.processing.org/bugs/show_bug.cgi?id=899
-X finish getImage() method inside PImage
-X delay() is broken
-X http://dev.processing.org/bugs/show_bug.cgi?id=894
-X remove extra ~ files from core.jar
-X also fix for other libraries in the make scripts across platforms
-X fix problems in PApplet regarding signed code
-X createInput() wasn't bothering to check files when not online
-X unhint() has been removed, see the reference for hint() for changes
-o enable() and disable() instead of hint()/unhint()
-o should these use text strings? how will that be compiled?
-X remove unhint(), add opposite hints for those that need to be disabled
-o maybe update hint() ref to be more clear about screen not accumulating
-X no, it's explicitly stated as such
-X make decisions about whether PGraphics is an abstract class or not
-X method signature is a real problem
-X figure out how to handle constructor mess
-X clean up setMainDrawingSurface()
-X should instead be inside size(), and init(), no?
-X add to hint(DISABLE_DEPTH_TEST)
-X gl.glClear(GL.GL_DEPTH_BUFFER_BIT);
-X or clearing the zbuffer for P3D
-X also add a note to the hint() reference
-X DISABLE_DEPTH_TEST bad results
-X have to clear the zbuffer to make it work
-X this may be specific to lines
-X http://dev.processing.org/bugs/show_bug.cgi?id=827
-X though it also seems to be a problem with opengl
-X also make a note of disabling as a way to help font appearance
-o Font width calculation fails when using vectorfonts and PDF
-o http://dev.processing.org/bugs/show_bug.cgi?id=920
-X um, this is gross: getMatrix((PMatrix2D) null)
-X no changing point sizes when using beginShape(POINTS)
-X this is an opengl restriction, should we stick with it elsewhere?
-X and changing stroke weight in general (with lines/shapes)
-o no renderer does this, we should probably disable it
-X added a note to the reference about it
-X may need to add to PApplet.main() for OS X 10.5
-X System.setProperty("apple.awt.graphics.UseQuartz", "true");
-X deprecate arraycopy(), change to arrayCopy()
-
-cleaning
-o chooseFile() and chooseFolder() with named fxn callbacks
-o the function must take a File object as a parameter
-o add better error messages for all built-in renderers
-o i.e. "import library -> pdf" when pdf is missing
-o cameraXYZ doesn't seem to actually be used for anything
-o since camera functions don't even look at it or set it
-o registerSize() in arcball is causing trouble
-o some sort of infinite loop issue
-o textMode(SCREEN) is broken for opengl
-o http://dev.processing.org/bugs/show_bug.cgi?id=426
-o textSpace(SCREEN) for opengl and java2d
-o don't use loadPixels for either
-o use font code to set the cached color of the font, then call set()
-o although set() with alpha is a little different..
-o resizing opengl applet likely to cause big trouble
-o componentlistener should prolly only do size() command outside of draw
-o fjen says blend() doens't work in JAVA2D
-o the functions are fairly well separated now in PMethods
-o just go through all the stuff to make sure it's setting properly
-
-point()
-X java2d - if strokeWeight is 1, do screenX/Y and set()
-X if strokeWeight larger, should work ok with line()
-X no, use an ellipse if strokeWeight is larger
-X gl points not working again
-X need to implement point() as actual gl points
-X this means adding points to the pipeline
-X point() doesn't work with some graphics card setups
-X particularly with opengl and java2d
-X http://dev.processing.org/bugs/show_bug.cgi?id=121
-X point() issues
-o point() being funneled through beginShape is terribly slow
-X go the other way 'round
-X sometimes broken, could be a problem with java 1.5? (was using win2k)
-
-font
-X fix getFontMetrics() warning
-X need to have a getGraphics() to get the actual Graphics object
-X where drawing is happening. parent.getGraphics() works except for OpenGL
-X Java2D textLinePlacedImpl should check for ENABLE_NATIVE_FONTS hint
-X http://dev.processing.org/bugs/show_bug.cgi?id=633
-X also try to check native font on textFont() commands
-X in case the hint() has been enabled in the meantime
-X or rather, always load native font, even w/o the hint() being set
-
-PGraphics API changes
-X setMainDrawingSurface() -> setPrimarySurface()
-X mainDrawingSurface = primarySurface;
-X resize() -> setSize() (roughly)
-X endShape() with no params is no longer 'final'
-X X/Y/Z -> TX/TY/TZ
-X MX/MY/MZ -> X/Y/Z (for sake of PShape)
-X render_triangles -> renderTriangles()
-X depth_sort_triangles -> sortTriangles()
-X render_lines -> renderLines()
-X depth_sort_lines -> sortLines()
-X no longer any abstract methods in PGraphics itself
-X removed support for specular alpha (and its 'SPA' constant)
-X clear() -> backgroundImpl()
-X add DIAMETER as synonym for CENTER for ellipseMode and friends
-X textFontNative and textFontNativeMetrics have been removed
-X they've been re-implemented per-PGraphics in a less hacky way
-X hint(ENABLE_NATIVE_FONTS) goes away
-X need to mention in createFont() reference
-X also maybe cover in the loadFont() reference? (maybe problem...)
-X image.cache has been removed, replaced with get/set/removeCache()
-X this allows per-renderer image cache data to be stored
-X imageMode has been removed from PImage, too awkward
-X this also means that imageMode ignored for get(), set(), blend() and copy()
-X smooth is now part of PGraphics, moved out of PImage
-X raw must handle points, lines, triangles, and textures
-X light position and normal are now PVector object
-X changed NORMALIZED to NORMAL for textureMode()
-
-shapes
-X maybe finish off the svg crap for this release
-X working on pshape
-X add shape() methods to PGraphics/PApplet
-X test and fix svg examples
-X revisions.txt for x/y/z/ tx/ty/tz.. other changes in api.txt
-X bring svg into main lib
-X need to straighten out 'table' object for quick object lookup
-X maybe add to all parent tables? (no, this gets enormous quickly)
-X fix svg caps/joins for opengl with svg library
-X http://dev.processing.org/bugs/show_bug.cgi?id=628
-X save/restore more of the p5 graphics drawing state
-X not setting colorMode(), strokeCap, etc.
-X ignoreStyles is broken - how to handle
-X need a whole "styles" handler
-X handle cap/join stuff by
-X if it's setting the default, no error message
-X if it's not the default, then show an error msg once
-X have a list Strings for errors called, rather than constants for all
-X that way, no need to have an error message for every friggin function
-X PMatrix now PMatrix3D (maybe not yet?)
-X change svg library reference
-
-hint/unhint/enable/disable
-X option to have renderer errors show up
-X 1) as text warnings 2) as runtime exceptions 3) never
-X add warning system for pgraphics, rather than runtime exceptions
-X keep array of warning strings, and booleans for whether they've called
-X ENABLE_DEPTH_SORT not really working for GL
-X because the zbuffer is still there, it's still calculating
-X actually, this is probably because it happens after the frame
-X so really, flush is required whenever the depth sort is called
-X need to check this--isn't this referring to DISABLE_DEPTH_TEST?
-X ENABLE_DEPTH_SORT causing trouble with MovieMaker
-X need to make the flush() api accessible
-X http://dev.processing.org/bugs/show_bug.cgi?id=692
-X image smoothing
-X straighten out default vs. ACCURATE vs. whatever
-X Java2D and P3D and OpenGL are all inconsistent
-o need to be able to do hint() to do nearest neighbor filtering
-X http://dev.processing.org/bugs/show_bug.cgi?id=685
-o imageDetail(), textDetail(), etc?
-o decisions on image smoothing vs. text smoothing vs. all
-
-
-0148 core
-X tweaks to PGraphicsOpenGL to support GLGraphics
-
-
-0147 core
-X processing sketches not restarting after switching pages in safari
-X http://dev.processing.org/bugs/show_bug.cgi?id=581
-
-cleaning
-X misshapen fonts on osx (apple fixed their bug)
-X http://dev.processing.org/bugs/show_bug.cgi?id=404
-
-
-0146 core
-X fix the internal file chooser so that people don't need to make their own
-X threading is a problem with inputFile() and inputFolder()
-X dynamically load swingworker?
-o remove saveFile() methods?
-o write up examples for these instead?
-o start an integration section?
-X get() in java2d not honoring imageMode or rectMode
-X add imageMode(CENTER) implementation
-X add a bunch of changes to the reference to support this
-X Duplicate 3d faces in beginRaw() export
-X this was actually doubling geometry, potentially a bit of a disaster
-X http://dev.processing.org/bugs/show_bug.cgi?id=737
-o bezierVertex YZ Plane fill problem
-X http://dev.processing.org/bugs/show_bug.cgi?id=752
-X weird coplanar stuff, shouldn't be doing 3D anyway
-
-cleanup
-X switch to requestImage() (done in 0145)
-o can bug 77 be fixed with a finalizer? (no, it cannot)
-X make sure that images with alpha still have alpha in current code
-X text in rectangle is drawing outside the box
-X http://dev.processing.org/bugs/show_bug.cgi?id=844
-X points missing in part of screen
-X http://dev.processing.org/bugs/show_bug.cgi?id=269
-
-
-0145 core
-X separate x/y axis on sphereDetail() params
-X http://dev.processing.org/bugs/show_bug.cgi?id=856
-X make sure docs for PImage use createImage
-X add notes about JOGLAppletLauncher
-X http://download.java.net/media/jogl/builds/nightly/javadoc_public/com/sun/opengl/util/JOGLAppletLauncher.html
-X added to javadoc
-o need a halt() method which will kill but not quit app (sets finished?)
-o exit() will actually leave the application
-o this may in fact only be internal
-X this is just the stop() method, though maybe we need to document it
-X text(String, float, float, float, float) draws text outside box
-X http://dev.processing.org/bugs/show_bug.cgi?id=844
-X implement textAlign() for y coords in text rect
-X need to add reference for this
-X textAlign() bottom now takes textDescent() into account
-X remove gzip-related hint()
-
-threading
-X major threading overhaul before 1.0 (compendium)
-X http://dev.processing.org/bugs/show_bug.cgi?id=511
-X ewjordan has added a good trace of the badness
-X need to move off anim off the main event thread
-X move away from using method like display
-X look into opengl stuff for dealing with this
-X move addListeners() calls back out of PGraphics
-X resize window will nuke font setting
-X textFont() used in setup() is null once draw() arrives
-X http://dev.processing.org/bugs/show_bug.cgi?id=726
-X colorMode() set inside setup() sometimes not set once draw() arrives
-X http://dev.processing.org/bugs/show_bug.cgi?id=767
-X applet sizing issues with external vm
-X could this possibly be related to the linux bug?
-X http://dev.processing.org/bugs/show_bug.cgi?id=430
-X alloc() stuff not fixed because of thread halting
-X problem where alloc happens inside setup(), so, uh..
-X http://dev.processing.org/bugs/show_bug.cgi?id=369
-X should instead create new buffer, and swap it in next time through
-X sonia (and anything awt) is locking up on load in rev 91
-X prolly something w/ the threading issues
-X paint is synchronized in 0091
-X however this is a necessity, otherwise nasty flickering ensues
-X and using a "glock" object seems to completely deadlock
-X http://dev.processing.org/bugs/show_bug.cgi?id=46
-o claim that things are much slower in 107 vs 92
-o http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Suggestions;action=display;num=1141763531
-X hopefully this is cleaned up by removing some of the synchronization
-X sketches lock up when system time is changed
-X http://dev.processing.org/bugs/show_bug.cgi?id=639
-X can draw() not be run on awt event thread?
-X look into opengl stuff for dealing with this
-o "is there a better way to do this" thread in lists folder
-X framerate that's reported is out of joint with actual
-X http://dev.processing.org/bugs/show_bug.cgi?id=512
-X accuracy of frame timer is incorrect
-X seems to be aliasing effect of low resolution on millis()
-X so rates coming out double or half of their actual
-X probably need to integrate over a rolling array of 10 frames or so
-X frameRate() speeds up temporarily if CPU load drops dramatically
-X http://dev.processing.org/bugs/show_bug.cgi?id=297
-o perhaps add a hint(DISABLE_FRAMERATE_DAMPER)
-X fix the flicker in java2d mode
-X http://dev.processing.org/bugs/show_bug.cgi?id=122
-X framerate(30) is still flickery and jumpy..
-X not clear what's happening here
-X appears to be much worse (unfinished drawing) on macosx
-X try turning off hw accel on the mac to see if that's the problem
-
-
-0144 core
-X if loading an image in p5 and the image is bad, no error msg shown
-X that is, if a loadImage() turns up an access denied page
-X added an error message for this, and the image width and height will be -1
-X added loadImageAsync() for threaded image loading
-
-opengl fixes
-X incorporate changes from andres colubri into PGraphicsOpenGL
-X most of the changes incorporated, something weird with constructors
-X use gluErrorString() for glError() stuff
-X PGraphicsOpenGL.java:
-X directionalLight() and .pointLight() are both calling
-X glLightNoAmbient() which then creates a new FloatBuffer
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1199376364
-
-
-0143 core
-X some fonts broken in java 1.5 on osx have changed again
-X http://dev.processing.org/bugs/show_bug.cgi?id=407
-X filed as bug #4769141 with apple http://bugreport.apple.com/
-X appears that asking for the postscript name no longer works
-o fix "create font" and associated font stuff to straighten it out
-X was grabbing the wrong native font with ico sketch
-X seems that the psname is no longer a good way to grab the font? related?
-X available font issues
-X is getFontList returning a different set of fonts from device2d?
-X try it out on java 1.3 versus 1.4
-X getAllFonts() not quite working for many fonts
-X i.e. Orator Std on windows.. macosx seems to be ok
-X is getFamilyNames() any different/better?
-X when did this break? 1.4.1? 1.4.x vs 1.3?
-X may be that cff fonts won't work?
-X or is it only those with ps names?
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1117445969
-o leading looks too big, at least in PGraphics2 with news gothic
-X though prolly the converted version of the .ttf?
-X add a fix so that negative angle values won't hork up arc() command
-X add resize() method to PImage
-
-
-0142 core
-X update iText in PDF library to 2.1.2u
-X loadStrings(".") should not list directory contents
-X http://dev.processing.org/bugs/show_bug.cgi?id=716
-
-
-0141 core
-X no changes to core in 0141
-
-
-0140 core
-X add static version of loadBytes() that reads from a File object
-X slightly clearer error messages when OpenGL stuff is missing
-
-
-0139 core
-X no changes to core in 0139
-
-
-0138 core
-X improve tessellation accuracy by using doubles internally
-X http://dev.processing.org/bugs/show_bug.cgi?id=774
-
-
-0137 core
-X add gz handling for createOutput()
-X change openStream() to createInput() (done in 0136)
-X add createOutput()
-X deprecate openStream() naming
-
-
-0136 core
-X add static version of saveStream() (uses a File and InputStream object)
-X A "noLoop()" sketch may be unresponsive to exit request
-X http://dev.processing.org/bugs/show_bug.cgi?id=694
-X Fixed bug with subset() when no length parameter was specified
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Syntax;action=display;num=1196366408
-X http://dev.processing.org/bugs/show_bug.cgi?id=707
-X figure out why tiff images won't open with after effects
-X http://dev.processing.org/bugs/show_bug.cgi?id=153
-X open with photoshop, resave, see which tags change
-X specifically, which tags that were in the original image file
-X perhaps something gets corrected?
-X had a fix, but decided not to re-implement the loadTIFF stuff too
-X fix for bezierTangent() problem from dave bollinger
-X http://dev.processing.org/bugs/show_bug.cgi?id=710
-X implement curveTangent (thanks to davbol)
-X http://dev.processing.org/bugs/show_bug.cgi?id=715
-X fix problem with get() when imageMode(CORNERS) was in use
-X fix bug with splice() and arrays
-X http://dev.processing.org/bugs/show_bug.cgi?id=734
-X 'screen' is now static
-X undo this--may need to be better about specifying screen and all
-X PImage mask doesn't work after first call
-X http://dev.processing.org/bugs/show_bug.cgi?id=744
-X load and save tga results in upside down tga
-X http://dev.processing.org/bugs/show_bug.cgi?id=742
-X fix problem with g.smooth always returning false in JAVA2D
-X http://dev.processing.org/bugs/show_bug.cgi?id=762
-X add XMLElement (not filename) constructor to SVG lib
-X http://dev.processing.org/bugs/show_bug.cgi?id=773
-
-
-0135 core
-X modelX/Y/Z still having trouble
-X http://dev.processing.org/bugs/show_bug.cgi?id=486
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Suggestions;action=display;num=1186614415
-X add docs for model/screen/Y/Z
-X added for model, along with example.
-X screen was already complete
-X bring back opengl mipmaps (create them myself? try w/ newer jogl?)
-X opengl mipmaps are leaking (regression in spite of #150 fix)
-X http://dev.processing.org/bugs/show_bug.cgi?id=610
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=OpenGL;action=display;num=1193967684
-X seems to not actually be a problem on mbp, try desktop?
-X copy() was needing updatePixels() when used with OPENGL or JAVA2D
-X http://dev.processing.org/bugs/show_bug.cgi?id=681
-X check on the bug report for this one as well
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Syntax;action=display;num=1173394373
-
-earlier
-o add notes about fixing serial on the mac to the faq (and link to bug)
-X not necessary, hopefuly things working better now
-X utf8 and encodings
-X createWriter() and createReader() that take encodings
-X xml files seem to be a lot of UTF-8
-X xml stuff
-X getItem("name");
-X getItems("name"); (same, but looks for multiple matches
-X getItem("path/to/item");
-o or could use getItem and getItemList? getItemArray()?
-o read more about xpath
-X parse xml from a string object
-X not have to just use Reader
-X add mention of this to the board
-o update to new version of jogl
-X fix mini p5 bugs for eugene
-
-
-0134 core
-X add noLights() method
-X http://dev.processing.org/bugs/show_bug.cgi?id=666
-X redraw the screen after resize events (even with noLoop)
-X http://dev.processing.org/bugs/show_bug.cgi?id=664
-o problem with transparency in mask()
-o http://dev.processing.org/bugs/show_bug.cgi?id=674
-X mark bug as invalid, using fill() instead of tint()
-X move to UTF-8 as native format for core file i/o operations
-X update reference to document the change
-o jogl glibc 2.4 problem on linux
-o move back to previous jogl until 1.1.1 is released
-X http://dev.processing.org/bugs/show_bug.cgi?id=675
-o deal with opengl applet export changes
-o what is deployment suggestion for all the different platforms?
-o can the jar files actually provide the DLLs properly?
-X revert back to jogl 1.0
-
-
-0133 core
-X fix problem with "export to application" and opengl
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=OpenGL;action=display;num=1193142573
-X add focus requests so that better chance of keys etc working
-X http://dev.processing.org/bugs/show_bug.cgi?id=645
-X argh, these make things worse (P3D run internal)
-X add stuff about classversionerrors to the reference
-X also update the libraries page
-X fix background() with P3D and beginRaw()
-X endRaw() has a problem with hint(ENABLE_DEPTH_SORT)
-X because the triangles won't be rendered by the time endRaw() is called
-X force depth sorted triangles to flush
-X is mousePressed broken with noLoop() or redraw()?
-X sort of but not really, add notes to reference about it
-
-cleaning
-o calling graphics.smooth(), graphics.colorMode() outside begin/endDraw
-o this causes everything to be reset once the draw occurs
-o kinda seems problematic and prone to errors?
-X nope, just need to say to do all commands inside begin/endDraw
-o finish implementation so 1.1 support can return
-X http://dev.processing.org/bugs/show_bug.cgi?id=125
-o check into ricard's problems with beginRecord()
-X i believe these were caused by linux java2d issues
-X beginFrame()/beginDraw() and defaults()
-X when should these be called, when not?
-X seems as though the begin/end should happen inside beginRaw/Record
-X defaults() gets called by the size() command in PApplet
-o would be cool if could sort w/o the sort class..
-o meaning use reflection to sort objects, just by implementing a few methods
-o would be much simpler and less confusing than new Sort() etc
-o or would it be ridiculously slow?
-X just using Comparator instead, since moving to Java 1.4
-X make a PException that extends RuntimeException but packages an ex?
-X http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html
-X no, not necessary, and exceptions suck
-o need to write an error if people try to use opengl with 1.3 (i.e. on export)
-o don't let users with java < 1.4 load OPENGL
-o http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Contribution_3DOpenGL;action=display;num=1114368123;start=3
-o catch security exceptions around applet i/o calls
-o not just for saving files, but provide better error msgs when
-o attempting to download from another server
-X nope, just cover this in the reference
-o files not in the data folder (works in env, not in sketch)
-X mentioned repeatedly in the docs
-o fix link() to handle relative URLs
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1081710684
-X more trouble (and bug-worthy) than it's worth
-o put SecurityException things around file i/o for applets
-o rather than checking online(), since applets might be signed
-X no, better to let errors come through
-o slow on java2d, fast on p3d
-o http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1115276250;start=3
-
-ancient
-o strokeWeight is still broken
-o setting stroke width on circle makes odd patterns
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1077013848
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1080347160
-o more weirdness with stroke on rect, prolly not alpha
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1085799526
-o rect is not getting it's stroke color set
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1073582391;start=0
-o weird problem with drawing/filling squares
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1077226984
-o alpha of zero still draws boogers on screen
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1073329613;start=0
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1080342288;start=0
-o break apart functions into local (placement) and override (blitting)
-o just have a "thin_flat_line" option in opengl code
-o is quad strip broken or not behaving as expected?
-X may be correct, it worked for nik
-X inside draw() mode, delay() does nothing
-X delay might be a good way to signal drawing to the screen/updating
-X set(x, y, image) x, y not setting with processing
-
-fixed earlier
-X is the texture[] array in PGraphics3D causing the problems with memory?
-X actually it's a PGraphicsGL problem..
-X maybe the image binding not getting unbound?
-o should image i/o be moved into PImage?
-o still needs applet object, so it's not like this is very useful
-o external PImage methods could take stream, i suppose..
-X relevant parts were moved in, others not
-o loadImage() using spaces in the name
-o if loadImage() with spaces when online(), throw an error
-o get tiff exporter for p5 to support argb and gray
-X would also need to modify the tiff loading code,
-X because the header would be different
-X http://dev.processing.org/bugs/show_bug.cgi?id=343
-X map() is not colored, neither is norm
-X image outofmemoryerror for casey's students
-X http://dev.processing.org/bugs/show_bug.cgi?id=355
-X this may be related to a ton of other memory bugs
-X 1.5.0_07 and 1.4.2_12 contain the -XX:+HeapDumpOnOutOfMemoryError switch
-X invaluable for tracking down memory leaks
-X can't replicate anymore
-X texture mapping
-X very odd, "doom era" stuff
-X would it be possible to have a 'slow but accurate' mode?
-X http://dev.processing.org/bugs/show_bug.cgi?id=103
-X fixed in release 0125
-X add hint() and unhint()
-X also add unhint() to the keywords file
-X and maybe remove hint() from keywords_base?
-o present mode is flakey.. applet doesn't always come up
-o seems like hitting stop helps shut it down?
-o is full screen window not being taken down properly?
-o has this fixed itself, or is it an issue with launching externally?
-X seems to be fixed in later java versions
-X rewrite getImpl/setImpl inside opengl
-X placement of 100x100 items is odd
-X happens with P3D and maybe also P2D?
-X http://dev.processing.org/bugs/show_bug.cgi?id=128
-
-
-0132 core
-X an image marked RGB but with 0s for the alpha won't draw in JAVA2D
-X images with 0x00 in their high bits being drawn transparent
-X also if transparency set but RGB is setting, still honors transparency
-X http://dev.processing.org/bugs/show_bug.cgi?id=351
-X improve memory requirements for drawing images with JAVA2D
-X now using significantly less memory
-
-tint/textures
-X tint() and noTint() switching problem in P2D
-X this should be a quick fix
-X http://dev.processing.org/bugs/show_bug.cgi?id=222
-X related to the fill bugs: when fill is identical, no fill applied
-X actually tint() should take over for fill as per-vertex color
-X when textured images are being used
-X http://dev.processing.org/bugs/show_bug.cgi?id=169
-X tint() should set texture color, fill() is ignored with textures
-X add to the reference
-X fix tint() for PGraphics3 (what could be wrong?)
-X tint() honoring alpha but not colored tint
-X maybe not setting fill color when drawing textures
-X guessing it's an implementation issue in sami's renderer
-X check with the a_Displaying example and tint(255, 0, 0, 100);
-X http://dev.processing.org/bugs/show_bug.cgi?id=90
-
-
-0131 core
-X hint(DISABLE_DEPTH_TEST) not behaving consistently
-X http://dev.processing.org/bugs/show_bug.cgi?id=483
-o make hints static - cannot do that
-X clean up hinting mechanism a bit
-X look into jogl anti-aliasing on osx
-o smoothMode(2) and smoothMode(4), right after size()?
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=OpenGL;action=display;num=1175552759
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=OpenGL;action=display;num=1164236069
-X look into capabilities stuff from mike creighton
-X also sets the aa mode on the pc so it no longer needs control panel bunk
-X update to JOGL 1.1.0
-X add gluegen-rt back to the applet export
-X http://download.java.net/media/jogl/builds/nightly/javadoc_public/com/sun/opengl/util/JOGLAppletLauncher.html
-X add print() and println() for long and double
-X http://dev.processing.org/bugs/show_bug.cgi?id=652
-X fix minor bug in saveStream() (undocumented)
-X "this file is named" errors don't like subdirectories
-X need to strip off past the file separator or something
-
-
-0130 core
-X fixed problem with size() and the default renderer
-X the renderer was being reset after setup(),
-X so anything that occurred inside setup() was completely ignored.
-X http://dev.processing.org/bugs/show_bug.cgi?id=646
-X http://dev.processing.org/bugs/show_bug.cgi?id=648
-X http://dev.processing.org/bugs/show_bug.cgi?id=649
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1192873557
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1192731014
-
-
-0129 core
-X width and height not always set properly
-X http://dev.processing.org/bugs/show_bug.cgi?id=642
-X bring back background() with alpha
-
-
-0128 core
-X remove PFont reflection stuff
-X remove cursor reflection stuff
-X fix up sorting functions
-X implement sortCompare() and sortSwap()
-X discuss this with casey
-X also could be using Arrays.sort(blah) with Comparable (1.2+)
-X make sorting functions static
-X use methods from Arrays class, cuts down on code significantly
-X implement sortCompare() and sortSwap()
-X discuss this with casey
-o also could be using Arrays.sort(blah) with Comparable (1.2+)
-X make sorting functions static?
-o should loadFont() work with ttf files (instead of createFont?)
-X otherwise loadFont() would work with font names as well, awkward
-X better to use createFont() for both
-o jogl issues with some cards on linux, might be fixed with newer jogl
-X http://dev.processing.org/bugs/show_bug.cgi?id=367
-X remove methods for background() to include an alpha value
-X this is undefined territory because of zbuffer and all
-X if you want that effect, use a rect()
-X saveFrame() produces a black background because bg not set correctly:
-X http://dev.processing.org/bugs/show_bug.cgi?id=421
-X background not being set properly
-X http://dev.processing.org/bugs/show_bug.cgi?id=454
-X having shut off the defaults reset, background not getting called for java2d
-X so this will make that other stuff regress again
-X in particular, when the applet is resized, but renderer not changed
-X why aren't background() / defaults() being called for opengl?
-o http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Contribution_3DOpenGL;action=display;num=1118784331
-o simon reports borders on P3D and OPENGL if background() not called
-X window fixed at 100x100 pixels
-X http://dev.processing.org/bugs/show_bug.cgi?id=197
-X width/height on problem machine prints out as:
-X 100x100 issues are exhibited on bh140c PCs, test and fix!
-X 100,200 and 128,200
-o AIOOBE on PLine 757.. halts renderer
-o fix erik's problems with export (also in bugs db)
-X draw() called twice in vista with java 1.6
-X http://dev.processing.org/bugs/show_bug.cgi?id=587
-
-cleanup from previous releases
-X P3D not doing bilinear interpolation in text and images
-X because smooth() has to be set (and smooth throws an error in P3D)
-X how should this be handled? a hint? allowing smooth()?
-X probably just allow smooth() but don't smooth anything
-o pdf export ignoring transparency on linux
-o check to see if this is the case on other linux machines
-o seems to be working fine on windows
-o http://dev.processing.org/bugs/show_bug.cgi?id=345
-X change how java version is determined on mac
-X http://developer.apple.com/technotes/tn2002/tn2110.html
-X (this tn provides no guidance for macos8/9.. gah)
-o little window showing up on macosx when running
-X never able to confirm, probably just old java bug
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1081284410
-o flicker happening on osx java 1.4, but not 1.3:
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1083184297
-o don't let users on < 1.3 load JAVA2D
-X set upper bound on framerate so as not to completely hose things?
-
-fixed in 0127
-X ARGB problems with createGraphics
-o P3D from createGraphics needs to be marked RGB not ARGB
-X http://dev.processing.org/bugs/show_bug.cgi?id=160
-X http://dev.processing.org/bugs/show_bug.cgi?id=428
-X http://dev.processing.org/bugs/show_bug.cgi?id=482
-X http://dev.processing.org/bugs/show_bug.cgi?id=530
-X http://dev.processing.org/bugs/show_bug.cgi?id=527
-
-reasons to drop 1.1 support (and support 1.3+)
-X remove reflection from createFont() constructor/methods in PFont
-X this would make PFont much smaller
-X array functions could be done through Arrays.xxx class
-X although some of these may be built in
-X sorting could be done through built-in sort() class
-X split() function could echo the built in split/regexp setup
-X and add features for regexp
-X could introduce use of Timer class in examples
-X also use SwingWorker to launch things on other threads
-X weirdness of two modes of handling font metrics
-X textFontNativeMetrics gives deprecation error
-X getFontList stuff in PFont causes problems
-
-
-0127 core
-X pixel operations are broken in opengl
-X get(), set(), copy(), blend(), loadPixels, updatePixels()
-X set(x, y, image) y reversed in openGL
-X background(image) also broken
-X also textMode(SCREEN)
-X http://dev.processing.org/bugs/show_bug.cgi?id=91
-o replaceAll() not supported by 1.1
-o http://dev.processing.org/bugs/show_bug.cgi?id=561
-o make version of loadBytes that checks length of the stream first
-o this might not be worth it
-o the number of cases where this works is small (half of url streams)
-o and who knows if the value returned will be correct
-o (i.e. will it be the uncompressed or compressed size of the data?)
-
-createGraphics() issues
-X offscreen buffers fail with texture mapping
-X pixels not being set opaque (only with textures?)
-X http://dev.processing.org/bugs/show_bug.cgi?id=594
-X add note to createGraphics() docs that opacity at edges is binary
-X PGraphics problem with fillColor
-X http://dev.processing.org/bugs/show_bug.cgi?id=468
-
-fixed earlier
-X add to open() reference problems with mac
-X need to use the 'open' command on osx
-X or need to do this by hand
-X prolly better to do it by default, since on windows we use cmd?
-X check to see if the user has 'open' in there already
-X they can call Runtime.getRuntime().exec() if they want more control
-
-fixed earlier (in 0125) by ewjordan
-X accuracy in P3D is very low
-X http://dev.processing.org/bugs/show_bug.cgi?id=95
-X textured polys throwing a lot of exceptions (ouch)
-X http://dev.processing.org/bugs/show_bug.cgi?id=546
-X polygons in z axis with nonzero x or y not filling properly
-X http://dev.processing.org/bugs/show_bug.cgi?id=547
-
-
-0126 core
-o rect() after strokeWeight(1) gives wrong coords
-X http://dev.processing.org/bugs/show_bug.cgi?id=535
-X bug in osx java 1.4 vs 1.5
-X fix bug in str() methods that take arrays
-X method was not working properly, was using the object reference
-X new version of saveStream()
-X implement auto-gzip and gunzip
-X fix bug where sort() on 0 length array would return null
-X instead, returns an array
-X unregisterXxxx() calls to remove methods from libs
-X http://dev.processing.org/bugs/show_bug.cgi?id=312
-X implemented by ewjordan
-X sort() on strings ignores case
-X mention the change in the reference
-X added MIN_FLOAT, MAX_FLOAT, MIN_INT, MAX_INT to PConstants
-X throw AIOOBE when min() or max() called on zero length array
-o fix lerpColor() to take the shortest route around the HSB scale
-o loadBytes() doesn't do auto gunzip? but loadStrings and createReader do?
-X this might be a good solution for dealing with the differences
-o with loadBytes(), they can use gzipInput (or loadBytesGZ?)
-o although what does openStream do? (doesn't do auto?)
-X auto-gunzip on createReader()
-o add auto-gunzip to loadStrings()
-X others for auto-gunzip?
-X do the same for createWriter() et al
-X disable mipmaps in 0126
-X http://dev.processing.org/bugs/show_bug.cgi?id=610
-X add match() method that returns an array of matched items
-
-
-0125 core
-X more blend() modes (the five listed on the thread below?)
-X http://dev.processing.org/bugs/show_bug.cgi?id=132
-X figure out what the modes should actually be:
-X photoshop: normal, dissolve; darken, multiply, color burn,
-X linear burn; lighten, screen, color dodge, linear
-X dodge; overlay, soft light, hard light, vivid light,
-X linear light, pin light, hard mix; difference,
-X exclusion; hue, saturation, color, luminosity
-X illustrator: normal; darken, multiply, color burn; lighten,
-X screen, color dodge; overlay, soft light, hard light;
-X difference, exclusion; hue, sat, color, luminosity
-X director: Copy, Transparent, Reverse, Ghost, Not copy,
-X Not transparent, Not reverse, Not ghost, Matte, Mask;
-X (below seems more useful:
-X Blend, Add pin, Add, Subtract pin, Background transparent,
-X Lightest, Subtract, Darkest, Lighten, Darken
-X flash:
-X DIFFERENCE: C = abs(A-B);
-X MULTIPLY: C = (A * B ) / 255
-X SCREEN: C= 255 - ( (255-A) * (255-B) / 255 )
-X OVERLAY: C = B < 128 ? (2*A*B/255) : 255-2*(255-A)*(255-B)/255
-X HARD_LIGHT: C = A < 128 ? (2*A*B/255) : 255-2*(255-A)*(255-B)/255
-X SOFT_LIGHT: C = B < 128 ? 2*((A>>1)+64)*B/255 : 255-(2*(255-((A>>1)+64))*(255-B)/255)
-X jre 1.5.0_10 is still default at java.com.. blech
-X http://dev.processing.org/bugs/show_bug.cgi?id=513
-X constant CENTER_RADIUS will be changed to just RADIUS
-X CENTER_RADIUS is being deprecated, not removed
-X remove CENTER_RADIUS from any p5 code (i.e. examples)
-X split() inconsistency (emailed casey, will discuss later)
-X make split(String, String) behave like String.split(String)
-X and make current split(String) into splitTokens(String)
-X that means split(String) no longer exists
-o add splitTokens() documentation
-o document new version of split() and regexp
-o should we mention String.split?
-X ironed out more of the preproc parseXxxx() functions
-X deal with targa upside-down and non-rle encoding for tga images
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1171576234
-X change println(array) to be useful
-o document using join() for old method
-X remove print(array) since it's silly?
-X make sure it's not in the reference
-X [0] "potato", [1] "tomato", [2] "apple"
-X fix filter(GRAY) on an ALPHA image to produce a good RGB image
-
-0125p2
-X updatePixels ref is wrong
-X has x/y/w/h version
-X the reference is also cut off
-X make ENTER, TAB, etc all into char values (instead of int)
-X some way to vertically center text
-X either by setting its middle vertical point
-X or by setting a top/bottom for the rectangle in which it should be placed
-o maybe textAlign(CENTER | VERTICAL_CENTER);
-X or TOP, MIDDLE, and BOTTOM
-o textAlign(CENTER | TOP);
-o could even have textAlign(CENTER) and textAlign(TOP) not replace each other
-X or textAlign(LEFT, MIDDLE); -> this one seems best
-X add reference for new param, and update keywords.txt
-X given to andy
-
-0125p3
-X PImage.save() method is not working with get()
-X http://dev.processing.org/bugs/show_bug.cgi?id=558
-X NullPointerException in Create Font with "All Characters" enabled
-X http://dev.processing.org/bugs/show_bug.cgi?id=564
-X added min() and max() for float and int arrays
-X need to update reference
-X moved around min/max functions
-X opengl image memory leaking
-X when creating a new PImage on every frame, slurps a ton of memory
-X workaround is to write the code properly, but suggests something bad
-X http://dev.processing.org/bugs/show_bug.cgi?id=150
-X opengl keeping memory around..
-X could this be in vertices that have an image associated
-X or the image buffer used for textures
-X that never gets cleared fully?
-X registerSize() was registering as pre() instead
-X http://dev.processing.org/bugs/show_bug.cgi?id=582
-X set() doesn't bounds check
-X this shouldn't actually be the case
-X http://dev.processing.org/bugs/show_bug.cgi?id=522
-X get()/set() in PGraphicsJava2D don't bounds check
-X was actually a dumb error in setDataElements()
-X set modified to true on endDraw() so that image updates properly
-X http://dev.processing.org/bugs/show_bug.cgi?id=526
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Syntax;action=display;num=1171574044
-
-0125p4 (in progress)
-X significant improvement to text and images in opengl
-X now using mipmaps to interpolate large and small images
-X fix bug with mipmapping on radeon 9700
-X things not showing up in linux
-X this may be fixed along with bug #341
-X probably threading issue, 98 doesn't have any trouble
-X signs point to Runner or PApplet changes between 98 and 99
-X commenting out applet.setupFrameResizeListener()
-X in line 307 from Runner.java solved the problem
-X http://dev.processing.org/bugs/show_bug.cgi?id=282
-X size of sketch different in setup() and draw() on linux
-X make sure that the sketch isn't being sized based on bad insets
-X problem with resizing the component when the frame wasn't resizable
-X http://dev.processing.org/bugs/show_bug.cgi?id=341
-X major rework of the open() command
-X add gnome-open/kde-open for with PApplet.open()
-X add open (-a?) on osx to the open() command
-X make changes in the javadoc and reference
-X opengl crashes when depth sorting more than two textured shapes
-X http://dev.processing.org/bugs/show_bug.cgi?id=560
-
-ewjordan stuff (changes checked in)
-X rect() changes size as it changes position
-X http://dev.processing.org/bugs/show_bug.cgi?id=95
-X strange texture warping in P3D
-X hint(ENABLE_ACCURATE_TEXTURES)
-X http://dev.processing.org/bugs/show_bug.cgi?id=103
-X lines skip on 200x200 surface because of fixed point rounding error
-X http://dev.processing.org/bugs/show_bug.cgi?id=267
-X this may be same as 95
-X Polygons parallel to z-axis not always filling with nonzero x or y
-X http://dev.processing.org/bugs/show_bug.cgi?id=547
-
-
-0124 core
-X with smooth() turned off, shouldn't be smoothing image on resize
-X but on osx, apple defaults the image smoothing to true
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Programs;action=display;num=1164753510
-X http://developer.apple.com/documentation/Java/Conceptual/JavaPropVMInfoRef/Articles/JavaSystemProperties.html#//apple_ref/doc/uid/TP40001975-DontLinkElementID_6
-X background(0, 0, 0, 0) was resetting stroke, smooth, etc.
-X make imageImpl() use WritableRaster in an attempt to speed things up
-X fix weird situation where fonts used in more than one renderer wouldn't show
-X opengl doesn't draw a background for the raw recorder
-X change P3D to smooth images nicely (bilinear was disabled)
-X ambientLight(r,g,b) was still ambientLight(r,g,r)
-X http://dev.processing.org/bugs/show_bug.cgi?id=465
-X fix from dave bollinger for the POSTERIZE filter
-X http://dev.processing.org/bugs/show_bug.cgi?id=399
-X fix PImage regression in 0124 and the cache crap
-X added a version of trim() that handles an entire array
-X removed contract(), one can use expand() and subset() instead
-X backgroundColor to cccccc instead of c0c0c0
-X loadImage() requires an extension, maybe add a second version?
-X loadImage("blah", "jpg");
-X otherwise people have to use strange hacks to get around it
-X also chop off ? from url detritus
-X also just pass off to default createImage() if no extension available
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Syntax;action=display;num=1165174666
-X http://dev.processing.org/bugs/show_bug.cgi?id=500
-X java 1.5.0_10 breaks jogl
-X add error message to p5 about it
-X http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6504460
-X http://www.javagaming.org/forums/index.php?topic=15439.0
-X upgrade to 1.5.0_11 or later:
-X http://java.sun.com/javase/downloads/index_jdk5.jsp
-X or downgrade to 1.5.0_09
-X http://java.sun.com/products/archive/j2se/5.0_09/index.html
-X no disk in drive error
-X was this something that changed with the java updates? (1.5_10)
-X doesn't seem to be, still not sure
-X problem was the floppy drive.. gak
-X http://dev.processing.org/bugs/show_bug.cgi?id=478
-X copy() sort of broken in JAVA2D
-X example sketch posted with bug report
-X http://dev.processing.org/bugs/show_bug.cgi?id=372
-o saveStrings(filename, strings, count)
-o otherwise the save is kinda wonky
-o or maybe that should just be done with the array fxns
-
-fixed earlier
-o sketches often freeze when stop is hit on an HT machine
-o need to test the examples cited on pardis' machine
-o http://dev.processing.org/bugs/show_bug.cgi?id=232
-X debug NumberFormat InterruptedException on dual proc machine
-X use notify() instead of interrupt()?
-X or Thread.currentThread() should be checked first?
-o svg loader is on the list for 1.0
-o maybe include as part of PApplet (casey thinks so)
-X using gl, lines don't show up in pdf with record (they're ok with p3d)
-X http://dev.processing.org/bugs/show_bug.cgi?id=325
-o with network connection
-o download a copy of the source for 0069, get the renderer
-o svn mv PGraphics2 PGraphicsJava
-o version of BApplet that replaces g. with ai. or pdf.
-
-
-0123 core
-X setup() and basic mode apps not working
-X http://dev.processing.org/bugs/show_bug.cgi?id=463
-
-
-0122 core
-X noiseSeed() only works once, before the arrays are created
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1162856262
-X make lerpColor honor the current color mode
-X lerpColor(c1, c2, amt, RGB/HSB/???)
-o test this out for a bit
-o though that's awkward b/c colors always RGB
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Suggestions;action=display;num=1160096087
-X regression in P3D that prevents point() from drawing
-X problem is with setup_vertex() not adding similar points
-X http://dev.processing.org/bugs/show_bug.cgi?id=444
-X if doing openstream on url, says that "the file" is missing or invalid
-X add notes about it being a url
-
-fixed earlier, bug cleaning
-X gray background in pdf (using both gl and p3d)
-X http://dev.processing.org/bugs/show_bug.cgi?id=324
-X verified as fixed in 0122
-
-
-0121 core
-X need to document changes to int() (no longer accepts boolean)
-X background(0, 0, 0, 0) is the way to really clear everything with zeroes
-X or background(0, 0), but the former is prolly better conceptually
-X how to clear the screen with alpha? background(0, 0, 0, 0)?
-o background(EMPTY) -> background(0x01000000) or something?
-X size(), beginRecords(), beginRaw(), createGraphics()
-X broken for file-based renderers in 0120
-X http://dev.processing.org/bugs/show_bug.cgi?id=434
-
-
-0120 core
-X fixed error when using hint(ENABLE_NATIVE_FONTS) with JAVA2D
-X java.lang.IllegalArgumentException:
-X null incompatible with Global antialiasing enable key
-X fix issue where ambientLight(r, g, b) was instead ambientLight(r, g, r)
-X http://dev.processing.org/bugs/show_bug.cgi?id=412
-X createFont() should always use native fonts
-X need to warn that fonts may not be installed
-X recommend that people include the ttf if that's the thing
-X or rather, that this is only recommended for offline use
-X fix 3D tessellation problems with curveVertex and bezierVertex
-X actually was z = Float.MAX_VALUE regression
-X http://dev.processing.org/bugs/show_bug.cgi?id=390
-X two examples in sketchbook
-X this has been reported several times
-X concave polygons having trouble if points come back to meet
-X tesselator/triangulator gets confused when points doubled up
-X might need to avoid previous vertex hitting itself
-X http://dev.processing.org/bugs/show_bug.cgi?id=97
-X graphics gems 5 has more about tessellation
-X polygons perpendicular to axis not drawing
-X is this a clipping error?
-X probably a triangulation error, because triangles work ok
-X http://dev.processing.org/bugs/show_bug.cgi?id=111
-X problem is that the area of the polygon isn't taking into account z
-X lookat is now camera(), but not fixed in the docs
-X add notes to the faq about the camera changes on the changes page
-o update run.bat for new quicktime
-o unfortunately this is messy because qtjava sometimes has quotes
-o and qtsystem might be somewhere besides c:\progra~1
-X run.bat has been removed from current releases
-X registering font directories in pdf.. is it necessary?
-X (commented out for 0100)
-X re-added for 0120
-o when re-calling size() with opengl, need to remove the old canvas
-o need to check to see if this is working properly now
-X passing applet into createGraphics.. problems with re-adding listeners
-X since the listeners are added to the PApplet
-X i think the listeners aren't re-added, but need to double check
-X createGraphics() having problems with JAVA2D, and sometimes with P3D
-X http://dev.processing.org/bugs/show_bug.cgi?id=419
-X with default renderer, no default background color?
-X only sometimes.. why is this?
-X only call defaults() when it's part of a PApplet canvas
-X make sure that defaults() is no longer necessary
-X don't want to hose PGraphics for others
-X both for pdf, and making background transparent images
-X PGraphics3D should alloc to all transparent
-X unless it's the main drawing surface (does it know on alloc?)
-X in which case it should be set to opaque
-X have createGraphics() create a completely transparent image
-X and also not require defaults() to be called
-X make a note in the createFont() reference that 1.5 on OS X has problems
-o if calling beginPixels inside another, need to increment a counter
-o otherwise the end will look like it's time to update
-o which may not actually be the case
-o i.e. calling filter() inside begin/end block
-X get creating new PGraphics/2/3 working again
-X http://dev.processing.org/bugs/show_bug.cgi?id=92
-X maybe createGraphics(200, 200) to create same as source
-X createGraphics(200, 200, P2D) to create 2D from 3D
-X also, drawing a PGraphics2 doesn't seem to work
-X new PGraphics2 objects are set as RGB, but on loadPixels/updatePixels
-X they're drawn as transparent and don't have their high bits set
-X problems between modelX between alpha and beta
-X http://dev.processing.org/bugs/show_bug.cgi?id=386
-X y may be flipped in modelX/Y/Z stuff on opengl
-X is this the same bug? assuming that it is
-
-in previous releases
-X when using PGraphics, must call beginFrame() and endFrame()
-X also need to be able to turn off MemoryImageSource on endFrame
-X call defaults() in beginFrame()
-X should PGraphics be a base class with implementations and variables?
-X then PGraphics2D and PGraphics3D that subclass it?
-X (or even just PGraphics2 and PGraphics3)
-X also rename PGraphics2 to PGraphicsJava
-X it's goofy to have the naming so different
-X tweak to only exit from ESC on keyPressed
-o probably should just make this a hint() instead
-X just documented in reference instead
-o metaballs example dies when using box()
-o long string of exceptions, which are also missing their newlines
-X grabbing sun.cpu.endian throws a security exception with gl applets
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Contribution_3DOpenGL;action=display;num=1114368123
-
-
-0119 core
-X add saveStream() method
-X change to handle Java 1.5 f-up where URLs now give FileNotFoundException
-X http://dev.processing.org/bugs/show_bug.cgi?id=403
-X add unlerp() method
-
-
-0118 core
-X replace jogl.jar with a signed version
-X fix the export.txt file for the linux release
-X fix problem with setting the parent and the PDF renderer
-
-
-0117 core
-X no changes, only to the build scripts
-
-
-0116 core
-X make background() ignore transformations in JAVA2D
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1147010374
-o createGraphics to not require defaults()
-X can't do, because an end() function must be called to clear the renderer
-X add "hide stop button" arg for PApplet
-X beginFrame/endFrame -> beginDraw/endDraw
-X add new constant for the DXF renderer
-X array utilities on Object[] are worthless.. fix it with reflection?
-X see if reflection will allow expand for all class types
-X expand, append, contract, subset, splice, concat, reverse
-X typed version of array functions:
-X append(), shorten(), splice, slice, subset, concat, reverse
-X http://dev.processing.org/bugs/show_bug.cgi?id=115
-X fix issue where processing applets would run extremely fast
-X after having been starved of resources where there framerate dropped
-X http://dev.processing.org/bugs/show_bug.cgi?id=336
-X added color/stroke/tint/fill(#FF8800, 30);
-X test imageio with images that have alpha (does it work?)
-X nope, doesn't, didn't finish support
-X http://dev.processing.org/bugs/show_bug.cgi?id=350
-X openStream() fails with java plug-in because non-null stream returned
-X http://dev.processing.org/bugs/show_bug.cgi?id=359
-X update jogl to latest beta 5
-X make framerate into frameRate (to match frameCount)
-X AIOOBE in P3D during defaults/background/clear
-X PGraphics.clear() problem from workbench and malware stuff
-X had to put synchronized onto draw and size()
-X actually it'll work if it's only on size()
-X the sync on the mac hangs an applet running by itself
-X even though it seems to be ok for a component
-X thread sync problem with allocation
-X http://dev.processing.org/bugs/show_bug.cgi?id=369
-X major threading change to use wait()/notifyAll() instead of interrupt/sleep
-X noLoop() at end of setup is prolly b/c of interruptedex
-X need to not call Thread.interrupt()
-X opengl + noLoop() causes InterruptedException
-X check to see noLoop() breakage is fixed in 92 vs 91
-X checked, not fixed
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1115330568
-X http://dev.processing.org/bugs/show_bug.cgi?id=164
-X remove image(filename) and textFont(filename) et al.
-X revision 115 may be saving raw files as TIFF format
-X may be a bug specific to java 1.5 (nope)
-X http://dev.processing.org/bugs/show_bug.cgi?id=378
-X saveFrame() not working for casey
-X problem with tiff loading in photoshop etc
-X check http:// stuff to see if it's a url first on openStream()
-X it's the most harmless, since prolly just a MFUEx
-X fix problem where root of exported sketch won't be checked
-X http://dev.processing.org/bugs/show_bug.cgi?id=389
-X createFont not working from applets (only with .ttf?)
-X throws a security exception because of the reflection stuff
-X http://dev.processing.org/bugs/show_bug.cgi?id=101
-X urls with ampersands don't work with link()
-X Runtime.getRuntime().exec("cmd /c start " + url.replaceAll("&","^&"));
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1149974261
-X fix bug where smooth() was shut off after using text
-X (that had the smoothing turned off when used in "Create Font")
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1148362664
-X fix dxf to use begin/endDraw instead of begin/endFrame
-X fixes axel's bug with dxf export
-X set default frameRate cap at 60
-X otherwise really thrashing the cpu when not necessary
-X jpeg loading may be extremely slow (loadBytes?)
-X seems specific to 0115 versus the others
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1158111639
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1154714548
-X http://dev.processing.org/bugs/show_bug.cgi?id=392
-X loadImage() problems with png and jpg
-X actually it's an issue with some types of jpeg files
-X http://dev.processing.org/bugs/show_bug.cgi?id=279
-X java.lang.IllegalArgumentException:
-X Width (-1) and height (-1) cannot be <= 0
-X identical to what happens when the image data is bad
-X for instance, trying to load a tiff image with the jpg loader
-X http://dev.processing.org/bugs/show_bug.cgi?id=305
-o blend() mode param should be moved to the front
-X nah, works better with the other format
-X make sure there's parity with the copy() functions
-X remove single pixel blend functions
-o blend() should prolly have its mode be the first param
-X move blend() to blendColor() when applying it to a color
-X added lerpColor(), though it needs a new name
-X went back to old image i/o (sometimes caused trouble when exported)
-X http://dev.processing.org/bugs/show_bug.cgi?id=376
-X change reader() to createReader() for consistency?
-X though printwriter is odd for output..
-X also createWriter() and the rest
-o add to docs: save() on a PImage needs savePath() added
-X hint(DISABLE_NATIVE_FONTS) to disable the built-in stuff?
-X or maybe this should be hint(ENABLE_NATIVE_FONTS) instead?
-X figure out default behavior for native text fonts
-X make sure insideDrawWait() is in other resize() methods
-X begin/end/alloc waits to PGraphicsJava2D, PGraphicsOpenGL, PGraphics3D
-X fix bug with fill(#ffcc00, 50);
-X toInt() on a float string needs to work
-X need to check for periods to see if float -> int first
-X shape changes
-X remove LINE_STRIP - tell people to use beginShape() with no params
-X remove LINE_LOOP - tell people to use endShape(CLOSE)
-o also remove POLYGON?
-X may as well remove it
-X though something still needed as an internal constant
-X add endShape(CLOSE) or CLOSED
-X when running as an applet, sketchPath won't be set
-X change the error message slightly
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Syntax;action=display;num=1153150923
-X use parseFloat instead of toFloat()? to be consistent with javascript
-X also clean up some of the casting silliness
-
-more recent
-X only update mouse pos on moved and dragged
-X http://dev.processing.org/bugs/show_bug.cgi?id=170
-X also updates a bug that caused sketches to jump in funny ways
-
-fixed in 0115 / quicktime 7.1
-X color values on camera input flipped on intel macs
-X checked in a change for this recommended on qtjava list
-X http://dev.processing.org/bugs/show_bug.cgi?id=313
-
-really old stuff
-o get loop, noLoop, redraw, and framerate all working in opengl
-o needs custom animator thread..
-o depth() shouldn't be needed for opengl unless actually 3D
-o right now the camera doesn't get set up unless you call depth()
-o box and sphere are broken in gl
-o what should the update image function be called?
-
-
-0115 core
-X remove debug message from loadPixels()
-X remove debug message from PGraphics2.save()
-X fix error message with dxf when used with opengl
-X if file is missing for reader()
-X return null and println an error rather than failing
-X add arraycopy(from, to, count);
-X fix fill/stroke issues in bugs db (bug 339)
-X saveTIFF, saveHeaderTIFF, saveTGA no longer public/static in PImage
-X this was a mistake to expose the api this way
-X more image file i/o in java 1.4
-X add dynamic loading of the jpeg, png, and gif(?) encoder classes
-X http://dev.processing.org/bugs/show_bug.cgi?id=165
-X http://java.sun.com/products/java-media/jai/index.jsp
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Programs;action=display;num=1120174647
-X P5 cannot read files generated by saveFrame()
-X need to update docs re: tga
-X and add support for reading its own uncompressed TIFs
-X http://dev.processing.org/bugs/show_bug.cgi?id=260
-
-
-0114 core
-X added createGraphics(width, height, renderer)
-X no need to use (..., null) anymore
-X fix set() for JAVA2D, also fixes background(PImage) for JAVA2D
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Syntax;action=display;num=1145108567
-X remove "max texture size" debug message
-X flicker with depth sort enabled
-X implement basic depth sorting for triangles in P3D and OPENGL
-X add option to sort triangles back to front so alpha works
-X http://dev.processing.org/bugs/show_bug.cgi?id=176
-o at least add it to the faq, or this would be a test case w/ the sorting
-
-
-0113 core
-X fix for open() on macosx submitted by chandler
-
-
-0112 core
-X saveFrame() issues with JAVA2D on osx
-X http://dev.processing.org/bugs/show_bug.cgi?id=189
-o implement hint(NO_DEPTH_TEST) for opengl
-X already done hint(DISABLE_DEPTH_TEXT);
-X check min/max texture sizes when binding to avoid problems
-X minimum texture size may be 64x64
-X maximum appears to be 2048, on macs maybe 512
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Contribution_3DOpenGL;action=display;num=1137130317
-X fix non-bound textures from mangling everything else
-X http://dev.processing.org/bugs/show_bug.cgi?id=322
-X fix enable/disable textures for some objects
-X also a big problem for fonts
-X calling updatePixels() on each frame fixes the issue (sorta)
-X images are memory leaking pretty badly
-X texture re-allocated on each frame
-X lighting bug introduced in rev 109
-X spotLight has troubles with an invalid value
-X probably somethign weird about the params (3 vs 4) being sent
-X the first spotLight works fine, it's something with the second
-X (the one that follows the mouse)
-X just something to debug in the example
-X regression from contributed code..
-X was using apply() instead of set() in PMatrix inverse copy
-X filter() is also broken (not rewinding the intbuffer)
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Contribution_3DOpenGL;action=display;num=1144561113
-
-sound has been removed
-o duration as an internal param, not a function
-o When a sound is finished playing,
-o it should return to 0 so it can play again
-o Putting sound.loop() in draw() seemed to spawn multiple sounds threads?
-o After a sound is paused, it will only play from where it was paused
-o to its end and will not loop again
-o The ref in PSound2 says volume accepts vals from 0...1
-o but values larger than one increase the volume.
-o SoundEvent // is sound finished?? Can't access now.
-o make java 1.1 version of PSound work properly
-o merge PSound and PSound2 via reflection?
-o once debugged, merge these back together and use reflection
-o (unless it's a messy disaster)
-o Unsupported control type: Master Gain
-o what's actually causing this error?
-o http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1115467831
-o PSound.play() won't play the sound a 2nd time (reopened)
-o http://dev.processing.org/bugs/show_bug.cgi?id=208
-o loadSound apparently broken in java 1.5?
-o http://dev.processing.org/bugs/show_bug.cgi?id=285
-X need to just remove PSound altogether
-
-
-0111 core
-X need to have a better way of getting/figuring out the endian
-X use ByteOrder class in jdk 1.4, since issue is local to JOGL
-X security ex when run as an applet
-X also can no longer assume that macosx is big endian
-X http://dev.processing.org/bugs/show_bug.cgi?id=309
-o making 'run' synchronized caused a freeze on start w/ opengl
-X display() as a function name is problematic
-X causes nothing to show up.. either rename or mark it final
-X http://dev.processing.org/bugs/show_bug.cgi?id=213
-X fix for lights throwing a BufferOverflowException
-
-
-0110 core
-X finish updates for osx and opengl
-X http://developer.apple.com/qa/qa2005/qa1295.html
-X find/build universal version of jogl
-
-
-0109 core
-X loadImage("") produces weird error message
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Programs;action=display;num=1136487954
-X still having strokeCap() problems
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1134011764
-X fixes contributed by willis morse to deal with memory wastefulness
-X should help speed up some types of OPENGL and P3D mode sketches
-
-
-0108 core
-X image(String filename, ...) and textFont(String filename, ...) implemented
-X add notes to faq about video fix
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=VideoCamera;action=display;num=1134871549
-X look into code that fixes crash on camera.settings()
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=VideoCamera;action=display;num=1139376484
-X finish dxf writer that'll work with recordRaw()
-
-
-0107 core
-X no changes, only fixes for "save" bugs
-
-
-0106 core
-X fix bug where more than 512 vertices would cause trouble in P3D and OPENGL
-
-
-0105 core
-X fix some issues with beginRaw and opengl
-
-
-0104 core
-X don't open a window the size of the pdf if in pdf mode
-X need to have some sort of flag in the gfx context that it's visible or not
-o handled inside updateSize()?
-X if it doesn't display to the screen, needs to never show a window
-X basically if the main gfx context isn't viewable, close the window
-X since it may have already been opened at 100x100
-X avoid opening it in the first place?
-X added toolkit getFontMetrics() for shape mode fonts to be able to change size
-X recordRaw() to a PGraphics3 should send 3D data.
-X but recordRaw() to a PGraphics(2) should send only 2D data.
-
-
-0103 core
-X fix stack overflow problem
-X bug in itext implementation on osx (10.4 only?)
-X http://www.mail-archive.com/itext-questions@lists.sourceforge.net/msg20234.html
-
-in previous releases
-X recordFrame() and beginFile()/endFile()
-X how to deal with triangles/lines and triangleCount and lineCount
-X maybe just need a triangleImpl and lineImpl
-X because it's too messy to retain the triangle objects and info
-X calling recordFrame() from mousePressed is important
-X dangerous tho because mouse fxn called just before endFrame
-
-
-0102 core
-X no changes, windows-only release to deal with processing.exe
-
-
-0101 core
-X add dispose() call to the shutdown part of PApplet
-
-
-0100 core
-X user.dir wasn't getting set properly
-X when graphics can be resized, resize rather than creating new context
-X change savePath() et al a great deal, include better docs
-X http://dev.processing.org/bugs/show_bug.cgi?id=199
-X straighten out save() and saveFrame()
-o use File object for when people know what they're doing?
-X same issue occurs with pdf and creating graphics obj
-
-get initial version of pdf working
-X get rid of beginFrame/endFrame echo to recorders?
-X that way begin/end can just be where the recorder starts/stops?
-X recordRaw is really confusing..
-X when to use beginFrame/endFrame
-X is beginRaw/endRaw really needed?
-X seems to be a problem that it's an applet method
-X but then it's called on the g of the applet
-X but then it's the recorderRaw of that g that gets it called..
-X how to flush when the sketch is done
-X inside dispose method? explicit close?
-X call exit() at end of pdf apps? exit calls dispose on gfx?
-X beginRecord() and endRecord() so that record doesn't stop after frame?
-X enable PGraphicsPDF for inclusion
-X write documentation on images (they suck) and fonts (use ttf)
-
-
-0099 core
-X removed playing() method from PSound
-X integrate destroy() method from shiffman as dispose() in PSound2
-X ComponentListener is probably what's needed for resize()
-X make sure that components can be resized properly via size()
-X http://dev.processing.org/bugs/show_bug.cgi?id=209
-X or that it properly responds to a setBounds() call
-X calling size() elsewhere in the app doesn't quite work
-X A second call to size almost works.
-X The buffer apparently gets allocated and saveFrame saves the
-X new size but drawing appears to be disabled.
-X http://dev.processing.org/bugs/show_bug.cgi?id=243
-
-
-0098 core
-X change recordShapes() to just record() and recordRaw()
-X width, height set to zero in static mode
-X http://dev.processing.org/bugs/show_bug.cgi?id=198
-X probably only set when resize() is called, and it's not happening
-X be careful when fixing this, bugs 195/197 were a result:
-X http://dev.processing.org/bugs/show_bug.cgi?id=195
-X http://dev.processing.org/bugs/show_bug.cgi?id=197
-X PSound.play() won't play the sound a 2nd time
-X (have to call stop() first)
-X http://dev.processing.org/bugs/show_bug.cgi?id=208
-
-
-0097 core
-X no changes, only export to application stuff
-
-
-0096 core
-X set applet.path to user.dir if init() is reached and it's not set
-X add DISABLE_DEPTH_TEST to PGraphics3
-X need to document this somewhere
-X also need to add to PGraphicsGL
-X access logs are being spammed because openStream() gets a 404
-X the default should be to check the .jar file
-X openStream() doesn't work with subfolders
-X http://dev.processing.org/bugs/show_bug.cgi?id=218
-X screwed up movie loading paths (quick fix)
-X http://dev.processing.org/bugs/show_bug.cgi?id=216
-X additional cleanup in the Movie class
-X make path thing into getPath() or something?
-X sketchPath(), dataPath(), savePath(), createPath()
-X applet shouldn't be resizing itself
-X opens at correct size, then makes itself small, then large again
-X setup() mode apps often don't open at the correct placement
-X because of their resizing
-X check into bug where applet crashing if image not available
-X probably need to add a hint() to make things not halt
-X loadBytes() and openStream() et al need to return null
-X loadImage() can too, but print an error to the console
-X "not available in P3D" should read "OPENGL" in opengl lib
-X keypressed ref: repeating keys
-X also remove "no drawing inside keypressed"
-X text block wrap problem with manual break character (\n)
-X http://dev.processing.org/bugs/show_bug.cgi?id=188
-
-draw mode issues
-X when run externally without a draw, applets will exit immediately
-X when run internally (no code folder or .java files) will just wait
-X shouldn't quit draw mode apps immediately
-X otherwise something gets drawn then the applet exits
-X should instead use exit() when they need to exit
-X NullPointerException when no draw()
-X http://dev.processing.org/bugs/show_bug.cgi?id=210
-X window closing immediately with library imports
-X http://dev.processing.org/bugs/show_bug.cgi?id=204
-X check into loadImage() with jars bug, very frustrating
-o when using loadImage() on a jar, turn off "no cache" option?
-X image no load halts the program (rather than returning null)
-X note in the reference: png images work with java 1.3+
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=WebsiteBugs;action=display;num=1125968697
-X add bug re: gif image break missing to revisions.txt
-X http://dev.processing.org/bugs/show_bug.cgi?id=217
-
-image pile
-X get loadImage() to work properly with data folder
-X should probably use the code from loadStream
-X and the url stuff should be an alternate method altogether
-o loadImage() seems to be caching everything from the jar
-X http://java.sun.com/developer/technicalArticles/Media/imagestrategies/index.html
-o make a note of how to disable this
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Programs;action=display;num=1078795681
-o bizarre image loading error with c_Rollover.zip
-X couldn't find/replicate this
-o read uncompressed tiff
-X read uncompressed tga files.
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_Software;action=display;num=1081190619
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Tools;action=display;num=1066742994
-o updated png encoder
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Syntax;action=display;num=1083792994
-
-older stuff, no longer an issue
-o don't cache stuff from loadStrings and others
-o mac java vm won't give up old version of file
-o or use setUseCaches(false)
-o too many push() will silently stop the applet inside a loop
-X allow save(), saveFrame() et al to properly pass in absolute paths
-X (so that it doesn't always save to the applet folder)
-X could require that save() takes an absolute path?
-X loadImage must be used inside or after setup
-X either document this and/or provide a better error message
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Programs;action=display;num=1060879468
-X expose function to write tiff header in PImage (advanced)
-X helps with writing enormous images
-X tag release 93 (francis thinks it's rev 1666)
-
-
-0095 core
-X undo the fix that causes the width/height to be properly set
-
-
-0094 core
-X fix bug that was causing font sizes not to be set on opengl
-X http://dev.processing.org/bugs/show_bug.cgi?id=174
-X apply fix from toxi to make targa files less picky
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1127999630
-X "folder" has been renamed to "path" to match savePath().
-X added "dataPath" to return the full path to something in the data folder
-X savePath should maybe be appletPath or sketchPath
-X because can be used for opening files too
-X (i.e. if needing a File object)
-X width, height set to zero in static mode
-X probably only set when resize() is called, and it's not happening
-X g.smooth is always false in opengl
-X http://dev.processing.org/bugs/show_bug.cgi?id=192
-
-o triangleColors are different because they're per-triangle
-o as opposed to per-vertex, because it's based on the facet of the tri
-X make vertexCount etc properly accessible in PGraphics3
-X so that people can do things like the dxf renderer
-X also have a simple way to hook in triangle leeches to PGraphics3
-X this exists, but needs to be documented, or have accessors
-
-
-0093 core
-X upgrade jogl to a newer rev to fix osx "cannot lock" issues
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1118603714
-X http://192.18.37.44/forums/index.php?topic=1596.msg79680#msg79680
-X faster blur code contributed by toxi
-X filter(ERODE) and filter(DILATE) contributed by toxi
-o textAscent() should probably be g.textAscent instead
-o more like textLeading() etc
-X nope, because it requires grabbing the font metrics and other calculations
-X bezierDetail, curveDetail made public
-X added textMode(SHAPE) for OPENGL
-X error message saying that strokeCap and strokeJoin don't work in P3D
-X textMode(SHAPE) throws ex when drawing and font not installed
-X fix a bug with filename capitalization error throwing
-X add NO_DEPTH_TEST to PGraphics3
-X java 1.4 code snuck into PApplet, causing problems on the mac
-X http://dev.processing.org/bugs/show_bug.cgi?id=146
-X prevent PGraphics.save() from inserting a file prefix
-X so that people can use absolute paths
-X or add a version that takes a file object
-
-nixed or fixed in previous releases
-X textMode(SCREEN) having issues on Mac OS X
-X seem to be problems with updatePixels() on the mac
-X appears to run asynchronously
-X move zbuffer et al into PGraphics so that people don't have to cast to P3
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Contribution_3DOpenGL;action=display;num=1116978834
-o noLoop() is behaving strangely
-o http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1116002432;start=0
-
-
-0092 core
-X rle-compressed tga save() method added by toxi
-X also version that only saves RGB instead of ARGB
-X proper/consistent api to access matrices in PGraphics/PGraphics3
-X first use loadMatrix(), then m00, m01 etc
-X find the post on the board and make a note of this
-X proper api for access to Graphics2D object in PGraphics2
-X just add the current "g2" thing to the faq
-X and make a note of it on the suggestions board
-X vars like cameraX etc need to be in PGraphics
-X otherwise g.xxxx won't work
-X how far should this go? vertices etc?
-X vertices not included because switching to triangleImpl and lineImpl
-X fix for copy() in java2d to make things a little speedier
-X make PApplet.main() for java 1.3 friendly (Color class constants)
-X remove call to background() in PGraphics2
-o change PGraphics to PGraphics2
-o or not, because PGraphics has all the base stuff for 3D
-o change PGraphics2 to PGraphicsJava or PGraphicsJava2D
-o maybe wait until the new shape stuff is done?
-X move font placement stuff back into PGraphics?
-X figure out how to get regular + java fonts working
-X use that do drive how the api is set up
-X optimize fonts by using native fonts in PGraphics2
-X especially textMode(SCREEN) which is disastrously slow
-X in java2d, can quickly blit the image itself
-X this way, can isolate it for gl too, which will use glBitmap
-X danger of this setup is that it may run much nicer for the author
-X i.e. with the font installed, and then super slow for their users
-X add "smooth" as a field inside the font file
-X and when smooth field is set, make sure JAVA2D enables smoothing
-X since otherwise smooth() has to be called for the whole g2
-X rob saunders contributed a fix for a bug in PImage.copy()
-X the wrong boundaries were being copied in the code
-X fix bug where noLoop() was waiting 10 secs to call exit()
-X add ability to draw text from the current text position
-
-
-0091 core
-X change to synchronization to hopefully fix some update issues
-X curveVertex() problem in P2D when > 128 points fixed
-_ http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1115856359;start=0
-X for present mode, need to set a default display
-X currently crashes if only --present is specified w/o --display
-o make the 1.4 code in PApplet load via reflection
-X doesn't appear necessary with 1.3 applets
-o or is some of the stuff usable in 1.3 but not all?
-o ie. the device config classes exist but not the set full screen method
-X currently some bugs in the main() because it's not sizing applets
-X if running in present mode it works ok
-X but that also needs its display set.. argh
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1115834600;start=0
-X add exit() function to actually explicitly quit
-X scripts will just require that people include exit at the end
-X esc should kill fullscreen mode (actually now it just quits anything)
-X can a key handler be added to the window? not really
-X add an escape listener to the applet tho.. but will it work with gl?
-X how can this be shut off for presentations?
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1114027594;start=0
-X present mode wasn't reading the stop button color
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Suggestions;action=display;num=1116166897;start=0
-X cleaned up the createFont() functions a little
-X java 1.3 required message isn't clickable
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1117552076
-
-
-0090 core
-X added arraycopy() function that calls System.arraycopy()
-X also the useful shortcut fxn
-
-
-0089 core
-X no changes since 88
-
-
-0088 core
-X createFont crashes on verdana (win2k)
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1115258282;start=0
-X made ceil(), floor(), and round() return ints instead of floats
-X fix for PSound: Unsupported control type: Master Gain
-X just shuts off the volume control
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1115467831;start=0
-
-cleared out / completed in previous releases
-X typed version of expand() and contract()
-o fishwick bug with text() and shapes
-o ellipses no longer completed when g.dimensions = 2 or 3,
-o or not even drawn.. what a mess.
-X go through and figure out what stuff to make public
-o depth testing of lines vs text is problematic
-o probably need to patch in an older version of the line code
-o use depth()/noDepth() to handle depth test
-X on exceptions, use die to just kill the applet
-X make the file i/o stuff work more cleanly
-X if people want to use their own file i/o they can do that too
-o this could also be contributing to the hanging bug
-X static applets need to be able to resize themselves on 'play'
-X figure out what to do with static apps exported as application
-X needs to just hang there
-o scripts (w/ no graphics) will need to call exit() explicitly
-o actually.. just override the default draw() to say exit()
-X may need a fileOutput() and fileInput() function
-X to take care of exception handling
-o or maybe scripts are just handled with a different method? (yech)
-o or maybe setup() can actually throw and Exception?
-o but that's inserted by the parser, and hidden from the user?
-o implement size(0, 0) -> just doesn't bother doing a frame.show();
-o too abstract, just have draw() call exit by default
-o so if nothing inside draw, just quits
-o make properly exit after things are finished
-o still some weirdness with thread flickering on the mac
-o and frenetic display updates on the pc
-o move really general things out of PConstants (X, Y, Z..) ?
-X add something to PApplet to have constants for the platform
-o needed for error messages (don't talk about winvdig on mac)
-X and also useful for programs
-X bring screen space and font size settings back in to PGraphics
-X causing too much trouble to be stuck down in PFont
-
-
-0087 core
-
-fixed in previous releases
-X The PushPop example in Transformations is not working
-X with lights() callled
-X The transparency of the Rotate3D example in Translformations
-X is not as expected
-X lighting totally sucks (both PGraphics3 and PGraphicsGL)
-X bring in materials for opengl as well?
-X don't include a class, just make it similar to the light functions
-X sphere() and box() should set normals and take textures
-X background color seems to be wrong?
-X check this once lighting actually works
-X printarr() of null array crashes without an error
-X actually, errors from many crashes not coming through on the mac?
-
-
-0086 core
-X java 1.4 getButton() was inside the mouse handler
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1114147314;start=3
-X color() doesn't work properly because g might be null?
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1114518309;start=0
-X textMode(RIGHT) etc causing trouble.. tell ppl to use textAlign()
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Syntax;action=display;num=1114219121;start=4
-X saveFrame with a filename still causing trouble:
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1114097641;start=0
-X fov should be in radians
-X present mode not working on macosx 10.2?
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1114381302;start=0
-X ex on endshape if no calls to vertex
-X http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1113940972
-X is camera backwards, or staying fixed and moving the scene?
-X camera() is broken, should be ok to call it at beinning of loop
-X end of lookat might be backwards
-X or endCamera might be swapping camera and cameraInv
-X beginCamera also grabs it backwards
-
-
-0085 core
-X camera() was missing from PGraphics
-X some tweaks to openStream() for loading images and less errors
-X basic clipping in P3D from simon
-
-
-0084 core
-X fixed create font / incremented font file version number
-X simon lighting fixes
-X added simon's lighting docs to lights() fxn in javadoc
-X set default stroke cap as ROUND
-X otherwise smooth() makes points disappear
-X hack for text with a z coordinate
-
-
-0083 core
-X fix double key events
-X fix mrj.version security error on the pc
-X set() fixes for PGraphics2 and setImpl inside PGraphics
-X remove angleMode (also from PMatrix classes)
-X remove/rename postSetup() stuff from PGraphics/PApplet
-X camera(), perspective(), ortho()
-X matrix set by the camera on each beginFrame
-X push/pop are now pushMatrix/popMatrix
-o get PGraphics.java engine working again
-
-lighting stuff
-X make fill() cover ambient and diffuse
-X provide separate call for ambient to shut it off
-o why does diffuse just mirror fill()?
-o seems to cover just diffuse, not ambient_and_diffuse like fill
-o maybe fill() should set diffuse, and sep call to ambient() sets ambient?
-X removed it
-X move dot() to the bottom w/ the other math
-
-already done
-X remove PMethods as actual class, use recordFrame(PGraphics)
-X size(200, 200, "processing.illustrator.PGraphicsAI");
-
-api questions
-o image(String name) and textFont(String name)
-o do we change to font(arial, 12) ?
-X remove angleMode() ?
-X be consistent about getXxx() methods
-X just use the variable names.. don't do overkill on fillR et al
-X or just what functions are actually made public
-X is fillRi needed? it's pretty goofy..
-X how to handle full screen (opengl especially) or no screen (for scripts)
-
-tweaking up simong light code
-o what's up with resetLights?
-o add PLight object to avoid method overflow
-o preApplyMatrix, invApplyMatrix?
-o applyMatrixPre and applyMatrixIn
-o rotateXInv is ugly..
-o irotateX?, papplyMatrix?
-
-wednesday evening
-X expose api to launch files, folders, URLs
-X use with/in place of link()
-X call it open()
-X what to call firstMouse
-X implement rightMouse?
-X yes, mouseButton = LEFT, CENTER, or RIGHT
-X error when running on 1.1...
-X You need to install Java 1.3 or later to view this content.
-X Click here to visit java.com and install.
-X make inverseCamera into cameraInv
-X fix messages referring to depth()
-X route all of them through a single function rather than current waste
-X fix bezierVertex() in P3D for newer api
-
-wednesday late
-X track loadImage() with filenames that are inconsistent
-X really a problem with the ves61r kids
-X i.e. mixed case filename in sketch is different in windows
-X but when uploaded to a unix server causes a serious problem
-X use canonicalPath to flag possible problems
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1096508877;start=5
-o fix shapes in P3D (line loop, polygons, etc)
-o should we include a from and to for the directional light?
-X no, cuz it doesn't do much really..
-X fromX-toX etc is all that's different
-
-thursday day
-X set modelview to camera on endCamera
-X add ortho() and perspective() to PGraphics.java
-
-thursday evening
-o textMode(ALIGN_LEFT) etc, should make sure that left/center/right not used
-X though since have to change to LEFT, should be easy to switch
-
-friday night
-o should toInt('5') return the ascii or the char?
-X since (int) '5' returns the ascii, that's what it does
-X made a note in the PApplet reference
-
-text api
-X textMode ALIGN_CENTER _LEFT _RIGHT -> CENTER, LEFT, RIGHT ?
-X use built-in font if available? yes
-o text() with \n is semi-broken
-X does the font or PApplet control the size? (the font, ala java)
-X without setting the font, SCREEN_SPACE comes out weird
-o move SCREEN_SPACE into ScreenFont() class?
-o probably not, casey thinks screen space text is prolly more useful
-o that way can clear up some of the general confusion in the code
-X textFont with a named font can use the renderer/os font
-X illustrator api can get the ps name from the java font name
-X since it's associated with the font file.. wee!
-X for postscript, can grab the real font
-o altho problem here is that really the fonts just need a name
-o since needs to render to screen as well
-o font has to be installed to get psname
-X fine because why would you embed a ps font that you don't have?
-o need to resolve SCREEN_SPACE vs OBJECT_SPACE
-o can this be auto-detected with noDepth()?
-o how does rotated text work?
-o PFont.rotate(180) rotate(PI)
-o or can this be detected from the matrix?
-X don't use pixels to do screen space text inside PFont
-X add a function in PGraphics for direct pixel image impl
-X store the font name in the vlw font file (at the end)
-o could include multiple names for multi platforms
-X get text impl stuff working properly
-o look into fixing the texture mapping to not squash fonts
-o NEW_GRAPHICS totally smashes everything
-
-friday postgame
-X implement createFont()
-X with a .ttf does a create font internally (1.3+ only)
-X although the images aren't populated
-X until a P2D/P3D/OPENGL tries to draw them, which triggers it
-X but if PGraphics2, just uses the built-in font
-X also works for font names and just creating them
-X if font name doesn't end with otf or ttf, then tries to create it
-X change objectX/Y/Z to modelX/Y/Z
-X PFont.list() to return string list of all the available fonts
-X probably not a mode of use that we really want to encourage
-X actually important because the whole graphicsdevice crap is silly
-X and we need a 1.1 versus 1.3/1.4 version
-X implement printarr() as println() ?
-X actually deal with all the array types.. oy
-X should nf() handle commas as well?
-X just add a basic nfc() version for ints and floats
-o yes, and add nf(int what) so that non-padded version works
-o but don't put commas into the zero-padded version
-o make nf/nfs/nfp not so weird
-o nf(PLUS, ...) nf(PAD, ...) nfc(PLUS, ...)
-X unhex was broken for numbers bigger than 2^31
-
-saturday late afternoon
-X fix bug with openStream() and upper/lowercase stuff
-X do a better job of handling any kind of URLs in openStream()
-
-sunday morning
-X incorporate simon's new lighting code
-
-
-0082 core
-X make jdkVersion, jdkVersionName, platform, platformName variables
-X additional note about screen sizes and displays
-X sto instead of stop in present mode
-X appears that opengl libraries weren't correctly added in 81?
-X requestFocus() now called on gl canvas
-X basic lights now work by default
-
-
-0081 core
-X background(PImage) now works in opengl
-X when running externally, applets don't always get placed properly
-X if size is never set, then doesn't always layout
-X problem is in gl and in core, and is inconsistent
-X move more logic for layout into PApplet.. maybe a static method?
-X this way can avoid duplicating / breaking things
-o what is the stroked version of a sphere? a circle?
-X write list of params that can be passed to PApplet
-o document in the code a note about how size() et al place themselves
-X saveFrame was double-adding the save path because of save() changes
-
-size(200, 200, P3D) - createGraphics and placement issues
-X make pappletgl work back inside papplet
-X and then size(300, 300, DEPTH) etc
-X get rid of opengl renderer menu
-o otherwise hint() to use the p5 renderer instead of java2d
-X applet placement is screwy
-X how to force PGraphics() instead of PGraphics2()
-X size(300, 200, P2D);
-X size() doing a setBounds() is really bad
-X because it means things can't be embedded properly
-o applets on osx (and windows) sometimes show up 20 pixels off the top
-X how to shut off rendering to screen when illustrator in use?
-X need size(30000, 20000) for illustrator, problem in papplet
-X size(30000, 20000, ILLUSTRATOR)
-X make Graphics2 et al load dynamically using reflection
-X can this be done with g2 and if exception just falls back to g1?
-X this way people can remove g1 by hand
-o size() that changes renderer will throw nasty exception in draw()
-X or maybe that's ok? document that no changing renderers?
-X take a look to see what needs to happen to get PAppletGL merged in
-X i.e. can i just extend GLCanvas?
-
-present mode
-o call present() from inside the code?
-o that if applet is 500x500, centers on a 800x600 window
-X no, that's nasty... use --present to launch in present window
-X though how do you get the screen size?
-X screen.width and screen.height? - yes
-X write java 1.4 code for full screen version of PApplet
-X this might be used for presentation mode
-X proper full screen code for present mode
-X why do mouse motion events go away in full screen mode
-X or with a Window object
-X use screen manager to run present mode properly
-X set both versions to require java 1.4
-X change the Info.plist inside macosx
-X and add something to PdeBase to make sure that it's in 1.4
-X running present mode with a bug in the program hoses things
-X make sure the program compiles before starting present mode
-
-
-0080 core
-X PApplet.saveFrame() is saving to sketch folder, PApplet.save() is not
-X PApplet.save() will save to the applet folder,
-X but PImage.save() or PGraphics.save() will save only to the current
-X working directory, usually the Processing folder.
-X removed static version of mask() from PImage
-X no more PImage.mask(theImage, maskImage)
-X just use theImage.mask(maskImage)
-X PImage.filter()
-X maybe use quasimondo's gaussian blur code?
-X http://incubator.quasimondo.com/processing/gaussian_blur_1.php
-o filter() on subsections? yes, in keeping with rest of api
-X no, in keeping with getting shit done
-X BLUR - write simple blur
-X how does photoshop handle this?
-X BLUR - add gaussian blur
-X email re: credit/attribution and descrepancy between algos
-X forgot to mention the line hack to get points working in 78
-X implemented PGraphicsGL.set(x, y, argb)
-X implement PGraphicsGL.set(x, y, PImage)
-X blend, copy, filter all implemented for opengl
-X copy(Pimage, x, y) has become set(x, y, PImage)
-X textMode -> textAlign
-X ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT -> LEFT, CENTER, RIGHT
-X textSpace -> textMode
-X NORMAL_SPACE -> NORMALIZED, OBJECT_SPACE -> OBJECT
-X text in a box is broken (at least for PGraphics2)
-o check to see if it's a rounding error with width()
-o get text rect working again (seems to be in infinite loop)
-X nope, was just that the space width wasn't being scaled up properly
-X clean up the javadoc so no more errors
-X change mbox to PFont.size?
-o make width() return values based on natural size?
-X not a great idea.. plus java2d uses 1 pixel font for things
-X email simon re: lighting api
-X things are actually more on track than expected
-X camera is swapping colors in gl (on mac?)
-X in fact, all textures on mac were swapping colors
-X test this on windows to see if fixed
-X sphere x,y,z,r or box w,h,d.. need to make them consistent
-X goodbye sphere(x, y, z, r)
-o should available() be waiting() or something like that instead?
-o go through and see what functions (no pixel ops?) frame recorders should have
-X decided instead to use recordFrame(PGraphics)
-o remove SCREEN_SPACE altogether?
-X can't do this for now
-
-implemented in 79
-X make sure arc goes in the right direction that we want it to
-X (make sure that PGraphics3 goes the same direction)
-
-
-0079 core
-X no changes to core in this release
-
-
-0078 core
-X text fixes
-X lines were getting horizontally mashed together
-X lines also getting vertically smashed together
-X make a note of the change to font.width()
-X backwards rects and backwards ellipses weren't properly drawn
-X code now compensates for negative widths or swapped x1/x2
-X what to do about backwards images
-X imageMode() wasn't being set properly
-X fix noLoop() not properly running
-X If noLoop() is called in setup(), nothing is drawn to the screen.
-X also fix redraw() to include interrupt() again
-X loadPixels throwing NPEs
-X fixes to SCREEN_SPACE text not being sized properly
-X loadPixels()/updatePixels() on screen space text (ouch)
-X get SCREEN_SPACE text working again
-X patch in newer jogl.. too many BSODs
-X saveFrame seems to be broken
-X fixed for PGraphics2
-X fixed for PGraphicsGL
-X also implemented loadPixels/updatePixels for gl
-X fix tint() with color and alpha for PGraphics2
-X alpha() colors are inverted (white is opaque.. doesn't make sense)
-X should we swap this around? no - this is how photoshop works
-X fix arc
-X get() is back
-X set camera.modified so that it draws properly
-X it's annoying not having a copy() function inside PImage
-X formerly get() with no params
-o clone throws an exception
-o PImage constructor that takes itself?
-o PImage copy = new PImage(another);
-X got rid of CONCAVE_POLYGON and CONVEX_POLYGON
-X hack for points to work in opengl, but still not working broadly
-X work on filter() functions
-X POSTERIZE - find simple code that does it?
-X there must be a straightforward optimized version of it
-o EDGES - find edges in casey's example is differen than photoshop
-o which version do people want with their stuff
-X edges filter removed
-X several fixes to Movie and Camera to work with the new gfx model
-X PImage.get(x, y, w, h) had a bug when things went off the edge
-X set defaults for strokeCap and strokeJoin
-X get() and gl images were broken for screen sizes less than full size
-X fix arcs, were badly broken between java2d and pgraphics
-X look at curve functions more closely
-X should we switch to curveVertex(1,2,3) (ala curveto)
-X because some confusion with mixing types of curves
-o make sure we don't want curveVertices(1,2,3,u,v)
-o also make test cases so that java2d and java11 behave the same
-X implement PGraphics2.curveVertex()
-X updatePixels() not setting PApplet.pixels
-X make loadPixels in PGraphics ignored, and put it in PApplet
-X made loadStrings() and openStream(File) static again
-X test loadPixels()/updatePixels()/saveFrame() on the pc
-X better, just assume that they need the endian swap
-X fixed draw mode apps for opengl
-X (gl was missing a beginFrame)
-X pmouseX, pmouseY are not working in OpenGL mode
-X (as they are working in Processing mode)
-
-o screenX/Y aren't properly working for 2D points against a 3D matrix
-o (ryan alexander rounding bug)
-o Just to clarify, it works completely correctly with rounding
-o screenX/Y and also using the 3 arg version of translate -
-o ie translate(hw,hh,0) instead of just translate(hw,hh).
-X no longer an issue because moving to 2D and 3D modes
-o PImage: remove the static versions of manipulators?
-o probably not, because they're inherited by PApplet
-o i.e. mask(image, themask);
-X no PImage needed b/c PGraphics is a PImage
-o colorMode(GRAY) to avoid stroke(0) causing trouble?
-o or maybe get rid of stroke(0)? hrm
-
-
-0077 core
-X bring back pmouseX/Y using a tricky method of storing separate
-X values for inside draw() versus inside the event handler versions
-X debug handling, and make firstMouse public
-X explicitly state depth()/nodepth()
-X don't allocate zbuffer & stencil until depth() is called
-X arc with stroke only draws the arc shape itself
-X may need a 'wedge' function to draw a stroke around the whole thing
-X only allocate stencil and zbuffer on first call to depth()
-X this will require changes to PTriangle and PLine inside their loops
-X try running javadoc
-X die() may need to throw a RuntimeException
-o call filter() to convert RGB/RGBA/ALPHA/GRAY
-o cuz the cache is gonna be bad going rgb to rgba
-X don't bother, people can re-create the image or set cache null
-X fix font coloring in PGraphics2
-X fix tint() for PGraphics2
-X get text working again
-X partially the problem is with ALPHA images
-X how should they be stored internally
-X also colored text, requires tint() to work properly
-X move textMode and textSpace back out of PFont
-X use die() to fail in font situations
-X can't, just use a RuntimeException
-
-covered in previous
-X before graphics engine change, attach jogl stuff
-X need to try jogl to make sure no further changes
-X and the illustrator stuff
-o massive graphics engine changes
-o move to new graphics engine
-o test with rgb cube, shut off smoothing
-o make sure line artifacts are because of smoothing
-o implement 2x oversampling for anti-aliasing
-o renderers can plug in:
-o at direct api level
-o taking over all color() functions and vertex collection
-o at endShape() level
-o where vertices are collected by core and blit on endShape()
-o (takes polygons and lines)
-o at post tesselation level
-o takes only line segments and triangles to blit (dxf writer)
-o api for file-based renderers
-o need to work this out since it will affect other api changes
-o size(0, 0) and then ai.size(10000, 20000)
-o size 0 is code for internal to not show any window
-o saveFrame(PRenderer) or saveFrame("name", PRenderer)
-o saveFrame gets called at the beginning of loop()
-o or is just a message to save the next frame (problem for anim)
-X vertices max out at 512.. make it grow
-X add gzipInput and gzipOutput
-X light(x, y, z, c1, c2, c3, TYPE)
-X also BLight with same constructor, and on() and off() fxn
-X make sure applet is stopping in draw mode
-X loadImage() is broken on some machines
-X hacked for a fix in 72, but need to better coordinate with openStream()
-
-postscript
-X pushing all intelligence down into class that implements PMethods
-o keep hints about type of geometry used to reconstruct
-o no special class, just uses public vars from PGraphics
-o how to hook into curve rendering so that curve segments are drawn
-o maybe lines are rendered and sorted,
-o but they point to an original version of the curve geometry
-o that can be re-rendered
-o also integrate catmull-rom -> bezier inverse matrices
-o even with the general catmull-rom, to render via ai beziers
-
-api changes
-X removed circle.. it's dumb when ellipse() is in there
-X (it's not like we have square() in the api)
-X arcMode is gone.. just uses ellipseMode()
-X save tga and tif methods are static and public
-X imageMode(CORNER) and CORNERS are the only usable versions
-X alpha(PImage) is now called mask() instead
-X already have an alpha() function that gets alpha bits
-X on start, mouseX is 0.. how to avoid?
-X use firstMouse variable.. figure out naming
-X get frame recording working
-X not tested, but at least it's there
-
-image stuff
-o could also do PImage2, which would need a getPixels() before messing w/ it
-o bad idea, distinction not clear
-o even in java 1.1, could use regular java.awt.Image and require getPixels()
-o -> 1.1 wouldn't help anything, because needs pixels to render, oops
-X the updatePixels() in PGraphics has to be overridden (from PImage)
-X to make itself actually update on-screen
-X actually, should be no different than the check_image function
-X PGraphics2 and PGraphicsGL will need loadPixels() to be called
-X in order to read pixels from the buffer
-X loadPixels() and updatePixels() prolly should be shut off in opengl
-X make people use get() instead to grab sub-images
-X PGraphicsGL.copy() needs to be overridden.. use glDrawBitmap
-o loadImage() needs to handle 1.1 vs 1.3 loading
-o set image.format to be BUFFERED? no.. just use RGBA always
-o have a flag to always use the cache, i.e. with BufferedImage
-o turn that off when someone modifies it (nope, no need to)
-X PImage.getPixels(), updatePixels(), updatePixels(x, y, w, h),
-o PImage.setPixels(int another[]);
-X imageMode(CENTER) is weird for copy() and updatePixels()
-X perhaps copy() and get() ignore imageMode and use xywh or x1y1x2y2?
-X or disallow imageMode(CENTER) altogether?
-o in java 1.3, getPixels() can call getRGB() via reflection
-o cache.getClass().getName().equals("BufferedImage")
-X readPixels/writePixels?
-X has to happen, since this is so fundamental to gl as well
-X loadImage in 1.3 leaves pixels[] null (not in 1.1)
-X 1.3 plus gl is a problem, since conflicting caches
-X gl has no need for a bufferedimage tho
-X so maybe checks to see if the cache is a BufferedImage
-X if it is, calls getPixels to set the int array
-X then replaces cache with glimageache
-X pappletgl loadimage could take care of this instead
-X calls super.loadImage(), if cache != null, proceed..
-X this is prolly a mess
-X PImage.getPixels() and PImage.getPixels(x, y, w, h) ->
-X (the xywh version still allocates the entire array, but only updates those)
-X only needed for java2d
-X not (necessarily) needed when loading images,
-X but definitely needed when setting pixels on PGraphics
-X PImage.updatePixels() and PImage.updatePixels(x, y, w, h)
-X (this is actually just setModified)
-X in opengl, marks all or some as modified
-X so next time it's drawn, the texture is updated PGraphicsGL.image()
-X in java2d, updates the BufferedImage on next draw
-X can't use regular getPixels() on PGraphics, because its image isn't 'cache'
-X also, the cache may be used to draw the whole surface as a gl texture (?)
-X not a problem for the main PGraphics, but for any others created to draw on
-
-opengl
-X make light() functions actually do something in PGraphicsGL
-X box() and sphere() working again
-X make opengl work in draw mode
-X set initial size using --size=
-X color channels seem to be swapped on windows in image example
-X check on the mac to see what it looks like
-
-X default to single byte input from serial port
-X and add serial.setBuffer() for message length as alternative
-X or serial.setDelimiter() to fire message on delim
-X named it bufferUntil();
-
-
-0076 core
-X no changes, only launcher issues
-
-
-0075
-X textureMode(NORMAL_SPACE) screws up the image() command
-X image() appears to require IMAGE_SPACE to function properly.
-X added focusGained() and focusLost()
-X lots of changes to internal naming of vars
-X screenX(x, y) and screenY(x, y) added for noDepth()
-X add TRIANGLE_FAN
-X eyeX, eyeY etc have been renamed cameraX/Y/Z, and cameraNear/Far
-X modify targa and tiff writing routines to break into header writing
-X writeTIFF, writeHeaderTIFF, writeTGA, writeHeaderTGA
-X MAJOR CHANGE: RGBA becomes ARGB for accuracy
-o uv coords > 1 shouldn't clamp, they should just repeat ala opengl
-o actually i think opengl has a setting for it
-o remove need to use depth() at the beginning
-X need only be set once
-X pmouseX is broken again
-X remove pmouseX/Y altogether
-X maintain things a bit different
-o email the beta@ list to see how people are using pmouseX
-X changed PMovie.length to PMovie.duration
-X move around/simplify loadImage() inside PApplet
-X working to add more die() statements inside PApplet
-o can ALPHA fonts work using the other replace modes?
-
-fixed in previous releases
-X text stuff
-X text() with alignment doesn't work for multiple lines
-X don't change the size of a font when in screen space mode
-X patch rotated text (from visualclusto) into bfont
-X what sort of api? textSpace(ROTATED) ?
-X rotated text has a bug for when it goes offscreen
-
-opengl
-X why is the thing hanging until 'stop' is hit?
-X what happens when stop is hit that sets it free?
-X (at what point does it start working properly?)
-X cache needs to also make things a power of 2
-X if images are already a power of 2, then needn't re-alloc
-X cacheIndex needs to be set to -1 when the image is modified
-X or maybe have a modified() function?
-X debug why certain spots are having errors (see 'problem here' notes)
-X INVALID_OPERATION after drawing lines for cube
-X fix noLoop bug
-X remove errors when drawing textures
-X reverse y coordinates
-X make play button un-highlight with opengl
-X also make window move messages work properly
-X very necessary, since opens window at 100x100
-X problem was the threading issues
-X bring back renderer menu
-X reading/saving pref for opengl renderer
-X remove cameraMode(PERSPECTIVE) on each frame
-X why is the first one failing?
-X still threading issues with running opengl
-X threading really horks up dual processor machine..
-X first run hangs until quit
-X though doesn't seem to replicate when p5 is restarted
-X make sure background() gets called at least once with opengl
-X otherwise screen never actually updates
-X beginFrame() around setup()
-X draw mode stuff happens inside setup..
-o or maybe need to get better at size() inside of draw() ?
-X make this consistent with the regular PApplet
-X otherwise things are going to be weird/difficult for debugging
-
-
-0074 core
-X removed zbuffer precision hack in PLine to improve z ordering
-X no longer set g.dimensions = 3 when using vertex(x, y, 0)
-
-
-0073 core
-X tweak to fonts to use TEXT_ANTIALIAS because of macosx @#$(*&
-X loadImage() is broken on some machines
-X hacked for a fix in 72, but need to better coordinate with openStream()
-
-
-0072 core
-X make m00, m01 etc public
-X hack to make loadImage() work
-X cache settings are ignored, may be slow as hell
-X make hints[] no longer static
-X they weren't properly resetting
-
-
-0071 core
-X properly swap alpha values when lines need to be rendered backwards
-X make cursor() commands public
-X ltext and rtext for screen space stuff
-X ltext is broken when it goes y < 0 or y > height
-X ltext & rtext completely working
-X make sure font creator is making fonts properly fixed width
-X probably not using java charwidth for the char's width
-X probably wasn't using textFont() properly
-X now that it's actually a key, should it be a char? (what's keyChar?)
-X that way println(c) would work a little better..
-X libraryCalls() not properly working for pre, post, or draw()
-o image(myg, x, y) doesn't work but image(myg, x, y, w, h) does
-o (image kind prolly not set right and so image() gets pissy)
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1091798655
-
-text fixes
-X make text rect use rectMode for placement
-X if a word (no spaces) is too long to fit, insert a 'space'
-X move left/center/right aligning into the font class
-X otherwise text with alignment has problems with returns
-X could PFont2 be done entirely with reflection?
-X that way other font types can properly extend PFont
-o font char widths from orator were not fixed width
-o may just need to regenerate. if not, widths may be set wrong.
-
-
-0070 core
-o check ordering of split() in java vs perl for regexp
-X don't include empty chars in font builder
-X .vlw font files are enormous with full charset
-X check to see if the character exists before adding it to the font
-X fixed (unreported) problem with char lookup code
-o split() with multiple args (i think this is completed)
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Syntax;action=display;num=1078985667
-X trim() not chop().. whups
-X random(5, 5) -> return 5, random(6, 4) return error
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1083275855;start=0
-X use random.nextFloat() because it's faster
-X make grayscale image in p5
-X could be used with alpha() to properly set alpha values
-X made into filter(GRAYSCALE) and filter(BLACK_WHITE) functions
-X make g.depthTest settable as a hint
-X http://processing.org/discourse/yabb/YaBB.cgi?board=BugFixes;action=display;num=1096303102;start=0
-X #ifdef to remove client and server code as well
-X need to resolve issues between rendering screen/file
-X illustrator-based rendering needs to work for ars projects
-X screen may be 400x400 pixels, but file be 36x36"
-X launcher.cpp broke serial.. see versions in processing.notcvs
-X rewrite bagel code..
-X for this release, because it will break things along with the lib stuff
-X switch to PImage, PApplet, etc
-o bug in BImage.smooth() when resizing an image
-o http://processing.org/discourse/yabb/YaBB.cgi?board=BugFixes;action=display;num=1096303158;start=0
-X shut off the automatic gunzipping of streams, keep for fonts
-X fix for duplicated points in polygons that foiled the tesselator
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1077819175
-X cleaned up texture() code between NEW/OLD graphics
-X not quite so much duplicated in cases etc.
-X lines: vertex coloring bug with my swap hack
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1085348942
-X last vertex on LINE_LOOP fades out
-X http://processing.org/discourse/yabb/YaBB.cgi?board=BugFixes;action=display;num=1096303406;start=0
-X include values in PConstants for additional blend modes:
-X DIFFERENCE, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT
-X include a lerp()? is there one in flash?
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Programs;action=display;num=1083289030
-X should it be called lerp or mix?
-X acos, asin, atan, log, exp, ceil/floor, pow, mag(x,y,z)
-X color issues
-X doesn't work when outside a function:
-X color bg_color = color(255,0,0);
-X colorMode broken for red() green() etc
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1068664455
-X add color(gray) and color(gray, alpha)
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1089898189;start=0
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_Software;action=display;num=1090133107
-o update() mode needs to be hacked in (?)
-X make 'online' a boolean
-X pass in args[] from main
-X angleMode(DEGREES) and angleMode(RADIANS)
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_Software;action=display;num=1075507381;start=0
-X fixes to line and curve code
-X api to properly sense when applet has focus
-X add a 'focused' variable to the applet
-X code now in zipdecode, maybe just list this as a standard thing?
-X do applets know when they're stopped? stop? dispose?
-X would be good to set a param in p5 so that the thread dies
-X if people have other threads they've spawned, impossible to stop
-
-cleaning up
-X make bagel more usable as standalone
-X breakout BGraphics (have its own BImage)
-o breakout BApplet into BComponent ? (fix out-of-bounds mouse - doesn't)
-o opengl export / rendering mode
-o currently implemented, but somewhat broken
-o finish this once all the line code is done
-o make possible to use buzz.pl to create versions w/ stuff removed
-o build gl4java for java 1.4
-o separating of BGraphics and BApplet
-o change copyrights on the files again (to match ?)
-X loadStrings has a problem with URLs and a code folder
-o turned out to be a problem with firewall/antivirus software
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1086551792
-o when running as an applet, need to loadStream from documentBase too
-o problem is that BGraphics has the loadStream code, not BApplet
-o new sphere code from toxi
-o already added a while back
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Syntax;action=display;num=1067005325
-o sphere code needs only front face polygon
-o all triangles must be counter-clockwise (front-facing)
-X fix loadImage to be inside PApplet
-
-040715
-X saveFrame() to a folder horks things up if a mkdirs() is required
-X on macosx, this makes things hang; on windows it complains
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1081706752;start=0
-X decide on whether to use PTools
-X decided against, since it doesn't help anything
-X and some functions need the applet object, so it's just annoying
-o i.e. move math functions into utility library
-o check what other functions require PGraphics to exist but shouldn't
-o look at BGraphics to see if setting an 'applet' could be used
-o then other than that, if no applet set, no connection to PApplet
-
-040716
-X change font api to not use leading() as a way to reset the leading
-X resetLeading and resetSize are the things
-X embed all available chars from a font, so japanese, etc works
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_Software;action=display;num=1083598817;start=3
-X fix a bunch of font bugs regarding charsets and lookup
-X array operations: boolean, byte, char, int, float, String
-X expand/contract
-X append, shorten
-o shift/unshift
-o slice
-X splice
-X reverse
-X concat
-
-040717
-X make clone() into copy()
-X add a method BApplet.setPath() or something like that
-X use it to repair saveBytes, saveStrings, etc
-X put screenshots into their sketch folder
-o http://processing.org/discourse/yabb/YaBB.cgi?board=Syntax;action=display;num=1046185738;start=0
-X full casting operations on primitives and arrays of them
-X text(String text, x, y, width, height) // based on rectMode
-X textMode() for align left, center, right (no justify.. har!)
-X hex(), binary(), unhex(), unbinary()
-
-040725
-X fix array functions not returning a value
-
-040726
-X noiseSeed and randomSeed
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_Software;action=display;num=1090749784;start=0
-
-040727
-X incorporated NO_FLYING_POO line/poly hack developed for axel
-
-040902
-X sort() should return an array, rather than sort in place
-X fix binary function, had wrong offset number
-X casey: i wan't able to get binary() to work at all:
-o Typography: Helix won't compile
-o works fine, just needs BFont -> PFont
-X standalone 'alpha' function for PImage (static methods for alpha fxns)
-X Image: Edge, Image: Blur: Alpha not set? The error is easier to see on Blur
-X turns out bounds checking wasn't working properly on colors
-
-040903
-X fix mouse/key events, make properly public for the package stuff
-X The biggest problem was the key and mouse functions not working.
-X Input: Mouse_Functions
-X Input: Keyboard_Functions
-X processing.net -> PClient, PServer
-X write client/server implementations for new-style api
-X basic test with old net server has things working fine
-
-040908
-X inputFile, outputFile, reader, writer commands
-X also loadStrings(File file)
-
-040913
-X printarr instead of print/println for arrays
-X println(Object o) conflicts with println(int a[])
-X but println(Object o) is very needed
-
-040919
-X loop/noLoop setup
-
-040920
-X make loop/noLoop work properly
-X fixes/changes to key and mousehandling
-X tab key not working?
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1091853942;start=0
-X mousePressed, keyPressed, others.. queue them all
-X queue multiple times
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Syntax;action=display;num=1079555200;start=0
-X strangeness with key codes on keyPressed
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Syntax;action=display;num=1083406438;start=0
-X key codes not properly coming through for UP/DOWN/etc
-X had to bring back keyCode
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1075138932;start=0
-X add redraw() function
-X call redraw() on the first time through (to force initial draw)
-X otherwise noLoop() in setup means no drawing happens at all
-
-040920 evening
-X defaults for PApplet and PGraphics are different
-o PGraphics has none.. PApplet has fill/stroke
-X actually not the case, only that wasn't calling decent superclass
-X set PImage.format as RGB by default?
-X this was problem with rendering an image from PGraphics on board
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1091798655;start=0
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Syntax;action=display;num=1080671926;start=0
-
-040921 morning
-X bug in get() that was removing the high bits (rather than adding)
-
-040921 evening
-X lots of work on libraries, figuring out PLibrary api
-
-040922
-X get library stuff debugged
-X port arcball and finish up dxf writer
-X beginCamera() no longer sets an identity matrix
-
-040925
-X make savePath() and createPath() accessible to the outside world
-X useful for libraries saving files etc.
-
-
-0070p8
-X sizing bug fix to fonts, they now match platform standards
-X however, *this will break people's code*
-X text in a box not written
-X make sure to note in the docs that text/textrect position differently
-o for this reason, should it be called textrect()?
-X font heights and leading are bad
-X get good values for ascent and descent
-X if ScreenFont subclasses PFont.. can that be used in textFont()?
-X check to make sure the tops of fonts not getting chopped in font builder
-
-
-0069 bagel
-X text(x, y, z)
-X fixed camera modes / replaced how isometric is handled
-X whoa.. BGraphics.screenX() et al had the camera stuff shut off
-X and that's what shipped in 67. shite.
-X need to get things fixed up properly so camera is properly set
-X ISOMETRIC was completely broken.. need to implement properly
-X also, the default camera is perspective
-X cameraMode(PERSPECTIVE) and cameraMode(ORTHOGRAPHIC) setup basic cameras
-X if the user wants a custom camera, call cameraMode(CUSTOM); before begin()
-X printMatrix() and printCamera() to output the matrices for each
-X more functions made static (loadStrings, loadBytes) that could be
-X print() commands in BApplet were among these
-X die() command to exit an application or just stall out an applet
-X die(String error) and die(String error, Exception e)
-X more documentation in comments for functions
-X chop() function that properly also handles nbsp
-X join() was handled weird
-X run nf() and nfs() on arrays
-X nfp() to show plus sign
-X toInt, toFloat, toDouble (nf is for toString.. inconsistent)
-o split() function splits strings instead of splitStrings()
-o ints() converts an array of strings/doubles/floats to an int array
-o split() should also use StringTokenizer
-o to do countTokens() and then stuff into an array
-o shave() or chomp() or trim() method to remove whitespace on either side
-o including unicode nbsp
-X min() and max() with three values were broken (now fixed)
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1076804172
-X CONTROL wasn't properly set in BConstants
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1077058788
-X macosx.. flickering several times on startup
-X fixed this, along with other sluggishness related threading issues
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1073111031
-X bug with charset table on older fonts
-X index_hunt was look through the table, not what was in the font
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1077475307;start=0
-X seems to be some difficult threading problems still present
-X fixed many threading issues across macosx and linux
-X side-porting changes
-X new(er) line code is not in the main 'processing'
-X making perlin non-static not in the main bagel
-X polygon stroking hack code from the end of 68
-X erikb found a bug inside split(), it would die on empty strings
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1077664736
-X fixed it, also modified behavior of split() with a delimeter
-X previously, it would remove the final delimeter and an empty entry
-X but that's now disabled, since the split cmd is very specific
-X code from toxi to support .tga files in loadImage
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Programs;action=display;num=1078459847;start=0
-X fix bug where single pixel points were ignoring their alpha values
-X static loadStrings and loadBytes aren't being added to BApplet
-X (the versions that use an inputstream)
-X added support for handling static functions in make.pl
-X threading is broken again on windows
-X windows needs a sleep(1) instead of the yield()
-X random(3) should be non-inclusive of the 3
-X http://processing.org/discourse/yabb/YaBB.cgi?board=Syntax;action=display;num=1079935258;start=5
-
-api changes
-X loadStream -> openStream for better consistency
-
-jdf
-X dynamic loading of code for setting cursor (removed JDK13 ifdef)
-X why aren't cursors working on the mac?
-X fix from jdf to just set size to 0,0
diff --git a/core/license.txt b/core/license.txt
deleted file mode 100644
index 16f1ad1629d..00000000000
--- a/core/license.txt
+++ /dev/null
@@ -1,456 +0,0 @@
- GNU LESSER GENERAL PUBLIC LICENSE
- Version 2.1, February 1999
-
- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-[ This is the first released version of the Lesser GPL.
- It also counts as the successor of the GNU Library Public
- License, version 2, hence the version number 2.1. ]
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-Licenses are intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-
- This license, the Lesser General Public License, applies to some
-specially designated software packages--typically libraries--of the
-Free Software Foundation and other authors who decide to use it. You
-can use it too, but we suggest you first think carefully about whether
-this license or the ordinary General Public License is the better
-strategy to use in any particular case, based on the explanations below.
-
- When we speak of free software, we are referring to freedom of use,
-not price. Our General Public Licenses are designed to make sure that
-you have the freedom to distribute copies of free software (and charge
-for this service if you wish); that you receive source code or can get
-it if you want it; that you can change the software and use pieces of
-it in new free programs; and that you are informed that you can do
-these things.
-
- To protect your rights, we need to make restrictions that forbid
-distributors to deny you these rights or to ask you to surrender these
-rights. These restrictions translate to certain responsibilities for
-you if you distribute copies of the library or if you modify it.
-
- For example, if you distribute copies of the library, whether gratis
-or for a fee, you must give the recipients all the rights that we gave
-you. You must make sure that they, too, receive or can get the source
-code. If you link other code with the library, you must provide
-complete object files to the recipients, so that they can relink them
-with the library after making changes to the library and recompiling
-it. And you must show them these terms so they know their rights.
-
- We protect your rights with a two-step method: (1) we copyright the
-library, and (2) we offer you this license, which gives you legal
-permission to copy, distribute and/or modify the library.
-
- To protect each distributor, we want to make it very clear that
-there is no warranty for the free library. Also, if the library is
-modified by someone else and passed on, the recipients should know
-that what they have is not the original version, so that the original
-author's reputation will not be affected by problems that might be
-introduced by others.
-
- Finally, software patents pose a constant threat to the existence of
-any free program. We wish to make sure that a company cannot
-effectively restrict the users of a free program by obtaining a
-restrictive license from a patent holder. Therefore, we insist that
-any patent license obtained for a version of the library must be
-consistent with the full freedom of use specified in this license.
-
- Most GNU software, including some libraries, is covered by the
-ordinary GNU General Public License. This license, the GNU Lesser
-General Public License, applies to certain designated libraries, and
-is quite different from the ordinary General Public License. We use
-this license for certain libraries in order to permit linking those
-libraries into non-free programs.
-
- When a program is linked with a library, whether statically or using
-a shared library, the combination of the two is legally speaking a
-combined work, a derivative of the original library. The ordinary
-General Public License therefore permits such linking only if the
-entire combination fits its criteria of freedom. The Lesser General
-Public License permits more lax criteria for linking other code with
-the library.
-
- We call this license the "Lesser" General Public License because it
-does Less to protect the user's freedom than the ordinary General
-Public License. It also provides other free software developers Less
-of an advantage over competing non-free programs. These disadvantages
-are the reason we use the ordinary General Public License for many
-libraries. However, the Lesser license provides advantages in certain
-special circumstances.
-
- For example, on rare occasions, there may be a special need to
-encourage the widest possible use of a certain library, so that it becomes
-a de-facto standard. To achieve this, non-free programs must be
-allowed to use the library. A more frequent case is that a free
-library does the same job as widely used non-free libraries. In this
-case, there is little to gain by limiting the free library to free
-software only, so we use the Lesser General Public License.
-
- In other cases, permission to use a particular library in non-free
-programs enables a greater number of people to use a large body of
-free software. For example, permission to use the GNU C Library in
-non-free programs enables many more people to use the whole GNU
-operating system, as well as its variant, the GNU/Linux operating
-system.
-
- Although the Lesser General Public License is Less protective of the
-users' freedom, it does ensure that the user of a program that is
-linked with the Library has the freedom and the wherewithal to run
-that program using a modified version of the Library.
-
- The precise terms and conditions for copying, distribution and
-modification follow. Pay close attention to the difference between a
-"work based on the library" and a "work that uses the library". The
-former contains code derived from the library, whereas the latter must
-be combined with the library in order to run.
-
- GNU LESSER GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License Agreement applies to any software library or other
-program which contains a notice placed by the copyright holder or
-other authorized party saying it may be distributed under the terms of
-this Lesser General Public License (also called "this License").
-Each licensee is addressed as "you".
-
- A "library" means a collection of software functions and/or data
-prepared so as to be conveniently linked with application programs
-(which use some of those functions and data) to form executables.
-
- The "Library", below, refers to any such software library or work
-which has been distributed under these terms. A "work based on the
-Library" means either the Library or any derivative work under
-copyright law: that is to say, a work containing the Library or a
-portion of it, either verbatim or with modifications and/or translated
-straightforwardly into another language. (Hereinafter, translation is
-included without limitation in the term "modification".)
-
- "Source code" for a work means the preferred form of the work for
-making modifications to it. For a library, complete source code means
-all the source code for all modules it contains, plus any associated
-interface definition files, plus the scripts used to control compilation
-and installation of the library.
-
- Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running a program using the Library is not restricted, and output from
-such a program is covered only if its contents constitute a work based
-on the Library (independent of the use of the Library in a tool for
-writing it). Whether that is true depends on what the Library does
-and what the program that uses the Library does.
-
- 1. You may copy and distribute verbatim copies of the Library's
-complete source code as you receive it, in any medium, provided that
-you conspicuously and appropriately publish on each copy an
-appropriate copyright notice and disclaimer of warranty; keep intact
-all the notices that refer to this License and to the absence of any
-warranty; and distribute a copy of this License along with the
-Library.
-
- You may charge a fee for the physical act of transferring a copy,
-and you may at your option offer warranty protection in exchange for a
-fee.
-
- 2. You may modify your copy or copies of the Library or any portion
-of it, thus forming a work based on the Library, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) The modified work must itself be a software library.
-
- b) You must cause the files modified to carry prominent notices
- stating that you changed the files and the date of any change.
-
- c) You must cause the whole of the work to be licensed at no
- charge to all third parties under the terms of this License.
-
- d) If a facility in the modified Library refers to a function or a
- table of data to be supplied by an application program that uses
- the facility, other than as an argument passed when the facility
- is invoked, then you must make a good faith effort to ensure that,
- in the event an application does not supply such function or
- table, the facility still operates, and performs whatever part of
- its purpose remains meaningful.
-
- (For example, a function in a library to compute square roots has
- a purpose that is entirely well-defined independent of the
- application. Therefore, Subsection 2d requires that any
- application-supplied function or table used by this function must
- be optional: if the application does not supply it, the square
- root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Library,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Library, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote
-it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library
-with the Library (or with a work based on the Library) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may opt to apply the terms of the ordinary GNU General Public
-License instead of this License to a given copy of the Library. To do
-this, you must alter all the notices that refer to this License, so
-that they refer to the ordinary GNU General Public License, version 2,
-instead of to this License. (If a newer version than version 2 of the
-ordinary GNU General Public License has appeared, then you can specify
-that version instead if you wish.) Do not make any other change in
-these notices.
-
- Once this change is made in a given copy, it is irreversible for
-that copy, so the ordinary GNU General Public License applies to all
-subsequent copies and derivative works made from that copy.
-
- This option is useful when you wish to copy part of the code of
-the Library into a program that is not a library.
-
- 4. You may copy and distribute the Library (or a portion or
-derivative of it, under Section 2) in object code or executable form
-under the terms of Sections 1 and 2 above provided that you accompany
-it with the complete corresponding machine-readable source code, which
-must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange.
-
- If distribution of object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the
-source code from the same place satisfies the requirement to
-distribute the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 5. A program that contains no derivative of any portion of the
-Library, but is designed to work with the Library by being compiled or
-linked with it, is called a "work that uses the Library". Such a
-work, in isolation, is not a derivative work of the Library, and
-therefore falls outside the scope of this License.
-
- However, linking a "work that uses the Library" with the Library
-creates an executable that is a derivative of the Library (because it
-contains portions of the Library), rather than a "work that uses the
-library". The executable is therefore covered by this License.
-Section 6 states terms for distribution of such executables.
-
- When a "work that uses the Library" uses material from a header file
-that is part of the Library, the object code for the work may be a
-derivative work of the Library even though the source code is not.
-Whether this is true is especially significant if the work can be
-linked without the Library, or if the work is itself a library. The
-threshold for this to be true is not precisely defined by law.
-
- If such an object file uses only numerical parameters, data
-structure layouts and accessors, and small macros and small inline
-functions (ten lines or less in length), then the use of the object
-file is unrestricted, regardless of whether it is legally a derivative
-work. (Executables containing this object code plus portions of the
-Library will still fall under Section 6.)
-
- Otherwise, if the work is a derivative of the Library, you may
-distribute the object code for the work under the terms of Section 6.
-Any executables containing that work also fall under Section 6,
-whether or not they are linked directly with the Library itself.
-
- 6. As an exception to the Sections above, you may also combine or
-link a "work that uses the Library" with the Library to produce a
-work containing portions of the Library, and distribute that work
-under terms of your choice, provided that the terms permit
-modification of the work for the customer's own use and reverse
-engineering for debugging such modifications.
-
- You must give prominent notice with each copy of the work that the
-Library is used in it and that the Library and its use are covered by
-this License. You must supply a copy of this License. If the work
-during execution displays copyright notices, you must include the
-copyright notice for the Library among them, as well as a reference
-directing the user to the copy of this License. Also, you must do one
-of these things:
-
- a) Accompany the work with the complete corresponding
- machine-readable source code for the Library including whatever
- changes were used in the work (which must be distributed under
- Sections 1 and 2 above); and, if the work is an executable linked
- with the Library, with the complete machine-readable "work that
- uses the Library", as object code and/or source code, so that the
- user can modify the Library and then relink to produce a modified
- executable containing the modified Library. (It is understood
- that the user who changes the contents of definitions files in the
- Library will not necessarily be able to recompile the application
- to use the modified definitions.)
-
- b) Use a suitable shared library mechanism for linking with the
- Library. A suitable mechanism is one that (1) uses at run time a
- copy of the library already present on the user's computer system,
- rather than copying library functions into the executable, and (2)
- will operate properly with a modified version of the library, if
- the user installs one, as long as the modified version is
- interface-compatible with the version that the work was made with.
-
- c) Accompany the work with a written offer, valid for at
- least three years, to give the same user the materials
- specified in Subsection 6a, above, for a charge no more
- than the cost of performing this distribution.
-
- d) If distribution of the work is made by offering access to copy
- from a designated place, offer equivalent access to copy the above
- specified materials from the same place.
-
- e) Verify that the user has already received a copy of these
- materials or that you have already sent this user a copy.
-
- For an executable, the required form of the "work that uses the
-Library" must include any data and utility programs needed for
-reproducing the executable from it. However, as a special exception,
-the materials to be distributed need not include anything that is
-normally distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies
-the executable.
-
- It may happen that this requirement contradicts the license
-restrictions of other proprietary libraries that do not normally
-accompany the operating system. Such a contradiction means you cannot
-use both them and the Library together in an executable that you
-distribute.
-
- 7. You may place library facilities that are a work based on the
-Library side-by-side in a single library together with other library
-facilities not covered by this License, and distribute such a combined
-library, provided that the separate distribution of the work based on
-the Library and of the other library facilities is otherwise
-permitted, and provided that you do these two things:
-
- a) Accompany the combined library with a copy of the same work
- based on the Library, uncombined with any other library
- facilities. This must be distributed under the terms of the
- Sections above.
-
- b) Give prominent notice with the combined library of the fact
- that part of it is a work based on the Library, and explaining
- where to find the accompanying uncombined form of the same work.
-
- 8. You may not copy, modify, sublicense, link with, or distribute
-the Library except as expressly provided under this License. Any
-attempt otherwise to copy, modify, sublicense, link with, or
-distribute the Library is void, and will automatically terminate your
-rights under this License. However, parties who have received copies,
-or rights, from you under this License will not have their licenses
-terminated so long as such parties remain in full compliance.
-
- 9. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Library or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Library (or any work based on the
-Library), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Library or works based on it.
-
- 10. Each time you redistribute the Library (or any work based on the
-Library), the recipient automatically receives a license from the
-original licensor to copy, distribute, link with or modify the Library
-subject to these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties with
-this License.
-
- 11. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Library at all. For example, if a patent
-license would not permit royalty-free redistribution of the Library by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under any
-particular circumstance, the balance of the section is intended to apply,
-and the section as a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 12. If the distribution and/or use of the Library is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Library under this License may add
-an explicit geographical distribution limitation excluding those countries,
-so that distribution is permitted only in or among countries not thus
-excluded. In such case, this License incorporates the limitation as if
-written in the body of this License.
-
- 13. The Free Software Foundation may publish revised and/or new
-versions of the Lesser General Public License from time to time.
-Such new versions will be similar in spirit to the present version,
-but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Library
-specifies a version number of this License which applies to it and
-"any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation. If the Library does not specify a
-license version number, you may choose any version ever published by
-the Free Software Foundation.
-
- 14. If you wish to incorporate parts of the Library into other free
-programs whose distribution conditions are incompatible with these,
-write to the author to ask for permission. For software which is
-copyrighted by the Free Software Foundation, write to the Free
-Software Foundation; we sometimes make exceptions for this. Our
-decision will be guided by the two goals of preserving the free status
-of all derivatives of our free software and of promoting the sharing
-and reuse of software generally.
-
- NO WARRANTY
-
- 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
-KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
-THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
-FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
-CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
-LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
-FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
-SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES.
\ No newline at end of file
diff --git a/core/make.sh b/core/make.sh
deleted file mode 100755
index 78d91b33aa4..00000000000
--- a/core/make.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/bin/sh
-
-#javadoc -public -d doc *.java
-#javadoc -private -d doc *.java
-chmod +x preproc.pl
-./preproc.pl
-jikes -d . +D *.java
diff --git a/core/methods/.classpath b/core/methods/.classpath
deleted file mode 100644
index d9132e9f49e..00000000000
--- a/core/methods/.classpath
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
diff --git a/core/methods/.project b/core/methods/.project
deleted file mode 100644
index 629f1c16a34..00000000000
--- a/core/methods/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
- preproc
-
-
-
-
-
- org.eclipse.jdt.core.javabuilder
-
-
-
-
-
- org.eclipse.jdt.core.javanature
-
-
diff --git a/core/methods/build.xml b/core/methods/build.xml
deleted file mode 100644
index c37b243eba2..00000000000
--- a/core/methods/build.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/core/methods/demo/PApplet.java b/core/methods/demo/PApplet.java
deleted file mode 100644
index b2a09c1bb13..00000000000
--- a/core/methods/demo/PApplet.java
+++ /dev/null
@@ -1,9483 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2004-10 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, version 2.1.
-
- 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.applet.*;
-import java.awt.*;
-import java.awt.event.*;
-import java.awt.image.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.text.*;
-import java.util.*;
-import java.util.regex.*;
-import java.util.zip.*;
-
-import javax.imageio.ImageIO;
-import javax.swing.JFileChooser;
-import javax.swing.SwingUtilities;
-
-import processing.core.PShape;
-
-
-/**
- * Base class for all sketches that use processing.core.
- *
- * Note that you should not use AWT or Swing components inside a Processing
- * applet. The surface is made to automatically update itself, and will cause
- * problems with redraw of components drawn above it. If you'd like to
- * integrate other Java components, see below.
- *
- * As of release 0145, Processing uses active mode rendering in all cases.
- * All animation tasks happen on the "Processing Animation Thread". The
- * setup() and draw() methods are handled by that thread, and events (like
- * mouse movement and key presses, which are fired by the event dispatch
- * thread or EDT) are queued to be (safely) handled at the end of draw().
- * For code that needs to run on the EDT, use SwingUtilities.invokeLater().
- * When doing so, be careful to synchronize between that code (since
- * invokeLater() will make your code run from the EDT) and the Processing
- * animation thread. Use of a callback function or the registerXxx() methods
- * in PApplet can help ensure that your code doesn't do something naughty.
- *
- * As of release 0136 of Processing, we have discontinued support for versions
- * of Java prior to 1.5. We don't have enough people to support it, and for a
- * project of our size, we should be focusing on the future, rather than
- * working around legacy Java code. In addition, Java 1.5 gives us access to
- * better timing facilities which will improve the steadiness of animation.
- *
- * This class extends Applet instead of JApplet because 1) historically,
- * we supported Java 1.1, which does not include Swing (without an
- * additional, sizable, download), and 2) Swing is a bloated piece of crap.
- * A Processing applet is a heavyweight AWT component, and can be used the
- * same as any other AWT component, with or without Swing.
- *
- * Similarly, Processing runs in a Frame and not a JFrame. However, there's
- * nothing to prevent you from embedding a PApplet into a JFrame, it's just
- * that the base version uses a regular AWT frame because there's simply
- * no need for swing in that context. If people want to use Swing, they can
- * embed themselves as they wish.
- *
- * It is possible to use PApplet, along with core.jar in other projects.
- * In addition to enabling you to use Java 1.5+ features with your sketch,
- * this also allows you to embed a Processing drawing area into another Java
- * application. This means you can use standard GUI controls with a Processing
- * sketch. Because AWT and Swing GUI components cannot be used on top of a
- * PApplet, you can instead embed the PApplet inside another GUI the way you
- * would any other Component.
- *
- * It is also possible to resize the Processing window by including
- * frame.setResizable(true) inside your setup() method.
- * Note that the Java method frame.setSize() will not work unless
- * you first set the frame to be resizable.
- *
- * Because the default animation thread will run at 60 frames per second,
- * an embedded PApplet can make the parent sluggish. You can use frameRate()
- * to make it update less often, or you can use noLoop() and loop() to disable
- * and then re-enable looping. If you want to only update the sketch
- * intermittently, use noLoop() inside setup(), and redraw() whenever
- * the screen needs to be updated once (or loop() to re-enable the animation
- * thread). The following example embeds a sketch and also uses the noLoop()
- * and redraw() methods. You need not use noLoop() and redraw() when embedding
- * if you want your application to animate continuously.
- *
- * 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();
- * }
- * }
- *
- *
- *
Processing on multiple displays
- *
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;
- }
- }
-
- /**
- * 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 future releases need to be better
- * at handling multiple displays.
- */
- 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.
- *
Advanced:
- * If running on Mac OS, a ctrl-click will be interpreted as
- * the righthand mouse button (unlike Java, which reports it as
- * the left mouse).
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mousePressed()
- * @see PApplet#mouseReleased()
- * @see PApplet#mouseMoved()
- * @see PApplet#mouseDragged()
- */
- public int mouseButton;
-
- /**
- * Variable storing if a mouse button is pressed. The value of the system variable mousePressed is true if a mouse button is pressed and false if a button is not pressed.
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mouseReleased()
- * @see PApplet#mouseMoved()
- * @see PApplet#mouseDragged()
- */
- public boolean mousePressed;
- public MouseEvent mouseEvent;
-
- /**
- * The system variable key always contains the value of the most recent key on the keyboard that was used (either pressed or released).
- * For non-ASCII keys, use the keyCode variable.
- * 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.
- * =advanced
- *
- * Last key 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()");
-
- // 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) {
- 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.
- * Do not use variables as the parameters to size() command, because it will cause problems when exporting your sketch. When variables are used, the dimensions of your sketch cannot be determined during export. Instead, employ numeric values in the size() statement, and then use the built-in width and height variables inside your program when you need the dimensions of the display window are needed.
- * The MODE parameters selects which rendering engine to use. For example, if you will be drawing 3D shapes for the web use P3D, if you want to export a program with OpenGL graphics acceleration use OPENGL. A brief description of the four primary renderers follows:
JAVA2D - The default renderer. This renderer supports two dimensional drawing and provides higher image quality in overall, but generally slower than P2D.
P2D (Processing 2D) - Fast 2D renderer, best used with pixel data, but not as accurate as the JAVA2D default.
P3D (Processing 3D) - Fast 3D renderer for the web. Sacrifices rendering quality for quick 3D drawing.
OPENGL - High speed 3D graphics renderer that makes use of OpenGL-compatible graphics hardware is available. Keep in mind that OpenGL is not magic pixie dust that makes any sketch faster (though it's close), so other rendering options may produce better results depending on the nature of your code. Also note that with OpenGL, all graphics are smoothed: the smooth() and noSmooth() commands are ignored.
PDF - The PDF renderer draws 2D graphics directly to an Acrobat PDF file. This produces excellent results when you need vector shapes for high resolution output or printing. You must first use Import Library → PDF to make use of the library. More information can be found in the PDF library reference.
- * If you're manipulating pixels (using methods like get() or blend(), or manipulating the pixels[] array), P2D and P3D will usually be faster than the default (JAVA2D) setting, and often the OPENGL setting as well. Similarly, when handling lots of images, or doing video playback, P2D and P3D will tend to be faster.
- * The P2D, P3D, and OPENGL renderers do not support strokeCap() or strokeJoin(), which can lead to ugly results when using strokeWeight(). (Bug 955)
- * For the most elegant and accurate results when drawing in 2D, particularly when using smooth(), use the JAVA2D renderer setting. It may be slower than the others, but is the most complete, which is why it's the default. Advanced users will want to switch to other renderers as they learn the tradeoffs.
- * Rendering graphics requires tradeoffs between speed, accuracy, and general usefulness of the available features. None of the renderers are perfect, so we provide multiple options so that you can decide what tradeoffs make the most sense for your project. We'd prefer all of them to have perfect visual accuracy, high performance, and support a wide range of features, but that's simply not possible.
- * The maximum width and height is limited by your operating system, and is usually the width and height of your actual screen. On some machines it may simply be the number of pixels on your current screen, meaning that a screen that's 800x600 could support size(1600, 300), since it's the same number of pixels. This varies widely so you'll have to try different rendering modes and sizes until you get what you're looking for. If you need something larger, use createGraphics to create a non-visible drawing surface.
- *
Again, the size() method must be the first line of the code (or first item inside setup). Any code that appears before the size() command may run more than once, which can lead to confusing results.
- *
- * =advanced
- * Starts up and creates a two-dimensional drawing surface,
- * or resizes the current drawing surface.
- *
- * 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.
- *
- *
Do not use "new PGraphicsXxxx()", use this method. This method
- * ensures that internal variables are set up properly that tie the
- * new graphics context back to its parent PApplet.
- *
The basic way to create bitmap images is to use the saveFrame()
- * function.
- *
If you want to create a really large scene and write that,
- * first make sure that you've allocated a lot of memory in the Preferences.
- *
If you want to create images that are larger than the screen,
- * you should create your own PGraphics object, draw to that, and use
- * save().
- * For now, it's best to use P3D in this scenario.
- * P2D is currently disabled, and the JAVA2D default will give mixed
- * results. An example of using P3D:
- *
- *
- * 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");
- * }
- *
- *
- *
It's important to always wrap drawing to createGraphics() with
- * beginDraw() and endDraw() (beginFrame() and endFrame() prior to
- * revision 0115). The reason is that the renderer needs to know when
- * drawing has stopped, so that it can update itself internally.
- * This also handles calling the defaults() method, for people familiar
- * with that.
- *
It's not possible to use createGraphics() with the OPENGL renderer,
- * because it doesn't allow offscreen use.
- *
With Processing 0115 and later, it's possible to write images in
- * formats other than the default .tga and .tiff. The exact formats and
- * background information can be found in the developer's reference for
- * PImage.save().
- *
- *
- * @webref rendering
- * @param iwidth width in pixels
- * @param iheight height in pixels
- * @param irenderer Either P2D (not yet implemented), P3D, JAVA2D, PDF, DXF
- *
- * @see processing.core.PGraphics
- *
- */
- public PGraphics createGraphics(int iwidth, int iheight,
- String irenderer) {
- PGraphics pg = makeGraphics(iwidth, iheight, irenderer, null, false);
- //pg.parent = this; // make save() work
- return pg;
- }
-
-
- /**
- * Create an offscreen graphics surface for drawing, in this case
- * for a renderer that writes to a file (such as PDF or DXF).
- * @param ipath the name of the file (can be an absolute or relative path)
- */
- public PGraphics createGraphics(int iwidth, int iheight,
- String irenderer, String ipath) {
- if (ipath != null) {
- ipath = savePath(ipath);
- }
- PGraphics pg = makeGraphics(iwidth, iheight, irenderer, ipath, false);
- pg.parent = this; // make save() work
- return pg;
- }
-
-
- /**
- * Version of createGraphics() used internally.
- *
- * @param ipath must be an absolute path, usually set via savePath()
- * @oaram applet the parent applet object, this should only be non-null
- * in cases where this is the main drawing surface object.
- */
- protected PGraphics makeGraphics(int iwidth, int iheight,
- String irenderer, String ipath,
- boolean iprimary) {
- if (irenderer.equals(OPENGL)) {
- if (PApplet.platform == WINDOWS) {
- String s = System.getProperty("java.version");
- if (s != null) {
- if (s.equals("1.5.0_10")) {
- System.err.println("OpenGL support is broken with Java 1.5.0_10");
- System.err.println("See http://dev.processing.org" +
- "/bugs/show_bug.cgi?id=513 for more info.");
- throw new RuntimeException("Please update your Java " +
- "installation (see bug #513)");
- }
- }
- }
- }
-
-// if (irenderer.equals(P2D)) {
-// throw new RuntimeException("The P2D renderer is currently disabled, " +
-// "please use P3D or JAVA2D.");
-// }
-
- String openglError =
- "Before using OpenGL, first select " +
- "Import Library > opengl from the Sketch menu.";
-
- try {
- /*
- Class> rendererClass = Class.forName(irenderer);
-
- Class> constructorParams[] = null;
- Object constructorValues[] = null;
-
- if (ipath == null) {
- constructorParams = new Class[] {
- Integer.TYPE, Integer.TYPE, PApplet.class
- };
- constructorValues = new Object[] {
- new Integer(iwidth), new Integer(iheight), this
- };
- } else {
- constructorParams = new Class[] {
- Integer.TYPE, Integer.TYPE, PApplet.class, String.class
- };
- constructorValues = new Object[] {
- new Integer(iwidth), new Integer(iheight), this, ipath
- };
- }
-
- Constructor> constructor =
- rendererClass.getConstructor(constructorParams);
- PGraphics pg = (PGraphics) constructor.newInstance(constructorValues);
- */
-
- Class> rendererClass =
- Thread.currentThread().getContextClassLoader().loadClass(irenderer);
-
- //Class> params[] = null;
- //PApplet.println(rendererClass.getConstructors());
- Constructor> constructor = rendererClass.getConstructor(new Class[] { });
- PGraphics pg = (PGraphics) constructor.newInstance();
-
- pg.setParent(this);
- pg.setPrimary(iprimary);
- if (ipath != null) pg.setPath(ipath);
- pg.setSize(iwidth, iheight);
-
- // everything worked, return it
- return pg;
-
- } catch (InvocationTargetException ite) {
- String msg = ite.getTargetException().getMessage();
- if ((msg != null) &&
- (msg.indexOf("no jogl in java.library.path") != -1)) {
- throw new RuntimeException(openglError +
- " (The native library is missing.)");
-
- } else {
- ite.getTargetException().printStackTrace();
- Throwable target = ite.getTargetException();
- if (platform == MACOSX) target.printStackTrace(System.out); // bug
- // neither of these help, or work
- //target.printStackTrace(System.err);
- //System.err.flush();
- //System.out.println(System.err); // and the object isn't null
- throw new RuntimeException(target.getMessage());
- }
-
- } catch (ClassNotFoundException cnfe) {
- if (cnfe.getMessage().indexOf("processing.opengl.PGraphicsGL") != -1) {
- throw new RuntimeException(openglError +
- " (The library .jar file is missing.)");
- } else {
- throw new RuntimeException("You need to use \"Import Library\" " +
- "to add " + irenderer + " to your sketch.");
- }
-
- } catch (Exception e) {
- //System.out.println("ex3");
- if ((e instanceof IllegalArgumentException) ||
- (e instanceof NoSuchMethodException) ||
- (e instanceof IllegalAccessException)) {
- e.printStackTrace();
- /*
- String msg = "public " +
- irenderer.substring(irenderer.lastIndexOf('.') + 1) +
- "(int width, int height, PApplet parent" +
- ((ipath == null) ? "" : ", String filename") +
- ") does not exist.";
- */
- String msg = irenderer + " needs to be updated " +
- "for the current release of Processing.";
- throw new RuntimeException(msg);
-
- } else {
- if (platform == MACOSX) e.printStackTrace(System.out);
- throw new RuntimeException(e.getMessage());
- }
- }
- }
-
-
- /**
- * Creates a new PImage (the datatype for storing images). This provides a fresh buffer of pixels to play with. Set the size of the buffer with the width and height parameters. The format parameter defines how the pixels are stored. See the PImage reference for more information.
- *
Be sure to include all three parameters, specifying only the width and height (but no format) will produce a strange error.
- *
Advanced users please note that createImage() should be used instead of the syntax new PImage().
- * =advanced
- * Preferred method of creating new PImage objects, ensures that a
- * reference to the parent PApplet is included, which makes save() work
- * without needing an absolute path.
- *
- * @webref image
- * @param wide width in pixels
- * @param high height in pixels
- * @param format Either RGB, ARGB, ALPHA (grayscale alpha channel)
- *
- * @see processing.core.PImage
- * @see processing.core.PGraphics
- */
- public PImage createImage(int wide, int high, int format) {
- PImage image = new PImage(wide, high, format);
- image.parent = this; // make save() work
- return image;
- }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- public void update(Graphics screen) {
- paint(screen);
- }
-
-
- //synchronized public void paint(Graphics screen) { // shutting off for 0146
- public void paint(Graphics screen) {
- // ignore the very first call to paint, since it's coming
- // from the o.s., and the applet will soon update itself anyway.
- if (frameCount == 0) {
-// println("Skipping frame");
- // paint() may be called more than once before things
- // are finally painted to the screen and the thread gets going
- return;
- }
-
- // without ignoring the first call, the first several frames
- // are confused because paint() gets called in the midst of
- // the initial nextFrame() call, so there are multiple
- // updates fighting with one another.
-
- // g.image is synchronized so that draw/loop and paint don't
- // try to fight over it. this was causing a randomized slowdown
- // that would cut the frameRate into a third on macosx,
- // and is probably related to the windows sluggishness bug too
-
- // make sure the screen is visible and usable
- // (also prevents over-drawing when using PGraphicsOpenGL)
- if ((g != null) && (g.image != null)) {
-// println("inside paint(), screen.drawImage()");
- screen.drawImage(g.image, 0, 0, null);
- }
- }
-
-
- // active paint method
- protected void paint() {
- try {
- Graphics screen = this.getGraphics();
- if (screen != null) {
- if ((g != null) && (g.image != null)) {
- screen.drawImage(g.image, 0, 0, null);
- }
- Toolkit.getDefaultToolkit().sync();
- }
- } catch (Exception e) {
- // Seen on applet destroy, maybe can ignore?
- e.printStackTrace();
-
-// } finally {
-// if (g != null) {
-// g.dispose();
-// }
- }
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- /**
- * Main method for the primary animation thread.
- *
- * Painting in AWT and Swing
- */
- public void run() { // not good to make this synchronized, locks things up
- long beforeTime = System.nanoTime();
- long overSleepTime = 0L;
-
- int noDelays = 0;
- // Number of frames with a delay of 0 ms before the
- // animation thread yields to other running threads.
- final int NO_DELAYS_PER_YIELD = 15;
-
- /*
- // this has to be called after the exception is thrown,
- // otherwise the supporting libs won't have a valid context to draw to
- Object methodArgs[] =
- new Object[] { new Integer(width), new Integer(height) };
- sizeMethods.handle(methodArgs);
- */
-
- while ((Thread.currentThread() == thread) && !finished) {
- // Don't resize the renderer from the EDT (i.e. from a ComponentEvent),
- // otherwise it may attempt a resize mid-render.
- if (resizeRequest) {
- resizeRenderer(resizeWidth, resizeHeight);
- resizeRequest = false;
- }
-
- // render a single frame
- handleDraw();
-
- if (frameCount == 1) {
- // Call the request focus event once the image is sure to be on
- // screen and the component is valid. The OpenGL renderer will
- // request focus for its canvas inside beginDraw().
- // http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html
- //println("requesting focus");
- requestFocus();
- }
-
- // wait for update & paint to happen before drawing next frame
- // this is necessary since the drawing is sometimes in a
- // separate thread, meaning that the next frame will start
- // before the update/paint is completed
-
- long afterTime = System.nanoTime();
- long timeDiff = afterTime - beforeTime;
- //System.out.println("time diff is " + timeDiff);
- long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime;
-
- if (sleepTime > 0) { // some time left in this cycle
- try {
-// Thread.sleep(sleepTime / 1000000L); // nanoseconds -> milliseconds
- Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L));
- noDelays = 0; // Got some sleep, not delaying anymore
- } catch (InterruptedException ex) { }
-
- overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
- //System.out.println(" oversleep is " + overSleepTime);
-
- } else { // sleepTime <= 0; the frame took longer than the period
-// excess -= sleepTime; // store excess time value
- overSleepTime = 0L;
-
- if (noDelays > NO_DELAYS_PER_YIELD) {
- Thread.yield(); // give another thread a chance to run
- noDelays = 0;
- }
- }
-
- beforeTime = System.nanoTime();
- }
-
- stop(); // call to shutdown libs?
-
- // If the user called the exit() function, the window should close,
- // rather than the sketch just halting.
- if (exitCalled) {
- exit2();
- }
- }
-
-
- //synchronized public void handleDisplay() {
- public void handleDraw() {
- if (g != null && (looping || redraw)) {
- if (!g.canDraw()) {
- // Don't draw if the renderer is not yet ready.
- // (e.g. OpenGL has to wait for a peer to be on screen)
- return;
- }
-
- //System.out.println("handleDraw() " + frameCount);
-
- g.beginDraw();
- if (recorder != null) {
- recorder.beginDraw();
- }
-
- long now = System.nanoTime();
-
- if (frameCount == 0) {
- try {
- //println("Calling setup()");
- setup();
- //println("Done with setup()");
-
- } catch (RendererChangeException e) {
- // Give up, instead set the new renderer and re-attempt setup()
- return;
- }
- this.defaultSize = false;
-
- } else { // frameCount > 0, meaning an actual draw()
- // update the current frameRate
- double rate = 1000000.0 / ((now - frameRateLastNanos) / 1000000.0);
- float instantaneousRate = (float) rate / 1000.0f;
- frameRate = (frameRate * 0.9f) + (instantaneousRate * 0.1f);
-
- preMethods.handle();
-
- // use dmouseX/Y as previous mouse pos, since this is the
- // last position the mouse was in during the previous draw.
- pmouseX = dmouseX;
- pmouseY = dmouseY;
-
- //println("Calling draw()");
- draw();
- //println("Done calling draw()");
-
- // dmouseX/Y is updated only once per frame (unlike emouseX/Y)
- dmouseX = mouseX;
- dmouseY = mouseY;
-
- // these are called *after* loop so that valid
- // drawing commands can be run inside them. it can't
- // be before, since a call to background() would wipe
- // out anything that had been drawn so far.
- dequeueMouseEvents();
- dequeueKeyEvents();
-
- drawMethods.handle();
-
- redraw = false; // unset 'redraw' flag in case it was set
- // (only do this once draw() has run, not just setup())
-
- }
-
- g.endDraw();
- if (recorder != null) {
- recorder.endDraw();
- }
-
- frameRateLastNanos = now;
- frameCount++;
-
- // Actively render the screen
- paint();
-
-// repaint();
-// getToolkit().sync(); // force repaint now (proper method)
-
- postMethods.handle();
- }
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
-
- synchronized public void redraw() {
- if (!looping) {
- redraw = true;
-// if (thread != null) {
-// // wake from sleep (necessary otherwise it'll be
-// // up to 10 seconds before update)
-// if (CRUSTY_THREADS) {
-// thread.interrupt();
-// } else {
-// synchronized (blocker) {
-// blocker.notifyAll();
-// }
-// }
-// }
- }
- }
-
-
- synchronized public void loop() {
- if (!looping) {
- looping = true;
- }
- }
-
-
- synchronized public void noLoop() {
- if (looping) {
- looping = false;
- }
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- public void addListeners() {
- addMouseListener(this);
- addMouseMotionListener(this);
- addKeyListener(this);
- addFocusListener(this);
-
- addComponentListener(new ComponentAdapter() {
- public void componentResized(ComponentEvent e) {
- Component c = e.getComponent();
- //System.out.println("componentResized() " + c);
- Rectangle bounds = c.getBounds();
- resizeRequest = true;
- resizeWidth = bounds.width;
- resizeHeight = bounds.height;
- }
- });
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- MouseEvent mouseEventQueue[] = new MouseEvent[10];
- int mouseEventCount;
-
- protected void enqueueMouseEvent(MouseEvent e) {
- synchronized (mouseEventQueue) {
- if (mouseEventCount == mouseEventQueue.length) {
- MouseEvent temp[] = new MouseEvent[mouseEventCount << 1];
- System.arraycopy(mouseEventQueue, 0, temp, 0, mouseEventCount);
- mouseEventQueue = temp;
- }
- mouseEventQueue[mouseEventCount++] = e;
- }
- }
-
- protected void dequeueMouseEvents() {
- synchronized (mouseEventQueue) {
- for (int i = 0; i < mouseEventCount; i++) {
- mouseEvent = mouseEventQueue[i];
- handleMouseEvent(mouseEvent);
- }
- mouseEventCount = 0;
- }
- }
-
-
- /**
- * Actually take action based on a mouse event.
- * Internally updates mouseX, mouseY, mousePressed, and mouseEvent.
- * Then it calls the event type with no params,
- * i.e. mousePressed() or mouseReleased() that the user may have
- * overloaded to do something more useful.
- */
- protected void handleMouseEvent(MouseEvent event) {
- int id = event.getID();
-
- // http://dev.processing.org/bugs/show_bug.cgi?id=170
- // also prevents mouseExited() on the mac from hosing the mouse
- // position, because x/y are bizarre values on the exit event.
- // see also the id check below.. both of these go together
- if ((id == MouseEvent.MOUSE_DRAGGED) ||
- (id == MouseEvent.MOUSE_MOVED)) {
- pmouseX = emouseX;
- pmouseY = emouseY;
- mouseX = event.getX();
- mouseY = event.getY();
- }
-
- mouseEvent = event;
-
- int modifiers = event.getModifiers();
- if ((modifiers & InputEvent.BUTTON1_MASK) != 0) {
- mouseButton = LEFT;
- } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
- mouseButton = CENTER;
- } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
- mouseButton = RIGHT;
- }
- // if running on macos, allow ctrl-click as right mouse
- if (platform == MACOSX) {
- if (mouseEvent.isPopupTrigger()) {
- mouseButton = RIGHT;
- }
- }
-
- mouseEventMethods.handle(new Object[] { event });
-
- // this used to only be called on mouseMoved and mouseDragged
- // change it back if people run into trouble
- if (firstMouse) {
- pmouseX = mouseX;
- pmouseY = mouseY;
- dmouseX = mouseX;
- dmouseY = mouseY;
- firstMouse = false;
- }
-
- //println(event);
-
- switch (id) {
- case MouseEvent.MOUSE_PRESSED:
- mousePressed = true;
- mousePressed();
- break;
- case MouseEvent.MOUSE_RELEASED:
- mousePressed = false;
- mouseReleased();
- break;
- case MouseEvent.MOUSE_CLICKED:
- mouseClicked();
- break;
- case MouseEvent.MOUSE_DRAGGED:
- mouseDragged();
- break;
- case MouseEvent.MOUSE_MOVED:
- mouseMoved();
- break;
- }
-
- if ((id == MouseEvent.MOUSE_DRAGGED) ||
- (id == MouseEvent.MOUSE_MOVED)) {
- emouseX = mouseX;
- emouseY = mouseY;
- }
- }
-
-
- /**
- * Figure out how to process a mouse event. When loop() has been
- * called, the events will be queued up until drawing is complete.
- * If noLoop() has been called, then events will happen immediately.
- */
- protected void checkMouseEvent(MouseEvent event) {
- if (looping) {
- enqueueMouseEvent(event);
- } else {
- handleMouseEvent(event);
- }
- }
-
-
- /**
- * If you override this or any function that takes a "MouseEvent e"
- * without calling its super.mouseXxxx() then mouseX, mouseY,
- * mousePressed, and mouseEvent will no longer be set.
- */
- public void mousePressed(MouseEvent e) {
- checkMouseEvent(e);
- }
-
- public void mouseReleased(MouseEvent e) {
- checkMouseEvent(e);
- }
-
- public void mouseClicked(MouseEvent e) {
- checkMouseEvent(e);
- }
-
- public void mouseEntered(MouseEvent e) {
- checkMouseEvent(e);
- }
-
- public void mouseExited(MouseEvent e) {
- checkMouseEvent(e);
- }
-
- public void mouseDragged(MouseEvent e) {
- checkMouseEvent(e);
- }
-
- public void mouseMoved(MouseEvent e) {
- checkMouseEvent(e);
- }
-
-
- /**
- * The mousePressed() function is called once after every time a mouse button is pressed. The mouseButton variable (see the related reference entry) can be used to determine which button has been pressed.
- * =advanced
- *
- * If you must, use
- * int button = mouseEvent.getButton();
- * to figure out which button was clicked. It will be one of:
- * MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3
- * Note, however, that this is completely inconsistent across
- * platforms.
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mousePressed
- * @see PApplet#mouseReleased()
- * @see PApplet#mouseMoved()
- * @see PApplet#mouseDragged()
- */
- public void mousePressed() { }
-
- /**
- * The mouseReleased() function is called every time a mouse button is released.
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mousePressed
- * @see PApplet#mousePressed()
- * @see PApplet#mouseMoved()
- * @see PApplet#mouseDragged()
- */
- public void mouseReleased() { }
-
- /**
- * The mouseClicked() function is called once after a mouse button has been pressed and then released.
- * =advanced
- * When the mouse is clicked, mousePressed() will be called,
- * then mouseReleased(), then mouseClicked(). Note that
- * mousePressed is already false inside of mouseClicked().
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mouseButton
- * @see PApplet#mousePressed()
- * @see PApplet#mouseReleased()
- * @see PApplet#mouseMoved()
- * @see PApplet#mouseDragged()
- */
- public void mouseClicked() { }
-
- /**
- * The mouseDragged() function is called once every time the mouse moves and a mouse button is pressed.
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mousePressed
- * @see PApplet#mousePressed()
- * @see PApplet#mouseReleased()
- * @see PApplet#mouseMoved()
- */
- public void mouseDragged() { }
-
- /**
- * The mouseMoved() function is called every time the mouse moves and a mouse button is not pressed.
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mousePressed
- * @see PApplet#mousePressed()
- * @see PApplet#mouseReleased()
- * @see PApplet#mouseDragged()
- */
- public void mouseMoved() { }
-
-
- //////////////////////////////////////////////////////////////
-
-
- KeyEvent keyEventQueue[] = new KeyEvent[10];
- int keyEventCount;
-
- protected void enqueueKeyEvent(KeyEvent e) {
- synchronized (keyEventQueue) {
- if (keyEventCount == keyEventQueue.length) {
- KeyEvent temp[] = new KeyEvent[keyEventCount << 1];
- System.arraycopy(keyEventQueue, 0, temp, 0, keyEventCount);
- keyEventQueue = temp;
- }
- keyEventQueue[keyEventCount++] = e;
- }
- }
-
- protected void dequeueKeyEvents() {
- synchronized (keyEventQueue) {
- for (int i = 0; i < keyEventCount; i++) {
- keyEvent = keyEventQueue[i];
- handleKeyEvent(keyEvent);
- }
- keyEventCount = 0;
- }
- }
-
-
- protected void handleKeyEvent(KeyEvent event) {
- keyEvent = event;
- key = event.getKeyChar();
- keyCode = event.getKeyCode();
-
- keyEventMethods.handle(new Object[] { event });
-
- switch (event.getID()) {
- case KeyEvent.KEY_PRESSED:
- keyPressed = true;
- keyPressed();
- break;
- case KeyEvent.KEY_RELEASED:
- keyPressed = false;
- keyReleased();
- break;
- case KeyEvent.KEY_TYPED:
- keyTyped();
- break;
- }
-
- // if someone else wants to intercept the key, they should
- // set key to zero (or something besides the ESC).
- if (event.getID() == KeyEvent.KEY_PRESSED) {
- if (key == KeyEvent.VK_ESCAPE) {
- exit();
- }
- // When running tethered to the Processing application, respond to
- // Ctrl-W (or Cmd-W) events by closing the sketch. Disable this behavior
- // when running independently, because this sketch may be one component
- // embedded inside an application that has its own close behavior.
- if (external &&
- event.getModifiers() == MENU_SHORTCUT &&
- event.getKeyCode() == 'W') {
- exit();
- }
- }
- }
-
-
- protected void checkKeyEvent(KeyEvent event) {
- if (looping) {
- enqueueKeyEvent(event);
- } else {
- handleKeyEvent(event);
- }
- }
-
-
- /**
- * Overriding keyXxxxx(KeyEvent e) functions will cause the 'key',
- * 'keyCode', and 'keyEvent' variables to no longer work;
- * key events will no longer be queued until the end of draw();
- * and the keyPressed(), keyReleased() and keyTyped() methods
- * will no longer be called.
- */
- public void keyPressed(KeyEvent e) { checkKeyEvent(e); }
- public void keyReleased(KeyEvent e) { checkKeyEvent(e); }
- public void keyTyped(KeyEvent e) { checkKeyEvent(e); }
-
-
- /**
- *
- * The keyPressed() function is called once every time a key is pressed. The key that was pressed is stored in the key variable.
- *
For non-ASCII keys, use the keyCode variable.
- * 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.
Because of how operating systems handle key repeats, holding down a key may cause multiple calls to keyPressed() (and keyReleased() as well).
- * The rate of repeat is set by the operating system and how each computer is configured.
- * =advanced
- *
- * Called each time a single key on the keyboard is pressed.
- * Because of how operating systems handle key repeats, holding
- * down a key will cause multiple calls to keyPressed(), because
- * the OS repeat takes over.
- *
- * 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).
- *
- * The args parameter is a String or String array which is passed to the command line. If you have multiple parameters, e.g. an application and a document, or a command with multiple switches, use the version that takes a String array, and place each individual item in a separate element.
- *
- * If args is a String (not an array), then it can only be a single file or application with no parameters. It's not the same as executing that String using a shell. For instance, open("jikes -help") will not work properly.
- *
- * This function behaves differently on each platform. On Windows, the parameters are sent to the Windows shell via "cmd /c". On Mac OS X, the "open" command is used (type "man open" in Terminal.app for documentation). On Linux, it first tries gnome-open, then kde-open, but if neither are available, it sends the command to the shell without any alterations.
- *
- * For users familiar with Java, this is not quite the same as Runtime.exec(), because the launcher command is prepended. Instead, the exec(String[]) function is a shortcut for Runtime.getRuntime.exec(String[]).
- *
- * @webref input:files
- * @param filename name of the file
- * @usage Application
- */
- static public void open(String filename) {
- open(new String[] { filename });
- }
-
-
- static String openLauncher;
-
- /**
- * Launch a process using a platforms shell. This version uses an array
- * to make it easier to deal with spaces in the individual elements.
- * (This avoids the situation of trying to put single or double quotes
- * around different bits).
- *
- * @param list of commands passed to the command line
- */
- static public Process open(String argv[]) {
- String[] params = null;
-
- if (platform == WINDOWS) {
- // just launching the .html file via the shell works
- // but make sure to chmod +x the .html files first
- // also place quotes around it in case there's a space
- // in the user.dir part of the url
- params = new String[] { "cmd", "/c" };
-
- } else if (platform == MACOSX) {
- params = new String[] { "open" };
-
- } else if (platform == LINUX) {
- if (openLauncher == null) {
- // Attempt to use gnome-open
- try {
- Process p = Runtime.getRuntime().exec(new String[] { "gnome-open" });
- /*int result =*/ p.waitFor();
- // Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04)
- openLauncher = "gnome-open";
- } catch (Exception e) { }
- }
- if (openLauncher == null) {
- // Attempt with kde-open
- try {
- Process p = Runtime.getRuntime().exec(new String[] { "kde-open" });
- /*int result =*/ p.waitFor();
- openLauncher = "kde-open";
- } catch (Exception e) { }
- }
- if (openLauncher == null) {
- System.err.println("Could not find gnome-open or kde-open, " +
- "the open() command may not work.");
- }
- if (openLauncher != null) {
- params = new String[] { openLauncher };
- }
- //} else { // give up and just pass it to Runtime.exec()
- //open(new String[] { filename });
- //params = new String[] { filename };
- }
- if (params != null) {
- // If the 'open', 'gnome-open' or 'cmd' are already included
- if (params[0].equals(argv[0])) {
- // then don't prepend those params again
- return exec(argv);
- } else {
- params = concat(params, argv);
- return exec(params);
- }
- } else {
- return exec(argv);
- }
- }
-
-
- static public Process exec(String[] argv) {
- try {
- return Runtime.getRuntime().exec(argv);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("Could not open " + join(argv, ' '));
- }
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- /**
- * Function for an applet/application to kill itself and
- * display an error. Mostly this is here to be improved later.
- */
- public void die(String what) {
- stop();
- throw new RuntimeException(what);
- }
-
-
- /**
- * Same as above but with an exception. Also needs work.
- */
- public void die(String what, Exception e) {
- if (e != null) e.printStackTrace();
- die(what);
- }
-
-
- /**
- * Call to safely exit the sketch when finished. For instance,
- * to render a single frame, save it, and quit.
- */
- public void exit() {
- if (thread == null) {
- // exit immediately, stop() has already been called,
- // meaning that the main thread has long since exited
- exit2();
-
- } else if (looping) {
- // stop() will be called as the thread exits
- finished = true;
- // tell the code to call exit2() to do a System.exit()
- // once the next draw() has completed
- exitCalled = true;
-
- } else if (!looping) {
- // if not looping, need to call stop explicitly,
- // because the main thread will be sleeping
- stop();
-
- // now get out
- exit2();
- }
- }
-
-
- void exit2() {
- try {
- System.exit(0);
- } catch (SecurityException e) {
- // don't care about applet security exceptions
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
-
- public void method(String name) {
-// final Object o = this;
-// final Class> c = getClass();
- try {
- Method method = getClass().getMethod(name, new Class[] {});
- method.invoke(this, new Object[] { });
-
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.getTargetException().printStackTrace();
- } catch (NoSuchMethodException nsme) {
- System.err.println("There is no public " + name + "() method " +
- "in the class " + getClass().getName());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
- public void thread(final String name) {
- Thread later = new Thread() {
- public void run() {
- method(name);
- }
- };
- later.start();
- }
-
-
- /*
- public void thread(String name) {
- final Object o = this;
- final Class> c = getClass();
- try {
- final Method method = c.getMethod(name, new Class[] {});
- Thread later = new Thread() {
- public void run() {
- try {
- method.invoke(o, new Object[] { });
-
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.getTargetException().printStackTrace();
- }
- }
- };
- later.start();
-
- } catch (NoSuchMethodException nsme) {
- System.err.println("There is no " + name + "() method " +
- "in the class " + getClass().getName());
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- */
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SCREEN GRABASS
-
-
- /**
- * Intercepts any relative paths to make them absolute (relative
- * to the sketch folder) before passing to save() in PImage.
- * (Changed in 0100)
- */
- public void save(String filename) {
- g.save(savePath(filename));
- }
-
-
- /**
- * Grab an image of what's currently in the drawing area and save it
- * as a .tif or .tga file.
- *
- * 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<>= 1;
- }
-
- if (x<0) x=-x;
- if (y<0) y=-y;
- if (z<0) z=-z;
-
- int xi=(int)x, yi=(int)y, zi=(int)z;
- float xf = (float)(x-xi);
- float yf = (float)(y-yi);
- float zf = (float)(z-zi);
- float rxf, ryf;
-
- float r=0;
- float ampl=0.5f;
-
- float n1,n2,n3;
-
- for (int i=0; i=1.0f) { xi++; xf--; }
- if (yf>=1.0f) { yi++; yf--; }
- if (zf>=1.0f) { zi++; zf--; }
- }
- return r;
- }
-
- // [toxi 031112]
- // now adjusts to the size of the cosLUT used via
- // the new variables, defined above
- private float noise_fsc(float i) {
- // using bagel's cosine table instead
- return 0.5f*(1.0f-perlin_cosTable[(int)(i*perlin_PI)%perlin_TWOPI]);
- }
-
- // [toxi 040903]
- // make perlin noise quality user controlled to allow
- // for different levels of detail. lower values will produce
- // smoother results as higher octaves are surpressed
-
- public void noiseDetail(int lod) {
- if (lod>0) perlin_octaves=lod;
- }
-
- public void noiseDetail(int lod, float falloff) {
- if (lod>0) perlin_octaves=lod;
- if (falloff>0) perlin_amp_falloff=falloff;
- }
-
- public void noiseSeed(long what) {
- if (perlinRandom == null) perlinRandom = new Random();
- perlinRandom.setSeed(what);
- // force table reset after changing the random number seed [0122]
- perlin = null;
- }
-
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- protected String[] loadImageFormats;
-
-
- /**
- * Load an image from the data folder or a local directory.
- * Supports .gif (including transparency), .tga, and .jpg images.
- * In Java 1.3 or later, .png images are
- *
- * also supported.
- *
- * 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:
- *
- *
TGA and TIFF images are loaded using the internal load methods.
- *
JPG, GIF, and PNG images are loaded via loadBytes().
- *
If the image still isn't loaded, it's passed to javax.imageio.
- *
- * 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.
- *
- * 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.
- *
- * 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);
- }
- 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;
- }
-
-
- public PFont createFont(String name, float size) {
- return createFont(name, size, true, PFont.DEFAULT_CHARSET);
- }
-
-
- public PFont createFont(String name, float size, boolean smooth) {
- return createFont(name, size, smooth, PFont.DEFAULT_CHARSET);
- }
-
-
- /**
- * 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.
- *
- * Only works with Java 1.3 or later. Many .otf fonts don't seem
- * to be supported by Java, perhaps because they're CFF based?
- *
- * Font names are inconsistent across platforms and Java versions.
- * On Mac OS X, Java 1.3 uses the font menu name of the font,
- * whereas Java 1.4 uses the PostScript name of the font. Java 1.4
- * on OS X will also accept the font menu name as well. On Windows,
- * it appears that only the menu names are used, no matter what
- * Java version is in use. Naming system unknown/untested for 1.5.
- *
- * Use 'null' for the charset if you want to use any of the 65,536
- * unicode characters that exist in the font. Note that this can
- * produce an enormous file or may cause an OutOfMemoryError.
- */
- public PFont createFont(String name, float size,
- boolean smooth, char charset[]) {
- String lowerName = name.toLowerCase();
- Font baseFont = null;
-
- try {
- if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) {
- InputStream stream = createInput(name);
- if (stream == null) {
- System.err.println("The font \"" + name + "\" " +
- "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;
- }
- baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name));
-
- } else {
- //baseFont = new Font(name, Font.PLAIN, 1);
- baseFont = PFont.findFont(name);
- }
- } catch (Exception e) {
- System.err.println("Problem using createFont() with " + name);
- e.printStackTrace();
- }
- return new PFont(baseFont.deriveFont(size), smooth, charset);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // FILE/FOLDER SELECTION
-
-
- public File selectedFile;
- protected Frame parentFrame;
-
-
- protected void checkParentFrame() {
- if (parentFrame == null) {
- Component comp = getParent();
- while (comp != null) {
- if (comp instanceof Frame) {
- parentFrame = (Frame) comp;
- break;
- }
- comp = comp.getParent();
- }
- // Who you callin' a hack?
- if (parentFrame == null) {
- parentFrame = new Frame();
- }
- }
- }
-
-
- /**
- * Open a platform-specific file chooser dialog to select a file for input.
- * @return full path to the selected file, or null if no selection.
- */
- public String selectInput() {
- return selectInput("Select a file...");
- }
-
-
- /**
- * Opens a platform-specific file chooser dialog to select a file for input. This function returns the full path to the selected file as a String, or null if no selection.
- *
- * @webref input:files
- * @param prompt message you want the user to see in the file chooser
- * @return full path to the selected file, or null if canceled.
- *
- * @see processing.core.PApplet#selectOutput(String)
- * @see processing.core.PApplet#selectFolder(String)
- */
- public String selectInput(String prompt) {
- return selectFileImpl(prompt, FileDialog.LOAD);
- }
-
-
- /**
- * Open a platform-specific file save dialog to select a file for output.
- * @return full path to the file entered, or null if canceled.
- */
- public String selectOutput() {
- return selectOutput("Save as...");
- }
-
-
- /**
- * Open a platform-specific file save dialog to create of select a file for output.
- * This function returns the full path to the selected file as a String, or null if no selection.
- * If you select an existing file, that file will be replaced.
- * Alternatively, you can navigate to a folder and create a new file to write to.
- *
- * @param prompt message you want the user to see in the file chooser
- * @return full path to the file entered, or null if canceled.
- *
- * @webref input:files
- * @see processing.core.PApplet#selectInput(String)
- * @see processing.core.PApplet#selectFolder(String)
- */
- public String selectOutput(String prompt) {
- return selectFileImpl(prompt, FileDialog.SAVE);
- }
-
-
- protected String selectFileImpl(final String prompt, final int mode) {
- checkParentFrame();
-
- try {
- SwingUtilities.invokeAndWait(new Runnable() {
- public void run() {
- FileDialog fileDialog =
- new FileDialog(parentFrame, prompt, mode);
- fileDialog.setVisible(true);
- String directory = fileDialog.getDirectory();
- String filename = fileDialog.getFile();
- selectedFile =
- (filename == null) ? null : new File(directory, filename);
- }
- });
- return (selectedFile == null) ? null : selectedFile.getAbsolutePath();
-
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
-
- public String selectFolder() {
- return selectFolder("Select a folder...");
- }
-
-
- /**
- * Opens a platform-specific file chooser dialog to select a folder for input.
- * This function returns the full path to the selected folder as a String, or null if no selection.
- *
- * @webref input:files
- * @param prompt message you want the user to see in the file chooser
- * @return full path to the selected folder, or null if no selection.
- *
- * @see processing.core.PApplet#selectOutput(String)
- * @see processing.core.PApplet#selectInput(String)
- */
- public String selectFolder(final String prompt) {
- checkParentFrame();
-
- try {
- SwingUtilities.invokeAndWait(new Runnable() {
- public void run() {
- if (platform == MACOSX) {
- FileDialog fileDialog =
- new FileDialog(parentFrame, prompt, FileDialog.LOAD);
- System.setProperty("apple.awt.fileDialogForDirectories", "true");
- fileDialog.setVisible(true);
- System.setProperty("apple.awt.fileDialogForDirectories", "false");
- String filename = fileDialog.getFile();
- selectedFile = (filename == null) ? null :
- new File(fileDialog.getDirectory(), fileDialog.getFile());
- } else {
- JFileChooser fileChooser = new JFileChooser();
- fileChooser.setDialogTitle(prompt);
- fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
-
- int returned = fileChooser.showOpenDialog(parentFrame);
- System.out.println(returned);
- if (returned == JFileChooser.CANCEL_OPTION) {
- selectedFile = null;
- } else {
- selectedFile = fileChooser.getSelectedFile();
- }
- }
- }
- });
- return (selectedFile == null) ? null : selectedFile.getAbsolutePath();
-
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // READERS AND WRITERS
-
-
- /**
- * I want to read lines from a file. I have RSI from typing these
- * eight lines of code so many times.
- */
- public BufferedReader createReader(String filename) {
- try {
- InputStream is = createInput(filename);
- if (is == null) {
- System.err.println(filename + " does not exist or could not be read");
- return null;
- }
- return createReader(is);
-
- } catch (Exception e) {
- if (filename == null) {
- System.err.println("Filename passed to reader() was null");
- } else {
- System.err.println("Couldn't create a reader for " + filename);
- }
- }
- return null;
- }
-
-
- /**
- * I want to read lines from a file. And I'm still annoyed.
- */
- static public BufferedReader createReader(File file) {
- try {
- InputStream is = new FileInputStream(file);
- if (file.getName().toLowerCase().endsWith(".gz")) {
- is = new GZIPInputStream(is);
- }
- return createReader(is);
-
- } catch (Exception e) {
- if (file == null) {
- throw new RuntimeException("File passed to createReader() was null");
- } else {
- e.printStackTrace();
- throw new RuntimeException("Couldn't create a reader for " +
- file.getAbsolutePath());
- }
- }
- //return null;
- }
-
-
- /**
- * I want to read lines from a stream. If I have to type the
- * following lines any more I'm gonna send Sun my medical bills.
- */
- static public BufferedReader createReader(InputStream input) {
- InputStreamReader isr = null;
- try {
- isr = new InputStreamReader(input, "UTF-8");
- } catch (UnsupportedEncodingException e) { } // not gonna happen
- return new BufferedReader(isr);
- }
-
-
- /**
- * I want to print lines to a file. Why can't I?
- */
- public PrintWriter createWriter(String filename) {
- return createWriter(saveFile(filename));
- }
-
-
- /**
- * I want to print lines to a file. I have RSI from typing these
- * eight lines of code so many times.
- */
- static public PrintWriter createWriter(File file) {
- try {
- createPath(file); // make sure in-between folders exist
- OutputStream output = new FileOutputStream(file);
- if (file.getName().toLowerCase().endsWith(".gz")) {
- output = new GZIPOutputStream(output);
- }
- return createWriter(output);
-
- } catch (Exception e) {
- if (file == null) {
- throw new RuntimeException("File passed to createWriter() was null");
- } else {
- e.printStackTrace();
- throw new RuntimeException("Couldn't create a writer for " +
- file.getAbsolutePath());
- }
- }
- //return null;
- }
-
-
- /**
- * I want to print lines to a file. Why am I always explaining myself?
- * It's the JavaSoft API engineers who need to explain themselves.
- */
- static public PrintWriter createWriter(OutputStream output) {
- try {
- OutputStreamWriter osw = new OutputStreamWriter(output, "UTF-8");
- return new PrintWriter(osw);
- } catch (UnsupportedEncodingException e) { } // not gonna happen
- return null;
- }
-
-
- //////////////////////////////////////////////////////////////
-
- // FILE INPUT
-
-
- /**
- * @deprecated As of release 0136, use createInput() instead.
- */
- public InputStream openStream(String filename) {
- return createInput(filename);
- }
-
-
- /**
- * This is a method for advanced programmers to open a Java InputStream. The method is useful if you want to use the facilities provided by PApplet to easily open files 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.
- *
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.
- *
- * 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:
- *
- *
A URL, for instance openStream("http://processing.org/");
- *
A file in the sketch's data folder
- *
Another file to be opened locally (when running as an application)
- *
- *
- * @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;
- }
- }
-
- 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.
- *
- * 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.
- *
- * If the path does not exist, intermediate folders will be created. If an
- * exception occurs, it will be printed to the console, and null will be
- * returned.
- *
- * Future releases may also add support for handling HTTP POST via this
- * method (for better symmetry with createInput), however that's maybe a
- * little too clever (and then we'd have to add the same features to the
- * other file functions like createWriter). Who you callin' bloated?
- */
- public OutputStream createOutput(String filename) {
- return createOutput(saveFile(filename));
- }
-
-
- static public OutputStream createOutput(File file) {
- try {
- createPath(file); // make sure the path exists
- FileOutputStream fos = new FileOutputStream(file);
- if (file.getName().toLowerCase().endsWith(".gz")) {
- return new GZIPOutputStream(fos);
- }
- return fos;
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
-
- /**
- * Save the contents of a stream to a file in the sketch folder.
- * This is basically saveBytes(blah, loadBytes()), but done
- * more efficiently (and with less confusing syntax).
- */
- public void saveStream(String targetFilename, String sourceLocation) {
- saveStream(saveFile(targetFilename), sourceLocation);
- }
-
-
- /**
- * Identical to the other saveStream(), but writes to a File
- * object, for greater control over the file location.
- * Note that unlike other api methods, this will not automatically
- * compress or uncompress gzip files.
- */
- public void saveStream(File targetFile, String sourceLocation) {
- saveStream(targetFile, createInputRaw(sourceLocation));
- }
-
-
- static public void saveStream(File targetFile, InputStream sourceStream) {
- File tempFile = null;
- try {
- File parentDir = targetFile.getParentFile();
- tempFile = File.createTempFile(targetFile.getName(), null, parentDir);
-
- BufferedInputStream bis = new BufferedInputStream(sourceStream, 16384);
- FileOutputStream fos = new FileOutputStream(tempFile);
- BufferedOutputStream bos = new BufferedOutputStream(fos);
-
- byte[] buffer = new byte[8192];
- int bytesRead;
- while ((bytesRead = bis.read(buffer)) != -1) {
- bos.write(buffer, 0, bytesRead);
- }
-
- bos.flush();
- bos.close();
- bos = null;
-
- if (!tempFile.renameTo(targetFile)) {
- System.err.println("Could not rename temporary file " +
- tempFile.getAbsolutePath());
- }
- } catch (IOException e) {
- if (tempFile != null) {
- tempFile.delete();
- }
- e.printStackTrace();
- }
- }
-
-
- /**
- * Saves bytes to a file to inside the sketch folder.
- * The filename can be a relative path, i.e. "poo/bytefun.txt"
- * would save to a file named "bytefun.txt" to a subfolder
- * called 'poo' inside the sketch folder. If the in-between
- * subfolders don't exist, they'll be created.
- */
- public void saveBytes(String filename, byte buffer[]) {
- saveBytes(saveFile(filename), buffer);
- }
-
-
- /**
- * Saves bytes to a specific File location specified by the user.
- */
- static public void saveBytes(File file, byte buffer[]) {
- File tempFile = null;
- try {
- File parentDir = file.getParentFile();
- tempFile = File.createTempFile(file.getName(), null, parentDir);
-
- /*
- String filename = file.getAbsolutePath();
- createPath(filename);
- OutputStream output = new FileOutputStream(file);
- if (file.getName().toLowerCase().endsWith(".gz")) {
- output = new GZIPOutputStream(output);
- }
- */
- OutputStream output = createOutput(tempFile);
- saveBytes(output, buffer);
- output.close();
- output = null;
-
- if (!tempFile.renameTo(file)) {
- System.err.println("Could not rename temporary file " +
- tempFile.getAbsolutePath());
- }
-
- } catch (IOException e) {
- System.err.println("error saving bytes to " + file);
- if (tempFile != null) {
- tempFile.delete();
- }
- e.printStackTrace();
- }
- }
-
-
- /**
- * Spews a buffer of bytes to an OutputStream.
- */
- static public void saveBytes(OutputStream output, byte buffer[]) {
- try {
- output.write(buffer);
- output.flush();
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- //
-
- public void saveStrings(String filename, String strings[]) {
- saveStrings(saveFile(filename), strings);
- }
-
-
- static public void saveStrings(File file, String strings[]) {
- saveStrings(createOutput(file), strings);
- /*
- try {
- String location = file.getAbsolutePath();
- createPath(location);
- OutputStream output = new FileOutputStream(location);
- if (file.getName().toLowerCase().endsWith(".gz")) {
- output = new GZIPOutputStream(output);
- }
- saveStrings(output, strings);
- output.close();
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- */
- }
-
-
- static public void saveStrings(OutputStream output, String strings[]) {
- PrintWriter writer = createWriter(output);
- for (int i = 0; i < strings.length; i++) {
- writer.println(strings[i]);
- }
- writer.flush();
- writer.close();
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- /**
- * Prepend the sketch folder path to the filename (or path) that is
- * passed in. External libraries should use this function to save to
- * the sketch folder.
- *
- * Note that when running as an applet inside a web browser,
- * the sketchPath will be set to null, because security restrictions
- * prevent applets from accessing that information.
- *
- * This will also cause an error if the sketch is not inited properly,
- * meaning that init() was never called on the PApplet when hosted
- * my some other main() or by other code. For proper use of init(),
- * see the examples in the main description text for PApplet.
- */
- public String sketchPath(String where) {
- if (sketchPath == null) {
- return where;
-// throw new RuntimeException("The applet was not inited properly, " +
-// "or security restrictions prevented " +
-// "it from determining its path.");
- }
- // isAbsolute() could throw an access exception, but so will writing
- // to the local disk using the sketch path, so this is safe here.
- // for 0120, added a try/catch anyways.
- try {
- if (new File(where).isAbsolute()) return where;
- } catch (Exception e) { }
-
- return sketchPath + File.separator + where;
- }
-
-
- public File sketchFile(String where) {
- return new File(sketchPath(where));
- }
-
-
- /**
- * Returns a path inside the applet folder to save to. Like sketchPath(),
- * but creates any in-between folders so that things save properly.
- *
- * All saveXxxx() functions use the path to the sketch folder, rather than
- * its data folder. Once exported, the data folder will be found inside the
- * jar file of the exported application or applet. In this case, it's not
- * possible to save data into the jar file, because it will often be running
- * from a server, or marked in-use if running from a local file system.
- * With this in mind, saving to the data path doesn't make sense anyway.
- * If you know you're running locally, and want to save to the data folder,
- * use saveXxxx("data/blah.dat").
- */
- public String savePath(String where) {
- if (where == null) return null;
- String filename = sketchPath(where);
- createPath(filename);
- return filename;
- }
-
-
- /**
- * Identical to savePath(), but returns a File object.
- */
- public File saveFile(String where) {
- return new File(savePath(where));
- }
-
-
- /**
- * Return a full path to an item in the data folder.
- *
- * 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 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.
- *
- * 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.
- *
- * 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.
- *
- * 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).
- *
- */
- 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.
- *
- */
- 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.
- *
- * 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 items = new ArrayList();
- int index;
- int offset = 0;
- while ((index = what.indexOf(delim, offset)) != -1) {
- items.add(what.substring(offset, index));
- offset = index + delim.length();
- }
- items.add(what.substring(offset));
- String[] outgoing = new String[items.size()];
- items.toArray(outgoing);
- return outgoing;
- }
-
-
- /**
- * Match a string with a regular expression, and returns the match as an
- * array. The first index is the matching expression, and array elements
- * [1] and higher represent each of the groups (sequences found in parens).
- *
- * This uses multiline matching (Pattern.MULTILINE) and dotall mode
- * (Pattern.DOTALL) by default, so that ^ and $ match the beginning and
- * end of any lines found in the source, and the . operator will also
- * pick up newline characters.
- */
- static public String[] match(String what, String regexp) {
- Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
- Matcher m = p.matcher(what);
- if (m.find()) {
- int count = m.groupCount() + 1;
- String[] groups = new String[count];
- for (int i = 0; i < count; i++) {
- groups[i] = m.group(i);
- }
- return groups;
- }
- return null;
- }
-
-
- /**
- * Identical to match(), except that it returns an array of all matches in
- * the specified String, rather than just the first.
- */
- static public String[][] matchAll(String what, String regexp) {
- Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
- Matcher m = p.matcher(what);
- ArrayList results = new ArrayList();
- int count = m.groupCount() + 1;
- while (m.find()) {
- String[] groups = new String[count];
- for (int i = 0; i < count; i++) {
- groups[i] = m.group(i);
- }
- results.add(groups);
- }
- if (results.isEmpty()) {
- return null;
- }
- String[][] matches = new String[results.size()][count];
- for (int i = 0; i < matches.length; i++) {
- matches[i] = (String[]) results.get(i);
- }
- return matches;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CASTING FUNCTIONS, INSERTED BY PREPROC
-
-
- /**
- * Convert a char to a boolean. 'T', 't', and '1' will become the
- * boolean value true, while 'F', 'f', or '0' will become false.
- */
- /*
- static final public boolean parseBoolean(char what) {
- return ((what == 't') || (what == 'T') || (what == '1'));
- }
- */
-
- /**
- *
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).
- * @return false if 0, true if any other number
- */
- static final public boolean parseBoolean(int what) {
- return (what != 0);
- }
-
- /*
- // removed because this makes no useful sense
- static final public boolean parseBoolean(float what) {
- return (what != 0);
- }
- */
-
- /**
- * Convert the string "true" or "false" to a boolean.
- * @return true if 'what' is "true" or "TRUE", false otherwise
- */
- static final public boolean parseBoolean(String what) {
- return new Boolean(what).booleanValue();
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- /*
- // removed, no need to introduce strange syntax from other languages
- static final public boolean[] parseBoolean(char what[]) {
- boolean outgoing[] = new boolean[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] =
- ((what[i] == 't') || (what[i] == 'T') || (what[i] == '1'));
- }
- return outgoing;
- }
- */
-
- /**
- * Convert a byte array to a boolean array. Each element will be
- * evaluated identical to the integer case, where a byte equal
- * to zero will return false, and any other value will return true.
- * @return array of boolean elements
- */
- static final public boolean[] parseBoolean(byte what[]) {
- boolean outgoing[] = new boolean[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (what[i] != 0);
- }
- return outgoing;
- }
-
- /**
- * Convert an int array to a boolean array. An int equal
- * to zero will return false, and any other value will return true.
- * @return array of boolean elements
- */
- static final public boolean[] parseBoolean(int what[]) {
- boolean outgoing[] = new boolean[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (what[i] != 0);
- }
- return outgoing;
- }
-
- /*
- // removed, not necessary... if necessary, convert to int array first
- static final public boolean[] parseBoolean(float what[]) {
- boolean outgoing[] = new boolean[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (what[i] != 0);
- }
- return outgoing;
- }
- */
-
- static final public boolean[] parseBoolean(String what[]) {
- boolean outgoing[] = new boolean[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = new Boolean(what[i]).booleanValue();
- }
- return outgoing;
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- static final public byte parseByte(boolean what) {
- return what ? (byte)1 : 0;
- }
-
- static final public byte parseByte(char what) {
- return (byte) what;
- }
-
- static final public byte parseByte(int what) {
- return (byte) what;
- }
-
- static final public byte parseByte(float what) {
- return (byte) what;
- }
-
- /*
- // nixed, no precedent
- static final public byte[] parseByte(String what) { // note: array[]
- return what.getBytes();
- }
- */
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- static final public byte[] parseByte(boolean what[]) {
- byte outgoing[] = new byte[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = what[i] ? (byte)1 : 0;
- }
- return outgoing;
- }
-
- static final public byte[] parseByte(char what[]) {
- byte outgoing[] = new byte[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (byte) what[i];
- }
- return outgoing;
- }
-
- static final public byte[] parseByte(int what[]) {
- byte outgoing[] = new byte[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (byte) what[i];
- }
- return outgoing;
- }
-
- static final public byte[] parseByte(float what[]) {
- byte outgoing[] = new byte[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (byte) what[i];
- }
- return outgoing;
- }
-
- /*
- static final public byte[][] parseByte(String what[]) { // note: array[][]
- byte outgoing[][] = new byte[what.length][];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = what[i].getBytes();
- }
- return outgoing;
- }
- */
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- /*
- static final public char parseChar(boolean what) { // 0/1 or T/F ?
- return what ? 't' : 'f';
- }
- */
-
- static final public char parseChar(byte what) {
- return (char) (what & 0xff);
- }
-
- static final public char parseChar(int what) {
- return (char) what;
- }
-
- /*
- static final public char parseChar(float what) { // nonsensical
- return (char) what;
- }
-
- static final public char[] parseChar(String what) { // note: array[]
- return what.toCharArray();
- }
- */
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- /*
- static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ?
- char outgoing[] = new char[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = what[i] ? 't' : 'f';
- }
- return outgoing;
- }
- */
-
- static final public char[] parseChar(byte what[]) {
- char outgoing[] = new char[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (char) (what[i] & 0xff);
- }
- return outgoing;
- }
-
- static final public char[] parseChar(int what[]) {
- char outgoing[] = new char[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (char) what[i];
- }
- return outgoing;
- }
-
- /*
- static final public char[] parseChar(float what[]) { // nonsensical
- char outgoing[] = new char[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (char) what[i];
- }
- return outgoing;
- }
-
- static final public char[][] parseChar(String what[]) { // note: array[][]
- char outgoing[][] = new char[what.length][];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = what[i].toCharArray();
- }
- return outgoing;
- }
- */
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- static final public int parseInt(boolean what) {
- return what ? 1 : 0;
- }
-
- /**
- * Note that parseInt() will un-sign a signed byte value.
- */
- static final public int parseInt(byte what) {
- return what & 0xff;
- }
-
- /**
- * Note that parseInt('5') is unlike String in the sense that it
- * won't return 5, but the ascii value. This is because ((int) someChar)
- * returns the ascii value, and parseInt() is just longhand for the cast.
- */
- static final public int parseInt(char what) {
- return what;
- }
-
- /**
- * Same as floor(), or an (int) cast.
- */
- static final public int parseInt(float what) {
- return (int) what;
- }
-
- /**
- * Parse a String into an int value. Returns 0 if the value is bad.
- */
- static final public int parseInt(String what) {
- return parseInt(what, 0);
- }
-
- /**
- * Parse a String to an int, and provide an alternate value that
- * should be used when the number is invalid.
- */
- static final public int parseInt(String what, int otherwise) {
- try {
- int offset = what.indexOf('.');
- if (offset == -1) {
- return Integer.parseInt(what);
- } else {
- return Integer.parseInt(what.substring(0, offset));
- }
- } catch (NumberFormatException e) { }
- return otherwise;
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- static final public int[] parseInt(boolean what[]) {
- int list[] = new int[what.length];
- for (int i = 0; i < what.length; i++) {
- list[i] = what[i] ? 1 : 0;
- }
- return list;
- }
-
- static final public int[] parseInt(byte what[]) { // note this unsigns
- int list[] = new int[what.length];
- for (int i = 0; i < what.length; i++) {
- list[i] = (what[i] & 0xff);
- }
- return list;
- }
-
- static final public int[] parseInt(char what[]) {
- int list[] = new int[what.length];
- for (int i = 0; i < what.length; i++) {
- list[i] = what[i];
- }
- return list;
- }
-
- static public int[] parseInt(float what[]) {
- int inties[] = new int[what.length];
- for (int i = 0; i < what.length; i++) {
- inties[i] = (int)what[i];
- }
- return inties;
- }
-
- /**
- * Make an array of int elements from an array of String objects.
- * If the String can't be parsed as a number, it will be set to zero.
- *
- * String s[] = { "1", "300", "44" };
- * int numbers[] = parseInt(s);
- *
- * numbers will contain { 1, 300, 44 }
- */
- static public int[] parseInt(String what[]) {
- return parseInt(what, 0);
- }
-
- /**
- * Make an array of int elements from an array of String objects.
- * If the String can't be parsed as a number, its entry in the
- * array will be set to the value of the "missing" parameter.
- *
- * String s[] = { "1", "300", "apple", "44" };
- * int numbers[] = parseInt(s, 9999);
- *
- * numbers will contain { 1, 300, 9999, 44 }
- */
- static public int[] parseInt(String what[], int missing) {
- int output[] = new int[what.length];
- for (int i = 0; i < what.length; i++) {
- try {
- output[i] = Integer.parseInt(what[i]);
- } catch (NumberFormatException e) {
- output[i] = missing;
- }
- }
- return output;
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- /*
- static final public float parseFloat(boolean what) {
- return what ? 1 : 0;
- }
- */
-
- /**
- * Convert an int to a float value. Also handles bytes because of
- * Java's rules for upgrading values.
- */
- static final public float parseFloat(int what) { // also handles byte
- return (float)what;
- }
-
- static final public float parseFloat(String what) {
- return parseFloat(what, Float.NaN);
- }
-
- static final public float parseFloat(String what, float otherwise) {
- try {
- return new Float(what).floatValue();
- } catch (NumberFormatException e) { }
-
- return otherwise;
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- /*
- static final public float[] parseFloat(boolean what[]) {
- float floaties[] = new float[what.length];
- for (int i = 0; i < what.length; i++) {
- floaties[i] = what[i] ? 1 : 0;
- }
- return floaties;
- }
-
- static final public float[] parseFloat(char what[]) {
- float floaties[] = new float[what.length];
- for (int i = 0; i < what.length; i++) {
- floaties[i] = (char) what[i];
- }
- return floaties;
- }
- */
-
- static final public float[] parseByte(byte what[]) {
- float floaties[] = new float[what.length];
- for (int i = 0; i < what.length; i++) {
- floaties[i] = what[i];
- }
- return floaties;
- }
-
- static final public float[] parseFloat(int what[]) {
- float floaties[] = new float[what.length];
- for (int i = 0; i < what.length; i++) {
- floaties[i] = what[i];
- }
- return floaties;
- }
-
- static final public float[] parseFloat(String what[]) {
- return parseFloat(what, Float.NaN);
- }
-
- static final public float[] parseFloat(String what[], float missing) {
- float output[] = new float[what.length];
- for (int i = 0; i < what.length; i++) {
- try {
- output[i] = new Float(what[i]).floatValue();
- } catch (NumberFormatException e) {
- output[i] = missing;
- }
- }
- return output;
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- static final public String str(boolean x) {
- return String.valueOf(x);
- }
-
- static final public String str(byte x) {
- return String.valueOf(x);
- }
-
- static final public String str(char x) {
- return String.valueOf(x);
- }
-
- static final public String str(int x) {
- return String.valueOf(x);
- }
-
- static final public String str(float x) {
- return String.valueOf(x);
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- static final public String[] str(boolean x[]) {
- String s[] = new String[x.length];
- for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
- return s;
- }
-
- static final public String[] str(byte x[]) {
- String s[] = new String[x.length];
- for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
- return s;
- }
-
- static final public String[] str(char x[]) {
- String s[] = new String[x.length];
- for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
- return s;
- }
-
- static final public String[] str(int x[]) {
- String s[] = new String[x.length];
- for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
- return s;
- }
-
- static final public String[] str(float x[]) {
- String s[] = new String[x.length];
- for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
- return s;
- }
-
-
- //////////////////////////////////////////////////////////////
-
- // INT NUMBER FORMATTING
-
-
- /**
- * Integer number formatter.
- */
- static private NumberFormat int_nf;
- static private int int_nf_digits;
- static private boolean int_nf_commas;
-
-
- static public String[] nf(int num[], int digits) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nf(num[i], digits);
- }
- return formatted;
- }
-
-
- static public String nf(int num, int digits) {
- if ((int_nf != null) &&
- (int_nf_digits == digits) &&
- !int_nf_commas) {
- return int_nf.format(num);
- }
-
- int_nf = NumberFormat.getInstance();
- int_nf.setGroupingUsed(false); // no commas
- int_nf_commas = false;
- int_nf.setMinimumIntegerDigits(digits);
- int_nf_digits = digits;
- return int_nf.format(num);
- }
-
-
- static public String[] nfc(int num[]) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nfc(num[i]);
- }
- return formatted;
- }
-
-
- static public String nfc(int num) {
- if ((int_nf != null) &&
- (int_nf_digits == 0) &&
- int_nf_commas) {
- return int_nf.format(num);
- }
-
- int_nf = NumberFormat.getInstance();
- int_nf.setGroupingUsed(true);
- int_nf_commas = true;
- int_nf.setMinimumIntegerDigits(0);
- int_nf_digits = 0;
- return int_nf.format(num);
- }
-
-
- /**
- * number format signed (or space)
- * Formats a number but leaves a blank space in the front
- * when it's positive so that it can be properly aligned with
- * numbers that have a negative sign in front of them.
- */
- static public String nfs(int num, int digits) {
- return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits));
- }
-
- static public String[] nfs(int num[], int digits) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nfs(num[i], digits);
- }
- return formatted;
- }
-
- //
-
- /**
- * number format positive (or plus)
- * Formats a number, always placing a - or + sign
- * in the front when it's negative or positive.
- */
- static public String nfp(int num, int digits) {
- return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits));
- }
-
- static public String[] nfp(int num[], int digits) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nfp(num[i], digits);
- }
- return formatted;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // FLOAT NUMBER FORMATTING
-
-
- static private NumberFormat float_nf;
- static private int float_nf_left, float_nf_right;
- static private boolean float_nf_commas;
-
-
- static public String[] nf(float num[], int left, int right) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nf(num[i], left, right);
- }
- return formatted;
- }
-
-
- static public String nf(float num, int left, int right) {
- if ((float_nf != null) &&
- (float_nf_left == left) &&
- (float_nf_right == right) &&
- !float_nf_commas) {
- return float_nf.format(num);
- }
-
- float_nf = NumberFormat.getInstance();
- float_nf.setGroupingUsed(false);
- float_nf_commas = false;
-
- if (left != 0) float_nf.setMinimumIntegerDigits(left);
- if (right != 0) {
- float_nf.setMinimumFractionDigits(right);
- float_nf.setMaximumFractionDigits(right);
- }
- float_nf_left = left;
- float_nf_right = right;
- return float_nf.format(num);
- }
-
-
- static public String[] nfc(float num[], int right) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nfc(num[i], right);
- }
- return formatted;
- }
-
-
- static public String nfc(float num, int right) {
- if ((float_nf != null) &&
- (float_nf_left == 0) &&
- (float_nf_right == right) &&
- float_nf_commas) {
- return float_nf.format(num);
- }
-
- float_nf = NumberFormat.getInstance();
- float_nf.setGroupingUsed(true);
- float_nf_commas = true;
-
- if (right != 0) {
- float_nf.setMinimumFractionDigits(right);
- float_nf.setMaximumFractionDigits(right);
- }
- float_nf_left = 0;
- float_nf_right = right;
- return float_nf.format(num);
- }
-
-
- /**
- * Number formatter that takes into account whether the number
- * has a sign (positive, negative, etc) in front of it.
- */
- static public String[] nfs(float num[], int left, int right) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nfs(num[i], left, right);
- }
- return formatted;
- }
-
- static public String nfs(float num, int left, int right) {
- return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right));
- }
-
-
- static public String[] nfp(float num[], int left, int right) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nfp(num[i], left, right);
- }
- return formatted;
- }
-
- static public String nfp(float num, int left, int right) {
- return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right));
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // HEX/BINARY CONVERSION
-
-
- static final public String hex(byte what) {
- return hex(what, 2);
- }
-
- static final public String hex(char what) {
- return hex(what, 4);
- }
-
- static final public String hex(int what) {
- return hex(what, 8);
- }
-
- static final public String hex(int what, int digits) {
- String stuff = Integer.toHexString(what).toUpperCase();
-
- int length = stuff.length();
- if (length > digits) {
- return stuff.substring(length - digits);
-
- } else if (length < digits) {
- return "00000000".substring(8 - (digits-length)) + stuff;
- }
- return stuff;
- }
-
- static final public int unhex(String what) {
- // has to parse as a Long so that it'll work for numbers bigger than 2^31
- return (int) (Long.parseLong(what, 16));
- }
-
- //
-
- /**
- * Returns a String that contains the binary value of a byte.
- * The returned value will always have 8 digits.
- */
- static final public String binary(byte what) {
- return binary(what, 8);
- }
-
- /**
- * Returns a String that contains the binary value of a char.
- * The returned value will always have 16 digits because chars
- * are two bytes long.
- */
- static final public String binary(char what) {
- return binary(what, 16);
- }
-
- /**
- * Returns a String that contains the binary value of an int.
- * The length depends on the size of the number itself.
- * An int can be up to 32 binary digits, but that seems like
- * overkill for almost any situation, so this function just
- * auto-size. If you want a specific number of digits (like all 32)
- * use binary(int what, int digits) to specify how many digits.
- */
- static final public String binary(int what) {
- return Integer.toBinaryString(what);
- //return binary(what, 32);
- }
-
- /**
- * Returns a String that contains the binary value of an int.
- * The digits parameter determines how many digits will be used.
- */
- static final public String binary(int what, int digits) {
- String stuff = Integer.toBinaryString(what);
-
- int length = stuff.length();
- if (length > digits) {
- return stuff.substring(length - digits);
-
- } else if (length < digits) {
- int offset = 32 - (digits-length);
- return "00000000000000000000000000000000".substring(offset) + stuff;
- }
- return stuff;
- }
-
-
- /**
- * Unpack a binary String into an int.
- * i.e. unbinary("00001000") would return 8.
- */
- static final public int unbinary(String what) {
- return Integer.parseInt(what, 2);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR FUNCTIONS
-
- // moved here so that they can work without
- // the graphics actually being instantiated (outside setup)
-
-
- public final int color(int gray) {
- if (g == null) {
- if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
- return 0xff000000 | (gray << 16) | (gray << 8) | gray;
- }
- return g.color(gray);
- }
-
-
- public final int color(float fgray) {
- if (g == null) {
- int gray = (int) fgray;
- if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
- return 0xff000000 | (gray << 16) | (gray << 8) | gray;
- }
- return g.color(fgray);
- }
-
-
- /**
- * As of 0116 this also takes color(#FF8800, alpha)
- *
- * @param gray number specifying value between white and black
- */
- public final int color(int gray, int alpha) {
- if (g == null) {
- if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
- if (gray > 255) {
- // then assume this is actually a #FF8800
- return (alpha << 24) | (gray & 0xFFFFFF);
- } else {
- //if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
- return (alpha << 24) | (gray << 16) | (gray << 8) | gray;
- }
- }
- return g.color(gray, alpha);
- }
-
-
- public final int color(float fgray, float falpha) {
- if (g == null) {
- int gray = (int) fgray;
- int alpha = (int) falpha;
- if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
- if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
- return 0xff000000 | (gray << 16) | (gray << 8) | gray;
- }
- return g.color(fgray, falpha);
- }
-
-
- public final int color(int x, int y, int z) {
- if (g == null) {
- if (x > 255) x = 255; else if (x < 0) x = 0;
- if (y > 255) y = 255; else if (y < 0) y = 0;
- if (z > 255) z = 255; else if (z < 0) z = 0;
-
- return 0xff000000 | (x << 16) | (y << 8) | z;
- }
- return g.color(x, y, z);
- }
-
-
- public final int color(float x, float y, float z) {
- if (g == null) {
- if (x > 255) x = 255; else if (x < 0) x = 0;
- if (y > 255) y = 255; else if (y < 0) y = 0;
- if (z > 255) z = 255; else if (z < 0) z = 0;
-
- return 0xff000000 | ((int)x << 16) | ((int)y << 8) | (int)z;
- }
- return g.color(x, y, z);
- }
-
-
- public final int color(int x, int y, int z, int a) {
- if (g == null) {
- if (a > 255) a = 255; else if (a < 0) a = 0;
- if (x > 255) x = 255; else if (x < 0) x = 0;
- if (y > 255) y = 255; else if (y < 0) y = 0;
- if (z > 255) z = 255; else if (z < 0) z = 0;
-
- return (a << 24) | (x << 16) | (y << 8) | z;
- }
- return g.color(x, y, z, a);
- }
-
- /**
- * Creates colors for storing in variables of the color datatype. The parameters are interpreted as RGB or HSB values depending on the current colorMode(). The default mode is RGB values from 0 to 255 and therefore, the function call color(255, 204, 0) will return a bright yellow color. More about how colors are stored can be found in the reference for the color datatype.
- *
- * @webref color:creating_reading
- * @param x red or hue values relative to the current color range
- * @param y green or saturation values relative to the current color range
- * @param z blue or brightness values relative to the current color range
- * @param a alpha relative to current color range
- *
- * @see processing.core.PApplet#colorMode(int)
- * @ref color_datatype
- */
- public final int color(float x, float y, float z, float a) {
- if (g == null) {
- if (a > 255) a = 255; else if (a < 0) a = 0;
- if (x > 255) x = 255; else if (x < 0) x = 0;
- if (y > 255) y = 255; else if (y < 0) y = 0;
- if (z > 255) z = 255; else if (z < 0) z = 0;
-
- return ((int)a << 24) | ((int)x << 16) | ((int)y << 8) | (int)z;
- }
- return g.color(x, y, z, a);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MAIN
-
-
- /**
- * Set this sketch to communicate its state back to the PDE.
- *
- * This uses the stderr stream to write positions of the window
- * (so that it will be saved by the PDE for the next run) and
- * notify on quit. See more notes in the Worker class.
- */
- public void setupExternalMessages() {
-
- frame.addComponentListener(new ComponentAdapter() {
- public void componentMoved(ComponentEvent e) {
- Point where = ((Frame) e.getSource()).getLocation();
- System.err.println(PApplet.EXTERNAL_MOVE + " " +
- where.x + " " + where.y);
- System.err.flush(); // doesn't seem to help or hurt
- }
- });
-
- frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
-// System.err.println(PApplet.EXTERNAL_QUIT);
-// System.err.flush(); // important
-// System.exit(0);
- exit(); // don't quit, need to just shut everything down (0133)
- }
- });
- }
-
-
- /**
- * Set up a listener that will fire proper component resize events
- * in cases where frame.setResizable(true) is called.
- */
- public void setupFrameResizeListener() {
- frame.addComponentListener(new ComponentAdapter() {
-
- public void componentResized(ComponentEvent e) {
- // Ignore bad resize events fired during setup to fix
- // http://dev.processing.org/bugs/show_bug.cgi?id=341
- // This should also fix the blank screen on Linux bug
- // http://dev.processing.org/bugs/show_bug.cgi?id=282
- if (frame.isResizable()) {
- // might be multiple resize calls before visible (i.e. first
- // when pack() is called, then when it's resized for use).
- // ignore them because it's not the user resizing things.
- Frame farm = (Frame) e.getComponent();
- if (farm.isVisible()) {
- Insets insets = farm.getInsets();
- Dimension windowSize = farm.getSize();
- int usableW = windowSize.width - insets.left - insets.right;
- int usableH = windowSize.height - insets.top - insets.bottom;
-
- // the ComponentListener in PApplet will handle calling size()
- setBounds(insets.left, insets.top, usableW, usableH);
- }
- }
- }
- });
- }
-
-
- /**
- * GIF image of the Processing logo.
- */
- static public final byte[] ICON_IMAGE = {
- 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -77, 0, 0, 0, 0, 0, -1, -1, -1, 12,
- 12, 13, -15, -15, -14, 45, 57, 74, 54, 80, 111, 47, 71, 97, 62, 88, 117,
- 1, 14, 27, 7, 41, 73, 15, 52, 85, 2, 31, 55, 4, 54, 94, 18, 69, 109, 37,
- 87, 126, -1, -1, -1, 33, -7, 4, 1, 0, 0, 15, 0, 44, 0, 0, 0, 0, 16, 0, 16,
- 0, 0, 4, 122, -16, -107, 114, -86, -67, 83, 30, -42, 26, -17, -100, -45,
- 56, -57, -108, 48, 40, 122, -90, 104, 67, -91, -51, 32, -53, 77, -78, -100,
- 47, -86, 12, 76, -110, -20, -74, -101, 97, -93, 27, 40, 20, -65, 65, 48,
- -111, 99, -20, -112, -117, -123, -47, -105, 24, 114, -112, 74, 69, 84, 25,
- 93, 88, -75, 9, 46, 2, 49, 88, -116, -67, 7, -19, -83, 60, 38, 3, -34, 2,
- 66, -95, 27, -98, 13, 4, -17, 55, 33, 109, 11, 11, -2, -128, 121, 123, 62,
- 91, 120, -128, 127, 122, 115, 102, 2, 119, 0, -116, -113, -119, 6, 102,
- 121, -108, -126, 5, 18, 6, 4, -102, -101, -100, 114, 15, 17, 0, 59
- };
-
-
- /**
- * main() method for running this class from the command line.
- *
- * 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:
- *
- * 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", "true");
- }
-
- // 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 ");
- System.err.println("For additional options, " +
- "see the Javadoc for PApplet");
- System.exit(1);
- }
-
- boolean external = false;
- int[] location = null;
- int[] editorLocation = null;
-
- String name = null;
- boolean present = false;
- boolean exclusive = false;
- Color backgroundColor = Color.BLACK;
- Color stopColor = Color.GRAY;
- GraphicsDevice displayDevice = null;
- boolean hideStop = false;
-
- String param = null, value = null;
-
- // try to get the user folder. if running under java web start,
- // this may cause a security exception if the code is not signed.
- // http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274
- String folder = null;
- try {
- folder = System.getProperty("user.dir");
- } catch (Exception e) { }
-
- int argIndex = 0;
- while (argIndex < args.length) {
- int equals = args[argIndex].indexOf('=');
- if (equals != -1) {
- param = args[argIndex].substring(0, equals);
- value = args[argIndex].substring(equals + 1);
-
- if (param.equals(ARGS_EDITOR_LOCATION)) {
- external = true;
- editorLocation = parseInt(split(value, ','));
-
- } else if (param.equals(ARGS_DISPLAY)) {
- int deviceIndex = Integer.parseInt(value) - 1;
-
- //DisplayMode dm = device.getDisplayMode();
- //if ((dm.getWidth() == 1024) && (dm.getHeight() == 768)) {
-
- GraphicsEnvironment environment =
- GraphicsEnvironment.getLocalGraphicsEnvironment();
- GraphicsDevice devices[] = environment.getScreenDevices();
- if ((deviceIndex >= 0) && (deviceIndex < devices.length)) {
- displayDevice = devices[deviceIndex];
- } else {
- System.err.println("Display " + value + " does not exist, " +
- "using the default display instead.");
- }
-
- } else if (param.equals(ARGS_BGCOLOR)) {
- if (value.charAt(0) == '#') value = value.substring(1);
- backgroundColor = new Color(Integer.parseInt(value, 16));
-
- } else if (param.equals(ARGS_STOP_COLOR)) {
- if (value.charAt(0) == '#') value = value.substring(1);
- stopColor = new Color(Integer.parseInt(value, 16));
-
- } else if (param.equals(ARGS_SKETCH_FOLDER)) {
- folder = value;
-
- } else if (param.equals(ARGS_LOCATION)) {
- location = parseInt(split(value, ','));
- }
-
- } else {
- if (args[argIndex].equals(ARGS_PRESENT)) {
- present = true;
-
- } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) {
- exclusive = true;
-
- } else if (args[argIndex].equals(ARGS_HIDE_STOP)) {
- hideStop = true;
-
- } else if (args[argIndex].equals(ARGS_EXTERNAL)) {
- external = true;
-
- } else {
- name = args[argIndex];
- break;
- }
- }
- argIndex++;
- }
-
- // Set this property before getting into any GUI init code
- //System.setProperty("com.apple.mrj.application.apple.menu.about.name", name);
- // This )*)(*@#$ Apple crap don't work no matter where you put it
- // (static method of the class, at the top of main, wherever)
-
- if (displayDevice == null) {
- GraphicsEnvironment environment =
- GraphicsEnvironment.getLocalGraphicsEnvironment();
- displayDevice = environment.getDefaultScreenDevice();
- }
-
- Frame frame = new Frame(displayDevice.getDefaultConfiguration());
- /*
- Frame frame = null;
- if (displayDevice != null) {
- frame = new Frame(displayDevice.getDefaultConfiguration());
- } else {
- frame = new Frame();
- }
- */
- //Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
-
- // remove the grow box by default
- // users who want it back can call frame.setResizable(true)
- frame.setResizable(false);
-
- // Set the trimmings around the image
- Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE);
- frame.setIconImage(image);
- frame.setTitle(name);
-
- final PApplet applet;
- try {
- Class> c = Thread.currentThread().getContextClassLoader().loadClass(name);
- applet = (PApplet) c.newInstance();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
-
- // these are needed before init/start
- applet.frame = frame;
- applet.sketchPath = folder;
- applet.args = PApplet.subset(args, 1);
- applet.external = external;
-
- // Need to save the window bounds at full screen,
- // because pack() will cause the bounds to go to zero.
- // http://dev.processing.org/bugs/show_bug.cgi?id=923
- Rectangle fullScreenRect = null;
-
- // For 0149, moving this code (up to the pack() method) before init().
- // For OpenGL (and perhaps other renderers in the future), a peer is
- // needed before a GLDrawable can be created. So pack() needs to be
- // called on the Frame before applet.init(), which itself calls size(),
- // and launches the Thread that will kick off setup().
- // http://dev.processing.org/bugs/show_bug.cgi?id=891
- // http://dev.processing.org/bugs/show_bug.cgi?id=908
- if (present) {
- frame.setUndecorated(true);
- frame.setBackground(backgroundColor);
- if (exclusive) {
- displayDevice.setFullScreenWindow(frame);
- frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
- fullScreenRect = frame.getBounds();
- } else {
- DisplayMode mode = displayDevice.getDisplayMode();
- fullScreenRect = new Rectangle(0, 0, mode.getWidth(), mode.getHeight());
- frame.setBounds(fullScreenRect);
- frame.setVisible(true);
- }
- }
- frame.setLayout(null);
- frame.add(applet);
- if (present) {
- frame.invalidate();
- } else {
- frame.pack();
- }
- // insufficient, places the 100x100 sketches offset strangely
- //frame.validate();
-
- applet.init();
-
- // Wait until the applet has figured out its width.
- // In a static mode app, this will be after setup() has completed,
- // and the empty draw() has set "finished" to true.
- // TODO make sure this won't hang if the applet has an exception.
- while (applet.defaultSize && !applet.finished) {
- //System.out.println("default size");
- try {
- Thread.sleep(5);
-
- } catch (InterruptedException e) {
- //System.out.println("interrupt");
- }
- }
- //println("not default size " + applet.width + " " + applet.height);
- //println(" (g width/height is " + applet.g.width + "x" + applet.g.height + ")");
-
- if (present) {
- // After the pack(), the screen bounds are gonna be 0s
- frame.setBounds(fullScreenRect);
- applet.setBounds((fullScreenRect.width - applet.width) / 2,
- (fullScreenRect.height - applet.height) / 2,
- applet.width, applet.height);
-
- if (!hideStop) {
- Label label = new Label("stop");
- label.setForeground(stopColor);
- label.addMouseListener(new MouseAdapter() {
- public void mousePressed(MouseEvent e) {
- System.exit(0);
- }
- });
- frame.add(label);
-
- Dimension labelSize = label.getPreferredSize();
- // sometimes shows up truncated on mac
- //System.out.println("label width is " + labelSize.width);
- labelSize = new Dimension(100, labelSize.height);
- label.setSize(labelSize);
- label.setLocation(20, fullScreenRect.height - labelSize.height - 20);
- }
-
- // not always running externally when in present mode
- if (external) {
- applet.setupExternalMessages();
- }
-
- } else { // if not presenting
- // can't do pack earlier cuz present mode don't like it
- // (can't go full screen with a frame after calling pack)
- // frame.pack(); // get insets. get more.
- Insets insets = frame.getInsets();
-
- int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) +
- insets.left + insets.right;
- int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) +
- insets.top + insets.bottom;
-
- frame.setSize(windowW, windowH);
-
- if (location != null) {
- // a specific location was received from PdeRuntime
- // (applet has been run more than once, user placed window)
- frame.setLocation(location[0], location[1]);
-
- } else if (external) {
- int locationX = editorLocation[0] - 20;
- int locationY = editorLocation[1];
-
- if (locationX - windowW > 10) {
- // if it fits to the left of the window
- frame.setLocation(locationX - windowW, locationY);
-
- } else { // doesn't fit
- // if it fits inside the editor window,
- // offset slightly from upper lefthand corner
- // so that it's plunked inside the text area
- locationX = editorLocation[0] + 66;
- locationY = editorLocation[1] + 66;
-
- if ((locationX + windowW > applet.screen.width - 33) ||
- (locationY + windowH > applet.screen.height - 33)) {
- // otherwise center on screen
- locationX = (applet.screen.width - windowW) / 2;
- locationY = (applet.screen.height - windowH) / 2;
- }
- frame.setLocation(locationX, locationY);
- }
- } else { // just center on screen
- frame.setLocation((applet.screen.width - applet.width) / 2,
- (applet.screen.height - applet.height) / 2);
- }
-
- if (backgroundColor == Color.black) { //BLACK) {
- // this means no bg color unless specified
- backgroundColor = SystemColor.control;
- }
- frame.setBackground(backgroundColor);
-
- int usableWindowH = windowH - insets.top - insets.bottom;
- applet.setBounds((windowW - applet.width)/2,
- insets.top + (usableWindowH - applet.height)/2,
- applet.width, applet.height);
-
- if (external) {
- applet.setupExternalMessages();
-
- } else { // !external
- frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- System.exit(0);
- }
- });
- }
-
- // handle frame resizing events
- applet.setupFrameResizeListener();
-
- // all set for rockin
- if (applet.displayable()) {
- frame.setVisible(true);
- }
- }
-
- applet.requestFocus(); // ask for keydowns
- //System.out.println("exiting main()");
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- /**
- * Begin recording to a new renderer of the specified type, using the width
- * and height of the main drawing surface.
- */
- public PGraphics beginRecord(String renderer, String filename) {
- filename = insertFrame(filename);
- PGraphics rec = createGraphics(width, height, renderer, filename);
- beginRecord(rec);
- return rec;
- }
-
-
- /**
- * Begin recording (echoing) commands to the specified PGraphics object.
- */
- public void beginRecord(PGraphics recorder) {
- this.recorder = recorder;
- recorder.beginDraw();
- }
-
-
- public void endRecord() {
- if (recorder != null) {
- recorder.endDraw();
- recorder.dispose();
- recorder = null;
- }
- }
-
-
- /**
- * Begin recording raw shape data to a renderer of the specified type,
- * using the width and height of the main drawing surface.
- *
- * If hashmarks (###) are found in the filename, they'll be replaced
- * by the current frame number (frameCount).
- */
- public PGraphics beginRaw(String renderer, String filename) {
- filename = insertFrame(filename);
- PGraphics rec = createGraphics(width, height, renderer, filename);
- g.beginRaw(rec);
- return rec;
- }
-
-
- /**
- * Begin recording raw shape data to the specified renderer.
- *
- * This simply echoes to g.beginRaw(), but since is placed here (rather than
- * generated by preproc.pl) for clarity and so that it doesn't echo the
- * command should beginRecord() be in use.
- */
- public void beginRaw(PGraphics rawGraphics) {
- g.beginRaw(rawGraphics);
- }
-
-
- /**
- * Stop recording raw shape data to the specified renderer.
- *
- * This simply echoes to g.beginRaw(), but since is placed here (rather than
- * generated by preproc.pl) for clarity and so that it doesn't echo the
- * command should beginRecord() be in use.
- */
- public void endRaw() {
- g.endRaw();
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- /**
- * Loads the pixel data for the display window into the pixels[] array. This function must always be called before reading from or writing to pixels[].
- *
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. NO TOUCH!
- // This includes all of the comments, which are automatically pulled
- // from their respective functions in PGraphics or PImage.
-
- // public functions for processing.core
-
-
- public void flush() {
- if (recorder != null) recorder.flush();
- g.flush();
- }
-
-
- /**
- * Enable a hint option.
- *
- * For the most part, hints are temporary api quirks,
- * for which a proper api hasn't been properly worked out.
- * for instance SMOOTH_IMAGES existed because smooth()
- * wasn't yet implemented, but it will soon go away.
- *
- * They also exist for obscure features in the graphics
- * engine, like enabling/disabling single pixel lines
- * that ignore the zbuffer, the way they do in alphabot.
- *
- * Current hint options:
- *
- *
DISABLE_DEPTH_TEST -
- * turns off the z-buffer in the P3D or OPENGL renderers.
- *
- */
- 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.
- *
- * 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.
- *
- * This is for drawing three dimensional shapes and surfaces,
- * allowing you to specify a vector perpendicular to the surface
- * of the shape, which determines how lighting affects it.
- *
- * For the most part, PGraphics3D will attempt to automatically
- * assign normals to shapes, but since that's imperfect,
- * this is a better option when you want more control.
- *
- * For people familiar with OpenGL, this function is basically
- * identical to glNormal3f().
- */
- public void normal(float nx, float ny, float nz) {
- if (recorder != null) recorder.normal(nx, ny, nz);
- g.normal(nx, ny, nz);
- }
-
-
- /**
- * Set texture mode to either to use coordinates based on the IMAGE
- * (more intuitive for new users) or NORMALIZED (better for advanced chaps)
- */
- public void textureMode(int mode) {
- if (recorder != null) recorder.textureMode(mode);
- g.textureMode(mode);
- }
-
-
- /**
- * Set texture image for current shape.
- * Needs to be called between @see beginShape and @see endShape
- *
- * @param image reference to a PImage object
- */
- public void texture(PImage image) {
- if (recorder != null) recorder.texture(image);
- g.texture(image);
- }
-
-
- public void vertex(float x, float y) {
- if (recorder != null) recorder.vertex(x, y);
- g.vertex(x, y);
- }
-
-
- public void vertex(float x, float y, float z) {
- if (recorder != null) recorder.vertex(x, y, z);
- g.vertex(x, y, z);
- }
-
-
- /**
- * Used by renderer subclasses or PShape to efficiently pass in already
- * formatted vertex information.
- * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT
- */
- public void vertex(float[] v) {
- if (recorder != null) recorder.vertex(v);
- g.vertex(v);
- }
-
-
- public void vertex(float x, float y, float u, float v) {
- if (recorder != null) recorder.vertex(x, y, u, v);
- g.vertex(x, y, u, v);
- }
-
-
- public void vertex(float x, float y, float z, float u, float v) {
- if (recorder != null) recorder.vertex(x, y, z, u, v);
- g.vertex(x, y, z, u, v);
- }
-
-
- /** This feature is in testing, do not use or rely upon its implementation */
- public void breakShape() {
- if (recorder != null) recorder.breakShape();
- g.breakShape();
- }
-
-
- public void endShape() {
- if (recorder != null) recorder.endShape();
- g.endShape();
- }
-
-
- public void endShape(int mode) {
- if (recorder != null) recorder.endShape(mode);
- g.endShape(mode);
- }
-
-
- public void bezierVertex(float x2, float y2,
- float x3, float y3,
- float x4, float y4) {
- if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4);
- g.bezierVertex(x2, y2, x3, y3, x4, y4);
- }
-
-
- public void bezierVertex(float x2, float y2, float z2,
- float x3, float y3, float z3,
- float x4, float y4, float z4) {
- if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
- g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
- }
-
-
- public void curveVertex(float x, float y) {
- if (recorder != null) recorder.curveVertex(x, y);
- g.curveVertex(x, y);
- }
-
-
- public void curveVertex(float x, float y, float z) {
- if (recorder != null) recorder.curveVertex(x, y, z);
- g.curveVertex(x, y, z);
- }
-
-
- public void point(float x, float y) {
- if (recorder != null) recorder.point(x, y);
- g.point(x, y);
- }
-
-
- 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);
- }
-
-
- 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);
- }
-
-
- 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);
- }
-
-
- 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);
- }
-
-
- 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 ellipseMode(int mode) {
- if (recorder != null) recorder.ellipseMode(mode);
- g.ellipseMode(mode);
- }
-
-
- 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);
- }
-
-
- /**
- * Identical parameters and placement to ellipse,
- * but draws only an arc of that ellipse.
- *
- * start and stop are always radians because angleMode() was goofy.
- * ellipseMode() sets the placement.
- *
- * also tries to be smart about start < stop.
- */
- 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);
- }
-
-
- public void box(float size) {
- if (recorder != null) recorder.box(size);
- g.box(size);
- }
-
-
- public void box(float w, float h, float d) {
- if (recorder != null) recorder.box(w, h, d);
- g.box(w, h, d);
- }
-
-
- public void sphereDetail(int res) {
- if (recorder != null) recorder.sphereDetail(res);
- g.sphereDetail(res);
- }
-
-
- /**
- * Set the detail level for approximating a sphere. The ures and vres params
- * control the horizontal and vertical resolution.
- *
- * Code for sphereDetail() submitted by toxi [031031].
- * Code for enhanced u/v version from davbol [080801].
- */
- 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.
- *
- * 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
- *
- * [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
- *
- */
- 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.
- * t varies between 0 and 1, and a and d are the on curve points,
- * 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 bezier curve at t.
- *
- * 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();
- */
- public float bezierPoint(float a, float b, float c, float d, float t) {
- return g.bezierPoint(a, b, c, d, t);
- }
-
-
- /**
- * Provide the tangent at the given point on the bezier curve.
- * Fix from davbol for 0136.
- */
- public float bezierTangent(float a, float b, float c, float d, float t) {
- return g.bezierTangent(a, b, c, d, t);
- }
-
-
- public void bezierDetail(int detail) {
- if (recorder != null) recorder.bezierDetail(detail);
- g.bezierDetail(detail);
- }
-
-
- /**
- * 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.
- *
- * 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);
- */
- 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);
- }
-
-
- /**
- * Get a location along a catmull-rom curve segment.
- *
- * @param t Value between zero and one for how far along the segment
- */
- public float curvePoint(float a, float b, float c, float d, float t) {
- return g.curvePoint(a, b, c, d, t);
- }
-
-
- /**
- * Calculate the tangent at a t value (0..1) on a Catmull-Rom curve.
- * Code thanks to Dave Bollinger (Bug #715)
- */
- public float curveTangent(float a, float b, float c, float d, float t) {
- return g.curveTangent(a, b, c, d, t);
- }
-
-
- public void curveDetail(int detail) {
- if (recorder != null) recorder.curveDetail(detail);
- g.curveDetail(detail);
- }
-
-
- public void curveTightness(float tightness) {
- if (recorder != null) recorder.curveTightness(tightness);
- g.curveTightness(tightness);
- }
-
-
- /**
- * Draws a segment of Catmull-Rom curve.
- *
- * As of 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().
- *
- */
- 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();
- }
-
-
- /**
- * The mode can only be set to CORNERS, CORNER, and CENTER.
- *
- * Support for CENTER was added in release 0146.
- */
- 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);
- }
-
-
- 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);
- }
-
-
- /**
- * Set the orientation for the shape() command (like imageMode() or rectMode()).
- * @param mode Either CORNER, CORNERS, or CENTER.
- */
- 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);
- }
-
-
- 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);
- }
-
-
- /**
- * 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.
- *
- * 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);
- }
-
-
- 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.
- */
- 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);
- }
-
-
- 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);
- }
-
-
- 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);
- }
-
-
- 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);
- }
-
-
- public void tint(int rgb, float alpha) {
- if (recorder != null) recorder.tint(rgb, alpha);
- g.tint(rgb, alpha);
- }
-
-
- 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);
- }
-
-
- 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);
- }
-
-
- public void noFill() {
- if (recorder != null) recorder.noFill();
- g.noFill();
- }
-
-
- /**
- * Set the fill to either a grayscale value or an ARGB int.
- */
- 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);
- }
-
-
- 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);
- }
-
-
- 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.
- *
- * 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.
- */
- 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).
- */
- 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);
- }
-
-
- /**
- * 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.
- */
- public void background(float x, float y, float z, float a) {
- if (recorder != null) recorder.background(x, y, z, a);
- g.background(x, y, z, a);
- }
-
-
- /**
- * Takes an RGB or ARGB image and sets it as the background.
- * The width and height of the image must be the same size as the sketch.
- * Use image.resize(width, height) to make short work of such a task.
- *
- * 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);
- }
-
-
- 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
- *
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);
- }
-
-
- 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);
- }
-
-
- public final float alpha(int what) {
- return g.alpha(what);
- }
-
-
- public final float red(int what) {
- return g.red(what);
- }
-
-
- public final float green(int what) {
- return g.green(what);
- }
-
-
- public final float blue(int what) {
- return g.blue(what);
- }
-
-
- public final float hue(int what) {
- return g.hue(what);
- }
-
-
- public final float saturation(int what) {
- return g.saturation(what);
- }
-
-
- public final float brightness(int what) {
- return g.brightness(what);
- }
-
-
- /**
- * Interpolate between two colors, using the current color mode.
- */
- 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.
- *
- * 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).
- *
- * 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.
- *
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 image. The x and y parameter specify the pixel or the upper-left corner of the image. The color parameter specifies the color value.
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". Processing requires calling loadPixels() to load the display window data into the pixels[] array before getting the values and calling updatePixels() to update the window.
- *
As of release 0149, this function ignores imageMode().
- *
- * @webref
- * @brief Writes a color to any pixel or writes an image into another
- * @param x x-coordinate of the pixel or upper-left corner of the image
- * @param y y-coordinate of the pixel or upper-left corner of the image
- * @param c any value of the color datatype
- *
- * @see processing.core.PImage#get(int, int, int, int)
- * @see processing.core.PImage#pixels
- * @see processing.core.PImage#copy(PImage, int, int, int, int, int, int, int, int)
- */
- 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.
- *
- * 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:
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.
- *
- *
- *
filter(BLUR) provides a basic blur.
- *
filter(GRAY) converts the image to grayscale based on luminance.
- *
filter(INVERT) will invert the color components in the image.
- *
filter(OPAQUE) set all the high bits in the image to opaque
- *
filter(THRESHOLD) converts the image to black and white.
- *
filter(DILATE) grow white/light areas
- *
filter(ERODE) shrink white/light areas
- *
- * 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.PApplet#alpha(int)
- * @see processing.core.PApplet#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.
- *
- *
REPLACE - destination colour equals colour of source pixel: C = A.
- * Sometimes called "Normal" or "Copy" in other software.
- *
- *
BLEND - linear interpolation of colours:
- * C = A*factor + B
- *
- *
ADD - additive blending with white clip:
- * C = min(A*factor + B, 255).
- * Clipped to 0..255, Photoshop calls this "Linear Burn",
- * and Director calls it "Add Pin".
- *
- *
SUBTRACT - substractive blend with black clip:
- * C = max(B - A*factor, 0).
- * Clipped to 0..255, Photoshop calls this "Linear Dodge",
- * and Director calls it "Subtract Pin".
- *
- *
DARKEST - only the darkest colour succeeds:
- * C = min(A*factor, B).
- * Illustrator calls this "Darken".
- *
- *
LIGHTEST - only the lightest colour succeeds:
- * C = max(A*factor, B).
- * Illustrator calls this "Lighten".
- *
- *
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.
- *
- *
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.
- */
- static public int blendColor(int c1, int c2, int mode) {
- return PGraphics.blendColor(c1, c2, mode);
- }
-
-
- /**
- * Blends one area of this image to another area.
- *
- *
- * @see processing.core.PImage#blendColor(int,int,int)
- */
- public void blend(int sx, int sy, int sw, int sh,
- int dx, int dy, int dw, int dh, int mode) {
- if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
- g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
- }
-
-
- /**
- * Blends a region of pixels into the image specified by the img parameter. These copies utilize full alpha channel support and a choice of the following modes to blend the colors of source pixels (A) with the ones of pixels in the destination image (B):
- * 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.PApplet#alpha(int)
- * @see processing.core.PApplet#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);
- }
-}
diff --git a/core/methods/demo/PGraphics.java b/core/methods/demo/PGraphics.java
deleted file mode 100644
index 95834f24b00..00000000000
--- a/core/methods/demo/PGraphics.java
+++ /dev/null
@@ -1,5075 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2004-09 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.*;
-import java.util.HashMap;
-
-
-/**
- * Main graphics and rendering context, as well as the base API implementation for processing "core".
- * Use this class if you need to draw into an off-screen graphics buffer.
- * A PGraphics object can be constructed with the createGraphics() function.
- * The beginDraw() and endDraw() methods (see above example) are necessary to set up the buffer and to finalize it.
- * The fields and methods for this class are extensive;
- * for a complete list visit the developer's reference: http://dev.processing.org/reference/core/
- * =advanced
- * Main graphics and rendering context, as well as the base API implementation.
- *
- *
Subclassing and initializing PGraphics objects
- * Starting in release 0149, subclasses of PGraphics are handled differently.
- * The constructor for subclasses takes no parameters, instead a series of
- * functions are called by the hosting PApplet to specify its attributes.
- *
- *
setParent(PApplet) - is called to specify the parent PApplet.
- *
setPrimary(boolean) - called with true if this PGraphics will be the
- * primary drawing surface used by the sketch, or false if not.
- *
setPath(String) - called when the renderer needs a filename or output
- * path, such as with the PDF or DXF renderers.
- *
setSize(int, int) - this is called last, at which point it's safe for
- * the renderer to complete its initialization routine.
- *
- * The functions were broken out because of the growing number of parameters
- * such as these that might be used by a renderer, yet with the exception of
- * setSize(), it's not clear which will be necessary. So while the size could
- * be passed in to the constructor instead of a setSize() function, a function
- * would still be needed that would notify the renderer that it was time to
- * finish its initialization. Thus, setSize() simply does both.
- *
- *
Know your rights: public vs. private methods
- * Methods that are protected are often subclassed by other renderers, however
- * they are not set 'public' because they shouldn't be part of the user-facing
- * public API accessible from PApplet. That is, we don't want sketches calling
- * textModeCheck() or vertexTexture() directly.
- *
- *
Handling warnings and exceptions
- * Methods that are unavailable generally show a warning, unless their lack of
- * availability will soon cause another exception. For instance, if a method
- * like getMatrix() returns null because it is unavailable, an exception will
- * be thrown stating that the method is unavailable, rather than waiting for
- * the NullPointerException that will occur when the sketch tries to use that
- * method. As of release 0149, warnings will only be shown once, and exceptions
- * have been changed to warnings where possible.
- *
- *
Using xxxxImpl() for subclassing smoothness
- * The xxxImpl() methods are generally renderer-specific handling for some
- * subset if tasks for a particular function (vague enough for you?) For
- * instance, imageImpl() handles drawing an image whose x/y/w/h and u/v coords
- * have been specified, and screen placement (independent of imageMode) has
- * been determined. There's no point in all renderers implementing the
- * if (imageMode == BLAH) placement/sizing logic, so that's handled
- * by PGraphics, which then calls imageImpl() once all that is figured out.
- *
- *
His brother PImage
- * PGraphics subclasses PImage so that it can be drawn and manipulated in a
- * similar fashion. As such, many methods are inherited from PGraphics,
- * though many are unavailable: for instance, resize() is not likely to be
- * implemented; the same goes for mask(), depending on the situation.
- *
- *
What's in PGraphics, what ain't
- * For the benefit of subclasses, as much as possible has been placed inside
- * PGraphics. For instance, bezier interpolation code and implementations of
- * the strokeCap() method (that simply sets the strokeCap variable) are
- * handled here. Features that will vary widely between renderers are located
- * inside the subclasses themselves. For instance, all matrix handling code
- * is per-renderer: Java 2D uses its own AffineTransform, P2D uses a PMatrix2D,
- * and PGraphics3D needs to keep continually update forward and reverse
- * transformations. A proper (future) OpenGL implementation will have all its
- * matrix madness handled by the card. Lighting also falls under this
- * category, however the base material property settings (emissive, specular,
- * et al.) are handled in PGraphics because they use the standard colorMode()
- * logic. Subclasses should override methods like emissiveFromCalc(), which
- * is a point where a valid color has been defined internally, and can be
- * applied in some manner based on the calcXxxx values.
- *
- *
What's in the PGraphics documentation, what ain't
- * Some things are noted here, some things are not. For public API, always
- * refer to the reference
- * on Processing.org for proper explanations. No attempt has been made to
- * keep the javadoc up to date or complete. It's an enormous task for
- * which we simply do not have the time. That is, it's not something that
- * to be done once—it's a matter of keeping the multiple references
- * synchronized (to say nothing of the translation issues), while targeting
- * them for their separate audiences. Ouch.
- *
- * We're working right now on synchronizing the two references, so the website reference
- * is generated from the javadoc comments. Yay.
- *
- * @webref rendering
- * @instanceName graphics any object of the type PGraphics
- * @usage Web & Application
- * @see processing.core.PApplet#createGraphics(int, int, String)
- */
-public class PGraphics extends PImage implements PConstants {
-
- // ........................................................
-
- // width and height are already inherited from PImage
-
-
- /// width minus one (useful for many calculations)
- protected int width1;
-
- /// height minus one (useful for many calculations)
- protected int height1;
-
- /// width * height (useful for many calculations)
- public int pixelCount;
-
- /// true if smoothing is enabled (read-only)
- public boolean smooth = false;
-
- // ........................................................
-
- /// true if defaults() has been called a first time
- protected boolean settingsInited;
-
- /// set to a PGraphics object being used inside a beginRaw/endRaw() block
- protected PGraphics raw;
-
- // ........................................................
-
- /** path to the file being saved for this renderer (if any) */
- protected String path;
-
- /**
- * true if this is the main drawing surface for a particular sketch.
- * This would be set to false for an offscreen buffer or if it were
- * created any other way than size(). When this is set, the listeners
- * are also added to the sketch.
- */
- protected boolean primarySurface;
-
- // ........................................................
-
- /**
- * Array of hint[] items. These are hacks to get around various
- * temporary workarounds inside the environment.
- *
- * Note that this array cannot be static, as a hint() may result in a
- * runtime change specific to a renderer. For instance, calling
- * hint(DISABLE_DEPTH_TEST) has to call glDisable() right away on an
- * instance of PGraphicsOpenGL.
- *
- * The hints[] array is allocated early on because it might
- * be used inside beginDraw(), allocate(), etc.
- */
- protected boolean[] hints = new boolean[HINT_COUNT];
-
-
- ////////////////////////////////////////////////////////////
-
- // STYLE PROPERTIES
-
- // Also inherits imageMode() and smooth() (among others) from PImage.
-
- /** The current colorMode */
- public int colorMode; // = RGB;
-
- /** Max value for red (or hue) set by colorMode */
- public float colorModeX; // = 255;
-
- /** Max value for green (or saturation) set by colorMode */
- public float colorModeY; // = 255;
-
- /** Max value for blue (or value) set by colorMode */
- public float colorModeZ; // = 255;
-
- /** Max value for alpha set by colorMode */
- public float colorModeA; // = 255;
-
- /** True if colors are not in the range 0..1 */
- boolean colorModeScale; // = true;
-
- /** True if colorMode(RGB, 255) */
- boolean colorModeDefault; // = true;
-
- // ........................................................
-
- // Tint color for images
-
- /**
- * True if tint() is enabled (read-only).
- *
- * Using tint/tintColor seems a better option for naming than
- * tintEnabled/tint because the latter seems ugly, even though
- * g.tint as the actual color seems a little more intuitive,
- * it's just that g.tintEnabled is even more unintuitive.
- * Same goes for fill and stroke, et al.
- */
- public boolean tint;
-
- /** tint that was last set (read-only) */
- public int tintColor;
-
- protected boolean tintAlpha;
- protected float tintR, tintG, tintB, tintA;
- protected int tintRi, tintGi, tintBi, tintAi;
-
- // ........................................................
-
- // Fill color
-
- /** true if fill() is enabled, (read-only) */
- public boolean fill;
-
- /** fill that was last set (read-only) */
- public int fillColor = 0xffFFFFFF;
-
- protected boolean fillAlpha;
- protected float fillR, fillG, fillB, fillA;
- protected int fillRi, fillGi, fillBi, fillAi;
-
- // ........................................................
-
- // Stroke color
-
- /** true if stroke() is enabled, (read-only) */
- public boolean stroke;
-
- /** stroke that was last set (read-only) */
- public int strokeColor = 0xff000000;
-
- protected boolean strokeAlpha;
- protected float strokeR, strokeG, strokeB, strokeA;
- protected int strokeRi, strokeGi, strokeBi, strokeAi;
-
- // ........................................................
-
- // Additional stroke properties
-
- static protected final float DEFAULT_STROKE_WEIGHT = 1;
- static protected final int DEFAULT_STROKE_JOIN = MITER;
- static protected final int DEFAULT_STROKE_CAP = ROUND;
-
- /**
- * Last value set by strokeWeight() (read-only). This has a default
- * setting, rather than fighting with renderers about whether that
- * renderer supports thick lines.
- */
- public float strokeWeight = DEFAULT_STROKE_WEIGHT;
-
- /**
- * Set by strokeJoin() (read-only). This has a default setting
- * so that strokeJoin() need not be called by defaults,
- * because subclasses may not implement it (i.e. PGraphicsGL)
- */
- public int strokeJoin = DEFAULT_STROKE_JOIN;
-
- /**
- * Set by strokeCap() (read-only). This has a default setting
- * so that strokeCap() need not be called by defaults,
- * because subclasses may not implement it (i.e. PGraphicsGL)
- */
- public int strokeCap = DEFAULT_STROKE_CAP;
-
- // ........................................................
-
- // Shape placement properties
-
- // imageMode() is inherited from PImage
-
- /** The current rect mode (read-only) */
- public int rectMode;
-
- /** The current ellipse mode (read-only) */
- public int ellipseMode;
-
- /** The current shape alignment mode (read-only) */
- public int shapeMode;
-
- /** The current image alignment (read-only) */
- public int imageMode = CORNER;
-
- // ........................................................
-
- // Text and font properties
-
- /** The current text font (read-only) */
- public PFont textFont;
-
- /** The current text align (read-only) */
- public int textAlign = LEFT;
-
- /** The current vertical text alignment (read-only) */
- public int textAlignY = BASELINE;
-
- /** The current text mode (read-only) */
- public int textMode = MODEL;
-
- /** The current text size (read-only) */
- public float textSize;
-
- /** The current text leading (read-only) */
- public float textLeading;
-
- // ........................................................
-
- // Material properties
-
-// PMaterial material;
-// PMaterial[] materialStack;
-// int materialStackPointer;
-
- public float ambientR, ambientG, ambientB;
- public float specularR, specularG, specularB;
- public float emissiveR, emissiveG, emissiveB;
- public float shininess;
-
-
- // Style stack
-
- static final int STYLE_STACK_DEPTH = 64;
- PStyle[] styleStack = new PStyle[STYLE_STACK_DEPTH];
- int styleStackDepth;
-
-
- ////////////////////////////////////////////////////////////
-
-
- /** Last background color that was set, zero if an image */
- public int backgroundColor = 0xffCCCCCC;
-
- protected boolean backgroundAlpha;
- protected float backgroundR, backgroundG, backgroundB, backgroundA;
- protected int backgroundRi, backgroundGi, backgroundBi, backgroundAi;
-
- // ........................................................
-
- /**
- * Current model-view matrix transformation of the form m[row][column],
- * which is a "column vector" (as opposed to "row vector") matrix.
- */
-// PMatrix matrix;
-// public float m00, m01, m02, m03;
-// public float m10, m11, m12, m13;
-// public float m20, m21, m22, m23;
-// public float m30, m31, m32, m33;
-
-// static final int MATRIX_STACK_DEPTH = 32;
-// float[][] matrixStack = new float[MATRIX_STACK_DEPTH][16];
-// float[][] matrixInvStack = new float[MATRIX_STACK_DEPTH][16];
-// int matrixStackDepth;
-
- static final int MATRIX_STACK_DEPTH = 32;
-
- // ........................................................
-
- /**
- * Java AWT Image object associated with this renderer. For P2D and P3D,
- * this will be associated with their MemoryImageSource. For PGraphicsJava2D,
- * it will be the offscreen drawing buffer.
- */
- public Image image;
-
- // ........................................................
-
- // internal color for setting/calculating
- protected float calcR, calcG, calcB, calcA;
- protected int calcRi, calcGi, calcBi, calcAi;
- protected int calcColor;
- protected boolean calcAlpha;
-
- /** The last RGB value converted to HSB */
- int cacheHsbKey;
- /** Result of the last conversion to HSB */
- float[] cacheHsbValue = new float[3];
-
- // ........................................................
-
- /**
- * Type of shape passed to beginShape(),
- * zero if no shape is currently being drawn.
- */
- protected int shape;
-
- // vertices
- static final int DEFAULT_VERTICES = 512;
- protected float vertices[][] =
- new float[DEFAULT_VERTICES][VERTEX_FIELD_COUNT];
- protected int vertexCount; // total number of vertices
-
- // ........................................................
-
- protected boolean bezierInited = false;
- public int bezierDetail = 20;
-
- // used by both curve and bezier, so just init here
- protected PMatrix3D bezierBasisMatrix =
- new PMatrix3D(-1, 3, -3, 1,
- 3, -6, 3, 0,
- -3, 3, 0, 0,
- 1, 0, 0, 0);
-
- //protected PMatrix3D bezierForwardMatrix;
- protected PMatrix3D bezierDrawMatrix;
-
- // ........................................................
-
- protected boolean curveInited = false;
- protected int curveDetail = 20;
- public float curveTightness = 0;
- // catmull-rom basis matrix, perhaps with optional s parameter
- protected PMatrix3D curveBasisMatrix;
- protected PMatrix3D curveDrawMatrix;
-
- protected PMatrix3D bezierBasisInverse;
- protected PMatrix3D curveToBezierMatrix;
-
- // ........................................................
-
- // spline vertices
-
- protected float curveVertices[][];
- protected int curveVertexCount;
-
- // ........................................................
-
- // precalculate sin/cos lookup tables [toxi]
- // circle resolution is determined from the actual used radii
- // passed to ellipse() method. this will automatically take any
- // scale transformations into account too
-
- // [toxi 031031]
- // changed table's precision to 0.5 degree steps
- // introduced new vars for more flexible code
- static final protected float sinLUT[];
- static final protected float cosLUT[];
- static final protected float SINCOS_PRECISION = 0.5f;
- static final protected int SINCOS_LENGTH = (int) (360f / SINCOS_PRECISION);
- static {
- sinLUT = new float[SINCOS_LENGTH];
- cosLUT = new float[SINCOS_LENGTH];
- for (int i = 0; i < SINCOS_LENGTH; i++) {
- sinLUT[i] = (float) Math.sin(i * DEG_TO_RAD * SINCOS_PRECISION);
- cosLUT[i] = (float) Math.cos(i * DEG_TO_RAD * SINCOS_PRECISION);
- }
- }
-
- // ........................................................
-
- /** The current font if a Java version of it is installed */
- //protected Font textFontNative;
-
- /** Metrics for the current native Java font */
- //protected FontMetrics textFontNativeMetrics;
-
- /** Last text position, because text often mixed on lines together */
- protected float textX, textY, textZ;
-
- /**
- * Internal buffer used by the text() functions
- * because the String object is slow
- */
- protected char[] textBuffer = new char[8 * 1024];
- protected char[] textWidthBuffer = new char[8 * 1024];
-
- protected int textBreakCount;
- protected int[] textBreakStart;
- protected int[] textBreakStop;
-
- // ........................................................
-
- public boolean edge = true;
-
- // ........................................................
-
- /// normal calculated per triangle
- static protected final int NORMAL_MODE_AUTO = 0;
- /// one normal manually specified per shape
- static protected final int NORMAL_MODE_SHAPE = 1;
- /// normals specified for each shape vertex
- static protected final int NORMAL_MODE_VERTEX = 2;
-
- /// Current mode for normals, one of AUTO, SHAPE, or VERTEX
- protected int normalMode;
-
- /// Keep track of how many calls to normal, to determine the mode.
- //protected int normalCount;
-
- /** Current normal vector. */
- public float normalX, normalY, normalZ;
-
- // ........................................................
-
- /**
- * Sets whether texture coordinates passed to
- * vertex() calls will be based on coordinates that are
- * based on the IMAGE or NORMALIZED.
- */
- public int textureMode;
-
- /**
- * Current horizontal coordinate for texture, will always
- * be between 0 and 1, even if using textureMode(IMAGE).
- */
- public float textureU;
-
- /** Current vertical coordinate for texture, see above. */
- public float textureV;
-
- /** Current image being used as a texture */
- public PImage textureImage;
-
- // ........................................................
-
- // [toxi031031] new & faster sphere code w/ support flexibile resolutions
- // will be set by sphereDetail() or 1st call to sphere()
- float sphereX[], sphereY[], sphereZ[];
-
- /// Number of U steps (aka "theta") around longitudinally spanning 2*pi
- public int sphereDetailU = 0;
- /// Number of V steps (aka "phi") along latitudinally top-to-bottom spanning pi
- public int sphereDetailV = 0;
-
-
- //////////////////////////////////////////////////////////////
-
- // INTERNAL
-
-
- /**
- * Constructor for the PGraphics object. Use this to ensure that
- * the defaults get set properly. In a subclass, use this(w, h)
- * as the first line of a subclass' constructor to properly set
- * the internal fields and defaults.
- *
- */
- public PGraphics() {
- }
-
-
- public void setParent(PApplet parent) { // ignore
- this.parent = parent;
- }
-
-
- /**
- * Set (or unset) this as the main drawing surface. Meaning that it can
- * safely be set to opaque (and given a default gray background), or anything
- * else that goes along with that.
- */
- public void setPrimary(boolean primary) { // ignore
- this.primarySurface = primary;
-
- // base images must be opaque (for performance and general
- // headache reasons.. argh, a semi-transparent opengl surface?)
- // use createGraphics() if you want a transparent surface.
- if (primarySurface) {
- format = RGB;
- }
- }
-
-
- public void setPath(String path) { // ignore
- this.path = path;
- }
-
-
- /**
- * The final step in setting up a renderer, set its size of this renderer.
- * This was formerly handled by the constructor, but instead it's been broken
- * out so that setParent/setPrimary/setPath can be handled differently.
- *
- * Important that this is ignored by preproc.pl because otherwise it will
- * override setSize() in PApplet/Applet/Component, which will 1) not call
- * super.setSize(), and 2) will cause the renderer to be resized from the
- * event thread (EDT), causing a nasty crash as it collides with the
- * animation thread.
- */
- public void setSize(int w, int h) { // ignore
- width = w;
- height = h;
- width1 = width - 1;
- height1 = height - 1;
-
- allocate();
- reapplySettings();
- }
-
-
- /**
- * Allocate memory for this renderer. Generally will need to be implemented
- * for all renderers.
- */
- protected void allocate() { }
-
-
- /**
- * Handle any takedown for this graphics context.
- *
- * This is called when a sketch is shut down and this renderer was
- * specified using the size() command, or inside endRecord() and
- * endRaw(), in order to shut things off.
- */
- public void dispose() { // ignore
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // FRAME
-
-
- /**
- * Some renderers have requirements re: when they are ready to draw.
- */
- public boolean canDraw() { // ignore
- return true;
- }
-
-
- /**
- * Sets the default properties for a PGraphics object. It should be called before anything is drawn into the object.
- * =advanced
- *
- * When creating your own PGraphics, you should call this before
- * drawing anything.
- *
- * @webref
- * @brief Sets up the rendering context
- */
- public void beginDraw() { // ignore
- }
-
-
- /**
- * Finalizes the rendering of a PGraphics object so that it can be shown on screen.
- * =advanced
- *
- * When creating your own PGraphics, you should call this when
- * you're finished drawing.
- *
- * @webref
- * @brief Finalizes the renderering context
- */
- public void endDraw() { // ignore
- }
-
-
- public void flush() {
- // no-op, mostly for P3D to write sorted stuff
- }
-
-
- protected void checkSettings() {
- if (!settingsInited) defaultSettings();
- }
-
-
- /**
- * Set engine's default values. This has to be called by PApplet,
- * somewhere inside setup() or draw() because it talks to the
- * graphics buffer, meaning that for subclasses like OpenGL, there
- * needs to be a valid graphics context to mess with otherwise
- * you'll get some good crashing action.
- *
- * This is currently called by checkSettings(), during beginDraw().
- */
- protected void defaultSettings() { // ignore
-// System.out.println("PGraphics.defaultSettings() " + width + " " + height);
-
- noSmooth(); // 0149
-
- colorMode(RGB, 255);
- fill(255);
- stroke(0);
- // other stroke attributes are set in the initializers
- // inside the class (see above, strokeWeight = 1 et al)
-
- // init shape stuff
- shape = 0;
-
- // init matrices (must do before lights)
- //matrixStackDepth = 0;
-
- rectMode(CORNER);
- ellipseMode(DIAMETER);
-
- // no current font
- textFont = null;
- textSize = 12;
- textLeading = 14;
- textAlign = LEFT;
- textMode = MODEL;
-
- // if this fella is associated with an applet, then clear its background.
- // if it's been created by someone else through createGraphics,
- // they have to call background() themselves, otherwise everything gets
- // a gray background (when just a transparent surface or an empty pdf
- // is what's desired).
- // this background() call is for the Java 2D and OpenGL renderers.
- if (primarySurface) {
- //System.out.println("main drawing surface bg " + getClass().getName());
- background(backgroundColor);
- }
-
- settingsInited = true;
- // defaultSettings() overlaps reapplySettings(), don't do both
- //reapplySettings = false;
- }
-
-
- /**
- * Re-apply current settings. Some methods, such as textFont(), require that
- * their methods be called (rather than simply setting the textFont variable)
- * because they affect the graphics context, or they require parameters from
- * the context (e.g. getting native fonts for text).
- *
- * This will only be called from an allocate(), which is only called from
- * size(), which is safely called from inside beginDraw(). And it cannot be
- * called before defaultSettings(), so we should be safe.
- */
- protected void reapplySettings() {
-// System.out.println("attempting reapplySettings()");
- if (!settingsInited) return; // if this is the initial setup, no need to reapply
-
-// System.out.println(" doing reapplySettings");
-// new Exception().printStackTrace(System.out);
-
- colorMode(colorMode, colorModeX, colorModeY, colorModeZ);
- if (fill) {
-// PApplet.println(" fill " + PApplet.hex(fillColor));
- fill(fillColor);
- } else {
- noFill();
- }
- if (stroke) {
- stroke(strokeColor);
-
- // The if() statements should be handled inside the functions,
- // otherwise an actual reset/revert won't work properly.
- //if (strokeWeight != DEFAULT_STROKE_WEIGHT) {
- strokeWeight(strokeWeight);
- //}
-// if (strokeCap != DEFAULT_STROKE_CAP) {
- strokeCap(strokeCap);
-// }
-// if (strokeJoin != DEFAULT_STROKE_JOIN) {
- strokeJoin(strokeJoin);
-// }
- } else {
- noStroke();
- }
- if (tint) {
- tint(tintColor);
- } else {
- noTint();
- }
- if (smooth) {
- smooth();
- } else {
- // Don't bother setting this, cuz it'll anger P3D.
- noSmooth();
- }
- if (textFont != null) {
-// System.out.println(" textFont in reapply is " + textFont);
- // textFont() resets the leading, so save it in case it's changed
- float saveLeading = textLeading;
- textFont(textFont, textSize);
- textLeading(saveLeading);
- }
- textMode(textMode);
- textAlign(textAlign, textAlignY);
- background(backgroundColor);
-
- //reapplySettings = false;
- }
-
-
- //////////////////////////////////////////////////////////////
-
- // HINTS
-
- /**
- * Enable a hint option.
- *
- * For the most part, hints are temporary api quirks,
- * for which a proper api hasn't been properly worked out.
- * for instance SMOOTH_IMAGES existed because smooth()
- * wasn't yet implemented, but it will soon go away.
- *
- * They also exist for obscure features in the graphics
- * engine, like enabling/disabling single pixel lines
- * that ignore the zbuffer, the way they do in alphabot.
- *
- * Current hint options:
- *
- *
DISABLE_DEPTH_TEST -
- * turns off the z-buffer in the P3D or OPENGL renderers.
- *
- */
- public void hint(int which) {
- if (which > 0) {
- hints[which] = true;
- } else {
- hints[-which] = false;
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // VERTEX SHAPES
-
- /**
- * Start a new shape of type POLYGON
- */
- public void beginShape() {
- beginShape(POLYGON);
- }
-
-
- /**
- * Start a new shape.
- *
- * 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) {
- shape = kind;
- }
-
-
- /**
- * Sets whether the upcoming vertex is part of an edge.
- * Equivalent to glEdgeFlag(), for people familiar with OpenGL.
- */
- public void edge(boolean edge) {
- this.edge = edge;
- }
-
-
- /**
- * Sets the current normal vector. Only applies with 3D rendering
- * and inside a beginShape/endShape block.
- *
- * This is for drawing three dimensional shapes and surfaces,
- * allowing you to specify a vector perpendicular to the surface
- * of the shape, which determines how lighting affects it.
- *
- * For the most part, PGraphics3D will attempt to automatically
- * assign normals to shapes, but since that's imperfect,
- * this is a better option when you want more control.
- *
- * For people familiar with OpenGL, this function is basically
- * identical to glNormal3f().
- */
- public void normal(float nx, float ny, float nz) {
- normalX = nx;
- normalY = ny;
- normalZ = nz;
-
- // if drawing a shape and the normal hasn't been set yet,
- // then we need to set the normals for each vertex so far
- if (shape != 0) {
- if (normalMode == NORMAL_MODE_AUTO) {
- // either they set the normals, or they don't [0149]
-// for (int i = vertex_start; i < vertexCount; i++) {
-// vertices[i][NX] = normalX;
-// vertices[i][NY] = normalY;
-// vertices[i][NZ] = normalZ;
-// }
- // One normal per begin/end shape
- normalMode = NORMAL_MODE_SHAPE;
-
- } else if (normalMode == NORMAL_MODE_SHAPE) {
- // a separate normal for each vertex
- normalMode = NORMAL_MODE_VERTEX;
- }
- }
- }
-
-
- /**
- * Set texture mode to either to use coordinates based on the IMAGE
- * (more intuitive for new users) or NORMALIZED (better for advanced chaps)
- */
- public void textureMode(int mode) {
- this.textureMode = mode;
- }
-
-
- /**
- * Set texture image for current shape.
- * Needs to be called between @see beginShape and @see endShape
- *
- * @param image reference to a PImage object
- */
- public void texture(PImage image) {
- textureImage = image;
- }
-
-
- protected void vertexCheck() {
- if (vertexCount == vertices.length) {
- float temp[][] = new float[vertexCount << 1][VERTEX_FIELD_COUNT];
- System.arraycopy(vertices, 0, temp, 0, vertexCount);
- vertices = temp;
- }
- }
-
-
- public void vertex(float x, float y) {
- vertexCheck();
- float[] vertex = vertices[vertexCount];
-
- curveVertexCount = 0;
-
- vertex[X] = x;
- vertex[Y] = y;
-
- vertex[EDGE] = edge ? 1 : 0;
-
-// if (fill) {
-// vertex[R] = fillR;
-// vertex[G] = fillG;
-// vertex[B] = fillB;
-// vertex[A] = fillA;
-// }
- if (fill || textureImage != null) {
- if (textureImage == null) {
- vertex[R] = fillR;
- vertex[G] = fillG;
- vertex[B] = fillB;
- vertex[A] = fillA;
- } else {
- if (tint) {
- vertex[R] = tintR;
- vertex[G] = tintG;
- vertex[B] = tintB;
- vertex[A] = tintA;
- } else {
- vertex[R] = 1;
- vertex[G] = 1;
- vertex[B] = 1;
- vertex[A] = 1;
- }
- }
- }
-
- if (stroke) {
- vertex[SR] = strokeR;
- vertex[SG] = strokeG;
- vertex[SB] = strokeB;
- vertex[SA] = strokeA;
- vertex[SW] = strokeWeight;
- }
-
- if (textureImage != null) {
- vertex[U] = textureU;
- vertex[V] = textureV;
- }
-
- vertexCount++;
- }
-
-
- public void vertex(float x, float y, float z) {
- vertexCheck();
- float[] vertex = vertices[vertexCount];
-
- // only do this if we're using an irregular (POLYGON) shape that
- // will go through the triangulator. otherwise it'll do thinks like
- // disappear in mathematically odd ways
- // http://dev.processing.org/bugs/show_bug.cgi?id=444
- if (shape == POLYGON) {
- if (vertexCount > 0) {
- float pvertex[] = vertices[vertexCount-1];
- if ((Math.abs(pvertex[X] - x) < EPSILON) &&
- (Math.abs(pvertex[Y] - y) < EPSILON) &&
- (Math.abs(pvertex[Z] - z) < EPSILON)) {
- // this vertex is identical, don't add it,
- // because it will anger the triangulator
- return;
- }
- }
- }
-
- // User called vertex(), so that invalidates anything queued up for curve
- // vertices. If this is internally called by curveVertexSegment,
- // then curveVertexCount will be saved and restored.
- curveVertexCount = 0;
-
- vertex[X] = x;
- vertex[Y] = y;
- vertex[Z] = z;
-
- vertex[EDGE] = edge ? 1 : 0;
-
- if (fill || textureImage != null) {
- if (textureImage == null) {
- vertex[R] = fillR;
- vertex[G] = fillG;
- vertex[B] = fillB;
- vertex[A] = fillA;
- } else {
- if (tint) {
- vertex[R] = tintR;
- vertex[G] = tintG;
- vertex[B] = tintB;
- vertex[A] = tintA;
- } else {
- vertex[R] = 1;
- vertex[G] = 1;
- vertex[B] = 1;
- vertex[A] = 1;
- }
- }
-
- vertex[AR] = ambientR;
- vertex[AG] = ambientG;
- vertex[AB] = ambientB;
-
- vertex[SPR] = specularR;
- vertex[SPG] = specularG;
- vertex[SPB] = specularB;
- //vertex[SPA] = specularA;
-
- vertex[SHINE] = shininess;
-
- vertex[ER] = emissiveR;
- vertex[EG] = emissiveG;
- vertex[EB] = emissiveB;
- }
-
- if (stroke) {
- vertex[SR] = strokeR;
- vertex[SG] = strokeG;
- vertex[SB] = strokeB;
- vertex[SA] = strokeA;
- vertex[SW] = strokeWeight;
- }
-
- if (textureImage != null) {
- vertex[U] = textureU;
- vertex[V] = textureV;
- }
-
- vertex[NX] = normalX;
- vertex[NY] = normalY;
- vertex[NZ] = normalZ;
-
- vertex[BEEN_LIT] = 0;
-
- vertexCount++;
- }
-
-
- /**
- * Used by renderer subclasses or PShape to efficiently pass in already
- * formatted vertex information.
- * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT
- */
- public void vertex(float[] v) {
- vertexCheck();
- curveVertexCount = 0;
- float[] vertex = vertices[vertexCount];
- System.arraycopy(v, 0, vertex, 0, VERTEX_FIELD_COUNT);
- vertexCount++;
- }
-
-
- public void vertex(float x, float y, float u, float v) {
- vertexTexture(u, v);
- vertex(x, y);
- }
-
-
- public void vertex(float x, float y, float z, float u, float v) {
- vertexTexture(u, v);
- vertex(x, y, z);
- }
-
-
- /**
- * Internal method to copy all style information for the given vertex.
- * Can be overridden by subclasses to handle only properties pertinent to
- * that renderer. (e.g. no need to copy the emissive color in P2D)
- */
-// protected void vertexStyle() {
-// }
-
-
- /**
- * Set (U, V) coords for the next vertex in the current shape.
- * This is ugly as its own function, and will (almost?) always be
- * coincident with a call to vertex. As of beta, this was moved to
- * the protected method you see here, and called from an optional
- * param of and overloaded vertex().
- *
- * The parameters depend on the current textureMode. When using
- * textureMode(IMAGE), the coordinates will be relative to the size
- * of the image texture, when used with textureMode(NORMAL),
- * they'll be in the range 0..1.
- *
- * Used by both PGraphics2D (for images) and PGraphics3D.
- */
- protected void vertexTexture(float u, float v) {
- if (textureImage == null) {
- throw new RuntimeException("You must first call texture() before " +
- "using u and v coordinates with vertex()");
- }
- if (textureMode == IMAGE) {
- u /= (float) textureImage.width;
- v /= (float) textureImage.height;
- }
-
- textureU = u;
- textureV = v;
-
- if (textureU < 0) textureU = 0;
- else if (textureU > 1) textureU = 1;
-
- if (textureV < 0) textureV = 0;
- else if (textureV > 1) textureV = 1;
- }
-
-
- /** This feature is in testing, do not use or rely upon its implementation */
- public void breakShape() {
- showWarning("This renderer cannot currently handle concave shapes, " +
- "or shapes with holes.");
- }
-
-
- public void endShape() {
- endShape(OPEN);
- }
-
-
- public void endShape(int mode) {
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CURVE/BEZIER VERTEX HANDLING
-
-
- protected void bezierVertexCheck() {
- if (shape == 0 || shape != POLYGON) {
- throw new RuntimeException("beginShape() or beginShape(POLYGON) " +
- "must be used before bezierVertex()");
- }
- if (vertexCount == 0) {
- throw new RuntimeException("vertex() must be used at least once" +
- "before bezierVertex()");
- }
- }
-
-
- public void bezierVertex(float x2, float y2,
- float x3, float y3,
- float x4, float y4) {
- bezierInitCheck();
- bezierVertexCheck();
- PMatrix3D draw = bezierDrawMatrix;
-
- float[] prev = vertices[vertexCount-1];
- float x1 = prev[X];
- float y1 = prev[Y];
-
- float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4;
- float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4;
- float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4;
-
- float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4;
- float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4;
- float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4;
-
- for (int j = 0; j < bezierDetail; j++) {
- x1 += xplot1; xplot1 += xplot2; xplot2 += xplot3;
- y1 += yplot1; yplot1 += yplot2; yplot2 += yplot3;
- vertex(x1, y1);
- }
- }
-
-
- public void bezierVertex(float x2, float y2, float z2,
- float x3, float y3, float z3,
- float x4, float y4, float z4) {
- bezierInitCheck();
- bezierVertexCheck();
- PMatrix3D draw = bezierDrawMatrix;
-
- float[] prev = vertices[vertexCount-1];
- float x1 = prev[X];
- float y1 = prev[Y];
- float z1 = prev[Z];
-
- float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4;
- float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4;
- float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4;
-
- float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4;
- float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4;
- float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4;
-
- float zplot1 = draw.m10*z1 + draw.m11*z2 + draw.m12*z3 + draw.m13*z4;
- float zplot2 = draw.m20*z1 + draw.m21*z2 + draw.m22*z3 + draw.m23*z4;
- float zplot3 = draw.m30*z1 + draw.m31*z2 + draw.m32*z3 + draw.m33*z4;
-
- for (int j = 0; j < bezierDetail; j++) {
- x1 += xplot1; xplot1 += xplot2; xplot2 += xplot3;
- y1 += yplot1; yplot1 += yplot2; yplot2 += yplot3;
- z1 += zplot1; zplot1 += zplot2; zplot2 += zplot3;
- vertex(x1, y1, z1);
- }
- }
-
-
- /**
- * Perform initialization specific to curveVertex(), and handle standard
- * error modes. Can be overridden by subclasses that need the flexibility.
- */
- protected void curveVertexCheck() {
- if (shape != POLYGON) {
- throw new RuntimeException("You must use beginShape() or " +
- "beginShape(POLYGON) before curveVertex()");
- }
- // to improve code init time, allocate on first use.
- if (curveVertices == null) {
- curveVertices = new float[128][3];
- }
-
- if (curveVertexCount == curveVertices.length) {
- // Can't use PApplet.expand() cuz it doesn't do the copy properly
- float[][] temp = new float[curveVertexCount << 1][3];
- System.arraycopy(curveVertices, 0, temp, 0, curveVertexCount);
- curveVertices = temp;
- }
- curveInitCheck();
- }
-
-
- public void curveVertex(float x, float y) {
- curveVertexCheck();
- float[] vertex = curveVertices[curveVertexCount];
- vertex[X] = x;
- vertex[Y] = y;
- curveVertexCount++;
-
- // draw a segment if there are enough points
- if (curveVertexCount > 3) {
- curveVertexSegment(curveVertices[curveVertexCount-4][X],
- curveVertices[curveVertexCount-4][Y],
- curveVertices[curveVertexCount-3][X],
- curveVertices[curveVertexCount-3][Y],
- curveVertices[curveVertexCount-2][X],
- curveVertices[curveVertexCount-2][Y],
- curveVertices[curveVertexCount-1][X],
- curveVertices[curveVertexCount-1][Y]);
- }
- }
-
-
- public void curveVertex(float x, float y, float z) {
- curveVertexCheck();
- float[] vertex = curveVertices[curveVertexCount];
- vertex[X] = x;
- vertex[Y] = y;
- vertex[Z] = z;
- curveVertexCount++;
-
- // draw a segment if there are enough points
- if (curveVertexCount > 3) {
- curveVertexSegment(curveVertices[curveVertexCount-4][X],
- curveVertices[curveVertexCount-4][Y],
- curveVertices[curveVertexCount-4][Z],
- curveVertices[curveVertexCount-3][X],
- curveVertices[curveVertexCount-3][Y],
- curveVertices[curveVertexCount-3][Z],
- curveVertices[curveVertexCount-2][X],
- curveVertices[curveVertexCount-2][Y],
- curveVertices[curveVertexCount-2][Z],
- curveVertices[curveVertexCount-1][X],
- curveVertices[curveVertexCount-1][Y],
- curveVertices[curveVertexCount-1][Z]);
- }
- }
-
-
- /**
- * Handle emitting a specific segment of Catmull-Rom curve. This can be
- * overridden by subclasses that need more efficient rendering options.
- */
- protected void curveVertexSegment(float x1, float y1,
- float x2, float y2,
- float x3, float y3,
- float x4, float y4) {
- float x0 = x2;
- float y0 = y2;
-
- PMatrix3D draw = curveDrawMatrix;
-
- float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4;
- float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4;
- float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4;
-
- float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4;
- float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4;
- float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4;
-
- // vertex() will reset splineVertexCount, so save it
- int savedCount = curveVertexCount;
-
- vertex(x0, y0);
- for (int j = 0; j < curveDetail; j++) {
- x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3;
- y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3;
- vertex(x0, y0);
- }
- curveVertexCount = savedCount;
- }
-
-
- /**
- * Handle emitting a specific segment of Catmull-Rom curve. This can be
- * overridden by subclasses that need more efficient rendering options.
- */
- protected void curveVertexSegment(float x1, float y1, float z1,
- float x2, float y2, float z2,
- float x3, float y3, float z3,
- float x4, float y4, float z4) {
- float x0 = x2;
- float y0 = y2;
- float z0 = z2;
-
- PMatrix3D draw = curveDrawMatrix;
-
- float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4;
- float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4;
- float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4;
-
- float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4;
- float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4;
- float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4;
-
- // vertex() will reset splineVertexCount, so save it
- int savedCount = curveVertexCount;
-
- float zplot1 = draw.m10*z1 + draw.m11*z2 + draw.m12*z3 + draw.m13*z4;
- float zplot2 = draw.m20*z1 + draw.m21*z2 + draw.m22*z3 + draw.m23*z4;
- float zplot3 = draw.m30*z1 + draw.m31*z2 + draw.m32*z3 + draw.m33*z4;
-
- vertex(x0, y0, z0);
- for (int j = 0; j < curveDetail; j++) {
- x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3;
- y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3;
- z0 += zplot1; zplot1 += zplot2; zplot2 += zplot3;
- vertex(x0, y0, z0);
- }
- curveVertexCount = savedCount;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SIMPLE SHAPES WITH ANALOGUES IN beginShape()
-
-
- public void point(float x, float y) {
- beginShape(POINTS);
- vertex(x, y);
- endShape();
- }
-
-
- public void point(float x, float y, float z) {
- beginShape(POINTS);
- vertex(x, y, z);
- endShape();
- }
-
-
- public void line(float x1, float y1, float x2, float y2) {
- beginShape(LINES);
- vertex(x1, y1);
- vertex(x2, y2);
- endShape();
- }
-
-
- public void line(float x1, float y1, float z1,
- float x2, float y2, float z2) {
- beginShape(LINES);
- vertex(x1, y1, z1);
- vertex(x2, y2, z2);
- endShape();
- }
-
-
- public void triangle(float x1, float y1, float x2, float y2,
- float x3, float y3) {
- beginShape(TRIANGLES);
- vertex(x1, y1);
- vertex(x2, y2);
- vertex(x3, y3);
- endShape();
- }
-
-
- public void quad(float x1, float y1, float x2, float y2,
- float x3, float y3, float x4, float y4) {
- beginShape(QUADS);
- vertex(x1, y1);
- vertex(x2, y2);
- vertex(x3, y3);
- vertex(x4, y4);
- endShape();
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // RECT
-
-
- public void rectMode(int mode) {
- rectMode = mode;
- }
-
-
- public void rect(float a, float b, float c, float d) {
- float hradius, vradius;
- switch (rectMode) {
- case CORNERS:
- break;
- case CORNER:
- c += a; d += b;
- break;
- case RADIUS:
- hradius = c;
- vradius = d;
- c = a + hradius;
- d = b + vradius;
- a -= hradius;
- b -= vradius;
- break;
- case CENTER:
- hradius = c / 2.0f;
- vradius = d / 2.0f;
- c = a + hradius;
- d = b + vradius;
- a -= hradius;
- b -= vradius;
- }
-
- if (a > c) {
- float temp = a; a = c; c = temp;
- }
-
- if (b > d) {
- float temp = b; b = d; d = temp;
- }
-
- rectImpl(a, b, c, d);
- }
-
-
- protected void rectImpl(float x1, float y1, float x2, float y2) {
- quad(x1, y1, x2, y1, x2, y2, x1, y2);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // ELLIPSE AND ARC
-
-
- public void ellipseMode(int mode) {
- ellipseMode = mode;
- }
-
-
- public void ellipse(float a, float b, float c, float d) {
- float x = a;
- float y = b;
- float w = c;
- float h = d;
-
- if (ellipseMode == CORNERS) {
- w = c - a;
- h = d - b;
-
- } else if (ellipseMode == RADIUS) {
- x = a - c;
- y = b - d;
- w = c * 2;
- h = d * 2;
-
- } else if (ellipseMode == DIAMETER) {
- x = a - c/2f;
- y = b - d/2f;
- }
-
- if (w < 0) { // undo negative width
- x += w;
- w = -w;
- }
-
- if (h < 0) { // undo negative height
- y += h;
- h = -h;
- }
-
- ellipseImpl(x, y, w, h);
- }
-
-
- protected void ellipseImpl(float x, float y, float w, float h) {
- }
-
-
- /**
- * Identical parameters and placement to ellipse,
- * but draws only an arc of that ellipse.
- *
- * start and stop are always radians because angleMode() was goofy.
- * ellipseMode() sets the placement.
- *
- * also tries to be smart about start < stop.
- */
- public void arc(float a, float b, float c, float d,
- float start, float stop) {
- float x = a;
- float y = b;
- float w = c;
- float h = d;
-
- if (ellipseMode == CORNERS) {
- w = c - a;
- h = d - b;
-
- } else if (ellipseMode == RADIUS) {
- x = a - c;
- y = b - d;
- w = c * 2;
- h = d * 2;
-
- } else if (ellipseMode == CENTER) {
- x = a - c/2f;
- y = b - d/2f;
- }
-
- // make sure this loop will exit before starting while
- if (Float.isInfinite(start) || Float.isInfinite(stop)) return;
-// while (stop < start) stop += TWO_PI;
- if (stop < start) return; // why bother
-
- // make sure that we're starting at a useful point
- while (start < 0) {
- start += TWO_PI;
- stop += TWO_PI;
- }
-
- if (stop - start > TWO_PI) {
- start = 0;
- stop = TWO_PI;
- }
-
- arcImpl(x, y, w, h, start, stop);
- }
-
-
- /**
- * Start and stop are in radians, converted by the parent function.
- * Note that the radians can be greater (or less) than TWO_PI.
- * This is so that an arc can be drawn that crosses zero mark,
- * and the user will still collect $200.
- */
- protected void arcImpl(float x, float y, float w, float h,
- float start, float stop) {
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BOX
-
-
- public void box(float size) {
- box(size, size, size);
- }
-
-
- // TODO not the least bit efficient, it even redraws lines
- // along the vertices. ugly ugly ugly!
- public void box(float w, float h, float d) {
- float x1 = -w/2f; float x2 = w/2f;
- float y1 = -h/2f; float y2 = h/2f;
- float z1 = -d/2f; float z2 = d/2f;
-
- beginShape(QUADS);
-
- // front
- normal(0, 0, 1);
- vertex(x1, y1, z1);
- vertex(x2, y1, z1);
- vertex(x2, y2, z1);
- vertex(x1, y2, z1);
-
- // right
- normal(1, 0, 0);
- vertex(x2, y1, z1);
- vertex(x2, y1, z2);
- vertex(x2, y2, z2);
- vertex(x2, y2, z1);
-
- // back
- normal(0, 0, -1);
- vertex(x2, y1, z2);
- vertex(x1, y1, z2);
- vertex(x1, y2, z2);
- vertex(x2, y2, z2);
-
- // left
- normal(-1, 0, 0);
- vertex(x1, y1, z2);
- vertex(x1, y1, z1);
- vertex(x1, y2, z1);
- vertex(x1, y2, z2);
-
- // top
- normal(0, 1, 0);
- vertex(x1, y1, z2);
- vertex(x2, y1, z2);
- vertex(x2, y1, z1);
- vertex(x1, y1, z1);
-
- // bottom
- normal(0, -1, 0);
- vertex(x1, y2, z1);
- vertex(x2, y2, z1);
- vertex(x2, y2, z2);
- vertex(x1, y2, z2);
-
- endShape();
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SPHERE
-
-
- public void sphereDetail(int res) {
- sphereDetail(res, res);
- }
-
-
- /**
- * Set the detail level for approximating a sphere. The ures and vres params
- * control the horizontal and vertical resolution.
- *
- * Code for sphereDetail() submitted by toxi [031031].
- * Code for enhanced u/v version from davbol [080801].
- */
- public void sphereDetail(int ures, int vres) {
- if (ures < 3) ures = 3; // force a minimum res
- if (vres < 2) vres = 2; // force a minimum res
- if ((ures == sphereDetailU) && (vres == sphereDetailV)) return;
-
- float delta = (float)SINCOS_LENGTH/ures;
- float[] cx = new float[ures];
- float[] cz = new float[ures];
- // calc unit circle in XZ plane
- for (int i = 0; i < ures; i++) {
- cx[i] = cosLUT[(int) (i*delta) % SINCOS_LENGTH];
- cz[i] = sinLUT[(int) (i*delta) % SINCOS_LENGTH];
- }
- // computing vertexlist
- // vertexlist starts at south pole
- int vertCount = ures * (vres-1) + 2;
- int currVert = 0;
-
- // re-init arrays to store vertices
- sphereX = new float[vertCount];
- sphereY = new float[vertCount];
- sphereZ = new float[vertCount];
-
- float angle_step = (SINCOS_LENGTH*0.5f)/vres;
- float angle = angle_step;
-
- // step along Y axis
- for (int i = 1; i < vres; i++) {
- float curradius = sinLUT[(int) angle % SINCOS_LENGTH];
- float currY = -cosLUT[(int) angle % SINCOS_LENGTH];
- for (int j = 0; j < ures; j++) {
- sphereX[currVert] = cx[j] * curradius;
- sphereY[currVert] = currY;
- sphereZ[currVert++] = cz[j] * curradius;
- }
- angle += angle_step;
- }
- sphereDetailU = ures;
- sphereDetailV = vres;
- }
-
-
- /**
- * Draw a sphere with radius r centered at coordinate 0, 0, 0.
- *
- * 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
- *
- * [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
- *
- */
- public void sphere(float r) {
- if ((sphereDetailU < 3) || (sphereDetailV < 2)) {
- sphereDetail(30);
- }
-
- pushMatrix();
- scale(r);
- edge(false);
-
- // 1st ring from south pole
- beginShape(TRIANGLE_STRIP);
- for (int i = 0; i < sphereDetailU; i++) {
- normal(0, -1, 0);
- vertex(0, -1, 0);
- normal(sphereX[i], sphereY[i], sphereZ[i]);
- vertex(sphereX[i], sphereY[i], sphereZ[i]);
- }
- //normal(0, -1, 0);
- vertex(0, -1, 0);
- normal(sphereX[0], sphereY[0], sphereZ[0]);
- vertex(sphereX[0], sphereY[0], sphereZ[0]);
- endShape();
-
- int v1,v11,v2;
-
- // middle rings
- int voff = 0;
- for (int i = 2; i < sphereDetailV; i++) {
- v1 = v11 = voff;
- voff += sphereDetailU;
- v2 = voff;
- beginShape(TRIANGLE_STRIP);
- for (int j = 0; j < sphereDetailU; j++) {
- normal(sphereX[v1], sphereY[v1], sphereZ[v1]);
- vertex(sphereX[v1], sphereY[v1], sphereZ[v1++]);
- normal(sphereX[v2], sphereY[v2], sphereZ[v2]);
- vertex(sphereX[v2], sphereY[v2], sphereZ[v2++]);
- }
- // close each ring
- v1 = v11;
- v2 = voff;
- normal(sphereX[v1], sphereY[v1], sphereZ[v1]);
- vertex(sphereX[v1], sphereY[v1], sphereZ[v1]);
- normal(sphereX[v2], sphereY[v2], sphereZ[v2]);
- vertex(sphereX[v2], sphereY[v2], sphereZ[v2]);
- endShape();
- }
-
- // add the northern cap
- beginShape(TRIANGLE_STRIP);
- for (int i = 0; i < sphereDetailU; i++) {
- v2 = voff + i;
- normal(sphereX[v2], sphereY[v2], sphereZ[v2]);
- vertex(sphereX[v2], sphereY[v2], sphereZ[v2]);
- normal(0, 1, 0);
- vertex(0, 1, 0);
- }
- normal(sphereX[voff], sphereY[voff], sphereZ[voff]);
- vertex(sphereX[voff], sphereY[voff], sphereZ[voff]);
- normal(0, 1, 0);
- vertex(0, 1, 0);
- endShape();
-
- edge(true);
- popMatrix();
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BEZIER
-
-
- /**
- * Evalutes quadratic bezier at point t for points a, b, c, d.
- * t varies between 0 and 1, and a and d are the on curve points,
- * 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 bezier curve at t.
- *
- * 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();
- */
- public float bezierPoint(float a, float b, float c, float d, float t) {
- float t1 = 1.0f - t;
- return a*t1*t1*t1 + 3*b*t*t1*t1 + 3*c*t*t*t1 + d*t*t*t;
- }
-
-
- /**
- * Provide the tangent at the given point on the bezier curve.
- * Fix from davbol for 0136.
- */
- public float bezierTangent(float a, float b, float c, float d, float t) {
- return (3*t*t * (-a+3*b-3*c+d) +
- 6*t * (a-2*b+c) +
- 3 * (-a+b));
- }
-
-
- protected void bezierInitCheck() {
- if (!bezierInited) {
- bezierInit();
- }
- }
-
-
- protected void bezierInit() {
- // overkill to be broken out, but better parity with the curve stuff below
- bezierDetail(bezierDetail);
- bezierInited = true;
- }
-
-
- public void bezierDetail(int detail) {
- bezierDetail = detail;
-
- if (bezierDrawMatrix == null) {
- bezierDrawMatrix = new PMatrix3D();
- }
-
- // setup matrix for forward differencing to speed up drawing
- splineForward(detail, bezierDrawMatrix);
-
- // multiply the basis and forward diff matrices together
- // saves much time since this needn't be done for each curve
- //mult_spline_matrix(bezierForwardMatrix, bezier_basis, bezierDrawMatrix, 4);
- //bezierDrawMatrix.set(bezierForwardMatrix);
- bezierDrawMatrix.apply(bezierBasisMatrix);
- }
-
-
- /**
- * 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.
- *
- * 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);
- */
- public void bezier(float x1, float y1,
- float x2, float y2,
- float x3, float y3,
- float x4, float y4) {
- beginShape();
- vertex(x1, y1);
- bezierVertex(x2, y2, x3, y3, x4, y4);
- endShape();
- }
-
-
- 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) {
- beginShape();
- vertex(x1, y1, z1);
- bezierVertex(x2, y2, z2,
- x3, y3, z3,
- x4, y4, z4);
- endShape();
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CATMULL-ROM CURVE
-
-
- /**
- * Get a location along a catmull-rom curve segment.
- *
- * @param t Value between zero and one for how far along the segment
- */
- public float curvePoint(float a, float b, float c, float d, float t) {
- curveInitCheck();
-
- float tt = t * t;
- float ttt = t * tt;
- PMatrix3D cb = curveBasisMatrix;
-
- // not optimized (and probably need not be)
- return (a * (ttt*cb.m00 + tt*cb.m10 + t*cb.m20 + cb.m30) +
- b * (ttt*cb.m01 + tt*cb.m11 + t*cb.m21 + cb.m31) +
- c * (ttt*cb.m02 + tt*cb.m12 + t*cb.m22 + cb.m32) +
- d * (ttt*cb.m03 + tt*cb.m13 + t*cb.m23 + cb.m33));
- }
-
-
- /**
- * Calculate the tangent at a t value (0..1) on a Catmull-Rom curve.
- * Code thanks to Dave Bollinger (Bug #715)
- */
- public float curveTangent(float a, float b, float c, float d, float t) {
- curveInitCheck();
-
- float tt3 = t * t * 3;
- float t2 = t * 2;
- PMatrix3D cb = curveBasisMatrix;
-
- // not optimized (and probably need not be)
- return (a * (tt3*cb.m00 + t2*cb.m10 + cb.m20) +
- b * (tt3*cb.m01 + t2*cb.m11 + cb.m21) +
- c * (tt3*cb.m02 + t2*cb.m12 + cb.m22) +
- d * (tt3*cb.m03 + t2*cb.m13 + cb.m23) );
- }
-
-
- public void curveDetail(int detail) {
- curveDetail = detail;
- curveInit();
- }
-
-
- public void curveTightness(float tightness) {
- curveTightness = tightness;
- curveInit();
- }
-
-
- protected void curveInitCheck() {
- if (!curveInited) {
- curveInit();
- }
- }
-
-
- /**
- * Set the number of segments to use when drawing a Catmull-Rom
- * curve, and setting the s parameter, which defines how tightly
- * the curve fits to each vertex. Catmull-Rom curves are actually
- * a subset of this curve type where the s is set to zero.
- *
- * (This function is not optimized, since it's not expected to
- * be called all that often. there are many juicy and obvious
- * opimizations in here, but it's probably better to keep the
- * code more readable)
- */
- protected void curveInit() {
- // allocate only if/when used to save startup time
- if (curveDrawMatrix == null) {
- curveBasisMatrix = new PMatrix3D();
- curveDrawMatrix = new PMatrix3D();
- curveInited = true;
- }
-
- float s = curveTightness;
- curveBasisMatrix.set((s-1)/2f, (s+3)/2f, (-3-s)/2f, (1-s)/2f,
- (1-s), (-5-s)/2f, (s+2), (s-1)/2f,
- (s-1)/2f, 0, (1-s)/2f, 0,
- 0, 1, 0, 0);
-
- //setup_spline_forward(segments, curveForwardMatrix);
- splineForward(curveDetail, curveDrawMatrix);
-
- if (bezierBasisInverse == null) {
- bezierBasisInverse = bezierBasisMatrix.get();
- bezierBasisInverse.invert();
- curveToBezierMatrix = new PMatrix3D();
- }
-
- // TODO only needed for PGraphicsJava2D? if so, move it there
- // actually, it's generally useful for other renderers, so keep it
- // or hide the implementation elsewhere.
- curveToBezierMatrix.set(curveBasisMatrix);
- curveToBezierMatrix.preApply(bezierBasisInverse);
-
- // multiply the basis and forward diff matrices together
- // saves much time since this needn't be done for each curve
- curveDrawMatrix.apply(curveBasisMatrix);
- }
-
-
- /**
- * Draws a segment of Catmull-Rom curve.
- *
- * As of 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().
- *
- */
- public void curve(float x1, float y1,
- float x2, float y2,
- float x3, float y3,
- float x4, float y4) {
- beginShape();
- curveVertex(x1, y1);
- curveVertex(x2, y2);
- curveVertex(x3, y3);
- curveVertex(x4, y4);
- endShape();
- }
-
-
- 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) {
- beginShape();
- curveVertex(x1, y1, z1);
- curveVertex(x2, y2, z2);
- curveVertex(x3, y3, z3);
- curveVertex(x4, y4, z4);
- endShape();
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SPLINE UTILITY FUNCTIONS (used by both Bezier and Catmull-Rom)
-
-
- /**
- * Setup forward-differencing matrix to be used for speedy
- * curve rendering. It's based on using a specific number
- * of curve segments and just doing incremental adds for each
- * vertex of the segment, rather than running the mathematically
- * expensive cubic equation.
- * @param segments number of curve segments to use when drawing
- * @param matrix target object for the new matrix
- */
- protected void splineForward(int segments, PMatrix3D matrix) {
- float f = 1.0f / segments;
- float ff = f * f;
- float fff = ff * f;
-
- matrix.set(0, 0, 0, 1,
- fff, ff, f, 0,
- 6*fff, 2*ff, 0, 0,
- 6*fff, 0, 0, 0);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SMOOTHING
-
-
- /**
- * If true in PImage, use bilinear interpolation for copy()
- * operations. When inherited by PGraphics, also controls shapes.
- */
- public void smooth() {
- smooth = true;
- }
-
-
- /**
- * Disable smoothing. See smooth().
- */
- public void noSmooth() {
- smooth = false;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // IMAGE
-
-
- /**
- * The mode can only be set to CORNERS, CORNER, and CENTER.
- *
- * Support for CENTER was added in release 0146.
- */
- public void imageMode(int mode) {
- if ((mode == CORNER) || (mode == CORNERS) || (mode == CENTER)) {
- imageMode = mode;
- } else {
- String msg =
- "imageMode() only works with CORNER, CORNERS, or CENTER";
- throw new RuntimeException(msg);
- }
- }
-
-
- public void image(PImage image, float x, float y) {
- // Starting in release 0144, image errors are simply ignored.
- // loadImageAsync() sets width and height to -1 when loading fails.
- if (image.width == -1 || image.height == -1) return;
-
- if (imageMode == CORNER || imageMode == CORNERS) {
- imageImpl(image,
- x, y, x+image.width, y+image.height,
- 0, 0, image.width, image.height);
-
- } else if (imageMode == CENTER) {
- float x1 = x - image.width/2;
- float y1 = y - image.height/2;
- imageImpl(image,
- x1, y1, x1+image.width, y1+image.height,
- 0, 0, image.width, image.height);
- }
- }
-
-
- public void image(PImage image, float x, float y, float c, float d) {
- image(image, x, y, c, d, 0, 0, image.width, image.height);
- }
-
-
- /**
- * 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) {
- // Starting in release 0144, image errors are simply ignored.
- // loadImageAsync() sets width and height to -1 when loading fails.
- if (image.width == -1 || image.height == -1) return;
-
- if (imageMode == CORNER) {
- if (c < 0) { // reset a negative width
- a += c; c = -c;
- }
- if (d < 0) { // reset a negative height
- b += d; d = -d;
- }
-
- imageImpl(image,
- a, b, a + c, b + d,
- u1, v1, u2, v2);
-
- } else if (imageMode == CORNERS) {
- if (c < a) { // reverse because x2 < x1
- float temp = a; a = c; c = temp;
- }
- if (d < b) { // reverse because y2 < y1
- float temp = b; b = d; d = temp;
- }
-
- imageImpl(image,
- a, b, c, d,
- u1, v1, u2, v2);
-
- } else if (imageMode == CENTER) {
- // c and d are width/height
- if (c < 0) c = -c;
- if (d < 0) d = -d;
- float x1 = a - c/2;
- float y1 = b - d/2;
-
- imageImpl(image,
- x1, y1, x1 + c, y1 + d,
- u1, v1, u2, v2);
- }
- }
-
-
- /**
- * Expects x1, y1, x2, y2 coordinates where (x2 >= x1) and (y2 >= y1).
- * If tint() has been called, the image will be colored.
- *
- * The default implementation draws an image as a textured quad.
- * The (u, v) coordinates are in image space (they're ints, after all..)
- */
- protected void imageImpl(PImage image,
- float x1, float y1, float x2, float y2,
- int u1, int v1, int u2, int v2) {
- boolean savedStroke = stroke;
-// boolean savedFill = fill;
- int savedTextureMode = textureMode;
-
- stroke = false;
-// fill = true;
- textureMode = IMAGE;
-
-// float savedFillR = fillR;
-// float savedFillG = fillG;
-// float savedFillB = fillB;
-// float savedFillA = fillA;
-//
-// if (tint) {
-// fillR = tintR;
-// fillG = tintG;
-// fillB = tintB;
-// fillA = tintA;
-//
-// } else {
-// fillR = 1;
-// fillG = 1;
-// fillB = 1;
-// fillA = 1;
-// }
-
- beginShape(QUADS);
- texture(image);
- vertex(x1, y1, u1, v1);
- vertex(x1, y2, u1, v2);
- vertex(x2, y2, u2, v2);
- vertex(x2, y1, u2, v1);
- endShape();
-
- stroke = savedStroke;
-// fill = savedFill;
- textureMode = savedTextureMode;
-
-// fillR = savedFillR;
-// fillG = savedFillG;
-// fillB = savedFillB;
-// fillA = savedFillA;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SHAPE
-
-
- /**
- * Set the orientation for the shape() command (like imageMode() or rectMode()).
- * @param mode Either CORNER, CORNERS, or CENTER.
- */
- public void shapeMode(int mode) {
- this.shapeMode = mode;
- }
-
-
- public void shape(PShape shape) {
- if (shape.isVisible()) { // don't do expensive matrix ops if invisible
- if (shapeMode == CENTER) {
- pushMatrix();
- translate(-shape.getWidth()/2, -shape.getHeight()/2);
- }
-
- shape.draw(this); // needs to handle recorder too
-
- if (shapeMode == CENTER) {
- popMatrix();
- }
- }
- }
-
-
- /**
- * Convenience method to draw at a particular location.
- */
- public void shape(PShape shape, float x, float y) {
- if (shape.isVisible()) { // don't do expensive matrix ops if invisible
- pushMatrix();
-
- if (shapeMode == CENTER) {
- translate(x - shape.getWidth()/2, y - shape.getHeight()/2);
-
- } else if ((shapeMode == CORNER) || (shapeMode == CORNERS)) {
- translate(x, y);
- }
- shape.draw(this);
-
- popMatrix();
- }
- }
-
-
- public void shape(PShape shape, float x, float y, float c, float d) {
- if (shape.isVisible()) { // don't do expensive matrix ops if invisible
- pushMatrix();
-
- if (shapeMode == CENTER) {
- // x and y are center, c and d refer to a diameter
- translate(x - c/2f, y - d/2f);
- scale(c / shape.getWidth(), d / shape.getHeight());
-
- } else if (shapeMode == CORNER) {
- translate(x, y);
- scale(c / shape.getWidth(), d / shape.getHeight());
-
- } else if (shapeMode == CORNERS) {
- // c and d are x2/y2, make them into width/height
- c -= x;
- d -= y;
- // then same as above
- translate(x, y);
- scale(c / shape.getWidth(), d / shape.getHeight());
- }
- shape.draw(this);
-
- popMatrix();
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // TEXT/FONTS
-
-
- /**
- * 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) {
- textAlign(align, BASELINE);
- }
-
-
- /**
- * 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) {
- textAlign = alignX;
- textAlignY = 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() {
- if (textFont == null) {
- showTextFontException("textAscent");
- }
- return textFont.ascent() * ((textMode == SCREEN) ? textFont.size : textSize);
- }
-
-
- /**
- * 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() {
- if (textFont == null) {
- showTextFontException("textDescent");
- }
- return textFont.descent() * ((textMode == SCREEN) ? textFont.size : textSize);
- }
-
-
- /**
- * 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 (which != null) {
- textFont = which;
- if (hints[ENABLE_NATIVE_FONTS]) {
- //if (which.font == null) {
- which.findFont();
- //}
- }
- /*
- textFontNative = which.font;
-
- //textFontNativeMetrics = null;
- // changed for rev 0104 for textMode(SHAPE) in opengl
- if (textFontNative != null) {
- // TODO need a better way to handle this. could use reflection to get
- // rid of the warning, but that'd be a little silly. supporting this is
- // an artifact of supporting java 1.1, otherwise we'd use getLineMetrics,
- // as recommended by the @deprecated flag.
- textFontNativeMetrics =
- Toolkit.getDefaultToolkit().getFontMetrics(textFontNative);
- // The following is what needs to be done, however we need to be able
- // to get the actual graphics context where the drawing is happening.
- // For instance, parent.getGraphics() doesn't work for OpenGL since
- // an OpenGL drawing surface is an embedded component.
-// if (parent != null) {
-// textFontNativeMetrics = parent.getGraphics().getFontMetrics(textFontNative);
-// }
-
- // float w = font.getStringBounds(text, g2.getFontRenderContext()).getWidth();
- }
- */
- textSize(which.size);
-
- } else {
- throw new RuntimeException(ERROR_TEXTFONT_NULL_PFONT);
- }
- }
-
-
- /**
- * Useful function to set the font and size at the same time.
- */
- public void textFont(PFont which, float size) {
- textFont(which);
- textSize(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) {
- 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) {
- // CENTER and MODEL overlap (they're both 3)
- if ((mode == LEFT) || (mode == RIGHT)) {
- showWarning("Since Processing beta, textMode() is now textAlign().");
- return;
- }
-// if ((mode != SCREEN) && (mode != MODEL)) {
-// showError("Only textMode(SCREEN) and textMode(MODEL) " +
-// "are available with this renderer.");
-// }
-
- if (textModeCheck(mode)) {
- textMode = mode;
- } else {
- String modeStr = String.valueOf(mode);
- switch (mode) {
- case SCREEN: modeStr = "SCREEN"; break;
- case MODEL: modeStr = "MODEL"; break;
- case SHAPE: modeStr = "SHAPE"; break;
- }
- showWarning("textMode(" + modeStr + ") is not supported by this renderer.");
- }
-
- // reset the font to its natural size
- // (helps with width calculations and all that)
- //if (textMode == SCREEN) {
- //textSize(textFont.size);
- //}
-
- //} else {
- //throw new RuntimeException("use textFont() before textMode()");
- //}
- }
-
-
- protected boolean textModeCheck(int mode) {
- return true;
- }
-
-
- /**
- * Sets the text size, also resets the value for the leading.
- */
- public void textSize(float size) {
- if (textFont != null) {
-// if ((textMode == SCREEN) && (size != textFont.size)) {
-// throw new RuntimeException("textSize() is ignored with " +
-// "textMode(SCREEN)");
-// }
- textSize = size;
- textLeading = (textAscent() + textDescent()) * 1.275f;
-
- } else {
- showTextFontException("textSize");
- }
- }
-
-
- // ........................................................
-
-
- public float textWidth(char c) {
- textWidthBuffer[0] = c;
- return textWidthImpl(textWidthBuffer, 0, 1);
- }
-
-
- /**
- * 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) {
- if (textFont == null) {
- showTextFontException("textWidth");
- }
-
- int length = str.length();
- if (length > textWidthBuffer.length) {
- textWidthBuffer = new char[length + 10];
- }
- str.getChars(0, length, textWidthBuffer, 0);
-
- float wide = 0;
- int index = 0;
- int start = 0;
-
- while (index < length) {
- if (textWidthBuffer[index] == '\n') {
- wide = Math.max(wide, textWidthImpl(textWidthBuffer, start, index));
- start = index+1;
- }
- index++;
- }
- if (start < length) {
- wide = Math.max(wide, textWidthImpl(textWidthBuffer, start, index));
- }
- return wide;
- }
-
-
- /**
- * TODO not sure if this stays...
- */
- public float textWidth(char[] chars, int start, int length) {
- return textWidthImpl(chars, start, start + length);
- }
-
-
- /**
- * Implementation of returning the text width of
- * the chars [start, stop) in the buffer.
- * Unlike the previous version that was inside PFont, this will
- * return the size not of a 1 pixel font, but the actual current size.
- */
- protected float textWidthImpl(char buffer[], int start, int stop) {
- float wide = 0;
- for (int i = start; i < stop; i++) {
- // could add kerning here, but it just ain't implemented
- wide += textFont.width(buffer[i]) * textSize;
- }
- return wide;
- }
-
-
- // ........................................................
-
-
- /**
- * Write text where we just left off.
- */
- public void text(char c) {
- text(c, textX, textY, textZ);
- }
-
-
- /**
- * 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 (textFont == null) {
- showTextFontException("text");
- }
-
- if (textMode == SCREEN) loadPixels();
-
- if (textAlignY == CENTER) {
- y += textAscent() / 2;
- } else if (textAlignY == TOP) {
- y += textAscent();
- } else if (textAlignY == BOTTOM) {
- y -= textDescent();
- //} else if (textAlignY == BASELINE) {
- // do nothing
- }
-
- textBuffer[0] = c;
- textLineAlignImpl(textBuffer, 0, 1, x, y);
-
- if (textMode == SCREEN) updatePixels();
- }
-
-
- /**
- * Draw a single character on screen (with a z coordinate)
- */
- public void text(char c, float x, float y, float z) {
-// if ((z != 0) && (textMode == SCREEN)) {
-// String msg = "textMode(SCREEN) cannot have a z coordinate";
-// throw new RuntimeException(msg);
-// }
-
- if (z != 0) translate(0, 0, z); // slowness, badness
-
- text(c, x, y);
- textZ = z;
-
- if (z != 0) translate(0, 0, -z);
- }
-
-
- /**
- * Write text where we just left off.
- */
- public void text(String str) {
- text(str, textX, textY, textZ);
- }
-
-
- /**
- * 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 (textFont == null) {
- showTextFontException("text");
- }
-
- if (textMode == SCREEN) loadPixels();
-
- int length = str.length();
- if (length > textBuffer.length) {
- textBuffer = new char[length + 10];
- }
- str.getChars(0, length, textBuffer, 0);
- text(textBuffer, 0, length, 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 multiple lines, sum the height of the additional lines
- float high = 0; //-textAscent();
- for (int i = start; i < stop; i++) {
- if (chars[i] == '\n') {
- high += textLeading;
- }
- }
- if (textAlignY == CENTER) {
- // for a single line, this adds half the textAscent to y
- // for multiple lines, subtract half the additional height
- //y += (textAscent() - textDescent() - high)/2;
- y += (textAscent() - high)/2;
- } else if (textAlignY == TOP) {
- // for a single line, need to add textAscent to y
- // for multiple lines, no different
- y += textAscent();
- } else if (textAlignY == BOTTOM) {
- // for a single line, this is just offset by the descent
- // for multiple lines, subtract leading for each line
- y -= textDescent() + high;
- //} else if (textAlignY == BASELINE) {
- // do nothing
- }
-
-// int start = 0;
- int index = 0;
- while (index < stop) { //length) {
- if (chars[index] == '\n') {
- textLineAlignImpl(chars, start, index, x, y);
- start = index + 1;
- y += textLeading;
- }
- index++;
- }
- if (start < stop) { //length) {
- textLineAlignImpl(chars, start, index, x, y);
- }
- if (textMode == SCREEN) updatePixels();
- }
-
-
- /**
- * Same as above but with a z coordinate.
- */
- public void text(String str, float x, float y, float z) {
- if (z != 0) translate(0, 0, z); // slow!
-
- text(str, x, y);
- textZ = z;
-
- if (z != 0) translate(0, 0, -z); // inaccurate!
- }
-
-
- public void text(char[] chars, int start, int stop,
- float x, float y, float z) {
- if (z != 0) translate(0, 0, z); // slow!
-
- text(chars, start, stop, x, y);
- textZ = z;
-
- if (z != 0) translate(0, 0, -z); // inaccurate!
- }
-
-
- /**
- * 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 (textFont == null) {
- showTextFontException("text");
- }
-
- if (textMode == SCREEN) loadPixels();
-
- float hradius, vradius;
- switch (rectMode) {
- case CORNER:
- x2 += x1; y2 += y1;
- break;
- case RADIUS:
- hradius = x2;
- vradius = y2;
- x2 = x1 + hradius;
- y2 = y1 + vradius;
- x1 -= hradius;
- y1 -= vradius;
- break;
- case CENTER:
- hradius = x2 / 2.0f;
- vradius = y2 / 2.0f;
- x2 = x1 + hradius;
- y2 = y1 + vradius;
- x1 -= hradius;
- y1 -= vradius;
- }
- if (x2 < x1) {
- float temp = x1; x1 = x2; x2 = temp;
- }
- if (y2 < y1) {
- float temp = y1; y1 = y2; y2 = temp;
- }
-
-// float currentY = y1;
- float boxWidth = x2 - x1;
-
-// // ala illustrator, the text itself must fit inside the box
-// currentY += textAscent(); //ascent() * textSize;
-// // if the box is already too small, tell em to f off
-// if (currentY > y2) return;
-
- float spaceWidth = textWidth(' ');
-
- if (textBreakStart == null) {
- textBreakStart = new int[20];
- textBreakStop = new int[20];
- }
- textBreakCount = 0;
-
- int length = str.length();
- if (length + 1 > textBuffer.length) {
- textBuffer = new char[length + 1];
- }
- str.getChars(0, length, textBuffer, 0);
- // add a fake newline to simplify calculations
- textBuffer[length++] = '\n';
-
- int sentenceStart = 0;
- for (int i = 0; i < length; i++) {
- if (textBuffer[i] == '\n') {
-// currentY = textSentence(textBuffer, sentenceStart, i,
-// lineX, boxWidth, currentY, y2, spaceWidth);
- boolean legit =
- textSentence(textBuffer, sentenceStart, i, boxWidth, spaceWidth);
- if (!legit) break;
-// if (Float.isNaN(currentY)) break; // word too big (or error)
-// if (currentY > y2) break; // past the box
- sentenceStart = i + 1;
- }
- }
-
- // lineX is the position where the text starts, which is adjusted
- // to left/center/right based on the current textAlign
- float lineX = x1; //boxX1;
- if (textAlign == CENTER) {
- lineX = lineX + boxWidth/2f;
- } else if (textAlign == RIGHT) {
- lineX = x2; //boxX2;
- }
-
- float boxHeight = y2 - y1;
- //int lineFitCount = 1 + PApplet.floor((boxHeight - textAscent()) / textLeading);
- // incorporate textAscent() for the top (baseline will be y1 + ascent)
- // and textDescent() for the bottom, so that lower parts of letters aren't
- // outside the box. [0151]
- float topAndBottom = textAscent() + textDescent();
- int lineFitCount = 1 + PApplet.floor((boxHeight - topAndBottom) / textLeading);
- int lineCount = Math.min(textBreakCount, lineFitCount);
-
- if (textAlignY == CENTER) {
- float lineHigh = textAscent() + textLeading * (lineCount - 1);
- float y = y1 + textAscent() + (boxHeight - lineHigh) / 2;
- for (int i = 0; i < lineCount; i++) {
- textLineAlignImpl(textBuffer, textBreakStart[i], textBreakStop[i], lineX, y);
- y += textLeading;
- }
-
- } else if (textAlignY == BOTTOM) {
- float y = y2 - textDescent() - textLeading * (lineCount - 1);
- for (int i = 0; i < lineCount; i++) {
- textLineAlignImpl(textBuffer, textBreakStart[i], textBreakStop[i], lineX, y);
- y += textLeading;
- }
-
- } else { // TOP or BASELINE just go to the default
- float y = y1 + textAscent();
- for (int i = 0; i < lineCount; i++) {
- textLineAlignImpl(textBuffer, textBreakStart[i], textBreakStop[i], lineX, y);
- y += textLeading;
- }
- }
-
- if (textMode == SCREEN) updatePixels();
- }
-
-
- /**
- * Emit a sentence of text, defined as a chunk of text without any newlines.
- * @param stop non-inclusive, the end of the text in question
- */
- protected boolean textSentence(char[] buffer, int start, int stop,
- float boxWidth, float spaceWidth) {
- float runningX = 0;
-
- // Keep track of this separately from index, since we'll need to back up
- // from index when breaking words that are too long to fit.
- int lineStart = start;
- int wordStart = start;
- int index = start;
- while (index <= stop) {
- // boundary of a word or end of this sentence
- if ((buffer[index] == ' ') || (index == stop)) {
- float wordWidth = textWidthImpl(buffer, wordStart, index);
-
- if (runningX + wordWidth > boxWidth) {
- if (runningX != 0) {
- // Next word is too big, output the current line and advance
- index = wordStart;
- textSentenceBreak(lineStart, index);
- // Eat whitespace because multiple spaces don't count for s*
- // when they're at the end of a line.
- while ((index < stop) && (buffer[index] == ' ')) {
- index++;
- }
- } else { // (runningX == 0)
- // If this is the first word on the line, and its width is greater
- // than the width of the text box, then break the word where at the
- // max width, and send the rest of the word to the next line.
- do {
- index--;
- if (index == wordStart) {
- // Not a single char will fit on this line. screw 'em.
- //System.out.println("screw you");
- return false; //Float.NaN;
- }
- wordWidth = textWidthImpl(buffer, wordStart, index);
- } while (wordWidth > boxWidth);
-
- //textLineImpl(buffer, lineStart, index, x, y);
- textSentenceBreak(lineStart, index);
- }
- lineStart = index;
- wordStart = index;
- runningX = 0;
-
- } else if (index == stop) {
- // last line in the block, time to unload
- //textLineImpl(buffer, lineStart, index, x, y);
- textSentenceBreak(lineStart, index);
-// y += textLeading;
- index++;
-
- } else { // this word will fit, just add it to the line
- runningX += wordWidth + spaceWidth;
- wordStart = index + 1; // move on to the next word
- index++;
- }
- } else { // not a space or the last character
- index++; // this is just another letter
- }
- }
-// return y;
- return true;
- }
-
-
- protected void textSentenceBreak(int start, int stop) {
- if (textBreakCount == textBreakStart.length) {
- textBreakStart = PApplet.expand(textBreakStart);
- textBreakStop = PApplet.expand(textBreakStop);
- }
- textBreakStart[textBreakCount] = start;
- textBreakStop[textBreakCount] = stop;
- textBreakCount++;
- }
-
-
- public void text(String s, float x1, float y1, float x2, float y2, float z) {
- if (z != 0) translate(0, 0, z); // slowness, badness
-
- text(s, x1, y1, x2, y2);
- textZ = z;
-
- if (z != 0) translate(0, 0, -z); // TEMPORARY HACK! SLOW!
- }
-
-
- public void text(int num, float x, float y) {
- text(String.valueOf(num), x, y);
- }
-
-
- public void text(int num, float x, float y, float z) {
- text(String.valueOf(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) {
- text(PApplet.nfs(num, 0, 3), x, y);
- }
-
-
- public void text(float num, float x, float y, float z) {
- text(PApplet.nfs(num, 0, 3), x, y, z);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // TEXT IMPL
-
- // These are most likely to be overridden by subclasses, since the other
- // (public) functions handle generic features like setting alignment.
-
-
- /**
- * Handles placement of a text line, then calls textLineImpl
- * to actually render at the specific point.
- */
- protected void textLineAlignImpl(char buffer[], int start, int stop,
- float x, float y) {
- if (textAlign == CENTER) {
- x -= textWidthImpl(buffer, start, stop) / 2f;
-
- } else if (textAlign == RIGHT) {
- x -= textWidthImpl(buffer, start, stop);
- }
-
- textLineImpl(buffer, start, stop, x, y);
- }
-
-
- /**
- * Implementation of actual drawing for a line of text.
- */
- protected void textLineImpl(char buffer[], int start, int stop,
- float x, float y) {
- for (int index = start; index < stop; index++) {
- textCharImpl(buffer[index], x, y);
-
- // this doesn't account for kerning
- x += textWidth(buffer[index]);
- }
- textX = x;
- textY = y;
- textZ = 0; // this will get set by the caller if non-zero
- }
-
-
- protected void textCharImpl(char ch, float x, float y) { //, float z) {
- int index = textFont.index(ch);
- if (index == -1) return;
-
- PImage glyph = textFont.images[index];
-
- if (textMode == MODEL) {
- float high = (float) textFont.height[index] / textFont.fheight;
- float bwidth = (float) textFont.width[index] / textFont.fwidth;
- float lextent = (float) textFont.leftExtent[index] / textFont.fwidth;
- float textent = (float) textFont.topExtent[index] / textFont.fheight;
-
- float x1 = x + lextent * textSize;
- float y1 = y - textent * textSize;
- float x2 = x1 + bwidth * textSize;
- float y2 = y1 + high * textSize;
-
- textCharModelImpl(glyph,
- x1, y1, x2, y2,
- //x1, y1, z, x2, y2, z,
- textFont.width[index], textFont.height[index]);
-
- } else if (textMode == SCREEN) {
- int xx = (int) x + textFont.leftExtent[index];;
- int yy = (int) y - textFont.topExtent[index];
-
- int w0 = textFont.width[index];
- int h0 = textFont.height[index];
-
- textCharScreenImpl(glyph, xx, yy, w0, h0);
- }
- }
-
-
- protected void textCharModelImpl(PImage glyph,
- float x1, float y1, //float z1,
- float x2, float y2, //float z2,
- int u2, int v2) {
- boolean savedTint = tint;
- int savedTintColor = tintColor;
- float savedTintR = tintR;
- float savedTintG = tintG;
- float savedTintB = tintB;
- float savedTintA = tintA;
- boolean savedTintAlpha = tintAlpha;
-
- tint = true;
- tintColor = fillColor;
- tintR = fillR;
- tintG = fillG;
- tintB = fillB;
- tintA = fillA;
- tintAlpha = fillAlpha;
-
- imageImpl(glyph, x1, y1, x2, y2, 0, 0, u2, v2);
-
- tint = savedTint;
- tintColor = savedTintColor;
- tintR = savedTintR;
- tintG = savedTintG;
- tintB = savedTintB;
- tintA = savedTintA;
- tintAlpha = savedTintAlpha;
- }
-
-
- protected void textCharScreenImpl(PImage glyph,
- int xx, int yy,
- int w0, int h0) {
- int x0 = 0;
- int y0 = 0;
-
- if ((xx >= width) || (yy >= height) ||
- (xx + w0 < 0) || (yy + h0 < 0)) return;
-
- if (xx < 0) {
- x0 -= xx;
- w0 += xx;
- xx = 0;
- }
- if (yy < 0) {
- y0 -= yy;
- h0 += yy;
- yy = 0;
- }
- if (xx + w0 > width) {
- w0 -= ((xx + w0) - width);
- }
- if (yy + h0 > height) {
- h0 -= ((yy + h0) - height);
- }
-
- int fr = fillRi;
- int fg = fillGi;
- int fb = fillBi;
- int fa = fillAi;
-
- int pixels1[] = glyph.pixels; //images[glyph].pixels;
-
- // TODO this can be optimized a bit
- for (int row = y0; row < y0 + h0; row++) {
- for (int col = x0; col < x0 + w0; col++) {
- int a1 = (fa * pixels1[row * textFont.twidth + col]) >> 8;
- int a2 = a1 ^ 0xff;
- //int p1 = pixels1[row * glyph.width + col];
- int p2 = pixels[(yy + row-y0)*width + (xx+col-x0)];
-
- pixels[(yy + row-y0)*width + xx+col-x0] =
- (0xff000000 |
- (((a1 * fr + a2 * ((p2 >> 16) & 0xff)) & 0xff00) << 8) |
- (( a1 * fg + a2 * ((p2 >> 8) & 0xff)) & 0xff00) |
- (( a1 * fb + a2 * ( p2 & 0xff)) >> 8));
- }
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX STACK
-
-
- /**
- * Push a copy of the current transformation matrix onto the stack.
- */
- public void pushMatrix() {
- showMethodWarning("pushMatrix");
- }
-
-
- /**
- * Replace the current transformation matrix with the top of the stack.
- */
- public void popMatrix() {
- showMethodWarning("popMatrix");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX TRANSFORMATIONS
-
-
- /**
- * Translate in X and Y.
- */
- public void translate(float tx, float ty) {
- showMissingWarning("translate");
- }
-
-
- /**
- * Translate in X, Y, and Z.
- */
- public void translate(float tx, float ty, float tz) {
- showMissingWarning("translate");
- }
-
-
- /**
- * 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) {
- showMissingWarning("rotate");
- }
-
-
- /**
- * Rotate around the X axis.
- */
- public void rotateX(float angle) {
- showMethodWarning("rotateX");
- }
-
-
- /**
- * Rotate around the Y axis.
- */
- public void rotateY(float angle) {
- showMethodWarning("rotateY");
- }
-
-
- /**
- * 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) {
- showMethodWarning("rotateZ");
- }
-
-
- /**
- * Rotate about a vector in space. Same as the glRotatef() function.
- */
- public void rotate(float angle, float vx, float vy, float vz) {
- showMissingWarning("rotate");
- }
-
-
- /**
- * Scale in all dimensions.
- */
- public void scale(float s) {
- showMissingWarning("scale");
- }
-
-
- /**
- * 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) {
- showMissingWarning("scale");
- }
-
-
- /**
- * Scale in X, Y, and Z.
- */
- public void scale(float x, float y, float z) {
- showMissingWarning("scale");
- }
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX FULL MONTY
-
-
- /**
- * Set the current transformation matrix to identity.
- */
- public void resetMatrix() {
- showMethodWarning("resetMatrix");
- }
-
-
- public void applyMatrix(PMatrix source) {
- if (source instanceof PMatrix2D) {
- applyMatrix((PMatrix2D) source);
- } else if (source instanceof PMatrix3D) {
- applyMatrix((PMatrix3D) source);
- }
- }
-
-
- public void applyMatrix(PMatrix2D source) {
- applyMatrix(source.m00, source.m01, source.m02,
- source.m10, source.m11, source.m12);
- }
-
-
- /**
- * Apply a 3x2 affine transformation matrix.
- */
- public void applyMatrix(float n00, float n01, float n02,
- float n10, float n11, float n12) {
- showMissingWarning("applyMatrix");
- }
-
-
- 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.
- */
- 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) {
- showMissingWarning("applyMatrix");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX GET/SET/PRINT
-
-
- public PMatrix getMatrix() {
- showMissingWarning("getMatrix");
- return null;
- }
-
-
- /**
- * Copy the current transformation matrix into the specified target.
- * Pass in null to create a new matrix.
- */
- public PMatrix2D getMatrix(PMatrix2D target) {
- showMissingWarning("getMatrix");
- return null;
- }
-
-
- /**
- * Copy the current transformation matrix into the specified target.
- * Pass in null to create a new matrix.
- */
- public PMatrix3D getMatrix(PMatrix3D target) {
- showMissingWarning("getMatrix");
- return null;
- }
-
-
- /**
- * Set the current transformation matrix to the contents of another.
- */
- public void setMatrix(PMatrix source) {
- if (source instanceof PMatrix2D) {
- setMatrix((PMatrix2D) source);
- } else if (source instanceof PMatrix3D) {
- setMatrix((PMatrix3D) source);
- }
- }
-
-
- /**
- * Set the current transformation to the contents of the specified source.
- */
- public void setMatrix(PMatrix2D source) {
- showMissingWarning("setMatrix");
- }
-
-
- /**
- * Set the current transformation to the contents of the specified source.
- */
- public void setMatrix(PMatrix3D source) {
- showMissingWarning("setMatrix");
- }
-
-
- /**
- * Print the current model (or "transformation") matrix.
- */
- public void printMatrix() {
- showMethodWarning("printMatrix");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CAMERA
-
-
- public void beginCamera() {
- showMethodWarning("beginCamera");
- }
-
-
- public void endCamera() {
- showMethodWarning("endCamera");
- }
-
-
- public void camera() {
- showMissingWarning("camera");
- }
-
-
- public void camera(float eyeX, float eyeY, float eyeZ,
- float centerX, float centerY, float centerZ,
- float upX, float upY, float upZ) {
- showMissingWarning("camera");
- }
-
-
- public void printCamera() {
- showMethodWarning("printCamera");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // PROJECTION
-
-
- public void ortho() {
- showMissingWarning("ortho");
- }
-
-
- public void ortho(float left, float right,
- float bottom, float top,
- float near, float far) {
- showMissingWarning("ortho");
- }
-
-
- public void perspective() {
- showMissingWarning("perspective");
- }
-
-
- public void perspective(float fovy, float aspect, float zNear, float zFar) {
- showMissingWarning("perspective");
- }
-
-
- public void frustum(float left, float right,
- float bottom, float top,
- float near, float far) {
- showMethodWarning("frustum");
- }
-
-
- public void printProjection() {
- showMethodWarning("printCamera");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SCREEN TRANSFORMS
-
-
- /**
- * 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) {
- showMissingWarning("screenX");
- return 0;
- }
-
-
- /**
- * 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) {
- showMissingWarning("screenY");
- return 0;
- }
-
-
- /**
- * Maps a three dimensional point to its placement on-screen.
- *
- * 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) {
- showMissingWarning("screenX");
- return 0;
- }
-
-
- /**
- * 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) {
- showMissingWarning("screenY");
- return 0;
- }
-
-
- /**
- * 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) {
- showMissingWarning("screenZ");
- return 0;
- }
-
-
- /**
- * 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) {
- showMissingWarning("modelX");
- return 0;
- }
-
-
- /**
- * Returns the model space y value for an x, y, z coordinate.
- */
- public float modelY(float x, float y, float z) {
- showMissingWarning("modelY");
- return 0;
- }
-
-
- /**
- * Returns the model space z value for an x, y, z coordinate.
- */
- public float modelZ(float x, float y, float z) {
- showMissingWarning("modelZ");
- return 0;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // STYLE
-
-
- public void pushStyle() {
- if (styleStackDepth == styleStack.length) {
- styleStack = (PStyle[]) PApplet.expand(styleStack);
- }
- if (styleStack[styleStackDepth] == null) {
- styleStack[styleStackDepth] = new PStyle();
- }
- PStyle s = styleStack[styleStackDepth++];
- getStyle(s);
- }
-
-
- public void popStyle() {
- if (styleStackDepth == 0) {
- throw new RuntimeException("Too many popStyle() without enough pushStyle()");
- }
- styleStackDepth--;
- style(styleStack[styleStackDepth]);
- }
-
-
- public void style(PStyle s) {
- // if (s.smooth) {
- // smooth();
- // } else {
- // noSmooth();
- // }
-
- imageMode(s.imageMode);
- rectMode(s.rectMode);
- ellipseMode(s.ellipseMode);
- shapeMode(s.shapeMode);
-
- if (s.tint) {
- tint(s.tintColor);
- } else {
- noTint();
- }
- if (s.fill) {
- fill(s.fillColor);
- } else {
- noFill();
- }
- if (s.stroke) {
- stroke(s.strokeColor);
- } else {
- noStroke();
- }
- strokeWeight(s.strokeWeight);
- strokeCap(s.strokeCap);
- strokeJoin(s.strokeJoin);
-
- // Set the colorMode() for the material properties.
- // TODO this is really inefficient, need to just have a material() method,
- // but this has the least impact to the API.
- colorMode(RGB, 1);
- ambient(s.ambientR, s.ambientG, s.ambientB);
- emissive(s.emissiveR, s.emissiveG, s.emissiveB);
- specular(s.specularR, s.specularG, s.specularB);
- shininess(s.shininess);
-
- /*
- s.ambientR = ambientR;
- s.ambientG = ambientG;
- s.ambientB = ambientB;
- s.specularR = specularR;
- s.specularG = specularG;
- s.specularB = specularB;
- s.emissiveR = emissiveR;
- s.emissiveG = emissiveG;
- s.emissiveB = emissiveB;
- s.shininess = shininess;
- */
- // material(s.ambientR, s.ambientG, s.ambientB,
- // s.emissiveR, s.emissiveG, s.emissiveB,
- // s.specularR, s.specularG, s.specularB,
- // s.shininess);
-
- // Set this after the material properties.
- colorMode(s.colorMode,
- s.colorModeX, s.colorModeY, s.colorModeZ, s.colorModeA);
-
- // This is a bit asymmetric, since there's no way to do "noFont()",
- // and a null textFont will produce an error (since usually that means that
- // the font couldn't load properly). So in some cases, the font won't be
- // 'cleared' to null, even though that's technically correct.
- if (s.textFont != null) {
- textFont(s.textFont, s.textSize);
- textLeading(s.textLeading);
- }
- // These don't require a font to be set.
- textAlign(s.textAlign, s.textAlignY);
- textMode(s.textMode);
- }
-
-
- public PStyle getStyle() { // ignore
- return getStyle(null);
- }
-
-
- public PStyle getStyle(PStyle s) { // ignore
- if (s == null) {
- s = new PStyle();
- }
-
- s.imageMode = imageMode;
- s.rectMode = rectMode;
- s.ellipseMode = ellipseMode;
- s.shapeMode = shapeMode;
-
- s.colorMode = colorMode;
- s.colorModeX = colorModeX;
- s.colorModeY = colorModeY;
- s.colorModeZ = colorModeZ;
- s.colorModeA = colorModeA;
-
- s.tint = tint;
- s.tintColor = tintColor;
- s.fill = fill;
- s.fillColor = fillColor;
- s.stroke = stroke;
- s.strokeColor = strokeColor;
- s.strokeWeight = strokeWeight;
- s.strokeCap = strokeCap;
- s.strokeJoin = strokeJoin;
-
- s.ambientR = ambientR;
- s.ambientG = ambientG;
- s.ambientB = ambientB;
- s.specularR = specularR;
- s.specularG = specularG;
- s.specularB = specularB;
- s.emissiveR = emissiveR;
- s.emissiveG = emissiveG;
- s.emissiveB = emissiveB;
- s.shininess = shininess;
-
- s.textFont = textFont;
- s.textAlign = textAlign;
- s.textAlignY = textAlignY;
- s.textMode = textMode;
- s.textSize = textSize;
- s.textLeading = textLeading;
-
- return s;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // STROKE CAP/JOIN/WEIGHT
-
-
- public void strokeWeight(float weight) {
- strokeWeight = weight;
- }
-
-
- public void strokeJoin(int join) {
- strokeJoin = join;
- }
-
-
- public void strokeCap(int cap) {
- strokeCap = cap;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // STROKE COLOR
-
-
- public void noStroke() {
- stroke = false;
- }
-
-
- /**
- * Set the tint to either a grayscale or ARGB value.
- * See notes attached to the fill() function.
- */
- public void stroke(int rgb) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above
-// stroke((float) rgb);
-//
-// } else {
-// colorCalcARGB(rgb, colorModeA);
-// strokeFromCalc();
-// }
- colorCalc(rgb);
- strokeFromCalc();
- }
-
-
- public void stroke(int rgb, float alpha) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// stroke((float) rgb, alpha);
-//
-// } else {
-// colorCalcARGB(rgb, alpha);
-// strokeFromCalc();
-// }
- colorCalc(rgb, alpha);
- strokeFromCalc();
- }
-
-
- public void stroke(float gray) {
- colorCalc(gray);
- strokeFromCalc();
- }
-
-
- public void stroke(float gray, float alpha) {
- colorCalc(gray, alpha);
- strokeFromCalc();
- }
-
-
- public void stroke(float x, float y, float z) {
- colorCalc(x, y, z);
- strokeFromCalc();
- }
-
-
- public void stroke(float x, float y, float z, float a) {
- colorCalc(x, y, z, a);
- strokeFromCalc();
- }
-
-
- protected void strokeFromCalc() {
- stroke = true;
- strokeR = calcR;
- strokeG = calcG;
- strokeB = calcB;
- strokeA = calcA;
- strokeRi = calcRi;
- strokeGi = calcGi;
- strokeBi = calcBi;
- strokeAi = calcAi;
- strokeColor = calcColor;
- strokeAlpha = calcAlpha;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // TINT COLOR
-
-
- public void noTint() {
- tint = false;
- }
-
-
- /**
- * Set the tint to either a grayscale or ARGB value.
- */
- public void tint(int rgb) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// tint((float) rgb);
-//
-// } else {
-// colorCalcARGB(rgb, colorModeA);
-// tintFromCalc();
-// }
- colorCalc(rgb);
- tintFromCalc();
- }
-
- public void tint(int rgb, float alpha) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// tint((float) rgb, alpha);
-//
-// } else {
-// colorCalcARGB(rgb, alpha);
-// tintFromCalc();
-// }
- colorCalc(rgb, alpha);
- tintFromCalc();
- }
-
- public void tint(float gray) {
- colorCalc(gray);
- tintFromCalc();
- }
-
-
- public void tint(float gray, float alpha) {
- colorCalc(gray, alpha);
- tintFromCalc();
- }
-
-
- public void tint(float x, float y, float z) {
- colorCalc(x, y, z);
- tintFromCalc();
- }
-
-
- public void tint(float x, float y, float z, float a) {
- colorCalc(x, y, z, a);
- tintFromCalc();
- }
-
-
- protected void tintFromCalc() {
- tint = true;
- tintR = calcR;
- tintG = calcG;
- tintB = calcB;
- tintA = calcA;
- tintRi = calcRi;
- tintGi = calcGi;
- tintBi = calcBi;
- tintAi = calcAi;
- tintColor = calcColor;
- tintAlpha = calcAlpha;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // FILL COLOR
-
-
- public void noFill() {
- fill = false;
- }
-
-
- /**
- * Set the fill to either a grayscale value or an ARGB int.
- */
- public void fill(int rgb) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above
-// fill((float) rgb);
-//
-// } else {
-// colorCalcARGB(rgb, colorModeA);
-// fillFromCalc();
-// }
- colorCalc(rgb);
- fillFromCalc();
- }
-
-
- public void fill(int rgb, float alpha) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above
-// fill((float) rgb, alpha);
-//
-// } else {
-// colorCalcARGB(rgb, alpha);
-// fillFromCalc();
-// }
- colorCalc(rgb, alpha);
- fillFromCalc();
- }
-
-
- public void fill(float gray) {
- colorCalc(gray);
- fillFromCalc();
- }
-
-
- public void fill(float gray, float alpha) {
- colorCalc(gray, alpha);
- fillFromCalc();
- }
-
-
- public void fill(float x, float y, float z) {
- colorCalc(x, y, z);
- fillFromCalc();
- }
-
-
- public void fill(float x, float y, float z, float a) {
- colorCalc(x, y, z, a);
- fillFromCalc();
- }
-
-
- protected void fillFromCalc() {
- fill = true;
- fillR = calcR;
- fillG = calcG;
- fillB = calcB;
- fillA = calcA;
- fillRi = calcRi;
- fillGi = calcGi;
- fillBi = calcBi;
- fillAi = calcAi;
- fillColor = calcColor;
- fillAlpha = calcAlpha;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATERIAL PROPERTIES
-
-
- public void ambient(int rgb) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// ambient((float) rgb);
-//
-// } else {
-// colorCalcARGB(rgb, colorModeA);
-// ambientFromCalc();
-// }
- colorCalc(rgb);
- ambientFromCalc();
- }
-
-
- public void ambient(float gray) {
- colorCalc(gray);
- ambientFromCalc();
- }
-
-
- public void ambient(float x, float y, float z) {
- colorCalc(x, y, z);
- ambientFromCalc();
- }
-
-
- protected void ambientFromCalc() {
- ambientR = calcR;
- ambientG = calcG;
- ambientB = calcB;
- }
-
-
- public void specular(int rgb) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// specular((float) rgb);
-//
-// } else {
-// colorCalcARGB(rgb, colorModeA);
-// specularFromCalc();
-// }
- colorCalc(rgb);
- specularFromCalc();
- }
-
-
- public void specular(float gray) {
- colorCalc(gray);
- specularFromCalc();
- }
-
-
- public void specular(float x, float y, float z) {
- colorCalc(x, y, z);
- specularFromCalc();
- }
-
-
- protected void specularFromCalc() {
- specularR = calcR;
- specularG = calcG;
- specularB = calcB;
- }
-
-
- public void shininess(float shine) {
- shininess = shine;
- }
-
-
- public void emissive(int rgb) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// emissive((float) rgb);
-//
-// } else {
-// colorCalcARGB(rgb, colorModeA);
-// emissiveFromCalc();
-// }
- colorCalc(rgb);
- emissiveFromCalc();
- }
-
-
- public void emissive(float gray) {
- colorCalc(gray);
- emissiveFromCalc();
- }
-
-
- public void emissive(float x, float y, float z) {
- colorCalc(x, y, z);
- emissiveFromCalc();
- }
-
-
- protected void emissiveFromCalc() {
- emissiveR = calcR;
- emissiveG = calcG;
- emissiveB = calcB;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // LIGHTS
-
- // The details of lighting are very implementation-specific, so this base
- // class does not handle any details of settings lights. It does however
- // display warning messages that the functions are not available.
-
-
- public void lights() {
- showMethodWarning("lights");
- }
-
- public void noLights() {
- showMethodWarning("noLights");
- }
-
- public void ambientLight(float red, float green, float blue) {
- showMethodWarning("ambientLight");
- }
-
- public void ambientLight(float red, float green, float blue,
- float x, float y, float z) {
- showMethodWarning("ambientLight");
- }
-
- public void directionalLight(float red, float green, float blue,
- float nx, float ny, float nz) {
- showMethodWarning("directionalLight");
- }
-
- public void pointLight(float red, float green, float blue,
- float x, float y, float z) {
- showMethodWarning("pointLight");
- }
-
- 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) {
- showMethodWarning("spotLight");
- }
-
- public void lightFalloff(float constant, float linear, float quadratic) {
- showMethodWarning("lightFalloff");
- }
-
- public void lightSpecular(float x, float y, float z) {
- showMethodWarning("lightSpecular");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BACKGROUND
-
- /**
- * Set the background to a gray or ARGB color.
- *
- * 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.
- */
- public void background(int rgb) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// background((float) rgb);
-//
-// } else {
-// if (format == RGB) {
-// rgb |= 0xff000000; // ignore alpha for main drawing surface
-// }
-// colorCalcARGB(rgb, colorModeA);
-// backgroundFromCalc();
-// backgroundImpl();
-// }
- colorCalc(rgb);
- backgroundFromCalc();
- }
-
-
- /**
- * See notes about alpha in background(x, y, z, a).
- */
- public void background(int rgb, float alpha) {
-// if (format == RGB) {
-// background(rgb); // ignore alpha for main drawing surface
-//
-// } else {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// background((float) rgb, alpha);
-//
-// } else {
-// colorCalcARGB(rgb, alpha);
-// backgroundFromCalc();
-// backgroundImpl();
-// }
-// }
- colorCalc(rgb, alpha);
- backgroundFromCalc();
- }
-
-
- /**
- * Set the background to a grayscale value, based on the
- * current colorMode.
- */
- public void background(float gray) {
- colorCalc(gray);
- backgroundFromCalc();
-// backgroundImpl();
- }
-
-
- /**
- * See notes about alpha in background(x, y, z, a).
- */
- public void background(float gray, float alpha) {
- if (format == RGB) {
- background(gray); // ignore alpha for main drawing surface
-
- } else {
- colorCalc(gray, alpha);
- backgroundFromCalc();
-// backgroundImpl();
- }
- }
-
-
- /**
- * 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) {
- colorCalc(x, y, z);
- backgroundFromCalc();
-// backgroundImpl();
- }
-
-
- /**
- * 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.
- */
- public void background(float x, float y, float z, float a) {
-// if (format == RGB) {
-// background(x, y, z); // don't allow people to set alpha
-//
-// } else {
-// colorCalc(x, y, z, a);
-// backgroundFromCalc();
-// backgroundImpl();
-// }
- colorCalc(x, y, z, a);
- backgroundFromCalc();
- }
-
-
- protected void backgroundFromCalc() {
- backgroundR = calcR;
- backgroundG = calcG;
- backgroundB = calcB;
- backgroundA = (format == RGB) ? colorModeA : calcA;
- backgroundRi = calcRi;
- backgroundGi = calcGi;
- backgroundBi = calcBi;
- backgroundAi = (format == RGB) ? 255 : calcAi;
- backgroundAlpha = (format == RGB) ? false : calcAlpha;
- backgroundColor = calcColor;
-
- backgroundImpl();
- }
-
-
- /**
- * Takes an RGB or ARGB image and sets it as the background.
- * The width and height of the image must be the same size as the sketch.
- * Use image.resize(width, height) to make short work of such a task.
- *
- * 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 ((image.width != width) || (image.height != height)) {
- throw new RuntimeException(ERROR_BACKGROUND_IMAGE_SIZE);
- }
- if ((image.format != RGB) && (image.format != ARGB)) {
- throw new RuntimeException(ERROR_BACKGROUND_IMAGE_FORMAT);
- }
- backgroundColor = 0; // just zero it out for images
- backgroundImpl(image);
- }
-
-
- /**
- * Actually set the background image. This is separated from the error
- * handling and other semantic goofiness that is shared across renderers.
- */
- protected void backgroundImpl(PImage image) {
- // blit image to the screen
- set(0, 0, image);
- }
-
-
- /**
- * Actual implementation of clearing the background, now that the
- * internal variables for background color have been set. Called by the
- * backgroundFromCalc() method, which is what all the other background()
- * methods call once the work is done.
- */
- protected void backgroundImpl() {
- pushStyle();
- pushMatrix();
- resetMatrix();
- fill(backgroundColor);
- rect(0, 0, width, height);
- popMatrix();
- popStyle();
- }
-
-
- /**
- * Callback to handle clearing the background when begin/endRaw is in use.
- * Handled as separate function for OpenGL (or other) subclasses that
- * override backgroundImpl() but still needs this to work properly.
- */
-// protected void backgroundRawImpl() {
-// if (raw != null) {
-// raw.colorMode(RGB, 1);
-// raw.noStroke();
-// raw.fill(backgroundR, backgroundG, backgroundB);
-// raw.beginShape(TRIANGLES);
-//
-// raw.vertex(0, 0);
-// raw.vertex(width, 0);
-// raw.vertex(0, height);
-//
-// raw.vertex(width, 0);
-// raw.vertex(width, height);
-// raw.vertex(0, height);
-//
-// raw.endShape();
-// }
-// }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR MODE
-
-
- public void colorMode(int mode) {
- colorMode(mode, colorModeX, colorModeY, colorModeZ, colorModeA);
- }
-
-
- public void colorMode(int mode, float max) {
- colorMode(mode, max, max, max, 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
- *
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) {
- colorMode(mode, maxX, maxY, maxZ, colorModeA);
- }
-
-
- public void colorMode(int mode,
- float maxX, float maxY, float maxZ, float maxA) {
- colorMode = mode;
-
- colorModeX = maxX; // still needs to be set for hsb
- colorModeY = maxY;
- colorModeZ = maxZ;
- colorModeA = maxA;
-
- // if color max values are all 1, then no need to scale
- colorModeScale =
- ((maxA != 1) || (maxX != maxY) || (maxY != maxZ) || (maxZ != maxA));
-
- // if color is rgb/0..255 this will make it easier for the
- // red() green() etc functions
- colorModeDefault = (colorMode == RGB) &&
- (colorModeA == 255) && (colorModeX == 255) &&
- (colorModeY == 255) && (colorModeZ == 255);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR CALCULATIONS
-
- // Given input values for coloring, these functions will fill the calcXxxx
- // variables with values that have been properly filtered through the
- // current colorMode settings.
-
- // Renderers that need to subclass any drawing properties such as fill or
- // stroke will usally want to override methods like fillFromCalc (or the
- // same for stroke, ambient, etc.) That way the color calcuations are
- // covered by this based PGraphics class, leaving only a single function
- // to override/implement in the subclass.
-
-
- /**
- * Set the fill to either a grayscale value or an ARGB int.
- *
- * The problem with this code is that it has to detect between these two
- * situations automatically. This is done by checking to see if the high bits
- * (the alpha for 0xAA000000) is set, and if not, whether the color value
- * that follows is less than colorModeX (first param passed to colorMode).
- *
- * This auto-detect would break in the following situation:
- *
size(256, 256);
- * for (int i = 0; i < 256; i++) {
- * color c = color(0, 0, 0, i);
- * stroke(c);
- * line(i, 0, i, 256);
- * }
- * ...on the first time through the loop, where (i == 0), since the color
- * itself is zero (black) then it would appear indistinguishable from code
- * that reads "fill(0)". The solution is to use the four parameter versions
- * of stroke or fill to more directly specify the desired result.
- */
- protected void colorCalc(int rgb) {
- if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
- colorCalc((float) rgb);
-
- } else {
- colorCalcARGB(rgb, colorModeA);
- }
- }
-
-
- protected void colorCalc(int rgb, float alpha) {
- if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above
- colorCalc((float) rgb, alpha);
-
- } else {
- colorCalcARGB(rgb, alpha);
- }
- }
-
-
- protected void colorCalc(float gray) {
- colorCalc(gray, colorModeA);
- }
-
-
- protected void colorCalc(float gray, float alpha) {
- if (gray > colorModeX) gray = colorModeX;
- if (alpha > colorModeA) alpha = colorModeA;
-
- if (gray < 0) gray = 0;
- if (alpha < 0) alpha = 0;
-
- calcR = colorModeScale ? (gray / colorModeX) : gray;
- calcG = calcR;
- calcB = calcR;
- calcA = colorModeScale ? (alpha / colorModeA) : alpha;
-
- calcRi = (int)(calcR*255); calcGi = (int)(calcG*255);
- calcBi = (int)(calcB*255); calcAi = (int)(calcA*255);
- calcColor = (calcAi << 24) | (calcRi << 16) | (calcGi << 8) | calcBi;
- calcAlpha = (calcAi != 255);
- }
-
-
- protected void colorCalc(float x, float y, float z) {
- colorCalc(x, y, z, colorModeA);
- }
-
-
- protected void colorCalc(float x, float y, float z, float a) {
- if (x > colorModeX) x = colorModeX;
- if (y > colorModeY) y = colorModeY;
- if (z > colorModeZ) z = colorModeZ;
- if (a > colorModeA) a = colorModeA;
-
- if (x < 0) x = 0;
- if (y < 0) y = 0;
- if (z < 0) z = 0;
- if (a < 0) a = 0;
-
- switch (colorMode) {
- case RGB:
- if (colorModeScale) {
- calcR = x / colorModeX;
- calcG = y / colorModeY;
- calcB = z / colorModeZ;
- calcA = a / colorModeA;
- } else {
- calcR = x; calcG = y; calcB = z; calcA = a;
- }
- break;
-
- case HSB:
- x /= colorModeX; // h
- y /= colorModeY; // s
- z /= colorModeZ; // b
-
- calcA = colorModeScale ? (a/colorModeA) : a;
-
- if (y == 0) { // saturation == 0
- calcR = calcG = calcB = z;
-
- } else {
- float which = (x - (int)x) * 6.0f;
- float f = which - (int)which;
- float p = z * (1.0f - y);
- float q = z * (1.0f - y * f);
- float t = z * (1.0f - (y * (1.0f - f)));
-
- switch ((int)which) {
- case 0: calcR = z; calcG = t; calcB = p; break;
- case 1: calcR = q; calcG = z; calcB = p; break;
- case 2: calcR = p; calcG = z; calcB = t; break;
- case 3: calcR = p; calcG = q; calcB = z; break;
- case 4: calcR = t; calcG = p; calcB = z; break;
- case 5: calcR = z; calcG = p; calcB = q; break;
- }
- }
- break;
- }
- calcRi = (int)(255*calcR); calcGi = (int)(255*calcG);
- calcBi = (int)(255*calcB); calcAi = (int)(255*calcA);
- calcColor = (calcAi << 24) | (calcRi << 16) | (calcGi << 8) | calcBi;
- calcAlpha = (calcAi != 255);
- }
-
-
- /**
- * Unpacks AARRGGBB color for direct use with colorCalc.
- *
- * Handled here with its own function since this is indepenent
- * of the color mode.
- *
- * Strangely the old version of this code ignored the alpha
- * value. not sure if that was a bug or what.
- *
- * Note, no need for a bounds check since it's a 32 bit number.
- */
- protected void colorCalcARGB(int argb, float alpha) {
- if (alpha == colorModeA) {
- calcAi = (argb >> 24) & 0xff;
- calcColor = argb;
- } else {
- calcAi = (int) (((argb >> 24) & 0xff) * (alpha / colorModeA));
- calcColor = (calcAi << 24) | (argb & 0xFFFFFF);
- }
- calcRi = (argb >> 16) & 0xff;
- calcGi = (argb >> 8) & 0xff;
- calcBi = argb & 0xff;
- calcA = (float)calcAi / 255.0f;
- calcR = (float)calcRi / 255.0f;
- calcG = (float)calcGi / 255.0f;
- calcB = (float)calcBi / 255.0f;
- calcAlpha = (calcAi != 255);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR DATATYPE STUFFING
-
- // The 'color' primitive type in Processing syntax is in fact a 32-bit int.
- // These functions handle stuffing color values into a 32-bit cage based
- // on the current colorMode settings.
-
- // These functions are really slow (because they take the current colorMode
- // into account), but they're easy to use. Advanced users can write their
- // own bit shifting operations to setup 'color' data types.
-
-
- public final int color(int gray) { // ignore
- if (((gray & 0xff000000) == 0) && (gray <= colorModeX)) {
- if (colorModeDefault) {
- // bounds checking to make sure the numbers aren't to high or low
- if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
- return 0xff000000 | (gray << 16) | (gray << 8) | gray;
- } else {
- colorCalc(gray);
- }
- } else {
- colorCalcARGB(gray, colorModeA);
- }
- return calcColor;
- }
-
-
- public final int color(float gray) { // ignore
- colorCalc(gray);
- return calcColor;
- }
-
-
- /**
- * @param gray can be packed ARGB or a gray in this case
- */
- public final int color(int gray, int alpha) { // ignore
- if (colorModeDefault) {
- // bounds checking to make sure the numbers aren't to high or low
- if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
- if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
-
- return ((alpha & 0xff) << 24) | (gray << 16) | (gray << 8) | gray;
- }
- colorCalc(gray, alpha);
- return calcColor;
- }
-
-
- /**
- * @param rgb can be packed ARGB or a gray in this case
- */
- public final int color(int rgb, float alpha) { // ignore
- if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
- colorCalc(rgb, alpha);
- } else {
- colorCalcARGB(rgb, alpha);
- }
- return calcColor;
- }
-
-
- public final int color(float gray, float alpha) { // ignore
- colorCalc(gray, alpha);
- return calcColor;
- }
-
-
- public final int color(int x, int y, int z) { // ignore
- if (colorModeDefault) {
- // bounds checking to make sure the numbers aren't to high or low
- if (x > 255) x = 255; else if (x < 0) x = 0;
- if (y > 255) y = 255; else if (y < 0) y = 0;
- if (z > 255) z = 255; else if (z < 0) z = 0;
-
- return 0xff000000 | (x << 16) | (y << 8) | z;
- }
- colorCalc(x, y, z);
- return calcColor;
- }
-
-
- public final int color(float x, float y, float z) { // ignore
- colorCalc(x, y, z);
- return calcColor;
- }
-
-
- public final int color(int x, int y, int z, int a) { // ignore
- if (colorModeDefault) {
- // bounds checking to make sure the numbers aren't to high or low
- if (a > 255) a = 255; else if (a < 0) a = 0;
- if (x > 255) x = 255; else if (x < 0) x = 0;
- if (y > 255) y = 255; else if (y < 0) y = 0;
- if (z > 255) z = 255; else if (z < 0) z = 0;
-
- return (a << 24) | (x << 16) | (y << 8) | z;
- }
- colorCalc(x, y, z, a);
- return calcColor;
- }
-
-
- public final int color(float x, float y, float z, float a) { // ignore
- colorCalc(x, y, z, a);
- return calcColor;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR DATATYPE EXTRACTION
-
- // Vee have veys of making the colors talk.
-
-
- public final float alpha(int what) {
- float c = (what >> 24) & 0xff;
- if (colorModeA == 255) return c;
- return (c / 255.0f) * colorModeA;
- }
-
-
- public final float red(int what) {
- float c = (what >> 16) & 0xff;
- if (colorModeDefault) return c;
- return (c / 255.0f) * colorModeX;
- }
-
-
- public final float green(int what) {
- float c = (what >> 8) & 0xff;
- if (colorModeDefault) return c;
- return (c / 255.0f) * colorModeY;
- }
-
-
- public final float blue(int what) {
- float c = (what) & 0xff;
- if (colorModeDefault) return c;
- return (c / 255.0f) * colorModeZ;
- }
-
-
- public final float hue(int what) {
- if (what != cacheHsbKey) {
- Color.RGBtoHSB((what >> 16) & 0xff, (what >> 8) & 0xff,
- what & 0xff, cacheHsbValue);
- cacheHsbKey = what;
- }
- return cacheHsbValue[0] * colorModeX;
- }
-
-
- public final float saturation(int what) {
- if (what != cacheHsbKey) {
- Color.RGBtoHSB((what >> 16) & 0xff, (what >> 8) & 0xff,
- what & 0xff, cacheHsbValue);
- cacheHsbKey = what;
- }
- return cacheHsbValue[1] * colorModeY;
- }
-
-
- public final float brightness(int what) {
- if (what != cacheHsbKey) {
- Color.RGBtoHSB((what >> 16) & 0xff, (what >> 8) & 0xff,
- what & 0xff, cacheHsbValue);
- cacheHsbKey = what;
- }
- return cacheHsbValue[2] * colorModeZ;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR DATATYPE INTERPOLATION
-
- // Against our better judgement.
-
-
- /**
- * Interpolate between two colors, using the current color mode.
- */
- public int lerpColor(int c1, int c2, float amt) {
- return lerpColor(c1, c2, amt, colorMode);
- }
-
- static float[] lerpColorHSB1;
- static float[] lerpColorHSB2;
-
- /**
- * 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) {
- if (mode == RGB) {
- float a1 = ((c1 >> 24) & 0xff);
- float r1 = (c1 >> 16) & 0xff;
- float g1 = (c1 >> 8) & 0xff;
- float b1 = c1 & 0xff;
- float a2 = (c2 >> 24) & 0xff;
- float r2 = (c2 >> 16) & 0xff;
- float g2 = (c2 >> 8) & 0xff;
- float b2 = c2 & 0xff;
-
- return (((int) (a1 + (a2-a1)*amt) << 24) |
- ((int) (r1 + (r2-r1)*amt) << 16) |
- ((int) (g1 + (g2-g1)*amt) << 8) |
- ((int) (b1 + (b2-b1)*amt)));
-
- } else if (mode == HSB) {
- if (lerpColorHSB1 == null) {
- lerpColorHSB1 = new float[3];
- lerpColorHSB2 = new float[3];
- }
-
- float a1 = (c1 >> 24) & 0xff;
- float a2 = (c2 >> 24) & 0xff;
- int alfa = ((int) (a1 + (a2-a1)*amt)) << 24;
-
- Color.RGBtoHSB((c1 >> 16) & 0xff, (c1 >> 8) & 0xff, c1 & 0xff,
- lerpColorHSB1);
- Color.RGBtoHSB((c2 >> 16) & 0xff, (c2 >> 8) & 0xff, c2 & 0xff,
- lerpColorHSB2);
-
- /* If mode is HSB, this will take the shortest path around the
- * color wheel to find the new color. For instance, red to blue
- * will go red violet blue (backwards in hue space) rather than
- * cycling through ROYGBIV.
- */
- // Disabling rollover (wasn't working anyway) for 0126.
- // Otherwise it makes full spectrum scale impossible for
- // those who might want it...in spite of how despicable
- // a full spectrum scale might be.
- // roll around when 0.9 to 0.1
- // more than 0.5 away means that it should roll in the other direction
- /*
- float h1 = lerpColorHSB1[0];
- float h2 = lerpColorHSB2[0];
- if (Math.abs(h1 - h2) > 0.5f) {
- if (h1 > h2) {
- // i.e. h1 is 0.7, h2 is 0.1
- h2 += 1;
- } else {
- // i.e. h1 is 0.1, h2 is 0.7
- h1 += 1;
- }
- }
- float ho = (PApplet.lerp(lerpColorHSB1[0], lerpColorHSB2[0], amt)) % 1.0f;
- */
- float ho = PApplet.lerp(lerpColorHSB1[0], lerpColorHSB2[0], amt);
- float so = PApplet.lerp(lerpColorHSB1[1], lerpColorHSB2[1], amt);
- float bo = PApplet.lerp(lerpColorHSB1[2], lerpColorHSB2[2], amt);
-
- return alfa | (Color.HSBtoRGB(ho, so, bo) & 0xFFFFFF);
- }
- return 0;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BEGINRAW/ENDRAW
-
-
- /**
- * Record individual lines and triangles by echoing them to another renderer.
- */
- public void beginRaw(PGraphics rawGraphics) { // ignore
- this.raw = rawGraphics;
- rawGraphics.beginDraw();
- }
-
-
- public void endRaw() { // ignore
- if (raw != null) {
- // for 3D, need to flush any geometry that's been stored for sorting
- // (particularly if the ENABLE_DEPTH_SORT hint is set)
- flush();
-
- // just like beginDraw, this will have to be called because
- // endDraw() will be happening outside of draw()
- raw.endDraw();
- raw.dispose();
- raw = null;
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // WARNINGS and EXCEPTIONS
-
-
- static protected HashMap warnings;
-
-
- /**
- * Show a renderer error, and keep track of it so that it's only shown once.
- * @param msg the error message (which will be stored for later comparison)
- */
- static public void showWarning(String msg) { // ignore
- if (warnings == null) {
- warnings = new HashMap();
- }
- if (!warnings.containsKey(msg)) {
- System.err.println(msg);
- warnings.put(msg, new Object());
- }
- }
-
-
- /**
- * Display a warning that the specified method is only available with 3D.
- * @param method The method name (no parentheses)
- */
- static protected void showDepthWarning(String method) {
- showWarning(method + "() can only be used with a renderer that " +
- "supports 3D, such as P3D or OPENGL.");
- }
-
-
- /**
- * Display a warning that the specified method that takes x, y, z parameters
- * can only be used with x and y parameters in this renderer.
- * @param method The method name (no parentheses)
- */
- static protected void showDepthWarningXYZ(String method) {
- showWarning(method + "() with x, y, and z coordinates " +
- "can only be used with a renderer that " +
- "supports 3D, such as P3D or OPENGL. " +
- "Use a version without a z-coordinate instead.");
- }
-
-
- /**
- * Display a warning that the specified method is simply unavailable.
- */
- static protected void showMethodWarning(String method) {
- showWarning(method + "() is not available with this renderer.");
- }
-
-
- /**
- * Error that a particular variation of a method is unavailable (even though
- * other variations are). For instance, if vertex(x, y, u, v) is not
- * available, but vertex(x, y) is just fine.
- */
- static protected void showVariationWarning(String str) {
- showWarning(str + " is not available with this renderer.");
- }
-
-
- /**
- * Display a warning that the specified method is not implemented, meaning
- * that it could be either a completely missing function, although other
- * variations of it may still work properly.
- */
- static protected void showMissingWarning(String method) {
- showWarning(method + "(), or this particular variation of it, " +
- "is not available with this renderer.");
- }
-
-
- /**
- * Show an renderer-related exception that halts the program. Currently just
- * wraps the message as a RuntimeException and throws it, but might do
- * something more specific might be used in the future.
- */
- static public void showException(String msg) { // ignore
- throw new RuntimeException(msg);
- }
-
-
- /**
- * Throw an exeption that halts the program because textFont() has not been
- * used prior to the specified method.
- */
- static protected void showTextFontException(String method) {
- throw new RuntimeException("Use textFont() before " + method + "()");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // RENDERER SUPPORT QUERIES
-
-
- /**
- * 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.
- *
- * A better name? showFrame, displayable, isVisible, visible, shouldDisplay,
- * what to call this?
- */
- public boolean displayable() {
- return true;
- }
-
-
- /**
- * Return true if this renderer supports 2D drawing. Defaults to true.
- */
- public boolean is2D() {
- return true;
- }
-
-
- /**
- * Return true if this renderer supports 2D drawing. Defaults to true.
- */
- public boolean is3D() {
- return false;
- }
-}
diff --git a/core/methods/demo/PImage.java b/core/methods/demo/PImage.java
deleted file mode 100644
index 276617825de..00000000000
--- a/core/methods/demo/PImage.java
+++ /dev/null
@@ -1,2862 +0,0 @@
-/* -*- 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.image.*;
-import java.io.*;
-import java.util.HashMap;
-
-import javax.imageio.ImageIO;
-
-
-
-
-/**
- * Datatype for storing images. Processing can display .gif, .jpg, .tga, and .png images. Images may be displayed in 2D and 3D space.
- * Before an image is used, it must be loaded with the loadImage() function.
- * The PImage object contains fields for the width and height of the image,
- * as well as an array called pixels[] which contains the values for every pixel in the image.
- * A group of methods, described below, allow easy access to the image's pixels and alpha channel and simplify the process of compositing.
- *
Before using the pixels[] array, be sure to use the loadPixels() method on the image to make sure that the pixel data is properly loaded.
- *
To create a new image, use the createImage() function (do not use new PImage()).
- * =advanced
- *
- * Storage class for pixel data. This is the base class for most image and
- * pixel information, such as PGraphics and the video library classes.
- *
- * Code for copying, resizing, scaling, and blending contributed
- * by toxi.
- *
- *
- * @webref image
- * @usage Web & Application
- * @instanceName img any variable of type PImage
- * @see processing.core.PApplet#loadImage(String)
- * @see processing.core.PApplet#imageMode(int)
- * @see processing.core.PApplet#createImage(int, int)
- */
-public class PImage implements PConstants, Cloneable {
-
- /**
- * Format for this image, one of RGB, ARGB or ALPHA.
- * note that RGB images still require 0xff in the high byte
- * because of how they'll be manipulated by other functions
- */
- public int format;
-
- /**
- * Array containing the values for all the pixels in the image. These values are of the color datatype.
- * This array is the size of the image, meaning 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 statement color b = img.pixels[230] will set the variable b equal to the value at that location in the array.
- * Before accessing this array, the data must loaded with the loadPixels() method.
- * After the array data has been modified, the updatePixels() method must be run to update the changes.
- * Without loadPixels(), running the code may (or will in future releases) result in a NullPointerException.
- * @webref
- * @brief Array containing the color of every pixel in the image
- */
- public int[] pixels;
-
- /**
- * The width of the image in units of pixels.
- * @webref
- * @brief Image width
- */
- public int width;
- /**
- * The height of the image in units of pixels.
- * @webref
- * @brief Image height
- */
- public int height;
-
- /**
- * Path to parent object that will be used with save().
- * This prevents users from needing savePath() to use PImage.save().
- */
- public PApplet parent;
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- /** for subclasses that need to store info about the image */
- protected HashMap
- * Also figured out how to avoid parsing the image upside-down
- * (there's a header flag to set the image origin to top-left)
- *
- * Starting with revision 0092, the format setting is taken into account:
- *
- *
ALPHA images written as 8bit grayscale (uses lowest byte)
- *
RGB → 24 bits
- *
ARGB → 32 bits
- *
- * All versions are RLE compressed.
- *
- * Contributed by toxi 8-10 May 2005, based on this RLE
- * specification
- */
- protected boolean saveTGA(OutputStream output) {
- byte header[] = new byte[18];
-
- if (format == ALPHA) { // save ALPHA images as 8bit grayscale
- header[2] = 0x0B;
- header[16] = 0x08;
- header[17] = 0x28;
-
- } else if (format == RGB) {
- header[2] = 0x0A;
- header[16] = 24;
- header[17] = 0x20;
-
- } else if (format == ARGB) {
- header[2] = 0x0A;
- header[16] = 32;
- header[17] = 0x28;
-
- } else {
- throw new RuntimeException("Image format not recognized inside save()");
- }
- // set image dimensions lo-hi byte order
- header[12] = (byte) (width & 0xff);
- header[13] = (byte) (width >> 8);
- header[14] = (byte) (height & 0xff);
- header[15] = (byte) (height >> 8);
-
- try {
- output.write(header);
-
- int maxLen = height * width;
- int index = 0;
- int col; //, prevCol;
- int[] currChunk = new int[128];
-
- // 8bit image exporter is in separate loop
- // to avoid excessive conditionals...
- if (format == ALPHA) {
- while (index < maxLen) {
- boolean isRLE = false;
- int rle = 1;
- currChunk[0] = col = pixels[index] & 0xff;
- while (index + rle < maxLen) {
- if (col != (pixels[index + rle]&0xff) || rle == 128) {
- isRLE = (rle > 1);
- break;
- }
- rle++;
- }
- if (isRLE) {
- output.write(0x80 | (rle - 1));
- output.write(col);
-
- } else {
- rle = 1;
- while (index + rle < maxLen) {
- int cscan = pixels[index + rle] & 0xff;
- if ((col != cscan && rle < 128) || rle < 3) {
- currChunk[rle] = col = cscan;
- } else {
- if (col == cscan) rle -= 2;
- break;
- }
- rle++;
- }
- output.write(rle - 1);
- for (int i = 0; i < rle; i++) output.write(currChunk[i]);
- }
- index += rle;
- }
- } else { // export 24/32 bit TARGA
- while (index < maxLen) {
- boolean isRLE = false;
- currChunk[0] = col = pixels[index];
- int rle = 1;
- // try to find repeating bytes (min. len = 2 pixels)
- // maximum chunk size is 128 pixels
- while (index + rle < maxLen) {
- if (col != pixels[index + rle] || rle == 128) {
- isRLE = (rle > 1); // set flag for RLE chunk
- break;
- }
- rle++;
- }
- if (isRLE) {
- output.write(128 | (rle - 1));
- output.write(col & 0xff);
- output.write(col >> 8 & 0xff);
- output.write(col >> 16 & 0xff);
- if (format == ARGB) output.write(col >>> 24 & 0xff);
-
- } else { // not RLE
- rle = 1;
- while (index + rle < maxLen) {
- if ((col != pixels[index + rle] && rle < 128) || rle < 3) {
- currChunk[rle] = col = pixels[index + rle];
- } else {
- // check if the exit condition was the start of
- // a repeating colour
- if (col == pixels[index + rle]) rle -= 2;
- break;
- }
- rle++;
- }
- // write uncompressed chunk
- output.write(rle - 1);
- if (format == ARGB) {
- for (int i = 0; i < rle; i++) {
- col = currChunk[i];
- output.write(col & 0xff);
- output.write(col >> 8 & 0xff);
- output.write(col >> 16 & 0xff);
- output.write(col >>> 24 & 0xff);
- }
- } else {
- for (int i = 0; i < rle; i++) {
- col = currChunk[i];
- output.write(col & 0xff);
- output.write(col >> 8 & 0xff);
- output.write(col >> 16 & 0xff);
- }
- }
- }
- index += rle;
- }
- }
- output.flush();
- return true;
-
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
- }
-
-
- /**
- * Use ImageIO functions from Java 1.4 and later to handle image save.
- * Various formats are supported, typically jpeg, png, bmp, and wbmp.
- * To get a list of the supported formats for writing, use:
- * println(javax.imageio.ImageIO.getReaderFormatNames())
- */
- protected void saveImageIO(String path) throws IOException {
- try {
- BufferedImage bimage =
- new BufferedImage(width, height, (format == ARGB) ?
- BufferedImage.TYPE_INT_ARGB :
- BufferedImage.TYPE_INT_RGB);
- /*
- Class bufferedImageClass =
- Class.forName("java.awt.image.BufferedImage");
- Constructor bufferedImageConstructor =
- bufferedImageClass.getConstructor(new Class[] {
- Integer.TYPE,
- Integer.TYPE,
- Integer.TYPE });
- Field typeIntRgbField = bufferedImageClass.getField("TYPE_INT_RGB");
- int typeIntRgb = typeIntRgbField.getInt(typeIntRgbField);
- Field typeIntArgbField = bufferedImageClass.getField("TYPE_INT_ARGB");
- int typeIntArgb = typeIntArgbField.getInt(typeIntArgbField);
- Object bimage =
- bufferedImageConstructor.newInstance(new Object[] {
- new Integer(width),
- new Integer(height),
- new Integer((format == ARGB) ? typeIntArgb : typeIntRgb)
- });
- */
-
- bimage.setRGB(0, 0, width, height, pixels, 0, width);
- /*
- Method setRgbMethod =
- bufferedImageClass.getMethod("setRGB", new Class[] {
- Integer.TYPE, Integer.TYPE,
- Integer.TYPE, Integer.TYPE,
- pixels.getClass(),
- Integer.TYPE, Integer.TYPE
- });
- setRgbMethod.invoke(bimage, new Object[] {
- new Integer(0), new Integer(0),
- new Integer(width), new Integer(height),
- pixels, new Integer(0), new Integer(width)
- });
- */
-
- File file = new File(path);
- String extension = path.substring(path.lastIndexOf('.') + 1);
-
- ImageIO.write(bimage, extension, file);
- /*
- Class renderedImageClass =
- Class.forName("java.awt.image.RenderedImage");
- Class ioClass = Class.forName("javax.imageio.ImageIO");
- Method writeMethod =
- ioClass.getMethod("write", new Class[] {
- renderedImageClass, String.class, File.class
- });
- writeMethod.invoke(null, new Object[] { bimage, extension, file });
- */
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new IOException("image save failed.");
- }
- }
-
-
- protected String[] saveImageFormats;
-
- /**
- * Saves the image into a file. Images are saved in TIFF, TARGA, JPEG, and PNG format depending on the extension within the filename parameter.
- * For example, "image.tif" will have a TIFF image and "image.png" will save a PNG image.
- * If no extension is included in the filename, the image will save in TIFF format and .tif will be added to the name.
- * These files are saved to the sketch's folder, which may be opened by selecting "Show sketch folder" from the "Sketch" menu.
- * It is not possible to use save() while running the program in a web browser.
- * To save an image created within the code, rather than through loading, it's necessary to make the image with the createImage()
- * function so it is aware of the location of the program and can therefore save the file to the right place.
- * See the createImage() reference for more information.
- *
- * =advanced
- * Save this image to disk.
- *
- * 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.
- *
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.
- */
- static public int blendColor(int c1, int c2, int mode) {
- switch (mode) {
- case REPLACE: return c2;
- case BLEND: return blend_blend(c1, c2);
-
- case ADD: return blend_add_pin(c1, c2);
- case SUBTRACT: return blend_sub_pin(c1, c2);
-
- case LIGHTEST: return blend_lightest(c1, c2);
- case DARKEST: return blend_darkest(c1, c2);
-
- case DIFFERENCE: return blend_difference(c1, c2);
- case EXCLUSION: return blend_exclusion(c1, c2);
-
- case MULTIPLY: return blend_multiply(c1, c2);
- case SCREEN: return blend_screen(c1, c2);
-
- case HARD_LIGHT: return blend_hard_light(c1, c2);
- case SOFT_LIGHT: return blend_soft_light(c1, c2);
- case OVERLAY: return blend_overlay(c1, c2);
-
- case DODGE: return blend_dodge(c1, c2);
- case BURN: return blend_burn(c1, c2);
- }
- return 0;
- }
-
-
- /**
- * Blends one area of this image to another area.
- * @see processing.core.PImage#blendColor(int,int,int)
- */
- public void blend(int sx, int sy, int sw, int sh,
- int dx, int dy, int dw, int dh, int mode) {
- blend(this, sx, sy, sw, sh, dx, dy, dw, dh, mode);
- }
-
-
- /**
- * Copies area of one image into another PImage object.
- * @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 (imageMode == CORNER) { // if CORNERS, do nothing
- sx2 += sx1;
- sy2 += sy1;
- dx2 += dx1;
- dy2 += dy1;
-
- } else if (imageMode == CENTER) {
- sx1 -= sx2 / 2f;
- sy1 -= sy2 / 2f;
- sx2 += sx1;
- sy2 += sy1;
- dx1 -= dx2 / 2f;
- dy1 -= dy2 / 2f;
- dx2 += dx1;
- dy2 += dy1;
- }
- */
- int sx2 = sx + sw;
- int sy2 = sy + sh;
- int dx2 = dx + dw;
- int dy2 = dy + dh;
-
- loadPixels();
- if (src == this) {
- if (intersect(sx, sy, sx2, sy2, dx, dy, dx2, dy2)) {
- blit_resize(get(sx, sy, sx2 - sx, sy2 - sy),
- 0, 0, sx2 - sx - 1, sy2 - sy - 1,
- pixels, width, height, dx, dy, dx2, dy2, mode);
- } else {
- // same as below, except skip the loadPixels() because it'd be redundant
- blit_resize(src, sx, sy, sx2, sy2,
- pixels, width, height, dx, dy, dx2, dy2, mode);
- }
- } else {
- src.loadPixels();
- blit_resize(src, sx, sy, sx2, sy2,
- pixels, width, height, dx, dy, dx2, dy2, mode);
- //src.updatePixels();
- }
- updatePixels();
- }
-
-
- /**
- * Check to see if two rectangles intersect one another
- */
- private boolean intersect(int sx1, int sy1, int sx2, int sy2,
- int dx1, int dy1, int dx2, int dy2) {
- int sw = sx2 - sx1 + 1;
- int sh = sy2 - sy1 + 1;
- int dw = dx2 - dx1 + 1;
- int dh = dy2 - dy1 + 1;
-
- if (dx1 < sx1) {
- dw += dx1 - sx1;
- if (dw > sw) {
- dw = sw;
- }
- } else {
- int w = sw + sx1 - dx1;
- if (dw > w) {
- dw = w;
- }
- }
- if (dy1 < sy1) {
- dh += dy1 - sy1;
- if (dh > sh) {
- dh = sh;
- }
- } else {
- int h = sh + sy1 - dy1;
- if (dh > h) {
- dh = h;
- }
- }
- return !(dw <= 0 || dh <= 0);
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- /**
- * Internal blitter/resizer/copier from toxi.
- * Uses bilinear filtering if smooth() has been enabled
- * 'mode' determines the blending mode used in the process.
- */
- private void blit_resize(PImage img,
- int srcX1, int srcY1, int srcX2, int srcY2,
- int[] destPixels, int screenW, int screenH,
- int destX1, int destY1, int destX2, int destY2,
- int mode) {
- if (srcX1 < 0) srcX1 = 0;
- if (srcY1 < 0) srcY1 = 0;
- if (srcX2 >= img.width) srcX2 = img.width - 1;
- if (srcY2 >= img.height) srcY2 = img.height - 1;
-
- int srcW = srcX2 - srcX1;
- int srcH = srcY2 - srcY1;
- int destW = destX2 - destX1;
- int destH = destY2 - destY1;
-
- boolean smooth = true; // may as well go with the smoothing these days
-
- if (!smooth) {
- srcW++; srcH++;
- }
-
- if (destW <= 0 || destH <= 0 ||
- srcW <= 0 || srcH <= 0 ||
- destX1 >= screenW || destY1 >= screenH ||
- srcX1 >= img.width || srcY1 >= img.height) {
- return;
- }
-
- int dx = (int) (srcW / (float) destW * PRECISIONF);
- int dy = (int) (srcH / (float) destH * PRECISIONF);
-
- srcXOffset = (int) (destX1 < 0 ? -destX1 * dx : srcX1 * PRECISIONF);
- srcYOffset = (int) (destY1 < 0 ? -destY1 * dy : srcY1 * PRECISIONF);
-
- if (destX1 < 0) {
- destW += destX1;
- destX1 = 0;
- }
- if (destY1 < 0) {
- destH += destY1;
- destY1 = 0;
- }
-
- destW = low(destW, screenW - destX1);
- destH = low(destH, screenH - destY1);
-
- int destOffset = destY1 * screenW + destX1;
- srcBuffer = img.pixels;
-
- if (smooth) {
- // use bilinear filtering
- iw = img.width;
- iw1 = img.width - 1;
- ih1 = img.height - 1;
-
- switch (mode) {
-
- case BLEND:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- // davbol - renamed old blend_multiply to blend_blend
- destPixels[destOffset + x] =
- blend_blend(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case ADD:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_add_pin(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case SUBTRACT:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_sub_pin(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case LIGHTEST:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_lightest(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case DARKEST:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_darkest(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case REPLACE:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] = filter_bilinear();
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case DIFFERENCE:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_difference(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case EXCLUSION:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_exclusion(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case MULTIPLY:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_multiply(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case SCREEN:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_screen(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case OVERLAY:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_overlay(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case HARD_LIGHT:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_hard_light(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case SOFT_LIGHT:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_soft_light(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- // davbol - proposed 2007-01-09
- case DODGE:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_dodge(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case BURN:
- for (int y = 0; y < destH; y++) {
- filter_new_scanline();
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_burn(destPixels[destOffset + x], filter_bilinear());
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- }
-
- } else {
- // nearest neighbour scaling (++fast!)
- switch (mode) {
-
- case BLEND:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- // davbol - renamed old blend_multiply to blend_blend
- destPixels[destOffset + x] =
- blend_blend(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case ADD:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_add_pin(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case SUBTRACT:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_sub_pin(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case LIGHTEST:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_lightest(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case DARKEST:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_darkest(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case REPLACE:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] = srcBuffer[sY + (sX >> PRECISIONB)];
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case DIFFERENCE:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_difference(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case EXCLUSION:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_exclusion(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case MULTIPLY:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_multiply(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case SCREEN:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_screen(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case OVERLAY:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_overlay(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case HARD_LIGHT:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_hard_light(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case SOFT_LIGHT:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_soft_light(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- // davbol - proposed 2007-01-09
- case DODGE:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_dodge(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- case BURN:
- for (int y = 0; y < destH; y++) {
- sX = srcXOffset;
- sY = (srcYOffset >> PRECISIONB) * img.width;
- for (int x = 0; x < destW; x++) {
- destPixels[destOffset + x] =
- blend_burn(destPixels[destOffset + x],
- srcBuffer[sY + (sX >> PRECISIONB)]);
- sX += dx;
- }
- destOffset += screenW;
- srcYOffset += dy;
- }
- break;
-
- }
- }
- }
-
-
- private void filter_new_scanline() {
- sX = srcXOffset;
- fracV = srcYOffset & PREC_MAXVAL;
- ifV = PREC_MAXVAL - fracV;
- v1 = (srcYOffset >> PRECISIONB) * iw;
- v2 = low((srcYOffset >> PRECISIONB) + 1, ih1) * iw;
- }
-
-
- private int filter_bilinear() {
- fracU = sX & PREC_MAXVAL;
- ifU = PREC_MAXVAL - fracU;
- ul = (ifU * ifV) >> PRECISIONB;
- ll = (ifU * fracV) >> PRECISIONB;
- ur = (fracU * ifV) >> PRECISIONB;
- lr = (fracU * fracV) >> PRECISIONB;
- u1 = (sX >> PRECISIONB);
- u2 = low(u1 + 1, iw1);
-
- // get color values of the 4 neighbouring texels
- cUL = srcBuffer[v1 + u1];
- cUR = srcBuffer[v1 + u2];
- cLL = srcBuffer[v2 + u1];
- cLR = srcBuffer[v2 + u2];
-
- r = ((ul*((cUL&RED_MASK)>>16) + ll*((cLL&RED_MASK)>>16) +
- ur*((cUR&RED_MASK)>>16) + lr*((cLR&RED_MASK)>>16))
- << PREC_RED_SHIFT) & RED_MASK;
-
- g = ((ul*(cUL&GREEN_MASK) + ll*(cLL&GREEN_MASK) +
- ur*(cUR&GREEN_MASK) + lr*(cLR&GREEN_MASK))
- >>> PRECISIONB) & GREEN_MASK;
-
- b = (ul*(cUL&BLUE_MASK) + ll*(cLL&BLUE_MASK) +
- ur*(cUR&BLUE_MASK) + lr*(cLR&BLUE_MASK))
- >>> PRECISIONB;
-
- a = ((ul*((cUL&ALPHA_MASK)>>>24) + ll*((cLL&ALPHA_MASK)>>>24) +
- ur*((cUR&ALPHA_MASK)>>>24) + lr*((cLR&ALPHA_MASK)>>>24))
- << PREC_ALPHA_SHIFT) & ALPHA_MASK;
-
- return a | r | g | b;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // internal blending methods
-
-
- private static int low(int a, int b) {
- return (a < b) ? a : b;
- }
-
-
- private static int high(int a, int b) {
- return (a > b) ? a : b;
- }
-
- // davbol - added peg helper, equiv to constrain(n,0,255)
- private static int peg(int n) {
- return (n < 0) ? 0 : ((n > 255) ? 255 : n);
- }
-
- private static int mix(int a, int b, int f) {
- return a + (((b - a) * f) >> 8);
- }
-
-
-
- /////////////////////////////////////////////////////////////
-
- // BLEND MODE IMPLEMENTIONS
-
-
- private static int blend_blend(int a, int b) {
- int f = (b & ALPHA_MASK) >>> 24;
-
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- mix(a & RED_MASK, b & RED_MASK, f) & RED_MASK |
- mix(a & GREEN_MASK, b & GREEN_MASK, f) & GREEN_MASK |
- mix(a & BLUE_MASK, b & BLUE_MASK, f));
- }
-
-
- /**
- * additive blend with clipping
- */
- private static int blend_add_pin(int a, int b) {
- int f = (b & ALPHA_MASK) >>> 24;
-
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- low(((a & RED_MASK) +
- ((b & RED_MASK) >> 8) * f), RED_MASK) & RED_MASK |
- low(((a & GREEN_MASK) +
- ((b & GREEN_MASK) >> 8) * f), GREEN_MASK) & GREEN_MASK |
- low((a & BLUE_MASK) +
- (((b & BLUE_MASK) * f) >> 8), BLUE_MASK));
- }
-
-
- /**
- * subtractive blend with clipping
- */
- private static int blend_sub_pin(int a, int b) {
- int f = (b & ALPHA_MASK) >>> 24;
-
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- high(((a & RED_MASK) - ((b & RED_MASK) >> 8) * f),
- GREEN_MASK) & RED_MASK |
- high(((a & GREEN_MASK) - ((b & GREEN_MASK) >> 8) * f),
- BLUE_MASK) & GREEN_MASK |
- high((a & BLUE_MASK) - (((b & BLUE_MASK) * f) >> 8), 0));
- }
-
-
- /**
- * only returns the blended lightest colour
- */
- private static int blend_lightest(int a, int b) {
- int f = (b & ALPHA_MASK) >>> 24;
-
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- high(a & RED_MASK, ((b & RED_MASK) >> 8) * f) & RED_MASK |
- high(a & GREEN_MASK, ((b & GREEN_MASK) >> 8) * f) & GREEN_MASK |
- high(a & BLUE_MASK, ((b & BLUE_MASK) * f) >> 8));
- }
-
-
- /**
- * only returns the blended darkest colour
- */
- private static int blend_darkest(int a, int b) {
- int f = (b & ALPHA_MASK) >>> 24;
-
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- mix(a & RED_MASK,
- low(a & RED_MASK,
- ((b & RED_MASK) >> 8) * f), f) & RED_MASK |
- mix(a & GREEN_MASK,
- low(a & GREEN_MASK,
- ((b & GREEN_MASK) >> 8) * f), f) & GREEN_MASK |
- mix(a & BLUE_MASK,
- low(a & BLUE_MASK,
- ((b & BLUE_MASK) * f) >> 8), f));
- }
-
-
- /**
- * returns the absolute value of the difference of the input colors
- * C = |A - B|
- */
- private static int blend_difference(int a, int b) {
- // setup (this portion will always be the same)
- int f = (b & ALPHA_MASK) >>> 24;
- int ar = (a & RED_MASK) >> 16;
- int ag = (a & GREEN_MASK) >> 8;
- int ab = (a & BLUE_MASK);
- int br = (b & RED_MASK) >> 16;
- int bg = (b & GREEN_MASK) >> 8;
- int bb = (b & BLUE_MASK);
- // formula:
- int cr = (ar > br) ? (ar-br) : (br-ar);
- int cg = (ag > bg) ? (ag-bg) : (bg-ag);
- int cb = (ab > bb) ? (ab-bb) : (bb-ab);
- // alpha blend (this portion will always be the same)
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- (peg(ar + (((cr - ar) * f) >> 8)) << 16) |
- (peg(ag + (((cg - ag) * f) >> 8)) << 8) |
- (peg(ab + (((cb - ab) * f) >> 8)) ) );
- }
-
-
- /**
- * Cousin of difference, algorithm used here is based on a Lingo version
- * found here: http://www.mediamacros.com/item/item-1006687616/
- * (Not yet verified to be correct).
- */
- private static int blend_exclusion(int a, int b) {
- // setup (this portion will always be the same)
- int f = (b & ALPHA_MASK) >>> 24;
- int ar = (a & RED_MASK) >> 16;
- int ag = (a & GREEN_MASK) >> 8;
- int ab = (a & BLUE_MASK);
- int br = (b & RED_MASK) >> 16;
- int bg = (b & GREEN_MASK) >> 8;
- int bb = (b & BLUE_MASK);
- // formula:
- int cr = ar + br - ((ar * br) >> 7);
- int cg = ag + bg - ((ag * bg) >> 7);
- int cb = ab + bb - ((ab * bb) >> 7);
- // alpha blend (this portion will always be the same)
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- (peg(ar + (((cr - ar) * f) >> 8)) << 16) |
- (peg(ag + (((cg - ag) * f) >> 8)) << 8) |
- (peg(ab + (((cb - ab) * f) >> 8)) ) );
- }
-
-
- /**
- * returns the product of the input colors
- * C = A * B
- */
- private static int blend_multiply(int a, int b) {
- // setup (this portion will always be the same)
- int f = (b & ALPHA_MASK) >>> 24;
- int ar = (a & RED_MASK) >> 16;
- int ag = (a & GREEN_MASK) >> 8;
- int ab = (a & BLUE_MASK);
- int br = (b & RED_MASK) >> 16;
- int bg = (b & GREEN_MASK) >> 8;
- int bb = (b & BLUE_MASK);
- // formula:
- int cr = (ar * br) >> 8;
- int cg = (ag * bg) >> 8;
- int cb = (ab * bb) >> 8;
- // alpha blend (this portion will always be the same)
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- (peg(ar + (((cr - ar) * f) >> 8)) << 16) |
- (peg(ag + (((cg - ag) * f) >> 8)) << 8) |
- (peg(ab + (((cb - ab) * f) >> 8)) ) );
- }
-
-
- /**
- * returns the inverse of the product of the inverses of the input colors
- * (the inverse of multiply). C = 1 - (1-A) * (1-B)
- */
- private static int blend_screen(int a, int b) {
- // setup (this portion will always be the same)
- int f = (b & ALPHA_MASK) >>> 24;
- int ar = (a & RED_MASK) >> 16;
- int ag = (a & GREEN_MASK) >> 8;
- int ab = (a & BLUE_MASK);
- int br = (b & RED_MASK) >> 16;
- int bg = (b & GREEN_MASK) >> 8;
- int bb = (b & BLUE_MASK);
- // formula:
- int cr = 255 - (((255 - ar) * (255 - br)) >> 8);
- int cg = 255 - (((255 - ag) * (255 - bg)) >> 8);
- int cb = 255 - (((255 - ab) * (255 - bb)) >> 8);
- // alpha blend (this portion will always be the same)
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- (peg(ar + (((cr - ar) * f) >> 8)) << 16) |
- (peg(ag + (((cg - ag) * f) >> 8)) << 8) |
- (peg(ab + (((cb - ab) * f) >> 8)) ) );
- }
-
-
- /**
- * returns either multiply or screen for darker or lighter values of A
- * (the inverse of hard light)
- * C =
- * A < 0.5 : 2 * A * B
- * A >=0.5 : 1 - (2 * (255-A) * (255-B))
- */
- private static int blend_overlay(int a, int b) {
- // setup (this portion will always be the same)
- int f = (b & ALPHA_MASK) >>> 24;
- int ar = (a & RED_MASK) >> 16;
- int ag = (a & GREEN_MASK) >> 8;
- int ab = (a & BLUE_MASK);
- int br = (b & RED_MASK) >> 16;
- int bg = (b & GREEN_MASK) >> 8;
- int bb = (b & BLUE_MASK);
- // formula:
- int cr = (ar < 128) ? ((ar*br)>>7) : (255-(((255-ar)*(255-br))>>7));
- int cg = (ag < 128) ? ((ag*bg)>>7) : (255-(((255-ag)*(255-bg))>>7));
- int cb = (ab < 128) ? ((ab*bb)>>7) : (255-(((255-ab)*(255-bb))>>7));
- // alpha blend (this portion will always be the same)
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- (peg(ar + (((cr - ar) * f) >> 8)) << 16) |
- (peg(ag + (((cg - ag) * f) >> 8)) << 8) |
- (peg(ab + (((cb - ab) * f) >> 8)) ) );
- }
-
-
- /**
- * returns either multiply or screen for darker or lighter values of B
- * (the inverse of overlay)
- * C =
- * B < 0.5 : 2 * A * B
- * B >=0.5 : 1 - (2 * (255-A) * (255-B))
- */
- private static int blend_hard_light(int a, int b) {
- // setup (this portion will always be the same)
- int f = (b & ALPHA_MASK) >>> 24;
- int ar = (a & RED_MASK) >> 16;
- int ag = (a & GREEN_MASK) >> 8;
- int ab = (a & BLUE_MASK);
- int br = (b & RED_MASK) >> 16;
- int bg = (b & GREEN_MASK) >> 8;
- int bb = (b & BLUE_MASK);
- // formula:
- int cr = (br < 128) ? ((ar*br)>>7) : (255-(((255-ar)*(255-br))>>7));
- int cg = (bg < 128) ? ((ag*bg)>>7) : (255-(((255-ag)*(255-bg))>>7));
- int cb = (bb < 128) ? ((ab*bb)>>7) : (255-(((255-ab)*(255-bb))>>7));
- // alpha blend (this portion will always be the same)
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- (peg(ar + (((cr - ar) * f) >> 8)) << 16) |
- (peg(ag + (((cg - ag) * f) >> 8)) << 8) |
- (peg(ab + (((cb - ab) * f) >> 8)) ) );
- }
-
-
- /**
- * returns the inverse multiply plus screen, which simplifies to
- * C = 2AB + A^2 - 2A^2B
- */
- private static int blend_soft_light(int a, int b) {
- // setup (this portion will always be the same)
- int f = (b & ALPHA_MASK) >>> 24;
- int ar = (a & RED_MASK) >> 16;
- int ag = (a & GREEN_MASK) >> 8;
- int ab = (a & BLUE_MASK);
- int br = (b & RED_MASK) >> 16;
- int bg = (b & GREEN_MASK) >> 8;
- int bb = (b & BLUE_MASK);
- // formula:
- int cr = ((ar*br)>>7) + ((ar*ar)>>8) - ((ar*ar*br)>>15);
- int cg = ((ag*bg)>>7) + ((ag*ag)>>8) - ((ag*ag*bg)>>15);
- int cb = ((ab*bb)>>7) + ((ab*ab)>>8) - ((ab*ab*bb)>>15);
- // alpha blend (this portion will always be the same)
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- (peg(ar + (((cr - ar) * f) >> 8)) << 16) |
- (peg(ag + (((cg - ag) * f) >> 8)) << 8) |
- (peg(ab + (((cb - ab) * f) >> 8)) ) );
- }
-
-
- /**
- * Returns the first (underlay) color divided by the inverse of
- * the second (overlay) color. C = A / (255-B)
- */
- private static int blend_dodge(int a, int b) {
- // setup (this portion will always be the same)
- int f = (b & ALPHA_MASK) >>> 24;
- int ar = (a & RED_MASK) >> 16;
- int ag = (a & GREEN_MASK) >> 8;
- int ab = (a & BLUE_MASK);
- int br = (b & RED_MASK) >> 16;
- int bg = (b & GREEN_MASK) >> 8;
- int bb = (b & BLUE_MASK);
- // formula:
- int cr = (br==255) ? 255 : peg((ar << 8) / (255 - br)); // division requires pre-peg()-ing
- int cg = (bg==255) ? 255 : peg((ag << 8) / (255 - bg)); // "
- int cb = (bb==255) ? 255 : peg((ab << 8) / (255 - bb)); // "
- // alpha blend (this portion will always be the same)
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- (peg(ar + (((cr - ar) * f) >> 8)) << 16) |
- (peg(ag + (((cg - ag) * f) >> 8)) << 8) |
- (peg(ab + (((cb - ab) * f) >> 8)) ) );
- }
-
-
- /**
- * returns the inverse of the inverse of the first (underlay) color
- * divided by the second (overlay) color. C = 255 - (255-A) / B
- */
- private static int blend_burn(int a, int b) {
- // setup (this portion will always be the same)
- int f = (b & ALPHA_MASK) >>> 24;
- int ar = (a & RED_MASK) >> 16;
- int ag = (a & GREEN_MASK) >> 8;
- int ab = (a & BLUE_MASK);
- int br = (b & RED_MASK) >> 16;
- int bg = (b & GREEN_MASK) >> 8;
- int bb = (b & BLUE_MASK);
- // formula:
- int cr = (br==0) ? 0 : 255 - peg(((255 - ar) << 8) / br); // division requires pre-peg()-ing
- int cg = (bg==0) ? 0 : 255 - peg(((255 - ag) << 8) / bg); // "
- int cb = (bb==0) ? 0 : 255 - peg(((255 - ab) << 8) / bb); // "
- // alpha blend (this portion will always be the same)
- return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 |
- (peg(ar + (((cr - ar) * f) >> 8)) << 16) |
- (peg(ag + (((cg - ag) * f) >> 8)) << 8) |
- (peg(ab + (((cb - ab) * f) >> 8)) ) );
- }
-
-
- //////////////////////////////////////////////////////////////
-
- // FILE I/O
-
-
- static byte TIFF_HEADER[] = {
- 77, 77, 0, 42, 0, 0, 0, 8, 0, 9, 0, -2, 0, 4, 0, 0, 0, 1, 0, 0,
- 0, 0, 1, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 3, 0, 0, 0, 1,
- 0, 0, 0, 0, 1, 2, 0, 3, 0, 0, 0, 3, 0, 0, 0, 122, 1, 6, 0, 3, 0,
- 0, 0, 1, 0, 2, 0, 0, 1, 17, 0, 4, 0, 0, 0, 1, 0, 0, 3, 0, 1, 21,
- 0, 3, 0, 0, 0, 1, 0, 3, 0, 0, 1, 22, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0,
- 1, 23, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 8, 0, 8
- };
-
-
- static final String TIFF_ERROR =
- "Error: Processing can only read its own TIFF files.";
-
- static protected PImage loadTIFF(byte tiff[]) {
- if ((tiff[42] != tiff[102]) || // width/height in both places
- (tiff[43] != tiff[103])) {
- System.err.println(TIFF_ERROR);
- return null;
- }
-
- int width =
- ((tiff[30] & 0xff) << 8) | (tiff[31] & 0xff);
- int height =
- ((tiff[42] & 0xff) << 8) | (tiff[43] & 0xff);
-
- int count =
- ((tiff[114] & 0xff) << 24) |
- ((tiff[115] & 0xff) << 16) |
- ((tiff[116] & 0xff) << 8) |
- (tiff[117] & 0xff);
- if (count != width * height * 3) {
- System.err.println(TIFF_ERROR + " (" + width + ", " + height +")");
- return null;
- }
-
- // check the rest of the header
- for (int i = 0; i < TIFF_HEADER.length; i++) {
- if ((i == 30) || (i == 31) || (i == 42) || (i == 43) ||
- (i == 102) || (i == 103) ||
- (i == 114) || (i == 115) || (i == 116) || (i == 117)) continue;
-
- if (tiff[i] != TIFF_HEADER[i]) {
- System.err.println(TIFF_ERROR + " (" + i + ")");
- return null;
- }
- }
-
- PImage outgoing = new PImage(width, height, RGB);
- int index = 768;
- count /= 3;
- for (int i = 0; i < count; i++) {
- outgoing.pixels[i] =
- 0xFF000000 |
- (tiff[index++] & 0xff) << 16 |
- (tiff[index++] & 0xff) << 8 |
- (tiff[index++] & 0xff);
- }
- return outgoing;
- }
-
-
- protected boolean saveTIFF(OutputStream output) {
- // shutting off the warning, people can figure this out themselves
- /*
- if (format != RGB) {
- System.err.println("Warning: only RGB information is saved with " +
- ".tif files. Use .tga or .png for ARGB images and others.");
- }
- */
- try {
- byte tiff[] = new byte[768];
- System.arraycopy(TIFF_HEADER, 0, tiff, 0, TIFF_HEADER.length);
-
- tiff[30] = (byte) ((width >> 8) & 0xff);
- tiff[31] = (byte) ((width) & 0xff);
- tiff[42] = tiff[102] = (byte) ((height >> 8) & 0xff);
- tiff[43] = tiff[103] = (byte) ((height) & 0xff);
-
- int count = width*height*3;
- tiff[114] = (byte) ((count >> 24) & 0xff);
- tiff[115] = (byte) ((count >> 16) & 0xff);
- tiff[116] = (byte) ((count >> 8) & 0xff);
- tiff[117] = (byte) ((count) & 0xff);
-
- // spew the header to the disk
- output.write(tiff);
-
- for (int i = 0; i < pixels.length; i++) {
- output.write((pixels[i] >> 16) & 0xff);
- output.write((pixels[i] >> 8) & 0xff);
- output.write(pixels[i] & 0xff);
- }
- output.flush();
- return true;
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- return false;
- }
-
-
- /**
- * Creates a Targa32 formatted byte sequence of specified
- * pixel buffer using RLE compression.
- *
- * Also figured out how to avoid parsing the image upside-down
- * (there's a header flag to set the image origin to top-left)
- *
- * Starting with revision 0092, the format setting is taken into account:
- *
- *
ALPHA images written as 8bit grayscale (uses lowest byte)
- *
RGB → 24 bits
- *
ARGB → 32 bits
- *
- * All versions are RLE compressed.
- *
- * Contributed by toxi 8-10 May 2005, based on this RLE
- * specification
- */
- protected boolean saveTGA(OutputStream output) {
- byte header[] = new byte[18];
-
- if (format == ALPHA) { // save ALPHA images as 8bit grayscale
- header[2] = 0x0B;
- header[16] = 0x08;
- header[17] = 0x28;
-
- } else if (format == RGB) {
- header[2] = 0x0A;
- header[16] = 24;
- header[17] = 0x20;
-
- } else if (format == ARGB) {
- header[2] = 0x0A;
- header[16] = 32;
- header[17] = 0x28;
-
- } else {
- throw new RuntimeException("Image format not recognized inside save()");
- }
- // set image dimensions lo-hi byte order
- header[12] = (byte) (width & 0xff);
- header[13] = (byte) (width >> 8);
- header[14] = (byte) (height & 0xff);
- header[15] = (byte) (height >> 8);
-
- try {
- output.write(header);
-
- int maxLen = height * width;
- int index = 0;
- int col; //, prevCol;
- int[] currChunk = new int[128];
-
- // 8bit image exporter is in separate loop
- // to avoid excessive conditionals...
- if (format == ALPHA) {
- while (index < maxLen) {
- boolean isRLE = false;
- int rle = 1;
- currChunk[0] = col = pixels[index] & 0xff;
- while (index + rle < maxLen) {
- if (col != (pixels[index + rle]&0xff) || rle == 128) {
- isRLE = (rle > 1);
- break;
- }
- rle++;
- }
- if (isRLE) {
- output.write(0x80 | (rle - 1));
- output.write(col);
-
- } else {
- rle = 1;
- while (index + rle < maxLen) {
- int cscan = pixels[index + rle] & 0xff;
- if ((col != cscan && rle < 128) || rle < 3) {
- currChunk[rle] = col = cscan;
- } else {
- if (col == cscan) rle -= 2;
- break;
- }
- rle++;
- }
- output.write(rle - 1);
- for (int i = 0; i < rle; i++) output.write(currChunk[i]);
- }
- index += rle;
- }
- } else { // export 24/32 bit TARGA
- while (index < maxLen) {
- boolean isRLE = false;
- currChunk[0] = col = pixels[index];
- int rle = 1;
- // try to find repeating bytes (min. len = 2 pixels)
- // maximum chunk size is 128 pixels
- while (index + rle < maxLen) {
- if (col != pixels[index + rle] || rle == 128) {
- isRLE = (rle > 1); // set flag for RLE chunk
- break;
- }
- rle++;
- }
- if (isRLE) {
- output.write(128 | (rle - 1));
- output.write(col & 0xff);
- output.write(col >> 8 & 0xff);
- output.write(col >> 16 & 0xff);
- if (format == ARGB) output.write(col >>> 24 & 0xff);
-
- } else { // not RLE
- rle = 1;
- while (index + rle < maxLen) {
- if ((col != pixels[index + rle] && rle < 128) || rle < 3) {
- currChunk[rle] = col = pixels[index + rle];
- } else {
- // check if the exit condition was the start of
- // a repeating colour
- if (col == pixels[index + rle]) rle -= 2;
- break;
- }
- rle++;
- }
- // write uncompressed chunk
- output.write(rle - 1);
- if (format == ARGB) {
- for (int i = 0; i < rle; i++) {
- col = currChunk[i];
- output.write(col & 0xff);
- output.write(col >> 8 & 0xff);
- output.write(col >> 16 & 0xff);
- output.write(col >>> 24 & 0xff);
- }
- } else {
- for (int i = 0; i < rle; i++) {
- col = currChunk[i];
- output.write(col & 0xff);
- output.write(col >> 8 & 0xff);
- output.write(col >> 16 & 0xff);
- }
- }
- }
- index += rle;
- }
- }
- output.flush();
- return true;
-
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
- }
-
-
- /**
- * Use ImageIO functions from Java 1.4 and later to handle image save.
- * Various formats are supported, typically jpeg, png, bmp, and wbmp.
- * To get a list of the supported formats for writing, use:
- * println(javax.imageio.ImageIO.getReaderFormatNames())
- */
- protected void saveImageIO(String path) throws IOException {
- try {
- BufferedImage bimage =
- new BufferedImage(width, height, (format == ARGB) ?
- BufferedImage.TYPE_INT_ARGB :
- BufferedImage.TYPE_INT_RGB);
- /*
- Class bufferedImageClass =
- Class.forName("java.awt.image.BufferedImage");
- Constructor bufferedImageConstructor =
- bufferedImageClass.getConstructor(new Class[] {
- Integer.TYPE,
- Integer.TYPE,
- Integer.TYPE });
- Field typeIntRgbField = bufferedImageClass.getField("TYPE_INT_RGB");
- int typeIntRgb = typeIntRgbField.getInt(typeIntRgbField);
- Field typeIntArgbField = bufferedImageClass.getField("TYPE_INT_ARGB");
- int typeIntArgb = typeIntArgbField.getInt(typeIntArgbField);
- Object bimage =
- bufferedImageConstructor.newInstance(new Object[] {
- new Integer(width),
- new Integer(height),
- new Integer((format == ARGB) ? typeIntArgb : typeIntRgb)
- });
- */
-
- bimage.setRGB(0, 0, width, height, pixels, 0, width);
- /*
- Method setRgbMethod =
- bufferedImageClass.getMethod("setRGB", new Class[] {
- Integer.TYPE, Integer.TYPE,
- Integer.TYPE, Integer.TYPE,
- pixels.getClass(),
- Integer.TYPE, Integer.TYPE
- });
- setRgbMethod.invoke(bimage, new Object[] {
- new Integer(0), new Integer(0),
- new Integer(width), new Integer(height),
- pixels, new Integer(0), new Integer(width)
- });
- */
-
- File file = new File(path);
- String extension = path.substring(path.lastIndexOf('.') + 1);
-
- ImageIO.write(bimage, extension, file);
- /*
- Class renderedImageClass =
- Class.forName("java.awt.image.RenderedImage");
- Class ioClass = Class.forName("javax.imageio.ImageIO");
- Method writeMethod =
- ioClass.getMethod("write", new Class[] {
- renderedImageClass, String.class, File.class
- });
- writeMethod.invoke(null, new Object[] { bimage, extension, file });
- */
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new IOException("image save failed.");
- }
- }
-
-
- protected String[] saveImageFormats;
-
- /**
- * Save this image to disk.
- *
- * 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.
- */
- public void save(String path) { // ignore
- boolean success = false;
-
- File file = new File(path);
- if (!file.isAbsolute()) {
- if (parent != null) {
- //file = new File(parent.savePath(filename));
- path = parent.savePath(path);
- } 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 (path.endsWith("." + saveImageFormats[i])) {
- saveImageIO(path);
- return;
- }
- }
- }
-
- if (path.toLowerCase().endsWith(".tga")) {
- os = new BufferedOutputStream(new FileOutputStream(path), 32768);
- success = saveTGA(os); //, pixels, width, height, format);
-
- } else {
- if (!path.toLowerCase().endsWith(".tif") &&
- !path.toLowerCase().endsWith(".tiff")) {
- // if no .tif extension, add it..
- path += ".tif";
- }
- os = new BufferedOutputStream(new FileOutputStream(path), 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.");
- }
- }
-}
-
diff --git a/core/preproc/preproc.jar b/core/preproc/preproc.jar
deleted file mode 100644
index e025d6a25e221cf9bdff231c440076a4baccaad7..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 3943
zcmZ{ncRUpSAIDFka*?w_NGIdY=IoVq#+`jeh^&juvuCAYuQ(2O$l0QZN+RUW-V(Ap
zGn+_h@YDDAt>5qad-QvM9-sAiyq=Hu``@QAg8Dce;AidP8I=Bd{C%7P90wR^qtr$9
z4B_GjT>yab-_etRouerEJSfoQC~AMSS&sJasDZkn9$ecDC1wEMG3e<=B1FXo=@FvP
zzMlRXQ;9dy?-zV~G?_3Wy2w6Vb3hywf3NybpLSU+e;K6SFrD{PaVYI}R7QPN+aeuj
z5)F+)8C`BjXJ~eVZG-La5deS_|1&M{XapZ$ZzmT&KR2&y;=g7E0Ji@p2>NHxF~H5k
z`FH%}UvchN37gHQ0RZi@0093V9xna{F8;3G&VFJ}9u9tfiI%`{vk{KNJbd8`
z18)T0bPK9)OnSxlz}$?=L`x}OLcPj(aANmaVxeB$i%4SW&b|7woyJJRrNs(7!wke!
zdkHv`T!xnlkT2e;E=gXV#Qx|v;2dJQe{iFBe?wtre|qMSu+uY&m!-}WVc5|CvFBCI
zI!I?Fkm~Pnm+96@%ilzUK{D$vil>-2k)af}fjNty0bO2L|AGkr-~z350HA76Eh%9UpGD>b^!5y*z&-IjYy^me7k3Kq2-
z(eCBXTWi@kxlPQP)dYEDiSeg}!A&)3UM~exSu!P-Y>?@kX~pYfrsg@40@qVQB0Vui
ze!XCEC{1m+aKu)Dezuv(>BwqMWg%i?j%n0QOOXHQnsh4!kKRvO2jWjDF(pgtexu_u
zmeAEfX!;SLZNN2y<;c4Z9F4`E){)bwAqM|Us%+JkXiTYTwb~tpL-}sqU9H!haJPH4
ze#F|HOVDy2o(~$i=DP=(#yvV-r4OsivaQ53+vXRoI(?NR0G1u%6Pg^YvKUlh@^~
z#DZJlYg)q}b{*+jrA_b85!}k;wXV((S|Y`)S!2lSx5znC(fPN|q?z#3oG+&MaJ5VZ
z;rDuyoRzz*`sCJlA_qrgUWS4{%ec!k4Z9ZJ*UhXpjEvIgoN|G>6ZjmXq6!KvMv|_v
z6+v{|<>6mThuX;&Bw2H=ZmDis&$_cM=BXFv;^XErNyv-9{S|Fst0b0KU^%gf?3S|V
zM~uf}4L%hQuC{IqZ967iT40Q7u=xCQ`S@U02kWXN^Z)NU|;1N*b
zUFs`kR%346mn;d18PthwK9f>K+bW!3`5ZLdF$bLotKqe+{lci-6F;3VvB|_kk0~j4
z-rZq!)%+F-R9o4iDbf=ssz-t>8QSIZ9R`cR{wZHn)Tl-ahci6*|tRsiv8+aGE1O9%h?>
zxF}Yk%P}|~1E62P=tAj`M8E1>7D{mK$YNEUHQf+jwf|Bl=^Es!u>xh*`bBzlL~wH=r-@CT8|mYNysDf^*Q{6}6OTZW{u5CK@sv81a%t90Q&@BpW8AT8Ukj7Yz`}(BzC2Mx
z!waAXT}(UssP8$wW79ojNNmL+_5``<167W@$@VFSXVro5uqX8q>Q@pIdQP+EVHBFx
zSo6#l`)u%WhsFU<;|@Qz32=a~L|*Tn=OEo+KxVSV6cGorn+HzsHxcQlxPk`W?m6c`
zkGH<8sD9RH%_^3ZCoVT5(nNQ=hd%^J&v
z3g!?wyAO$ks5d82lqIX-inu|k;K-U%K_-N*vL#qD#53;m9@F?(-R-kHK_whX`izMa
zz}bfJJ!6n%MwQPz*6jKlhpbK%7QE}dmSLM^Tm`-N>?2VGC`x^cM_9U^Ipc*XxY0q6
z849d}WYy_ca+|cSEOOU$Y+TR}3ey%9?TB<0IWfjj`zh{gzD4h>Gf%wH8;W&aDX0M)
zMs6Xk
_PJ5bbYVCzJBSneT&$i=VVDV&5jaF%08U-NsCp
zV|ouK0&48$53Ok_5u7$C$om;y>e&JPj6j+6PNN`emV5B!f_EC}c>MQA#c?-mD=jU|
zk*CsE7u+amlkTHViFSq|&fJyBfktI4MZO0=jLpr*6_J6&LKh+m0;lJoAaO|qvEHS(
z59uVA(1jytw<^`El&uRn^UWHeo&oYfKp7>^;gxXUxH)vNOJq#l&_lc@o`)_lzlHm?>RD;n5j`ZhsmS)v4!m{zb
z;om%33ugILT~*uX=s-G<*K9>xM#3j%Ib7&+&9k=&L$}XjEgDKQgY_=ovBW;yD)&8S
zXXYh1^CMU@guy0#J=koY-5X+m75`CY8WWP@oA~r!2`g
zG>7p7#tRm)dDS)mwf)+c$tXKVH{_0Acb1;gJiY50FVXW3G3qeD^C>ma;S!7?rZZ?^
zLrI%qB02= 0) {
- break;
- }
- }
-
- // read the rest of the file and append it to the
- while ((line = applet.readLine()) != null) {
- content.append(line + "\n");
- }
-
- applet.close();
- process(out, graphicsFile);
- process(out, imageFile);
-
- out.println("}");
-
- } catch (IOException e) {
- e.printStackTrace();
-
- } catch(Exception ex) {
- ex.printStackTrace();
- }
- out.flush();
-
- if (content.toString().equals(outBytes.toString())) {
- System.out.println("No changes to PApplet API.");
- } else {
- System.out.println("Updating PApplet with API changes from PImage or PGraphics.");
- try {
- PrintStream temp = new PrintStream(appletFile);
- temp.print(outBytes.toString());
- temp.flush();
- temp.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
- }
-
-
- private void process(PrintStream out, File input) throws IOException {
- BufferedReader in = createReader(input);
- int comments = 0;
- String line = null;
-
- while ((line = in.readLine()) != null) {
- String decl = "";
-
- // Keep track of comments
- if (line.matches(Pattern.quote("/*"))) {
- comments ++;
- }
-
- if (line.matches(Pattern.quote("*/"))) {
- comments --;
- }
-
- // Ignore everything inside comments
- if (comments > 0) {
- continue;
- }
-
- boolean gotSomething = false;
- boolean gotStatic = false;
-
- Matcher result;
-
- if ((result = Pattern.compile("^\\s*public ([\\w\\[\\]]+) [a-zA-z_]+\\(.*$").matcher(line)).matches()) {
- gotSomething = true;
- }
- else if ((result = Pattern.compile("^\\s*abstract public ([\\w\\[\\]]+) [a-zA-z_]+\\(.*$").matcher(line)).matches()) {
- gotSomething = true;
- }
- else if ((result = Pattern.compile("^\\s*public final ([\\w\\[\\]]+) [a-zA-z_]+\\(.*$").matcher(line)).matches()) {
- gotSomething = true;
- }
- else if ((result = Pattern.compile("^\\s*static public ([\\w\\[\\]]+) [a-zA-z_]+\\(.*$").matcher(line)).matches()) {
- gotSomething = true;
- gotStatic = true;
- }
-
- // if function is marked "// ignore" then, uh, ignore it.
- if (gotSomething && line.indexOf("// ignore") >= 0) {
- gotSomething = false;
- }
-
- String returns = "";
- if (gotSomething) {
- if (result.group(1).equals("void")) {
- returns = "";
- } else {
- returns = "return ";
- }
-
- // remove the abstract modifier
- line = line.replaceFirst(Pattern.quote("abstract"), " ");
-
- // replace semicolons with a start def
- line = line.replaceAll(Pattern.quote(";"), " {\n");
-
- out.println("\n\n" + line);
-
- decl += line;
- while(line.indexOf(')') == -1) {
- line = in.readLine();
- decl += line;
- line = line.replaceAll("\\;\\s*$", " {\n");
- out.println(line);
- }
-
- result = Pattern.compile(".*?\\s(\\S+)\\(.*?").matcher(decl);
- result.matches(); // try to match. DON't remove this or things will stop working!
- String declName = result.group(1);
- String gline = "";
- String rline = "";
- if (gotStatic) {
- gline = " " + returns + "PGraphics." + declName + "(";
- } else {
- rline = " if (recorder != null) recorder." + declName + "(";
- gline = " " + returns + "g." + declName + "(";
- }
-
- decl = decl.replaceAll("\\s+", " "); // smush onto a single line
- decl = decl.replaceFirst("^.*\\(", "");
- decl = decl.replaceFirst("\\).*$", "");
-
- int prev = 0;
- String parts[] = decl.split("\\, ");
-
- for (String part : parts) {
- if (!part.trim().equals("")) {
- String blargh[] = part.split(" ");
- String theArg = blargh[1].replaceAll("[\\[\\]]", "");
-
- if (prev != 0) {
- gline += ", ";
- rline += ", ";
- }
-
- gline += theArg;
- rline += theArg;
- prev = 1;
- }
- }
-
- gline += ");";
- rline += ");";
-
- if (!gotStatic && returns.equals("")) {
- out.println(rline);
- }
-
- out.println(gline);
- out.println(" }");
- }
- }
-
- in.close();
- }
-
-
- private static BufferedReader createReader(File f) throws FileNotFoundException {
- return new BufferedReader(new InputStreamReader(new FileInputStream(f)));
- }
-}
diff --git a/core/src/processing/core/PApplet.java b/core/src/processing/core/PApplet.java
deleted file mode 100644
index 9504a471a69..00000000000
--- a/core/src/processing/core/PApplet.java
+++ /dev/null
@@ -1,10184 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2004-10 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, version 2.1.
-
- 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.applet.*;
-import java.awt.*;
-import java.awt.event.*;
-import java.awt.image.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.text.*;
-import java.util.*;
-import java.util.regex.*;
-import java.util.zip.*;
-
-import javax.imageio.ImageIO;
-import javax.swing.JFileChooser;
-import javax.swing.SwingUtilities;
-
-import processing.core.PShape;
-
-
-/**
- * Base class for all sketches that use processing.core.
- *
- * Note that you should not use AWT or Swing components inside a Processing
- * applet. The surface is made to automatically update itself, and will cause
- * problems with redraw of components drawn above it. If you'd like to
- * integrate other Java components, see below.
- *
- * As of release 0145, Processing uses active mode rendering in all cases.
- * All animation tasks happen on the "Processing Animation Thread". The
- * setup() and draw() methods are handled by that thread, and events (like
- * mouse movement and key presses, which are fired by the event dispatch
- * thread or EDT) are queued to be (safely) handled at the end of draw().
- * For code that needs to run on the EDT, use SwingUtilities.invokeLater().
- * When doing so, be careful to synchronize between that code (since
- * invokeLater() will make your code run from the EDT) and the Processing
- * animation thread. Use of a callback function or the registerXxx() methods
- * in PApplet can help ensure that your code doesn't do something naughty.
- *
- * As of release 0136 of Processing, we have discontinued support for versions
- * of Java prior to 1.5. We don't have enough people to support it, and for a
- * project of our size, we should be focusing on the future, rather than
- * working around legacy Java code. In addition, Java 1.5 gives us access to
- * better timing facilities which will improve the steadiness of animation.
- *
- * This class extends Applet instead of JApplet because 1) historically,
- * we supported Java 1.1, which does not include Swing (without an
- * additional, sizable, download), and 2) Swing is a bloated piece of crap.
- * A Processing applet is a heavyweight AWT component, and can be used the
- * same as any other AWT component, with or without Swing.
- *
- * Similarly, Processing runs in a Frame and not a JFrame. However, there's
- * nothing to prevent you from embedding a PApplet into a JFrame, it's just
- * that the base version uses a regular AWT frame because there's simply
- * no need for swing in that context. If people want to use Swing, they can
- * embed themselves as they wish.
- *
- * It is possible to use PApplet, along with core.jar in other projects.
- * In addition to enabling you to use Java 1.5+ features with your sketch,
- * this also allows you to embed a Processing drawing area into another Java
- * application. This means you can use standard GUI controls with a Processing
- * sketch. Because AWT and Swing GUI components cannot be used on top of a
- * PApplet, you can instead embed the PApplet inside another GUI the way you
- * would any other Component.
- *
- * It is also possible to resize the Processing window by including
- * frame.setResizable(true) inside your setup() method.
- * Note that the Java method frame.setSize() will not work unless
- * you first set the frame to be resizable.
- *
- * Because the default animation thread will run at 60 frames per second,
- * an embedded PApplet can make the parent sluggish. You can use frameRate()
- * to make it update less often, or you can use noLoop() and loop() to disable
- * and then re-enable looping. If you want to only update the sketch
- * intermittently, use noLoop() inside setup(), and redraw() whenever
- * the screen needs to be updated once (or loop() to re-enable the animation
- * thread). The following example embeds a sketch and also uses the noLoop()
- * and redraw() methods. You need not use noLoop() and redraw() when embedding
- * if you want your application to animate continuously.
- *
- * 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();
- * }
- * }
- *
- *
- *
Processing on multiple displays
- *
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().
- *
- * 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 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.
- *
Advanced:
- * If running on Mac OS, a ctrl-click will be interpreted as
- * the righthand mouse button (unlike Java, which reports it as
- * the left mouse).
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mousePressed()
- * @see PApplet#mouseReleased()
- * @see PApplet#mouseMoved()
- * @see PApplet#mouseDragged()
- */
- public int mouseButton;
-
- /**
- * Variable storing if a mouse button is pressed. The value of the system variable mousePressed is true if a mouse button is pressed and false if a button is not pressed.
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mouseReleased()
- * @see PApplet#mouseMoved()
- * @see PApplet#mouseDragged()
- */
- public boolean mousePressed;
- public MouseEvent mouseEvent;
-
- /**
- * The system variable key always contains the value of the most recent key on the keyboard that was used (either pressed or released).
- * For non-ASCII keys, use the keyCode variable.
- * 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.
- * =advanced
- *
- * Last key 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) {
- 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.
- * Do not use variables as the parameters to size() command, because it will cause problems when exporting your sketch. When variables are used, the dimensions of your sketch cannot be determined during export. Instead, employ numeric values in the size() statement, and then use the built-in width and height variables inside your program when you need the dimensions of the display window are needed.
- * The MODE parameters selects which rendering engine to use. For example, if you will be drawing 3D shapes for the web use P3D, if you want to export a program with OpenGL graphics acceleration use OPENGL. A brief description of the four primary renderers follows:
JAVA2D - The default renderer. This renderer supports two dimensional drawing and provides higher image quality in overall, but generally slower than P2D.
P2D (Processing 2D) - Fast 2D renderer, best used with pixel data, but not as accurate as the JAVA2D default.
P3D (Processing 3D) - Fast 3D renderer for the web. Sacrifices rendering quality for quick 3D drawing.
OPENGL - High speed 3D graphics renderer that makes use of OpenGL-compatible graphics hardware is available. Keep in mind that OpenGL is not magic pixie dust that makes any sketch faster (though it's close), so other rendering options may produce better results depending on the nature of your code. Also note that with OpenGL, all graphics are smoothed: the smooth() and noSmooth() commands are ignored.
PDF - The PDF renderer draws 2D graphics directly to an Acrobat PDF file. This produces excellent results when you need vector shapes for high resolution output or printing. You must first use Import Library → PDF to make use of the library. More information can be found in the PDF library reference.
- * If you're manipulating pixels (using methods like get() or blend(), or manipulating the pixels[] array), P2D and P3D will usually be faster than the default (JAVA2D) setting, and often the OPENGL setting as well. Similarly, when handling lots of images, or doing video playback, P2D and P3D will tend to be faster.
- * The P2D, P3D, and OPENGL renderers do not support strokeCap() or strokeJoin(), which can lead to ugly results when using strokeWeight(). (Bug 955)
- * For the most elegant and accurate results when drawing in 2D, particularly when using smooth(), use the JAVA2D renderer setting. It may be slower than the others, but is the most complete, which is why it's the default. Advanced users will want to switch to other renderers as they learn the tradeoffs.
- * Rendering graphics requires tradeoffs between speed, accuracy, and general usefulness of the available features. None of the renderers are perfect, so we provide multiple options so that you can decide what tradeoffs make the most sense for your project. We'd prefer all of them to have perfect visual accuracy, high performance, and support a wide range of features, but that's simply not possible.
- * The maximum width and height is limited by your operating system, and is usually the width and height of your actual screen. On some machines it may simply be the number of pixels on your current screen, meaning that a screen that's 800x600 could support size(1600, 300), since it's the same number of pixels. This varies widely so you'll have to try different rendering modes and sizes until you get what you're looking for. If you need something larger, use createGraphics to create a non-visible drawing surface.
- *
Again, the size() method must be the first line of the code (or first item inside setup). Any code that appears before the size() command may run more than once, which can lead to confusing results.
- *
- * =advanced
- * Starts up and creates a two-dimensional drawing surface,
- * or resizes the current drawing surface.
- *
- * 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.
- *
- *
Do not use "new PGraphicsXxxx()", use this method. This method
- * ensures that internal variables are set up properly that tie the
- * new graphics context back to its parent PApplet.
- *
The basic way to create bitmap images is to use the saveFrame()
- * function.
- *
If you want to create a really large scene and write that,
- * first make sure that you've allocated a lot of memory in the Preferences.
- *
If you want to create images that are larger than the screen,
- * you should create your own PGraphics object, draw to that, and use
- * save().
- * For now, it's best to use P3D in this scenario.
- * P2D is currently disabled, and the JAVA2D default will give mixed
- * results. An example of using P3D:
- *
- *
- * 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");
- * }
- *
- *
- *
It's important to always wrap drawing to createGraphics() with
- * beginDraw() and endDraw() (beginFrame() and endFrame() prior to
- * revision 0115). The reason is that the renderer needs to know when
- * drawing has stopped, so that it can update itself internally.
- * This also handles calling the defaults() method, for people familiar
- * with that.
- *
It's not possible to use createGraphics() with the OPENGL renderer,
- * because it doesn't allow offscreen use.
- *
With Processing 0115 and later, it's possible to write images in
- * formats other than the default .tga and .tiff. The exact formats and
- * background information can be found in the developer's reference for
- * PImage.save().
- *
- *
- * @webref rendering
- * @param iwidth width in pixels
- * @param iheight height in pixels
- * @param irenderer Either P2D (not yet implemented), P3D, JAVA2D, PDF, DXF
- *
- * @see processing.core.PGraphics
- *
- */
- public PGraphics createGraphics(int iwidth, int iheight,
- String irenderer) {
- PGraphics pg = makeGraphics(iwidth, iheight, irenderer, null, false);
- //pg.parent = this; // make save() work
- return pg;
- }
-
-
- /**
- * Create an offscreen graphics surface for drawing, in this case
- * for a renderer that writes to a file (such as PDF or DXF).
- * @param ipath the name of the file (can be an absolute or relative path)
- */
- public PGraphics createGraphics(int iwidth, int iheight,
- String irenderer, String ipath) {
- if (ipath != null) {
- ipath = savePath(ipath);
- }
- PGraphics pg = makeGraphics(iwidth, iheight, irenderer, ipath, false);
- pg.parent = this; // make save() work
- return pg;
- }
-
-
- /**
- * Version of createGraphics() used internally.
- *
- * @param ipath must be an absolute path, usually set via savePath()
- * @oaram applet the parent applet object, this should only be non-null
- * in cases where this is the main drawing surface object.
- */
- protected PGraphics makeGraphics(int iwidth, int iheight,
- String irenderer, String ipath,
- boolean iprimary) {
- if (irenderer.equals(OPENGL)) {
- if (PApplet.platform == WINDOWS) {
- String s = System.getProperty("java.version");
- if (s != null) {
- if (s.equals("1.5.0_10")) {
- System.err.println("OpenGL support is broken with Java 1.5.0_10");
- System.err.println("See http://dev.processing.org" +
- "/bugs/show_bug.cgi?id=513 for more info.");
- throw new RuntimeException("Please update your Java " +
- "installation (see bug #513)");
- }
- }
- }
- }
-
-// if (irenderer.equals(P2D)) {
-// throw new RuntimeException("The P2D renderer is currently disabled, " +
-// "please use P3D or JAVA2D.");
-// }
-
- String openglError =
- "Before using OpenGL, first select " +
- "Import Library > opengl from the Sketch menu.";
-
- try {
- /*
- Class> rendererClass = Class.forName(irenderer);
-
- Class> constructorParams[] = null;
- Object constructorValues[] = null;
-
- if (ipath == null) {
- constructorParams = new Class[] {
- Integer.TYPE, Integer.TYPE, PApplet.class
- };
- constructorValues = new Object[] {
- new Integer(iwidth), new Integer(iheight), this
- };
- } else {
- constructorParams = new Class[] {
- Integer.TYPE, Integer.TYPE, PApplet.class, String.class
- };
- constructorValues = new Object[] {
- new Integer(iwidth), new Integer(iheight), this, ipath
- };
- }
-
- Constructor> constructor =
- rendererClass.getConstructor(constructorParams);
- PGraphics pg = (PGraphics) constructor.newInstance(constructorValues);
- */
-
- Class> rendererClass =
- Thread.currentThread().getContextClassLoader().loadClass(irenderer);
-
- //Class> params[] = null;
- //PApplet.println(rendererClass.getConstructors());
- Constructor> constructor = rendererClass.getConstructor(new Class[] { });
- PGraphics pg = (PGraphics) constructor.newInstance();
-
- pg.setParent(this);
- pg.setPrimary(iprimary);
- if (ipath != null) pg.setPath(ipath);
- pg.setSize(iwidth, iheight);
-
- // everything worked, return it
- return pg;
-
- } catch (InvocationTargetException ite) {
- String msg = ite.getTargetException().getMessage();
- if ((msg != null) &&
- (msg.indexOf("no jogl in java.library.path") != -1)) {
- throw new RuntimeException(openglError +
- " (The native library is missing.)");
-
- } else {
- ite.getTargetException().printStackTrace();
- Throwable target = ite.getTargetException();
- if (platform == MACOSX) target.printStackTrace(System.out); // bug
- // neither of these help, or work
- //target.printStackTrace(System.err);
- //System.err.flush();
- //System.out.println(System.err); // and the object isn't null
- throw new RuntimeException(target.getMessage());
- }
-
- } catch (ClassNotFoundException cnfe) {
- if (cnfe.getMessage().indexOf("processing.opengl.PGraphicsGL") != -1) {
- throw new RuntimeException(openglError +
- " (The library .jar file is missing.)");
- } else {
- throw new RuntimeException("You need to use \"Import Library\" " +
- "to add " + irenderer + " to your sketch.");
- }
-
- } catch (Exception e) {
- //System.out.println("ex3");
- if ((e instanceof IllegalArgumentException) ||
- (e instanceof NoSuchMethodException) ||
- (e instanceof IllegalAccessException)) {
- e.printStackTrace();
- /*
- String msg = "public " +
- irenderer.substring(irenderer.lastIndexOf('.') + 1) +
- "(int width, int height, PApplet parent" +
- ((ipath == null) ? "" : ", String filename") +
- ") does not exist.";
- */
- String msg = irenderer + " needs to be updated " +
- "for the current release of Processing.";
- throw new RuntimeException(msg);
-
- } else {
- if (platform == MACOSX) e.printStackTrace(System.out);
- throw new RuntimeException(e.getMessage());
- }
- }
- }
-
-
- /**
- * Creates a new PImage (the datatype for storing images). This provides a fresh buffer of pixels to play with. Set the size of the buffer with the width and height parameters. The format parameter defines how the pixels are stored. See the PImage reference for more information.
- *
Be sure to include all three parameters, specifying only the width and height (but no format) will produce a strange error.
- *
Advanced users please note that createImage() should be used instead of the syntax new PImage().
- * =advanced
- * Preferred method of creating new PImage objects, ensures that a
- * reference to the parent PApplet is included, which makes save() work
- * without needing an absolute path.
- *
- * @webref image
- * @param wide width in pixels
- * @param high height in pixels
- * @param format Either RGB, ARGB, ALPHA (grayscale alpha channel)
- *
- * @see processing.core.PImage
- * @see processing.core.PGraphics
- */
- public PImage createImage(int wide, int high, int format) {
- PImage image = new PImage(wide, high, format);
- image.parent = this; // make save() work
- return image;
- }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- public void update(Graphics screen) {
- paint(screen);
- }
-
-
- //synchronized public void paint(Graphics screen) { // shutting off for 0146
- public void paint(Graphics screen) {
- // ignore the very first call to paint, since it's coming
- // from the o.s., and the applet will soon update itself anyway.
- if (frameCount == 0) {
-// println("Skipping frame");
- // paint() may be called more than once before things
- // are finally painted to the screen and the thread gets going
- return;
- }
-
- // without ignoring the first call, the first several frames
- // are confused because paint() gets called in the midst of
- // the initial nextFrame() call, so there are multiple
- // updates fighting with one another.
-
- // g.image is synchronized so that draw/loop and paint don't
- // try to fight over it. this was causing a randomized slowdown
- // that would cut the frameRate into a third on macosx,
- // and is probably related to the windows sluggishness bug too
-
- // make sure the screen is visible and usable
- // (also prevents over-drawing when using PGraphicsOpenGL)
- if ((g != null) && (g.image != null)) {
-// println("inside paint(), screen.drawImage()");
- screen.drawImage(g.image, 0, 0, null);
- }
- }
-
-
- // active paint method
- protected void paint() {
- try {
- Graphics screen = this.getGraphics();
- if (screen != null) {
- if ((g != null) && (g.image != null)) {
- screen.drawImage(g.image, 0, 0, null);
- }
- Toolkit.getDefaultToolkit().sync();
- }
- } catch (Exception e) {
- // Seen on applet destroy, maybe can ignore?
- e.printStackTrace();
-
-// } finally {
-// if (g != null) {
-// g.dispose();
-// }
- }
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- /**
- * Main method for the primary animation thread.
- *
- * Painting in AWT and Swing
- */
- public void run() { // not good to make this synchronized, locks things up
- long beforeTime = System.nanoTime();
- long overSleepTime = 0L;
-
- int noDelays = 0;
- // Number of frames with a delay of 0 ms before the
- // animation thread yields to other running threads.
- final int NO_DELAYS_PER_YIELD = 15;
-
- /*
- // this has to be called after the exception is thrown,
- // otherwise the supporting libs won't have a valid context to draw to
- Object methodArgs[] =
- new Object[] { new Integer(width), new Integer(height) };
- sizeMethods.handle(methodArgs);
- */
-
- while ((Thread.currentThread() == thread) && !finished) {
- // Don't resize the renderer from the EDT (i.e. from a ComponentEvent),
- // otherwise it may attempt a resize mid-render.
- if (resizeRequest) {
- resizeRenderer(resizeWidth, resizeHeight);
- resizeRequest = false;
- }
-
- // render a single frame
- handleDraw();
-
- if (frameCount == 1) {
- // Call the request focus event once the image is sure to be on
- // screen and the component is valid. The OpenGL renderer will
- // request focus for its canvas inside beginDraw().
- // http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html
- //println("requesting focus");
- requestFocus();
- }
-
- // wait for update & paint to happen before drawing next frame
- // this is necessary since the drawing is sometimes in a
- // separate thread, meaning that the next frame will start
- // before the update/paint is completed
-
- long afterTime = System.nanoTime();
- long timeDiff = afterTime - beforeTime;
- //System.out.println("time diff is " + timeDiff);
- long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime;
-
- if (sleepTime > 0) { // some time left in this cycle
- try {
-// Thread.sleep(sleepTime / 1000000L); // nanoseconds -> milliseconds
- Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L));
- noDelays = 0; // Got some sleep, not delaying anymore
- } catch (InterruptedException ex) { }
-
- overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
- //System.out.println(" oversleep is " + overSleepTime);
-
- } else { // sleepTime <= 0; the frame took longer than the period
-// excess -= sleepTime; // store excess time value
- overSleepTime = 0L;
-
- if (noDelays > NO_DELAYS_PER_YIELD) {
- Thread.yield(); // give another thread a chance to run
- noDelays = 0;
- }
- }
-
- beforeTime = System.nanoTime();
- }
-
- stop(); // call to shutdown libs?
-
- // If the user called the exit() function, the window should close,
- // rather than the sketch just halting.
- if (exitCalled) {
- exit2();
- }
- }
-
-
- //synchronized public void handleDisplay() {
- public void handleDraw() {
- if (g != null && (looping || redraw)) {
- if (!g.canDraw()) {
- // Don't draw if the renderer is not yet ready.
- // (e.g. OpenGL has to wait for a peer to be on screen)
- return;
- }
-
- //System.out.println("handleDraw() " + frameCount);
-
- g.beginDraw();
- if (recorder != null) {
- recorder.beginDraw();
- }
-
- long now = System.nanoTime();
-
- if (frameCount == 0) {
- try {
- //println("Calling setup()");
- setup();
- //println("Done with setup()");
-
- } catch (RendererChangeException e) {
- // Give up, instead set the new renderer and re-attempt setup()
- return;
- }
- this.defaultSize = false;
-
- } else { // frameCount > 0, meaning an actual draw()
- // update the current frameRate
- double rate = 1000000.0 / ((now - frameRateLastNanos) / 1000000.0);
- float instantaneousRate = (float) rate / 1000.0f;
- frameRate = (frameRate * 0.9f) + (instantaneousRate * 0.1f);
-
- preMethods.handle();
-
- // use dmouseX/Y as previous mouse pos, since this is the
- // last position the mouse was in during the previous draw.
- pmouseX = dmouseX;
- pmouseY = dmouseY;
-
- //println("Calling draw()");
- draw();
- //println("Done calling draw()");
-
- // dmouseX/Y is updated only once per frame (unlike emouseX/Y)
- dmouseX = mouseX;
- dmouseY = mouseY;
-
- // these are called *after* loop so that valid
- // drawing commands can be run inside them. it can't
- // be before, since a call to background() would wipe
- // out anything that had been drawn so far.
- dequeueMouseEvents();
- dequeueKeyEvents();
-
- drawMethods.handle();
-
- redraw = false; // unset 'redraw' flag in case it was set
- // (only do this once draw() has run, not just setup())
-
- }
-
- g.endDraw();
- if (recorder != null) {
- recorder.endDraw();
- }
-
- frameRateLastNanos = now;
- frameCount++;
-
- // Actively render the screen
- paint();
-
-// repaint();
-// getToolkit().sync(); // force repaint now (proper method)
-
- postMethods.handle();
- }
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
-
- synchronized public void redraw() {
- if (!looping) {
- redraw = true;
-// if (thread != null) {
-// // wake from sleep (necessary otherwise it'll be
-// // up to 10 seconds before update)
-// if (CRUSTY_THREADS) {
-// thread.interrupt();
-// } else {
-// synchronized (blocker) {
-// blocker.notifyAll();
-// }
-// }
-// }
- }
- }
-
-
- synchronized public void loop() {
- if (!looping) {
- looping = true;
- }
- }
-
-
- synchronized public void noLoop() {
- if (looping) {
- looping = false;
- }
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- public void addListeners() {
- addMouseListener(this);
- addMouseMotionListener(this);
- addKeyListener(this);
- addFocusListener(this);
-
- addComponentListener(new ComponentAdapter() {
- public void componentResized(ComponentEvent e) {
- Component c = e.getComponent();
- //System.out.println("componentResized() " + c);
- Rectangle bounds = c.getBounds();
- resizeRequest = true;
- resizeWidth = bounds.width;
- resizeHeight = bounds.height;
- }
- });
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- MouseEvent mouseEventQueue[] = new MouseEvent[10];
- int mouseEventCount;
-
- protected void enqueueMouseEvent(MouseEvent e) {
- synchronized (mouseEventQueue) {
- if (mouseEventCount == mouseEventQueue.length) {
- MouseEvent temp[] = new MouseEvent[mouseEventCount << 1];
- System.arraycopy(mouseEventQueue, 0, temp, 0, mouseEventCount);
- mouseEventQueue = temp;
- }
- mouseEventQueue[mouseEventCount++] = e;
- }
- }
-
- protected void dequeueMouseEvents() {
- synchronized (mouseEventQueue) {
- for (int i = 0; i < mouseEventCount; i++) {
- mouseEvent = mouseEventQueue[i];
- handleMouseEvent(mouseEvent);
- }
- mouseEventCount = 0;
- }
- }
-
-
- /**
- * Actually take action based on a mouse event.
- * Internally updates mouseX, mouseY, mousePressed, and mouseEvent.
- * Then it calls the event type with no params,
- * i.e. mousePressed() or mouseReleased() that the user may have
- * overloaded to do something more useful.
- */
- protected void handleMouseEvent(MouseEvent event) {
- int id = event.getID();
-
- // http://dev.processing.org/bugs/show_bug.cgi?id=170
- // also prevents mouseExited() on the mac from hosing the mouse
- // position, because x/y are bizarre values on the exit event.
- // see also the id check below.. both of these go together
- if ((id == MouseEvent.MOUSE_DRAGGED) ||
- (id == MouseEvent.MOUSE_MOVED)) {
- pmouseX = emouseX;
- pmouseY = emouseY;
- mouseX = event.getX();
- mouseY = event.getY();
- }
-
- mouseEvent = event;
-
- int modifiers = event.getModifiers();
- if ((modifiers & InputEvent.BUTTON1_MASK) != 0) {
- mouseButton = LEFT;
- } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
- mouseButton = CENTER;
- } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
- mouseButton = RIGHT;
- }
- // if running on macos, allow ctrl-click as right mouse
- if (platform == MACOSX) {
- if (mouseEvent.isPopupTrigger()) {
- mouseButton = RIGHT;
- }
- }
-
- mouseEventMethods.handle(new Object[] { event });
-
- // this used to only be called on mouseMoved and mouseDragged
- // change it back if people run into trouble
- if (firstMouse) {
- pmouseX = mouseX;
- pmouseY = mouseY;
- dmouseX = mouseX;
- dmouseY = mouseY;
- firstMouse = false;
- }
-
- //println(event);
-
- switch (id) {
- case MouseEvent.MOUSE_PRESSED:
- mousePressed = true;
- mousePressed();
- break;
- case MouseEvent.MOUSE_RELEASED:
- mousePressed = false;
- mouseReleased();
- break;
- case MouseEvent.MOUSE_CLICKED:
- mouseClicked();
- break;
- case MouseEvent.MOUSE_DRAGGED:
- mouseDragged();
- break;
- case MouseEvent.MOUSE_MOVED:
- mouseMoved();
- break;
- }
-
- if ((id == MouseEvent.MOUSE_DRAGGED) ||
- (id == MouseEvent.MOUSE_MOVED)) {
- emouseX = mouseX;
- emouseY = mouseY;
- }
- }
-
-
- /**
- * Figure out how to process a mouse event. When loop() has been
- * called, the events will be queued up until drawing is complete.
- * If noLoop() has been called, then events will happen immediately.
- */
- protected void checkMouseEvent(MouseEvent event) {
- if (looping) {
- enqueueMouseEvent(event);
- } else {
- handleMouseEvent(event);
- }
- }
-
-
- /**
- * If you override this or any function that takes a "MouseEvent e"
- * without calling its super.mouseXxxx() then mouseX, mouseY,
- * mousePressed, and mouseEvent will no longer be set.
- */
- public void mousePressed(MouseEvent e) {
- checkMouseEvent(e);
- }
-
- public void mouseReleased(MouseEvent e) {
- checkMouseEvent(e);
- }
-
- public void mouseClicked(MouseEvent e) {
- checkMouseEvent(e);
- }
-
- public void mouseEntered(MouseEvent e) {
- checkMouseEvent(e);
- }
-
- public void mouseExited(MouseEvent e) {
- checkMouseEvent(e);
- }
-
- public void mouseDragged(MouseEvent e) {
- checkMouseEvent(e);
- }
-
- public void mouseMoved(MouseEvent e) {
- checkMouseEvent(e);
- }
-
-
- /**
- * The mousePressed() function is called once after every time a mouse button is pressed. The mouseButton variable (see the related reference entry) can be used to determine which button has been pressed.
- * =advanced
- *
- * If you must, use
- * int button = mouseEvent.getButton();
- * to figure out which button was clicked. It will be one of:
- * MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3
- * Note, however, that this is completely inconsistent across
- * platforms.
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mousePressed
- * @see PApplet#mouseReleased()
- * @see PApplet#mouseMoved()
- * @see PApplet#mouseDragged()
- */
- public void mousePressed() { }
-
- /**
- * The mouseReleased() function is called every time a mouse button is released.
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mousePressed
- * @see PApplet#mousePressed()
- * @see PApplet#mouseMoved()
- * @see PApplet#mouseDragged()
- */
- public void mouseReleased() { }
-
- /**
- * The mouseClicked() function is called once after a mouse button has been pressed and then released.
- * =advanced
- * When the mouse is clicked, mousePressed() will be called,
- * then mouseReleased(), then mouseClicked(). Note that
- * mousePressed is already false inside of mouseClicked().
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mouseButton
- * @see PApplet#mousePressed()
- * @see PApplet#mouseReleased()
- * @see PApplet#mouseMoved()
- * @see PApplet#mouseDragged()
- */
- public void mouseClicked() { }
-
- /**
- * The mouseDragged() function is called once every time the mouse moves and a mouse button is pressed.
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mousePressed
- * @see PApplet#mousePressed()
- * @see PApplet#mouseReleased()
- * @see PApplet#mouseMoved()
- */
- public void mouseDragged() { }
-
- /**
- * The mouseMoved() function is called every time the mouse moves and a mouse button is not pressed.
- * @webref input:mouse
- * @see PApplet#mouseX
- * @see PApplet#mouseY
- * @see PApplet#mousePressed
- * @see PApplet#mousePressed()
- * @see PApplet#mouseReleased()
- * @see PApplet#mouseDragged()
- */
- public void mouseMoved() { }
-
-
- //////////////////////////////////////////////////////////////
-
-
- KeyEvent keyEventQueue[] = new KeyEvent[10];
- int keyEventCount;
-
- protected void enqueueKeyEvent(KeyEvent e) {
- synchronized (keyEventQueue) {
- if (keyEventCount == keyEventQueue.length) {
- KeyEvent temp[] = new KeyEvent[keyEventCount << 1];
- System.arraycopy(keyEventQueue, 0, temp, 0, keyEventCount);
- keyEventQueue = temp;
- }
- keyEventQueue[keyEventCount++] = e;
- }
- }
-
- protected void dequeueKeyEvents() {
- synchronized (keyEventQueue) {
- for (int i = 0; i < keyEventCount; i++) {
- keyEvent = keyEventQueue[i];
- handleKeyEvent(keyEvent);
- }
- keyEventCount = 0;
- }
- }
-
-
- protected void handleKeyEvent(KeyEvent event) {
- keyEvent = event;
- key = event.getKeyChar();
- keyCode = event.getKeyCode();
-
- keyEventMethods.handle(new Object[] { event });
-
- switch (event.getID()) {
- case KeyEvent.KEY_PRESSED:
- keyPressed = true;
- keyPressed();
- break;
- case KeyEvent.KEY_RELEASED:
- keyPressed = false;
- keyReleased();
- break;
- case KeyEvent.KEY_TYPED:
- keyTyped();
- break;
- }
-
- // if someone else wants to intercept the key, they should
- // set key to zero (or something besides the ESC).
- if (event.getID() == KeyEvent.KEY_PRESSED) {
- if (key == KeyEvent.VK_ESCAPE) {
- exit();
- }
- // When running tethered to the Processing application, respond to
- // Ctrl-W (or Cmd-W) events by closing the sketch. Disable this behavior
- // when running independently, because this sketch may be one component
- // embedded inside an application that has its own close behavior.
- if (external &&
- event.getModifiers() == MENU_SHORTCUT &&
- event.getKeyCode() == 'W') {
- exit();
- }
- }
- }
-
-
- protected void checkKeyEvent(KeyEvent event) {
- if (looping) {
- enqueueKeyEvent(event);
- } else {
- handleKeyEvent(event);
- }
- }
-
-
- /**
- * Overriding keyXxxxx(KeyEvent e) functions will cause the 'key',
- * 'keyCode', and 'keyEvent' variables to no longer work;
- * key events will no longer be queued until the end of draw();
- * and the keyPressed(), keyReleased() and keyTyped() methods
- * will no longer be called.
- */
- public void keyPressed(KeyEvent e) { checkKeyEvent(e); }
- public void keyReleased(KeyEvent e) { checkKeyEvent(e); }
- public void keyTyped(KeyEvent e) { checkKeyEvent(e); }
-
-
- /**
- *
- * The keyPressed() function is called once every time a key is pressed. The key that was pressed is stored in the key variable.
- *
For non-ASCII keys, use the keyCode variable.
- * 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.
Because of how operating systems handle key repeats, holding down a key may cause multiple calls to keyPressed() (and keyReleased() as well).
- * The rate of repeat is set by the operating system and how each computer is configured.
- * =advanced
- *
- * Called each time a single key on the keyboard is pressed.
- * Because of how operating systems handle key repeats, holding
- * down a key will cause multiple calls to keyPressed(), because
- * the OS repeat takes over.
- *
- * 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).
- *
- * The args parameter is a String or String array which is passed to the command line. If you have multiple parameters, e.g. an application and a document, or a command with multiple switches, use the version that takes a String array, and place each individual item in a separate element.
- *
- * If args is a String (not an array), then it can only be a single file or application with no parameters. It's not the same as executing that String using a shell. For instance, open("jikes -help") will not work properly.
- *
- * This function behaves differently on each platform. On Windows, the parameters are sent to the Windows shell via "cmd /c". On Mac OS X, the "open" command is used (type "man open" in Terminal.app for documentation). On Linux, it first tries gnome-open, then kde-open, but if neither are available, it sends the command to the shell without any alterations.
- *
- * For users familiar with Java, this is not quite the same as Runtime.exec(), because the launcher command is prepended. Instead, the exec(String[]) function is a shortcut for Runtime.getRuntime.exec(String[]).
- *
- * @webref input:files
- * @param filename name of the file
- * @usage Application
- */
- static public void open(String filename) {
- open(new String[] { filename });
- }
-
-
- static String openLauncher;
-
- /**
- * Launch a process using a platforms shell. This version uses an array
- * to make it easier to deal with spaces in the individual elements.
- * (This avoids the situation of trying to put single or double quotes
- * around different bits).
- *
- * @param list of commands passed to the command line
- */
- static public Process open(String argv[]) {
- String[] params = null;
-
- if (platform == WINDOWS) {
- // just launching the .html file via the shell works
- // but make sure to chmod +x the .html files first
- // also place quotes around it in case there's a space
- // in the user.dir part of the url
- params = new String[] { "cmd", "/c" };
-
- } else if (platform == MACOSX) {
- params = new String[] { "open" };
-
- } else if (platform == LINUX) {
- if (openLauncher == null) {
- // Attempt to use gnome-open
- try {
- Process p = Runtime.getRuntime().exec(new String[] { "gnome-open" });
- /*int result =*/ p.waitFor();
- // Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04)
- openLauncher = "gnome-open";
- } catch (Exception e) { }
- }
- if (openLauncher == null) {
- // Attempt with kde-open
- try {
- Process p = Runtime.getRuntime().exec(new String[] { "kde-open" });
- /*int result =*/ p.waitFor();
- openLauncher = "kde-open";
- } catch (Exception e) { }
- }
- if (openLauncher == null) {
- System.err.println("Could not find gnome-open or kde-open, " +
- "the open() command may not work.");
- }
- if (openLauncher != null) {
- params = new String[] { openLauncher };
- }
- //} else { // give up and just pass it to Runtime.exec()
- //open(new String[] { filename });
- //params = new String[] { filename };
- }
- if (params != null) {
- // If the 'open', 'gnome-open' or 'cmd' are already included
- if (params[0].equals(argv[0])) {
- // then don't prepend those params again
- return exec(argv);
- } else {
- params = concat(params, argv);
- return exec(params);
- }
- } else {
- return exec(argv);
- }
- }
-
-
- static public Process exec(String[] argv) {
- try {
- return Runtime.getRuntime().exec(argv);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("Could not open " + join(argv, ' '));
- }
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- /**
- * Function for an applet/application to kill itself and
- * display an error. Mostly this is here to be improved later.
- */
- public void die(String what) {
- stop();
- throw new RuntimeException(what);
- }
-
-
- /**
- * Same as above but with an exception. Also needs work.
- */
- public void die(String what, Exception e) {
- if (e != null) e.printStackTrace();
- die(what);
- }
-
-
- /**
- * Call to safely exit the sketch when finished. For instance,
- * to render a single frame, save it, and quit.
- */
- public void exit() {
- if (thread == null) {
- // exit immediately, stop() has already been called,
- // meaning that the main thread has long since exited
- exit2();
-
- } else if (looping) {
- // stop() will be called as the thread exits
- finished = true;
- // tell the code to call exit2() to do a System.exit()
- // once the next draw() has completed
- exitCalled = true;
-
- } else if (!looping) {
- // if not looping, need to call stop explicitly,
- // because the main thread will be sleeping
- stop();
-
- // now get out
- exit2();
- }
- }
-
-
- void exit2() {
- try {
- System.exit(0);
- } catch (SecurityException e) {
- // don't care about applet security exceptions
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
-
- public void method(String name) {
-// final Object o = this;
-// final Class> c = getClass();
- try {
- Method method = getClass().getMethod(name, new Class[] {});
- method.invoke(this, new Object[] { });
-
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.getTargetException().printStackTrace();
- } catch (NoSuchMethodException nsme) {
- System.err.println("There is no public " + name + "() method " +
- "in the class " + getClass().getName());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
- public void thread(final String name) {
- Thread later = new Thread() {
- public void run() {
- method(name);
- }
- };
- later.start();
- }
-
-
- /*
- public void thread(String name) {
- final Object o = this;
- final Class> c = getClass();
- try {
- final Method method = c.getMethod(name, new Class[] {});
- Thread later = new Thread() {
- public void run() {
- try {
- method.invoke(o, new Object[] { });
-
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.getTargetException().printStackTrace();
- }
- }
- };
- later.start();
-
- } catch (NoSuchMethodException nsme) {
- System.err.println("There is no " + name + "() method " +
- "in the class " + getClass().getName());
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- */
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SCREEN GRABASS
-
-
- /**
- * Intercepts any relative paths to make them absolute (relative
- * to the sketch folder) before passing to save() in PImage.
- * (Changed in 0100)
- */
- public void save(String filename) {
- g.save(savePath(filename));
- }
-
-
- /**
- * Grab an image of what's currently in the drawing area and save it
- * as a .tif or .tga file.
- *
- * 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<>= 1;
- }
-
- if (x<0) x=-x;
- if (y<0) y=-y;
- if (z<0) z=-z;
-
- int xi=(int)x, yi=(int)y, zi=(int)z;
- float xf = (float)(x-xi);
- float yf = (float)(y-yi);
- float zf = (float)(z-zi);
- float rxf, ryf;
-
- float r=0;
- float ampl=0.5f;
-
- float n1,n2,n3;
-
- for (int i=0; i=1.0f) { xi++; xf--; }
- if (yf>=1.0f) { yi++; yf--; }
- if (zf>=1.0f) { zi++; zf--; }
- }
- return r;
- }
-
- // [toxi 031112]
- // now adjusts to the size of the cosLUT used via
- // the new variables, defined above
- private float noise_fsc(float i) {
- // using bagel's cosine table instead
- return 0.5f*(1.0f-perlin_cosTable[(int)(i*perlin_PI)%perlin_TWOPI]);
- }
-
- // [toxi 040903]
- // make perlin noise quality user controlled to allow
- // for different levels of detail. lower values will produce
- // smoother results as higher octaves are surpressed
-
- public void noiseDetail(int lod) {
- if (lod>0) perlin_octaves=lod;
- }
-
- public void noiseDetail(int lod, float falloff) {
- if (lod>0) perlin_octaves=lod;
- if (falloff>0) perlin_amp_falloff=falloff;
- }
-
- public void noiseSeed(long what) {
- if (perlinRandom == null) perlinRandom = new Random();
- perlinRandom.setSeed(what);
- // force table reset after changing the random number seed [0122]
- perlin = null;
- }
-
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- protected String[] loadImageFormats;
-
-
- /**
- * Load an image from the data folder or a local directory.
- * Supports .gif (including transparency), .tga, and .jpg images.
- * In Java 1.3 or later, .png images are
- *
- * also supported.
- *
- * 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:
- *
- *
TGA and TIFF images are loaded using the internal load methods.
- *
JPG, GIF, and PNG images are loaded via loadBytes().
- *
If the image still isn't loaded, it's passed to javax.imageio.
- *
- * 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.
- *
- * 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.
- *
- * 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);
- }
- 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.
- *
- * Many .otf fonts don't seem to be supported by Java, perhaps because
- * they're CFF based?
- *
- * Font names are inconsistent across platforms and Java versions.
- * On Mac OS X, Java 1.3 uses the font menu name of the font,
- * whereas Java 1.4 uses the PostScript name of the font. Java 1.4
- * on OS X will also accept the font menu name as well. On Windows,
- * it appears that only the menu names are used, no matter what
- * Java version is in use. Naming system unknown/untested for 1.5.
- *
- * Use 'null' for the charset if you want to dynamically create
- * character bitmaps only as they're needed. (Version 1.0.9 and
- * earlier would interpret null as all unicode characters.)
- */
- public PFont createFont(String name, float size,
- boolean smooth, char charset[]) {
- String lowerName = name.toLowerCase();
- Font baseFont = null;
-
- try {
- InputStream stream = null;
- if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) {
- stream = createInput(name);
- if (stream == null) {
- System.err.println("The font \"" + name + "\" " +
- "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;
- }
- baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name));
-
- } else {
- baseFont = PFont.findFont(name);
- }
- return new PFont(baseFont.deriveFont(size), smooth, charset,
- stream != null);
-
- } catch (Exception e) {
- System.err.println("Problem createFont(" + name + ")");
- e.printStackTrace();
- return null;
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // FILE/FOLDER SELECTION
-
-
- public File selectedFile;
- protected Frame parentFrame;
-
-
- protected void checkParentFrame() {
- if (parentFrame == null) {
- Component comp = getParent();
- while (comp != null) {
- if (comp instanceof Frame) {
- parentFrame = (Frame) comp;
- break;
- }
- comp = comp.getParent();
- }
- // Who you callin' a hack?
- if (parentFrame == null) {
- parentFrame = new Frame();
- }
- }
- }
-
-
- /**
- * Open a platform-specific file chooser dialog to select a file for input.
- * @return full path to the selected file, or null if no selection.
- */
- public String selectInput() {
- return selectInput("Select a file...");
- }
-
-
- /**
- * Opens a platform-specific file chooser dialog to select a file for input. This function returns the full path to the selected file as a String, or null if no selection.
- *
- * @webref input:files
- * @param prompt message you want the user to see in the file chooser
- * @return full path to the selected file, or null if canceled.
- *
- * @see processing.core.PApplet#selectOutput(String)
- * @see processing.core.PApplet#selectFolder(String)
- */
- public String selectInput(String prompt) {
- return selectFileImpl(prompt, FileDialog.LOAD);
- }
-
-
- /**
- * Open a platform-specific file save dialog to select a file for output.
- * @return full path to the file entered, or null if canceled.
- */
- public String selectOutput() {
- return selectOutput("Save as...");
- }
-
-
- /**
- * Open a platform-specific file save dialog to create of select a file for output.
- * This function returns the full path to the selected file as a String, or null if no selection.
- * If you select an existing file, that file will be replaced.
- * Alternatively, you can navigate to a folder and create a new file to write to.
- *
- * @param prompt message you want the user to see in the file chooser
- * @return full path to the file entered, or null if canceled.
- *
- * @webref input:files
- * @see processing.core.PApplet#selectInput(String)
- * @see processing.core.PApplet#selectFolder(String)
- */
- public String selectOutput(String prompt) {
- return selectFileImpl(prompt, FileDialog.SAVE);
- }
-
-
- protected String selectFileImpl(final String prompt, final int mode) {
- checkParentFrame();
-
- try {
- SwingUtilities.invokeAndWait(new Runnable() {
- public void run() {
- FileDialog fileDialog =
- new FileDialog(parentFrame, prompt, mode);
- fileDialog.setVisible(true);
- String directory = fileDialog.getDirectory();
- String filename = fileDialog.getFile();
- selectedFile =
- (filename == null) ? null : new File(directory, filename);
- }
- });
- return (selectedFile == null) ? null : selectedFile.getAbsolutePath();
-
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
-
- public String selectFolder() {
- return selectFolder("Select a folder...");
- }
-
-
- /**
- * Opens a platform-specific file chooser dialog to select a folder for input.
- * This function returns the full path to the selected folder as a String, or null if no selection.
- *
- * @webref input:files
- * @param prompt message you want the user to see in the file chooser
- * @return full path to the selected folder, or null if no selection.
- *
- * @see processing.core.PApplet#selectOutput(String)
- * @see processing.core.PApplet#selectInput(String)
- */
- public String selectFolder(final String prompt) {
- checkParentFrame();
-
- try {
- SwingUtilities.invokeAndWait(new Runnable() {
- public void run() {
- if (platform == MACOSX) {
- FileDialog fileDialog =
- new FileDialog(parentFrame, prompt, FileDialog.LOAD);
- System.setProperty("apple.awt.fileDialogForDirectories", "true");
- fileDialog.setVisible(true);
- System.setProperty("apple.awt.fileDialogForDirectories", "false");
- String filename = fileDialog.getFile();
- selectedFile = (filename == null) ? null :
- new File(fileDialog.getDirectory(), fileDialog.getFile());
- } else {
- JFileChooser fileChooser = new JFileChooser();
- fileChooser.setDialogTitle(prompt);
- fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
-
- int returned = fileChooser.showOpenDialog(parentFrame);
- System.out.println(returned);
- if (returned == JFileChooser.CANCEL_OPTION) {
- selectedFile = null;
- } else {
- selectedFile = fileChooser.getSelectedFile();
- }
- }
- }
- });
- return (selectedFile == null) ? null : selectedFile.getAbsolutePath();
-
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // READERS AND WRITERS
-
-
- /**
- * I want to read lines from a file. I have RSI from typing these
- * eight lines of code so many times.
- */
- public BufferedReader createReader(String filename) {
- try {
- InputStream is = createInput(filename);
- if (is == null) {
- System.err.println(filename + " does not exist or could not be read");
- return null;
- }
- return createReader(is);
-
- } catch (Exception e) {
- if (filename == null) {
- System.err.println("Filename passed to reader() was null");
- } else {
- System.err.println("Couldn't create a reader for " + filename);
- }
- }
- return null;
- }
-
-
- /**
- * I want to read lines from a file. And I'm still annoyed.
- */
- static public BufferedReader createReader(File file) {
- try {
- InputStream is = new FileInputStream(file);
- if (file.getName().toLowerCase().endsWith(".gz")) {
- is = new GZIPInputStream(is);
- }
- return createReader(is);
-
- } catch (Exception e) {
- if (file == null) {
- throw new RuntimeException("File passed to createReader() was null");
- } else {
- e.printStackTrace();
- throw new RuntimeException("Couldn't create a reader for " +
- file.getAbsolutePath());
- }
- }
- //return null;
- }
-
-
- /**
- * I want to read lines from a stream. If I have to type the
- * following lines any more I'm gonna send Sun my medical bills.
- */
- static public BufferedReader createReader(InputStream input) {
- InputStreamReader isr = null;
- try {
- isr = new InputStreamReader(input, "UTF-8");
- } catch (UnsupportedEncodingException e) { } // not gonna happen
- return new BufferedReader(isr);
- }
-
-
- /**
- * I want to print lines to a file. Why can't I?
- */
- public PrintWriter createWriter(String filename) {
- return createWriter(saveFile(filename));
- }
-
-
- /**
- * I want to print lines to a file. I have RSI from typing these
- * eight lines of code so many times.
- */
- static public PrintWriter createWriter(File file) {
- try {
- createPath(file); // make sure in-between folders exist
- OutputStream output = new FileOutputStream(file);
- if (file.getName().toLowerCase().endsWith(".gz")) {
- output = new GZIPOutputStream(output);
- }
- return createWriter(output);
-
- } catch (Exception e) {
- if (file == null) {
- throw new RuntimeException("File passed to createWriter() was null");
- } else {
- e.printStackTrace();
- throw new RuntimeException("Couldn't create a writer for " +
- file.getAbsolutePath());
- }
- }
- //return null;
- }
-
-
- /**
- * I want to print lines to a file. Why am I always explaining myself?
- * It's the JavaSoft API engineers who need to explain themselves.
- */
- static public PrintWriter createWriter(OutputStream output) {
- try {
- OutputStreamWriter osw = new OutputStreamWriter(output, "UTF-8");
- return new PrintWriter(osw);
- } catch (UnsupportedEncodingException e) { } // not gonna happen
- return null;
- }
-
-
- //////////////////////////////////////////////////////////////
-
- // FILE INPUT
-
-
- /**
- * @deprecated As of release 0136, use createInput() instead.
- */
- public InputStream openStream(String filename) {
- return createInput(filename);
- }
-
-
- /**
- * This is a method for advanced programmers to open a Java InputStream. The method is useful if you want to use the facilities provided by PApplet to easily open files 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.
- *
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.
- *
- * 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:
- *
- *
A URL, for instance openStream("http://processing.org/");
- *
A file in the sketch's data folder
- *
Another file to be opened locally (when running as an application)
- *
- *
- * @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;
- }
- }
-
- 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.
- *
- * 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.
- *
- * If the path does not exist, intermediate folders will be created. If an
- * exception occurs, it will be printed to the console, and null will be
- * returned.
- *
- * Future releases may also add support for handling HTTP POST via this
- * method (for better symmetry with createInput), however that's maybe a
- * little too clever (and then we'd have to add the same features to the
- * other file functions like createWriter). Who you callin' bloated?
- */
- public OutputStream createOutput(String filename) {
- return createOutput(saveFile(filename));
- }
-
-
- static public OutputStream createOutput(File file) {
- try {
- createPath(file); // make sure the path exists
- FileOutputStream fos = new FileOutputStream(file);
- if (file.getName().toLowerCase().endsWith(".gz")) {
- return new GZIPOutputStream(fos);
- }
- return fos;
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
-
- /**
- * Save the contents of a stream to a file in the sketch folder.
- * This is basically saveBytes(blah, loadBytes()), but done
- * more efficiently (and with less confusing syntax).
- */
- public void saveStream(String targetFilename, String sourceLocation) {
- saveStream(saveFile(targetFilename), sourceLocation);
- }
-
-
- /**
- * Identical to the other saveStream(), but writes to a File
- * object, for greater control over the file location.
- * Note that unlike other api methods, this will not automatically
- * compress or uncompress gzip files.
- */
- public void saveStream(File targetFile, String sourceLocation) {
- saveStream(targetFile, createInputRaw(sourceLocation));
- }
-
-
- static public void saveStream(File targetFile, InputStream sourceStream) {
- File tempFile = null;
- try {
- File parentDir = targetFile.getParentFile();
- tempFile = File.createTempFile(targetFile.getName(), null, parentDir);
-
- BufferedInputStream bis = new BufferedInputStream(sourceStream, 16384);
- FileOutputStream fos = new FileOutputStream(tempFile);
- BufferedOutputStream bos = new BufferedOutputStream(fos);
-
- byte[] buffer = new byte[8192];
- int bytesRead;
- while ((bytesRead = bis.read(buffer)) != -1) {
- bos.write(buffer, 0, bytesRead);
- }
-
- bos.flush();
- bos.close();
- bos = null;
-
- if (!tempFile.renameTo(targetFile)) {
- System.err.println("Could not rename temporary file " +
- tempFile.getAbsolutePath());
- }
- } catch (IOException e) {
- if (tempFile != null) {
- tempFile.delete();
- }
- e.printStackTrace();
- }
- }
-
-
- /**
- * Saves bytes to a file to inside the sketch folder.
- * The filename can be a relative path, i.e. "poo/bytefun.txt"
- * would save to a file named "bytefun.txt" to a subfolder
- * called 'poo' inside the sketch folder. If the in-between
- * subfolders don't exist, they'll be created.
- */
- public void saveBytes(String filename, byte buffer[]) {
- saveBytes(saveFile(filename), buffer);
- }
-
-
- /**
- * Saves bytes to a specific File location specified by the user.
- */
- static public void saveBytes(File file, byte buffer[]) {
- File tempFile = null;
- try {
- File parentDir = file.getParentFile();
- tempFile = File.createTempFile(file.getName(), null, parentDir);
-
- /*
- String filename = file.getAbsolutePath();
- createPath(filename);
- OutputStream output = new FileOutputStream(file);
- if (file.getName().toLowerCase().endsWith(".gz")) {
- output = new GZIPOutputStream(output);
- }
- */
- OutputStream output = createOutput(tempFile);
- saveBytes(output, buffer);
- output.close();
- output = null;
-
- if (!tempFile.renameTo(file)) {
- System.err.println("Could not rename temporary file " +
- tempFile.getAbsolutePath());
- }
-
- } catch (IOException e) {
- System.err.println("error saving bytes to " + file);
- if (tempFile != null) {
- tempFile.delete();
- }
- e.printStackTrace();
- }
- }
-
-
- /**
- * Spews a buffer of bytes to an OutputStream.
- */
- static public void saveBytes(OutputStream output, byte buffer[]) {
- try {
- output.write(buffer);
- output.flush();
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- //
-
- public void saveStrings(String filename, String strings[]) {
- saveStrings(saveFile(filename), strings);
- }
-
-
- static public void saveStrings(File file, String strings[]) {
- saveStrings(createOutput(file), strings);
- /*
- try {
- String location = file.getAbsolutePath();
- createPath(location);
- OutputStream output = new FileOutputStream(location);
- if (file.getName().toLowerCase().endsWith(".gz")) {
- output = new GZIPOutputStream(output);
- }
- saveStrings(output, strings);
- output.close();
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- */
- }
-
-
- static public void saveStrings(OutputStream output, String strings[]) {
- PrintWriter writer = createWriter(output);
- for (int i = 0; i < strings.length; i++) {
- writer.println(strings[i]);
- }
- writer.flush();
- writer.close();
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- /**
- * Prepend the sketch folder path to the filename (or path) that is
- * passed in. External libraries should use this function to save to
- * the sketch folder.
- *
- * Note that when running as an applet inside a web browser,
- * the sketchPath will be set to null, because security restrictions
- * prevent applets from accessing that information.
- *
- * This will also cause an error if the sketch is not inited properly,
- * meaning that init() was never called on the PApplet when hosted
- * my some other main() or by other code. For proper use of init(),
- * see the examples in the main description text for PApplet.
- */
- public String sketchPath(String where) {
- if (sketchPath == null) {
- return where;
-// throw new RuntimeException("The applet was not inited properly, " +
-// "or security restrictions prevented " +
-// "it from determining its path.");
- }
- // isAbsolute() could throw an access exception, but so will writing
- // to the local disk using the sketch path, so this is safe here.
- // for 0120, added a try/catch anyways.
- try {
- if (new File(where).isAbsolute()) return where;
- } catch (Exception e) { }
-
- return sketchPath + File.separator + where;
- }
-
-
- public File sketchFile(String where) {
- return new File(sketchPath(where));
- }
-
-
- /**
- * Returns a path inside the applet folder to save to. Like sketchPath(),
- * but creates any in-between folders so that things save properly.
- *
- * All saveXxxx() functions use the path to the sketch folder, rather than
- * its data folder. Once exported, the data folder will be found inside the
- * jar file of the exported application or applet. In this case, it's not
- * possible to save data into the jar file, because it will often be running
- * from a server, or marked in-use if running from a local file system.
- * With this in mind, saving to the data path doesn't make sense anyway.
- * If you know you're running locally, and want to save to the data folder,
- * use saveXxxx("data/blah.dat").
- */
- public String savePath(String where) {
- if (where == null) return null;
- String filename = sketchPath(where);
- createPath(filename);
- return filename;
- }
-
-
- /**
- * Identical to savePath(), but returns a File object.
- */
- public File saveFile(String where) {
- return new File(savePath(where));
- }
-
-
- /**
- * Return a full path to an item in the data folder.
- *
- * 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 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.
- *
- * 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.
- *
- * 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.
- *
- * 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).
- *
- */
- 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.
- *
- */
- 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.
- *
- * 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 items = new ArrayList();
- int index;
- int offset = 0;
- while ((index = what.indexOf(delim, offset)) != -1) {
- items.add(what.substring(offset, index));
- offset = index + delim.length();
- }
- items.add(what.substring(offset));
- String[] outgoing = new String[items.size()];
- items.toArray(outgoing);
- return outgoing;
- }
-
-
- /**
- * Match a string with a regular expression, and returns the match as an
- * array. The first index is the matching expression, and array elements
- * [1] and higher represent each of the groups (sequences found in parens).
- *
- * This uses multiline matching (Pattern.MULTILINE) and dotall mode
- * (Pattern.DOTALL) by default, so that ^ and $ match the beginning and
- * end of any lines found in the source, and the . operator will also
- * pick up newline characters.
- */
- static public String[] match(String what, String regexp) {
- Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
- Matcher m = p.matcher(what);
- if (m.find()) {
- int count = m.groupCount() + 1;
- String[] groups = new String[count];
- for (int i = 0; i < count; i++) {
- groups[i] = m.group(i);
- }
- return groups;
- }
- return null;
- }
-
-
- /**
- * Identical to match(), except that it returns an array of all matches in
- * the specified String, rather than just the first.
- */
- static public String[][] matchAll(String what, String regexp) {
- Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
- Matcher m = p.matcher(what);
- ArrayList results = new ArrayList();
- int count = m.groupCount() + 1;
- while (m.find()) {
- String[] groups = new String[count];
- for (int i = 0; i < count; i++) {
- groups[i] = m.group(i);
- }
- results.add(groups);
- }
- if (results.isEmpty()) {
- return null;
- }
- String[][] matches = new String[results.size()][count];
- for (int i = 0; i < matches.length; i++) {
- matches[i] = (String[]) results.get(i);
- }
- return matches;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CASTING FUNCTIONS, INSERTED BY PREPROC
-
-
- /**
- * Convert a char to a boolean. 'T', 't', and '1' will become the
- * boolean value true, while 'F', 'f', or '0' will become false.
- */
- /*
- static final public boolean parseBoolean(char what) {
- return ((what == 't') || (what == 'T') || (what == '1'));
- }
- */
-
- /**
- *
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).
- * @return false if 0, true if any other number
- */
- static final public boolean parseBoolean(int what) {
- return (what != 0);
- }
-
- /*
- // removed because this makes no useful sense
- static final public boolean parseBoolean(float what) {
- return (what != 0);
- }
- */
-
- /**
- * Convert the string "true" or "false" to a boolean.
- * @return true if 'what' is "true" or "TRUE", false otherwise
- */
- static final public boolean parseBoolean(String what) {
- return new Boolean(what).booleanValue();
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- /*
- // removed, no need to introduce strange syntax from other languages
- static final public boolean[] parseBoolean(char what[]) {
- boolean outgoing[] = new boolean[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] =
- ((what[i] == 't') || (what[i] == 'T') || (what[i] == '1'));
- }
- return outgoing;
- }
- */
-
- /**
- * Convert a byte array to a boolean array. Each element will be
- * evaluated identical to the integer case, where a byte equal
- * to zero will return false, and any other value will return true.
- * @return array of boolean elements
- */
- static final public boolean[] parseBoolean(byte what[]) {
- boolean outgoing[] = new boolean[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (what[i] != 0);
- }
- return outgoing;
- }
-
- /**
- * Convert an int array to a boolean array. An int equal
- * to zero will return false, and any other value will return true.
- * @return array of boolean elements
- */
- static final public boolean[] parseBoolean(int what[]) {
- boolean outgoing[] = new boolean[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (what[i] != 0);
- }
- return outgoing;
- }
-
- /*
- // removed, not necessary... if necessary, convert to int array first
- static final public boolean[] parseBoolean(float what[]) {
- boolean outgoing[] = new boolean[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (what[i] != 0);
- }
- return outgoing;
- }
- */
-
- static final public boolean[] parseBoolean(String what[]) {
- boolean outgoing[] = new boolean[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = new Boolean(what[i]).booleanValue();
- }
- return outgoing;
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- static final public byte parseByte(boolean what) {
- return what ? (byte)1 : 0;
- }
-
- static final public byte parseByte(char what) {
- return (byte) what;
- }
-
- static final public byte parseByte(int what) {
- return (byte) what;
- }
-
- static final public byte parseByte(float what) {
- return (byte) what;
- }
-
- /*
- // nixed, no precedent
- static final public byte[] parseByte(String what) { // note: array[]
- return what.getBytes();
- }
- */
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- static final public byte[] parseByte(boolean what[]) {
- byte outgoing[] = new byte[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = what[i] ? (byte)1 : 0;
- }
- return outgoing;
- }
-
- static final public byte[] parseByte(char what[]) {
- byte outgoing[] = new byte[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (byte) what[i];
- }
- return outgoing;
- }
-
- static final public byte[] parseByte(int what[]) {
- byte outgoing[] = new byte[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (byte) what[i];
- }
- return outgoing;
- }
-
- static final public byte[] parseByte(float what[]) {
- byte outgoing[] = new byte[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (byte) what[i];
- }
- return outgoing;
- }
-
- /*
- static final public byte[][] parseByte(String what[]) { // note: array[][]
- byte outgoing[][] = new byte[what.length][];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = what[i].getBytes();
- }
- return outgoing;
- }
- */
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- /*
- static final public char parseChar(boolean what) { // 0/1 or T/F ?
- return what ? 't' : 'f';
- }
- */
-
- static final public char parseChar(byte what) {
- return (char) (what & 0xff);
- }
-
- static final public char parseChar(int what) {
- return (char) what;
- }
-
- /*
- static final public char parseChar(float what) { // nonsensical
- return (char) what;
- }
-
- static final public char[] parseChar(String what) { // note: array[]
- return what.toCharArray();
- }
- */
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- /*
- static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ?
- char outgoing[] = new char[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = what[i] ? 't' : 'f';
- }
- return outgoing;
- }
- */
-
- static final public char[] parseChar(byte what[]) {
- char outgoing[] = new char[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (char) (what[i] & 0xff);
- }
- return outgoing;
- }
-
- static final public char[] parseChar(int what[]) {
- char outgoing[] = new char[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (char) what[i];
- }
- return outgoing;
- }
-
- /*
- static final public char[] parseChar(float what[]) { // nonsensical
- char outgoing[] = new char[what.length];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = (char) what[i];
- }
- return outgoing;
- }
-
- static final public char[][] parseChar(String what[]) { // note: array[][]
- char outgoing[][] = new char[what.length][];
- for (int i = 0; i < what.length; i++) {
- outgoing[i] = what[i].toCharArray();
- }
- return outgoing;
- }
- */
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- static final public int parseInt(boolean what) {
- return what ? 1 : 0;
- }
-
- /**
- * Note that parseInt() will un-sign a signed byte value.
- */
- static final public int parseInt(byte what) {
- return what & 0xff;
- }
-
- /**
- * Note that parseInt('5') is unlike String in the sense that it
- * won't return 5, but the ascii value. This is because ((int) someChar)
- * returns the ascii value, and parseInt() is just longhand for the cast.
- */
- static final public int parseInt(char what) {
- return what;
- }
-
- /**
- * Same as floor(), or an (int) cast.
- */
- static final public int parseInt(float what) {
- return (int) what;
- }
-
- /**
- * Parse a String into an int value. Returns 0 if the value is bad.
- */
- static final public int parseInt(String what) {
- return parseInt(what, 0);
- }
-
- /**
- * Parse a String to an int, and provide an alternate value that
- * should be used when the number is invalid.
- */
- static final public int parseInt(String what, int otherwise) {
- try {
- int offset = what.indexOf('.');
- if (offset == -1) {
- return Integer.parseInt(what);
- } else {
- return Integer.parseInt(what.substring(0, offset));
- }
- } catch (NumberFormatException e) { }
- return otherwise;
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- static final public int[] parseInt(boolean what[]) {
- int list[] = new int[what.length];
- for (int i = 0; i < what.length; i++) {
- list[i] = what[i] ? 1 : 0;
- }
- return list;
- }
-
- static final public int[] parseInt(byte what[]) { // note this unsigns
- int list[] = new int[what.length];
- for (int i = 0; i < what.length; i++) {
- list[i] = (what[i] & 0xff);
- }
- return list;
- }
-
- static final public int[] parseInt(char what[]) {
- int list[] = new int[what.length];
- for (int i = 0; i < what.length; i++) {
- list[i] = what[i];
- }
- return list;
- }
-
- static public int[] parseInt(float what[]) {
- int inties[] = new int[what.length];
- for (int i = 0; i < what.length; i++) {
- inties[i] = (int)what[i];
- }
- return inties;
- }
-
- /**
- * Make an array of int elements from an array of String objects.
- * If the String can't be parsed as a number, it will be set to zero.
- *
- * String s[] = { "1", "300", "44" };
- * int numbers[] = parseInt(s);
- *
- * numbers will contain { 1, 300, 44 }
- */
- static public int[] parseInt(String what[]) {
- return parseInt(what, 0);
- }
-
- /**
- * Make an array of int elements from an array of String objects.
- * If the String can't be parsed as a number, its entry in the
- * array will be set to the value of the "missing" parameter.
- *
- * String s[] = { "1", "300", "apple", "44" };
- * int numbers[] = parseInt(s, 9999);
- *
- * numbers will contain { 1, 300, 9999, 44 }
- */
- static public int[] parseInt(String what[], int missing) {
- int output[] = new int[what.length];
- for (int i = 0; i < what.length; i++) {
- try {
- output[i] = Integer.parseInt(what[i]);
- } catch (NumberFormatException e) {
- output[i] = missing;
- }
- }
- return output;
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- /*
- static final public float parseFloat(boolean what) {
- return what ? 1 : 0;
- }
- */
-
- /**
- * Convert an int to a float value. Also handles bytes because of
- * Java's rules for upgrading values.
- */
- static final public float parseFloat(int what) { // also handles byte
- return (float)what;
- }
-
- static final public float parseFloat(String what) {
- return parseFloat(what, Float.NaN);
- }
-
- static final public float parseFloat(String what, float otherwise) {
- try {
- return new Float(what).floatValue();
- } catch (NumberFormatException e) { }
-
- return otherwise;
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- /*
- static final public float[] parseFloat(boolean what[]) {
- float floaties[] = new float[what.length];
- for (int i = 0; i < what.length; i++) {
- floaties[i] = what[i] ? 1 : 0;
- }
- return floaties;
- }
-
- static final public float[] parseFloat(char what[]) {
- float floaties[] = new float[what.length];
- for (int i = 0; i < what.length; i++) {
- floaties[i] = (char) what[i];
- }
- return floaties;
- }
- */
-
- static final public float[] parseByte(byte what[]) {
- float floaties[] = new float[what.length];
- for (int i = 0; i < what.length; i++) {
- floaties[i] = what[i];
- }
- return floaties;
- }
-
- static final public float[] parseFloat(int what[]) {
- float floaties[] = new float[what.length];
- for (int i = 0; i < what.length; i++) {
- floaties[i] = what[i];
- }
- return floaties;
- }
-
- static final public float[] parseFloat(String what[]) {
- return parseFloat(what, Float.NaN);
- }
-
- static final public float[] parseFloat(String what[], float missing) {
- float output[] = new float[what.length];
- for (int i = 0; i < what.length; i++) {
- try {
- output[i] = new Float(what[i]).floatValue();
- } catch (NumberFormatException e) {
- output[i] = missing;
- }
- }
- return output;
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- static final public String str(boolean x) {
- return String.valueOf(x);
- }
-
- static final public String str(byte x) {
- return String.valueOf(x);
- }
-
- static final public String str(char x) {
- return String.valueOf(x);
- }
-
- static final public String str(int x) {
- return String.valueOf(x);
- }
-
- static final public String str(float x) {
- return String.valueOf(x);
- }
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
- static final public String[] str(boolean x[]) {
- String s[] = new String[x.length];
- for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
- return s;
- }
-
- static final public String[] str(byte x[]) {
- String s[] = new String[x.length];
- for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
- return s;
- }
-
- static final public String[] str(char x[]) {
- String s[] = new String[x.length];
- for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
- return s;
- }
-
- static final public String[] str(int x[]) {
- String s[] = new String[x.length];
- for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
- return s;
- }
-
- static final public String[] str(float x[]) {
- String s[] = new String[x.length];
- for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
- return s;
- }
-
-
- //////////////////////////////////////////////////////////////
-
- // INT NUMBER FORMATTING
-
-
- /**
- * Integer number formatter.
- */
- static private NumberFormat int_nf;
- static private int int_nf_digits;
- static private boolean int_nf_commas;
-
-
- static public String[] nf(int num[], int digits) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nf(num[i], digits);
- }
- return formatted;
- }
-
-
- static public String nf(int num, int digits) {
- if ((int_nf != null) &&
- (int_nf_digits == digits) &&
- !int_nf_commas) {
- return int_nf.format(num);
- }
-
- int_nf = NumberFormat.getInstance();
- int_nf.setGroupingUsed(false); // no commas
- int_nf_commas = false;
- int_nf.setMinimumIntegerDigits(digits);
- int_nf_digits = digits;
- return int_nf.format(num);
- }
-
-
- static public String[] nfc(int num[]) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nfc(num[i]);
- }
- return formatted;
- }
-
-
- static public String nfc(int num) {
- if ((int_nf != null) &&
- (int_nf_digits == 0) &&
- int_nf_commas) {
- return int_nf.format(num);
- }
-
- int_nf = NumberFormat.getInstance();
- int_nf.setGroupingUsed(true);
- int_nf_commas = true;
- int_nf.setMinimumIntegerDigits(0);
- int_nf_digits = 0;
- return int_nf.format(num);
- }
-
-
- /**
- * number format signed (or space)
- * Formats a number but leaves a blank space in the front
- * when it's positive so that it can be properly aligned with
- * numbers that have a negative sign in front of them.
- */
- static public String nfs(int num, int digits) {
- return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits));
- }
-
- static public String[] nfs(int num[], int digits) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nfs(num[i], digits);
- }
- return formatted;
- }
-
- //
-
- /**
- * number format positive (or plus)
- * Formats a number, always placing a - or + sign
- * in the front when it's negative or positive.
- */
- static public String nfp(int num, int digits) {
- return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits));
- }
-
- static public String[] nfp(int num[], int digits) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nfp(num[i], digits);
- }
- return formatted;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // FLOAT NUMBER FORMATTING
-
-
- static private NumberFormat float_nf;
- static private int float_nf_left, float_nf_right;
- static private boolean float_nf_commas;
-
-
- static public String[] nf(float num[], int left, int right) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nf(num[i], left, right);
- }
- return formatted;
- }
-
-
- static public String nf(float num, int left, int right) {
- if ((float_nf != null) &&
- (float_nf_left == left) &&
- (float_nf_right == right) &&
- !float_nf_commas) {
- return float_nf.format(num);
- }
-
- float_nf = NumberFormat.getInstance();
- float_nf.setGroupingUsed(false);
- float_nf_commas = false;
-
- if (left != 0) float_nf.setMinimumIntegerDigits(left);
- if (right != 0) {
- float_nf.setMinimumFractionDigits(right);
- float_nf.setMaximumFractionDigits(right);
- }
- float_nf_left = left;
- float_nf_right = right;
- return float_nf.format(num);
- }
-
-
- static public String[] nfc(float num[], int right) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nfc(num[i], right);
- }
- return formatted;
- }
-
-
- static public String nfc(float num, int right) {
- if ((float_nf != null) &&
- (float_nf_left == 0) &&
- (float_nf_right == right) &&
- float_nf_commas) {
- return float_nf.format(num);
- }
-
- float_nf = NumberFormat.getInstance();
- float_nf.setGroupingUsed(true);
- float_nf_commas = true;
-
- if (right != 0) {
- float_nf.setMinimumFractionDigits(right);
- float_nf.setMaximumFractionDigits(right);
- }
- float_nf_left = 0;
- float_nf_right = right;
- return float_nf.format(num);
- }
-
-
- /**
- * Number formatter that takes into account whether the number
- * has a sign (positive, negative, etc) in front of it.
- */
- static public String[] nfs(float num[], int left, int right) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nfs(num[i], left, right);
- }
- return formatted;
- }
-
- static public String nfs(float num, int left, int right) {
- return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right));
- }
-
-
- static public String[] nfp(float num[], int left, int right) {
- String formatted[] = new String[num.length];
- for (int i = 0; i < formatted.length; i++) {
- formatted[i] = nfp(num[i], left, right);
- }
- return formatted;
- }
-
- static public String nfp(float num, int left, int right) {
- return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right));
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // HEX/BINARY CONVERSION
-
-
- static final public String hex(byte what) {
- return hex(what, 2);
- }
-
- static final public String hex(char what) {
- return hex(what, 4);
- }
-
- static final public String hex(int what) {
- return hex(what, 8);
- }
-
- static final public String hex(int what, int digits) {
- String stuff = Integer.toHexString(what).toUpperCase();
-
- int length = stuff.length();
- if (length > digits) {
- return stuff.substring(length - digits);
-
- } else if (length < digits) {
- return "00000000".substring(8 - (digits-length)) + stuff;
- }
- return stuff;
- }
-
- static final public int unhex(String what) {
- // has to parse as a Long so that it'll work for numbers bigger than 2^31
- return (int) (Long.parseLong(what, 16));
- }
-
- //
-
- /**
- * Returns a String that contains the binary value of a byte.
- * The returned value will always have 8 digits.
- */
- static final public String binary(byte what) {
- return binary(what, 8);
- }
-
- /**
- * Returns a String that contains the binary value of a char.
- * The returned value will always have 16 digits because chars
- * are two bytes long.
- */
- static final public String binary(char what) {
- return binary(what, 16);
- }
-
- /**
- * Returns a String that contains the binary value of an int.
- * The length depends on the size of the number itself.
- * An int can be up to 32 binary digits, but that seems like
- * overkill for almost any situation, so this function just
- * auto-size. If you want a specific number of digits (like all 32)
- * use binary(int what, int digits) to specify how many digits.
- */
- static final public String binary(int what) {
- return Integer.toBinaryString(what);
- //return binary(what, 32);
- }
-
- /**
- * Returns a String that contains the binary value of an int.
- * The digits parameter determines how many digits will be used.
- */
- static final public String binary(int what, int digits) {
- String stuff = Integer.toBinaryString(what);
-
- int length = stuff.length();
- if (length > digits) {
- return stuff.substring(length - digits);
-
- } else if (length < digits) {
- int offset = 32 - (digits-length);
- return "00000000000000000000000000000000".substring(offset) + stuff;
- }
- return stuff;
- }
-
-
- /**
- * Unpack a binary String into an int.
- * i.e. unbinary("00001000") would return 8.
- */
- static final public int unbinary(String what) {
- return Integer.parseInt(what, 2);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR FUNCTIONS
-
- // moved here so that they can work without
- // the graphics actually being instantiated (outside setup)
-
-
- public final int color(int gray) {
- if (g == null) {
- if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
- return 0xff000000 | (gray << 16) | (gray << 8) | gray;
- }
- return g.color(gray);
- }
-
-
- public final int color(float fgray) {
- if (g == null) {
- int gray = (int) fgray;
- if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
- return 0xff000000 | (gray << 16) | (gray << 8) | gray;
- }
- return g.color(fgray);
- }
-
-
- /**
- * As of 0116 this also takes color(#FF8800, alpha)
- *
- * @param gray number specifying value between white and black
- */
- public final int color(int gray, int alpha) {
- if (g == null) {
- if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
- if (gray > 255) {
- // then assume this is actually a #FF8800
- return (alpha << 24) | (gray & 0xFFFFFF);
- } else {
- //if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
- return (alpha << 24) | (gray << 16) | (gray << 8) | gray;
- }
- }
- return g.color(gray, alpha);
- }
-
-
- public final int color(float fgray, float falpha) {
- if (g == null) {
- int gray = (int) fgray;
- int alpha = (int) falpha;
- if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
- if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
- return 0xff000000 | (gray << 16) | (gray << 8) | gray;
- }
- return g.color(fgray, falpha);
- }
-
-
- public final int color(int x, int y, int z) {
- if (g == null) {
- if (x > 255) x = 255; else if (x < 0) x = 0;
- if (y > 255) y = 255; else if (y < 0) y = 0;
- if (z > 255) z = 255; else if (z < 0) z = 0;
-
- return 0xff000000 | (x << 16) | (y << 8) | z;
- }
- return g.color(x, y, z);
- }
-
-
- public final int color(float x, float y, float z) {
- if (g == null) {
- if (x > 255) x = 255; else if (x < 0) x = 0;
- if (y > 255) y = 255; else if (y < 0) y = 0;
- if (z > 255) z = 255; else if (z < 0) z = 0;
-
- return 0xff000000 | ((int)x << 16) | ((int)y << 8) | (int)z;
- }
- return g.color(x, y, z);
- }
-
-
- public final int color(int x, int y, int z, int a) {
- if (g == null) {
- if (a > 255) a = 255; else if (a < 0) a = 0;
- if (x > 255) x = 255; else if (x < 0) x = 0;
- if (y > 255) y = 255; else if (y < 0) y = 0;
- if (z > 255) z = 255; else if (z < 0) z = 0;
-
- return (a << 24) | (x << 16) | (y << 8) | z;
- }
- return g.color(x, y, z, a);
- }
-
- /**
- * Creates colors for storing in variables of the color datatype. The parameters are interpreted as RGB or HSB values depending on the current colorMode(). The default mode is RGB values from 0 to 255 and therefore, the function call color(255, 204, 0) will return a bright yellow color. More about how colors are stored can be found in the reference for the color datatype.
- *
- * @webref color:creating_reading
- * @param x red or hue values relative to the current color range
- * @param y green or saturation values relative to the current color range
- * @param z blue or brightness values relative to the current color range
- * @param a alpha relative to current color range
- *
- * @see processing.core.PApplet#colorMode(int)
- * @ref color_datatype
- */
- public final int color(float x, float y, float z, float a) {
- if (g == null) {
- if (a > 255) a = 255; else if (a < 0) a = 0;
- if (x > 255) x = 255; else if (x < 0) x = 0;
- if (y > 255) y = 255; else if (y < 0) y = 0;
- if (z > 255) z = 255; else if (z < 0) z = 0;
-
- return ((int)a << 24) | ((int)x << 16) | ((int)y << 8) | (int)z;
- }
- return g.color(x, y, z, a);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MAIN
-
-
- /**
- * Set this sketch to communicate its state back to the PDE.
- *
- * This uses the stderr stream to write positions of the window
- * (so that it will be saved by the PDE for the next run) and
- * notify on quit. See more notes in the Worker class.
- */
- public void setupExternalMessages() {
-
- frame.addComponentListener(new ComponentAdapter() {
- public void componentMoved(ComponentEvent e) {
- Point where = ((Frame) e.getSource()).getLocation();
- System.err.println(PApplet.EXTERNAL_MOVE + " " +
- where.x + " " + where.y);
- System.err.flush(); // doesn't seem to help or hurt
- }
- });
-
- frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
-// System.err.println(PApplet.EXTERNAL_QUIT);
-// System.err.flush(); // important
-// System.exit(0);
- exit(); // don't quit, need to just shut everything down (0133)
- }
- });
- }
-
-
- /**
- * Set up a listener that will fire proper component resize events
- * in cases where frame.setResizable(true) is called.
- */
- public void setupFrameResizeListener() {
- frame.addComponentListener(new ComponentAdapter() {
-
- public void componentResized(ComponentEvent e) {
- // Ignore bad resize events fired during setup to fix
- // http://dev.processing.org/bugs/show_bug.cgi?id=341
- // This should also fix the blank screen on Linux bug
- // http://dev.processing.org/bugs/show_bug.cgi?id=282
- if (frame.isResizable()) {
- // might be multiple resize calls before visible (i.e. first
- // when pack() is called, then when it's resized for use).
- // ignore them because it's not the user resizing things.
- Frame farm = (Frame) e.getComponent();
- if (farm.isVisible()) {
- Insets insets = farm.getInsets();
- Dimension windowSize = farm.getSize();
- int usableW = windowSize.width - insets.left - insets.right;
- int usableH = windowSize.height - insets.top - insets.bottom;
-
- // the ComponentListener in PApplet will handle calling size()
- setBounds(insets.left, insets.top, usableW, usableH);
- }
- }
- }
- });
- }
-
-
- /**
- * GIF image of the Processing logo.
- */
- static public final byte[] ICON_IMAGE = {
- 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -60, 0, 0, 0, 0, 0,
- 0, 0, -127, 0, -127, 0, 0, -127, -127, -127, 0, 0, -127, 0, -127, -127,
- -127, 0, -127, -127, -127, -63, -63, -63, 0, 0, -1, 0, -1, 0, 0, -1,
- -1, -1, 0, 0, -1, 0, -1, -1, -1, 0, -1, -1, -1, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, -7, 4,
- 9, 0, 0, 16, 0, 44, 0, 0, 0, 0, 16, 0, 16, 0, 0, 5,
- 75, 32, 36, -118, -57, 96, 14, -57, -88, 66, -27, -23, -90, -86, 43, -97,
- 99, 59, -65, -30, 125, -77, 3, -14, -4, 8, -109, 15, -120, -22, 61, 78,
- 15, -124, 15, 25, 28, 28, 93, 63, -45, 115, -22, -116, 90, -83, 82, 89,
- -44, -103, 61, 44, -91, -54, -89, 19, -111, 50, 18, -51, -55, 1, 73, -121,
- -53, -79, 77, 43, -101, 12, -74, -30, -99, -24, -94, 16, 0, 59,
- };
-
-
- /**
- * main() method for running this class from the command line.
- *
- * 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:
- *
- * 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", 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 ");
- System.err.println("For additional options, " +
- "see the Javadoc for PApplet");
- System.exit(1);
- }
-
- boolean external = false;
- int[] location = null;
- int[] editorLocation = null;
-
- String name = null;
- boolean present = false;
- boolean exclusive = false;
- Color backgroundColor = Color.BLACK;
- Color stopColor = Color.GRAY;
- GraphicsDevice displayDevice = null;
- boolean hideStop = false;
-
- String param = null, value = null;
-
- // try to get the user folder. if running under java web start,
- // this may cause a security exception if the code is not signed.
- // http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274
- String folder = null;
- try {
- folder = System.getProperty("user.dir");
- } catch (Exception e) { }
-
- int argIndex = 0;
- while (argIndex < args.length) {
- int equals = args[argIndex].indexOf('=');
- if (equals != -1) {
- param = args[argIndex].substring(0, equals);
- value = args[argIndex].substring(equals + 1);
-
- if (param.equals(ARGS_EDITOR_LOCATION)) {
- external = true;
- editorLocation = parseInt(split(value, ','));
-
- } else if (param.equals(ARGS_DISPLAY)) {
- int deviceIndex = Integer.parseInt(value) - 1;
-
- //DisplayMode dm = device.getDisplayMode();
- //if ((dm.getWidth() == 1024) && (dm.getHeight() == 768)) {
-
- GraphicsEnvironment environment =
- GraphicsEnvironment.getLocalGraphicsEnvironment();
- GraphicsDevice devices[] = environment.getScreenDevices();
- if ((deviceIndex >= 0) && (deviceIndex < devices.length)) {
- displayDevice = devices[deviceIndex];
- } else {
- System.err.println("Display " + value + " does not exist, " +
- "using the default display instead.");
- }
-
- } else if (param.equals(ARGS_BGCOLOR)) {
- if (value.charAt(0) == '#') value = value.substring(1);
- backgroundColor = new Color(Integer.parseInt(value, 16));
-
- } else if (param.equals(ARGS_STOP_COLOR)) {
- if (value.charAt(0) == '#') value = value.substring(1);
- stopColor = new Color(Integer.parseInt(value, 16));
-
- } else if (param.equals(ARGS_SKETCH_FOLDER)) {
- folder = value;
-
- } else if (param.equals(ARGS_LOCATION)) {
- location = parseInt(split(value, ','));
- }
-
- } else {
- if (args[argIndex].equals(ARGS_PRESENT)) {
- present = true;
-
- } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) {
- exclusive = true;
-
- } else if (args[argIndex].equals(ARGS_HIDE_STOP)) {
- hideStop = true;
-
- } else if (args[argIndex].equals(ARGS_EXTERNAL)) {
- external = true;
-
- } else {
- name = args[argIndex];
- break;
- }
- }
- argIndex++;
- }
-
- // Set this property before getting into any GUI init code
- //System.setProperty("com.apple.mrj.application.apple.menu.about.name", name);
- // This )*)(*@#$ Apple crap don't work no matter where you put it
- // (static method of the class, at the top of main, wherever)
-
- if (displayDevice == null) {
- GraphicsEnvironment environment =
- GraphicsEnvironment.getLocalGraphicsEnvironment();
- displayDevice = environment.getDefaultScreenDevice();
- }
-
- Frame frame = new Frame(displayDevice.getDefaultConfiguration());
- /*
- Frame frame = null;
- if (displayDevice != null) {
- frame = new Frame(displayDevice.getDefaultConfiguration());
- } else {
- frame = new Frame();
- }
- */
- //Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
-
- // remove the grow box by default
- // users who want it back can call frame.setResizable(true)
- frame.setResizable(false);
-
- // Set the trimmings around the image
- Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE);
- frame.setIconImage(image);
- frame.setTitle(name);
-
- final PApplet applet;
- try {
- Class> c = Thread.currentThread().getContextClassLoader().loadClass(name);
- applet = (PApplet) c.newInstance();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
-
- // these are needed before init/start
- applet.frame = frame;
- applet.sketchPath = folder;
- applet.args = PApplet.subset(args, 1);
- applet.external = external;
-
- // Need to save the window bounds at full screen,
- // because pack() will cause the bounds to go to zero.
- // http://dev.processing.org/bugs/show_bug.cgi?id=923
- Rectangle fullScreenRect = null;
-
- // For 0149, moving this code (up to the pack() method) before init().
- // For OpenGL (and perhaps other renderers in the future), a peer is
- // needed before a GLDrawable can be created. So pack() needs to be
- // called on the Frame before applet.init(), which itself calls size(),
- // and launches the Thread that will kick off setup().
- // http://dev.processing.org/bugs/show_bug.cgi?id=891
- // http://dev.processing.org/bugs/show_bug.cgi?id=908
- if (present) {
- frame.setUndecorated(true);
- frame.setBackground(backgroundColor);
- if (exclusive) {
- displayDevice.setFullScreenWindow(frame);
- frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
- fullScreenRect = frame.getBounds();
- } else {
- DisplayMode mode = displayDevice.getDisplayMode();
- fullScreenRect = new Rectangle(0, 0, mode.getWidth(), mode.getHeight());
- frame.setBounds(fullScreenRect);
- frame.setVisible(true);
- }
- }
- frame.setLayout(null);
- frame.add(applet);
- if (present) {
- frame.invalidate();
- } else {
- frame.pack();
- }
- // insufficient, places the 100x100 sketches offset strangely
- //frame.validate();
-
- applet.init();
-
- // Wait until the applet has figured out its width.
- // In a static mode app, this will be after setup() has completed,
- // and the empty draw() has set "finished" to true.
- // TODO make sure this won't hang if the applet has an exception.
- while (applet.defaultSize && !applet.finished) {
- //System.out.println("default size");
- try {
- Thread.sleep(5);
-
- } catch (InterruptedException e) {
- //System.out.println("interrupt");
- }
- }
- //println("not default size " + applet.width + " " + applet.height);
- //println(" (g width/height is " + applet.g.width + "x" + applet.g.height + ")");
-
- if (present) {
- // After the pack(), the screen bounds are gonna be 0s
- frame.setBounds(fullScreenRect);
- applet.setBounds((fullScreenRect.width - applet.width) / 2,
- (fullScreenRect.height - applet.height) / 2,
- applet.width, applet.height);
-
- if (!hideStop) {
- Label label = new Label("stop");
- label.setForeground(stopColor);
- label.addMouseListener(new MouseAdapter() {
- public void mousePressed(MouseEvent e) {
- System.exit(0);
- }
- });
- frame.add(label);
-
- Dimension labelSize = label.getPreferredSize();
- // sometimes shows up truncated on mac
- //System.out.println("label width is " + labelSize.width);
- labelSize = new Dimension(100, labelSize.height);
- label.setSize(labelSize);
- label.setLocation(20, fullScreenRect.height - labelSize.height - 20);
- }
-
- // not always running externally when in present mode
- if (external) {
- applet.setupExternalMessages();
- }
-
- } else { // if not presenting
- // can't do pack earlier cuz present mode don't like it
- // (can't go full screen with a frame after calling pack)
- // frame.pack(); // get insets. get more.
- Insets insets = frame.getInsets();
-
- int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) +
- insets.left + insets.right;
- int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) +
- insets.top + insets.bottom;
-
- frame.setSize(windowW, windowH);
-
- if (location != null) {
- // a specific location was received from PdeRuntime
- // (applet has been run more than once, user placed window)
- frame.setLocation(location[0], location[1]);
-
- } else if (external) {
- int locationX = editorLocation[0] - 20;
- int locationY = editorLocation[1];
-
- if (locationX - windowW > 10) {
- // if it fits to the left of the window
- frame.setLocation(locationX - windowW, locationY);
-
- } else { // doesn't fit
- // if it fits inside the editor window,
- // offset slightly from upper lefthand corner
- // so that it's plunked inside the text area
- locationX = editorLocation[0] + 66;
- locationY = editorLocation[1] + 66;
-
- if ((locationX + windowW > applet.screen.width - 33) ||
- (locationY + windowH > applet.screen.height - 33)) {
- // otherwise center on screen
- locationX = (applet.screen.width - windowW) / 2;
- locationY = (applet.screen.height - windowH) / 2;
- }
- frame.setLocation(locationX, locationY);
- }
- } else { // just center on screen
- frame.setLocation((applet.screen.width - applet.width) / 2,
- (applet.screen.height - applet.height) / 2);
- }
-
- if (backgroundColor == Color.black) { //BLACK) {
- // this means no bg color unless specified
- backgroundColor = SystemColor.control;
- }
- frame.setBackground(backgroundColor);
-
- int usableWindowH = windowH - insets.top - insets.bottom;
- applet.setBounds((windowW - applet.width)/2,
- insets.top + (usableWindowH - applet.height)/2,
- applet.width, applet.height);
-
- if (external) {
- applet.setupExternalMessages();
-
- } else { // !external
- frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- System.exit(0);
- }
- });
- }
-
- // handle frame resizing events
- applet.setupFrameResizeListener();
-
- // all set for rockin
- if (applet.displayable()) {
- frame.setVisible(true);
- }
- }
-
- applet.requestFocus(); // ask for keydowns
- //System.out.println("exiting main()");
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- /**
- * Begin recording to a new renderer of the specified type, using the width
- * and height of the main drawing surface.
- */
- public PGraphics beginRecord(String renderer, String filename) {
- filename = insertFrame(filename);
- PGraphics rec = createGraphics(width, height, renderer, filename);
- beginRecord(rec);
- return rec;
- }
-
-
- /**
- * Begin recording (echoing) commands to the specified PGraphics object.
- */
- public void beginRecord(PGraphics recorder) {
- this.recorder = recorder;
- recorder.beginDraw();
- }
-
-
- public void endRecord() {
- if (recorder != null) {
- recorder.endDraw();
- recorder.dispose();
- recorder = null;
- }
- }
-
-
- /**
- * Begin recording raw shape data to a renderer of the specified type,
- * using the width and height of the main drawing surface.
- *
- * If hashmarks (###) are found in the filename, they'll be replaced
- * by the current frame number (frameCount).
- */
- public PGraphics beginRaw(String renderer, String filename) {
- filename = insertFrame(filename);
- PGraphics rec = createGraphics(width, height, renderer, filename);
- g.beginRaw(rec);
- return rec;
- }
-
-
- /**
- * Begin recording raw shape data to the specified renderer.
- *
- * This simply echoes to g.beginRaw(), but since is placed here (rather than
- * generated by preproc.pl) for clarity and so that it doesn't echo the
- * command should beginRecord() be in use.
- */
- public void beginRaw(PGraphics rawGraphics) {
- g.beginRaw(rawGraphics);
- }
-
-
- /**
- * Stop recording raw shape data to the specified renderer.
- *
- * This simply echoes to g.beginRaw(), but since is placed here (rather than
- * generated by preproc.pl) for clarity and so that it doesn't echo the
- * command should beginRecord() be in use.
- */
- public void endRaw() {
- g.endRaw();
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- /**
- * Loads the pixel data for the display window into the pixels[] array. This function must always be called before reading from or writing to pixels[].
- *
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.
- *
- * 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.
- *
- * This is for drawing three dimensional shapes and surfaces,
- * allowing you to specify a vector perpendicular to the surface
- * of the shape, which determines how lighting affects it.
- *
- * For the most part, PGraphics3D will attempt to automatically
- * assign normals to shapes, but since that's imperfect,
- * this is a better option when you want more control.
- *
- * For people familiar with OpenGL, this function is basically
- * identical to glNormal3f().
- */
- public void normal(float nx, float ny, float nz) {
- if (recorder != null) recorder.normal(nx, ny, nz);
- g.normal(nx, ny, nz);
- }
-
-
- /**
- * Set texture mode to either to use coordinates based on the IMAGE
- * (more intuitive for new users) or NORMALIZED (better for advanced chaps)
- */
- public void textureMode(int mode) {
- if (recorder != null) recorder.textureMode(mode);
- g.textureMode(mode);
- }
-
-
- /**
- * Set texture image for current shape.
- * Needs to be called between @see beginShape and @see endShape
- *
- * @param image reference to a PImage object
- */
- public void texture(PImage image) {
- if (recorder != null) recorder.texture(image);
- g.texture(image);
- }
-
-
- public void vertex(float x, float y) {
- if (recorder != null) recorder.vertex(x, y);
- g.vertex(x, y);
- }
-
-
- public void vertex(float x, float y, float z) {
- if (recorder != null) recorder.vertex(x, y, z);
- g.vertex(x, y, z);
- }
-
-
- /**
- * Used by renderer subclasses or PShape to efficiently pass in already
- * formatted vertex information.
- * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT
- */
- public void vertex(float[] v) {
- if (recorder != null) recorder.vertex(v);
- g.vertex(v);
- }
-
-
- public void vertex(float x, float y, float u, float v) {
- if (recorder != null) recorder.vertex(x, y, u, v);
- g.vertex(x, y, u, v);
- }
-
-
- public void vertex(float x, float y, float z, float u, float v) {
- if (recorder != null) recorder.vertex(x, y, z, u, v);
- g.vertex(x, y, z, u, v);
- }
-
-
- /** This feature is in testing, do not use or rely upon its implementation */
- public void breakShape() {
- if (recorder != null) recorder.breakShape();
- g.breakShape();
- }
-
-
- public void endShape() {
- if (recorder != null) recorder.endShape();
- g.endShape();
- }
-
-
- public void endShape(int mode) {
- if (recorder != null) recorder.endShape(mode);
- g.endShape(mode);
- }
-
-
- public void bezierVertex(float x2, float y2,
- float x3, float y3,
- float x4, float y4) {
- if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4);
- g.bezierVertex(x2, y2, x3, y3, x4, y4);
- }
-
-
- public void bezierVertex(float x2, float y2, float z2,
- float x3, float y3, float z3,
- float x4, float y4, float z4) {
- if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
- g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
- }
-
-
- public void curveVertex(float x, float y) {
- if (recorder != null) recorder.curveVertex(x, y);
- g.curveVertex(x, y);
- }
-
-
- public void curveVertex(float x, float y, float z) {
- if (recorder != null) recorder.curveVertex(x, y, z);
- g.curveVertex(x, y, z);
- }
-
-
- public void point(float x, float y) {
- if (recorder != null) recorder.point(x, y);
- g.point(x, y);
- }
-
-
- /**
- * Draws a point, a coordinate in space at the dimension of one pixel.
- * The first parameter is the horizontal value for the point, the second
- * value is the vertical value for the point, and the optional third value
- * is the depth value. 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.
- *
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);
- }
-
-
- /**
- * 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
- *
- * 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
- *
- * [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.
- *
- * 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().
- *
- *
- * @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);
- }
-
-
- /**
- * 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.
- *
- * 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).
- *
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.
- *
- * 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) 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
- *
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.
- *
- * @webref color:setting
- * @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)
- *
- * @see PGraphics#stroke(float)
- * @see PGraphics#fill(float)
- * @see PGraphics#tint(float)
- * @see PGraphics#colorMode(int)
- */
- public void background(float x, float y, float z, float a) {
- if (recorder != null) recorder.background(x, y, z, a);
- g.background(x, y, z, a);
- }
-
-
- /**
- * Takes an RGB or ARGB image and sets it as the background.
- * The width and height of the image must be the same size as the sketch.
- * Use image.resize(width, height) to make short work of such a task.
- *
- * 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
- *
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:
- *
- * @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.
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:
- *
- * @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.
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:
- *
- * @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.
- *
- * 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).
- *
- * 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.
- *
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.
- *
- * 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:
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.
- *
- *
- *
filter(BLUR) provides a basic blur.
- *
filter(GRAY) converts the image to grayscale based on luminance.
- *
filter(INVERT) will invert the color components in the image.
- *
filter(OPAQUE) set all the high bits in the image to opaque
- *
filter(THRESHOLD) converts the image to black and white.
- *
filter(DILATE) grow white/light areas
- *
filter(ERODE) shrink white/light areas
- *
- * 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.
- *
- *
REPLACE - destination colour equals colour of source pixel: C = A.
- * Sometimes called "Normal" or "Copy" in other software.
- *
- *
BLEND - linear interpolation of colours:
- * C = A*factor + B
- *
- *
ADD - additive blending with white clip:
- * C = min(A*factor + B, 255).
- * Clipped to 0..255, Photoshop calls this "Linear Burn",
- * and Director calls it "Add Pin".
- *
- *
SUBTRACT - substractive blend with black clip:
- * C = max(B - A*factor, 0).
- * Clipped to 0..255, Photoshop calls this "Linear Dodge",
- * and Director calls it "Subtract Pin".
- *
- *
DARKEST - only the darkest colour succeeds:
- * C = min(A*factor, B).
- * Illustrator calls this "Darken".
- *
- *
LIGHTEST - only the lightest colour succeeds:
- * C = max(A*factor, B).
- * Illustrator calls this "Lighten".
- *
- *
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.
- *
- *
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.
- */
- static public int blendColor(int c1, int c2, int mode) {
- return PGraphics.blendColor(c1, c2, mode);
- }
-
-
- /**
- * Blends one area of this image to another area.
- *
- * @see processing.core.PImage#blendColor(int,int,int)
- */
- public void blend(int sx, int sy, int sw, int sh,
- int dx, int dy, int dw, int dh, int mode) {
- if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
- g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
- }
-
-
- /**
- * Blends a region of pixels into the image specified by the img parameter. These copies utilize full alpha channel support and a choice of the following modes to blend the colors of source pixels (A) with the ones of pixels in the destination image (B):
- * 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);
- }
-}
diff --git a/core/src/processing/core/PConstants.java b/core/src/processing/core/PConstants.java
deleted file mode 100644
index f1eae5882e0..00000000000
--- a/core/src/processing/core/PConstants.java
+++ /dev/null
@@ -1,504 +0,0 @@
-/* -*- 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.Cursor;
-import java.awt.event.KeyEvent;
-
-
-/**
- * Numbers shared throughout processing.core.
- *
- * 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.
- *
- * Changed value in 0093 to not interfere with LEFT, CENTER, and RIGHT.
- */
- static final int MODEL = 4;
-
- /**
- * textMode(SHAPE) draws text using the the glyph outlines of
- * individual characters rather than as textures. If the outlines are
- * not available, then textMode(SHAPE) will be ignored and textMode(MODEL)
- * will be used instead. For this reason, be sure to call textMode()
- * after calling textFont().
- *
- * Currently, textMode(SHAPE) is only supported by OPENGL mode.
- * It also requires Java 1.2 or higher (OPENGL requires 1.4 anyway)
- */
- static final int SHAPE = 5;
-
-
- // text alignment modes
- // are inherited from LEFT, CENTER, RIGHT
-
-
- // stroke modes
-
- static final int SQUARE = 1 << 0; // called 'butt' in the svg spec
- static final int ROUND = 1 << 1;
- static final int PROJECT = 1 << 2; // called 'square' in the svg spec
- static final int MITER = 1 << 3;
- static final int BEVEL = 1 << 5;
-
-
- // lighting
-
- static final int AMBIENT = 0;
- static final int DIRECTIONAL = 1;
- //static final int POINT = 2; // shared with shape feature
- static final int SPOT = 3;
-
-
- // key constants
-
- // only including the most-used of these guys
- // if people need more esoteric keys, they can learn about
- // the esoteric java KeyEvent api and of virtual keys
-
- // both key and keyCode will equal these values
- // for 0125, these were changed to 'char' values, because they
- // can be upgraded to ints automatically by Java, but having them
- // as ints prevented split(blah, TAB) from working
- static final char BACKSPACE = 8;
- static final char TAB = 9;
- static final char ENTER = 10;
- static final char RETURN = 13;
- static final char ESC = 27;
- static final char DELETE = 127;
-
- // i.e. if ((key == CODED) && (keyCode == UP))
- static final int CODED = 0xffff;
-
- // key will be CODED and keyCode will be this value
- static final int UP = KeyEvent.VK_UP;
- static final int DOWN = KeyEvent.VK_DOWN;
- static final int LEFT = KeyEvent.VK_LEFT;
- static final int RIGHT = KeyEvent.VK_RIGHT;
-
- // key will be CODED and keyCode will be this value
- static final int ALT = KeyEvent.VK_ALT;
- static final int CONTROL = KeyEvent.VK_CONTROL;
- static final int SHIFT = KeyEvent.VK_SHIFT;
-
-
- // cursor types
-
- static final int ARROW = Cursor.DEFAULT_CURSOR;
- static final int CROSS = Cursor.CROSSHAIR_CURSOR;
- static final int HAND = Cursor.HAND_CURSOR;
- static final int MOVE = Cursor.MOVE_CURSOR;
- static final int TEXT = Cursor.TEXT_CURSOR;
- static final int WAIT = Cursor.WAIT_CURSOR;
-
-
- // hints - hint values are positive for the alternate version,
- // negative of the same value returns to the normal/default state
-
- static final int DISABLE_OPENGL_2X_SMOOTH = 1;
- static final int ENABLE_OPENGL_2X_SMOOTH = -1;
- static final int ENABLE_OPENGL_4X_SMOOTH = 2;
-
- static final int ENABLE_NATIVE_FONTS = 3;
-
- static final int DISABLE_DEPTH_TEST = 4;
- static final int ENABLE_DEPTH_TEST = -4;
-
- static final int ENABLE_DEPTH_SORT = 5;
- static final int DISABLE_DEPTH_SORT = -5;
-
- static final int DISABLE_OPENGL_ERROR_REPORT = 6;
- static final int ENABLE_OPENGL_ERROR_REPORT = -6;
-
- static final int ENABLE_ACCURATE_TEXTURES = 7;
- static final int DISABLE_ACCURATE_TEXTURES = -7;
-
- static final int HINT_COUNT = 10;
-
-
- // error messages
-
- static final String ERROR_BACKGROUND_IMAGE_SIZE =
- "background image must be the same size as your application";
- static final String ERROR_BACKGROUND_IMAGE_FORMAT =
- "background images should be RGB or ARGB";
-
- static final String ERROR_TEXTFONT_NULL_PFONT =
- "A null PFont was passed to textFont()";
-
- static final String ERROR_PUSHMATRIX_OVERFLOW =
- "Too many calls to pushMatrix().";
- static final String ERROR_PUSHMATRIX_UNDERFLOW =
- "Too many calls to popMatrix(), and not enough to pushMatrix().";
-}
diff --git a/core/src/processing/core/PFont.java b/core/src/processing/core/PFont.java
deleted file mode 100644
index 421cfb09e72..00000000000
--- a/core/src/processing/core/PFont.java
+++ /dev/null
@@ -1,877 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2004-10 Ben Fry & 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 version 2.01 of the GNU Lesser General
- Public License 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.*;
-import java.awt.image.*;
-import java.io.*;
-import java.util.Arrays;
-import java.util.HashMap;
-
-
-/**
- * Grayscale bitmap font class used by Processing.
- *
- * Awful (and by that, I mean awesome) ASCII (non-)art for how this works:
- *
- * |
- * | height is the full used height of the image
- * |
- * | ..XX.. }
- * | ..XX.. }
- * | ...... }
- * | XXXX.. } topExtent (top y is baseline - topExtent)
- * | ..XX.. }
- * | ..XX.. } dotted areas are where the image data
- * | ..XX.. } is actually located for the character
- * +---XXXXXX---- } (it extends to the right and down
- * | for power of two texture sizes)
- * ^^^^ leftExtent (amount to move over before drawing the image
- *
- * ^^^^^^^^^^^^^^ setWidth (width displaced by char)
- *
- */
-public class PFont implements PConstants {
-
- /** Number of character glyphs in this font. */
- protected int glyphCount;
-
- /**
- * Actual glyph data. The length of this array won't necessarily be the
- * same size as glyphCount, in cases where lazy font loading is in use.
- */
- protected Glyph[] glyphs;
-
- /**
- * Name of the font as seen by Java when it was created.
- * If the font is available, the native version will be used.
- */
- protected String name;
-
- /**
- * Postscript name of the font that this bitmap was created from.
- */
- protected String psname;
-
- /**
- * The original size of the font when it was first created
- */
- protected int size;
-
- /** true if smoothing was enabled for this font, used for native impl */
- protected boolean smooth;
-
- /**
- * The ascent of the font. If the 'd' character is present in this PFont,
- * this value is replaced with its pixel height, because the values returned
- * by FontMetrics.getAscent() seem to be terrible.
- */
- protected int ascent;
-
- /**
- * The descent of the font. If the 'p' character is present in this PFont,
- * this value is replaced with its lowest pixel height, because the values
- * returned by FontMetrics.getDescent() are gross.
- */
- protected int descent;
-
- /**
- * A more efficient array lookup for straight ASCII characters. For Unicode
- * characters, a QuickSort-style search is used.
- */
- protected int[] ascii;
-
- /**
- * True if this font is set to load dynamically. This is the default when
- * createFont() method is called without a character set. Bitmap versions of
- * characters are only created when prompted by an index() call.
- */
- protected boolean lazy;
-
- /**
- * Native Java version of the font. If possible, this allows the
- * PGraphics subclass to just use Java's font rendering stuff
- * in situations where that's faster.
- */
- protected Font font;
-
- /** True if this font was loaded from a stream, rather than from the OS. */
- protected boolean stream;
-
- /**
- * True if we've already tried to find the native AWT version of this font.
- */
- protected boolean fontSearched;
-
- /**
- * Array of the native system fonts. Used to lookup native fonts by their
- * PostScript name. This is a workaround for a several year old Apple Java
- * bug that they can't be bothered to fix.
- */
- static protected Font[] fonts;
- static protected HashMap fontDifferent;
-
-
- // objects to handle creation of font characters only as they're needed
- BufferedImage lazyImage;
- Graphics2D lazyGraphics;
- FontMetrics lazyMetrics;
- int[] lazySamples;
-
-
- public PFont() { } // for subclasses
-
-
- /**
- * Create a new Processing font from a native font, but don't create all the
- * characters at once, instead wait until they're used to include them.
- * @param font
- * @param smooth
- */
- public PFont(Font font, boolean smooth) {
- this(font, smooth, null);
- }
-
-
- /**
- * Create a new image-based font on the fly. If charset is set to null,
- * the characters will only be created as bitmaps when they're drawn.
- *
- * @param font the font object to create from
- * @param charset array of all unicode chars that should be included
- * @param smooth true to enable smoothing/anti-aliasing
- */
- public PFont(Font font, boolean smooth, char charset[]) {
- // save this so that we can use the native version
- this.font = font;
- this.smooth = smooth;
-
- name = font.getName();
- psname = font.getPSName();
- size = font.getSize();
-
- // no, i'm not interested in getting off the couch
- lazy = true;
- // not sure what else to do here
- //mbox2 = 0;
-
- int initialCount = 10;
- glyphs = new Glyph[initialCount];
-
- ascii = new int[128];
- Arrays.fill(ascii, -1);
-
- int mbox3 = size * 3;
-
- lazyImage = new BufferedImage(mbox3, mbox3, BufferedImage.TYPE_INT_RGB);
- lazyGraphics = (Graphics2D) lazyImage.getGraphics();
- lazyGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
- smooth ?
- RenderingHints.VALUE_ANTIALIAS_ON :
- RenderingHints.VALUE_ANTIALIAS_OFF);
- // adding this for post-1.0.9
- lazyGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
- smooth ?
- RenderingHints.VALUE_TEXT_ANTIALIAS_ON :
- RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
-
- lazyGraphics.setFont(font);
- lazyMetrics = lazyGraphics.getFontMetrics();
- lazySamples = new int[mbox3 * mbox3];
-
- // These values are terrible/unusable. Verified again for Processing 1.1.
- // They vary widely per-platform and per-font, so instead we'll use the
- // calculate-by-hand method of measuring pixels in characters.
- //ascent = lazyMetrics.getAscent();
- //descent = lazyMetrics.getDescent();
-
- if (charset != null) {
- // charset needs to be sorted to make index lookup run more quickly
- // http://dev.processing.org/bugs/show_bug.cgi?id=494
- Arrays.sort(charset);
-
- glyphs = new Glyph[charset.length];
-
- glyphCount = 0;
- for (char c : charset) {
- if (font.canDisplay(c)) {
- glyphs[glyphCount++] = new Glyph(c);
- }
- }
-
- // shorten the array if necessary
- if (glyphCount != charset.length) {
- glyphs = (Glyph[]) PApplet.subset(glyphs, 0, glyphCount);
- }
-
- // foreign font, so just make ascent the max topExtent
- // for > 1.0.9, not doing this anymore.
- // instead using getAscent() and getDescent() values for these cases.
-// if ((ascent == 0) && (descent == 0)) {
-// //for (int i = 0; i < charCount; i++) {
-// for (Glyph glyph : glyphs) {
-// char cc = (char) glyph.value;
-// //char cc = (char) glyphs[i].value;
-// if (Character.isWhitespace(cc) ||
-// (cc == '\u00A0') || (cc == '\u2007') || (cc == '\u202F')) {
-// continue;
-// }
-// if (glyph.topExtent > ascent) {
-// ascent = glyph.topExtent;
-// }
-// int d = -glyph.topExtent + glyph.height;
-// if (d > descent) {
-// descent = d;
-// }
-// }
-// }
- }
-
- // If not already created, just create these two characters to calculate
- // the ascent and descent values for the font. This was tested to only
- // require 5-10 ms on a 2.4 GHz MacBook Pro.
- // In versions 1.0.9 and earlier, fonts that could not display d or p
- // used the max up/down values as calculated by looking through the font.
- // That's no longer valid with the auto-generating fonts, so we'll just
- // use getAscent() and getDescent() in such (minor) cases.
- if (ascent == 0) {
- if (font.canDisplay('d')) {
- new Glyph('d');
- } else {
- ascent = lazyMetrics.getAscent();
- }
- }
- if (descent == 0) {
- if (font.canDisplay('p')) {
- new Glyph('p');
- } else {
- descent = lazyMetrics.getDescent();
- }
- }
- }
-
-
- /**
- * Adds an additional parameter that indicates the font came from a file,
- * not a built-in OS font.
- */
- public PFont(Font font, boolean smooth, char charset[], boolean stream) {
- this(font, smooth, charset);
- this.stream = stream;
- }
-
-
- public PFont(InputStream input) throws IOException {
- DataInputStream is = new DataInputStream(input);
-
- // number of character images stored in this font
- glyphCount = is.readInt();
-
- // used to be the bitCount, but now used for version number.
- // version 8 is any font before 69, so 9 is anything from 83+
- // 9 was buggy so gonna increment to 10.
- int version = is.readInt();
-
- // this was formerly ignored, now it's the actual font size
- //mbox = is.readInt();
- size = is.readInt();
-
- // this was formerly mboxY, the one that was used
- // this will make new fonts downward compatible
- is.readInt(); // ignore the other mbox attribute
-
- ascent = is.readInt(); // formerly baseHt (zero/ignored)
- descent = is.readInt(); // formerly ignored struct padding
-
- // allocate enough space for the character info
- glyphs = new Glyph[glyphCount];
-
- ascii = new int[128];
- Arrays.fill(ascii, -1);
-
- // read the information about the individual characters
- for (int i = 0; i < glyphCount; i++) {
- Glyph glyph = new Glyph(is);
- // cache locations of the ascii charset
- if (glyph.value < 128) {
- ascii[glyph.value] = i;
- }
- glyphs[i] = glyph;
- }
-
- // not a roman font, so throw an error and ask to re-build.
- // that way can avoid a bunch of error checking hacks in here.
- if ((ascent == 0) && (descent == 0)) {
- throw new RuntimeException("Please use \"Create Font\" to " +
- "re-create this font.");
- }
-
- for (Glyph glyph : glyphs) {
- glyph.readBitmap(is);
- }
-
- if (version >= 10) { // includes the font name at the end of the file
- name = is.readUTF();
- psname = is.readUTF();
- }
- if (version == 11) {
- smooth = is.readBoolean();
- }
- }
-
-
- /**
- * Write this PFont to an OutputStream.
- *
- * This is used by the Create Font tool, or whatever anyone else dreams
- * up for messing with fonts themselves.
- *
- * It is assumed that the calling class will handle closing
- * the stream when finished.
- */
- public void save(OutputStream output) throws IOException {
- DataOutputStream os = new DataOutputStream(output);
-
- os.writeInt(glyphCount);
-
- if ((name == null) || (psname == null)) {
- name = "";
- psname = "";
- }
-
- os.writeInt(11); // formerly numBits, now used for version number
- os.writeInt(size); // formerly mboxX (was 64, now 48)
- os.writeInt(0); // formerly mboxY, now ignored
- os.writeInt(ascent); // formerly baseHt (was ignored)
- os.writeInt(descent); // formerly struct padding for c version
-
- for (int i = 0; i < glyphCount; i++) {
- glyphs[i].writeHeader(os);
- }
-
- for (int i = 0; i < glyphCount; i++) {
- glyphs[i].writeBitmap(os);
- }
-
- // version 11
- os.writeUTF(name);
- os.writeUTF(psname);
- os.writeBoolean(smooth);
-
- os.flush();
- }
-
-
- /**
- * Create a new glyph, and add the character to the current font.
- * @param c character to create an image for.
- */
- protected void addGlyph(char c) {
- Glyph glyph = new Glyph(c);
-
- if (glyphCount == glyphs.length) {
- glyphs = (Glyph[]) PApplet.expand(glyphs);
- }
- if (glyphCount == 0) {
- glyphs[glyphCount] = glyph;
- if (glyph.value < 128) {
- ascii[glyph.value] = 0;
- }
-
- } else if (glyphs[glyphCount-1].value < glyph.value) {
- glyphs[glyphCount] = glyph;
- if (glyph.value < 128) {
- ascii[glyph.value] = glyphCount;
- }
-
- } else {
- for (int i = 0; i < glyphCount; i++) {
- if (glyphs[i].value > c) {
- for (int j = glyphCount; j > i; --j) {
- glyphs[j] = glyphs[j-1];
- if (glyphs[j].value < 128) {
- ascii[glyphs[j].value] = j;
- }
- }
- glyphs[i] = glyph;
- // cache locations of the ascii charset
- if (c < 128) ascii[c] = i;
- break;
- }
- }
- }
- glyphCount++;
- }
-
-
- public String getName() {
- return name;
- }
-
-
- public String getPostScriptName() {
- return psname;
- }
-
-
- /**
- * Set the native complement of this font.
- */
- public void setFont(Font font) {
- this.font = font;
- }
-
-
- /**
- * Return the native java.awt.Font associated with this PFont (if any).
- */
- public Font getFont() {
-// if (font == null && !fontSearched) {
-// font = findFont();
-// }
- return font;
- }
-
-
- public boolean isStream() {
- return stream;
- }
-
-
- /**
- * Attempt to find the native version of this font.
- * (Public so that it can be used by OpenGL or other renderers.)
- */
- public Font findFont() {
- if (font == null) {
- if (!fontSearched) {
- // this font may or may not be installed
- font = new Font(name, Font.PLAIN, size);
- // if the ps name matches, then we're in fine shape
- if (!font.getPSName().equals(psname)) {
- // on osx java 1.4 (not 1.3.. ugh), you can specify the ps name
- // of the font, so try that in case this .vlw font was created on pc
- // and the name is different, but the ps name is found on the
- // java 1.4 mac that's currently running this sketch.
- font = new Font(psname, Font.PLAIN, size);
- }
- // check again, and if still bad, screw em
- if (!font.getPSName().equals(psname)) {
- font = null;
- }
- fontSearched = true;
- }
- }
- return font;
- }
-
-
- public Glyph getGlyph(char c) {
- int index = index(c);
- return (index == -1) ? null : glyphs[index];
- }
-
-
- /**
- * Get index for the character.
- * @return index into arrays or -1 if not found
- */
- protected int index(char c) {
- if (lazy) {
- int index = indexActual(c);
- if (index != -1) {
- return index;
- }
- if (font.canDisplay(c)) {
- // create the glyph
- addGlyph(c);
- // now where did i put that?
- return indexActual(c);
-
- } else {
- return -1;
- }
-
- } else {
- return indexActual(c);
- }
- }
-
-
- protected int indexActual(char c) {
- // degenerate case, but the find function will have trouble
- // if there are somehow zero chars in the lookup
- //if (value.length == 0) return -1;
- if (glyphCount == 0) return -1;
-
- // quicker lookup for the ascii fellers
- if (c < 128) return ascii[c];
-
- // some other unicode char, hunt it out
- //return index_hunt(c, 0, value.length-1);
- return indexHunt(c, 0, glyphCount-1);
- }
-
-
- protected int indexHunt(int c, int start, int stop) {
- int pivot = (start + stop) / 2;
-
- // if this is the char, then return it
- if (c == glyphs[pivot].value) return pivot;
-
- // char doesn't exist, otherwise would have been the pivot
- //if (start == stop) return -1;
- if (start >= stop) return -1;
-
- // if it's in the lower half, continue searching that
- if (c < glyphs[pivot].value) return indexHunt(c, start, pivot-1);
-
- // if it's in the upper half, continue there
- return indexHunt(c, pivot+1, stop);
- }
-
-
- /**
- * Currently un-implemented for .vlw fonts,
- * but honored for layout in case subclasses use it.
- */
- public float kern(char a, char b) {
- return 0;
- }
-
-
- /**
- * Returns the ascent of this font from the baseline.
- * The value is based on a font of size 1.
- */
- public float ascent() {
- return ((float) ascent / (float) size);
- }
-
-
- /**
- * Returns how far this font descends from the baseline.
- * The value is based on a font size of 1.
- */
- public float descent() {
- return ((float) descent / (float) size);
- }
-
-
- /**
- * Width of this character for a font of size 1.
- */
- public float width(char c) {
- if (c == 32) return width('i');
-
- int cc = index(c);
- if (cc == -1) return 0;
-
- return ((float) glyphs[cc].setWidth / (float) size);
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- static final char[] EXTRA_CHARS = {
- 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087,
- 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x008D, 0x008E, 0x008F,
- 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097,
- 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E, 0x009F,
- 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,
- 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,
- 0x00B0, 0x00B1, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x00BA,
- 0x00BB, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5,
- 0x00C6, 0x00C7, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD,
- 0x00CE, 0x00CF, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6,
- 0x00D7, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DF,
- 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7,
- 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF,
- 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8,
- 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FF, 0x0102, 0x0103,
- 0x0104, 0x0105, 0x0106, 0x0107, 0x010C, 0x010D, 0x010E, 0x010F,
- 0x0110, 0x0111, 0x0118, 0x0119, 0x011A, 0x011B, 0x0131, 0x0139,
- 0x013A, 0x013D, 0x013E, 0x0141, 0x0142, 0x0143, 0x0144, 0x0147,
- 0x0148, 0x0150, 0x0151, 0x0152, 0x0153, 0x0154, 0x0155, 0x0158,
- 0x0159, 0x015A, 0x015B, 0x015E, 0x015F, 0x0160, 0x0161, 0x0162,
- 0x0163, 0x0164, 0x0165, 0x016E, 0x016F, 0x0170, 0x0171, 0x0178,
- 0x0179, 0x017A, 0x017B, 0x017C, 0x017D, 0x017E, 0x0192, 0x02C6,
- 0x02C7, 0x02D8, 0x02D9, 0x02DA, 0x02DB, 0x02DC, 0x02DD, 0x03A9,
- 0x03C0, 0x2013, 0x2014, 0x2018, 0x2019, 0x201A, 0x201C, 0x201D,
- 0x201E, 0x2020, 0x2021, 0x2022, 0x2026, 0x2030, 0x2039, 0x203A,
- 0x2044, 0x20AC, 0x2122, 0x2202, 0x2206, 0x220F, 0x2211, 0x221A,
- 0x221E, 0x222B, 0x2248, 0x2260, 0x2264, 0x2265, 0x25CA, 0xF8FF,
- 0xFB01, 0xFB02
- };
-
-
- /**
- * The default Processing character set.
- *
- * This is the union of the Mac Roman and Windows ANSI (CP1250)
- * character sets. ISO 8859-1 Latin 1 is Unicode characters 0x80 -> 0xFF,
- * and would seem a good standard, but in practice, most P5 users would
- * rather have characters that they expect from their platform's fonts.
- *
- * This is more of an interim solution until a much better
- * font solution can be determined. (i.e. create fonts on
- * the fly from some sort of vector format).
- *
- * Not that I expect that to happen.
- */
- static public char[] CHARSET;
- static {
- CHARSET = new char[126-33+1 + EXTRA_CHARS.length];
- int index = 0;
- for (int i = 33; i <= 126; i++) {
- CHARSET[index++] = (char)i;
- }
- for (int i = 0; i < EXTRA_CHARS.length; i++) {
- CHARSET[index++] = EXTRA_CHARS[i];
- }
- };
-
-
- /**
- * Get a list of the fonts installed on the system that can be used
- * by Java. Not all fonts can be used in Java, in fact it's mostly
- * only TrueType fonts. OpenType fonts with CFF data such as Adobe's
- * OpenType fonts seem to have trouble (even though they're sort of
- * TrueType fonts as well, or may have a .ttf extension). Regular
- * PostScript fonts seem to work OK, however.
- *
- * Not recommended for use in applets, but this is implemented
- * in PFont because the Java methods to access this information
- * have changed between 1.1 and 1.4, and the 1.4 method is
- * typical of the sort of undergraduate-level over-abstraction
- * that the seems to have made its way into the Java API after 1.1.
- */
- static public String[] list() {
- loadFonts();
- String list[] = new String[fonts.length];
- for (int i = 0; i < list.length; i++) {
- list[i] = fonts[i].getName();
- }
- return list;
- }
-
-
- static public void loadFonts() {
- if (fonts == null) {
- GraphicsEnvironment ge =
- GraphicsEnvironment.getLocalGraphicsEnvironment();
- fonts = ge.getAllFonts();
- if (PApplet.platform == PConstants.MACOSX) {
- fontDifferent = new HashMap();
- for (Font font : fonts) {
- // getName() returns the PostScript name on OS X 10.6 w/ Java 6.
- fontDifferent.put(font.getName(), font);
- //fontDifferent.put(font.getPSName(), font);
- }
- }
- }
- }
-
-
- /**
- * Starting with Java 1.5, Apple broke the ability to specify most fonts.
- * This bug was filed years ago as #4769141 at bugreporter.apple.com. More:
- * Bug 407.
- */
- static public Font findFont(String name) {
- loadFonts();
- if (PApplet.platform == PConstants.MACOSX) {
- Font maybe = fontDifferent.get(name);
- if (maybe != null) {
- return maybe;
- }
-// for (int i = 0; i < fonts.length; i++) {
-// if (name.equals(fonts[i].getName())) {
-// return fonts[i];
-// }
-// }
- }
- return new Font(name, Font.PLAIN, 1);
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- /**
- * A single character, and its visage.
- */
- public class Glyph {
- PImage image;
- int value;
- int height;
- int width;
- int setWidth;
- int topExtent;
- int leftExtent;
-
-
- protected Glyph() {
- // used when reading from a stream or for subclasses
- }
-
-
- protected Glyph(DataInputStream is) throws IOException {
- readHeader(is);
- }
-
-
- protected void readHeader(DataInputStream is) throws IOException {
- value = is.readInt();
- height = is.readInt();
- width = is.readInt();
- setWidth = is.readInt();
- topExtent = is.readInt();
- leftExtent = is.readInt();
-
- // pointer from a struct in the c version, ignored
- is.readInt();
-
- // the values for getAscent() and getDescent() from FontMetrics
- // seem to be way too large.. perhaps they're the max?
- // as such, use a more traditional marker for ascent/descent
- if (value == 'd') {
- if (ascent == 0) ascent = topExtent;
- }
- if (value == 'p') {
- if (descent == 0) descent = -topExtent + height;
- }
- }
-
-
- protected void writeHeader(DataOutputStream os) throws IOException {
- os.writeInt(value);
- os.writeInt(height);
- os.writeInt(width);
- os.writeInt(setWidth);
- os.writeInt(topExtent);
- os.writeInt(leftExtent);
- os.writeInt(0); // padding
- }
-
-
- protected void readBitmap(DataInputStream is) throws IOException {
- image = new PImage(width, height, ALPHA);
- int bitmapSize = width * height;
-
- byte[] temp = new byte[bitmapSize];
- is.readFully(temp);
-
- // convert the bitmap to an alpha channel
- int w = width;
- int h = height;
- int[] pixels = image.pixels;
- for (int y = 0; y < h; y++) {
- for (int x = 0; x < w; x++) {
- pixels[y * width + x] = temp[y*w + x] & 0xff;
-// System.out.print((image.pixels[y*64+x] > 128) ? "*" : ".");
- }
-// System.out.println();
- }
-// System.out.println();
- }
-
-
- protected void writeBitmap(DataOutputStream os) throws IOException {
- int[] pixels = image.pixels;
- for (int y = 0; y < height; y++) {
- for (int x = 0; x < width; x++) {
- os.write(pixels[y * width + x] & 0xff);
- }
- }
- }
-
-
- protected Glyph(char c) {
- int mbox3 = size * 3;
- lazyGraphics.setColor(Color.white);
- lazyGraphics.fillRect(0, 0, mbox3, mbox3);
- lazyGraphics.setColor(Color.black);
- lazyGraphics.drawString(String.valueOf(c), size, size * 2);
-
- WritableRaster raster = lazyImage.getRaster();
- raster.getDataElements(0, 0, mbox3, mbox3, lazySamples);
-
- int minX = 1000, maxX = 0;
- int minY = 1000, maxY = 0;
- boolean pixelFound = false;
-
- for (int y = 0; y < mbox3; y++) {
- for (int x = 0; x < mbox3; x++) {
- int sample = lazySamples[y * mbox3 + x] & 0xff;
- if (sample != 255) {
- if (x < minX) minX = x;
- if (y < minY) minY = y;
- if (x > maxX) maxX = x;
- if (y > maxY) maxY = y;
- pixelFound = true;
- }
- }
- }
-
- if (!pixelFound) {
- minX = minY = 0;
- maxX = maxY = 0;
- // this will create a 1 pixel white (clear) character..
- // maybe better to set one to -1 so nothing is added?
- }
-
- value = c;
- height = (maxY - minY) + 1;
- width = (maxX - minX) + 1;
- setWidth = lazyMetrics.charWidth(c);
-
- // offset from vertical location of baseline
- // of where the char was drawn (size*2)
- topExtent = size*2 - minY;
-
- // offset from left of where coord was drawn
- leftExtent = minX - size;
-
- image = new PImage(width, height, ALPHA);
- int[] pixels = image.pixels;
- for (int y = minY; y <= maxY; y++) {
- for (int x = minX; x <= maxX; x++) {
- int val = 255 - (lazySamples[y * mbox3 + x] & 0xff);
- int pindex = (y - minY) * width + (x - minX);
- pixels[pindex] = val;
- }
- }
-
- // replace the ascent/descent values with something.. err, decent.
- if (value == 'd') {
- if (ascent == 0) ascent = topExtent;
- }
- if (value == 'p') {
- if (descent == 0) descent = -topExtent + height;
- }
- }
- }
-}
diff --git a/core/src/processing/core/PGraphics.java b/core/src/processing/core/PGraphics.java
deleted file mode 100644
index 9d50cdedd15..00000000000
--- a/core/src/processing/core/PGraphics.java
+++ /dev/null
@@ -1,5707 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2004-09 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.*;
-import java.util.HashMap;
-
-
-/**
- * Main graphics and rendering context, as well as the base API implementation for processing "core".
- * Use this class if you need to draw into an off-screen graphics buffer.
- * A PGraphics object can be constructed with the createGraphics() function.
- * The beginDraw() and endDraw() methods (see above example) are necessary to set up the buffer and to finalize it.
- * The fields and methods for this class are extensive;
- * for a complete list visit the developer's reference: http://dev.processing.org/reference/core/
- * =advanced
- * Main graphics and rendering context, as well as the base API implementation.
- *
- *
Subclassing and initializing PGraphics objects
- * Starting in release 0149, subclasses of PGraphics are handled differently.
- * The constructor for subclasses takes no parameters, instead a series of
- * functions are called by the hosting PApplet to specify its attributes.
- *
- *
setParent(PApplet) - is called to specify the parent PApplet.
- *
setPrimary(boolean) - called with true if this PGraphics will be the
- * primary drawing surface used by the sketch, or false if not.
- *
setPath(String) - called when the renderer needs a filename or output
- * path, such as with the PDF or DXF renderers.
- *
setSize(int, int) - this is called last, at which point it's safe for
- * the renderer to complete its initialization routine.
- *
- * The functions were broken out because of the growing number of parameters
- * such as these that might be used by a renderer, yet with the exception of
- * setSize(), it's not clear which will be necessary. So while the size could
- * be passed in to the constructor instead of a setSize() function, a function
- * would still be needed that would notify the renderer that it was time to
- * finish its initialization. Thus, setSize() simply does both.
- *
- *
Know your rights: public vs. private methods
- * Methods that are protected are often subclassed by other renderers, however
- * they are not set 'public' because they shouldn't be part of the user-facing
- * public API accessible from PApplet. That is, we don't want sketches calling
- * textModeCheck() or vertexTexture() directly.
- *
- *
Handling warnings and exceptions
- * Methods that are unavailable generally show a warning, unless their lack of
- * availability will soon cause another exception. For instance, if a method
- * like getMatrix() returns null because it is unavailable, an exception will
- * be thrown stating that the method is unavailable, rather than waiting for
- * the NullPointerException that will occur when the sketch tries to use that
- * method. As of release 0149, warnings will only be shown once, and exceptions
- * have been changed to warnings where possible.
- *
- *
Using xxxxImpl() for subclassing smoothness
- * The xxxImpl() methods are generally renderer-specific handling for some
- * subset if tasks for a particular function (vague enough for you?) For
- * instance, imageImpl() handles drawing an image whose x/y/w/h and u/v coords
- * have been specified, and screen placement (independent of imageMode) has
- * been determined. There's no point in all renderers implementing the
- * if (imageMode == BLAH) placement/sizing logic, so that's handled
- * by PGraphics, which then calls imageImpl() once all that is figured out.
- *
- *
His brother PImage
- * PGraphics subclasses PImage so that it can be drawn and manipulated in a
- * similar fashion. As such, many methods are inherited from PGraphics,
- * though many are unavailable: for instance, resize() is not likely to be
- * implemented; the same goes for mask(), depending on the situation.
- *
- *
What's in PGraphics, what ain't
- * For the benefit of subclasses, as much as possible has been placed inside
- * PGraphics. For instance, bezier interpolation code and implementations of
- * the strokeCap() method (that simply sets the strokeCap variable) are
- * handled here. Features that will vary widely between renderers are located
- * inside the subclasses themselves. For instance, all matrix handling code
- * is per-renderer: Java 2D uses its own AffineTransform, P2D uses a PMatrix2D,
- * and PGraphics3D needs to keep continually update forward and reverse
- * transformations. A proper (future) OpenGL implementation will have all its
- * matrix madness handled by the card. Lighting also falls under this
- * category, however the base material property settings (emissive, specular,
- * et al.) are handled in PGraphics because they use the standard colorMode()
- * logic. Subclasses should override methods like emissiveFromCalc(), which
- * is a point where a valid color has been defined internally, and can be
- * applied in some manner based on the calcXxxx values.
- *
- *
What's in the PGraphics documentation, what ain't
- * Some things are noted here, some things are not. For public API, always
- * refer to the reference
- * on Processing.org for proper explanations. No attempt has been made to
- * keep the javadoc up to date or complete. It's an enormous task for
- * which we simply do not have the time. That is, it's not something that
- * to be done once—it's a matter of keeping the multiple references
- * synchronized (to say nothing of the translation issues), while targeting
- * them for their separate audiences. Ouch.
- *
- * We're working right now on synchronizing the two references, so the website reference
- * is generated from the javadoc comments. Yay.
- *
- * @webref rendering
- * @instanceName graphics any object of the type PGraphics
- * @usage Web & Application
- * @see processing.core.PApplet#createGraphics(int, int, String)
- */
-public class PGraphics extends PImage implements PConstants {
-
- // ........................................................
-
- // width and height are already inherited from PImage
-
-
- /// width minus one (useful for many calculations)
- protected int width1;
-
- /// height minus one (useful for many calculations)
- protected int height1;
-
- /// width * height (useful for many calculations)
- public int pixelCount;
-
- /// true if smoothing is enabled (read-only)
- public boolean smooth = false;
-
- // ........................................................
-
- /// true if defaults() has been called a first time
- protected boolean settingsInited;
-
- /// set to a PGraphics object being used inside a beginRaw/endRaw() block
- protected PGraphics raw;
-
- // ........................................................
-
- /** path to the file being saved for this renderer (if any) */
- protected String path;
-
- /**
- * true if this is the main drawing surface for a particular sketch.
- * This would be set to false for an offscreen buffer or if it were
- * created any other way than size(). When this is set, the listeners
- * are also added to the sketch.
- */
- protected boolean primarySurface;
-
- // ........................................................
-
- /**
- * Array of hint[] items. These are hacks to get around various
- * temporary workarounds inside the environment.
- *
- * Note that this array cannot be static, as a hint() may result in a
- * runtime change specific to a renderer. For instance, calling
- * hint(DISABLE_DEPTH_TEST) has to call glDisable() right away on an
- * instance of PGraphicsOpenGL.
- *
- * The hints[] array is allocated early on because it might
- * be used inside beginDraw(), allocate(), etc.
- */
- protected boolean[] hints = new boolean[HINT_COUNT];
-
-
- ////////////////////////////////////////////////////////////
-
- // STYLE PROPERTIES
-
- // Also inherits imageMode() and smooth() (among others) from PImage.
-
- /** The current colorMode */
- public int colorMode; // = RGB;
-
- /** Max value for red (or hue) set by colorMode */
- public float colorModeX; // = 255;
-
- /** Max value for green (or saturation) set by colorMode */
- public float colorModeY; // = 255;
-
- /** Max value for blue (or value) set by colorMode */
- public float colorModeZ; // = 255;
-
- /** Max value for alpha set by colorMode */
- public float colorModeA; // = 255;
-
- /** True if colors are not in the range 0..1 */
- boolean colorModeScale; // = true;
-
- /** True if colorMode(RGB, 255) */
- boolean colorModeDefault; // = true;
-
- // ........................................................
-
- // Tint color for images
-
- /**
- * True if tint() is enabled (read-only).
- *
- * Using tint/tintColor seems a better option for naming than
- * tintEnabled/tint because the latter seems ugly, even though
- * g.tint as the actual color seems a little more intuitive,
- * it's just that g.tintEnabled is even more unintuitive.
- * Same goes for fill and stroke, et al.
- */
- public boolean tint;
-
- /** tint that was last set (read-only) */
- public int tintColor;
-
- protected boolean tintAlpha;
- protected float tintR, tintG, tintB, tintA;
- protected int tintRi, tintGi, tintBi, tintAi;
-
- // ........................................................
-
- // Fill color
-
- /** true if fill() is enabled, (read-only) */
- public boolean fill;
-
- /** fill that was last set (read-only) */
- public int fillColor = 0xffFFFFFF;
-
- protected boolean fillAlpha;
- protected float fillR, fillG, fillB, fillA;
- protected int fillRi, fillGi, fillBi, fillAi;
-
- // ........................................................
-
- // Stroke color
-
- /** true if stroke() is enabled, (read-only) */
- public boolean stroke;
-
- /** stroke that was last set (read-only) */
- public int strokeColor = 0xff000000;
-
- protected boolean strokeAlpha;
- protected float strokeR, strokeG, strokeB, strokeA;
- protected int strokeRi, strokeGi, strokeBi, strokeAi;
-
- // ........................................................
-
- // Additional stroke properties
-
- static protected final float DEFAULT_STROKE_WEIGHT = 1;
- static protected final int DEFAULT_STROKE_JOIN = MITER;
- static protected final int DEFAULT_STROKE_CAP = ROUND;
-
- /**
- * Last value set by strokeWeight() (read-only). This has a default
- * setting, rather than fighting with renderers about whether that
- * renderer supports thick lines.
- */
- public float strokeWeight = DEFAULT_STROKE_WEIGHT;
-
- /**
- * Set by strokeJoin() (read-only). This has a default setting
- * so that strokeJoin() need not be called by defaults,
- * because subclasses may not implement it (i.e. PGraphicsGL)
- */
- public int strokeJoin = DEFAULT_STROKE_JOIN;
-
- /**
- * Set by strokeCap() (read-only). This has a default setting
- * so that strokeCap() need not be called by defaults,
- * because subclasses may not implement it (i.e. PGraphicsGL)
- */
- public int strokeCap = DEFAULT_STROKE_CAP;
-
- // ........................................................
-
- // Shape placement properties
-
- // imageMode() is inherited from PImage
-
- /** The current rect mode (read-only) */
- public int rectMode;
-
- /** The current ellipse mode (read-only) */
- public int ellipseMode;
-
- /** The current shape alignment mode (read-only) */
- public int shapeMode;
-
- /** The current image alignment (read-only) */
- public int imageMode = CORNER;
-
- // ........................................................
-
- // Text and font properties
-
- /** The current text font (read-only) */
- public PFont textFont;
-
- /** The current text align (read-only) */
- public int textAlign = LEFT;
-
- /** The current vertical text alignment (read-only) */
- public int textAlignY = BASELINE;
-
- /** The current text mode (read-only) */
- public int textMode = MODEL;
-
- /** The current text size (read-only) */
- public float textSize;
-
- /** The current text leading (read-only) */
- public float textLeading;
-
- // ........................................................
-
- // Material properties
-
-// PMaterial material;
-// PMaterial[] materialStack;
-// int materialStackPointer;
-
- public float ambientR, ambientG, ambientB;
- public float specularR, specularG, specularB;
- public float emissiveR, emissiveG, emissiveB;
- public float shininess;
-
-
- // Style stack
-
- static final int STYLE_STACK_DEPTH = 64;
- PStyle[] styleStack = new PStyle[STYLE_STACK_DEPTH];
- int styleStackDepth;
-
-
- ////////////////////////////////////////////////////////////
-
-
- /** Last background color that was set, zero if an image */
- public int backgroundColor = 0xffCCCCCC;
-
- protected boolean backgroundAlpha;
- protected float backgroundR, backgroundG, backgroundB, backgroundA;
- protected int backgroundRi, backgroundGi, backgroundBi, backgroundAi;
-
- // ........................................................
-
- /**
- * Current model-view matrix transformation of the form m[row][column],
- * which is a "column vector" (as opposed to "row vector") matrix.
- */
-// PMatrix matrix;
-// public float m00, m01, m02, m03;
-// public float m10, m11, m12, m13;
-// public float m20, m21, m22, m23;
-// public float m30, m31, m32, m33;
-
-// static final int MATRIX_STACK_DEPTH = 32;
-// float[][] matrixStack = new float[MATRIX_STACK_DEPTH][16];
-// float[][] matrixInvStack = new float[MATRIX_STACK_DEPTH][16];
-// int matrixStackDepth;
-
- static final int MATRIX_STACK_DEPTH = 32;
-
- // ........................................................
-
- /**
- * Java AWT Image object associated with this renderer. For P2D and P3D,
- * this will be associated with their MemoryImageSource. For PGraphicsJava2D,
- * it will be the offscreen drawing buffer.
- */
- public Image image;
-
- // ........................................................
-
- // internal color for setting/calculating
- protected float calcR, calcG, calcB, calcA;
- protected int calcRi, calcGi, calcBi, calcAi;
- protected int calcColor;
- protected boolean calcAlpha;
-
- /** The last RGB value converted to HSB */
- int cacheHsbKey;
- /** Result of the last conversion to HSB */
- float[] cacheHsbValue = new float[3];
-
- // ........................................................
-
- /**
- * Type of shape passed to beginShape(),
- * zero if no shape is currently being drawn.
- */
- protected int shape;
-
- // vertices
- static final int DEFAULT_VERTICES = 512;
- protected float vertices[][] =
- new float[DEFAULT_VERTICES][VERTEX_FIELD_COUNT];
- protected int vertexCount; // total number of vertices
-
- // ........................................................
-
- protected boolean bezierInited = false;
- public int bezierDetail = 20;
-
- // used by both curve and bezier, so just init here
- protected PMatrix3D bezierBasisMatrix =
- new PMatrix3D(-1, 3, -3, 1,
- 3, -6, 3, 0,
- -3, 3, 0, 0,
- 1, 0, 0, 0);
-
- //protected PMatrix3D bezierForwardMatrix;
- protected PMatrix3D bezierDrawMatrix;
-
- // ........................................................
-
- protected boolean curveInited = false;
- protected int curveDetail = 20;
- public float curveTightness = 0;
- // catmull-rom basis matrix, perhaps with optional s parameter
- protected PMatrix3D curveBasisMatrix;
- protected PMatrix3D curveDrawMatrix;
-
- protected PMatrix3D bezierBasisInverse;
- protected PMatrix3D curveToBezierMatrix;
-
- // ........................................................
-
- // spline vertices
-
- protected float curveVertices[][];
- protected int curveVertexCount;
-
- // ........................................................
-
- // precalculate sin/cos lookup tables [toxi]
- // circle resolution is determined from the actual used radii
- // passed to ellipse() method. this will automatically take any
- // scale transformations into account too
-
- // [toxi 031031]
- // changed table's precision to 0.5 degree steps
- // introduced new vars for more flexible code
- static final protected float sinLUT[];
- static final protected float cosLUT[];
- static final protected float SINCOS_PRECISION = 0.5f;
- static final protected int SINCOS_LENGTH = (int) (360f / SINCOS_PRECISION);
- static {
- sinLUT = new float[SINCOS_LENGTH];
- cosLUT = new float[SINCOS_LENGTH];
- for (int i = 0; i < SINCOS_LENGTH; i++) {
- sinLUT[i] = (float) Math.sin(i * DEG_TO_RAD * SINCOS_PRECISION);
- cosLUT[i] = (float) Math.cos(i * DEG_TO_RAD * SINCOS_PRECISION);
- }
- }
-
- // ........................................................
-
- /** The current font if a Java version of it is installed */
- //protected Font textFontNative;
-
- /** Metrics for the current native Java font */
- //protected FontMetrics textFontNativeMetrics;
-
- /** Last text position, because text often mixed on lines together */
- protected float textX, textY, textZ;
-
- /**
- * Internal buffer used by the text() functions
- * because the String object is slow
- */
- protected char[] textBuffer = new char[8 * 1024];
- protected char[] textWidthBuffer = new char[8 * 1024];
-
- protected int textBreakCount;
- protected int[] textBreakStart;
- protected int[] textBreakStop;
-
- // ........................................................
-
- public boolean edge = true;
-
- // ........................................................
-
- /// normal calculated per triangle
- static protected final int NORMAL_MODE_AUTO = 0;
- /// one normal manually specified per shape
- static protected final int NORMAL_MODE_SHAPE = 1;
- /// normals specified for each shape vertex
- static protected final int NORMAL_MODE_VERTEX = 2;
-
- /// Current mode for normals, one of AUTO, SHAPE, or VERTEX
- protected int normalMode;
-
- /// Keep track of how many calls to normal, to determine the mode.
- //protected int normalCount;
-
- /** Current normal vector. */
- public float normalX, normalY, normalZ;
-
- // ........................................................
-
- /**
- * Sets whether texture coordinates passed to
- * vertex() calls will be based on coordinates that are
- * based on the IMAGE or NORMALIZED.
- */
- public int textureMode;
-
- /**
- * Current horizontal coordinate for texture, will always
- * be between 0 and 1, even if using textureMode(IMAGE).
- */
- public float textureU;
-
- /** Current vertical coordinate for texture, see above. */
- public float textureV;
-
- /** Current image being used as a texture */
- public PImage textureImage;
-
- // ........................................................
-
- // [toxi031031] new & faster sphere code w/ support flexibile resolutions
- // will be set by sphereDetail() or 1st call to sphere()
- float sphereX[], sphereY[], sphereZ[];
-
- /// Number of U steps (aka "theta") around longitudinally spanning 2*pi
- public int sphereDetailU = 0;
- /// Number of V steps (aka "phi") along latitudinally top-to-bottom spanning pi
- public int sphereDetailV = 0;
-
-
- //////////////////////////////////////////////////////////////
-
- // INTERNAL
-
-
- /**
- * Constructor for the PGraphics object. Use this to ensure that
- * the defaults get set properly. In a subclass, use this(w, h)
- * as the first line of a subclass' constructor to properly set
- * the internal fields and defaults.
- *
- */
- public PGraphics() {
- }
-
-
- public void setParent(PApplet parent) { // ignore
- this.parent = parent;
- }
-
-
- /**
- * Set (or unset) this as the main drawing surface. Meaning that it can
- * safely be set to opaque (and given a default gray background), or anything
- * else that goes along with that.
- */
- public void setPrimary(boolean primary) { // ignore
- this.primarySurface = primary;
-
- // base images must be opaque (for performance and general
- // headache reasons.. argh, a semi-transparent opengl surface?)
- // use createGraphics() if you want a transparent surface.
- if (primarySurface) {
- format = RGB;
- }
- }
-
-
- public void setPath(String path) { // ignore
- this.path = path;
- }
-
-
- /**
- * The final step in setting up a renderer, set its size of this renderer.
- * This was formerly handled by the constructor, but instead it's been broken
- * out so that setParent/setPrimary/setPath can be handled differently.
- *
- * Important that this is ignored by preproc.pl because otherwise it will
- * override setSize() in PApplet/Applet/Component, which will 1) not call
- * super.setSize(), and 2) will cause the renderer to be resized from the
- * event thread (EDT), causing a nasty crash as it collides with the
- * animation thread.
- */
- public void setSize(int w, int h) { // ignore
- width = w;
- height = h;
- width1 = width - 1;
- height1 = height - 1;
-
- allocate();
- reapplySettings();
- }
-
-
- /**
- * Allocate memory for this renderer. Generally will need to be implemented
- * for all renderers.
- */
- protected void allocate() { }
-
-
- /**
- * Handle any takedown for this graphics context.
- *
- * This is called when a sketch is shut down and this renderer was
- * specified using the size() command, or inside endRecord() and
- * endRaw(), in order to shut things off.
- */
- public void dispose() { // ignore
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // FRAME
-
-
- /**
- * Some renderers have requirements re: when they are ready to draw.
- */
- public boolean canDraw() { // ignore
- return true;
- }
-
-
- /**
- * Sets the default properties for a PGraphics object. It should be called before anything is drawn into the object.
- * =advanced
- *
- * When creating your own PGraphics, you should call this before
- * drawing anything.
- *
- * @webref
- * @brief Sets up the rendering context
- */
- public void beginDraw() { // ignore
- }
-
-
- /**
- * Finalizes the rendering of a PGraphics object so that it can be shown on screen.
- * =advanced
- *
- * When creating your own PGraphics, you should call this when
- * you're finished drawing.
- *
- * @webref
- * @brief Finalizes the renderering context
- */
- public void endDraw() { // ignore
- }
-
-
- public void flush() {
- // no-op, mostly for P3D to write sorted stuff
- }
-
-
- protected void checkSettings() {
- if (!settingsInited) defaultSettings();
- }
-
-
- /**
- * Set engine's default values. This has to be called by PApplet,
- * somewhere inside setup() or draw() because it talks to the
- * graphics buffer, meaning that for subclasses like OpenGL, there
- * needs to be a valid graphics context to mess with otherwise
- * you'll get some good crashing action.
- *
- * This is currently called by checkSettings(), during beginDraw().
- */
- protected void defaultSettings() { // ignore
-// System.out.println("PGraphics.defaultSettings() " + width + " " + height);
-
- noSmooth(); // 0149
-
- colorMode(RGB, 255);
- fill(255);
- stroke(0);
-
- // as of 0178, no longer relying on local versions of the variables
- // being set, because subclasses may need to take extra action.
- strokeWeight(DEFAULT_STROKE_WEIGHT);
- strokeJoin(DEFAULT_STROKE_JOIN);
- strokeCap(DEFAULT_STROKE_CAP);
-
- // init shape stuff
- shape = 0;
-
- // init matrices (must do before lights)
- //matrixStackDepth = 0;
-
- rectMode(CORNER);
- ellipseMode(DIAMETER);
-
- // no current font
- textFont = null;
- textSize = 12;
- textLeading = 14;
- textAlign = LEFT;
- textMode = MODEL;
-
- // if this fella is associated with an applet, then clear its background.
- // if it's been created by someone else through createGraphics,
- // they have to call background() themselves, otherwise everything gets
- // a gray background (when just a transparent surface or an empty pdf
- // is what's desired).
- // this background() call is for the Java 2D and OpenGL renderers.
- if (primarySurface) {
- //System.out.println("main drawing surface bg " + getClass().getName());
- background(backgroundColor);
- }
-
- settingsInited = true;
- // defaultSettings() overlaps reapplySettings(), don't do both
- //reapplySettings = false;
- }
-
-
- /**
- * Re-apply current settings. Some methods, such as textFont(), require that
- * their methods be called (rather than simply setting the textFont variable)
- * because they affect the graphics context, or they require parameters from
- * the context (e.g. getting native fonts for text).
- *
- * This will only be called from an allocate(), which is only called from
- * size(), which is safely called from inside beginDraw(). And it cannot be
- * called before defaultSettings(), so we should be safe.
- */
- protected void reapplySettings() {
-// System.out.println("attempting reapplySettings()");
- if (!settingsInited) return; // if this is the initial setup, no need to reapply
-
-// System.out.println(" doing reapplySettings");
-// new Exception().printStackTrace(System.out);
-
- colorMode(colorMode, colorModeX, colorModeY, colorModeZ);
- if (fill) {
-// PApplet.println(" fill " + PApplet.hex(fillColor));
- fill(fillColor);
- } else {
- noFill();
- }
- if (stroke) {
- stroke(strokeColor);
-
- // The if() statements should be handled inside the functions,
- // otherwise an actual reset/revert won't work properly.
- //if (strokeWeight != DEFAULT_STROKE_WEIGHT) {
- strokeWeight(strokeWeight);
- //}
-// if (strokeCap != DEFAULT_STROKE_CAP) {
- strokeCap(strokeCap);
-// }
-// if (strokeJoin != DEFAULT_STROKE_JOIN) {
- strokeJoin(strokeJoin);
-// }
- } else {
- noStroke();
- }
- if (tint) {
- tint(tintColor);
- } else {
- noTint();
- }
- if (smooth) {
- smooth();
- } else {
- // Don't bother setting this, cuz it'll anger P3D.
- noSmooth();
- }
- if (textFont != null) {
-// System.out.println(" textFont in reapply is " + textFont);
- // textFont() resets the leading, so save it in case it's changed
- float saveLeading = textLeading;
- textFont(textFont, textSize);
- textLeading(saveLeading);
- }
- textMode(textMode);
- textAlign(textAlign, textAlignY);
- background(backgroundColor);
-
- //reapplySettings = false;
- }
-
-
- //////////////////////////////////////////////////////////////
-
- // HINTS
-
- /**
- * 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 (which > 0) {
- hints[which] = true;
- } else {
- hints[-which] = false;
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // VERTEX SHAPES
-
- /**
- * Start a new shape of type POLYGON
- */
- public void beginShape() {
- beginShape(POLYGON);
- }
-
-
- /**
- * Start a new shape.
- *
- * 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) {
- shape = kind;
- }
-
-
- /**
- * Sets whether the upcoming vertex is part of an edge.
- * Equivalent to glEdgeFlag(), for people familiar with OpenGL.
- */
- public void edge(boolean edge) {
- this.edge = edge;
- }
-
-
- /**
- * Sets the current normal vector. Only applies with 3D rendering
- * and inside a beginShape/endShape block.
- *
- * This is for drawing three dimensional shapes and surfaces,
- * allowing you to specify a vector perpendicular to the surface
- * of the shape, which determines how lighting affects it.
- *
- * For the most part, PGraphics3D will attempt to automatically
- * assign normals to shapes, but since that's imperfect,
- * this is a better option when you want more control.
- *
- * For people familiar with OpenGL, this function is basically
- * identical to glNormal3f().
- */
- public void normal(float nx, float ny, float nz) {
- normalX = nx;
- normalY = ny;
- normalZ = nz;
-
- // if drawing a shape and the normal hasn't been set yet,
- // then we need to set the normals for each vertex so far
- if (shape != 0) {
- if (normalMode == NORMAL_MODE_AUTO) {
- // either they set the normals, or they don't [0149]
-// for (int i = vertex_start; i < vertexCount; i++) {
-// vertices[i][NX] = normalX;
-// vertices[i][NY] = normalY;
-// vertices[i][NZ] = normalZ;
-// }
- // One normal per begin/end shape
- normalMode = NORMAL_MODE_SHAPE;
-
- } else if (normalMode == NORMAL_MODE_SHAPE) {
- // a separate normal for each vertex
- normalMode = NORMAL_MODE_VERTEX;
- }
- }
- }
-
-
- /**
- * Set texture mode to either to use coordinates based on the IMAGE
- * (more intuitive for new users) or NORMALIZED (better for advanced chaps)
- */
- public void textureMode(int mode) {
- this.textureMode = mode;
- }
-
-
- /**
- * Set texture image for current shape.
- * Needs to be called between @see beginShape and @see endShape
- *
- * @param image reference to a PImage object
- */
- public void texture(PImage image) {
- textureImage = image;
- }
-
-
- protected void vertexCheck() {
- if (vertexCount == vertices.length) {
- float temp[][] = new float[vertexCount << 1][VERTEX_FIELD_COUNT];
- System.arraycopy(vertices, 0, temp, 0, vertexCount);
- vertices = temp;
- }
- }
-
-
- public void vertex(float x, float y) {
- vertexCheck();
- float[] vertex = vertices[vertexCount];
-
- curveVertexCount = 0;
-
- vertex[X] = x;
- vertex[Y] = y;
-
- vertex[EDGE] = edge ? 1 : 0;
-
-// if (fill) {
-// vertex[R] = fillR;
-// vertex[G] = fillG;
-// vertex[B] = fillB;
-// vertex[A] = fillA;
-// }
- if (fill || textureImage != null) {
- if (textureImage == null) {
- vertex[R] = fillR;
- vertex[G] = fillG;
- vertex[B] = fillB;
- vertex[A] = fillA;
- } else {
- if (tint) {
- vertex[R] = tintR;
- vertex[G] = tintG;
- vertex[B] = tintB;
- vertex[A] = tintA;
- } else {
- vertex[R] = 1;
- vertex[G] = 1;
- vertex[B] = 1;
- vertex[A] = 1;
- }
- }
- }
-
- if (stroke) {
- vertex[SR] = strokeR;
- vertex[SG] = strokeG;
- vertex[SB] = strokeB;
- vertex[SA] = strokeA;
- vertex[SW] = strokeWeight;
- }
-
- if (textureImage != null) {
- vertex[U] = textureU;
- vertex[V] = textureV;
- }
-
- vertexCount++;
- }
-
-
- public void vertex(float x, float y, float z) {
- vertexCheck();
- float[] vertex = vertices[vertexCount];
-
- // only do this if we're using an irregular (POLYGON) shape that
- // will go through the triangulator. otherwise it'll do thinks like
- // disappear in mathematically odd ways
- // http://dev.processing.org/bugs/show_bug.cgi?id=444
- if (shape == POLYGON) {
- if (vertexCount > 0) {
- float pvertex[] = vertices[vertexCount-1];
- if ((Math.abs(pvertex[X] - x) < EPSILON) &&
- (Math.abs(pvertex[Y] - y) < EPSILON) &&
- (Math.abs(pvertex[Z] - z) < EPSILON)) {
- // this vertex is identical, don't add it,
- // because it will anger the triangulator
- return;
- }
- }
- }
-
- // User called vertex(), so that invalidates anything queued up for curve
- // vertices. If this is internally called by curveVertexSegment,
- // then curveVertexCount will be saved and restored.
- curveVertexCount = 0;
-
- vertex[X] = x;
- vertex[Y] = y;
- vertex[Z] = z;
-
- vertex[EDGE] = edge ? 1 : 0;
-
- if (fill || textureImage != null) {
- if (textureImage == null) {
- vertex[R] = fillR;
- vertex[G] = fillG;
- vertex[B] = fillB;
- vertex[A] = fillA;
- } else {
- if (tint) {
- vertex[R] = tintR;
- vertex[G] = tintG;
- vertex[B] = tintB;
- vertex[A] = tintA;
- } else {
- vertex[R] = 1;
- vertex[G] = 1;
- vertex[B] = 1;
- vertex[A] = 1;
- }
- }
-
- vertex[AR] = ambientR;
- vertex[AG] = ambientG;
- vertex[AB] = ambientB;
-
- vertex[SPR] = specularR;
- vertex[SPG] = specularG;
- vertex[SPB] = specularB;
- //vertex[SPA] = specularA;
-
- vertex[SHINE] = shininess;
-
- vertex[ER] = emissiveR;
- vertex[EG] = emissiveG;
- vertex[EB] = emissiveB;
- }
-
- if (stroke) {
- vertex[SR] = strokeR;
- vertex[SG] = strokeG;
- vertex[SB] = strokeB;
- vertex[SA] = strokeA;
- vertex[SW] = strokeWeight;
- }
-
- if (textureImage != null) {
- vertex[U] = textureU;
- vertex[V] = textureV;
- }
-
- vertex[NX] = normalX;
- vertex[NY] = normalY;
- vertex[NZ] = normalZ;
-
- vertex[BEEN_LIT] = 0;
-
- vertexCount++;
- }
-
-
- /**
- * Used by renderer subclasses or PShape to efficiently pass in already
- * formatted vertex information.
- * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT
- */
- public void vertex(float[] v) {
- vertexCheck();
- curveVertexCount = 0;
- float[] vertex = vertices[vertexCount];
- System.arraycopy(v, 0, vertex, 0, VERTEX_FIELD_COUNT);
- vertexCount++;
- }
-
-
- public void vertex(float x, float y, float u, float v) {
- vertexTexture(u, v);
- vertex(x, y);
- }
-
-
- public void vertex(float x, float y, float z, float u, float v) {
- vertexTexture(u, v);
- vertex(x, y, z);
- }
-
-
- /**
- * Internal method to copy all style information for the given vertex.
- * Can be overridden by subclasses to handle only properties pertinent to
- * that renderer. (e.g. no need to copy the emissive color in P2D)
- */
-// protected void vertexStyle() {
-// }
-
-
- /**
- * Set (U, V) coords for the next vertex in the current shape.
- * This is ugly as its own function, and will (almost?) always be
- * coincident with a call to vertex. As of beta, this was moved to
- * the protected method you see here, and called from an optional
- * param of and overloaded vertex().
- *
- * The parameters depend on the current textureMode. When using
- * textureMode(IMAGE), the coordinates will be relative to the size
- * of the image texture, when used with textureMode(NORMAL),
- * they'll be in the range 0..1.
- *
- * Used by both PGraphics2D (for images) and PGraphics3D.
- */
- protected void vertexTexture(float u, float v) {
- if (textureImage == null) {
- throw new RuntimeException("You must first call texture() before " +
- "using u and v coordinates with vertex()");
- }
- if (textureMode == IMAGE) {
- u /= (float) textureImage.width;
- v /= (float) textureImage.height;
- }
-
- textureU = u;
- textureV = v;
-
- if (textureU < 0) textureU = 0;
- else if (textureU > 1) textureU = 1;
-
- if (textureV < 0) textureV = 0;
- else if (textureV > 1) textureV = 1;
- }
-
-
- /** This feature is in testing, do not use or rely upon its implementation */
- public void breakShape() {
- showWarning("This renderer cannot currently handle concave shapes, " +
- "or shapes with holes.");
- }
-
-
- public void endShape() {
- endShape(OPEN);
- }
-
-
- public void endShape(int mode) {
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CURVE/BEZIER VERTEX HANDLING
-
-
- protected void bezierVertexCheck() {
- if (shape == 0 || shape != POLYGON) {
- throw new RuntimeException("beginShape() or beginShape(POLYGON) " +
- "must be used before bezierVertex()");
- }
- if (vertexCount == 0) {
- throw new RuntimeException("vertex() must be used at least once" +
- "before bezierVertex()");
- }
- }
-
-
- public void bezierVertex(float x2, float y2,
- float x3, float y3,
- float x4, float y4) {
- bezierInitCheck();
- bezierVertexCheck();
- PMatrix3D draw = bezierDrawMatrix;
-
- float[] prev = vertices[vertexCount-1];
- float x1 = prev[X];
- float y1 = prev[Y];
-
- float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4;
- float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4;
- float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4;
-
- float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4;
- float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4;
- float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4;
-
- for (int j = 0; j < bezierDetail; j++) {
- x1 += xplot1; xplot1 += xplot2; xplot2 += xplot3;
- y1 += yplot1; yplot1 += yplot2; yplot2 += yplot3;
- vertex(x1, y1);
- }
- }
-
-
- public void bezierVertex(float x2, float y2, float z2,
- float x3, float y3, float z3,
- float x4, float y4, float z4) {
- bezierInitCheck();
- bezierVertexCheck();
- PMatrix3D draw = bezierDrawMatrix;
-
- float[] prev = vertices[vertexCount-1];
- float x1 = prev[X];
- float y1 = prev[Y];
- float z1 = prev[Z];
-
- float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4;
- float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4;
- float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4;
-
- float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4;
- float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4;
- float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4;
-
- float zplot1 = draw.m10*z1 + draw.m11*z2 + draw.m12*z3 + draw.m13*z4;
- float zplot2 = draw.m20*z1 + draw.m21*z2 + draw.m22*z3 + draw.m23*z4;
- float zplot3 = draw.m30*z1 + draw.m31*z2 + draw.m32*z3 + draw.m33*z4;
-
- for (int j = 0; j < bezierDetail; j++) {
- x1 += xplot1; xplot1 += xplot2; xplot2 += xplot3;
- y1 += yplot1; yplot1 += yplot2; yplot2 += yplot3;
- z1 += zplot1; zplot1 += zplot2; zplot2 += zplot3;
- vertex(x1, y1, z1);
- }
- }
-
-
- /**
- * Perform initialization specific to curveVertex(), and handle standard
- * error modes. Can be overridden by subclasses that need the flexibility.
- */
- protected void curveVertexCheck() {
- if (shape != POLYGON) {
- throw new RuntimeException("You must use beginShape() or " +
- "beginShape(POLYGON) before curveVertex()");
- }
- // to improve code init time, allocate on first use.
- if (curveVertices == null) {
- curveVertices = new float[128][3];
- }
-
- if (curveVertexCount == curveVertices.length) {
- // Can't use PApplet.expand() cuz it doesn't do the copy properly
- float[][] temp = new float[curveVertexCount << 1][3];
- System.arraycopy(curveVertices, 0, temp, 0, curveVertexCount);
- curveVertices = temp;
- }
- curveInitCheck();
- }
-
-
- public void curveVertex(float x, float y) {
- curveVertexCheck();
- float[] vertex = curveVertices[curveVertexCount];
- vertex[X] = x;
- vertex[Y] = y;
- curveVertexCount++;
-
- // draw a segment if there are enough points
- if (curveVertexCount > 3) {
- curveVertexSegment(curveVertices[curveVertexCount-4][X],
- curveVertices[curveVertexCount-4][Y],
- curveVertices[curveVertexCount-3][X],
- curveVertices[curveVertexCount-3][Y],
- curveVertices[curveVertexCount-2][X],
- curveVertices[curveVertexCount-2][Y],
- curveVertices[curveVertexCount-1][X],
- curveVertices[curveVertexCount-1][Y]);
- }
- }
-
-
- public void curveVertex(float x, float y, float z) {
- curveVertexCheck();
- float[] vertex = curveVertices[curveVertexCount];
- vertex[X] = x;
- vertex[Y] = y;
- vertex[Z] = z;
- curveVertexCount++;
-
- // draw a segment if there are enough points
- if (curveVertexCount > 3) {
- curveVertexSegment(curveVertices[curveVertexCount-4][X],
- curveVertices[curveVertexCount-4][Y],
- curveVertices[curveVertexCount-4][Z],
- curveVertices[curveVertexCount-3][X],
- curveVertices[curveVertexCount-3][Y],
- curveVertices[curveVertexCount-3][Z],
- curveVertices[curveVertexCount-2][X],
- curveVertices[curveVertexCount-2][Y],
- curveVertices[curveVertexCount-2][Z],
- curveVertices[curveVertexCount-1][X],
- curveVertices[curveVertexCount-1][Y],
- curveVertices[curveVertexCount-1][Z]);
- }
- }
-
-
- /**
- * Handle emitting a specific segment of Catmull-Rom curve. This can be
- * overridden by subclasses that need more efficient rendering options.
- */
- protected void curveVertexSegment(float x1, float y1,
- float x2, float y2,
- float x3, float y3,
- float x4, float y4) {
- float x0 = x2;
- float y0 = y2;
-
- PMatrix3D draw = curveDrawMatrix;
-
- float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4;
- float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4;
- float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4;
-
- float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4;
- float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4;
- float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4;
-
- // vertex() will reset splineVertexCount, so save it
- int savedCount = curveVertexCount;
-
- vertex(x0, y0);
- for (int j = 0; j < curveDetail; j++) {
- x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3;
- y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3;
- vertex(x0, y0);
- }
- curveVertexCount = savedCount;
- }
-
-
- /**
- * Handle emitting a specific segment of Catmull-Rom curve. This can be
- * overridden by subclasses that need more efficient rendering options.
- */
- protected void curveVertexSegment(float x1, float y1, float z1,
- float x2, float y2, float z2,
- float x3, float y3, float z3,
- float x4, float y4, float z4) {
- float x0 = x2;
- float y0 = y2;
- float z0 = z2;
-
- PMatrix3D draw = curveDrawMatrix;
-
- float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4;
- float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4;
- float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4;
-
- float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4;
- float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4;
- float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4;
-
- // vertex() will reset splineVertexCount, so save it
- int savedCount = curveVertexCount;
-
- float zplot1 = draw.m10*z1 + draw.m11*z2 + draw.m12*z3 + draw.m13*z4;
- float zplot2 = draw.m20*z1 + draw.m21*z2 + draw.m22*z3 + draw.m23*z4;
- float zplot3 = draw.m30*z1 + draw.m31*z2 + draw.m32*z3 + draw.m33*z4;
-
- vertex(x0, y0, z0);
- for (int j = 0; j < curveDetail; j++) {
- x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3;
- y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3;
- z0 += zplot1; zplot1 += zplot2; zplot2 += zplot3;
- vertex(x0, y0, z0);
- }
- curveVertexCount = savedCount;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SIMPLE SHAPES WITH ANALOGUES IN beginShape()
-
-
- public void point(float x, float y) {
- beginShape(POINTS);
- vertex(x, y);
- endShape();
- }
-
-
- /**
- * Draws a point, a coordinate in space at the dimension of one pixel.
- * The first parameter is the horizontal value for the point, the second
- * value is the vertical value for the point, and the optional third value
- * is the depth value. 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.
- *
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) {
- beginShape(POINTS);
- vertex(x, y, z);
- endShape();
- }
-
-
- public void line(float x1, float y1, float x2, float y2) {
- beginShape(LINES);
- vertex(x1, y1);
- vertex(x2, y2);
- endShape();
- }
-
-
-
- /**
- * 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) {
- beginShape(LINES);
- vertex(x1, y1, z1);
- vertex(x2, y2, z2);
- endShape();
- }
-
-
- /**
- * 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) {
- beginShape(TRIANGLES);
- vertex(x1, y1);
- vertex(x2, y2);
- vertex(x3, y3);
- endShape();
- }
-
-
- /**
- * 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) {
- beginShape(QUADS);
- vertex(x1, y1);
- vertex(x2, y2);
- vertex(x3, y3);
- vertex(x4, y4);
- endShape();
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // RECT
-
-
- public void rectMode(int mode) {
- 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) {
- float hradius, vradius;
- switch (rectMode) {
- case CORNERS:
- break;
- case CORNER:
- c += a; d += b;
- break;
- case RADIUS:
- hradius = c;
- vradius = d;
- c = a + hradius;
- d = b + vradius;
- a -= hradius;
- b -= vradius;
- break;
- case CENTER:
- hradius = c / 2.0f;
- vradius = d / 2.0f;
- c = a + hradius;
- d = b + vradius;
- a -= hradius;
- b -= vradius;
- }
-
- if (a > c) {
- float temp = a; a = c; c = temp;
- }
-
- if (b > d) {
- float temp = b; b = d; d = temp;
- }
-
- rectImpl(a, b, c, d);
- }
-
-
- protected void rectImpl(float x1, float y1, float x2, float y2) {
- quad(x1, y1, x2, y1, x2, y2, x1, y2);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // ELLIPSE AND ARC
-
-
- /**
- * 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) {
- 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) {
- float x = a;
- float y = b;
- float w = c;
- float h = d;
-
- if (ellipseMode == CORNERS) {
- w = c - a;
- h = d - b;
-
- } else if (ellipseMode == RADIUS) {
- x = a - c;
- y = b - d;
- w = c * 2;
- h = d * 2;
-
- } else if (ellipseMode == DIAMETER) {
- x = a - c/2f;
- y = b - d/2f;
- }
-
- if (w < 0) { // undo negative width
- x += w;
- w = -w;
- }
-
- if (h < 0) { // undo negative height
- y += h;
- h = -h;
- }
-
- ellipseImpl(x, y, w, h);
- }
-
-
- protected void ellipseImpl(float x, float y, float w, float h) {
- }
-
-
- /**
- * 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) {
- float x = a;
- float y = b;
- float w = c;
- float h = d;
-
- if (ellipseMode == CORNERS) {
- w = c - a;
- h = d - b;
-
- } else if (ellipseMode == RADIUS) {
- x = a - c;
- y = b - d;
- w = c * 2;
- h = d * 2;
-
- } else if (ellipseMode == CENTER) {
- x = a - c/2f;
- y = b - d/2f;
- }
-
- // make sure this loop will exit before starting while
- if (Float.isInfinite(start) || Float.isInfinite(stop)) return;
-// while (stop < start) stop += TWO_PI;
- if (stop < start) return; // why bother
-
- // make sure that we're starting at a useful point
- while (start < 0) {
- start += TWO_PI;
- stop += TWO_PI;
- }
-
- if (stop - start > TWO_PI) {
- start = 0;
- stop = TWO_PI;
- }
-
- arcImpl(x, y, w, h, start, stop);
- }
-
-
- /**
- * Start and stop are in radians, converted by the parent function.
- * Note that the radians can be greater (or less) than TWO_PI.
- * This is so that an arc can be drawn that crosses zero mark,
- * and the user will still collect $200.
- */
- protected void arcImpl(float x, float y, float w, float h,
- float start, float stop) {
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BOX
-
-
- /**
- * @param size dimension of the box in all dimensions, creates a cube
- */
- public void box(float size) {
- box(size, size, 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) {
- float x1 = -w/2f; float x2 = w/2f;
- float y1 = -h/2f; float y2 = h/2f;
- float z1 = -d/2f; float z2 = d/2f;
-
- // TODO not the least bit efficient, it even redraws lines
- // along the vertices. ugly ugly ugly!
-
- beginShape(QUADS);
-
- // front
- normal(0, 0, 1);
- vertex(x1, y1, z1);
- vertex(x2, y1, z1);
- vertex(x2, y2, z1);
- vertex(x1, y2, z1);
-
- // right
- normal(1, 0, 0);
- vertex(x2, y1, z1);
- vertex(x2, y1, z2);
- vertex(x2, y2, z2);
- vertex(x2, y2, z1);
-
- // back
- normal(0, 0, -1);
- vertex(x2, y1, z2);
- vertex(x1, y1, z2);
- vertex(x1, y2, z2);
- vertex(x2, y2, z2);
-
- // left
- normal(-1, 0, 0);
- vertex(x1, y1, z2);
- vertex(x1, y1, z1);
- vertex(x1, y2, z1);
- vertex(x1, y2, z2);
-
- // top
- normal(0, 1, 0);
- vertex(x1, y1, z2);
- vertex(x2, y1, z2);
- vertex(x2, y1, z1);
- vertex(x1, y1, z1);
-
- // bottom
- normal(0, -1, 0);
- vertex(x1, y2, z1);
- vertex(x2, y2, z1);
- vertex(x2, y2, z2);
- vertex(x1, y2, z2);
-
- endShape();
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SPHERE
-
-
- /**
- * @param res number of segments (minimum 3) used per full circle revolution
- */
- public void sphereDetail(int res) {
- sphereDetail(res, 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 (ures < 3) ures = 3; // force a minimum res
- if (vres < 2) vres = 2; // force a minimum res
- if ((ures == sphereDetailU) && (vres == sphereDetailV)) return;
-
- float delta = (float)SINCOS_LENGTH/ures;
- float[] cx = new float[ures];
- float[] cz = new float[ures];
- // calc unit circle in XZ plane
- for (int i = 0; i < ures; i++) {
- cx[i] = cosLUT[(int) (i*delta) % SINCOS_LENGTH];
- cz[i] = sinLUT[(int) (i*delta) % SINCOS_LENGTH];
- }
- // computing vertexlist
- // vertexlist starts at south pole
- int vertCount = ures * (vres-1) + 2;
- int currVert = 0;
-
- // re-init arrays to store vertices
- sphereX = new float[vertCount];
- sphereY = new float[vertCount];
- sphereZ = new float[vertCount];
-
- float angle_step = (SINCOS_LENGTH*0.5f)/vres;
- float angle = angle_step;
-
- // step along Y axis
- for (int i = 1; i < vres; i++) {
- float curradius = sinLUT[(int) angle % SINCOS_LENGTH];
- float currY = -cosLUT[(int) angle % SINCOS_LENGTH];
- for (int j = 0; j < ures; j++) {
- sphereX[currVert] = cx[j] * curradius;
- sphereY[currVert] = currY;
- sphereZ[currVert++] = cz[j] * curradius;
- }
- angle += angle_step;
- }
- sphereDetailU = ures;
- sphereDetailV = vres;
- }
-
-
- /**
- * Draw a sphere with radius r centered at coordinate 0, 0, 0.
- * A sphere is a hollow ball made from tessellated triangles.
- * =advanced
- *
- * 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
- *
- * [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 ((sphereDetailU < 3) || (sphereDetailV < 2)) {
- sphereDetail(30);
- }
-
- pushMatrix();
- scale(r);
- edge(false);
-
- // 1st ring from south pole
- beginShape(TRIANGLE_STRIP);
- for (int i = 0; i < sphereDetailU; i++) {
- normal(0, -1, 0);
- vertex(0, -1, 0);
- normal(sphereX[i], sphereY[i], sphereZ[i]);
- vertex(sphereX[i], sphereY[i], sphereZ[i]);
- }
- //normal(0, -1, 0);
- vertex(0, -1, 0);
- normal(sphereX[0], sphereY[0], sphereZ[0]);
- vertex(sphereX[0], sphereY[0], sphereZ[0]);
- endShape();
-
- int v1,v11,v2;
-
- // middle rings
- int voff = 0;
- for (int i = 2; i < sphereDetailV; i++) {
- v1 = v11 = voff;
- voff += sphereDetailU;
- v2 = voff;
- beginShape(TRIANGLE_STRIP);
- for (int j = 0; j < sphereDetailU; j++) {
- normal(sphereX[v1], sphereY[v1], sphereZ[v1]);
- vertex(sphereX[v1], sphereY[v1], sphereZ[v1++]);
- normal(sphereX[v2], sphereY[v2], sphereZ[v2]);
- vertex(sphereX[v2], sphereY[v2], sphereZ[v2++]);
- }
- // close each ring
- v1 = v11;
- v2 = voff;
- normal(sphereX[v1], sphereY[v1], sphereZ[v1]);
- vertex(sphereX[v1], sphereY[v1], sphereZ[v1]);
- normal(sphereX[v2], sphereY[v2], sphereZ[v2]);
- vertex(sphereX[v2], sphereY[v2], sphereZ[v2]);
- endShape();
- }
-
- // add the northern cap
- beginShape(TRIANGLE_STRIP);
- for (int i = 0; i < sphereDetailU; i++) {
- v2 = voff + i;
- normal(sphereX[v2], sphereY[v2], sphereZ[v2]);
- vertex(sphereX[v2], sphereY[v2], sphereZ[v2]);
- normal(0, 1, 0);
- vertex(0, 1, 0);
- }
- normal(sphereX[voff], sphereY[voff], sphereZ[voff]);
- vertex(sphereX[voff], sphereY[voff], sphereZ[voff]);
- normal(0, 1, 0);
- vertex(0, 1, 0);
- endShape();
-
- edge(true);
- popMatrix();
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BEZIER
-
- /**
- * Evaluates the Bezier 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 bezier curve at t.
- */
-
- /**
- * 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) {
- float t1 = 1.0f - t;
- return a*t1*t1*t1 + 3*b*t*t1*t1 + 3*c*t*t*t1 + d*t*t*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 (3*t*t * (-a+3*b-3*c+d) +
- 6*t * (a-2*b+c) +
- 3 * (-a+b));
- }
-
-
- protected void bezierInitCheck() {
- if (!bezierInited) {
- bezierInit();
- }
- }
-
-
- protected void bezierInit() {
- // overkill to be broken out, but better parity with the curve stuff below
- bezierDetail(bezierDetail);
- bezierInited = true;
- }
-
-
- /**
- * 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) {
- bezierDetail = detail;
-
- if (bezierDrawMatrix == null) {
- bezierDrawMatrix = new PMatrix3D();
- }
-
- // setup matrix for forward differencing to speed up drawing
- splineForward(detail, bezierDrawMatrix);
-
- // multiply the basis and forward diff matrices together
- // saves much time since this needn't be done for each curve
- //mult_spline_matrix(bezierForwardMatrix, bezier_basis, bezierDrawMatrix, 4);
- //bezierDrawMatrix.set(bezierForwardMatrix);
- bezierDrawMatrix.apply(bezierBasisMatrix);
- }
-
-
- /**
- * 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.
- *
- * 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) {
- beginShape();
- vertex(x1, y1);
- bezierVertex(x2, y2, x3, y3, x4, y4);
- endShape();
- }
-
-
- 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) {
- beginShape();
- vertex(x1, y1, z1);
- bezierVertex(x2, y2, z2,
- x3, y3, z3,
- x4, y4, z4);
- endShape();
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CATMULL-ROM CURVE
-
-
- /**
- * 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) {
- curveInitCheck();
-
- float tt = t * t;
- float ttt = t * tt;
- PMatrix3D cb = curveBasisMatrix;
-
- // not optimized (and probably need not be)
- return (a * (ttt*cb.m00 + tt*cb.m10 + t*cb.m20 + cb.m30) +
- b * (ttt*cb.m01 + tt*cb.m11 + t*cb.m21 + cb.m31) +
- c * (ttt*cb.m02 + tt*cb.m12 + t*cb.m22 + cb.m32) +
- d * (ttt*cb.m03 + tt*cb.m13 + t*cb.m23 + cb.m33));
- }
-
-
- /**
- * 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) {
- curveInitCheck();
-
- float tt3 = t * t * 3;
- float t2 = t * 2;
- PMatrix3D cb = curveBasisMatrix;
-
- // not optimized (and probably need not be)
- return (a * (tt3*cb.m00 + t2*cb.m10 + cb.m20) +
- b * (tt3*cb.m01 + t2*cb.m11 + cb.m21) +
- c * (tt3*cb.m02 + t2*cb.m12 + cb.m22) +
- d * (tt3*cb.m03 + t2*cb.m13 + cb.m23) );
- }
-
-
- /**
- * 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) {
- curveDetail = detail;
- curveInit();
- }
-
-
- /**
- * 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) {
- curveTightness = tightness;
- curveInit();
- }
-
-
- protected void curveInitCheck() {
- if (!curveInited) {
- curveInit();
- }
- }
-
-
- /**
- * Set the number of segments to use when drawing a Catmull-Rom
- * curve, and setting the s parameter, which defines how tightly
- * the curve fits to each vertex. Catmull-Rom curves are actually
- * a subset of this curve type where the s is set to zero.
- *
- * (This function is not optimized, since it's not expected to
- * be called all that often. there are many juicy and obvious
- * opimizations in here, but it's probably better to keep the
- * code more readable)
- */
- protected void curveInit() {
- // allocate only if/when used to save startup time
- if (curveDrawMatrix == null) {
- curveBasisMatrix = new PMatrix3D();
- curveDrawMatrix = new PMatrix3D();
- curveInited = true;
- }
-
- float s = curveTightness;
- curveBasisMatrix.set((s-1)/2f, (s+3)/2f, (-3-s)/2f, (1-s)/2f,
- (1-s), (-5-s)/2f, (s+2), (s-1)/2f,
- (s-1)/2f, 0, (1-s)/2f, 0,
- 0, 1, 0, 0);
-
- //setup_spline_forward(segments, curveForwardMatrix);
- splineForward(curveDetail, curveDrawMatrix);
-
- if (bezierBasisInverse == null) {
- bezierBasisInverse = bezierBasisMatrix.get();
- bezierBasisInverse.invert();
- curveToBezierMatrix = new PMatrix3D();
- }
-
- // TODO only needed for PGraphicsJava2D? if so, move it there
- // actually, it's generally useful for other renderers, so keep it
- // or hide the implementation elsewhere.
- curveToBezierMatrix.set(curveBasisMatrix);
- curveToBezierMatrix.preApply(bezierBasisInverse);
-
- // multiply the basis and forward diff matrices together
- // saves much time since this needn't be done for each curve
- curveDrawMatrix.apply(curveBasisMatrix);
- }
-
-
- /**
- * 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().
- *
- *
- * @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) {
- beginShape();
- curveVertex(x1, y1);
- curveVertex(x2, y2);
- curveVertex(x3, y3);
- curveVertex(x4, y4);
- endShape();
- }
-
-
- 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) {
- beginShape();
- curveVertex(x1, y1, z1);
- curveVertex(x2, y2, z2);
- curveVertex(x3, y3, z3);
- curveVertex(x4, y4, z4);
- endShape();
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SPLINE UTILITY FUNCTIONS (used by both Bezier and Catmull-Rom)
-
-
- /**
- * Setup forward-differencing matrix to be used for speedy
- * curve rendering. It's based on using a specific number
- * of curve segments and just doing incremental adds for each
- * vertex of the segment, rather than running the mathematically
- * expensive cubic equation.
- * @param segments number of curve segments to use when drawing
- * @param matrix target object for the new matrix
- */
- protected void splineForward(int segments, PMatrix3D matrix) {
- float f = 1.0f / segments;
- float ff = f * f;
- float fff = ff * f;
-
- matrix.set(0, 0, 0, 1,
- fff, ff, f, 0,
- 6*fff, 2*ff, 0, 0,
- 6*fff, 0, 0, 0);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SMOOTHING
-
-
- /**
- * If true in PImage, use bilinear interpolation for copy()
- * operations. When inherited by PGraphics, also controls shapes.
- */
- public void smooth() {
- smooth = true;
- }
-
-
- /**
- * Disable smoothing. See smooth().
- */
- public void noSmooth() {
- smooth = false;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // IMAGE
-
-
- /**
- * 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 ((mode == CORNER) || (mode == CORNERS) || (mode == CENTER)) {
- imageMode = mode;
- } else {
- String msg =
- "imageMode() only works with CORNER, CORNERS, or CENTER";
- throw new RuntimeException(msg);
- }
- }
-
-
- public void image(PImage image, float x, float y) {
- // Starting in release 0144, image errors are simply ignored.
- // loadImageAsync() sets width and height to -1 when loading fails.
- if (image.width == -1 || image.height == -1) return;
-
- if (imageMode == CORNER || imageMode == CORNERS) {
- imageImpl(image,
- x, y, x+image.width, y+image.height,
- 0, 0, image.width, image.height);
-
- } else if (imageMode == CENTER) {
- float x1 = x - image.width/2;
- float y1 = y - image.height/2;
- imageImpl(image,
- x1, y1, x1+image.width, y1+image.height,
- 0, 0, image.width, image.height);
- }
- }
-
-
- /**
- * 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) {
- image(image, x, y, c, d, 0, 0, image.width, image.height);
- }
-
-
- /**
- * 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) {
- // Starting in release 0144, image errors are simply ignored.
- // loadImageAsync() sets width and height to -1 when loading fails.
- if (image.width == -1 || image.height == -1) return;
-
- if (imageMode == CORNER) {
- if (c < 0) { // reset a negative width
- a += c; c = -c;
- }
- if (d < 0) { // reset a negative height
- b += d; d = -d;
- }
-
- imageImpl(image,
- a, b, a + c, b + d,
- u1, v1, u2, v2);
-
- } else if (imageMode == CORNERS) {
- if (c < a) { // reverse because x2 < x1
- float temp = a; a = c; c = temp;
- }
- if (d < b) { // reverse because y2 < y1
- float temp = b; b = d; d = temp;
- }
-
- imageImpl(image,
- a, b, c, d,
- u1, v1, u2, v2);
-
- } else if (imageMode == CENTER) {
- // c and d are width/height
- if (c < 0) c = -c;
- if (d < 0) d = -d;
- float x1 = a - c/2;
- float y1 = b - d/2;
-
- imageImpl(image,
- x1, y1, x1 + c, y1 + d,
- u1, v1, u2, v2);
- }
- }
-
-
- /**
- * Expects x1, y1, x2, y2 coordinates where (x2 >= x1) and (y2 >= y1).
- * If tint() has been called, the image will be colored.
- *
- * The default implementation draws an image as a textured quad.
- * The (u, v) coordinates are in image space (they're ints, after all..)
- */
- protected void imageImpl(PImage image,
- float x1, float y1, float x2, float y2,
- int u1, int v1, int u2, int v2) {
- boolean savedStroke = stroke;
-// boolean savedFill = fill;
- int savedTextureMode = textureMode;
-
- stroke = false;
-// fill = true;
- textureMode = IMAGE;
-
-// float savedFillR = fillR;
-// float savedFillG = fillG;
-// float savedFillB = fillB;
-// float savedFillA = fillA;
-//
-// if (tint) {
-// fillR = tintR;
-// fillG = tintG;
-// fillB = tintB;
-// fillA = tintA;
-//
-// } else {
-// fillR = 1;
-// fillG = 1;
-// fillB = 1;
-// fillA = 1;
-// }
-
- beginShape(QUADS);
- texture(image);
- vertex(x1, y1, u1, v1);
- vertex(x1, y2, u1, v2);
- vertex(x2, y2, u2, v2);
- vertex(x2, y1, u2, v1);
- endShape();
-
- stroke = savedStroke;
-// fill = savedFill;
- textureMode = savedTextureMode;
-
-// fillR = savedFillR;
-// fillG = savedFillG;
-// fillB = savedFillB;
-// fillA = savedFillA;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SHAPE
-
-
- /**
- * 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) {
- this.shapeMode = mode;
- }
-
-
- public void shape(PShape shape) {
- if (shape.isVisible()) { // don't do expensive matrix ops if invisible
- if (shapeMode == CENTER) {
- pushMatrix();
- translate(-shape.getWidth()/2, -shape.getHeight()/2);
- }
-
- shape.draw(this); // needs to handle recorder too
-
- if (shapeMode == CENTER) {
- popMatrix();
- }
- }
- }
-
-
- /**
- * Convenience method to draw at a particular location.
- */
- public void shape(PShape shape, float x, float y) {
- if (shape.isVisible()) { // don't do expensive matrix ops if invisible
- pushMatrix();
-
- if (shapeMode == CENTER) {
- translate(x - shape.getWidth()/2, y - shape.getHeight()/2);
-
- } else if ((shapeMode == CORNER) || (shapeMode == CORNERS)) {
- translate(x, y);
- }
- shape.draw(this);
-
- popMatrix();
- }
- }
-
-
- /**
- * 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 (shape.isVisible()) { // don't do expensive matrix ops if invisible
- pushMatrix();
-
- if (shapeMode == CENTER) {
- // x and y are center, c and d refer to a diameter
- translate(x - c/2f, y - d/2f);
- scale(c / shape.getWidth(), d / shape.getHeight());
-
- } else if (shapeMode == CORNER) {
- translate(x, y);
- scale(c / shape.getWidth(), d / shape.getHeight());
-
- } else if (shapeMode == CORNERS) {
- // c and d are x2/y2, make them into width/height
- c -= x;
- d -= y;
- // then same as above
- translate(x, y);
- scale(c / shape.getWidth(), d / shape.getHeight());
- }
- shape.draw(this);
-
- popMatrix();
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // TEXT/FONTS
-
-
- /**
- * 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) {
- textAlign(align, BASELINE);
- }
-
-
- /**
- * 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) {
- textAlign = alignX;
- textAlignY = 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() {
- if (textFont == null) {
- defaultFontOrDeath("textAscent");
- }
- return textFont.ascent() * ((textMode == SCREEN) ? textFont.size : textSize);
- }
-
-
- /**
- * 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() {
- if (textFont == null) {
- defaultFontOrDeath("textDescent");
- }
- return textFont.descent() * ((textMode == SCREEN) ? textFont.size : textSize);
- }
-
-
- /**
- * 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 (which != null) {
- textFont = which;
- if (hints[ENABLE_NATIVE_FONTS]) {
- //if (which.font == null) {
- which.findFont();
- //}
- }
- /*
- textFontNative = which.font;
-
- //textFontNativeMetrics = null;
- // changed for rev 0104 for textMode(SHAPE) in opengl
- if (textFontNative != null) {
- // TODO need a better way to handle this. could use reflection to get
- // rid of the warning, but that'd be a little silly. supporting this is
- // an artifact of supporting java 1.1, otherwise we'd use getLineMetrics,
- // as recommended by the @deprecated flag.
- textFontNativeMetrics =
- Toolkit.getDefaultToolkit().getFontMetrics(textFontNative);
- // The following is what needs to be done, however we need to be able
- // to get the actual graphics context where the drawing is happening.
- // For instance, parent.getGraphics() doesn't work for OpenGL since
- // an OpenGL drawing surface is an embedded component.
-// if (parent != null) {
-// textFontNativeMetrics = parent.getGraphics().getFontMetrics(textFontNative);
-// }
-
- // float w = font.getStringBounds(text, g2.getFontRenderContext()).getWidth();
- }
- */
- textSize(which.size);
-
- } else {
- throw new RuntimeException(ERROR_TEXTFONT_NULL_PFONT);
- }
- }
-
-
- /**
- * Useful function to set the font and size at the same time.
- */
- public void textFont(PFont which, float size) {
- textFont(which);
- textSize(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) {
- 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) {
- // CENTER and MODEL overlap (they're both 3)
- if ((mode == LEFT) || (mode == RIGHT)) {
- showWarning("Since Processing beta, textMode() is now textAlign().");
- return;
- }
-// if ((mode != SCREEN) && (mode != MODEL)) {
-// showError("Only textMode(SCREEN) and textMode(MODEL) " +
-// "are available with this renderer.");
-// }
-
- if (textModeCheck(mode)) {
- textMode = mode;
- } else {
- String modeStr = String.valueOf(mode);
- switch (mode) {
- case SCREEN: modeStr = "SCREEN"; break;
- case MODEL: modeStr = "MODEL"; break;
- case SHAPE: modeStr = "SHAPE"; break;
- }
- showWarning("textMode(" + modeStr + ") is not supported by this renderer.");
- }
-
- // reset the font to its natural size
- // (helps with width calculations and all that)
- //if (textMode == SCREEN) {
- //textSize(textFont.size);
- //}
-
- //} else {
- //throw new RuntimeException("use textFont() before textMode()");
- //}
- }
-
-
- protected boolean textModeCheck(int mode) {
- return true;
- }
-
-
- /**
- * Sets the text size, also resets the value for the leading.
- */
- public void textSize(float size) {
- if (textFont == null) {
- defaultFontOrDeath("textSize", size);
- }
- textSize = size;
- textLeading = (textAscent() + textDescent()) * 1.275f;
- }
-
-
- // ........................................................
-
-
- public float textWidth(char c) {
- textWidthBuffer[0] = c;
- return textWidthImpl(textWidthBuffer, 0, 1);
- }
-
-
- /**
- * 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) {
- if (textFont == null) {
- defaultFontOrDeath("textWidth");
- }
-
- int length = str.length();
- if (length > textWidthBuffer.length) {
- textWidthBuffer = new char[length + 10];
- }
- str.getChars(0, length, textWidthBuffer, 0);
-
- float wide = 0;
- int index = 0;
- int start = 0;
-
- while (index < length) {
- if (textWidthBuffer[index] == '\n') {
- wide = Math.max(wide, textWidthImpl(textWidthBuffer, start, index));
- start = index+1;
- }
- index++;
- }
- if (start < length) {
- wide = Math.max(wide, textWidthImpl(textWidthBuffer, start, index));
- }
- return wide;
- }
-
-
- /**
- * TODO not sure if this stays...
- */
- public float textWidth(char[] chars, int start, int length) {
- return textWidthImpl(chars, start, start + length);
- }
-
-
- /**
- * Implementation of returning the text width of
- * the chars [start, stop) in the buffer.
- * Unlike the previous version that was inside PFont, this will
- * return the size not of a 1 pixel font, but the actual current size.
- */
- protected float textWidthImpl(char buffer[], int start, int stop) {
- float wide = 0;
- for (int i = start; i < stop; i++) {
- // could add kerning here, but it just ain't implemented
- wide += textFont.width(buffer[i]) * textSize;
- }
- return wide;
- }
-
-
- // ........................................................
-
-
- /**
- * Write text where we just left off.
- */
- public void text(char c) {
- text(c, textX, textY, textZ);
- }
-
-
- /**
- * 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 (textFont == null) {
- defaultFontOrDeath("text");
- }
-
- if (textMode == SCREEN) loadPixels();
-
- if (textAlignY == CENTER) {
- y += textAscent() / 2;
- } else if (textAlignY == TOP) {
- y += textAscent();
- } else if (textAlignY == BOTTOM) {
- y -= textDescent();
- //} else if (textAlignY == BASELINE) {
- // do nothing
- }
-
- textBuffer[0] = c;
- textLineAlignImpl(textBuffer, 0, 1, x, y);
-
- if (textMode == SCREEN) updatePixels();
- }
-
-
- /**
- * Draw a single character on screen (with a z coordinate)
- */
- public void text(char c, float x, float y, float z) {
-// if ((z != 0) && (textMode == SCREEN)) {
-// String msg = "textMode(SCREEN) cannot have a z coordinate";
-// throw new RuntimeException(msg);
-// }
-
- if (z != 0) translate(0, 0, z); // slowness, badness
-
- text(c, x, y);
- textZ = z;
-
- if (z != 0) translate(0, 0, -z);
- }
-
-
- /**
- * Write text where we just left off.
- */
- public void text(String str) {
- text(str, textX, textY, textZ);
- }
-
-
- /**
- * 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 (textFont == null) {
- defaultFontOrDeath("text");
- }
-
- if (textMode == SCREEN) loadPixels();
-
- int length = str.length();
- if (length > textBuffer.length) {
- textBuffer = new char[length + 10];
- }
- str.getChars(0, length, textBuffer, 0);
- text(textBuffer, 0, length, 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 multiple lines, sum the height of the additional lines
- float high = 0; //-textAscent();
- for (int i = start; i < stop; i++) {
- if (chars[i] == '\n') {
- high += textLeading;
- }
- }
- if (textAlignY == CENTER) {
- // for a single line, this adds half the textAscent to y
- // for multiple lines, subtract half the additional height
- //y += (textAscent() - textDescent() - high)/2;
- y += (textAscent() - high)/2;
- } else if (textAlignY == TOP) {
- // for a single line, need to add textAscent to y
- // for multiple lines, no different
- y += textAscent();
- } else if (textAlignY == BOTTOM) {
- // for a single line, this is just offset by the descent
- // for multiple lines, subtract leading for each line
- y -= textDescent() + high;
- //} else if (textAlignY == BASELINE) {
- // do nothing
- }
-
-// int start = 0;
- int index = 0;
- while (index < stop) { //length) {
- if (chars[index] == '\n') {
- textLineAlignImpl(chars, start, index, x, y);
- start = index + 1;
- y += textLeading;
- }
- index++;
- }
- if (start < stop) { //length) {
- textLineAlignImpl(chars, start, index, x, y);
- }
- if (textMode == SCREEN) updatePixels();
- }
-
-
- /**
- * Same as above but with a z coordinate.
- */
- public void text(String str, float x, float y, float z) {
- if (z != 0) translate(0, 0, z); // slow!
-
- text(str, x, y);
- textZ = z;
-
- if (z != 0) translate(0, 0, -z); // inaccurate!
- }
-
-
- public void text(char[] chars, int start, int stop,
- float x, float y, float z) {
- if (z != 0) translate(0, 0, z); // slow!
-
- text(chars, start, stop, x, y);
- textZ = z;
-
- if (z != 0) translate(0, 0, -z); // inaccurate!
- }
-
-
- /**
- * 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 (textFont == null) {
- defaultFontOrDeath("text");
- }
-
- if (textMode == SCREEN) loadPixels();
-
- float hradius, vradius;
- switch (rectMode) {
- case CORNER:
- x2 += x1; y2 += y1;
- break;
- case RADIUS:
- hradius = x2;
- vradius = y2;
- x2 = x1 + hradius;
- y2 = y1 + vradius;
- x1 -= hradius;
- y1 -= vradius;
- break;
- case CENTER:
- hradius = x2 / 2.0f;
- vradius = y2 / 2.0f;
- x2 = x1 + hradius;
- y2 = y1 + vradius;
- x1 -= hradius;
- y1 -= vradius;
- }
- if (x2 < x1) {
- float temp = x1; x1 = x2; x2 = temp;
- }
- if (y2 < y1) {
- float temp = y1; y1 = y2; y2 = temp;
- }
-
-// float currentY = y1;
- float boxWidth = x2 - x1;
-
-// // ala illustrator, the text itself must fit inside the box
-// currentY += textAscent(); //ascent() * textSize;
-// // if the box is already too small, tell em to f off
-// if (currentY > y2) return;
-
- float spaceWidth = textWidth(' ');
-
- if (textBreakStart == null) {
- textBreakStart = new int[20];
- textBreakStop = new int[20];
- }
- textBreakCount = 0;
-
- int length = str.length();
- if (length + 1 > textBuffer.length) {
- textBuffer = new char[length + 1];
- }
- str.getChars(0, length, textBuffer, 0);
- // add a fake newline to simplify calculations
- textBuffer[length++] = '\n';
-
- int sentenceStart = 0;
- for (int i = 0; i < length; i++) {
- if (textBuffer[i] == '\n') {
-// currentY = textSentence(textBuffer, sentenceStart, i,
-// lineX, boxWidth, currentY, y2, spaceWidth);
- boolean legit =
- textSentence(textBuffer, sentenceStart, i, boxWidth, spaceWidth);
- if (!legit) break;
-// if (Float.isNaN(currentY)) break; // word too big (or error)
-// if (currentY > y2) break; // past the box
- sentenceStart = i + 1;
- }
- }
-
- // lineX is the position where the text starts, which is adjusted
- // to left/center/right based on the current textAlign
- float lineX = x1; //boxX1;
- if (textAlign == CENTER) {
- lineX = lineX + boxWidth/2f;
- } else if (textAlign == RIGHT) {
- lineX = x2; //boxX2;
- }
-
- float boxHeight = y2 - y1;
- //int lineFitCount = 1 + PApplet.floor((boxHeight - textAscent()) / textLeading);
- // incorporate textAscent() for the top (baseline will be y1 + ascent)
- // and textDescent() for the bottom, so that lower parts of letters aren't
- // outside the box. [0151]
- float topAndBottom = textAscent() + textDescent();
- int lineFitCount = 1 + PApplet.floor((boxHeight - topAndBottom) / textLeading);
- int lineCount = Math.min(textBreakCount, lineFitCount);
-
- if (textAlignY == CENTER) {
- float lineHigh = textAscent() + textLeading * (lineCount - 1);
- float y = y1 + textAscent() + (boxHeight - lineHigh) / 2;
- for (int i = 0; i < lineCount; i++) {
- textLineAlignImpl(textBuffer, textBreakStart[i], textBreakStop[i], lineX, y);
- y += textLeading;
- }
-
- } else if (textAlignY == BOTTOM) {
- float y = y2 - textDescent() - textLeading * (lineCount - 1);
- for (int i = 0; i < lineCount; i++) {
- textLineAlignImpl(textBuffer, textBreakStart[i], textBreakStop[i], lineX, y);
- y += textLeading;
- }
-
- } else { // TOP or BASELINE just go to the default
- float y = y1 + textAscent();
- for (int i = 0; i < lineCount; i++) {
- textLineAlignImpl(textBuffer, textBreakStart[i], textBreakStop[i], lineX, y);
- y += textLeading;
- }
- }
-
- if (textMode == SCREEN) updatePixels();
- }
-
-
- /**
- * Emit a sentence of text, defined as a chunk of text without any newlines.
- * @param stop non-inclusive, the end of the text in question
- */
- protected boolean textSentence(char[] buffer, int start, int stop,
- float boxWidth, float spaceWidth) {
- float runningX = 0;
-
- // Keep track of this separately from index, since we'll need to back up
- // from index when breaking words that are too long to fit.
- int lineStart = start;
- int wordStart = start;
- int index = start;
- while (index <= stop) {
- // boundary of a word or end of this sentence
- if ((buffer[index] == ' ') || (index == stop)) {
- float wordWidth = textWidthImpl(buffer, wordStart, index);
-
- if (runningX + wordWidth > boxWidth) {
- if (runningX != 0) {
- // Next word is too big, output the current line and advance
- index = wordStart;
- textSentenceBreak(lineStart, index);
- // Eat whitespace because multiple spaces don't count for s*
- // when they're at the end of a line.
- while ((index < stop) && (buffer[index] == ' ')) {
- index++;
- }
- } else { // (runningX == 0)
- // If this is the first word on the line, and its width is greater
- // than the width of the text box, then break the word where at the
- // max width, and send the rest of the word to the next line.
- do {
- index--;
- if (index == wordStart) {
- // Not a single char will fit on this line. screw 'em.
- //System.out.println("screw you");
- return false; //Float.NaN;
- }
- wordWidth = textWidthImpl(buffer, wordStart, index);
- } while (wordWidth > boxWidth);
-
- //textLineImpl(buffer, lineStart, index, x, y);
- textSentenceBreak(lineStart, index);
- }
- lineStart = index;
- wordStart = index;
- runningX = 0;
-
- } else if (index == stop) {
- // last line in the block, time to unload
- //textLineImpl(buffer, lineStart, index, x, y);
- textSentenceBreak(lineStart, index);
-// y += textLeading;
- index++;
-
- } else { // this word will fit, just add it to the line
- runningX += wordWidth + spaceWidth;
- wordStart = index + 1; // move on to the next word
- index++;
- }
- } else { // not a space or the last character
- index++; // this is just another letter
- }
- }
-// return y;
- return true;
- }
-
-
- protected void textSentenceBreak(int start, int stop) {
- if (textBreakCount == textBreakStart.length) {
- textBreakStart = PApplet.expand(textBreakStart);
- textBreakStop = PApplet.expand(textBreakStop);
- }
- textBreakStart[textBreakCount] = start;
- textBreakStop[textBreakCount] = stop;
- textBreakCount++;
- }
-
-
- public void text(String s, float x1, float y1, float x2, float y2, float z) {
- if (z != 0) translate(0, 0, z); // slowness, badness
-
- text(s, x1, y1, x2, y2);
- textZ = z;
-
- if (z != 0) translate(0, 0, -z); // TEMPORARY HACK! SLOW!
- }
-
-
- public void text(int num, float x, float y) {
- text(String.valueOf(num), x, y);
- }
-
-
- public void text(int num, float x, float y, float z) {
- text(String.valueOf(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) {
- text(PApplet.nfs(num, 0, 3), x, y);
- }
-
-
- public void text(float num, float x, float y, float z) {
- text(PApplet.nfs(num, 0, 3), x, y, z);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // TEXT IMPL
-
- // These are most likely to be overridden by subclasses, since the other
- // (public) functions handle generic features like setting alignment.
-
-
- /**
- * Handles placement of a text line, then calls textLineImpl
- * to actually render at the specific point.
- */
- protected void textLineAlignImpl(char buffer[], int start, int stop,
- float x, float y) {
- if (textAlign == CENTER) {
- x -= textWidthImpl(buffer, start, stop) / 2f;
-
- } else if (textAlign == RIGHT) {
- x -= textWidthImpl(buffer, start, stop);
- }
-
- textLineImpl(buffer, start, stop, x, y);
- }
-
-
- /**
- * Implementation of actual drawing for a line of text.
- */
- protected void textLineImpl(char buffer[], int start, int stop,
- float x, float y) {
- for (int index = start; index < stop; index++) {
- textCharImpl(buffer[index], x, y);
-
- // this doesn't account for kerning
- x += textWidth(buffer[index]);
- }
- textX = x;
- textY = y;
- textZ = 0; // this will get set by the caller if non-zero
- }
-
-
- protected void textCharImpl(char ch, float x, float y) { //, float z) {
- PFont.Glyph glyph = textFont.getGlyph(ch);
- if (glyph != null) {
- if (textMode == MODEL) {
- float high = glyph.height / (float) textFont.size;
- float bwidth = glyph.width / (float) textFont.size;
- float lextent = glyph.leftExtent / (float) textFont.size;
- float textent = glyph.topExtent / (float) textFont.size;
-
- float x1 = x + lextent * textSize;
- float y1 = y - textent * textSize;
- float x2 = x1 + bwidth * textSize;
- float y2 = y1 + high * textSize;
-
- textCharModelImpl(glyph.image,
- x1, y1, x2, y2,
- glyph.width, glyph.height);
-
- } else if (textMode == SCREEN) {
- int xx = (int) x + glyph.leftExtent;
- int yy = (int) y - glyph.topExtent;
-
- int w0 = glyph.width;
- int h0 = glyph.height;
-
- textCharScreenImpl(glyph.image, xx, yy, w0, h0);
- }
- }
- }
-
-
- protected void textCharModelImpl(PImage glyph,
- float x1, float y1, //float z1,
- float x2, float y2, //float z2,
- int u2, int v2) {
- boolean savedTint = tint;
- int savedTintColor = tintColor;
- float savedTintR = tintR;
- float savedTintG = tintG;
- float savedTintB = tintB;
- float savedTintA = tintA;
- boolean savedTintAlpha = tintAlpha;
-
- tint = true;
- tintColor = fillColor;
- tintR = fillR;
- tintG = fillG;
- tintB = fillB;
- tintA = fillA;
- tintAlpha = fillAlpha;
-
- imageImpl(glyph, x1, y1, x2, y2, 0, 0, u2, v2);
-
- tint = savedTint;
- tintColor = savedTintColor;
- tintR = savedTintR;
- tintG = savedTintG;
- tintB = savedTintB;
- tintA = savedTintA;
- tintAlpha = savedTintAlpha;
- }
-
-
- protected void textCharScreenImpl(PImage glyph,
- int xx, int yy,
- int w0, int h0) {
- int x0 = 0;
- int y0 = 0;
-
- if ((xx >= width) || (yy >= height) ||
- (xx + w0 < 0) || (yy + h0 < 0)) return;
-
- if (xx < 0) {
- x0 -= xx;
- w0 += xx;
- xx = 0;
- }
- if (yy < 0) {
- y0 -= yy;
- h0 += yy;
- yy = 0;
- }
- if (xx + w0 > width) {
- w0 -= ((xx + w0) - width);
- }
- if (yy + h0 > height) {
- h0 -= ((yy + h0) - height);
- }
-
- int fr = fillRi;
- int fg = fillGi;
- int fb = fillBi;
- int fa = fillAi;
-
- int pixels1[] = glyph.pixels; //images[glyph].pixels;
-
- // TODO this can be optimized a bit
- for (int row = y0; row < y0 + h0; row++) {
- for (int col = x0; col < x0 + w0; col++) {
- //int a1 = (fa * pixels1[row * textFont.twidth + col]) >> 8;
- int a1 = (fa * pixels1[row * glyph.width + col]) >> 8;
- int a2 = a1 ^ 0xff;
- //int p1 = pixels1[row * glyph.width + col];
- int p2 = pixels[(yy + row-y0)*width + (xx+col-x0)];
-
- pixels[(yy + row-y0)*width + xx+col-x0] =
- (0xff000000 |
- (((a1 * fr + a2 * ((p2 >> 16) & 0xff)) & 0xff00) << 8) |
- (( a1 * fg + a2 * ((p2 >> 8) & 0xff)) & 0xff00) |
- (( a1 * fb + a2 * ( p2 & 0xff)) >> 8));
- }
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX STACK
-
-
- /**
- * Push a copy of the current transformation matrix onto the stack.
- */
- public void pushMatrix() {
- showMethodWarning("pushMatrix");
- }
-
-
- /**
- * Replace the current transformation matrix with the top of the stack.
- */
- public void popMatrix() {
- showMethodWarning("popMatrix");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX TRANSFORMATIONS
-
-
- /**
- * Translate in X and Y.
- */
- public void translate(float tx, float ty) {
- showMissingWarning("translate");
- }
-
-
- /**
- * Translate in X, Y, and Z.
- */
- public void translate(float tx, float ty, float tz) {
- showMissingWarning("translate");
- }
-
-
- /**
- * 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) {
- showMissingWarning("rotate");
- }
-
-
- /**
- * Rotate around the X axis.
- */
- public void rotateX(float angle) {
- showMethodWarning("rotateX");
- }
-
-
- /**
- * Rotate around the Y axis.
- */
- public void rotateY(float angle) {
- showMethodWarning("rotateY");
- }
-
-
- /**
- * 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) {
- showMethodWarning("rotateZ");
- }
-
-
- /**
- * Rotate about a vector in space. Same as the glRotatef() function.
- */
- public void rotate(float angle, float vx, float vy, float vz) {
- showMissingWarning("rotate");
- }
-
-
- /**
- * Scale in all dimensions.
- */
- public void scale(float s) {
- showMissingWarning("scale");
- }
-
-
- /**
- * 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) {
- showMissingWarning("scale");
- }
-
-
- /**
- * Scale in X, Y, and Z.
- */
- public void scale(float x, float y, float z) {
- showMissingWarning("scale");
- }
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX FULL MONTY
-
-
- /**
- * Set the current transformation matrix to identity.
- */
- public void resetMatrix() {
- showMethodWarning("resetMatrix");
- }
-
-
- public void applyMatrix(PMatrix source) {
- if (source instanceof PMatrix2D) {
- applyMatrix((PMatrix2D) source);
- } else if (source instanceof PMatrix3D) {
- applyMatrix((PMatrix3D) source);
- }
- }
-
-
- public void applyMatrix(PMatrix2D source) {
- applyMatrix(source.m00, source.m01, source.m02,
- source.m10, source.m11, source.m12);
- }
-
-
- /**
- * Apply a 3x2 affine transformation matrix.
- */
- public void applyMatrix(float n00, float n01, float n02,
- float n10, float n11, float n12) {
- showMissingWarning("applyMatrix");
- }
-
-
- 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.
- */
- 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) {
- showMissingWarning("applyMatrix");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX GET/SET/PRINT
-
-
- public PMatrix getMatrix() {
- showMissingWarning("getMatrix");
- return null;
- }
-
-
- /**
- * Copy the current transformation matrix into the specified target.
- * Pass in null to create a new matrix.
- */
- public PMatrix2D getMatrix(PMatrix2D target) {
- showMissingWarning("getMatrix");
- return null;
- }
-
-
- /**
- * Copy the current transformation matrix into the specified target.
- * Pass in null to create a new matrix.
- */
- public PMatrix3D getMatrix(PMatrix3D target) {
- showMissingWarning("getMatrix");
- return null;
- }
-
-
- /**
- * Set the current transformation matrix to the contents of another.
- */
- public void setMatrix(PMatrix source) {
- if (source instanceof PMatrix2D) {
- setMatrix((PMatrix2D) source);
- } else if (source instanceof PMatrix3D) {
- setMatrix((PMatrix3D) source);
- }
- }
-
-
- /**
- * Set the current transformation to the contents of the specified source.
- */
- public void setMatrix(PMatrix2D source) {
- showMissingWarning("setMatrix");
- }
-
-
- /**
- * Set the current transformation to the contents of the specified source.
- */
- public void setMatrix(PMatrix3D source) {
- showMissingWarning("setMatrix");
- }
-
-
- /**
- * Print the current model (or "transformation") matrix.
- */
- public void printMatrix() {
- showMethodWarning("printMatrix");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CAMERA
-
-
- public void beginCamera() {
- showMethodWarning("beginCamera");
- }
-
-
- public void endCamera() {
- showMethodWarning("endCamera");
- }
-
-
- public void camera() {
- showMissingWarning("camera");
- }
-
-
- public void camera(float eyeX, float eyeY, float eyeZ,
- float centerX, float centerY, float centerZ,
- float upX, float upY, float upZ) {
- showMissingWarning("camera");
- }
-
-
- public void printCamera() {
- showMethodWarning("printCamera");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // PROJECTION
-
-
- public void ortho() {
- showMissingWarning("ortho");
- }
-
-
- public void ortho(float left, float right,
- float bottom, float top,
- float near, float far) {
- showMissingWarning("ortho");
- }
-
-
- public void perspective() {
- showMissingWarning("perspective");
- }
-
-
- public void perspective(float fovy, float aspect, float zNear, float zFar) {
- showMissingWarning("perspective");
- }
-
-
- public void frustum(float left, float right,
- float bottom, float top,
- float near, float far) {
- showMethodWarning("frustum");
- }
-
-
- public void printProjection() {
- showMethodWarning("printCamera");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SCREEN TRANSFORMS
-
-
- /**
- * 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) {
- showMissingWarning("screenX");
- return 0;
- }
-
-
- /**
- * 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) {
- showMissingWarning("screenY");
- return 0;
- }
-
-
- /**
- * Maps a three dimensional point to its placement on-screen.
- *
- * 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) {
- showMissingWarning("screenX");
- return 0;
- }
-
-
- /**
- * 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) {
- showMissingWarning("screenY");
- return 0;
- }
-
-
- /**
- * 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) {
- showMissingWarning("screenZ");
- return 0;
- }
-
-
- /**
- * 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) {
- showMissingWarning("modelX");
- return 0;
- }
-
-
- /**
- * Returns the model space y value for an x, y, z coordinate.
- */
- public float modelY(float x, float y, float z) {
- showMissingWarning("modelY");
- return 0;
- }
-
-
- /**
- * Returns the model space z value for an x, y, z coordinate.
- */
- public float modelZ(float x, float y, float z) {
- showMissingWarning("modelZ");
- return 0;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // STYLE
-
-
- public void pushStyle() {
- if (styleStackDepth == styleStack.length) {
- styleStack = (PStyle[]) PApplet.expand(styleStack);
- }
- if (styleStack[styleStackDepth] == null) {
- styleStack[styleStackDepth] = new PStyle();
- }
- PStyle s = styleStack[styleStackDepth++];
- getStyle(s);
- }
-
-
- public void popStyle() {
- if (styleStackDepth == 0) {
- throw new RuntimeException("Too many popStyle() without enough pushStyle()");
- }
- styleStackDepth--;
- style(styleStack[styleStackDepth]);
- }
-
-
- public void style(PStyle s) {
- // if (s.smooth) {
- // smooth();
- // } else {
- // noSmooth();
- // }
-
- imageMode(s.imageMode);
- rectMode(s.rectMode);
- ellipseMode(s.ellipseMode);
- shapeMode(s.shapeMode);
-
- if (s.tint) {
- tint(s.tintColor);
- } else {
- noTint();
- }
- if (s.fill) {
- fill(s.fillColor);
- } else {
- noFill();
- }
- if (s.stroke) {
- stroke(s.strokeColor);
- } else {
- noStroke();
- }
- strokeWeight(s.strokeWeight);
- strokeCap(s.strokeCap);
- strokeJoin(s.strokeJoin);
-
- // Set the colorMode() for the material properties.
- // TODO this is really inefficient, need to just have a material() method,
- // but this has the least impact to the API.
- colorMode(RGB, 1);
- ambient(s.ambientR, s.ambientG, s.ambientB);
- emissive(s.emissiveR, s.emissiveG, s.emissiveB);
- specular(s.specularR, s.specularG, s.specularB);
- shininess(s.shininess);
-
- /*
- s.ambientR = ambientR;
- s.ambientG = ambientG;
- s.ambientB = ambientB;
- s.specularR = specularR;
- s.specularG = specularG;
- s.specularB = specularB;
- s.emissiveR = emissiveR;
- s.emissiveG = emissiveG;
- s.emissiveB = emissiveB;
- s.shininess = shininess;
- */
- // material(s.ambientR, s.ambientG, s.ambientB,
- // s.emissiveR, s.emissiveG, s.emissiveB,
- // s.specularR, s.specularG, s.specularB,
- // s.shininess);
-
- // Set this after the material properties.
- colorMode(s.colorMode,
- s.colorModeX, s.colorModeY, s.colorModeZ, s.colorModeA);
-
- // This is a bit asymmetric, since there's no way to do "noFont()",
- // and a null textFont will produce an error (since usually that means that
- // the font couldn't load properly). So in some cases, the font won't be
- // 'cleared' to null, even though that's technically correct.
- if (s.textFont != null) {
- textFont(s.textFont, s.textSize);
- textLeading(s.textLeading);
- }
- // These don't require a font to be set.
- textAlign(s.textAlign, s.textAlignY);
- textMode(s.textMode);
- }
-
-
- public PStyle getStyle() { // ignore
- return getStyle(null);
- }
-
-
- public PStyle getStyle(PStyle s) { // ignore
- if (s == null) {
- s = new PStyle();
- }
-
- s.imageMode = imageMode;
- s.rectMode = rectMode;
- s.ellipseMode = ellipseMode;
- s.shapeMode = shapeMode;
-
- s.colorMode = colorMode;
- s.colorModeX = colorModeX;
- s.colorModeY = colorModeY;
- s.colorModeZ = colorModeZ;
- s.colorModeA = colorModeA;
-
- s.tint = tint;
- s.tintColor = tintColor;
- s.fill = fill;
- s.fillColor = fillColor;
- s.stroke = stroke;
- s.strokeColor = strokeColor;
- s.strokeWeight = strokeWeight;
- s.strokeCap = strokeCap;
- s.strokeJoin = strokeJoin;
-
- s.ambientR = ambientR;
- s.ambientG = ambientG;
- s.ambientB = ambientB;
- s.specularR = specularR;
- s.specularG = specularG;
- s.specularB = specularB;
- s.emissiveR = emissiveR;
- s.emissiveG = emissiveG;
- s.emissiveB = emissiveB;
- s.shininess = shininess;
-
- s.textFont = textFont;
- s.textAlign = textAlign;
- s.textAlignY = textAlignY;
- s.textMode = textMode;
- s.textSize = textSize;
- s.textLeading = textLeading;
-
- return s;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // STROKE CAP/JOIN/WEIGHT
-
-
- public void strokeWeight(float weight) {
- strokeWeight = weight;
- }
-
-
- public void strokeJoin(int join) {
- strokeJoin = join;
- }
-
-
- public void strokeCap(int cap) {
- strokeCap = cap;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // STROKE COLOR
-
-
- /**
- * 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() {
- stroke = false;
- }
-
-
- /**
- * 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) {
- colorCalc(rgb);
- strokeFromCalc();
- }
-
-
- public void stroke(int rgb, float alpha) {
- colorCalc(rgb, alpha);
- strokeFromCalc();
- }
-
-
- /**
- *
- * @param gray specifies a value between white and black
- */
- public void stroke(float gray) {
- colorCalc(gray);
- strokeFromCalc();
- }
-
-
- public void stroke(float gray, float alpha) {
- colorCalc(gray, alpha);
- strokeFromCalc();
- }
-
-
- public void stroke(float x, float y, float z) {
- colorCalc(x, y, z);
- strokeFromCalc();
- }
-
-
- /**
- * 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).
- *
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) {
- colorCalc(x, y, z, a);
- strokeFromCalc();
- }
-
-
- protected void strokeFromCalc() {
- stroke = true;
- strokeR = calcR;
- strokeG = calcG;
- strokeB = calcB;
- strokeA = calcA;
- strokeRi = calcRi;
- strokeGi = calcGi;
- strokeBi = calcBi;
- strokeAi = calcAi;
- strokeColor = calcColor;
- strokeAlpha = calcAlpha;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // TINT COLOR
-
-
- /**
- * 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() {
- tint = false;
- }
-
-
- /**
- * Set the tint to either a grayscale or ARGB value.
- */
- public void tint(int rgb) {
- colorCalc(rgb);
- tintFromCalc();
- }
-
-
- /**
- * @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) {
- colorCalc(rgb, alpha);
- tintFromCalc();
- }
-
-
- /**
- * @param gray any valid number
- */
- public void tint(float gray) {
- colorCalc(gray);
- tintFromCalc();
- }
-
-
- public void tint(float gray, float alpha) {
- colorCalc(gray, alpha);
- tintFromCalc();
- }
-
-
- public void tint(float x, float y, float z) {
- colorCalc(x, y, z);
- tintFromCalc();
- }
-
-
- /**
- * 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) {
- colorCalc(x, y, z, a);
- tintFromCalc();
- }
-
-
- protected void tintFromCalc() {
- tint = true;
- tintR = calcR;
- tintG = calcG;
- tintB = calcB;
- tintA = calcA;
- tintRi = calcRi;
- tintGi = calcGi;
- tintBi = calcBi;
- tintAi = calcAi;
- tintColor = calcColor;
- tintAlpha = calcAlpha;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // FILL COLOR
-
-
- /**
- * 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() {
- fill = false;
- }
-
-
- /**
- * 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) {
- colorCalc(rgb);
- fillFromCalc();
- }
-
-
- public void fill(int rgb, float alpha) {
- colorCalc(rgb, alpha);
- fillFromCalc();
- }
-
-
- /**
- * @param gray number specifying value between white and black
- */
- public void fill(float gray) {
- colorCalc(gray);
- fillFromCalc();
- }
-
-
- public void fill(float gray, float alpha) {
- colorCalc(gray, alpha);
- fillFromCalc();
- }
-
-
- public void fill(float x, float y, float z) {
- colorCalc(x, y, z);
- fillFromCalc();
- }
-
-
- /**
- * 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) {
- colorCalc(x, y, z, a);
- fillFromCalc();
- }
-
-
- protected void fillFromCalc() {
- fill = true;
- fillR = calcR;
- fillG = calcG;
- fillB = calcB;
- fillA = calcA;
- fillRi = calcRi;
- fillGi = calcGi;
- fillBi = calcBi;
- fillAi = calcAi;
- fillColor = calcColor;
- fillAlpha = calcAlpha;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATERIAL PROPERTIES
-
-
- public void ambient(int rgb) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// ambient((float) rgb);
-//
-// } else {
-// colorCalcARGB(rgb, colorModeA);
-// ambientFromCalc();
-// }
- colorCalc(rgb);
- ambientFromCalc();
- }
-
-
- public void ambient(float gray) {
- colorCalc(gray);
- ambientFromCalc();
- }
-
-
- public void ambient(float x, float y, float z) {
- colorCalc(x, y, z);
- ambientFromCalc();
- }
-
-
- protected void ambientFromCalc() {
- ambientR = calcR;
- ambientG = calcG;
- ambientB = calcB;
- }
-
-
- public void specular(int rgb) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// specular((float) rgb);
-//
-// } else {
-// colorCalcARGB(rgb, colorModeA);
-// specularFromCalc();
-// }
- colorCalc(rgb);
- specularFromCalc();
- }
-
-
- public void specular(float gray) {
- colorCalc(gray);
- specularFromCalc();
- }
-
-
- public void specular(float x, float y, float z) {
- colorCalc(x, y, z);
- specularFromCalc();
- }
-
-
- protected void specularFromCalc() {
- specularR = calcR;
- specularG = calcG;
- specularB = calcB;
- }
-
-
- public void shininess(float shine) {
- shininess = shine;
- }
-
-
- public void emissive(int rgb) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// emissive((float) rgb);
-//
-// } else {
-// colorCalcARGB(rgb, colorModeA);
-// emissiveFromCalc();
-// }
- colorCalc(rgb);
- emissiveFromCalc();
- }
-
-
- public void emissive(float gray) {
- colorCalc(gray);
- emissiveFromCalc();
- }
-
-
- public void emissive(float x, float y, float z) {
- colorCalc(x, y, z);
- emissiveFromCalc();
- }
-
-
- protected void emissiveFromCalc() {
- emissiveR = calcR;
- emissiveG = calcG;
- emissiveB = calcB;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // LIGHTS
-
- // The details of lighting are very implementation-specific, so this base
- // class does not handle any details of settings lights. It does however
- // display warning messages that the functions are not available.
-
-
- public void lights() {
- showMethodWarning("lights");
- }
-
- public void noLights() {
- showMethodWarning("noLights");
- }
-
- public void ambientLight(float red, float green, float blue) {
- showMethodWarning("ambientLight");
- }
-
- public void ambientLight(float red, float green, float blue,
- float x, float y, float z) {
- showMethodWarning("ambientLight");
- }
-
- public void directionalLight(float red, float green, float blue,
- float nx, float ny, float nz) {
- showMethodWarning("directionalLight");
- }
-
- public void pointLight(float red, float green, float blue,
- float x, float y, float z) {
- showMethodWarning("pointLight");
- }
-
- 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) {
- showMethodWarning("spotLight");
- }
-
- public void lightFalloff(float constant, float linear, float quadratic) {
- showMethodWarning("lightFalloff");
- }
-
- public void lightSpecular(float x, float y, float z) {
- showMethodWarning("lightSpecular");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BACKGROUND
-
-
- /**
- * Set the background to a gray or ARGB color.
- *
- * 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) or any value of the color datatype
- */
- public void background(int rgb) {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// background((float) rgb);
-//
-// } else {
-// if (format == RGB) {
-// rgb |= 0xff000000; // ignore alpha for main drawing surface
-// }
-// colorCalcARGB(rgb, colorModeA);
-// backgroundFromCalc();
-// backgroundImpl();
-// }
- colorCalc(rgb);
- backgroundFromCalc();
- }
-
-
- /**
- * See notes about alpha in background(x, y, z, a).
- */
- public void background(int rgb, float alpha) {
-// if (format == RGB) {
-// background(rgb); // ignore alpha for main drawing surface
-//
-// } else {
-// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
-// background((float) rgb, alpha);
-//
-// } else {
-// colorCalcARGB(rgb, alpha);
-// backgroundFromCalc();
-// backgroundImpl();
-// }
-// }
- colorCalc(rgb, alpha);
- backgroundFromCalc();
- }
-
-
- /**
- * Set the background to a grayscale value, based on the
- * current colorMode.
- */
- public void background(float gray) {
- colorCalc(gray);
- backgroundFromCalc();
-// backgroundImpl();
- }
-
-
- /**
- * 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 (format == RGB) {
- background(gray); // ignore alpha for main drawing surface
-
- } else {
- colorCalc(gray, alpha);
- backgroundFromCalc();
-// backgroundImpl();
- }
- }
-
-
- /**
- * 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) {
- colorCalc(x, y, z);
- backgroundFromCalc();
-// backgroundImpl();
- }
-
-
- /**
- * 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
- *
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.
- *
- * @webref color:setting
- * @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)
- *
- * @see PGraphics#stroke(float)
- * @see PGraphics#fill(float)
- * @see PGraphics#tint(float)
- * @see PGraphics#colorMode(int)
- */
- public void background(float x, float y, float z, float a) {
-// if (format == RGB) {
-// background(x, y, z); // don't allow people to set alpha
-//
-// } else {
-// colorCalc(x, y, z, a);
-// backgroundFromCalc();
-// backgroundImpl();
-// }
- colorCalc(x, y, z, a);
- backgroundFromCalc();
- }
-
-
- protected void backgroundFromCalc() {
- backgroundR = calcR;
- backgroundG = calcG;
- backgroundB = calcB;
- backgroundA = (format == RGB) ? colorModeA : calcA;
- backgroundRi = calcRi;
- backgroundGi = calcGi;
- backgroundBi = calcBi;
- backgroundAi = (format == RGB) ? 255 : calcAi;
- backgroundAlpha = (format == RGB) ? false : calcAlpha;
- backgroundColor = calcColor;
-
- backgroundImpl();
- }
-
-
- /**
- * Takes an RGB or ARGB image and sets it as the background.
- * The width and height of the image must be the same size as the sketch.
- * Use image.resize(width, height) to make short work of such a task.
- *
- * 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 ((image.width != width) || (image.height != height)) {
- throw new RuntimeException(ERROR_BACKGROUND_IMAGE_SIZE);
- }
- if ((image.format != RGB) && (image.format != ARGB)) {
- throw new RuntimeException(ERROR_BACKGROUND_IMAGE_FORMAT);
- }
- backgroundColor = 0; // just zero it out for images
- backgroundImpl(image);
- }
-
-
- /**
- * Actually set the background image. This is separated from the error
- * handling and other semantic goofiness that is shared across renderers.
- */
- protected void backgroundImpl(PImage image) {
- // blit image to the screen
- set(0, 0, image);
- }
-
-
- /**
- * Actual implementation of clearing the background, now that the
- * internal variables for background color have been set. Called by the
- * backgroundFromCalc() method, which is what all the other background()
- * methods call once the work is done.
- */
- protected void backgroundImpl() {
- pushStyle();
- pushMatrix();
- resetMatrix();
- fill(backgroundColor);
- rect(0, 0, width, height);
- popMatrix();
- popStyle();
- }
-
-
- /**
- * Callback to handle clearing the background when begin/endRaw is in use.
- * Handled as separate function for OpenGL (or other) subclasses that
- * override backgroundImpl() but still needs this to work properly.
- */
-// protected void backgroundRawImpl() {
-// if (raw != null) {
-// raw.colorMode(RGB, 1);
-// raw.noStroke();
-// raw.fill(backgroundR, backgroundG, backgroundB);
-// raw.beginShape(TRIANGLES);
-//
-// raw.vertex(0, 0);
-// raw.vertex(width, 0);
-// raw.vertex(0, height);
-//
-// raw.vertex(width, 0);
-// raw.vertex(width, height);
-// raw.vertex(0, height);
-//
-// raw.endShape();
-// }
-// }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR MODE
-
-
- /**
- * @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) {
- colorMode(mode, colorModeX, colorModeY, colorModeZ, colorModeA);
- }
-
-
- public void colorMode(int mode, float max) {
- colorMode(mode, max, max, max, 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
- *
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) {
- colorMode(mode, maxX, maxY, maxZ, colorModeA);
- }
-
-
- /**
- * 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) {
- colorMode = mode;
-
- colorModeX = maxX; // still needs to be set for hsb
- colorModeY = maxY;
- colorModeZ = maxZ;
- colorModeA = maxA;
-
- // if color max values are all 1, then no need to scale
- colorModeScale =
- ((maxA != 1) || (maxX != maxY) || (maxY != maxZ) || (maxZ != maxA));
-
- // if color is rgb/0..255 this will make it easier for the
- // red() green() etc functions
- colorModeDefault = (colorMode == RGB) &&
- (colorModeA == 255) && (colorModeX == 255) &&
- (colorModeY == 255) && (colorModeZ == 255);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR CALCULATIONS
-
- // Given input values for coloring, these functions will fill the calcXxxx
- // variables with values that have been properly filtered through the
- // current colorMode settings.
-
- // Renderers that need to subclass any drawing properties such as fill or
- // stroke will usally want to override methods like fillFromCalc (or the
- // same for stroke, ambient, etc.) That way the color calcuations are
- // covered by this based PGraphics class, leaving only a single function
- // to override/implement in the subclass.
-
-
- /**
- * Set the fill to either a grayscale value or an ARGB int.
- *
- * The problem with this code is that it has to detect between these two
- * situations automatically. This is done by checking to see if the high bits
- * (the alpha for 0xAA000000) is set, and if not, whether the color value
- * that follows is less than colorModeX (first param passed to colorMode).
- *
- * This auto-detect would break in the following situation:
- *
size(256, 256);
- * for (int i = 0; i < 256; i++) {
- * color c = color(0, 0, 0, i);
- * stroke(c);
- * line(i, 0, i, 256);
- * }
- * ...on the first time through the loop, where (i == 0), since the color
- * itself is zero (black) then it would appear indistinguishable from code
- * that reads "fill(0)". The solution is to use the four parameter versions
- * of stroke or fill to more directly specify the desired result.
- */
- protected void colorCalc(int rgb) {
- if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
- colorCalc((float) rgb);
-
- } else {
- colorCalcARGB(rgb, colorModeA);
- }
- }
-
-
- protected void colorCalc(int rgb, float alpha) {
- if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above
- colorCalc((float) rgb, alpha);
-
- } else {
- colorCalcARGB(rgb, alpha);
- }
- }
-
-
- protected void colorCalc(float gray) {
- colorCalc(gray, colorModeA);
- }
-
-
- protected void colorCalc(float gray, float alpha) {
- if (gray > colorModeX) gray = colorModeX;
- if (alpha > colorModeA) alpha = colorModeA;
-
- if (gray < 0) gray = 0;
- if (alpha < 0) alpha = 0;
-
- calcR = colorModeScale ? (gray / colorModeX) : gray;
- calcG = calcR;
- calcB = calcR;
- calcA = colorModeScale ? (alpha / colorModeA) : alpha;
-
- calcRi = (int)(calcR*255); calcGi = (int)(calcG*255);
- calcBi = (int)(calcB*255); calcAi = (int)(calcA*255);
- calcColor = (calcAi << 24) | (calcRi << 16) | (calcGi << 8) | calcBi;
- calcAlpha = (calcAi != 255);
- }
-
-
- protected void colorCalc(float x, float y, float z) {
- colorCalc(x, y, z, colorModeA);
- }
-
-
- protected void colorCalc(float x, float y, float z, float a) {
- if (x > colorModeX) x = colorModeX;
- if (y > colorModeY) y = colorModeY;
- if (z > colorModeZ) z = colorModeZ;
- if (a > colorModeA) a = colorModeA;
-
- if (x < 0) x = 0;
- if (y < 0) y = 0;
- if (z < 0) z = 0;
- if (a < 0) a = 0;
-
- switch (colorMode) {
- case RGB:
- if (colorModeScale) {
- calcR = x / colorModeX;
- calcG = y / colorModeY;
- calcB = z / colorModeZ;
- calcA = a / colorModeA;
- } else {
- calcR = x; calcG = y; calcB = z; calcA = a;
- }
- break;
-
- case HSB:
- x /= colorModeX; // h
- y /= colorModeY; // s
- z /= colorModeZ; // b
-
- calcA = colorModeScale ? (a/colorModeA) : a;
-
- if (y == 0) { // saturation == 0
- calcR = calcG = calcB = z;
-
- } else {
- float which = (x - (int)x) * 6.0f;
- float f = which - (int)which;
- float p = z * (1.0f - y);
- float q = z * (1.0f - y * f);
- float t = z * (1.0f - (y * (1.0f - f)));
-
- switch ((int)which) {
- case 0: calcR = z; calcG = t; calcB = p; break;
- case 1: calcR = q; calcG = z; calcB = p; break;
- case 2: calcR = p; calcG = z; calcB = t; break;
- case 3: calcR = p; calcG = q; calcB = z; break;
- case 4: calcR = t; calcG = p; calcB = z; break;
- case 5: calcR = z; calcG = p; calcB = q; break;
- }
- }
- break;
- }
- calcRi = (int)(255*calcR); calcGi = (int)(255*calcG);
- calcBi = (int)(255*calcB); calcAi = (int)(255*calcA);
- calcColor = (calcAi << 24) | (calcRi << 16) | (calcGi << 8) | calcBi;
- calcAlpha = (calcAi != 255);
- }
-
-
- /**
- * Unpacks AARRGGBB color for direct use with colorCalc.
- *
- * Handled here with its own function since this is indepenent
- * of the color mode.
- *
- * Strangely the old version of this code ignored the alpha
- * value. not sure if that was a bug or what.
- *
- * Note, no need for a bounds check since it's a 32 bit number.
- */
- protected void colorCalcARGB(int argb, float alpha) {
- if (alpha == colorModeA) {
- calcAi = (argb >> 24) & 0xff;
- calcColor = argb;
- } else {
- calcAi = (int) (((argb >> 24) & 0xff) * (alpha / colorModeA));
- calcColor = (calcAi << 24) | (argb & 0xFFFFFF);
- }
- calcRi = (argb >> 16) & 0xff;
- calcGi = (argb >> 8) & 0xff;
- calcBi = argb & 0xff;
- calcA = (float)calcAi / 255.0f;
- calcR = (float)calcRi / 255.0f;
- calcG = (float)calcGi / 255.0f;
- calcB = (float)calcBi / 255.0f;
- calcAlpha = (calcAi != 255);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR DATATYPE STUFFING
-
- // The 'color' primitive type in Processing syntax is in fact a 32-bit int.
- // These functions handle stuffing color values into a 32-bit cage based
- // on the current colorMode settings.
-
- // These functions are really slow (because they take the current colorMode
- // into account), but they're easy to use. Advanced users can write their
- // own bit shifting operations to setup 'color' data types.
-
-
- public final int color(int gray) { // ignore
- if (((gray & 0xff000000) == 0) && (gray <= colorModeX)) {
- if (colorModeDefault) {
- // bounds checking to make sure the numbers aren't to high or low
- if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
- return 0xff000000 | (gray << 16) | (gray << 8) | gray;
- } else {
- colorCalc(gray);
- }
- } else {
- colorCalcARGB(gray, colorModeA);
- }
- return calcColor;
- }
-
-
- public final int color(float gray) { // ignore
- colorCalc(gray);
- return calcColor;
- }
-
-
- /**
- * @param gray can be packed ARGB or a gray in this case
- */
- public final int color(int gray, int alpha) { // ignore
- if (colorModeDefault) {
- // bounds checking to make sure the numbers aren't to high or low
- if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
- if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
-
- return ((alpha & 0xff) << 24) | (gray << 16) | (gray << 8) | gray;
- }
- colorCalc(gray, alpha);
- return calcColor;
- }
-
-
- /**
- * @param rgb can be packed ARGB or a gray in this case
- */
- public final int color(int rgb, float alpha) { // ignore
- if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
- colorCalc(rgb, alpha);
- } else {
- colorCalcARGB(rgb, alpha);
- }
- return calcColor;
- }
-
-
- public final int color(float gray, float alpha) { // ignore
- colorCalc(gray, alpha);
- return calcColor;
- }
-
-
- public final int color(int x, int y, int z) { // ignore
- if (colorModeDefault) {
- // bounds checking to make sure the numbers aren't to high or low
- if (x > 255) x = 255; else if (x < 0) x = 0;
- if (y > 255) y = 255; else if (y < 0) y = 0;
- if (z > 255) z = 255; else if (z < 0) z = 0;
-
- return 0xff000000 | (x << 16) | (y << 8) | z;
- }
- colorCalc(x, y, z);
- return calcColor;
- }
-
-
- public final int color(float x, float y, float z) { // ignore
- colorCalc(x, y, z);
- return calcColor;
- }
-
-
- public final int color(int x, int y, int z, int a) { // ignore
- if (colorModeDefault) {
- // bounds checking to make sure the numbers aren't to high or low
- if (a > 255) a = 255; else if (a < 0) a = 0;
- if (x > 255) x = 255; else if (x < 0) x = 0;
- if (y > 255) y = 255; else if (y < 0) y = 0;
- if (z > 255) z = 255; else if (z < 0) z = 0;
-
- return (a << 24) | (x << 16) | (y << 8) | z;
- }
- colorCalc(x, y, z, a);
- return calcColor;
- }
-
-
- public final int color(float x, float y, float z, float a) { // ignore
- colorCalc(x, y, z, a);
- return calcColor;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR DATATYPE EXTRACTION
-
- // Vee have veys of making the colors talk.
-
-
- /**
- * 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) {
- float c = (what >> 24) & 0xff;
- if (colorModeA == 255) return c;
- return (c / 255.0f) * colorModeA;
- }
-
-
- /**
- * 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:
- *
- * @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) {
- float c = (what >> 16) & 0xff;
- if (colorModeDefault) return c;
- return (c / 255.0f) * colorModeX;
- }
-
-
- /**
- * 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.
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:
- *
- * @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) {
- float c = (what >> 8) & 0xff;
- if (colorModeDefault) return c;
- return (c / 255.0f) * colorModeY;
- }
-
-
- /**
- * 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.
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:
- *
- * @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) {
- float c = (what) & 0xff;
- if (colorModeDefault) return c;
- return (c / 255.0f) * colorModeZ;
- }
-
-
- /**
- * 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) {
- if (what != cacheHsbKey) {
- Color.RGBtoHSB((what >> 16) & 0xff, (what >> 8) & 0xff,
- what & 0xff, cacheHsbValue);
- cacheHsbKey = what;
- }
- return cacheHsbValue[0] * colorModeX;
- }
-
-
- /**
- * 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) {
- if (what != cacheHsbKey) {
- Color.RGBtoHSB((what >> 16) & 0xff, (what >> 8) & 0xff,
- what & 0xff, cacheHsbValue);
- cacheHsbKey = what;
- }
- return cacheHsbValue[1] * colorModeY;
- }
-
-
- /**
- * 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) {
- if (what != cacheHsbKey) {
- Color.RGBtoHSB((what >> 16) & 0xff, (what >> 8) & 0xff,
- what & 0xff, cacheHsbValue);
- cacheHsbKey = what;
- }
- return cacheHsbValue[2] * colorModeZ;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR DATATYPE INTERPOLATION
-
- // Against our better judgement.
-
-
- /**
- * 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 lerpColor(c1, c2, amt, colorMode);
- }
-
- static float[] lerpColorHSB1;
- static float[] lerpColorHSB2;
-
- /**
- * 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) {
- if (mode == RGB) {
- float a1 = ((c1 >> 24) & 0xff);
- float r1 = (c1 >> 16) & 0xff;
- float g1 = (c1 >> 8) & 0xff;
- float b1 = c1 & 0xff;
- float a2 = (c2 >> 24) & 0xff;
- float r2 = (c2 >> 16) & 0xff;
- float g2 = (c2 >> 8) & 0xff;
- float b2 = c2 & 0xff;
-
- return (((int) (a1 + (a2-a1)*amt) << 24) |
- ((int) (r1 + (r2-r1)*amt) << 16) |
- ((int) (g1 + (g2-g1)*amt) << 8) |
- ((int) (b1 + (b2-b1)*amt)));
-
- } else if (mode == HSB) {
- if (lerpColorHSB1 == null) {
- lerpColorHSB1 = new float[3];
- lerpColorHSB2 = new float[3];
- }
-
- float a1 = (c1 >> 24) & 0xff;
- float a2 = (c2 >> 24) & 0xff;
- int alfa = ((int) (a1 + (a2-a1)*amt)) << 24;
-
- Color.RGBtoHSB((c1 >> 16) & 0xff, (c1 >> 8) & 0xff, c1 & 0xff,
- lerpColorHSB1);
- Color.RGBtoHSB((c2 >> 16) & 0xff, (c2 >> 8) & 0xff, c2 & 0xff,
- lerpColorHSB2);
-
- /* If mode is HSB, this will take the shortest path around the
- * color wheel to find the new color. For instance, red to blue
- * will go red violet blue (backwards in hue space) rather than
- * cycling through ROYGBIV.
- */
- // Disabling rollover (wasn't working anyway) for 0126.
- // Otherwise it makes full spectrum scale impossible for
- // those who might want it...in spite of how despicable
- // a full spectrum scale might be.
- // roll around when 0.9 to 0.1
- // more than 0.5 away means that it should roll in the other direction
- /*
- float h1 = lerpColorHSB1[0];
- float h2 = lerpColorHSB2[0];
- if (Math.abs(h1 - h2) > 0.5f) {
- if (h1 > h2) {
- // i.e. h1 is 0.7, h2 is 0.1
- h2 += 1;
- } else {
- // i.e. h1 is 0.1, h2 is 0.7
- h1 += 1;
- }
- }
- float ho = (PApplet.lerp(lerpColorHSB1[0], lerpColorHSB2[0], amt)) % 1.0f;
- */
- float ho = PApplet.lerp(lerpColorHSB1[0], lerpColorHSB2[0], amt);
- float so = PApplet.lerp(lerpColorHSB1[1], lerpColorHSB2[1], amt);
- float bo = PApplet.lerp(lerpColorHSB1[2], lerpColorHSB2[2], amt);
-
- return alfa | (Color.HSBtoRGB(ho, so, bo) & 0xFFFFFF);
- }
- return 0;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BEGINRAW/ENDRAW
-
-
- /**
- * Record individual lines and triangles by echoing them to another renderer.
- */
- public void beginRaw(PGraphics rawGraphics) { // ignore
- this.raw = rawGraphics;
- rawGraphics.beginDraw();
- }
-
-
- public void endRaw() { // ignore
- if (raw != null) {
- // for 3D, need to flush any geometry that's been stored for sorting
- // (particularly if the ENABLE_DEPTH_SORT hint is set)
- flush();
-
- // just like beginDraw, this will have to be called because
- // endDraw() will be happening outside of draw()
- raw.endDraw();
- raw.dispose();
- raw = null;
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // WARNINGS and EXCEPTIONS
-
-
- static protected HashMap warnings;
-
-
- /**
- * Show a renderer error, and keep track of it so that it's only shown once.
- * @param msg the error message (which will be stored for later comparison)
- */
- static public void showWarning(String msg) { // ignore
- if (warnings == null) {
- warnings = new HashMap();
- }
- if (!warnings.containsKey(msg)) {
- System.err.println(msg);
- warnings.put(msg, new Object());
- }
- }
-
-
- /**
- * Display a warning that the specified method is only available with 3D.
- * @param method The method name (no parentheses)
- */
- static protected void showDepthWarning(String method) {
- showWarning(method + "() can only be used with a renderer that " +
- "supports 3D, such as P3D or OPENGL.");
- }
-
-
- /**
- * Display a warning that the specified method that takes x, y, z parameters
- * can only be used with x and y parameters in this renderer.
- * @param method The method name (no parentheses)
- */
- static protected void showDepthWarningXYZ(String method) {
- showWarning(method + "() with x, y, and z coordinates " +
- "can only be used with a renderer that " +
- "supports 3D, such as P3D or OPENGL. " +
- "Use a version without a z-coordinate instead.");
- }
-
-
- /**
- * Display a warning that the specified method is simply unavailable.
- */
- static protected void showMethodWarning(String method) {
- showWarning(method + "() is not available with this renderer.");
- }
-
-
- /**
- * Error that a particular variation of a method is unavailable (even though
- * other variations are). For instance, if vertex(x, y, u, v) is not
- * available, but vertex(x, y) is just fine.
- */
- static protected void showVariationWarning(String str) {
- showWarning(str + " is not available with this renderer.");
- }
-
-
- /**
- * Display a warning that the specified method is not implemented, meaning
- * that it could be either a completely missing function, although other
- * variations of it may still work properly.
- */
- static protected void showMissingWarning(String method) {
- showWarning(method + "(), or this particular variation of it, " +
- "is not available with this renderer.");
- }
-
-
- /**
- * Show an renderer-related exception that halts the program. Currently just
- * wraps the message as a RuntimeException and throws it, but might do
- * something more specific might be used in the future.
- */
- static public void showException(String msg) { // ignore
- throw new RuntimeException(msg);
- }
-
-
- /**
- * Same as below, but defaults to a 12 point font, just as MacWrite intended.
- */
- protected void defaultFontOrDeath(String method) {
- defaultFontOrDeath(method, 12);
- }
-
-
- /**
- * First try to create a default font, but if that's not possible, throw
- * an exception that halts the program because textFont() has not been used
- * prior to the specified method.
- */
- protected void defaultFontOrDeath(String method, float size) {
- if (parent != null) {
- textFont = parent.createDefaultFont(size);
- } else {
- throw new RuntimeException("Use textFont() before " + method + "()");
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // RENDERER SUPPORT QUERIES
-
-
- /**
- * 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.
- *
- * A better name? showFrame, displayable, isVisible, visible, shouldDisplay,
- * what to call this?
- */
- public boolean displayable() {
- return true;
- }
-
-
- /**
- * Return true if this renderer supports 2D drawing. Defaults to true.
- */
- public boolean is2D() {
- return true;
- }
-
-
- /**
- * Return true if this renderer supports 2D drawing. Defaults to true.
- */
- public boolean is3D() {
- return false;
- }
-}
diff --git a/core/src/processing/core/PGraphics2D.java b/core/src/processing/core/PGraphics2D.java
deleted file mode 100644
index 0c0bfa77e94..00000000000
--- a/core/src/processing/core/PGraphics2D.java
+++ /dev/null
@@ -1,2144 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2006-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;
-
-import java.awt.Toolkit;
-import java.awt.image.DirectColorModel;
-import java.awt.image.MemoryImageSource;
-import java.util.Arrays;
-
-
-/**
- * Subclass of PGraphics that handles fast 2D rendering using a
- * MemoryImageSource. The renderer found in this class is not as accurate as
- * PGraphicsJava2D, but offers certain speed tradeoffs, particular when
- * messing with the pixels array, or displaying image or video data.
- */
-public class PGraphics2D extends PGraphics {
-
- PMatrix2D ctm = new PMatrix2D();
-
- //PPolygon polygon; // general polygon to use for shape
- PPolygon fpolygon; // used to fill polys for tri or quad strips
- PPolygon spolygon; // stroke/line polygon
- float svertices[][]; // temp vertices used for stroking end of poly
-
- PPolygon tpolygon;
- int[] vertexOrder;
-
- PLine line;
-
- float[][] matrixStack = new float[MATRIX_STACK_DEPTH][6];
- int matrixStackDepth;
-
- DirectColorModel cm;
- MemoryImageSource mis;
-
-
- //////////////////////////////////////////////////////////////
-
-
- public PGraphics2D() { }
-
-
- //public void setParent(PApplet parent)
-
-
- //public void setPrimary(boolean primary)
-
-
- //public void setPath(String path)
-
-
- //public void setSize(int iwidth, int iheight)
-
-
- protected void allocate() {
- pixelCount = width * height;
- pixels = new int[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);
- }
- }
-
-
- //public void dispose()
-
-
-
- //////////////////////////////////////////////////////////////
-
-
- public boolean canDraw() {
- return true;
- }
-
-
- 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();
-
-// polygon = new PPolygon(this);
- fpolygon = new PPolygon(this);
- spolygon = new PPolygon(this);
- spolygon.vertexCount = 4;
- svertices = new float[2][];
- }
-
- resetMatrix(); // reset model matrix
-
- // reset vertices
- vertexCount = 0;
- }
-
-
- public void endDraw() {
- 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();
- }
-
-
- // public void flush()
-
-
-
- //////////////////////////////////////////////////////////////
-
-
- //protected void checkSettings()
-
-
- //protected void defaultSettings()
-
-
- //protected void reapplySettings()
-
-
-
- //////////////////////////////////////////////////////////////
-
-
- //public void hint(int which)
-
-
-
- //////////////////////////////////////////////////////////////
-
-
- //public void beginShape()
-
-
- public void beginShape(int kind) {
- shape = kind;
- vertexCount = 0;
- curveVertexCount = 0;
-
-// polygon.reset(0);
- fpolygon.reset(4);
- spolygon.reset(4);
-
- textureImage = null;
-// polygon.interpUV = false;
- }
-
-
- //public void edge(boolean e)
-
-
- //public void normal(float nx, float ny, float nz)
-
-
- //public void textureMode(int mode)
-
-
- //public void texture(PImage image)
-
-
- /*
- public void vertex(float x, float y) {
- if (shape == POINTS) {
- point(x, y);
- } else {
- super.vertex(x, y);
- }
- }
- */
-
-
- public void vertex(float x, float y, float z) {
- showDepthWarningXYZ("vertex");
- }
-
-
- //public void vertex(float x, float y, float u, float v)
-
-
- public void vertex(float x, float y, float z, float u, float v) {
- showDepthWarningXYZ("vertex");
- }
-
-
- //protected void vertexTexture(float u, float v);
-
-
- public void breakShape() {
- showWarning("This renderer cannot handle concave shapes " +
- "or shapes with holes.");
- }
-
-
- //public void endShape()
-
-
- public void endShape(int mode) {
- if (ctm.isIdentity()) {
- for (int i = 0; i < vertexCount; i++) {
- vertices[i][TX] = vertices[i][X];
- vertices[i][TY] = vertices[i][Y];
- }
- } else {
- for (int i = 0; i < vertexCount; i++) {
- vertices[i][TX] = ctm.multX(vertices[i][X], vertices[i][Y]);
- vertices[i][TY] = ctm.multY(vertices[i][X], vertices[i][Y]);
- }
- }
-
- // ------------------------------------------------------------------
- // TEXTURES
-
- fpolygon.texture(textureImage);
-
- // ------------------------------------------------------------------
- // COLORS
- // calculate RGB for each vertex
-
- spolygon.interpARGB = true; //strokeChanged; //false;
- fpolygon.interpARGB = true; //fillChanged; //false;
-
- // all the values for r, g, b have been set with calls to vertex()
- // (no need to re-calculate anything here)
-
- // ------------------------------------------------------------------
- // RENDER SHAPES
-
- int increment;
-
- switch (shape) {
- case POINTS:
- // stroke cannot change inside beginShape(POINTS);
- if (stroke) {
- if ((ctm.m00 == ctm.m11) && (strokeWeight == 1)) {
- for (int i = 0; i < vertexCount; i++) {
- thin_point(vertices[i][TX], vertices[i][TY], strokeColor);
- }
- } else {
- for (int i = 0; i < vertexCount; i++) {
- float[] v = vertices[i];
- thick_point(v[TX], v[TY], v[TZ], v[SR], v[SG], v[SB], v[SA]);
- }
- }
- }
- break;
-
- case LINES:
- if (stroke) {
- // increment by two for individual lines
- increment = (shape == LINES) ? 2 : 1;
- draw_lines(vertices, vertexCount-1, 1, increment, 0);
- }
- break;
-
- case TRIANGLE_FAN:
- // do fill and stroke separately because otherwise
- // the lines will be stroked more than necessary
- if (fill || textureImage != null) {
- fpolygon.vertexCount = 3;
-
- for (int i = 1; i < vertexCount-1; i++) {
-// System.out.println(i + " of " + vertexCount);
-
- fpolygon.vertices[2][R] = vertices[0][R];
- fpolygon.vertices[2][G] = vertices[0][G];
- fpolygon.vertices[2][B] = vertices[0][B];
- fpolygon.vertices[2][A] = vertices[0][A];
-
- fpolygon.vertices[2][TX] = vertices[0][TX];
- fpolygon.vertices[2][TY] = vertices[0][TY];
-
- if (textureImage != null) {
- fpolygon.vertices[2][U] = vertices[0][U];
- fpolygon.vertices[2][V] = vertices[0][V];
- }
-// System.out.println(fpolygon.vertices[2][TX] + " " + fpolygon.vertices[2][TY]);
-
- for (int j = 0; j < 2; j++) {
- fpolygon.vertices[j][R] = vertices[i+j][R];
- fpolygon.vertices[j][G] = vertices[i+j][G];
- fpolygon.vertices[j][B] = vertices[i+j][B];
- fpolygon.vertices[j][A] = vertices[i+j][A];
-
- fpolygon.vertices[j][TX] = vertices[i+j][TX];
- fpolygon.vertices[j][TY] = vertices[i+j][TY];
-
-// System.out.println(fpolygon.vertices[j][TX] + " " + fpolygon.vertices[j][TY]);
-
- if (textureImage != null) {
- fpolygon.vertices[j][U] = vertices[i+j][U];
- fpolygon.vertices[j][V] = vertices[i+j][V];
- }
- }
-// System.out.println();
- fpolygon.render();
- }
- }
- if (stroke) {
- // draw internal lines
- for (int i = 1; i < vertexCount; i++) {
- draw_line(vertices[0], vertices[i]);
- }
- // draw a ring around the outside
- for (int i = 1; i < vertexCount-1; i++) {
- draw_line(vertices[i], vertices[i+1]);
- }
- // close the shape
- draw_line(vertices[vertexCount-1], vertices[1]);
- }
- break;
-
- case TRIANGLES:
- case TRIANGLE_STRIP:
- increment = (shape == TRIANGLES) ? 3 : 1;
- // do fill and stroke separately because otherwise
- // the lines will be stroked more than necessary
- if (fill || textureImage != null) {
- fpolygon.vertexCount = 3;
- for (int i = 0; i < vertexCount-2; i += increment) {
- for (int j = 0; j < 3; j++) {
- fpolygon.vertices[j][R] = vertices[i+j][R];
- fpolygon.vertices[j][G] = vertices[i+j][G];
- fpolygon.vertices[j][B] = vertices[i+j][B];
- fpolygon.vertices[j][A] = vertices[i+j][A];
-
- fpolygon.vertices[j][TX] = vertices[i+j][TX];
- fpolygon.vertices[j][TY] = vertices[i+j][TY];
- fpolygon.vertices[j][TZ] = vertices[i+j][TZ];
-
- if (textureImage != null) {
- fpolygon.vertices[j][U] = vertices[i+j][U];
- fpolygon.vertices[j][V] = vertices[i+j][V];
- }
- }
- fpolygon.render();
- }
- }
- if (stroke) {
- // first draw all vertices as a line strip
- if (shape == TRIANGLE_STRIP) {
- draw_lines(vertices, vertexCount-1, 1, 1, 0);
- } else {
- draw_lines(vertices, vertexCount-1, 1, 1, 3);
- }
- // then draw from vertex (n) to (n+2)
- // incrementing n using the same as above
- draw_lines(vertices, vertexCount-2, 2, increment, 0);
- // changed this to vertexCount-2, because it seemed
- // to be adding an extra (nonexistant) line
- }
- break;
-
- case QUADS:
- if (fill || textureImage != null) {
- fpolygon.vertexCount = 4;
- for (int i = 0; i < vertexCount-3; i += 4) {
- for (int j = 0; j < 4; j++) {
- int jj = i+j;
- fpolygon.vertices[j][R] = vertices[jj][R];
- fpolygon.vertices[j][G] = vertices[jj][G];
- fpolygon.vertices[j][B] = vertices[jj][B];
- fpolygon.vertices[j][A] = vertices[jj][A];
-
- fpolygon.vertices[j][TX] = vertices[jj][TX];
- fpolygon.vertices[j][TY] = vertices[jj][TY];
- fpolygon.vertices[j][TZ] = vertices[jj][TZ];
-
- if (textureImage != null) {
- fpolygon.vertices[j][U] = vertices[jj][U];
- fpolygon.vertices[j][V] = vertices[jj][V];
- }
- }
- fpolygon.render();
- }
- }
- if (stroke) {
- for (int i = 0; i < vertexCount-3; i += 4) {
- draw_line(vertices[i+0], vertices[i+1]);
- draw_line(vertices[i+1], vertices[i+2]);
- draw_line(vertices[i+2], vertices[i+3]);
- draw_line(vertices[i+3], vertices[i+0]);
- }
- }
- break;
-
- case QUAD_STRIP:
- if (fill || textureImage != null) {
- fpolygon.vertexCount = 4;
- for (int i = 0; i < vertexCount-3; i += 2) {
- for (int j = 0; j < 4; j++) {
- int jj = i+j;
- if (j == 2) jj = i+3; // swap 2nd and 3rd vertex
- if (j == 3) jj = i+2;
-
- fpolygon.vertices[j][R] = vertices[jj][R];
- fpolygon.vertices[j][G] = vertices[jj][G];
- fpolygon.vertices[j][B] = vertices[jj][B];
- fpolygon.vertices[j][A] = vertices[jj][A];
-
- fpolygon.vertices[j][TX] = vertices[jj][TX];
- fpolygon.vertices[j][TY] = vertices[jj][TY];
- fpolygon.vertices[j][TZ] = vertices[jj][TZ];
-
- if (textureImage != null) {
- fpolygon.vertices[j][U] = vertices[jj][U];
- fpolygon.vertices[j][V] = vertices[jj][V];
- }
- }
- fpolygon.render();
- }
- }
- if (stroke) {
- draw_lines(vertices, vertexCount-1, 1, 2, 0); // inner lines
- draw_lines(vertices, vertexCount-2, 2, 1, 0); // outer lines
- }
- break;
-
- case POLYGON:
- if (isConvex()) {
- if (fill || textureImage != null) {
- //System.out.println("convex");
- fpolygon.renderPolygon(vertices, vertexCount);
- //if (stroke) polygon.unexpand();
- }
-
- if (stroke) {
- draw_lines(vertices, vertexCount-1, 1, 1, 0);
- if (mode == CLOSE) {
- // draw the last line connecting back to the first point in poly
- //svertices[0] = vertices[vertexCount-1];
- //svertices[1] = vertices[0];
- //draw_lines(svertices, 1, 1, 1, 0);
- draw_line(vertices[vertexCount-1], vertices[0]);
- }
- }
- } else { // not convex
- //System.out.println("concave");
- if (fill || textureImage != null) {
- // the triangulator produces polygons that don't align
- // when smoothing is enabled. but if there is a stroke around
- // the polygon, then smoothing can be temporarily disabled.
- boolean smoov = smooth;
- //if (stroke && !hints[DISABLE_SMOOTH_HACK]) smooth = false;
- if (stroke) smooth = false;
- concaveRender();
- //if (stroke && !hints[DISABLE_SMOOTH_HACK]) smooth = smoov;
- if (stroke) smooth = smoov;
- }
-
- if (stroke) {
- draw_lines(vertices, vertexCount-1, 1, 1, 0);
- if (mode == CLOSE) {
- // draw the last line connecting back
- // to the first point in poly
-// svertices[0] = vertices[vertexCount-1];
-// svertices[1] = vertices[0];
-// draw_lines(svertices, 1, 1, 1, 0);
- draw_line(vertices[vertexCount-1], vertices[0]);
- }
- }
- }
- break;
- }
-
- // to signify no shape being drawn
- shape = 0;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CONCAVE/CONVEX POLYGONS
-
-
- private boolean isConvex() {
- //float v[][] = polygon.vertices;
- //int n = polygon.vertexCount;
- //int j,k;
- //float tol = 0.001f;
-
- if (vertexCount < 3) {
- // ERROR: this is a line or a point, render as convex
- return true;
- }
-
- int flag = 0;
- // iterate along border doing dot product.
- // if the sign of the result changes, then is concave
- for (int i = 0; i < vertexCount; i++) {
- float[] vi = vertices[i];
- float[] vj = vertices[(i + 1) % vertexCount];
- float[] vk = vertices[(i + 2) % vertexCount];
- float calc = ((vj[TX] - vi[TX]) * (vk[TY] - vj[TY]) -
- (vj[TY] - vi[TY]) * (vk[TX] - vj[TX]));
- if (calc < 0) {
- flag |= 1;
- } else if (calc > 0) {
- flag |= 2;
- }
- if (flag == 3) {
- return false; // CONCAVE
- }
- }
- if (flag != 0) {
- return true; // CONVEX
- } else {
- // ERROR: colinear points, self intersection
- // treat as CONVEX
- return true;
- }
- }
-
-
- /**
- * 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 concaveRender() {
- if (vertexOrder == null || vertexOrder.length != vertices.length) {
- vertexOrder = new int[vertices.length];
-// int[] temp = new int[vertices.length];
-// // since vertex_start may not be zero, might need to keep old stuff around
-// PApplet.arrayCopy(vertexOrder, temp, vertexCount);
-// vertexOrder = temp;
- }
-
- if (tpolygon == null) {
- tpolygon = new PPolygon(this);
- }
- tpolygon.reset(3);
-
- // first we check if the polygon goes clockwise or counterclockwise
- float area = 0;
- for (int p = vertexCount - 1, q = 0; q < vertexCount; p = q++) {
- area += (vertices[q][X] * vertices[p][Y] -
- vertices[p][X] * vertices[q][Y]);
- }
- // ain't nuthin there
- if (area == 0) return;
-
- // 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[0];
- float vlast[] = vertices[vertexCount-1];
- if ((Math.abs(vfirst[X] - vlast[X]) < EPSILON) &&
- (Math.abs(vfirst[Y] - vlast[Y]) < EPSILON) &&
- (Math.abs(vfirst[Z] - vlast[Z]) < EPSILON)) {
- vertexCount--;
- }
-
- // then sort the vertices so they are always in a counterclockwise order
- for (int i = 0; i < vertexCount; i++) {
- vertexOrder[i] = (area > 0) ? i : (vertexCount-1 - i);
- }
-
- // remove vc-2 Vertices, creating 1 triangle every time
- int vc = vertexCount; // vc will be decremented while working
- 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]][X];
- double Ay = 10 * vertices[vertexOrder[u]][Y];
- double Bx = -10 * vertices[vertexOrder[v]][X];
- double By = 10 * vertices[vertexOrder[v]][Y];
- double Cx = -10 * vertices[vertexOrder[w]][X];
- double Cy = 10 * vertices[vertexOrder[w]][Y];
-
- // 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]][X];
- double Py = 10 * vertices[vertexOrder[p]][Y];
-
- 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) {
- tpolygon.renderTriangle(vertices[vertexOrder[u]],
- vertices[vertexOrder[v]],
- vertices[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;
- }
- }
- }
-
-
- /*
- // triangulate the current polygon
- private void concaveRender() {
- float polyVertices[][] = polygon.vertices;
-
- if (tpolygon == null) {
- // allocate on first use, rather than slowing
- // the startup of the class.
- tpolygon = new PPolygon(this);
- tpolygon_vertex_order = new int[TPOLYGON_MAX_VERTICES];
- }
- tpolygon.reset(3);
-
- // copy render parameters
-
- if (textureImage != null) {
- tpolygon.texture(textureImage); //polygon.timage);
- }
-
- tpolygon.interpX = polygon.interpX;
- tpolygon.interpUV = polygon.interpUV;
- tpolygon.interpARGB = polygon.interpARGB;
-
- // simple ear clipping polygon triangulation
- // addapted from code by john w. ratcliff (jratcliff@verant.com)
-
- // 1 - first we check if the polygon goes CW or CCW
- // CW-CCW ordering adapted from code by
- // Joseph O'Rourke orourke@cs.smith.edu
- // 1A - we start by finding the lowest-right most vertex
-
- boolean ccw = false; // clockwise
-
- int n = polygon.vertexCount;
- int mm; // postion for LR vertex
- //float min[] = new float[2];
- float minX = polyVertices[0][TX];
- float minY = polyVertices[0][TY];
- mm = 0;
-
- for(int i = 0; i < n; i++ ) {
- if ((polyVertices[i][TY] < minY) ||
- ((polyVertices[i][TY] == minY) && (polyVertices[i][TX] > minX) )
- ) {
- mm = i;
- minX = polyVertices[mm][TX];
- minY = polyVertices[mm][TY];
- }
- }
-
- // 1B - now we compute the cross product of the edges of this vertex
- float cp;
- int mm1;
-
- // just for renaming
- float a[] = new float[2];
- float b[] = new float[2];
- float c[] = new float[2];
-
- mm1 = (mm + (n-1)) % n;
-
- // assign a[0] to point to poly[m1][0] etc.
- for(int i = 0; i < 2; i++ ) {
- a[i] = polyVertices[mm1][i];
- b[i] = polyVertices[mm][i];
- c[i] = polyVertices[(mm+1)%n][i];
- }
-
- cp = a[0] * b[1] - a[1] * b[0] +
- a[1] * c[0] - a[0] * c[1] +
- b[0] * c[1] - c[0] * b[1];
-
- if ( cp > 0 )
- ccw = true; // CCW
- else
- ccw = false; // CW
-
- // 1C - then we sort the vertices so they
- // are always in a counterclockwise order
- //int j = 0;
- if (!ccw) {
- // keep the same order
- for (int i = 0; i < n; i++) {
- tpolygon_vertex_order[i] = i;
- }
-
- } else {
- // invert the order
- for (int i = 0; i < n; i++) {
- tpolygon_vertex_order[i] = (n - 1) - i;
- }
- }
-
- // 2 - begin triangulation
- // resulting triangles are stored in the triangle array
- // remove vc-2 Vertices, creating 1 triangle every time
- int vc = n;
- 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
-
- // triangle A B C
- float Ax, Ay, Bx, By, Cx, Cy, Px, Py;
-
- Ax = -polyVertices[tpolygon_vertex_order[u]][TX];
- Ay = polyVertices[tpolygon_vertex_order[u]][TY];
- Bx = -polyVertices[tpolygon_vertex_order[v]][TX];
- By = polyVertices[tpolygon_vertex_order[v]][TY];
- Cx = -polyVertices[tpolygon_vertex_order[w]][TX];
- Cy = polyVertices[tpolygon_vertex_order[w]][TY];
-
- if ( EPSILON > (((Bx-Ax) * (Cy-Ay)) - ((By-Ay) * (Cx-Ax)))) {
- continue;
- }
-
- for (int p = 0; p < vc; p++) {
-
- // this part is a bit osbscure, basically what it does
- // is test if this tree vertices are and ear or not, looking for
- // intersections with the remaining vertices using a cross product
- float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
- float cCROSSap, bCROSScp, aCROSSbp;
-
- if( (p == u) || (p == v) || (p == w) ) {
- continue;
- }
-
- Px = -polyVertices[tpolygon_vertex_order[p]][TX];
- Py = polyVertices[tpolygon_vertex_order[p]][TY];
-
- ax = Cx - Bx; ay = Cy - By;
- bx = Ax - Cx; by = Ay - Cy;
- cx = Bx - Ax; cy = By - Ay;
- apx= Px - Ax; apy= Py - Ay;
- bpx= Px - Bx; bpy= Py - By;
- cpx= Px - Cx; cpy= Py - Cy;
-
- aCROSSbp = ax * bpy - ay * bpx;
- cCROSSap = cx * apy - cy * apx;
- bCROSScp = bx * cpy - by * cpx;
-
- if ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f)) {
- snip = false;
- }
- }
-
- if (snip) {
- // yes, the trio is an ear, render it and cut it
-
- int triangle_vertices[] = new int[3];
- int s,t;
-
- // true names of the vertices
- triangle_vertices[0] = tpolygon_vertex_order[u];
- triangle_vertices[1] = tpolygon_vertex_order[v];
- triangle_vertices[2] = tpolygon_vertex_order[w];
-
- // create triangle
- //render_triangle(triangle_vertices);
- //private final void render_triangle(int[] triangle_vertices) {
- // copy all fields of the triangle vertices
- for (int i = 0; i < 3; i++) {
- float[] src = polygon.vertices[triangle_vertices[i]];
- float[] dest = tpolygon.vertices[i];
- for (int k = 0; k < VERTEX_FIELD_COUNT; k++) {
- dest[k] = src[k];
- }
- }
- // render triangle
- tpolygon.render();
- //}
-
- m++;
-
- // remove v from remaining polygon
- for( s = v, t = v + 1; t < vc; s++, t++) {
- tpolygon_vertex_order[s] = tpolygon_vertex_order[t];
- }
-
- vc--;
-
- // resest error detection counter
- count = 2 * vc;
- }
- }
- }
- */
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BEZIER VERTICES
-
-
- //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)
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CURVE VERTICES
-
-
- //public void curveVertex(float x, float y)
-
-
- //public void curveVertex(float x, float y, float z)
-
-
-
- //////////////////////////////////////////////////////////////
-
- // FLUSH
-
-
- //public void flush()
-
-
-
- //////////////////////////////////////////////////////////////
-
- // PRIMITIVES
-
-
- //public void point(float x, float y)
-
-
- public void point(float x, float y, float z) {
- showDepthWarningXYZ("point");
- }
-
-
- //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
-
-
- protected void rectImpl(float x1f, float y1f, float x2f, float y2f) {
- if (smooth || strokeAlpha || ctm.isWarped()) {
- // screw the efficiency, send this off to beginShape().
- super.rectImpl(x1f, y1f, x2f, y2f);
-
- } else {
- int x1 = (int) (x1f + ctm.m02);
- int y1 = (int) (y1f + ctm.m12);
- int x2 = (int) (x2f + ctm.m02);
- int y2 = (int) (y2f + ctm.m12);
-
- if (fill) {
- simple_rect_fill(x1, y1, x2, y2);
- }
-
- if (stroke) {
- if (strokeWeight == 1) {
- thin_flat_line(x1, y1, x2, y1);
- thin_flat_line(x2, y1, x2, y2);
- thin_flat_line(x2, y2, x1, y2);
- thin_flat_line(x1, y2, x1, y1);
-
- } else {
- thick_flat_line(x1, y1, strokeR, strokeG, strokeB, strokeA,
- x2, y1, strokeR, strokeG, strokeB, strokeA);
- thick_flat_line(x2, y1, strokeR, strokeG, strokeB, strokeA,
- x2, y2, strokeR, strokeG, strokeB, strokeA);
- thick_flat_line(x2, y2, strokeR, strokeG, strokeB, strokeA,
- x1, y2, strokeR, strokeG, strokeB, strokeA);
- thick_flat_line(x1, y2, strokeR, strokeG, strokeB, strokeA,
- x1, y1, strokeR, strokeG, strokeB, strokeA);
- }
- }
- }
- }
-
-
- /**
- * Draw a rectangle that hasn't been warped by the CTM (though it may be
- * translated). Just fill a bunch of pixels, or blend them if there's alpha.
- */
- private void simple_rect_fill(int x1, int y1, int x2, int y2) {
- if (y2 < y1) {
- int temp = y1; y1 = y2; y2 = temp;
- }
- if (x2 < x1) {
- int temp = x1; x1 = x2; x2 = temp;
- }
- // check to see if completely off-screen (e.g. if the left edge of the
- // rectangle is bigger than the width, and so on.)
- if ((x1 > width1) || (x2 < 0) ||
- (y1 > height1) || (y2 < 0)) return;
-
- // these only affect the fill, not the stroke
- // (otherwise strange boogers at edges b/c frame changes shape)
- if (x1 < 0) x1 = 0;
- if (x2 > width) x2 = width;
- if (y1 < 0) y1 = 0;
- if (y2 > height) y2 = height;
-
- int ww = x2 - x1;
-
- if (fillAlpha) {
- for (int y = y1; y < y2; y++) {
- int index = y*width + x1;
- for (int x = 0; x < ww; x++) {
- pixels[index] = blend_fill(pixels[index]);
- index++;
- }
- }
-
- } else {
- // on avg. 20-25% faster fill routine using System.arraycopy() [toxi 031223]
- // removed temporary row[] array for (hopefully) better performance [fry 081117]
- int hh = y2 - y1;
- // int[] row = new int[ww];
- // for (int i = 0; i < ww; i++) row[i] = fillColor;
- int index = y1 * width + x1;
- int rowIndex = index;
- for (int i = 0; i < ww; i++) {
- pixels[index + i] = fillColor;
- }
- for (int y = 0; y < hh; y++) {
- // System.arraycopy(row, 0, pixels, idx, ww);
- System.arraycopy(pixels, rowIndex, pixels, index, ww);
- index += width;
- }
- // row = null;
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // ELLIPSE AND ARC
-
-
- protected void ellipseImpl(float x, float y, float w, float h) {
- if (smooth || (strokeWeight != 1) ||
- fillAlpha || strokeAlpha || ctm.isWarped()) {
- // identical to PGraphics version, but uses POLYGON
- // for the fill instead of a TRIANGLE_FAN
- 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);
- int accuracy = (int) (TWO_PI * PApplet.dist(sx1, sy1, sx2, sy2) / 8);
- if (accuracy < 4) return; // don't bother?
- //System.out.println("diameter " + w + " " + h + " -> " + accuracy);
-
- float inc = (float)SINCOS_LENGTH / accuracy;
-
- float val = 0;
-
- if (fill) {
- boolean savedStroke = stroke;
- stroke = false;
-
- beginShape();
- for (int i = 0; i < accuracy; i++) {
- vertex(centerX + cosLUT[(int) val] * radiusH,
- centerY + sinLUT[(int) val] * radiusV);
- val += inc;
- }
- endShape(CLOSE);
-
- stroke = savedStroke;
- }
-
- if (stroke) {
- 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 += inc;
- }
- endShape(CLOSE);
-
- fill = savedFill;
- }
- } else {
- float hradius = w / 2f;
- float vradius = h / 2f;
-
- int centerX = (int) (x + hradius + ctm.m02);
- int centerY = (int) (y + vradius + ctm.m12);
-
- int hradiusi = (int) hradius;
- int vradiusi = (int) vradius;
-
- if (hradiusi == vradiusi) {
- if (fill) flat_circle_fill(centerX, centerY, hradiusi);
- if (stroke) flat_circle_stroke(centerX, centerY, hradiusi);
-
- } else {
- if (fill) flat_ellipse_internal(centerX, centerY, hradiusi, vradiusi, true);
- if (stroke) flat_ellipse_internal(centerX, centerY, hradiusi, vradiusi, false);
- }
- }
- }
-
-
- /**
- * Draw the outline around a flat circle using a bresenham-style
- * algorithm. Adapted from drawCircle function in "Computer Graphics
- * for Java Programmers" by Leen Ammeraal, p. 110.
- *
- * This function is included because the quality is so much better,
- * and the drawing significantly faster than with adaptive ellipses
- * drawn using the sine/cosine tables.
- *
- * Circle quadrants break down like so:
- *
- * @param xc x center
- * @param yc y center
- * @param r radius
- */
- private void flat_circle_stroke(int xC, int yC, int r) {
- int x = 0, y = r, u = 1, v = 2 * r - 1, E = 0;
- while (x < y) {
- thin_point(xC + x, yC + y, strokeColor); // NNE
- thin_point(xC + y, yC - x, strokeColor); // ESE
- thin_point(xC - x, yC - y, strokeColor); // SSW
- thin_point(xC - y, yC + x, strokeColor); // WNW
-
- x++; E += u; u += 2;
- if (v < 2 * E) {
- y--; E -= v; v -= 2;
- }
- if (x > y) break;
-
- thin_point(xC + y, yC + x, strokeColor); // ENE
- thin_point(xC + x, yC - y, strokeColor); // SSE
- thin_point(xC - y, yC - x, strokeColor); // WSW
- thin_point(xC - x, yC + y, strokeColor); // NNW
- }
- }
-
-
- /**
- * Heavily adapted version of the above algorithm that handles
- * filling the ellipse. Works by drawing from the center and
- * outwards to the points themselves. Has to be done this way
- * because the values for the points are changed halfway through
- * the function, making it impossible to just store a series of
- * left and right edges to be drawn more quickly.
- *
- * @param xc x center
- * @param yc y center
- * @param r radius
- */
- private void flat_circle_fill(int xc, int yc, int r) {
- int x = 0, y = r, u = 1, v = 2 * r - 1, E = 0;
- while (x < y) {
- for (int xx = xc; xx < xc + x; xx++) { // NNE
- thin_point(xx, yc + y, fillColor);
- }
- for (int xx = xc; xx < xc + y; xx++) { // ESE
- thin_point(xx, yc - x, fillColor);
- }
- for (int xx = xc - x; xx < xc; xx++) { // SSW
- thin_point(xx, yc - y, fillColor);
- }
- for (int xx = xc - y; xx < xc; xx++) { // WNW
- thin_point(xx, yc + x, fillColor);
- }
-
- x++; E += u; u += 2;
- if (v < 2 * E) {
- y--; E -= v; v -= 2;
- }
- if (x > y) break;
-
- for (int xx = xc; xx < xc + y; xx++) { // ENE
- thin_point(xx, yc + x, fillColor);
- }
- for (int xx = xc; xx < xc + x; xx++) { // SSE
- thin_point(xx, yc - y, fillColor);
- }
- for (int xx = xc - y; xx < xc; xx++) { // WSW
- thin_point(xx, yc - x, fillColor);
- }
- for (int xx = xc - x; xx < xc; xx++) { // NNW
- thin_point(xx, yc + y, fillColor);
- }
- }
- }
-
-
- // unfortunately this can't handle fill and stroke simultaneously,
- // because the fill will later replace some of the stroke points
-
- private final void flat_ellipse_symmetry(int centerX, int centerY,
- int ellipseX, int ellipseY,
- boolean filling) {
- if (filling) {
- for (int i = centerX - ellipseX + 1; i < centerX + ellipseX; i++) {
- thin_point(i, centerY - ellipseY, fillColor);
- thin_point(i, centerY + ellipseY, fillColor);
- }
- } else {
- thin_point(centerX - ellipseX, centerY + ellipseY, strokeColor);
- thin_point(centerX + ellipseX, centerY + ellipseY, strokeColor);
- thin_point(centerX - ellipseX, centerY - ellipseY, strokeColor);
- thin_point(centerX + ellipseX, centerY - ellipseY, strokeColor);
- }
- }
-
-
- /**
- * Bresenham-style ellipse drawing function, adapted from a posting to
- * comp.graphics.algortihms.
- *
- * This function is included because the quality is so much better,
- * and the drawing significantly faster than with adaptive ellipses
- * drawn using the sine/cosine tables.
- *
- * @param centerX x coordinate of the center
- * @param centerY y coordinate of the center
- * @param a horizontal radius
- * @param b vertical radius
- */
- private void flat_ellipse_internal(int centerX, int centerY,
- int a, int b, boolean filling) {
- int x, y, a2, b2, s, t;
-
- a2 = a*a;
- b2 = b*b;
- x = 0;
- y = b;
- s = a2*(1-2*b) + 2*b2;
- t = b2 - 2*a2*(2*b-1);
- flat_ellipse_symmetry(centerX, centerY, x, y, filling);
-
- do {
- if (s < 0) {
- s += 2*b2*(2*x+3);
- t += 4*b2*(x+1);
- x++;
- } else if (t < 0) {
- s += 2*b2*(2*x+3) - 4*a2*(y-1);
- t += 4*b2*(x+1) - 2*a2*(2*y-3);
- x++;
- y--;
- } else {
- s -= 4*a2*(y-1);
- t -= 2*a2*(2*y-3);
- y--;
- }
- flat_ellipse_symmetry(centerX, centerY, x, y, filling);
-
- } while (y > 0);
- }
-
-
- // TODO really need a decent arc function in here..
-
- 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();
- vertex(centerX, centerY);
- for (int i = startLUT; i < stopLUT; i++) {
- 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);
- }
- endShape(CLOSE);
-
- 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) {
- showDepthWarning("box");
- }
-
- public void box(float w, float h, float d) {
- showDepthWarning("box");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SPHERE
-
-
- public void sphereDetail(int res) {
- showDepthWarning("sphereDetail");
- }
-
- public void sphereDetail(int ures, int vres) {
- showDepthWarning("sphereDetail");
- }
-
- public void sphere(float r) {
- showDepthWarning("sphere");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BEZIER & CURVE
-
-
- 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) {
- showDepthWarningXYZ("bezier");
- }
-
-
- 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) {
- showDepthWarningXYZ("curve");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // IMAGE
-
-
- protected void imageImpl(PImage image,
- float x1, float y1, float x2, float y2,
- int u1, int v1, int u2, int v2) {
- if ((x2 - x1 == image.width) &&
- (y2 - y1 == image.height) &&
- !tint && !ctm.isWarped()) {
- simple_image(image, (int) (x1 + ctm.m02), (int) (y1 + ctm.m12), u1, v1, u2, v2);
-
- } else {
- super.imageImpl(image, x1, y1, x2, y2, u1, v1, u2, v2);
- }
- }
-
-
- /**
- * Image drawn in flat "screen space", with no scaling or warping.
- * this is so common that a special routine is included for it,
- * because the alternative is much slower.
- *
- * @param image image to be drawn
- * @param sx1 x coordinate of upper-lefthand corner in screen space
- * @param sy1 y coordinate of upper-lefthand corner in screen space
- */
- private void simple_image(PImage image, int sx1, int sy1,
- int ix1, int iy1, int ix2, int iy2) {
- int sx2 = sx1 + image.width;
- int sy2 = sy1 + image.height;
-
- // don't draw if completely offscreen
- // (without this check, ArrayIndexOutOfBoundsException)
- if ((sx1 > width1) || (sx2 < 0) ||
- (sy1 > height1) || (sy2 < 0)) return;
-
- if (sx1 < 0) { // off left edge
- ix1 -= sx1;
- sx1 = 0;
- }
- if (sy1 < 0) { // off top edge
- iy1 -= sy1;
- sy1 = 0;
- }
- if (sx2 > width) { // off right edge
- ix2 -= sx2 - width;
- sx2 = width;
- }
- if (sy2 > height) { // off bottom edge
- iy2 -= sy2 - height;
- sy2 = height;
- }
-
- int source = iy1 * image.width + ix1;
- int target = sy1 * width;
-
- if (image.format == ARGB) {
- for (int y = sy1; y < sy2; y++) {
- int tx = 0;
-
- for (int x = sx1; x < sx2; x++) {
- pixels[target + x] =
-// _blend(pixels[target + x],
-// image.pixels[source + tx],
-// image.pixels[source + tx++] >>> 24);
- blend_color(pixels[target + x],
- image.pixels[source + tx++]);
- }
- source += image.width;
- target += width;
- }
- } else if (image.format == ALPHA) {
- for (int y = sy1; y < sy2; y++) {
- int tx = 0;
-
- for (int x = sx1; x < sx2; x++) {
- pixels[target + x] =
- blend_color_alpha(pixels[target + x],
- fillColor,
- image.pixels[source + tx++]);
- }
- source += image.width;
- target += width;
- }
-
- } else if (image.format == RGB) {
- target += sx1;
- int tw = sx2 - sx1;
- for (int y = sy1; y < sy2; y++) {
- System.arraycopy(image.pixels, source, pixels, target, tw);
- // should set z coordinate in here
- // or maybe not, since dims=0, meaning no relevant z
- source += image.width;
- target += width;
- }
- }
- }
-
-
- //////////////////////////////////////////////////////////////
-
- // TEXT/FONTS
-
-
- // These will be handled entirely by PGraphics.
-
-
-
- //////////////////////////////////////////////////////////////
-
- // UGLY RENDERING SHITE
-
-
- // expects properly clipped coords, hence does
- // NOT check if x/y are in bounds [toxi]
- private void thin_point_at(int x, int y, float z, int color) {
- int index = y*width+x; // offset values are pre-calced in constructor
- pixels[index] = color;
- }
-
- // expects offset/index in pixelbuffer array instead of x/y coords
- // used by optimized parts of thin_flat_line() [toxi]
- private void thin_point_at_index(int offset, float z, int color) {
- pixels[offset] = color;
- }
-
-
- private void thick_point(float x, float y, float z, // note floats
- float r, float g, float b, float a) {
- spolygon.reset(4);
- spolygon.interpARGB = false; // no changes for vertices of a point
-
- float strokeWidth2 = strokeWeight/2.0f;
-
- float svertex[] = spolygon.vertices[0];
- svertex[TX] = x - strokeWidth2;
- svertex[TY] = y - strokeWidth2;
- svertex[TZ] = z;
-
- svertex[R] = r;
- svertex[G] = g;
- svertex[B] = b;
- svertex[A] = a;
-
- svertex = spolygon.vertices[1];
- svertex[TX] = x + strokeWidth2;
- svertex[TY] = y - strokeWidth2;
- svertex[TZ] = z;
-
- svertex = spolygon.vertices[2];
- svertex[TX] = x + strokeWidth2;
- svertex[TY] = y + strokeWidth2;
- svertex[TZ] = z;
-
- svertex = spolygon.vertices[3];
- svertex[TX] = x - strokeWidth2;
- svertex[TY] = y + strokeWidth2;
- svertex[TZ] = z;
-
- spolygon.render();
- }
-
-
- // new bresenham clipping code, as old one was buggy [toxi]
- private void thin_flat_line(int x1, int y1, int x2, int y2) {
- int nx1,ny1,nx2,ny2;
-
- // get the "dips" for the points to clip
- int code1 = thin_flat_line_clip_code(x1, y1);
- int code2 = thin_flat_line_clip_code(x2, y2);
-
- if ((code1 & code2)!=0) {
- return;
- } else {
- int dip = code1 | code2;
- if (dip != 0) {
- // now calculate the clipped points
- float a1 = 0, a2 = 1, a = 0;
- for (int i=0;i<4;i++) {
- if (((dip>>i)%2)==1) {
- a = thin_flat_line_slope((float)x1, (float)y1,
- (float)x2, (float)y2, i+1);
- if (((code1>>i)%2)==1) {
- a1 = (float)Math.max(a, a1);
- } else {
- a2 = (float)Math.min(a, a2);
- }
- }
- }
- if (a1>a2) return;
- else {
- nx1=(int) (x1+a1*(x2-x1));
- ny1=(int) (y1+a1*(y2-y1));
- nx2=(int) (x1+a2*(x2-x1));
- ny2=(int) (y1+a2*(y2-y1));
- }
- // line is fully visible/unclipped
- } else {
- nx1=x1; nx2=x2;
- ny1=y1; ny2=y2;
- }
- }
-
- // new "extremely fast" line code
- // adapted from http://www.edepot.com/linee.html
-
- boolean yLonger=false;
- int shortLen=ny2-ny1;
- int longLen=nx2-nx1;
- if (Math.abs(shortLen)>Math.abs(longLen)) {
- int swap=shortLen;
- shortLen=longLen;
- longLen=swap;
- yLonger=true;
- }
- int decInc;
- if (longLen==0) decInc=0;
- else decInc = (shortLen << 16) / longLen;
-
- if (nx1==nx2) {
- // special case: vertical line
- if (ny1>ny2) { int ty=ny1; ny1=ny2; ny2=ty; }
- int offset=ny1*width+nx1;
- for(int j=ny1; j<=ny2; j++) {
- thin_point_at_index(offset,0,strokeColor);
- offset+=width;
- }
- return;
- } else if (ny1==ny2) {
- // special case: horizontal line
- if (nx1>nx2) { int tx=nx1; nx1=nx2; nx2=tx; }
- int offset=ny1*width+nx1;
- for(int j=nx1; j<=nx2; j++) thin_point_at_index(offset++,0,strokeColor);
- return;
- } else if (yLonger) {
- if (longLen>0) {
- longLen+=ny1;
- for (int j=0x8000+(nx1<<16);ny1<=longLen;++ny1) {
- thin_point_at(j>>16, ny1, 0, strokeColor);
- j+=decInc;
- }
- return;
- }
- longLen+=ny1;
- for (int j=0x8000+(nx1<<16);ny1>=longLen;--ny1) {
- thin_point_at(j>>16, ny1, 0, strokeColor);
- j-=decInc;
- }
- return;
- } else if (longLen>0) {
- longLen+=nx1;
- for (int j=0x8000+(ny1<<16);nx1<=longLen;++nx1) {
- thin_point_at(nx1, j>>16, 0, strokeColor);
- j+=decInc;
- }
- return;
- }
- longLen+=nx1;
- for (int j=0x8000+(ny1<<16);nx1>=longLen;--nx1) {
- thin_point_at(nx1, j>>16, 0, strokeColor);
- j-=decInc;
- }
- }
-
-
- private int thin_flat_line_clip_code(float x, float y) {
- return ((y < 0 ? 8 : 0) | (y > height1 ? 4 : 0) |
- (x < 0 ? 2 : 0) | (x > width1 ? 1 : 0));
- }
-
-
- private float thin_flat_line_slope(float x1, float y1,
- float x2, float y2, int border) {
- switch (border) {
- case 4: {
- return (-y1)/(y2-y1);
- }
- case 3: {
- return (height1-y1)/(y2-y1);
- }
- case 2: {
- return (-x1)/(x2-x1);
- }
- case 1: {
- return (width1-x1)/(x2-x1);
- }
- }
- return -1f;
- }
-
-
- private void thick_flat_line(float ox1, float oy1,
- float r1, float g1, float b1, float a1,
- float ox2, float oy2,
- float r2, float g2, float b2, float a2) {
- spolygon.interpARGB = (r1 != r2) || (g1 != g2) || (b1 != b2) || (a1 != a2);
-// spolygon.interpZ = false;
-
- float dX = ox2-ox1 + EPSILON;
- float dY = oy2-oy1 + EPSILON;
- float len = (float) Math.sqrt(dX*dX + dY*dY);
-
- // TODO stroke width should be transformed!
- float rh = (strokeWeight / len) / 2;
-
- float dx0 = rh * dY;
- float dy0 = rh * dX;
- float dx1 = rh * dY;
- float dy1 = rh * dX;
-
- spolygon.reset(4);
-
- float svertex[] = spolygon.vertices[0];
- svertex[TX] = ox1+dx0;
- svertex[TY] = oy1-dy0;
- svertex[R] = r1;
- svertex[G] = g1;
- svertex[B] = b1;
- svertex[A] = a1;
-
- svertex = spolygon.vertices[1];
- svertex[TX] = ox1-dx0;
- svertex[TY] = oy1+dy0;
- svertex[R] = r1;
- svertex[G] = g1;
- svertex[B] = b1;
- svertex[A] = a1;
-
- svertex = spolygon.vertices[2];
- svertex[TX] = ox2-dx1;
- svertex[TY] = oy2+dy1;
- svertex[R] = r2;
- svertex[G] = g2;
- svertex[B] = b2;
- svertex[A] = a2;
-
- svertex = spolygon.vertices[3];
- svertex[TX] = ox2+dx1;
- svertex[TY] = oy2-dy1;
- svertex[R] = r2;
- svertex[G] = g2;
- svertex[B] = b2;
- svertex[A] = a2;
-
- spolygon.render();
- }
-
-
- private void draw_line(float[] v1, float[] v2) {
- if (strokeWeight == 1) {
- if (line == null) line = new PLine(this);
-
- line.reset();
- line.setIntensities(v1[SR], v1[SG], v1[SB], v1[SA],
- v2[SR], v2[SG], v2[SB], v2[SA]);
- line.setVertices(v1[TX], v1[TY], v1[TZ],
- v2[TX], v2[TY], v2[TZ]);
- line.draw();
-
- } else { // use old line code for thickness != 1
- thick_flat_line(v1[TX], v1[TY], v1[SR], v1[SG], v1[SB], v1[SA],
- v2[TX], v2[TY], v2[SR], v2[SG], v2[SB], v2[SA]);
- }
- }
-
-
- /**
- * @param max is what to count to
- * @param offset is offset to the 'next' vertex
- * @param increment is how much to increment in the loop
- */
- private void draw_lines(float vertices[][], int max,
- int offset, int increment, int skip) {
-
- if (strokeWeight == 1) {
- for (int i = 0; i < max; i += increment) {
- if ((skip != 0) && (((i+offset) % skip) == 0)) continue;
-
- float a[] = vertices[i];
- float b[] = vertices[i+offset];
-
- if (line == null) line = new PLine(this);
-
- 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]);
- line.draw();
- }
-
- } else { // use old line code for thickness != 1
- for (int i = 0; i < max; i += increment) {
- if ((skip != 0) && (((i+offset) % skip) == 0)) continue;
-
- float v1[] = vertices[i];
- float v2[] = vertices[i+offset];
- thick_flat_line(v1[TX], v1[TY], v1[SR], v1[SG], v1[SB], v1[SA],
- v2[TX], v2[TY], v2[SR], v2[SG], v2[SB], v2[SA]);
- }
- }
- }
-
-
- private void thin_point(float fx, float fy, int color) {
- int x = (int) (fx + 0.4999f);
- int y = (int) (fy + 0.4999f);
- if (x < 0 || x > width1 || y < 0 || y > height1) return;
-
- int index = y*width + x;
- if ((color & 0xff000000) == 0xff000000) { // opaque
- pixels[index] = color;
-
- } else { // transparent
- // a1 is how much of the orig pixel
- int a2 = (color >> 24) & 0xff;
- int a1 = a2 ^ 0xff;
-
- int p2 = strokeColor;
- int p1 = pixels[index];
-
- int r = (a1 * ((p1 >> 16) & 0xff) + a2 * ((p2 >> 16) & 0xff)) & 0xff00;
- int g = (a1 * ((p1 >> 8) & 0xff) + a2 * ((p2 >> 8) & 0xff)) & 0xff00;
- int b = (a1 * ( p1 & 0xff) + a2 * ( p2 & 0xff)) >> 8;
-
- pixels[index] = 0xff000000 | (r << 8) | g | b;
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX TRANSFORMATIONS
-
-
- public void translate(float tx, float ty) {
- ctm.translate(tx, ty);
- }
-
-
- public void translate(float tx, float ty, float tz) {
- showDepthWarningXYZ("translate");
- }
-
-
- public void rotate(float angle) {
- ctm.rotate(angle);
-// float c = (float) Math.cos(angle);
-// float s = (float) Math.sin(angle);
-// applyMatrix(c, -s, 0, s, c, 0);
- }
-
-
- public void rotateX(float angle) {
- showDepthWarning("rotateX");
- }
-
- public void rotateY(float angle) {
- showDepthWarning("rotateY");
- }
-
-
- public void rotateZ(float angle) {
- showDepthWarning("rotateZ");
- }
-
-
- public void rotate(float angle, float vx, float vy, float vz) {
- showVariationWarning("rotate(angle, x, y, z)");
- }
-
-
- public void scale(float s) {
- ctm.scale(s);
-// applyMatrix(s, 0, 0,
-// 0, s, 0);
- }
-
-
- public void scale(float sx, float sy) {
- ctm.scale(sx, sy);
-// applyMatrix(sx, 0, 0,
-// 0, sy, 0);
- }
-
-
- public void scale(float x, float y, float z) {
- showDepthWarningXYZ("scale");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // TRANSFORMATION MATRIX
-
-
- public void pushMatrix() {
- if (matrixStackDepth == MATRIX_STACK_DEPTH) {
- throw new RuntimeException(ERROR_PUSHMATRIX_OVERFLOW);
- }
- ctm.get(matrixStack[matrixStackDepth]);
- matrixStackDepth++;
- }
-
-
- public void popMatrix() {
- if (matrixStackDepth == 0) {
- throw new RuntimeException(ERROR_PUSHMATRIX_UNDERFLOW);
- }
- matrixStackDepth--;
- ctm.set(matrixStack[matrixStackDepth]);
- }
-
-
- /**
- * Load identity as the transform/model matrix.
- * Same as glLoadIdentity().
- */
- public void resetMatrix() {
- ctm.reset();
-// m00 = 1; m01 = 0; m02 = 0;
-// m10 = 0; m11 = 1; m12 = 0;
- }
-
-
- /**
- * Apply a 3x2 affine transformation matrix.
- */
- public void applyMatrix(float n00, float n01, float n02,
- float n10, float n11, float n12) {
- ctm.apply(n00, n01, n02,
- n10, n11, n12);
-//
-// float r00 = m00*n00 + m01*n10;
-// float r01 = m00*n01 + m01*n11;
-// float r02 = m00*n02 + m01*n12 + m02;
-//
-// float r10 = m10*n00 + m11*n10;
-// float r11 = m10*n01 + m11*n11;
-// float r12 = m10*n02 + m11*n12 + m12;
-//
-// m00 = r00; m01 = r01; m02 = r02;
-// m10 = r10; m11 = r11; m12 = r12;
- }
-
-
- 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) {
- showDepthWarningXYZ("applyMatrix");
- }
-
-
- /**
- * Loads the current matrix into m00, m01 etc (or modelview and
- * projection when using 3D) so that the values can be read.
- *
- * Note that there is no "updateMatrix" because that gets too
- * complicated (unnecessary) when considering the 3D matrices.
- */
-// public void loadMatrix() {
- // no-op on base PGraphics because they're used directly
-// }
-
-
- /**
- * Print the current model (or "transformation") matrix.
- */
- public void printMatrix() {
- ctm.print();
-
-// loadMatrix(); // just to make sure
-//
-// float big = Math.abs(m00);
-// if (Math.abs(m01) > big) big = Math.abs(m01);
-// if (Math.abs(m02) > big) big = Math.abs(m02);
-// if (Math.abs(m10) > big) big = Math.abs(m10);
-// if (Math.abs(m11) > big) big = Math.abs(m11);
-// if (Math.abs(m12) > big) big = Math.abs(m12);
-//
-// // avoid infinite loop
-// if (Float.isNaN(big) || Float.isInfinite(big)) {
-// big = 1000000; // set to something arbitrary
-// }
-//
-// int d = 1;
-// int bigi = (int) big;
-// while ((bigi /= 10) != 0) d++; // cheap log()
-//
-// System.out.println(PApplet.nfs(m00, d, 4) + " " +
-// PApplet.nfs(m01, d, 4) + " " +
-// PApplet.nfs(m02, d, 4));
-//
-// System.out.println(PApplet.nfs(m10, d, 4) + " " +
-// PApplet.nfs(m11, d, 4) + " " +
-// PApplet.nfs(m12, d, 4));
-//
-// System.out.println();
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SCREEN TRANSFORMS
-
-
- public float screenX(float x, float y) {
- return ctm.m00 * x + ctm.m01 * y + ctm.m02;
- }
-
-
- public float screenY(float x, float y) {
- return ctm.m10 * x + ctm.m11 * y + ctm.m12;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BACKGROUND AND FRIENDS
-
-
- /**
- * Clear the pixel buffer.
- */
- protected void backgroundImpl() {
- Arrays.fill(pixels, backgroundColor);
- }
-
-
-
- /*
- public void ambient(int rgb) {
- showDepthError("ambient");
- }
-
- public void ambient(float gray) {
- showDepthError("ambient");
- }
-
- public void ambient(float x, float y, float z) {
- // This doesn't take
- if ((x != PMaterial.DEFAULT_AMBIENT) ||
- (y != PMaterial.DEFAULT_AMBIENT) ||
- (z != PMaterial.DEFAULT_AMBIENT)) {
- showDepthError("ambient");
- }
- }
-
- public void specular(int rgb) {
- showDepthError("specular");
- }
-
- public void specular(float gray) {
- showDepthError("specular");
- }
-
- public void specular(float x, float y, float z) {
- showDepthError("specular");
- }
-
- public void shininess(float shine) {
- showDepthError("shininess");
- }
-
-
- public void emissive(int rgb) {
- showDepthError("emissive");
- }
-
- public void emissive(float gray) {
- showDepthError("emissive");
- }
-
- public void emissive(float x, float y, float z ) {
- showDepthError("emissive");
- }
- */
-
-
-
- //////////////////////////////////////////////////////////////
-
- // INTERNAL SCHIZZLE
-
-
- // TODO make this more efficient, or move into PMatrix2D
-// private boolean untransformed() {
-// return ((ctm.m00 == 1) && (ctm.m01 == 0) && (ctm.m02 == 0) &&
-// (ctm.m10 == 0) && (ctm.m11 == 1) && (ctm.m12 == 0));
-// }
-//
-//
-// // TODO make this more efficient, or move into PMatrix2D
-// private boolean unwarped() {
-// return ((ctm.m00 == 1) && (ctm.m01 == 0) &&
-// (ctm.m10 == 0) && (ctm.m11 == 1));
-// }
-
-
- // only call this if there's an alpha in the fill
- private final int blend_fill(int p1) {
- int a2 = fillAi;
- int a1 = a2 ^ 0xff;
-
- int r = (a1 * ((p1 >> 16) & 0xff)) + (a2 * fillRi) & 0xff00;
- int g = (a1 * ((p1 >> 8) & 0xff)) + (a2 * fillGi) & 0xff00;
- int b = (a1 * ( p1 & 0xff)) + (a2 * fillBi) & 0xff00;
-
- return 0xff000000 | (r << 8) | g | (b >> 8);
- }
-
-
- private final int blend_color(int p1, int p2) {
- int a2 = (p2 >>> 24);
-
- if (a2 == 0xff) {
- // full replacement
- return p2;
-
- } else {
- int a1 = a2 ^ 0xff;
- int r = (a1 * ((p1 >> 16) & 0xff) + a2 * ((p2 >> 16) & 0xff)) & 0xff00;
- int g = (a1 * ((p1 >> 8) & 0xff) + a2 * ((p2 >> 8) & 0xff)) & 0xff00;
- int b = (a1 * ( p1 & 0xff) + a2 * ( p2 & 0xff)) >> 8;
-
- return 0xff000000 | (r << 8) | g | b;
- }
- }
-
-
- private final int blend_color_alpha(int p1, int p2, int a2) {
- // scale alpha by alpha of incoming pixel
- a2 = (a2 * (p2 >>> 24)) >> 8;
-
- int a1 = a2 ^ 0xff;
- int r = (a1 * ((p1 >> 16) & 0xff) + a2 * ((p2 >> 16) & 0xff)) & 0xff00;
- int g = (a1 * ((p1 >> 8) & 0xff) + a2 * ((p2 >> 8) & 0xff)) & 0xff00;
- int b = (a1 * ( p1 & 0xff) + a2 * ( p2 & 0xff)) >> 8;
-
- return 0xff000000 | (r << 8) | g | b;
- }
-}
diff --git a/core/src/processing/core/PGraphics3D.java b/core/src/processing/core/PGraphics3D.java
deleted file mode 100644
index 2a47d9547cf..00000000000
--- a/core/src/processing/core/PGraphics3D.java
+++ /dev/null
@@ -1,4379 +0,0 @@
-/* -*- 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, lineCount);
- 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);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // 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.
- *
- * 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
- *
- * 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
- *
- */
- 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.
- *
- * 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:
- *
- * 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.
- *
- * 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:
- *
- * 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.
- *
- * 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.
- *
- * 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];
- }
- */
-}
-
diff --git a/core/src/processing/core/PGraphicsJava2D.java b/core/src/processing/core/PGraphicsJava2D.java
deleted file mode 100644
index f72a566bb06..00000000000
--- a/core/src/processing/core/PGraphicsJava2D.java
+++ /dev/null
@@ -1,1847 +0,0 @@
-/* -*- 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;
-
-import java.awt.*;
-import java.awt.geom.*;
-import java.awt.image.*;
-
-
-/**
- * Subclass for PGraphics that implements the graphics API using Java2D.
- *
- *
Pixel operations too slow? As of release 0085 (the first beta),
- * the default renderer uses Java2D. It's more accurate than the renderer
- * used in alpha releases of Processing (it handles stroke caps and joins,
- * and has better polygon tessellation), but it's super slow for handling
- * pixels. At least until we get a chance to get the old 2D renderer
- * (now called P2D) working in a similar fashion, you can use
- * size(w, h, P3D) instead of size(w, h) which will
- * be faster for general pixel flipping madness.
- *
- *
To get access to the Java 2D "Graphics2D" object for the default
- * renderer, use:
- *
Graphics2D g2 = ((PGraphicsJava2D)g).g2;
- * This will let you do Java 2D stuff directly, but is not supported in
- * any way shape or form. Which just means "have fun, but don't complain
- * if it breaks."
- */
-public class PGraphicsJava2D extends PGraphics /*PGraphics2D*/ {
-
- public Graphics2D g2;
- GeneralPath gpath;
-
- /// break the shape at the next vertex (next vertex() call is a moveto())
- boolean breakShape;
-
- /// coordinates for internal curve calculation
- float[] curveCoordX;
- float[] curveCoordY;
- float[] curveDrawX;
- float[] curveDrawY;
-
- int transformCount;
- AffineTransform transformStack[] =
- new AffineTransform[MATRIX_STACK_DEPTH];
- double[] transform = new double[6];
-
- Line2D.Float line = new Line2D.Float();
- Ellipse2D.Float ellipse = new Ellipse2D.Float();
- Rectangle2D.Float rect = new Rectangle2D.Float();
- Arc2D.Float arc = new Arc2D.Float();
-
- protected Color tintColorObject;
-
- protected Color fillColorObject;
- public boolean fillGradient;
- public Paint fillGradientObject;
-
- protected Color strokeColorObject;
- public boolean strokeGradient;
- public Paint strokeGradientObject;
-
-
-
- //////////////////////////////////////////////////////////////
-
- // INTERNAL
-
-
- public PGraphicsJava2D() { }
-
-
- //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.
- */
- public void setSize(int iwidth, int iheight) { // ignore
- width = iwidth;
- height = iheight;
- width1 = width - 1;
- height1 = height - 1;
-
- allocate();
- reapplySettings();
- }
-
-
- // broken out because of subclassing for opengl
- protected void allocate() {
-// System.out.println("PGraphicsJava2D allocate() " + width + " " + height);
-// System.out.println("allocate " + Thread.currentThread().getName());
- image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
- g2 = (Graphics2D) image.getGraphics();
- // can't un-set this because this may be only a resize
- // http://dev.processing.org/bugs/show_bug.cgi?id=463
- //defaultsInited = false;
- //checkSettings();
- //reapplySettings = true;
- }
-
-
- //public void dispose()
-
-
-
- //////////////////////////////////////////////////////////////
-
- // FRAME
-
-
- public boolean canDraw() {
- return true;
- }
-
-
- public void beginDraw() {
- checkSettings();
-
- resetMatrix(); // reset model matrix
-
- // reset vertices
- vertexCount = 0;
- }
-
-
- public void endDraw() {
- // hm, mark pixels as changed, because this will instantly do a full
- // copy of all the pixels to the surface.. so that's kind of a mess.
- //updatePixels();
-
- // TODO this is probably overkill for most tasks...
- if (!primarySurface) {
- loadPixels();
- }
- modified = true;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SETTINGS
-
-
- //protected void checkSettings()
-
-
- //protected void defaultSettings()
-
-
- //protected void reapplySettings()
-
-
-
- //////////////////////////////////////////////////////////////
-
- // HINT
-
-
- //public void hint(int which)
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SHAPES
-
-
- //public void beginShape(int kind)
-
-
- public void beginShape(int kind) {
- //super.beginShape(kind);
- shape = kind;
- vertexCount = 0;
- curveVertexCount = 0;
-
- // set gpath to null, because when mixing curves and straight
- // lines, vertexCount will be set back to zero, so vertexCount == 1
- // is no longer a good indicator of whether the shape is new.
- // this way, just check to see if gpath is null, and if it isn't
- // then just use it to continue the shape.
- gpath = null;
- }
-
-
- //public boolean edge(boolean e)
-
-
- //public void normal(float nx, float ny, float nz) {
-
-
- //public void textureMode(int mode)
-
-
- public void texture(PImage image) {
- showMethodWarning("texture");
- }
-
-
- public void vertex(float x, float y) {
- curveVertexCount = 0;
- //float vertex[];
-
- if (vertexCount == vertices.length) {
- float temp[][] = new float[vertexCount<<1][VERTEX_FIELD_COUNT];
- System.arraycopy(vertices, 0, temp, 0, vertexCount);
- vertices = temp;
- //message(CHATTER, "allocating more vertices " + vertices.length);
- }
- // not everyone needs this, but just easier to store rather
- // than adding another moving part to the code...
- vertices[vertexCount][X] = x;
- vertices[vertexCount][Y] = y;
- vertexCount++;
-
- switch (shape) {
-
- case POINTS:
- point(x, y);
- break;
-
- case LINES:
- if ((vertexCount % 2) == 0) {
- line(vertices[vertexCount-2][X],
- vertices[vertexCount-2][Y], x, y);
- }
- break;
-
- case TRIANGLES:
- if ((vertexCount % 3) == 0) {
- triangle(vertices[vertexCount - 3][X],
- vertices[vertexCount - 3][Y],
- vertices[vertexCount - 2][X],
- vertices[vertexCount - 2][Y],
- x, y);
- }
- break;
-
- case TRIANGLE_STRIP:
- if (vertexCount >= 3) {
- triangle(vertices[vertexCount - 2][X],
- vertices[vertexCount - 2][Y],
- vertices[vertexCount - 1][X],
- vertices[vertexCount - 1][Y],
- vertices[vertexCount - 3][X],
- vertices[vertexCount - 3][Y]);
- }
- break;
-
- case TRIANGLE_FAN:
- if (vertexCount == 3) {
- triangle(vertices[0][X], vertices[0][Y],
- vertices[1][X], vertices[1][Y],
- x, y);
- } else if (vertexCount > 3) {
- gpath = new GeneralPath();
- // when vertexCount > 3, draw an un-closed triangle
- // for indices 0 (center), previous, current
- gpath.moveTo(vertices[0][X],
- vertices[0][Y]);
- gpath.lineTo(vertices[vertexCount - 2][X],
- vertices[vertexCount - 2][Y]);
- gpath.lineTo(x, y);
- drawShape(gpath);
- }
- break;
-
- case QUADS:
- if ((vertexCount % 4) == 0) {
- quad(vertices[vertexCount - 4][X],
- vertices[vertexCount - 4][Y],
- vertices[vertexCount - 3][X],
- vertices[vertexCount - 3][Y],
- vertices[vertexCount - 2][X],
- vertices[vertexCount - 2][Y],
- x, y);
- }
- break;
-
- case QUAD_STRIP:
- // 0---2---4
- // | | |
- // 1---3---5
- if ((vertexCount >= 4) && ((vertexCount % 2) == 0)) {
- quad(vertices[vertexCount - 4][X],
- vertices[vertexCount - 4][Y],
- vertices[vertexCount - 2][X],
- vertices[vertexCount - 2][Y],
- x, y,
- vertices[vertexCount - 3][X],
- vertices[vertexCount - 3][Y]);
- }
- break;
-
- case POLYGON:
- if (gpath == null) {
- gpath = new GeneralPath();
- gpath.moveTo(x, y);
- } else if (breakShape) {
- gpath.moveTo(x, y);
- breakShape = false;
- } else {
- gpath.lineTo(x, y);
- }
- break;
- }
- }
-
-
- public void vertex(float x, float y, float z) {
- showDepthWarningXYZ("vertex");
- }
-
-
- public void vertex(float x, float y, float u, float v) {
- showVariationWarning("vertex(x, y, u, v)");
- }
-
-
- public void vertex(float x, float y, float z, float u, float v) {
- showDepthWarningXYZ("vertex");
- }
-
-
- public void breakShape() {
- breakShape = true;
- }
-
-
- public void endShape(int mode) {
- if (gpath != null) { // make sure something has been drawn
- if (shape == POLYGON) {
- if (mode == CLOSE) {
- gpath.closePath();
- }
- drawShape(gpath);
- }
- }
- shape = 0;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BEZIER VERTICES
-
-
- public void bezierVertex(float x1, float y1,
- float x2, float y2,
- float x3, float y3) {
- bezierVertexCheck();
- gpath.curveTo(x1, y1, x2, y2, x3, y3);
- }
-
-
- public void bezierVertex(float x2, float y2, float z2,
- float x3, float y3, float z3,
- float x4, float y4, float z4) {
- showDepthWarningXYZ("bezierVertex");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CURVE VERTICES
-
-
- protected void curveVertexCheck() {
- super.curveVertexCheck();
-
- if (curveCoordX == null) {
- curveCoordX = new float[4];
- curveCoordY = new float[4];
- curveDrawX = new float[4];
- curveDrawY = new float[4];
- }
- }
-
-
- protected void curveVertexSegment(float x1, float y1,
- float x2, float y2,
- float x3, float y3,
- float x4, float y4) {
- curveCoordX[0] = x1;
- curveCoordY[0] = y1;
-
- curveCoordX[1] = x2;
- curveCoordY[1] = y2;
-
- curveCoordX[2] = x3;
- curveCoordY[2] = y3;
-
- curveCoordX[3] = x4;
- curveCoordY[3] = y4;
-
- curveToBezierMatrix.mult(curveCoordX, curveDrawX);
- curveToBezierMatrix.mult(curveCoordY, curveDrawY);
-
- // since the paths are continuous,
- // only the first point needs the actual moveto
- if (gpath == null) {
- gpath = new GeneralPath();
- gpath.moveTo(curveDrawX[0], curveDrawY[0]);
- }
-
- gpath.curveTo(curveDrawX[1], curveDrawY[1],
- curveDrawX[2], curveDrawY[2],
- curveDrawX[3], curveDrawY[3]);
- }
-
-
- public void curveVertex(float x, float y, float z) {
- showDepthWarningXYZ("curveVertex");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // RENDERER
-
-
- //public void flush()
-
-
-
- //////////////////////////////////////////////////////////////
-
- // POINT, LINE, TRIANGLE, QUAD
-
-
- public void point(float x, float y) {
- if (stroke) {
-// if (strokeWeight > 1) {
- line(x, y, x + EPSILON, y + EPSILON);
-// } else {
-// set((int) screenX(x, y), (int) screenY(x, y), strokeColor);
-// }
- }
- }
-
-
- public void line(float x1, float y1, float x2, float y2) {
- line.setLine(x1, y1, x2, y2);
- strokeShape(line);
- }
-
-
- public void triangle(float x1, float y1, float x2, float y2,
- float x3, float y3) {
- gpath = new GeneralPath();
- gpath.moveTo(x1, y1);
- gpath.lineTo(x2, y2);
- gpath.lineTo(x3, y3);
- gpath.closePath();
- drawShape(gpath);
- }
-
-
- public void quad(float x1, float y1, float x2, float y2,
- float x3, float y3, float x4, float y4) {
- GeneralPath gp = new GeneralPath();
- gp.moveTo(x1, y1);
- gp.lineTo(x2, y2);
- gp.lineTo(x3, y3);
- gp.lineTo(x4, y4);
- gp.closePath();
- drawShape(gp);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // 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) {
- rect.setFrame(x1, y1, x2-x1, y2-y1);
- drawShape(rect);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // 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) {
- ellipse.setFrame(x, y, w, h);
- drawShape(ellipse);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // ARC
-
-
- //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) {
- // 0 to 90 in java would be 0 to -90 for p5 renderer
- // but that won't work, so -90 to 0?
-
- start = -start * RAD_TO_DEG;
- stop = -stop * RAD_TO_DEG;
-
- // ok to do this because already checked for NaN
-// while (start < 0) {
-// start += 360;
-// stop += 360;
-// }
-// if (start > stop) {
-// float temp = start;
-// start = stop;
-// stop = temp;
-// }
- float sweep = stop - start;
-
- // stroke as Arc2D.OPEN, fill as Arc2D.PIE
- if (fill) {
- //System.out.println("filla");
- arc.setArc(x, y, w, h, start, sweep, Arc2D.PIE);
- fillShape(arc);
- }
- if (stroke) {
- //System.out.println("strokey");
- arc.setArc(x, y, w, h, start, sweep, Arc2D.OPEN);
- strokeShape(arc);
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // JAVA2D SHAPE/PATH HANDLING
-
-
- protected void fillShape(Shape s) {
- if (fillGradient) {
- g2.setPaint(fillGradientObject);
- g2.fill(s);
- } else if (fill) {
- g2.setColor(fillColorObject);
- g2.fill(s);
- }
- }
-
-
- protected void strokeShape(Shape s) {
- if (strokeGradient) {
- g2.setPaint(strokeGradientObject);
- g2.draw(s);
- } else if (stroke) {
- g2.setColor(strokeColorObject);
- g2.draw(s);
- }
- }
-
-
- protected void drawShape(Shape s) {
- if (fillGradient) {
- g2.setPaint(fillGradientObject);
- g2.fill(s);
- } else if (fill) {
- g2.setColor(fillColorObject);
- g2.fill(s);
- }
- if (strokeGradient) {
- g2.setPaint(strokeGradientObject);
- g2.draw(s);
- } else if (stroke) {
- g2.setColor(strokeColorObject);
- g2.draw(s);
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BOX
-
-
- //public void box(float size)
-
-
- public void box(float w, float h, float d) {
- showMethodWarning("box");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SPHERE
-
-
- //public void sphereDetail(int res)
-
-
- //public void sphereDetail(int ures, int vres)
-
-
- public void sphere(float r) {
- showMethodWarning("sphere");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // 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)
-
-
- //protected void bezierInitCheck()
-
-
- //protected void bezierInit()
-
-
- /** Ignored (not needed) in Java 2D. */
- 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)
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CURVE
-
-
- //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)
-
-
- /** Ignored (not needed) in Java 2D. */
- public void curveDetail(int detail) {
- }
-
- //public void curveTightness(float tightness)
-
-
- //protected void curveInitCheck()
-
-
- //protected void curveInit()
-
-
- //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() {
- smooth = true;
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
- RenderingHints.VALUE_ANTIALIAS_ON);
- g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
-// RenderingHints.VALUE_INTERPOLATION_BILINEAR);
- RenderingHints.VALUE_INTERPOLATION_BICUBIC);
- }
-
-
- public void noSmooth() {
- smooth = false;
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
- RenderingHints.VALUE_ANTIALIAS_OFF);
- g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
- RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // IMAGE
-
-
- //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)
-
-
- /**
- * Handle renderer-specific image drawing.
- */
- protected void imageImpl(PImage who,
- float x1, float y1, float x2, float y2,
- int u1, int v1, int u2, int v2) {
- // Image not ready yet, or an error
- if (who.width <= 0 || who.height <= 0) return;
-
- if (who.getCache(this) == null) {
- //System.out.println("making new image cache");
- who.setCache(this, new ImageCache(who));
- who.updatePixels(); // mark the whole thing for update
- who.modified = true;
- }
-
- ImageCache cash = (ImageCache) who.getCache(this);
- // if image previously was tinted, or the color changed
- // or the image was tinted, and tint is now disabled
- if ((tint && !cash.tinted) ||
- (tint && (cash.tintedColor != tintColor)) ||
- (!tint && cash.tinted)) {
- // for tint change, mark all pixels as needing update
- who.updatePixels();
- }
-
- if (who.modified) {
- cash.update(tint, tintColor);
- who.modified = false;
- }
-
- g2.drawImage(((ImageCache) who.getCache(this)).image,
- (int) x1, (int) y1, (int) x2, (int) y2,
- u1, v1, u2, v2, null);
- }
-
-
- class ImageCache {
- PImage source;
- boolean tinted;
- int tintedColor;
- int tintedPixels[]; // one row of tinted pixels
- BufferedImage image;
-
- public ImageCache(PImage source) {
- this.source = source;
- // even if RGB, set the image type to ARGB, because the
- // image may have an alpha value for its tint().
-// int type = BufferedImage.TYPE_INT_ARGB;
- //System.out.println("making new buffered image");
-// image = new BufferedImage(source.width, source.height, type);
- }
-
- /**
- * Update the pixels of the cache image. Already determined that the tint
- * has changed, or the pixels have changed, so should just go through
- * with the update without further checks.
- */
- public void update(boolean tint, int tintColor) {
- int bufferType = BufferedImage.TYPE_INT_ARGB;
- boolean opaque = (tintColor & 0xFF000000) == 0xFF000000;
- if (source.format == RGB) {
- if (!tint || (tint && opaque)) {
- bufferType = BufferedImage.TYPE_INT_RGB;
- }
- }
- boolean wrongType = (image != null) && (image.getType() != bufferType);
- if ((image == null) || wrongType) {
- image = new BufferedImage(source.width, source.height, bufferType);
- }
-
- WritableRaster wr = image.getRaster();
- if (tint) {
- if (tintedPixels == null || tintedPixels.length != source.width) {
- tintedPixels = new int[source.width];
- }
- int a2 = (tintColor >> 24) & 0xff;
- int r2 = (tintColor >> 16) & 0xff;
- int g2 = (tintColor >> 8) & 0xff;
- int b2 = (tintColor) & 0xff;
-
- if (bufferType == BufferedImage.TYPE_INT_RGB) {
- //int alpha = tintColor & 0xFF000000;
- int index = 0;
- for (int y = 0; y < source.height; y++) {
- for (int x = 0; x < source.width; x++) {
- int argb1 = source.pixels[index++];
- int r1 = (argb1 >> 16) & 0xff;
- int g1 = (argb1 >> 8) & 0xff;
- int b1 = (argb1) & 0xff;
-
- tintedPixels[x] = //0xFF000000 |
- (((r2 * r1) & 0xff00) << 8) |
- ((g2 * g1) & 0xff00) |
- (((b2 * b1) & 0xff00) >> 8);
- }
- wr.setDataElements(0, y, source.width, 1, tintedPixels);
- }
- // could this be any slower?
-// float[] scales = { tintR, tintG, tintB };
-// float[] offsets = new float[3];
-// RescaleOp op = new RescaleOp(scales, offsets, null);
-// op.filter(image, image);
-
- } else if (bufferType == BufferedImage.TYPE_INT_ARGB) {
- int index = 0;
- for (int y = 0; y < source.height; y++) {
- if (source.format == RGB) {
- int alpha = tintColor & 0xFF000000;
- for (int x = 0; x < source.width; x++) {
- int argb1 = source.pixels[index++];
- int r1 = (argb1 >> 16) & 0xff;
- int g1 = (argb1 >> 8) & 0xff;
- int b1 = (argb1) & 0xff;
- tintedPixels[x] = alpha |
- (((r2 * r1) & 0xff00) << 8) |
- ((g2 * g1) & 0xff00) |
- (((b2 * b1) & 0xff00) >> 8);
- }
- } else if (source.format == ARGB) {
- for (int x = 0; x < source.width; x++) {
- int argb1 = source.pixels[index++];
- int a1 = (argb1 >> 24) & 0xff;
- int r1 = (argb1 >> 16) & 0xff;
- int g1 = (argb1 >> 8) & 0xff;
- int b1 = (argb1) & 0xff;
- tintedPixels[x] =
- (((a2 * a1) & 0xff00) << 16) |
- (((r2 * r1) & 0xff00) << 8) |
- ((g2 * g1) & 0xff00) |
- (((b2 * b1) & 0xff00) >> 8);
- }
- } else if (source.format == ALPHA) {
- int lower = tintColor & 0xFFFFFF;
- for (int x = 0; x < source.width; x++) {
- int a1 = source.pixels[index++];
- tintedPixels[x] =
- (((a2 * a1) & 0xff00) << 16) | lower;
- }
- }
- wr.setDataElements(0, y, source.width, 1, tintedPixels);
- }
- // Not sure why ARGB images take the scales in this order...
-// float[] scales = { tintR, tintG, tintB, tintA };
-// float[] offsets = new float[4];
-// RescaleOp op = new RescaleOp(scales, offsets, null);
-// op.filter(image, image);
- }
- } else {
- wr.setDataElements(0, 0, source.width, source.height, source.pixels);
- }
- this.tinted = tint;
- this.tintedColor = tintColor;
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // 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 ATTRIBTUES
-
-
- //public void textAlign(int align)
-
-
- //public void textAlign(int alignX, int alignY)
-
-
- public float textAscent() {
- if (textFont == null) {
- defaultFontOrDeath("textAscent");
- }
- Font font = textFont.getFont();
- if (font == null) {
- return super.textAscent();
- }
- FontMetrics metrics = parent.getFontMetrics(font);
- return metrics.getAscent();
- }
-
-
- public float textDescent() {
- if (textFont == null) {
- defaultFontOrDeath("textAscent");
- }
- Font font = textFont.getFont();
- if (font == null) {
- return super.textDescent();
- }
- FontMetrics metrics = parent.getFontMetrics(font);
- return metrics.getDescent();
- }
-
-
- //public void textFont(PFont which)
-
-
- //public void textFont(PFont which, float size)
-
-
- //public void textLeading(float leading)
-
-
- //public void textMode(int mode)
-
-
- protected boolean textModeCheck(int mode) {
- return (mode == MODEL) || (mode == SCREEN);
- }
-
-
- /**
- * Same as parent, but override for native version of the font.
- *
- * Also gets called by textFont, so the metrics
- * will get recorded properly.
- */
- public void textSize(float size) {
- if (textFont == null) {
- defaultFontOrDeath("textAscent", size);
- }
-
- // if a native version available, derive this font
-// if (textFontNative != null) {
-// textFontNative = textFontNative.deriveFont(size);
-// g2.setFont(textFontNative);
-// textFontNativeMetrics = g2.getFontMetrics(textFontNative);
-// }
- Font font = textFont.getFont();
- if (font != null) {
- Font dfont = font.deriveFont(size);
- g2.setFont(dfont);
- textFont.setFont(dfont);
- }
-
- // take care of setting the textSize and textLeading vars
- // this has to happen second, because it calls textAscent()
- // (which requires the native font metrics to be set)
- super.textSize(size);
- }
-
-
- //public float textWidth(char c)
-
-
- //public float textWidth(String str)
-
-
- protected float textWidthImpl(char buffer[], int start, int stop) {
- Font font = textFont.getFont();
- if (font == null) {
- return super.textWidthImpl(buffer, start, stop);
- }
- // maybe should use one of the newer/fancier functions for this?
- int length = stop - start;
- FontMetrics metrics = g2.getFontMetrics(font);
- return metrics.charsWidth(buffer, start, length);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // TEXT
-
- // None of the variations of text() are overridden from PGraphics.
-
-
-
- //////////////////////////////////////////////////////////////
-
- // TEXT IMPL
-
-
- //protected void textLineAlignImpl(char buffer[], int start, int stop,
- // float x, float y)
-
-
- protected void textLineImpl(char buffer[], int start, int stop,
- float x, float y) {
- Font font = textFont.getFont();
- if (font == null) {
- super.textLineImpl(buffer, start, stop, x, y);
- return;
- }
-
- /*
- // save the current setting for text smoothing. note that this is
- // different from the smooth() function, because the font smoothing
- // is controlled when the font is created, not now as it's drawn.
- // fixed a bug in 0116 that handled this incorrectly.
- Object textAntialias =
- g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
-
- // override the current text smoothing setting based on the font
- // (don't change the global smoothing settings)
- g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
- textFont.smooth ?
- RenderingHints.VALUE_ANTIALIAS_ON :
- RenderingHints.VALUE_ANTIALIAS_OFF);
- */
-
- Object antialias =
- g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
- if (antialias == null) {
- // if smooth() and noSmooth() not called, this will be null (0120)
- antialias = RenderingHints.VALUE_ANTIALIAS_DEFAULT;
- }
-
- // override the current smoothing setting based on the font
- // also changes global setting for antialiasing, but this is because it's
- // not possible to enable/disable them independently in some situations.
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
- textFont.smooth ?
- RenderingHints.VALUE_ANTIALIAS_ON :
- RenderingHints.VALUE_ANTIALIAS_OFF);
-
- //System.out.println("setting frac metrics");
- //g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
- // RenderingHints.VALUE_FRACTIONALMETRICS_ON);
-
- g2.setColor(fillColorObject);
- int length = stop - start;
- g2.drawChars(buffer, start, length, (int) (x + 0.5f), (int) (y + 0.5f));
- // better to use drawString() with floats? (nope, draws the same)
- //g2.drawString(new String(buffer, start, length), x, y);
-
- // this didn't seem to help the scaling issue
- // and creates garbage because of the new temporary object
- //java.awt.font.GlyphVector gv = textFontNative.createGlyphVector(g2.getFontRenderContext(), new String(buffer, start, stop));
- //g2.drawGlyphVector(gv, x, y);
-
-// System.out.println("text() " + new String(buffer, start, stop));
-
- // return to previous smoothing state if it was changed
- //g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textAntialias);
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialias);
-
- textX = x + textWidthImpl(buffer, start, stop);
- textY = y;
- textZ = 0; // this will get set by the caller if non-zero
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX STACK
-
-
- public void pushMatrix() {
- if (transformCount == transformStack.length) {
- throw new RuntimeException("pushMatrix() cannot use push more than " +
- transformStack.length + " times");
- }
- transformStack[transformCount] = g2.getTransform();
- transformCount++;
- }
-
-
- public void popMatrix() {
- if (transformCount == 0) {
- throw new RuntimeException("missing a popMatrix() " +
- "to go with that pushMatrix()");
- }
- transformCount--;
- g2.setTransform(transformStack[transformCount]);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX TRANSFORMS
-
-
- public void translate(float tx, float ty) {
- g2.translate(tx, ty);
- }
-
-
- //public void translate(float tx, float ty, float tz)
-
-
- public void rotate(float angle) {
- g2.rotate(angle);
- }
-
-
- public void rotateX(float angle) {
- showDepthWarning("rotateX");
- }
-
-
- public void rotateY(float angle) {
- showDepthWarning("rotateY");
- }
-
-
- public void rotateZ(float angle) {
- showDepthWarning("rotateZ");
- }
-
-
- public void rotate(float angle, float vx, float vy, float vz) {
- showVariationWarning("rotate");
- }
-
-
- public void scale(float s) {
- g2.scale(s, s);
- }
-
-
- public void scale(float sx, float sy) {
- g2.scale(sx, sy);
- }
-
-
- public void scale(float sx, float sy, float sz) {
- showDepthWarningXYZ("scale");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX MORE
-
-
- public void resetMatrix() {
- g2.setTransform(new AffineTransform());
- }
-
-
- //public void applyMatrix(PMatrix2D source)
-
-
- public void applyMatrix(float n00, float n01, float n02,
- float n10, float n11, float n12) {
- //System.out.println("PGraphicsJava2D.applyMatrix()");
- //System.out.println(new AffineTransform(n00, n10, n01, n11, n02, n12));
- g2.transform(new AffineTransform(n00, n10, n01, n11, n02, n12));
- //g2.transform(new AffineTransform(n00, n01, n02, n10, n11, n12));
- }
-
-
- //public void applyMatrix(PMatrix3D source)
-
-
- 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) {
- showVariationWarning("applyMatrix");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATRIX GET/SET
-
-
- public PMatrix getMatrix() {
- return getMatrix((PMatrix2D) null);
- }
-
-
- public PMatrix2D getMatrix(PMatrix2D target) {
- if (target == null) {
- target = new PMatrix2D();
- }
- g2.getTransform().getMatrix(transform);
- target.set((float) transform[0], (float) transform[2], (float) transform[4],
- (float) transform[1], (float) transform[3], (float) transform[5]);
- return target;
- }
-
-
- public PMatrix3D getMatrix(PMatrix3D target) {
- showVariationWarning("getMatrix");
- return target;
- }
-
-
- //public void setMatrix(PMatrix source)
-
-
- public void setMatrix(PMatrix2D source) {
- g2.setTransform(new AffineTransform(source.m00, source.m10,
- source.m01, source.m11,
- source.m02, source.m12));
- }
-
-
- public void setMatrix(PMatrix3D source) {
- showVariationWarning("setMatrix");
- }
-
-
- public void printMatrix() {
- getMatrix((PMatrix2D) null).print();
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // CAMERA and PROJECTION
-
- // Inherit the plaintive warnings from PGraphics
-
-
- //public void beginCamera()
- //public void endCamera()
- //public void camera()
- //public void camera(float eyeX, float eyeY, float eyeZ,
- // float centerX, float centerY, float centerZ,
- // float upX, float upY, float upZ)
- //public void printCamera()
-
- //public void ortho()
- //public void ortho(float left, float right,
- // float bottom, float top,
- // float near, float far)
- //public void perspective()
- //public void perspective(float fov, float aspect, float near, float far)
- //public void frustum(float left, float right,
- // float bottom, float top,
- // float near, float far)
- //public void printProjection()
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SCREEN and MODEL transforms
-
-
- public float screenX(float x, float y) {
- g2.getTransform().getMatrix(transform);
- return (float)transform[0]*x + (float)transform[2]*y + (float)transform[4];
- }
-
-
- public float screenY(float x, float y) {
- g2.getTransform().getMatrix(transform);
- return (float)transform[1]*x + (float)transform[3]*y + (float)transform[5];
- }
-
-
- public float screenX(float x, float y, float z) {
- showDepthWarningXYZ("screenX");
- return 0;
- }
-
-
- public float screenY(float x, float y, float z) {
- showDepthWarningXYZ("screenY");
- return 0;
- }
-
-
- public float screenZ(float x, float y, float z) {
- showDepthWarningXYZ("screenZ");
- return 0;
- }
-
-
- //public float modelX(float x, float y, float z)
-
-
- //public float modelY(float x, float y, float z)
-
-
- //public float modelZ(float x, float y, float z)
-
-
-
- //////////////////////////////////////////////////////////////
-
- // STYLE
-
- // pushStyle(), popStyle(), style() and getStyle() inherited.
-
-
-
- //////////////////////////////////////////////////////////////
-
- // STROKE CAP/JOIN/WEIGHT
-
-
- public void strokeCap(int cap) {
- super.strokeCap(cap);
- strokeImpl();
- }
-
-
- public void strokeJoin(int join) {
- super.strokeJoin(join);
- strokeImpl();
- }
-
-
- public void strokeWeight(float weight) {
- super.strokeWeight(weight);
- strokeImpl();
- }
-
-
- protected void strokeImpl() {
- int cap = BasicStroke.CAP_BUTT;
- if (strokeCap == ROUND) {
- cap = BasicStroke.CAP_ROUND;
- } else if (strokeCap == PROJECT) {
- cap = BasicStroke.CAP_SQUARE;
- }
-
- int join = BasicStroke.JOIN_BEVEL;
- if (strokeJoin == MITER) {
- join = BasicStroke.JOIN_MITER;
- } else if (strokeJoin == ROUND) {
- join = BasicStroke.JOIN_ROUND;
- }
-
- g2.setStroke(new BasicStroke(strokeWeight, cap, join));
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // STROKE
-
- // noStroke() and stroke() inherited from PGraphics.
-
-
- protected void strokeFromCalc() {
- super.strokeFromCalc();
- strokeColorObject = new Color(strokeColor, true);
- strokeGradient = false;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // TINT
-
- // noTint() and tint() inherited from PGraphics.
-
-
- protected void tintFromCalc() {
- super.tintFromCalc();
- // TODO actually implement tinted images
- tintColorObject = new Color(tintColor, true);
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // FILL
-
- // noFill() and fill() inherited from PGraphics.
-
-
- protected void fillFromCalc() {
- super.fillFromCalc();
- fillColorObject = new Color(fillColor, true);
- fillGradient = false;
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MATERIAL PROPERTIES
-
-
- //public void ambient(int rgb)
- //public void ambient(float gray)
- //public void ambient(float x, float y, float z)
- //protected void ambientFromCalc()
- //public void specular(int rgb)
- //public void specular(float gray)
- //public void specular(float x, float y, float z)
- //protected void specularFromCalc()
- //public void shininess(float shine)
- //public void emissive(int rgb)
- //public void emissive(float gray)
- //public void emissive(float x, float y, float z )
- //protected void emissiveFromCalc()
-
-
-
- //////////////////////////////////////////////////////////////
-
- // LIGHTS
-
-
- //public void lights()
- //public void noLights()
- //public void ambientLight(float red, float green, float blue)
- //public void ambientLight(float red, float green, float blue,
- // float x, float y, float z)
- //public void directionalLight(float red, float green, float blue,
- // float nx, float ny, float nz)
- //public void pointLight(float red, float green, float blue,
- // float x, float y, float 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)
- //public void lightFalloff(float constant, float linear, float quadratic)
- //public void lightSpecular(float x, float y, float z)
- //protected void lightPosition(int num, float x, float y, float z)
- //protected void lightDirection(int num, float x, float y, float z)
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BACKGROUND
-
- // background() methods inherited from PGraphics, along with the
- // PImage version of backgroundImpl(), since it just calls set().
-
-
- //public void backgroundImpl(PImage image)
-
-
- int[] clearPixels;
-
- public void backgroundImpl() {
- if (backgroundAlpha) {
- // Create a small array that can be used to set the pixels several times.
- // Using a single-pixel line of length 'width' is a tradeoff between
- // speed (setting each pixel individually is too slow) and memory
- // (an array for width*height would waste lots of memory if it stayed
- // resident, and would terrify the gc if it were re-created on each trip
- // to background().
- WritableRaster raster = ((BufferedImage) image).getRaster();
- if ((clearPixels == null) || (clearPixels.length < width)) {
- clearPixels = new int[width];
- }
- java.util.Arrays.fill(clearPixels, backgroundColor);
- for (int i = 0; i < height; i++) {
- raster.setDataElements(0, i, width, 1, clearPixels);
- }
- } else {
- //new Exception().printStackTrace(System.out);
- // in case people do transformations before background(),
- // need to handle this with a push/reset/pop
- pushMatrix();
- resetMatrix();
- g2.setColor(new Color(backgroundColor)); //, backgroundAlpha));
- g2.fillRect(0, 0, width, height);
- popMatrix();
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR MODE
-
- // All colorMode() variations are inherited from PGraphics.
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COLOR CALC
-
- // colorCalc() and colorCalcARGB() inherited from PGraphics.
-
-
-
- //////////////////////////////////////////////////////////////
-
- // 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
-
-
- public void beginRaw(PGraphics recorderRaw) {
- showMethodWarning("beginRaw");
- }
-
-
- public void endRaw() {
- showMethodWarning("endRaw");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // WARNINGS and EXCEPTIONS
-
- // showWarning and showException inherited.
-
-
-
- //////////////////////////////////////////////////////////////
-
- // RENDERER SUPPORT QUERIES
-
-
- //public boolean displayable() // true
-
-
- //public boolean is2D() // true
-
-
- //public boolean is3D() // false
-
-
-
- //////////////////////////////////////////////////////////////
-
- // PIMAGE METHODS
-
-
- // getImage, setCache, getCache, removeCache, isModified, setModified
-
-
- public void loadPixels() {
- if ((pixels == null) || (pixels.length != width * height)) {
- pixels = new int[width * height];
- }
- //((BufferedImage) image).getRGB(0, 0, width, height, pixels, 0, width);
- WritableRaster raster = ((BufferedImage) image).getRaster();
- raster.getDataElements(0, 0, width, height, pixels);
- }
-
-
- /**
- * Update the pixels[] buffer to the PGraphics image.
- *
- * Unlike in PImage, where updatePixels() only requests that the
- * update happens, in PGraphicsJava2D, this will happen immediately.
- */
- public void updatePixels() {
- //updatePixels(0, 0, width, height);
- WritableRaster raster = ((BufferedImage) image).getRaster();
- raster.setDataElements(0, 0, width, height, pixels);
- }
-
-
- /**
- * Update the pixels[] buffer to the PGraphics image.
- *
- * Unlike in PImage, where updatePixels() only requests that the
- * update happens, in PGraphicsJava2D, this will happen immediately.
- */
- public void updatePixels(int x, int y, int c, int d) {
- //if ((x == 0) && (y == 0) && (c == width) && (d == height)) {
- if ((x != 0) || (y != 0) || (c != width) || (d != height)) {
- // Show a warning message, but continue anyway.
- showVariationWarning("updatePixels(x, y, w, h)");
- }
- updatePixels();
- }
-
-
- public void resize(int wide, int high) {
- showMethodWarning("resize");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // GET/SET
-
-
- static int getset[] = new int[1];
-
-
- public int get(int x, int y) {
- if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return 0;
- //return ((BufferedImage) image).getRGB(x, y);
- WritableRaster raster = ((BufferedImage) image).getRaster();
- raster.getDataElements(x, y, getset);
- return getset[0];
- }
-
-
- //public PImage get(int x, int y, int w, int h)
-
-
- public PImage getImpl(int x, int y, int w, int h) {
- PImage output = new PImage(w, h);
- output.parent = parent;
-
- // oops, the last parameter is the scan size of the *target* buffer
- //((BufferedImage) image).getRGB(x, y, w, h, output.pixels, 0, w);
- WritableRaster raster = ((BufferedImage) image).getRaster();
- raster.getDataElements(x, y, w, h, output.pixels);
-
- return output;
- }
-
-
- public PImage get() {
- return get(0, 0, width, height);
- }
-
-
- public void set(int x, int y, int argb) {
- if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return;
-// ((BufferedImage) image).setRGB(x, y, argb);
- getset[0] = argb;
- WritableRaster raster = ((BufferedImage) image).getRaster();
- raster.setDataElements(x, y, getset);
- }
-
-
- protected void setImpl(int dx, int dy, int sx, int sy, int sw, int sh,
- PImage src) {
- WritableRaster raster = ((BufferedImage) image).getRaster();
- if ((sx == 0) && (sy == 0) && (sw == src.width) && (sh == src.height)) {
- raster.setDataElements(dx, dy, src.width, src.height, src.pixels);
- } else {
- // TODO Optimize, incredibly inefficient to reallocate this much memory
- PImage temp = src.get(sx, sy, sw, sh);
- raster.setDataElements(dx, dy, temp.width, temp.height, temp.pixels);
- }
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // MASK
-
-
- public void mask(int alpha[]) {
- showMethodWarning("mask");
- }
-
-
- public void mask(PImage alpha) {
- showMethodWarning("mask");
- }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // FILTER
-
- // Because the PImage versions call loadPixels() and
- // updatePixels(), no need to override anything here.
-
-
- //public void filter(int kind)
-
-
- //public void filter(int kind, float param)
-
-
-
- //////////////////////////////////////////////////////////////
-
- // COPY
-
-
- public void copy(int sx, int sy, int sw, int sh,
- int dx, int dy, int dw, int dh) {
- if ((sw != dw) || (sh != dh)) {
- // use slow version if changing size
- copy(this, sx, sy, sw, sh, dx, dy, dw, dh);
-
- } else {
- dx = dx - sx; // java2d's "dx" is the delta, not dest
- dy = dy - sy;
- g2.copyArea(sx, sy, sw, sh, dx, dy);
- }
- }
-
-
-// public void copy(PImage src,
-// int sx1, int sy1, int sx2, int sy2,
-// int dx1, int dy1, int dx2, int dy2) {
-// loadPixels();
-// super.copy(src, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2);
-// updatePixels();
-// }
-
-
-
- //////////////////////////////////////////////////////////////
-
- // BLEND
-
-
-// static public int blendColor(int c1, int c2, int mode)
-
-
-// public void blend(int sx, int sy, int sw, int sh,
-// int dx, int dy, int dw, int dh, int mode)
-
-
-// public void blend(PImage src,
-// int sx, int sy, int sw, int sh,
-// int dx, int dy, int dw, int dh, int mode)
-
-
-
- //////////////////////////////////////////////////////////////
-
- // SAVE
-
-
-// public void save(String filename) {
-// loadPixels();
-// super.save(filename);
-// }
-}
\ No newline at end of file
diff --git a/core/src/processing/core/PImage.java b/core/src/processing/core/PImage.java
deleted file mode 100644
index c9fa247805b..00000000000
--- a/core/src/processing/core/PImage.java
+++ /dev/null
@@ -1,2862 +0,0 @@
-/* -*- 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.image.*;
-import java.io.*;
-import java.util.HashMap;
-
-import javax.imageio.ImageIO;
-
-
-
-
-/**
- * Datatype for storing images. Processing can display .gif, .jpg, .tga, and .png images. Images may be displayed in 2D and 3D space.
- * Before an image is used, it must be loaded with the loadImage() function.
- * The PImage object contains fields for the width and height of the image,
- * as well as an array called pixels[] which contains the values for every pixel in the image.
- * A group of methods, described below, allow easy access to the image's pixels and alpha channel and simplify the process of compositing.
- *
Before using the pixels[] array, be sure to use the loadPixels() method on the image to make sure that the pixel data is properly loaded.
- *
To create a new image, use the createImage() function (do not use new PImage()).
- * =advanced
- *
- * Storage class for pixel data. This is the base class for most image and
- * pixel information, such as PGraphics and the video library classes.
- *
- * Code for copying, resizing, scaling, and blending contributed
- * by toxi.
- *
- *
- * @webref image
- * @usage Web & Application
- * @instanceName img any variable of type PImage
- * @see processing.core.PApplet#loadImage(String)
- * @see processing.core.PGraphics#imageMode(int)
- * @see processing.core.PApplet#createImage(int, int)
- */
-public class PImage implements PConstants, Cloneable {
-
- /**
- * Format for this image, one of RGB, ARGB or ALPHA.
- * note that RGB images still require 0xff in the high byte
- * because of how they'll be manipulated by other functions
- */
- public int format;
-
- /**
- * Array containing the values for all the pixels in the image. These values are of the color datatype.
- * This array is the size of the image, meaning 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 statement color b = img.pixels[230] will set the variable b equal to the value at that location in the array.
- * Before accessing this array, the data must loaded with the loadPixels() method.
- * After the array data has been modified, the updatePixels() method must be run to update the changes.
- * Without loadPixels(), running the code may (or will in future releases) result in a NullPointerException.
- * @webref
- * @brief Array containing the color of every pixel in the image
- */
- public int[] pixels;
-
- /**
- * The width of the image in units of pixels.
- * @webref
- * @brief Image width
- */
- public int width;
- /**
- * The height of the image in units of pixels.
- * @webref
- * @brief Image height
- */
- public int height;
-
- /**
- * Path to parent object that will be used with save().
- * This prevents users from needing savePath() to use PImage.save().
- */
- public PApplet parent;
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- /** for subclasses that need to store info about the image */
- protected HashMap
- * Also figured out how to avoid parsing the image upside-down
- * (there's a header flag to set the image origin to top-left)
- *
- * Starting with revision 0092, the format setting is taken into account:
- *
- *
ALPHA images written as 8bit grayscale (uses lowest byte)
- *
RGB → 24 bits
- *
ARGB → 32 bits
- *
- * All versions are RLE compressed.
- *
- * Contributed by toxi 8-10 May 2005, based on this RLE
- * specification
- */
- protected boolean saveTGA(OutputStream output) {
- byte header[] = new byte[18];
-
- if (format == ALPHA) { // save ALPHA images as 8bit grayscale
- header[2] = 0x0B;
- header[16] = 0x08;
- header[17] = 0x28;
-
- } else if (format == RGB) {
- header[2] = 0x0A;
- header[16] = 24;
- header[17] = 0x20;
-
- } else if (format == ARGB) {
- header[2] = 0x0A;
- header[16] = 32;
- header[17] = 0x28;
-
- } else {
- throw new RuntimeException("Image format not recognized inside save()");
- }
- // set image dimensions lo-hi byte order
- header[12] = (byte) (width & 0xff);
- header[13] = (byte) (width >> 8);
- header[14] = (byte) (height & 0xff);
- header[15] = (byte) (height >> 8);
-
- try {
- output.write(header);
-
- int maxLen = height * width;
- int index = 0;
- int col; //, prevCol;
- int[] currChunk = new int[128];
-
- // 8bit image exporter is in separate loop
- // to avoid excessive conditionals...
- if (format == ALPHA) {
- while (index < maxLen) {
- boolean isRLE = false;
- int rle = 1;
- currChunk[0] = col = pixels[index] & 0xff;
- while (index + rle < maxLen) {
- if (col != (pixels[index + rle]&0xff) || rle == 128) {
- isRLE = (rle > 1);
- break;
- }
- rle++;
- }
- if (isRLE) {
- output.write(0x80 | (rle - 1));
- output.write(col);
-
- } else {
- rle = 1;
- while (index + rle < maxLen) {
- int cscan = pixels[index + rle] & 0xff;
- if ((col != cscan && rle < 128) || rle < 3) {
- currChunk[rle] = col = cscan;
- } else {
- if (col == cscan) rle -= 2;
- break;
- }
- rle++;
- }
- output.write(rle - 1);
- for (int i = 0; i < rle; i++) output.write(currChunk[i]);
- }
- index += rle;
- }
- } else { // export 24/32 bit TARGA
- while (index < maxLen) {
- boolean isRLE = false;
- currChunk[0] = col = pixels[index];
- int rle = 1;
- // try to find repeating bytes (min. len = 2 pixels)
- // maximum chunk size is 128 pixels
- while (index + rle < maxLen) {
- if (col != pixels[index + rle] || rle == 128) {
- isRLE = (rle > 1); // set flag for RLE chunk
- break;
- }
- rle++;
- }
- if (isRLE) {
- output.write(128 | (rle - 1));
- output.write(col & 0xff);
- output.write(col >> 8 & 0xff);
- output.write(col >> 16 & 0xff);
- if (format == ARGB) output.write(col >>> 24 & 0xff);
-
- } else { // not RLE
- rle = 1;
- while (index + rle < maxLen) {
- if ((col != pixels[index + rle] && rle < 128) || rle < 3) {
- currChunk[rle] = col = pixels[index + rle];
- } else {
- // check if the exit condition was the start of
- // a repeating colour
- if (col == pixels[index + rle]) rle -= 2;
- break;
- }
- rle++;
- }
- // write uncompressed chunk
- output.write(rle - 1);
- if (format == ARGB) {
- for (int i = 0; i < rle; i++) {
- col = currChunk[i];
- output.write(col & 0xff);
- output.write(col >> 8 & 0xff);
- output.write(col >> 16 & 0xff);
- output.write(col >>> 24 & 0xff);
- }
- } else {
- for (int i = 0; i < rle; i++) {
- col = currChunk[i];
- output.write(col & 0xff);
- output.write(col >> 8 & 0xff);
- output.write(col >> 16 & 0xff);
- }
- }
- }
- index += rle;
- }
- }
- output.flush();
- return true;
-
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
- }
-
-
- /**
- * Use ImageIO functions from Java 1.4 and later to handle image save.
- * Various formats are supported, typically jpeg, png, bmp, and wbmp.
- * To get a list of the supported formats for writing, use:
- * println(javax.imageio.ImageIO.getReaderFormatNames())
- */
- protected void saveImageIO(String path) throws IOException {
- try {
- BufferedImage bimage =
- new BufferedImage(width, height, (format == ARGB) ?
- BufferedImage.TYPE_INT_ARGB :
- BufferedImage.TYPE_INT_RGB);
- /*
- Class bufferedImageClass =
- Class.forName("java.awt.image.BufferedImage");
- Constructor bufferedImageConstructor =
- bufferedImageClass.getConstructor(new Class[] {
- Integer.TYPE,
- Integer.TYPE,
- Integer.TYPE });
- Field typeIntRgbField = bufferedImageClass.getField("TYPE_INT_RGB");
- int typeIntRgb = typeIntRgbField.getInt(typeIntRgbField);
- Field typeIntArgbField = bufferedImageClass.getField("TYPE_INT_ARGB");
- int typeIntArgb = typeIntArgbField.getInt(typeIntArgbField);
- Object bimage =
- bufferedImageConstructor.newInstance(new Object[] {
- new Integer(width),
- new Integer(height),
- new Integer((format == ARGB) ? typeIntArgb : typeIntRgb)
- });
- */
-
- bimage.setRGB(0, 0, width, height, pixels, 0, width);
- /*
- Method setRgbMethod =
- bufferedImageClass.getMethod("setRGB", new Class[] {
- Integer.TYPE, Integer.TYPE,
- Integer.TYPE, Integer.TYPE,
- pixels.getClass(),
- Integer.TYPE, Integer.TYPE
- });
- setRgbMethod.invoke(bimage, new Object[] {
- new Integer(0), new Integer(0),
- new Integer(width), new Integer(height),
- pixels, new Integer(0), new Integer(width)
- });
- */
-
- File file = new File(path);
- String extension = path.substring(path.lastIndexOf('.') + 1);
-
- ImageIO.write(bimage, extension, file);
- /*
- Class renderedImageClass =
- Class.forName("java.awt.image.RenderedImage");
- Class ioClass = Class.forName("javax.imageio.ImageIO");
- Method writeMethod =
- ioClass.getMethod("write", new Class[] {
- renderedImageClass, String.class, File.class
- });
- writeMethod.invoke(null, new Object[] { bimage, extension, file });
- */
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new IOException("image save failed.");
- }
- }
-
-
- protected String[] saveImageFormats;
-
- /**
- * Saves the image into a file. Images are saved in TIFF, TARGA, JPEG, and PNG format depending on the extension within the filename parameter.
- * For example, "image.tif" will have a TIFF image and "image.png" will save a PNG image.
- * If no extension is included in the filename, the image will save in TIFF format and .tif will be added to the name.
- * These files are saved to the sketch's folder, which may be opened by selecting "Show sketch folder" from the "Sketch" menu.
- * It is not possible to use save() while running the program in a web browser.
- * To save an image created within the code, rather than through loading, it's necessary to make the image with the createImage()
- * function so it is aware of the location of the program and can therefore save the file to the right place.
- * See the createImage() reference for more information.
- *
- * =advanced
- * Save this image to disk.
- *
- * 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.");
- }
- }
-}
-
diff --git a/core/src/processing/core/PLine.java b/core/src/processing/core/PLine.java
deleted file mode 100644
index a18afda9cdb..00000000000
--- a/core/src/processing/core/PLine.java
+++ /dev/null
@@ -1,1278 +0,0 @@
-/* -*- 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 a1) {
- return false;
- } else {
- float xt = x_array[0];
- float yt = y_array[0];
-
- x_array[0] = xt + a0 * (x_array[1] - xt);
- y_array[0] = yt + a0 * (y_array[1] - yt);
- x_array[1] = xt + a1 * (x_array[1] - xt);
- y_array[1] = yt + a1 * (y_array[1] - yt);
-
- // interpolate remaining parameters
- if (INTERPOLATE_RGB) {
- float t = r_array[0];
- r_array[0] = t + a0 * (r_array[1] - t);
- r_array[1] = t + a1 * (r_array[1] - t);
- t = g_array[0];
- g_array[0] = t + a0 * (g_array[1] - t);
- g_array[1] = t + a1 * (g_array[1] - t);
- t = b_array[0];
- b_array[0] = t + a0 * (b_array[1] - t);
- b_array[1] = t + a1 * (b_array[1] - t);
- }
-
- if (INTERPOLATE_ALPHA) {
- float t = a_array[0];
- a_array[0] = t + a0 * (a_array[1] - t);
- a_array[1] = t + a1 * (a_array[1] - t);
- }
- }
- }
- return true;
- }
-
-
- private int lineClipCode(float xi, float yi) {
- int xmin = 0;
- int ymin = 0;
- int xmax = SCREEN_WIDTH1;
- int ymax = SCREEN_HEIGHT1;
-
- //return ((yi < ymin ? 8 : 0) | (yi > ymax ? 4 : 0) |
- // (xi < xmin ? 2 : 0) | (xi > xmax ? 1 : 0));
- //(int) added by ewjordan 6/13/07 because otherwise we sometimes clip last pixel when it should actually be displayed.
- //Currently the min values are okay because values less than 0 should not be rendered; however, bear in mind that
- //(int) casts towards zero, so without this clipping, values between -1+eps and +1-eps would all be rendered as 0.
- return ((yi < ymin ? 8 : 0) | ((int)yi > ymax ? 4 : 0) |
- (xi < xmin ? 2 : 0) | ((int)xi > xmax ? 1 : 0));
- }
-
-
- private float lineSlope(float x1, float y1, float x2, float y2, int border) {
- int xmin = 0;
- int ymin = 0;
- int xmax = SCREEN_WIDTH1;
- int ymax = SCREEN_HEIGHT1;
-
- switch (border) {
- case 4: return (ymin-y1)/(y2-y1);
- case 3: return (ymax-y1)/(y2-y1);
- case 2: return (xmin-x1)/(x2-x1);
- case 1: return (xmax-x1)/(x2-x1);
- }
- return -1f;
- }
-
-
- private void drawPoint(int x0, int y0) {
- float iz = m_z0;
- int offset = y0 * SCREEN_WIDTH + x0;
-
- if (m_zbuffer == null) {
- m_pixels[offset] = m_stroke;
-
- } else {
- if (iz <= m_zbuffer[offset]) {
- m_pixels[offset] = m_stroke;
- m_zbuffer[offset] = iz;
- }
- }
- }
-
-
- private void drawPoint_alpha(int x0, int y0) {
- int ia = (int) a_array[0];
- int pr = m_stroke & 0xFF0000;
- int pg = m_stroke & 0xFF00;
- int pb = m_stroke & 0xFF;
- float iz = m_z0;
- int offset = y0 * SCREEN_WIDTH + x0;
-
- if ((m_zbuffer == null) || iz <= m_zbuffer[offset]) {
- int alpha = ia >> 16;
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0 &= 0xFF0000;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- if (m_zbuffer != null) m_zbuffer[offset] = iz;
- }
- }
-
-
- private void drawLine_plain(int x0, int y0, int dt,
- int length, boolean vertical) {
- // new "extremely fast" line code
- // adapted from http://www.edepot.com/linee.html
- // first version modified by [toxi]
- // simplified by [rocha]
- // length must be >= 0
-
- //assert length>=0:length;
-
- int offset = 0;
-
- if (vertical) {
- // vertical
- length += y0;
- for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) {
- offset = y0 * SCREEN_WIDTH + (j>>16);
- m_pixels[offset] = m_stroke;
- if (m_zbuffer != null) m_zbuffer[offset] = m_z0;
- j+=dt;
- }
-
- } else {
- // horizontal
- length += x0;
- for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) {
- offset = (j>>16) * SCREEN_WIDTH + x0;
- m_pixels[offset] = m_stroke;
- if (m_zbuffer != null) m_zbuffer[offset] = m_z0;
- j+=dt;
- }
- }
- }
-
-
- private void drawLine_plain_alpha(int x0, int y0, int dt,
- int length, boolean vertical) {
- int offset = 0;
-
- int pr = m_stroke & 0xFF0000;
- int pg = m_stroke & 0xFF00;
- int pb = m_stroke & 0xFF;
-
- int ia = (int) (m_a0);
-
- if (vertical) {
- length += y0;
- for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) {
- offset = y0 * SCREEN_WIDTH + (j>>16);
-
- int alpha = ia >> 16;
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0 &= 0xFF0000;
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- //m_zbuffer[offset] = m_z0; // don't set zbuffer w/ alpha lines
-
- ia += da;
- j += dt;
- }
-
- } else { // horizontal
- length += x0;
- for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) {
- offset = (j>>16) * SCREEN_WIDTH + x0;
-
- int alpha = ia >> 16;
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0&=0xFF0000;
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- //m_zbuffer[offset] = m_z0; // no zbuffer w/ alpha lines
-
- ia += da;
- j += dt;
- }
- }
- }
-
-
- private void drawLine_color(int x0, int y0, int dt,
- int length, boolean vertical) {
- int offset = 0;
-
- int ir = (int) m_r0;
- int ig = (int) m_g0;
- int ib = (int) m_b0;
-
- if (vertical) {
- length += y0;
- for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) {
- offset = y0 * SCREEN_WIDTH + (j>>16);
- m_pixels[offset] = 0xFF000000 |
- ((ir & 0xFF0000) | ((ig >> 8) & 0xFF00) | (ib >> 16));
- if (m_zbuffer != null) m_zbuffer[offset] = m_z0;
- ir += dr;
- ig += dg;
- ib += db;
- j +=dt;
- }
-
- } else { // horizontal
- length += x0;
- for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) {
- offset = (j>>16) * SCREEN_WIDTH + x0;
- m_pixels[offset] = 0xFF000000 |
- ((ir & 0xFF0000) | ((ig >> 8) & 0xFF00) | (ib >> 16));
- if (m_zbuffer != null) m_zbuffer[offset] = m_z0;
- ir += dr;
- ig += dg;
- ib += db;
- j += dt;
- }
- }
- }
-
-
- private void drawLine_color_alpha(int x0, int y0, int dt,
- int length, boolean vertical) {
- int offset = 0;
-
- int ir = (int) m_r0;
- int ig = (int) m_g0;
- int ib = (int) m_b0;
- int ia = (int) m_a0;
-
- if (vertical) {
- length += y0;
- for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) {
- offset = y0 * SCREEN_WIDTH + (j>>16);
-
- int pr = ir & 0xFF0000;
- int pg = (ig >> 8) & 0xFF00;
- int pb = (ib >> 16);
-
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0&=0xFF0000;
-
- int alpha = ia >> 16;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- if (m_zbuffer != null) m_zbuffer[offset] = m_z0;
-
- ir+= dr;
- ig+= dg;
- ib+= db;
- ia+= da;
- j+=dt;
- }
-
- } else { // horizontal
- length += x0;
- for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) {
- offset = (j>>16) * SCREEN_WIDTH + x0;
-
- int pr = ir & 0xFF0000;
- int pg = (ig >> 8) & 0xFF00;
- int pb = (ib >> 16);
-
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0&=0xFF0000;
-
- int alpha = ia >> 16;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- if (m_zbuffer != null) m_zbuffer[offset] = m_z0;
-
- ir+= dr;
- ig+= dg;
- ib+= db;
- ia+= da;
- j+=dt;
- }
- }
- }
-
-
- private void drawLine_plain_spatial(int x0, int y0, int dt,
- int length, boolean vertical) {
- int offset = 0;
- float iz = m_z0;
-
- if (vertical) {
- length += y0;
- for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) {
- offset = y0 * SCREEN_WIDTH + (j>>16);
- if (offset < m_pixels.length) {
- if (iz <= m_zbuffer[offset]) {
- m_pixels[offset] = m_stroke;
- m_zbuffer[offset] = iz;
- }
- }
- iz+=dz;
- j+=dt;
- }
-
- } else { // horizontal
- length += x0;
- for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) {
- offset = (j>>16) * SCREEN_WIDTH + x0;
- if (offset < m_pixels.length) {
- if (iz <= m_zbuffer[offset]) {
- m_pixels[offset] = m_stroke;
- m_zbuffer[offset] = iz;
- }
- }
- iz+=dz;
- j+=dt;
- }
- }
- }
-
-
- private void drawLine_plain_alpha_spatial(int x0, int y0, int dt,
- int length, boolean vertical) {
- int offset = 0;
- float iz = m_z0;
-
- int pr = m_stroke & 0xFF0000;
- int pg = m_stroke & 0xFF00;
- int pb = m_stroke & 0xFF;
-
- int ia = (int) m_a0;
-
- if (vertical) {
- length += y0;
- for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) {
- offset = y0 * SCREEN_WIDTH + (j>>16);
- if (offset < m_pixels.length) {
- if (iz <= m_zbuffer[offset]) {
- int alpha = ia >> 16;
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0 &= 0xFF0000;
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- m_zbuffer[offset] = iz;
- }
- }
- iz +=dz;
- ia += da;
- j += dt;
- }
-
- } else { // horizontal
- length += x0;
- for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) {
- offset = (j>>16) * SCREEN_WIDTH + x0;
-
- if (offset < m_pixels.length) {
- if (iz <= m_zbuffer[offset]) {
- int alpha = ia >> 16;
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0&=0xFF0000;
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- m_zbuffer[offset] = iz;
- }
- }
- iz += dz;
- ia += da;
- j += dt;
- }
- }
- }
-
-
- private void drawLine_color_spatial(int x0, int y0, int dt,
- int length, boolean vertical) {
- int offset = 0;
- float iz = m_z0;
-
- int ir = (int) m_r0;
- int ig = (int) m_g0;
- int ib = (int) m_b0;
-
- if (vertical) {
- length += y0;
- for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) {
- offset = y0 * SCREEN_WIDTH + (j>>16);
-
- if (iz <= m_zbuffer[offset]) {
- m_pixels[offset] = 0xFF000000 |
- ((ir & 0xFF0000) | ((ig >> 8) & 0xFF00) | (ib >> 16));
- m_zbuffer[offset] = iz;
- }
- iz +=dz;
- ir += dr;
- ig += dg;
- ib += db;
- j += dt;
- }
- } else { // horizontal
- length += x0;
- for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) {
- offset = (j>>16) * SCREEN_WIDTH + x0;
- if (iz <= m_zbuffer[offset]) {
- m_pixels[offset] = 0xFF000000 |
- ((ir & 0xFF0000) | ((ig >> 8) & 0xFF00) | (ib >> 16));
- m_zbuffer[offset] = iz;
- }
- iz += dz;
- ir += dr;
- ig += dg;
- ib += db;
- j += dt;
- }
- return;
- }
- }
-
-
- private void drawLine_color_alpha_spatial(int x0, int y0, int dt,
- int length, boolean vertical) {
- int offset = 0;
- float iz = m_z0;
-
- int ir = (int) m_r0;
- int ig = (int) m_g0;
- int ib = (int) m_b0;
- int ia = (int) m_a0;
-
- if (vertical) {
- length += y0;
- for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) {
- offset = y0 * SCREEN_WIDTH + (j>>16);
-
- if (iz <= m_zbuffer[offset]) {
- int pr = ir & 0xFF0000;
- int pg = (ig >> 8) & 0xFF00;
- int pb = (ib >> 16);
-
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0&=0xFF0000;
-
- int alpha = ia >> 16;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- m_zbuffer[offset] = iz;
- }
- iz+=dz;
- ir+= dr;
- ig+= dg;
- ib+= db;
- ia+= da;
- j+=dt;
- }
-
- } else { // horizontal
- length += x0;
- for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) {
- offset = (j>>16) * SCREEN_WIDTH + x0;
-
- if (iz <= m_zbuffer[offset]) {
- int pr = ir & 0xFF0000;
- int pg = (ig >> 8) & 0xFF00;
- int pb = (ib >> 16);
-
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0 &= 0xFF0000;
-
- int alpha = ia >> 16;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- m_zbuffer[offset] = iz;
- }
- iz += dz;
- ir += dr;
- ig += dg;
- ib += db;
- ia += da;
- j += dt;
- }
- }
- }
-
-
- private void drawLine_smooth(int x0, int y0, int dt,
- int length, boolean vertical) {
- int xi, yi; // these must be >=32 bits
- int offset = 0;
- int temp;
- int end;
-
- float iz = m_z0;
-
- int ir = (int) m_r0;
- int ig = (int) m_g0;
- int ib = (int) m_b0;
- int ia = (int) m_a0;
-
- if (vertical) {
- xi = x0 << 16;
- yi = y0 << 16;
-
- end = length + y0;
-
- while ((yi >> 16) < end) {
-
- offset = (yi>>16) * SCREEN_WIDTH + (xi>>16);
-
- int pr = ir & 0xFF0000;
- int pg = (ig >> 8) & 0xFF00;
- int pb = (ib >> 16);
-
- if ((m_zbuffer == null) || (iz <= m_zbuffer[offset])) {
- int alpha = (((~xi >> 8) & 0xFF) * (ia >> 16)) >> 8;
-
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0&=0xFF0000;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- if (m_zbuffer != null) m_zbuffer[offset] = iz;
- }
-
- // this if() makes things slow. there should be a better way to check
- // if the second pixel is within the image array [rocha]
- temp = ((xi>>16)+1);
- if (temp >= SCREEN_WIDTH) {
- xi += dt;
- yi += (1 << 16);
- continue;
- }
-
- offset = (yi>>16) * SCREEN_WIDTH + temp;
-
- if ((m_zbuffer == null) || (iz <= m_zbuffer[offset])) {
- int alpha = (((xi >> 8) & 0xFF) * (ia >> 16)) >> 8;
-
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0 &= 0xFF0000;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- if (m_zbuffer != null) m_zbuffer[offset] = iz;
- }
-
- xi += dt;
- yi += (1 << 16);
-
- iz+=dz;
- ir+= dr;
- ig+= dg;
- ib+= db;
- ia+= da;
- }
-
- } else { // horizontal
- xi = x0 << 16;
- yi = y0 << 16;
- end = length + x0;
-
- while ((xi >> 16) < end) {
- offset = (yi>>16) * SCREEN_WIDTH + (xi>>16);
-
- int pr = ir & 0xFF0000;
- int pg = (ig >> 8) & 0xFF00;
- int pb = (ib >> 16);
-
- if ((m_zbuffer == null) || (iz <= m_zbuffer[offset])) {
- int alpha = (((~yi >> 8) & 0xFF) * (ia >> 16)) >> 8;
-
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0 &= 0xFF0000;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- if (m_zbuffer != null) m_zbuffer[offset] = iz;
- }
-
- // see above [rocha]
- temp = ((yi>>16)+1);
- if (temp >= SCREEN_HEIGHT) {
- xi += (1 << 16);
- yi += dt;
- continue;
- }
-
- offset = temp * SCREEN_WIDTH + (xi>>16);
-
- if ((m_zbuffer == null) || (iz <= m_zbuffer[offset])) {
- int alpha = (((yi >> 8) & 0xFF) * (ia >> 16)) >> 8;
-
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0&=0xFF0000;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
- if (m_zbuffer != null) m_zbuffer[offset] = iz;
- }
-
- xi += (1 << 16);
- yi += dt;
-
- iz += dz;
- ir += dr;
- ig += dg;
- ib += db;
- ia += da;
- }
- }
- }
-
-
- /*
- void drawLine_smooth(int x0, int y0, int dt,
- int length, boolean vertical) {
- int xi, yi; // these must be >=32 bits
- int offset = 0;
- int temp;
- int end;
-
- int ir = (int) m_r0;
- int ig = (int) m_g0;
- int ib = (int) m_b0;
- int ia = (int) m_a0;
-
- if (vertical) {
- xi = x0 << 16;
- yi = y0 << 16;
-
- end = length + y0;
-
- while ((yi >> 16) < end) {
- offset = (yi>>16) * SCREEN_WIDTH + (xi>>16);
-
- int pr = ir & 0xFF0000;
- int pg = (ig >> 8) & 0xFF00;
- int pb = (ib >> 16);
-
- int alpha = (((~xi >> 8) & 0xFF) * (ia >> 16)) >> 8;
-
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0 &= 0xFF0000;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
-
- // this if() makes things slow. there should be a better way to check
- // if the second pixel is within the image array [rocha]
- temp = ((xi>>16)+1);
- if (temp >= SCREEN_WIDTH) {
- xi += dt;
- yi += (1 << 16);
- continue;
- }
-
- offset = (yi>>16) * SCREEN_WIDTH + temp;
-
- alpha = (((xi >> 8) & 0xFF) * (ia >> 16)) >> 8;
-
- r0 = m_pixels[offset];
- g0 = r0 & 0xFF00;
- b0 = r0 & 0xFF;
- r0 &= 0xFF0000;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
-
- xi += dt;
- yi += (1 << 16);
-
- ir += dr;
- ig += dg;
- ib += db;
- ia += da;
- }
-
- } else { // horizontal
- xi = x0 << 16;
- yi = y0 << 16;
- end = length + x0;
-
- while ((xi >> 16) < end) {
- offset = (yi>>16) * SCREEN_WIDTH + (xi>>16);
-
- int pr = ir & 0xFF0000;
- int pg = (ig >> 8) & 0xFF00;
- int pb = (ib >> 16);
-
- int alpha = (((~yi >> 8) & 0xFF) * (ia >> 16)) >> 8;
-
- int r0 = m_pixels[offset];
- int g0 = r0 & 0xFF00;
- int b0 = r0 & 0xFF;
- r0 &= 0xFF0000;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
-
- // see above [rocha]
- temp = ((yi>>16)+1);
- if (temp >= SCREEN_HEIGHT) {
- xi += (1 << 16);
- yi += dt;
- continue;
- }
-
- offset = temp * SCREEN_WIDTH + (xi>>16);
-
- alpha = (((yi >> 8) & 0xFF) * (ia >> 16)) >> 8;
-
- r0 = m_pixels[offset];
- g0 = r0 & 0xFF00;
- b0 = r0 & 0xFF;
- r0 &= 0xFF0000;
-
- r0 = r0 + (((pr - r0) * alpha) >> 8);
- g0 = g0 + (((pg - g0) * alpha) >> 8);
- b0 = b0 + (((pb - b0) * alpha) >> 8);
-
- m_pixels[offset] = 0xFF000000 |
- (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF);
-
- xi += (1 << 16);
- yi += dt;
-
- ir+= dr;
- ig+= dg;
- ib+= db;
- ia+= da;
- }
- }
- }
- */
-}
diff --git a/core/src/processing/core/PMatrix.java b/core/src/processing/core/PMatrix.java
deleted file mode 100644
index aac9c0625e7..00000000000
--- a/core/src/processing/core/PMatrix.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/* -*- 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;
-
-
-public interface PMatrix {
-
- public void reset();
-
- /**
- * Returns a copy of this PMatrix.
- */
- public PMatrix get();
-
- /**
- * Copies the matrix contents into a float array.
- * If target is null (or not the correct size), a new array will be created.
- */
- public float[] get(float[] target);
-
-
- public void set(PMatrix src);
-
- public void set(float[] source);
-
- public void set(float m00, float m01, float m02,
- float m10, float m11, float 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);
-
- public void translate(float tx, float ty, float tz);
-
- public void rotate(float angle);
-
- public void rotateX(float angle);
-
- public void rotateY(float angle);
-
- public void rotateZ(float angle);
-
- public void rotate(float angle, float v0, float v1, float v2);
-
- public void scale(float s);
-
- public void scale(float sx, float sy);
-
- public void scale(float x, float y, float z);
-
- public void skewX(float angle);
-
- public void skewY(float angle);
-
- /**
- * Multiply this matrix by another.
- */
- public void apply(PMatrix source);
-
- public void apply(PMatrix2D source);
-
- public void apply(PMatrix3D source);
-
- public void apply(float n00, float n01, float n02,
- float n10, float n11, float n12);
-
- 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);
-
- /**
- * Apply another matrix to the left of this one.
- */
- public void preApply(PMatrix2D left);
-
- public void preApply(PMatrix3D left);
-
- public void preApply(float n00, float n01, float n02,
- float n10, float n11, float n12);
-
- 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);
-
-
- /**
- * Multiply a PVector by this matrix.
- */
- public PVector mult(PVector source, PVector target);
-
-
- /**
- * Multiply a multi-element vector against this matrix.
- */
- public float[] mult(float[] source, float[] target);
-
-
-// public float multX(float x, float y);
-// public float multY(float x, float y);
-
-// public float multX(float x, float y, float z);
-// public float multY(float x, float y, float z);
-// public float multZ(float x, float y, float z);
-
-
- /**
- * Transpose this matrix.
- */
- public void transpose();
-
-
- /**
- * Invert this matrix.
- * @return true if successful
- */
- public boolean invert();
-
-
- /**
- * @return the determinant of the matrix
- */
- public float determinant();
-}
\ No newline at end of file
diff --git a/core/src/processing/core/PMatrix2D.java b/core/src/processing/core/PMatrix2D.java
deleted file mode 100644
index fad4d0fa826..00000000000
--- a/core/src/processing/core/PMatrix2D.java
+++ /dev/null
@@ -1,450 +0,0 @@
-/* -*- 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, angle, 0, 0);
- }
-
-
- public void skewY(float angle) {
- apply(1, 0, 1, 0, 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);
- }
-}
diff --git a/core/src/processing/core/PMatrix3D.java b/core/src/processing/core/PMatrix3D.java
deleted file mode 100644
index 25d9fd11d35..00000000000
--- a/core/src/processing/core/PMatrix3D.java
+++ /dev/null
@@ -1,782 +0,0 @@
-/* -*- 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;
-
-
-/**
- * 4x4 matrix implementation.
- */
-public final class PMatrix3D implements PMatrix /*, PConstants*/ {
-
- public float m00, m01, m02, m03;
- public float m10, m11, m12, m13;
- public float m20, m21, m22, m23;
- public float m30, m31, m32, m33;
-
-
- // locally allocated version to avoid creating new memory
- protected PMatrix3D inverseCopy;
-
-
- public PMatrix3D() {
- reset();
- }
-
-
- public PMatrix3D(float m00, float m01, float m02,
- float m10, float m11, float m12) {
- set(m00, m01, m02, 0,
- m10, m11, m12, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- }
-
-
- public PMatrix3D(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) {
- set(m00, m01, m02, m03,
- m10, m11, m12, m13,
- m20, m21, m22, m23,
- m30, m31, m32, m33);
- }
-
-
- public PMatrix3D(PMatrix matrix) {
- set(matrix);
- }
-
-
- public void reset() {
- set(1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- }
-
-
- /**
- * Returns a copy of this PMatrix.
- */
- public PMatrix3D get() {
- PMatrix3D outgoing = new PMatrix3D();
- outgoing.set(this);
- return outgoing;
- }
-
-
- /**
- * Copies the matrix contents into a 16 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 != 16)) {
- target = new float[16];
- }
- target[0] = m00;
- target[1] = m01;
- target[2] = m02;
- target[3] = m03;
-
- target[4] = m10;
- target[5] = m11;
- target[6] = m12;
- target[7] = m13;
-
- target[8] = m20;
- target[9] = m21;
- target[10] = m22;
- target[11] = m23;
-
- target[12] = m30;
- target[13] = m31;
- target[14] = m32;
- target[15] = m33;
-
- return target;
- }
-
-
- public void set(PMatrix matrix) {
- if (matrix instanceof PMatrix3D) {
- PMatrix3D src = (PMatrix3D) matrix;
- set(src.m00, src.m01, src.m02, src.m03,
- src.m10, src.m11, src.m12, src.m13,
- src.m20, src.m21, src.m22, src.m23,
- src.m30, src.m31, src.m32, src.m33);
- } else {
- PMatrix2D src = (PMatrix2D) matrix;
- set(src.m00, src.m01, 0, src.m02,
- src.m10, src.m11, 0, src.m12,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- }
- }
-
-
- public void set(float[] source) {
- if (source.length == 6) {
- set(source[0], source[1], source[2],
- source[3], source[4], source[5]);
-
- } else if (source.length == 16) {
- m00 = source[0];
- m01 = source[1];
- m02 = source[2];
- m03 = source[3];
-
- m10 = source[4];
- m11 = source[5];
- m12 = source[6];
- m13 = source[7];
-
- m20 = source[8];
- m21 = source[9];
- m22 = source[10];
- m23 = source[11];
-
- m30 = source[12];
- m31 = source[13];
- m32 = source[14];
- m33 = source[15];
- }
- }
-
-
- public void set(float m00, float m01, float m02,
- float m10, float m11, float m12) {
- set(m00, m01, 0, m02,
- m10, m11, 0, m12,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- }
-
-
- 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) {
- this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03;
- this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13;
- this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23;
- this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33;
- }
-
-
- public void translate(float tx, float ty) {
- translate(tx, ty, 0);
- }
-
-// public void invTranslate(float tx, float ty) {
-// invTranslate(tx, ty, 0);
-// }
-
-
- public void translate(float tx, float ty, float tz) {
- m03 += tx*m00 + ty*m01 + tz*m02;
- m13 += tx*m10 + ty*m11 + tz*m12;
- m23 += tx*m20 + ty*m21 + tz*m22;
- m33 += tx*m30 + ty*m31 + tz*m32;
- }
-
-
- public void rotate(float angle) {
- rotateZ(angle);
- }
-
-
- public void rotateX(float angle) {
- float c = cos(angle);
- float s = sin(angle);
- apply(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
- }
-
-
- public void rotateY(float angle) {
- float c = cos(angle);
- float s = sin(angle);
- apply(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
- }
-
-
- public void rotateZ(float angle) {
- float c = cos(angle);
- float s = sin(angle);
- apply(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
-
-
- public void rotate(float angle, float v0, float v1, float v2) {
- // TODO should make sure this vector is normalized
-
- float c = cos(angle);
- float s = sin(angle);
- float t = 1.0f - c;
-
- apply((t*v0*v0) + c, (t*v0*v1) - (s*v2), (t*v0*v2) + (s*v1), 0,
- (t*v0*v1) + (s*v2), (t*v1*v1) + c, (t*v1*v2) - (s*v0), 0,
- (t*v0*v2) - (s*v1), (t*v1*v2) + (s*v0), (t*v2*v2) + c, 0,
- 0, 0, 0, 1);
- }
-
-
- public void scale(float s) {
- //apply(s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, 0, 0, 0, 1);
- scale(s, s, s);
- }
-
-
- public void scale(float sx, float sy) {
- //apply(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- scale(sx, sy, 1);
- }
-
-
- public void scale(float x, float y, float z) {
- //apply(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
- m00 *= x; m01 *= y; m02 *= z;
- m10 *= x; m11 *= y; m12 *= z;
- m20 *= x; m21 *= y; m22 *= z;
- m30 *= x; m31 *= y; m32 *= z;
- }
-
-
- public void skewX(float angle) {
- float t = (float) Math.tan(angle);
- apply(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);
- apply(1, 0, 0, 0,
- t, 1, 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- }
-
-
- 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, 0, source.m02,
- source.m10, source.m11, 0, source.m12,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- }
-
-
- public void apply(PMatrix3D source) {
- apply(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);
- }
-
-
- public void apply(float n00, float n01, float n02,
- float n10, float n11, float n12) {
- apply(n00, n01, 0, n02,
- n10, n11, 0, n12,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- }
-
-
- 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) {
-
- float r00 = m00*n00 + m01*n10 + m02*n20 + m03*n30;
- float r01 = m00*n01 + m01*n11 + m02*n21 + m03*n31;
- float r02 = m00*n02 + m01*n12 + m02*n22 + m03*n32;
- float r03 = m00*n03 + m01*n13 + m02*n23 + m03*n33;
-
- float r10 = m10*n00 + m11*n10 + m12*n20 + m13*n30;
- float r11 = m10*n01 + m11*n11 + m12*n21 + m13*n31;
- float r12 = m10*n02 + m11*n12 + m12*n22 + m13*n32;
- float r13 = m10*n03 + m11*n13 + m12*n23 + m13*n33;
-
- float r20 = m20*n00 + m21*n10 + m22*n20 + m23*n30;
- float r21 = m20*n01 + m21*n11 + m22*n21 + m23*n31;
- float r22 = m20*n02 + m21*n12 + m22*n22 + m23*n32;
- float r23 = m20*n03 + m21*n13 + m22*n23 + m23*n33;
-
- float r30 = m30*n00 + m31*n10 + m32*n20 + m33*n30;
- float r31 = m30*n01 + m31*n11 + m32*n21 + m33*n31;
- float r32 = m30*n02 + m31*n12 + m32*n22 + m33*n32;
- float r33 = m30*n03 + m31*n13 + m32*n23 + m33*n33;
-
- m00 = r00; m01 = r01; m02 = r02; m03 = r03;
- m10 = r10; m11 = r11; m12 = r12; m13 = r13;
- m20 = r20; m21 = r21; m22 = r22; m23 = r23;
- m30 = r30; m31 = r31; m32 = r32; m33 = r33;
- }
-
-
- public void preApply(PMatrix2D left) {
- preApply(left.m00, left.m01, 0, left.m02,
- left.m10, left.m11, 0, left.m12,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- }
-
-
- /**
- * Apply another matrix to the left of this one.
- */
- public void preApply(PMatrix3D left) {
- preApply(left.m00, left.m01, left.m02, left.m03,
- left.m10, left.m11, left.m12, left.m13,
- left.m20, left.m21, left.m22, left.m23,
- left.m30, left.m31, left.m32, left.m33);
- }
-
-
- public void preApply(float n00, float n01, float n02,
- float n10, float n11, float n12) {
- preApply(n00, n01, 0, n02,
- n10, n11, 0, n12,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- }
-
-
- 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) {
-
- float r00 = n00*m00 + n01*m10 + n02*m20 + n03*m30;
- float r01 = n00*m01 + n01*m11 + n02*m21 + n03*m31;
- float r02 = n00*m02 + n01*m12 + n02*m22 + n03*m32;
- float r03 = n00*m03 + n01*m13 + n02*m23 + n03*m33;
-
- float r10 = n10*m00 + n11*m10 + n12*m20 + n13*m30;
- float r11 = n10*m01 + n11*m11 + n12*m21 + n13*m31;
- float r12 = n10*m02 + n11*m12 + n12*m22 + n13*m32;
- float r13 = n10*m03 + n11*m13 + n12*m23 + n13*m33;
-
- float r20 = n20*m00 + n21*m10 + n22*m20 + n23*m30;
- float r21 = n20*m01 + n21*m11 + n22*m21 + n23*m31;
- float r22 = n20*m02 + n21*m12 + n22*m22 + n23*m32;
- float r23 = n20*m03 + n21*m13 + n22*m23 + n23*m33;
-
- float r30 = n30*m00 + n31*m10 + n32*m20 + n33*m30;
- float r31 = n30*m01 + n31*m11 + n32*m21 + n33*m31;
- float r32 = n30*m02 + n31*m12 + n32*m22 + n33*m32;
- float r33 = n30*m03 + n31*m13 + n32*m23 + n33*m33;
-
- m00 = r00; m01 = r01; m02 = r02; m03 = r03;
- m10 = r10; m11 = r11; m12 = r12; m13 = r13;
- m20 = r20; m21 = r21; m22 = r22; m23 = r23;
- m30 = r30; m31 = r31; m32 = r32; m33 = r33;
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- public PVector mult(PVector source, PVector target) {
- if (target == null) {
- target = new PVector();
- }
- target.x = m00*source.x + m01*source.y + m02*source.z + m03;
- target.y = m10*source.x + m11*source.y + m12*source.z + m13;
- target.z = m20*source.x + m21*source.y + m22*source.z + m23;
-// float tw = m30*source.x + m31*source.y + m32*source.z + m33;
-// if (tw != 0 && tw != 1) {
-// target.div(tw);
-// }
- return target;
- }
-
-
- /*
- public PVector cmult(PVector source, PVector target) {
- if (target == null) {
- target = new PVector();
- }
- target.x = m00*source.x + m10*source.y + m20*source.z + m30;
- target.y = m01*source.x + m11*source.y + m21*source.z + m31;
- target.z = m02*source.x + m12*source.y + m22*source.z + m32;
- float tw = m03*source.x + m13*source.y + m23*source.z + m33;
- if (tw != 0 && tw != 1) {
- target.div(tw);
- }
- return target;
- }
- */
-
-
- /**
- * Multiply a three or four element vector against this matrix. If out is
- * null or not length 3 or 4, a new float array (length 3) will be returned.
- */
- public float[] mult(float[] source, float[] target) {
- if (target == null || target.length < 3) {
- target = new float[3];
- }
- if (source == target) {
- throw new RuntimeException("The source and target vectors used in " +
- "PMatrix3D.mult() cannot be identical.");
- }
- if (target.length == 3) {
- target[0] = m00*source[0] + m01*source[1] + m02*source[2] + m03;
- target[1] = m10*source[0] + m11*source[1] + m12*source[2] + m13;
- target[2] = m20*source[0] + m21*source[1] + m22*source[2] + m23;
- //float w = m30*source[0] + m31*source[1] + m32*source[2] + m33;
- //if (w != 0 && w != 1) {
- // target[0] /= w; target[1] /= w; target[2] /= w;
- //}
- } else if (target.length > 3) {
- target[0] = m00*source[0] + m01*source[1] + m02*source[2] + m03*source[3];
- target[1] = m10*source[0] + m11*source[1] + m12*source[2] + m13*source[3];
- target[2] = m20*source[0] + m21*source[1] + m22*source[2] + m23*source[3];
- target[3] = m30*source[0] + m31*source[1] + m32*source[2] + m33*source[3];
- }
- return target;
- }
-
-
- public float multX(float x, float y) {
- return m00*x + m01*y + m03;
- }
-
-
- public float multY(float x, float y) {
- return m10*x + m11*y + m13;
- }
-
-
- public float multX(float x, float y, float z) {
- return m00*x + m01*y + m02*z + m03;
- }
-
-
- public float multY(float x, float y, float z) {
- return m10*x + m11*y + m12*z + m13;
- }
-
-
- public float multZ(float x, float y, float z) {
- return m20*x + m21*y + m22*z + m23;
- }
-
-
- public float multW(float x, float y, float z) {
- return m30*x + m31*y + m32*z + m33;
- }
-
-
- public float multX(float x, float y, float z, float w) {
- return m00*x + m01*y + m02*z + m03*w;
- }
-
-
- public float multY(float x, float y, float z, float w) {
- return m10*x + m11*y + m12*z + m13*w;
- }
-
-
- public float multZ(float x, float y, float z, float w) {
- return m20*x + m21*y + m22*z + m23*w;
- }
-
-
- public float multW(float x, float y, float z, float w) {
- return m30*x + m31*y + m32*z + m33*w;
- }
-
-
- /**
- * Transpose this matrix.
- */
- public void transpose() {
- float temp;
- temp = m01; m01 = m10; m10 = temp;
- temp = m02; m02 = m20; m20 = temp;
- temp = m03; m03 = m30; m30 = temp;
- temp = m12; m12 = m21; m21 = temp;
- temp = m13; m13 = m31; m31 = temp;
- temp = m23; m23 = m32; m32 = temp;
- }
-
-
- /**
- * Invert this matrix.
- * @return true if successful
- */
- public boolean invert() {
- float determinant = determinant();
- if (determinant == 0) {
- return false;
- }
-
- // first row
- float t00 = determinant3x3(m11, m12, m13, m21, m22, m23, m31, m32, m33);
- float t01 = -determinant3x3(m10, m12, m13, m20, m22, m23, m30, m32, m33);
- float t02 = determinant3x3(m10, m11, m13, m20, m21, m23, m30, m31, m33);
- float t03 = -determinant3x3(m10, m11, m12, m20, m21, m22, m30, m31, m32);
-
- // second row
- float t10 = -determinant3x3(m01, m02, m03, m21, m22, m23, m31, m32, m33);
- float t11 = determinant3x3(m00, m02, m03, m20, m22, m23, m30, m32, m33);
- float t12 = -determinant3x3(m00, m01, m03, m20, m21, m23, m30, m31, m33);
- float t13 = determinant3x3(m00, m01, m02, m20, m21, m22, m30, m31, m32);
-
- // third row
- float t20 = determinant3x3(m01, m02, m03, m11, m12, m13, m31, m32, m33);
- float t21 = -determinant3x3(m00, m02, m03, m10, m12, m13, m30, m32, m33);
- float t22 = determinant3x3(m00, m01, m03, m10, m11, m13, m30, m31, m33);
- float t23 = -determinant3x3(m00, m01, m02, m10, m11, m12, m30, m31, m32);
-
- // fourth row
- float t30 = -determinant3x3(m01, m02, m03, m11, m12, m13, m21, m22, m23);
- float t31 = determinant3x3(m00, m02, m03, m10, m12, m13, m20, m22, m23);
- float t32 = -determinant3x3(m00, m01, m03, m10, m11, m13, m20, m21, m23);
- float t33 = determinant3x3(m00, m01, m02, m10, m11, m12, m20, m21, m22);
-
- // transpose and divide by the determinant
- m00 = t00 / determinant;
- m01 = t10 / determinant;
- m02 = t20 / determinant;
- m03 = t30 / determinant;
-
- m10 = t01 / determinant;
- m11 = t11 / determinant;
- m12 = t21 / determinant;
- m13 = t31 / determinant;
-
- m20 = t02 / determinant;
- m21 = t12 / determinant;
- m22 = t22 / determinant;
- m23 = t32 / determinant;
-
- m30 = t03 / determinant;
- m31 = t13 / determinant;
- m32 = t23 / determinant;
- m33 = t33 / determinant;
-
- return true;
- }
-
-
- /**
- * Calculate the determinant of a 3x3 matrix.
- * @return result
- */
- private float determinant3x3(float t00, float t01, float t02,
- float t10, float t11, float t12,
- float t20, float t21, float t22) {
- return (t00 * (t11 * t22 - t12 * t21) +
- t01 * (t12 * t20 - t10 * t22) +
- t02 * (t10 * t21 - t11 * t20));
- }
-
-
- /**
- * @return the determinant of the matrix
- */
- public float determinant() {
- float f =
- m00
- * ((m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32)
- - m13 * m22 * m31
- - m11 * m23 * m32
- - m12 * m21 * m33);
- f -= m01
- * ((m10 * m22 * m33 + m12 * m23 * m30 + m13 * m20 * m32)
- - m13 * m22 * m30
- - m10 * m23 * m32
- - m12 * m20 * m33);
- f += m02
- * ((m10 * m21 * m33 + m11 * m23 * m30 + m13 * m20 * m31)
- - m13 * m21 * m30
- - m10 * m23 * m31
- - m11 * m20 * m33);
- f -= m03
- * ((m10 * m21 * m32 + m11 * m22 * m30 + m12 * m20 * m31)
- - m12 * m21 * m30
- - m10 * m22 * m31
- - m11 * m20 * m32);
- return f;
- }
-
-
- //////////////////////////////////////////////////////////////
-
- // REVERSE VERSIONS OF MATRIX OPERATIONS
-
- // These functions should not be used, as they will be removed in the future.
-
-
- protected void invTranslate(float tx, float ty, float tz) {
- preApply(1, 0, 0, -tx,
- 0, 1, 0, -ty,
- 0, 0, 1, -tz,
- 0, 0, 0, 1);
- }
-
-
- protected void invRotateX(float angle) {
- float c = cos(-angle);
- float s = sin(-angle);
- preApply(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
- }
-
-
- protected void invRotateY(float angle) {
- float c = cos(-angle);
- float s = sin(-angle);
- preApply(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
- }
-
-
- protected void invRotateZ(float angle) {
- float c = cos(-angle);
- float s = sin(-angle);
- preApply(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
-
-
- protected void invRotate(float angle, float v0, float v1, float v2) {
- //TODO should make sure this vector is normalized
-
- float c = cos(-angle);
- float s = sin(-angle);
- float t = 1.0f - c;
-
- preApply((t*v0*v0) + c, (t*v0*v1) - (s*v2), (t*v0*v2) + (s*v1), 0,
- (t*v0*v1) + (s*v2), (t*v1*v1) + c, (t*v1*v2) - (s*v0), 0,
- (t*v0*v2) - (s*v1), (t*v1*v2) + (s*v0), (t*v2*v2) + c, 0,
- 0, 0, 0, 1);
- }
-
-
- protected void invScale(float x, float y, float z) {
- preApply(1/x, 0, 0, 0, 0, 1/y, 0, 0, 0, 0, 1/z, 0, 0, 0, 0, 1);
- }
-
-
- protected boolean invApply(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 (inverseCopy == null) {
- inverseCopy = new PMatrix3D();
- }
- inverseCopy.set(n00, n01, n02, n03,
- n10, n11, n12, n13,
- n20, n21, n22, n23,
- n30, n31, n32, n33);
- if (!inverseCopy.invert()) {
- return false;
- }
- preApply(inverseCopy);
- return true;
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- public void print() {
- /*
- System.out.println(m00 + " " + m01 + " " + m02 + " " + m03 + "\n" +
- m10 + " " + m11 + " " + m12 + " " + m13 + "\n" +
- m20 + " " + m21 + " " + m22 + " " + m23 + "\n" +
- m30 + " " + m31 + " " + m32 + " " + m33 + "\n");
- */
- int big = (int) Math.abs(max(max(max(max(abs(m00), abs(m01)),
- max(abs(m02), abs(m03))),
- max(max(abs(m10), abs(m11)),
- max(abs(m12), abs(m13)))),
- max(max(max(abs(m20), abs(m21)),
- max(abs(m22), abs(m23))),
- max(max(abs(m30), abs(m31)),
- max(abs(m32), abs(m33))))));
-
- 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) + " " +
- PApplet.nfs(m03, digits, 4));
-
- System.out.println(PApplet.nfs(m10, digits, 4) + " " +
- PApplet.nfs(m11, digits, 4) + " " +
- PApplet.nfs(m12, digits, 4) + " " +
- PApplet.nfs(m13, digits, 4));
-
- System.out.println(PApplet.nfs(m20, digits, 4) + " " +
- PApplet.nfs(m21, digits, 4) + " " +
- PApplet.nfs(m22, digits, 4) + " " +
- PApplet.nfs(m23, digits, 4));
-
- System.out.println(PApplet.nfs(m30, digits, 4) + " " +
- PApplet.nfs(m31, digits, 4) + " " +
- PApplet.nfs(m32, digits, 4) + " " +
- PApplet.nfs(m33, digits, 4));
-
- System.out.println();
- }
-
-
- //////////////////////////////////////////////////////////////
-
-
- 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);
- }
-}
diff --git a/core/src/processing/core/PPolygon.java b/core/src/processing/core/PPolygon.java
deleted file mode 100644
index 0651fbe2dc3..00000000000
--- a/core/src/processing/core/PPolygon.java
+++ /dev/null
@@ -1,701 +0,0 @@
-/* -*- 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;
-
-
-/**
- * Z-buffer polygon rendering object used by PGraphics2D.
- */
-public class PPolygon implements PConstants {
-
- static final int DEFAULT_SIZE = 64; // this is needed for spheres
- float vertices[][] = new float[DEFAULT_SIZE][VERTEX_FIELD_COUNT];
- int vertexCount;
-
- 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];
-
- protected boolean interpX;
- protected boolean interpUV; // is this necessary? could just check timage != null
- protected boolean interpARGB;
-
- private int rgba;
- private int r2, g2, b2, a2, a2orig;
-
- PGraphics parent;
- int[] pixels;
- // 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;
-
- // 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;
-
- final private int MODYRES(int y) {
- return (y & SUBYRES1);
- }
-
-
- public PPolygon(PGraphics iparent) {
- parent = iparent;
- reset(0);
- }
-
-
- protected void reset(int count) {
- vertexCount = count;
- interpX = true;
-// interpZ = true;
- interpUV = false;
- interpARGB = true;
- timage = null;
- }
-
-
- protected float[] nextVertex() {
- if (vertexCount == vertices.length) {
- float temp[][] = new float[vertexCount<<1][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
- }
-
-
- /**
- * Return true if this vertex is redundant. If so, will also
- * decrement the vertex count.
- */
- /*
- public boolean redundantVertex(float x, float y, float z) {
- // because vertexCount will be 2 when setting vertex[1]
- if (vertexCount < 2) return false;
-
- // vertexCount-1 is the current vertex that would be used
- // vertexCount-2 would be the previous feller
- if ((Math.abs(vertices[vertexCount-2][MX] - x) < EPSILON) &&
- (Math.abs(vertices[vertexCount-2][MY] - y) < EPSILON) &&
- (Math.abs(vertices[vertexCount-2][MZ] - z) < EPSILON)) {
- vertexCount--;
- return true;
- }
- return false;
- }
- */
-
-
- protected void texture(PImage image) {
- this.timage = image;
-
- if (image != null) {
- this.tpixels = image.pixels;
- this.twidth = image.width;
- this.theight = image.height;
- this.tformat = image.format;
-
- twidth1 = twidth - 1;
- theight1 = theight - 1;
- interpUV = true;
-
- } else {
- interpUV = false;
- }
- }
-
-
- protected void renderPolygon(float[][] v, int count) {
- vertices = v;
- vertexCount = count;
-
- if (r.length < vertexCount) {
- r = new float[vertexCount]; // storage used by incrementalize
- dr = new float[vertexCount];
- l = new float[vertexCount]; // more storage for incrementalize
- dl = new float[vertexCount];
- sp = new float[vertexCount]; // temporary storage for scanline
- sdp = new float[vertexCount];
- }
-
- render();
- checkExpand();
- }
-
-
- protected void renderTriangle(float[] v1, float[] v2, float[] v3) {
- // Calling code will have already done reset(3).
- // Can't do it here otherwise would nuke any texture settings.
-
- vertices[0] = v1;
- vertices[1] = v2;
- vertices[2] = v3;
-
- render();
- checkExpand();
- }
-
-
- protected void checkExpand() {
- if (smooth) {
- for (int i = 0; i < vertexCount; i++) {
- vertices[i][TX] /= SUBXRES;
- vertices[i][TY] /= SUBYRES;
- }
- }
- }
-
-
- protected void render() {
- if (vertexCount < 3) return;
-
- // these may have changed due to a resize()
- // so they should be refreshed here
- pixels = parent.pixels;
- //zbuffer = parent.zbuffer;
-
-// noDepthTest = parent.hints[DISABLE_DEPTH_TEST];
- 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;
- }
-
- /*
- // hack to not make polygons fly into the screen
- if (parent.hints[DISABLE_FLYING_POO]) {
- float nwidth2 = -width * 2;
- float nheight2 = -height * 2;
- float width2 = width * 2;
- float height2 = height * 2;
- for (int i = 0; i < vertexCount; i++) {
- if ((vertices[i][TX] < nwidth2) ||
- (vertices[i][TX] > width2) ||
- (vertices[i][TY] < nheight2) ||
- (vertices[i][TY] > height2)) {
- return; // this is a bad poly
- }
- }
- }
- */
-
-// for (int i = 0; i < 4; i++) {
-// System.out.println(vertices[i][R] + " " + vertices[i][G] + " " + vertices[i][B]);
-// }
-// System.out.println();
-
- if (smooth) {
- for (int i = 0; i < vertexCount; i++) {
- vertices[i][TX] *= SUBXRES;
- vertices[i][TY] *= SUBYRES;
- }
- firstModY = -1;
- }
-
- // find top vertex (y is zero at top, higher downwards)
- int topi = 0;
- float ymin = vertices[0][TY];
- float ymax = vertices[0][TY]; // fry 031001
- for (int i = 1; i < vertexCount; i++) {
- if (vertices[i][TY] < ymin) {
- ymin = vertices[i][TY];
- topi = i;
- }
- if (vertices[i][TY] > ymax) {
- ymax = vertices[i][TY];
- }
- }
-
- // 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);
- incrementalizeY(vertices[lefti], vertices[i], l, dl, y);
- lefty = (int) (vertices[i][TY] + 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;
- incrementalizeY(vertices[righti], vertices[i], r, dr, y);
- righty = (int) (vertices[i][TY] + 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[TX] <= r[TX]) 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);
- //}
- }
-
-
- 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[TX] + 0.49999f); // ceil(l[TX]-.5);
- if (lx < 0) lx = 0;
- int rx = (int) (r[TX] - 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
- incrementalizeX(l, r, sp, sdp, lx);
-
- // 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;
- }
-
- interpX = false;
- int tr, tg, tb, ta;
-
-// System.out.println("P2D interp uv " + interpUV + " " +
-// vertices[2][U] + " " + vertices[2][V]);
- for (int x = lx; x <= rx; x++) {
- // map texture based on U, V coords in sp[U] and sp[V]
- if (interpUV) {
- int tu = (int) (sp[U] * twidth);
- int tv = (int) (sp[V] * theight);
-
- 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;
-
- int tuf1 = (int) (255f * (sp[U]*twidth - (float)tu));
- int tvf1 = (int) (255f * (sp[V]*theight - (float)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];
-
- int p00, p01, p10, p11;
- int px0, px1; //, pxy;
-
-
- // calculate alpha component (ta)
-
- 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
- ta = interpARGB ? ((int) (sp[A]*255)) : a2orig;
- }
-
- // calculate r,g,b components (tr, tg, tb)
-
- 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;
-
- } 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;
- }
- }
-
- int weight = smooth ? coverage(x) : 255;
- if (weight != 255) ta = ta*weight >> 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;
-
- } 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);
- }
-
- } 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 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))) {
- 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 incrementalizeY(float p1[], float p2[],
- float p[], float dp[], int y) {
- float delta = p2[TY] - p1[TY];
- if (delta == 0) delta = 1;
- float fraction = y + 0.5f - p1[TY];
-
- if (interpX) {
- dp[TX] = (p2[TX] - p1[TX]) / delta;
- p[TX] = p1[TX] + dp[TX] * 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;
-
- p[U] = p1[U] + dp[U] * fraction;
- p[V] = p1[V] + dp[V] * fraction;
- }
- }
-
-
- private void incrementalizeX(float p1[], float p2[],
- float p[], float dp[], int x) {
- float delta = p2[TX] - p1[TX];
- if (delta == 0) delta = 1;
- float fraction = x + 0.5f - p1[TX];
- if (smooth) {
- delta /= SUBXRES;
- fraction /= SUBXRES;
- }
-
- if (interpX) {
- dp[TX] = (p2[TX] - p1[TX]) / delta;
- p[TX] = p1[TX] + dp[TX] * 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;
-
- p[U] = p1[U] + dp[U] * fraction;
- p[V] = p1[V] + dp[V] * fraction;
- }
- }
-
-
- private void increment(float p[], float dp[]) {
- if (interpX) p[TX] += dp[TX];
-
- if (interpARGB) {
- p[R] += dp[R];
- p[G] += dp[G];
- p[B] += dp[B];
- p[A] += dp[A];
- }
-
- if (interpUV) {
- p[U] += dp[U];
- p[V] += dp[V];
- }
- }
-}
diff --git a/core/src/processing/core/PShape.java b/core/src/processing/core/PShape.java
deleted file mode 100644
index a1a5fb99ed2..00000000000
--- a/core/src/processing/core/PShape.java
+++ /dev/null
@@ -1,955 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2006-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;
-
-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:
- *
- *
- *
addition of proper accessors to read shape vertex and coloring data
- * (this is the second most important part of having a PShape class after all).
- *
a means of creating PShape objects ala beginShape() and endShape().
- *
load(), update(), and cache methods ala PImage, so that shapes can
- * have renderer-specific optimizations, such as vertex arrays in OpenGL.
- *
splitting this class into multiple classes to handle different
- * varieties of shape data (primitives vs collections of vertices vs paths)
- *
change of package declaration, for instance moving the code into
- * package processing.shape (if the code grows too much).
- *
- *
- *
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 nameTable;
-
- /** Generic, only draws its child objects. */
- static public final int GROUP = 0;
- /** A line, ellipse, arc, image, etc. */
- static public final int PRIMITIVE = 1;
- /** A series of vertex, curveVertex, and bezierVertex calls. */
- static public final int PATH = 2;
- /** Collections of vertices created with beginShape(). */
- static public final int GEOMETRY = 3;
- /** The shape type, one of GROUP, PRIMITIVE, PATH, or GEOMETRY. */
- protected int family;
-
- /** ELLIPSE, LINE, QUAD; TRIANGLE_FAN, QUAD_STRIP; etc. */
- protected int kind;
-
- protected PMatrix matrix;
-
- /** Texture or image data associated with this shape. */
- protected PImage image;
-
- // boundary box of this shape
- //protected float x;
- //protected float y;
- //protected float width;
- //protected float height;
- /**
- * The width of the PShape document.
- * @webref
- * @brief Shape document width
- */
- public float width;
- /**
- * The width of the PShape document.
- * @webref
- * @brief Shape document height
- */
- public float height;
-
- // set to false if the object is hidden in the layers palette
- protected boolean visible = true;
-
- protected boolean stroke;
- protected int strokeColor;
- protected float strokeWeight; // default is 1
- protected int strokeCap;
- protected int strokeJoin;
-
- protected boolean fill;
- protected int fillColor;
-
- /** Temporary toggle for whether styles should be honored. */
- protected boolean style = true;
-
- /** For primitive shapes in particular, parms like x/y/w/h or x1/y1/x2/y2. */
- protected float[] params;
-
- protected int vertexCount;
- /**
- * When drawing POLYGON shapes, the second param is an array of length
- * VERTEX_FIELD_COUNT. When drawing PATH shapes, the second param has only
- * two variables.
- */
- protected float[][] vertices;
-
- static public final int VERTEX = 0;
- static public final int BEZIER_VERTEX = 1;
- static public final int CURVE_VERTEX = 2;
- static public final int BREAK = 3;
- /** Array of VERTEX, BEZIER_VERTEX, and CURVE_VERTEXT calls. */
- protected int vertexCodeCount;
- protected int[] vertexCodes;
- /** True if this is a closed path. */
- protected boolean close;
-
- // should this be called vertices (consistent with PGraphics internals)
- // or does that hurt flexibility?
-
- protected PShape parent;
- protected int childCount;
- protected PShape[] children;
-
- // POINTS, LINES, xLINE_STRIP, xLINE_LOOP
- // TRIANGLES, TRIANGLE_STRIP, TRIANGLE_FAN
- // QUADS, QUAD_STRIP
- // xPOLYGON
-// static final int PATH = 1; // POLYGON, LINE_LOOP, LINE_STRIP
-// static final int GROUP = 2;
-
- // how to handle rectmode/ellipsemode?
- // are they bitshifted into the constant?
- // CORNER, CORNERS, CENTER, (CENTER_RADIUS?)
-// static final int RECT = 3; // could just be QUAD, but would be x1/y1/x2/y2
-// static final int ELLIPSE = 4;
-//
-// static final int VERTEX = 7;
-// static final int CURVE = 5;
-// static final int BEZIER = 6;
-
-
- // fill and stroke functions will need a pointer to the parent
- // PGraphics object.. may need some kind of createShape() fxn
- // or maybe the values are stored until draw() is called?
-
- // attaching images is very tricky.. it's a different type of data
-
- // material parameters will be thrown out,
- // except those currently supported (kinds of lights)
-
- // pivot point for transformations
-// public float px;
-// public float py;
-
-
- public PShape() {
- this.family = GROUP;
- }
-
-
- public PShape(int family) {
- this.family = family;
- }
-
-
- public void setName(String name) {
- this.name = name;
- }
-
-
- public String getName() {
- return name;
- }
-
- /**
- * Returns a boolean value "true" if the image is set to be visible, "false" if not. This is modified with the setVisible() parameter.
- *
The visibility of a shape is usually controlled by whatever program created the SVG file.
- * For instance, this parameter is controlled by showing or hiding the shape in the layers palette in Adobe Illustrator.
- *
- * @webref
- * @brief Returns a boolean value "true" if the image is set to be visible, "false" if not
- */
- public boolean isVisible() {
- return visible;
- }
-
- /**
- * Sets the shape to be visible or invisible. This is determined by the value of the visible parameter.
- *
The visibility of a shape is usually controlled by whatever program created the SVG file.
- * For instance, this parameter is controlled by showing or hiding the shape in the layers palette in Adobe Illustrator.
- * @param visible "false" makes the shape invisible and "true" makes it visible
- * @webref
- * @brief Sets the shape to be visible or invisible
- */
- public void setVisible(boolean visible) {
- this.visible = visible;
- }
-
-
- /**
- * Disables the shape's style data and uses Processing's current styles. Styles include attributes such as colors, stroke weight, and stroke joints.
- * =advanced
- * Overrides this shape's style information and uses PGraphics styles and
- * colors. Identical to ignoreStyles(true). Also disables styles for all
- * child shapes.
- * @webref
- * @brief Disables the shape's style data and uses Processing styles
- */
- public void disableStyle() {
- style = false;
-
- for (int i = 0; i < childCount; i++) {
- children[i].disableStyle();
- }
- }
-
-
- /**
- * Enables the shape's style data and ignores Processing's current styles. Styles include attributes such as colors, stroke weight, and stroke joints.
- * @webref
- * @brief Enables the shape's style data and ignores the Processing styles
- */
- public void enableStyle() {
- style = true;
-
- for (int i = 0; i < childCount; i++) {
- children[i].enableStyle();
- }
- }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
-// protected void checkBounds() {
-// if (width == 0 || height == 0) {
-// // calculate bounds here (also take kids into account)
-// width = 1;
-// height = 1;
-// }
-// }
-
-
- /**
- * Get the width of the drawing area (not necessarily the shape boundary).
- */
- public float getWidth() {
- //checkBounds();
- return width;
- }
-
-
- /**
- * Get the height of the drawing area (not necessarily the shape boundary).
- */
- public float getHeight() {
- //checkBounds();
- return height;
- }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- /*
- boolean strokeSaved;
- int strokeColorSaved;
- float strokeWeightSaved;
- int strokeCapSaved;
- int strokeJoinSaved;
-
- boolean fillSaved;
- int fillColorSaved;
-
- int rectModeSaved;
- int ellipseModeSaved;
- int shapeModeSaved;
- */
-
-
- protected void pre(PGraphics g) {
- if (matrix != null) {
- g.pushMatrix();
- g.applyMatrix(matrix);
- }
-
- /*
- strokeSaved = g.stroke;
- strokeColorSaved = g.strokeColor;
- strokeWeightSaved = g.strokeWeight;
- strokeCapSaved = g.strokeCap;
- strokeJoinSaved = g.strokeJoin;
-
- fillSaved = g.fill;
- fillColorSaved = g.fillColor;
-
- rectModeSaved = g.rectMode;
- ellipseModeSaved = g.ellipseMode;
- shapeModeSaved = g.shapeMode;
- */
- if (style) {
- g.pushStyle();
- styles(g);
- }
- }
-
-
- protected void styles(PGraphics g) {
- // should not be necessary because using only the int version of color
- //parent.colorMode(PConstants.RGB, 255);
-
- if (stroke) {
- g.stroke(strokeColor);
- g.strokeWeight(strokeWeight);
- g.strokeCap(strokeCap);
- g.strokeJoin(strokeJoin);
- } else {
- g.noStroke();
- }
-
- if (fill) {
- //System.out.println("filling " + PApplet.hex(fillColor));
- g.fill(fillColor);
- } else {
- g.noFill();
- }
- }
-
-
- public void post(PGraphics g) {
-// for (int i = 0; i < childCount; i++) {
-// children[i].draw(g);
-// }
-
- /*
- // TODO this is not sufficient, since not saving fillR et al.
- g.stroke = strokeSaved;
- g.strokeColor = strokeColorSaved;
- g.strokeWeight = strokeWeightSaved;
- g.strokeCap = strokeCapSaved;
- g.strokeJoin = strokeJoinSaved;
-
- g.fill = fillSaved;
- g.fillColor = fillColorSaved;
-
- g.ellipseMode = ellipseModeSaved;
- */
-
- if (matrix != null) {
- g.popMatrix();
- }
-
- if (style) {
- g.popStyle();
- }
- }
-
-
- /**
- * Called by the following (the shape() command adds the g)
- * PShape s = loadShapes("blah.svg");
- * shape(s);
- */
- public void draw(PGraphics g) {
- if (visible) {
- pre(g);
- drawImpl(g);
- post(g);
- }
- }
-
-
- /**
- * Draws the SVG document.
- */
- public void drawImpl(PGraphics g) {
- //System.out.println("drawing " + family);
- if (family == GROUP) {
- drawGroup(g);
- } else if (family == PRIMITIVE) {
- drawPrimitive(g);
- } else if (family == GEOMETRY) {
- drawGeometry(g);
- } else if (family == PATH) {
- drawPath(g);
- }
- }
-
-
- protected void drawGroup(PGraphics g) {
- for (int i = 0; i < childCount; i++) {
- children[i].draw(g);
- }
- }
-
-
- protected void drawPrimitive(PGraphics g) {
- if (kind == POINT) {
- g.point(params[0], params[1]);
-
- } else if (kind == LINE) {
- if (params.length == 4) { // 2D
- g.line(params[0], params[1],
- params[2], params[3]);
- } else { // 3D
- g.line(params[0], params[1], params[2],
- params[3], params[4], params[5]);
- }
-
- } else if (kind == TRIANGLE) {
- g.triangle(params[0], params[1],
- params[2], params[3],
- params[4], params[5]);
-
- } else if (kind == QUAD) {
- g.quad(params[0], params[1],
- params[2], params[3],
- params[4], params[5],
- params[6], params[7]);
-
- } else if (kind == RECT) {
- if (image != null) {
- g.imageMode(CORNER);
- g.image(image, params[0], params[1], params[2], params[3]);
- } else {
- g.rectMode(CORNER);
- g.rect(params[0], params[1], params[2], params[3]);
- }
-
- } else if (kind == ELLIPSE) {
- g.ellipseMode(CORNER);
- g.ellipse(params[0], params[1], params[2], params[3]);
-
- } else if (kind == ARC) {
- g.ellipseMode(CORNER);
- g.arc(params[0], params[1], params[2], params[3], params[4], params[5]);
-
- } else if (kind == BOX) {
- if (params.length == 1) {
- g.box(params[0]);
- } else {
- g.box(params[0], params[1], params[2]);
- }
-
- } else if (kind == SPHERE) {
- g.sphere(params[0]);
- }
- }
-
-
- protected void drawGeometry(PGraphics g) {
- g.beginShape(kind);
- if (style) {
- for (int i = 0; i < vertexCount; i++) {
- g.vertex(vertices[i]);
- }
- } else {
- for (int i = 0; i < vertexCount; i++) {
- float[] vert = vertices[i];
- if (vert[PGraphics.Z] == 0) {
- g.vertex(vert[X], vert[Y]);
- } else {
- g.vertex(vert[X], vert[Y], vert[Z]);
- }
- }
- }
- g.endShape();
- }
-
-
- /*
- protected void drawPath(PGraphics g) {
- g.beginShape();
- for (int j = 0; j < childCount; j++) {
- if (j > 0) g.breakShape();
- int count = children[j].vertexCount;
- float[][] vert = children[j].vertices;
- int[] code = children[j].vertexCodes;
-
- for (int i = 0; i < count; i++) {
- if (style) {
- if (children[j].fill) {
- g.fill(vert[i][R], vert[i][G], vert[i][B]);
- } else {
- g.noFill();
- }
- if (children[j].stroke) {
- g.stroke(vert[i][R], vert[i][G], vert[i][B]);
- } else {
- g.noStroke();
- }
- }
- g.edge(vert[i][EDGE] == 1);
-
- if (code[i] == VERTEX) {
- g.vertex(vert[i]);
-
- } else if (code[i] == BEZIER_VERTEX) {
- float z0 = vert[i+0][Z];
- float z1 = vert[i+1][Z];
- float z2 = vert[i+2][Z];
- if (z0 == 0 && z1 == 0 && z2 == 0) {
- g.bezierVertex(vert[i+0][X], vert[i+0][Y], z0,
- vert[i+1][X], vert[i+1][Y], z1,
- vert[i+2][X], vert[i+2][Y], z2);
- } else {
- g.bezierVertex(vert[i+0][X], vert[i+0][Y],
- vert[i+1][X], vert[i+1][Y],
- vert[i+2][X], vert[i+2][Y]);
- }
- } else if (code[i] == CURVE_VERTEX) {
- float z = vert[i][Z];
- if (z == 0) {
- g.curveVertex(vert[i][X], vert[i][Y]);
- } else {
- g.curveVertex(vert[i][X], vert[i][Y], z);
- }
- }
- }
- }
- g.endShape();
- }
- */
-
-
- protected void drawPath(PGraphics g) {
- // Paths might be empty (go figure)
- // http://dev.processing.org/bugs/show_bug.cgi?id=982
- if (vertices == null) return;
-
- g.beginShape();
-
- if (vertexCodeCount == 0) { // each point is a simple vertex
- if (vertices[0].length == 2) { // drawing 2D vertices
- for (int i = 0; i < vertexCount; i++) {
- g.vertex(vertices[i][X], vertices[i][Y]);
- }
- } else { // drawing 3D vertices
- for (int i = 0; i < vertexCount; i++) {
- g.vertex(vertices[i][X], vertices[i][Y], vertices[i][Z]);
- }
- }
-
- } else { // coded set of vertices
- int index = 0;
-
- if (vertices[0].length == 2) { // drawing a 2D path
- for (int j = 0; j < vertexCodeCount; j++) {
- switch (vertexCodes[j]) {
-
- case VERTEX:
- g.vertex(vertices[index][X], vertices[index][Y]);
- index++;
- break;
-
- case BEZIER_VERTEX:
- g.bezierVertex(vertices[index+0][X], vertices[index+0][Y],
- vertices[index+1][X], vertices[index+1][Y],
- vertices[index+2][X], vertices[index+2][Y]);
- index += 3;
- break;
-
- case CURVE_VERTEX:
- g.curveVertex(vertices[index][X], vertices[index][Y]);
- index++;
-
- case BREAK:
- g.breakShape();
- }
- }
- } else { // drawing a 3D path
- for (int j = 0; j < vertexCodeCount; j++) {
- switch (vertexCodes[j]) {
-
- case VERTEX:
- g.vertex(vertices[index][X], vertices[index][Y], vertices[index][Z]);
- index++;
- break;
-
- case BEZIER_VERTEX:
- g.bezierVertex(vertices[index+0][X], vertices[index+0][Y], vertices[index+0][Z],
- vertices[index+1][X], vertices[index+1][Y], vertices[index+1][Z],
- vertices[index+2][X], vertices[index+2][Y], vertices[index+2][Z]);
- index += 3;
- break;
-
- case CURVE_VERTEX:
- g.curveVertex(vertices[index][X], vertices[index][Y], vertices[index][Z]);
- index++;
-
- case BREAK:
- g.breakShape();
- }
- }
- }
- }
- g.endShape(close ? CLOSE : OPEN);
- }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- public int getChildCount() {
- return childCount;
- }
-
- /**
- *
- * @param index the layer position of the shape to get
- */
- public PShape getChild(int index) {
- return children[index];
- }
-
- /**
- * Extracts a child shape from a parent shape. Specify the name of the shape with the target parameter.
- * The shape is returned as a PShape object, or null is returned if there is an error.
- * @param target the name of the shape to get
- * @webref
- * @brief Returns a child element of a shape as a PShape object
- */
- public PShape getChild(String target) {
- if (name != null && name.equals(target)) {
- return this;
- }
- if (nameTable != null) {
- PShape found = nameTable.get(target);
- if (found != null) return found;
- }
- for (int i = 0; i < childCount; i++) {
- PShape found = children[i].getChild(target);
- if (found != null) return found;
- }
- return null;
- }
-
-
- /**
- * Same as getChild(name), except that it first walks all the way up the
- * hierarchy to the farthest parent, so that children can be found anywhere.
- */
- public PShape findChild(String target) {
- if (parent == null) {
- return getChild(target);
-
- } else {
- return parent.findChild(target);
- }
- }
-
-
- // can't be just 'add' because that suggests additive geometry
- public void addChild(PShape who) {
- if (children == null) {
- children = new PShape[1];
- }
- if (childCount == children.length) {
- children = (PShape[]) PApplet.expand(children);
- }
- children[childCount++] = who;
- who.parent = this;
-
- if (who.getName() != null) {
- addName(who.getName(), who);
- }
- }
-
-
- /**
- * Add a shape to the name lookup table.
- */
- protected void addName(String nom, PShape shape) {
- if (parent != null) {
- parent.addName(nom, shape);
- } else {
- if (nameTable == null) {
- nameTable = new HashMap();
- }
- nameTable.put(nom, shape);
- }
- }
-
-
-// public PShape createGroup() {
-// PShape group = new PShape();
-// group.kind = GROUP;
-// addChild(group);
-// return group;
-// }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- // translate, rotate, scale, apply (no push/pop)
- // these each call matrix.translate, etc
- // if matrix is null when one is called,
- // it is created and set to identity
-
- public void translate(float tx, float ty) {
- checkMatrix(2);
- matrix.translate(tx, ty);
- }
-
- /**
- * Specifies an amount to displace the shape. The x parameter specifies left/right translation, the y parameter specifies up/down translation, and the z parameter specifies translations toward/away from the screen. Subsequent calls to the method accumulates the effect. For example, calling translate(50, 0) and then translate(20, 0) is the same as translate(70, 0). This transformation is applied directly to the shape, it's not refreshed each time draw() is run.
- *
Using this method with the z parameter requires using the P3D or OPENGL parameter in combination with size.
- * @webref
- * @param tx left/right translation
- * @param ty up/down translation
- * @param tz forward/back translation
- * @brief Displaces the shape
- */
- public void translate(float tx, float ty, float tz) {
- checkMatrix(3);
- matrix.translate(tx, ty, 0);
- }
-
- /**
- * Rotates a shape around the x-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO_PI) or converted to radians with the radians() method.
- *
Shapes are always rotated around the upper-left corner of their bounding box. Positive numbers rotate objects in a clockwise direction.
- * Subsequent calls to the method accumulates the effect. For example, calling rotateX(HALF_PI) and then rotateX(HALF_PI) is the same as rotateX(PI).
- * This transformation is applied directly to the shape, it's not refreshed each time draw() is run.
- *
This method requires a 3D renderer. You need to pass P3D or OPENGL as a third parameter into the size() method as shown in the example above.
- * @param angle angle of rotation specified in radians
- * @webref
- * @brief Rotates the shape around the x-axis
- */
- public void rotateX(float angle) {
- rotate(angle, 1, 0, 0);
- }
-
- /**
- * Rotates a shape around the y-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO_PI) or converted to radians with the radians() method.
- *
Shapes are always rotated around the upper-left corner of their bounding box. Positive numbers rotate objects in a clockwise direction.
- * Subsequent calls to the method accumulates the effect. For example, calling rotateY(HALF_PI) and then rotateY(HALF_PI) is the same as rotateY(PI).
- * This transformation is applied directly to the shape, it's not refreshed each time draw() is run.
- *
This method requires a 3D renderer. You need to pass P3D or OPENGL as a third parameter into the size() method as shown in the example above.
- * @param angle angle of rotation specified in radians
- * @webref
- * @brief Rotates the shape around the y-axis
- */
- public void rotateY(float angle) {
- rotate(angle, 0, 1, 0);
- }
-
-
- /**
- * Rotates a shape around the z-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO_PI) or converted to radians with the radians() method.
- *
Shapes are always rotated around the upper-left corner of their bounding box. Positive numbers rotate objects in a clockwise direction.
- * Subsequent calls to the method accumulates the effect. For example, calling rotateZ(HALF_PI) and then rotateZ(HALF_PI) is the same as rotateZ(PI).
- * This transformation is applied directly to the shape, it's not refreshed each time draw() is run.
- *
This method requires a 3D renderer. You need to pass P3D or OPENGL as a third parameter into the size() method as shown in the example above.
- * @param angle angle of rotation specified in radians
- * @webref
- * @brief Rotates the shape around the z-axis
- */
- public void rotateZ(float angle) {
- rotate(angle, 0, 0, 1);
- }
-
- /**
- * Rotates a shape the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO_PI) or converted to radians with the radians() method.
- *
Shapes are always rotated around the upper-left corner of their bounding box. Positive numbers rotate objects in a clockwise direction.
- * Transformations apply to everything that happens after and subsequent calls to the method accumulates the effect.
- * For example, calling rotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI).
- * This transformation is applied directly to the shape, it's not refreshed each time draw() is run.
- * @param angle angle of rotation specified in radians
- * @webref
- * @brief Rotates the shape
- */
- public void rotate(float angle) {
- checkMatrix(2); // at least 2...
- matrix.rotate(angle);
- }
-
-
- public void rotate(float angle, float v0, float v1, float v2) {
- checkMatrix(3);
- matrix.rotate(angle, v0, v1, v2);
- }
-
-
- //
-
- /**
- * @param s percentage to scale the object
- */
- public void scale(float s) {
- checkMatrix(2); // at least 2...
- matrix.scale(s);
- }
-
-
- public void scale(float x, float y) {
- checkMatrix(2);
- matrix.scale(x, y);
- }
-
-
- /**
- * Increases or decreases the size of a shape by expanding and contracting vertices. Shapes always scale from the relative origin of their bounding box.
- * Scale values are specified as decimal percentages. For example, the method call scale(2.0) increases the dimension of a shape by 200%.
- * Subsequent calls to the method multiply the effect. For example, calling scale(2.0) and then scale(1.5) is the same as scale(3.0).
- * This transformation is applied directly to the shape, it's not refreshed each time draw() is run.
- *
Using this fuction with the z parameter requires passing P3D or OPENGL into the size() parameter.
- * @param x percentage to scale the object in the x-axis
- * @param y percentage to scale the object in the y-axis
- * @param z percentage to scale the object in the z-axis
- * @webref
- * @brief Increases and decreases the size of a shape
- */
- public void scale(float x, float y, float z) {
- checkMatrix(3);
- matrix.scale(x, y, z);
- }
-
-
- //
-
-
- public void resetMatrix() {
- checkMatrix(2);
- matrix.reset();
- }
-
-
- public void applyMatrix(PMatrix source) {
- if (source instanceof PMatrix2D) {
- applyMatrix((PMatrix2D) source);
- } else if (source instanceof PMatrix3D) {
- applyMatrix((PMatrix3D) source);
- }
- }
-
-
- public void applyMatrix(PMatrix2D source) {
- applyMatrix(source.m00, source.m01, 0, source.m02,
- source.m10, source.m11, 0, source.m12,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- }
-
-
- public void applyMatrix(float n00, float n01, float n02,
- float n10, float n11, float n12) {
- checkMatrix(2);
- matrix.apply(n00, n01, n02, 0,
- n10, n11, n12, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- }
-
-
- public void apply(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);
- }
-
-
- 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) {
- checkMatrix(3);
- matrix.apply(n00, n01, n02, n03,
- n10, n11, n12, n13,
- n20, n21, n22, n23,
- n30, n31, n32, n33);
- }
-
-
- //
-
-
- /**
- * Make sure that the shape's matrix is 1) not null, and 2) has a matrix
- * that can handle at least the specified number of dimensions.
- */
- protected void checkMatrix(int dimensions) {
- if (matrix == null) {
- if (dimensions == 2) {
- matrix = new PMatrix2D();
- } else {
- matrix = new PMatrix3D();
- }
- } else if (dimensions == 3 && (matrix instanceof PMatrix2D)) {
- // time for an upgrayedd for a double dose of my pimpin'
- matrix = new PMatrix3D(matrix);
- }
- }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- /**
- * Center the shape based on its bounding box. Can't assume
- * that the bounding box is 0, 0, width, height. Common case will be
- * opening a letter size document in Illustrator, and drawing something
- * in the middle, then reading it in as an svg file.
- * This will also need to flip the y axis (scale(1, -1)) in cases
- * like Adobe Illustrator where the coordinates start at the bottom.
- */
-// public void center() {
-// }
-
-
- /**
- * Set the pivot point for all transformations.
- */
-// public void pivot(float x, float y) {
-// px = x;
-// py = y;
-// }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-}
\ No newline at end of file
diff --git a/core/src/processing/core/PShapeSVG.java b/core/src/processing/core/PShapeSVG.java
deleted file mode 100644
index 0bbf2c51a6a..00000000000
--- a/core/src/processing/core/PShapeSVG.java
+++ /dev/null
@@ -1,1473 +0,0 @@
-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)
- *
- *
- *
- * 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.
- *
- *
- *
- * Late October 2008 revisions from ricardmp, incorporated by fry (0154)
- *
- *
- * October 2008 revisions by fry (Processing 0149, pre-1.0)
- *
- *
Candy is no longer a separate library, and is instead part of core.
- *
Loading now works through loadShape()
- *
Shapes are now drawn using the new PGraphics shape() method.
- *
- *
- * August 2008 revisions by fry (Processing 0149)
- *
- *
Major changes to rework around PShape.
- *
Now implementing more of the "transform" attribute.
- *
- *
- * February 2008 revisions by fry (Processing 0136)
- *
- *
Added support for quadratic curves in paths (Q, q, T, and t operators)
- *
Support for reading SVG font data (though not rendering it yet)
- *
- *
- * Revisions for "Candy 2" November 2006 by fry
- *
- *
Switch to the new processing.xml library
- *
Several bug fixes for parsing of shape data
- *
Support for linear and radial gradients
- *
Support for additional types of shapes
- *
Added compound shapes (shapes with interior points)
- *
Added methods to get shapes from an internal table
- *
- *
- * Revision 10/31/06 by flux
- *
- *
Now properly supports Processing 0118
- *
Fixed a bunch of things for Casey's students and general buggity.
- *
Will now properly draw #FFFFFFFF colors (were being represented as -1)
- *
SVGs without tags are now properly caught and loaded
- *
Added a method customStyle() for overriding SVG colors/styles
- *
Added a method SVGStyle() to go back to using SVG colors/styles
- *
- *
- * Some SVG objects and features may not yet be supported.
- * Here is a partial list of non-included features
- *
- *
Rounded rectangles
- *
Drop shadow objects
- *
Typography
- *
Layers added for Candy 2
- *
Patterns
- *
Embedded images
- *
- *
- * For those interested, the SVG specification can be found
- * here.
- */
-public class PShapeSVG extends PShape {
- XMLElement element;
-
- 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