Started rewriting math screen and conversion logics

This commit is contained in:
XDrake99 2017-04-10 22:50:43 +02:00
parent b89883147b
commit c2df21d682
91 changed files with 1219 additions and 1015 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry excluding="org/warp/picalculator/deprecatedmath/|org/warp/picalculator/device/PIDisplay.java|org/warp/picalculator/device/graphicengine/Display.java" kind="src" path="src"/>
<classpathentry excluding="org/warp/picalculator/deprecatedmath/|org/warp/picalculator/device/PIDisplay.java|org/warp/picalculator/device/graphicengine/Display.java|com/rits/cloning/|com/rits/perspectives/|com/rits/|com/|org/warp/picalculator/TestCalcBenchmark.java" kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="src" path="res"/>
<classpathentry exported="true" kind="con" path="org.eclipse.jdt.USER_LIBRARY/JOGL"/>

BIN
res/draft2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

View File

@ -116,8 +116,7 @@ public class BMPFile extends Component {
final byte rgb[] = new byte[3];
size = (biWidth * biHeight) - 1;
pad = 4 - ((biWidth * 3) % 4);
if (pad == 4)
{
if (pad == 4) {
pad = 0; // <==== Bug correction
}
rowCount = 1;

View File

@ -14,6 +14,9 @@ public class Main {
public static Main instance;
public static boolean haxMode = true;
public static String[] args;
public static final String calculatorName = "WarpPI";
public static final String calculatorNameLOWER = "warppi";
public static final String calculatorNameUPPER = "WARPPI";
public Main(String[] args) throws InterruptedException {
this(new LoadingScreen(), args);
@ -23,7 +26,7 @@ public class Main {
instance = this;
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Thread.currentThread().setName("Main thread");
this.args = args;
Main.args = args;
beforeStart();
new DisplayManager(screen);
Utils.debug.println("Shutdown...");

View File

@ -7,22 +7,22 @@ public class TestCalcBenchmark {
public static void main(String[] args) throws Error {
Utils.debugOn = true;
int times = 1;
final int times = 1;
MathContext mc = new MathContext();
long time1 = System.nanoTime();
final MathContext mc = new MathContext();
final long time1 = System.nanoTime();
mc.parseInputString("5WABCDEFGHIWABCDEFGHIWABCDEFGHIWABCDEFGHIWABCDEFGHIWABCDEFGHI");
long time2 = System.nanoTime();
final long time2 = System.nanoTime();
for (int i = 0; i < times; i++) {
if (i == 1) {
Utils.debugOn = false;
}
mc.f2 = mc.solveExpression(mc.f);
}
long time3 = System.nanoTime();
final long time3 = System.nanoTime();
// System.out.println(mc.f2.get(0).toString());
System.out.println("PARSING\t"+((time2-time1) / 1000000d / ((double) times)) + " milliseconds");
System.out.println("WORK\t"+((time3-time2) / 1000000d / ((double) times)) + " milliseconds");
System.out.println("TOTAL\t"+((time3-time1) / 1000000d / ((double) times)) + " milliseconds");
System.out.println("PARSING\t" + ((time2 - time1) / 1000000d / (times)) + " milliseconds");
System.out.println("WORK\t" + ((time3 - time2) / 1000000d / (times)) + " milliseconds");
System.out.println("TOTAL\t" + ((time3 - time1) / 1000000d / (times)) + " milliseconds");
}
}

View File

@ -6,24 +6,24 @@ public class TestDrivers {
String className;
className = "jogamp.newt.driver.bcm.vc.iv.DisplayDriver";
if (exists(className)) {
System.out.println("[FOUND] "+className);
System.out.println("[FOUND] " + className);
} else {
System.out.println("[NOT FOUND] "+className);
System.out.println("[NOT FOUND] " + className);
}
className = ".bcm.vc.iv.DisplayDriver";
if (exists(className)) {
System.out.println("[FOUND] "+className);
System.out.println("[FOUND] " + className);
} else {
System.out.println("[NOT FOUND] "+className);
System.out.println("[NOT FOUND] " + className);
}
System.out.println("Test finished.");
}
public static boolean exists(String className) {
try {
Class.forName(className);
return true;
} catch( ClassNotFoundException e ) {
} catch (final ClassNotFoundException e) {
return false;
}
}

View File

@ -8,17 +8,14 @@ import org.warp.picalculator.gui.graphicengine.RenderingLoop;
import org.warp.picalculator.device.Keyboard;
import org.warp.picalculator.device.Keyboard.Key;
import org.warp.picalculator.device.KeyboardEventListener;
import org.warp.picalculator.gui.GUIErrorMessage;
import org.warp.picalculator.gui.expression.BlockContainer;
import org.warp.picalculator.gui.expression.containers.NormalInputContainer;
import org.warp.picalculator.gui.graphicengine.BinaryFont;
import org.warp.picalculator.gui.graphicengine.Skin;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.gui.graphicengine.gpu.GPUEngine;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.functions.Expression;
import org.warp.picalculator.math.functions.Root;
import org.warp.picalculator.math.parser.MathParser;
public class TestGPU {
@ -107,37 +104,37 @@ public class TestGPU {
case EQUAL:
Expression expr;
try {
expr = MathParser.parseInput(new MathContext(), c.root);
System.out.println("Parsed input:"+expr.toString());
} catch (Error e) {
expr = MathParser.parseInput(new MathContext(), c);
System.out.println("Parsed input:" + expr.toString());
} catch (final Error e) {
e.printStackTrace();
}
}
return false;
}
@Override
public boolean keyReleased(Key k) {
return false;
}
});
final Scene s = new Scene(d);
}
private static NormalInputContainer c = null;
private static class Scene implements RenderingLoop {
private BinaryFont exampleFont;
private final BinaryFont exampleFont;
private final Skin exampleSkin;
private final Renderer r;
private final GraphicEngine d;
private long lastTime = 0L;
public Scene(GraphicEngine d) throws IOException, Error {
this.d = d;
r = d.getRenderer();
@ -147,7 +144,6 @@ public class TestGPU {
exampleSkin = d.loadSkin("skin.png");
BlockContainer.initializeFonts(d.loadFont("ex"), d.loadFont("big"));
//New expression framework test
c = new NormalInputContainer(false, 0, 200);
@ -162,7 +158,7 @@ public class TestGPU {
c.typeChar('2');
c.typeChar('2');
c.recomputeDimensions();
d.start(this);
// fonts = new RAWFont[1];
@ -184,7 +180,7 @@ public class TestGPU {
System.exit(0);
}
}).start();
d.waitUntilExit();
}
@ -198,20 +194,20 @@ public class TestGPU {
exampleFont.use(d);
r.glColor3f(1, 0, 0);
r.glDrawStringLeft(10, 170, "Prova! 123456789 222");
//MSAA TEST
r.glDrawStringLeft(10f, 190.5f, "Test MSAA");
exampleSkin.use(d);
r.glColor3f(1.0f, 1.0f, 1.0f);
r.glFillRect(162, 2.5f, 160, 160, 0, 0, 16, 16);
//New expression framework test
if (lastTime == 0) {
lastTime = System.currentTimeMillis();
}
double delta = System.currentTimeMillis()-lastTime;
final double delta = System.currentTimeMillis() - lastTime;
lastTime = System.currentTimeMillis();
c.beforeRender((float) (delta/1000d));
c.beforeRender((float) (delta / 1000d));
c.draw(d, r, 10, 220);
}

View File

@ -37,8 +37,6 @@ import org.warp.picalculator.math.functions.Variable;
import org.warp.picalculator.math.functions.equations.Equation;
import org.warp.picalculator.math.functions.equations.EquationsSystemPart;
import com.rits.cloning.Cloner;
public class Utils {
public static final int scale = 24;
@ -52,8 +50,6 @@ public class Utils {
public static boolean debugOn;
public static boolean debugThirdScreen;
public static Cloner cloner = new Cloner();
public static final class DebugStream extends StringWriter {
public void println(String str) {
@ -123,7 +119,7 @@ public class Utils {
for (final char symbol : array) {
boolean contained = false;
for (final String smb : regexNormalSymbols) {
if ((smb).equals(symbol+"")) {
if ((smb).equals(symbol + "")) {
contained = true;
break;
}
@ -138,7 +134,7 @@ public class Utils {
if (regex != null) {
regex += "|" + symbol;
} else {
regex = symbol+"";
regex = symbol + "";
}
}
}
@ -198,7 +194,8 @@ public class Utils {
return true;
}
public static boolean areThereOnlySettedUpFunctionsSumsMultiplicationsEquationsAndSystems(ObjectArrayList<Function> fl) {
public static boolean areThereOnlySettedUpFunctionsSumsMultiplicationsEquationsAndSystems(
ObjectArrayList<Function> fl) {
for (int i = 0; i < fl.size(); i++) {
if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Multiplication || fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Subtraction || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) {
if (fl.get(i) instanceof FunctionSingle) {
@ -536,14 +533,13 @@ public class Utils {
}
return results;
}
public static Function[][] joinFunctionsResults(ObjectArrayList<ObjectArrayList<Function>> ln) {
final int[] sizes = new int[ln.size()];
for (int i = 0; i < ln.size(); i++) {
sizes[i] = ln.get(i).size();
}
int[] curs = new int[sizes.length];
final int[] curs = new int[sizes.length];
int total = 0;
for (int i = 0; i < ln.size(); i++) {
if (i == 0) {
@ -615,27 +611,27 @@ public class Utils {
public static void printSystemResourcesUsage() {
System.out.println("============");
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
for (final Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
method.setAccessible(true);
if (method.getName().startsWith("get") && Modifier.isPublic(method.getModifiers())) {
Object value;
try {
value = method.invoke(operatingSystemMXBean);
} catch (Exception e) {
} catch (final Exception e) {
value = e;
} // try
boolean percent = false;
boolean mb = false;
String displayName = method.getName();
String displayValue = value.toString();
final String displayName = method.getName();
final String displayValue = value.toString();
if (displayName.endsWith("CpuLoad")) {
percent = true;
}
if (displayName.endsWith("MemorySize")) {
mb = true;
}
ObjectArrayList<String> arr = new ObjectArrayList<>();
final ObjectArrayList<String> arr = new ObjectArrayList<>();
arr.add("getFreePhysicalMemorySize");
arr.add("getProcessCpuLoad");
arr.add("getSystemCpuLoad");
@ -643,14 +639,14 @@ public class Utils {
if (arr.contains(displayName)) {
if (percent) {
try {
System.out.println(displayName + " = " + (((int)(Float.parseFloat(displayValue) * 10000f))/100f) + "%");
}catch(Exception ex) {
System.out.println(displayName + " = " + (((int) (Float.parseFloat(displayValue) * 10000f)) / 100f) + "%");
} catch (final Exception ex) {
System.out.println(displayName + " = " + displayValue);
}
} else if (mb) {
try {
System.out.println(displayName + " = " + (Long.parseLong(displayValue) / 1024L / 1024L) + " MB");
}catch(Exception ex) {
} catch (final Exception ex) {
System.out.println(displayName + " = " + displayValue);
}
} else {
@ -664,21 +660,20 @@ public class Utils {
public static boolean isRunningOnRaspberry() {
if (System.getProperty("os.name").equals("Linux")) {
final File file = new File("/etc", "os-release");
try (FileInputStream fis = new FileInputStream(file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis))) {
String string;
while ((string = bufferedReader.readLine()) != null) {
if (string.toLowerCase().contains("raspbian")) {
if (string.toLowerCase().contains("name")) {
return true;
}
}
}
} catch (final Exception e) {
e.printStackTrace();
}
}
final File file = new File("/etc", "os-release");
try (FileInputStream fis = new FileInputStream(file); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis))) {
String string;
while ((string = bufferedReader.readLine()) != null) {
if (string.toLowerCase().contains("raspbian")) {
if (string.toLowerCase().contains("name")) {
return true;
}
}
}
} catch (final Exception e) {
e.printStackTrace();
}
}
return false;
}
}

View File

@ -0,0 +1,88 @@
package org.warp.picalculator.device;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;
import org.warp.picalculator.Main;
public class CacheFile {
private String path;
private ObjectOutputStream lastOOS;
private FileOutputStream lastFOS;
private ObjectInputStream lastOIS;
private FileInputStream lastFIS;
public CacheFile() {
do {
path = UUID.randomUUID().toString()+".ser";
} while (Files.exists(Paths.get(path)));
try {
Files.createTempFile(Main.calculatorNameLOWER, "");
} catch (IOException e) {
e.printStackTrace();
}
}
public ObjectOutputStream getObjectOutputStram() {
if (lastOOS == null) {
try {
return new ObjectOutputStream(new FileOutputStream(path));
} catch (IOException e) {
e.printStackTrace();
return lastOOS;
}
} else {
return lastOOS;
}
}
public ObjectInputStream getObjectInputStram() {
if (lastOIS == null) {
try {
return new ObjectInputStream(new FileInputStream(path));
} catch (IOException e) {
return lastOIS;
}
} else {
return lastOIS;
}
}
public void closeStreams() {
try {
if (lastOOS != null) {
lastOOS.close();
lastOOS = null;
}
if (lastFOS != null) {
lastFOS.close();
lastFOS = null;
}
if (lastOIS != null) {
lastOIS.close();
lastOIS = null;
}
if (lastFIS != null) {
lastFIS.close();
lastFIS = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void dispose() {
closeStreams();
try {
Files.deleteIfExists(Paths.get(path));
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -30,9 +30,9 @@ public class Keyboard {
private static volatile boolean[][] precedentStates = new boolean[8][8];
public static volatile boolean[][] debugKeysDown = new boolean[8][8];
public static volatile int debugKeyCode = -1;
private static volatile boolean refreshRequest = false;
private static KeyboardEventListener additionalListener;
public synchronized static void startKeyboard() {
@ -703,7 +703,7 @@ public class Keyboard {
if (additionalListener != null) {
try {
done = additionalListener.keyPressed(k);
} catch (Exception ex) {
} catch (final Exception ex) {
new GUIErrorMessage(ex);
}
}
@ -713,7 +713,7 @@ public class Keyboard {
boolean scrdone = false;
try {
scrdone = scr.keyPressed(k);
} catch (Exception ex) {
} catch (final Exception ex) {
new GUIErrorMessage(ex);
}
if (scr != null && scr.initialized && scrdone) {
@ -807,7 +807,7 @@ public class Keyboard {
Utils.debug.println("Key " + k.toString() + " ignored.");
}
}
public static void setAdditionalKeyboardListener(KeyboardEventListener l) {
additionalListener = l;
}

View File

@ -6,7 +6,7 @@ public interface KeyboardEventListener {
public default boolean keyPressed(Key k) {
return false;
}
public default boolean keyReleased(Key k) {
return false;
}

View File

@ -20,103 +20,102 @@ import org.warp.picalculator.Utils;
*/
public class RAWFont {
public boolean[][] rawchars;
public int[] chars32;
public int minBound = 10;
public int maxBound = 0;
public int charW;
public int charH;
public int charS;
public int charIntCount;
public static final int intBits = 31;
public boolean[][] rawchars;
public int[] chars32;
public int minBound = 10;
public int maxBound = 0;
public int charW;
public int charH;
public int charS;
public int charIntCount;
public static final int intBits = 31;
public void create(String name) {
try {
loadFont("/font_"+name+".rft");
} catch (IOException e) {
public void create(String name) {
try {
loadFont("/font_" + name + ".rft");
} catch (final IOException e) {
e.printStackTrace();
System.exit(1);
}
chars32 = new int[(maxBound-minBound)*charIntCount];
for (int charIndex = 0; charIndex < maxBound-minBound; charIndex++) {
boolean[] currentChar = rawchars[charIndex];
if (currentChar == null) {
int currentInt = 0;
int currentBit = 0;
for (int i = 0; i < charS; i++) {
if (currentInt*intBits+currentBit >= (currentInt+1)*intBits) {
currentInt += 1;
currentBit = 0;
}
chars32[charIndex*charIntCount+currentInt] = (chars32[charIndex*charIntCount+currentInt] << 1) + 1;
currentBit += 1;
}
} else {
int currentInt = 0;
int currentBit = 0;
for (int i = 0; i < charS; i++) {
if (currentBit >= intBits) {
currentInt += 1;
currentBit = 0;
}
chars32[charIndex*charIntCount+currentInt] = (chars32[charIndex*charIntCount+currentInt]) | ((currentChar[i] ? 1 : 0) << currentBit);
currentBit++;
}
}
}
Object obj = new Object();
WeakReference<Object> ref = new WeakReference<>(obj);
obj = null;
while (ref.get() != null) {
System.gc();
}
}
chars32 = new int[(maxBound - minBound) * charIntCount];
for (int charIndex = 0; charIndex < maxBound - minBound; charIndex++) {
final boolean[] currentChar = rawchars[charIndex];
if (currentChar == null) {
int currentInt = 0;
int currentBit = 0;
for (int i = 0; i < charS; i++) {
if (currentInt * intBits + currentBit >= (currentInt + 1) * intBits) {
currentInt += 1;
currentBit = 0;
}
chars32[charIndex * charIntCount + currentInt] = (chars32[charIndex * charIntCount + currentInt] << 1) + 1;
currentBit += 1;
}
} else {
int currentInt = 0;
int currentBit = 0;
for (int i = 0; i < charS; i++) {
if (currentBit >= intBits) {
currentInt += 1;
currentBit = 0;
}
chars32[charIndex * charIntCount + currentInt] = (chars32[charIndex * charIntCount + currentInt]) | ((currentChar[i] ? 1 : 0) << currentBit);
currentBit++;
}
}
}
Object obj = new Object();
final WeakReference<Object> ref = new WeakReference<>(obj);
obj = null;
while (ref.get() != null) {
System.gc();
}
}
private void loadFont(String string) throws IOException {
URL res = Main.instance.getClass().getResource(string);
int[] file = Utils.realBytes(Utils.convertStreamToByteArray(res.openStream(), res.getFile().length()));
int filelength = file.length;
final URL res = Main.instance.getClass().getResource(string);
final int[] file = Utils.realBytes(Utils.convertStreamToByteArray(res.openStream(), res.getFile().length()));
final int filelength = file.length;
if (filelength >= 16) {
if (file[0x0] == 114 && file[0x1] == 97 && file[0x2] == 119 && file[0x3] == 0xFF && file[0x8] == 0xFF && file[0xD] == 0xFF) {
charW = file[0x4] << 8 | file[0x5];
charH = file[0x6] << 8 | file[0x7];
charS = charW*charH;
charIntCount = (int) Math.ceil(((double)charS)/((double)intBits));
charS = charW * charH;
charIntCount = (int) Math.ceil(((double) charS) / ((double) intBits));
minBound = file[0x9] << 24 | file[0xA] << 16 | file[0xB] << 8 | file[0xC];
maxBound = file[0xE] << 24 | file[0xF] << 16 | file[0x10] << 8 | file[0x11];
if (maxBound <= minBound) {
maxBound = 10000; //TODO remove it: temp fix
}
rawchars = new boolean[maxBound-minBound][];
int index = 0x12;
while (index < filelength) {
try {
int charIndex = file[index] << 8 | file[index+1];
boolean[] rawchar = new boolean[charS];
int charbytescount = 0;
while (charbytescount*8 < charS) {
charbytescount+=1;
}
int currentBit = 0;
for (int i = 0; i <= charbytescount; i++) {
for (int bit = 0; bit < 8; bit++) {
if (currentBit >= charS) {
break;
}
rawchar[currentBit] = (((file[index + 2 + i] >> (8-1-bit)) & 0x1)==1)?true:false;
currentBit++;
}
}
rawchars[charIndex - minBound] = rawchar;
index += 2 + charbytescount;
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println(string);
System.exit(-1);
}
}
rawchars = new boolean[maxBound - minBound][];
int index = 0x12;
while (index < filelength) {
try {
final int charIndex = file[index] << 8 | file[index + 1];
final boolean[] rawchar = new boolean[charS];
int charbytescount = 0;
while (charbytescount * 8 < charS) {
charbytescount += 1;
}
int currentBit = 0;
for (int i = 0; i <= charbytescount; i++) {
for (int bit = 0; bit < 8; bit++) {
if (currentBit >= charS) {
break;
}
rawchar[currentBit] = (((file[index + 2 + i] >> (8 - 1 - bit)) & 0x1) == 1) ? true : false;
currentBit++;
}
}
rawchars[charIndex - minBound] = rawchar;
index += 2 + charbytescount;
} catch (final Exception ex) {
ex.printStackTrace();
System.out.println(string);
System.exit(-1);
}
}
} else {
throw new IOException();
}
@ -126,56 +125,55 @@ public class RAWFont {
}
public int[] getCharIndexes(String txt) {
final int l = txt.length();
int[] indexes = new int[l];
char[] chars = txt.toCharArray();
for (int i = 0; i < l; i++) {
indexes[i] = (chars[i] & 0xFFFF)-minBound;
}
return indexes;
}
final int l = txt.length();
final int[] indexes = new int[l];
final char[] chars = txt.toCharArray();
for (int i = 0; i < l; i++) {
indexes[i] = (chars[i] & 0xFFFF) - minBound;
}
return indexes;
}
@SuppressWarnings("unused")
@SuppressWarnings("unused")
private void saveArray(int[] screen, String coutputpng) {
BufferedImage bi = new BufferedImage(300, 200, BufferedImage.TYPE_INT_RGB);
final int[] a = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData();
System.arraycopy(screen, 0, a, 0, screen.length);
try {
ImageIO.write(bi, "PNG", new File(coutputpng));
} catch (IOException ex) {
Logger.getLogger(RAWFont.class.getName()).log(Level.SEVERE, null, ex);
}
}
final BufferedImage bi = new BufferedImage(300, 200, BufferedImage.TYPE_INT_RGB);
final int[] a = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData();
System.arraycopy(screen, 0, a, 0, screen.length);
try {
ImageIO.write(bi, "PNG", new File(coutputpng));
} catch (final IOException ex) {
Logger.getLogger(RAWFont.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void drawText(int[] screen, int[] screenSize, int x, int y, int[] text, int color) {
final int screenLength = screen.length;
int screenPos = 0;
int currentInt;
int currentIntBitPosition;
int bitData;
int cpos;
int j;
final int l = text.length;
for (int i = 0; i < l; i++) {
cpos = (i * (charW + 1));
final int charIndex = text[i];
for (int dy = 0; dy < charH; dy++) {
for (int dx = 0; dx < charW; dx++) {
j = x + cpos + dx;
if (j > 0 & j < screenSize[0]) {
int bit = dx + dy * charW;
currentInt = (int) (Math.floor(bit)/(intBits));
currentIntBitPosition = bit-(currentInt*intBits);
bitData = (chars32[charIndex*charIntCount+currentInt] >> currentIntBitPosition) & 1;
screenPos = x + cpos + dx + (y + dy) * screenSize[0];
if (bitData == 1 & screenLength > screenPos) {
screen[screenPos] = color;
}
}
}
}
}
}
public void drawText(int[] screen, int[] screenSize, int x, int y, int[] text, int color) {
final int screenLength = screen.length;
int screenPos = 0;
int currentInt;
int currentIntBitPosition;
int bitData;
int cpos;
int j;
final int l = text.length;
for (int i = 0; i < l; i++) {
cpos = (i * (charW + 1));
final int charIndex = text[i];
for (int dy = 0; dy < charH; dy++) {
for (int dx = 0; dx < charW; dx++) {
j = x + cpos + dx;
if (j > 0 & j < screenSize[0]) {
final int bit = dx + dy * charW;
currentInt = (int) (Math.floor(bit) / (intBits));
currentIntBitPosition = bit - (currentInt * intBits);
bitData = (chars32[charIndex * charIntCount + currentInt] >> currentIntBitPosition) & 1;
screenPos = x + cpos + dx + (y + dy) * screenSize[0];
if (bitData == 1 & screenLength > screenPos) {
screen[screenPos] = color;
}
}
}
}
}
}
}

View File

@ -1,10 +1,6 @@
package org.warp.picalculator.gui;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Main;
@ -357,7 +353,7 @@ public final class DisplayManager implements RenderingLoop {
Main.screenSize[1] = engine.getHeight();
}
};
public void loop() {
try {
load_skin();
@ -373,7 +369,7 @@ public final class DisplayManager implements RenderingLoop {
}
//Working thread
Thread workThread = new Thread(() -> {
final Thread workThread = new Thread(() -> {
try {
while (true) {
float dt = 0;
@ -388,7 +384,7 @@ public final class DisplayManager implements RenderingLoop {
* Calcoli
*/
checkDisplayResized();
screen.beforeRender(dt);
Thread.sleep(50);
@ -449,9 +445,9 @@ public final class DisplayManager implements RenderingLoop {
workThread.setDaemon(true);
workThread.setName("Work thread");
workThread.start();
engine.start(getDrawable());
engine.waitUntilExit();
} catch (final Exception ex) {
ex.printStackTrace();
@ -488,13 +484,13 @@ public final class DisplayManager implements RenderingLoop {
public static float getBrightness() {
return brightness;
}
public static int currentSession = 0;
public static Screen[] sessions = new Screen[5];
@Deprecated
public static void colore(float f1, float f2, float f3, float f4) {
renderer.glColor4f(f1,f2,f3,f4);
renderer.glColor4f(f1, f2, f3, f4);
}
public static RenderingLoop getDrawable() {
@ -503,6 +499,6 @@ public final class DisplayManager implements RenderingLoop {
@Deprecated
public static void drawSkinPart(int x, int y, int uvX, int uvY, int uvX2, int uvY2) {
renderer.glFillRect(x, y, uvX2-uvX, uvY2-uvY, uvX, uvY, uvX2-uvX, uvY2-uvY);
renderer.glFillRect(x, y, uvX2 - uvX, uvY2 - uvY, uvX, uvY, uvX2 - uvX, uvY2 - uvY);
}
}

View File

@ -6,30 +6,30 @@ import org.warp.picalculator.Error;
public class GUIErrorMessage {
private String err;
private long creationTime;
private final String err;
private final long creationTime;
public GUIErrorMessage(Error e) {
this.err = e.getLocalizedMessage();
this.creationTime = System.currentTimeMillis();
err = e.getLocalizedMessage();
creationTime = System.currentTimeMillis();
}
public GUIErrorMessage(Exception ex) {
err = ex.getLocalizedMessage();
this.creationTime = System.currentTimeMillis();
creationTime = System.currentTimeMillis();
}
public void draw(GraphicEngine g, Renderer r, String msg) {
int scrW = g.getWidth();
int scrH = g.getHeight();
int width = 200;
int height = 20;
int margin = 4;
final int scrW = g.getWidth();
final int scrH = g.getHeight();
final int width = 200;
final int height = 20;
final int margin = 4;
r.glClearSkin();
r.glColor(0x00000000);
r.glFillRect(scrW-width-margin, scrH-height-margin, width, height, 0, 0, 0, 0);
r.glFillRect(scrW - width - margin, scrH - height - margin, width, height, 0, 0, 0, 0);
}
public long getCreationTime() {
return creationTime;
}

View File

@ -1,60 +1,53 @@
package org.warp.picalculator.gui;
public class GraphicUtils {
public static final float sin(float rad)
{
return sin[(int) (rad * radToIndex) & SIN_MASK];
}
public static final float sin(float rad) {
return sin[(int) (rad * radToIndex) & SIN_MASK];
}
public static final float cos(float rad)
{
return cos[(int) (rad * radToIndex) & SIN_MASK];
}
public static final float cos(float rad) {
return cos[(int) (rad * radToIndex) & SIN_MASK];
}
public static final float sinDeg(float deg)
{
return sin[(int) (deg * degToIndex) & SIN_MASK];
}
public static final float sinDeg(float deg) {
return sin[(int) (deg * degToIndex) & SIN_MASK];
}
public static final float cosDeg(float deg)
{
return cos[(int) (deg * degToIndex) & SIN_MASK];
}
public static final float cosDeg(float deg) {
return cos[(int) (deg * degToIndex) & SIN_MASK];
}
private static final float RAD,DEG;
private static final int SIN_BITS,SIN_MASK,SIN_COUNT;
private static final float radFull,radToIndex;
private static final float degFull,degToIndex;
private static final float[] sin, cos;
private static final float RAD, DEG;
private static final int SIN_BITS, SIN_MASK, SIN_COUNT;
private static final float radFull, radToIndex;
private static final float degFull, degToIndex;
private static final float[] sin, cos;
static
{
RAD = (float) Math.PI / 180.0f;
DEG = 180.0f / (float) Math.PI;
static {
RAD = (float) Math.PI / 180.0f;
DEG = 180.0f / (float) Math.PI;
SIN_BITS = 12;
SIN_MASK = ~(-1 << SIN_BITS);
SIN_COUNT = SIN_MASK + 1;
SIN_BITS = 12;
SIN_MASK = ~(-1 << SIN_BITS);
SIN_COUNT = SIN_MASK + 1;
radFull = (float) (Math.PI * 2.0);
degFull = (float) (360.0);
radToIndex = SIN_COUNT / radFull;
degToIndex = SIN_COUNT / degFull;
radFull = (float) (Math.PI * 2.0);
degFull = (float) (360.0);
radToIndex = SIN_COUNT / radFull;
degToIndex = SIN_COUNT / degFull;
sin = new float[SIN_COUNT];
cos = new float[SIN_COUNT];
sin = new float[SIN_COUNT];
cos = new float[SIN_COUNT];
for (int i = 0; i < SIN_COUNT; i++)
{
sin[i] = (float) Math.sin((i + 0.5f) / SIN_COUNT * radFull);
cos[i] = (float) Math.cos((i + 0.5f) / SIN_COUNT * radFull);
}
for (int i = 0; i < SIN_COUNT; i++) {
sin[i] = (float) Math.sin((i + 0.5f) / SIN_COUNT * radFull);
cos[i] = (float) Math.cos((i + 0.5f) / SIN_COUNT * radFull);
}
// Four cardinal directions (credits: Nate)
for (int i = 0; i < 360; i += 90)
{
sin[(int)(i * degToIndex) & SIN_MASK] = (float)Math.sin(i * Math.PI / 180.0);
cos[(int)(i * degToIndex) & SIN_MASK] = (float)Math.cos(i * Math.PI / 180.0);
}
}
// Four cardinal directions (credits: Nate)
for (int i = 0; i < 360; i += 90) {
sin[(int) (i * degToIndex) & SIN_MASK] = (float) Math.sin(i * Math.PI / 180.0);
cos[(int) (i * degToIndex) & SIN_MASK] = (float) Math.cos(i * Math.PI / 180.0);
}
}
}

View File

@ -3,25 +3,28 @@ package org.warp.picalculator.gui;
public interface GraphicalElement {
/**
* Recompute element's dimension parameters, like <strong>width</strong>, <strong>height</strong>, <strong>line</strong> or <strong>length</strong>.
* Recompute element's dimension parameters, like <strong>width</strong>,
* <strong>height</strong>, <strong>line</strong> or
* <strong>length</strong>.
*/
public void recomputeDimensions();
/**
*
* @return Width of the element.
*/
public int getWidth();
/**
*
* @return Height of the element.
*/
public int getHeight();
/**
*
* @return Position of the vertical alignment line of the element, relative to itself.
* @return Position of the vertical alignment line of the element, relative
* to itself.
*/
public int getLine();
}

View File

@ -3,21 +3,23 @@ package org.warp.picalculator.gui.expression;
import org.warp.picalculator.gui.GraphicalElement;
import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer;
import org.warp.picalculator.math.parser.features.interfaces.Feature;
public abstract class Block implements GraphicalElement {
protected boolean small;
protected int width;
protected int height;
protected int line;
/**
*
* @param r Graphic Renderer class.
* @param x Position relative to the window.
* @param y Position relative to the window.
* @param small
* @param r
* Graphic Renderer class.
* @param x
* Position relative to the window.
* @param y
* Position relative to the window.
* @param small
*/
public abstract void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret);
@ -29,7 +31,7 @@ public abstract class Block implements GraphicalElement {
public abstract void recomputeDimensions();
public abstract int computeCaretMaxBound();
@Override
public int getWidth() {
return width;
@ -50,6 +52,6 @@ public abstract class Block implements GraphicalElement {
}
public abstract void setSmall(boolean small);
public abstract int getClassID();
}

View File

@ -2,15 +2,13 @@ package org.warp.picalculator.gui.expression;
import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer;
import org.warp.picalculator.math.parser.features.FeatureChar;
import org.warp.picalculator.math.parser.features.interfaces.Feature;
public class BlockChar extends Block {
public static final int CLASS_ID = 0x00000001;
private final char ch;
public BlockChar(char ch) {
this.ch = ch;
recomputeDimensions();
@ -32,12 +30,12 @@ public class BlockChar extends Block {
public boolean delBlock(Caret caret) {
return false;
}
@Override
public void recomputeDimensions() {
width = BlockContainer.getDefaultCharWidth(small);
height = BlockContainer.getDefaultCharHeight(small);
line = height/2;
line = height / 2;
}
@Override
@ -45,7 +43,7 @@ public class BlockChar extends Block {
this.small = small;
recomputeDimensions();
}
public char getChar() {
return ch;
}

View File

@ -10,7 +10,7 @@ import org.warp.picalculator.gui.graphicengine.Renderer;
public class BlockContainer implements GraphicalElement {
private static boolean initialized = false;
private final int minWidth;
private final int minHeight;
private final ObjectArrayList<Block> content;
@ -19,29 +19,29 @@ public class BlockContainer implements GraphicalElement {
private int height;
private int line;
public final boolean withBorder;
public BlockContainer() {
this(false, BlockContainer.getDefaultCharWidth(false), BlockContainer.getDefaultCharHeight(false), true);
}
public BlockContainer(boolean small) {
this(small, BlockContainer.getDefaultCharWidth(small), BlockContainer.getDefaultCharHeight(small), true);
}
public BlockContainer(boolean small, boolean withBorder) {
this(small, BlockContainer.getDefaultCharWidth(small), BlockContainer.getDefaultCharHeight(small), withBorder);
}
public BlockContainer(boolean small, int minWidth, int minHeight, boolean withBorder) {
this(small, minWidth, minHeight, new ObjectArrayList<>(), withBorder);
}
public BlockContainer(boolean small, int minWidth, int minHeight, ObjectArrayList<Block> content, boolean withBorder) {
this.small = small;
this.minWidth = minWidth;
this.minHeight = minHeight;
this.withBorder = withBorder;
for (Block b: content) {
for (final Block b : content) {
if (b.isSmall() != small) {
b.setSmall(small);
}
@ -61,13 +61,17 @@ public class BlockContainer implements GraphicalElement {
}
recomputeDimensions();
}
public void appendBlock(Block b) {
appendBlockUnsafe(b);
recomputeDimensions();
}
public void appendBlockUnsafe(Block b) {
if (b.isSmall() != small) {
b.setSmall(small);
}
content.add(b);
recomputeDimensions();
}
public void removeBlock(Block b) {
@ -79,46 +83,53 @@ public class BlockContainer implements GraphicalElement {
content.remove(i);
recomputeDimensions();
}
public Block getBlockAt(int i) {
return content.get(i);
}
public void clear() {
content.clear();
recomputeDimensions();
}
/**
*
* @param ge Graphic Engine class.
* @param r Graphic Renderer class of <b>ge</b>.
* @param x Position relative to the window.
* @param y Position relative to the window.
* @param caret Position of the caret.
* @param ge
* Graphic Engine class.
* @param r
* Graphic Renderer class of <b>ge</b>.
* @param x
* Position relative to the window.
* @param y
* Position relative to the window.
* @param caret
* Position of the caret.
*/
public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) {
int paddingX = 1;
if (caret.getRemaining() == 0) {
if (content.size() > 0) {
BlockContainer.drawCaret(ge, r, caret, x, y+line-content.get(0).line, content.get(0).height);
BlockContainer.drawCaret(ge, r, caret, x, y + line - content.get(0).line, content.get(0).height);
} else {
BlockContainer.drawCaret(ge, r, caret, x, y, height);
}
}
if (withBorder && content.size() == 0) {
r.glDrawLine(x+paddingX, y, x+paddingX+width-1, y);
r.glDrawLine(x+paddingX, y, x+paddingX, y+height-1);
r.glDrawLine(x+paddingX+width-1, y, x+paddingX+width-1, y+height-1);
r.glDrawLine(x+paddingX, y+height-1, x+paddingX+width-1, y+height-1);
r.glDrawLine(x + paddingX, y, x + paddingX + width - 1, y);
r.glDrawLine(x + paddingX, y, x + paddingX, y + height - 1);
r.glDrawLine(x + paddingX + width - 1, y, x + paddingX + width - 1, y + height - 1);
r.glDrawLine(x + paddingX, y + height - 1, x + paddingX + width - 1, y + height - 1);
} else {
for (Block b : content) {
for (final Block b : content) {
caret.skip(1);
b.draw(ge, r, x+paddingX, y+line-b.line, caret);
b.draw(ge, r, x + paddingX, y + line - b.line, caret);
paddingX += b.getWidth();
if (caret.getRemaining() == 0) BlockContainer.drawCaret(ge, r, caret, x + paddingX, y+line-b.line, b.height);
if (caret.getRemaining() == 0) {
BlockContainer.drawCaret(ge, r, caret, x + paddingX, y + line - b.line, b.height);
}
paddingX += 1;
}
}
@ -129,17 +140,17 @@ public class BlockContainer implements GraphicalElement {
boolean added = false;
if (caret.getRemaining() == 0) {
this.addBlock(0, newBlock);
addBlock(0, newBlock);
added = true;
}
int pos = 0;
for (Block b : content) {
for (final Block b : content) {
caret.skip(1);
pos++;
added = added|b.putBlock(caret, newBlock);
added = added | b.putBlock(caret, newBlock);
if (caret.getRemaining() == 0) {
this.addBlock(pos, newBlock);
addBlock(pos, newBlock);
added = true;
}
}
@ -152,16 +163,16 @@ public class BlockContainer implements GraphicalElement {
public boolean delBlock(Caret caret) {
boolean removed = false;
int pos = 0;
for (Block b : content) {
for (final Block b : content) {
caret.skip(1);
pos++;
int deltaCaret = caret.getRemaining();
removed = removed|b.delBlock(caret);
final int deltaCaret = caret.getRemaining();
removed = removed | b.delBlock(caret);
if (caret.getRemaining() == 0 || (removed == false && deltaCaret >= 0 && caret.getRemaining() < 0)) {
this.removeAt(pos-1);
caret.setPosition(caret.getPosition()-deltaCaret);
removeAt(pos - 1);
caret.setPosition(caret.getPosition() - deltaCaret);
removed = true;
}
}
@ -172,15 +183,14 @@ public class BlockContainer implements GraphicalElement {
return removed;
}
@Override
public void recomputeDimensions() {
int l = 0; //Line
int w = 0; //Width
int h2 = 0; //Height under the line. h = h2 + l
int h = 0; //Height
for (Block b : content) {
for (final Block b : content) {
w += b.getWidth() + 1;
final int bl = b.getLine();
final int bh = b.getHeight();
@ -192,11 +202,11 @@ public class BlockContainer implements GraphicalElement {
h2 = bh2;
}
}
if (content.size() > 0) {
w -= 1;
}
h = h2 + l;
line = l;
@ -209,7 +219,7 @@ public class BlockContainer implements GraphicalElement {
height = h;
} else {
height = minHeight;
line = height/2;
line = height / 2;
}
}
@ -231,7 +241,7 @@ public class BlockContainer implements GraphicalElement {
private static final BinaryFont[] defFonts = new BinaryFont[2];
private static final int[] defFontSizes = new int[4];
private static final int defColor = 0xFF000000;
public static void initializeFonts(BinaryFont big, BinaryFont small) {
defFonts[0] = big;
defFonts[1] = small;
@ -241,10 +251,10 @@ public class BlockContainer implements GraphicalElement {
defFontSizes[3] = small.getCharacterHeight();
initialized = true;
}
public static BinaryFont getDefaultFont(boolean small) {
checkInitialized();
return defFonts[small?1:0];
return defFonts[small ? 1 : 0];
}
public static int getDefaultColor() {
@ -253,20 +263,20 @@ public class BlockContainer implements GraphicalElement {
public static int getDefaultCharWidth(boolean b) {
checkInitialized();
return defFontSizes[b?2:0];
return defFontSizes[b ? 2 : 0];
}
public static int getDefaultCharHeight(boolean b) {
checkInitialized();
return defFontSizes[b?3:1];
return defFontSizes[b ? 3 : 1];
}
public static void drawCaret(GraphicEngine ge, Renderer r, Caret caret, int x, int y, int height) {
if (caret.getState() == CaretState.VISIBLE_ON) {
r.glColor(getDefaultColor());
r.glDrawLine(x, y, x, y-1+height);
r.glDrawLine(x+1, y, x+1, y-1+height);
r.glDrawLine(x+2, y, x+2, y-1+height);
r.glDrawLine(x, y, x, y - 1 + height);
r.glDrawLine(x + 1, y, x + 1, y - 1 + height);
r.glDrawLine(x + 2, y, x + 2, y - 1 + height);
}
}
@ -278,17 +288,19 @@ public class BlockContainer implements GraphicalElement {
public ObjectArrayList<Block> getContent() {
return content.clone();
}
private static void checkInitialized() {
if (!initialized) throw new ExceptionInInitializerError("Please initialize BlockContainer by running the method BlockContainer.initialize(...) first!");
if (!initialized) {
throw new ExceptionInInitializerError("Please initialize BlockContainer by running the method BlockContainer.initialize(...) first!");
}
}
public int computeCaretMaxBound() {
int maxpos = 0;
for (Block b : content) {
maxpos+=1+b.computeCaretMaxBound();
for (final Block b : content) {
maxpos += 1 + b.computeCaretMaxBound();
}
return maxpos+1;
return maxpos + 1;
}
}

View File

@ -1,14 +1,10 @@
package org.warp.picalculator.gui.expression;
import org.warp.picalculator.Main;
import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer;
import org.warp.picalculator.math.parser.features.interfaces.Feature;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class BlockDivision extends Block {
public static final int CLASS_ID = 0x00000002;
private final BlockContainer containerUp;
@ -17,10 +13,10 @@ public class BlockDivision extends Block {
private int paddingLeftUpper;
private int paddingLeftLower;
private int h1;
public BlockDivision() {
this.containerUp = new BlockContainer(false);
this.containerDown = new BlockContainer(false);
containerUp = new BlockContainer(false);
containerDown = new BlockContainer(false);
recomputeDimensions();
}
@ -28,16 +24,16 @@ public class BlockDivision extends Block {
public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) {
BlockContainer.getDefaultFont(small).use(ge);
r.glColor(BlockContainer.getDefaultColor());
containerUp.draw(ge, r, x+1+paddingLeftUpper, y, caret);
r.glDrawLine(x, y+h1+1, x+width-1, y+h1+1);
containerDown.draw(ge, r, x+1+paddingLeftLower, y + h1+3, caret);
containerUp.draw(ge, r, x + 1 + paddingLeftUpper, y, caret);
r.glDrawLine(x, y + h1 + 1, x + width - 1, y + h1 + 1);
containerDown.draw(ge, r, x + 1 + paddingLeftLower, y + h1 + 3, caret);
}
@Override
public boolean putBlock(Caret caret, Block newBlock) {
boolean added = false;
added = added|containerUp.putBlock(caret, newBlock);
added = added|containerDown.putBlock(caret, newBlock);
added = added | containerUp.putBlock(caret, newBlock);
added = added | containerDown.putBlock(caret, newBlock);
if (added) {
recomputeDimensions();
}
@ -47,8 +43,8 @@ public class BlockDivision extends Block {
@Override
public boolean delBlock(Caret caret) {
boolean removed = false;
removed = removed|containerUp.delBlock(caret);
removed = removed|containerDown.delBlock(caret);
removed = removed | containerUp.delBlock(caret);
removed = removed | containerDown.delBlock(caret);
if (removed) {
recomputeDimensions();
}
@ -61,9 +57,9 @@ public class BlockDivision extends Block {
final int w2 = containerDown.getWidth();
final int h1 = containerUp.getHeight();
final int h2 = containerDown.getHeight();
width = (w1>w2?w1:w2) + 4;
height = h1+3+h2;
line = h1+1;
width = (w1 > w2 ? w1 : w2) + 4;
height = h1 + 3 + h2;
line = h1 + 1;
this.h1 = h1;
if (w1 != w2) {
if (w1 > w2) {
@ -82,15 +78,15 @@ public class BlockDivision extends Block {
@Override
public void setSmall(boolean small) {
this.small = small;
this.containerUp.setSmall(small);
this.containerDown.setSmall(small);
containerUp.setSmall(small);
containerDown.setSmall(small);
recomputeDimensions();
}
public BlockContainer getUpperContainer() {
return containerUp;
}
public BlockContainer getLowerContainer() {
return containerDown;
}
@ -102,6 +98,6 @@ public class BlockDivision extends Block {
@Override
public int computeCaretMaxBound() {
return containerUp.computeCaretMaxBound()+containerDown.computeCaretMaxBound();
return containerUp.computeCaretMaxBound() + containerDown.computeCaretMaxBound();
}
}

View File

@ -4,27 +4,27 @@ import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer;
public class BlockParenthesis extends Block {
public static final int CLASS_ID = 0x00000004;
private final BlockContainer containerNumber;
public BlockParenthesis() {
this.containerNumber = new BlockContainer(false);
containerNumber = new BlockContainer(false);
recomputeDimensions();
}
@Override
public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) {
BlockContainer.getDefaultFont(small).use(ge);
r.glColor(BlockContainer.getDefaultColor());
containerNumber.draw(ge, r, x+7, y+3, caret);
containerNumber.draw(ge, r, x + 7, y + 3, caret);
}
@Override
public boolean putBlock(Caret caret, Block newBlock) {
boolean added = false;
added = added|containerNumber.putBlock(caret, newBlock);
added = added | containerNumber.putBlock(caret, newBlock);
if (added) {
recomputeDimensions();
}
@ -34,7 +34,7 @@ public class BlockParenthesis extends Block {
@Override
public boolean delBlock(Caret caret) {
boolean removed = false;
removed = removed|containerNumber.delBlock(caret);
removed = removed | containerNumber.delBlock(caret);
if (removed) {
recomputeDimensions();
}
@ -43,15 +43,15 @@ public class BlockParenthesis extends Block {
@Override
public void recomputeDimensions() {
this.width = containerNumber.getWidth()+BlockContainer.getDefaultCharWidth(small)*2;
this.height = containerNumber.getHeight();
this.line = containerNumber.getLine();
width = containerNumber.getWidth() + BlockContainer.getDefaultCharWidth(small) * 2;
height = containerNumber.getHeight();
line = containerNumber.getLine();
}
@Override
public void setSmall(boolean small) {
this.small = small;
this.containerNumber.setSmall(small);
containerNumber.setSmall(small);
recomputeDimensions();
}

View File

@ -1,22 +1,18 @@
package org.warp.picalculator.gui.expression;
import org.warp.picalculator.Main;
import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer;
import org.warp.picalculator.math.parser.features.interfaces.Feature;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class BlockSquareRoot extends Block {
public static final int CLASS_ID = 0x00000003;
private final BlockContainer containerNumber;
private int h1;
public BlockSquareRoot() {
this.containerNumber = new BlockContainer(false);
containerNumber = new BlockContainer(false);
recomputeDimensions();
}
@ -24,21 +20,21 @@ public class BlockSquareRoot extends Block {
public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) {
BlockContainer.getDefaultFont(small).use(ge);
r.glColor(BlockContainer.getDefaultColor());
r.glDrawLine(x, y+height-10+1, x, y+height-10+2); // /
r.glDrawLine(x+1, y+height-10, x+1, y+height-10+1); // /
r.glDrawLine(x+2, y+height-10+2, x+2, y+height-10+6); // \
r.glDrawLine(x+3, y+height-10+7, x+3, y+height-10+9); // \
r.glDrawLine(x+5, y+height-h1-1-2, x+width-1, y+height-h1-1-2); // ----
r.glDrawLine(x+5, y+height-h1-1-2, x+5, y+height-(h1-2)/3f*2f-1); // |
r.glDrawLine(x+4, y+height-(h1-2)/3f*2f-1, x+4, y+height-(h1-2)/3f-1); // |
r.glDrawLine(x+3, y+height-(h1-2)/3f-1, x+3, y+height-1); // |
containerNumber.draw(ge, r, x+7, y+3, caret);
r.glDrawLine(x, y + height - 10 + 1, x, y + height - 10 + 2); // /
r.glDrawLine(x + 1, y + height - 10, x + 1, y + height - 10 + 1); // /
r.glDrawLine(x + 2, y + height - 10 + 2, x + 2, y + height - 10 + 6); // \
r.glDrawLine(x + 3, y + height - 10 + 7, x + 3, y + height - 10 + 9); // \
r.glDrawLine(x + 5, y + height - h1 - 1 - 2, x + width - 1, y + height - h1 - 1 - 2); // ----
r.glDrawLine(x + 5, y + height - h1 - 1 - 2, x + 5, y + height - (h1 - 2) / 3f * 2f - 1); // |
r.glDrawLine(x + 4, y + height - (h1 - 2) / 3f * 2f - 1, x + 4, y + height - (h1 - 2) / 3f - 1); // |
r.glDrawLine(x + 3, y + height - (h1 - 2) / 3f - 1, x + 3, y + height - 1); // |
containerNumber.draw(ge, r, x + 7, y + 3, caret);
}
@Override
public boolean putBlock(Caret caret, Block newBlock) {
boolean added = false;
added = added|containerNumber.putBlock(caret, newBlock);
added = added | containerNumber.putBlock(caret, newBlock);
if (added) {
recomputeDimensions();
}
@ -48,7 +44,7 @@ public class BlockSquareRoot extends Block {
@Override
public boolean delBlock(Caret caret) {
boolean removed = false;
removed = removed|containerNumber.delBlock(caret);
removed = removed | containerNumber.delBlock(caret);
if (removed) {
recomputeDimensions();
}
@ -60,19 +56,19 @@ public class BlockSquareRoot extends Block {
final int w1 = containerNumber.getWidth();
h1 = containerNumber.getHeight();
final int l1 = containerNumber.getLine();
width = 8+w1+2;
height = 3+h1;
line = 3+l1;
width = 8 + w1 + 2;
height = 3 + h1;
line = 3 + l1;
if (height < 9) {
height = 9;
line+=(9-(3+h1));
line += (9 - (3 + h1));
}
}
@Override
public void setSmall(boolean small) {
this.small = small;
this.containerNumber.setSmall(small);
containerNumber.setSmall(small);
recomputeDimensions();
}

View File

@ -5,45 +5,45 @@ public class Caret {
private int pos;
private int remaining;
private CaretState state;
public Caret(CaretState state, int pos) {
this.state = state;
this.pos = pos;
this.remaining = pos;
remaining = pos;
}
public void skip(int i) {
remaining-=i;
remaining -= i;
}
public int getPosition() {
return pos;
}
public int getRemaining() {
return remaining;
}
public CaretState getState() {
return state;
}
public void flipState() {
if (this.state == CaretState.VISIBLE_ON) {
this.state = CaretState.VISIBLE_OFF;
} else if (this.state == CaretState.VISIBLE_OFF) {
this.state = CaretState.VISIBLE_ON;
if (state == CaretState.VISIBLE_ON) {
state = CaretState.VISIBLE_OFF;
} else if (state == CaretState.VISIBLE_OFF) {
state = CaretState.VISIBLE_ON;
}
}
public void turnOn() {
if (this.state == CaretState.VISIBLE_OFF) {
this.state = CaretState.VISIBLE_ON;
if (state == CaretState.VISIBLE_OFF) {
state = CaretState.VISIBLE_ON;
}
}
public void setPosition(int i) {
this.pos = i;
pos = i;
}
public void resetRemaining() {

View File

@ -1,7 +1,5 @@
package org.warp.picalculator.gui.expression;
public enum CaretState {
VISIBLE_ON,
VISIBLE_OFF,
HIDDEN
VISIBLE_ON, VISIBLE_OFF, HIDDEN
}

View File

@ -5,19 +5,19 @@ import org.warp.picalculator.gui.expression.BlockChar;
import org.warp.picalculator.math.MathematicalSymbols;
public class InlineInputContainer extends InputContainer {
public InlineInputContainer() {
super();
}
public InlineInputContainer(boolean small) {
super(small);
}
public InlineInputContainer(boolean small, int minWidth, int minHeight) {
super(small, minWidth, minHeight);
}
@Override
public Block parseChar(char c) {
return new BlockChar(MathematicalSymbols.DIVISION);

View File

@ -1,5 +1,8 @@
package org.warp.picalculator.gui.expression.containers;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.warp.picalculator.gui.GraphicalElement;
import org.warp.picalculator.gui.expression.Block;
import org.warp.picalculator.gui.expression.BlockContainer;
@ -9,42 +12,47 @@ import org.warp.picalculator.gui.expression.layouts.InputLayout;
import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer;
public abstract class InputContainer implements GraphicalElement, InputLayout {
public final BlockContainer root;
import it.unimi.dsi.fastutil.Arrays;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public abstract class InputContainer implements GraphicalElement, InputLayout, Serializable {
private static final long serialVersionUID = 923589369317765667L;
private final BlockContainer root;
private Caret caret;
private static final float CARET_DURATION = 0.5f;
private float caretTime;
private int maxPosition = 0;
private boolean parsed = false;
public InputContainer() {
caret = new Caret(CaretState.VISIBLE_ON, 0);
root = new BlockContainer(false, false);
}
public InputContainer(boolean small) {
caret = new Caret(CaretState.VISIBLE_ON, 0);
root = new BlockContainer(small, false);
}
public InputContainer(boolean small, int minWidth, int minHeight) {
caret = new Caret(CaretState.VISIBLE_ON, 0);
root = new BlockContainer(small, false);
}
public void typeChar(char c) {
Block b = parseChar(c);
final Block b = parseChar(c);
if (b != null) {
caret.resetRemaining();
if (root.putBlock(caret, b)) {
caret.setPosition(caret.getPosition()+1);
maxPosition=root.computeCaretMaxBound();
caret.setPosition(caret.getPosition() + 1);
maxPosition = root.computeCaretMaxBound();
root.recomputeDimensions();
}
}
caretTime = 0;
caret.turnOn();
}
public void typeChar(String c) {
typeChar(c.charAt(0));
}
@ -55,26 +63,26 @@ public abstract class InputContainer implements GraphicalElement, InputLayout {
root.recomputeDimensions();
}
if (caret.getPosition() > 0) {
caret.setPosition(caret.getPosition()-1);
maxPosition=root.computeCaretMaxBound();
caret.setPosition(caret.getPosition() - 1);
maxPosition = root.computeCaretMaxBound();
}
caret.turnOn();
caretTime = 0;
}
public void moveLeft() {
int curPos = caret.getPosition();
final int curPos = caret.getPosition();
if (curPos > 0) {
caret.setPosition(curPos-1);
caret.setPosition(curPos - 1);
}
caret.turnOn();
caretTime = 0;
}
public void moveRight() {
int curPos = caret.getPosition();
if (curPos+1 < maxPosition) {
caret.setPosition(curPos+1);
final int curPos = caret.getPosition();
if (curPos + 1 < maxPosition) {
caret.setPosition(curPos + 1);
}
caret.turnOn();
caretTime = 0;
@ -98,11 +106,12 @@ public abstract class InputContainer implements GraphicalElement, InputLayout {
@Override
public int getLine() {
return root.getLine();
}
}
/**
*
* @param delta Time, in seconds
* @param delta
* Time, in seconds
* @return true if something changed
*/
public boolean beforeRender(float delta) {
@ -115,16 +124,20 @@ public abstract class InputContainer implements GraphicalElement, InputLayout {
somethingChanged = true;
}
}
return somethingChanged;
}
/**
*
* @param ge Graphic Engine class.
* @param r Graphic Renderer class of <b>ge</b>.
* @param x Position relative to the window.
* @param y Position relative to the window.
* @param ge
* Graphic Engine class.
* @param r
* Graphic Renderer class of <b>ge</b>.
* @param x
* Position relative to the window.
* @param y
* Position relative to the window.
*/
public void draw(GraphicEngine ge, Renderer r, int x, int y) {
caret.resetRemaining();
@ -134,7 +147,40 @@ public abstract class InputContainer implements GraphicalElement, InputLayout {
public void clear() {
caret = new Caret(CaretState.VISIBLE_ON, 0);
root.clear();
maxPosition=root.computeCaretMaxBound();
maxPosition = root.computeCaretMaxBound();
recomputeDimensions();
}
public boolean isEmpty() {
return maxPosition <= 1;
}
public int getCaretMaxPosition() {
return maxPosition;
}
public void setCaretPosition(int pos) {
if (pos > 0 && pos < maxPosition) {
caret.setPosition(pos);
}
caret.turnOn();
caretTime = 0;
}
public void setParsed(boolean parsed) {
this.parsed = parsed;
}
public boolean isAlreadyParsed() {
return parsed;
}
/**
* <strong>WARNING! DO NOT MODIFY THIS ARRAY!!!</strong>
*
* @return an arraylist representing the content
*/
public ObjectArrayList<Block> getContent() {
return root.getContent();
}
}

View File

@ -2,31 +2,28 @@ package org.warp.picalculator.gui.expression.containers;
import org.warp.picalculator.gui.expression.Block;
import org.warp.picalculator.gui.expression.BlockChar;
import org.warp.picalculator.gui.expression.BlockContainer;
import org.warp.picalculator.gui.expression.BlockDivision;
import org.warp.picalculator.gui.expression.BlockParenthesis;
import org.warp.picalculator.gui.expression.BlockSquareRoot;
import org.warp.picalculator.gui.expression.Caret;
import org.warp.picalculator.gui.expression.CaretState;
import org.warp.picalculator.math.MathematicalSymbols;
public class NormalInputContainer extends InputContainer {
public NormalInputContainer() {
super();
}
public NormalInputContainer(boolean small) {
super(small);
}
public NormalInputContainer(boolean small, int minWidth, int minHeight) {
super(small, minWidth, minHeight);
}
@Override
public Block parseChar(char c) {
switch(c) {
switch (c) {
case MathematicalSymbols.DIVISION:
return new BlockDivision();
case MathematicalSymbols.SQUARE_ROOT:

View File

@ -4,11 +4,11 @@ public class NormalOutputContainer extends OutputContainer {
public NormalOutputContainer() {
super();
}
public NormalOutputContainer(boolean small) {
super(small);
}
public NormalOutputContainer(boolean small, int minWidth, int minHeight) {
super(small, minWidth, minHeight);
}

View File

@ -1,29 +1,41 @@
package org.warp.picalculator.gui.expression.containers;
import java.io.Serializable;
import org.warp.picalculator.gui.GraphicalElement;
import org.warp.picalculator.gui.expression.Block;
import org.warp.picalculator.gui.expression.BlockContainer;
import org.warp.picalculator.gui.expression.Caret;
import org.warp.picalculator.gui.expression.CaretState;
import org.warp.picalculator.gui.expression.layouts.InputLayout;
import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer;
public abstract class OutputContainer implements GraphicalElement, OutputLayout {
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public abstract class OutputContainer implements GraphicalElement, OutputLayout, Serializable {
private static final long serialVersionUID = -5714825964892683571L;
public final BlockContainer root;
private final Caret caret = new Caret(CaretState.HIDDEN, 0);
public OutputContainer() {
root = new BlockContainer();
}
public OutputContainer(boolean small) {
root = new BlockContainer(small);
}
public OutputContainer(boolean small, int minWidth, int minHeight) {
root = new BlockContainer(small);
}
public void setContent(ObjectArrayList<Block> blocks) {
root.clear();
for (Block b : blocks) {
root.appendBlockUnsafe(b);
}
recomputeDimensions();
}
@Override
public void recomputeDimensions() {
@ -43,22 +55,27 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout
@Override
public int getLine() {
return root.getLine();
}
}
/**
*
* @param delta Time, in seconds
* @param delta
* Time, in seconds
*/
public void beforeRender(double delta) {
}
/**
*
* @param ge Graphic Engine class.
* @param r Graphic Renderer class of <b>ge</b>.
* @param x Position relative to the window.
* @param y Position relative to the window.
* @param ge
* Graphic Engine class.
* @param r
* Graphic Renderer class of <b>ge</b>.
* @param x
* Position relative to the window.
* @param y
* Position relative to the window.
*/
public void draw(GraphicEngine ge, Renderer r, int x, int y) {
root.draw(ge, r, x, y, caret);

View File

@ -37,6 +37,6 @@ public interface GraphicEngine {
public void waitUntilExit();
public boolean isSupported();
public boolean doesRefreshPauses();
}

View File

@ -1,7 +1,5 @@
package org.warp.picalculator.gui.graphicengine;
import java.awt.FontMetrics;
public interface Renderer {
public void glColor3i(int r, int gg, int b);
@ -25,22 +23,23 @@ public interface Renderer {
public void glDrawLine(float x0, float y0, float x1, float y1);
public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, float uvHeight);
public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth,
float uvHeight);
public void glFillColor(float x, float y, float width, float height);
public void glDrawCharLeft(int x, int y, char ch);
public void glDrawCharCenter(int x, int y, char ch);
public void glDrawCharRight(int x, int y, char ch);
public void glDrawStringLeft(float x, float y, String text);
public void glDrawStringCenter(float x, float y, String text);
public void glDrawStringRight(float x, float y, String text);
public void glClearSkin();
public BinaryFont getCurrentFont();

View File

@ -45,7 +45,7 @@ public class CPUEngine implements GraphicEngine {
g = new BufferedImage(ww, wh, BufferedImage.TYPE_INT_ARGB);
INSTANCE.wasResized = false;
}
@Override
public void create() {
INSTANCE = new SwingWindow(this);
@ -87,7 +87,7 @@ public class CPUEngine implements GraphicEngine {
@Override
public void start(RenderingLoop d) {
INSTANCE.setRenderingLoop(d);
Thread th = new Thread(() -> {
final Thread th = new Thread(() -> {
try {
double extratime = 0;
while (initialized) {
@ -171,7 +171,7 @@ public class CPUEngine implements GraphicEngine {
@Override
public void glClearColor4f(float red, float green, float blue, float alpha) {
clearcolor = ((int)(alpha*255) << 24) + ((int)(red*255) << 16) + ((int)(green*255) << 8) + ((int)(blue*255));
clearcolor = ((int) (alpha * 255) << 24) + ((int) (red * 255) << 16) + ((int) (green * 255) << 8) + ((int) (blue * 255));
}
@Override
@ -269,13 +269,13 @@ public class CPUEngine implements GraphicEngine {
}
if (iy0 == iy1) {
for (int x = 0; x <= ix1 - ix0; x++) {
if ((ix0+x < size[0]) & (iy0 < size[1])) {
if ((ix0 + x < size[0]) & (iy0 < size[1])) {
canvas2d[ix0 + x + iy0 * size[0]] = color;
}
}
} else if (ix0 == ix1) {
for (int y = 0; y <= iy1 - iy0; y++) {
if ((ix0 < size[0]) & (iy0+y < size[1])) {
if ((ix0 < size[0]) & (iy0 + y < size[1])) {
canvas2d[ix0 + (iy0 + y) * size[0]] = color;
}
}
@ -305,12 +305,12 @@ public class CPUEngine implements GraphicEngine {
public void glFillColor(float x, float y, float width, float height) {
x += Main.screenPos[0];
y += Main.screenPos[1];
final int ix = (int) x;
final int iy = (int) y;
final int iw = (int) width;
final int ih = (int) height;
int x1 = ix + iw;
int y1 = iy + ih;
if (ix >= size[0] || iy >= size[0]) {
@ -337,7 +337,7 @@ public class CPUEngine implements GraphicEngine {
final int ix = (int) x;
final int iy = (int) y;
final int[] text = currentFont.getCharIndexes(textString);
final int[] screen = canvas2d;
final int[] screenSize = size;
@ -418,17 +418,17 @@ public class CPUEngine implements GraphicEngine {
@Override
public void glDrawCharLeft(int x, int y, char ch) {
glDrawStringLeft(x, y, ch+"");
glDrawStringLeft(x, y, ch + "");
}
@Override
public void glDrawCharCenter(int x, int y, char ch) {
glDrawStringCenter(x, y, ch+"");
glDrawStringCenter(x, y, ch + "");
}
@Override
public void glDrawCharRight(int x, int y, char ch) {
glDrawStringRight(x, y, ch+"");
glDrawStringRight(x, y, ch + "");
}
}
@ -463,9 +463,9 @@ public class CPUEngine implements GraphicEngine {
try {
do {
Thread.sleep(500);
} while(initialized);
} catch (InterruptedException e) {
} while (initialized);
} catch (final InterruptedException e) {
}
}

View File

@ -5,7 +5,6 @@ import java.io.IOException;
import javax.imageio.ImageIO;
import org.warp.picalculator.Main;
import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Skin;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine.CPURenderer;
@ -21,7 +20,7 @@ public class CPUSkin implements Skin {
@Override
public void load(String file) throws IOException {
final BufferedImage img = ImageIO.read(this.getClass().getResource("/"+file));
final BufferedImage img = ImageIO.read(this.getClass().getResource("/" + file));
skinData = getMatrixOfImage(img);
skinSize = new int[] { img.getWidth(), img.getHeight() };
}

View File

@ -221,7 +221,7 @@ public class SwingWindow extends JFrame {
public int getHeight() {
return c.getHeight();
}
public void setRenderingLoop(RenderingLoop renderingLoop) {
this.renderingLoop = renderingLoop;
}
@ -240,21 +240,21 @@ public class SwingWindow extends JFrame {
// long time1 = System.nanoTime();
if (renderingLoop != null) {
renderingLoop.refresh();
final int[] a = ((DataBufferInt) display.g.getRaster().getDataBuffer()).getData();
// System.arraycopy(canvas2d, 0, a, 0, canvas2d.length);
// System.arraycopy(canvas2d, 0, a, 0, canvas2d.length);
CPUEngine.canvas2d = a;
g.clearRect(0, 0, display.size[0], display.size[1]);
g.drawImage(display.g, 0, 0, null);
// long time2 = System.nanoTime();
// double timeDelta = ((double)(time2-time1))/1000000000d;
// double mediaAttuale = timeDelta;
// mediaValori.add(mediaAttuale);
// double somma = 0;
// for (Double val : mediaValori) {
// somma+=val;
// }
// System.out.println(somma/((double)mediaValori.size()));
// long time2 = System.nanoTime();
// double timeDelta = ((double)(time2-time1))/1000000000d;
// double mediaAttuale = timeDelta;
// mediaValori.add(mediaAttuale);
// double somma = 0;
// for (Double val : mediaValori) {
// somma+=val;
// }
// System.out.println(somma/((double)mediaValori.size()));
}
}
}

View File

@ -401,15 +401,15 @@ public class DeallocationHelper {
attachmentOrByteBufferFieldMap.put(bufferClass, bufferField);
}
} catch (final ClassNotFoundException cnfe) {// TODO The Java version
// isn't very useful
// under
// Android as it is
// always zero, rather
// use
// android.os.Build.VERSION.RELEASE
// to show something
// meaningful supported
// since the API level 1
// isn't very useful
// under
// Android as it is
// always zero, rather
// use
// android.os.Build.VERSION.RELEASE
// to show something
// meaningful supported
// since the API level 1
final String msg = "The class " + classname + " hasn't been found while initializing the deallocator. Java vendor: " + javaVendor + " Java version: " + javaVersion;
logger.log(Level.WARNING, msg, cnfe);
}

View File

@ -9,7 +9,6 @@ import org.warp.picalculator.gui.graphicengine.BinaryFont;
import org.warp.picalculator.gui.graphicengine.Skin;
import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.egl.EGL;
public class GPUEngine implements org.warp.picalculator.gui.graphicengine.GraphicEngine {
@ -18,7 +17,7 @@ public class GPUEngine implements org.warp.picalculator.gui.graphicengine.Graphi
private NEWTWindow wnd;
private RenderingLoop d;
private GPURenderer r;
int[] size = new int[]{Main.screenSize[0], Main.screenSize[1]};
int[] size = new int[] { Main.screenSize[0], Main.screenSize[1] };
@Override
public int[] getSize() {
@ -47,9 +46,9 @@ public class GPUEngine implements org.warp.picalculator.gui.graphicengine.Graphi
@Override
public void setDisplayMode(int ww, int wh) {
this.size[0] = ww;
this.size[1] = wh;
wnd.window.setSize(Utils.debugOn?ww*2:ww, Utils.debugOn?wh*2:wh);
size[0] = ww;
size[1] = wh;
wnd.window.setSize(Utils.debugOn ? ww * 2 : ww, Utils.debugOn ? wh * 2 : wh);
}
@Override
@ -93,7 +92,7 @@ public class GPUEngine implements org.warp.picalculator.gui.graphicengine.Graphi
@Override
public void repaint() {
if (d != null & r != null && r.gl != null) {
if (d != null & r != null && GPURenderer.gl != null) {
d.refresh();
}
}
@ -118,15 +117,15 @@ public class GPUEngine implements org.warp.picalculator.gui.graphicengine.Graphi
try {
do {
Thread.sleep(500);
} while(initialized | created);
} catch (InterruptedException e) {
} while (initialized | created);
} catch (final InterruptedException e) {
}
}
@Override
public boolean isSupported() {
boolean available = GLProfile.isAvailable(GLProfile.GL2ES1);
final boolean available = GLProfile.isAvailable(GLProfile.GL2ES1);
if (!available) {
System.err.println(GLProfile.glAvailabilityToString());
}

View File

@ -1,11 +1,8 @@
package org.warp.picalculator.gui.graphicengine.gpu;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.BinaryFont;
import org.warp.picalculator.gui.graphicengine.cpu.CPUFont;
@ -44,7 +41,7 @@ public class GPUFont implements BinaryFont {
tmpFont = font;
font = null;
}
public int[] getCharIndexes(String txt) {
final int l = txt.length();
final int[] indexes = new int[l];
@ -54,7 +51,7 @@ public class GPUFont implements BinaryFont {
}
return indexes;
}
public int getCharIndex(char ch) {
return (ch & 0xFFFF) - minCharIndex;
}
@ -72,7 +69,7 @@ public class GPUFont implements BinaryFont {
if (currentChar != null && currentChar.length > 0) {
for (int charY = 0; charY < charH; charY++) {
for (int charX = 0; charX < charW; charX++) {
if (currentChar[charY*charW+charX]) {
if (currentChar[charY * charW + charX]) {
bfi.setRGB(indexX * charW + charX, indexY * charH + charY, 0xFFFFFFFF);
}
}

View File

@ -1,6 +1,5 @@
package org.warp.picalculator.gui.graphicengine.gpu;
import java.awt.FontMetrics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -33,19 +32,19 @@ public class GPURenderer implements Renderer {
int fbElements;
float[] currentColor = new float[16];
float[] currentClearColorARGBf = new float[]{1f, 197f/255f, 194f/255f, 175f/255f};
float[] currentClearColorARGBf = new float[] { 1f, 197f / 255f, 194f / 255f, 175f / 255f };
boolean currentTexEnabled;
Texture currentTex;
float currentTexWidth;
float currentTexHeight;
GPUFont currentFont;
@Override
public void glColor3i(int r, int gg, int b) {
final float red = ((float)r) / 255f;
final float gre = ((float)gg) / 255f;
final float blu = ((float)b) / 255f;
final float red = (r) / 255f;
final float gre = (gg) / 255f;
final float blu = (b) / 255f;
currentColor = new float[] { red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, };
}
@ -70,15 +69,15 @@ public class GPURenderer implements Renderer {
@Override
public int glGetClearColor() {
return (int)(currentClearColorARGBf[0] * 255) << 24 | (int)(currentClearColorARGBf[1] * 255) << 16 | (int)(currentClearColorARGBf[2] * 255) << 8 | (int)(currentClearColorARGBf[3] * 255);
return (int) (currentClearColorARGBf[0] * 255) << 24 | (int) (currentClearColorARGBf[1] * 255) << 16 | (int) (currentClearColorARGBf[2] * 255) << 8 | (int) (currentClearColorARGBf[3] * 255);
}
@Override
public void glClearColor(int rgb) {
final float alpha = (float)((rgb >> 24) & 0xFF) / 255f;
final float red = (float)((rgb >> 16) & 0xFF) / 255f;
final float green = (float)((rgb >> 8) & 0xFF) / 255f;
final float blue = (float)(rgb & 0xFF) / 255f;
final float alpha = ((rgb >> 24) & 0xFF) / 255f;
final float red = ((rgb >> 16) & 0xFF) / 255f;
final float green = ((rgb >> 8) & 0xFF) / 255f;
final float blue = (rgb & 0xFF) / 255f;
glClearColor4f(red, green, blue, alpha);
}
@ -97,12 +96,12 @@ public class GPURenderer implements Renderer {
final float gre = (green) / 255f;
final float blu = (blue) / 255f;
final float alp = (alpha) / 255f;
currentClearColorARGBf = new float[]{alp, ros, gre, blu};
currentClearColorARGBf = new float[] { alp, ros, gre, blu };
}
@Override
public void glClearColor4f(float red, float green, float blue, float alpha) {
currentClearColorARGBf = new float[]{alpha, red, green, blue};
currentClearColorARGBf = new float[] { alpha, red, green, blue };
}
@Override
@ -113,16 +112,17 @@ public class GPURenderer implements Renderer {
@Override
public void glDrawLine(float x0, float y0, float x1, float y1) {
glFillColor(x0, y0, x1-x0+1, y1-y0+1);
glFillColor(x0, y0, x1 - x0 + 1, y1 - y0 + 1);
}
@Override
public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, float uvHeight) {
public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth,
float uvHeight) {
enableTexture();
uvWidth/=currentTexWidth;
uvX/=currentTexWidth;
uvHeight/=currentTexHeight;
uvY = 1 - uvY/currentTexHeight - uvHeight;
uvWidth /= currentTexWidth;
uvX /= currentTexWidth;
uvHeight /= currentTexHeight;
uvY = 1 - uvY / currentTexHeight - uvHeight;
final float[] vertices = { x, y, 0.0f, x, y + height, 0.0f, x + width, y, 0.0f, x + width, y + height, 0.0f, };
final float[] tex_vertices = { uvX, uvY + uvHeight, uvX, uvY, uvX + uvWidth, uvY + uvHeight, uvX + uvWidth, uvY, };
fbElements++;
@ -145,13 +145,13 @@ public class GPURenderer implements Renderer {
@Override
public void glDrawStringLeft(float x, float y, String text) {
final int txtLen = text.length();
int[] txtArray = currentFont.getCharIndexes(text);
final int[] txtArray = currentFont.getCharIndexes(text);
int tableIndexX;
int tableIndexY;
for (int currentCharIndex = 0; currentCharIndex < txtLen; currentCharIndex++) {
tableIndexX = txtArray[currentCharIndex] % currentFont.memoryWidthOfEachColumn;
tableIndexY = (txtArray[currentCharIndex] - tableIndexX) / currentFont.memoryWidthOfEachColumn;
glFillRect(x + ((float)currentCharIndex) * ((float)(currentFont.charW)), y, currentFont.charW, currentFont.charH, tableIndexX*currentFont.charW, tableIndexY*currentFont.charH, currentFont.charW, currentFont.charH);
glFillRect(x + ((float) currentCharIndex) * ((float) (currentFont.charW)), y, currentFont.charW, currentFont.charH, tableIndexX * currentFont.charW, tableIndexY * currentFont.charH, currentFont.charW, currentFont.charH);
}
}
@ -167,10 +167,10 @@ public class GPURenderer implements Renderer {
@Override
public void glDrawCharLeft(int x, int y, char ch) {
int index = currentFont.getCharIndex(ch);
int tableIndexX = index % currentFont.memoryWidthOfEachColumn;
int tableIndexY = (index - tableIndexX) / currentFont.memoryWidthOfEachColumn;
glFillRect(x, y, currentFont.charW, currentFont.charH, tableIndexX*currentFont.charW, tableIndexY*currentFont.charH, currentFont.charW, currentFont.charH);
final int index = currentFont.getCharIndex(ch);
final int tableIndexX = index % currentFont.memoryWidthOfEachColumn;
final int tableIndexY = (index - tableIndexX) / currentFont.memoryWidthOfEachColumn;
glFillRect(x, y, currentFont.charW, currentFont.charH, tableIndexX * currentFont.charW, tableIndexY * currentFont.charH, currentFont.charW, currentFont.charH);
}
@Override
@ -208,7 +208,7 @@ public class GPURenderer implements Renderer {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(img, "png", os);
final InputStream fis = new ByteArrayInputStream(os.toByteArray());
Texture tex = TextureIO.newTexture(fis, false, TextureIO.PNG);
final Texture tex = TextureIO.newTexture(fis, false, TextureIO.PNG);
tex.setTexParameteri(gl, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
tex.setTexParameteri(gl, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
return tex;
@ -234,7 +234,7 @@ public class GPURenderer implements Renderer {
private boolean precTexEnabled;
private Texture precTex;
public void endDrawCycle() {
fbVertices.rewind();
txVertices.rewind();
@ -248,14 +248,14 @@ public class GPURenderer implements Renderer {
precTexEnabled = currentTexEnabled;
precTex = currentTex;
if (currentTexEnabled) {
gl.glEnable(GL2ES1.GL_TEXTURE_2D);
gl.glEnable(GL.GL_TEXTURE_2D);
currentTex.bind(gl);
} else {
gl.glDisable(GL2ES1.GL_TEXTURE_2D);
gl.glDisable(GL.GL_TEXTURE_2D);
}
}
gl.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, fbElements*4);
gl.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, fbElements * 4);
// deleteBuffer(fbVertices);
// deleteBuffer(txVertices);

View File

@ -5,6 +5,7 @@ import java.io.IOException;
import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Skin;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2ES1;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.util.texture.Texture;
@ -33,12 +34,12 @@ public class GPUSkin implements Skin {
@Override
public void initialize(GraphicEngine d) {
try {
BufferedImage i = GPURenderer.openTexture(texturePath);
GL2ES1 gl = ((GPURenderer)d.getRenderer()).gl;
final BufferedImage i = GPURenderer.openTexture(texturePath);
final GL2ES1 gl = GPURenderer.gl;
t = GPURenderer.importTexture(i);
w = i.getWidth();
h = i.getHeight();
t.setTexParameteri(gl, GL2ES1.GL_TEXTURE_MAG_FILTER, GL2ES1.GL_NEAREST);
t.setTexParameteri(gl, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
initialized = true;
} catch (GLException | IOException e) {
e.printStackTrace();
@ -52,7 +53,7 @@ public class GPUSkin implements Skin {
initialize(d);
}
final GPURenderer r = (GPURenderer) d.getRenderer();
r.useTexture(t,w,h);
r.useTexture(t, w, h);
}
}

View File

@ -33,13 +33,10 @@ import com.jogamp.opengl.GL2ES1;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.fixedfunc.GLLightingFunc;
import com.jogamp.opengl.fixedfunc.GLMatrixFunc;
import com.jogamp.opengl.fixedfunc.GLPointerFunc;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.nativewindow.util.DimensionImmutable;
import com.jogamp.nativewindow.util.PixelFormat;
import com.jogamp.nativewindow.util.PixelRectangle;
import com.jogamp.newt.NewtFactory;
import com.jogamp.newt.event.KeyEvent;
import com.jogamp.newt.event.KeyListener;
import com.jogamp.newt.event.WindowEvent;
@ -49,16 +46,10 @@ import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.nio.ByteBuffer;
import java.util.Collection;
import org.warp.picalculator.Utils;
import org.warp.picalculator.device.Keyboard;
import org.warp.picalculator.device.Keyboard.Key;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.GraphicEngine;
/**
*
@ -93,15 +84,15 @@ class NEWTWindow implements GLEventListener {
caps.setSampleBuffers(false);
final GLWindow glWindow = GLWindow.create(caps);
window = glWindow;
glWindow.setTitle("WarpPI Calculator by Andrea Cavalli (XDrake99)");
glWindow.addWindowListener(new WindowListener() {
@Override
public void windowDestroyNotify(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
@ -112,32 +103,32 @@ class NEWTWindow implements GLEventListener {
@Override
public void windowGainedFocus(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowLostFocus(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowMoved(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowRepaint(WindowUpdateEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowResized(WindowEvent e) {
}
});
glWindow.addKeyListener(new KeyListener() {
@Override
@ -272,15 +263,15 @@ class NEWTWindow implements GLEventListener {
//Vsync
gl.setSwapInterval(2);
//Textures
gl.glEnable(GL.GL_TEXTURE_2D);
//Transparency
gl.glEnable(GL2ES1.GL_BLEND);
gl.glBlendFunc(GL2ES1.GL_SRC_ALPHA, GL2ES1.GL_ONE_MINUS_SRC_ALPHA);
gl.glShadeModel(GL2ES1.GL_FLAT);
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
gl.glShadeModel(GLLightingFunc.GL_FLAT);
try {
renderer.currentTex = ((GPUSkin) disp.loadSkin("test.png")).t;
} catch (final Exception e) {
@ -296,8 +287,8 @@ class NEWTWindow implements GLEventListener {
@Override
public void reshape(GLAutoDrawable glad, int x, int y, int width, int height) {
disp.size[0] = Utils.debugOn?width/2:width;
disp.size[1] = Utils.debugOn?height/2:height;
disp.size[0] = Utils.debugOn ? width / 2 : width;
disp.size[1] = Utils.debugOn ? height / 2 : height;
final GL2ES1 gl = glad.getGL().getGL2ES1();
float max_wh, min_wh;
if (width == 0) {
@ -319,7 +310,7 @@ class NEWTWindow implements GLEventListener {
gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrtho(0.0, Utils.debugOn?width/2:width, Utils.debugOn?height/2:height, 0.0, -1, 1);
gl.glOrtho(0.0, Utils.debugOn ? width / 2 : width, Utils.debugOn ? height / 2 : height, 0.0, -1, 1);
gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
gl.glLoadIdentity();
@ -329,19 +320,19 @@ class NEWTWindow implements GLEventListener {
public void display(GLAutoDrawable glad) {
final GL2ES1 gl = glad.getGL().getGL2ES1();
renderer.gl = gl;
GPURenderer.gl = gl;
gl.glEnableClientState(GLPointerFunc.GL_COLOR_ARRAY);
gl.glEnableClientState(GLPointerFunc.GL_VERTEX_ARRAY);
gl.glEnableClientState(GLPointerFunc.GL_TEXTURE_COORD_ARRAY);
renderer.startDrawCycle();
disp.repaint();
renderer.endDrawCycle();
renderer.gl = null;
GPURenderer.gl = null;
gl.glDisableClientState(GLPointerFunc.GL_COLOR_ARRAY);
gl.glDisableClientState(GLPointerFunc.GL_TEXTURE_COORD_ARRAY);

View File

@ -35,7 +35,7 @@ public class ChooseVariableValueScreen extends Screen {
DisplayManager.renderer.glDrawStringCenter(Main.screenSize[0] / 2 + 1, Main.screenSize[1] / 2 - 20 + 1, "WORK IN PROGRESS.");
DisplayManager.renderer.glColor3i(255, 0, 0);
DisplayManager.renderer.glDrawStringCenter(Main.screenSize[0] / 2, Main.screenSize[1] / 2 - 20, "WORK IN PROGRESS.");
Utils.getFont(false, false).use(DisplayManager.engine);
DisplayManager.renderer.glColor4i(0, 0, 0, 64);
DisplayManager.renderer.glDrawStringCenter(Main.screenSize[0] / 2 + 1, Main.screenSize[1] / 2, "THIS SCREEN MUST HAVE A GUI TO SELECT THE VARIABLE TO SOLVE.");

View File

@ -29,7 +29,7 @@ public class KeyboardDebugScreen extends Screen {
@Override
public void render() {
Renderer renderer = DisplayManager.renderer;
final Renderer renderer = DisplayManager.renderer;
fonts[2].use(DisplayManager.engine);
renderer.glColor4f(0.75f, 0.0f, 0.0f, 1.0f);
renderer.glDrawStringRight(Main.screenSize[0] - 10, 30, "-" + keyevent.toUpperCase() + "-");

View File

@ -1,8 +1,5 @@
package org.warp.picalculator.gui.screens;
import static org.warp.picalculator.gui.DisplayManager.colore;
import static org.warp.picalculator.gui.DisplayManager.fonts;
import org.warp.picalculator.Main;
import org.warp.picalculator.device.Keyboard.Key;
import org.warp.picalculator.gui.DisplayManager;
@ -45,11 +42,11 @@ public class LoadingScreen extends Screen {
public void render() {
DisplayManager.guiSkin.use(DisplayManager.engine);
DisplayManager.renderer.glColor3i(255, 255, 255);
DisplayManager.renderer.glFillRect(Main.screenSize[0]/2f-80, Main.screenSize[1]/2f-64, 160, 48, 0, 32, 160, 48);
DisplayManager.renderer.glFillRect(Main.screenSize[0]/2f-24, Main.screenSize[1]/2f-loadingTextTranslation, 48, 48, 160, 32, 48, 48);
DisplayManager.renderer.glFillRect(Main.screenSize[0] / 2f - 80, Main.screenSize[1] / 2f - 64, 160, 48, 0, 32, 160, 48);
DisplayManager.renderer.glFillRect(Main.screenSize[0] / 2f - 24, Main.screenSize[1] / 2f - loadingTextTranslation, 48, 48, 160, 32, 48, 48);
DisplayManager.renderer.glFillRect(Main.screenSize[0]-224, Main.screenSize[1]-48, 224, 48, 0, 80, 224, 48);
DisplayManager.renderer.glFillRect(Main.screenSize[0]-160-24-224, Main.screenSize[1]-48, 160, 48, 224, 80, 160, 48);
DisplayManager.renderer.glFillRect(Main.screenSize[0] - 224, Main.screenSize[1] - 48, 224, 48, 0, 80, 224, 48);
DisplayManager.renderer.glFillRect(Main.screenSize[0] - 160 - 24 - 224, Main.screenSize[1] - 48, 160, 48, 224, 80, 160, 48);
}

View File

@ -1,11 +1,7 @@
package org.warp.picalculator.gui.screens;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.warp.picalculator.Main;
import org.warp.picalculator.device.Keyboard;
import org.warp.picalculator.device.Keyboard.Key;
import org.warp.picalculator.gui.DisplayManager;
@ -37,7 +33,7 @@ public class MarioScreen extends Screen {
try {
skin = DisplayManager.engine.loadSkin("marioskin.png");
groundskin = DisplayManager.engine.loadSkin("marioground.png");
} catch (IOException e) {
} catch (final IOException e) {
e.printStackTrace();
}
}
@ -45,7 +41,7 @@ public class MarioScreen extends Screen {
@Override
public void created() throws InterruptedException {
if (!errored) {
}
}

View File

@ -4,19 +4,20 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.warp.picalculator.Error;
import org.warp.picalculator.Errors;
import org.warp.picalculator.Main;
import org.warp.picalculator.Utils;
import org.warp.picalculator.device.Keyboard;
import org.warp.picalculator.device.Keyboard.Key;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.expression.Block;
import org.warp.picalculator.gui.expression.BlockContainer;
import org.warp.picalculator.gui.expression.containers.InputContainer;
import org.warp.picalculator.gui.expression.containers.NormalInputContainer;
@ -34,6 +35,8 @@ import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.functions.Variable;
import org.warp.picalculator.math.functions.Variable.VariableValue;
import org.warp.picalculator.math.functions.equations.Equation;
import org.warp.picalculator.math.parser.MathParser;
import org.warp.picalculator.math.functions.Expression;
import org.warp.picalculator.math.functions.Number;
public class MathInputScreen extends Screen {
@ -52,17 +55,17 @@ public class MathInputScreen extends Screen {
@Override
public void created() throws InterruptedException {
calc = new MathContext();
try {
BlockContainer.initializeFonts(DisplayManager.engine.loadFont("ex"), DisplayManager.engine.loadFont("big"));
} catch (IOException e) {
} catch (final IOException e) {
e.printStackTrace();
System.exit(1);
}
userInput = new NormalInputContainer();
result = new NormalOutputContainer();
calc.init();
}
@ -70,7 +73,7 @@ public class MathInputScreen extends Screen {
public void init() throws InterruptedException {
/* Fine caricamento */
}
@Override
public void beforeRender(float dt) {
@ -88,7 +91,7 @@ public class MathInputScreen extends Screen {
@Override
public void renderStatusbar() {
Renderer renderer = DisplayManager.renderer;
final Renderer renderer = DisplayManager.renderer;
renderer.glColor3f(1, 1, 1);
final int pos = 2;
final int spacersNumb = 1;
@ -107,11 +110,11 @@ public class MathInputScreen extends Screen {
final int textColor = 0xFF000000;
final int padding = 4;
DisplayManager.renderer.glColor(textColor);
userInput.draw(DisplayManager.engine, DisplayManager.renderer, padding, padding + 20);
if (!result.root.getContent().isEmpty()) {
result.draw(DisplayManager.engine, DisplayManager.renderer, DisplayManager.engine.getWidth() - 2, DisplayManager.engine.getHeight() - 2);
result.draw(DisplayManager.engine, DisplayManager.renderer, DisplayManager.engine.getWidth() - result.getWidth() - 2, DisplayManager.engine.getHeight() - result.getHeight() - 2);
}
}
@ -127,6 +130,7 @@ public class MathInputScreen extends Screen {
@Override
public boolean keyPressed(Key k) {
Utils.debug.println(k.toString());
switch (k) {
case STEP:
// if (newExpression.length() > 0) {
@ -160,46 +164,51 @@ public class MathInputScreen extends Screen {
// }
// return true;
case SIMPLIFY:
// if (DisplayManager.error != null) {
// Utils.debug.println("Resetting after error...");
// DisplayManager.error = null;
// currentExpression = null;
// calc.f = null;
// calc.f2 = null;
// calc.resultsCount = 0;
// return true;
// } else {
// try {
// try {
// if (!firstStep) {
// step();
// } else {
// if (newExpression != currentExpression && newExpression.length() > 0) {
// changeEquationScreen();
// interpreta(true);
// showVariablesDialog(() -> {
// currentExpression = newExpression;
// simplify();
// });
// }
// }
// } catch (final Exception ex) {
// if (Utils.debugOn) {
// ex.printStackTrace();
// }
// throw new Error(Errors.SYNTAX_ERROR);
// }
// } catch (final Error e) {
// final StringWriter sw = new StringWriter();
// final PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// d.errorStackTrace = sw.toString().toUpperCase().replace("\t", " ").replace("\r", "").split("\n");
// DisplayManager.error = e.id.toString();
// System.err.println(e.id);
// }
// return true;
// }
return true;
if (DisplayManager.error != null) {
//TODO: make the error management a global API rather than being relegated to this screen.
Utils.debug.println("Resetting after error...");
DisplayManager.error = null;
calc.f = null;
calc.f2 = null;
calc.resultsCount = 0;
return true;
} else {
try {
try {
if (!userInput.isAlreadyParsed() && !userInput.isEmpty()) {
Expression expr = MathParser.parseInput(calc, userInput);
if (calc.f == null | calc.f2 == null) {
calc.f = new ObjectArrayList<>();
calc.f2 = new ObjectArrayList<>();
} else {
calc.f.clear();
calc.f2.clear();
}
calc.f.add(expr);
ObjectArrayList<Function> resultExpression = expr.solve();
ObjectArrayList<Block> resultBlocks = MathParser.parseOutput(calc, resultExpression);
result.setContent(resultBlocks);
// showVariablesDialog(() -> {
// currentExpression = newExpression;
// simplify();
// });
}
} catch (final Exception ex) {
if (Utils.debugOn) {
ex.printStackTrace();
}
throw new Error(Errors.SYNTAX_ERROR);
}
} catch (final Error e) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
d.errorStackTrace = sw.toString().toUpperCase().replace("\t", " ").replace("\r", "").split("\n");
DisplayManager.error = e.id.toString();
System.err.println(e.id);
}
return true;
}
case NUM0:
typeChar('0');
return true;
@ -317,13 +326,13 @@ public class MathInputScreen extends Screen {
}
return true;
case SURD_MODE:
// calc.exactMode = !calc.exactMode;
// if (calc.exactMode == false) {
// calc.f2 = solveExpression(calc.f2);
// } else {
// currentExpression = "";
// Keyboard.keyPressed(Key.SIMPLIFY);
// }
calc.exactMode = !calc.exactMode;
if (calc.exactMode == false) {
calc.f2 = solveExpression(calc.f2);
} else {
result.clear();
Keyboard.keyPressed(Key.SIMPLIFY);
}
return true;
case debug1:
DisplayManager.INSTANCE.setScreen(new EmptyScreen());
@ -436,9 +445,6 @@ public class MathInputScreen extends Screen {
results.clear();
results.addAll(hs);
calc.f2 = results;
for (final Function rf : calc.f2) {
rf.recomputeDimensions(null);
}
}
Utils.debug.println(calc.f2.toString());
} catch (final Exception ex) {
@ -479,9 +485,6 @@ public class MathInputScreen extends Screen {
results.clear();
results.addAll(hs);
calc.f2 = results;
for (final Function rf : calc.f2) {
rf.recomputeDimensions(null);
}
}
} catch (final Exception ex) {
if (Utils.debugOn) {
@ -499,27 +502,26 @@ public class MathInputScreen extends Screen {
}
}
@SuppressWarnings("unused")
@Deprecated
private void changeEquationScreen() {
if (currentExpression != null && currentExpression.length() > 0) {
final MathInputScreen cloned = clone();
cloned.caretPos = cloned.currentExpression.length();
cloned.newExpression = cloned.currentExpression;
cloned.scrollX = fontBig.getStringWidth(cloned.currentExpression);
try {
cloned.interpreta(true);
} catch (final Error e) {}
DisplayManager.INSTANCE.replaceScreen(cloned);
initialized = false;
DisplayManager.INSTANCE.setScreen(this);
}
throw new NotImplementedException();
//
// if (!userInput.isEmpty()) {
// final MathInputScreen cloned = clone();
// cloned.userInput.setCaretPosition(cloned.userInput.getCaretMaxPosition()-1);
// DisplayManager.INSTANCE.replaceScreen(cloned);
// initialized = false;
// DisplayManager.INSTANCE.setScreen(this);
//
// }
}
public void typeChar(char chr) {
userInput.typeChar(chr);
mustRefresh = true;
}
@Override
public boolean keyReleased(Key k) {
return false;
@ -537,7 +539,7 @@ public class MathInputScreen extends Screen {
knownVarsInFunctions.remove(f.v);
}
}
boolean cancelled = false;
for (final Function f : knownVarsInFunctions) {
final ChooseVariableValueScreen cvs = new ChooseVariableValueScreen(this, new VariableValue((Variable) f, new Number(calc, 0)));
@ -583,7 +585,7 @@ public class MathInputScreen extends Screen {
} else if (f instanceof FunctionSingle) {
res.addAll(getKnownVariables(new Function[] { ((FunctionSingle) f).getParameter() }));
} else if (f instanceof Variable) {
if (((Variable)f).getType() == Variable.V_TYPE.KNOWN) {
if (((Variable) f).getType() == Variable.V_TYPE.KNOWN) {
if (!res.contains(f)) {
res.add(f);
}
@ -594,15 +596,17 @@ public class MathInputScreen extends Screen {
}
@Override
@Deprecated
public MathInputScreen clone() {
final MathInputScreen es = this;
final MathInputScreen es2 = new MathInputScreen();
es2.errorLevel = es.errorLevel;
es2.mustRefresh = es.mustRefresh;
es2.calc = Utils.cloner.deepClone(es.calc);
es2.userInput = Utils.cloner.deepClone(es.userInput);
es2.result = Utils.cloner.deepClone(es.result);
return es2;
throw new NotImplementedException();
// final MathInputScreen es = this;
// final MathInputScreen es2 = new MathInputScreen();
// es2.errorLevel = es.errorLevel;
// es2.mustRefresh = es.mustRefresh;
// es2.calc = Utils.cloner.deepClone(es.calc);
// es2.userInput = Utils.cloner.deepClone(es.userInput);
// es2.result = Utils.cloner.deepClone(es.result);
// return es2;
}
}

View File

@ -1,10 +1,8 @@
package org.warp.picalculator.gui.screens;
import org.warp.picalculator.Error;
import org.warp.picalculator.Main;
import org.warp.picalculator.device.Keyboard.Key;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext;
public class SolveEquationScreen extends Screen {

View File

@ -8,6 +8,7 @@ public interface Function {
/**
* Returns this function and its children in a string form.
*
* @return This function and its children in a string form.
*/
@Override
@ -15,30 +16,37 @@ public interface Function {
@Override
public boolean equals(Object o);
/**
* Deep clone this function.
*
* @return A clone of this function.
*/
public Function clone();
/**
* Generic method to change a parameter in a known position.
* @param index parameter index.
* @param var parameter.
*
* @param index
* parameter index.
* @param var
* parameter.
* @return A new instance of this function.
*/
public Function setParameter(int index, Function var) throws IndexOutOfBoundsException;
/**
* Generic method to retrieve a parameter in a known position.
* @param index parameter index.
*
* @param index
* parameter index.
* @return The requested parameter.
*/
public Function getParameter(int index) throws IndexOutOfBoundsException;
/**
* Retrieve the current Math Context used by this function
*
* @return Calculator mathContext
*/
public MathContext getMathContext();
@ -47,9 +55,10 @@ public interface Function {
* Simplify the current function or it's children
*/
public List<Function> simplify() throws Error;
/**
* The current simplification status of this function and it's childrens
*
* @return boolean
*/
public boolean isSimplified();

View File

@ -7,8 +7,6 @@ import java.util.List;
import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import com.rits.cloning.Cloner;
public abstract class FunctionDynamic implements Function {
public FunctionDynamic(MathContext root) {
this.root = root;
@ -37,7 +35,7 @@ public abstract class FunctionDynamic implements Function {
}
public FunctionDynamic setParameters(final List<Function> value) {
FunctionDynamic f = this.clone();
final FunctionDynamic f = clone();
final int vsize = value.size();
final Function[] tmp = new Function[vsize];
for (int i = 0; i < vsize; i++) {
@ -48,11 +46,11 @@ public abstract class FunctionDynamic implements Function {
}
public FunctionDynamic setParameters(final Function[] value) {
FunctionDynamic f = this.clone();
final FunctionDynamic f = clone();
f.functions = value;
return f;
}
@Override
public Function getParameter(int index) {
return functions[index];
@ -60,13 +58,13 @@ public abstract class FunctionDynamic implements Function {
@Override
public FunctionDynamic setParameter(int index, Function value) {
FunctionDynamic f = this.clone();
final FunctionDynamic f = clone();
f.functions[index] = value;
return f;
}
public FunctionDynamic appendParameter(Function value) {
FunctionDynamic f = this.clone();
final FunctionDynamic f = clone();
f.functions = Arrays.copyOf(f.functions, f.functions.length + 1);
f.functions[f.functions.length - 1] = value;
return f;
@ -74,6 +72,7 @@ public abstract class FunctionDynamic implements Function {
/**
* Retrieve the current number of parameters.
*
* @return The number of parameters.
*/
public int getParametersLength() {
@ -81,11 +80,11 @@ public abstract class FunctionDynamic implements Function {
}
public FunctionDynamic setParametersLength(int length) {
FunctionDynamic f = this.clone();
final FunctionDynamic f = clone();
f.functions = Arrays.copyOf(functions, length);
return f;
}
@Override
public boolean isSimplified() {
for (final Function variable : functions) {
@ -95,18 +94,21 @@ public abstract class FunctionDynamic implements Function {
}
return !isSolvable();
}
/**
* The current simplification status of this function, assuming that its children are already simplified.
* @return <strong>true</strong> if this function can be solved, otherwise <strong>false</strong>.
* The current simplification status of this function, assuming that its
* children are already simplified.
*
* @return <strong>true</strong> if this function can be solved, otherwise
* <strong>false</strong>.
*/
protected abstract boolean isSolvable();
@Override
public final ObjectArrayList<Function> simplify() throws Error {
boolean solved = true;
Function[] fncs = getParameters();
for (Function f : fncs) {
final Function[] fncs = getParameters();
for (final Function f : fncs) {
if (f.isSimplified() == false) {
solved = false;
break;
@ -118,12 +120,12 @@ public abstract class FunctionDynamic implements Function {
result = new ObjectArrayList<>();
final ObjectArrayList<ObjectArrayList<Function>> ln = new ObjectArrayList<>();
for (int i = 0; i < fncs.length; i++) {
ObjectArrayList<Function> l = new ObjectArrayList<>();
if (fncs[i].isSimplified()) {
l.add(fncs[i]);
for (final Function fnc : fncs) {
final ObjectArrayList<Function> l = new ObjectArrayList<>();
if (fnc.isSimplified()) {
l.add(fnc);
} else {
l.addAll(fncs[i].simplify());
l.addAll(fnc.simplify());
}
ln.add(l);
}
@ -137,14 +139,17 @@ public abstract class FunctionDynamic implements Function {
return result;
}
/**
* Solves only this function, assuming that its children are already simplified and it can be solved.
* Solves only this function, assuming that its children are already
* simplified and it can be solved.
*
* @return The solved function.
* @throws Error Errors during computation, like a/0 or similar.
* @throws Error
* Errors during computation, like a/0 or similar.
*/
protected abstract ObjectArrayList<Function> solve() throws Error;
@Override
public MathContext getMathContext() {
return root;

View File

@ -6,26 +6,34 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
public abstract class FunctionOperator implements Function {
/**
* Create a new instance of FunctionOperator. The Math Context will be the same of <strong>value1</strong>'s.
* @throws NullPointerException when value1 is null.
* @param value1 The parameter of this function.
* @param value2 The parameter of this function.
* Create a new instance of FunctionOperator. The Math Context will be the
* same of <strong>value1</strong>'s.
*
* @throws NullPointerException
* when value1 is null.
* @param value1
* The parameter of this function.
* @param value2
* The parameter of this function.
*/
public FunctionOperator(Function value1, Function value2) throws NullPointerException {
this.mathContext = value1.getMathContext();
mathContext = value1.getMathContext();
parameter1 = value1;
parameter2 = value2;
}
/**
* Create a new instance of FunctionOperator.
* @param value1 The parameter of this function.
* @param value2 The parameter of this function.
*
* @param value1
* The parameter of this function.
* @param value2
* The parameter of this function.
*/
public FunctionOperator(MathContext mc, Function value1, Function value2) {
this.mathContext = mc;
mathContext = mc;
parameter1 = value1;
parameter2 = value2;
}
@ -53,33 +61,35 @@ public abstract class FunctionOperator implements Function {
/**
*
* @param var First parameter.
* @param var
* First parameter.
* @return A new instance of this function.
*/
public FunctionOperator setParameter1(Function var) {
FunctionOperator s = this.clone();
final FunctionOperator s = clone();
s.parameter1 = var;
return s;
}
/**
*
* @param var Second parameter.
* @param var
* Second parameter.
* @return A new instance of this function.
*/
public FunctionOperator setParameter2(Function var) {
FunctionOperator s = this.clone();
final FunctionOperator s = clone();
s.parameter2 = var;
return s;
}
@Override
public FunctionOperator setParameter(int index, Function var) throws IndexOutOfBoundsException {
switch(index) {
switch (index) {
case 0:
return this.setParameter1(var);
return setParameter1(var);
case 1:
return this.setParameter2(var);
return setParameter2(var);
default:
throw new IndexOutOfBoundsException();
}
@ -87,11 +97,11 @@ public abstract class FunctionOperator implements Function {
@Override
public Function getParameter(int index) throws IndexOutOfBoundsException {
switch(index) {
switch (index) {
case 0:
return this.getParameter1();
return getParameter1();
case 1:
return this.getParameter2();
return getParameter2();
default:
throw new IndexOutOfBoundsException();
}
@ -106,10 +116,13 @@ public abstract class FunctionOperator implements Function {
public boolean isSimplified() {
return (parameter1.isSimplified() & parameter2.isSimplified()) ? !isSolvable() : false;
}
/**
* The current simplification status of this function, assuming that its children are already simplified.
* @return <strong>true</strong> if this function can be solved, otherwise <strong>false</strong>.
* The current simplification status of this function, assuming that its
* children are already simplified.
*
* @return <strong>true</strong> if this function can be solved, otherwise
* <strong>false</strong>.
*/
protected abstract boolean isSolvable();
@ -137,23 +150,26 @@ public abstract class FunctionOperator implements Function {
final Function[][] results = Utils.joinFunctionsResults(l1, l2);
for (final Function[] f : results) {
result.add(this.setParameter1(f[0]).setParameter2(f[1]));
result.add(setParameter1(f[0]).setParameter2(f[1]));
}
}
return result;
}
/**
* Solves only this function, assuming that its children are already simplified and it can be solved.
* Solves only this function, assuming that its children are already
* simplified and it can be solved.
*
* @return The solved function.
* @throws Error Errors during computation, like a/0 or similar.
* @throws Error
* Errors during computation, like a/0 or similar.
*/
protected abstract ObjectArrayList<Function> solve() throws Error;
@Override
public abstract FunctionOperator clone();
@Override
public int hashCode() {
return parameter1.hashCode() + 7 * parameter2.hashCode() + 883 * super.hashCode();

View File

@ -5,29 +5,36 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error;
public abstract class FunctionSingle implements Function {
/**
* Create a new instance of FunctionSingle. The Math Context will be the same of <strong>value</strong>'s.
* @throws NullPointerException when value is null.
* @param value The parameter of this function.
* Create a new instance of FunctionSingle. The Math Context will be the
* same of <strong>value</strong>'s.
*
* @throws NullPointerException
* when value is null.
* @param value
* The parameter of this function.
*/
public FunctionSingle(Function value) throws NullPointerException {
mathContext = value.getMathContext();
parameter = value;
}
/**
* Create a new instance of FunctionSingle.
* @param mathContext Math Context
* @param value The parameter of this function.
*
* @param mathContext
* Math Context
* @param value
* The parameter of this function.
*/
public FunctionSingle(MathContext mathContext, Function value) {
this.mathContext = mathContext;
parameter = value;
}
protected final MathContext mathContext;
/**
* Function parameter.<br>
* <u>MUST NOT BE MODIFIED IF ALREADY SET UP.</u>
@ -41,13 +48,15 @@ public abstract class FunctionSingle implements Function {
public Function getParameter() {
return parameter;
}
/**
*
* @param var Parameter.
* @param var
* Parameter.
* @return A new instance of this function.
*/
public FunctionSingle setParameter(Function value) {
FunctionSingle s = this.clone();
final FunctionSingle s = clone();
s.parameter = value;
return s;
}
@ -69,7 +78,7 @@ public abstract class FunctionSingle implements Function {
throw new IndexOutOfBoundsException();
}
}
@Override
public MathContext getMathContext() {
return mathContext;
@ -98,11 +107,13 @@ public abstract class FunctionSingle implements Function {
return result;
}
/**
* Solves only this function, assuming that its children are already simplified and it can be solved.
* Solves only this function, assuming that its children are already
* simplified and it can be solved.
*
* @return The solved function.
* @throws Error Errors during computation, like a/0 or similar.
* @throws Error
* Errors during computation, like a/0 or similar.
*/
protected abstract ObjectArrayList<Function> solve() throws Error;
@ -112,14 +123,17 @@ public abstract class FunctionSingle implements Function {
}
/**
* The current simplification status of this function, assuming that its children are already simplified.
* @return <strong>true</strong> if this function can be solved, otherwise <strong>false</strong>.
* The current simplification status of this function, assuming that its
* children are already simplified.
*
* @return <strong>true</strong> if this function can be solved, otherwise
* <strong>false</strong>.
*/
protected abstract boolean isSolvable();
@Override
public abstract FunctionSingle clone();
@Override
public int hashCode() {
return parameter.hashCode() + 883 * super.hashCode();

View File

@ -12,7 +12,7 @@ import org.warp.picalculator.math.functions.equations.Equation;
import org.warp.picalculator.math.functions.equations.EquationsSystem;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
public class MathContext {
@ -122,4 +122,17 @@ public class MathContext {
}
}*/
@Override
@Deprecated
public MathContext clone() {
// MathContext mc = new MathContext();
// mc.angleMode = this.angleMode;
// mc.exactMode = this.exactMode;
// mc.f = this.f;
// mc.f2 = this.f2;
// mc.variablesValues = this.variablesValues;
// mc.resultsCount = this.resultsCount;
// return mc;
throw new NotImplementedException();
}
}

View File

@ -27,7 +27,6 @@ public class MathematicalSymbols {
public static final char ARC_TANGENT = 'Ⓗ';
public static final char PI = 'π';
public static final char[] functionsNSN = new char[] { NTH_ROOT, POWER };
public static final char[] functionsSN = new char[] { SQUARE_ROOT, POWER_OF_TWO, MINUS, SINE, COSINE, TANGENT, ARC_SINE, ARC_COSINE, ARC_TANGENT };
@ -36,7 +35,7 @@ public class MathematicalSymbols {
private static final char[] signumsWithoutMultiplication = new char[] { SUM, SUM_SUBTRACTION, SUBTRACTION, DIVISION };
private static final char[] signumsWithMultiplication = Utils.add(signumsWithoutMultiplication, MULTIPLICATION);
public static final char[] signums(boolean withMultiplication) {
if (withMultiplication) {
return signumsWithMultiplication;
@ -54,5 +53,5 @@ public class MathematicalSymbols {
return string.replace("", "^").replace("", "SIN").replace("", "COS").replace("", "TAN").replace("", "ASIN").replace("", "ACOS").replace("", "ATAN");
}
public static final char[] numbers = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
public static final char[] numbers = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
}

View File

@ -3,14 +3,9 @@ package org.warp.picalculator.math.functions;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.GraphicalElement;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.FractionsRule1;
import org.warp.picalculator.math.rules.FractionsRule11;
import org.warp.picalculator.math.rules.FractionsRule12;
@ -26,8 +21,8 @@ public class Division extends FunctionOperator {
@Override
protected boolean isSolvable() {
Function variable1 = getParameter1();
Function variable2 = getParameter2();
final Function variable1 = getParameter1();
final Function variable2 = getParameter2();
if (FractionsRule1.compare(this)) {
return true;
}
@ -49,8 +44,8 @@ public class Division extends FunctionOperator {
if (variable1 instanceof Number && variable2 instanceof Number) {
if (getMathContext().exactMode) {
try {
return ((Number)variable1).divide((Number)variable2).isInteger();
} catch (Error e) {
return ((Number) variable1).divide((Number) variable2).isInteger();
} catch (final Error e) {
return false;
}
} else {
@ -62,8 +57,8 @@ public class Division extends FunctionOperator {
@Override
public ObjectArrayList<Function> solve() throws Error {
Function variable1 = getParameter1();
Function variable2 = getParameter2();
final Function variable1 = getParameter1();
final Function variable2 = getParameter2();
ObjectArrayList<Function> result = new ObjectArrayList<>();
if (FractionsRule1.compare(this)) {
result = FractionsRule1.execute(this);
@ -82,7 +77,7 @@ public class Division extends FunctionOperator {
}
return result;
}
@Override
public boolean equals(Object o) {
if (o instanceof Division) {
@ -94,11 +89,11 @@ public class Division extends FunctionOperator {
@Override
public FunctionOperator clone() {
return new Division(this.getMathContext(), this.getParameter1(), this.getParameter2());
return new Division(getMathContext(), getParameter1(), getParameter2());
}
@Override
public String toString() {
return "("+this.getParameter1()+")/("+this.getParameter2()+")";
return "(" + getParameter1() + ")/(" + getParameter2() + ")";
}
}

View File

@ -1,12 +1,7 @@
package org.warp.picalculator.math.functions;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List;
import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
@ -18,7 +13,6 @@ public class EmptyNumber implements Function {
private final MathContext root;
@Override
public ObjectArrayList<Function> simplify() throws Error {
// TODO Auto-generated method stub
@ -34,7 +28,7 @@ public class EmptyNumber implements Function {
public MathContext getMathContext() {
return root;
}
@Override
public boolean equals(Object o) {
return o instanceof EmptyNumber;
@ -54,5 +48,5 @@ public class EmptyNumber implements Function {
public Function getParameter(int index) throws IndexOutOfBoundsException {
throw new IndexOutOfBoundsException();
}
}

View File

@ -12,7 +12,6 @@ import java.util.regex.Pattern;
import org.warp.picalculator.Error;
import org.warp.picalculator.Errors;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionDynamic;
@ -37,7 +36,7 @@ public class Expression extends FunctionDynamic {
}
public Expression(MathContext root, Function value) {
super(root, new Function[]{value});
super(root, new Function[] { value });
}
private boolean initialParenthesis = false;
@ -599,7 +598,7 @@ public class Expression extends FunctionDynamic {
return ret;
}
}
public boolean parenthesisNeeded() {
boolean parenthesisneeded = true;
if (initialParenthesis) {
@ -623,21 +622,21 @@ public class Expression extends FunctionDynamic {
}
return parenthesisneeded;
}
@Override
public String toString() {
String s = "(";
if (functions.length > 0) {
for (Function f : functions) {
for (final Function f : functions) {
if (f == null) {
s+="[null],";
s += "[null],";
} else {
s+=f.toString()+",";
s += f.toString() + ",";
}
}
s = s.substring(0, s.length()-1);
s = s.substring(0, s.length() - 1);
}
s+=")";
s += ")";
return s;
}

View File

@ -1,13 +1,7 @@
package org.warp.picalculator.math.functions;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List;
import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.BinaryFont;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;

View File

@ -5,9 +5,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.ExponentRule15;
import org.warp.picalculator.math.rules.ExponentRule16;
import org.warp.picalculator.math.rules.FractionsRule14;
@ -29,8 +27,8 @@ public class Multiplication extends FunctionOperator {
@Override
protected boolean isSolvable() {
Function variable1 = getParameter1();
Function variable2 = getParameter2();
final Function variable1 = getParameter1();
final Function variable2 = getParameter2();
if (variable1 instanceof Number & variable2 instanceof Number) {
return true;
}
@ -103,9 +101,9 @@ public class Multiplication extends FunctionOperator {
public Multiplication clone() {
return new Multiplication(mathContext, parameter1, parameter2);
}
@Override
public String toString() {
return "("+parameter1.toString()+")*("+parameter2.toString()+")";
return "(" + parameter1.toString() + ")*(" + parameter2.toString() + ")";
}
}

View File

@ -4,13 +4,9 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error;
import org.warp.picalculator.Errors;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.ExpandRule1;
import org.warp.picalculator.math.rules.ExpandRule5;

View File

@ -7,16 +7,11 @@ import java.util.LinkedList;
import java.util.List;
import org.nevec.rjm.BigDecimalMath;
import org.nevec.rjm.BigIntegerMath;
import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.BinaryFont;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import com.rits.cloning.Cloner;
public class Number implements Function {
private final MathContext root;
@ -109,7 +104,7 @@ public class Number implements Function {
public Number clone() {
return new Number(root, term);
}
@Override
public boolean isSimplified() {
if (root.exactMode) {
@ -123,20 +118,20 @@ public class Number implements Function {
public List<Function> simplify() throws Error {
final List<Function> result = new ObjectArrayList<>();
if (root.exactMode) {
Number divisor = new Number(root, BigInteger.TEN.pow(getNumberOfDecimalPlaces()));
Number numb = new Number(root, term.multiply(divisor.term));
Division div = new Division(root, numb, divisor);
final Number divisor = new Number(root, BigInteger.TEN.pow(getNumberOfDecimalPlaces()));
final Number numb = new Number(root, term.multiply(divisor.term));
final Division div = new Division(root, numb, divisor);
result.add(div);
} else {
result.add(this);
}
return result;
}
public int getNumberOfDecimalPlaces() {
return Math.max(0, term.stripTrailingZeros().scale());
return Math.max(0, term.stripTrailingZeros().scale());
}
public boolean isInteger() {
return getNumberOfDecimalPlaces() <= 0;
}

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.ExponentRule1;
import org.warp.picalculator.math.rules.ExponentRule2;
import org.warp.picalculator.math.rules.ExponentRule3;
@ -78,7 +77,7 @@ public class Power extends FunctionOperator {
}
return result;
}
@Override
public boolean equals(Object o) {
if (o instanceof Power) {

View File

@ -5,11 +5,9 @@ import java.math.BigInteger;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
public class Root extends FunctionOperator {
@ -60,7 +58,7 @@ public class Root extends FunctionOperator {
}
return result;
}
@Override
public boolean equals(Object o) {
if (o instanceof Root) {
@ -74,5 +72,5 @@ public class Root extends FunctionOperator {
public Root clone() {
return new Root(mathContext, parameter1, parameter2);
}
}

View File

@ -4,11 +4,9 @@ import java.math.BigInteger;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class RootSquare extends FunctionSingle {

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.ExpandRule1;
import org.warp.picalculator.math.rules.ExpandRule5;
import org.warp.picalculator.math.rules.NumberRule3;
@ -92,5 +91,5 @@ public class Subtraction extends FunctionOperator {
public Subtraction clone() {
return new Subtraction(mathContext, parameter1, parameter2);
}
}

View File

@ -5,12 +5,9 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error;
import org.warp.picalculator.Errors;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.NumberRule3;
import org.warp.picalculator.math.rules.NumberRule5;
import org.warp.picalculator.math.rules.NumberRule7;
@ -115,5 +112,5 @@ public class Sum extends FunctionOperator {
public Sum clone() {
return new Sum(mathContext, parameter1, parameter2);
}
}

View File

@ -4,13 +4,9 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error;
import org.warp.picalculator.Errors;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.ExpandRule1;
import org.warp.picalculator.math.rules.NumberRule3;
import org.warp.picalculator.math.rules.NumberRule4;
@ -76,5 +72,5 @@ public class SumSubtraction extends FunctionOperator {
public SumSubtraction clone() {
return new SumSubtraction(mathContext, parameter1, parameter2);
}
}

View File

@ -3,9 +3,6 @@ package org.warp.picalculator.math.functions;
import java.util.List;
import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
@ -16,7 +13,7 @@ public class Undefined implements Function {
public Undefined(MathContext root) {
this.root = root;
}
@Override
public List<Function> simplify() throws Error {
return null;

View File

@ -4,13 +4,9 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List;
import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import com.rits.cloning.Cloner;
public class Variable implements Function {
protected char var;
@ -47,7 +43,7 @@ public class Variable implements Function {
public String toString() {
return "" + getChar();
}
public static class VariableValue {
public final Variable v;
public final Number n;
@ -87,16 +83,14 @@ public class Variable implements Function {
public MathContext getMathContext() {
return root;
}
@Override
public Variable clone() {
return new Variable(root, var, type);
}
public static enum V_TYPE {
KNOWN,
UNKNOWN,
SOLUTION
KNOWN, UNKNOWN, SOLUTION
}
@Override

View File

@ -11,19 +11,16 @@ import org.warp.picalculator.Errors;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.SolveMethod;
import org.warp.picalculator.math.functions.Number;
import org.warp.picalculator.math.functions.Subtraction;
import com.rits.cloning.Cloner;
public class Equation extends FunctionOperator {
public Equation(MathContext root, Function value1, Function value2) {
super(root, value1, value2);
}
@Override
protected boolean isSolvable() {
if (parameter1 instanceof Number & parameter2 instanceof Number) {
@ -81,8 +78,7 @@ public class Equation extends FunctionOperator {
@Override
public Equation clone() {
final Cloner cloner = new Cloner();
return cloner.deepClone(this);
return new Equation(mathContext, parameter1, parameter2);
}
@Override

View File

@ -4,7 +4,6 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List;
import org.warp.picalculator.Error;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionDynamic;
@ -69,5 +68,5 @@ public class EquationsSystem extends FunctionDynamic {
public EquationsSystem clone() {
return new EquationsSystem(root, functions);
}
}

View File

@ -1,14 +1,10 @@
package org.warp.picalculator.math.functions.equations;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List;
import org.warp.picalculator.Error;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class EquationsSystemPart extends FunctionSingle {
@ -38,5 +34,5 @@ public class EquationsSystemPart extends FunctionSingle {
public EquationsSystemPart clone() {
return new EquationsSystemPart(mathContext, (Equation) parameter);
}
}

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class ArcCosine extends FunctionSingle {

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class ArcSine extends FunctionSingle {

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class ArcTangent extends FunctionSingle {

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class Cosine extends FunctionSingle {

View File

@ -8,7 +8,6 @@ import org.warp.picalculator.math.AngleMode;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.functions.Number;
public class Sine extends FunctionSingle {
@ -16,7 +15,7 @@ public class Sine extends FunctionSingle {
public Sine(MathContext root, Function value) {
super(root, value);
}
@Override
protected boolean isSolvable() {
if (parameter instanceof Number) {

View File

@ -6,14 +6,13 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class Tangent extends FunctionSingle {
public Tangent(MathContext root, Function value) {
super(root, value);
}
@Override
public ObjectArrayList<Function> solve() throws Error {
// TODO Auto-generated method stub

View File

@ -1,11 +1,16 @@
package org.warp.picalculator.math.parser;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import org.warp.picalculator.Error;
import org.warp.picalculator.Errors;
import org.warp.picalculator.gui.expression.Block;
import org.warp.picalculator.gui.expression.BlockChar;
import org.warp.picalculator.gui.expression.BlockContainer;
import org.warp.picalculator.gui.expression.BlockDivision;
import org.warp.picalculator.gui.expression.containers.InputContainer;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.FunctionSingle;
@ -15,6 +20,8 @@ import org.warp.picalculator.math.functions.Number;
import org.warp.picalculator.math.functions.Subtraction;
import org.warp.picalculator.math.functions.Sum;
import org.warp.picalculator.math.functions.SumSubtraction;
import org.warp.picalculator.math.functions.Variable;
import org.warp.picalculator.math.functions.Variable.V_TYPE;
import org.warp.picalculator.math.functions.Division;
import org.warp.picalculator.math.functions.Expression;
import org.warp.picalculator.math.functions.Multiplication;
@ -23,6 +30,7 @@ import org.warp.picalculator.math.parser.features.FeatureDivision;
import org.warp.picalculator.math.parser.features.FeatureMultiplication;
import org.warp.picalculator.math.parser.features.FeatureNumber;
import org.warp.picalculator.math.parser.features.FeatureSum;
import org.warp.picalculator.math.parser.features.FeatureVariable;
import org.warp.picalculator.math.parser.features.interfaces.Feature;
import org.warp.picalculator.math.parser.features.interfaces.FeatureDouble;
@ -30,75 +38,115 @@ import com.sun.org.apache.xpath.internal.functions.Function2Args;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectListIterator;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
public class MathParser {
public static Expression parseInput(MathContext context, BlockContainer root) throws Error {
public static Expression parseInput(MathContext context, InputContainer c) throws Error {
Expression result;
Function resultFunction = parseContainer(context, root);
final Function resultFunction = parseContainer(context, c.getContent());
result = new Expression(context, resultFunction);
return result;
}
private static Function parseContainer(final MathContext context, final BlockContainer container) throws Error {
final ObjectArrayList<Block> blocks = container.getContent();
final ObjectArrayList<Feature> blockFeatures = new ObjectArrayList<>();
public static ObjectArrayList<Block> parseOutput(MathContext context, ObjectArrayList<Function> expr) {
final ObjectArrayList<Block> resultBlocks = new ObjectArrayList<>();
for (final Block block : blocks) {
Feature blockFeature = parseBlock(context, block);
blockFeatures.add(blockFeature);
for (Function f : expr) {
resultBlocks.addAll(parseFunction(context, f));
}
Function result = joinFeatures(context, blockFeatures);
return result;
return resultBlocks;
}
private static ObjectArrayList<Block> parseFunction(MathContext context, Function func) {
ObjectArrayList<Block> result = new ObjectArrayList<>();
if (func instanceof FunctionOperator) {
ObjectArrayList<Block> sub1 = parseFunction(context, func.getParameter(0));
ObjectArrayList<Block> sub2 = parseFunction(context, func.getParameter(1));
if (func instanceof Sum) {
result.addAll(sub1);
result.add(new BlockChar(MathematicalSymbols.SUM));
result.addAll(sub2);
return result;
}
}
if (func instanceof Number) {
Number numb = (Number) func;
BigDecimal decimal = numb.getTerm();
String numberString;
if (numb.isInteger()) {
BigInteger integ = decimal.toBigInteger();
numberString = integ.toString();
} else {
numberString = decimal.toPlainString();
}
for (char c : numberString.toCharArray()) {
result.add(new BlockChar(c));
}
return result;
}
throw new UnsupportedOperationException("Unknown function " + func.getClass().getSimpleName());
}
private static Function parseContainer(final MathContext context, final Iterable<Block> blocks) throws Error {
final ObjectArrayList<Feature> blockFeatures = new ObjectArrayList<>();
for (final Block block : blocks) {
final Feature blockFeature = parseBlock(context, block);
blockFeatures.add(blockFeature);
}
final Function result = joinFeatures(context, blockFeatures);
return result;
}
private static Feature parseBlock(final MathContext context, final Block block) throws Error {
Feature result;
int blockType = block.getClassID();
final int blockType = block.getClassID();
switch (blockType) {
case BlockChar.CLASS_ID:
result = new FeatureChar(((BlockChar) block).getChar());
break;
case BlockDivision.CLASS_ID:
BlockDivision bd = (BlockDivision) block;
Function upper = parseContainer(context, bd.getUpperContainer());
Function lower = parseContainer(context, bd.getLowerContainer());
final BlockDivision bd = (BlockDivision) block;
final Function upper = parseContainer(context, bd.getUpperContainer().getContent());
final Function lower = parseContainer(context, bd.getLowerContainer().getContent());
result = new FeatureDivision(upper, lower);
break;
default:
throw new Error(Errors.SYNTAX_ERROR);
}
return result;
}
private static Function joinFeatures(final MathContext context, ObjectArrayList<Feature> features) throws Error {
features = fixFeatures(context, features);
ObjectArrayList<Function> process = makeFunctions(context, features);
final ObjectArrayList<Function> process = makeFunctions(context, features);
fixStack(context, process);
if (process.size() > 1) {
throw new Error(Errors.UNBALANCED_STACK, "The stack is unbalanced. Not all the functions are nested correctly");
}
return process.get(0);
}
private static void fixStack(MathContext context, ObjectArrayList<Function> process) throws Error {
//Phase 1
ObjectListIterator<Function> stackIterator = process.listIterator(process.size());
Function lastElement = null;
while (stackIterator.hasPrevious()) {
Function f = stackIterator.previous();
final Function f = stackIterator.previous();
if (f instanceof FunctionSingle) {
if (((FunctionSingle) f).getParameter() == null) {
if (lastElement == null) {
@ -115,19 +163,16 @@ public class MathParser {
//Phase 2
stackIterator = process.listIterator();
while (stackIterator.hasNext()) {
Function f = stackIterator.next();
final Function f = stackIterator.next();
final int curIndex = stackIterator.previousIndex();
if (f instanceof Multiplication || f instanceof Division) {
if (curIndex-1>=0 && stackIterator.hasNext()) {
Function next = process.get(curIndex+1);
Function prev = process.get(curIndex-1);
stackIterator.set(
f.setParameter(0, prev)
.setParameter(1, next)
);
process.remove(curIndex+1);
process.remove(curIndex-1);
if (curIndex - 1 >= 0 && stackIterator.hasNext()) {
final Function next = process.get(curIndex + 1);
final Function prev = process.get(curIndex - 1);
stackIterator.set(f.setParameter(0, prev).setParameter(1, next));
process.remove(curIndex + 1);
process.remove(curIndex - 1);
} else {
if (f.getParameter(0) == null || f.getParameter(1) == null) {
throw new Error(Errors.MISSING_ARGUMENTS, "There is a function at the end without any argument specified.");
@ -139,65 +184,88 @@ public class MathParser {
//Phase 3
stackIterator = process.listIterator();
while (stackIterator.hasNext()) {
Function f = stackIterator.next();
final Function f = stackIterator.next();
final int curIndex = stackIterator.previousIndex();
if (f instanceof Sum || f instanceof Subtraction || f instanceof SumSubtraction) {
if (curIndex - 1 >= 0 && stackIterator.hasNext()) {
final Function next = process.get(curIndex + 1);
final Function prev = process.get(curIndex - 1);
stackIterator.set(f.setParameter(0, prev).setParameter(1, next));
process.remove(curIndex + 1);
process.remove(curIndex - 1);
} else {
if (f.getParameter(0) == null || f.getParameter(1) == null) {
throw new Error(Errors.MISSING_ARGUMENTS, "There is a function at the end without any argument specified.");
}
}
}
}
//Phase 4
stackIterator = process.iterator();
while (stackIterator.hasNext()) {
Function f = stackIterator.next();
final Function f = stackIterator.next();
if (f instanceof Function2Args) {
}
}
}
private static ObjectArrayList<Function> makeFunctions(MathContext context, ObjectArrayList<Feature> features) throws Error {
ObjectArrayList<Function> process = new ObjectArrayList<>();
for (Feature f : features) {
private static ObjectArrayList<Function> makeFunctions(MathContext context, ObjectArrayList<Feature> features)
throws Error {
final ObjectArrayList<Function> process = new ObjectArrayList<>();
for (final Feature f : features) {
if (f instanceof FeatureDivision) {
process.add(new Division(context, (Function) ((FeatureDouble) f).getChild1(), (Function) ((FeatureDouble) f).getChild2()));
} else if (f instanceof FeatureMultiplication) {
process.add(new Multiplication(context, (Function) ((FeatureDouble) f).getChild1(), (Function) ((FeatureDouble) f).getChild2()));
} else if (f instanceof FeatureVariable) {
process.add(new Variable(context, ((FeatureVariable) f).ch, ((FeatureVariable) f).varType));
} else if (f instanceof FeatureSum) {
process.add(new Sum(context, (Function) ((FeatureDouble) f).getChild1(), (Function) ((FeatureDouble) f).getChild2()));
// } else if (f instanceof FeatureSubtraction) {
// process.add(new Subtraction(context, (Function) ((FeatureDouble) f).getChild1(), (Function) ((FeatureDouble) f).getChild2()));
// } else if (f instanceof FeatureSumSubtraction) {
// process.add(new SumSubtraction(context, (Function) ((FeatureDouble) f).getChild1(), (Function) ((FeatureDouble) f).getChild2()));
} else if (f instanceof FeatureNumber) {
process.add(new Number(context, ((FeatureNumber) f).getNumberString()));
} else if (f instanceof FeatureChar) {
//All the char features must have been changed already before
throw new Error(Errors.SYNTAX_ERROR, "\"" + f.getClass().getSimpleName().toString() + "\" can't be converted into a Function!");
throw new Error(Errors.SYNTAX_ERROR, "\"" + f.getClass().getSimpleName() + "\" can't be converted into a Function!");
} else {
throw new Error(Errors.SYNTAX_ERROR, "\"" + f.getClass().getSimpleName().toString() + "\" can't be converted into a Function!");
throw new Error(Errors.SYNTAX_ERROR, "\"" + f.getClass().getSimpleName() + "\" can't be converted into a Function!");
}
}
return process;
}
private static ObjectArrayList<Feature> fixFeatures(final MathContext context, ObjectArrayList<Feature> features) throws Error {
private static ObjectArrayList<Feature> fixFeatures(final MathContext context, ObjectArrayList<Feature> features)
throws Error {
features = fixMinuses(context, features);
features = makeNumbers(context, features);
features = convertFunctionChars(context, features);
return features;
}
/**
* Create function features from char features
*
* @param context
* @param features
* @return
*/
private static ObjectArrayList<Feature> convertFunctionChars(MathContext context, ObjectArrayList<Feature> features) throws Error {
ObjectArrayList<Feature> process = new ObjectArrayList<>();
for (Feature f : features) {
private static ObjectArrayList<Feature> convertFunctionChars(MathContext context, ObjectArrayList<Feature> features)
throws Error {
final ObjectArrayList<Feature> process = new ObjectArrayList<>();
for (final Feature f : features) {
if (f instanceof FeatureChar) {
final char featureChar = ((FeatureChar) f).ch;
Feature result = null;
@ -210,35 +278,44 @@ public class MathParser {
break;
}
//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
for (char var : MathematicalSymbols.variables) {
if ( featureChar == var) {
result = new FeatureVariable(featureChar, V_TYPE.UNKNOWN);
break;
}
}
if (result == null) {
throw new Error(Errors.SYNTAX_ERROR, "Char " + featureChar + " isn't a known feature");
}
process.add(result);
} else {
process.add(f);
}
}
return process;
}
/**
* Make numbers [-][1][2][+][-][3] => [-12]
*
* @param context
* @param features
* @return
*/
private static ObjectArrayList<Feature> makeNumbers(MathContext context, ObjectArrayList<Feature> features) {
ObjectArrayList<Feature> process = new ObjectArrayList<>();
final ObjectArrayList<Feature> process = new ObjectArrayList<>();
FeatureNumber numberBuffer = null;
for (Feature f : features) {
for (final Feature f : features) {
if (f instanceof FeatureChar) {
final FeatureChar bcf = (FeatureChar) f;
final char[] numbers = MathematicalSymbols.numbers;
boolean isNumber = false;
for (char n : numbers) {
for (final char n : numbers) {
if (bcf.ch == n) {
isNumber = true;
break;
@ -264,29 +341,31 @@ public class MathParser {
process.add(f);
}
}
return process;
}
/**
* Fix minuses [-][1][2][+][-][3][-][2] => [-][12][+][-][3][][2]
*
* @param context
* @param features
* @return
* @throws Error
*/
private static ObjectArrayList<Feature> fixMinuses(final MathContext context, ObjectArrayList<Feature> features) throws Error {
ObjectArrayList<Feature> process = new ObjectArrayList<>();
private static ObjectArrayList<Feature> fixMinuses(final MathContext context, ObjectArrayList<Feature> features)
throws Error {
final ObjectArrayList<Feature> process = new ObjectArrayList<>();
Feature lastFeature = null;
for (Feature f : features) {
if (f instanceof FeatureChar && ((FeatureChar)f).ch == MathematicalSymbols.SUBTRACTION) {
for (final Feature f : features) {
if (f instanceof FeatureChar && ((FeatureChar) f).ch == MathematicalSymbols.SUBTRACTION) {
boolean isNegativeOfNumber = false;
if (lastFeature == null) {
isNegativeOfNumber = true;
} else if (lastFeature instanceof FeatureChar) {
FeatureChar lcf = (FeatureChar) lastFeature;
final FeatureChar lcf = (FeatureChar) lastFeature;
final char[] operators = MathematicalSymbols.functionsNSN;
for (char operator : operators) {
for (final char operator : operators) {
if (lcf.ch == operator) {
isNegativeOfNumber = true;
break;

View File

@ -5,7 +5,7 @@ import org.warp.picalculator.math.parser.features.interfaces.Feature;
public class FeatureChar implements Feature {
public final char ch;
public FeatureChar(char ch) {
this.ch = ch;
}

View File

@ -5,12 +5,12 @@ import org.warp.picalculator.math.parser.features.interfaces.FeatureDouble;
public abstract class FeatureDoubleImpl implements FeatureDouble {
private Object child_1;
private Object child_2;
public FeatureDoubleImpl(Object child1, Object child2) {
child_1 = child1;
child_2 = child2;
}
@Override
public Object getChild1() {
return child_1;

View File

@ -4,24 +4,24 @@ import org.warp.picalculator.math.parser.features.interfaces.FeatureBasic;
public class FeatureNumber implements FeatureBasic {
private String numberString;
public FeatureNumber(char c){
numberString = c+"";
public FeatureNumber(char c) {
numberString = c + "";
}
public FeatureNumber(String s) {
numberString = s;
}
public FeatureNumber() {
numberString = "";
}
public String getNumberString() {
return numberString;
}
public void append(char ch) {
numberString+=ch;
numberString += ch;
}
}

View File

@ -4,11 +4,11 @@ import org.warp.picalculator.math.parser.features.interfaces.FeatureSingle;
public abstract class FeatureSingleImpl implements FeatureSingle {
private Object child;
public FeatureSingleImpl(Object child) {
this.child = child;
}
@Override
public Object getChild() {
return child;

View File

@ -0,0 +1,15 @@
package org.warp.picalculator.math.parser.features;
import org.warp.picalculator.math.functions.Variable.V_TYPE;
import org.warp.picalculator.math.parser.features.interfaces.Feature;
public class FeatureVariable extends FeatureChar {
public V_TYPE varType;
public FeatureVariable(char ch, V_TYPE varType) {
super(ch);
this.varType = varType;
}
}

View File

@ -1,5 +1,5 @@
package org.warp.picalculator.math.parser.features.interfaces;
public abstract interface Feature {
}

View File

@ -1,4 +1,3 @@
package org.warp.picalculator.math.parser.features.interfaces;
public interface FeatureBasic extends Feature {
}
public interface FeatureBasic extends Feature {}

View File

@ -2,7 +2,10 @@ package org.warp.picalculator.math.parser.features.interfaces;
public interface FeatureDouble extends Feature {
public Object getChild1();
public void setChild1(Object obj);
public Object getChild2();
public void setChild2(Object obj);
}

View File

@ -2,9 +2,14 @@ package org.warp.picalculator.math.parser.features.interfaces;
public interface FeatureMultiple extends Feature {
public Object[] getChildren();
public Object getChild(int index);
public int getChildCount();
public void setChild(int index, Object obj);
public void setChildren(Object[] objs);
public void addChild(Object obj);
}

View File

@ -2,5 +2,6 @@ package org.warp.picalculator.math.parser.features.interfaces;
public interface FeatureSingle extends Feature {
public Object getChild();
public void setChild(Object obj);
}

View File

@ -23,11 +23,11 @@ public class ExponentRule16 {
public static boolean compare(Function f) {
final Multiplication fnc = (Multiplication) f;
if (fnc.getParameter1() instanceof Power && fnc.getParameter2() instanceof Power) {
return ((Power)fnc.getParameter1()).getParameter1().equals(((Power)fnc.getParameter2()).getParameter1());
return ((Power) fnc.getParameter1()).getParameter1().equals(((Power) fnc.getParameter2()).getParameter1());
} else if (fnc.getParameter1() instanceof Power) {
return ((Power)fnc.getParameter1()).getParameter1().equals(fnc.getParameter2());
return ((Power) fnc.getParameter1()).getParameter1().equals(fnc.getParameter2());
} else if (fnc.getParameter2() instanceof Power) {
return ((Power)fnc.getParameter2()).getParameter1().equals(fnc.getParameter1());
return ((Power) fnc.getParameter2()).getParameter1().equals(fnc.getParameter1());
}
return false;
}
@ -37,11 +37,11 @@ public class ExponentRule16 {
final ObjectArrayList<Function> result = new ObjectArrayList<>();
final Multiplication fnc = (Multiplication) f;
if (fnc.getParameter1() instanceof Power && fnc.getParameter2() instanceof Power) {
result.add(new Power(root, ((Power)fnc.getParameter1()).getParameter1(), new Sum(root, new Expression(root, ((Power)fnc.getParameter1()).getParameter2()), new Expression(root, ((Power)fnc.getParameter2()).getParameter2()))));
result.add(new Power(root, ((Power) fnc.getParameter1()).getParameter1(), new Sum(root, new Expression(root, ((Power) fnc.getParameter1()).getParameter2()), new Expression(root, ((Power) fnc.getParameter2()).getParameter2()))));
} else if (fnc.getParameter1() instanceof Power) {
result.add(new Power(root, ((Power)fnc.getParameter1()).getParameter1(), new Sum(root, new Expression(root, ((Power)fnc.getParameter1()).getParameter2()), new Number(root, 1))));
result.add(new Power(root, ((Power) fnc.getParameter1()).getParameter1(), new Sum(root, new Expression(root, ((Power) fnc.getParameter1()).getParameter2()), new Number(root, 1))));
} else if (fnc.getParameter2() instanceof Power) {
result.add(new Power(root, ((Power)fnc.getParameter1()).getParameter1(), new Sum(root, new Number(root, 1), new Expression(root, ((Power)fnc.getParameter2()).getParameter2()))));
result.add(new Power(root, ((Power) fnc.getParameter1()).getParameter1(), new Sum(root, new Number(root, 1), new Expression(root, ((Power) fnc.getParameter2()).getParameter2()))));
}
return result;
}

View File

@ -7,7 +7,6 @@ import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.functions.Expression;
import org.warp.picalculator.math.functions.Multiplication;
import org.warp.picalculator.math.functions.Number;
import org.warp.picalculator.math.functions.Power;
/**

View File

@ -39,8 +39,8 @@ public class FractionsRule11 {
Function b;
Function c;
Division div2 = (Division) fnc.getParameter2();
final Division div2 = (Division) fnc.getParameter2();
a = fnc.getParameter1();
b = div2.getParameter1();
c = div2.getParameter2();

View File

@ -38,7 +38,6 @@ public class VariableRule2 {
final Function a = m1.getParameter1();
final Function x = fnc.getParameter2();
FunctionOperator rets;
if (fnc instanceof Sum) {
rets = new Sum(root, a, new Number(root, 1));