Automatic code cleanup

This commit is contained in:
Andrea Cavalli 2018-05-12 21:18:29 +02:00
parent d379f8a318
commit 5d585a9ad6
91 changed files with 1257 additions and 1277 deletions

View File

@ -31,7 +31,8 @@ import java.nio.file.ProviderNotFoundException;
import java.nio.file.StandardCopyOption;
/**
* A simple library class which helps with loading dynamic libraries stored in the
* A simple library class which helps with loading dynamic libraries stored in
* the
* JAR archive. These libraries usualy contain implementation of some methods in
* native code (using JNI - Java Native Interface).
*
@ -40,106 +41,112 @@ import java.nio.file.StandardCopyOption;
*
*/
public class NativeUtils {
/**
* The minimum length a prefix for a file has to have according to {@link File#createTempFile(String, String)}}.
*/
private static final int MIN_PREFIX_LENGTH = 3;
/**
* Temporary directory which will contain the DLLs.
*/
private static File temporaryDir;
/**
* The minimum length a prefix for a file has to have according to
* {@link File#createTempFile(String, String)}}.
*/
private static final int MIN_PREFIX_LENGTH = 3;
/**
* Private constructor - this class will never be instanced
*/
private NativeUtils() {
}
/**
* Temporary directory which will contain the DLLs.
*/
private static File temporaryDir;
/**
* Loads library from current JAR archive
*
* The file from JAR is copied into system temporary directory and then loaded. The temporary file is deleted after
* exiting.
* Method uses String as filename because the pathname is "abstract", not system-dependent.
*
* @param path The path of file inside JAR as absolute path (beginning with '/'), e.g. /package/File.ext
* @throws IOException If temporary file creation or read/write operation fails
* @throws IllegalArgumentException If source file (param path) does not exist
* @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than three characters
* (restriction of {@link File#createTempFile(java.lang.String, java.lang.String)}).
* @throws FileNotFoundException If the file could not be found inside the JAR.
*/
public static void loadLibraryFromJar(String path) throws IOException {
if (!path.startsWith("/")) {
throw new IllegalArgumentException("The path has to be absolute (start with '/').");
}
// Obtain filename from path
String[] parts = path.split("/");
String filename = (parts.length > 1) ? parts[parts.length - 1] : null;
// Check if the filename is okay
if (filename == null || filename.length() < MIN_PREFIX_LENGTH) {
throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
}
// Prepare temporary file
if (temporaryDir == null) {
temporaryDir = createTempDirectory("nativeutils");
temporaryDir.deleteOnExit();
}
/**
* Private constructor - this class will never be instanced
*/
private NativeUtils() {}
File temp = new File(temporaryDir, filename);
/**
* Loads library from current JAR archive
*
* The file from JAR is copied into system temporary directory and then
* loaded. The temporary file is deleted after
* exiting.
* Method uses String as filename because the pathname is "abstract", not
* system-dependent.
*
* @param path
* The path of file inside JAR as absolute path (beginning with
* '/'), e.g. /package/File.ext
* @throws IOException
* If temporary file creation or read/write operation fails
* @throws IllegalArgumentException
* If source file (param path) does not exist
* @throws IllegalArgumentException
* If the path is not absolute or if the filename is shorter
* than three characters
* (restriction of
* {@link File#createTempFile(java.lang.String, java.lang.String)}).
* @throws FileNotFoundException
* If the file could not be found inside the JAR.
*/
public static void loadLibraryFromJar(String path) throws IOException {
try (InputStream is = NativeUtils.class.getResourceAsStream(path)) {
Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
temp.delete();
throw e;
} catch (NullPointerException e) {
temp.delete();
throw new FileNotFoundException("File " + path + " was not found inside JAR.");
}
if (!path.startsWith("/")) {
throw new IllegalArgumentException("The path has to be absolute (start with '/').");
}
try {
System.load(temp.getAbsolutePath());
} finally {
if (isPosixCompliant()) {
// Assume POSIX compliant file system, can be deleted after loading
temp.delete();
} else {
// Assume non-POSIX, and don't delete until last file descriptor closed
temp.deleteOnExit();
}
}
}
// Obtain filename from path
final String[] parts = path.split("/");
final String filename = (parts.length > 1) ? parts[parts.length - 1] : null;
private static boolean isPosixCompliant() {
try {
if (FileSystems.getDefault()
.supportedFileAttributeViews()
.contains("posix")) {
return true;
}
return false;
} catch (FileSystemNotFoundException
| ProviderNotFoundException
| SecurityException e) {
return false;
}
}
private static File createTempDirectory(String prefix) throws IOException
{
String tempDir = System.getProperty("java.io.tmpdir");
File generatedDir = new File(tempDir, prefix + System.nanoTime());
if (!generatedDir.mkdir())
throw new IOException("Failed to create temp directory " + generatedDir.getName());
return generatedDir;
}
// Check if the filename is okay
if (filename == null || filename.length() < MIN_PREFIX_LENGTH) {
throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
}
// Prepare temporary file
if (temporaryDir == null) {
temporaryDir = createTempDirectory("nativeutils");
temporaryDir.deleteOnExit();
}
final File temp = new File(temporaryDir, filename);
try (InputStream is = NativeUtils.class.getResourceAsStream(path)) {
Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (final IOException e) {
temp.delete();
throw e;
} catch (final NullPointerException e) {
temp.delete();
throw new FileNotFoundException("File " + path + " was not found inside JAR.");
}
try {
System.load(temp.getAbsolutePath());
} finally {
if (isPosixCompliant()) {
// Assume POSIX compliant file system, can be deleted after loading
temp.delete();
} else {
// Assume non-POSIX, and don't delete until last file descriptor closed
temp.deleteOnExit();
}
}
}
private static boolean isPosixCompliant() {
try {
if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
return true;
}
return false;
} catch (FileSystemNotFoundException | ProviderNotFoundException | SecurityException e) {
return false;
}
}
private static File createTempDirectory(String prefix) throws IOException {
final String tempDir = System.getProperty("java.io.tmpdir");
final File generatedDir = new File(tempDir, prefix + System.nanoTime());
if (!generatedDir.mkdir()) {
throw new IOException("Failed to create temp directory " + generatedDir.getName());
}
return generatedDir;
}
}

View File

@ -1,12 +1,5 @@
package org.warp.picalculator;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.warp.picalculator.device.Keyboard;
import org.warp.picalculator.device.PIHardwareDisplay;
import org.warp.picalculator.gui.CalculatorHUD;
@ -23,6 +16,7 @@ import com.pi4j.wiringpi.Gpio;
public class Main {
public static Main instance;
public static String[] args;
public Main(String[] args) throws InterruptedException, Error {
this(new LoadingScreen(), new PIHardwareDisplay(), new CalculatorHUD(), args);
}
@ -52,7 +46,7 @@ public class Main {
boolean isRaspi = false;
try {
isRaspi = com.pi4j.system.SystemInfo.getBoardType() != BoardType.UNKNOWN;
} catch (Exception e) {}
} catch (final Exception e) {}
if (Utils.isRunningOnRaspberry() && !Utils.isInArray("-noraspi", args) && isRaspi) {
Gpio.wiringPiSetupPhys();
Gpio.pinMode(12, Gpio.PWM_OUTPUT);
@ -61,7 +55,7 @@ public class Main {
StaticVars.debugOn = true;
}
Utils.debugThirdScreen = StaticVars.debugOn & false;
for (String arg : args) {
for (final String arg : args) {
if (arg.contains("2x")) {
StaticVars.debugWindow2x = true;
}

View File

@ -1,13 +1,12 @@
package org.warp.picalculator;
import java.nio.ByteBuffer;
public class MmapByteBuffer {
private int fd;
private int address;
private int length;
private ByteBuffer buffer;
private final int fd;
private final int address;
private final int length;
private final ByteBuffer buffer;
public MmapByteBuffer(int fd, int address, int length, ByteBuffer buffer) {
this.fd = fd;
@ -19,15 +18,15 @@ public class MmapByteBuffer {
public int getFd() {
return fd;
}
public int getAddress() {
return address;
}
public int getLength() {
return length;
}
public ByteBuffer getBuffer() {
return buffer;
}

View File

@ -10,13 +10,13 @@ public class ScriptUtils {
}
public static LinkedList<BigInteger> mcm(LinkedList<BigInteger> factors1, LinkedList<BigInteger> factors2) {
LinkedList<BigInteger> mcm = new LinkedList<>();
Iterator<BigInteger> i1 = factors1.iterator();
while(i1.hasNext()) {
BigInteger int1 = i1.next();
Iterator<BigInteger> i2 = factors2.iterator();
while(i2.hasNext()) {
BigInteger int2 = i2.next();
final LinkedList<BigInteger> mcm = new LinkedList<>();
final Iterator<BigInteger> i1 = factors1.iterator();
while (i1.hasNext()) {
final BigInteger int1 = i1.next();
final Iterator<BigInteger> i2 = factors2.iterator();
while (i2.hasNext()) {
final BigInteger int2 = i2.next();
if (int1.equals(int2)) {
i1.remove();
i2.remove();

View File

@ -14,9 +14,9 @@ public class StaticVars {
public static boolean debugWindow2x = false;
public static Class<?> classLoader;
public static float windowZoom = 2;
private StaticVars() {
}
public static float getCurrentZoomValue() {

View File

@ -115,7 +115,7 @@ public class TestGPU {
break;
}
return false;
} catch (Exception ex) {
} catch (final Exception ex) {
ex.printStackTrace();
}
return false;

View File

@ -2,12 +2,11 @@ package org.warp.picalculator;
import org.warp.picalculator.MmapByteBuffer;
public class TestJNI {
public TestJNI() {
}
static {
System.load("/boot/libpicalc.so");
}
@ -19,7 +18,7 @@ public class TestJNI {
public MmapByteBuffer retrieveBuffer() {
return getDisplayBuffer();
}
public void deleteBuffer() {
disposeDisplayBuffer();
}

View File

@ -77,46 +77,29 @@ public class Utils {
public static boolean msDosMode;
public static boolean debugCache;
public static boolean newtMode = true;
public static final class AdvancedOutputStream extends StringWriter {
private void print(PrintStream stream, String str) {
stream.print(fixString(str));
}
private void println(PrintStream stream, String str) {
stream.println(fixString(str));
}
private void println(PrintStream stream) {
stream.println();
}
private String fixString(String str) {
return str
.replace(""+MathematicalSymbols.NTH_ROOT, "root")
.replace(""+MathematicalSymbols.SQUARE_ROOT, "sqrt")
.replace(""+MathematicalSymbols.POWER, "powerOf")
.replace(""+MathematicalSymbols.POWER_OF_TWO, "powerOfTwo")
.replace(""+MathematicalSymbols.SINE, "sine")
.replace(""+MathematicalSymbols.COSINE, "cosine")
.replace(""+MathematicalSymbols.TANGENT, "tangent")
.replace(""+MathematicalSymbols.ARC_SINE, "asin")
.replace(""+MathematicalSymbols.ARC_COSINE, "acos")
.replace(""+MathematicalSymbols.ARC_TANGENT, "atan")
.replace(""+MathematicalSymbols.UNDEFINED, "undefined")
.replace(""+MathematicalSymbols.PI, "PI")
.replace(""+MathematicalSymbols.EULER_NUMBER, "EULER_NUMBER")
.replace(""+MathematicalSymbols.X, "X")
.replace(""+MathematicalSymbols.Y, "Y")
;
return str.replace("" + MathematicalSymbols.NTH_ROOT, "root").replace("" + MathematicalSymbols.SQUARE_ROOT, "sqrt").replace("" + MathematicalSymbols.POWER, "powerOf").replace("" + MathematicalSymbols.POWER_OF_TWO, "powerOfTwo").replace("" + MathematicalSymbols.SINE, "sine").replace("" + MathematicalSymbols.COSINE, "cosine").replace("" + MathematicalSymbols.TANGENT, "tangent").replace("" + MathematicalSymbols.ARC_SINE, "asin").replace("" + MathematicalSymbols.ARC_COSINE, "acos").replace("" + MathematicalSymbols.ARC_TANGENT, "atan").replace("" + MathematicalSymbols.UNDEFINED, "undefined").replace("" + MathematicalSymbols.PI, "PI").replace("" + MathematicalSymbols.EULER_NUMBER, "EULER_NUMBER").replace("" + MathematicalSymbols.X, "X").replace("" + MathematicalSymbols.Y, "Y");
}
public void println(String str) {
println(0, str);
}
public void println(int level) {
if (StaticVars.outputLevel >= level) {
@ -133,9 +116,9 @@ public class Utils {
if (StaticVars.outputLevel >= level) {
final String time = getTimeString();
if (StaticVars.outputLevel == 0) {
println(System.out, "[" + time + "]"+str);
println(System.out, "[" + time + "]" + str);
} else {
println(System.out, "[" + time + "]"+str);
println(System.out, "[" + time + "]" + str);
}
}
}
@ -179,7 +162,7 @@ public class Utils {
}
}
}
private String getTimeString() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
@ -809,29 +792,29 @@ public class Utils {
}
public static <T> ObjectArrayList<T> newArrayList(T o) {
ObjectArrayList<T> t = new ObjectArrayList<T>();
final ObjectArrayList<T> t = new ObjectArrayList<>();
t.add(o);
return t;
}
public static Path getResource(String string) throws IOException, URISyntaxException {
URL res = Main.instance.getClass().getResource(string);
boolean isResource = res != null;
final URL res = Main.instance.getClass().getResource(string);
final boolean isResource = res != null;
if (isResource) {
try {
final URI uri = res.toURI();
if (res.getProtocol().equalsIgnoreCase("jar")) {
try {
FileSystems.newFileSystem(uri, Collections.emptyMap());
} catch (FileSystemAlreadyExistsException e) {
FileSystems.getFileSystem(uri);
}
Path myFolderPath = Paths.get(uri);
} catch (final FileSystemAlreadyExistsException e) {
FileSystems.getFileSystem(uri);
}
final Path myFolderPath = Paths.get(uri);
return myFolderPath;
} else {
return Paths.get(uri);
}
} catch (java.lang.IllegalArgumentException e) {
} catch (final java.lang.IllegalArgumentException e) {
throw e;
}
} else {
@ -842,81 +825,81 @@ public class Utils {
public static InputStream getResourceStreamSafe(String string) throws IOException, URISyntaxException {
try {
return getResourceStream(string);
} catch (Exception ex) {
} catch (final Exception ex) {
return null;
}
}
public static InputStream getResourceStream(String string) throws IOException, URISyntaxException {
URL res = Main.instance.getClass().getResource(string);
boolean isResource = res != null;
final URL res = Main.instance.getClass().getResource(string);
final boolean isResource = res != null;
if (isResource) {
try {
final URI uri = res.toURI();
if (res.getProtocol().equalsIgnoreCase("jar")) {
try {
FileSystems.newFileSystem(uri, Collections.emptyMap());
} catch (FileSystemAlreadyExistsException e) {
FileSystems.getFileSystem(uri);
}
Path myFolderPath = Paths.get(uri);
} catch (final FileSystemAlreadyExistsException e) {
FileSystems.getFileSystem(uri);
}
final Path myFolderPath = Paths.get(uri);
return Files.newInputStream(myFolderPath);
} else {
return Files.newInputStream(Paths.get(uri));
}
} catch (java.lang.IllegalArgumentException e) {
} catch (final java.lang.IllegalArgumentException e) {
throw e;
}
} else {
return Files.newInputStream(Paths.get(string.substring(1)));
}
}
public static String read(InputStream input) throws IOException {
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
return buffer.lines().collect(Collectors.joining("\n"));
}
}
public static void zip(String targetPath, String destinationFilePath, String password) {
try {
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
if(password.length()>0){
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword(password);
}
public static String read(InputStream input) throws IOException {
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
return buffer.lines().collect(Collectors.joining("\n"));
}
}
ZipFile zipFile = new ZipFile(destinationFilePath);
public static void zip(String targetPath, String destinationFilePath, String password) {
try {
final ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
File targetFile = new File(targetPath);
if(targetFile.isFile()){
zipFile.addFile(targetFile, parameters);
}else if(targetFile.isDirectory()){
zipFile.addFolder(targetFile, parameters);
}
if (password.length() > 0) {
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword(password);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void unzip(String targetZipFilePath, String destinationFolderPath, String password) {
try {
ZipFile zipFile = new ZipFile(targetZipFilePath);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(destinationFolderPath);
final ZipFile zipFile = new ZipFile(destinationFilePath);
} catch (Exception e) {
e.printStackTrace();
}
}
final File targetFile = new File(targetPath);
if (targetFile.isFile()) {
zipFile.addFile(targetFile, parameters);
} else if (targetFile.isDirectory()) {
zipFile.addFolder(targetFile, parameters);
}
} catch (final Exception e) {
e.printStackTrace();
}
}
public static void unzip(String targetZipFilePath, String destinationFolderPath, String password) {
try {
final ZipFile zipFile = new ZipFile(targetZipFilePath);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(destinationFolderPath);
} catch (final Exception e) {
e.printStackTrace();
}
}
public static Path getJarDirectory() {
return Paths.get("").toAbsolutePath();

View File

@ -24,7 +24,7 @@ public class CacheFile {
} while (Files.exists(Paths.get(path)));
try {
Files.createTempFile(StaticVars.calculatorNameLOWER, "");
} catch (IOException e) {
} catch (final IOException e) {
e.printStackTrace();
}
}
@ -33,7 +33,7 @@ public class CacheFile {
if (lastOOS == null) {
try {
return new ObjectOutputStream(new FileOutputStream(path));
} catch (IOException e) {
} catch (final IOException e) {
e.printStackTrace();
return lastOOS;
}
@ -46,7 +46,7 @@ public class CacheFile {
if (lastOIS == null) {
try {
return new ObjectInputStream(new FileInputStream(path));
} catch (IOException e) {
} catch (final IOException e) {
return lastOIS;
}
} else {
@ -72,7 +72,7 @@ public class CacheFile {
lastFIS.close();
lastFIS = null;
}
} catch (IOException e) {
} catch (final IOException e) {
e.printStackTrace();
}
}
@ -81,7 +81,7 @@ public class CacheFile {
closeStreams();
try {
Files.deleteIfExists(Paths.get(path));
} catch (IOException e) {
} catch (final IOException e) {
e.printStackTrace();
}
}

View File

@ -1,12 +1,5 @@
package org.warp.picalculator.device;
public enum Key {
POWEROFF, debug_DEG, debug_RAD, debug_GRA, SHIFT, ALPHA, NONE, HISTORY_BACK,
HISTORY_FORWARD, SURD_MODE, DRG_CYCLE, LETTER_X, LETTER_Y, LETTER_Z, STEP,
SIMPLIFY, BRIGHTNESS_CYCLE, BRIGHTNESS_CYCLE_REVERSE, DOT, NUM0, NUM1, NUM2,
NUM3, NUM4, NUM5, NUM6, NUM7, NUM8, NUM9, PARENTHESIS_OPEN, PARENTHESIS_CLOSE,
PLUS, MINUS, PLUS_MINUS, MULTIPLY, DIVIDE, EQUAL, DELETE, RESET, LEFT, RIGHT,
UP, DOWN, OK, debug1, debug2, debug3, debug4, debug5, SQRT, ROOT, POWER_OF_2,
POWER_OF_x, SINE, COSINE, TANGENT, ARCSINE, ARCCOSINE, ARCTANGENT, PI, SETTINGS,
F1, F2, F3, F4, BACK, ZOOM_MODE, LOGARITHM, EULER_NUMBER
POWEROFF, debug_DEG, debug_RAD, debug_GRA, SHIFT, ALPHA, NONE, HISTORY_BACK, HISTORY_FORWARD, SURD_MODE, DRG_CYCLE, LETTER_X, LETTER_Y, LETTER_Z, STEP, SIMPLIFY, BRIGHTNESS_CYCLE, BRIGHTNESS_CYCLE_REVERSE, DOT, NUM0, NUM1, NUM2, NUM3, NUM4, NUM5, NUM6, NUM7, NUM8, NUM9, PARENTHESIS_OPEN, PARENTHESIS_CLOSE, PLUS, MINUS, PLUS_MINUS, MULTIPLY, DIVIDE, EQUAL, DELETE, RESET, LEFT, RIGHT, UP, DOWN, OK, debug1, debug2, debug3, debug4, debug5, SQRT, ROOT, POWER_OF_2, POWER_OF_x, SINE, COSINE, TANGENT, ARCSINE, ARCCOSINE, ARCTANGENT, PI, SETTINGS, F1, F2, F3, F4, BACK, ZOOM_MODE, LOGARITHM, EULER_NUMBER
}

View File

@ -523,89 +523,80 @@ public class Keyboard {
}
static final Key[][][] keyMap = /* [ROW, COLUMN, (0:normal 1:shift 2:alpha)] */
{
{ /* ROW 0 */
{Key.SHIFT, Key.SHIFT, Key.SHIFT}, /* 0,0 */
{Key.ALPHA, Key.ALPHA, Key.ALPHA}, /* 0,1 */
{Key.NONE, Key.NONE, Key.NONE}, /* 0,2 */
{Key.NONE, Key.NONE, Key.NONE}, /* 0,3 */
{Key.NONE, Key.NONE, Key.NONE}, /* 0,4 */
{Key.SETTINGS, Key.NONE, Key.NONE}, /* 0,5 */
{Key.BRIGHTNESS_CYCLE, Key.BRIGHTNESS_CYCLE_REVERSE, Key.ZOOM_MODE}, /* 0,6 */
{Key.SIMPLIFY, Key.STEP, Key.NONE} /* 0,7 */
},
{ /* ROW 1 */
{Key.F4, Key.F4, Key.F4}, /* 1,0 */
{Key.NONE, Key.NONE, Key.NONE}, /* 1,1 */
{Key.LEFT, Key.NONE, Key.NONE}, /* 1,2 */
{Key.OK, Key.NONE, Key.NONE}, /* 1,3 */
{Key.RIGHT, Key.NONE, Key.NONE}, /* 1,4 */
{Key.HISTORY_BACK, Key.NONE, Key.NONE}, /* 1,5 */
{Key.HISTORY_FORWARD, Key.NONE, Key.NONE}, /* 1,6 */
{Key.NONE, Key.PI, Key.DRG_CYCLE} /* 1,7 */
},
{ /* ROW 2 */
{Key.F3, Key.F4, Key.F4}, /* 2,0 */
{Key.SQRT, Key.ROOT, Key.NONE}, /* 2,1 */
{Key.NONE, Key.NONE, Key.NONE}, /* 2,2 */
{Key.DOWN, Key.NONE, Key.NONE}, /* 2,3 */
{Key.BACK, Key.NONE, Key.NONE}, /* 2,4 */
{Key.HISTORY_BACK, Key.NONE, Key.NONE}, /* 2,5 */
{Key.HISTORY_FORWARD, Key.NONE, Key.NONE}, /* 2,6 */
{Key.NONE, Key.NONE, Key.LETTER_Z} /* 2,7 */
},
{ /* ROW 3 */
{Key.F2, Key.F2, Key.F2}, /* 3,0 */
{Key.NONE, Key.NONE, Key.NONE}, /* 3,1 */
{Key.POWER_OF_x, Key.NONE, Key.NONE}, /* 3,2 */
{Key.POWER_OF_2, Key.NONE, Key.NONE}, /* 3,3 */
{Key.NONE, Key.NONE, Key.NONE}, /* 3,4 */
{Key.NONE, Key.NONE, Key.NONE}, /* 3,5 */
{Key.NONE, Key.NONE, Key.NONE}, /* 3,6 */
{Key.DOT, Key.NONE, Key.LETTER_Y} /* 3,7 */
},
{ /* ROW 4 */
{Key.F1, Key.F1, Key.F1}, /* 4,0 */
{Key.NONE, Key.NONE, Key.NONE}, /* 4,1 */
{Key.PARENTHESIS_OPEN, Key.NONE, Key.NONE}, /* 4,2 */
{Key.PARENTHESIS_CLOSE, Key.NONE, Key.NONE}, /* 4,3 */
{Key.NONE, Key.NONE, Key.NONE}, /* 4,4 */
{Key.SURD_MODE, Key.NONE, Key.NONE}, /* 4,5 */
{Key.NONE, Key.NONE, Key.NONE}, /* 4,6 */
{Key.NUM0, Key.NONE, Key.LETTER_X} /* 4,7 */
},
{ /* ROW 5 */
{Key.NUM7, Key.NONE, Key.NONE}, /* 5,0 */
{Key.NUM8, Key.NONE, Key.NONE}, /* 5,1 */
{Key.NUM9, Key.NONE, Key.NONE}, /* 5,2 */
{Key.DELETE, Key.NONE, Key.NONE}, /* 5,3 */
{Key.RESET, Key.NONE, Key.NONE}, /* 5,4 */
{Key.NONE, Key.NONE, Key.NONE}, /* 5,5 */
{Key.NONE, Key.NONE, Key.NONE}, /* 5,6 */
{Key.NONE, Key.NONE, Key.NONE} /* 5,7 */
},
{ /* ROW 6 */
{Key.NUM4, Key.NONE, Key.NONE}, /* 6,0 */
{Key.NUM5, Key.NONE, Key.NONE}, /* 6,1 */
{Key.NUM6, Key.NONE, Key.NONE}, /* 6,2 */
{Key.MULTIPLY, Key.NONE, Key.NONE}, /* 6,3 */
{Key.DIVIDE, Key.NONE, Key.NONE}, /* 6,4 */
{Key.NONE, Key.NONE, Key.NONE}, /* 6,5 */
{Key.NONE, Key.NONE, Key.NONE}, /* 6,6 */
{Key.NONE, Key.NONE, Key.NONE} /* 6,7 */
},
{ /* ROW 7 */
{Key.NUM1, Key.NONE, Key.NONE}, /* 7,0 */
{Key.NUM2, Key.NONE, Key.NONE}, /* 7,1 */
{Key.NUM3, Key.NONE, Key.NONE}, /* 7,2 */
{Key.PLUS, Key.PLUS_MINUS, Key.NONE}, /* 7,3 */
{Key.MINUS, Key.NONE, Key.NONE}, /* 7,4 */
{Key.NONE, Key.NONE, Key.NONE}, /* 7,5 */
{Key.NONE, Key.NONE, Key.NONE}, /* 7,6 */
{Key.NONE, Key.NONE, Key.NONE} /* 7,7 */
}
};
{ { /* ROW 0 */
{ Key.SHIFT, Key.SHIFT, Key.SHIFT }, /* 0,0 */
{ Key.ALPHA, Key.ALPHA, Key.ALPHA }, /* 0,1 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 0,2 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 0,3 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 0,4 */
{ Key.SETTINGS, Key.NONE, Key.NONE }, /* 0,5 */
{ Key.BRIGHTNESS_CYCLE, Key.BRIGHTNESS_CYCLE_REVERSE, Key.ZOOM_MODE }, /* 0,6 */
{ Key.SIMPLIFY, Key.STEP, Key.NONE } /* 0,7 */
}, { /* ROW 1 */
{ Key.F4, Key.F4, Key.F4 }, /* 1,0 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 1,1 */
{ Key.LEFT, Key.NONE, Key.NONE }, /* 1,2 */
{ Key.OK, Key.NONE, Key.NONE }, /* 1,3 */
{ Key.RIGHT, Key.NONE, Key.NONE }, /* 1,4 */
{ Key.HISTORY_BACK, Key.NONE, Key.NONE }, /* 1,5 */
{ Key.HISTORY_FORWARD, Key.NONE, Key.NONE }, /* 1,6 */
{ Key.NONE, Key.PI, Key.DRG_CYCLE } /* 1,7 */
}, { /* ROW 2 */
{ Key.F3, Key.F4, Key.F4 }, /* 2,0 */
{ Key.SQRT, Key.ROOT, Key.NONE }, /* 2,1 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 2,2 */
{ Key.DOWN, Key.NONE, Key.NONE }, /* 2,3 */
{ Key.BACK, Key.NONE, Key.NONE }, /* 2,4 */
{ Key.HISTORY_BACK, Key.NONE, Key.NONE }, /* 2,5 */
{ Key.HISTORY_FORWARD, Key.NONE, Key.NONE }, /* 2,6 */
{ Key.NONE, Key.NONE, Key.LETTER_Z } /* 2,7 */
}, { /* ROW 3 */
{ Key.F2, Key.F2, Key.F2 }, /* 3,0 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 3,1 */
{ Key.POWER_OF_x, Key.NONE, Key.NONE }, /* 3,2 */
{ Key.POWER_OF_2, Key.NONE, Key.NONE }, /* 3,3 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 3,4 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 3,5 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 3,6 */
{ Key.DOT, Key.NONE, Key.LETTER_Y } /* 3,7 */
}, { /* ROW 4 */
{ Key.F1, Key.F1, Key.F1 }, /* 4,0 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 4,1 */
{ Key.PARENTHESIS_OPEN, Key.NONE, Key.NONE }, /* 4,2 */
{ Key.PARENTHESIS_CLOSE, Key.NONE, Key.NONE }, /* 4,3 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 4,4 */
{ Key.SURD_MODE, Key.NONE, Key.NONE }, /* 4,5 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 4,6 */
{ Key.NUM0, Key.NONE, Key.LETTER_X } /* 4,7 */
}, { /* ROW 5 */
{ Key.NUM7, Key.NONE, Key.NONE }, /* 5,0 */
{ Key.NUM8, Key.NONE, Key.NONE }, /* 5,1 */
{ Key.NUM9, Key.NONE, Key.NONE }, /* 5,2 */
{ Key.DELETE, Key.NONE, Key.NONE }, /* 5,3 */
{ Key.RESET, Key.NONE, Key.NONE }, /* 5,4 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 5,5 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 5,6 */
{ Key.NONE, Key.NONE, Key.NONE } /* 5,7 */
}, { /* ROW 6 */
{ Key.NUM4, Key.NONE, Key.NONE }, /* 6,0 */
{ Key.NUM5, Key.NONE, Key.NONE }, /* 6,1 */
{ Key.NUM6, Key.NONE, Key.NONE }, /* 6,2 */
{ Key.MULTIPLY, Key.NONE, Key.NONE }, /* 6,3 */
{ Key.DIVIDE, Key.NONE, Key.NONE }, /* 6,4 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 6,5 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 6,6 */
{ Key.NONE, Key.NONE, Key.NONE } /* 6,7 */
}, { /* ROW 7 */
{ Key.NUM1, Key.NONE, Key.NONE }, /* 7,0 */
{ Key.NUM2, Key.NONE, Key.NONE }, /* 7,1 */
{ Key.NUM3, Key.NONE, Key.NONE }, /* 7,2 */
{ Key.PLUS, Key.PLUS_MINUS, Key.NONE }, /* 7,3 */
{ Key.MINUS, Key.NONE, Key.NONE }, /* 7,4 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 7,5 */
{ Key.NONE, Key.NONE, Key.NONE }, /* 7,6 */
{ Key.NONE, Key.NONE, Key.NONE } /* 7,7 */
} };
static synchronized void keyPressedRaw(int row, int col) {
// KeyboardDebugScreen.keyX = row;
// KeyboardDebugScreen.keyY = col;
@ -614,7 +605,7 @@ public class Keyboard {
keyPressed(k);
} else {
if (false) {
} else {
keyPressed(Key.NONE);
}

View File

@ -1,15 +1,15 @@
package org.warp.picalculator.extra.mario;
public class MarioBlock {
private int x, y;
private byte id;
private final int x, y;
private final byte id;
public MarioBlock(int x, int y, byte b) {
this.x = x;
this.y = y;
id = b;
}
public boolean isSolid() {
return MarioBlock.isSolid(id);
}
@ -17,11 +17,11 @@ public class MarioBlock {
public byte getID() {
return id;
}
public int getX() {
return x;
}
public int getY() {
return y;
}

View File

@ -10,13 +10,13 @@ public class MarioEntity {
public boolean collisionLeft;
public boolean collisionRight;
public boolean subjectToGravity;
public MarioEntity(double x, double y, double forceX, double forceY, boolean onGround, boolean subjectToGravity) {
this.x = x;
this.y = y;
this.forceX = forceX;
this.forceY = forceY;
this.collisionDown = onGround;
collisionDown = onGround;
this.subjectToGravity = subjectToGravity;
}
@ -28,55 +28,55 @@ public class MarioEntity {
public void setPosition(double x, double y, boolean onGround) {
this.x = x;
this.y = y;
this.collisionDown = onGround;
collisionDown = onGround;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public boolean isOnGround() {
return collisionDown;
}
public void setOnGround(boolean onGround) {
this.collisionDown = onGround;
collisionDown = onGround;
}
public void gameTick(double dt) {
this.x = computeFutureDX(dt);
this.y = computeFutureDY(dt);
this.forceX = computeFutureForceDX(dt);
this.forceY = computeFutureForceDY(dt);
x = computeFutureDX(dt);
y = computeFutureDY(dt);
forceX = computeFutureForceDX(dt);
forceY = computeFutureForceDY(dt);
}
public double computeFutureDX(double dt) {
return (x + dt * forceX) - this.x;
return (x + dt * forceX) - x;
}
public double computeFutureDY(double dt) {
double forceY = this.forceY;
final double forceY = this.forceY;
double y = this.y;
if (!collisionDown) {
y += dt * forceY;
}
return y - this.y;
}
public double computeFutureForceDX(double dt) {
double forceX = this.forceX;
forceX *= 0.75;
return forceX - this.forceX;
}
public double computeFutureForceDY(double dt) {
double forceY = this.forceY;
if (subjectToGravity && !this.collisionDown) {
forceY -= dt * 1569.6/16f;
if (subjectToGravity && !collisionDown) {
forceY -= dt * 1569.6 / 16f;
} else {
forceY *= 0.75;
}

File diff suppressed because one or more lines are too long

View File

@ -2,13 +2,13 @@ package org.warp.picalculator.extra.mario;
public class MarioWorld {
private int[] spawnPoint;
private int width;
private int height;
private byte[][] data;
private MarioEvent[] events;
private MarioEntity[] entities;
private final int[] spawnPoint;
private final int width;
private final int height;
private final byte[][] data;
private final MarioEvent[] events;
private final MarioEntity[] entities;
/**
* @param width
* @param height
@ -26,10 +26,14 @@ public class MarioWorld {
}
public byte getBlockIdAt(int x, int y) {
int idy = (height - 1 - y);
if (idy < 0 || idy >= data.length) return 0b0;
int idx = x;
if (idx < 0 || idx >= data[0].length) return 0b0;
final int idy = (height - 1 - y);
if (idy < 0 || idy >= data.length) {
return 0b0;
}
final int idx = x;
if (idx < 0 || idx >= data[0].length) {
return 0b0;
}
return data[idy][idx];
}
@ -46,7 +50,7 @@ public class MarioWorld {
}
public void reset() {
}
public double getSpawnPointX() {

View File

@ -1,8 +1,8 @@
package org.warp.picalculator.extra.mario;
public class PlayerEntity extends MarioEntity {
private int life;
private final int life;
public float walkAnimation = 0;
public float jumptime = 0;
public boolean walking = false;
@ -12,19 +12,19 @@ public class PlayerEntity extends MarioEntity {
public int[] marioSkinPos = new int[] { 0, 0 };
private double controllerDX;
private double controllerDY;
public PlayerEntity(double x, double y, int life) {
super(x, y, 0, 0, true, true);
this.life = life;
}
@Override
public void gameTick(double dt) {
walkAnimation += dt;
this.x += computeFutureDX(dt);
this.y += computeFutureDY(dt);
this.forceX += computeFutureForceDX(dt);
this.forceY += computeFutureForceDY(dt);
x += computeFutureDX(dt);
y += computeFutureDY(dt);
forceX += computeFutureForceDX(dt);
forceY += computeFutureForceDY(dt);
if (controllerDX == 0) {
walking = false;
walkAnimation = 0;
@ -47,8 +47,7 @@ public class PlayerEntity extends MarioEntity {
if (jumptime <= 0.5f && !jumping && collisionDown) {
jumping = true;
collisionDown = false;
} else if (jumptime <= 0.5f) {
} else {
} else if (jumptime <= 0.5f) {} else {
jumping = false;
}
} else {
@ -81,34 +80,36 @@ public class PlayerEntity extends MarioEntity {
marioSkinPos[1] = 1;
}
}
@Override
public double computeFutureDX(double dt) {
return super.computeFutureDX(dt);
}
public double computeFuturedDY(double dt) {
return super.computeFutureDY(dt);
}
@Override
public double computeFutureForceDX(double dt) {
double forceX = this.forceX;
if (controllerDX == 0) {
} else {
if (controllerDX == 0) {} else {
if (controllerDX > 0) { //RIGHT
if (forceX < 500f/16f) {
forceX += dt * 500f/16f;
if (forceX < 500f / 16f) {
forceX += dt * 500f / 16f;
}
}
if (controllerDX < 0) { //LEFT
if (forceX > -500f/16f) {
forceX -= dt * 500f/16f;
if (forceX > -500f / 16f) {
forceX -= dt * 500f / 16f;
}
}
}
return (forceX + super.computeFutureForceDX(dt)) - this.forceX;
}
@Override
public double computeFutureForceDY(double dt) {
float jumptime = this.jumptime;
double forceY = this.forceY;
@ -118,9 +119,9 @@ public class PlayerEntity extends MarioEntity {
}
jumptime += dt;
if (jumptime <= 0.5f && !jumping && collisionDown) {
forceY = dt * (4 * 1569.6f)/16f;
forceY = dt * (4 * 1569.6f) / 16f;
} else if (jumptime <= 0.5f) {
forceY = dt * (4 * 1569.6f)/16f;
forceY = dt * (4 * 1569.6f) / 16f;
}
}
return (forceY + super.computeFutureForceDY(dt)) - this.forceY;
@ -128,9 +129,9 @@ public class PlayerEntity extends MarioEntity {
public void move(float dt, double dX, double dY) {
walkAnimation += dt;
this.controllerDX = dX;
this.controllerDY = dY;
controllerDX = dX;
controllerDY = dY;
}
}

View File

@ -12,37 +12,37 @@ public class CalculatorHUD extends HUD {
@Override
public void created() throws InterruptedException {
// TODO Auto-generated method stub
}
@Override
public void initialized() throws InterruptedException {
// TODO Auto-generated method stub
}
@Override
public void render() {
// TODO Auto-generated method stub
}
@Override
public void renderTopmostBackground() {
Renderer renderer = d.renderer;
GraphicEngine engine = d.engine;
Skin guiSkin = d.guiSkin;
final Renderer renderer = d.renderer;
final GraphicEngine engine = d.engine;
final Skin guiSkin = d.guiSkin;
renderer.glColor(0xFFc5c2af);
renderer.glFillColor(0, 0, engine.getWidth(), 20);
}
@Override
public void renderTopmost() {
Renderer renderer = d.renderer;
GraphicEngine engine = d.engine;
Skin guiSkin = d.guiSkin;
final Renderer renderer = d.renderer;
final GraphicEngine engine = d.engine;
final Skin guiSkin = d.guiSkin;
//DRAW TOP
renderer.glColor3i(0, 0, 0);
renderer.glDrawLine(0, 20, engine.getWidth() - 1, 20);
@ -107,10 +107,9 @@ public class CalculatorHUD extends HUD {
}
padding += 18;
//DRAW BOTTOM
this.d.renderer.glDrawStringLeft(2, 90, this.d.displayDebugString);
d.renderer.glDrawStringLeft(2, 90, d.displayDebugString);
Utils.getFont(true, false).use(DisplayManager.INSTANCE.engine);
DisplayManager.INSTANCE.renderer.glColor4i(255, 0, 0, 40);
@ -126,13 +125,13 @@ public class CalculatorHUD extends HUD {
@Override
public void beforeRender(float dt) {
// TODO Auto-generated method stub
}
@Override
public void renderBackground() {
// TODO Auto-generated method stub
}
}

View File

@ -41,7 +41,7 @@ public final class DisplayManager implements RenderingLoop {
public final int[] glyphsHeight;
private Screen screen;
private HUD hud;
private final HUD hud;
public Semaphore screenChange = new Semaphore(0);
public String displayDebugString;
public ObjectArrayList<GUIErrorMessage> errorMessages;
@ -50,31 +50,33 @@ public final class DisplayManager implements RenderingLoop {
INSTANCE = this;
engine = chooseGraphicEngine();
supportsPauses = engine.doesRefreshPauses();
this.monitor = monitor;
this.hud = hud;
monitor.initialize();
glyphsHeight = new int[] { 9, 6, 12, 9 };
displayDebugString = "";
errorMessages = new ObjectArrayList<>();
try {
hud.d = this;
hud.create();
if (!hud.initialized) hud.initialize();
if (!hud.initialized) {
hud.initialize();
}
} catch (final Exception e) {
e.printStackTrace();
System.exit(0);
}
setScreen(screen);
try {
engine.create();
renderer = engine.getRenderer();
engine.setTitle(title);
loop();
} catch (Exception ex) {
} catch (final Exception ex) {
ex.printStackTrace();
}
monitor.shutdown();
@ -154,7 +156,7 @@ public final class DisplayManager implements RenderingLoop {
if (screen.initialized == false) {
if (screen.canBeInHistory) {
if (DisplayManager.INSTANCE.currentSession > 0) {
int sl = DisplayManager.INSTANCE.sessions.length + 5; //TODO: I don't know why if i don't add +5 or more some items disappear
final int sl = DisplayManager.INSTANCE.sessions.length + 5; //TODO: I don't know why if i don't add +5 or more some items disappear
DisplayManager.INSTANCE.sessions = Arrays.copyOfRange(DisplayManager.INSTANCE.sessions, DisplayManager.INSTANCE.currentSession, sl);
}
DisplayManager.INSTANCE.currentSession = 0;
@ -293,8 +295,8 @@ public final class DisplayManager implements RenderingLoop {
private void draw_init() {
if (engine.supportsFontRegistering()) {
List<BinaryFont> fontsIterator = engine.getRegisteredFonts();
for (BinaryFont f : fontsIterator) {
final List<BinaryFont> fontsIterator = engine.getRegisteredFonts();
for (final BinaryFont f : fontsIterator) {
if (!f.isInitialized()) {
f.initialize(engine);
}
@ -307,7 +309,7 @@ public final class DisplayManager implements RenderingLoop {
renderer.glColor3i(255, 255, 255);
if (error != null) {
BinaryFont fnt = Utils.getFont(false, false);
final BinaryFont fnt = Utils.getFont(false, false);
if (fnt != null && fnt != engine.getRenderer().getCurrentFont()) {
fnt.use(engine);
}

View File

@ -2,9 +2,14 @@ package org.warp.picalculator.gui;
public interface GraphicalInterface {
public void create() throws InterruptedException;
public void initialize() throws InterruptedException;
public void render();
public void renderTopmost();
public void beforeRender(float dt);
public boolean mustBeRefreshed();
}

View File

@ -22,18 +22,18 @@ public abstract class HUD implements GraphicalInterface {
created();
}
}
public abstract void created() throws InterruptedException;
public abstract void initialized() throws InterruptedException;
public abstract void renderBackground();
@Override
public abstract void render();
public abstract void renderTopmostBackground();
@Override
public abstract void renderTopmost();
@ -44,5 +44,5 @@ public abstract class HUD implements GraphicalInterface {
public boolean mustBeRefreshed() {
return true;
}
}

View File

@ -2,6 +2,8 @@ package org.warp.picalculator.gui;
public interface HardwareDisplay {
public void initialize();
public void shutdown();
public void setBrightness(double value);
}

View File

@ -5,8 +5,8 @@ public class Caret {
private int pos;
private int remaining;
private CaretState state;
private int[] lastSize;
private int[] lastLocation;
private final int[] lastSize;
private final int[] lastLocation;
public Caret(CaretState state, int pos) {
this(state, pos, new int[] { 0, 0 }, new int[] { 2, 5 });

View File

@ -30,8 +30,8 @@ public abstract class ExtraMenu<T extends Block> implements Serializable, Keyboa
public abstract void close();
public boolean beforeRender(float delta, Caret caret) {
int[] l = caret.getLastLocation();
int[] cs = caret.getLastSize();
final int[] l = caret.getLastLocation();
final int[] cs = caret.getLastSize();
location[0] = l[0] - block.getWidth() / 2 - width / 2;
location[1] = l[1] + cs[1];
return false;

View File

@ -11,9 +11,9 @@ public class InputContext {
public BlockVariable variableTypeDirtyID = null;
public InputContext() {
this.variableTypes = new HashMap<>();
this.variableTypes.put(MathematicalSymbols.PI, V_TYPE.CONSTANT);
this.variableTypes.put(MathematicalSymbols.EULER_NUMBER, V_TYPE.CONSTANT);
variableTypes = new HashMap<>();
variableTypes.put(MathematicalSymbols.PI, V_TYPE.CONSTANT);
variableTypes.put(MathematicalSymbols.EULER_NUMBER, V_TYPE.CONSTANT);
}
public InputContext(HashMap<Character, V_TYPE> variableTypes) {

View File

@ -72,7 +72,7 @@ public class BlockContainer implements GraphicalElement {
addBlockUnsafe(position, b);
recomputeDimensions();
}
public void addBlockUnsafe(int position, Block b) {
if (b.isSmall() != small) {
b.setSmall(small);
@ -111,7 +111,7 @@ public class BlockContainer implements GraphicalElement {
}
public BlockReference<?> getBlockAt(int i) {
Block b = content.get(i);
final Block b = content.get(i);
return new BlockReference<>(b, i, this);
}
@ -336,11 +336,11 @@ public class BlockContainer implements GraphicalElement {
public void setSmall(boolean small) {
this.small = small;
if (this.autoMinimums) {
this.minWidth = BlockContainer.getDefaultCharWidth(small);
this.minHeight = BlockContainer.getDefaultCharHeight(small);
if (autoMinimums) {
minWidth = BlockContainer.getDefaultCharWidth(small);
minHeight = BlockContainer.getDefaultCharHeight(small);
}
for (Block b : this.content) {
for (final Block b : content) {
b.setSmall(small);
}
recomputeDimensions();
@ -365,13 +365,14 @@ public class BlockContainer implements GraphicalElement {
}
public Function toFunction(MathContext context) throws Error {
ObjectArrayList<Block> blocks = getContent();
final ObjectArrayList<Block> blocks = getContent();
final ObjectArrayList<Feature> blockFeatures = new ObjectArrayList<>();
for (final Block block : blocks) {
final Feature blockFeature = block.toFeature(context);
if (blockFeature == null)
if (blockFeature == null) {
throw new Error(Errors.NOT_IMPLEMENTED, "The block " + block.getClass().getSimpleName() + " isn't a known Block");
}
blockFeatures.add(blockFeature);
}

View File

@ -21,6 +21,6 @@ public class BlockExponentialNotation extends BlockPower {
super.recomputeDimensions();
bw = (int) (BlockContainer.getDefaultCharWidth(small) * 1.5);
bh = BlockContainer.getDefaultCharHeight(small);
this.width += bw;
width += bw;
}
}

View File

@ -58,7 +58,7 @@ public class BlockLogarithm extends Block {
r.glDrawCharLeft(x + width - chw, y + toph, '╮');
r.glDrawCharLeft(x + width - chw, y + toph + nmbh - chh, '╯');
r.glColor(BlockContainer.getDefaultColor());
containerBase.draw(ge, r, x + prw, y + line + chh/2 - bl, caret);
containerBase.draw(ge, r, x + prw, y + line + chh / 2 - bl, caret);
r.glColor(BlockContainer.getDefaultColor());
containerNumber.draw(ge, r, x + bw + prw + chw, y + toph, caret);
}
@ -111,7 +111,7 @@ public class BlockLogarithm extends Block {
schh = BlockContainer.getDefaultCharHeight(true);
width = prw + bw + chw + containerNumber.getWidth() + chw + 3;
nmbh = containerNumber.getHeight();
int nl = containerNumber.getLine();
final int nl = containerNumber.getLine();
if (bl > nmbh) {
toph = bl - nmbh;
line = toph + nl;

View File

@ -27,13 +27,13 @@ public abstract class BlockParenthesisAbstract extends Block {
public BlockParenthesisAbstract() {
containerNumber = new BlockContainer(false);
this.prefix = null;
prefix = null;
recomputeDimensions();
}
public BlockParenthesisAbstract(ObjectArrayList<Block> blocks) {
containerNumber = new BlockContainer(false, blocks);
this.prefix = null;
prefix = null;
recomputeDimensions();
}

View File

@ -4,13 +4,13 @@ public class BlockReference<T extends Block> {
private final T block;
private final BlockContainer container;
private final int blockPosition;
public BlockReference(T block, int blockPosition, BlockContainer container) {
this.block = block;
this.blockPosition = blockPosition;
this.container = container;
}
public T get() {
return block;
}
@ -22,19 +22,19 @@ public class BlockReference<T extends Block> {
public int getIndex() {
return blockPosition;
}
public BlockReference<?> getNextBlock() {
return getBlockAtSafe(this.blockPosition + 1);
}
public boolean hasNextBlock() {
return isInsideBounds(this.blockPosition + 1);
}
public BlockReference<?> getPreviousBlock() {
return getBlockAtSafe(this.blockPosition - 1);
}
public boolean hasPreviousBlock() {
return isInsideBounds(this.blockPosition - 1);
}
@ -45,10 +45,9 @@ public class BlockReference<T extends Block> {
}
return null;
}
private boolean isInsideBounds(int i) {
return i < container.getSize() && i >= 0;
}
}

View File

@ -16,7 +16,7 @@ import org.warp.picalculator.math.parser.features.interfaces.Feature;
public class BlockVariable extends Block {
private InputContext ic;
private final InputContext ic;
private final char ch;
private final VariableMenu menu;
private V_TYPE type;
@ -32,11 +32,11 @@ public class BlockVariable extends Block {
public BlockVariable(InputContext ic, char ch, boolean typeLocked) {
this.ic = ic;
this.ch = ch;
this.type = V_TYPE.VARIABLE;
this.color = 0xFF304ffe;
this.typeDirtyID = this;
type = V_TYPE.VARIABLE;
color = 0xFF304ffe;
typeDirtyID = this;
this.typeLocked = typeLocked;
this.menu = typeLocked ? null : new VariableMenu(this);
menu = typeLocked ? null : new VariableMenu(this);
retrieveValue();
recomputeDimensions();
}
@ -205,7 +205,7 @@ public class BlockVariable extends Block {
if (mustRefreshMenu) {
mustRefreshMenu = false;
text = block.type.toString();
BinaryFont f = BlockContainer.getDefaultFont(true);
final BinaryFont f = BlockContainer.getDefaultFont(true);
width = 7 + f.getStringWidth(text) + 7;
height = 2 + f.getCharacterHeight() + 2;
@ -227,7 +227,7 @@ public class BlockVariable extends Block {
if (popupY < 0) {
popupY = 0;
}
int[] screenSize = ge.getSize();
final int[] screenSize = ge.getSize();
if (popupX + width >= screenSize[0]) {
popupX = screenSize[0] - width - 1;
}

View File

@ -96,7 +96,7 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S
public BlockReference<?> getSelectedBlock() {
caret.resetRemaining();
BlockReference<?> selectedBlock = root.getBlock(caret);
final BlockReference<?> selectedBlock = root.getBlock(caret);
return selectedBlock;
}
@ -230,7 +230,7 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S
public void toggleExtra() {
if (extra == null) {
BlockReference<?> selectedBlock = getSelectedBlock();
final BlockReference<?> selectedBlock = getSelectedBlock();
if (selectedBlock != null) {
extra = selectedBlock.get().getExtraMenu();
extra.open();

View File

@ -79,7 +79,7 @@ public class NormalInputContainer extends InputContainer {
case MathematicalSymbols.EULER_NUMBER:
return new BlockVariable(inputContext, c, true);
default:
for (char v : MathematicalSymbols.variables) {
for (final char v : MathematicalSymbols.variables) {
if (c == v) {
return new BlockVariable(inputContext, c);
}
@ -93,18 +93,20 @@ public class NormalInputContainer extends InputContainer {
super.typeChar(c);
switch (c) {
case MathematicalSymbols.PARENTHESIS_CLOSE:
this.moveRight();
moveRight();
case MathematicalSymbols.DIVISION:
@SuppressWarnings("unchecked")
BlockReference<BlockDivision> ref = (BlockReference<BlockDivision>) this.getSelectedBlock();
BlockContainer parentContainer = ref.getContainer();
@SuppressWarnings("unchecked") final
BlockReference<BlockDivision> ref = (BlockReference<BlockDivision>) getSelectedBlock();
final BlockContainer parentContainer = ref.getContainer();
BlockReference<?> currentBlock = ref;
boolean groupedBefore = false;
int before = 0;
while (true) {
currentBlock = currentBlock.getPreviousBlock();
if (currentBlock == null) break;
Block b = currentBlock.get();
if (currentBlock == null) {
break;
}
final Block b = currentBlock.get();
if (b instanceof BlockNumericChar || b instanceof BlockVariable) {
if (!groupedBefore) {
groupedBefore = true;
@ -115,21 +117,21 @@ public class NormalInputContainer extends InputContainer {
}
}
if (groupedBefore) {
this.moveLeft();
moveLeft();
for (int i = 0; i < before; i++) {
BlockReference<?> b = this.getSelectedBlock();
this.del();
this.moveRight();
this.typeBlock(b.get());
this.moveLeft();
this.moveLeft();
final BlockReference<?> b = getSelectedBlock();
del();
moveRight();
typeBlock(b.get());
moveLeft();
moveLeft();
}
for (int i = 0; i < before + 1; i++) {
this.moveRight();
moveRight();
}
this.moveRight();// Move to the divisor
moveRight();// Move to the divisor
}
}
}
}

View File

@ -35,8 +35,8 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
public void setContentAsSingleGroup(ObjectArrayList<Block> blocks) {
roots.clear();
BlockContainer bcnt = new BlockContainer();
for (Block block : blocks) {
final BlockContainer bcnt = new BlockContainer();
for (final Block block : blocks) {
bcnt.appendBlockUnsafe(block);
}
roots.add(bcnt);
@ -45,9 +45,9 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
public void setContentAsMultipleGroups(ObjectArrayList<ObjectArrayList<Block>> roots) {
this.roots.clear();
for (ObjectArrayList<Block> blocks : roots) {
BlockContainer bcnt = new BlockContainer();
for (Block block : blocks) {
for (final ObjectArrayList<Block> blocks : roots) {
final BlockContainer bcnt = new BlockContainer();
for (final Block block : blocks) {
bcnt.appendBlockUnsafe(block);
}
this.roots.add(bcnt);
@ -56,18 +56,18 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
}
public void setContentAsMultipleElements(ObjectArrayList<Block> elems) {
this.roots.clear();
for (Block block : elems) {
BlockContainer bcnt = new BlockContainer();
roots.clear();
for (final Block block : elems) {
final BlockContainer bcnt = new BlockContainer();
bcnt.appendBlockUnsafe(block);
this.roots.add(bcnt);
roots.add(bcnt);
}
recomputeDimensions();
}
@Override
public void recomputeDimensions() {
for (BlockContainer root : roots) {
for (final BlockContainer root : roots) {
root.recomputeDimensions();
}
}
@ -75,10 +75,11 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
@Override
public int getWidth() {
int maxw = 0;
for (BlockContainer root : roots) {
int w = root.getWidth();
if (w > maxw)
for (final BlockContainer root : roots) {
final int w = root.getWidth();
if (w > maxw) {
maxw = w;
}
}
return maxw;
}
@ -86,7 +87,7 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
@Override
public int getHeight() {
int h = 0;
for (BlockContainer root : roots) {
for (final BlockContainer root : roots) {
h += root.getHeight() + 2;
}
if (h > 0) {
@ -123,7 +124,7 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
*/
public void draw(GraphicEngine ge, Renderer r, int x, int y) {
int offset = 0;
for (BlockContainer root : roots) {
for (final BlockContainer root : roots) {
root.draw(ge, r, x, y + offset, caret);
offset += root.getHeight() + 2;
}
@ -136,8 +137,8 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
}
public boolean isContentEmpty() {
for (BlockContainer root : roots) {
ObjectArrayList<Block> cnt = root.getContent();
for (final BlockContainer root : roots) {
final ObjectArrayList<Block> cnt = root.getContent();
if (cnt != null && !cnt.isEmpty()) {
return false;
}

View File

@ -36,7 +36,7 @@ public interface GraphicEngine {
public Renderer getRenderer();
public BinaryFont loadFont(String fontName) throws IOException;
public BinaryFont loadFont(String path, String fontName) throws IOException;
public Skin loadSkin(String file) throws IOException;

View File

@ -11,8 +11,8 @@ public interface Skin {
public boolean isInitialized();
public void use(GraphicEngine d);
public int getSkinWidth();
public int getSkinHeight();
}

View File

@ -55,16 +55,21 @@ public class CPUEngine implements GraphicEngine {
setDisplayMode(StaticVars.screenSize[0], StaticVars.screenSize[1]);
INSTANCE.setVisible(true);
initialized = true;
if (onInitialized != null)
if (onInitialized != null) {
onInitialized.run();
}
}
@Override
public boolean wasResized() {
if (INSTANCE.wasResized) {
r.size = new int[] { INSTANCE.getWidth(), INSTANCE.getHeight() };
if (r.size[0] <= 0) r.size[0] = 1;
if (r.size[1] <= 0) r.size[1] = 1;
if (r.size[0] <= 0) {
r.size[0] = 1;
}
if (r.size[1] <= 0) {
r.size[1] = 1;
}
CPURenderer.canvas2d = new int[r.size[0] * r.size[1]];
g = new BufferedImage(r.size[0], r.size[1], BufferedImage.TYPE_INT_ARGB);
INSTANCE.wasResized = false;
@ -180,13 +185,14 @@ public class CPUEngine implements GraphicEngine {
public void waitForExit() {
try {
exitSemaphore.acquire();
} catch (InterruptedException e) {}
} catch (final InterruptedException e) {}
}
@Override
public boolean isSupported() {
if (Utils.forceEngine != null && Utils.forceEngine != "cpu")
if (Utils.forceEngine != null && Utils.forceEngine != "cpu") {
return false;
}
return (Utils.headlessOverride || GraphicsEnvironment.isHeadless()) == false;
}

View File

@ -38,11 +38,11 @@ public class CPUFont implements BinaryFont {
isResource = true;
load("/font_" + fontName + ".rft", onlyRaw);
}
public CPUFont(String path, String fontName) throws IOException {
this(path, fontName, false);
}
CPUFont(String path, String fontName, boolean onlyRaw) throws IOException {
isResource = false;
load(path + "/font_" + fontName + ".rft", onlyRaw);
@ -60,7 +60,7 @@ public class CPUFont implements BinaryFont {
public void load(String path) throws IOException {
load(path, false);
}
private void load(String path, boolean onlyRaw) throws IOException {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_MIN, "Loading font " + path);
loadFont(path);
@ -167,38 +167,38 @@ public class CPUFont implements BinaryFont {
}
private void findIntervals() {
final LinkedList<int[]> intervals = new LinkedList<int[]>();
final LinkedList<int[]> intervals = new LinkedList<>();
int beginIndex = -1;
int endIndex = 0;
int intervalSize = 0;
int holeSize = 0;
final int holeSize = 0;
for (int i = 0; i < rawchars.length; i++) {
if (rawchars[i] != null) {
beginIndex = i;
int firstNull = 0;
while(i+firstNull < rawchars.length && rawchars[i+firstNull] != null) {
while (i + firstNull < rawchars.length && rawchars[i + firstNull] != null) {
firstNull++;
}
endIndex = beginIndex + firstNull - 1;
i = endIndex;
if (endIndex >= 0) {
intervalSize = endIndex - beginIndex + 1;
intervals.add(new int[] {beginIndex, endIndex, intervalSize});
intervals.add(new int[] { beginIndex, endIndex, intervalSize });
intervalsTotalSize += intervalSize;
}
beginIndex = -1;
}
}
int lastIndex = 0;
boolean[][] newrawchars = new boolean[intervalsTotalSize][];
for (int[] interval: intervals) {
final boolean[][] newrawchars = new boolean[intervalsTotalSize][];
for (final int[] interval : intervals) {
if (rawchars.length - (interval[0]) - interval[2] < 0) {
System.err.println(interval[0] + "-" + interval[1] + "(" + interval[2] + ")");
System.err.println(rawchars.length - (interval[0]) - interval[2]);
throw new ArrayIndexOutOfBoundsException();
}
if (newrawchars.length - (lastIndex-1) - interval[2] < 0) {
System.err.println(newrawchars.length - (lastIndex-1) - interval[2]);
if (newrawchars.length - (lastIndex - 1) - interval[2] < 0) {
System.err.println(newrawchars.length - (lastIndex - 1) - interval[2]);
throw new ArrayIndexOutOfBoundsException();
}
System.arraycopy(rawchars, interval[0], newrawchars, lastIndex, interval[2]);
@ -208,7 +208,7 @@ public class CPUFont implements BinaryFont {
final int intervalsSize = intervals.size();
this.intervals = new int[intervalsSize * 3];
for (int i = 0; i < intervalsSize; i++) {
int[] interval = intervals.get(i);
final int[] interval = intervals.get(i);
this.intervals[i * 3 + 0] = interval[0];
this.intervals[i * 3 + 1] = interval[1];
this.intervals[i * 3 + 2] = interval[2];
@ -232,41 +232,41 @@ public class CPUFont implements BinaryFont {
final int[] indexes = new int[l];
final char[] chars = txt.toCharArray();
for (int i = 0; i < l; i++) {
int originalIndex = (chars[i] & 0xFFFF) - minBound;
final int originalIndex = (chars[i] & 0xFFFF) - minBound;
indexes[i] = compressIndex(originalIndex);
}
return indexes;
}
public int getCharIndex(char c) {
int originalIndex = c & 0xFFFF;
final int originalIndex = c & 0xFFFF;
return compressIndex(originalIndex);
}
private int compressIndex(int originalIndex) {
int compressedIndex = 0;
for (int i = 0; i < intervals.length; i+=3) {
for (int i = 0; i < intervals.length; i += 3) {
if (intervals[i] > originalIndex) {
break;
} else if (originalIndex <= intervals[i+1]) {
compressedIndex+=(originalIndex-intervals[i]);
} else if (originalIndex <= intervals[i + 1]) {
compressedIndex += (originalIndex - intervals[i]);
break;
} else {
compressedIndex+=intervals[i+2];
compressedIndex += intervals[i + 2];
}
}
return compressedIndex;
}
private int decompressIndex(int compressedIndex) {
int originalIndex = 0;
final int originalIndex = 0;
int i = 0;
for (int intvl = 0; intvl < intervals.length; intvl+=3) {
i+=intervals[intvl+2];
for (int intvl = 0; intvl < intervals.length; intvl += 3) {
i += intervals[intvl + 2];
if (i == compressedIndex) {
return intervals[intvl+1];
return intervals[intvl + 1];
} else if (i > compressedIndex) {
return intervals[intvl+1] - (i - compressedIndex);
return intervals[intvl + 1] - (i - compressedIndex);
}
}
return originalIndex;

View File

@ -48,8 +48,10 @@ public class CPURenderer implements Renderer {
public void glClear(int screenWidth, int screenHeight) {
for (int x = 0; x < screenWidth; x++) {
for (int y = 0; y < screenHeight; y++) {
int index = x + y * size[0];
if (index >= 0 && index < canvas2d.length) canvas2d[index] = clearcolor;
final int index = x + y * size[0];
if (index >= 0 && index < canvas2d.length) {
canvas2d[index] = clearcolor;
}
}
}
}
@ -57,10 +59,10 @@ public class CPURenderer implements Renderer {
private void glDrawSkin(int x0, int y0, int x1, int y1, int s0, int t0, int s1, int t1, boolean transparent) {
x0 += StaticVars.screenPos[0];
y0 += StaticVars.screenPos[1];
double incrementX = Math.abs((double)(x1-x0)/(double)(s1-s0));
double incrementY = Math.abs((double)(y1-y0)/(double)(t1-t0));
boolean flippedX = (x1-x0)/(s1-s0) < 0;
boolean flippedY = (y1-y0)/(t1-t0) < 0;
final double incrementX = Math.abs((double) (x1 - x0) / (double) (s1 - s0));
final double incrementY = Math.abs((double) (y1 - y0) / (double) (t1 - t0));
final boolean flippedX = (x1 - x0) / (s1 - s0) < 0;
final boolean flippedY = (y1 - y0) / (t1 - t0) < 0;
int oldColor;
int newColor;
final int onex = s0 <= s1 ? 1 : -1;
@ -106,25 +108,25 @@ public class CPURenderer implements Renderer {
}
y0 = 0;
}
for (double pixelX = 0; pixelX < x1-x0; pixelX++) {
for (double pixelY = 0; pixelY < y1-y0; pixelY++) {
final int index = (int) (x0+pixelX + (y0+pixelY) * size[0]);
for (double pixelX = 0; pixelX < x1 - x0; pixelX++) {
for (double pixelY = 0; pixelY < y1 - y0; pixelY++) {
final int index = (int) (x0 + pixelX + (y0 + pixelY) * size[0]);
if (index >= 0 && index < canvas2d.length && pixelX < size[0]) {
int texx = (int) (pixelX / incrementX);
int texy = (int) (pixelY / incrementY);
final int texx = (int) (pixelX / incrementX);
final int texy = (int) (pixelY / incrementY);
int expX = 0;
int expY = 0;
if (incrementX < 1) {
expX = (int) Math.round(1d/incrementX/2d);
expX = (int) Math.round(1d / incrementX / 2d);
}
if (incrementY < 1) {
expY = (int) Math.round(1d/incrementY/2d);
expY = (int) Math.round(1d / incrementY / 2d);
}
int[] newColors = new int[(1+expX*2)*(1+expY*2)];
final int[] newColors = new int[(1 + expX * 2) * (1 + expY * 2)];
for (int expXi = -expX; expXi <= expX; expXi++) {
for (int expYi = -expY; expYi <= expY; expYi++) {
int skinIndex = (int) (s0 + (texx*(flippedX ? -1d : 1d)+(flippedX ? -(s0 - s1)-1 : 0)+expXi) + (t0 + (texy*(flippedY ? -1d : 1d)+(flippedY ? -(t0 - t1)-1 : 0)+expYi)) * currentSkin.skinSize[0]);
int idx = (expXi+expX)+(expYi+expY)*(1+expY*2);
final int skinIndex = (int) (s0 + (texx * (flippedX ? -1d : 1d) + (flippedX ? -(s0 - s1) - 1 : 0) + expXi) + (t0 + (texy * (flippedY ? -1d : 1d) + (flippedY ? -(t0 - t1) - 1 : 0) + expYi)) * currentSkin.skinSize[0]);
final int idx = (expXi + expX) + (expYi + expY) * (1 + expY * 2);
if (idx >= 0 && idx < newColors.length) {
newColors[idx] = getSkinColorAt(currentSkin.skinData, skinIndex);
}
@ -135,12 +137,12 @@ public class CPURenderer implements Renderer {
oldColor = canvas2d[index];
final float a2 = (newColor >> 24 & 0xFF) / 255f;
final float a1 = 1f - a2;
int r = (int) ((oldColor >> 16 & 0xFF) * a1 + (newColor >> 16 & 0xFF) * a2);
int g = (int) ((oldColor >> 8 & 0xFF) * a1 + (newColor >> 8 & 0xFF) * a2);
int b = (int) ((oldColor & 0xFF) * a1 + (newColor & 0xFF) * a2);
final int r = (int) ((oldColor >> 16 & 0xFF) * a1 + (newColor >> 16 & 0xFF) * a2);
final int g = (int) ((oldColor >> 8 & 0xFF) * a1 + (newColor >> 8 & 0xFF) * a2);
final int b = (int) ((oldColor & 0xFF) * a1 + (newColor & 0xFF) * a2);
newColor = 0xFF000000 | r << 16 | g << 8 | b;
}
canvas2d[index] = stackColors(canvas2d[index], newColor);
}
}
@ -152,14 +154,13 @@ public class CPURenderer implements Renderer {
int r = 0;
int g = 0;
int b = 0;
for (int i = 0; i < newColors.length; i++) {
int newColor = newColors[i];
for (final int newColor : newColors) {
a += newColor >> 24 & 0xFF;
r += newColor >> 16 & 0xFF;
g += newColor >> 8 & 0xFF;
b += newColor & 0xFF;
}
return (a/newColors.length) << 24 | (r/newColors.length) << 16 | (g/newColors.length) << 8 | (b/newColors.length);
return (a / newColors.length) << 24 | (r / newColors.length) << 16 | (g / newColors.length) << 8 | (b / newColors.length);
}
private int stackColors(int... color) {
@ -167,25 +168,24 @@ public class CPURenderer implements Renderer {
double r = 0;
double g = 0;
double b = 0;
for (int i = 0; i < color.length; i++) {
int newColor = color[i];
double alpha = (newColor >> 24 & 0xFF) / 255d;
a = a * (1d-alpha) + (newColor >> 24 & 0xFF) * alpha;
r = r * (1d-alpha) + (newColor >> 16 & 0xFF) * alpha;
g = g * (1d-alpha) + (newColor >> 8 & 0xFF) * alpha;
b = b * (1d-alpha) + (newColor & 0xFF) * alpha;
for (final int newColor : color) {
final double alpha = (newColor >> 24 & 0xFF) / 255d;
a = a * (1d - alpha) + (newColor >> 24 & 0xFF) * alpha;
r = r * (1d - alpha) + (newColor >> 16 & 0xFF) * alpha;
g = g * (1d - alpha) + (newColor >> 8 & 0xFF) * alpha;
b = b * (1d - alpha) + (newColor & 0xFF) * alpha;
}
return ((int)a) << 24 | ((int)r) << 16 | ((int)g) << 8 | ((int)b);
return ((int) a) << 24 | ((int) r) << 16 | ((int) g) << 8 | ((int) b);
}
private int getSkinColorAt(int[] skinData, int skinIndex) {
int newColor = 0;
if (skinIndex >= 0 && skinIndex < skinData.length) {
newColor = skinData[skinIndex];
final int a = (int) ((double)(newColor >> 24 & 0xFF) * ((double)(color >> 24 & 0xFF)/(double)0xFF));
int r = (int) ((double)(newColor >> 16 & 0xFF) * ((double)(color >> 16 & 0xFF)/(double)0xFF));
int g = (int) ((double)(newColor >> 8 & 0xFF) * ((double)(color >> 8 & 0xFF)/(double)0xFF));
int b = (int) ((double)(newColor & 0xFF) * ((double)(color & 0xFF)/(double)0xFF));
final int a = (int) ((newColor >> 24 & 0xFF) * ((double) (color >> 24 & 0xFF) / (double) 0xFF));
final int r = (int) ((newColor >> 16 & 0xFF) * ((double) (color >> 16 & 0xFF) / (double) 0xFF));
final int g = (int) ((newColor >> 8 & 0xFF) * ((double) (color >> 8 & 0xFF) / (double) 0xFF));
final int b = (int) ((newColor & 0xFF) * ((double) (color & 0xFF) / (double) 0xFF));
newColor = a << 24 | r << 16 | g << 8 | b;
}
return newColor;
@ -270,9 +270,10 @@ public class CPURenderer implements Renderer {
final int sizeW = size[0];
for (int px = x0; px < x1; px++) {
for (int py = y0; py < y1; py++) {
int idx = (px) + (py) * sizeW;
if (px < sizeW && idx >= 0 && idx < canvas2d.length)
final int idx = (px) + (py) * sizeW;
if (px < sizeW && idx >= 0 && idx < canvas2d.length) {
canvas2d[idx] = stackColors(canvas2d[idx], color);
}
}
}
}
@ -307,7 +308,7 @@ public class CPURenderer implements Renderer {
final int bit = dx + dy * currentFont.charW;
currentInt = (int) (Math.floor(bit) / (CPUFont.intBits));
currentIntBitPosition = bit - (currentInt * CPUFont.intBits);
int charIdx = charIndex * currentFont.charIntCount + currentInt;
final int charIdx = charIndex * currentFont.charIntCount + currentInt;
if (charIdx >= 0 && charIdx < currentFont.chars32.length) {
bitData = (currentFont.chars32[charIdx] >> currentIntBitPosition) & 1;
screenPos = ix + cpos + dx + (iy + dy) * screenSize[0];

View File

@ -25,7 +25,7 @@ public class CPUSkin implements Skin {
final BufferedImage img = ImageIO.read(isResource ? this.getClass().getResource("/" + file) : new File(file).toURI().toURL());
if (img == null) {
skinData = new int[0];
skinSize = new int[] {0,0};
skinSize = new int[] { 0, 0 };
} else {
skinData = getMatrixOfImage(img);
skinSize = new int[] { img.getWidth(), img.getHeight() };

View File

@ -39,7 +39,9 @@ public class SwingWindow extends JFrame {
// Transparent 16 x 16 pixel cursor image.
final BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
if (StaticVars.debugOn & StaticVars.debugWindow2x) mult = 2;
if (StaticVars.debugOn & StaticVars.debugWindow2x) {
mult = 2;
}
if (StaticVars.debugOn) {
if (Utils.debugThirdScreen) {
this.setLocation(2880, 900);
@ -100,10 +102,10 @@ public class SwingWindow extends JFrame {
@Override
public void setSize(int width, int height) {
c.setSize(new Dimension(width*mult, height*mult));
c.setPreferredSize(new Dimension(width*mult, height*mult));
super.getContentPane().setSize(new Dimension(width*mult, height*mult));
super.getContentPane().setPreferredSize(new Dimension(width*mult, height*mult));
c.setSize(new Dimension(width * mult, height * mult));
c.setPreferredSize(new Dimension(width * mult, height * mult));
super.getContentPane().setSize(new Dimension(width * mult, height * mult));
super.getContentPane().setPreferredSize(new Dimension(width * mult, height * mult));
super.pack();
}
@ -114,12 +116,12 @@ public class SwingWindow extends JFrame {
@Override
public int getWidth() {
return c.getWidth()/mult;
return c.getWidth() / mult;
}
@Override
public int getHeight() {
return c.getHeight()/mult;
return c.getHeight() / mult;
}
public void setRenderingLoop(RenderingLoop renderingLoop) {
@ -127,12 +129,12 @@ public class SwingWindow extends JFrame {
}
public void centerWindow() {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - super.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - super.getHeight()) / 2);
super.setLocation(x, y);
final Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
final int x = (int) ((dimension.getWidth() - super.getWidth()) / 2);
final int y = (int) ((dimension.getHeight() - super.getHeight()) / 2);
super.setLocation(x, y);
}
// private static ObjectArrayList<Double> mediaValori = new ObjectArrayList<Double>();
public class CustomCanvas extends JPanel {
@ -151,8 +153,8 @@ public class SwingWindow extends JFrame {
final int[] a = ((DataBufferInt) display.g.getRaster().getDataBuffer()).getData();
// System.arraycopy(canvas2d, 0, a, 0, canvas2d.length);
CPURenderer.canvas2d = a;
g.clearRect(0, 0, display.r.size[0]*mult, display.r.size[1]*mult);
g.drawImage(display.g, 0, 0, display.r.size[0]*mult, display.r.size[1]*mult, null);
g.clearRect(0, 0, display.r.size[0] * mult, display.r.size[1] * mult);
g.drawImage(display.g, 0, 0, display.r.size[0] * mult, display.r.size[1] * mult, null);
// long time2 = System.nanoTime();
// double timeDelta = ((double)(time2-time1))/1000000000d;
// double mediaAttuale = timeDelta;

View File

@ -1,11 +1,9 @@
package org.warp.picalculator.gui.graphicengine.framebuffer;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.Semaphore;
import org.warp.picalculator.MmapByteBuffer;
@ -26,8 +24,8 @@ public class FBEngine implements GraphicEngine {
private static final int FB_DISPLAY_BPP = 32;
private static final int WIDTH = 480;
private static final int HEIGHT = 320;
private static final int[] SIZE = new int[] {WIDTH, HEIGHT};
private TestJNI jni = new TestJNI();
private static final int[] SIZE = new int[] { WIDTH, HEIGHT };
private final TestJNI jni = new TestJNI();
public FBRenderer r;
private MappedByteBuffer fb;
MmapByteBuffer realFb;
@ -35,8 +33,7 @@ public class FBEngine implements GraphicEngine {
public volatile boolean initialized = false;
public Semaphore exitSemaphore = new Semaphore(0);
private boolean resizedTrigger = false;
@Override
public int[] getSize() {
return SIZE;
@ -48,16 +45,13 @@ public class FBEngine implements GraphicEngine {
}
@Override
public void setTitle(String title) {
}
public void setTitle(String title) {}
@Override
public void setResizable(boolean r) {
}
public void setResizable(boolean r) {}
@Override
public void setDisplayMode(int ww, int wh) {
}
public void setDisplayMode(int ww, int wh) {}
@Override
public void create(Runnable onInitialized) {
@ -65,12 +59,13 @@ public class FBEngine implements GraphicEngine {
realFb = jni.retrieveBuffer();
final long fbLen = realFb.getLength();
fb = (MappedByteBuffer) ByteBuffer.allocateDirect((int) fbLen);
r = new FBRenderer(this, fb);
initialized = true;
if (onInitialized != null)
if (onInitialized != null) {
onInitialized.run();
}
}
@Override
@ -97,7 +92,7 @@ public class FBEngine implements GraphicEngine {
public void destroy() {
try {
fbFileRW.close();
} catch (IOException e) {
} catch (final IOException e) {
e.printStackTrace();
}
}
@ -132,7 +127,7 @@ public class FBEngine implements GraphicEngine {
}
private int _________________TMP = 0;
@Override
public void repaint() {
if (_________________TMP % 100 == 0) {
@ -142,10 +137,10 @@ public class FBEngine implements GraphicEngine {
_________________TMP++;
realFb.getBuffer().clear();
realFb.getBuffer().put(fb);
for (int i = 0; i < fb.capacity()/2; i++) {
for (int i = 0; i < fb.capacity() / 2; i++) {
realFb.getBuffer().put(i, (byte) (_________________TMP < 50 ? 0xFF : 0xF0));
}
for (int i = fb.capacity()/2; i < fb.capacity(); i++) {
for (int i = fb.capacity() / 2; i < fb.capacity(); i++) {
realFb.getBuffer().put(i, (byte) (0x18));
}
}
@ -174,13 +169,14 @@ public class FBEngine implements GraphicEngine {
public void waitForExit() {
try {
exitSemaphore.acquire();
} catch (InterruptedException e) {}
} catch (final InterruptedException e) {}
}
@Override
public boolean isSupported() {
if (Utils.forceEngine != null && Utils.forceEngine != "fb")
if (Utils.forceEngine != null && Utils.forceEngine != "fb") {
return false;
}
if (Utils.headlessOverride) {
return false;
}
@ -203,5 +199,5 @@ public class FBEngine implements GraphicEngine {
public boolean doesRefreshPauses() {
return true;
}
}

View File

@ -7,49 +7,48 @@ import org.warp.picalculator.gui.graphicengine.Renderer;
public class FBRenderer implements Renderer {
public FBRenderer(FBEngine fbEngine, MappedByteBuffer fb) {
}
public FBRenderer(FBEngine fbEngine, MappedByteBuffer fb) {}
@Override
public void glColor3i(int r, int gg, int b) {
// TODO Auto-generated method stub
}
@Override
public void glColor(int c) {
// TODO Auto-generated method stub
}
@Override
public void glColor4i(int red, int green, int blue, int alpha) {
// TODO Auto-generated method stub
}
@Override
public void glColor3f(float red, float green, float blue) {
// TODO Auto-generated method stub
}
@Override
public void glColor4f(float red, float green, float blue, float alpha) {
// TODO Auto-generated method stub
}
@Override
public void glClearColor4i(int red, int green, int blue, int alpha) {
// TODO Auto-generated method stub
}
@Override
public void glClearColor4f(float red, float green, float blue, float alpha) {
// TODO Auto-generated method stub
}
@Override
@ -61,74 +60,74 @@ public class FBRenderer implements Renderer {
@Override
public void glClearColor(int c) {
// TODO Auto-generated method stub
}
@Override
public void glClear(int screenWidth, int screenHeight) {
// TODO Auto-generated method stub
}
@Override
public void glDrawLine(float x0, float y0, float x1, float y1) {
// TODO Auto-generated method stub
}
@Override
public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth,
float uvHeight) {
// TODO Auto-generated method stub
}
@Override
public void glFillColor(float x, float y, float width, float height) {
// TODO Auto-generated method stub
}
@Override
public void glDrawCharLeft(int x, int y, char ch) {
// TODO Auto-generated method stub
}
@Override
public void glDrawCharCenter(int x, int y, char ch) {
// TODO Auto-generated method stub
}
@Override
public void glDrawCharRight(int x, int y, char ch) {
// TODO Auto-generated method stub
}
@Override
public void glDrawStringLeft(float x, float y, String text) {
// TODO Auto-generated method stub
}
@Override
public void glDrawStringCenter(float x, float y, String text) {
// TODO Auto-generated method stub
}
@Override
public void glDrawStringRight(float x, float y, String text) {
// TODO Auto-generated method stub
}
@Override
public void glClearSkin() {
// TODO Auto-generated method stub
}
@Override

View File

@ -15,7 +15,6 @@ import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.RenderingLoop;
import org.warp.picalculator.gui.graphicengine.Skin;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.util.texture.Texture;
@ -26,10 +25,10 @@ public class GPUEngine implements GraphicEngine {
private NEWTWindow wnd;
private RenderingLoop d;
private GPURenderer r;
private Map<String, GPUFont> fontCache = new HashMap<String, GPUFont>();
private final Map<String, GPUFont> fontCache = new HashMap<>();
int[] size = new int[] { StaticVars.screenSize[0], StaticVars.screenSize[1] };
private final CopyOnWriteArrayList<BinaryFont> registeredFonts = new CopyOnWriteArrayList<BinaryFont>();
private Semaphore exitSemaphore = new Semaphore(0);
private final CopyOnWriteArrayList<BinaryFont> registeredFonts = new CopyOnWriteArrayList<>();
private final Semaphore exitSemaphore = new Semaphore(0);
protected LinkedList<Texture> registeredTextures;
protected LinkedList<Texture> unregisteredTextures;
@ -127,24 +126,24 @@ public class GPUEngine implements GraphicEngine {
@Override
public BinaryFont loadFont(String name) throws IOException {
for (Entry<String, GPUFont> entry : fontCache.entrySet()) {
for (final Entry<String, GPUFont> entry : fontCache.entrySet()) {
if (entry.getKey().equals(name)) {
return entry.getValue();
}
}
GPUFont font = new GPUFont(this, name);
final GPUFont font = new GPUFont(this, name);
fontCache.put(name, font);
return font;
}
@Override
public BinaryFont loadFont(String path, String name) throws IOException {
for (Entry<String, GPUFont> entry : fontCache.entrySet()) {
for (final Entry<String, GPUFont> entry : fontCache.entrySet()) {
if (entry.getKey().equals(name)) {
return entry.getValue();
}
}
GPUFont font = new GPUFont(this, path, name);
final GPUFont font = new GPUFont(this, path, name);
fontCache.put(name, font);
return font;
}
@ -158,22 +157,24 @@ public class GPUEngine implements GraphicEngine {
public void waitForExit() {
try {
exitSemaphore.acquire();
} catch (InterruptedException e) {}
} catch (final InterruptedException e) {}
}
@Override
public boolean isSupported() {
if (Utils.forceEngine != null && Utils.forceEngine != "gpu")
if (Utils.forceEngine != null && Utils.forceEngine != "gpu") {
return false;
if (Utils.headlessOverride)
}
if (Utils.headlessOverride) {
return false;
}
boolean available = false;
boolean errored = false;
try {
available = GLProfile.isAvailable(GLProfile.GL2ES2);
} catch (Exception ex) {
} catch (final Exception ex) {
errored = true;
System.err.println("OpenGL Error: "+ex.getMessage());
System.err.println("OpenGL Error: " + ex.getMessage());
}
if (!available && !errored) {
System.err.println(GLProfile.glAvailabilityToString());

View File

@ -4,8 +4,6 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.LinkedList;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.graphicengine.BinaryFont;
import org.warp.picalculator.gui.graphicengine.GraphicEngine;
@ -45,7 +43,7 @@ public class GPUFont implements BinaryFont {
load(path, name);
((GPUEngine) g).registerFont(this);
}
@Override
public void load(String name) throws IOException {
load(null, name);
@ -75,79 +73,79 @@ public class GPUFont implements BinaryFont {
public int[] getCharIndexes(String txt) {
final int[] indexes = new int[txt.length()];
int i = 0;
for (char c : txt.toCharArray()) {
for (final char c : txt.toCharArray()) {
indexes[i] = compressIndex((c & 0xFFFF) - minCharIndex);
i++;
}
return indexes;
}
public int getCharIndex(char c) {
int originalIndex = c & 0xFFFF;
final int originalIndex = c & 0xFFFF;
return compressIndex(originalIndex);
}
private int compressIndex(int originalIndex) {
int compressedIndex = 0;
for (int i = 0; i < intervals.length; i+=3) {
for (int i = 0; i < intervals.length; i += 3) {
if (intervals[i] > originalIndex) {
break;
} else if (originalIndex <= intervals[i+1]) {
compressedIndex+=(originalIndex-intervals[i]);
} else if (originalIndex <= intervals[i + 1]) {
compressedIndex += (originalIndex - intervals[i]);
break;
} else {
compressedIndex+=intervals[i+2];
compressedIndex += intervals[i + 2];
}
}
return compressedIndex;
}
private int decompressIndex(int compressedIndex) {
int originalIndex = 0;
final int originalIndex = 0;
int i = 0;
for (int intvl = 0; i < intervals.length; i+=3) {
i+=intervals[intvl+2];
for (final int intvl = 0; i < intervals.length; i += 3) {
i += intervals[intvl + 2];
if (i >= compressedIndex) {
return intervals[intvl+1] - (i - compressedIndex);
return intervals[intvl + 1] - (i - compressedIndex);
}
}
return originalIndex;
}
private void pregenTexture(boolean[][] chars) throws IOException {
final int totalChars = this.intervalsTotalSize;
final int totalChars = intervalsTotalSize;
int w = powerOf2((int) (Math.ceil(Math.sqrt(totalChars) * charW)));
int h = powerOf2((int) (Math.ceil(Math.sqrt(totalChars) * charH)));
int maxIndexW = (int) Math.floor(((double) w) / ((double) charW)) - 1;
int maxIndexH = (int) Math.floor(((double) h) / ((double) charH)) - 1;
if (w > h) {
System.out.println("w > h");
h = powerOf2((int) (Math.ceil((((double)totalChars)/((double)(maxIndexW))) * charH)));
h = powerOf2((int) (Math.ceil((((double) totalChars) / ((double) (maxIndexW))) * charH)));
maxIndexH = (int) Math.floor(((double) h) / ((double) charH)) - 1;
} else {
System.out.println("w <= h");
w = powerOf2((int) (Math.ceil((((double)totalChars)/((double)(maxIndexH))) * charW)));
w = powerOf2((int) (Math.ceil((((double) totalChars) / ((double) (maxIndexH))) * charW)));
maxIndexW = (int) Math.floor(((double) w) / ((double) charW)) - 1;
}
// final int h = powerOf2((int) (Math.ceil(Math.sqrt(totalChars) * charH)));
System.out.println(((int)Math.ceil(Math.sqrt(totalChars) * charW)) + " * " + ((int)Math.ceil(Math.sqrt(totalChars) * charH)) + " --> " + w + " * " + h);
File f = Files.createTempFile("texture-font-", ".png").toFile();
System.out.println(((int) Math.ceil(Math.sqrt(totalChars) * charW)) + " * " + ((int) Math.ceil(Math.sqrt(totalChars) * charH)) + " --> " + w + " * " + h);
final File f = Files.createTempFile("texture-font-", ".png").toFile();
f.deleteOnExit();
final FileOutputStream outputStream = new FileOutputStream(f);
final ImageInfo imi = new ImageInfo(w, h, 8, true); // 8 bits per channel, alpha
// open image for writing to a output stream
final PngWriter png = new PngWriter(outputStream, imi);
for (int y = 0; y < png.imgInfo.rows; y++) {
ImageLineInt iline = new ImageLineInt(imi);
int[] xValues = new int[imi.cols];
final ImageLineInt iline = new ImageLineInt(imi);
final int[] xValues = new int[imi.cols];
for (int indexX = 0; indexX <= maxIndexW; indexX++) {// this line will be written to all rows
final int charY = (y % charH);
final int indexY = (y - charY)/charH;
final int i = indexY * (maxIndexW+1) + indexX - this.minCharIndex;
final int indexY = (y - charY) / charH;
final int i = indexY * (maxIndexW + 1) + indexX - minCharIndex;
boolean[] currentChar;
if (i < totalChars && (currentChar=chars[i]) != null) {
if (i < totalChars && (currentChar = chars[i]) != null) {
for (int charX = 0; charX < charW; charX++) {
if (i >= 0 & i < totalChars && currentChar != null && currentChar[charX + charY * charW]) {
xValues[indexX * charW + charX] = 0xFFFFFFFF;
@ -165,7 +163,7 @@ public class GPUFont implements BinaryFont {
chars = null;
png.end();
Utils.gc();
try {
memoryWidth = w;
memoryHeight = h;
@ -175,7 +173,7 @@ public class GPUFont implements BinaryFont {
outputStream.flush();
outputStream.close();
Utils.gc();
this.tmpFont = f;
tmpFont = f;
} catch (GLException | IOException e) {
e.printStackTrace();
}
@ -191,7 +189,7 @@ public class GPUFont implements BinaryFont {
}
private int powerOf2(int i) {
return i >1 ? Integer.highestOneBit(i-1)<<1 : 1;
return i > 1 ? Integer.highestOneBit(i - 1) << 1 : 1;
}
@Override
@ -238,11 +236,11 @@ public class GPUFont implements BinaryFont {
@Override
public int getSkinWidth() {
return this.memoryWidth;
return memoryWidth;
}
@Override
public int getSkinHeight() {
return this.memoryHeight;
return memoryHeight;
}
}

View File

@ -6,7 +6,6 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.file.Files;
import javax.imageio.ImageIO;
@ -28,10 +27,8 @@ public class GPURenderer implements Renderer {
public static GL2ES1 gl;
private static final int ELEMENTS_MAX_COUNT_PER_BUFFER = StaticVars.enableVBO ? 128 : 1;
private static final int ELEMENT_VERTICES_COUNT = 6,
vertSize = 3, texSize = 2, colSize = 4,
vertBuffer = 0, texBuffer = 1, colBuffer = 2,
vertMax = vertSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER,
private static final int ELEMENT_VERTICES_COUNT = 6, vertSize = 3, texSize = 2, colSize = 4, vertBuffer = 0,
texBuffer = 1, colBuffer = 2, vertMax = vertSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER,
texMax = texSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER,
colMax = colSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER;
@ -256,19 +253,19 @@ public class GPURenderer implements Renderer {
} else {
f = new File(file);
}
int imgW = img.getWidth();
int imgH = img.getHeight();
final int imgW = img.getWidth();
final int imgH = img.getHeight();
img = null;
Utils.gc();
return new OpenedTextureData(imgW, imgH, f, isResource);
}
public static class OpenedTextureData {
public final int w;
public final int h;
public final File f;
public final boolean deleteOnExit;
/**
* @param w
* @param h
@ -281,16 +278,18 @@ public class GPURenderer implements Renderer {
this.f = f;
this.deleteOnExit = deleteOnExit;
}
}
static Texture importTexture(File f, boolean deleteOnExit) throws GLException, IOException {
final Texture tex = TextureIO.newTexture(f, false);
if (deleteOnExit && f.exists()) {
try {
if (StaticVars.debugOn) throw new IOException("Delete on exit!");
if (StaticVars.debugOn) {
throw new IOException("Delete on exit!");
}
f.delete();
}catch (Exception ex) {
} catch (final Exception ex) {
f.deleteOnExit();
}
}
@ -328,7 +327,7 @@ public class GPURenderer implements Renderer {
}
}
}
private void changeTexture() {
precTexEnabled = currentTexEnabled;
precTex = currentTex;
@ -340,7 +339,7 @@ public class GPURenderer implements Renderer {
}
firstBufferTexDataCall = true;
}
public void startDrawSegment(boolean continuation) {
if (!continuation || cycleEnded) {
fbElements = 0;
@ -371,52 +370,37 @@ public class GPURenderer implements Renderer {
boolean firstBufferDataCall = true;
boolean firstBufferTexDataCall = true;
public void endDrawSegment() {
fbVertices.flip();
fbTextures.flip();
fbColors.flip();
// gl.glVertexPointer(vertSize, GL.GL_FLOAT, 0, fbVertices);
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[vertBuffer]);
if (firstBufferTexDataCall) {
gl.glBufferData(
GL.GL_ARRAY_BUFFER, fbVertices.limit() * Buffers.SIZEOF_FLOAT,
fbVertices,
GL2ES1.GL_STATIC_DRAW);
gl.glBufferData(GL.GL_ARRAY_BUFFER, fbVertices.limit() * Buffers.SIZEOF_FLOAT, fbVertices, GL.GL_STATIC_DRAW);
} else {
gl.glBufferSubData(
GL.GL_ARRAY_BUFFER, 0, fbVertices.limit() * Buffers.SIZEOF_FLOAT,
fbVertices);
gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, fbVertices.limit() * Buffers.SIZEOF_FLOAT, fbVertices);
}
gl.glVertexPointer(vertSize, GL.GL_FLOAT, 0, 0l);
// gl.glTexCoordPointer(texSize, GL.GL_FLOAT, 0, fbTextures);
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[texBuffer]);
if (firstBufferTexDataCall) {
gl.glBufferData(
GL.GL_ARRAY_BUFFER, fbTextures.limit() * Buffers.SIZEOF_FLOAT,
fbTextures,
GL2ES1.GL_STATIC_DRAW);
gl.glBufferData(GL.GL_ARRAY_BUFFER, fbTextures.limit() * Buffers.SIZEOF_FLOAT, fbTextures, GL.GL_STATIC_DRAW);
} else {
gl.glBufferSubData(
GL.GL_ARRAY_BUFFER, 0, fbTextures.limit() * Buffers.SIZEOF_FLOAT,
fbTextures);
gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, fbTextures.limit() * Buffers.SIZEOF_FLOAT, fbTextures);
}
gl.glTexCoordPointer(texSize, GL.GL_FLOAT, 0, 0l);
// gl.glColorPointer(colSize, GL.GL_FLOAT, 0, fbColors);
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[colBuffer]);
if (firstBufferTexDataCall) {
gl.glBufferData(
GL.GL_ARRAY_BUFFER, fbColors.limit() * Buffers.SIZEOF_FLOAT,
fbColors,
GL2ES1.GL_STATIC_DRAW);
gl.glBufferData(GL.GL_ARRAY_BUFFER, fbColors.limit() * Buffers.SIZEOF_FLOAT, fbColors, GL.GL_STATIC_DRAW);
} else {
gl.glBufferSubData(
GL.GL_ARRAY_BUFFER, 0, fbColors.limit() * Buffers.SIZEOF_FLOAT,
fbColors);
gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, fbColors.limit() * Buffers.SIZEOF_FLOAT, fbColors);
}
gl.glColorPointer(colSize, GL.GL_FLOAT, 0, 0l);
fbVertices.limit(vertMax);
fbTextures.limit(texMax);
fbColors.limit(colMax);

View File

@ -8,7 +8,6 @@ import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Skin;
import org.warp.picalculator.gui.graphicengine.gpu.GPURenderer.OpenedTextureData;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2ES1;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.util.texture.Texture;
@ -22,14 +21,14 @@ public class GPUSkin implements Skin {
private String texturePath;
private boolean initialized = false;
private boolean isResource;
GPUSkin(GraphicEngine d, String file) throws IOException {
load(file);
}
@Override
public void load(String file) throws IOException {
boolean isResource = !Files.exists(Paths.get(file));
final boolean isResource = !Files.exists(Paths.get(file));
if (isResource && (this.getClass().getClassLoader().getResource(file)) == null) {
throw new IOException("File '" + file + "' not found!");
}
@ -45,7 +44,7 @@ public class GPUSkin implements Skin {
t = GPURenderer.importTexture(i.f, i.deleteOnExit);
w = i.w;
h = i.h;
((GPUEngine)d).registerTexture(t);
((GPUEngine) d).registerTexture(t);
initialized = true;
} catch (GLException | IOException e) {
e.printStackTrace();

View File

@ -28,10 +28,6 @@
package org.warp.picalculator.gui.graphicengine.gpu;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.warp.picalculator.StaticVars;
import org.warp.picalculator.device.Key;
import org.warp.picalculator.device.Keyboard;
@ -72,7 +68,7 @@ class NEWTWindow implements GLEventListener {
public NEWTWindow(GPUEngine disp) {
this.disp = disp;
renderer = disp.getRenderer();
realWindowSize = new int[] {1,1};
realWindowSize = new int[] { 1, 1 };
}
public GLWindow window;
@ -300,7 +296,7 @@ class NEWTWindow implements GLEventListener {
//Vsync
gl.setSwapInterval(2);
}
//Textures
gl.glEnable(GL.GL_TEXTURE_2D);
@ -341,24 +337,24 @@ class NEWTWindow implements GLEventListener {
}
private void onZoomChanged(GL2ES1 gl, boolean sizeChanged) {
float precWindowZoom = windowZoom;
final float precWindowZoom = windowZoom;
windowZoom = StaticVars.getCurrentZoomValue();
if (((precWindowZoom % ((int)precWindowZoom)) != 0f) != ((windowZoom % ((int)windowZoom)) != 0f)) {
boolean linear = (windowZoom % ((int)windowZoom)) != 0f;
if (((precWindowZoom % ((int) precWindowZoom)) != 0f) != ((windowZoom % ((int) windowZoom)) != 0f)) {
final boolean linear = (windowZoom % ((int) windowZoom)) != 0f;
for(Texture t : disp.registeredTextures) {
for (final Texture t : disp.registeredTextures) {
t.setTexParameteri(gl, GL.GL_TEXTURE_MAG_FILTER, linear ? GL.GL_LINEAR : GL.GL_NEAREST);
t.setTexParameteri(gl, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
}
}
final int width = realWindowSize[0];
final int height = realWindowSize[1];
disp.size[0] = (int) (realWindowSize[0] / windowZoom);
disp.size[1] = (int) (realWindowSize[1] / windowZoom);
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
@ -369,28 +365,28 @@ class NEWTWindow implements GLEventListener {
gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
gl.glLoadIdentity();
}
@Override
public void display(GLAutoDrawable glad) {
final GL2ES1 gl = glad.getGL().getGL2ES1();
GPURenderer.gl = gl;
if (windowZoom != StaticVars.getCurrentZoomValue()) {
onZoomChanged(gl, false);
}
Boolean linear = null;
while(!disp.unregisteredTextures.isEmpty()) {
while (!disp.unregisteredTextures.isEmpty()) {
if (linear == null) {
linear = (windowZoom % ((int)windowZoom)) != 0f;
linear = (windowZoom % ((int) windowZoom)) != 0f;
}
Texture t = disp.unregisteredTextures.pop();
final Texture t = disp.unregisteredTextures.pop();
t.setTexParameteri(gl, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
t.setTexParameteri(gl, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
disp.registeredTextures.addLast(t);
}
gl.glEnableClientState(GLPointerFunc.GL_COLOR_ARRAY);
gl.glEnableClientState(GLPointerFunc.GL_VERTEX_ARRAY);
gl.glEnableClientState(GLPointerFunc.GL_TEXTURE_COORD_ARRAY);

View File

@ -14,7 +14,7 @@ import org.warp.picalculator.gui.graphicengine.RenderingLoop;
public class Headless24bitEngine implements org.warp.picalculator.gui.graphicengine.GraphicEngine {
private Headless24bitRenderer r = new Headless24bitRenderer();
private final Headless24bitRenderer r = new Headless24bitRenderer();
private boolean stopped = true;
private RenderingLoop renderLoop;
public static final int C_MUL_X = 4;//8;
@ -67,7 +67,7 @@ public class Headless24bitEngine implements org.warp.picalculator.gui.graphiceng
if (Utils.isWindows() && !Utils.msDosMode) {
win = true;
WindowsSupport.setConsoleMode(0x0200);
Thread t = new Thread(() -> {
final Thread t = new Thread(() -> {
int ch = -1;
while (true) {
if (precKey != null) {
@ -132,8 +132,9 @@ public class Headless24bitEngine implements org.warp.picalculator.gui.graphiceng
t.start();
}
stopped = false;
if (onInitialized != null)
if (onInitialized != null) {
onInitialized.run();
}
}
@Override
@ -158,7 +159,7 @@ public class Headless24bitEngine implements org.warp.picalculator.gui.graphiceng
@Override
public void start(RenderingLoop d) {
this.renderLoop = d;
renderLoop = d;
final Thread th = new Thread(() -> {
try {
double extratime = 0;
@ -215,10 +216,10 @@ public class Headless24bitEngine implements org.warp.picalculator.gui.graphiceng
}
}
int[] newpix = new int[3];
for (int i = 0; i < pixs.length; i++) {
newpix[0] += pixs[i][0];
newpix[1] += pixs[i][1];
newpix[2] += pixs[i][2];
for (final int[] pix : pixs) {
newpix[0] += pix[0];
newpix[1] += pix[1];
newpix[2] += pix[2];
}
newpix[0] /= pixs.length;
newpix[1] /= pixs.length;
@ -233,10 +234,10 @@ public class Headless24bitEngine implements org.warp.picalculator.gui.graphiceng
}
}
newpix = new int[3];
for (int i = 0; i < pixs.length; i++) {
newpix[0] += pixs[i][0];
newpix[1] += pixs[i][1];
newpix[2] += pixs[i][2];
for (final int[] pix : pixs) {
newpix[0] += pix[0];
newpix[1] += pix[1];
newpix[2] += pix[2];
}
newpix[0] /= pixs.length;
newpix[1] /= pixs.length;
@ -318,8 +319,9 @@ public class Headless24bitEngine implements org.warp.picalculator.gui.graphiceng
@Override
public boolean isSupported() {
if (Utils.msDosMode || (Utils.forceEngine != null && Utils.forceEngine != "console-24bit"))
if (Utils.msDosMode || (Utils.forceEngine != null && Utils.forceEngine != "console-24bit")) {
return false;
}
return true;
}

View File

@ -82,11 +82,11 @@ public class Headless24bitRenderer implements Renderer {
@Override
public void glDrawLine(float x1, float y1, float x2, float y2) {
int dx = (int) Math.abs(x2 - x1);
int dy = (int) Math.abs(y2 - y1);
final int dx = (int) Math.abs(x2 - x1);
final int dy = (int) Math.abs(y2 - y1);
int sx = (x1 < x2) ? 1 : -1;
int sy = (y1 < y2) ? 1 : -1;
final int sx = (x1 < x2) ? 1 : -1;
final int sy = (y1 < y2) ? 1 : -1;
int err = dx - dy;
@ -101,7 +101,7 @@ public class Headless24bitRenderer implements Renderer {
break;
}
int e2 = 2 * err;
final int e2 = 2 * err;
if (e2 > -dy) {
err = err - dy;
@ -185,7 +185,7 @@ public class Headless24bitRenderer implements Renderer {
final int cx = (int) x;
final int cy = (int) y;
int i = 0;
for (char c : text.toCharArray()) {
for (final char c : text.toCharArray()) {
if (cx + i >= size[0] || cy >= size[1]) {
break;
}
@ -200,7 +200,7 @@ public class Headless24bitRenderer implements Renderer {
final int cx = ((int) x) - (text.length() / 2) * Headless24bitEngine.C_MUL_X;
final int cy = ((int) y);
int i = 0;
for (char c : text.toCharArray()) {
for (final char c : text.toCharArray()) {
if (cx + i >= size[0] || cy >= size[1]) {
break;
}

View File

@ -31,12 +31,12 @@ public class Headless24bitSkin implements Skin {
final int[][] pixels = new int[width * height][];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int rgb = bufferedImage.getRGB(i, j);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
boolean transparent = ((rgb >> 24) & 0xFF) <= 128;
int[] curCol = Headless24bitRenderer.rgbToIntArray(r, g, b);
final int rgb = bufferedImage.getRGB(i, j);
final int r = (rgb >> 16) & 0xFF;
final int g = (rgb >> 8) & 0xFF;
final int b = rgb & 0xFF;
final boolean transparent = ((rgb >> 24) & 0xFF) <= 128;
final int[] curCol = Headless24bitRenderer.rgbToIntArray(r, g, b);
pixels[i + j * width] = new int[] { curCol[0], curCol[1], curCol[2], transparent ? 1 : 0 };
}
}

View File

@ -15,7 +15,7 @@ import org.warp.picalculator.gui.graphicengine.headless24bit.Headless24bitRender
public class Headless256Engine implements org.warp.picalculator.gui.graphicengine.GraphicEngine {
private Headless256Renderer r = new Headless256Renderer();
private final Headless256Renderer r = new Headless256Renderer();
private boolean stopped = true;
private RenderingLoop renderLoop;
public static final int C_MUL_X = 4;//8;
@ -66,7 +66,7 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
if (Utils.isWindows() && !Utils.msDosMode) {
win = true;
WindowsSupport.setConsoleMode(0x0200);
Thread t = new Thread(() -> {
final Thread t = new Thread(() -> {
int ch = -1;
while (true) {
if (precKey != null) {
@ -131,8 +131,9 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
t.start();
}
stopped = false;
if (onInitialized != null)
if (onInitialized != null) {
onInitialized.run();
}
}
@Override
@ -157,7 +158,7 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
@Override
public void start(RenderingLoop d) {
this.renderLoop = d;
renderLoop = d;
final Thread th = new Thread(() -> {
try {
double extratime = 0;
@ -207,7 +208,7 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
curBgColor = r.bgColorMatrix[x + y * C_WIDTH];
curFgColor = r.fgColorMatrix[x + y * C_WIDTH];
if (precBgColor != curBgColor) {
String str = Headless256Renderer.ANSI_PREFIX + Headless256Renderer.ansiBgColorPrefix + curBgColor + Headless256Renderer.ansiColorSuffix;
final String str = Headless256Renderer.ANSI_PREFIX + Headless256Renderer.ansiBgColorPrefix + curBgColor + Headless256Renderer.ansiColorSuffix;
if (win) {
WindowsSupport.writeConsole(str);
} else {
@ -215,7 +216,7 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
}
}
if (precFgColor != curFgColor) {
String str = Headless256Renderer.ANSI_PREFIX + Headless256Renderer.ansiFgColorPrefix + curFgColor + Headless256Renderer.ansiColorSuffix;
final String str = Headless256Renderer.ANSI_PREFIX + Headless256Renderer.ansiFgColorPrefix + curFgColor + Headless256Renderer.ansiColorSuffix;
if (win) {
WindowsSupport.writeConsole(str);
} else {
@ -223,7 +224,7 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
}
}
String stri = r.charmatrix[x + y * C_WIDTH] + "";
final String stri = r.charmatrix[x + y * C_WIDTH] + "";
if (win) {
WindowsSupport.writeConsole(stri);
} else {
@ -275,8 +276,9 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
@Override
public boolean isSupported() {
if (Utils.msDosMode || (Utils.forceEngine != null && Utils.forceEngine != "console-256"))
if (Utils.msDosMode || (Utils.forceEngine != null && Utils.forceEngine != "console-256")) {
return false;
}
return true;
}

View File

@ -41,20 +41,20 @@ public class Headless256Renderer implements Renderer {
public static int rgbToX256(int r_U, int g_U, int b_U) {
// Calculate the nearest 0-based color index at 16 .. 231
int ir = v2ci(r_U), ig = v2ci(g_U), ib = v2ci(b_U); // 0..5 each
final int ir = v2ci(r_U), ig = v2ci(g_U), ib = v2ci(b_U); // 0..5 each
/* 0..215, lazy evaluation */
// Calculate the nearest 0-based gray index at 232 .. 255
int average = (r_U + g_U + b_U) / 3;
int grayIndex = average > 238 ? 23 : (average - 3) / 10; // 0..23
final int average = (r_U + g_U + b_U) / 3;
final int grayIndex = average > 238 ? 23 : (average - 3) / 10; // 0..23
int cr = i2cv[ir], cg = i2cv[ig], cb = i2cv[ib]; // r/g/b, 0..255 each
int gv = 8 + 10 * grayIndex; // same value for r/g/b, 0..255
final int cr = i2cv[ir], cg = i2cv[ig], cb = i2cv[ib]; // r/g/b, 0..255 each
final int gv = 8 + 10 * grayIndex; // same value for r/g/b, 0..255
// Return the one which is nearer to the original input rgb value
int colorErr = distSquare(cr, cg, cb, r_U, g_U, b_U);
int grayErr = distSquare(gv, gv, gv, r_U, g_U, b_U);
final int colorErr = distSquare(cr, cg, cb, r_U, g_U, b_U);
final int grayErr = distSquare(gv, gv, gv, r_U, g_U, b_U);
return colorErr <= grayErr ? 16 + colorIndex(ir, ig, ib) : 232 + grayIndex;
}
@ -115,11 +115,11 @@ public class Headless256Renderer implements Renderer {
y1 /= Headless256Engine.C_MUL_Y;
y2 /= Headless256Engine.C_MUL_Y;
int dx = (int) Math.abs(x2 - x1);
int dy = (int) Math.abs(y2 - y1);
final int dx = (int) Math.abs(x2 - x1);
final int dy = (int) Math.abs(y2 - y1);
int sx = (x1 < x2) ? 1 : -1;
int sy = (y1 < y2) ? 1 : -1;
final int sx = (x1 < x2) ? 1 : -1;
final int sy = (y1 < y2) ? 1 : -1;
int err = dx - dy;
@ -134,7 +134,7 @@ public class Headless256Renderer implements Renderer {
break;
}
int e2 = 2 * err;
final int e2 = 2 * err;
if (e2 > -dy) {
err = err - dy;
@ -217,7 +217,7 @@ public class Headless256Renderer implements Renderer {
final int cx = ((int) x) / Headless256Engine.C_MUL_X;
final int cy = ((int) y) / Headless256Engine.C_MUL_Y;
int i = 0;
for (char c : text.toCharArray()) {
for (final char c : text.toCharArray()) {
if (cx + i >= Headless256Engine.C_WIDTH || cy >= Headless256Engine.C_HEIGHT) {
break;
}
@ -232,7 +232,7 @@ public class Headless256Renderer implements Renderer {
final int cx = ((int) x) / Headless256Engine.C_MUL_X - text.length() / 2;
final int cy = ((int) y) / Headless256Engine.C_MUL_Y;
int i = 0;
for (char c : text.toCharArray()) {
for (final char c : text.toCharArray()) {
if (cx + i >= Headless256Engine.C_WIDTH || cy >= Headless256Engine.C_HEIGHT) {
break;
}

View File

@ -28,9 +28,9 @@ public class Headless256Skin implements Skin {
public static int[] getMatrixOfImage(BufferedImage bufferedImage) {
BufferedImage after = new BufferedImage(bufferedImage.getWidth(null), bufferedImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
final AffineTransform at = new AffineTransform();
at.scale(1f / (Headless256Engine.C_MUL_X), 1f / (Headless256Engine.C_MUL_Y));
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
final AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(bufferedImage, after);
final int width = after.getWidth(null);
@ -38,11 +38,11 @@ public class Headless256Skin implements Skin {
final int[] pixels = new int[width * height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int rgb = after.getRGB(i, j);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
boolean transparent = ((rgb >> 24) & 0xFF) <= 128;
final int rgb = after.getRGB(i, j);
final int r = (rgb >> 16) & 0xFF;
final int g = (rgb >> 8) & 0xFF;
final int b = rgb & 0xFF;
final boolean transparent = ((rgb >> 24) & 0xFF) <= 128;
pixels[i + j * width] = Headless256Renderer.rgbToX256(r, g, b) | (transparent ? Headless256Renderer.TRANSPARENT : 0);
}
}

View File

@ -15,7 +15,7 @@ import org.warp.picalculator.gui.graphicengine.headless24bit.Headless24bitRender
public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.GraphicEngine {
private Headless8Renderer r = new Headless8Renderer();
private final Headless8Renderer r = new Headless8Renderer();
private boolean stopped = true;
private RenderingLoop renderLoop;
public static final int C_MUL_X = 4;//8;
@ -66,7 +66,7 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
if (Utils.isWindows() && !Utils.msDosMode) {
win = true;
WindowsSupport.setConsoleMode(0x0200);
Thread t = new Thread(() -> {
final Thread t = new Thread(() -> {
int ch = -1;
while (true) {
if (precKey != null) {
@ -131,8 +131,9 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
t.start();
}
stopped = false;
if (onInitialized != null)
if (onInitialized != null) {
onInitialized.run();
}
}
@Override
@ -157,7 +158,7 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
@Override
public void start(RenderingLoop d) {
this.renderLoop = d;
renderLoop = d;
final Thread th = new Thread(() -> {
try {
double extratime = 0;
@ -207,7 +208,7 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
curBgColor = (r.colorMatrix[x + y * C_WIDTH] & 0xF0) >> 4;
curFgColor = r.colorMatrix[x + y * C_WIDTH] & 0x0F;
if (precBgColor != curBgColor) {
String str = Headless8Renderer.ANSI_PREFIX + Headless8Renderer.ansiBgColorPrefix + Headless8Renderer.colorANSI[curBgColor] + Headless8Renderer.ansiColorSuffix;
final String str = Headless8Renderer.ANSI_PREFIX + Headless8Renderer.ansiBgColorPrefix + Headless8Renderer.colorANSI[curBgColor] + Headless8Renderer.ansiColorSuffix;
if (win) {
WindowsSupport.writeConsole(str);
} else {
@ -215,7 +216,7 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
}
}
if (precFgColor != curFgColor) {
String str = Headless8Renderer.ANSI_PREFIX + Headless8Renderer.ansiFgColorPrefix + Headless8Renderer.colorANSI[curFgColor] + Headless8Renderer.ansiColorSuffix;
final String str = Headless8Renderer.ANSI_PREFIX + Headless8Renderer.ansiFgColorPrefix + Headless8Renderer.colorANSI[curFgColor] + Headless8Renderer.ansiColorSuffix;
if (win) {
WindowsSupport.writeConsole(str);
} else {
@ -223,7 +224,7 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
}
}
String stri = r.charmatrix[x + y * C_WIDTH] + "";
final String stri = r.charmatrix[x + y * C_WIDTH] + "";
if (win) {
WindowsSupport.writeConsole(stri);
} else {
@ -275,8 +276,9 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
@Override
public boolean isSupported() {
if (Utils.forceEngine != null && Utils.forceEngine != "console-8")
if (Utils.forceEngine != null && Utils.forceEngine != "console-8") {
return false;
}
return true;
}

View File

@ -22,9 +22,14 @@ public class Headless8Renderer implements Renderer {
public static final char FILL = Utils.msDosMode ? 0xDB : '█';
private int hexColor(int red, int green, int blue) {
int r1 = red, r2, g1 = green, g2, b1 = blue, b2;
final int r1 = red;
int r2;
final int g1 = green;
int g2;
final int b1 = blue;
int b2;
float[] match = new float[16];
final float[] match = new float[16];
// COLOR
r2 = 0;
@ -124,7 +129,7 @@ public class Headless8Renderer implements Renderer {
int minIndex = 0;
for (int i = 1; i < match.length; i++) {
float newnumber = match[i];
final float newnumber = match[i];
if ((newnumber < match[minIndex])) {
minIndex = i;
}
@ -231,11 +236,11 @@ public class Headless8Renderer implements Renderer {
y1 /= Headless8Engine.C_MUL_Y;
y2 /= Headless8Engine.C_MUL_Y;
int dx = (int) Math.abs(x2 - x1);
int dy = (int) Math.abs(y2 - y1);
final int dx = (int) Math.abs(x2 - x1);
final int dy = (int) Math.abs(y2 - y1);
int sx = (x1 < x2) ? 1 : -1;
int sy = (y1 < y2) ? 1 : -1;
final int sx = (x1 < x2) ? 1 : -1;
final int sy = (y1 < y2) ? 1 : -1;
int err = dx - dy;
@ -243,7 +248,7 @@ public class Headless8Renderer implements Renderer {
if (((int) x1) >= Headless8Engine.C_WIDTH || ((int) y1) >= Headless8Engine.C_HEIGHT || ((int) x2) >= Headless8Engine.C_WIDTH || ((int) y2) >= Headless8Engine.C_HEIGHT) {
break;
}
int precBG = colorMatrix[((int) x1) + ((int) y1) * Headless8Engine.C_WIDTH] & 0xF0;
final int precBG = colorMatrix[((int) x1) + ((int) y1) * Headless8Engine.C_WIDTH] & 0xF0;
colorMatrix[((int) x1) + ((int) y1) * Headless8Engine.C_WIDTH] = precBG | curColor;
charmatrix[((int) x1) + ((int) y1) * Headless8Engine.C_WIDTH] = FILL;
@ -251,7 +256,7 @@ public class Headless8Renderer implements Renderer {
break;
}
int e2 = 2 * err;
final int e2 = 2 * err;
if (e2 > -dy) {
err = err - dy;
@ -300,7 +305,7 @@ public class Headless8Renderer implements Renderer {
final int sizeW = Headless8Engine.C_WIDTH;
for (int px = ix; px < x1; px++) {
for (int py = iy; py < y1; py++) {
int precBG = colorMatrix[(px) + (py) * sizeW] & 0xF0;
final int precBG = colorMatrix[(px) + (py) * sizeW] & 0xF0;
colorMatrix[(px) + (py) * sizeW] = precBG | color;
charmatrix[(px) + (py) * sizeW] = character;
}
@ -315,7 +320,7 @@ public class Headless8Renderer implements Renderer {
return;
}
charmatrix[cx + cy * Headless8Engine.C_WIDTH] = ch;
int precBG = colorMatrix[cx + cy * Headless8Engine.C_WIDTH] & 0xF0;
final int precBG = colorMatrix[cx + cy * Headless8Engine.C_WIDTH] & 0xF0;
colorMatrix[cx + cy * Headless8Engine.C_WIDTH] = precBG | curColor;
}
@ -332,7 +337,7 @@ public class Headless8Renderer implements Renderer {
return;
}
charmatrix[cx + cy * Headless8Engine.C_WIDTH] = ch;
int precBG = colorMatrix[cx + cy * Headless8Engine.C_WIDTH] & 0xF0;
final int precBG = colorMatrix[cx + cy * Headless8Engine.C_WIDTH] & 0xF0;
colorMatrix[cx + cy * Headless8Engine.C_WIDTH] = precBG | curColor;
}
@ -341,12 +346,12 @@ public class Headless8Renderer implements Renderer {
final int cx = ((int) x) / Headless8Engine.C_MUL_X;
final int cy = ((int) y) / Headless8Engine.C_MUL_Y;
int i = 0;
for (char c : text.toCharArray()) {
for (final char c : text.toCharArray()) {
if (cx + i >= Headless8Engine.C_WIDTH || cy >= Headless8Engine.C_HEIGHT) {
break;
}
charmatrix[cx + i + cy * Headless8Engine.C_WIDTH] = c;
int precBG = colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] & 0xF0;
final int precBG = colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] & 0xF0;
colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] = precBG | curColor;
i++;
}
@ -357,12 +362,12 @@ public class Headless8Renderer implements Renderer {
final int cx = ((int) x) / Headless8Engine.C_MUL_X - text.length() / 2;
final int cy = ((int) y) / Headless8Engine.C_MUL_Y;
int i = 0;
for (char c : text.toCharArray()) {
for (final char c : text.toCharArray()) {
if (cx + i >= Headless8Engine.C_WIDTH || cy >= Headless8Engine.C_HEIGHT) {
break;
}
charmatrix[cx + i + cy * Headless8Engine.C_WIDTH] = c;
int precBG = colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] & 0xF0;
final int precBG = colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] & 0xF0;
colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] = precBG | curColor;
i++;
}
@ -438,7 +443,7 @@ public class Headless8Renderer implements Renderer {
final int b = (int) ((oldColor & 0xFF) * a1 + (newColor & 0xFF) * a2);
newColor = 0xFF000000 | r << 16 | g << 8 | b;
}
int bgColor = colorMatrix[pixelX + pixelY * Headless8Engine.C_WIDTH] & 0xF0;
final int bgColor = colorMatrix[pixelX + pixelY * Headless8Engine.C_WIDTH] & 0xF0;
colorMatrix[pixelX + pixelY * Headless8Engine.C_WIDTH] = bgColor | hexColor(newColor >> 16 & 0xFF, newColor >> 8 & 0xFF, newColor & 0xFF);
charmatrix[pixelX + pixelY * Headless8Engine.C_WIDTH] = FILL;
}

View File

@ -28,9 +28,9 @@ public class Headless8Skin implements Skin {
public static int[] getMatrixOfImage(BufferedImage bufferedImage) {
BufferedImage after = new BufferedImage(bufferedImage.getWidth(null), bufferedImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
final AffineTransform at = new AffineTransform();
at.scale(1f / (Headless8Engine.C_MUL_X), 1f / (Headless8Engine.C_MUL_Y));
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
final AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(bufferedImage, after);
final int width = after.getWidth(null);

View File

@ -17,7 +17,7 @@ public class NoGuiEngine implements GraphicEngine {
@Override
public int[] getSize() {
return new int[] {2, 2};
return new int[] { 2, 2 };
}
@Override
@ -26,23 +26,20 @@ public class NoGuiEngine implements GraphicEngine {
}
@Override
public void setTitle(String title) {
}
public void setTitle(String title) {}
@Override
public void setResizable(boolean r) {
}
public void setResizable(boolean r) {}
@Override
public void setDisplayMode(int ww, int wh) {
}
public void setDisplayMode(int ww, int wh) {}
@Override
public void create(Runnable onInitialized) {
initialized = true;
if (onInitialized != null)
if (onInitialized != null) {
onInitialized.run();
}
}
@Override
@ -67,12 +64,10 @@ public class NoGuiEngine implements GraphicEngine {
}
@Override
public void start(RenderingLoop d) {
}
public void start(RenderingLoop d) {}
@Override
public void repaint() {
}
public void repaint() {}
@Override
public Renderer getRenderer() {
@ -81,83 +76,65 @@ public class NoGuiEngine implements GraphicEngine {
public int glGetClearColor() {
return 0;
}
@Override
public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth,
float uvHeight) {
}
float uvHeight) {}
@Override
public void glFillColor(float x, float y, float width, float height) {
}
public void glFillColor(float x, float y, float width, float height) {}
@Override
public void glDrawStringRight(float x, float y, String text) {
}
public void glDrawStringRight(float x, float y, String text) {}
@Override
public void glDrawStringLeft(float x, float y, String text) {
}
public void glDrawStringLeft(float x, float y, String text) {}
@Override
public void glDrawStringCenter(float x, float y, String text) {
}
public void glDrawStringCenter(float x, float y, String text) {}
@Override
public void glDrawLine(float x0, float y0, float x1, float y1) {
}
public void glDrawLine(float x0, float y0, float x1, float y1) {}
@Override
public void glDrawCharRight(int x, int y, char ch) {
}
public void glDrawCharRight(int x, int y, char ch) {}
@Override
public void glDrawCharLeft(int x, int y, char ch) {
}
public void glDrawCharLeft(int x, int y, char ch) {}
@Override
public void glDrawCharCenter(int x, int y, char ch) {
}
public void glDrawCharCenter(int x, int y, char ch) {}
@Override
public void glColor4i(int red, int green, int blue, int alpha) {
}
public void glColor4i(int red, int green, int blue, int alpha) {}
@Override
public void glColor4f(float red, float green, float blue, float alpha) {
}
public void glColor4f(float red, float green, float blue, float alpha) {}
@Override
public void glColor3i(int r, int gg, int b) {
}
public void glColor3i(int r, int gg, int b) {}
@Override
public void glColor3f(float red, float green, float blue) {
}
public void glColor3f(float red, float green, float blue) {}
@Override
public void glColor(int c) {
}
public void glColor(int c) {}
@Override
public void glClearSkin() {
}
public void glClearSkin() {}
@Override
public void glClearColor4i(int red, int green, int blue, int alpha) {
}
public void glClearColor4i(int red, int green, int blue, int alpha) {}
@Override
public void glClearColor4f(float red, float green, float blue, float alpha) {
}
public void glClearColor4f(float red, float green, float blue, float alpha) {}
@Override
public void glClearColor(int c) {
}
public void glClearColor(int c) {}
@Override
public void glClear(int screenWidth, int screenHeight) {
}
public void glClear(int screenWidth, int screenHeight) {}
@Override
public BinaryFont getCurrentFont() {
return null;
@ -169,32 +146,29 @@ public class NoGuiEngine implements GraphicEngine {
public BinaryFont loadFont(String fontName) throws IOException {
return new BinaryFont() {
@Override
public void use(GraphicEngine d) {
}
public void use(GraphicEngine d) {}
@Override
public void load(String file) throws IOException {
}
public void load(String file) throws IOException {}
@Override
public boolean isInitialized() {
return true;
}
@Override
public void initialize(GraphicEngine d) {
}
public void initialize(GraphicEngine d) {}
@Override
public int getStringWidth(String text) {
return 1;
}
@Override
public int getCharacterWidth() {
return 1;
}
@Override
public int getCharacterHeight() {
return 1;
@ -218,32 +192,29 @@ public class NoGuiEngine implements GraphicEngine {
public BinaryFont loadFont(String path, String fontName) throws IOException {
return new BinaryFont() {
@Override
public void use(GraphicEngine d) {
}
public void use(GraphicEngine d) {}
@Override
public void load(String file) throws IOException {
}
public void load(String file) throws IOException {}
@Override
public boolean isInitialized() {
return true;
}
@Override
public void initialize(GraphicEngine d) {
}
public void initialize(GraphicEngine d) {}
@Override
public int getStringWidth(String text) {
return 1;
}
@Override
public int getCharacterWidth() {
return 1;
}
@Override
public int getCharacterHeight() {
return 1;
@ -267,21 +238,18 @@ public class NoGuiEngine implements GraphicEngine {
public Skin loadSkin(String file) throws IOException {
return new Skin() {
@Override
public void use(GraphicEngine d) {
}
public void use(GraphicEngine d) {}
@Override
public void load(String file) throws IOException {
}
public void load(String file) throws IOException {}
@Override
public boolean isInitialized() {
return true;
}
@Override
public void initialize(GraphicEngine d) {
}
public void initialize(GraphicEngine d) {}
@Override
public int getSkinWidth() {
@ -301,7 +269,7 @@ public class NoGuiEngine implements GraphicEngine {
public void waitForExit() {
try {
exitSemaphore.acquire();
} catch (InterruptedException e) {}
} catch (final InterruptedException e) {}
}
@Override

View File

@ -14,7 +14,7 @@ import org.warp.picalculator.gui.graphicengine.Skin;
public class MarioScreen extends Screen {
private MarioGame g;
private static Skin skin;
private static Skin groundskin;
private static BinaryFont gpuTest2;
@ -23,8 +23,8 @@ public class MarioScreen extends Screen {
private static Skin gpuTest3;
private int gpuTestNum = 0;
private float gpuTestElapsed = 0;
private int gpuTestMax = 21;
private String[] gpuCharTest1 = new String[] {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "ò"};
private final int gpuTestMax = 21;
private final String[] gpuCharTest1 = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "ò" };
private int gpuCharTest1Num = 0;
private float gpuCharTestt1Elapsed = 0;
private boolean errored;
@ -45,29 +45,34 @@ public class MarioScreen extends Screen {
@Override
public void initialized() {
try {
if (skin == null)
if (skin == null) {
skin = DisplayManager.INSTANCE.engine.loadSkin("marioskin.png");
if (groundskin == null)
}
if (groundskin == null) {
groundskin = DisplayManager.INSTANCE.engine.loadSkin("marioground.png");
if (gpuTest2 == null)
}
if (gpuTest2 == null) {
try {
gpuTest2 = DisplayManager.INSTANCE.engine.loadFont("gputest2");
} catch (Exception ex) {}
if (gpuTest1 == null)
} catch (final Exception ex) {}
}
if (gpuTest1 == null) {
try {
gpuTest1 = DisplayManager.INSTANCE.engine.loadFont("gputest12");
gpuTest12 = true;
StaticVars.windowZoom = 1;
} catch (Exception ex) {
} catch (final Exception ex) {
gpuTest12 = false;
try {
gpuTest1 = DisplayManager.INSTANCE.engine.loadFont("gputest1");
} catch (Exception ex2) {}
} catch (final Exception ex2) {}
}
if (gpuTest3 == null)
}
if (gpuTest3 == null) {
try {
gpuTest3 = DisplayManager.INSTANCE.engine.loadSkin("font_gputest3.png");
} catch (Exception ex) {}
} catch (final Exception ex) {}
}
} catch (final IOException e) {
e.printStackTrace();
}
@ -99,7 +104,7 @@ public class MarioScreen extends Screen {
gpuCharTest1Num = (gpuCharTest1Num + 1) % gpuCharTest1.length;
gpuCharTestt1Elapsed -= 1.5;
}
DisplayManager.INSTANCE.renderer.glClearColor(0xff000000);
}
}
@ -110,23 +115,23 @@ public class MarioScreen extends Screen {
DisplayManager.INSTANCE.renderer.glDrawStringLeft(0, 20, "ERROR");
} else {
if (groundskin != null) {
double playerX = g.getPlayer().getX();
double playerY = g.getPlayer().getY();
final double playerX = g.getPlayer().getX();
final double playerY = g.getPlayer().getY();
groundskin.use(DisplayManager.INSTANCE.engine);
MarioWorld w = g.getCurrentWorld();
int width = w.getWidth();
int height = w.getHeight();
float screenX = DisplayManager.INSTANCE.engine.getWidth()/2f - 8f;
float screenY = DisplayManager.INSTANCE.engine.getHeight()/2f - 8f;
float shiftX = -8 + 16 * (float)playerX;
float shiftY = -8 + 16 * (height - (float)playerY);
final MarioWorld w = g.getCurrentWorld();
final int width = w.getWidth();
final int height = w.getHeight();
final float screenX = DisplayManager.INSTANCE.engine.getWidth() / 2f - 8f;
final float screenY = DisplayManager.INSTANCE.engine.getHeight() / 2f - 8f;
final float shiftX = -8 + 16 * (float) playerX;
final float shiftY = -8 + 16 * (height - (float) playerY);
int blue = -1;
for (int ix = 0; ix < width; ix++) {
for (int iy = 0; iy < height; iy++) {
double distX = Math.abs(playerX - ix);
double distY = Math.abs(playerY - iy - 1.5d);
if ((distX*distX + distY*distY/2d) < 25d) {
byte b = w.getBlockIdAt(ix, iy);
final double distX = Math.abs(playerX - ix);
final double distY = Math.abs(playerY - iy - 1.5d);
if ((distX * distX + distY * distY / 2d) < 25d) {
final byte b = w.getBlockIdAt(ix, iy);
if (b == 0) {
if (blue != 1) {
blue = 1;
@ -138,7 +143,7 @@ public class MarioScreen extends Screen {
blue = 0;
DisplayManager.INSTANCE.renderer.glColor(0xffffffff);
}
DisplayManager.INSTANCE.renderer.glFillRect(screenX - shiftX+ 16 * ix, screenY - shiftY + 16 * (height - iy), 16, 16, 0, 0, 16, 16);
DisplayManager.INSTANCE.renderer.glFillRect(screenX - shiftX + 16 * ix, screenY - shiftY + 16 * (height - iy), 16, 16, 0, 0, 16, 16);
}
}
}
@ -150,17 +155,14 @@ public class MarioScreen extends Screen {
//DRAW MARIO
skin.use(DisplayManager.INSTANCE.engine);
DisplayManager.INSTANCE.renderer.glFillRect(screenX - (g.getPlayer().flipped ? 3 : 0), screenY,
35, 27,
35 * (g.getPlayer().marioSkinPos[0] + (g.getPlayer().flipped ? 2 : 1)), 27 * g.getPlayer().marioSkinPos[1],
35 * (g.getPlayer().flipped ? -1 : 1), 27);
DisplayManager.INSTANCE.renderer.glFillRect(screenX - (g.getPlayer().flipped ? 3 : 0), screenY, 35, 27, 35 * (g.getPlayer().marioSkinPos[0] + (g.getPlayer().flipped ? 2 : 1)), 27 * g.getPlayer().marioSkinPos[1], 35 * (g.getPlayer().flipped ? -1 : 1), 27);
// PIDisplay.renderer.glDrawSkin(getPosX() - 18, 25 + getPosY(), 35 * (marioSkinPos[0] + (flipped ? 2 : 1)), 27 * marioSkinPos[1], 35 * (marioSkinPos[0] + (flipped ? 1 : 2)), 27 * (marioSkinPos[1] + 1), true);
}
// GPU PERFORMANCE TEST
if (gpuTest1 != null) {
DisplayManager.INSTANCE.renderer.glColor3f(1,1,1);
DisplayManager.INSTANCE.renderer.glFillColor(DisplayManager.INSTANCE.engine.getWidth()-(gpuTest12 ? 512 : 256), DisplayManager.INSTANCE.engine.getHeight() / 2 - (gpuTest12 ? 256 : 128), gpuTest12 ? 512 : 256, gpuTest12 ? 512 : 256);
DisplayManager.INSTANCE.renderer.glColor3f(1, 1, 1);
DisplayManager.INSTANCE.renderer.glFillColor(DisplayManager.INSTANCE.engine.getWidth() - (gpuTest12 ? 512 : 256), DisplayManager.INSTANCE.engine.getHeight() / 2 - (gpuTest12 ? 256 : 128), gpuTest12 ? 512 : 256, gpuTest12 ? 512 : 256);
gpuTest1.use(DisplayManager.INSTANCE.engine);
DisplayManager.INSTANCE.renderer.glColor3f(0, 0, 0);
DisplayManager.INSTANCE.renderer.glDrawStringRight(DisplayManager.INSTANCE.engine.getWidth(), DisplayManager.INSTANCE.engine.getHeight() / 2 - (gpuTest12 ? 256 : 128), gpuCharTest1[gpuCharTest1Num]);

View File

@ -38,7 +38,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class MathInputScreen extends Screen {
private static final BinaryFont fontBig = Utils.getFont(false);
public MathContext calc;
public InputContext ic;
public InputContainer userInput;
@ -93,7 +93,7 @@ public class MathInputScreen extends Screen {
}
if (computingResult) {
computingElapsedTime += dt;
computingAnimationElapsedTime+=dt;
computingAnimationElapsedTime += dt;
if (computingAnimationElapsedTime > 0.1) {
computingAnimationElapsedTime -= 0.1;
computingAnimationIndex = (computingAnimationIndex + 1) % 16;
@ -101,7 +101,7 @@ public class MathInputScreen extends Screen {
}
if (computingElapsedTime > 5) {
computingBreakTipVisible = true;
}
}
} else {
computingElapsedTime = 0;
computingAnimationElapsedTime = 0;
@ -109,6 +109,7 @@ public class MathInputScreen extends Screen {
computingBreakTipVisible = false;
}
}
@Override
public void render() {
final Renderer renderer = DisplayManager.INSTANCE.renderer;
@ -130,7 +131,7 @@ public class MathInputScreen extends Screen {
if (computingBreakTipVisible) {
Utils.getFont(false).use(DisplayManager.INSTANCE.engine);
renderer.glColor3f(0.75f, 0, 0);
renderer.glDrawStringRight(DisplayManager.INSTANCE.engine.getWidth() - 4 - size - 4, DisplayManager.INSTANCE.engine.getHeight() - size/2 - renderer.getCurrentFont().getCharacterHeight()/2 - 4, "Press (=) to stop");
renderer.glDrawStringRight(DisplayManager.INSTANCE.engine.getWidth() - 4 - size - 4, DisplayManager.INSTANCE.engine.getHeight() - size / 2 - renderer.getCurrentFont().getCharacterHeight() / 2 - 4, "Press (=) to stop");
}
} else {
if (!result.isContentEmpty()) {
@ -155,7 +156,6 @@ public class MathInputScreen extends Screen {
renderer.glFillRect(2 + 18 * pos + 2 * spacersNumb, 2, 16, 16, 16 * skinN, 16 * 0, 16, 16);
}
@Override
public boolean mustBeRefreshed() {
if (mustRefresh) {
@ -193,7 +193,9 @@ public class MathInputScreen extends Screen {
case STEP:
currentStep++;
case SIMPLIFY:
if (!step) currentStep = 0;
if (!step) {
currentStep = 0;
}
if (DisplayManager.INSTANCE.error != null) {
//TODO: make the error management a global API rather than being relegated to this screen.
Utils.out.println(1, "Resetting after error...");
@ -205,11 +207,11 @@ public class MathInputScreen extends Screen {
} else {
if (!computingResult) {
computingResult = true;
computingThread = new Thread(()-> {
computingThread = new Thread(() -> {
try {
try {
if (!userInput.isAlreadyParsed() && !userInput.isEmpty()) {
Expression expr = MathParser.parseInput(calc, userInput);
final Expression expr = MathParser.parseInput(calc, userInput);
if (calc.f == null | calc.f2 == null) {
calc.f = new ObjectArrayList<>();
calc.f2 = new ObjectArrayList<>();
@ -219,14 +221,14 @@ public class MathInputScreen extends Screen {
}
calc.f.add(expr);
Utils.out.println(2, "INPUT: " + expr);
MathSolver ms = new MathSolver(expr);
ObjectArrayList<ObjectArrayList<Function>> resultSteps = ms.solveAllSteps();
final MathSolver ms = new MathSolver(expr);
final ObjectArrayList<ObjectArrayList<Function>> resultSteps = ms.solveAllSteps();
resultSteps.add(0, Utils.newArrayList(expr));
ObjectArrayList<Function> resultExpressions = resultSteps.get(resultSteps.size() - 1);
for (Function rr : resultExpressions) {
final ObjectArrayList<Function> resultExpressions = resultSteps.get(resultSteps.size() - 1);
for (final Function rr : resultExpressions) {
Utils.out.println(0, "RESULT: " + rr.toString());
}
ObjectArrayList<ObjectArrayList<Block>> resultBlocks = MathParser.parseOutput(calc, resultExpressions);
final ObjectArrayList<ObjectArrayList<Block>> resultBlocks = MathParser.parseOutput(calc, resultExpressions);
result.setContentAsMultipleGroups(resultBlocks);
// showVariablesDialog(() -> {
// currentExpression = newExpression;
@ -454,7 +456,7 @@ public class MathInputScreen extends Screen {
}
}
}
} catch (Exception ex) {
} catch (final Exception ex) {
ex.printStackTrace();
return true;
}

View File

@ -52,11 +52,14 @@ public interface Function {
* @return Calculator mathContext
*/
public MathContext getMathContext();
/**
* Simplify the current function or it's children using the specified <b>rule</b>
* Simplify the current function or it's children using the specified
* <b>rule</b>
*
* @param rule
* @return A list of the resulting Functions if the rule is applicable and something changed, <b>null</b> otherwise
* @return A list of the resulting Functions if the rule is applicable and
* something changed, <b>null</b> otherwise
* @throws Error
* @throws InterruptedException
*/

View File

@ -90,15 +90,19 @@ public abstract class FunctionDynamic implements Function {
@Override
public final ObjectArrayList<Function> simplify(Rule rule) throws Error, InterruptedException {
final Function[] fncs = getParameters();
if (Thread.interrupted()) throw new InterruptedException();
ObjectArrayList<Function> result = new ObjectArrayList<>();
if (Thread.interrupted()) {
throw new InterruptedException();
}
final ObjectArrayList<Function> result = new ObjectArrayList<>();
final ObjectArrayList<ObjectArrayList<Function>> ln = new ObjectArrayList<>();
boolean alreadySolved = true;
for (final Function fnc : fncs) {
final ObjectArrayList<Function> l = new ObjectArrayList<>();
if (Thread.interrupted()) throw new InterruptedException();
ObjectArrayList<Function> simplifiedFnc = fnc.simplify(rule);
if (Thread.interrupted()) {
throw new InterruptedException();
}
final ObjectArrayList<Function> simplifiedFnc = fnc.simplify(rule);
if (simplifiedFnc == null) {
l.add(fnc);
} else {
@ -107,8 +111,10 @@ public abstract class FunctionDynamic implements Function {
}
ln.add(l);
}
if (alreadySolved) return rule.execute(this);
if (alreadySolved) {
return rule.execute(this);
}
final Function[][] results = Utils.joinFunctionsResults(ln);

View File

@ -116,35 +116,49 @@ public abstract class FunctionOperator implements Function {
@Override
public final ObjectArrayList<Function> simplify(Rule rule) throws Error, InterruptedException {
if (Thread.interrupted()) throw new InterruptedException();
if (Thread.interrupted()) {
throw new InterruptedException();
}
ObjectArrayList<Function> simplifiedParam1 = parameter1.simplify(rule);
ObjectArrayList<Function> simplifiedParam2 = parameter2.simplify(rule);
final ObjectArrayList<Function> simplifiedParam1 = parameter1.simplify(rule);
final ObjectArrayList<Function> simplifiedParam2 = parameter2.simplify(rule);
try {
if (simplifiedParam1 == null & simplifiedParam2 == null) return rule.execute(this);
} catch (Exception e) {
Error err = new Error(Errors.ERROR, "Error while executing rule '" + rule.getRuleName() + "'!\n" + e.getMessage());
if (simplifiedParam1 == null & simplifiedParam2 == null) {
return rule.execute(this);
}
} catch (final Exception e) {
final Error err = new Error(Errors.ERROR, "Error while executing rule '" + rule.getRuleName() + "'!\n" + e.getMessage());
err.initCause(e);
throw err;
}
if (Thread.interrupted()) throw new InterruptedException();
ObjectArrayList<Function> result = new ObjectArrayList<>();
if (Thread.interrupted()) {
throw new InterruptedException();
}
final ObjectArrayList<Function> result = new ObjectArrayList<>();
final ObjectArrayList<Function> l1 = new ObjectArrayList<>();
final ObjectArrayList<Function> l2 = new ObjectArrayList<>();
if (Thread.interrupted()) throw new InterruptedException();
if (Thread.interrupted()) {
throw new InterruptedException();
}
if (simplifiedParam1 == null) {
l1.add(parameter1);
} else {
if (Thread.interrupted()) throw new InterruptedException();
if (Thread.interrupted()) {
throw new InterruptedException();
}
l1.addAll(simplifiedParam1);
}
if (Thread.interrupted()) throw new InterruptedException();
if (Thread.interrupted()) {
throw new InterruptedException();
}
if (simplifiedParam2 == null) {
l2.add(parameter2);
} else {
if (Thread.interrupted()) throw new InterruptedException();
if (Thread.interrupted()) {
throw new InterruptedException();
}
l2.addAll(simplifiedParam2);
}
@ -153,7 +167,7 @@ public abstract class FunctionOperator implements Function {
for (final Function[] f : results) {
result.add(setParameter1(f[0]).setParameter2(f[1]));
}
return result;
}
@ -170,6 +184,6 @@ public abstract class FunctionOperator implements Function {
@Override
public String toString() {
return this.getClass().getSimpleName() + "(" + this.getParameter1() + "," + this.getParameter2() + ")";
return this.getClass().getSimpleName() + "(" + getParameter1() + "," + getParameter2() + ")";
}
}

View File

@ -98,10 +98,12 @@ public abstract class FunctionSingle implements Function {
@Override
public final ObjectArrayList<Function> simplify(Rule rule) throws Error, InterruptedException {
ObjectArrayList<Function> simplifiedParam = parameter.simplify(rule);
if (simplifiedParam == null) return rule.execute(this);
ObjectArrayList<Function> result = new ObjectArrayList<>();
final ObjectArrayList<Function> simplifiedParam = parameter.simplify(rule);
if (simplifiedParam == null) {
return rule.execute(this);
}
final ObjectArrayList<Function> result = new ObjectArrayList<>();
for (final Function f : simplifiedParam) {
result.add(this.setParameter(f));
}

View File

@ -14,7 +14,7 @@ public class Division extends FunctionOperator {
public Division(MathContext root, Function value1, Function value2) {
super(root, value1, value2);
}
@Override
public boolean equals(Object o) {
if (o instanceof Division) {
@ -36,16 +36,16 @@ public class Division extends FunctionOperator {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>();
ObjectArrayList<Block> sub1 = getParameter1().toBlock(context);
ObjectArrayList<Block> sub2 = getParameter2().toBlock(context);
BlockDivision bd = new BlockDivision();
BlockContainer uc = bd.getUpperContainer();
BlockContainer lc = bd.getLowerContainer();
for (Block b : sub1) {
final ObjectArrayList<Block> result = new ObjectArrayList<>();
final ObjectArrayList<Block> sub1 = getParameter1().toBlock(context);
final ObjectArrayList<Block> sub2 = getParameter2().toBlock(context);
final BlockDivision bd = new BlockDivision();
final BlockContainer uc = bd.getUpperContainer();
final BlockContainer lc = bd.getLowerContainer();
for (final Block b : sub1) {
uc.appendBlockUnsafe(b);
}
for (Block b : sub2) {
for (final Block b : sub2) {
lc.appendBlockUnsafe(b);
}
uc.recomputeDimensions();

View File

@ -26,7 +26,7 @@ public class Expression extends FunctionSingle {
super(root, value);
}
private boolean initialParenthesis = false;
private final boolean initialParenthesis = false;
@Deprecated
public Expression(MathContext root, String string) throws Error {
@ -570,11 +570,11 @@ public class Expression extends FunctionSingle {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>();
ObjectArrayList<Block> sub = getParameter(0).toBlock(context);
BlockParenthesis bp = new BlockParenthesis();
BlockContainer bpc = bp.getNumberContainer();
for (Block b : sub) {
final ObjectArrayList<Block> result = new ObjectArrayList<>();
final ObjectArrayList<Block> sub = getParameter(0).toBlock(context);
final BlockParenthesis bp = new BlockParenthesis();
final BlockContainer bpc = bp.getNumberContainer();
for (final Block b : sub) {
bpc.appendBlockUnsafe(b);
}
bpc.recomputeDimensions();
@ -602,7 +602,7 @@ public class Expression extends FunctionSingle {
} else {
final Function f = (Function) o;
if (f instanceof Expression) {
return (getParameter(0).equals(((Expression)f).getParameter(0)));
return (getParameter(0).equals(((Expression) f).getParameter(0)));
} else {
return (getParameter(0).equals(f));
}

View File

@ -1,10 +1,8 @@
package org.warp.picalculator.math.functions;
import org.warp.picalculator.Error;
import org.warp.picalculator.Errors;
import org.warp.picalculator.gui.expression.blocks.Block;
import org.warp.picalculator.gui.expression.blocks.BlockContainer;
import org.warp.picalculator.gui.expression.blocks.BlockDivision;
import org.warp.picalculator.gui.expression.blocks.BlockLogarithm;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator;
@ -34,16 +32,16 @@ public class Logarithm extends FunctionOperator {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>();
ObjectArrayList<Block> sub1 = getParameter1().toBlock(context);
ObjectArrayList<Block> sub2 = getParameter2().toBlock(context);
BlockLogarithm bd = new BlockLogarithm();
BlockContainer uc = bd.getBaseContainer();
BlockContainer lc = bd.getNumberContainer();
for (Block b : sub1) {
final ObjectArrayList<Block> result = new ObjectArrayList<>();
final ObjectArrayList<Block> sub1 = getParameter1().toBlock(context);
final ObjectArrayList<Block> sub2 = getParameter2().toBlock(context);
final BlockLogarithm bd = new BlockLogarithm();
final BlockContainer uc = bd.getBaseContainer();
final BlockContainer lc = bd.getNumberContainer();
for (final Block b : sub1) {
uc.appendBlockUnsafe(b);
}
for (Block b : sub2) {
for (final Block b : sub2) {
lc.appendBlockUnsafe(b);
}
uc.recomputeDimensions();

View File

@ -40,19 +40,19 @@ public class Multiplication extends FunctionOperator {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>();
Function par1 = getParameter1();
Function par2 = getParameter2();
ObjectArrayList<Block> sub1 = par1.toBlock(context);
ObjectArrayList<Block> sub2 = par2.toBlock(context);
Block nearLeft = sub1.get(sub1.size() - 1);
Block nearRight = sub2.get(0);
final ObjectArrayList<Block> result = new ObjectArrayList<>();
final Function par1 = getParameter1();
final Function par2 = getParameter2();
final ObjectArrayList<Block> sub1 = par1.toBlock(context);
final ObjectArrayList<Block> sub2 = par2.toBlock(context);
final Block nearLeft = sub1.get(sub1.size() - 1);
final Block nearRight = sub2.get(0);
if (par1 instanceof Number && ((Number) par1).equals(new Number(context, -1))) {
result.add(new BlockChar(MathematicalSymbols.MINUS));
if (new Expression(context, par2).parenthesisNeeded()) {
ObjectArrayList<Block> parBlocks = par2.toBlock(context);
BlockParenthesis par = new BlockParenthesis(parBlocks);
final ObjectArrayList<Block> parBlocks = par2.toBlock(context);
final BlockParenthesis par = new BlockParenthesis(parBlocks);
result.add(par);
} else {
result.addAll(sub2);
@ -60,23 +60,20 @@ public class Multiplication extends FunctionOperator {
return result;
} else {
if (new Expression(context, par1).parenthesisNeeded()) {
ObjectArrayList<Block> parBlocks = par1.toBlock(context);
BlockParenthesis par = new BlockParenthesis(parBlocks);
final ObjectArrayList<Block> parBlocks = par1.toBlock(context);
final BlockParenthesis par = new BlockParenthesis(parBlocks);
result.add(par);
} else {
result.addAll(sub1);
}
if ((nearLeft instanceof BlockChar && nearRight instanceof BlockChar)
&& !(par2 instanceof Negative)
&& !(par1 instanceof Number && par2 instanceof Number)
) {
if ((nearLeft instanceof BlockChar && nearRight instanceof BlockChar) && !(par2 instanceof Negative) && !(par1 instanceof Number && par2 instanceof Number)) {
} else {
result.add(new BlockChar(MathematicalSymbols.MULTIPLICATION));
}
if (new Expression(context, par2).parenthesisNeeded()) {
ObjectArrayList<Block> parBlocks = par2.toBlock(context);
BlockParenthesis par = new BlockParenthesis(parBlocks);
final ObjectArrayList<Block> parBlocks = par2.toBlock(context);
final BlockParenthesis par = new BlockParenthesis(parBlocks);
result.add(par);
} else {
result.addAll(sub2);
@ -84,11 +81,11 @@ public class Multiplication extends FunctionOperator {
return result;
}
}
public boolean isNegative() {
return parameter1.equals(new Number(getMathContext(), -1)) || parameter2.equals(new Number(getMathContext(), -1));
}
public Function toPositive() {
if (parameter1.equals(new Number(getMathContext(), -1))) {
return parameter2;
@ -98,7 +95,7 @@ public class Multiplication extends FunctionOperator {
return null;
}
}
public static Multiplication newNegative(MathContext context, Function value2) {
return new Multiplication(context, new Number(context, -1), value2);
}

View File

@ -32,12 +32,12 @@ public class Negative extends FunctionSingle {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> blocks = new ObjectArrayList<Block>();
final ObjectArrayList<Block> blocks = new ObjectArrayList<>();
blocks.add(new BlockChar(MathematicalSymbols.MINUS));
if (new Expression(context, getParameter()).parenthesisNeeded()) {
BlockParenthesis par = new BlockParenthesis();
ObjectArrayList<Block> parBlocks = getParameter().toBlock(context);
for (Block b : parBlocks) {
final BlockParenthesis par = new BlockParenthesis();
final ObjectArrayList<Block> parBlocks = getParameter().toBlock(context);
for (final Block b : parBlocks) {
par.getNumberContainer().appendBlockUnsafe(b); // Skips recomputeDimension
}
par.recomputeDimensions(); // Recompute dimensions after appendBlockUnsafe

View File

@ -76,7 +76,9 @@ public class Number implements Function {
if (Utils.isIntegerValue(f.term)) {
final BigInteger bi = f.term.toBigInteger().abs();
for (BigInteger i = BigInteger.ZERO; i.compareTo(bi) < 0; i = i.add(BigInteger.ONE)) {
if (Thread.interrupted()) throw new InterruptedException();
if (Thread.interrupted()) {
throw new InterruptedException();
}
ret = ret.multiply(new Number(root, getTerm()));
}
if (f.term.signum() == -1) {
@ -231,16 +233,16 @@ public class Number implements Function {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) {
ObjectArrayList<Block> result = new ObjectArrayList<>();
String numberString = this.toString();
final ObjectArrayList<Block> result = new ObjectArrayList<>();
final String numberString = toString();
if (numberString.contains("")) {
String[] numberParts = numberString.split("", 2);
BlockPower bp = new BlockExponentialNotation();
BlockContainer bpec = bp.getExponentContainer();
for (char c : numberParts[0].toCharArray()) {
final String[] numberParts = numberString.split("", 2);
final BlockPower bp = new BlockExponentialNotation();
final BlockContainer bpec = bp.getExponentContainer();
for (final char c : numberParts[0].toCharArray()) {
result.add(new BlockChar(c));
}
for (char c : numberParts[1].toCharArray()) {
for (final char c : numberParts[1].toCharArray()) {
bpec.appendBlockUnsafe(new BlockChar(c));
} ;
bpec.recomputeDimensions();
@ -248,7 +250,7 @@ public class Number implements Function {
result.add(bp);
return result;
} else {
for (char c : numberString.toCharArray()) {
for (final char c : numberString.toCharArray()) {
result.add(new BlockChar(c));
}
}

View File

@ -32,13 +32,13 @@ public class Power extends FunctionOperator {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>();
ObjectArrayList<Block> sub1 = getParameter1().toBlock(context);
ObjectArrayList<Block> sub2 = getParameter2().toBlock(context);
BlockPower bp = new BlockPower();
BlockContainer ec = bp.getExponentContainer();
final ObjectArrayList<Block> result = new ObjectArrayList<>();
final ObjectArrayList<Block> sub1 = getParameter1().toBlock(context);
final ObjectArrayList<Block> sub2 = getParameter2().toBlock(context);
final BlockPower bp = new BlockPower();
final BlockContainer ec = bp.getExponentContainer();
result.addAll(sub1);
for (Block b : sub2) {
for (final Block b : sub2) {
ec.appendBlockUnsafe(b);
}
ec.recomputeDimensions();

View File

@ -32,10 +32,10 @@ public class RootSquare extends FunctionOperator {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>();
BlockSquareRoot bsqr = new BlockSquareRoot();
BlockContainer bsqrc = bsqr.getNumberContainer();
for (Block b : getParameter2().toBlock(context)) {
final ObjectArrayList<Block> result = new ObjectArrayList<>();
final BlockSquareRoot bsqr = new BlockSquareRoot();
final BlockContainer bsqrc = bsqr.getNumberContainer();
for (final Block b : getParameter2().toBlock(context)) {
bsqrc.appendBlockUnsafe(b);
}
bsqrc.recomputeDimensions();

View File

@ -32,7 +32,7 @@ public class Subtraction extends FunctionOperator {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>();
final ObjectArrayList<Block> result = new ObjectArrayList<>();
result.addAll(getParameter1().toBlock(context));
result.add(new BlockChar(MathematicalSymbols.SUBTRACTION));
result.addAll(getParameter2().toBlock(context));

View File

@ -35,7 +35,7 @@ public class Sum extends FunctionOperator {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>();
final ObjectArrayList<Block> result = new ObjectArrayList<>();
result.addAll(getParameter1().toBlock(context));
result.add(new BlockChar(MathematicalSymbols.SUM));
result.addAll(getParameter2().toBlock(context));

View File

@ -32,7 +32,7 @@ public class SumSubtraction extends FunctionOperator {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>();
final ObjectArrayList<Block> result = new ObjectArrayList<>();
result.addAll(getParameter1().toBlock(context));
result.add(new BlockChar(MathematicalSymbols.SUM_SUBTRACTION));
result.addAll(getParameter2().toBlock(context));

View File

@ -49,11 +49,11 @@ public class Undefined implements Function {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) {
ObjectArrayList<Block> result = new ObjectArrayList<>();
final ObjectArrayList<Block> result = new ObjectArrayList<>();
result.add(new BlockUndefined());
return result;
}
@Override
public String toString() {
return "UNDEFINED";

View File

@ -55,7 +55,7 @@ public class Variable implements Function {
this.n = n;
}
}
@Override
public ObjectArrayList<Function> simplify(Rule rule) throws Error, InterruptedException {
return rule.execute(this);
@ -100,7 +100,7 @@ public class Variable implements Function {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) {
ObjectArrayList<Block> result = new ObjectArrayList<>();
final ObjectArrayList<Block> result = new ObjectArrayList<>();
//TODO: Temporary solution. In near future Variables will be distint objects and they will have a color. So they will be no longer a BlockChar/FeatureChar
result.add(new BlockChar(getChar()));
return result;

View File

@ -33,11 +33,11 @@ public class Sine extends FunctionSingle {
@Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>();
ObjectArrayList<Block> sub = getParameter(0).toBlock(context);
BlockSine bs = new BlockSine();
BlockContainer bpc = bs.getNumberContainer();
for (Block b : sub) {
final ObjectArrayList<Block> result = new ObjectArrayList<>();
final ObjectArrayList<Block> sub = getParameter(0).toBlock(context);
final BlockSine bs = new BlockSine();
final BlockContainer bpc = bs.getNumberContainer();
for (final Block b : sub) {
bpc.appendBlockUnsafe(b);
}
bpc.recomputeDimensions();

View File

@ -45,10 +45,11 @@ public class MathParser {
public static ObjectArrayList<ObjectArrayList<Block>> parseOutput(MathContext context,
ObjectArrayList<Function> resultExpressions) throws Error {
final ObjectArrayList<ObjectArrayList<Block>> result = new ObjectArrayList<>();
for (Function resultExpression : resultExpressions) {
ObjectArrayList<Block> resultBlocks = resultExpression.toBlock(context);
if (resultBlocks == null)
for (final Function resultExpression : resultExpressions) {
final ObjectArrayList<Block> resultBlocks = resultExpression.toBlock(context);
if (resultBlocks == null) {
throw new Error(Errors.NOT_IMPLEMENTED, "Unknown function " + resultExpression.getClass().getSimpleName());
}
result.add(resultBlocks);
}
return result;
@ -61,9 +62,10 @@ public class MathParser {
ObjectArrayList<Function> process = new ObjectArrayList<>();
for (final Feature f : features) {
Function fnc = f.toFunction(context);
if (fnc == null)
final Function fnc = f.toFunction(context);
if (fnc == null) {
throw new Error(Errors.SYNTAX_ERROR, "\"" + f.getClass().getSimpleName() + "\" can't be converted into a Function!");
}
process.add(fnc);
}
@ -78,35 +80,28 @@ public class MathParser {
private static ObjectArrayList<Function> fixStack(MathContext context, ObjectArrayList<Function> functionsList)
throws Error {
final MathParserStep[] steps = new MathParserStep[] {
new JoinNumberAndVariables(context),
new FixSingleFunctionArgs(),
new RemoveParentheses(context),
new FixMultiplicationsAndDivisions(),
new FixSumsAndSubtractions(),
new AddImplicitMultiplications(context),
};
final MathParserStep[] steps = new MathParserStep[] { new JoinNumberAndVariables(context), new FixSingleFunctionArgs(), new RemoveParentheses(context), new FixMultiplicationsAndDivisions(), new FixSumsAndSubtractions(), new AddImplicitMultiplications(context), };
boolean lastLoopDidSomething;
Function lastElement;
if (StaticVars.debugOn) {
Utils.out.print(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "\tStatus: ");
for (Function f : functionsList) {
for (final Function f : functionsList) {
Utils.out.print(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, f.toString());
}
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE);
}
for (MathParserStep step : steps) {
for (final MathParserStep step : steps) {
if (StaticVars.debugOn) {
Utils.out.println(2, "Stack fixing step \"" + step.getStepName() + "\"");
}
int stepQty = step.requiresReversedIteration() ? -1 : 1,
final int stepQty = step.requiresReversedIteration() ? -1 : 1,
initialIndex = step.requiresReversedIteration() ? functionsList.size() - 1 : 0;
do {
lastLoopDidSomething = false;
lastElement = null;
IntegerObj curIndex = new IntegerObj(initialIndex);
final IntegerObj curIndex = new IntegerObj(initialIndex);
while (curIndex.i >= 0 && curIndex.i < functionsList.size()) {
final int i = curIndex.i;
final Function f = functionsList.get(i);
@ -122,7 +117,7 @@ public class MathParser {
if (StaticVars.debugOn) {
Utils.out.print(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "\tStatus: ");
for (Function f : functionsList) {
for (final Function f : functionsList) {
Utils.out.print(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, f.toString());
}
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE);
@ -192,7 +187,7 @@ public class MathParser {
break;
}
for (char var : MathematicalSymbols.variables) {
for (final char var : MathematicalSymbols.variables) {
if (featureChar == var) {
result = new FeatureVariable(featureChar, V_TYPE.VARIABLE);
break;

View File

@ -3,7 +3,6 @@ package org.warp.picalculator.math.parser.features;
import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.functions.Logarithm;
import org.warp.picalculator.math.functions.Power;
public class FeatureLogarithm extends FeatureDoubleImpl {

View File

@ -13,7 +13,7 @@ public class FeatureParenthesis extends FeatureSingleImpl {
@Override
public Function toFunction(MathContext context) throws Error {
return new Expression(context, this.getFunction1());
return new Expression(context, getFunction1());
}
}

View File

@ -13,7 +13,7 @@ public class FeatureSine extends FeatureSingleImpl {
@Override
public Function toFunction(MathContext context) throws Error {
return new Sine(context, this.getFunction1());
return new Sine(context, getFunction1());
}
}

View File

@ -10,7 +10,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class AddImplicitMultiplications implements MathParserStep {
private MathContext context;
private final MathContext context;
public AddImplicitMultiplications(MathContext context) {
this.context = context;

View File

@ -13,14 +13,15 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class JoinNumberAndVariables implements MathParserStep {
private MathContext context;
private final MathContext context;
public JoinNumberAndVariables(MathContext context) {
this.context = context;
}
@Override
public boolean eval(IntegerObj curIndex, Function lastFunction, Function currentFunction, ObjectArrayList<Function> functionsList) {
public boolean eval(IntegerObj curIndex, Function lastFunction, Function currentFunction,
ObjectArrayList<Function> functionsList) {
if (currentFunction instanceof Number | currentFunction instanceof Variable | currentFunction instanceof Division) {
if (lastFunction instanceof Variable | lastFunction instanceof Number | (lastFunction instanceof Multiplication && ((Multiplication) lastFunction).getParameter2() != null)) {
final Function a = currentFunction;

View File

@ -10,19 +10,20 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class RemoveParentheses implements MathParserStep {
private MathContext context;
private final MathContext context;
public RemoveParentheses(MathContext context) {
this.context = context;
}
@Override
public boolean eval(IntegerObj curIndex, Function lastFunction, Function currentFunction, ObjectArrayList<Function> functionsList) {
public boolean eval(IntegerObj curIndex, Function lastFunction, Function currentFunction,
ObjectArrayList<Function> functionsList) {
if (currentFunction instanceof Expression) {
if (((Expression)currentFunction).getParameter() == null) {
if (((Expression) currentFunction).getParameter() == null) {
functionsList.remove(curIndex.i);
} else {
functionsList.set(curIndex.i, ((Expression)currentFunction).getParameter());
functionsList.set(curIndex.i, ((Expression) currentFunction).getParameter());
}
return true;
}

View File

@ -8,12 +8,14 @@ import jdk.nashorn.internal.objects.annotations.SpecializedFunction;
/**
* Rule interface
*
* @author Andrea Cavalli
*
*/
public interface Rule {
/**
* Get rule name
*
* @return
*/
public default String getRuleName() {
@ -22,16 +24,23 @@ public interface Rule {
/**
* Get rule type
*
* @return
*/
@SpecializedFunction
public RuleType getRuleType();
/**
*
* @param func
* @return <ul><li><code>null</code> if it's not executable on the function <b>func</b></li><li>An <code>ObjectArrayList&lt;Function&gt;</code> if it did something</li></ul>
* @throws Error
* @return
* <ul>
* <li><code>null</code> if it's not executable on the function
* <b>func</b></li>
* <li>An <code>ObjectArrayList&lt;Function&gt;</code> if it did
* something</li>
* </ul>
* @throws Error
*/
public ObjectArrayList<Function> execute(Function func) throws Error, InterruptedException;
}

View File

@ -2,11 +2,13 @@ package org.warp.picalculator.math.rules;
public enum RuleType {
/**
* A rule that tries to factorize and group a polynomial expression into a shorter expression
* A rule that tries to factorize and group a polynomial expression into a
* shorter expression
*/
REDUCTION,
/**
* A rule that tries to transform an expression to a simple polynomial expression
* A rule that tries to transform an expression to a simple polynomial
* expression
*/
EXPANSION,
/**

View File

@ -28,18 +28,17 @@ import org.warp.picalculator.math.solver.MathSolver;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class RulesManager {
public static ObjectArrayList<Rule>[] rules;
private RulesManager() {
}
private RulesManager() {}
@SuppressWarnings("unchecked")
public static void initialize() {
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Loading the rules");
rules = new ObjectArrayList[RuleType.values().length];
for (RuleType val : RuleType.values()) {
rules[val.ordinal()] = new ObjectArrayList<Rule>();
for (final RuleType val : RuleType.values()) {
rules[val.ordinal()] = new ObjectArrayList<>();
}
try {
boolean compiledSomething = false;
@ -47,31 +46,29 @@ public class RulesManager {
if (!Files.exists(defaultRulesPath)) {
throw new FileNotFoundException("default-rules.lst not found!");
}
List<String> ruleLines = new ArrayList<String>();
Path rulesPath = Paths.get("rules/");
final List<String> ruleLines = new ArrayList<>();
final Path rulesPath = Paths.get("rules/");
if (rulesPath.toFile().exists()) {
try (Stream<Path> paths = Files.walk(rulesPath)) {
paths
.filter(Files::isRegularFile)
.forEach((Path p) -> {
if (p.toString().endsWith(".java")) {
String path = rulesPath.relativize(p).toString();
path = path.substring(0, path.length() - ".java".length());
ruleLines.add(path);
Utils.out.print(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Found external rule: " + p.toAbsolutePath().toString());
System.err.println(path);
}
});
}
paths.filter(Files::isRegularFile).forEach((Path p) -> {
if (p.toString().endsWith(".java")) {
String path = rulesPath.relativize(p).toString();
path = path.substring(0, path.length() - ".java".length());
ruleLines.add(path);
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Found external rule: " + p.toAbsolutePath().toString());
System.err.println(path);
}
});
}
}
ruleLines.addAll(Files.readAllLines(defaultRulesPath));
boolean useCache = false;
Path tDir = Paths.get(System.getProperty("java.io.tmpdir"), "WarpPi-Calculator").resolve("rules-rt");
final Path tDir = Paths.get(System.getProperty("java.io.tmpdir"), "WarpPi-Calculator").resolve("rules-rt");
// try {
// final Path defaultResource = Utils.getResource("/math-rules-cache.zip");
// }
Path cacheFilePath = Utils.getResource("/math-rules-cache.zip");//Paths.get(Utils.getJarDirectory().toString()).resolve("math-rules-cache.zip").toAbsolutePath();
final Path cacheFilePath = Utils.getResource("/math-rules-cache.zip");//Paths.get(Utils.getJarDirectory().toString()).resolve("math-rules-cache.zip").toAbsolutePath();
if (cacheFilePath.toFile().exists()) {
try {
if (tDir.toFile().exists()) {
@ -79,19 +76,19 @@ public class RulesManager {
}
Utils.unzip(cacheFilePath.toString(), tDir.getParent().toString(), "");
useCache = !Utils.debugCache;
} catch (Exception ex) {
} catch (final Exception ex) {
ex.printStackTrace();
}
}
for (String rulesLine : ruleLines) {
for (final String rulesLine : ruleLines) {
if (rulesLine.length() > 0) {
String[] ruleDetails = rulesLine.split(",", 1);
String ruleName = ruleDetails[0];
String ruleNameEscaped = ruleName.replace(".", "_");
final String[] ruleDetails = rulesLine.split(",", 1);
final String ruleName = ruleDetails[0];
final String ruleNameEscaped = ruleName.replace(".", "_");
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Evaluating /rules/" + ruleNameEscaped + ".java");
String pathWithoutExtension = "/rules/" + ruleNameEscaped;
String scriptFile = pathWithoutExtension + ".java";
InputStream resourcePath = Utils.getResourceStream(scriptFile);
final String pathWithoutExtension = "/rules/" + ruleNameEscaped;
final String scriptFile = pathWithoutExtension + ".java";
final InputStream resourcePath = Utils.getResourceStream(scriptFile);
if (resourcePath == null) {
System.err.println(new FileNotFoundException("/rules/" + ruleName + ".java not found!"));
} else {
@ -103,7 +100,7 @@ public class RulesManager {
if (r != null) {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", ruleName, "Loaded cached rule");
}
} catch (Exception e) {
} catch (final Exception e) {
e.printStackTrace();
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", ruleName, "Can't load the rule!");
}
@ -116,7 +113,7 @@ public class RulesManager {
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
if (r != null) {
RulesManager.addRule(r);
@ -137,21 +134,21 @@ public class RulesManager {
System.exit(1);
}
}
public static Rule compileJavaRule(String scriptFile, Path tDir) throws IOException, URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException {
InputStream resource = Utils.getResourceStream(scriptFile);
String text = Utils.read(resource);
String[] textArray = text.split("\\n", 5);
String javaClassDeclaration = textArray[2].substring(6);
public static Rule compileJavaRule(String scriptFile, Path tDir) throws IOException, URISyntaxException,
InstantiationException, IllegalAccessException, ClassNotFoundException {
final InputStream resource = Utils.getResourceStream(scriptFile);
final String text = Utils.read(resource);
final String[] textArray = text.split("\\n", 5);
final String javaClassDeclaration = textArray[2].substring(6);
int extIndex = javaClassDeclaration.lastIndexOf('.');
String javaClassNameOnly = javaClassDeclaration.substring(extIndex + 1, javaClassDeclaration.length());
String javaClassNameAndPath = new StringBuilder("org.warp.picalculator.math.rules.").append(javaClassDeclaration).toString();
final String javaClassNameOnly = javaClassDeclaration.substring(extIndex + 1, javaClassDeclaration.length());
final String javaClassNameAndPath = new StringBuilder("org.warp.picalculator.math.rules.").append(javaClassDeclaration).toString();
extIndex = javaClassNameAndPath.lastIndexOf('.');
String javaCode = new StringBuilder("package ").append(javaClassNameAndPath.substring(0, extIndex >= 0 ? extIndex : javaClassNameAndPath.length())).append(";\n")
.append(textArray[4]).toString();
Path tDirPath = tDir.resolve(javaClassNameAndPath.replace('.', File.separatorChar)).getParent();
Path tFileJava = tDirPath.resolve(javaClassNameOnly + ".java");
Path tFileClass = tDirPath.resolve(javaClassNameOnly + ".class");
final String javaCode = new StringBuilder("package ").append(javaClassNameAndPath.substring(0, extIndex >= 0 ? extIndex : javaClassNameAndPath.length())).append(";\n").append(textArray[4]).toString();
final Path tDirPath = tDir.resolve(javaClassNameAndPath.replace('.', File.separatorChar)).getParent();
final Path tFileJava = tDirPath.resolve(javaClassNameOnly + ".java");
final Path tFileClass = tDirPath.resolve(javaClassNameOnly + ".class");
if (!tDirPath.toFile().exists()) {
Files.createDirectories(tDirPath);
}
@ -159,7 +156,7 @@ public class RulesManager {
tFileJava.toFile().delete();
}
Files.write(tFileJava, javaCode.getBytes("UTF-8"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
boolean compiled = org.eclipse.jdt.internal.compiler.batch.Main.compile(new String[] {"-nowarn", "-1.8", tFileJava.toString()}, new PrintWriter(System.out), new PrintWriter(System.err), null);
final boolean compiled = org.eclipse.jdt.internal.compiler.batch.Main.compile(new String[] { "-nowarn", "-1.8", tFileJava.toString() }, new PrintWriter(System.out), new PrintWriter(System.err), null);
if (Utils.debugCache) {
tFileJava.toFile().deleteOnExit();
} else {
@ -172,41 +169,43 @@ public class RulesManager {
throw new IOException("Can't build script file '" + scriptFile + "'");
}
}
public static Rule loadClassRuleFromSourceFile(String scriptFile, Path tDir) throws IOException, URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException {
InputStream resource = Utils.getResourceStream(scriptFile);
String text = Utils.read(resource);
String[] textArray = text.split("\\n", 5);
String javaClassName = textArray[2].substring(6);
String javaClassNameAndPath = new StringBuilder("org.warp.picalculator.math.rules.").append(javaClassName).toString();
public static Rule loadClassRuleFromSourceFile(String scriptFile, Path tDir) throws IOException, URISyntaxException,
InstantiationException, IllegalAccessException, ClassNotFoundException {
final InputStream resource = Utils.getResourceStream(scriptFile);
final String text = Utils.read(resource);
final String[] textArray = text.split("\\n", 5);
final String javaClassName = textArray[2].substring(6);
final String javaClassNameAndPath = new StringBuilder("org.warp.picalculator.math.rules.").append(javaClassName).toString();
try {
return loadClassRuleDirectly(javaClassNameAndPath, tDir);
} catch (Exception ex) {
} catch (final Exception ex) {
ex.printStackTrace();
return null;
}
}
public static Rule loadClassRuleDirectly(String javaClassNameAndPath, Path tDir) throws IOException, URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException {
URLClassLoader cl = new URLClassLoader(new URL[] {tDir.toUri().toURL()});
Class<?> aClass = cl.loadClass(javaClassNameAndPath);
public static Rule loadClassRuleDirectly(String javaClassNameAndPath, Path tDir) throws IOException,
URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException {
final URLClassLoader cl = new URLClassLoader(new URL[] { tDir.toUri().toURL() });
final Class<?> aClass = cl.loadClass(javaClassNameAndPath);
cl.close();
return (Rule) aClass.newInstance();
}
public static void warmUp() throws Error, InterruptedException {
ObjectArrayList<Function> uselessResult = null;
boolean uselessVariable = false;
for (RuleType val : RuleType.values()) {
for (final RuleType val : RuleType.values()) {
final ObjectArrayList<Rule> ruleList = rules[val.ordinal()];
for (final Rule rule : ruleList) {
String ruleName = "<null>";
try {
ruleName = rule.getRuleName();
ObjectArrayList<Function> uselessResult2 = rule.execute(generateUselessExpression());
final ObjectArrayList<Function> uselessResult2 = rule.execute(generateUselessExpression());
uselessVariable = (uselessResult == null ? new ObjectArrayList<>() : uselessResult).equals(uselessResult2);
uselessResult = uselessResult2;
} catch (Exception e) {
} catch (final Exception e) {
if (uselessVariable || true) {
System.err.println("Exception thrown by rule '" + ruleName + "'!");
e.printStackTrace();
@ -220,14 +219,14 @@ public class RulesManager {
e.printStackTrace();
}
}
private static Function generateUselessExpression() {
MathContext mc = new MathContext();
final MathContext mc = new MathContext();
Function expr = new Expression(mc);
expr = expr.setParameter(0, new Variable(mc, 'x', V_TYPE.VARIABLE));
return expr;
}
public static void addRule(Rule rule) {
rules[rule.getRuleType().ordinal()].add(rule);
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", rule.getRuleName(), "Loaded as " + rule.getRuleType() + " rule");

View File

@ -41,9 +41,9 @@ public class DivisionRule1 {
}*/
final int[] size = new int[] { elements[0].size(), elements[1].size() };
Function separatedDivision = new Division(root, elem1, elem2);
final Function separatedDivision = new Division(root, elem1, elem2);
Function[] resultDivisionArray = new Function[2];
final Function[] resultDivisionArray = new Function[2];
Function prec;
for (int part = 0; part < 2; part++) {
prec = null;
@ -76,7 +76,9 @@ public class DivisionRule1 {
final ObjectArrayList<Function> elementsNumerator = new ObjectArrayList<>();
Function numMult = division.getParameter1();
while (numMult instanceof Multiplication) {
if (Thread.interrupted()) throw new InterruptedException();
if (Thread.interrupted()) {
throw new InterruptedException();
}
elementsNumerator.add(((Multiplication) numMult).getParameter1());
numMult = ((Multiplication) numMult).getParameter2();
}
@ -85,7 +87,9 @@ public class DivisionRule1 {
final ObjectArrayList<Function> elementsDenominator = new ObjectArrayList<>();
Function denomMult = division.getParameter2();
while (denomMult instanceof Multiplication) {
if (Thread.interrupted()) throw new InterruptedException();
if (Thread.interrupted()) {
throw new InterruptedException();
}
elementsDenominator.add(((Multiplication) denomMult).getParameter1());
denomMult = ((Multiplication) denomMult).getParameter2();
}
@ -94,7 +98,8 @@ public class DivisionRule1 {
return new ObjectArrayList[] { elementsNumerator, elementsDenominator };
}
private static int[] getFirstWorkingDivisionCouple(ObjectArrayList<Function>[] elements) throws InterruptedException {
private static int[] getFirstWorkingDivisionCouple(ObjectArrayList<Function>[] elements)
throws InterruptedException {
return null;
//TODO:
// final int[] size = new int[] { elements[0].size(), elements[1].size() };

View File

@ -30,7 +30,9 @@ public class MultiplicationMethod1 {
final int size = elements.size();
Function prec = new Multiplication(root, elem1, elem2);
for (int i = size - 1; i >= 0; i--) {
if (Thread.interrupted()) throw new InterruptedException();
if (Thread.interrupted()) {
throw new InterruptedException();
}
if (i != workingElementCouple[0] & i != workingElementCouple[1]) {
final Function a = prec;
final Function b = elements.get(i);
@ -48,7 +50,9 @@ public class MultiplicationMethod1 {
private static ObjectArrayList<Function> getMultiplicationElements(Function mult) throws InterruptedException {
final ObjectArrayList<Function> elements = new ObjectArrayList<>();
while (mult instanceof Multiplication) {
if (Thread.interrupted()) throw new InterruptedException();
if (Thread.interrupted()) {
throw new InterruptedException();
}
elements.add(((Multiplication) mult).getParameter1());
mult = ((Multiplication) mult).getParameter2();
}
@ -56,7 +60,8 @@ public class MultiplicationMethod1 {
return elements;
}
private static int[] getFirstWorkingMultiplicationCouple(ObjectArrayList<Function> elements) throws InterruptedException {
private static int[] getFirstWorkingMultiplicationCouple(ObjectArrayList<Function> elements)
throws InterruptedException {
return null;
// TODO:
// final int size = elements.size();

View File

@ -41,7 +41,9 @@ public class SumMethod1 {
Function prec = new Sum(root, elem1, elem2);
for (int i = size - 1; i >= 0; i--) {
if (i != workingElementCouple[0] & i != workingElementCouple[1]) {
if (Thread.interrupted()) throw new InterruptedException();
if (Thread.interrupted()) {
throw new InterruptedException();
}
final Function a = prec;
final Function b = elements.get(i);
if (b instanceof Negative) {
@ -67,7 +69,9 @@ public class SumMethod1 {
final MathContext root = sum.getMathContext();
final ObjectArrayList<Function> elements = new ObjectArrayList<>();
while (sum instanceof Sum || sum instanceof Subtraction) {
if (Thread.interrupted()) throw new InterruptedException();
if (Thread.interrupted()) {
throw new InterruptedException();
}
if (sum instanceof Sum) {
elements.add(((FunctionOperator) sum).getParameter2());
} else {
@ -79,7 +83,8 @@ public class SumMethod1 {
return elements;
}
private static int[] getFirstWorkingSumCouple(MathContext root, ObjectArrayList<Function> elements) throws InterruptedException {
private static int[] getFirstWorkingSumCouple(MathContext root, ObjectArrayList<Function> elements)
throws InterruptedException {
return null;
// final int size = elements.size();
// Function a;

View File

@ -14,34 +14,33 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
public class MathSolver {
private final Function initialFunction;
private AtomicInteger stepState = new AtomicInteger(0);
private final AtomicInteger stepState = new AtomicInteger(0);
private int stepStateRepetitions = 0;
private int consecutiveNullSteps = 0;
private enum StepState {
_1_CALCULATION,
_2_EXPANSION,
_3_CALCULATION,
_4_REDUCTION
_1_CALCULATION, _2_EXPANSION, _3_CALCULATION, _4_REDUCTION
}
private final StepState[] stepStates = StepState.values();
@SuppressWarnings("unchecked")
private final ObjectArrayList<Function>[][] lastFunctions = new ObjectArrayList[2][stepStates.length];
public MathSolver(Function initialFunction) {
this.initialFunction = initialFunction;
}
@SuppressWarnings("unchecked")
public ObjectArrayList<ObjectArrayList<Function>> solveAllSteps() throws InterruptedException, Error {
ObjectArrayList<ObjectArrayList<Function>> steps = new ObjectArrayList<>();
final ObjectArrayList<ObjectArrayList<Function>> steps = new ObjectArrayList<>();
ObjectArrayList<Function> lastFnc = null, currFnc = new ObjectArrayList<>();
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", "Solving all steps. Input: " + initialFunction.toString());
currFnc.add(initialFunction);
long stepNumber = 0;
int initStepState = 0, endStepState = 0;
AtomicInteger stepState = new AtomicInteger(0);
final AtomicInteger stepState = new AtomicInteger(0);
do {
lastFunctions[1] = lastFunctions[0];
lastFunctions[0] = new ObjectArrayList[stepStates.length];
@ -52,9 +51,9 @@ public class MathSolver {
lastFnc = currFnc;
initStepState = stepState.get();
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", stepName, "Starting step " + stepStates[initStepState] + ". Input: " + currFnc);
ObjectArrayList<Function> stepResult = solveStep(lastFnc, stepState);
final ObjectArrayList<Function> stepResult = solveStep(lastFnc, stepState);
if (stepResult != null) {
for (Function result : stepResult) {
for (final Function result : stepResult) {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, result.toString());
}
currFnc = stepResult;
@ -72,7 +71,7 @@ public class MathSolver {
if (StaticVars.debugOn) {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", stepName, currFnc + " is " + (checkEquals(currFnc, lastFunctions[1][endStepState]) ? "" : "not ") + "equals to [1]:" + lastFunctions[1][endStepState]);
}
} while(consecutiveNullSteps < stepStates.length && !checkEquals(currFnc, lastFunctions[0][endStepState]) && !checkEquals(currFnc, lastFunctions[1][endStepState]));
} while (consecutiveNullSteps < stepStates.length && !checkEquals(currFnc, lastFunctions[0][endStepState]) && !checkEquals(currFnc, lastFunctions[1][endStepState]));
if (consecutiveNullSteps >= stepStates.length) {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", "Loop ended because " + consecutiveNullSteps + " >= " + stepStates.length);
} else if (checkEquals(currFnc, lastFunctions[0][endStepState])) {
@ -105,14 +104,15 @@ public class MathSolver {
private ObjectArrayList<Function> solveStep(ObjectArrayList<Function> fncs) throws InterruptedException, Error {
return solveStep(fncs, stepState);
}
private ObjectArrayList<Function> solveStep(ObjectArrayList<Function> fncs, AtomicInteger stepState) throws InterruptedException, Error {
ObjectArrayList<Function> processedFncs = applyRules(fncs, RuleType.EXISTENCE); // Apply existence rules before everything
private ObjectArrayList<Function> solveStep(ObjectArrayList<Function> fncs, AtomicInteger stepState)
throws InterruptedException, Error {
final ObjectArrayList<Function> processedFncs = applyRules(fncs, RuleType.EXISTENCE); // Apply existence rules before everything
if (processedFncs != null) {
fncs = processedFncs;
}
RuleType currentAcceptedRules;
switch(stepStates[stepState.get()]) {
switch (stepStates[stepState.get()]) {
case _1_CALCULATION: {
currentAcceptedRules = RuleType.CALCULATION;
break;
@ -133,8 +133,8 @@ public class MathSolver {
System.err.println("Unknown Step State");
throw new NotImplementedException();
}
ObjectArrayList<Function> results = applyRules(fncs, currentAcceptedRules);
switch(stepStates[stepState.get()]) {
final ObjectArrayList<Function> results = applyRules(fncs, currentAcceptedRules);
switch (stepStates[stepState.get()]) {
case _1_CALCULATION: {
if (results == null) {
stepState.incrementAndGet();
@ -195,17 +195,20 @@ public class MathSolver {
}
return null;
}
private ObjectArrayList<Function> applyRules(ObjectArrayList<Function> fncs, RuleType currentAcceptedRules) throws InterruptedException, Error {
ObjectArrayList<Rule> rules = initialFunction.getMathContext().getAcceptableRules(currentAcceptedRules);
private ObjectArrayList<Function> applyRules(ObjectArrayList<Function> fncs, RuleType currentAcceptedRules)
throws InterruptedException, Error {
final ObjectArrayList<Rule> rules = initialFunction.getMathContext().getAcceptableRules(currentAcceptedRules);
ObjectArrayList<Function> results = null;
Rule appliedRule = null;
out: {
for (Function fnc : fncs) {
for (Rule rule : rules) {
List<Function> ruleResults = fnc.simplify(rule);
for (final Function fnc : fncs) {
for (final Rule rule : rules) {
final List<Function> ruleResults = fnc.simplify(rule);
if (ruleResults != null && !ruleResults.isEmpty()) {
if (results == null) results = new ObjectArrayList<Function>();
if (results == null) {
results = new ObjectArrayList<>();
}
results.addAll(ruleResults);
appliedRule = rule;
break;