diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 989e74ff9..16af67824 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -15,6 +15,8 @@ jobs: runs-on: ubuntu-latest steps: + - name: Install updated FreeType + run: sudo apt-get update;sudo apt-get install libfreetype6 - name: Checkout repository and submodules uses: actions/checkout@v2 with: @@ -37,7 +39,7 @@ jobs: export DISPLAY=:0 - name: Pull a JavaFX JDK - run: wget http://static.azul.com/zulu/bin/zulu8.33.0.1-ca-fx-jdk8.0.192-linux_x64.tar.gz + run: wget http://static.azul.com/zulu/bin/zulu8.78.0.19-ca-fx-jdk8.0.412-linux_x64.tar.gz - name: After JDK download, list directory contnts run: pwd; ls -la @@ -46,7 +48,7 @@ jobs: uses: actions/setup-java@v1 with: java-version: 1.8 - jdkFile: ./zulu8.33.0.1-ca-fx-jdk8.0.192-linux_x64.tar.gz + jdkFile: ./zulu8.78.0.19-ca-fx-jdk8.0.412-linux_x64.tar.gz - name: Build with Gradle @@ -59,17 +61,17 @@ jobs: run: cat /home/runner/work/bowler-script-kernel/bowler-script-kernel/build/reports/tests/test/index.html - name: Test Bezier - run: xvfb-run -s '-screen 0 1024x768x24' java -Dprism.verbose=true -Dprism.forceGPU=true -jar build/libs/bowler-kernel.jar -g https://gist.github.com/4aeeaa49bd3a807eed8f8ff3dea84c48.git BezierEditorDemo.groovy + run: xvfb-run -s '-screen 0 1024x768x24' java -Dprism.order=sw -Dprism.verbose=true -jar build/libs/bowler-kernel.jar -g https://gist.github.com/4aeeaa49bd3a807eed8f8ff3dea84c48.git BezierEditorDemo.groovy - name: start xvfb run: Xvfb :0 & - name: Test Local - run: xvfb-run -s '-screen 0 1024x768x24' java -Dprism.verbose=true -Dprism.forceGPU=true -jar build/libs/bowler-kernel.jar -f kernel-return-test.groovy + run: xvfb-run -s '-screen 0 1024x768x24' java -Dprism.order=sw -Dprism.verbose=true -jar build/libs/bowler-kernel.jar -f kernel-return-test.groovy - name: Clean Cad run: rm -rf $HOME/bowler-workspace/gitcache/github.com/Hephaestus-Arm/HephaestusArm2 - name: build Cad - run: xvfb-run -s '-screen 0 1024x768x24' java -Dprism.verbose=true -Dprism.forceGPU=true -jar build/libs/bowler-kernel.jar -g https://github.com/Hephaestus-Arm/HephaestusArm2.git hephaestus.xml + run: xvfb-run -s '-screen 0 1024x768x24' java -Dprism.order=sw -Dprism.verbose=true -jar build/libs/bowler-kernel.jar -g https://github.com/Hephaestus-Arm/HephaestusArm2.git hephaestus.xml diff --git a/.gitignore b/.gitignore index e36658e55..db79a34f9 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,4 @@ physicsTest /test*.stl /test.blend1 /test.* +*.doodle diff --git a/GithubPasswordManager b/GithubPasswordManager index eda3dc602..9da2226c2 160000 --- a/GithubPasswordManager +++ b/GithubPasswordManager @@ -1 +1 @@ -Subproject commit eda3dc602e1bd50d2340fc9477b76476158c6921 +Subproject commit 9da2226c2553c0ede08a62bcf18c69e43175c2a6 diff --git a/JCSG b/JCSG index a6ad60b1a..21878fc49 160000 --- a/JCSG +++ b/JCSG @@ -1 +1 @@ -Subproject commit a6ad60b1a722898c4ed761437d031817ec7a42a8 +Subproject commit 21878fc49db49bd58474a3062a9d372d1f835c3b diff --git a/build.gradle b/build.gradle index c37148d2b..b43161c6c 100755 --- a/build.gradle +++ b/build.gradle @@ -7,7 +7,6 @@ buildscript { maven { url "https://repo1.maven.org/maven2/" }, - //jcenter(), mavenCentral(), maven { url "https://plugins.gradle.org/m2/" @@ -121,250 +120,155 @@ String getOsArch() { repositories { mavenCentral() maven { - url 'https://mlt.jfrog.io/artifactory/mlt-mvn-releases-local/' + url 'https://commonwealthrobotics.com/jcenter-mirror/' + allowInsecureProtocol = true } maven { url 'https://repo.maven.apache.org/maven2/' } - + maven { url 'https://repo1.maven.org/maven2/'} -//https://jcenter.bintray.com< - maven { url 'https://jcenter.bintray.com/'} - - //jcenter() + maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } //maven { url 'https://oss.sonatype.org/service/local/staging/deploy/maven2/' } maven { url 'https://oss.sonatype.org/content/repositories/releases/' } //com.neuronrobotics hosting point maven { url 'https://oss.sonatype.org/content/repositories/staging/' } - maven { - url "https://repo.myrobotlab.org/artifactory/myrobotlab/" - content { - includeGroup("de.dfki.mary") - } - } +// maven { +// url "https://repo.myrobotlab.org/artifactory/myrobotlab/" +// content { +// includeGroup("de.dfki.mary") +// } +// } maven { url 'https://maven-central.storage-download.googleapis.com/repos/central/data/'} maven {url 'https://repo.jenkins-ci.org/public/'} - // maven { - // url "https://dl.bintray.com/ihmcrobotics/maven-release/" - // content { - // includeGroup("us.ihmc") - // } - // } - // maven { - // url "https://dl.bintray.com/ihmcrobotics/maven-vendor/" - // content { - // includeGroup("us.ihmc.thirdparty.jinput") - // } - // } + maven { + url "https://repo.jenkins-ci.org/releases/" + } + + maven { url "https://jitpack.io" } + maven { url "https://repo.eclipse.org/content/groups/releases/" } + maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } + maven { url "https://dl.bintray.com/dfki-lt/maven/" } + maven { url "https://raw.github.com/marytts/marytts/master/repository/" } + maven { url "https://repo.jenkins-ci.org/public/" } + } dependencies { - //compile group: "de.swirtz", name: "ktsRunner", version: "0.0.7" -api 'us.ihmc:jinput:2.0.6-ihmc2' -api group: 'us.ihmc', name: 'ihmc-native-library-loader', version: '1.3.1' -//implementation 'net.java.jinput:jinput:2.0.10' // pegged to Java 17, no MacOS m1 support until java updated -//implementation 'net.java.jinput:jinput:2.0.10:natives-all' + api 'com.neuronrobotics:JavaCad:2.5.0' + api project('java-bowler') + api project('GithubPasswordManager:GithubPasswordManager') + -api 'com.google.crypto.tink:tink:1.3.0-rc1' -api group: 'org.json', name: 'json', version: '20180813' + //compile group: "de.swirtz", name: "ktsRunner", version: "0.0.7" + api 'us.ihmc:jinput:2.0.6-ihmc2' + api group: 'us.ihmc', name: 'ihmc-native-library-loader', version: '1.3.1' -api 'gov.nist.math:jama:1.0.2' + api 'com.google.crypto.tink:tink:1.3.0-rc1' -api group: 'org.fxmisc.richtext', name: 'richtextfx', version: '0.6' + api group: 'org.json', name: 'json', version: '20180813' -api group: 'org.reactfx', name: 'reactfx', version: '2.0-SNAPSHOT' + api 'gov.nist.math:jama:1.0.2' -// https://mvnrepository.com/artifact/org.apache.groovy/groovy -api group: 'org.apache.groovy', name: 'groovy', version: '4.0.22' -//make grapes work -api group: 'org.apache.ivy', name: 'ivy', version: '2.5.1' + api group: 'org.fxmisc.richtext', name: 'richtextfx', version: '0.6' - //compile group: 'org.controlsfx', name: 'controlsfx', version: '8.0.6' -api group: 'commons-lang', name: 'commons-lang', version: '2.6' -api group: 'commons-codec', name: 'commons-codec', version: '1.7' + api group: 'org.reactfx', name: 'reactfx', version: '2.0-SNAPSHOT' + // https://mvnrepository.com/artifact/org.apache.groovy/groovy + api group: 'org.apache.groovy', name: 'groovy', version: '4.0.22' + //make grapes work + api group: 'org.apache.ivy', name: 'ivy', version: '2.5.1' + //compile group: 'org.controlsfx', name: 'controlsfx', version: '8.0.6' + api group: 'commons-lang', name: 'commons-lang', version: '2.6' + api group: 'commons-codec', name: 'commons-codec', version: '1.7' // https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit - implementation group: 'org.eclipse.jgit', name: 'org.eclipse.jgit', version: '5.13.1.202206130422-r' + api group: 'org.eclipse.jgit', name: 'org.eclipse.jgit', version: '5.13.1.202206130422-r' // https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit.ssh.apache - implementation group: 'org.eclipse.jgit', name: 'org.eclipse.jgit.ssh.apache', version: '5.13.1.202206130422-r' - + api group: 'org.eclipse.jgit', name: 'org.eclipse.jgit.ssh.apache', version: '5.13.1.202206130422-r' // https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -api group: 'org.apache.httpcomponents.client5', name: 'httpclient5', version: '5.2.1' - + api group: 'org.apache.httpcomponents.client5', name: 'httpclient5', version: '5.2.1' + api group: 'com.squareup.okhttp', name: 'okhttp-urlconnection', version: '2.0.0' + api group: 'org.mockito', name: 'mockito-all', version: '1.9.5' + api group: 'com.infradna.tool', name: 'bridge-method-injector', version: '1.14' -api group: 'com.squareup.okhttp', name: 'okhttp-urlconnection', version: '2.0.0' -api group: 'org.mockito', name: 'mockito-all', version: '1.9.5' -api group: 'com.infradna.tool', name: 'bridge-method-injector', version: '1.14' - -api 'com.miglayout:miglayout-swing:4.2' -api 'commons-io:commons-io:2.6' -api group:'org.python',name:'jython',version:'2.5.3' -api group:'org.python',name:'jython-standalone',version:'2.5.2' -api 'org.clojure:clojure:1.8.0' + api 'com.miglayout:miglayout-swing:4.2' + api 'commons-io:commons-io:2.6' + api group:'org.python',name:'jython',version:'2.5.3' + api group:'org.python',name:'jython-standalone',version:'2.5.2' + api 'org.clojure:clojure:1.8.0' // jetty server -api "org.eclipse.jetty:jetty-server:9.0.2.v20130417" -api "org.eclipse.jetty:jetty-servlet:9.0.2.v20130417" -api "org.eclipse.jetty:jetty-servlets:9.0.2.v20130417" -api "org.eclipse.jetty:jetty-webapp:9.0.2.v20130417" -api "javax.servlet:javax.servlet-api:3.1.0" - + api "org.eclipse.jetty:jetty-server:9.0.2.v20130417" + api "org.eclipse.jetty:jetty-servlet:9.0.2.v20130417" + api "org.eclipse.jetty:jetty-servlets:9.0.2.v20130417" + api "org.eclipse.jetty:jetty-webapp:9.0.2.v20130417" + api "javax.servlet:javax.servlet-api:3.1.0" + api group: 'java3d', name: 'vecmath', version: '1.3.1' + api 'org.slf4j:slf4j-simple:1.6.1' - //compile 'org.clojure:tools.nrepl:0.2.10' - //compile "overtone:overtone:0.9.1" - //compile "edu.cmu.sphinx:sphinx4-core:5prealpha-SNAPSHOT" - //compile "edu.cmu.sphinx:sphinx4-data:5prealpha-SNAPSHOT" -api group: 'java3d', name: 'vecmath', version: '1.3.1' -api 'org.slf4j:slf4j-simple:1.6.1' + api group:'de.huxhorn.sulky', name:'de.huxhorn.sulky.3rdparty.jlayer', version:'1.0' + api 'com.google.code.gson:gson:2.5' + api 'org.jsoup:jsoup:1.8.3' + api 'org.apache.httpcomponents:httpclient:4.5.1' - //compile group: 'com.neuronrobotics', name:'GithubPasswordManager', version:'0.6.1' - //compile "com.neuronrobotics:JavaCad:0.14.0" - //compile project('JCSG') -api 'com.neuronrobotics:JavaCad:1.1.1' - - //compile "com.neuronrobotics:CHDK-PTP-Java:0.5.3-SNAPSHOT" - //compile "com.neuronrobotics:java-bowler:3.25.4" -api project('java-bowler') -api project('GithubPasswordManager:GithubPasswordManager') - //compile fileTree (dir: ':java-bowler/libs/', includes: ['*.jar']) - //compile fileTree (dir: '../java-bowler/build/libs/', includes: ['nrsdk-3.23.3-jar-with-dependencies.jar']) - //compile fileTree (dir: '../JCSG/build/libs/', includes: ['JavaCad-0.8.2.jar']) - //compile "com.neuronroboticsp:WalnutiQ:2.3.3" - - - /* - String basedir =System.getenv("OPENCV_DIR")+"/java/opencv-249.jar"; - if(isWindows()){ - basedir =System.getenv("OPENCV_DIR")+"\\..\\..\\java\\opencv-249.jar"; - println("OPENCV_DIR="+basedir); - compile files(basedir) - } - if(isOSX()){ - basedir =System.getenv("OPENCV_DIR")+"../../java/opencv-249.jar"; - println("OPENCV_DIR="+basedir); - if(System.getenv("OPENCV_DIR")!=null) - compile files(basedir) - else - //If you set your OPENCV_DIR environment variable, then we wouldnt have to do hacky things - compile files('/Applications/BowlerStudio.app/Contents/MacOS/opencv249build/bin/opencv-249.jar') - } - if(isLinux()){ - //compile files('/usr/share/java/opencv-249.jar') - if(new File("/usr/share/OpenCV/java/").exists()){ - System.out.println("Using the legacy opencv dir ") - compile fileTree (dir: '/usr/share/OpenCV/java/', includes: ['*opencv-24*.jar']) - }else{ - compile fileTree (dir: '/usr/share/java/', includes: ['*opencv-24*.jar']) - } - } - */ - //compile group: 'jfree', name: 'jfreechart', version: '1.0.12' - //compile group: 'jexcelapi', name: 'jxl', version: '2.4.2' - //compile group: 'com.google.zxing', name: 'zxing-parent', version: '3.2.0' - //compile group:'com.github.ellzord', name:'JALSE', version:'1.0.9' - -api group:'de.huxhorn.sulky', name:'de.huxhorn.sulky.3rdparty.jlayer', version:'1.0' - //compile("org.springframework.boot:spring-boot-starter-web:1.2.7.RELEASE") - -api 'com.google.code.gson:gson:2.5' -api 'org.jsoup:jsoup:1.8.3' -api 'org.apache.httpcomponents:httpclient:4.5.1' - //compile 'cz.advel.jbullet:jbullet:20101010-1' - //compile 'org.bubblecloud.jbullet:jbullet:2.72.2.4'// jars local because mave repo for this went down - //compile "alda:alda:1.0.0-rc14" - - //Deep Learning 4 j and dependancies - /* - compile 'org.deeplearning4j:deeplearning4j-core:0.4-rc3.8' - //compile 'org.nd4j:nd4j-x86:0.4-rc3.8' - compile 'org.deeplearning4j:deeplearning4j-nlp:0.4-rc3.8' - compile 'org.deeplearning4j:deeplearning4j-ui:0.4-rc3.8' - //compile 'com.google.guava:guava:19.0' - compile 'org.nd4j:canova-nd4j-image:0.0.0.14' - compile 'org.nd4j:canova-nd4j-codec:0.0.0.14' - compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.5.1' - */ - // JScience: - //compile 'org.jscience:jscience:4.3.1' - - //compile 'javax.media:jmf:2.1.1e' - - //Weka - //compile 'nz.ac.waikato.cms.weka:weka-stable:3.6.13' - - //Firmata -api 'com.github.kurbatov:firmata4j:2.3.4.1' + api 'com.github.kurbatov:firmata4j:2.3.4.1' testImplementation 'junit:junit:4.10' -//api fileTree (dir: 'libs', includes: ['*.jar']) - // https://mvnrepository.com/artifact/com.github.stephengold/jbullet api group: 'com.github.stephengold', name: 'jbullet', version: '1.0.3' - - implementation('de.dfki.mary:voice-cmu-slt-hsmm:5.2.1') - { + +// implementation('de.dfki.mary:voice-cmu-slt-hsmm:5.2.1') { +// exclude group: 'commons-io', module: 'commons-io' +// exclude group: 'com.twmacinta', module: 'fast-md5' +// exclude group: 'gov.nist.math', module: 'Jampack' +// } + implementation('de.dfki.mary:voice-dfki-poppy-hsmm:5.2') { exclude group: 'commons-io', module: 'commons-io' exclude group: 'com.twmacinta', module: 'fast-md5' exclude group: 'gov.nist.math', module: 'Jampack' } - implementation('de.dfki.mary:voice-dfki-poppy-hsmm:5.2') - { + + implementation('de.dfki.mary:voice-dfki-prudence-hsmm:5.2') { exclude group: 'commons-io', module: 'commons-io' exclude group: 'com.twmacinta', module: 'fast-md5' exclude group: 'gov.nist.math', module: 'Jampack' } -// implementation('de.dfki.mary:voice-cmu-awb-time:5.2') -// { -// exclude group: 'commons-io', module: 'commons-io' -// } - implementation('de.dfki.mary:voice-dfki-prudence-hsmm:5.2') - { + implementation('de.dfki.mary:voice-dfki-spike-hsmm:5.2') { exclude group: 'commons-io', module: 'commons-io' exclude group: 'com.twmacinta', module: 'fast-md5' exclude group: 'gov.nist.math', module: 'Jampack' } - implementation('de.dfki.mary:voice-dfki-spike-hsmm:5.2') - { + implementation('de.dfki.mary:voice-cmu-rms-hsmm:5.2') { exclude group: 'commons-io', module: 'commons-io' + exclude group: 'com.twmacinta', module: 'fast-md5' exclude group: 'gov.nist.math', module: 'Jampack' } - implementation('de.dfki.mary:voice-cmu-rms-hsmm:5.2') - { - exclude group: 'commons-io', module: 'commons-io' - - exclude group: 'com.twmacinta', module: 'fast-md5' - exclude group: 'gov.nist.math', module: 'Jampack' - } - implementation('de.dfki.mary:voice-dfki-obadiah-hsmm:5.2') - { - exclude group: 'commons-io', module: 'commons-io' - - exclude group: 'com.twmacinta', module: 'fast-md5' - exclude group: 'gov.nist.math', module: 'Jampack' - } - implementation('de.dfki.mary:voice-cmu-rms-hsmm:5.2') - { - exclude group: 'commons-io', module: 'commons-io' - - exclude group: 'com.twmacinta', module: 'fast-md5' - exclude group: 'gov.nist.math', module: 'Jampack' - } - implementation('de.dfki.mary:voice-cmu-bdl-hsmm:5.2') - { - exclude group: 'commons-io', module: 'commons-io' - - exclude group: 'com.twmacinta', module: 'fast-md5' - exclude group: 'gov.nist.math', module: 'Jampack' - } - implementation('de.dfki.mary:marytts-lang-en:5.2.1') - { + implementation('de.dfki.mary:voice-dfki-obadiah-hsmm:5.2') { + exclude group: 'commons-io', module: 'commons-io' + + exclude group: 'com.twmacinta', module: 'fast-md5' + exclude group: 'gov.nist.math', module: 'Jampack' + } + implementation('de.dfki.mary:voice-cmu-rms-hsmm:5.2') { + exclude group: 'commons-io', module: 'commons-io' + + exclude group: 'com.twmacinta', module: 'fast-md5' + exclude group: 'gov.nist.math', module: 'Jampack' + } + implementation('de.dfki.mary:voice-cmu-bdl-hsmm:5.2') { + exclude group: 'commons-io', module: 'commons-io' + + exclude group: 'com.twmacinta', module: 'fast-md5' + exclude group: 'gov.nist.math', module: 'Jampack' + } + implementation('de.dfki.mary:marytts-lang-en:5.2.1') { exclude group: 'commons-io', module: 'commons-io' exclude group: 'com.twmacinta', module: 'fast-md5' exclude group: 'gov.nist.math', module: 'Jampack' @@ -383,7 +287,19 @@ api 'com.github.kurbatov:firmata4j:2.3.4.1' //MuJoCo implementation group: 'org.bytedeco', name: 'javacpp', version: '1.5.7' - implementation group: 'com.neuronrobotics', name: 'mujoco-java', version:'3.1.3-pre.11' + implementation group: 'com.neuronrobotics', name: 'mujoco-java', version:'3.1.3-pre.17' + //Java17 update + // JAXB API + implementation 'javax.xml.bind:jaxb-api:2.3.1' + + // JAXB Implementation + implementation 'com.sun.xml.bind:jaxb-impl:2.3.1' + + // JAXB Core + implementation 'com.sun.xml.bind:jaxb-core:2.3.0.1' + + // Java Activation needed by JAXB + implementation 'javax.activation:javax.activation-api:1.2.0' // https://mvnrepository.com/artifact/org.robokind/org.robokind.api.speech implementation group: 'org.robokind', name: 'org.robokind.api.speech', version: '0.9.5' @@ -391,8 +307,7 @@ api 'com.github.kurbatov:firmata4j:2.3.4.1' // https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j implementation group: 'net.lingala.zip4j', name: 'zip4j', version: '2.11.5' // https://mvnrepository.com/artifact/com.alphacephei/vosk - implementation( 'com.alphacephei:vosk:0.3.38') - { + implementation( 'com.alphacephei:vosk:0.3.38') { exclude group: 'net.java.dev.jna', module: 'jna' } // Add OpenCV @@ -404,7 +319,7 @@ api 'com.github.kurbatov:firmata4j:2.3.4.1' implementation 'org.apache.commons:commons-compress:1.26.2' // Addiing advance system execution for advanced editors implementation 'org.apache.commons:commons-exec:1.3' - + implementation 'org.tukaani:xz:1.9' implementation 'org.brotli:dec:0.1.2' // Add this for Brotli support // Add 7z native bindings @@ -412,8 +327,6 @@ api 'com.github.kurbatov:firmata4j:2.3.4.1' implementation 'net.sf.sevenzipjbinding:sevenzipjbinding-all-platforms:16.02-2.01' // inkscape loading implementation group: 'org.apache.xmlgraphics', name: 'batik-all', version: '1.17' - - } @@ -457,13 +370,13 @@ archivesBaseName = "bowler-script-kernel" task javadocJar(type: Jar) { if (project == rootProject) - classifier = 'javadoc' + classifier = 'javadoc' from javadoc } task sourcesJar(type: Jar) { if (project == rootProject) - classifier = 'sources' + classifier = 'sources' from sourceSets.main.allSource } diff --git a/java-bowler b/java-bowler index f0c79d208..c25c1fe14 160000 --- a/java-bowler +++ b/java-bowler @@ -1 +1 @@ -Subproject commit f0c79d2083d993f5721d608b295e813ab5098c3f +Subproject commit c25c1fe14d0f7a6a64ad138bca6c15d82af685d1 diff --git a/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/BezierEditor.java b/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/BezierEditor.java index acc48e76a..60c53ce82 100644 --- a/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/BezierEditor.java +++ b/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/BezierEditor.java @@ -133,21 +133,21 @@ public BezierEditor(File data, int numPoints) { endManip.addSaveListener(() -> { save(); }); - endManip.addEventListener(() -> { + endManip.addEventListener(e -> { update(); }); cp1Manip.addSaveListener(() -> { save(); }); - cp1Manip.addEventListener(() -> { + cp1Manip.addEventListener(e -> { update(); }); cp2Manip.addSaveListener(() -> { save(); }); - cp2Manip.addEventListener(() -> { + cp2Manip.addEventListener(e -> { update(); }); ArrayList parts = new ArrayList<>(); @@ -232,7 +232,7 @@ private TransformNR updateLines(CartesianManipulator m, CartesianManipulator p, TransformNR az = new TransformNR(0, 0, 0, new RotationNR(0, -xyRot, 0)); TransformNR reorented = az.times(vect); - // System.out.println("CP1 "+reorented.getX()+" "+reorented.getY()+" + // com.neuronrobotics.sdk.common.Log.error("CP1 "+reorented.getX()+" "+reorented.getY()+" // "+reorented.getZ()); double xzRot = Math.toDegrees(Math.atan2(reorented.getZ(), reorented.getY())); @@ -325,14 +325,14 @@ public void save() { database.put("bezier", bezData); new Thread(() -> { - System.out.println("Saving to file " + cachejson.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Saving to file " + cachejson.getAbsolutePath()); String writeOut = gson.toJson(database, TT_mapStringString); if (url != null) { try { ScriptingEngine.pushCodeToGit(url, ScriptingEngine.getFullBranch(url), gitfile, writeOut, "Saving Bezier"); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } else { @@ -340,7 +340,7 @@ public void save() { try { cachejson.createNewFile(); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } OutputStream out = null; @@ -351,7 +351,7 @@ public void save() { // completes // normally } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } finally { IOUtils.closeQuietly(out); @@ -381,7 +381,7 @@ public void setStartManip(CartesianManipulator start) { start.addSaveListener(() -> { save(); }); - start.addEventListener(() -> { + start.addEventListener(e -> { update(); }); start.addDependant(cp1Manip); diff --git a/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/CartesianManipulator.java b/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/CartesianManipulator.java index 037d0372b..c2764ae30 100644 --- a/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/CartesianManipulator.java +++ b/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/CartesianManipulator.java @@ -9,6 +9,8 @@ import eu.mihosoft.vrl.v3d.CSG; import eu.mihosoft.vrl.v3d.Cylinder; import eu.mihosoft.vrl.v3d.Vector3d; +import javafx.event.EventHandler; +import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.transform.Affine; @@ -17,7 +19,7 @@ public class CartesianManipulator { CSG manip1 = new Cylinder(0, 5, 40, 10).toCSG().setColor(Color.BLUE); CSG manip2 = new Cylinder(0, 5, 40, 10).toCSG().roty(-90).setColor(Color.RED); CSG manip3 = new Cylinder(0, 5, 40, 10).toCSG().rotx(90).setColor(Color.GREEN); - private manipulation[] manipulationList = new manipulation[3]; + private Manipulation[] manipulationList = new Manipulation[3]; TransformNR globalPose; public CartesianManipulator(TransformNR globalPose) { @@ -25,12 +27,17 @@ public CartesianManipulator(TransformNR globalPose) { manip1.setMfg(incoming -> null); manip2.setMfg(incoming -> null); manip3.setMfg(incoming -> null); - manipulationList[0] = new manipulation(manipulationMatrix, new Vector3d(0, 0, 1), manip1, globalPose); - manipulationList[1] = new manipulation(manipulationMatrix, new Vector3d(0, 1, 0), manip3, globalPose); - manipulationList[2] = new manipulation(manipulationMatrix, new Vector3d(1, 0, 0), manip2, globalPose); + manipulationList[0] = new Manipulation(manipulationMatrix, new Vector3d(0, 0, 1), globalPose); + manipulationList[1] = new Manipulation(manipulationMatrix, new Vector3d(0, 1, 0), globalPose); + manipulationList[2] = new Manipulation(manipulationMatrix, new Vector3d(1, 0, 0), globalPose); + int i=0; + for(CSG manip:Arrays.asList(manip1,manip3,manip2)) { + manip.getStorage().set("manipulator", manipulationList[i++].map); + manip.setManipulator(manipulationMatrix); + } } - public void addEventListener(Runnable r) { + public void addEventListener(EventHandler r) { for (int i = 0; i < 3; i++) manipulationList[i].addEventListener(r); } @@ -45,15 +52,15 @@ public List get() { } public double getX() { - return manipulationList[2].currentPose.getX(); + return manipulationList[2].getCurrentPose().getX(); } public double getY() { - return manipulationList[1].currentPose.getY(); + return manipulationList[1].getCurrentPose().getY(); } public double getZ() { - return manipulationList[0].currentPose.getZ(); + return manipulationList[0].getCurrentPose().getZ(); } public void addDependant(CartesianManipulator r) { @@ -68,7 +75,7 @@ public boolean isMoving() { } public void clearListeners() { - // TODO Auto-generated method stub + // Auto-generated method stub for (int i = 0; i < 3; i++) manipulationList[i].clearListeners(); } diff --git a/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/IFrameProvider.java b/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/IFrameProvider.java new file mode 100644 index 000000000..9df2bd4d8 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/IFrameProvider.java @@ -0,0 +1,7 @@ +package com.neuronrobotics.bowlerkernel.Bezier3d; + +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +public interface IFrameProvider { + public TransformNR get(); +} diff --git a/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/Manipulation.java b/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/Manipulation.java new file mode 100644 index 000000000..9d43c0819 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/Manipulation.java @@ -0,0 +1,355 @@ +package com.neuronrobotics.bowlerkernel.Bezier3d; + +import java.util.ArrayList; +import javafx.scene.paint.Color; +import java.util.HashMap; +import java.util.List; + +import com.neuronrobotics.bowlerstudio.physics.TransformFactory; +import com.neuronrobotics.sdk.addons.kinematics.math.*; + +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.Vector3d; +import javafx.event.EventHandler; +import javafx.event.EventType; +import javafx.scene.input.MouseEvent; +import javafx.scene.paint.Color; +import javafx.scene.transform.Affine; +import javafx.scene.paint.PhongMaterial; + +public class Manipulation { + public HashMap, EventHandler> map = new HashMap<>(); + double startx = 0; + double starty = 0; + double newx = 0; + double newy = 0; + double newz = 0; + boolean dragging = false; + private double increment = 0.000001; + private static IInteractiveUIElementProvider ui = new IInteractiveUIElementProvider() { + }; + + private ArrayList> eventListeners = new ArrayList<>(); + private ArrayList saveListeners = new ArrayList<>(); + private ArrayList dependants = new ArrayList<>(); + private Affine manipulationMatrix; + private TransformNR orintation; + private TransformNR globalPose= new TransformNR(); + private TransformNR currentPose=new TransformNR(); + private IFrameProvider frameOfReference = ()->new TransformNR(); + //private PhongMaterial color;// = new PhongMaterial(getColor()); + //private PhongMaterial highlight = new PhongMaterial(Color.GOLD); + + private enum DragState { + IDLE, Dragging + } + + private DragState state = DragState.IDLE; + + public void addEventListener(EventHandler r) { + if (eventListeners.contains(r)) + return; + eventListeners.add(r); + } + + public void addDependant(Manipulation r) { + if (dependants.contains(r)) + return; + dependants.add(r); + + } + + public void addSaveListener(Runnable r) { + if (saveListeners.contains(r)) + return; + saveListeners.add(r); + } + + public void clearListeners() { + // Auto-generated method stub + saveListeners.clear(); + eventListeners.clear(); + } + + private void fireMove(TransformNR trans, MouseEvent event2) { + for (Manipulation R : dependants) { + R.performMove(trans,event2); + } + for (EventHandler R : eventListeners) { + R.handle(event2); + } + } + + public void fireSave() { + new Thread(() -> { + for (Runnable R : saveListeners) { + R.run(); + } + }).start(); + } +// public manipulation(Affine mm, Vector3d o, CSG m, TransformNR p) { +// +// } + public Manipulation(Affine mm, Vector3d o, TransformNR p) { + this.manipulationMatrix = mm; + this.orintation = new TransformNR(o.x, o.y, o.z); + //this.manip = m; + //color = new PhongMaterial(m.getColor()); + this.setGlobalPose(p); + setCurrentPose(p.copy()); + getUi().runLater(() -> { + try { + TransformFactory.nrToAffine(getGlobalPose(), manipulationMatrix); + } catch (Throwable t) { + t.printStackTrace(); + } + }); + + map.put(MouseEvent.ANY, getMouseEvents()); + + } + + public EventHandler getMouseEvents() { + return new EventHandler() { + @Override + public void handle(MouseEvent event) { + String name = event.getEventType().getName(); + switch (name) { + case "MOUSE_PRESSED": + if(event.isPrimaryButtonDown()) + pressed(event); + break; + case "MOUSE_DRAGGED": + dragged(event,event); + break; + case "MOUSE_RELEASED": + release(event); + break; + case "MOUSE_MOVED": + // ignore + break; +// case "MOUSE_ENTERED": +// m.getMesh().setMaterial(highlight); +// break; +// case "MOUSE_EXITED": +// if (state == DragState.IDLE) +// m.getMesh().setMaterial(color); +// break; + default: + // com.neuronrobotics.sdk.common.Log.error("UNKNOWN! Mouse event "+name); + break; + } + + } + }; + } + + private void pressed(MouseEvent event) { + state = DragState.Dragging; + new Thread(() -> { + event.consume(); + dragging = false; + for (Manipulation R : dependants) { + + R.dragging = false; + } + }).start(); + } + + private double getDepthNow() { + return -1600 / getUi().getCamerDepth(); + } + + private void release(MouseEvent event) { + mouseRelease(event); + for (Manipulation R : dependants) + R.mouseRelease(event); + state = DragState.IDLE; + //manip.getMesh().setMaterial(color); + } + + private void dragged(MouseEvent event, MouseEvent event2) { + if(state==DragState.Dragging) { + getUi().runLater(() -> { + setDragging(event); + double deltx = (startx - event.getScreenX()); + double delty = (starty - event.getScreenY()); + double x = deltx/ getDepthNow() ; + double y = delty/ getDepthNow() ; + //com.neuronrobotics.sdk.common.Log.error("Moved "+x+" "+y); + if(Double.isFinite(y) && Double.isFinite(x)) { + TransformNR trans = new TransformNR(x, y, 0, new RotationNR()); + performMove(trans,event2); + }else { + com.neuronrobotics.sdk.common.Log.error("ERROR?"); + } + }); + event.consume(); + } + } + + public boolean isMoving() { + return state == DragState.Dragging; + } + + private void mouseRelease(MouseEvent event) { + if (dragging) { + dragging = false; + getGlobalPose().setX(newx); + getGlobalPose().setY(newy); + getGlobalPose().setZ(newz); + if(event!=null) + event.consume(); + fireSave(); + } + } + + private void setDragging(MouseEvent event) { + if (dragging == false) { + startx = event.getScreenX(); + starty = event.getScreenY(); + } + dragging = true; + for (Manipulation R : dependants) { + R.setDragging(event); + } + } + + private void performMove(TransformNR trans, MouseEvent event2) { + TransformNR camerFrame = getUi().getCamerFrame(); + TransformNR globalTMP = new TransformNR(camerFrame.getRotation()); + try { + + TransformNR global = globalTMP.times(trans); + TransformNR wp = getFrameOfReference().copy(); + wp.setX(0); + wp.setY(0); + wp.setZ(0); + global=wp.inverse().times(global); + + newx = round((global.getX() * orintation.getX() )); + newy = round((global.getY() * orintation.getY() )); + newz = round((global.getZ() * orintation.getZ() )); + + TransformNR globalTrans = globalPose.copy().setRotation(new RotationNR()); + global.setX(newx); + global.setY(newy); + global.setZ(newz); + global.setRotation(new RotationNR()); + TransformNR o =wp.times(global).times(wp.inverse()).setRotation(new RotationNR()); + global=globalTrans.times(o); + + + global.setRotation(new RotationNR()); + setGlobal(global); + //com.neuronrobotics.sdk.common.Log.error(" drag "+global.getX()+" , "+global.getY()+" ,"+global.getZ()); + + }catch(Throwable t) { + t.printStackTrace(); + } + fireMove(trans,event2); + } + private double round(double in) { + return Math.round(in / increment) * increment; + } + + private void setGlobal(TransformNR global) { +// newx = global.getX(); +// newy = global.getY(); +// newz = global.getZ(); + getCurrentPose().setX(newx); + getCurrentPose().setY(newy); + getCurrentPose().setZ(newz); + getUi().runLater(() -> { + TransformFactory.nrToAffine(global, manipulationMatrix); + }); + } + + public static IInteractiveUIElementProvider getUi() { + return ui; + } + + public static void setUi(IInteractiveUIElementProvider ui) { + Manipulation.ui = ui; + } + + public void set(double newX, double newY, double newZ) { + newx = newX; + newy = newY; + newz = newZ; + getGlobalPose().setX(newX); + getGlobalPose().setY(newY); + getGlobalPose().setZ(newZ); + setGlobal(new TransformNR(newX, newY, newZ, new RotationNR())); + for (EventHandler R : eventListeners) { + R.handle(null); + } + + } + public void setInReferenceFrame(double newX, double newY, double newZ) { + TransformNR inLocal = new TransformNR(newX, newY, newZ); + TransformNR wp = new TransformNR( getFrameOfReference() .getRotation()); + inLocal=wp.times(inLocal); + inLocal.setRotation(new RotationNR()); + //com.neuronrobotics.sdk.common.Log.error("Setting in reference frame:"+inLocal.toSimpleString()); + setGlobal(inLocal); + for (EventHandler R : eventListeners) { + R.handle(null); + } + + } + public void reset() { + // Auto-generated method stub + + } + + public TransformNR getGlobalPose() { + return globalPose; + } + public TransformNR getGlobalPoseInReferenceFrame() { + TransformNR globalPose = getGlobalPose().copy(); + TransformNR wp = new TransformNR( getFrameOfReference() .getRotation()); + globalPose=wp.times(globalPose); + globalPose.setRotation(new RotationNR()); + return globalPose; + } + public TransformNR getCurrentPoseInReferenceFrame() { + TransformNR globalPose = getCurrentPose().copy(); + TransformNR wp = new TransformNR( getFrameOfReference() .getRotation()); + globalPose=wp.times(globalPose); + globalPose.setRotation(new RotationNR()); + return globalPose; + } + public void setGlobalPose(TransformNR globalPose) { + this.globalPose = globalPose; + } + + public double getIncrement() { + return increment; + } + + public void setIncrement(double increment) { + this.increment = increment; + } + + public TransformNR getCurrentPose() { + return currentPose; + } + + public void setCurrentPose(TransformNR currentPose) { + this.currentPose = currentPose; + } + + public void cancel() { + release(null); + } + + public TransformNR getFrameOfReference() { + return frameOfReference.get(); + } + + public void setFrameOfReference(IFrameProvider frameOfReference) { + this.frameOfReference = frameOfReference; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/manipulation.java b/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/manipulation.java deleted file mode 100644 index 1f108085c..000000000 --- a/src/main/java/com/neuronrobotics/bowlerkernel/Bezier3d/manipulation.java +++ /dev/null @@ -1,252 +0,0 @@ -package com.neuronrobotics.bowlerkernel.Bezier3d; - -import java.util.ArrayList; -import javafx.scene.paint.Color; -import java.util.HashMap; - -import com.neuronrobotics.bowlerstudio.physics.TransformFactory; -import com.neuronrobotics.sdk.addons.kinematics.math.*; - -import eu.mihosoft.vrl.v3d.CSG; -import eu.mihosoft.vrl.v3d.Vector3d; -import javafx.event.EventHandler; -import javafx.event.EventType; -import javafx.scene.input.MouseEvent; -import javafx.scene.paint.Color; -import javafx.scene.transform.Affine; -import javafx.scene.paint.PhongMaterial; - -public class manipulation { - HashMap, EventHandler> map = new HashMap<>(); - double startx = 0; - double starty = 0; - double newx = 0; - double newy = 0; - double newz = 0; - TransformNR camFrame = null; - boolean dragging = false; - double depth = 0; - private static IInteractiveUIElementProvider ui = new IInteractiveUIElementProvider() { - }; - - private ArrayList eventListeners = new ArrayList<>(); - private ArrayList saveListeners = new ArrayList<>(); - private ArrayList dependants = new ArrayList<>(); - private Affine manipulationMatrix; - private Vector3d orintation; - private CSG manip; - private TransformNR globalPose; - public TransformNR currentPose; - private PhongMaterial color;// = new PhongMaterial(getColor()); - private PhongMaterial highlight = new PhongMaterial(Color.GOLD); - - private enum DragState { - IDLE, Dragging - } - - private DragState state = DragState.IDLE; - - public void addEventListener(Runnable r) { - if (eventListeners.contains(r)) - return; - eventListeners.add(r); - } - - public void addDependant(manipulation r) { - if (dependants.contains(r)) - return; - dependants.add(r); - } - - public void addSaveListener(Runnable r) { - if (saveListeners.contains(r)) - return; - saveListeners.add(r); - } - - public void clearListeners() { - // TODO Auto-generated method stub - saveListeners.clear(); - eventListeners.clear(); - } - - private void fireMove(TransformNR trans, TransformNR camFrame2) { - for (manipulation R : dependants) { - R.performMove(trans, camFrame2); - } - for (Runnable R : eventListeners) { - R.run(); - } - } - - private void fireSave() { - new Thread(() -> { - for (Runnable R : saveListeners) { - R.run(); - } - }).start(); - } - - public manipulation(Affine mm, Vector3d o, CSG m, TransformNR p) { - this.manipulationMatrix = mm; - this.orintation = o; - this.manip = m; - color = new PhongMaterial(m.getColor()); - this.globalPose = p; - currentPose = p.copy(); - getUi().runLater(() -> { - try { - TransformFactory.nrToAffine(globalPose, manipulationMatrix); - } catch (Throwable t) { - t.printStackTrace(); - } - }); - - map.put(MouseEvent.ANY, new EventHandler() { - @Override - public void handle(MouseEvent event) { - String name = event.getEventType().getName(); - switch (name) { - case "MOUSE_PRESSED": - pressed(event); - break; - case "MOUSE_DRAGGED": - dragged(event); - break; - case "MOUSE_RELEASED": - release(event); - break; - case "MOUSE_MOVED": - // ignore - break; - case "MOUSE_ENTERED": - m.getMesh().setMaterial(highlight); - break; - case "MOUSE_EXITED": - if (state == DragState.IDLE) - m.getMesh().setMaterial(color); - break; - default: - // System.out.println("UNKNOWN! Mouse event "+name); - break; - } - - } - }); - manip.getStorage().set("manipulator", map); - manip.setManipulator(manipulationMatrix); - } - - private void pressed(MouseEvent event) { - state = DragState.Dragging; - new Thread(() -> { - camFrame = getUi().getCamerFrame(); - depth = -1600 / getUi().getCamerDepth(); - event.consume(); - dragging = false; - for (manipulation R : dependants) { - R.camFrame = getUi().getCamerFrame(); - R.depth = -1600 / getUi().getCamerDepth(); - R.dragging = false; - } - }).start(); - } - - private void release(MouseEvent event) { - mouseRelease(event); - for (manipulation R : dependants) - R.mouseRelease(event); - state = DragState.IDLE; - manip.getMesh().setMaterial(color); - } - - private void dragged(MouseEvent event) { - getUi().runLater(() -> { - setDragging(event); - double deltx = (startx - event.getScreenX()); - double delty = (starty - event.getScreenY()); - TransformNR trans = new TransformNR(deltx / depth, delty / depth, 0, new RotationNR()); - - performMove(trans, camFrame); - }); - event.consume(); - } - - public boolean isMoving() { - return state == DragState.Dragging; - } - - private void mouseRelease(MouseEvent event) { - if (dragging) { - dragging = false; - globalPose.setX(newx); - globalPose.setY(newy); - globalPose.setZ(newz); - event.consume(); - fireSave(); - } - } - - private void setDragging(MouseEvent event) { - if (dragging == false) { - startx = event.getScreenX(); - starty = event.getScreenY(); - } - dragging = true; - for (manipulation R : dependants) { - R.setDragging(event); - } - } - - private void performMove(TransformNR trans, TransformNR camFrame2) { - TransformNR globalTMP = camFrame2.copy(); - globalTMP.setX(0); - globalTMP.setY(0); - globalTMP.setZ(0); - TransformNR global = globalTMP.times(trans); - newx = (global.getX() * orintation.x + globalPose.getX()); - newy = (global.getY() * orintation.y + globalPose.getY()); - newz = (global.getZ() * orintation.z + globalPose.getZ()); - global.setX(newx); - global.setY(newy); - global.setZ(newz); - - global.setRotation(new RotationNR()); - setGlobal(global); - // System.out.println(" drag "+global.getX()+" , "+global.getY()+" , - // "+global.getZ()+" "+deltx+" "+delty); - fireMove(trans, camFrame2); - } - - private void setGlobal(TransformNR global) { - currentPose.setX(newx); - currentPose.setY(newy); - currentPose.setZ(newz); - getUi().runLater(() -> { - TransformFactory.nrToAffine(global, manipulationMatrix); - }); - } - - public static IInteractiveUIElementProvider getUi() { - return ui; - } - - public static void setUi(IInteractiveUIElementProvider ui) { - manipulation.ui = ui; - } - - public void set(double newX, double newY, double newZ) { - newx = newX; - newy = newY; - newz = newZ; - globalPose.setX(newX); - globalPose.setY(newY); - globalPose.setZ(newZ); - setGlobal(new TransformNR(newX, newY, newZ, new RotationNR())); - for (Runnable R : eventListeners) { - R.run(); - } - - } - -} diff --git a/src/main/java/com/neuronrobotics/bowlerkernel/BowlerKernelBuildInfo.java b/src/main/java/com/neuronrobotics/bowlerkernel/BowlerKernelBuildInfo.java index 24211628a..9793cd39f 100644 --- a/src/main/java/com/neuronrobotics/bowlerkernel/BowlerKernelBuildInfo.java +++ b/src/main/java/com/neuronrobotics/bowlerkernel/BowlerKernelBuildInfo.java @@ -120,7 +120,7 @@ public static String getBuildDate() { } } catch (IOException e) { } - // System.out.println("Manifest:\n"+s); + // com.neuronrobotics.sdk.common.Log.error("Manifest:\n"+s); return ""; } diff --git a/src/main/java/com/neuronrobotics/bowlerkernel/djl/UniquePersonFactory.java b/src/main/java/com/neuronrobotics/bowlerkernel/djl/UniquePersonFactory.java index 6cd4cdae0..eb28eb82e 100644 --- a/src/main/java/com/neuronrobotics/bowlerkernel/djl/UniquePersonFactory.java +++ b/src/main/java/com/neuronrobotics/bowlerkernel/djl/UniquePersonFactory.java @@ -105,13 +105,13 @@ private UniquePersonFactory(File database) { try { features = PredictorFactory.faceFeatureFactory(); } catch (ModelNotFoundException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } catch (MalformedModelException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } factory = ImageFactory.getInstance(); @@ -144,7 +144,7 @@ public String save() { try { Files.write(path, strToBytes); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } if (workingMemory != null) @@ -262,7 +262,7 @@ private void processBlocking() { if (up.features.size() >= numberOfTrainingHashes) { if (!longTermMemory.contains(up)) { longTermMemory.add(up); - System.out.println("Saving new Face to database " + up.name); + com.neuronrobotics.sdk.common.Log.error("Saving new Face to database " + up.name); save(); } } @@ -280,7 +280,7 @@ private void processBlocking() { try { id = features.predict(cmp); } catch (Throwable ex) { - System.out.println("Image failed h=" + imgBuff.getHeight() + " w=" + imgBuff.getWidth()); + com.neuronrobotics.sdk.common.Log.error("Image failed h=" + imgBuff.getHeight() + " w=" + imgBuff.getWidth()); // ex.printStackTrace(); continue; } @@ -344,7 +344,7 @@ private void processBlocking() { private EventHandler setAction(UniquePerson p) { return event -> { String newName = getUI(p).name.getText(); - System.out.println("Renaming " + p.name + " to " + newName); + com.neuronrobotics.sdk.common.Log.error("Renaming " + p.name + " to " + newName); p.name = newName; new Thread(() -> save()).start(); }; @@ -415,7 +415,7 @@ private boolean processMemory(HashMap tmpPe @Override public ArrayList getNamespacesImp() { - // TODO Auto-generated method stub + // Auto-generated method stub return null; } @@ -480,7 +480,7 @@ public void setDatabase(File database) { database.createNewFile(); save(); } catch (IOException e1) { - // TODO Auto-generated catch block + // Auto-generated catch block e1.printStackTrace(); } else { @@ -490,7 +490,7 @@ public void setDatabase(File database) { longTermMemory = gson.fromJson(jsonString, TT_mapStringString); resetHash(); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/AudioPlayer.java b/src/main/java/com/neuronrobotics/bowlerstudio/AudioPlayer.java index 72e5db80a..f8f62641e 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/AudioPlayer.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/AudioPlayer.java @@ -271,7 +271,7 @@ public float getGainValue() { public void setGain(float fGain) { // if (line != null) - // System.out.println(((FloatControl) + // com.neuronrobotics.sdk.common.Log.error(((FloatControl) // line.getControl(FloatControl.Type.MASTER_GAIN)).getValue()) // Set the value @@ -284,7 +284,7 @@ public void setGain(float fGain) { // OR (Math.log(fGain == 0.0 ? 0.0000 : fGain) / Math.log(10.0)) // if (line != null) - // System.out.println(((FloatControl) + // com.neuronrobotics.sdk.common.Log.error(((FloatControl) // line.getControl(FloatControl.Type.MASTER_GAIN)).getValue()) } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/BowlerKernel.java b/src/main/java/com/neuronrobotics/bowlerstudio/BowlerKernel.java index f534b7b1f..aad3662ad 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/BowlerKernel.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/BowlerKernel.java @@ -50,7 +50,9 @@ import com.neuronrobotics.bowlerstudio.creature.IgenerateBed; import com.neuronrobotics.bowlerstudio.creature.MobileBaseCadManager; import com.neuronrobotics.bowlerstudio.printbed.PrintBedManager; +import com.neuronrobotics.bowlerstudio.scripting.CaDoodleLoader; import com.neuronrobotics.bowlerstudio.scripting.ScriptingEngine; +import com.neuronrobotics.bowlerstudio.scripting.cadoodle.CaDoodleFile; import com.neuronrobotics.bowlerstudio.vitamins.VitaminBomManager; import com.neuronrobotics.sdk.addons.kinematics.MobileBase; @@ -70,6 +72,7 @@ public class BowlerKernel { // private static final String CSG = null; private static File historyFile = new File(ScriptingEngine.getWorkspace().getAbsolutePath() + "/bowler.history"); + private static boolean kernelMode=true; private static void loadHistoryLocal() { historyFile = new File(ScriptingEngine.getWorkspace().getAbsolutePath() + "/bowler.history"); @@ -78,7 +81,7 @@ private static void loadHistoryLocal() { try { historyFile.createNewFile(); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } history.add("println SDKBuildInfo.getVersion()"); @@ -99,15 +102,15 @@ private static void loadHistoryLocal() { } private static void fail() { - System.err.println( + com.neuronrobotics.sdk.common.Log.error( "Usage: \r\njava -jar BowlerScriptKernel.jar -s .. # This will load one script after the next "); - System.err.println( + com.neuronrobotics.sdk.common.Log.error( "java -jar BowlerScriptKernel.jar -p .. # This will load one script then take the list of objects returned and pss them to the next script as its 'args' variable "); - System.err.println( + com.neuronrobotics.sdk.common.Log.error( "java -jar BowlerScriptKernel.jar -r (Optional)(-s or -p) .. # This will start a shell in the requested langauge and run the files provided. "); - System.err.println("java -jar BowlerScriptKernel.jar -g # this will run a file from git"); - - System.exit(1); + com.neuronrobotics.sdk.common.Log.error("java -jar BowlerScriptKernel.jar -g # this will run a file from git"); + if(isKernelMode()) + System.exit(1); } /** @@ -159,7 +162,7 @@ public static void runArgumentsAfterStartup(String[] args, long startTime) } } if (!fileExists) { - System.err.println("\n\nERROR file does not exist: " + gitFile); + com.neuronrobotics.sdk.common.Log.error("\n\nERROR file does not exist: " + gitFile); gitFile = null; } if (gitFile != null) @@ -174,9 +177,9 @@ public static void runArgumentsAfterStartup(String[] args, long startTime) fail(); } else { - System.out.println("Files in git:"); + com.neuronrobotics.sdk.common.Log.error("Files in git:"); for (String f : files) { - System.out.println("\t" + f); + com.neuronrobotics.sdk.common.Log.error("\t" + f); } } finish(startTime); @@ -185,7 +188,7 @@ public static void runArgumentsAfterStartup(String[] args, long startTime) // "BowlerStudioVitamins/stl/servo/smallservo.stl"); // // ArrayList cad = (ArrayList )ScriptingEngine.inlineGistScriptRun("4814b39ee72e9f590757", "javaCad.groovy" , null); -// System.out.println(servo.exists()+" exists: "+servo); +// com.neuronrobotics.sdk.common.Log.error(servo.exists()+" exists: "+servo); boolean startLoadingScripts = false; for (String s : args) { @@ -206,9 +209,9 @@ public static void runArgumentsAfterStartup(String[] args, long startTime) } baseWorkspaceFile = new File(location); - System.out.println("Using working directory "+baseWorkspaceFile.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Using working directory "+baseWorkspaceFile.getAbsolutePath()); f=new File(baseWorkspaceFile.getAbsolutePath()+"/"+f.getName()); - System.out.println("File "+f.getName()); + com.neuronrobotics.sdk.common.Log.error("File "+f.getName()); ret = ScriptingEngine.inlineFileScriptRun(f, null); } catch (Throwable e) { e.printStackTrace(); @@ -241,7 +244,7 @@ public static void runArgumentsAfterStartup(String[] args, long startTime) } } if (startLoadingScripts) { - processReturnedObjectsStart(ret, null); + processReturnedObjectsStart(ret, new File(".")); finish(startTime); return; } @@ -266,12 +269,12 @@ public static void runArgumentsAfterStartup(String[] args, long startTime) if (!runShell) { finish(startTime); } - System.out.println("Starting Bowler REPL in langauge: " + shellTypeStorage); + com.neuronrobotics.sdk.common.Log.error("Starting Bowler REPL in langauge: " + shellTypeStorage); // sample from // http://jline.sourceforge.net/testapidocs/src-html/jline/example/Example.html if (!Terminal.getTerminal().isSupported()) { - System.out.println("Terminal not supported " + Terminal.getTerminal()); + com.neuronrobotics.sdk.common.Log.error("Terminal not supported " + Terminal.getTerminal()); } // Terminal.getTerminal().initializeTerminal(); @@ -326,7 +329,7 @@ public void run() { if (line.equalsIgnoreCase("history") || line.equalsIgnoreCase("h")) { List h = reader.getHistory().getHistoryList(); for (String s : h) { - System.out.println(s); + com.neuronrobotics.sdk.common.Log.error(s); } continue; } @@ -341,7 +344,7 @@ public void run() { try { ret = ScriptingEngine.inlineScriptStringRun(line, null, shellTypeStorage); if (ret != null) { - System.out.println(ret); + com.neuronrobotics.sdk.common.Log.error(ret); } processReturnedObjectsStart(ret, null); } catch (Error e) { @@ -361,7 +364,7 @@ private static void startupProcedures(String[] args) JavaFXInitializer.go(); } catch (Throwable t) { t.printStackTrace(); - System.err.println("ERROR No UI engine availible"); + com.neuronrobotics.sdk.common.Log.error("ERROR No UI engine availible"); } ScriptingEngine.waitForLogin(); if (args.length == 0) { @@ -369,71 +372,77 @@ private static void startupProcedures(String[] args) } ScriptingEngine.gitScriptRun("https://github.com/CommonWealthRobotics/DeviceProviders.git", "loadAll.groovy", null); + CSG.setPreventNonManifoldTriangles(true); + CSG.setProgressMoniter(new ICSGProgress() { + @Override + public void progressUpdate(int currentIndex, int finalIndex, String type, + eu.mihosoft.vrl.v3d.CSG intermediateShape) { + + } + + }); } private static void finish(long startTime) { - System.out.println( + com.neuronrobotics.sdk.common.Log.error( "Process took " + (((double) (System.currentTimeMillis() - startTime))) / 60000.0 + " minutes"); System.exit(0); } - private static void processReturnedObjectsStart(Object ret, File baseWorkspaceFile) { + public static void processReturnedObjectsStart(Object ret, File baseWorkspaceFile) { processUIOpening(ret); if(baseWorkspaceFile!=null) - System.out.println("Processing file in directory "+baseWorkspaceFile.getAbsolutePath()); - CSG.setProgressMoniter(new ICSGProgress() { - @Override - public void progressUpdate(int currentIndex, int finalIndex, String type, - eu.mihosoft.vrl.v3d.CSG intermediateShape) { - - } + com.neuronrobotics.sdk.common.Log.error("Processing file in directory "+baseWorkspaceFile.getAbsolutePath()); - }); + if (baseWorkspaceFile != null) { - File baseDirForFiles = new File("./manufacturing/"); + + File baseDirForFiles = new File(baseWorkspaceFile.getAbsolutePath()+"/manufacturing/"); if (baseDirForFiles.exists()) { // baseDirForFiles.mkdir(); File bomCSV = new File( - baseWorkspaceFile.getAbsolutePath() + "/" + VitaminBomManager.MANUFACTURING_BOM_CSV); + baseWorkspaceFile.getAbsolutePath() + "/" + VitaminBomManager.getManufacturingBomCsv()); if (bomCSV.exists()) { - File file = new File(baseDirForFiles.getAbsolutePath() + "/bom.csv"); - if (file.exists()) - file.delete(); + File file = new File(baseWorkspaceFile.getAbsolutePath() + "/"+ VitaminBomManager.getManufacturingBomCsv()); +// if (file.exists()) +// file.delete(); try { Files.copy(bomCSV.toPath(), file.toPath()); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } File bom = new File( - baseWorkspaceFile.getAbsolutePath() + "/" + VitaminBomManager.MANUFACTURING_BOM_JSON); + baseWorkspaceFile.getAbsolutePath() + "/" + VitaminBomManager.getManufacturingBomJson()); if (bom.exists()) { - File file = new File(baseDirForFiles.getAbsolutePath() + "/bom.json"); - if (file.exists()) - file.delete(); + File file = new File(baseWorkspaceFile.getAbsolutePath() + "/"+ VitaminBomManager.getManufacturingBomJson()); +// if (file.exists()) +// file.delete(); try { Files.copy(bom.toPath(), file.toPath()); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } + }else { + baseDirForFiles.mkdirs(); } } ArrayList csgBits = new ArrayList<>(); try { processReturnedObjects(ret, csgBits); String url = ScriptingEngine.locateGitUrl(baseWorkspaceFile); - System.out.println("Loading printbed URL "+url); + com.neuronrobotics.sdk.common.Log.error("Loading printbed URL "+url); PrintBedManager printBedManager = new PrintBedManager(baseWorkspaceFile, csgBits); if(printBedManager.hasPrintBed()) csgBits = printBedManager.makePrintBeds(); else { - System.out.println("Exporting files without print bed"); + com.neuronrobotics.sdk.common.Log.error("Exporting files without print bed"); } - new CadFileExporter().generateManufacturingParts(csgBits, new File(".")); + new CadFileExporter().generateManufacturingParts(csgBits, baseWorkspaceFile); } catch (Throwable t) { t.printStackTrace(); fail(); @@ -442,7 +451,7 @@ public void progressUpdate(int currentIndex, int finalIndex, String type, private static void processUIOpening(Object ret) { if(Tab.class.isInstance(ret)) { - System.out.println("Launching User Defined UI"); + com.neuronrobotics.sdk.common.Log.error("Launching User Defined UI"); Tab t=(Tab)ret; CompletableFuture future = new CompletableFuture<>(); @@ -472,7 +481,7 @@ private static void processUIOpening(Object ret) { newStage.setOnCloseRequest(event -> { // Exit the JVM when the window is closed future.complete(true); - Platform.exit(); + BowlerKernel.runLater(()->Platform.exit()); }); FontSizeManager.addListener(fontNum -> { int tmp = fontNum - 10; @@ -482,7 +491,7 @@ private static void processUIOpening(Object ret) { newStage.sizeToScene(); }); if(IStageReceiver.class.isInstance(ret)) { - System.out.println("UI is a IStageReceiver"); + com.neuronrobotics.sdk.common.Log.error("UI is a IStageReceiver"); IStageReceiver r=(IStageReceiver)ret; BowlerKernel.runLater(()->{ r.receiveStage(newStage, scene); @@ -514,6 +523,10 @@ private static void processReturnedObjects(Object ret, ArrayList csgBits) { if (CSG.class.isInstance(ret)) { csgBits.add((CSG) ret); } + if(CaDoodleFile.class.isInstance(ret)) { + processReturnedObjects(CaDoodleLoader.process((CaDoodleFile)ret), csgBits); + return; + } if (MobileBase.class.isInstance(ret)) { MobileBase ret2 = (MobileBase) ret; MobileBaseCadManager m = MobileBaseCadManager.get(ret2); @@ -521,19 +534,19 @@ private static void processReturnedObjects(Object ret, ArrayList csgBits) { @Override public void setSelectedCsg(Collection selectedCsg) { - // TODO Auto-generated method stub + // Auto-generated method stub } @Override public void setSelected(Affine rootListener) { - // TODO Auto-generated method stub + // Auto-generated method stub } @Override public void setAllCSG(Collection toAdd, File source) { - // TODO Auto-generated method stub + // Auto-generated method stub } @@ -545,13 +558,13 @@ public void highlightException(File fileEngineRunByName, Throwable ex) { @Override public Set getVisibleCSGs() { - // TODO Auto-generated method stub + // Auto-generated method stub return null; } @Override public void addCSG(Collection toAdd, File source) { - // TODO Auto-generated method stub + // Auto-generated method stub } }); @@ -578,7 +591,7 @@ public void addCSG(Collection toAdd, File source) { m._generateStls(ret2, dir, false); return; } - System.out.println("Found arrangeBed API in CAD engine"); + com.neuronrobotics.sdk.common.Log.error("Found arrangeBed API in CAD engine"); List totalAssembly = bed.arrangeBed(ret2); ret2.disconnect(); Thread.sleep(1000); @@ -589,24 +602,24 @@ public void addCSG(Collection toAdd, File source) { // Get maximum size of heap in bytes. The heap cannot grow beyond this size.// // Any attempt will result in an OutOfMemoryException. long heapMaxSize = Runtime.getRuntime().maxMemory(); - // System.out.println("Heap remaining + // com.neuronrobotics.sdk.common.Log.error("Heap remaining // "+(heapMaxSize-Runtime.getRuntime().totalMemory())); - // System.out.println("Of Heap "+(heapMaxSize)); + // com.neuronrobotics.sdk.common.Log.error("Of Heap "+(heapMaxSize)); for (int i = 0; i < totalAssembly.size(); i++) { List tmp = Arrays.asList(totalAssembly.get(i)); totalAssembly.set(i, null); - // System.out.println("Before Heap remaining + // com.neuronrobotics.sdk.common.Log.error("Before Heap remaining // "+(heapMaxSize-Runtime.getRuntime().totalMemory())); new CadFileExporter(m.getUi()).generateManufacturingParts(tmp, dir); tmp = null; System.gc(); - // System.out.println("After Heap remaining + // com.neuronrobotics.sdk.common.Log.error("After Heap remaining // "+(heapMaxSize-Runtime.getRuntime().totalMemory())); } } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); fail(); } @@ -627,7 +640,7 @@ public static ArrayList loadHistory() throws IOException { } public static void writeHistory(List history) { - System.out.println("Saving history"); + com.neuronrobotics.sdk.common.Log.error("Saving history"); FileOutputStream fos; try { fos = new FileOutputStream(historyFile); @@ -639,10 +652,10 @@ public static void writeHistory(List history) { bw.close(); } catch (FileNotFoundException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } @@ -680,7 +693,7 @@ public static int speak(String msg, Number rate, Number pitch, Number voiceNumbe } TextToSpeech tts = new TextToSpeech(); // cd .. - tts.getAvailableVoices().stream().forEach(voice -> System.out.println("Voice: " + voice)); + tts.getAvailableVoices().stream().forEach(voice -> com.neuronrobotics.sdk.common.Log.error("Voice: " + voice)); // Setting the Current Voice // voice =(tts.getAvailableVoices().toArray()[0].toString()); String voice = "dfki-poppy-hsmm"; @@ -699,7 +712,7 @@ else if (voiceNumber.doubleValue() > 100) tts.setVoice(voice); - System.out.println("Using voice " + voice); + com.neuronrobotics.sdk.common.Log.error("Using voice " + voice); RobotiserEffect vocalTractLSE = new RobotiserEffect(); // russian drunk effect vocalTractLSE.setParams("amount:" + pitch.intValue()); @@ -707,12 +720,12 @@ else if (voiceNumber.doubleValue() > 100) // TTS say something that we actually are typing into the first variable // tts.getAudioEffects().stream().forEach(audioEffect -> { // if(audioEffect.getName().contains("Rate")) { -// System.out.println("-----Name-----"); -// System.out.println(audioEffect.getName()); -// System.out.println("-----Examples-----"); -// System.out.println(audioEffect.getExampleParameters()); -// System.out.println("-----Help Text------"); -// System.out.println(audioEffect.getHelpText() + "\n\n"); +// com.neuronrobotics.sdk.common.Log.error("-----Name-----"); +// com.neuronrobotics.sdk.common.Log.error(audioEffect.getName()); +// com.neuronrobotics.sdk.common.Log.error("-----Examples-----"); +// com.neuronrobotics.sdk.common.Log.error(audioEffect.getExampleParameters()); +// com.neuronrobotics.sdk.common.Log.error("-----Help Text------"); +// com.neuronrobotics.sdk.common.Log.error(audioEffect.getHelpText() + "\n\n"); // } // }); String effect = ""; @@ -744,7 +757,7 @@ else if (voiceNumber.doubleValue() > 100) effect += "+" + volumeEffect.getFullEffectAsString(); if (pitch.intValue() > 0) effect += "+" + vocalTractLSE.getFullEffectAsString(); - System.out.println(msg + "-->" + effect); + com.neuronrobotics.sdk.common.Log.error(msg + "-->" + effect); tts.getMarytts().setAudioEffects(effect); tts.speak(msg, 2.0f, false, true, progress); @@ -754,15 +767,15 @@ else if (voiceNumber.doubleValue() > 100) public static void upenURL(String string) { - System.err.println("Opening " + string); + com.neuronrobotics.sdk.common.Log.error("Opening " + string); try { upenURL(new URI(string)); } catch (URISyntaxException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } catch (Throwable e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } @@ -772,7 +785,7 @@ public static void upenURL(URI htmlUrl) { try { Desktop.getDesktop().browse(htmlUrl); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } @@ -809,5 +822,13 @@ public static void runLater(Runnable r, Throwable ex) { }); } + public static boolean isKernelMode() { + return kernelMode; + } + + public static void setKernelMode(boolean kernelMode) { + BowlerKernel.kernelMode = kernelMode; + } + } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/CoquiDockerManager.java b/src/main/java/com/neuronrobotics/bowlerstudio/CoquiDockerManager.java index fb6d62c6c..2f6f1d3eb 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/CoquiDockerManager.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/CoquiDockerManager.java @@ -81,7 +81,7 @@ private CoquiDockerManager(String voice) throws InterruptedException, InvalidRem } managers.clear(); managers.put(voice, this); - System.out.println("Coqui Voice " + voice); + com.neuronrobotics.sdk.common.Log.error("Coqui Voice " + voice); String[] parts = voice.split("/"); String voiceSlug = "-" + parts[parts.length - 1]; ScriptingEngine.cloneRepo("https://github.com/Halloween2020TheChild/CoquiDocker.git", null); @@ -107,13 +107,13 @@ private CoquiDockerManager(String voice) throws InterruptedException, InvalidRem for (Container c : allCOntainers) { if (forMe != null) continue; - System.out.println("Container: " + c); + com.neuronrobotics.sdk.common.Log.error("Container: " + c); String[] names = c.getNames(); for (String n : names) { String cs = "/" + imageName + voiceSlug; - System.out.println("Checking " + n + " to " + cs); + com.neuronrobotics.sdk.common.Log.error("Checking " + n + " to " + cs); boolean PortMatch=false; ContainerPort[] conPorts = c.getPorts(); for(ContainerPort cp:conPorts) { @@ -147,7 +147,7 @@ public void onNext(BuildResponseItem item) { super.onNext(item); } }).awaitImageId(); - System.out.println("Docker image built successfully."); + com.neuronrobotics.sdk.common.Log.error("Docker image built successfully."); try { ExposedPort port = ExposedPort.tcp(hostPort); Ports portBindings = new Ports(); @@ -161,7 +161,7 @@ public void onNext(BuildResponseItem item) { @Override public void onNext(WaitResponse item) { // Handle build output (optional) - System.out.println(item.toString()); + com.neuronrobotics.sdk.common.Log.error(item.toString()); super.onNext(item); } }).awaitCompletion(); @@ -170,7 +170,7 @@ public void onNext(WaitResponse item) { @Override public void onNext(Frame item) { String string = item.toString(); - System.out.println(string); + com.neuronrobotics.sdk.common.Log.error(string); if(string.contains("Press CTRL+C to quit")) { started=true; } @@ -187,14 +187,14 @@ public void onNext(Frame item) { } while(!started) { Thread.sleep(1000); - System.out.println("Waiting for server to start"); + com.neuronrobotics.sdk.common.Log.error("Waiting for server to start"); } } public void disconnect() { - // TODO Auto-generated method stub + // Auto-generated method stub dockerClient.killContainerCmd(id).exec(); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/IssueReportingExceptionHandler.java b/src/main/java/com/neuronrobotics/bowlerstudio/IssueReportingExceptionHandler.java index 645d1efb6..c7fa0e69c 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/IssueReportingExceptionHandler.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/IssueReportingExceptionHandler.java @@ -69,7 +69,7 @@ public static void runLater(Runnable r, Throwable ex) { } public void except(Throwable e, String stacktraceFromCatch) { - System.out.println(stacktraceFromCatch); + com.neuronrobotics.sdk.common.Log.error(stacktraceFromCatch); new Thread(() -> { String stacktrace = org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(e); StackTraceElement[] element = e.getStackTrace(); @@ -96,7 +96,7 @@ public void except(Throwable e, String stacktraceFromCatch) { try { Thread.sleep(5000); } catch (InterruptedException e1) { - // TODO Auto-generated catch block + // Auto-generated catch block e1.printStackTrace(); } // wait for the Issue to be reported System.exit(-5); @@ -107,7 +107,7 @@ public void except(Throwable e, String stacktraceFromCatch) { try { Thread.sleep(5000); } catch (InterruptedException e1) { - // TODO Auto-generated catch block + // Auto-generated catch block e1.printStackTrace(); } // wait for the Issue to be reported System.exit(-5); @@ -133,10 +133,10 @@ public void except(Throwable e, String stacktraceFromCatch) { + "```\n" + stacktrace + "\n```" + "\n\nCaught and reported at: \n" + "```\n" + stacktraceFromCatch + "\n```\n" + "\nIssueReportingExceptionHandler Created at:\n" + "\n```\n" + stacktraceFromHandlerInstantiation + "\n```\n"; - System.err.println(body); - System.err.println("\r\n\r\nBug Reported!\r\n\r\n"); - System.out.println(body); - System.out.println("\r\n\r\nBug Reported!\r\n\r\n"); + com.neuronrobotics.sdk.common.Log.error(body); + com.neuronrobotics.sdk.common.Log.error("\r\n\r\nBug Reported!\r\n\r\n"); + com.neuronrobotics.sdk.common.Log.error(body); + com.neuronrobotics.sdk.common.Log.error("\r\n\r\nBug Reported!\r\n\r\n"); GitHub github = PasswordManager.getGithub(); if (github == null || github.isAnonymous()) @@ -171,7 +171,7 @@ private void runReport(StackTraceElement[] element, String body, GitHub github) String source = getTitle(element); for (GHIssue i : issues) { - System.err.println("Issues are :" + i.getTitle()); + com.neuronrobotics.sdk.common.Log.error("Issues are :" + i.getTitle()); if (i.getTitle().contains(source)) { List comments = i.getComments(); // Check to see if i created this issue @@ -217,7 +217,7 @@ private void runReport(StackTraceElement[] element, String body, GitHub github) BowlerKernel.upenURL(i.getHtmlUrl().toURI()); } catch (Throwable e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } processing = false; @@ -240,7 +240,7 @@ public void except(Throwable t) { return; } if (Platform.isFxApplicationThread()) { - System.err.println("Exception in Javafx thread! \n" + com.neuronrobotics.sdk.common.Log.error("Exception in Javafx thread! \n" + org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(t)); //throw new RuntimeException(t); return; diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/TextToSpeech.java b/src/main/java/com/neuronrobotics/bowlerstudio/TextToSpeech.java index 4a80fd253..fa398fbd3 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/TextToSpeech.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/TextToSpeech.java @@ -81,7 +81,7 @@ public int speak(String text , float gainValue , boolean daemon , boolean join, Logger.getLogger(getClass().getName()).log(Level.WARNING, "IO Exception", ex); } catch (InterruptedException ex) { Logger.getLogger(getClass().getName()).log(Level.WARNING, "Interrupted ", ex); - System.out.println("Speaking clean exit"); + com.neuronrobotics.sdk.common.Log.error("Speaking clean exit"); tts.cancel(); tts.interrupt(); return 1; diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/assets/AssetFactory.java b/src/main/java/com/neuronrobotics/bowlerstudio/assets/AssetFactory.java index 07a16ae8c..0b227df2f 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/assets/AssetFactory.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/assets/AssetFactory.java @@ -33,6 +33,10 @@ public class AssetFactory { private AssetFactory() { } + static { + com.neuronrobotics.sdk.common.Log.error("AssetFactory loaded"); + //new RuntimeException().printStackTrace(); + } public static FXMLLoader loadLayout(String file, boolean refresh) throws Exception { File fxmlFIle = loadFile(file); @@ -101,7 +105,7 @@ public static Image loadAsset(String file) throws Exception { } cache.put(file, obj_img); - System.out.println("No image at " + file); + com.neuronrobotics.sdk.common.Log.error("No image at " + file); try { new RuntimeException().printStackTrace(); @@ -149,7 +153,7 @@ public static String getGitSource() throws Exception { } public static void setGitSource(String gitSource, String assetRepoBranch) throws Exception { - System.err.println("Assets from: " + gitSource + "#" + assetRepoBranch); + com.neuronrobotics.sdk.common.Log.error("Assets from: " + gitSource + "#" + assetRepoBranch); //new Exception().printStackTrace(); setAssetRepoBranch(assetRepoBranch); AssetFactory.gitSource = gitSource; @@ -158,15 +162,15 @@ public static void setGitSource(String gitSource, String assetRepoBranch) throws } public static void loadAllAssets() throws Exception { - System.err.println("Loading assets"); + com.neuronrobotics.sdk.common.Log.error("Loading assets"); List files; try { files = ScriptingEngine.filesInGit(gitSource, StudioBuildInfo.getVersion(), null); }catch(Exception ex) { - files = ScriptingEngine.filesInGit(gitSource); + files = ScriptingEngine.filesInGit(getGitSource()); } for (String file : files) { - System.err.println("Loading asset file: "+file); + com.neuronrobotics.sdk.common.Log.error("Loading asset file: "+file); loadAsset(file); } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/assets/ConfigurationDatabase.java b/src/main/java/com/neuronrobotics/bowlerstudio/assets/ConfigurationDatabase.java index 2c22875b0..444d86bda 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/assets/ConfigurationDatabase.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/assets/ConfigurationDatabase.java @@ -57,6 +57,7 @@ public static Set keySet(String name) { } public static boolean containsKey(String paramsKey, String string) { boolean containsKey = false; + getDatabase(); synchronized(database){ containsKey = ConfigurationDatabase.getParamMap(paramsKey).containsKey(string); } @@ -89,7 +90,7 @@ public static Object getObject(String paramsKey, String objectKey, Object defau getDatabase(); synchronized(database){ if (getParamMap(paramsKey).get(objectKey) == null) { - //System.err.println("Cant find: " + paramsKey + ":" + objectKey); + //com.neuronrobotics.sdk.common.Log.error("Cant find: " + paramsKey + ":" + objectKey); setObject(paramsKey, objectKey, defaultValue); } ret= getParamMap(paramsKey).get(objectKey); @@ -141,11 +142,11 @@ public static void save() { try (PrintWriter out = new PrintWriter(f.getAbsolutePath())) { out.println(writeOut); } catch (FileNotFoundException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); return; } - System.out.println("Saved "+f.getName()); + com.neuronrobotics.sdk.common.Log.error("Saved "+f.getName()); } @SuppressWarnings("unchecked") @@ -156,11 +157,11 @@ public static void getDatabase() { File loadFile = loadFile(); if(loadFile.exists()) try { - database = Collections.synchronizedMap((HashMap>) ScriptingEngine.inlineFileScriptRun(loadFile, null)); + Object inlineFileScriptRun = ScriptingEngine.inlineFileScriptRun(loadFile, null); + database = Collections.synchronizedMap((HashMap>) inlineFileScriptRun); } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); + // databse is empty } if (database == null) { @@ -179,23 +180,6 @@ public static File loadFile() { } catch (IOException e) { throw new RuntimeException(e.getMessage()); } - String username = PasswordManager.getLoginID(); - if(username!=null) - try { - File file =ScriptingEngine.fileFromGit("https://github.com/"+username+"/BowlerStudioConfiguration.git", "database.json"); - if(file.exists()) { - String contents= FileUtils.readFileToString(file, StandardCharsets.UTF_8); - try (PrintWriter out = new PrintWriter(f.getAbsolutePath())) { - out.println(contents); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } } return f; } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/assets/StudioBuildInfo.java b/src/main/java/com/neuronrobotics/bowlerstudio/assets/StudioBuildInfo.java index b5c58f6f9..6cba98058 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/assets/StudioBuildInfo.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/assets/StudioBuildInfo.java @@ -86,7 +86,7 @@ public static String getBuildDate() { } } catch (IOException ignored) { } - // System.out.println("Manifest:\n"+s); + // com.neuronrobotics.sdk.common.Log.error("Manifest:\n"+s); return ""; } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/creature/CadFileExporter.java b/src/main/java/com/neuronrobotics/bowlerstudio/creature/CadFileExporter.java index a3520d40e..9bcd296fc 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/creature/CadFileExporter.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/creature/CadFileExporter.java @@ -10,6 +10,7 @@ import org.apache.commons.io.FilenameUtils; import com.neuronrobotics.bowlerstudio.scripting.BlenderLoader; +import com.neuronrobotics.bowlerstudio.scripting.FreecadLoader; import eu.mihosoft.vrl.v3d.CSG; import eu.mihosoft.vrl.v3d.FileUtil; @@ -29,37 +30,37 @@ public CadFileExporter(){ @Override public void setSelectedCsg(Collection selectedCsg) { - // TODO Auto-generated method stub + // Auto-generated method stub } @Override public void setAllCSG(Collection toAdd, File source) { - // TODO Auto-generated method stub + // Auto-generated method stub } @Override public void highlightException(File fileEngineRunByName, Throwable ex) { - // TODO Auto-generated method stub + // Auto-generated method stub } @Override public Set getVisibleCSGs() { - // TODO Auto-generated method stub + // Auto-generated method stub return null; } @Override public void addCSG(Collection toAdd, File source) { - // TODO Auto-generated method stub + // Auto-generated method stub } @Override public void setSelected(Affine rootListener) { - // TODO Auto-generated method stub + // Auto-generated method stub } }; @@ -82,7 +83,11 @@ public ArrayList generateManufacturingParts(List totalAssembly , File } int index=0; ArrayList svgParts = new ArrayList<>(); + ArrayList blendParts = new ArrayList<>(); + ArrayList freecadParts = new ArrayList<>(); String svgName =null; + String blendName=null; + String freecadName=null; String nameBase =""; for(CSG part: totalAssembly){ String name = part.getName(); @@ -99,7 +104,7 @@ public ArrayList generateManufacturingParts(List totalAssembly , File try { allCadStl.add(makeStl(nameBase,manufactured));// default to stl }catch(Throwable t) { - System.err.println("Failed to generate "+part.getName()); + com.neuronrobotics.sdk.common.Log.error("Failed to generate "+part.getName()); t.printStackTrace(); } }else{ @@ -109,10 +114,6 @@ public ArrayList generateManufacturingParts(List totalAssembly , File allCadStl.add(makeObj(nameBase,manufactured));// ui.setCsg(manufactured , null); } - if(format.toLowerCase().contains("blend")){ - allCadStl.add(makeBlender(nameBase,manufactured));// - ui.setCsg(manufactured , null); - } if(format.toLowerCase().contains("stl")){ allCadStl.add(makeStl(nameBase,manufactured));// default to stl ui.setCsg(manufactured , null); @@ -124,7 +125,22 @@ public ArrayList generateManufacturingParts(List totalAssembly , File svgParts.add(manufactured); ui.setAllCSG(svgParts , null); } - + if(format.toLowerCase().contains("blend")){ + //allCadStl.add(makeBlender(nameBase,manufactured));// + ui.setCsg(manufactured , null); + if(blendName==null){ + blendName =part.toString(); + } + blendParts.add(manufactured); + } + if(format.toLowerCase().contains("freecad")){ + //allCadStl.add(makeBlender(nameBase,manufactured));// + ui.setCsg(manufactured , null); + if(freecadName==null){ + freecadName =part.toString(); + } + freecadParts.add(manufactured); + } } } @@ -132,13 +148,29 @@ public ArrayList generateManufacturingParts(List totalAssembly , File if(svgParts.size()>0){ allCadStl.add(makeSvg(nameBase,svgParts));// default to stl } - + if(blendParts.size()>0){ + allCadStl.add(makeBlender(nameBase,blendParts));// default to stl + } + if(freecadParts.size()>0){ + allCadStl.add(makeFreecad(nameBase,freecadParts));// default to stl + } + System.out.println("Finished Export!"); return allCadStl; } + private File makeFreecad(String nameBase,List current ) throws IOException{ + File blend = new File(nameBase + ".FCStd"); + System.out.println("Writing "+blend.getAbsolutePath()); + for(CSG tmp:current) + FreecadLoader.addCSGToFreeCAD( blend,tmp); + return blend; + } + private File makeStl(String nameBase,CSG tmp ) throws IOException{ File stl = new File(nameBase + ".stl"); - +// boolean manifold=CSG.isPreventNonManifoldTriangles(); +// CSG.setPreventNonManifoldTriangles(false); FileUtil.write(Paths.get(stl.getAbsolutePath()), tmp.toStlString()); + //CSG.setPreventNonManifoldTriangles(manifold); System.out.println("Writing "+stl.getAbsolutePath()); return stl; } @@ -150,10 +182,11 @@ private File makeObj(String nameBase,CSG tmp ) throws IOException{ return stl; } - private File makeBlender(String nameBase,CSG tmp ) throws IOException{ + private File makeBlender(String nameBase,List current ) throws IOException{ File blend = new File(nameBase + ".blend"); System.out.println("Writing "+blend.getAbsolutePath()); - BlenderLoader.toBlenderFile(tmp, blend); + for(CSG tmp:current) + BlenderLoader.toBlenderFile(tmp, blend); return blend; } @@ -184,7 +217,7 @@ private File makeSvg(String nameBase, List currentCsg) throws IOException { System.out.println("Writing " + stl.getAbsolutePath()); } catch (Throwable t) { - System.err.println("ERROR, NO pixelization engine availible for slicing"); + com.neuronrobotics.sdk.common.Log.error("ERROR, NO pixelization engine availible for slicing"); t.printStackTrace(); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/creature/MobileBaseCadManager.java b/src/main/java/com/neuronrobotics/bowlerstudio/creature/MobileBaseCadManager.java index 3f906a5c6..807f0ad2b 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/creature/MobileBaseCadManager.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/creature/MobileBaseCadManager.java @@ -75,10 +75,9 @@ public class MobileBaseCadManager implements Runnable { private HashMap> DHtoCadMap = new HashMap<>(); private HashMap> LinktoCadMap = new HashMap<>(); private HashMap> BasetoCadMap = new HashMap<>(); - private HashMap vitaminCad=new HashMap<>(); - private HashMap vitaminDisplay=new HashMap<>(); - private HashMap vitaminLocation=new HashMap<>(); - + private HashMap vitaminCad = new HashMap<>(); + private HashMap vitaminDisplay = new HashMap<>(); + private HashMap vitaminLocation = new HashMap<>(); private boolean cadGenerating = false; private boolean showingStl = false; @@ -95,72 +94,75 @@ public class MobileBaseCadManager implements Runnable { private Thread renderWrangler = null; private HashMap cadScriptCache = new HashMap<>(); private static ArrayList toRun = new ArrayList(); - private ArrayList rendersync=new ArrayList<>(); + private ArrayList rendersync = new ArrayList<>(); private boolean forceChage = true; + public CSG getVitamin(VitaminLocation vitamin) throws Exception { - return getVitamin(vitamin,new Affine(),null); + return getVitamin(vitamin, new Affine(), null); } - public ArrayList getVitamins(IVitaminHolder link,Affine manipulator) { + public ArrayList getVitamins(IVitaminHolder link, Affine manipulator) { ArrayList vitamins = link.getVitamins(); - return toVitaminCad(vitamins,manipulator,null); + return toVitaminCad(vitamins, manipulator, null); } - public ArrayList getOriginVitamins(IVitaminHolder link,Affine manipulator,TransformNR offset){ + + public ArrayList getOriginVitamins(IVitaminHolder link, Affine manipulator, TransformNR offset) { ArrayList vitamins = link.getOriginVitamins(); - return toVitaminCad(vitamins,manipulator,offset); + return toVitaminCad(vitamins, manipulator, offset); } - public ArrayList getDefaultVitamins(IVitaminHolder link,Affine manipulator){ + + public ArrayList getDefaultVitamins(IVitaminHolder link, Affine manipulator) { ArrayList vitamins = link.getDefaultVitamins(); - return toVitaminCad(vitamins,manipulator,null); + return toVitaminCad(vitamins, manipulator, null); } - public ArrayList getPreviousLinkVitamins(IVitaminHolder link,Affine manipulator){ + + public ArrayList getPreviousLinkVitamins(IVitaminHolder link, Affine manipulator) { ArrayList vitamins = link.getPreviousLinkVitamins(); - return toVitaminCad(vitamins,manipulator,null); + return toVitaminCad(vitamins, manipulator, null); } - - private ArrayList toVitaminCad(ArrayList vitamins,Affine manipulator, TransformNR offset) { + private ArrayList toVitaminCad(ArrayList vitamins, Affine manipulator, TransformNR offset) { ArrayList parts = new ArrayList(); - for(VitaminLocation vi:vitamins) { + for (VitaminLocation vi : vitamins) { CSG vitamin; try { - vitamin = getVitamin(vi,manipulator,offset); + vitamin = getVitamin(vi, manipulator, offset); parts.add(vitamin); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } return parts; } - - + public ArrayList getVitamins(AbstractLink link) { LinkConfiguration conf = link.getLinkConfiguration(); return getVitamins(conf, (Affine) link.getGlobalPositionListener()); } - - public ArrayList getVitamins(AbstractLink link,Affine manipulator) { + public ArrayList getVitamins(AbstractLink link, Affine manipulator) { LinkConfiguration conf = link.getLinkConfiguration(); return getVitamins(conf, manipulator); } + public ArrayList getVitamins(MobileBase base) { Affine rootListener = (Affine) base.getRootListener(); return getVitamins(base, rootListener); } - public CSG getVitamin(VitaminLocation vitamin,Affine manipulator,TransformNR offset) { - if(!vitaminCad.containsKey(vitamin)) { + + public CSG getVitamin(VitaminLocation vitamin, Affine manipulator, TransformNR offset) { + if (!vitaminCad.containsKey(vitamin)) { CSG starting; try { CSG origin = vitaminMakeCSG(vitamin); - starting=origin.transformed(TransformFactory.nrToCSG(vitamin.getLocation())); - if(offset!=null) - starting=starting.transformed(TransformFactory.nrToCSG(offset)); + starting = origin.transformed(TransformFactory.nrToCSG(vitamin.getLocation())); + if (offset != null) + starting = starting.transformed(TransformFactory.nrToCSG(offset)); starting.setIsWireFrame(true); starting.syncProperties(origin); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); return null; } @@ -171,36 +173,37 @@ public CSG getVitamin(VitaminLocation vitamin,Affine manipulator,TransformNR off } public static CSG vitaminMakeCSG(VitaminLocation vitamin) throws Exception { - if(vitamin.isScript()) { - Object o =ScriptingEngine.gitScriptRun(vitamin.getType(), vitamin.getSize()); - ArrayList flat= new ArrayList(); - Vitamins.flatten(flat,o); - return CSG.unionAll( flat); - }else + if (vitamin.isScript()) { + Object o = ScriptingEngine.gitScriptRun(vitamin.getType(), vitamin.getSize()); + ArrayList flat = new ArrayList(); + Vitamins.flatten(flat, o); + return CSG.unionAll(flat); + } else return Vitamins.get(vitamin.getType(), vitamin.getSize()); } - public CSG getVitaminDisplay(VitaminLocation vitamin,Affine manipulator, TransformNR offset){ - if(!vitaminDisplay.containsKey(vitamin)) { + + public CSG getVitaminDisplay(VitaminLocation vitamin, Affine manipulator, TransformNR offset) { + if (!vitaminDisplay.containsKey(vitamin)) { CSG starting; Affine offsetDisplay = new Affine(); try { starting = vitaminMakeCSG(vitamin); - if(offset!=null){ - BowlerKernel.runLater(()->{ - TransformFactory.nrToAffine(offset,offsetDisplay); + if (offset != null) { + BowlerKernel.runLater(() -> { + TransformFactory.nrToAffine(offset, offsetDisplay); }); } } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); return null; } starting.setManipulator(manipulator); - Affine frameOffset=new Affine(); - Affine cameraFrame=new Affine(); + Affine frameOffset = new Affine(); + Affine cameraFrame = new Affine(); setFrames(vitamin, frameOffset, cameraFrame); vitaminLocation.put(vitamin, cameraFrame); - vitamin.addChangeListener(()->{ + vitamin.addChangeListener(() -> { setFrames(vitamin, frameOffset, cameraFrame); }); @@ -211,6 +214,7 @@ public CSG getVitaminDisplay(VitaminLocation vitamin,Affine manipulator, Transfo } return vitaminDisplay.get(vitamin); } + private void setFrames(VitaminLocation vitamin, Affine frameOffset, Affine cameraFrame) { BowlerKernel.runLater(() -> { TransformNR translationComponent = vitamin.getLocation().copy().setRotation(new RotationNR()); @@ -222,201 +226,211 @@ private void setFrames(VitaminLocation vitamin, Affine frameOffset, Affine camer public Affine getVitaminAffine(VitaminLocation vitamin) { Affine a = vitaminLocation.get(vitamin); - if(a!=null) + if (a != null) return a; - throw new RuntimeException("Affine not present! "+vitamin.getName()); + throw new RuntimeException("Affine not present! " + vitamin.getName()); } - - public ArrayList getOriginVitaminsDisplay(IVitaminHolder link,Affine manipulator,TransformNR offset){ + + public ArrayList getOriginVitaminsDisplay(IVitaminHolder link, Affine manipulator, TransformNR offset) { ArrayList vitamins = link.getOriginVitamins(); - return vitaminsToDisplay(vitamins,manipulator,offset); + return vitaminsToDisplay(vitamins, manipulator, offset); } - public ArrayList getDefaultVitaminsDisplay(IVitaminHolder link,Affine manipulator){ + + public ArrayList getDefaultVitaminsDisplay(IVitaminHolder link, Affine manipulator) { ArrayList vitamins = link.getDefaultVitamins(); - return vitaminsToDisplay(vitamins,manipulator); + return vitaminsToDisplay(vitamins, manipulator); } - public ArrayList getPreviousLinkVitaminsDisplay(IVitaminHolder link,Affine manipulator){ + + public ArrayList getPreviousLinkVitaminsDisplay(IVitaminHolder link, Affine manipulator) { ArrayList vitamins = link.getPreviousLinkVitamins(); - return vitaminsToDisplay(vitamins,manipulator); + return vitaminsToDisplay(vitamins, manipulator); } - - public ArrayList getVitaminsDisplay(IVitaminHolder link,Affine manipulator) { - - return vitaminsToDisplay(link.getVitamins(),manipulator); + + public ArrayList getVitaminsDisplay(IVitaminHolder link, Affine manipulator) { + + return vitaminsToDisplay(link.getVitamins(), manipulator); } - - public ArrayList vitaminsToDisplay(ArrayList l,Affine manipulator){ - return vitaminsToDisplay(l,manipulator,null); + + public ArrayList vitaminsToDisplay(ArrayList l, Affine manipulator) { + return vitaminsToDisplay(l, manipulator, null); } - public ArrayList vitaminsToDisplay(ArrayList l,Affine manipulator, TransformNR offset){ + + public ArrayList vitaminsToDisplay(ArrayList l, Affine manipulator, TransformNR offset) { ArrayList parts = new ArrayList(); - for(VitaminLocation vi:l) { + for (VitaminLocation vi : l) { CSG vitamin; try { - vitamin = getVitaminDisplay(vi,manipulator, offset); + vitamin = getVitaminDisplay(vi, manipulator, offset); parts.add(vitamin); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } return parts; } - + public ArrayList getVitaminsDisplay(AbstractLink link) { LinkConfiguration conf = link.getLinkConfiguration(); return getVitaminsDisplay(conf, (Affine) link.getGlobalPositionListener()); } - public ArrayList getVitaminsDisplay(AbstractLink link,Affine manipulator) { + + public ArrayList getVitaminsDisplay(AbstractLink link, Affine manipulator) { LinkConfiguration conf = link.getLinkConfiguration(); return getVitaminsDisplay(conf, manipulator); } - public ArrayList getVitaminsDisplay(MobileBase base) { Affine rootListener = (Affine) base.getRootListener(); return getVitaminsDisplay(base, rootListener); } - + public void render() { run(); - forceChage=true; - while(forceChage) + forceChage = true; + while (forceChage) ThreadUtil.wait(1); } + public void addIRenderSynchronizationEvent(IRenderSynchronizationEvent ev) { - if(rendersync.contains(ev)) + if (rendersync.contains(ev)) return; rendersync.add(ev); } + public void removeIRenderSynchronizationEvent(IRenderSynchronizationEvent ev) { - if(rendersync.contains(ev)) + if (rendersync.contains(ev)) rendersync.remove(ev); } - + private void fireIRenderSynchronizationEvent() { - for(int i=0;ihighest.x) - highest.x=high.x; - if(high.y>highest.y) - highest.y=high.y; - if(high.z>highest.z) - highest.z=high.z; + + if (highest == null) + highest = high; + if (high.x > highest.x) + highest.x = high.x; + if (high.y > highest.y) + highest.y = high.y; + if (high.z > highest.z) + highest.z = high.z; } - for(DHParameterKinematics k:cat.getAllDHChains()) { - for(int i=0;ihighest.x) - highest.x=high.x; - if(high.y>highest.y) - highest.y=high.y; - if(high.z>highest.z) - highest.z=high.z; + + if (highest == null) + highest = high; + if (high.x > highest.x) + highest.x = high.x; + if (high.y > highest.y) + highest.y = high.y; + if (high.z > highest.z) + highest.z = high.z; } } } return highest; } + public Vector3d computeLowestPoint() { render(); - MobileBase cat=base; + MobileBase cat = base; MobileBaseCadManager cadMan = MobileBaseCadManager.get(cat); - Vector3d lowest =null; - Affine l =(Affine) cat.getRootListener(); + Vector3d lowest = null; + Affine l = (Affine) cat.getRootListener(); TransformNR tmp = TransformFactory.affineToNr(l); Transform baseloc = TransformFactory.nrToCSG(tmp); - for(CSG c:cadMan.getBasetoCadMap().get(cat)) { + for (CSG c : cadMan.getBasetoCadMap().get(cat)) { CSG moved = c.transformed(baseloc); double z = moved.getMinZ(); - double y= moved.getMinY(); - double x=moved.getMinX(); + double y = moved.getMinY(); + double x = moved.getMinX(); Vector3d low = new Vector3d(x, y, z); - - if(lowest==null) - lowest=low; - if(low.x toAdd, File source) { - // TODO Auto-generated method stub - // TODO Auto-generated method stub + // Auto-generated method stub + // Auto-generated method stub list.clear(); list.addAll(toAdd); } @Override public void addCSG(Collection toAdd, File source) { - // TODO Auto-generated method stub + // Auto-generated method stub list.addAll(toAdd); } @Override public Set getVisibleCSGs() { - // TODO Auto-generated method stub + // Auto-generated method stub return new HashSet(list); } @Override public void setSelectedCsg(Collection selectedCsg) { - // TODO Auto-generated method stub + // Auto-generated method stub } @Override public void setSelected(Affine rootListener) { - // TODO Auto-generated method stub + // Auto-generated method stub } }; @@ -532,13 +546,14 @@ public void onBaseToFiducialUpdate(AbstractKinematicsNR source, TransformNR rege l.onIOnMobileBaseRenderChange(); } }; - ILinkConfigurationChangeListener confL= new ILinkConfigurationChangeListener() { + ILinkConfigurationChangeListener confL = new ILinkConfigurationChangeListener() { @Override public void event(LinkConfiguration newConf) { l.onIOnMobileBaseRenderChange(); } - + }; + @Override public void run() { base.addIOnMobileBaseRenderChange(l); @@ -551,14 +566,14 @@ public void run() { kin.addRegistrationListener(r); } // render on any configuration change - addConfL(base,confL); + addConfL(base, confL); setName("MobileBaseCadManager Render Thread for " + base.getScriptingName()); while (base.isAvailable()) { try { do { Thread.sleep(5); - if(forceChage) { - forceChage=false; + if (forceChage) { + forceChage = false; l.onIOnMobileBaseRenderChange(); } } while (rendering || changed == false); @@ -594,8 +609,8 @@ public void run() { jointPosesTmp.clear(); jointPosesTmp = null; - Affine[] iterator = tmp.keySet().stream().toArray(size->new Affine[size]); - TransformNR[] vals = tmp.values().stream().toArray(size->new TransformNR[size]); + Affine[] iterator = tmp.keySet().stream().toArray(size -> new Affine[size]); + TransformNR[] vals = tmp.values().stream().toArray(size -> new TransformNR[size]); tmp.clear(); if (iterator.length > 0) { BowlerKernel.runLater(() -> { @@ -635,7 +650,8 @@ public void run() { } } catch (Throwable t) { // rendering not availible - System.err.println("Exception for render engine " + base.getScriptingName()); + com.neuronrobotics.sdk.common.Log + .error("Exception for render engine " + base.getScriptingName()); t.printStackTrace(); try { Thread.sleep(100); @@ -643,17 +659,18 @@ public void run() { break; } } - + } renderWrangler = null; } + private void addConfL(MobileBase base, ILinkConfigurationChangeListener confL2) { - if(base==null) + if (base == null) return; - for(DHParameterKinematics k:base.getAllDHChains()) { - for(int i=0;i map2, HashMap jointPoses) { - TransformNR back =updateBase(b, baseLoc, map2); + TransformNR back = updateBase(b, baseLoc, map2); for (DHParameterKinematics k : b.getAllDHChains()) { updateLimb(k, back, map2, jointPoses); } @@ -691,7 +708,7 @@ private void updateMobileBase(MobileBase b, TransformNR baseLoc, HashMap map2, HashMap jointPoses) { - //updateBase(k, baseLoc, map2); + // updateBase(k, baseLoc, map2); TransformNR previous = k.getFiducialToGlobalTransform(); k.setGlobalToFiducialTransform(baseLoc, false); ArrayList ll = k.getChain().getChain(jointPoses.get(k)); @@ -719,8 +736,8 @@ private void updateLimb(DHParameterKinematics k, TransformNR baseLoc, HashMap { + Object cadForBodyEngine = scriptFromFileInfo(b.getScriptingName(), b.getGitCadEngine(), () -> { run(); generateCad(); }); @@ -868,10 +885,10 @@ private IgenerateBody getIgenerateBody(MobileBase b) throws Throwable{ return null; } - private IgenerateCad getIgenerateCad(DHParameterKinematics dh) throws Throwable{ + private IgenerateCad getIgenerateCad(DHParameterKinematics dh) throws Throwable { if (isConfigMode()) return getConfigurationDisplay(); - Object cadForBodyEngine = scriptFromFileInfo(dh.getScriptingName(),dh.getGitCadEngine(), () -> { + Object cadForBodyEngine = scriptFromFileInfo(dh.getScriptingName(), dh.getGitCadEngine(), () -> { run(); generateCad(); }); @@ -881,8 +898,8 @@ private IgenerateCad getIgenerateCad(DHParameterKinematics dh) throws Throwable{ return null; } - public IgenerateBed getIgenerateBed() throws Throwable{ - Object cadForBodyEngine = scriptFromFileInfo(base.getScriptingName(),base.getGitCadEngine(), () -> { + public IgenerateBed getIgenerateBed() throws Throwable { + Object cadForBodyEngine = scriptFromFileInfo(base.getScriptingName(), base.getGitCadEngine(), () -> { run(); }); if (IgenerateBed.class.isInstance(cadForBodyEngine)) { @@ -891,16 +908,16 @@ public IgenerateBed getIgenerateBed() throws Throwable{ return null; } - private ICadGenerator getConfigurationDisplay()throws Throwable { + private ICadGenerator getConfigurationDisplay() throws Throwable { if (cadEngineConfiguration == null) { - String[] args = new String[] { - "https://github.com/CommonWealthRobotics/DHParametersCadDisplay.git", "dhcad.groovy" }; + String[] args = new String[] { "https://github.com/CommonWealthRobotics/DHParametersCadDisplay.git", + "dhcad.groovy" }; Object cadForBodyEngine = scriptFromFileInfo("ConfigDisplay", args, () -> { cadEngineConfiguration = null; try { getConfigurationDisplay(); } catch (Throwable e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } MobileBaseCadManager mobileBaseCadManager = null; @@ -936,7 +953,7 @@ public ArrayList generateBody(MobileBase base, boolean clear) { getAllCad().clear(); setAllCad(new ArrayList<>()); } - //System.gc(); + // System.gc(); MobileBase device = base; if (getBasetoCadMap().get(device) == null) { getBasetoCadMap().put(device, new ArrayList()); @@ -974,9 +991,14 @@ public ArrayList generateBody(MobileBase base, boolean clear) { } else getUi().highlightException(null, new Exception()); ArrayList arrayList = getBasetoCadMap().get(device); + if (arrayList== null) { + arrayList=new ArrayList(); + getBasetoCadMap().put(device, arrayList); + } + if (clear) { arrayList.clear(); - //System.gc(); + // System.gc(); } for (CSG c : getAllCad()) { arrayList.add(c); @@ -991,11 +1013,11 @@ public ArrayList generateBody(MobileBase base, boolean clear) { } catch (Throwable e) { getUi().highlightException(getCadScriptFromMobileBase(device), e); } - System.out.println("Displaying Body"); + com.neuronrobotics.sdk.common.Log.error("Displaying Body"); setProgress(0.35); // clears old robot and places base getUi().setAllCSG(getBasetoCadMap().get(device), getCadScriptFromMobileBase(device)); - System.out.println("Rendering limbs"); + com.neuronrobotics.sdk.common.Log.error("Rendering limbs"); setProgress(0.4); ArrayList limbs = base.getAllDHChains(); double numLimbs = limbs.size(); @@ -1017,7 +1039,7 @@ public ArrayList generateBody(MobileBase base, boolean clear) { } else { if (clear) { arrayList.clear(); - //System.gc(); + // System.gc(); } ArrayList linksCad = generateCad(l); @@ -1039,7 +1061,7 @@ public ArrayList generateBody(MobileBase base, boolean clear) { getAllCad().addAll(m.generateBody(m.base, false)); } showingStl = false; - //setProgress(1); + // setProgress(1); // PhysicsEngine.clear(); // MobileBasePhysicsManager m = new MobileBasePhysicsManager(base, // baseCad, getSimplecad()); @@ -1053,7 +1075,7 @@ public File getCadScriptFromLimnb(DHParameterKinematics l) { try { return ScriptingEngine.fileFromGit(l.getGitCadEngine()[0], l.getGitCadEngine()[1]); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } return null; @@ -1063,7 +1085,7 @@ public File getCadScriptFromMobileBase(MobileBase device) { try { return ScriptingEngine.fileFromGit(device.getGitCadEngine()[0], device.getGitCadEngine()[1]); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } return null; @@ -1078,7 +1100,8 @@ private void set(MobileBase base, int limb, int link) { DHParameterKinematics dh = limbs.get(limb); double partsTotal = numLimbs * dh.getNumberOfLinks(); double progress = ((double) ((limb * dh.getNumberOfLinks()) + link)) / partsTotal; - // System.out.println("Cad progress " + progress + " limb " + limb + " link " + + // com.neuronrobotics.sdk.common.Log.error("Cad progress " + progress + " limb " + // + limb + " link " + // link + " total parts " + partsTotal); setProgress(0.333 + (2 * (progress / 3))); } @@ -1099,46 +1122,46 @@ public ArrayList generateStls(MobileBase base, File baseDirForFiles, boole File dir = new File(baseDirForFiles.getAbsolutePath() + "/" + base.getScriptingName()); if (!dir.exists()) dir.mkdirs(); - IgenerateBed bed=null; + IgenerateBed bed = null; String baseURL = base.getGitSelfSource()[0]; File baseWorkspaceFile = ScriptingEngine.getRepositoryCloneDirectory(baseURL); bed = getPrintBed(dir, bed, baseWorkspaceFile); if (bed == null || kinematic) { return _generateStls(base, dir, kinematic); } - - System.out.println("Found arrangeBed API in CAD engine"); + + com.neuronrobotics.sdk.common.Log.error("Found arrangeBed API in CAD engine"); List totalAssembly = bed.arrangeBed(base); getUi().setAllCSG(totalAssembly, getCadScriptFromMobileBase(base)); - return new CadFileExporter(getUi()).generateManufacturingParts(totalAssembly, dir); } + public IgenerateBed getPrintBed(File baseDirForFiles, IgenerateBed bed, File baseWorkspaceFile) throws IOException { - File bomCSV = new File(baseWorkspaceFile.getAbsolutePath()+"/"+VitaminBomManager.MANUFACTURING_BOM_CSV); - if(bomCSV.exists()) { - - File file = new File(baseDirForFiles.getAbsolutePath()+"/bom.csv"); - if(file.exists()) + File bomCSV = new File(baseWorkspaceFile.getAbsolutePath() + "/" + VitaminBomManager.getManufacturingBomCsv()); + if (bomCSV.exists()) { + + File file = new File(baseDirForFiles.getAbsolutePath() + "/bom.csv"); + if (file.exists()) file.delete(); - Files.copy(bomCSV.toPath(),file.toPath()); + Files.copy(bomCSV.toPath(), file.toPath()); } - File bom = new File(baseWorkspaceFile.getAbsolutePath()+"/"+VitaminBomManager.MANUFACTURING_BOM_JSON); - if(bom.exists()) { - File file = new File(baseDirForFiles.getAbsolutePath()+"/bom.json"); - if(file.exists()) + File bom = new File(baseWorkspaceFile.getAbsolutePath() + "/" + VitaminBomManager.getManufacturingBomJson()); + if (bom.exists()) { + File file = new File(baseDirForFiles.getAbsolutePath() + "/bom.json"); + if (file.exists()) file.delete(); - Files.copy(bom.toPath(),file.toPath()); + Files.copy(bom.toPath(), file.toPath()); } - try{ - bed= getIgenerateBed(); - }catch(Throwable T) { + try { + bed = getIgenerateBed(); + } catch (Throwable T) { throw new RuntimeException(T.getMessage()); } - if(bed == null) { - File printArrangment = new File(baseWorkspaceFile.getAbsolutePath()+"/"+PrintBedManager.file); - if(printArrangment.exists()) { - bed = new UserManagedPrintBed(printArrangment,this); + if (bed == null) { + File printArrangment = new File(baseWorkspaceFile.getAbsolutePath() + "/" + PrintBedManager.file); + if (printArrangment.exists()) { + bed = new UserManagedPrintBed(printArrangment, this); } } return bed; @@ -1178,24 +1201,30 @@ public ArrayList _generateStls(MobileBase base, File baseDirForFiles, bool else totalAssembly.add(tmp); LinkConfiguration conf = getLinkConfiguration(parts.get(j)); - if(conf!=null) { + if (conf != null) { String linkNum = conf.getLinkIndex() + "_Link_"; - + File dir = new File(baseDirForFiles.getAbsolutePath() + "/" + base.getScriptingName() + "/" + l.getScriptingName()); if (!dir.exists()) dir.mkdirs(); - - File stl = new File( - dir.getAbsolutePath() + "/" + linkNum + name + "_limb_" + i + "_Part_" + j + ".stl"); - System.out.println("Writing STL for " + name+" to "+stl.getAbsolutePath()); + + File stl = new File(dir.getAbsolutePath() + "/" + linkNum + name + "_limb_" + i + "_Part_" + + j + ".stl"); + com.neuronrobotics.sdk.common.Log + .error("Writing STL for " + name + " to " + stl.getAbsolutePath()); + boolean manifold = CSG.isPreventNonManifoldTriangles(); + //CSG.setPreventNonManifoldTriangles(false); FileUtil.write(Paths.get(stl.getAbsolutePath()), tmp.toStlString()); + + CSG.setPreventNonManifoldTriangles(manifold); allCadStl.add(stl); // totalAssembly.add(tmp); getUi().setAllCSG(totalAssembly, getCadScriptFromMobileBase(base)); set(base, i, j); - }else { - System.err.println("ERROR "+parts.get(j).getName()+" has no link associated "); + } else { + com.neuronrobotics.sdk.common.Log + .error("ERROR " + parts.get(j).getName() + " has no link associated "); } } } catch (Exception ex) { @@ -1270,7 +1299,7 @@ public void setMobileBase(MobileBase b) { for (DHParameterKinematics k : base.getAllDHChains()) { k.setRenderWrangler(this); } - base.setConfigurationUpdate(()->{ + base.setConfigurationUpdate(() -> { generateCad(); }); run(); @@ -1299,7 +1328,7 @@ public void onDisconnect(BowlerAbstractDevice arg0) { @Override public void onConnect(BowlerAbstractDevice arg0) { - // TODO Auto-generated method stub + // Auto-generated method stub } }); @@ -1361,7 +1390,7 @@ public ArrayList generateCad(DHParameterKinematics dh) { @Override public void onLinkPositionUpdate(AbstractLink arg0, double arg1) { - // TODO Auto-generated method stub + // Auto-generated method stub } @@ -1395,7 +1424,7 @@ public void selectCsgByMobileBase(MobileBase base) { getUi().setSelectedCsg(csg); } catch (Exception ex) { // getUi().highlightException(null, ex); - System.err.println("Base not loaded yet"); + com.neuronrobotics.sdk.common.Log.error("Base not loaded yet"); } } @@ -1408,7 +1437,7 @@ public void selectCsgByLimb(MobileBase base, DHParameterKinematics limb) { getUi().setSelected((Affine) limb.getRootListener()); } catch (Exception ex) { // getUi().highlightException(null, ex); - System.err.println("Limb not loaded yet"); + com.neuronrobotics.sdk.common.Log.error("Limb not loaded yet"); } } @@ -1418,12 +1447,14 @@ public void selectCsgByLink(MobileBase base, LinkConfiguration limb) { ArrayList limCad = MobileBaseCadManager.get(base).getLinktoCadMap().get(limb); getUi().setSelectedCsg(limCad); } catch (Exception ex) { - System.err.println("Limb not loaded yet"); + com.neuronrobotics.sdk.common.Log.error("Limb not loaded yet"); } } + public void generateCad() { - generateCadWithEnd((Runnable)null); + generateCadWithEnd((Runnable) null); } + public void generateCadWithEnd(Runnable done) { if (cadGenerating || !getAutoRegen()) return; @@ -1449,7 +1480,7 @@ public void run() { try { setAllCad(generateBody(device, true)); } catch (Exception e) { - + getUi().highlightException(getCadScriptFromMobileBase(device), e); } @@ -1464,14 +1495,14 @@ public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } setProgress(1); - if(done!=null) { + if (done != null) { try { done.run(); - }catch(Throwable t) { + } catch (Throwable t) { t.printStackTrace(); } } @@ -1479,12 +1510,14 @@ public void run() { } }.start(); } + private void setProgress(double val) { - if(cadGenerating==false) { - val=1; + if (cadGenerating == false) { + val = 1; } getProcesIndictor().set(val); } + public void onTabClosing() { } @@ -1533,8 +1566,6 @@ public static MobileBaseCadManager get(MobileBase device, IMobileBaseUI ui) { return mobileBaseCadManager; } - - public static MobileBaseCadManager get(MobileBase device) { if (cadmap.get(device) == null) { for (MobileBase mb : cadmap.keySet()) { @@ -1552,14 +1583,14 @@ public static MobileBaseCadManager get(MobileBase device) { @Override public void onDisconnect(BowlerAbstractDevice source) { - // TODO Auto-generated method stub + // Auto-generated method stub ui2.list.clear(); } @Override public void onConnect(BowlerAbstractDevice source) { - // TODO Auto-generated method stub + // Auto-generated method stub } }); @@ -1634,61 +1665,65 @@ public void setUi(IMobileBaseUI ui) { } public void setConfigurationViewerMode(boolean b) { - System.out.println("Setting config mode " + b); + com.neuronrobotics.sdk.common.Log.error("Setting config mode " + b); setConfigMode(b); for (MobileBaseCadManager m : slaves) { m.setConfigurationViewerMode(b); } } + public void invalidateModelCache() { - // TODO Auto-generated method stub - + // Auto-generated method stub + } + /** * @return the configMode */ public boolean isConfigMode() { return configMode; } + /** * @param configMode the configMode to set */ public void setConfigMode(boolean configMode) { this.configMode = configMode; } + public boolean isCADstarted() { - // TODO Auto-generated method stub + // Auto-generated method stub return cadGenerating; } public static MobileBaseCadManager get(IVitaminHolder holder) { Set keySet = cadmap.keySet(); - for(MobileBase b:keySet) { - MobileBaseCadManager m =checkforBase(holder, b); - if (m!=null) + for (MobileBase b : keySet) { + MobileBaseCadManager m = checkforBase(holder, b); + if (m != null) return m; } return null; } + private static MobileBaseCadManager checkforBase(IVitaminHolder holder, MobileBase b) { - if(b==holder) + if (b == holder) return get(b); - for(DHParameterKinematics k:b.getAllDHChains()) { - for(int i=0;i incoming) { + Vector3d min = null; + Vector3d max = null; + for (CSG c : incoming) { + if(c.isHide()) + continue; + if(c.isInGroup()) + continue; + Vector3d min2 = c.getBounds().getMin().clone(); + Vector3d max2 = c.getBounds().getMax().clone(); + if (min == null) + min = min2; + if (max == null) + max = max2; + if (min2.x < min.x) + min.x = min2.x; + if (min2.y < min.y) + min.y = min2.y; + if (min2.z < min.z) + min.z = min2.z; + if (max.x < max2.x) + max.x = max2.x; + if (max.y < max2.y) + max.y = max2.y; + if (max.z < max2.z) + max.z = max2.z; + } + if(max==null) + max=new Vector3d(0,0,0); + if(min==null) + min=new Vector3d(0,0,0); + return new Bounds(min, max); + } + + public static WritableImage get(List c) { + ArrayList csgList=new ArrayList() ; + for(CSG cs:c) { + if(cs.getManipulator()!=null) { + TransformNR nr = TransformFactory.affineToNr(cs.getManipulator()); + csgList.add(cs.transformed(TransformFactory.nrToCSG(nr)).syncProperties(cs)); + }else + csgList.add(cs); + } + // Create a group to hold all the meshes + Group root = new Group(); + + // Add all meshes to the group + Bounds b = getSellectedBounds(csgList); + + double yOffset = (b.getMax().y-b.getMin().y)/2; + double xOffset =(b.getMax().x -b.getMin().x)/2; + double zCenter = (b.getMax().z -b.getMin().z)/2; + for (CSG csg : csgList) { + if(csg.isHide()) + continue; + if(csg.isInGroup()) + continue; + MeshView meshView = csg.movez(-zCenter).getMesh(); + if (csg.isHole()) { + PhongMaterial material = new PhongMaterial(); + material.setDiffuseColor(new Color(0.25, 0.25, 0.25, 0.75)); + material.setSpecularColor(javafx.scene.paint.Color.WHITE); + meshView.setMaterial(material); + meshView.setOpacity(0.25); + } + meshView.setCullFace(CullFace.BACK); + root.getChildren().add(meshView); + } + + // Calculate the bounds of all CSGs combined + double totalz = b.getMax().z - b.getMin().z; + double totaly = b.getMax().y - b.getMin().y; + double totalx = b.getMax().x - b.getMin().x; + + // Create a perspective camera + PerspectiveCamera camera = new PerspectiveCamera(true); + + // Calculate camera position to fit all objects in view + double maxDimension = Math.max(totalx, Math.max(totaly, totalz)); + double cameraDistance = (maxDimension / Math.tan(Math.toRadians(camera.getFieldOfView() / 2)))*0.8 ; + + TransformNR camoffset = new TransformNR(xOffset, yOffset, 0); + TransformNR camDist = new TransformNR(0, 0, -cameraDistance); + TransformNR rot = new TransformNR(new RotationNR(-150, 45, 0)); + + Affine af = TransformFactory.nrToAffine(camoffset.times(rot.times(camDist))); + camera.getTransforms().add(af); + // Position the camera +// camera.setTranslateX(); +// camera.setTranslateY(); +// camera.setTranslateZ(); +// // Apply rotations to the root group instead of the camera +// root.getTransforms().addAll( +// new Rotate(-5, Rotate.Y_AXIS), +// new Rotate(-45, Rotate.X_AXIS) +// ); + // Create a scene with the group and camera + int i = 1000; + Scene scene = new Scene(root, i, i, true, SceneAntialiasing.BALANCED); + scene.setFill(Color.TRANSPARENT); + scene.setCamera(camera); + + // Set up snapshot parameters + SnapshotParameters params = new SnapshotParameters(); + params.setFill(Color.TRANSPARENT); + params.setCamera(camera); + params.setDepthBuffer(true); + params.setTransform(Transform.scale(1, 1)); + // Set the near and far clip + camera.setNearClip(0.1); // Set the near clip plane + camera.setFarClip(9000.0); // Set the far clip plane + + + // Create the WritableImage first + WritableImage snapshot = new WritableImage(i, i); + + root.snapshot(params, snapshot); + + return snapshot; + } +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/lipsync/RhubarbManager.java b/src/main/java/com/neuronrobotics/bowlerstudio/lipsync/RhubarbManager.java index 1cd1f2430..8f6d5db73 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/lipsync/RhubarbManager.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/lipsync/RhubarbManager.java @@ -41,7 +41,7 @@ public void processRaw(File f, String ttsLocation) throws Exception { + RhubarbVersion + "-" + os + "/rhubarb" + exeExtention); timeCodedVisemes = new ArrayList<>(); if (!exe.exists()) { - System.out.println("Downloading " + exe.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Downloading " + exe.getAbsolutePath()); String zipfileName = "Rhubarb-Lip-Sync-" + RhubarbVersion + "-" + os + ".zip"; String urlStr = "https://github.com/DanielSWolf/rhubarb-lip-sync/releases/download/v" + RhubarbVersion + "/" + zipfileName; @@ -73,7 +73,7 @@ public void processRaw(File f, String ttsLocation) throws Exception { Process process; String command = exe +" --dialogFile "+ttsLocation+" --machineReadable -f json " + f.getAbsolutePath(); - System.out.println(command); + com.neuronrobotics.sdk.common.Log.error(command); process = Runtime.getRuntime().exec(command); int exitCode = process.waitFor(); @@ -83,8 +83,8 @@ public void processRaw(File f, String ttsLocation) throws Exception { String utf8 = StandardCharsets.UTF_8.toString(); IOUtils.copy(is, writer, utf8); String result = writer.toString(); - // System.out.println(status); - // System.out.println(result); + // com.neuronrobotics.sdk.common.Log.error(status); + // com.neuronrobotics.sdk.common.Log.error(result); Type TT_mapStringString = new TypeToken>() { }.getType(); Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); @@ -99,7 +99,7 @@ public void processRaw(File f, String ttsLocation) throws Exception { // double percent = end / duration * 100.0; // AudioStatus val = AudioStatus.get(cue.get("value").toString().charAt(0)); -// System.out.println("End at " + percent + " " + val); +// com.neuronrobotics.sdk.common.Log.error("End at " + percent + " " + val); // HashMap map = new HashMap<>(); // map.put(val, percent); TimeCodedViseme map = new TimeCodedViseme(val, start, end, duration); @@ -112,7 +112,7 @@ public void processRaw(File f, String ttsLocation) throws Exception { public AudioInputStream startProcessing(AudioInputStream ais, String TTSString) { File audio = new File(ScriptingEngine.getWorkspace().getAbsolutePath() + "/tmp-tts.wav"); try { - System.out.println("Begin writing.."); + com.neuronrobotics.sdk.common.Log.error("Begin writing.."); AudioSystem.write(ais, AudioFileFormat.Type.WAVE, audio); ais = AudioSystem.getAudioInputStream(audio); File text = new File(ScriptingEngine.getWorkspace().getAbsolutePath() + "/tmp-tts.txt"); @@ -127,9 +127,9 @@ public AudioInputStream startProcessing(AudioInputStream ais, String TTSString) } // rhubarb! processRaw(audio, text.getAbsolutePath()); - System.out.println("Done writing!"); + com.neuronrobotics.sdk.common.Log.error("Done writing!"); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/lipsync/VoskLipSync.java b/src/main/java/com/neuronrobotics/bowlerstudio/lipsync/VoskLipSync.java index 41638bf93..b8aa7df5f 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/lipsync/VoskLipSync.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/lipsync/VoskLipSync.java @@ -120,7 +120,7 @@ public static void setModelName(String modelName) { FileOutputStream fis = new FileOutputStream(zipfile); byte[] buffer = new byte[1024]; int count = 0; - System.out.println("Downloading Vosk Model " + getModelName()); + com.neuronrobotics.sdk.common.Log.error("Downloading Vosk Model " + getModelName()); while ((count = bis.read(buffer, 0, 1024)) != -1) { fis.write(buffer, 0, count); System.out.print("."); @@ -130,7 +130,7 @@ public static void setModelName(String modelName) { String source = zipfile.getAbsolutePath(); String destination = ScriptingEngine.getWorkspace().getAbsolutePath(); - System.out.println("Unzipping Vosk Model " + getModelName()); + com.neuronrobotics.sdk.common.Log.error("Unzipping Vosk Model " + getModelName()); ZipFile zipFile = new ZipFile(source); zipFile.extractAll(destination); } @@ -370,7 +370,7 @@ public void processRaw(File f, String ttsLocation) throws UnsupportedAudioFileEx BufferedWriter writer = new BufferedWriter(new FileWriter(json.getAbsolutePath())); writer.write(s); writer.close(); - System.out.println("Lip Sync data writen to " + json.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Lip Sync data writen to " + json.getAbsolutePath()); timeCodedVisemesCache.clear(); } catch (Throwable tr) { tr.printStackTrace(); @@ -398,7 +398,7 @@ public AudioInputStream startProcessing(AudioInputStream ais, String TTSString) File audio = new File(ScriptingEngine.getWorkspace().getAbsolutePath() + "/tmp-tts.wav"); try { long start = System.currentTimeMillis(); - System.out.println("Vosk Lip Sync Begin writing.."); + com.neuronrobotics.sdk.common.Log.error("Vosk Lip Sync Begin writing.."); AudioSystem.write(ais, AudioFileFormat.Type.WAVE, audio); ais = AudioSystem.getAudioInputStream(audio); File text = new File(ScriptingEngine.getWorkspace().getAbsolutePath() + "/tmp-tts.txt"); @@ -413,9 +413,9 @@ public AudioInputStream startProcessing(AudioInputStream ais, String TTSString) } // rhubarb! processRaw(audio, text.getAbsolutePath()); - System.out.println("Vosk Lip Sync Done writing! took " + (System.currentTimeMillis() - start)); + com.neuronrobotics.sdk.common.Log.error("Vosk Lip Sync Done writing! took " + (System.currentTimeMillis() - start)); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } @@ -490,14 +490,14 @@ public static String promptFromMicrophone() throws IOException, LineUnavailableE // println "Listening..." } } else { - // System.out.println(recognizer.getPartialResult()); + // com.neuronrobotics.sdk.common.Log.error(recognizer.getPartialResult()); } } } catch (Throwable t) { t.printStackTrace(); } recognizer.close(); - // System.out.println(result); + // com.neuronrobotics.sdk.common.Log.error(result); microphone.close(); return result; } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/opencv/OpenCVManager.java b/src/main/java/com/neuronrobotics/bowlerstudio/opencv/OpenCVManager.java index 61f04cff9..bca3f0426 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/opencv/OpenCVManager.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/opencv/OpenCVManager.java @@ -52,7 +52,7 @@ public boolean connectDeviceImp() { @Override public ArrayList getNamespacesImp() { - // TODO Auto-generated method stub + // Auto-generated method stub return null; } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/physics/CSGPhysicsManager.java b/src/main/java/com/neuronrobotics/bowlerstudio/physics/CSGPhysicsManager.java index 8d40ecc3e..ec3de2d0f 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/physics/CSGPhysicsManager.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/physics/CSGPhysicsManager.java @@ -83,7 +83,7 @@ protected CSG loadCSGToPoints(CSG baseCSG, boolean adjustCenter, Transform pose, //if(polygons.size()>1000) // polygons = getBoundingBox(finalCSG).getPolygons(); for (Polygon p : polygons) { - for (Vertex v : p.vertices) { + for (Vertex v : p.getVertices()) { arg0.add(new Vector3f((float) v.getX(), (float) v.getY(), (float) v.getZ())); } } @@ -106,7 +106,7 @@ public void setup(CollisionShape fallShape, Transform pose, double mass, Physics this.setCore(core); // setup the motion state for the ball - System.out.println("Starting Object at " + TransformFactory.bulletToNr(pose)); + com.neuronrobotics.sdk.common.Log.error("Starting Object at " + TransformFactory.bulletToNr(pose)); DefaultMotionState fallMotionState = new DefaultMotionState(pose); // This we're going to give mass so it responds to gravity Vector3f fallInertia = new Vector3f(0, 0, 0); diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/physics/HingeCSGPhysicsManager.java b/src/main/java/com/neuronrobotics/bowlerstudio/physics/HingeCSGPhysicsManager.java index 8bf7ab2a8..1d0da0382 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/physics/HingeCSGPhysicsManager.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/physics/HingeCSGPhysicsManager.java @@ -43,14 +43,14 @@ public void update(float timeStep) { getCore().remove(this); setConstraint(null); getCore().add(this); - System.out.println( + com.neuronrobotics.sdk.common.Log.error( "ERROR Link Broken, Strength: " + getMuscleStrength() + " applied impluse " + constraint .getAppliedImpulse()); } } else if (constraint != null && flagBroken) { constraint.enableAngularMotor(false, 0, 0); } - //System.out.println("Constraint = "+constraint+" controller= "+getController()+" broken= "+flagBroken); + //com.neuronrobotics.sdk.common.Log.error("Constraint = "+constraint+" controller= "+getController()+" broken= "+flagBroken); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/physics/MobileBasePhysicsManager.java b/src/main/java/com/neuronrobotics/bowlerstudio/physics/MobileBasePhysicsManager.java index 3387b9e18..5d63506db 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/physics/MobileBasePhysicsManager.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/physics/MobileBasePhysicsManager.java @@ -116,7 +116,7 @@ public MobileBasePhysicsManager(MobileBase base, ArrayList baseCad, Maxz = c.getMaxZ(); } } - // System.out.println("Minimum z = "+minz); + // com.neuronrobotics.sdk.common.Log.error("Minimum z = "+minz); Transform start = new Transform(); base.setFiducialToGlobalTransform(new TransformNR()); // TransformNR globe= base.getFiducialToGlobalTransform(); @@ -279,7 +279,7 @@ public void run() { ILinkListener ll = new ILinkListener() { @Override public void onLinkPositionUpdate(AbstractLink source, double engineeringUnitsValue) { - // System.out.println(" + // com.neuronrobotics.sdk.common.Log.error(" // value="+engineeringUnitsValue); hingePhysicsManager.setTarget(Math.toRadians(-engineeringUnitsValue)); diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/physics/MuJoCoPhysicsManager.java b/src/main/java/com/neuronrobotics/bowlerstudio/physics/MuJoCoPhysicsManager.java index 9e24c8a9b..5e711c818 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/physics/MuJoCoPhysicsManager.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/physics/MuJoCoPhysicsManager.java @@ -147,7 +147,7 @@ public void controlStep(MuJoCoModelManager manager) { double target = Math.toRadians(link.getCurrentEngineeringUnits()) * gearRatios.get(link); // double error = target-positions.get(s); // double effort = error * kp; - // System.out.println("Actuator "+s+" position "+positions.get(s)+" effort + // com.neuronrobotics.sdk.common.Log.error("Actuator "+s+" position "+positions.get(s)+" effort // "+effort); setEfforts.put(s, target); } @@ -173,11 +173,11 @@ public void controlStep(MuJoCoModelManager manager) { rotxAcceleration, rotyAcceleration, rotzAcceleration, currentTimeMillis())); } catch (NullPointerException e) { // startup sync problems, ignore - System.out.println(e.getMessage()); + com.neuronrobotics.sdk.common.Log.error(e.getMessage()); } } - // System.out.println("Body "+s+" pose "+); + // com.neuronrobotics.sdk.common.Log.error("Body "+s+" pose "+); } } } @@ -309,14 +309,14 @@ public long stepAndWait() { try { Thread.sleep(diff); } catch (InterruptedException e) { - // TODO Auto-generated catch block + // Auto-generated catch block throw new RuntimeException(e); } } else if (diff == 0) { if (Thread.interrupted()) throw new RuntimeException("Interrupted exception!"); } else { - // System.err.println("MuJoCo Real time broken, expected + // com.neuronrobotics.sdk.common.Log.error("MuJoCo Real time broken, expected // "+getTimestepMilliSeconds()+" took "+time); } if (Thread.interrupted()) @@ -364,7 +364,7 @@ public File getXMLFile() throws IOException, JAXBException { } else { tempFile = new File(workingDir.getAbsolutePath() + "/" + name + ".xml"); } - System.out.println("Writing " + tempFile.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Writing " + tempFile.getAbsolutePath()); Files.write(Paths.get(tempFile.getAbsolutePath()), xml.getBytes()); return tempFile; } @@ -546,7 +546,7 @@ public void loadBase(MobileBase cat, org.mujoco.xml.BodyarchType.Builder link double val = part.getMassKG(mass) * KgtoMujocoMass; geom.withMass(BigDecimal.valueOf(val)); } else { - System.out.println("\nUsing density for "+part.getName()); + com.neuronrobotics.sdk.common.Log.error("\nUsing density for "+part.getName()); } } @@ -614,7 +614,7 @@ public void loadBase(MobileBase cat, org.mujoco.xml.BodyarchType.Builder link double val = csg.getMassKG(linkMass/numPartsWithoutMassLink) * KgtoMujocoMass; geom.withMass(BigDecimal.valueOf(val)); } else { - System.out.println("\nUsing density for "+csg.getName()); + com.neuronrobotics.sdk.common.Log.error("\nUsing density for "+csg.getName()); } } } @@ -778,7 +778,7 @@ public org.mujoco.xml.BodyarchType.Builder loadLink(MobileBase cat, DHParamet } } } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } else { @@ -954,7 +954,7 @@ public void putCSGInAssets(String nameOfCSG, CSG hull, boolean isFree) throws IO Files.write(Paths.get(tempFile.getAbsolutePath()), obj.getBytes()); System.out.print(" " + (System.currentTimeMillis() - start+"\n")); } else { - System.out.println("Loading cache " + tempFile.getName()); + com.neuronrobotics.sdk.common.Log.error("Loading cache " + tempFile.getName()); } if (isFree) { asset.addTexture().withRgb1(toColorString(hull.getColor())).withRgb2(toColorString(hull.getColor())) @@ -994,11 +994,11 @@ public void waitForCad(MobileBaseCadManager cadMan, long start) { try { Thread.sleep(1000); } catch (InterruptedException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } - System.out.println("Waiting for cad to process " + percent); + com.neuronrobotics.sdk.common.Log.error("Waiting for cad to process " + percent); } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/physics/PhysicsCore.java b/src/main/java/com/neuronrobotics/bowlerstudio/physics/PhysicsCore.java index 0e18de322..2306cb471 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/physics/PhysicsCore.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/physics/PhysicsCore.java @@ -170,7 +170,7 @@ public void startPhysicsThread(int ms) { if (took < msTime) { ThreadUtil.wait((int) (msTime - took)); } else { - System.out.println("Real time physics broken: " + took); + com.neuronrobotics.sdk.common.Log.error("Real time physics broken: " + took); } } catch (Exception E) { E.printStackTrace(); @@ -201,7 +201,7 @@ public void step(float timeStep) { getDynamicsWorld().stepSimulation(timeStep, getSimulationSubSteps()); if ((((float) (System.currentTimeMillis() - startTime)) / 1000.0f) > timeStep) { - // System.out.println(" Compute took too long "+timeStep); + // com.neuronrobotics.sdk.common.Log.error(" Compute took too long "+timeStep); } for (IPhysicsManager o : getPhysicsObjects()) { o.update(timeStep); diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/physics/PhysicsEngine.java b/src/main/java/com/neuronrobotics/bowlerstudio/physics/PhysicsEngine.java index d2730271c..ff1f40e85 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/physics/PhysicsEngine.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/physics/PhysicsEngine.java @@ -73,7 +73,7 @@ public static PhysicsCore get() { try { mainEngine = new PhysicsCore(); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/physics/TransformFactory.java b/src/main/java/com/neuronrobotics/bowlerstudio/physics/TransformFactory.java index b406ad530..caa193cbc 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/physics/TransformFactory.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/physics/TransformFactory.java @@ -11,7 +11,7 @@ import javafx.application.Platform; import javafx.scene.transform.Affine; -// TODO: Auto-generated Javadoc +// Auto-generated Javadoc /** * A factory for creating Transform objects. diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/printbed/PrintBedManager.java b/src/main/java/com/neuronrobotics/bowlerstudio/printbed/PrintBedManager.java index 40ce000e9..1d470deb0 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/printbed/PrintBedManager.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/printbed/PrintBedManager.java @@ -55,7 +55,7 @@ public PrintBedManager(File dir, ArrayList parts) { try { this.url=ScriptingEngine.locateGitUrl(dir); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } setHasPrintBed(init(dir, parts)); @@ -65,9 +65,9 @@ public boolean init(File dir, ArrayList parts) { if (url == null) return false; File f = new File(dir.getAbsolutePath() + "/" + file); - System.out.println("Searching for printbed at "+f); + com.neuronrobotics.sdk.common.Log.error("Searching for printbed at "+f); if (f.exists()) { - System.out.println("Print Bed file found! "+f.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Print Bed file found! "+f.getAbsolutePath()); String source; byte[] bytes; try { @@ -79,7 +79,7 @@ public boolean init(File dir, ArrayList parts) { } }else { - System.out.println("Print Bed NOT file found! "+f.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Print Bed NOT file found! "+f.getAbsolutePath()); return false; } if (database == null) { @@ -104,7 +104,7 @@ public boolean init(File dir, ArrayList parts) { if(names.contains(name)) continue; names.add(name); - System.out.println(bit.getName() + " on " + index + " rot " + zrot + " y " + yval); + com.neuronrobotics.sdk.common.Log.error(bit.getName() + " on " + index + " rot " + zrot + " y " + yval); if (database.locations.get(name) == null) { database.locations.put(name, new TransformNR()); } @@ -169,7 +169,7 @@ public ArrayList makePrintBeds() { bed.addExportFormat(s); } if (bed != null) { - //System.out.println("Mesh fixing for "+name); + //com.neuronrobotics.sdk.common.Log.error("Mesh fixing for "+name); //bed=bed.union(bed); bed.setName(name); } @@ -201,7 +201,7 @@ private synchronized void saveLocal() { // ScriptingEngine.commit(url, ScriptingEngine.getBranch(url), file, content, "Save Print Bed Locations", // true); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/printbed/PrintBedObject.java b/src/main/java/com/neuronrobotics/bowlerstudio/printbed/PrintBedObject.java index 7cb0f5abf..939cec0d2 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/printbed/PrintBedObject.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/printbed/PrintBedObject.java @@ -3,11 +3,13 @@ import java.util.Arrays; import java.util.List; -import com.neuronrobotics.bowlerkernel.Bezier3d.manipulation; +import com.neuronrobotics.bowlerkernel.Bezier3d.Manipulation; import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; import eu.mihosoft.vrl.v3d.CSG; import eu.mihosoft.vrl.v3d.Vector3d; +import javafx.event.EventHandler; +import javafx.scene.input.MouseEvent; import javafx.scene.transform.Affine; public class PrintBedObject { @@ -17,7 +19,7 @@ public class PrintBedObject { private double yMin; private CSG part; private String name; - private manipulation manip; + private Manipulation manip; private Affine affine = new Affine(); private TransformNR globalPose; public PrintBedObject(String name, CSG part, double xMax, double xMin, double yMax, double yMin, TransformNR startPose){ @@ -29,11 +31,13 @@ public PrintBedObject(String name, CSG part, double xMax, double xMin, double yM this.yMin = yMin; this.globalPose = startPose; - manip = new manipulation(affine, new Vector3d(1, 1, 0), part, startPose); - manip.addSaveListener(() -> System.out.println("Saving PrintBedObject "+name)); + manip = new Manipulation(affine, new Vector3d(1, 1, 0), startPose); + part.getStorage().set("manipulator",manip.map); + part.setManipulator(affine); + manip.addSaveListener(() -> com.neuronrobotics.sdk.common.Log.error("Saving PrintBedObject "+name)); checkBounds(); } - public void addEventListener(Runnable r) { + public void addEventListener(EventHandler r) { manip.addEventListener(r); } @@ -45,15 +49,15 @@ public List get() { } public double getX() { - return manip.currentPose.getX(); + return manip.getCurrentPose().getX(); } public double getY() { - return manip.currentPose.getY(); + return manip.getCurrentPose().getY(); } public double getZ() { - return manip.currentPose.getZ(); + return manip.getCurrentPose().getZ(); } public void checkBounds() { double minYTest = part.getMinY()-yMin+globalPose.getY(); diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ArduinoLoader.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ArduinoLoader.java index f9be1654c..6f6307dd2 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ArduinoLoader.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ArduinoLoader.java @@ -38,14 +38,14 @@ public Object inlineScriptRun(File code, ArrayList args) throws Exceptio } File ino = findIno(code); if (ino == null) { - //System.out.println("Error: no .ino file found!"); + //com.neuronrobotics.sdk.common.Log.error("Error: no .ino file found!"); return null; } commands.add("upload"); commands.add(ino.getAbsolutePath()); - //System.out.println("Arduino Load: \n"+execString); + //com.neuronrobotics.sdk.common.Log.error("Arduino Load: \n"+execString); Thread ret = DownloadManager.run(null, ino.getParentFile(), System.out, commands); ret.join(); @@ -83,7 +83,7 @@ private File findIno(File start) { @Override public Object inlineScriptRun(String code, ArrayList args) throws Exception { - // TODO Auto-generated method stub + // Auto-generated method stub return null; } @@ -164,7 +164,7 @@ public static String getARDUINOExec() { @Override public ArrayList getFileExtenetion() { - // TODO Auto-generated method stub + // Auto-generated method stub return new ArrayList<>(Arrays.asList( ".ino",".c", ".h", ".cpp", ".hpp")); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/BashLoader.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/BashLoader.java index bd22c24d5..b648b7d44 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/BashLoader.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/BashLoader.java @@ -39,10 +39,10 @@ public Object inlineScriptRun(File code, ArrayList args) throws Exceptio while ((s = stdInput.readLine()) != null || (e = errInput.readLine()) != null) { if (s != null) { back.add(s); - System.out.println(s); + com.neuronrobotics.sdk.common.Log.error(s); } if (e != null) - System.out.println(e); + com.neuronrobotics.sdk.common.Log.error(e); // } process.waitFor(); @@ -82,7 +82,7 @@ public String getDefaultContents() { @Override public boolean getIsTextFile() { - // TODO Auto-generated method stub + // Auto-generated method stub return true; } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/BlenderLoader.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/BlenderLoader.java index 6aae7f81a..746864ed4 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/BlenderLoader.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/BlenderLoader.java @@ -50,28 +50,20 @@ public static void toBlenderFile(CSG stlIn,File blenderfile) throws IOException toBlenderFile(stl, blenderfile); } - public static File getTmpSTL(CSG stlIn) throws IOException { - String name = stlIn.getName(); - if(name.length()==0) - name="CSG_EXPORT"; - File stl = File.createTempFile(name, ".stl"); - stl.deleteOnExit(); - FileUtil.write(Paths.get(stl.getAbsolutePath()), stlIn.toStlString()); - return stl; - } - public static void toBlenderFile(File incoming,File blenderfile) { - System.out.println("Converting to Blender file before loading"); + + public static void toBlenderFile(File stl,File blenderfile) { + com.neuronrobotics.sdk.common.Log.error("Converting to Blender file before loading"); File stlIn; try { - stlIn = File.createTempFile(incoming.getName(), ".stl"); + stlIn = File.createTempFile(stl.getName(), ".stl"); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); return; } stlIn.deleteOnExit(); - scaleStl(incoming,stlIn,0.001); + scaleStl(stl,stlIn,0.001); File dir = stlIn.getAbsoluteFile().getParentFile(); try { @@ -93,7 +85,7 @@ public static void toBlenderFile(File incoming,File blenderfile) { t.join(); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); return; } @@ -101,12 +93,49 @@ public static void toBlenderFile(File incoming,File blenderfile) { public static void scaleStl(File incoming, File outgoing, double scale) { CSG back = Vitamins.get(incoming,true).scale(scale); try { + boolean manifold=CSG.isPreventNonManifoldTriangles(); + CSG.setPreventNonManifoldTriangles(false); FileUtil.write(Paths.get(outgoing.getAbsolutePath()), back.toStlString()); + + CSG.setPreventNonManifoldTriangles(manifold); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } + public static CSG remesh(CSG incoming, double MMVoxel) throws Exception { + File stl = DownloadManager.getTmpSTL(incoming); + remeshSTLFile(stl, MMVoxel); + CSG back = Vitamins.get(stl,true); + return back.syncProperties(incoming).setName(incoming.getName()); + } + public static void remeshSTLFile(File stlout,double MMVoxel) throws Exception { + File blend = File.createTempFile(stlout.getName(), ".blend"); + blend.delete(); + toBlenderFile(stlout, blend); + remeshToSTLFile(blend, stlout, MMVoxel); + } + public static void remeshToSTLFile(File blenderfile,File stlout,double MMVoxel) throws InvalidRemoteException, TransportException, GitAPIException, IOException, InterruptedException { + File exe = getConfigExecutable("blender", null); + File export = ScriptingEngine.fileFromGit( + "https://github.com/CommonWealthRobotics/blender-bowler-cli.git", + "remesh.py"); + ArrayList args = new ArrayList<>(); + + if(stlout.exists()) + stlout.delete(); + args.add(exe.getAbsolutePath()); + + args.add("--background"); + args.add("--python"); + args.add(export.getAbsolutePath()); + args.add("--"); + args.add(blenderfile.getAbsolutePath()); + args.add(""+(MMVoxel/1000.0)); + args.add(stlout.getAbsolutePath()); + legacySystemRun(null, stlout.getAbsoluteFile().getParentFile(), System.out, args); + scaleStl(stlout,stlout,1000.0); + } public static void toSTLFile(File blenderfile,File stlout) throws InvalidRemoteException, TransportException, GitAPIException, IOException, InterruptedException { File exe = getConfigExecutable("blender", null); File export = ScriptingEngine.fileFromGit( @@ -133,7 +162,7 @@ public void getDefaultContents(File source) { String absolutePath = source.getAbsolutePath(); File parent = new File(absolutePath).getParentFile(); if(source.exists()) { - System.out.println("Blender file exists, being overwritten to blank "+absolutePath); + com.neuronrobotics.sdk.common.Log.error("Blender file exists, being overwritten to blank "+absolutePath); source.delete(); } ArrayList args = new ArrayList<>(); @@ -148,10 +177,10 @@ public void getDefaultContents(File source) { try { DownloadManager.legacySystemRun(null, parent, System.out, args); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } @@ -159,7 +188,7 @@ public void getDefaultContents(File source) { @Override public boolean getIsTextFile() { - // TODO Auto-generated method stub + // Auto-generated method stub return false; } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/CaDoodleLoader.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/CaDoodleLoader.java new file mode 100644 index 000000000..ef2208843 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/CaDoodleLoader.java @@ -0,0 +1,73 @@ +package com.neuronrobotics.bowlerstudio.scripting; + +import java.io.File; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import com.neuronrobotics.bowlerstudio.scripting.cadoodle.CaDoodleFile; + +import eu.mihosoft.vrl.v3d.CSG; + +public class CaDoodleLoader implements IScriptingLanguage { + @Override + public Object inlineScriptRun(File code, ArrayList args) throws Exception { + CaDoodleFile loaded = CaDoodleFile.fromFile(code); + return process(loaded); + } + + @Override + public Object inlineScriptRun(String code, ArrayList args) throws Exception { + CaDoodleFile loaded = CaDoodleFile.fromJsonString(code); + return process(loaded); + } + + public static Object process(CaDoodleFile loaded) { + List incoming = loaded.getCurrentState(); + ArrayList back = new ArrayList(); + back.addAll(incoming); + for(CSG c: incoming) { + if(c.isInGroup() || c.isHide()) { + back.remove(c); + } + } + return back; + } + + @Override + public String getShellType() { + return "CaDoodle"; + } + + @Override + public boolean getIsTextFile() { + return true; + } + + /** + * Get the contents of an empty file + * + * @return + */ + public String getDefaultContents() { + return "{\n" + + " \"opperations\": [],\n" + + " \"currentIndex\": 0,\n" + + " \"projectName\": \"A Test Project\"\n" + + "}"; + } + + @Override + public ArrayList getFileExtenetion() { + return new ArrayList<>(Arrays.asList("doodle","cadoodle")); + } +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ClojureHelper.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ClojureHelper.java index 547aa0856..db3142453 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ClojureHelper.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ClojureHelper.java @@ -69,10 +69,10 @@ public Object inlineScriptRun(File code, ArrayList args) { String s = new String(bytes, "UTF-8"); return inlineScriptRun(s, args); } catch (IOException e1) { - // TODO Auto-generated catch block + // Auto-generated catch block e1.printStackTrace(); } - // System.out.println("Clojure returned of type="+ret.getClass()+" value="+ret); + // com.neuronrobotics.sdk.common.Log.error("Clojure returned of type="+ret.getClass()+" value="+ret); return null; } @@ -89,7 +89,7 @@ public String getShellType() { @Override public boolean getIsTextFile() { - // TODO Auto-generated method stub + // Auto-generated method stub return true; } @@ -104,7 +104,7 @@ public String getDefaultContents() { @Override public ArrayList getFileExtenetion() { - // TODO Auto-generated method stub + // Auto-generated method stub return new ArrayList<>(Arrays.asList("clj", "cljs", "cljc")); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/DownloadManager.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/DownloadManager.java index 60e4fc351..7b15ecbf4 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/DownloadManager.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/DownloadManager.java @@ -3,6 +3,8 @@ import org.apache.commons.exec.*; import org.apache.commons.exec.environment.EnvironmentUtils; +import static com.neuronrobotics.bowlerstudio.scripting.DownloadManager.sanitizeString; + import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; @@ -33,8 +35,10 @@ import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -53,30 +57,88 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; +import com.neuronrobotics.bowlerstudio.BowlerKernel; +import com.neuronrobotics.bowlerstudio.assets.FontSizeManager; import com.neuronrobotics.video.OSUtil; +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.FileUtil; +import javafx.scene.Node; +import javafx.scene.control.Alert; //import javafx.scene.control.Alert; import javafx.scene.control.Button; +import javafx.scene.control.ButtonType; //import javafx.scene.control.ButtonType; //import javafx.scene.control.Alert.AlertType; import javafx.scene.image.Image; - +import javafx.stage.Stage; import net.sf.sevenzipjbinding.*; import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream; public class DownloadManager { + private static String STUDIO_INSTALL = "BowlerStudioInstall"; private static String editorsURL = "https://github.com/CommonWealthRobotics/ExternalEditorsBowlerStudio.git"; - private static String bindir = System.getProperty("user.home") + delim()+"bin"+delim()+"BowlerStudioInstall"+delim(); + private static String bindir = System.getProperty("user.home") + delim()+"bin"+delim()+getSTUDIO_INSTALL()+delim(); private static int ev = 0; private static String cmd = ""; + private static HashSet failedURLs = new HashSet(); + private static IDownloadManagerEvents downloadEvents = new IDownloadManagerEvents() { + + @Override + public void startDownload() { + // Auto-generated method stub + + } + + @Override + public void finishDownload() { + // Auto-generated method stub + + } + }; + public static String sanitizeString(String s) { + if(s.contains(" ")) + s=s.replace(' ', '_'); + return s; + } + public static File getTmpSTL(CSG stlIn) throws IOException { + String name = stlIn.getName(); + if(name.length()==0) + name="CSG_EXPORT"; + File stl = File.createTempFile(sanitizeString(name), ".stl"); + stl.deleteOnExit(); + boolean manifold=CSG.isPreventNonManifoldTriangles(); + CSG.setPreventNonManifoldTriangles(false); + FileUtil.write(Paths.get(stl.getAbsolutePath()), stlIn.toStlString()); + CSG.setPreventNonManifoldTriangles(manifold); + return stl; + } private static IApprovalForDownload approval = new IApprovalForDownload() { @Override public boolean get(String name, String url) { - System.out.println("Command line mode, assuming yes to downloading \n" + name + " \nfrom \n" + url); + com.neuronrobotics.sdk.common.Log.error("Command line mode, assuming yes to downloading \n" + name + " \nfrom \n" + url); return true; } + + @Override + public void onInstallFail(String url) { + com.neuronrobotics.sdk.common.Log.error("Plugin needs to be installed from "+url); + } + public void notifyOfFailure(String name) { + com.neuronrobotics.sdk.common.Log.error("Plugin failed "+name); + } + }; + private static GitLogProgressMonitor psudoSplash = new GitLogProgressMonitor() { + + @Override + public void onUpdate(String update, Exception e) { + // Auto-generated method stub + + } + }; + private static String jvmURL; public static Thread run(IExternalEditor editor, File dir, PrintStream out, List finalCommand) { return run(new HashMap(), editor, dir, out, finalCommand); @@ -119,7 +181,7 @@ public static void legacySystemRun(Map envincoming, File dir, Pr if (envincoming != null) { envir.putAll(envincoming); for (String s : envincoming.keySet()) { - System.out.println("Environment var set: " + s + " to " + envir.get(s)); + com.neuronrobotics.sdk.common.Log.error("Environment var set: " + s + " to " + envir.get(s)); } } // setting the directory @@ -151,7 +213,7 @@ public static void legacySystemRun(Map envincoming, File dir, Pr int ev = process.exitValue(); // out.println("Running "+commands); if (ev != 0) { - System.out.println("ERROR PROCESS Process exited with " + ev); + com.neuronrobotics.sdk.common.Log.error("ERROR PROCESS Process exited with " + ev); } while (process.isAlive()) { Thread.sleep(100); @@ -218,7 +280,7 @@ private static void startOutputReader(final InputStream is, final String type, P } }).start(); } - + @SuppressWarnings("unchecked") public static Map getEnvironment(String exeType) { String key = discoverKey(); @@ -242,7 +304,7 @@ public static Map getEnvironment(String exeType) { Map environment; Object o = vm.get("environment"); if (o != null) { - System.out.println("Environment found for " + exeType + " on " + key); + com.neuronrobotics.sdk.common.Log.error("Environment found for " + exeType + " on " + key); return (Map) o; } @@ -257,11 +319,28 @@ public static Map getEnvironment(String exeType) { } public static File getRunExecutable(String exeType, IExternalEditor editor) { - return getExecutable(exeType, editor, "executable"); + String executable = "executable"; + retryLoop(exeType, editor, executable); + return getExecutable(exeType, editor, executable); } public static File getConfigExecutable(String exeType, IExternalEditor editor) { - return getExecutable(exeType, editor, "configExecutable"); + String executable = "configExecutable"; + retryLoop(exeType, editor, executable); + return getExecutable(exeType, editor, executable); + } + private static void retryLoop(String exeType, IExternalEditor editor, String executable) { + for(int i=0;i<3;i++) { + if(getExecutable(exeType, editor, executable).exists()) { + return; + } + new RuntimeException("Download or extraction failed, retrying").printStackTrace(); + } + if(!failedURLs.contains(jvmURL)) { + failedURLs.add(jvmURL); + approval.notifyOfFailure(exeType); + approval.onInstallFail(jvmURL); + } } private static File getExecutable(String exeType, IExternalEditor editor, String executable) { @@ -280,13 +359,17 @@ private static File getExecutable(String exeType, IExternalEditor editor, String Map vm = (Map) database.get(key); if (vm != null) { String targetdir = exeType; - System.out.println("Configuration found for " + exeType + " on " + key); + com.neuronrobotics.sdk.common.Log.error("Configuration found for " + exeType + " on " + key); String baseURL = vm.get("url").toString(); String type = vm.get("type").toString(); String name = vm.get("name").toString(); + String ospath =null; + try { + ospath=vm.get("ospath").toString(); + }catch(Throwable t) {} String exeInZip = vm.get(executable).toString(); String configexe = vm.get("configExecutable").toString(); - String jvmURL = baseURL + name + "." + type; + jvmURL = baseURL + name + "." + type; Map environment; Object o = vm.get("environment"); if (o != null) { @@ -294,10 +377,15 @@ private static File getExecutable(String exeType, IExternalEditor editor, String } else environment = new HashMap<>(); File dest = new File(bindir + targetdir); - String cmd = bindir + targetdir + "/" + exeInZip; + String cmd = bindir + targetdir + delim() + exeInZip; + if(ospath!=null) { + String string = ospath+delim()+exeInZip; + if(new File(string).exists()) + cmd=string; + } if (!new File(cmd).exists()) { if(exeType.toLowerCase().contentEquals("freecad")) { - FreecadLoader.update(vm); + //FreecadLoader.update(vm); baseURL = vm.get("url").toString(); name = vm.get("name").toString(); exeInZip = vm.get(executable).toString(); @@ -316,7 +404,7 @@ private static File getExecutable(String exeType, IExternalEditor editor, String File jvmArchive = download("", jvmURL, 800000000, bindir, name + "." + type, exeType); if (dest.exists()) { - System.out.println("Erasing stale dir " + dest.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Erasing stale dir " + dest.getAbsolutePath()); deleteDirectory(dest); } if (type.toLowerCase().contains("zip")) { @@ -354,49 +442,49 @@ private static File getExecutable(String exeType, IExternalEditor editor, String Object configurations = database.get("Meta-Configuration"); if (configurations != null) { List configs = (List) configurations; - System.out.println("Got Configurations " + configs.size()); + com.neuronrobotics.sdk.common.Log.error("Got Configurations " + configs.size()); ev = -1; IExternalEditor errorcheckerEditor = new IExternalEditor() { @Override public void onProcessExit(int e) { ev = e; - // TODO Auto-generated method stub + // Auto-generated method stub } @Override public String nameOfEditor() { - // TODO Auto-generated method stub + // Auto-generated method stub return null; } @Override public void launch(File file, Button advanced) { - // TODO Auto-generated method stub + // Auto-generated method stub } @Override public Class getSupportedLangauge() { - // TODO Auto-generated method stub + // Auto-generated method stub return null; } @Override public URL getInstallURL() throws MalformedURLException { - // TODO Auto-generated method stub + // Auto-generated method stub return null; } @Override public Image getImage() { - // TODO Auto-generated method stub + // Auto-generated method stub return null; } }; for (int i = 0; i < configs.size(); i++) { - System.out.println("Running " + exeType + " Configuration " + (i + 1) + " of " + com.neuronrobotics.sdk.common.Log.error("Running " + exeType + " Configuration " + (i + 1) + " of " + configs.size()); ArrayList toRun = new ArrayList<>(); toRun.add(bindir + targetdir + "/" + configexe); @@ -406,7 +494,7 @@ public Image getImage() { } // = +" "+configs.get(i); - // System.out.println(toRun); + // com.neuronrobotics.sdk.common.Log.error(toRun); Thread thread = run(errorcheckerEditor, new File(bindir), System.out, toRun); thread.join(); @@ -419,7 +507,7 @@ public Image getImage() { } } else { - System.out.println("Not extraction, Application exists " + cmd); + com.neuronrobotics.sdk.common.Log.error("Not extraction, Application exists " + cmd); } return new File(cmd); @@ -427,7 +515,7 @@ public Image getImage() { } } } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } @@ -438,7 +526,7 @@ private static void saveFile(File file, String json) { try { FileUtils.writeStringToFile(file, json, Charset.forName("UTF-8")); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } @@ -457,7 +545,7 @@ private static void runInstaller(List installerList) { try { tcopy.join(); } catch (InterruptedException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } }else { @@ -465,7 +553,7 @@ private static void runInstaller(List installerList) { try { tcopy.join(); } catch (InterruptedException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } @@ -490,7 +578,7 @@ private static void standaloneEXE(String type, String name, String targetdir, St try { Files.move(Paths.get(bindir + name + "." + type), Paths.get(cmd), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } new File(cmd).setExecutable(true); @@ -505,7 +593,7 @@ private static void dmgExtract(File jvmArchive, String string, String appDir) { Set before = Stream.of(listFiles).filter(file -> file.isDirectory()).map(File::getName) .collect(Collectors.toSet()); Thread t = run(null, new File("."), System.out, - Arrays.asList("hdiutil", "attach", jvmArchive.getAbsolutePath())); + Arrays.asList("hdiutil", "attach","-verbose", jvmArchive.getAbsolutePath())); try { t.join(); Thread.sleep(2000);// wait for mount to settle @@ -515,7 +603,7 @@ private static void dmgExtract(File jvmArchive, String string, String appDir) { after.removeAll(before); Object[] array = after.toArray(); String newMount = (String) array[0]; - System.out.println("Extracted " + jvmArchive.getAbsolutePath() + " is mounted at " + newMount); + com.neuronrobotics.sdk.common.Log.error("Extracted " + jvmArchive.getAbsolutePath() + " is mounted at " + newMount); // asr restore --source "$MOUNT_POINT" --target "$DEST_PATH" --erase --noprompt if (!location.exists()) { location.mkdirs(); @@ -528,12 +616,12 @@ private static void dmgExtract(File jvmArchive, String string, String appDir) { Arrays.asList("hdiutil", "detach", "/Volumes/" + newMount)); tdetach.join(); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); return; } // wait for the mount to finish - System.out.println("Extracted " + jvmArchive.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Extracted " + jvmArchive.getAbsolutePath()); } @@ -548,7 +636,7 @@ public static boolean isExecutable(ZipArchiveEntry entry) { private static void extract7zSystemCall(String archivePath, String outputPath) { File outputDir = new File(outputPath); if (outputDir.exists()) { - System.err.println("Deleting partial extraction, using system 7z"); + com.neuronrobotics.sdk.common.Log.error("Deleting partial extraction, using system 7z"); deleteDirectory(outputDir); } outputDir.mkdirs(); @@ -564,10 +652,10 @@ private static void extract7zSystemCall(String archivePath, String outputPath) { try { legacySystemRun(null, outputDir, System.out, args); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } @@ -576,8 +664,8 @@ public static void extract7zArchive(String archivePath, String outputPath) { try (RandomAccessFile randomAccessFile = new RandomAccessFile(archivePath, "r"); IInArchive inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile))) { - System.out.println("Archive size: " + randomAccessFile.length() + " bytes"); - System.out.println("Items in archive: " + inArchive.getNumberOfItems()); + com.neuronrobotics.sdk.common.Log.error("Archive size: " + randomAccessFile.length() + " bytes"); + com.neuronrobotics.sdk.common.Log.error("Items in archive: " + inArchive.getNumberOfItems()); for (int i = 0; i < inArchive.getNumberOfItems(); i++) { Boolean isFolder = (Boolean) inArchive.getProperty(i, PropID.IS_FOLDER); @@ -586,10 +674,10 @@ public static void extract7zArchive(String archivePath, String outputPath) { } } - System.out.println("Extraction completed successfully."); + com.neuronrobotics.sdk.common.Log.error("Extraction completed successfully."); } catch (Exception e) { - System.err.println("Error extracting archive: " + e.getMessage()); + com.neuronrobotics.sdk.common.Log.error("Error extracting archive: " + e.getMessage()); e.printStackTrace(); } } @@ -606,12 +694,12 @@ private static void extractItem(IInArchive inArchive, int index, String outputPa } ExtractOperationResult result; - + downloadEvents.startDownload(); try (FileOutputStream fos = new FileOutputStream(outputFile)) { result = inArchive.extractSlow(index, new ISequentialOutStream() { public int write(byte[] data) throws SevenZipException { try { - System.out.println("Inflate 7z .. " + outputFile.getAbsolutePath()); + psudoSplash.onUpdate("Inflate 7z .. " + outputFile.getName(),null); fos.write(data); } catch (IOException e) { throw new SevenZipException("Error writing to file: " + e.getMessage()); @@ -620,11 +708,11 @@ public int write(byte[] data) throws SevenZipException { } }); } - + downloadEvents.finishDownload(); if (result == ExtractOperationResult.OK) { - System.out.println("Extracted: " + path); + com.neuronrobotics.sdk.common.Log.error("Extracted: " + path); } else { - System.err.println("Error extracting " + path + ": " + result); + com.neuronrobotics.sdk.common.Log.error("Error extracting " + path + ": " + result); } } @@ -643,17 +731,17 @@ public int write(byte[] data) throws SevenZipException { * (entry.isDirectory()) { continue; } File outputFile = new File(outputDir, * entry.getName()); File parent = outputFile.getParentFile(); if * (!parent.exists()) { parent.mkdirs(); } - * System.out.println("Inflating 7z "+outputFile.getAbsolutePath()); try + * com.neuronrobotics.sdk.common.Log.error("Inflating 7z "+outputFile.getAbsolutePath()); try * (FileOutputStream out = new FileOutputStream(outputFile)) { byte[] content = * new byte[(int) entry.getSize()]; sevenZFile.read(content, 0, content.length); * out.write(content); } } - * System.out.println("Extraction completed successfully."); } catch + * com.neuronrobotics.sdk.common.Log.error("Extraction completed successfully."); } catch * (IOException e) { e.printStackTrace(System.out); } } * * } */ public static void unzip(File path, String dir) throws Exception { - System.out.println("Unzipping " + path.getName() + " into " + dir); + com.neuronrobotics.sdk.common.Log.error("Unzipping " + path.getName() + " into " + dir); String fileBaseName = FilenameUtils.getBaseName(path.getName().toString()); Path destFolderPath = new File(dir).toPath(); @@ -674,7 +762,7 @@ public static void unzip(File path, String dir) throws Exception { String text = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)) .lines().collect(Collectors.joining("\n")); Path target = Paths.get(".", text); - System.out.println("Creating symlink " + entryPath + " with " + target); + com.neuronrobotics.sdk.common.Log.error("Creating symlink " + entryPath + " with " + target); Files.createSymbolicLink(entryPath, target); continue; @@ -684,7 +772,7 @@ public static void unzip(File path, String dir) throws Exception { } try (OutputStream out = new FileOutputStream(entryPath.toFile())) { IOUtils.copy(in, out); - System.out.println("Inflating " + entryPath); + com.neuronrobotics.sdk.common.Log.error("Inflating " + entryPath); } if (isExecutable(entry)) { @@ -717,12 +805,13 @@ public static void extractTarXz(String inputFile, String outputDir) throws IOExc Files.createDirectories(outDir); } - try (FileInputStream fis = new FileInputStream(inputFile); - XZCompressorInputStream xzIn = new XZCompressorInputStream(fis); - TarArchiveInputStream tarIn = new TarArchiveInputStream(xzIn)) { - + try { + FileInputStream fis = new FileInputStream(inputFile); + XZCompressorInputStream xzIn = new XZCompressorInputStream(fis); + TarArchiveInputStream tarIn = new TarArchiveInputStream(xzIn); TarArchiveEntry entry; - while ((entry = tarIn.getNextTarEntry()) != null) { + downloadEvents.startDownload(); + while ((entry = tarIn.getNextEntry()) != null) { Path outPath = outDir.resolve(entry.getName()); if (entry.isSymbolicLink()) { @@ -730,13 +819,13 @@ public static void extractTarXz(String inputFile, String outputDir) throws IOExc try { Files.createSymbolicLink(outPath, target); } catch (IOException | UnsupportedOperationException e) { - System.err.println("Failed to create symlink " + outPath + ". Copying target instead."); + com.neuronrobotics.sdk.common.Log.error("Failed to create symlink " + outPath + ". Copying target instead."); // Fallback: copy the target file instead Path resolvedTarget = outPath.getParent().resolve(target).normalize(); if (Files.exists(resolvedTarget)) { Files.copy(resolvedTarget, outPath); } else { - System.err.println("Symlink target does not exist: " + resolvedTarget); + com.neuronrobotics.sdk.common.Log.error("Symlink target does not exist: " + resolvedTarget); } } } else if (entry.isDirectory()) { @@ -746,7 +835,7 @@ public static void extractTarXz(String inputFile, String outputDir) throws IOExc try (OutputStream out = Files.newOutputStream(outPath)) { byte[] buffer = new byte[1024]; int len; - System.out.println("Inflate Tar XZ " + outPath.toAbsolutePath()); + psudoSplash.onUpdate("Inflate Tar XZ " + outPath.getFileName(),null); while ((len = tarIn.read(buffer)) != -1) { out.write(buffer, 0, len); } @@ -760,11 +849,17 @@ public static void extractTarXz(String inputFile, String outputDir) throws IOExc } } } + }catch(Throwable ex) { + downloadEvents.finishDownload(); + ex.printStackTrace(); + new File(inputFile).delete(); + throw ex; } + downloadEvents.finishDownload(); } public static void untar(File tarFile, String dir) throws Exception { - System.out.println("Untaring " + tarFile.getName() + " into " + dir); + com.neuronrobotics.sdk.common.Log.error("Untaring " + tarFile.getName() + " into " + dir); File dest = new File(dir); dest.mkdir(); @@ -780,7 +875,7 @@ public static void untar(File tarFile, String dir) throws Exception { // tarIn is a TarArchiveInputStream while (tarEntry != null) {// create a file with the same name as the tarEntry File destPath = new File(dest.toString() + System.getProperty("file.separator") + tarEntry.getName()); - System.out.println("Inflating: " + destPath.getCanonicalPath()); + com.neuronrobotics.sdk.common.Log.error("Inflating: " + destPath.getCanonicalPath()); if (tarEntry.isDirectory()) { destPath.mkdirs(); } else { @@ -853,15 +948,28 @@ public static String discoverKey() { } return key; } - - public static File download(String version, String downloadJsonURL, long sizeOfJson, String bindir, String filename, + /** + * + * @param version A string indicating version, this will be the folder name + * @param URL The direct URL of the download + * @param sizeOfFile The number of bytes in the file + * @param directoryInWhichFileIsStored The root directory into which this will all be downloaded + * @param filename The resulting filename + * @param downloadName User level name for asking about the download + * @return + * @throws MalformedURLException + * @throws IOException + * @throws FileNotFoundException + * @throws InterruptedException + */ + public static File download(String version, String URL, long sizeOfFile, String directoryInWhichFileIsStored, String filename, String downloadName) throws MalformedURLException, IOException, FileNotFoundException, InterruptedException { - URL url = new URL(downloadJsonURL); + URL url = new URL(URL); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); - ProcessInputStream pis = new ProcessInputStream(is, (int) sizeOfJson); + ProcessInputStream pis = new ProcessInputStream(is, (int) sizeOfFile); pis.addListener(new Listener() { long timeSinceePrint = System.currentTimeMillis(); @@ -869,7 +977,7 @@ public static File download(String version, String downloadJsonURL, long sizeOfJ public void process(double percent) { if (System.currentTimeMillis() - timeSinceePrint > 1000) { timeSinceePrint = System.currentTimeMillis(); - System.out.println("Download "+filename+" percent " + (int) (percent * 100)); + psudoSplash.onUpdate((int) (percent * 100)+" % "+filename ,null); } // if(progress!=null) // Platform.runLater(() -> { @@ -882,30 +990,48 @@ public void process(double percent) { if (!folder.exists() || !exe.exists()) { - if (approval.get(downloadName, downloadJsonURL)) { - System.out.println("Start Downloading " + filename); + if (approval.get(downloadName, URL)) { + com.neuronrobotics.sdk.common.Log.error("Start Downloading " + filename); + com.neuronrobotics.sdk.common.Log.error("From "+URL); } else { pis.close(); throw new RuntimeException("No Application insalled"); } - - folder.mkdirs(); - exe.createNewFile(); - byte dataBuffer[] = new byte[1024]; - int bytesRead; + downloadEvents.startDownload(); + rawFileDownload(pis, folder, exe); + com.neuronrobotics.sdk.common.Log.error("Finished downloading " + filename); + psudoSplash.onUpdate((int) (1 * 100)+" % " +filename , null); + downloadEvents.finishDownload(); + } else { + com.neuronrobotics.sdk.common.Log.error("Not downloading, it existst " + filename); + } + return exe; + } + private static void rawFileDownload(ProcessInputStream pis, File folder, File output) + throws IOException, FileNotFoundException { + folder.mkdirs(); + output.createNewFile(); + byte dataBuffer[] = new byte[1024 * 1000]; + int bytesRead; + File exe = File.createTempFile("tmp", output.getName()); + try { FileOutputStream fileOutputStream = new FileOutputStream(exe.getAbsoluteFile()); - while ((bytesRead = pis.read(dataBuffer, 0, 1024)) != -1) { + + while ((bytesRead = pis.read(dataBuffer, 0, dataBuffer.length)) != -1) { fileOutputStream.write(dataBuffer, 0, bytesRead); } fileOutputStream.close(); pis.close(); - System.out.println("Finished downloading " + filename); - System.out.println("Download percent " + (int) (1 * 100)); - } else { - System.out.println("Not downloading, it existst " + filename); + FileOutputStream out = new FileOutputStream(output.getAbsoluteFile()); + Files.copy(exe.toPath(), out); + out.flush(); + out.close(); + } catch (Exception ex) { + ex.printStackTrace(); + output.delete(); } - return exe; + exe.delete(); } /** @@ -931,17 +1057,17 @@ public static String delim() { // try { // PasswordManager.login(); // } catch (IOException e) { -// // TODO Auto-generated catch block +// // Auto-generated catch block // e.printStackTrace(); // } // File f = getRunExecutable("eclipse",null); // String ws = EclipseExternalEditor.getEclipseWorkspace(); // if(f.exists()) { -// System.out.println("Executable retrived:\n"+f.getAbsolutePath()); +// com.neuronrobotics.sdk.common.Log.error("Executable retrived:\n"+f.getAbsolutePath()); // run(getEnvironment("eclipse"),null,f.getParentFile(), System.err,Arrays.asList(f.getAbsolutePath(),"-data", ws)); // } // else -// System.out.println("Failed to load file!\n"+f.getAbsolutePath()); +// com.neuronrobotics.sdk.common.Log.error("Failed to load file!\n"+f.getAbsolutePath()); // } public static IApprovalForDownload getApproval() { @@ -951,5 +1077,21 @@ public static IApprovalForDownload getApproval() { public static void setApproval(IApprovalForDownload approval) { DownloadManager.approval = approval; } + public static void addLogListener(GitLogProgressMonitor psudoSplash) { + DownloadManager.psudoSplash = psudoSplash; + } + public static IDownloadManagerEvents getDownloadEvents() { + return downloadEvents; + } + public static void setDownloadEvents(IDownloadManagerEvents de) { + if(downloadEvents!=null) + downloadEvents = de; + } + public static String getSTUDIO_INSTALL() { + return STUDIO_INSTALL; + } + public static void setSTUDIO_INSTALL(String sTUDIO_INSTALL) { + STUDIO_INSTALL = sTUDIO_INSTALL; + } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/FXMLBowlerLoader.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/FXMLBowlerLoader.java index d82b5d74b..c802f1d7e 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/FXMLBowlerLoader.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/FXMLBowlerLoader.java @@ -24,12 +24,12 @@ public Object inlineScriptRun(String code, ArrayList args) throws Except @Override public String getShellType() { - // TODO Auto-generated method stub + // Auto-generated method stub return "fxml"; } @Override public boolean getIsTextFile() { - // TODO Auto-generated method stub + // Auto-generated method stub return true; } /** @@ -42,7 +42,7 @@ public String getDefaultContents() { } @Override public ArrayList getFileExtenetion() { - // TODO Auto-generated method stub + // Auto-generated method stub return new ArrayList<>(Arrays.asList("fxml","FXML","FxML")); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/FreecadLoader.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/FreecadLoader.java index 04634b107..e4ea89c76 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/FreecadLoader.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/FreecadLoader.java @@ -105,7 +105,7 @@ public static void addCSGToFreeCAD(File freecadModel,CSG incoming) throws IOExce addCSGToFreeCAD(freecadModel,incoming,incoming.getSlicePlanes()); } public static void addCSGToFreeCAD(File freecadModel,CSG toSlice, List slicePlanes) throws IOException { - File tmp = BlenderLoader.getTmpSTL(toSlice); + File tmp =getTmpSTL(toSlice); String name = toSlice.getName(); if(name.length()==0) { name="CSG_TO_FREECAD"; @@ -125,33 +125,7 @@ public static void addCSGToFreeCAD(File freecadModel,CSG toSlice, Listargs = Arrays.asList( - inkscape.getAbsolutePath(), - "--actions", - "\"select-all:all;path-simplify:threshold=" + threshhold+ ";;export-overwrite;export-do;quit-inkscape\"", - incoming.getAbsolutePath() - ); - legacySystemRun(null, inkscape.getAbsoluteFile().getParentFile(), System.out, args); - args = Arrays.asList( - inkscape.getAbsolutePath(), - "--export-plain-svg", - "--export-type=svg", - "--vacuum-defs", - "--export-filename="+svg.getAbsolutePath(), - incoming.getAbsolutePath() - ); - legacySystemRun(null, inkscape.getAbsoluteFile().getParentFile(), System.out, args); - return svg; - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return incoming; - } + public static void addSVGToFreeCAD(File freecadModel,File SVG, Transform pose, String name, String bodyName) { TransformNR nr=TransformFactory.csgToNR(pose); RotationNR r=nr.getRotation(); @@ -289,7 +263,7 @@ private static String readAll(Reader rd) throws IOException { return sb.toString(); } public static void update(Map vm) throws MalformedURLException, IOException { - String url= "https://api.github.com/repos/FreeCAD/FreeCAD-Bundle/releases/tags/weekly-builds"; + String url= "https://api.github.com/repos/FreeCAD/FreeCAD-Bundle/releases/tags/1.0rc2"; InputStream is = new URL(url).openStream(); String type = vm.get("type").toString(); @@ -331,7 +305,7 @@ public static void update(Map vm) throws MalformedURLException, continue; } String name = assetName.replace("."+type, ""); - System.out.println("Updating Freecad assets to "+name); + com.neuronrobotics.sdk.common.Log.error("Updating Freecad assets to "+name); vm.put("name",name); if(isMac()) continue; diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/GitTimeoutThread.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/GitTimeoutThread.java deleted file mode 100644 index 17d41fb17..000000000 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/GitTimeoutThread.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.neuronrobotics.bowlerstudio.scripting; - -import org.eclipse.jgit.api.Git; - -import com.neuronrobotics.bowlerstudio.IssueReportingExceptionHandler; - -public class GitTimeoutThread extends Thread { - Git git; - String ref; - private RuntimeException ex; - long startTime=0; - public GitTimeoutThread(Git g) { - git=g; - ref = git.getRepository().getConfig().getString("remote", "origin", "url"); - setException(new RuntimeException( - "Git opened here, timeout on close!!\nWhen Done with the git object, Call:\n ScriptingEngine.closeGit(git);\n" - + ref + "\n")); - } - public void run() { - resetTimer(); - try { - while((startTime+(1000*120))>System.currentTimeMillis()) - Thread.sleep(1000); - git.close(); - ScriptingEngine.gitOpenTimeout.remove(git); - new IssueReportingExceptionHandler().uncaughtException(Thread.currentThread(), getException()); - } catch (InterruptedException e) { - // exited clean - } - } - public void resetTimer() { - startTime=System.currentTimeMillis(); - } - public RuntimeException getException() { - return ex; - } - private void setException(RuntimeException ex) { - this.ex = ex; - } -} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/GroovyHelper.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/GroovyHelper.java index 18fa67f60..c5e13ed62 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/GroovyHelper.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/GroovyHelper.java @@ -39,14 +39,14 @@ private Object inline(Object code, ArrayList args) throws Exception { // } catch (Throwable e) { // //throw e; // } -//// System.err.println("Device " + bad.getScriptingName() + " is " +//// com.neuronrobotics.sdk.common.Log.error("Device " + bad.getScriptingName() + " is " //// + bad); // } binding.setVariable("args", args); GroovyShell shell = new GroovyShell(GroovyHelper.class .getClassLoader(), binding, cc); - //System.out.println(code + "\n\nStart\n\n"); + //com.neuronrobotics.sdk.common.Log.error(code + "\n\nStart\n\n"); Script script; if (String.class.isInstance(code)) { script = shell.parse((String) code); @@ -87,24 +87,24 @@ public Object inlineScriptRun(String code, ArrayList args) throws Except @Override public boolean getIsTextFile() { - // TODO Auto-generated method stub + // Auto-generated method stub return true; } @Override public ArrayList getFileExtenetion() { - // TODO Auto-generated method stub + // Auto-generated method stub return new ArrayList<>(Arrays.asList( "groovy","java")); } @Override public IDebugScriptRunner compileDebug(File f) { - // TODO Auto-generated method stub + // Auto-generated method stub return new IDebugScriptRunner() { @Override public String[] step() { - // TODO Auto-generated method stub + // Auto-generated method stub return new String[]{"fileame.groovy", "345"}; } }; diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IApprovalForDownload.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IApprovalForDownload.java index dac19f0af..9a9bd120f 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IApprovalForDownload.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IApprovalForDownload.java @@ -2,4 +2,6 @@ public interface IApprovalForDownload { boolean get(String name, String url); + void onInstallFail(String url); + void notifyOfFailure(String name); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IDownloadManagerEvents.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IDownloadManagerEvents.java new file mode 100644 index 000000000..eef4d26c8 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IDownloadManagerEvents.java @@ -0,0 +1,6 @@ +package com.neuronrobotics.bowlerstudio.scripting; + +public interface IDownloadManagerEvents { + public void startDownload(); + public void finishDownload(); +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IGitAccessor.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IGitAccessor.java new file mode 100644 index 000000000..12af69b58 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IGitAccessor.java @@ -0,0 +1,7 @@ +package com.neuronrobotics.bowlerstudio.scripting; + +import org.eclipse.jgit.api.Git; + +public interface IGitAccessor { + public void run(Git git) throws Exception; +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IScriptingLanguage.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IScriptingLanguage.java index 7a2797ace..a6101ef21 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IScriptingLanguage.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/IScriptingLanguage.java @@ -104,7 +104,7 @@ default void getDefaultContents(File source) { * @return */ default String getDefaultContents() { - // TODO Auto-generated method stub + // Auto-generated method stub throw new RuntimeException("This shell " + getShellType() + " has binary files "); } @@ -118,7 +118,7 @@ default void getDefaultContents(String gitURL, String fileSlug) { try { getDefaultContents(ScriptingEngine.fileFromGit(gitURL, fileSlug)); } catch (GitAPIException | IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/JsonRunner.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/JsonRunner.java index 7bccb9573..0c2f29972 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/JsonRunner.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/JsonRunner.java @@ -61,7 +61,7 @@ public String getDefaultContents() { @Override public ArrayList getFileExtenetion() { - // TODO Auto-generated method stub + // Auto-generated method stub return new ArrayList<>(Arrays.asList("json")); } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/JythonHelper.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/JythonHelper.java index 03d03a66b..ec46ca876 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/JythonHelper.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/JythonHelper.java @@ -42,10 +42,10 @@ public Object inlineScriptRun(String code, ArrayList args) { // Class.forName(bad.getClass().getName()) // .cast(bad)); // } catch (ClassNotFoundException e) { -// // TODO Auto-generated catch block +// // Auto-generated catch block // e.printStackTrace(); // } -// System.err.println("Device " + bad.getScriptingName() + " is " +// com.neuronrobotics.sdk.common.Log.error("Device " + bad.getScriptingName() + " is " // + bad); // } interp.set("args", args); @@ -82,7 +82,7 @@ public Object inlineScriptRun(File code, ArrayList args) { String s = new String(bytes, "UTF-8"); return inlineScriptRun(s, args); } catch (IOException e1) { - // TODO Auto-generated catch block + // Auto-generated catch block e1.printStackTrace(); } return null; @@ -103,13 +103,13 @@ public String getDefaultContents() { } @Override public boolean getIsTextFile() { - // TODO Auto-generated method stub + // Auto-generated method stub return true; } @Override public ArrayList getFileExtenetion() { - // TODO Auto-generated method stub + // Auto-generated method stub return new ArrayList<>(Arrays.asList("py", "jy")); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ObjLoader.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ObjLoader.java new file mode 100644 index 000000000..3bab3dc59 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ObjLoader.java @@ -0,0 +1,47 @@ +package com.neuronrobotics.bowlerstudio.scripting; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; + +import com.neuronrobotics.bowlerstudio.vitamins.Vitamins; + +import eu.mihosoft.vrl.v3d.CSG; + +public class ObjLoader implements IScriptingLanguage { + + @Override + public Object inlineScriptRun(File code, ArrayList args) throws Exception { + CSG sllLoaded = Vitamins.get(code); + return sllLoaded; + } + + @Override + public Object inlineScriptRun(String code, ArrayList args) throws Exception { + throw new RuntimeException("This engine only supports files"); + } + + @Override + public String getShellType() { + return "obj"; + } + @Override + public boolean getIsTextFile() { + // Auto-generated method stub + return false; + } + /** + * Get the contents of an empty file + * + * @return + */ + public String getDefaultContents() { + return null; + } + @Override + public ArrayList getFileExtenetion() { + // Auto-generated method stub + return new ArrayList<>(Arrays.asList("obj","OBJ","Obj")); + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/OpenSCADLoader.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/OpenSCADLoader.java new file mode 100644 index 000000000..904698372 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/OpenSCADLoader.java @@ -0,0 +1,102 @@ +package com.neuronrobotics.bowlerstudio.scripting; +import static com.neuronrobotics.bowlerstudio.scripting.DownloadManager.*; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; + +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.api.errors.InvalidRemoteException; +import org.eclipse.jgit.api.errors.TransportException; + +import com.neuronrobotics.bowlerstudio.vitamins.Vitamins; + +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.FileUtil; +import eu.mihosoft.vrl.v3d.STL; +import javafx.scene.paint.Color; + +public class OpenSCADLoader implements IScriptingLanguage { + + @Override + public Object inlineScriptRun(File code, ArrayList args) throws Exception { + File stl = File.createTempFile(sanitizeString(code.getName()), ".stl"); + stl.deleteOnExit(); + HashMap params=new HashMap(); + if(args!=null) { + Object o = args.get(0); + if(HashMap.class.isInstance(o)) { + params=(HashMap)o; + } + } + + toSTLFile(code,stl,params); + CSG back = Vitamins.get(stl,true); + back.setColor(Color.YELLOW); + return back; + } + + @Override + public Object inlineScriptRun(String code, ArrayList args) throws Exception { + throw new RuntimeException("Blender can not run from a string"); + } + + @Override + public String getShellType() { + return "OpenSCAD"; + } + + @Override + public ArrayList getFileExtenetion() { + ArrayList ext = new ArrayList<>(); + ext.add("scad"); + ext.add("SCad"); + + return ext; + } + + + + + public static void toSTLFile(File openscadfile,File stlout, HashMap params) throws InvalidRemoteException, TransportException, GitAPIException, IOException, InterruptedException { + File exe = getConfigExecutable("openscad", null); + if(params==null) + params=new HashMap(); + ArrayList args = new ArrayList<>(); + + if(stlout.exists()) + stlout.delete(); + args.add(exe.getAbsolutePath()); + for(String key:params.keySet()) { + args.add("-D"); + args.add(key+"="+params.get(key)); + } + args.add("-o"); + args.add(stlout.getAbsolutePath()); + args.add(openscadfile.getAbsolutePath()); + legacySystemRun(null, stlout.getAbsoluteFile().getParentFile(), System.out, args); + } + @Override + public String getDefaultContents() { + return "cube([30, 20, 10]);"; + } + + @Override + public boolean getIsTextFile() { + return true; + } + + public static void main(String[] args) throws InvalidRemoteException, TransportException, GitAPIException, IOException, InterruptedException { + OpenSCADLoader loader = new OpenSCADLoader(); + + // create test file + File testblend = new File("test.scad"); + if(!testblend.exists()) + loader.getDefaultContents(testblend); + HashMap params = new HashMap(); + toSTLFile(testblend, new File("testscad.stl"),params); + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/RobotHelper.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/RobotHelper.java index a9442065c..2b38c8781 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/RobotHelper.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/RobotHelper.java @@ -31,15 +31,15 @@ public Object inlineScriptRun(File code, ArrayList args) { mb.setGitSelfSource(ScriptingEngine.findGitTagFromFile(code)); return MobileBaseLoader.get(mb).getBase(); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); return null; } } catch (IOException e1) { - // TODO Auto-generated catch block + // Auto-generated catch block e1.printStackTrace(); } - // System.out.println("Clojure returned of type="+ret.getClass()+" value="+ret); + // com.neuronrobotics.sdk.common.Log.error("Clojure returned of type="+ret.getClass()+" value="+ret); return null; } @@ -50,7 +50,7 @@ public Object inlineScriptRun(String code, ArrayList args) { try { mb = new MobileBase(IOUtils.toInputStream(code, "UTF-8")); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); return null; } @@ -65,7 +65,7 @@ public String getShellType() { @Override public boolean getIsTextFile() { - // TODO Auto-generated method stub + // Auto-generated method stub return true; } @@ -134,7 +134,7 @@ public void getDefaultContents(String gitURL, String slug) { @Override public ArrayList getFileExtenetion() { - // TODO Auto-generated method stub + // Auto-generated method stub return new ArrayList<>(Arrays.asList("xml")); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ScriptingEngine.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ScriptingEngine.java index 8465cfece..b994c777c 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ScriptingEngine.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/ScriptingEngine.java @@ -6,6 +6,7 @@ import com.neuronrobotics.sdk.util.ThreadUtil; import com.neuronrobotics.video.OSUtil; +import eu.mihosoft.vrl.v3d.CSG; import eu.mihosoft.vrl.v3d.parametrics.CSGDatabase; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; @@ -63,6 +64,7 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.util.ArrayList; @@ -89,9 +91,50 @@ public class ScriptingEngine {// this subclasses boarder pane for the widgets // sake, because multiple inheritance is TOO // hard for java... private static final int TIME_TO_WAIT_BETWEEN_GIT_PULL = 100000; + /** * */ + public static void flatten(ArrayList flat, Object o) { + if (CSG.class.isInstance(o)) + flat.add((CSG) o); + if (List.class.isInstance(o)) { + for (Object ob : (List) o) { + flatten(flat, ob); + } + } + + } + + public static void flatenInterna(Object o, Class type, ArrayList flattened) { + if (type.isInstance(o)) + flattened.add((T) o); + else if (List.class.isInstance(o)) { + for (Object ob : (List) o) { + flatenInterna(ob, type, flattened); + } + } else if (Map.class.isInstance(o)) { + Map m = (Map) o; + for (Object key : m.keySet()) { + flatenInterna(m.get(key), type, flattened); + flatenInterna(key, type, flattened); + } + } + } + + public static List flaten(String git, String file, Class type, ArrayList args) throws Exception { + ArrayList flattened = new ArrayList(); + Object o = gitScriptRun(git, file, args); + flatenInterna(o, type, flattened); + return flattened; + } + + public static List flaten(File f, Class type, ArrayList args) throws Exception { + ArrayList flattened = new ArrayList(); + Object o = inlineFileScriptRun(f, args); + flatenInterna(o, type, flattened); + return flattened; + } private static final ArrayList logListeners = new ArrayList<>(); @@ -110,9 +153,8 @@ public class ScriptingEngine {// this subclasses boarder pane for the widgets "com.neuronrobotics.bowlerstudio.scripting", "com.neuronrobotics.bowlerstudio.tabs", "com.neuronrobotics.bowlerstudio.physics", "com.neuronrobotics.bowlerstudio.physics", "com.neuronrobotics.bowlerstudio.vitamins", "com.neuronrobotics.bowlerstudio.creature", - "com.neuronrobotics.bowlerstudio.threed","com.neuronrobotics.sdk.util.ThreadUtil", - "eu.mihosoft.vrl.v3d.Transform", - "com.neuronrobotics.bowlerstudio.vitamins.Vitamins" }; + "com.neuronrobotics.bowlerstudio.threed", "com.neuronrobotics.sdk.util.ThreadUtil", + "eu.mihosoft.vrl.v3d.Transform", "com.neuronrobotics.bowlerstudio.vitamins.Vitamins" }; private static HashMap filesRun = new HashMap<>(); @@ -131,11 +173,16 @@ public class ScriptingEngine {// this subclasses boarder pane for the widgets private static HashMap> onCommitEventListeners = new HashMap<>(); // static IssueReportingExceptionHandler exp = new // IssueReportingExceptionHandler(); - static HashMap gitOpenTimeout = new HashMap<>(); + // static HashMap gitOpenTimeout = new HashMap<>(); + static HashMap open = new HashMap(); + + private static String delim; + + private static String appName = "BowlerLauncher"; static { PasswordManager.hasNetwork(); - + addScriptingLanguage(new StlLoader()); addScriptingLanguage(new ClojureHelper()); addScriptingLanguage(new GroovyHelper()); addScriptingLanguage(new JythonHelper()); @@ -149,11 +196,14 @@ public class ScriptingEngine {// this subclasses boarder pane for the widgets addScriptingLanguage(new BlenderLoader()); addScriptingLanguage(new FreecadLoader()); addScriptingLanguage(new FXMLBowlerLoader()); + addScriptingLanguage(new OpenSCADLoader()); + addScriptingLanguage(new CaDoodleLoader()); + addScriptingLanguage(new ObjLoader()); } public static void setWorkspace(File file) { workspace = file; - System.err.println("Workspace: " + workspace.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Workspace: " + workspace.getAbsolutePath()); if (!workspace.exists()) { workspace.mkdir(); } @@ -189,7 +239,7 @@ public static void clearLogListener() { logListeners.clear(); } - private static Git cloneRepoLocalSelectAuth(String remoteURI, File dir, boolean useSSH) + private static void cloneRepoLocalSelectAuth(String remoteURI, File dir, boolean useSSH, IGitAccessor accessor) throws InvalidRemoteException, TransportException, GitAPIException { CloneCommand setURI = Git.cloneRepository().setURI(remoteURI); @@ -203,12 +253,18 @@ private static Git cloneRepoLocalSelectAuth(String remoteURI, File dir, boolean } Git git = setURI.call(); - gitOpenTimeout.put(git, makeTimeoutThread(git)); - return git; + open.put(dir.getAbsolutePath(), git); + try { + accessor.run(git); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + gitclose(git); } /** - * CLoe git and start a timeout timer + * Clone git and start a timeout timer * * @param remoteURI * @param branch @@ -218,21 +274,22 @@ private static Git cloneRepoLocalSelectAuth(String remoteURI, File dir, boolean * @throws TransportException * @throws GitAPIException */ - private static Git cloneRepoLocal(String remoteURI, File dir) + private static void cloneRepoLocal(String remoteURI, File dir, IGitAccessor accessor) throws InvalidRemoteException, TransportException, GitAPIException { boolean startsWith = remoteURI.startsWith("git@"); - try { - return cloneRepoLocalSelectAuth(remoteURI, dir, startsWith); + cloneRepoLocalSelectAuth(remoteURI, dir, startsWith, accessor); } catch (org.eclipse.jgit.api.errors.JGitInternalException ex) { if (ex.getMessage().contains("already exists and is not an empty directory")) { deleteRepo(remoteURI); - return cloneRepoLocal(remoteURI, dir); + cloneRepoLocal(remoteURI, dir, accessor); + return; } throw ex; } catch (org.eclipse.jgit.api.errors.TransportException ex) { if (ex.getMessage().contains("Auth fail") && !startsWith) { - return cloneRepoLocalSelectAuth(remoteURI, dir, true); + cloneRepoLocalSelectAuth(remoteURI, dir, true, accessor); + return; } throw ex; } @@ -251,14 +308,14 @@ private static ProgressMonitor getProgressMoniter(String type, String remoteURI) @Override public void update(int completed) { - for (Iterator iterator = gitOpenTimeout.keySet().iterator(); iterator.hasNext();) { - Git g = iterator.next(); - GitTimeoutThread t = gitOpenTimeout.get(g); - if (t.ref.toLowerCase().contentEquals(remoteURI.toLowerCase())) { - t.resetTimer(); - break; - } - } +// for (Iterator iterator = gitOpenTimeout.keySet().iterator(); iterator.hasNext();) { +// Git g = iterator.next(); +// GitTimeoutThread t = gitOpenTimeout.get(g); +// if (t.ref.toLowerCase().contentEquals(remoteURI.toLowerCase())) { +// t.resetTimer(); +// break; +// } +// } sum += completed; DecimalFormat df = new DecimalFormat("###.#"); @@ -270,10 +327,11 @@ public void update(int completed) { } String str = format + "% " + stage + " " + reponame + " " + tasks + " of task " + type; if (timeofLastUpdate + 500 < System.currentTimeMillis()) { - if(printProgress)System.out.println(str); + if (printProgress) + com.neuronrobotics.sdk.common.Log.error(str); timeofLastUpdate = System.currentTimeMillis(); } - // System.err.println(str); + // com.neuronrobotics.sdk.common.Log.error(str); for (GitLogProgressMonitor l : logListeners) { l.onUpdate(str, e); @@ -293,7 +351,8 @@ public boolean isCancelled() { @Override public void endTask() { String string = "100% " + stage + " " + reponame + " " + type; - if(printProgress)System.out.println(string); + if (printProgress) + com.neuronrobotics.sdk.common.Log.error(string); for (GitLogProgressMonitor l : logListeners) { l.onUpdate(string, e); } @@ -302,7 +361,8 @@ public void endTask() { @Override public void beginTask(String title, int totalWork) { stage = title; - // System.out.println("Setting totalWork to "+totalWork+" for stage "+stage); + // com.neuronrobotics.sdk.common.Log.error("Setting totalWork to "+totalWork+" + // for stage "+stage); total = totalWork; sum = 0; tasks += 1; @@ -317,29 +377,26 @@ public void beginTask(String title, int totalWork) { * @param url * @return */ - public static Git openGit(String url) { + public static void openGit(String url, IGitAccessor accessor) { Repository localRepo; try { localRepo = getRepository(url); - return openGit(localRepo); + openGit(localRepo, accessor); + return; } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } throw new RuntimeException("IOException making repo"); } - public static boolean isUrlAlreadyOpen(String URL) { + public static boolean isUrlAlreadyOpen(File URL) { if (URL == null) return false; - Object[] keySet; - synchronized(gitOpenTimeout) { - keySet = gitOpenTimeout.keySet().toArray(); - } - for (int i = 0; i < keySet.length; i++) { - Git g = (Git)keySet[i]; - GitTimeoutThread t = gitOpenTimeout.get(g); - if (t.ref.toLowerCase().contentEquals(URL.toLowerCase())) { + Set keySet = open.keySet(); + + for (String s : keySet) { + if (s.toLowerCase().contentEquals(URL.getAbsolutePath())) { // t.getException().printStackTrace(System.err); return true; } @@ -354,41 +411,43 @@ public static boolean isUrlAlreadyOpen(String URL) { * @return */ - public static Git openGit(Repository localRepo) { - - Object[] keySet; - synchronized(gitOpenTimeout) { - keySet = gitOpenTimeout.keySet().toArray(); - } - for (int j = 0; j < keySet.length; j++) { - Object gO = keySet[j]; - Git g=(Git)gO; - if (g.getRepository().getDirectory().getAbsolutePath() - .contentEquals(localRepo.getDirectory().getAbsolutePath())) { - GitTimeoutThread t = gitOpenTimeout.get(g); - int i = 0; - while (gitOpenTimeout.containsKey(g)) { - - System.out.println( - "Git is locked by other process, blocking " + localRepo.getDirectory().getAbsolutePath()); - System.out.println("Git locked " + t.ref); - if (i > 3) { - t.getException().printStackTrace(System.out); - System.out.println("Blocking process: "); - - new Exception().printStackTrace(System.out); - } - i++; - ThreadUtil.wait(1000); + public static void openGit(Repository localRepo, IGitAccessor accessor) { + Git git = null; + boolean alreadyOpen= false; + try { + String absolutePath = localRepo.getDirectory().getAbsolutePath(); + for (String s : open.keySet()) { + Git g = open.get(s); + if(g!=null) + if (g.getRepository().getDirectory().getAbsolutePath() + .contentEquals(absolutePath)) { + git=g; + alreadyOpen=true; + break; + } + } + if(!alreadyOpen) { + git = new Git(localRepo); + open.put(absolutePath, git); + } + if (accessor != null) { + try { + accessor.run(git); + } catch (Throwable t) { + //new IssueReportingExceptionHandler().except(t); + throw new RuntimeException(t); } - break; } + if(!alreadyOpen) + gitclose(git); + } catch (Throwable t) { + //new IssueReportingExceptionHandler().except(t); + if(!alreadyOpen) + if (git != null) { + gitclose(git); + } + throw new RuntimeException(t); } - - Git git = new Git(localRepo); - - gitOpenTimeout.put(git, makeTimeoutThread(git)); - return git; } /** @@ -396,35 +455,14 @@ public static Git openGit(Repository localRepo) { * * @param git */ - public static void closeGit(Git git) { + private static void gitclose(Git git) { if (git == null) return; - if (gitOpenTimeout.containsKey(git)) { - Thread thread = gitOpenTimeout.remove(git); - if (thread != null) { - thread.interrupt(); - } else { - new IssueReportingExceptionHandler().uncaughtException(Thread.currentThread(), - new RuntimeException("Closing a git object that was not opened with a timeout!")); - } - } - git.getRepository().close(); + open.remove(git.getRepository().getDirectory().getAbsolutePath()); + //git.getRepository().close(); git.close(); } - /** - * Make a timeout thread for printing an exception whenever a git object is - * opened and not closed within 5 seconds - * - * @return - */ - private static GitTimeoutThread makeTimeoutThread(Git git) { - - GitTimeoutThread thread = new GitTimeoutThread(git); - thread.start(); - return thread; - } - public static void addOnCommitEventListeners(String url, Runnable event) { synchronized (onCommitEventListeners) { if (!onCommitEventListeners.containsKey(url)) { @@ -458,11 +496,12 @@ public static void removeOnCommitEventListeners(String url, Runnable event) { public static Object inlineScriptRun(File code, ArrayList args, String shellTypeStorage) throws Exception { if (filesRun.get(code.getName()) == null) { filesRun.put(code.getName(), code); - // System.out.println("Loading "+code.getAbsolutePath()); + // com.neuronrobotics.sdk.common.Log.error("Loading "+code.getAbsolutePath()); } - if (langauges.get(shellTypeStorage) != null) { - return langauges.get(shellTypeStorage).inlineScriptRun(code, args); + IScriptingLanguage iScriptingLanguage = langauges.get(shellTypeStorage); + if (iScriptingLanguage != null) { + return iScriptingLanguage.inlineScriptRun(code, args); } return null; } @@ -501,25 +540,63 @@ public static void removeIGithubLoginListener(IGithubLoginListener l) { public static File getWorkspace() { if (workspace == null) { - String relative = FileSystemView.getFileSystemView().getDefaultDirectory().getPath(); - // https://github.com/CommonWealthRobotics/BowlerStudio/issues/378 - if (OSUtil.isOSX() || OSUtil.isLinux()) - if (!relative.endsWith("Documents")) { - relative = relative + "/Documents"; - } - if (OSUtil.isWindows()) { - if (!relative.endsWith("Documents")) { - relative = relative + "\\Documents"; - } - } - - File file = new File(relative + "/bowler-workspace/"); + File relative = getWorkingDirectory(); + File file = new File(relative.getAbsolutePath() + delim + "bowler-workspace" + delim); file.mkdirs(); setWorkspace(file); } return workspace; } + public static void createSymlinkInDocuments(File appDataDir) throws IOException { + String userHome = System.getProperty("user.home"); + Path documentsDir = Paths.get(userHome, "Documents"); + Path symlinkPath = documentsDir.resolve(appDataDir.getName()); + + // Delete existing symlink if it exists + if (Files.exists(symlinkPath)) { + return; + } + + // Create the symlink + Files.createSymbolicLink(symlinkPath, appDataDir.toPath()); + com.neuronrobotics.sdk.common.Log.error("Symlink created: " + symlinkPath); + } + + public static File getWorkingDirectory() { + String relative = Paths.get(System.getProperty("user.home"), "Documents").toString(); + if (OSUtil.isOSX()) { + File appDataDir = new File(System.getProperty("user.home") + "/Library/Application Support/" + appName); + + if (!appDataDir.exists()) { + if (!appDataDir.mkdirs()) { + throw new RuntimeException("Failed to create app data directory"); + } + } + relative = appDataDir.getAbsolutePath(); + try { + createSymlinkInDocuments(appDataDir); + } catch (IOException e) { + // Auto-generated catch block + e.printStackTrace(); + } + } + delim = "/"; + if (OSUtil.isLinux()) + if (!relative.endsWith("Documents")) { + relative = relative + delim + "Documents"; + } + if (OSUtil.isWindows()) { + delim = "\\"; + if (!relative.endsWith("Documents")) { + relative = relative + delim + "Documents"; + } + } + File file = new File(relative + delim); + file.mkdirs(); + return file; + } + public static String getShellType(String name) { for (IScriptingLanguage l : langauges.values()) { if (l.isSupportedFileExtenetion(name)) @@ -548,7 +625,7 @@ public static void logout() throws IOException { } public static GitHub setupAnyonmous() throws IOException { - //ScriptingEngine.setAutoupdate(false); + // ScriptingEngine.setAutoupdate(false); return PasswordManager.setupAnyonmous(); } @@ -585,11 +662,11 @@ private static List returnFirstGist(String html) { Elements links = doc.select("script"); for (int i = 0; i < links.size(); i++) { Element e = links.get(i); - /// System.out.println("Found gist embed: "+e); + /// com.neuronrobotics.sdk.common.Log.error("Found gist embed: "+e); Attributes n = e.attributes(); String jSSource = n.get("src"); if (jSSource.contains("https://gist.github.com/")) { - // System.out.println("Source = "+jSSource); + // com.neuronrobotics.sdk.common.Log.error("Source = "+jSSource); String slug = jSSource; String js = slug.split(".js")[0]; String[] id = js.split("/"); @@ -631,7 +708,7 @@ public static List getCurrentGist(String addr, Object engine) { */ public static void waitForLogin() throws IOException, InvalidRemoteException, TransportException, GitAPIException { if (!PasswordManager.hasNetwork()) { - System.err.println("No network, cant log in"); + com.neuronrobotics.sdk.common.Log.error("No network, cant log in"); return; } try { @@ -639,18 +716,18 @@ public static void waitForLogin() throws IOException, InvalidRemoteException, Tr if (PasswordManager.loggedIn()) return; if (PasswordManager.getLoginID() == null) { - System.err.println("No login ID found!"); + com.neuronrobotics.sdk.common.Log.error("No login ID found!"); return; } if (PasswordManager.getPassword() == null) { - System.err.println("No login api key found!"); + com.neuronrobotics.sdk.common.Log.error("No login api key found!"); return; } - System.err.println("Performing Login"); + com.neuronrobotics.sdk.common.Log.error("Performing Login"); PasswordManager.waitForLogin(); if (!PasswordManager.loggedIn()) { - System.err.println("\nERROR: Wrong Password!\n"); + com.neuronrobotics.sdk.common.Log.error("\nERROR: Wrong Password!\n"); login(); } @@ -661,22 +738,17 @@ public static void waitForLogin() throws IOException, InvalidRemoteException, Tr } public static void waitForRepo(String remoteURI, String reason) { - while (ScriptingEngine.isUrlAlreadyOpen(remoteURI)) { - ThreadUtil.wait(500); - for (Iterator iterator = gitOpenTimeout.keySet().iterator(); iterator.hasNext();) { - Git g = iterator.next(); - GitTimeoutThread t = gitOpenTimeout.get(g); - if (t.ref.toLowerCase().contentEquals(remoteURI.toLowerCase())) { - - System.err.println("\n\n\nPaused " + reason + " by another thread, waiting for repo " + remoteURI); - new Exception().printStackTrace(System.err); - System.err.println("Paused by:"); - t.getException().printStackTrace(System.err); - System.err.println("\n\n\n"); - - } + try { + File f = getRepository(remoteURI).getDirectory(); + while (ScriptingEngine.isUrlAlreadyOpen(f)) { + ThreadUtil.wait(500); + System.err.println("Waiting..."); } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } + } public static void deleteRepo(String remoteURI) { @@ -708,25 +780,25 @@ private static void deleteFolder(File folder) { try { FileChangeWatcher.notifyOfDelete(f); FileChangeWatcher.close(f); - System.out.println("Deleting File " + f.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Deleting File " + f.getAbsolutePath()); if (!f.delete()) { - System.err.println("File failed to delete! " + f); + com.neuronrobotics.sdk.common.Log.error("File failed to delete! " + f); } } catch (Throwable t) { t.printStackTrace(); } - // System.out.println("Deleting " + f.getAbsolutePath()); + // com.neuronrobotics.sdk.common.Log.error("Deleting " + f.getAbsolutePath()); } } } try { - System.out.println("Deleting Folder " + folder.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Deleting Folder " + folder.getAbsolutePath()); folder.delete(); } catch (Throwable t) { t.printStackTrace(); } if (folder.exists()) { - System.err.println("Folder failed to delete! " + folder); + com.neuronrobotics.sdk.common.Log.error("Folder failed to delete! " + folder); deleteFolder(folder); } @@ -821,10 +893,10 @@ private static boolean ensureExistance(File desired) throws IOException { File parent = desired.getParentFile(); if (!parent.exists()) { parent.mkdirs(); - System.err.println("Creating " + parent.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Creating " + parent.getAbsolutePath()); } if (!desired.exists() && parent.exists()) { - System.err.println("Creating " + desired.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Creating " + desired.getAbsolutePath()); desired.createNewFile(); createdFlag = true; } @@ -833,16 +905,18 @@ private static boolean ensureExistance(File desired) throws IOException { public static void commit(String id, String branch, String FileName, String content, String commitMessage, boolean flagNewFile) throws Exception { - commit(id, branch, FileName, content, commitMessage, flagNewFile, null); + openGit(id, git -> { + commit(id, branch, FileName, content, commitMessage, flagNewFile, git); + }); } @SuppressWarnings("deprecation") - public static void commit(String id, String branch, String FileName, String content, String commitMessage, + private static void commit(String id, String branch, String FileName, String content, String commitMessage, boolean flagNewFile, Git gitRef) throws Exception { - if(content !=null) - if("Binary File".contentEquals(content)){ - content=null; - } + if (content != null) + if ("Binary File".contentEquals(content)) { + content = null; + } if (PasswordManager.getUsername() == null) login(); if (!hasNetwork()) @@ -858,13 +932,11 @@ public static void commit(String id, String branch, String FileName, String cont Repository localRepo = new FileRepository(gitRepoFile.getAbsoluteFile()); Git git = gitRef; if (git == null) - git = openGit(localRepo); + throw new RuntimeException("Fail! Git must exist before commiting"); try { // latest version if (flagNewFile) { git.add().addFilepattern(FileName).call(); } - if (gitRef == null) - closeGit(git); if (content != null) { OutputStream out = null; try { @@ -880,13 +952,8 @@ public static void commit(String id, String branch, String FileName, String cont commit(id, branch, commitMessage, gitRef); } catch (Exception ex) { - if (gitRef == null) - closeGit(git); - throw ex; } - if (gitRef == null) - closeGit(git); try { if (!desired.getName().contentEquals("csgDatabase.json")) { String[] gitID = ScriptingEngine.findGitTagFromFile(desired, gitRef); @@ -901,7 +968,7 @@ public static void commit(String id, String branch, String FileName, String cont CSGDatabase.saveDatabase(); @SuppressWarnings("resource") String c = new Scanner(dbFile).useDelimiter("\\Z").next(); - ScriptingEngine.commit(remoteURI, branch, s, c, "saving CSG database", false, gitRef); + commit(remoteURI, branch, s, c, "saving CSG database", false, gitRef); } } } @@ -915,9 +982,9 @@ public static void commit(String id, String branch, String FileName, String cont public static void pushCodeToGit(String remoteURI, String branch, String FileName, String content, String commitMessage, boolean flagNewFile) throws Exception { waitForRepo(remoteURI, "push"); - if(content!=null) - if("Binary File".contentEquals(content)){ - content=null; + if (content != null) + if ("Binary File".contentEquals(content)) { + content = null; } commit(remoteURI, branch, FileName, content, commitMessage, flagNewFile); if (PasswordManager.getUsername() == null) @@ -945,40 +1012,40 @@ public static void pushCodeToGit(String remoteURI, String branch, String FileNam File gitRepoFile = new File(localPath + "/.git"); Repository localRepo = new FileRepository(gitRepoFile.getAbsoluteFile()); - Git git = null; + // Git git = null; try { try { pull(remoteURI, branch); } catch (java.lang.RuntimeException exp) { } - git = openGit(localRepo); - // latest version - if (flagNewFile) { - git.add().addFilepattern(FileName).call(); - } - if (content != null) { - OutputStream out = null; - try { - out = FileUtils.openOutputStream(desired, false); - IOUtils.write(content, out); - out.close(); // don't swallow close Exception if copy - // completes - // normally - } finally { - IOUtils.closeQuietly(out); + String c = content; + openGit(localRepo, git -> { + // latest version + if (flagNewFile) { + git.add().addFilepattern(FileName).call(); } - } - if (git.getRepository().getConfig().getString("remote", "origin", "url").startsWith("git@")) - git.push().setTransportConfigCallback(transportConfigCallback) - .setProgressMonitor(getProgressMoniter("Pushing ", remoteURI)).call(); - else - git.push().setCredentialsProvider(PasswordManager.getCredentialProvider()) - .setProgressMonitor(getProgressMoniter("Pushing ", remoteURI)).call(); - closeGit(git); + if (c != null) { + OutputStream out = null; + try { + out = FileUtils.openOutputStream(desired, false); + IOUtils.write(c, out, Charset.defaultCharset()); + out.close(); // don't swallow close Exception if copy + // completes + // normally + } finally { + IOUtils.closeQuietly(out); + } + } + if (git.getRepository().getConfig().getString("remote", "origin", "url").startsWith("git@")) + git.push().setTransportConfigCallback(transportConfigCallback) + .setProgressMonitor(getProgressMoniter("Pushing ", remoteURI)).call(); + else + git.push().setCredentialsProvider(PasswordManager.getCredentialProvider()) + .setProgressMonitor(getProgressMoniter("Pushing ", remoteURI)).call(); + }); System.out.println("PUSH OK! file: " + desired + " on branch " + getBranch(remoteURI)); } catch (Exception ex) { ex.printStackTrace(); - closeGit(git); String[] gitID = ScriptingEngine.findGitTagFromFile(desired); String id = gitID[0]; @@ -991,7 +1058,7 @@ public static String[] codeFromGit(String id, String FileName) throws Exception File targetFile = fileFromGit(id, FileName); if (targetFile.exists()) { - // System.err.println("Loading file: + // com.neuronrobotics.sdk.common.Log.error("Loading file: // "+targetFile.getAbsoluteFile()); // Target file is ready to go String text = new String(Files.readAllBytes(Paths.get(targetFile.getAbsolutePath())), @@ -999,7 +1066,7 @@ public static String[] codeFromGit(String id, String FileName) throws Exception return new String[] { text, FileName, targetFile.getAbsolutePath() }; } - return null; + throw new RuntimeException("File missing! " + targetFile.getAbsolutePath()); } private static String[] codeFromGistID(String id, String FileName) throws Exception { @@ -1007,7 +1074,7 @@ private static String[] codeFromGistID(String id, String FileName) throws Except File targetFile = fileFromGit(giturl, FileName); if (targetFile.exists()) { - System.err.println("Gist at GIT : " + giturl); + com.neuronrobotics.sdk.common.Log.error("Gist at GIT : " + giturl); // Target file is ready to go String text = new String(Files.readAllBytes(Paths.get(targetFile.getAbsolutePath())), StandardCharsets.UTF_8); @@ -1058,7 +1125,7 @@ public static File uriToFile(String remoteURI) { File gistDir = new File(getWorkspace().getAbsolutePath() + "/gitcache/" + gitSplit + "/.git"); return gistDir; } catch (ArrayIndexOutOfBoundsException ex) { - System.err.println("Failed to parse " + remoteURI); + com.neuronrobotics.sdk.common.Log.error("Failed to parse " + remoteURI); throw ex; } @@ -1120,31 +1187,31 @@ public static void deleteBranch(String remoteURI, String toDelete) throws Except // CheckoutCommand checkout; // String source = getFullBranch(remoteURI); - Git git; + openGit(localRepo, git -> { + String d = toDelete; + if (!toDelete.contains("heads")) { + d = "heads/" + d; + } + if (!toDelete.contains("refs")) { + d = "refs/" + d; + } + Exception ex = null; + try { + // delete branch 'branchToDelete' locally + git.branchDelete().setBranchNames(d).call(); - git = openGit(localRepo); - if (!toDelete.contains("heads")) { - toDelete = "heads/" + toDelete; - } - if (!toDelete.contains("refs")) { - toDelete = "refs/" + toDelete; - } - Exception ex = null; - try { - // delete branch 'branchToDelete' locally - git.branchDelete().setBranchNames(toDelete).call(); + // delete branch 'branchToDelete' on remote 'origin' + RefSpec refSpec = new RefSpec().setSource(null).setDestination(d); + git.push().setRefSpecs(refSpec).setRemote("origin") + .setCredentialsProvider(PasswordManager.getCredentialProvider()) + .setProgressMonitor(getProgressMoniter("Pushing ", remoteURI)).call(); + } catch (Exception e) { + ex = e; + } + if (ex != null) + throw ex; + }); - // delete branch 'branchToDelete' on remote 'origin' - RefSpec refSpec = new RefSpec().setSource(null).setDestination(toDelete); - git.push().setRefSpecs(refSpec).setRemote("origin") - .setCredentialsProvider(PasswordManager.getCredentialProvider()) - .setProgressMonitor(getProgressMoniter("Pushing ", remoteURI)).call(); - } catch (Exception e) { - ex = e; - } - closeGit(git); - if (ex != null) - throw ex; } public static String newBranch(String remoteURI, String newBranch) @@ -1160,41 +1227,32 @@ public static void newBranch(String remoteURI, String newBranch, RevCommit sourc waitForRepo(remoteURI, "newBranch"); Repository localRepo = getRepository(remoteURI); - Git git = null; try { for (String s : listBranchNames(remoteURI)) { if (s.contains(newBranch)) { // throw new RuntimeException(newBranch + " can not be created because " + s + " // is too similar"); - - git = openGit(localRepo); - shallowCheckout(remoteURI, newBranch, git); - closeGit(git); + openGit(localRepo, git -> { + shallowCheckout(remoteURI, newBranch, git); + }); return; } } } catch (Exception e) { e.printStackTrace(); - closeGit(git); } - git = openGit(localRepo); - try { + openGit(localRepo, git -> { try { - if (source == null) - source = git.log().setMaxCount(1).call().iterator().next(); - newBranchLocal(newBranch, remoteURI, git, source); + RevCommit s = source; + if (s == null) + s = git.log().setMaxCount(1).call().iterator().next(); + newBranchLocal(newBranch, remoteURI, git, s); } catch (NoHeadException ex) { newBranchLocal(newBranch, remoteURI, git, null); } - } catch (Throwable ex) { - closeGit(git); - throw ex; - } - - closeGit(git); - + }); } private static void newBranchLocal(String newBranch, String remoteURI, Git git, RevCommit source) @@ -1210,9 +1268,9 @@ private static void newBranchLocal(String newBranch, String remoteURI, Git git, setName.setForce(true); } setName.call(); - System.out.println("Created new branch " + remoteURI + "\t\t" + newBranch); + com.neuronrobotics.sdk.common.Log.error("Created new branch " + remoteURI + "\t\t" + newBranch); } catch (org.eclipse.jgit.api.errors.RefNotFoundException ex) { - System.err.println("ERROR Creating " + newBranch + " in " + remoteURI); + com.neuronrobotics.sdk.common.Log.error("ERROR Creating " + newBranch + " in " + remoteURI); ex.printStackTrace(); } catch (org.eclipse.jgit.api.errors.RefAlreadyExistsException ex) { // just checkout the existing branch then @@ -1241,7 +1299,7 @@ private static boolean hasAtLeastOneReference(Git git) throws Exception { if (ref.getObjectId() != null) { List branchList = listBranches(remoteURI, git); if (branchList.size() > 0) { - // System.out.println("Found "+branchList.size()+" + // com.neuronrobotics.sdk.common.Log.error("Found "+branchList.size()+" // branches"); return true; } @@ -1262,20 +1320,23 @@ public static List listBranches(String remoteURI) throws Exception { Repository localRepo = new FileRepository(gitRepoFile.getAbsoluteFile()); // https://gist.github.com/0e6454891a3b3f7c8f28.git - List Ret; - Git git = openGit(localRepo); - Ret = listBranches(remoteURI, git); - closeGit(git); - return Ret; + ArrayList back = new ArrayList(); + openGit(localRepo, git -> { + List Ret = listBranches(remoteURI, git); + back.addAll(Ret); + }); + return back; } public static List listBranches(String remoteURI, Git git) throws Exception { // https://gist.github.com/0e6454891a3b3f7c8f28.git - // System.out.println("Listing references from: "+remoteURI); - // System.out.println(" branch: "+getFullBranch(remoteURI)); + // com.neuronrobotics.sdk.common.Log.error("Listing references from: + // "+remoteURI); + // com.neuronrobotics.sdk.common.Log.error(" branch: + // "+getFullBranch(remoteURI)); List list = git.branchList().setListMode(ListMode.ALL).call(); - // System.out.println(" size : "+list.size()); + // com.neuronrobotics.sdk.common.Log.error(" size : "+list.size()); return list; } @@ -1288,16 +1349,12 @@ public static List listLocalBranches(String remoteURI) throws IOException { Repository localRepo = new FileRepository(gitRepoFile.getAbsoluteFile()); // https://gist.github.com/0e6454891a3b3f7c8f28.git - Git git = openGit(localRepo); - try { + ArrayList back = new ArrayList(); + openGit(localRepo, git -> { List list = git.branchList().call(); - closeGit(git); - return list; - } catch (Exception ex) { - - } - closeGit(git); - return new ArrayList<>(); + back.addAll(list); + }); + return back; } public static List listLocalBranchNames(String remoteURI) throws Exception { @@ -1305,7 +1362,8 @@ public static List listLocalBranchNames(String remoteURI) throws Excepti List list = listLocalBranches(remoteURI); for (Ref ref : list) { - // System.out.println("Branch: " + ref + " " + ref.getName() + " " + + // com.neuronrobotics.sdk.common.Log.error("Branch: " + ref + " " + + // ref.getName() + " " + // ref.getObjectId().getName()); branchNames.add(ref.getName()); } @@ -1317,7 +1375,8 @@ public static List listBranchNames(String remoteURI) throws Exception { List list = listBranches(remoteURI); for (Ref ref : list) { - // System.out.println("Branch: " + ref + " " + ref.getName() + " " + + // com.neuronrobotics.sdk.common.Log.error("Branch: " + ref + " " + + // ref.getName() + " " + // ref.getObjectId().getName()); branchNames.add(ref.getName()); } @@ -1337,8 +1396,7 @@ public static void pull(String remoteURI, String branch) throws IOException, Che } Repository localRepo = new FileRepository(gitRepoFile.getAbsoluteFile()); - Git git = openGit(localRepo); - try { + openGit(localRepo, git -> { String ref = git.getRepository().getConfig().getString("remote", "origin", "url"); try { @@ -1360,64 +1418,57 @@ public static void pull(String remoteURI, String branch) throws IOException, Che throw ex; } - closeGit(git); - // new Exception(ref).printStackTrace(); } catch (CheckoutConflictException ex) { -// closeGit(git); -// resolveConflict(remoteURI, ex, git); -// pull(remoteURI, branch); - closeGit(git); + PasswordManager.checkInternet(); throw ex; } catch (WrongRepositoryStateException e) { e.printStackTrace(); - closeGit(git); + PasswordManager.checkInternet(); // deleteRepo(remoteURI); throw e; } catch (InvalidConfigurationException e) { PasswordManager.checkInternet(); - closeGit(git); + throw new RuntimeException("remoteURI " + remoteURI + " branch " + branch + " " + e.getMessage()); } catch (DetachedHeadException e) { PasswordManager.checkInternet(); - closeGit(git); + throw new RuntimeException("remoteURI " + remoteURI + " branch " + branch + " " + e.getMessage()); } catch (InvalidRemoteException e) { PasswordManager.checkInternet(); - closeGit(git); + throw new InvalidRemoteException("remoteURI " + remoteURI + " branch " + branch + " " + e.getMessage()); } catch (CanceledException e) { PasswordManager.checkInternet(); - closeGit(git); + throw new RuntimeException("remoteURI " + remoteURI + " branch " + branch + " " + e.getMessage()); } catch (RefNotFoundException e) { PasswordManager.checkInternet(); - closeGit(git); + throw new RuntimeException("remoteURI " + remoteURI + " branch " + branch + " " + e.getMessage()); } catch (RefNotAdvertisedException e) { PasswordManager.checkInternet(); - closeGit(git); + try { if (branch != null) newBranch(remoteURI, branch); else { - git = openGit(remoteURI); - RevCommit source = git.log().setMaxCount(1).call().iterator().next(); + openGit(remoteURI, g -> { + RevCommit source = g.log().setMaxCount(1).call().iterator().next(); - newBranchLocal("main", remoteURI, git, source); - closeGit(git); + newBranchLocal("main", remoteURI, g, source); + }); } } catch (Exception ex) { - closeGit(git); ex.printStackTrace(); throw new RuntimeException("remoteURI " + remoteURI + " branch " + branch + " " + ex.getMessage()); } } catch (NoHeadException e) { PasswordManager.checkInternet(); - closeGit(git); throw e; // try { // closeGit(git); @@ -1435,30 +1486,20 @@ public static void pull(String remoteURI, String branch) throws IOException, Che try { git.pull().setTransportConfigCallback(transportConfigCallback) .setProgressMonitor(getProgressMoniter("Pull ", remoteURI)).call(); - closeGit(git); } catch (Exception ex) { - closeGit(git); throw new RuntimeException( "remoteURI " + remoteURI + " branch " + branch + " " + e.getMessage()); } } else { - closeGit(git); throw new RuntimeException("remoteURI " + remoteURI + " branch " + branch + " " + e.getMessage()); } } catch (GitAPIException e) { e.printStackTrace(); PasswordManager.checkInternet(); - closeGit(git); throw new RuntimeException("remoteURI " + remoteURI + " branch " + branch + " " + e.getMessage()); } - } catch (InvalidRemoteException e) { - PasswordManager.checkInternet(); - closeGit(git); - throw new InvalidRemoteException("remoteURI " + remoteURI + " branch " + branch + " " + e.getMessage()); - } catch (Throwable t) { - closeGit(git); - } + }); } @@ -1474,21 +1515,14 @@ public static void checkoutCommit(String remoteURI, String branch, String commit waitForRepo(remoteURI, "checkoutCommit"); File gitRepoFile = ScriptingEngine.uriToFile(remoteURI); if (!gitRepoFile.exists() || !gitRepoFile.getAbsolutePath().endsWith(".git")) { - System.err.println("Invailid git file!" + gitRepoFile.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Invailid git file!" + gitRepoFile.getAbsolutePath()); throw new RuntimeException("Invailid git file!" + gitRepoFile.getAbsolutePath()); } Repository localRepo = new FileRepository(gitRepoFile); - Git git = openGit(localRepo); - try { + openGit(localRepo, git -> { git.checkout().setName(commitHash).call(); git.checkout().setCreateBranch(true).setName(branch).setStartPoint(commitHash).call(); - - } catch (Exception ex) { - ex.printStackTrace(); - } - - closeGit(git); - + }); } public static void checkout(String remoteURI, RevCommit commit) @@ -1513,7 +1547,7 @@ public static void checkout(String remoteURI, String branch) // cloneRepo(remoteURI, branch); File gitRepoFile = uriToFile(remoteURI); if (!gitRepoFile.exists() || !gitRepoFile.getAbsolutePath().endsWith(".git")) { - System.err.println("Invailid git file!" + gitRepoFile.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Invailid git file!" + gitRepoFile.getAbsolutePath()); throw new RuntimeException("Invailid git file!" + gitRepoFile.getAbsolutePath()); } @@ -1525,58 +1559,50 @@ public static void checkout(String remoteURI, String branch) branch = currentBranch; if (currentBranch.length() < branch.length() || !currentBranch.endsWith(branch)) { - System.err.println("Current branch is " + currentBranch + " need " + branch); + com.neuronrobotics.sdk.common.Log.error("Current branch is " + currentBranch + " need " + branch); - Git git = null; try { Collection branches = getAllBranches(remoteURI); - git = openGit(localRepo); - for (Ref R : branches) { - if (R.getName().endsWith(branch)) { - System.err.println("\nFound upstream " + R.getName()); - shallowCheckout(remoteURI, branch, git); - closeGit(git); + String br = branch; + openGit(localRepo, git -> { + for (Ref R : branches) { + if (R.getName().endsWith(br)) { + com.neuronrobotics.sdk.common.Log.error("\nFound upstream " + R.getName()); + shallowCheckout(remoteURI, br, git); + } } - } - // The ref does not exist upstream, create - try { - PasswordManager.checkInternet(); - closeGit(git); - newBranch(remoteURI, branch); - } catch (org.eclipse.jgit.api.errors.TransportException ex) { - // Not logged in yet, just return - PasswordManager.checkInternet(); - closeGit(git); - return; - } catch (RefAlreadyExistsException e) { - PasswordManager.checkInternet(); - closeGit(git); - throw new RuntimeException(e); - } catch (RefNotFoundException e) { - PasswordManager.checkInternet(); - closeGit(git); - throw new RuntimeException(e); - } catch (InvalidRefNameException e) { - PasswordManager.checkInternet(); - closeGit(git); - throw new RuntimeException(e); - } catch (CheckoutConflictException e) { - resolveConflict(remoteURI, e, git); - } catch (GitAPIException e) { - PasswordManager.checkInternet(); - closeGit(git); - throw new RuntimeException(e); - } catch (Exception e) { - PasswordManager.checkInternet(); - closeGit(git); - throw new RuntimeException(e); - } + // The ref does not exist upstream, create + try { + PasswordManager.checkInternet(); + newBranch(remoteURI, br); + } catch (org.eclipse.jgit.api.errors.TransportException ex) { + // Not logged in yet, just return + PasswordManager.checkInternet(); + return; + } catch (RefAlreadyExistsException e) { + PasswordManager.checkInternet(); + throw new RuntimeException(e); + } catch (RefNotFoundException e) { + PasswordManager.checkInternet(); + throw new RuntimeException(e); + } catch (InvalidRefNameException e) { + PasswordManager.checkInternet(); + throw new RuntimeException(e); + } catch (CheckoutConflictException e) { + resolveConflict(remoteURI, e, git); + } catch (GitAPIException e) { + PasswordManager.checkInternet(); + throw new RuntimeException(e); + } catch (Exception e) { + PasswordManager.checkInternet(); + throw new RuntimeException(e); + } + }); + } catch (Exception ex) { PasswordManager.checkInternet(); - closeGit(git); throw new RuntimeException(ex); } - closeGit(git); } } @@ -1609,9 +1635,9 @@ private static boolean resolveConflict(String remoteURI, CheckoutConflictExcepti Status stat = git.status().call(); Set changed = stat.getModified(); if (changed.size() > 0) { - System.out.println("Modified "); + com.neuronrobotics.sdk.common.Log.error("Modified "); for (String p : changed) { - System.out.println("Modified Conflict with: " + p); + com.neuronrobotics.sdk.common.Log.error("Modified Conflict with: " + p); byte[] bytes; String content = ""; try { @@ -1621,11 +1647,11 @@ private static boolean resolveConflict(String remoteURI, CheckoutConflictExcepti commit(remoteURI, getBranch(remoteURI), p, content, "auto-save in ScriptingEngine.resolveConflict", false, git); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } catch (IOException e1) { - // TODO Auto-generated catch block + // Auto-generated catch block e1.printStackTrace(); } @@ -1634,16 +1660,16 @@ private static boolean resolveConflict(String remoteURI, CheckoutConflictExcepti } Set untracked = stat.getUntracked(); if (untracked.size() > 0) { - System.out.println("Untracked "); + com.neuronrobotics.sdk.common.Log.error("Untracked "); for (String p : untracked) { - System.out.println("Untracked Conflict with: " + p); + com.neuronrobotics.sdk.common.Log.error("Untracked Conflict with: " + p); File f = fileFromGit(remoteURI, p); f.delete(); } return resolveConflict(remoteURI, con, git); } } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } return true; @@ -1666,36 +1692,27 @@ public static File cloneRepo(String remoteURI, String branch) { if (!hasNetwork()) return null;// No login info means there is no way to publish waitForRepo(remoteURI, "cloneRepo"); - System.out.println("Cloning files from: " + remoteURI); + com.neuronrobotics.sdk.common.Log.error("Cloning files from: " + remoteURI); if (branch != null) - System.out.println(" branch: " + branch); - System.out.println(" to: " + localPath); + com.neuronrobotics.sdk.common.Log.error(" branch: " + branch); + com.neuronrobotics.sdk.common.Log.error(" to: " + localPath); Throwable ex = null; // Clone the repo - Git git = null; try { if (branch == null) { - git = cloneRepoLocal(remoteURI, dir); - hasAtLeastOneReference(git); - closeGit(git); + cloneRepoLocal(remoteURI, dir, git -> { + hasAtLeastOneReference(git); + }); branch = getFullBranch(remoteURI); } else { - git = cloneRepoLocal(remoteURI, dir); - hasAtLeastOneReference(git); - closeGit(git); + cloneRepoLocal(remoteURI, dir, git -> { + hasAtLeastOneReference(git); + }); checkout(remoteURI, branch); } - - } catch (org.eclipse.jgit.api.errors.JGitInternalException exe) { - closeGit(git); - // deleteRepo(remoteURI); - throw exe; - } catch (Throwable e) { - e.printStackTrace(); - closeGit(git); - PasswordManager.checkInternet(); - throw new RuntimeException(e); + } catch (Throwable t) { + t.printStackTrace(); } } @@ -1703,7 +1720,12 @@ public static File cloneRepo(String remoteURI, String branch) { try { checkout(remoteURI, branch); } catch (Exception e) { - throw new RuntimeException(e); + try { + // try the checkout with no branch specified + return cloneRepo(remoteURI, null); + } catch (Exception ex) { + throw new RuntimeException(e); + } } } @@ -1719,16 +1741,22 @@ public static String locateGitUrl(File f, Git ref) throws IOException { File gitRepoFile = new File(f.getAbsolutePath()); while (gitRepoFile != null) { if (new File(gitRepoFile.getAbsolutePath() + "/.git/config").exists()) { - // System.err.println("Fount git repo for file: "+gitRepoFile); + // com.neuronrobotics.sdk.common.Log.error("Fount git repo for file: + // "+gitRepoFile); Repository localRepo = new FileRepository(gitRepoFile.getAbsoluteFile() + "/.git"); - Git git = ref; - if (git == null) - git = openGit(localRepo); - String url = git.getRepository().getConfig().getString("remote", "origin", "url"); + // Git git = ref; + if (ref == null) { + ArrayList s = new ArrayList(); + File fi = gitRepoFile; + openGit(localRepo, git -> { + s.add(locateGitUrl(fi, git)); + }); + return s.get(0); + } + String url = ref.getRepository().getConfig().getString("remote", "origin", "url"); if (!url.endsWith(".git")) url += ".git"; - if (ref == null) - closeGit(git); + localRepo.close(); return url; } gitRepoFile = gitRepoFile.getParentFile(); @@ -1737,20 +1765,21 @@ public static String locateGitUrl(File f, Git ref) throws IOException { return null; } - public static Git locateGit(File f) throws IOException { + public static void locateGit(File f, IGitAccessor access) throws IOException { File gitRepoFile = f; while (gitRepoFile != null) { gitRepoFile = gitRepoFile.getParentFile(); if (gitRepoFile != null) if (new File(gitRepoFile.getAbsolutePath() + "/.git/config").exists()) { - // System.err.println("Fount git repo for file: "+gitRepoFile); + // com.neuronrobotics.sdk.common.Log.error("Fount git repo for file: + // "+gitRepoFile); Repository localRepo = new FileRepository(gitRepoFile.getAbsoluteFile() + "/.git"); - return openGit(localRepo); - + openGit(localRepo, access); + return; } } - throw new RuntimeException("File "+f+" is not in a git repository"); + throw new RuntimeException("File " + f + " is not in a git repository"); } public static String getText(URL website) throws Exception { @@ -1824,15 +1853,13 @@ public static String findLocalPath(File currentFile, Git git) { @SuppressWarnings("unused") public static String findLocalPath(File currentFile) { - Git git = null; try { - git = locateGit(currentFile); - String ret = findLocalPath(currentFile, git); - closeGit(git); - return ret; + ArrayList s = new ArrayList(); + locateGit(currentFile, git -> { + s.add(findLocalPath(currentFile, git)); + }); + return s.get(0); } catch (IOException e) { - if (git != null) - closeGit(git); throw new RuntimeException(e); } @@ -1844,55 +1871,39 @@ public static String[] findGitTagFromFile(File currentFile) throws IOException { public static String[] findGitTagFromFile(File currentFile, Git ref) throws IOException { String string = locateGitUrl(currentFile, ref); - Git git = ref; - if (git == null) - git = locateGit(currentFile); - try { - String[] strings = new String[] { string, findLocalPath(currentFile, git) }; - if (ref == null) - closeGit(git); - return strings; - } catch (Throwable t) { - t.printStackTrace(); - if (ref == null) - closeGit(git); - throw t; + String[] strings = new String[2]; + if (ref == null) + locateGit(currentFile, git -> { + String[] str = findGitTagFromFile(currentFile, git); + strings[0] = str[0]; + strings[1] = str[1]; + }); + else { + strings[0] = string; + strings[1] = findLocalPath(currentFile, ref); } + return strings; + } public static boolean checkOwner(String url) { - Git git = null; - try { - git = openGit(getRepository(url)); - } catch (IOException e1) { - closeGit(git); - throw new RuntimeException(e1); - } - boolean owned = checkOwner(git); - closeGit(git); - return owned; + ArrayList owners = new ArrayList(); + openGit(url, git -> { + owners.add(checkOwner(git)); + }); + return owners.get(0); } public static boolean checkOwner(File currentFile) { + ArrayList owners = new ArrayList(); try { - Git git; - try { - git = locateGit(currentFile); - } catch (Exception e1) { - - return false; - } - boolean owned; - try { - owned = checkOwner(git); - } catch (Throwable t) { - owned = false; - } - closeGit(git); - return owned; - } catch (Throwable t) { + locateGit(currentFile, git -> { + owners.add(checkOwner(git)); + }); + } catch (Throwable e1) { return false; } + return owners.get(0); } private static boolean checkOwner(Git git) { @@ -1953,7 +1964,7 @@ public static String fork(String sourceURL, String newRepoName, String newRepoDe } catch (org.kohsuke.github.HttpException ex) { if (ex.getMessage().contains("name already exists on this account")) { repository = github.getRepository(PasswordManager.getLoginID() + "/" + newRepoName); - System.out.println("Repo exists!"); + com.neuronrobotics.sdk.common.Log.error("Repo exists!"); return repository.getHttpTransportUrl(); } throw ex; @@ -1961,33 +1972,34 @@ public static String fork(String sourceURL, String newRepoName, String newRepoDe String gitRepo = repository.getHttpTransportUrl(); ArrayList files = filesInGit(sourceURL); - Git git = locateGit(fileFromGit(sourceURL, files.get(0))); - Repository sourceRepoObject = git.getRepository(); - try { - sourceRepoObject.getConfig().setString("remote", "origin", "url", gitRepo); - if (git.getRepository().getConfig().getString("remote", "origin", "url").startsWith("git@")) - git.push().setTransportConfigCallback(transportConfigCallback) - .setProgressMonitor(getProgressMoniter("Pushing ", gitRepo)).call(); - else - git.push().setCredentialsProvider(PasswordManager.getCredentialProvider()) - .setProgressMonitor(getProgressMoniter("Pushing ", gitRepo)).call(); - closeGit(git); - - filesInGit(gitRepo); - - return gitRepo; - } catch (org.kohsuke.github.HttpException ex) { - closeGit(git); - if (ex.getMessage().contains("name already exists on this account")) { - return PasswordManager.getGithub().getRepository(PasswordManager.getLoginID() + "/" + newRepoName) - .getHttpTransportUrl(); + ArrayList back = new ArrayList(); + locateGit(fileFromGit(sourceURL, files.get(0)), git -> { + Repository sourceRepoObject = git.getRepository(); + try { + sourceRepoObject.getConfig().setString("remote", "origin", "url", gitRepo); + if (git.getRepository().getConfig().getString("remote", "origin", "url").startsWith("git@")) + git.push().setTransportConfigCallback(transportConfigCallback) + .setProgressMonitor(getProgressMoniter("Pushing ", gitRepo)).call(); + else + git.push().setCredentialsProvider(PasswordManager.getCredentialProvider()) + .setProgressMonitor(getProgressMoniter("Pushing ", gitRepo)).call(); + + filesInGit(gitRepo); + + back.add(gitRepo); + } catch (org.kohsuke.github.HttpException ex) { + if (ex.getMessage().contains("name already exists on this account")) { + back.add(PasswordManager.getGithub().getRepository(PasswordManager.getLoginID() + "/" + newRepoName) + .getHttpTransportUrl()); + } + ex.printStackTrace(); + } catch (Throwable ex) { + ex.printStackTrace(); } - ex.printStackTrace(); - } catch (Throwable ex) { - ex.printStackTrace(); - } - closeGit(git); - throw new RuntimeException("Repo could not be forked and does not exist"); + if (back.size() == 0) + throw new RuntimeException("Repo could not be forked and does not exist"); + }); + return back.get(0); } public static GHRepository makeNewRepoNoFailOver(String newName, String description) @@ -2007,7 +2019,7 @@ public static GHRepository makeNewRepoNoFailOver(String newName, String descript try { Thread.sleep(1000); } catch (InterruptedException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } @@ -2032,7 +2044,7 @@ public static GHRepository makeNewRepo(String newName, String description) throw commit(url, "main", "firstCommit"); newBranch(url, "main"); } catch (IOException | GitAPIException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } catch (org.kohsuke.github.HttpException ex) { @@ -2047,14 +2059,15 @@ public static GHRepository makeNewRepo(String newName, String description) throw public static String locateGitUrlString(File f) { try { - Git locateGit = ScriptingEngine.locateGit(f); - Repository repository = locateGit.getRepository(); - String string = repository.getConfig().getString("remote", "origin", "url"); - ScriptingEngine.closeGit(locateGit); - return string; - + ArrayList back = new ArrayList(); + locateGit(f, locateGit -> { + Repository repository = locateGit.getRepository(); + String string = repository.getConfig().getString("remote", "origin", "url"); + back.add(string); + }); + return back.get(0); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } return null; @@ -2066,7 +2079,7 @@ public static String urlToString(URL htmlUrl) { public static String urlToGist(URL htmlUrl) { String externalForm = urlToString(htmlUrl); - System.out.println(externalForm); + com.neuronrobotics.sdk.common.Log.error(externalForm); return ScriptingEngine.urlToGist(externalForm); } @@ -2077,7 +2090,16 @@ public static List getAllLangauges() { } return langs; } - + public static List getAllExtentions() { + ArrayList langs = new ArrayList<>(); + for (String L : getLangaugesMap().keySet()) { + IScriptingLanguage lang = getLangaugesMap().get(L); + for(String s:lang.getFileExtenetion()) { + langs.add(s); + } + } + return langs; + } public static HashMap getLangaugesMap() { return langauges; } @@ -2142,16 +2164,18 @@ public static String[] copyGitFile(String sourceGit, String targetGit, String fi } String[] newFileCode; try { + System.out.println("Opening "+targetFilename+" from "+targetGit); newFileCode = ScriptingEngine.codeFromGit(targetGit, targetFilename); if (newFileCode == null) newFileCode = new String[] { "" }; if (newFileCode[0].length() < 10) { - System.out.println("Copy Content to " + targetGit + "/" + targetFilename); + com.neuronrobotics.sdk.common.Log.error("Copy Content to " + targetGit + "/" + targetFilename); ScriptingEngine.pushCodeToGit(targetGit, ScriptingEngine.getFullBranch(targetGit), targetFilename, WalkingEngine[0], "copy file content"); } } catch (Exception e) { - throw new RuntimeException(e); + ScriptingEngine.pushCodeToGit(targetGit, ScriptingEngine.getFullBranch(targetGit), targetFilename, + WalkingEngine[0], "copy file content"); } } catch (Exception e1) { throw new RuntimeException(e1); @@ -2174,9 +2198,11 @@ public static Ref getBranch(String remoteURI, String branch) throws IOException, public static Collection getAllBranches(String remoteURI) throws IOException, GitAPIException { cloneRepo(remoteURI, null); - Git git = openGit(getRepository(remoteURI)); - String ref = git.getRepository().getConfig().getString("remote", "origin", "url"); - closeGit(git); + ArrayList refs = new ArrayList(); + openGit(getRepository(remoteURI), git -> { + refs.add(git.getRepository().getConfig().getString("remote", "origin", "url")); + }); + String ref = refs.get(0); System.out.print("Getting branches " + ref + " "); if (ref != null && ref.startsWith("git@")) { @@ -2238,11 +2264,15 @@ private static void commit(String url, String branch, String message) private static void commit(String url, String branch, String message, Git passedRef) throws IOException, GitAPIException, NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, AbortedByHookException { - Git git = passedRef; - if (git == null) - git = openGit(getRepository(url)); + + if (passedRef == null) { + openGit(getRepository(url), git -> { + commit(url, branch, message, git); + }); + return; + } try { - git.commit().setAll(true).setMessage(message).call(); + passedRef.commit().setAll(true).setMessage(message).call(); ArrayList arrayList = onCommitEventListeners.get(url); if (arrayList != null) { for (int i = 0; i < arrayList.size(); i++) { @@ -2255,12 +2285,8 @@ private static void commit(String url, String branch, String message, Git passed } } } catch (Throwable t) { - if (passedRef == null) - closeGit(git); throw t; } - if (passedRef == null) - closeGit(git); } public static File getAppData() { @@ -2306,32 +2332,31 @@ public static int versionCompare(String v1, String v2) { public static List getAllTags(String gitRepo) { ArrayList tags = new ArrayList<>(); - Git jGit = openGit(gitRepo); - List call; - try { - call = jGit.tagList().call(); - for (Ref ref : call) { - String string = ref.getName().split("/")[2]; - tags.add(string); - } - } catch (Throwable e) { - // TODO Auto-generated catch block - e.printStackTrace(); - - } - Collections.sort(tags, new Comparator() { - public int compare(String object1, String object2) { - return versionCompare(object1, object2); + openGit(gitRepo, jGit -> { + List call; + try { + call = jGit.tagList().call(); + for (Ref ref : call) { + String string = ref.getName().split("/")[2]; + tags.add(string); + } + } catch (Throwable e) { + // Auto-generated catch block + e.printStackTrace(); } + Collections.sort(tags, new Comparator() { + public int compare(String object1, String object2) { + return versionCompare(object1, object2); + } + }); }); - closeGit(jGit); return tags; } public static boolean tagExists(String remoteURI, String newTag) { List tags = getAllTags(remoteURI); for (String s : tags) { - System.out.println("Checking " + newTag + " against " + s); + com.neuronrobotics.sdk.common.Log.error("Checking " + newTag + " against " + s); if (s.contentEquals(newTag)) { return true; } @@ -2340,14 +2365,12 @@ public static boolean tagExists(String remoteURI, String newTag) { } public static void tagRepo(String remoteURI, String newTag) { - System.out.println("Tagging " + remoteURI + " at " + newTag); + com.neuronrobotics.sdk.common.Log.error("Tagging " + remoteURI + " at " + newTag); if (tagExists(remoteURI, newTag)) { - System.out.println("ERROR! Tag exists " + remoteURI + "@" + newTag); + com.neuronrobotics.sdk.common.Log.error("ERROR! Tag exists " + remoteURI + "@" + newTag); return; } - Git git = openGit(remoteURI); - // Creating tag - try { + openGit(remoteURI, git -> { try { git.tag().setName(newTag).setForceUpdate(true).call(); } catch (Throwable t) { @@ -2359,11 +2382,7 @@ public static void tagRepo(String remoteURI, String newTag) { else git.push().setPushTags().setCredentialsProvider(PasswordManager.getCredentialProvider()) .setProgressMonitor(getProgressMoniter("Pushing ", remoteURI)).call(); - } catch (GitAPIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - closeGit(git); + }); } public static boolean isPrintProgress() { @@ -2373,22 +2392,23 @@ public static boolean isPrintProgress() { public static void setPrintProgress(boolean printProgress) { ScriptingEngine.printProgress = printProgress; } - - public static void ignore(String url,String filepattern) throws Exception { + + public static void ignore(String url, String filepattern) throws Exception { File ignorefile = fileFromGit(url, ".gitignore"); - String contents=""; - if(ignorefile.exists()) { + String contents = ""; + if (ignorefile.exists()) { BufferedReader reader; try { reader = new BufferedReader(new FileReader(ignorefile)); String line = reader.readLine(); while (line != null) { - if(line.contains(filepattern)) { - System.out.println(""+filepattern+" exists in "+ignorefile.getAbsolutePath()); + if (line.contains(filepattern)) { + com.neuronrobotics.sdk.common.Log + .error("" + filepattern + " exists in " + ignorefile.getAbsolutePath()); reader.close(); return; } - contents+=line+"\n"; + contents += line + "\n"; // read next line line = reader.readLine(); } @@ -2397,8 +2417,16 @@ public static void ignore(String url,String filepattern) throws Exception { e.printStackTrace(); } } - contents+=filepattern; - pushCodeToGit(url, null, ".gitignore", contents, "Adding ignore for "+filepattern); + contents += filepattern; + pushCodeToGit(url, null, ".gitignore", contents, "Adding ignore for " + filepattern); + } + + public static String getAppName() { + return appName; + } + + public static void setAppName(String appName) { + ScriptingEngine.appName = appName; } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/SequenceRunner.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/SequenceRunner.java index 3254ebb7c..32d333196 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/SequenceRunner.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/SequenceRunner.java @@ -55,7 +55,7 @@ public String getDefaultContents() { @Override public ArrayList getFileExtenetion() { - // TODO Auto-generated method stub + // Auto-generated method stub return new ArrayList<>(Arrays.asList("sequence")); } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/StlLoader.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/StlLoader.java index 39f9216f9..1b6c704b9 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/StlLoader.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/StlLoader.java @@ -23,12 +23,12 @@ public Object inlineScriptRun(String code, ArrayList args) throws Except @Override public String getShellType() { - // TODO Auto-generated method stub + // Auto-generated method stub return "Stl"; } @Override public boolean getIsTextFile() { - // TODO Auto-generated method stub + // Auto-generated method stub return false; } /** @@ -41,8 +41,8 @@ public String getDefaultContents() { } @Override public ArrayList getFileExtenetion() { - // TODO Auto-generated method stub - return new ArrayList<>(Arrays.asList("stl")); + // Auto-generated method stub + return new ArrayList<>(Arrays.asList("stl","STL","Stl")); } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/SvgLoader.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/SvgLoader.java index ab5e0256c..86c836b06 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/SvgLoader.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/SvgLoader.java @@ -6,6 +6,8 @@ import java.util.HashMap; import java.util.List; +import com.neuronrobotics.bowlerstudio.util.GeometrySimplification; + import eu.mihosoft.vrl.v3d.CSG; import eu.mihosoft.vrl.v3d.Polygon; import eu.mihosoft.vrl.v3d.svg.SVGExporter; @@ -16,8 +18,16 @@ public class SvgLoader implements IScriptingLanguage { @Override public Object inlineScriptRun(File code, ArrayList args) throws Exception { - SVGLoad s = new SVGLoad(code.toURI()); - return run(s); + try { + SVGLoad s = new SVGLoad(code.toURI()); + return run(s); + }catch(Exception e) { + e.printStackTrace(); + com.neuronrobotics.sdk.common.Log.error("SVG had error, attempting to fix "+code.getAbsolutePath()); + File tmp=GeometrySimplification.simplifySVG(code); + SVGLoad s = new SVGLoad(tmp.toURI()); + return run(s); + } } @Override @@ -40,9 +50,11 @@ private Object run(SVGLoad s) { double depth =5+(layers.size()*5); for(int i=0;i extrudeLayerToCSG = s.extrudeLayer(depth,layerName); //extrudeLayerToCSG.setColor(Color.web(SVGExporter.colorNames.get(i))); - polys.add(extrudeLayerToCSG); + polys.addAll(extrudeLayerToCSG); depth-=5; } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/AbstractAddFrom.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/AbstractAddFrom.java new file mode 100644 index 000000000..e24627312 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/AbstractAddFrom.java @@ -0,0 +1,48 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.io.File; +import java.nio.file.NoSuchFileException; +import java.util.HashSet; + +import com.google.gson.annotations.Expose; + +public abstract class AbstractAddFrom implements ICaDoodleOpperation { + @Expose (serialize = false, deserialize = false) + protected HashSet namesAdded = new HashSet<>(); + @Expose (serialize = false, deserialize = false) + protected int nameIndex = 0; + @Expose(serialize = true, deserialize = true) + protected String name = null; + public HashSet getNamesAdded() { + return namesAdded; + } + public String getName() { + if (name == null) { + setName(RandomStringFactory.generateRandomString()); + } + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getOrderedName() { + if(getName()==null) { + setName(RandomStringFactory.generateRandomString()); + } + String result= getName(); + if(nameIndex!=0){ + result+= "_"+nameIndex; + } + nameIndex++; + namesAdded.add(result); + return result; + } + + public abstract File getFile()throws NoSuchFileException; + @Override + public String toString() { + return getType()+" with name "+getName(); + } +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/AddFromFile.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/AddFromFile.java new file mode 100644 index 000000000..9251ea907 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/AddFromFile.java @@ -0,0 +1,234 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Random; +import java.util.stream.Collectors; + +import com.google.gson.annotations.Expose; +import com.neuronrobotics.bowlerstudio.physics.TransformFactory; +import com.neuronrobotics.bowlerstudio.scripting.DownloadManager; +import com.neuronrobotics.bowlerstudio.scripting.ScriptingEngine; +import com.neuronrobotics.bowlerstudio.vitamins.VitaminBomManager; +import com.neuronrobotics.sdk.addons.kinematics.VitaminLocation; +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.Transform; +import eu.mihosoft.vrl.v3d.parametrics.CSGDatabase; +import eu.mihosoft.vrl.v3d.parametrics.StringParameter; + +public class AddFromFile extends AbstractAddFrom implements ICaDoodleOpperation { + @Expose(serialize = true, deserialize = true) + private TransformNR location = null; + private ArrayList options = new ArrayList(); + @Expose(serialize = true, deserialize = true) + private Boolean preventBoM =false; + public AddFromFile set(File source) { + for(String s:ScriptingEngine.getAllExtentions()) { + if(source.getName().toLowerCase().endsWith(s.toLowerCase())) { + toLocal(source,getName()); + return this; + } + } + throw new RuntimeException("File Extention not supported: "+source.getName()); + } + + @Override + public String getType() { + return "Add Object"; + } + + @Override + public List process(List incoming) { + nameIndex = 0; + ArrayList back = new ArrayList(); + back.addAll(incoming); + if (getName() == null) { + + } + try { +// ArrayListargs = new ArrayList<>(); +// args.addAll(Arrays.asList(getName() )); + ArrayList collect = new ArrayList<>(); + File file = getFile(); + if(!file.exists()) { + throw new RuntimeException("Failed to find file"); + } + + ArrayListargs = new ArrayList<>(); + args.addAll(Arrays.asList(name )); + HashMap configs =new HashMap(); + configs.put("name", name); + configs.put("PreventBomAdd", preventBoM); + args.add(configs); + List flattenedCSGs = ScriptingEngine.flaten(file, CSG.class, args); + for (int i = 0; i < flattenedCSGs.size(); i++) { + CSG csg = flattenedCSGs.get(i); + try { + CSG processedCSG = processGiven(csg, i, getOrderedName()); + collect.add(processedCSG); + }catch(Exception ex) { + ex.printStackTrace(); + } + } + back.addAll(collect); +// VitaminBomManager boM = CaDoodleFile.getBoM(); +// VitaminLocation loc = boM.getByName(name); +// if(loc!=null) { +// loc.setLocation(location); +// boM.save(); +// } + } catch (Exception e) { + // Auto-generated catch block + e.printStackTrace(); + } + return back; + } + + public static File copyFileToNewDirectory(File sourceFile, File targetDirectory, String newBaseName) + throws IOException { + if (!sourceFile.exists()) { + throw new IOException("Source file does not exist: " + sourceFile.getAbsolutePath()); + } + + if (!targetDirectory.exists()) { + if (!targetDirectory.mkdirs()) { + throw new IOException("Failed to create target directory: " + targetDirectory.getAbsolutePath()); + } + } + + String fileName = sourceFile.getName(); + String fileExtension = ""; + int dotIndex = fileName.lastIndexOf('.'); + if (dotIndex > 0 && dotIndex < fileName.length() - 1) { + fileExtension = fileName.substring(dotIndex); + } + + String newFileName = newBaseName + fileExtension; + File targetFile = new File(targetDirectory, newFileName); + + Path sourcePath = sourceFile.toPath(); + Path targetPath = targetFile.toPath(); + + Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); + return targetFile; + } + public static File toLocal(File file, String name) { + StringParameter loc = new StringParameter("CaDoodle_File_Location", "NotSet", new ArrayList()); + File parentFileIncoming = file.getParentFile(); + File parentFile = new File(loc.getStrValue()).getParentFile(); +// if(parentFile==null) +// try { +// parentFile=File.createTempFile(name, name).getParentFile(); +// } catch (IOException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } + String source = parentFile.getAbsolutePath(); + if (parentFileIncoming != null) { + String parentIncoming = parentFileIncoming.getAbsolutePath(); + + String lowerCase = parentIncoming.toLowerCase(); + String lowerCase2 = source.toLowerCase(); + boolean b = !lowerCase.contentEquals(lowerCase2); + boolean exists = file.exists(); + if (b && exists) { + File copied; + try { + copied = copyFileToNewDirectory(file, parentFile, name); + file = copied; + } catch (IOException e) { + // Auto-generated catch block + e.printStackTrace(); + } + } + } + file = new File(source + DownloadManager.delim() + file.getName()); + return file; + } + + public static File getFile(String name) { + StringParameter loc = new StringParameter("CaDoodle_File_Location", "NotSet", new ArrayList()); + File parentFile = new File(loc.getStrValue()).getParentFile(); + for(String f:parentFile.list()) { + if(f.contains(name)) { + for(String s:ScriptingEngine.getAllExtentions()) { + if(f.toLowerCase().endsWith(s.toLowerCase())) { + String pathname = parentFile.getAbsolutePath() + DownloadManager.delim() + f; + return new File(pathname); + } + } + } + } + throw new RuntimeException("File not found! "+name); + } +// +// private String getStrValue() { +// +// return getParameter("UnKnown").getStrValue(); +// } + + private CSG processGiven(CSG csg, int i, String n) { + Transform nrToCSG = TransformFactory.nrToCSG(getLocation()); + String pathname = getFile(this.name).getAbsolutePath(); + + StringParameter parameter=new StringParameter(n + "_CaDoodle_File", pathname, options); + parameter.setStrValue(pathname); + CSG processedCSG = csg +// .moveToCenterX() +// .moveToCenterY() +// .toZMin() + .transformed(nrToCSG).syncProperties(csg).setParameter(parameter) + .setRegenerate(previous -> { + try { + File file = getFile(); + String fileLocation = file.getAbsolutePath(); + com.neuronrobotics.sdk.common.Log.error("Regenerating " + fileLocation); + List flattenedCSGs = ScriptingEngine.flaten(file, CSG.class, null); + CSG csg1 = flattenedCSGs.get(i); + return processGiven(csg1, i, n); + } catch (Exception e) { + e.printStackTrace(); + } + return previous; + }).setName(n); + MoveCenter.set(getName(), processedCSG, nrToCSG); + return processedCSG; + } + + public TransformNR getLocation() { + if (location == null) + location = new TransformNR(); + return location; + } + + public AddFromFile setLocation(TransformNR location) { + this.location = location; + return this; + } + + + + public Boolean getPreventBoM() { + return preventBoM; + } + + public AddFromFile setPreventBoM(Boolean preventBoM) { + this.preventBoM = preventBoM; + return this; + } + + @Override + public File getFile() throws NoSuchFileException { + return AddFromFile.getFile(name); + } +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/AddFromScript.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/AddFromScript.java new file mode 100644 index 000000000..9242e2f93 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/AddFromScript.java @@ -0,0 +1,130 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.stream.Collectors; + +import org.eclipse.jgit.api.errors.GitAPIException; + +import com.google.gson.annotations.Expose; +import com.neuronrobotics.bowlerstudio.assets.ConfigurationDatabase; +import com.neuronrobotics.bowlerstudio.physics.TransformFactory; +import com.neuronrobotics.bowlerstudio.scripting.ScriptingEngine; +import com.neuronrobotics.bowlerstudio.vitamins.VitaminBomManager; +import com.neuronrobotics.sdk.addons.kinematics.VitaminLocation; +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.Transform; + +public class AddFromScript extends AbstractAddFrom implements ICaDoodleOpperation { + @Expose(serialize = true, deserialize = true) + private String gitULR = ""; + @Expose(serialize = true, deserialize = true) + private String fileRel = ""; + + @Expose(serialize = true, deserialize = true) + private TransformNR location =null; + @Expose(serialize = true, deserialize = true) + private Boolean preventBoM = false; + + public AddFromScript set(String git, String f) { + gitULR = git; + fileRel = f; + return this; + } + + @Override + public String getType() { + return "Add Object"; + } + + @Override + public List process(List incoming) { + return process(incoming, fileRel); + } + + public List process(List incoming, String fileName) { + + nameIndex = 0; + ArrayList back = new ArrayList(); + back.addAll(incoming); + + try { + ArrayList args = new ArrayList<>(); + args.addAll(Arrays.asList(getName())); + HashMap configs = new HashMap(); + configs.put("name", getName()); + configs.put("PreventBomAdd", preventBoM); + args.add(configs); + List flaten = ScriptingEngine.flaten(gitULR, fileName, CSG.class, args); + ArrayList collect = new ArrayList<>(); + collect.addAll(flaten); + for(int i=0;i names = new ArrayList(); + @Expose (serialize = true, deserialize = true) + public Allignment z=null; + @Expose (serialize = true, deserialize = true) + public Allignment y=null; + @Expose (serialize = true, deserialize = true) + public Allignment x=null; + @Expose (serialize = true, deserialize = true) + private TransformNR workplane=null; + @Expose (serialize = true, deserialize = true) + public StoragbeBounds bounds=null; + @Expose(serialize = true, deserialize = true) + protected String name = null; + public String getName() { + if (name == null) { + setName(RandomStringFactory.generateRandomString()); + } + return name; + } + + public void setName(String name) { + this.name = name; + } + @Override + public String getType() { + return "Allign"; + } + + @Override + public String toString(){ + String string = getType()+" "+x+" "+y+" "+z; + for(String n:getNames()) { + string+=" "+n; + } + return string; + } + + @Override + public List process(List incoming) { + ArrayList back = new ArrayList(); + back.addAll(incoming); + + Bounds bounds2 ;// + if(bounds!=null) { + bounds2=bounds.getBounds(); + }else { + throw new RuntimeException("Allign can not be initialized without bounds!"); + } + HashMap moves= new HashMap<>(); + for(String name :names) { + for(CSG tmp:back) { + if(!tmp.getName().contentEquals(name)) + continue; + CSG c = tmp.transformed(TransformFactory.nrToCSG(getWorkplane()).inverse()); + TransformNR tf = performTransform(bounds2, c); + moves.put(c.getName(),tf); + } + } + for(String name:moves.keySet()) { + TransformNR wpinv = getWorkplane().inverse(); + TransformNR nr = moves.get(name); + TransformNR wp = getWorkplane(); + + TransformNR times = wp.times(nr.times(wpinv)); + Transform tf = TransformFactory.nrToCSG(times); + CaDoodleFile.applyToAllConstituantElements(false, name, back, (incoming1, depth) ->{ + ArrayList b = new ArrayList<>(); + CSG c=incoming1.transformed(tf); + sync(incoming1,c); + MoveCenter.set(getName() , c, times); + b.add(c); + return b; + }, 1); + } + return back; + } + +// private void collectToMove(ArrayList toMove, ArrayList back, String name) { +// ArrayList toSearch = new ArrayList(); +// toSearch.addAll(back); +// for (int i = 0; i < toSearch.size(); i++) { +// CSG c = toSearch.get(i); +// if(name.contentEquals(c.getName())) { +// toMove.add(c); +// } +// } +// } + + private TransformNR performTransform(Bounds reference, CSG incoming) { + //CSG c = incoming; + double tx=0,ty=0,tz=0; + if(z!=null) { + switch(z) { + case negative: + tz=-incoming.getMinZ()+reference.getMinZ(); + break; + case middle: + tz=-incoming.getCenterZ()+reference.getCenterZ(); + break; + case positive: + tz=-incoming.getMaxZ()+reference.getMaxZ(); + break; + default: + break; + } + } + if(x!=null) { + switch(x) { + case negative: + tx=-incoming.getMinX()+reference.getMinX(); + break; + case middle: + tx=-incoming.getCenterX()+reference.getCenterX(); + break; + case positive: + tx=-incoming.getMaxX()+reference.getMaxX(); + break; + default: + break; + + } + } + if(y!=null) { + switch(y) { + case negative: + ty=-incoming.getMinY()+reference.getMinY(); + break; + case middle: + ty=-incoming.getCenterY()+reference.getCenterY(); + break; + case positive: + ty=-incoming.getMaxY()+reference.getMaxY(); + break; + default: + break; + + } + } + return new TransformNR(tx,ty,tz); + } + + private CSG sync(CSG incoming, CSG c) { + return c.syncProperties(incoming).setName(incoming.getName()).setColor(incoming.getColor()); + } + + public List getNames() { + return names; + } + + public Allign setNames(List names) { + this.names = names; + return this; + } + public Allign setAllignParams(Allignment X, Allignment Y,Allignment Z) { + x=X; + y=Y; + z=Z; + return this; + } + + public TransformNR getWorkplane() { + if(workplane==null) + workplane= new TransformNR(); + return workplane; + } + + public Allign setWorkplane(TransformNR workplane) { + this.workplane = workplane; + return this; + } + + public Bounds getBounds() { + return bounds.getBounds(); + } + + public Allign setBounds(Bounds bounds) { + this.bounds = new StoragbeBounds(bounds); + return this; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Allignment.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Allignment.java new file mode 100644 index 000000000..e2759593a --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Allignment.java @@ -0,0 +1,7 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +public enum Allignment { + positive, + negative, + middle, +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/CaDoodleFile.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/CaDoodleFile.java new file mode 100644 index 000000000..41710687f --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/CaDoodleFile.java @@ -0,0 +1,876 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Type; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; + +import javax.imageio.ImageIO; +import javafx.scene.image.WritableImage; +import org.apache.commons.io.FileUtils; +import org.python.google.common.io.Files; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.annotations.Expose; +import com.google.gson.reflect.TypeToken; +import com.neuronrobotics.bowlerstudio.BowlerKernel; +import com.neuronrobotics.bowlerstudio.creature.ThumbnailImage; +import com.neuronrobotics.bowlerstudio.physics.TransformFactory; +import com.neuronrobotics.bowlerstudio.scripting.DownloadManager; +import com.neuronrobotics.bowlerstudio.scripting.ScriptingEngine; +import com.neuronrobotics.bowlerstudio.vitamins.VitaminBomManager; +import com.neuronrobotics.sdk.addons.kinematics.VitaminLocation; +import com.neuronrobotics.sdk.addons.kinematics.math.RotationNR; +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.Polygon; +import eu.mihosoft.vrl.v3d.PropertyStorage; +import eu.mihosoft.vrl.v3d.parametrics.CSGDatabase; +import eu.mihosoft.vrl.v3d.parametrics.IParametric; +import eu.mihosoft.vrl.v3d.parametrics.Parameter; +import eu.mihosoft.vrl.v3d.parametrics.StringParameter; +import javafx.embed.swing.SwingFXUtils; + +import static com.neuronrobotics.bowlerstudio.scripting.DownloadManager.*; + +public class CaDoodleFile { + public static final String NO_NAME = "NoName"; + @Expose(serialize = true, deserialize = true) + private ArrayList opperations = new ArrayList(); + @Expose(serialize = true, deserialize = true) + private int currentIndex = 0; + @Expose(serialize = true, deserialize = true) + private long timeCreated = -1; + @Expose(serialize = true, deserialize = true) + private String projectName = NO_NAME; + @Expose(serialize = true, deserialize = true) + private TransformNR rulerLocation = new TransformNR(); + @Expose(serialize = true, deserialize = true) + private TransformNR workplane = new TransformNR(); + @Expose(serialize = false, deserialize = false) + private File selfInternal; +// @Expose (serialize = false, deserialize = false) +// private List currentState = new ArrayList(); + @Expose(serialize = false, deserialize = false) + private double percentInitialized = 0; + @Expose(serialize = false, deserialize = false) + private HashMap> cache = new HashMap>(); + private static Type TT_CaDoodleFile = new TypeToken() { + }.getType(); + private static Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting() + .excludeFieldsWithoutExposeAnnotation().registerTypeAdapterFactory(new ICaDoodleOperationAdapterFactory()) + .create(); + private ArrayList listeners = new ArrayList(); + private Thread opperationRunner = null; + private boolean regenerating; + private CopyOnWriteArrayList toProcess = new CopyOnWriteArrayList(); + private javafx.scene.image.WritableImage img; + private boolean initializing; + private static HashMap bomManagers = new HashMap<>(); + private VitaminBomManager bom; + + public void close() { + for (ICaDoodleOpperation op : cache.keySet()) { + cache.get(op).clear(); + } + cache.clear(); + cache = null; + clearListeners(); + listeners = null; + toProcess.clear(); + toProcess = null; + img = null; + if (opperationRunner != null) + opperationRunner.interrupt(); + opperationRunner = null; + } + + public CaDoodleFile clearListeners() { + listeners.clear(); + return this; + } + + public CaDoodleFile removeListener(ICaDoodleStateUpdate l) { + if (listeners.contains(l)) + listeners.remove(l); + return this; + } + + public CaDoodleFile addListener(ICaDoodleStateUpdate l) { + if (!listeners.contains(l)) + listeners.add(l); + return this; + } + + public void initialize() { +// if (initializing) +// throw new RuntimeException("Can not initialize while initializing."); + fireInitializationStart(); + initializing = true; + if (selfInternal != null) { + File parent = selfInternal.getAbsoluteFile().getParentFile(); + File imageCacheDir = new File(parent.getAbsolutePath() + delim() + "timeline"); + if (!imageCacheDir.exists()) + imageCacheDir.mkdir(); + File db = new File(selfInternal.getAbsoluteFile().getParent() + delim() + "CSGdatabase.json"); + try { + // set a temp file for the database to clear + // this ensures that parameters are not cleared from another project :/ + File createTempFile = File.createTempFile(projectName, ".json"); + CSGDatabase.setDbFile(createTempFile); + CSGDatabase.clear(); + createTempFile.delete(); + } catch (IOException e) { + // Auto-generated catch block + e.printStackTrace(); + } + CSGDatabase.setDbFile(db); + StringParameter loc = new StringParameter("CaDoodle_File_Location", selfInternal.getAbsolutePath(), + new ArrayList()); + loc.setStrValue(selfInternal.getAbsolutePath()); + bom = CaDoodleFile.getBillOfMaterials(); + bom.clear(); + bom.save(); + + } + int indexStarting = getCurrentIndex(); + setCurrentIndex(0); + setPercentInitialized(0); + for (int i = 0; i < opperations.size(); i++) { + ICaDoodleOpperation op = opperations.get(i); + setPercentInitialized(((double) i) / (double) opperations.size()); + try { + process(op); + } catch (Throwable t) { + t.printStackTrace(); + pruneForward(); + indexStarting = i; + break; + } + } + setCurrentIndex(indexStarting); + updateCurrentFromCache(); + loadImageFromFile(); + setPercentInitialized(1); + for (ICaDoodleStateUpdate l : listeners) { + try { + l.onInitializationDone(); + } catch (Throwable e) { + e.printStackTrace(); + } + } + updateBoM(); + initializing = false; + } + + private void updateBoM() { + if (bom == null) + return; + bom.clear(); + bom.save(); + for (CSG c : getCurrentState()) { + String type = null; + String size = null; + for (String param : c.getParameters()) { + if (!param.contains(c.getName())) + continue; + if (param.contains("_CaDoodle_Vitamin_Type")) { + Parameter p = CSGDatabase.get(param); + type = p.getStrValue(); + } + if (param.contains("_CaDoodle_Vitamin_Size")) { + Parameter p = CSGDatabase.get(param); + size = p.getStrValue(); + } + if (type != null && size != null) { + bom.addVitamin(new VitaminLocation(false, c.getName(), type, size, new TransformNR())); + break; + } + } + } + bom.save(); + } + + public static VitaminBomManager getBillOfMaterials() { + + String strValue = getCadoodleFileLocation(); + File file = new File(strValue).getParentFile(); + if (bomManagers.get(strValue) == null) { + bomManagers.put(strValue, new VitaminBomManager(file)); + } + return bomManagers.get(strValue); + } + + private static String getCadoodleFileLocation() { + StringParameter loc = new StringParameter("CaDoodle_File_Location", "", new ArrayList()); + String strValue = loc.getStrValue(); + return strValue; + } + + public Thread regenerateFrom(ICaDoodleOpperation source) { + if (initializing) + return null; + if (isRegenerating() || isOperationRunning()) { + com.neuronrobotics.sdk.common.Log.error("Opperation is running, ignoring regen"); + return null; + } + fireRegenerateStart(); + int endIndex = getCurrentIndex(); + double size = opperations.size(); + if (endIndex != size) { +// new Exception("Regenerationg from a position back in time " + endIndex + " but have " + size) +// .printStackTrace(); + } + opperationRunner = new Thread(() -> { + opperationRunner.setName("Regeneration Thread"); + setRegenerating(true); + // com.neuronrobotics.sdk.common.Log.error("Regenerating Object from + // "+source.getType()); + int opIndex = 0; + for (int i = 0; i < size; i++) { + ICaDoodleOpperation op = opperations.get(i); + if (source == op) { + opIndex = i; + break; + } + } + setCurrentIndex(opIndex); + try { + for (; getCurrentIndex() < size;) { + setCurrentIndex(getCurrentIndex() + 1); + setPercentInitialized(((double) getCurrentIndex()) / size); + // com.neuronrobotics.sdk.common.Log.error("Regenerating "+currentIndex); + int currentIndex2 = getCurrentIndex() - 1; + ICaDoodleOpperation op = opperations.get(currentIndex2); + List process = op.process(getPreviouState()); + getTimelineImageFile(currentIndex2).delete(); + try { + setTimelineImage(process, currentIndex2); + } catch (IOException e) { + // Auto-generated catch block + e.printStackTrace(); + } + storeResultInCache(op, process); + setCurrentState(op, process); + } + if (getCurrentIndex() != endIndex) { + setCurrentIndex(endIndex); + updateCurrentFromCache(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + setPercentInitialized(1); + updateBoM(); + setRegenerating(false); + fireSaveSuggestion(); + opperationRunner = null; + fireRegenerateDone(); + }); + opperationRunner.start(); + return opperationRunner; + } + + public Thread regenerateCurrent() { + if (isOperationRunning()) { + return opperationRunner; + } + if (initializing) { + Thread t = new Thread(); + t.start(); + return t; + } + fireRegenerateStart(); + opperationRunner = new Thread(() -> { + opperationRunner.setName("regenerateCurrent Thread"); + + ICaDoodleOpperation op = getCurrentOpperation(); + List process = op.process(getPreviouState()); + int currentIndex2 = getCurrentIndex(); + getTimelineImageFile(currentIndex2).delete(); + try { + setTimelineImage(process, currentIndex2); + } catch (IOException e) { + // Auto-generated catch block + e.printStackTrace(); + } + storeResultInCache(op, process); + setCurrentState(op, process); + fireSaveSuggestion(); + opperationRunner = null; + fireRegenerateDone(); + }); + opperationRunner.start(); + return opperationRunner; + + } + + private void process(ICaDoodleOpperation op) { + List process = op.process(getCurrentState()); + int currentIndex2 = getCurrentIndex(); + try { + setTimelineImage(process, currentIndex2); + } catch (IOException e) { + // Auto-generated catch block + e.printStackTrace(); + } + storeResultInCache(op, process); + setCurrentIndex(currentIndex2 + 1); + setCurrentState(op, process); + } + + public boolean isOperationRunning() { + if (opperationRunner != null) + if (!opperationRunner.isAlive()) + opperationRunner = null; + return opperationRunner != null; + } + + public Thread addOpperation(ICaDoodleOpperation o) throws CadoodleConcurrencyException { + toProcess.add(o); + if (isOperationRunning()) { + + return opperationRunner; + } + opperationRunner = new Thread(() -> { + while (toProcess.size() > 0) { + opperationRunner.setName("addOpperation Thread " + toProcess.size()); + ICaDoodleOpperation op = toProcess.remove(0); + if (getCurrentIndex() != getOpperations().size()) { + pruneForward(); + } + try { + getOpperations().add(op); + process(op); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + updateBoM(); + fireSaveSuggestion(); + opperationRunner = null; + }); + opperationRunner.start(); + return opperationRunner; + } + + public static CSG getByName(List back, String name) { + for (CSG c : back) { + if (c.getName().contentEquals(name)) + return c; + } + throw new RuntimeException("Fail! there was no object named " + name); + } + + public static int applyToAllConstituantElements(boolean addRet, List targetNames, ArrayList back, + ICadoodleRecursiveEvent p, int depth) { + for (int i = 0; i < targetNames.size(); i++) { + String s = targetNames.get(i); + CSG c = getByName(back, s); + if (c.isInGroup()) + continue; + applyToAllConstituantElements(addRet, s, back, p, depth); + } + return back.size(); + } + + public static int applyToAllConstituantElements(boolean addRet, String targetName, ArrayList back, + ICadoodleRecursiveEvent p, int depth) { + ArrayList immutable = new ArrayList<>(); + immutable.addAll(back); + for (int i = 0; i < immutable.size(); i++) { + CSG csg = immutable.get(i); + if (csg.isLock()) + continue; + // boolean inGroup = csg.isInGroup(); + boolean thisCSGIsInGroupNamedAfterTarget = csg.checkGroupMembership(targetName); + String thisCSGName = csg.getName(); + boolean thisCSGIsTheTarget = thisCSGName.contentEquals(targetName); + boolean groupResult = csg.isGroupResult(); + + if (thisCSGIsTheTarget) { + // move it + ArrayList tmpToAdd = p.process(csg, depth); + if (addRet) { + back.addAll(tmpToAdd); + } else { + for (int j = 0; j < back.size(); j++) { + if (back.get(j).getName().contentEquals(csg.getName())) { + back.remove(j); + break; + } + } + back.addAll(tmpToAdd); + } + continue; + } + if (thisCSGIsInGroupNamedAfterTarget) { + // composite group + applyToAllConstituantElements(addRet, thisCSGName, back, p, depth + 1); + } + } + back.removeAll(Collections.singleton(null)); + return back.size(); + } + + public File getTimelineImageFile(ICaDoodleOpperation test) { + for (int i = 0; i < getOpperations().size(); i++) { + ICaDoodleOpperation key = getOpperations().get(i); + if (key == test) { + File file = getTimelineImageFile(i); + return file; + } + } + throw new RuntimeException("File not found!"); + } + + public File getTimelineImageFile(int i) { + File parent = selfInternal.getAbsoluteFile().getParentFile(); + File file = new File(parent.getAbsolutePath() + delim() + "timeline" + delim() + (i + 1) + ".png"); + return file; + } + + private void pruneForward() { + for (int i = getCurrentIndex(); i < getOpperations().size(); i++) { + ICaDoodleOpperation key = getOpperations().get(i); + List back = cache.remove(key); + if (back != null) + back.clear(); + File imageCache = getTimelineImageFile(i); + //System.err.println("Deleting " + imageCache.getAbsolutePath()); + imageCache.delete(); + } + List subList = (List) getOpperations().subList(0, getCurrentIndex()); + ArrayList newList = new ArrayList(); + newList.addAll(subList); + setOpperations(newList); + com.neuronrobotics.sdk.common.Log.error("Pruning forward here!"); + } + + private void storeResultInCache(ICaDoodleOpperation op, List process) { + ArrayList cachedCopy = new ArrayList(); + HashSet names = new HashSet<>(); + for (CSG c : process) { + if (names.contains(c.getName())) + throw new RuntimeException( + "There can not be 2 objects with the same name after an opperation! " + c.getName()); + names.add(c.getName()); + cachedCopy.add(cloneCSG(c).setStorage(new PropertyStorage()).syncProperties(c).setName(c.getName()) + .setRegenerate(c.getRegenerate())); + // cachedCopy.add(c); + } + cache.put(op, cachedCopy); + } + + private CSG cloneCSG(CSG dyingCSG) { + CSG csg = new CSG(); + + ArrayList collect = new ArrayList(); + for (Polygon p : dyingCSG.getPolygons()) { + if (p == null) + continue; + try { + collect.add(p); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + csg.setPolygons(collect); + Set params = dyingCSG.getParameters(); + for (String param : params) { + boolean existing = false; + for (String s : csg.getParameters()) { + if (s.contentEquals(param)) + existing = true; + } + if (!existing) { + Parameter vals = CSGDatabase.get(param); + if (vals != null) + csg.setParameter(vals, dyingCSG.getMapOfparametrics().get(param)); + } + } + if (csg.getName().length() == 0) + csg.setName(dyingCSG.getName()); + csg.setColor(dyingCSG.getColor()); + return csg; + } + + public void back() { + if (isBackAvailible()) + setCurrentIndex(getCurrentIndex() - 1); + updateCurrentFromCache(); + fireSaveSuggestion(); + } + + public boolean isBackAvailible() { + return getCurrentIndex() > 1; + } + + private void updateCurrentFromCache() { + ICaDoodleOpperation key = getCurrentOpperation(); + if (key == null) + return; + com.neuronrobotics.sdk.common.Log.error("Current opperation results: " + key.getType()); + setCurrentState(key, getCurrentState()); + } + + public ICaDoodleOpperation getCurrentOpperation() { + if (getCurrentIndex() == 0) + return null; + return getOpperations().get(getCurrentIndex() - 1); + } + + public void forward() { + if (isForwardAvailible()) + setCurrentIndex(getCurrentIndex() + 1); + updateCurrentFromCache(); + fireSaveSuggestion(); + } + + public boolean isForwardAvailible() { + return getCurrentIndex() < getOpperations().size(); + } + + public File getSelf() { + if (selfInternal == null) { + try { + selfInternal = File.createTempFile(DownloadManager.sanitizeString(projectName), ".doodle"); + } catch (IOException e) { + // Auto-generated catch block + e.printStackTrace(); + } + } + return selfInternal; + } + + public CaDoodleFile setSelf(File self) { + this.selfInternal = self; + return this; + } + + public List getCurrentState() { + if (getCurrentIndex() == 0) + return new ArrayList(); + List list = cache.get(getCurrentOpperation()); + if (list == null) + list = new ArrayList(); + return list; + } + + public List getSelect(List selectedSnapshot) { + List cur = getCurrentState(); + ArrayList back = new ArrayList(); + if (cur != null) + for (CSG c : cur) { + for (String s : selectedSnapshot) { + if (c.getName().contentEquals(s)) { + back.add(c); + } + } + } + return back; + } + + public List getPreviouState() { + if (getCurrentIndex() < 2) + return new ArrayList(); + return cache.get(getOpperations().get(getCurrentIndex() - 2)); + } + + private void setCurrentState(ICaDoodleOpperation op, List currentState) { + for (ICaDoodleStateUpdate l : listeners) { + try { + l.onUpdate(currentState, op, this); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + private void fireSaveSuggestion() { + + for (ICaDoodleStateUpdate l : listeners) { + try { + l.onSaveSuggestion(); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + private void fireInitializationStart() { + + for (ICaDoodleStateUpdate l : listeners) { + try { + l.onInitializationStart(); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + private void fireRegenerateDone() { + + for (ICaDoodleStateUpdate l : listeners) { + try { + l.onRegenerateDone(); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + private void fireRegenerateStart() { + + for (ICaDoodleStateUpdate l : listeners) { + try { + l.onRegenerateStart(); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + private void fireWorkplaneChange() { + + for (ICaDoodleStateUpdate l : listeners) { + try { + l.onWorkplaneChange(workplane); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + public String getMyProjectName() { + return projectName; + } + + public CaDoodleFile setProjectName(String projectName) { + this.projectName = projectName; + return this; + } + + public String toJson() { + String ret = null; + synchronized (this) { + ret = gson.toJson(this); + } + return ret; + } + + public File save() throws IOException { + + synchronized (selfInternal) { + String contents = toJson(); + List currentState = getCurrentState(); + int currentIndex2 = getCurrentIndex(); + FileUtils.write(selfInternal, contents, StandardCharsets.UTF_8, false); + setTimelineImage(currentState, currentIndex2); + if (bom != null) + bom.save(); + } + + return getSelf(); + } + + private void setTimelineImage(List currentState, int currentIndex2) throws IOException { + if(selfInternal==null) + return; + if(currentIndex2==0) + return; + File parent = selfInternal.getAbsoluteFile().getParentFile(); + File imageCache = new File(parent.getAbsolutePath() + delim() + "timeline" + delim() + currentIndex2 + ".png"); + File image = new File(parent.getAbsolutePath() + delim() + "snapshot.png"); + + if (imageCache.exists()) + return; + WritableImage image2 = loadingImageFromUIThread(currentState); + if (image2 != null) { + BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image2, null); + try { + ImageIO.write(bufferedImage, "png", imageCache); + System.err.println("Thumbnail saved successfully to " + imageCache.getAbsolutePath()); + } catch (IOException e) { + // com.neuronrobotics.sdk.common.Log.error("Error saving image: " + + // e.getMessage()); + e.printStackTrace(); + } + + if (currentIndex2 == currentIndex) { + Files.copy(imageCache, image); + } + + } + } + + public WritableImage loadImageFromFile() { + try { + File parent = selfInternal.getAbsoluteFile().getParentFile(); + File image = new File(parent.getAbsolutePath() + delim() + "snapshot.png"); + if (image.exists()) { + BufferedImage bufferedImage = ImageIO.read(image); + if (bufferedImage != null) { + img = SwingFXUtils.toFXImage(bufferedImage, null); + } + } else { + loadingImageFromUIThread(getCurrentState()); + } + } catch (Exception e) { + com.neuronrobotics.sdk.common.Log.error("Error loading image: " + e.getMessage()); + e.printStackTrace(); + } + return img; + } + + private javafx.scene.image.WritableImage loadingImageFromUIThread(List currentState) { + ArrayList holder = new ArrayList(); + try { + BowlerKernel.runLater(() -> { + holder.add(ThumbnailImage.get(currentState)); + }); + } catch (Throwable ex) { + ex.printStackTrace(); + return null; + } + while (holder.size() == 0) + try { + Thread.sleep(16); + // com.neuronrobotics.sdk.common.Log.error("Waiting for image to write"); + } catch (InterruptedException e) { + // Auto-generated catch block + e.printStackTrace(); + break; + } + return holder.get(0); + } + + public static CaDoodleFile fromJsonString(String content) throws Exception { + return fromJsonString(content, null, null, true); + } + + public static CaDoodleFile fromJsonString(String content, ICaDoodleStateUpdate listener, File self, + boolean initialize) throws Exception { + CaDoodleFile file = gson.fromJson(content, TT_CaDoodleFile); + if (file == null) { + file = new CaDoodleFile(); + file.setProjectName(RandomStringFactory.getNextRandomName()); + file.getTimeCreated(); + } + if (listener != null) { + file.addListener(listener); + } + if (self != null) { + file.setSelf(self); + } + if (initialize) { + file.initialize(); + } + return file; + } + + public static CaDoodleFile fromFile(File f) throws Exception { + return fromFile(f, null, true); + } + + public static String getProjectName(File f) throws Exception { + com.neuronrobotics.sdk.common.Log.error("CaDoodle file reading from " + f.getAbsolutePath()); + String content = FileUtils.readFileToString(f, StandardCharsets.UTF_8); + CaDoodleFile file = fromJsonString(content, null, f, false); + return file.getMyProjectName(); + } + + public static CaDoodleFile fromFile(File f, ICaDoodleStateUpdate listener, boolean initialize) throws Exception { + com.neuronrobotics.sdk.common.Log.error("CaDoodle file loading from " + f.getAbsolutePath()); + String content = FileUtils.readFileToString(f, StandardCharsets.UTF_8); + CaDoodleFile file = fromJsonString(content, listener, f, initialize); + return file; + } + + public ArrayList getOpperations() { + return opperations; + } + + public void setOpperations(ArrayList opperations) { + this.opperations = opperations; + } + + public TransformNR getWorkplane() { + if (workplane == null) + workplane = new TransformNR(); + return workplane; + } + + public void setWorkplane(TransformNR workplane) { + this.workplane = workplane; + fireWorkplaneChange(); + fireSaveSuggestion(); + } + + public int getCurrentIndex() { + return currentIndex; + } + + public void setCurrentIndex(int currentIndex) { + // new Exception("Current Index set to " + currentIndex).printStackTrace(); + if ((currentIndex - 1) >= opperations.size()) + throw new RuntimeException("Fail! Can not set an index greater than the availible operations"); + this.currentIndex = currentIndex; + } + + public javafx.scene.image.WritableImage getImage() { + return img; + } + + public javafx.scene.image.WritableImage setImage(javafx.scene.image.WritableImage img) { + this.img = img; + return img; + } + + public double getPercentInitialized() { + return percentInitialized; + } + + public void setPercentInitialized(double percentInitialized) { + this.percentInitialized = percentInitialized; + } + + public long getTimeCreated() { + if (timeCreated < 0) { + timeCreated = System.currentTimeMillis(); + } + return timeCreated; + } + + public boolean isRegenerating() { + return regenerating; + } + + private void setRegenerating(boolean regenerating) { + this.regenerating = regenerating; + } + + public TransformNR getRulerLocation() { + return rulerLocation; + } + + public void setRulerLocation(TransformNR rulerLocation) { + rulerLocation.setRotation(new RotationNR()); + this.rulerLocation = rulerLocation; + fireWorkplaneChange(); + fireSaveSuggestion(); + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/CaDoodleVitamin.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/CaDoodleVitamin.java new file mode 100644 index 000000000..6fca1af85 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/CaDoodleVitamin.java @@ -0,0 +1,121 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Optional; +import java.util.Set; + +import com.neuronrobotics.bowlerstudio.vitamins.Vitamins; +import com.neuronrobotics.sdk.addons.kinematics.VitaminLocation; +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.parametrics.CSGDatabase; +import eu.mihosoft.vrl.v3d.parametrics.IRegenerate; +import eu.mihosoft.vrl.v3d.parametrics.Parameter; +import eu.mihosoft.vrl.v3d.parametrics.StringParameter; + +public class CaDoodleVitamin { + public static CSG get(String typencoming, ArrayList args) { + String name = args.get(0).toString(); + ArrayListtypes=new ArrayList<>(); + types.addAll(Vitamins.listVitaminTypes()); + StringParameter typeParam = new StringParameter(name + "_CaDoodle_Vitamin_Type", typencoming, + types); + String type=typeParam.getStrValue(); + ArrayList listVitaminSizes = Vitamins.listVitaminSizes(type); + return get( type, listVitaminSizes.get(0), args); + } + public static boolean isVitamin(CSG c) { + for(String s:c.getParameters()) { + if(s.contains("_CaDoodle_Vitamin_") && s.contains(c.getName())) { + return true; + } + } + return false; + } + public static CSG get(String typencoming,String defaultValue, ArrayList args) { + String name = args.get(0).toString(); + + ArrayListtypes=new ArrayList<>(); + types.addAll(Vitamins.listVitaminTypes()); + StringParameter typeParam = new StringParameter(name + "_CaDoodle_Vitamin_Type", typencoming, + types); + String type=typeParam.getStrValue(); + ArrayList listVitaminSizes = Vitamins.listVitaminSizes(type); + + StringParameter size = new StringParameter(type + " Default", defaultValue, listVitaminSizes); + + String strValue = size.getStrValue(); + if(strValue.length() == 0) { + size.setStrValue(listVitaminSizes.get(0)); + } + String string = "_CaDoodle_Vitamin_Size"; + StringParameter word = new StringParameter(name + string, strValue, + listVitaminSizes); + boolean sizeExists=false; + for(String s:Vitamins.listVitaminSizes(type)) { + if(s.contentEquals(word.getStrValue())) { + sizeExists=true; + break; + } + } + if(!sizeExists) { + + word.setStrValue(strValue); + } + size.setStrValue(word.getStrValue()); + if (args.size() > 1) { + HashMap object = (HashMap) args.get(1); + if (!(Boolean) object.get("PreventBomAdd")) { + +// VitaminLocation vl = new VitaminLocation(false, name, type, word.getStrValue(), new TransformNR()); +// //System.out.println("BoM update "+vl); +// CaDoodleFile.getBoM().addVitamin(vl, true); + } + } + CSG part; + try { +// System.out.println("Generating Vitamin "+type+" "+word.getStrValue()+" for vitamin named "+name); + part = Vitamins.get(type, word.getStrValue()).setIsHole(true); + CSGDatabase.saveDatabase(); + Set params = part.getParameters(); + + part.setParameter(word); + part.setParameter(typeParam); + params = part.getParameters(); + part.setName(name); +// System.out.println("Parameters on Vitamin: "+name); +// for(String s:params) { +// System.out.println("\t"+s); +// } + CSG back = part.setRegenerate(new IRegenerate() { + @Override + public CSG regenerate(CSG previous) { + Optional pv = previous.getStorage().getValue("PreviousName"); + String name2 = null; + if(pv.isPresent()) + name2=pv.get().toString(); + else + name2=name; + //System.out.println("Regenerating source \n\t"+name+" on part \n\t"+name2); + ArrayList ar = new ArrayList<>(); + ar.addAll(args); + ar.set(0, previous.getName()); + Parameter s = CSGDatabase.get(name2+"_CaDoodle_Vitamin_Size"); + Parameter t = CSGDatabase.get(name2+"_CaDoodle_Vitamin_Type"); + if(t==null) { + System.out.println(" Error, type is null, previous "+name2+" has no parameters somehow??"); + } + return CaDoodleVitamin.get(t.getStrValue(),s.getStrValue(), ar); + } + }); + //back.getStorage().set("PreviousName", name); + return back; + } catch (Exception e) { + // Auto-generated catch block + e.printStackTrace(); + } + throw new RuntimeException("Failed to load vitamin of type " + type); + } +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/CadoodleConcurrencyException.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/CadoodleConcurrencyException.java new file mode 100644 index 000000000..dcd132897 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/CadoodleConcurrencyException.java @@ -0,0 +1,11 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +public class CadoodleConcurrencyException extends RuntimeException { + + private static final long serialVersionUID = -1210401639337288969L; + + public CadoodleConcurrencyException(String string) { + super(string); + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Delete.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Delete.java new file mode 100644 index 000000000..4d4afb8f5 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Delete.java @@ -0,0 +1,62 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.stream.Collectors; + +import com.google.gson.annotations.Expose; +import com.neuronrobotics.bowlerstudio.physics.TransformFactory; +import com.neuronrobotics.bowlerstudio.vitamins.VitaminBomManager; +import com.neuronrobotics.sdk.addons.kinematics.VitaminLocation; +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +import eu.mihosoft.vrl.v3d.CSG; + +public class Delete implements ICaDoodleOpperation { + @Expose(serialize = true, deserialize = true) + private TransformNR location = new TransformNR(); + @Expose(serialize = true, deserialize = true) + private List names = new ArrayList(); + + @Override + public String getType() { + return "Delete"; + } + + @Override + public List process(List incoming) { + ArrayList back = new ArrayList(); + back.addAll(incoming); + + CaDoodleFile.applyToAllConstituantElements(false, names, back, new ICadoodleRecursiveEvent() { + @Override + public ArrayList process(CSG incoming, int depth) { + + ArrayList b = new ArrayList<>(); + b.add(null); + return b; + } + },1); + + return back; + } + + public TransformNR getLocation() { + return location; + } + + public Delete setLocation(TransformNR location) { + this.location = location; + return this; + } + + public List getNames() { + return names; + } + + public Delete setNames(List names) { + this.names = names; + return this; + } +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Group.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Group.java new file mode 100644 index 000000000..bf3fd083e --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Group.java @@ -0,0 +1,133 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.io.File; +import java.nio.file.NoSuchFileException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import com.google.gson.annotations.Expose; + +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.parametrics.IParametric; +import javafx.scene.paint.Color; + +public class Group extends AbstractAddFrom implements ICaDoodleOpperation { + @Expose(serialize = true, deserialize = true) + private List names = new ArrayList(); + @Expose(serialize = true, deserialize = true) + public String groupID = null; + @Expose(serialize = true, deserialize = true) + public boolean hull = false; + @Expose(serialize = true, deserialize = true) + public boolean intersect = false; + + @Override + public String getType() { + return "Group"; + } + + @Override + public List process(List incoming) { + ArrayList holes = new ArrayList(); + ArrayList solids = new ArrayList(); + ArrayList back = new ArrayList(); + ArrayList replace = new ArrayList(); + back.addAll(incoming); + for (CSG csg : incoming) { + if (csg.isLock()) + continue; + for (String name : names) { + if (name.contentEquals(csg.getName())) { + replace.add(csg); + CSG c = csg.clone().syncProperties(csg).setRegenerate(csg.getRegenerate()).setName(name); + if (csg.isHole()) { + holes.add(c); + } else + solids.add(c); + c.addGroupMembership(getGroupID()); + back.add(c); + } + } + } + for (CSG c : replace) { + back.remove(c); + } + CSG result = null; + if (holes.size() > 0 && solids.size() == 0) { + result = CSG.unionAll(holes); + if (hull) + result = result.hull(); + result.setIsHole(true); + + } else { + CSG holecutter = null; + if (holes.size() > 0) { + if (intersect) + holecutter = intersect(holes); + else + holecutter = CSG.unionAll(holes); + if (hull) + holecutter = holecutter.hull(); + } + if (intersect) + result = intersect(solids); + else + result = CSG.unionAll(solids); + Color c = result.getColor(); + if (hull) { + result = result.hull(); + } + if (holecutter != null) + result = result.difference(holecutter); + result.setIsHole(false); + result.setColor(c); + } + HashMap mapOfparametrics = result.getMapOfparametrics(); + if (mapOfparametrics != null) + mapOfparametrics.clear(); + result.addIsGroupResult(getGroupID()); + result.setName(getGroupID()); + namesAdded.add(result.getName()); + back.add(result); + return back; + } + + private CSG intersect(ArrayList solids) { + CSG first = solids.get(0); + for(int i=1;i getNames() { + return names; + } + + public Group setNames(List names) { + this.names = names; + return this; + } + + public String getGroupID() { + if (groupID == null) + groupID = RandomStringFactory.generateRandomString(); + return groupID; + } + + public Group setIntersect(boolean intersect) { + this.intersect = intersect; + return this; + } + + public Group setHull(boolean hull) { + this.hull = hull; + return this; + } + + @Override + public File getFile() throws NoSuchFileException { + throw new NoSuchFileException(null); + } +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Hide.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Hide.java new file mode 100644 index 000000000..38389fb41 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Hide.java @@ -0,0 +1,48 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.Expose; + +import eu.mihosoft.vrl.v3d.CSG; + +public class Hide implements ICaDoodleOpperation { + @Expose (serialize = true, deserialize = true) + private List names = new ArrayList(); + @Override + public String getType() { + return "Hide"; + } + + @Override + public List process(List incoming) { + ArrayList replace = new ArrayList(); + ArrayList back = new ArrayList(); + back.addAll(incoming); + for(CSG c: incoming) { + for(String name:names) { + if(name.contentEquals(c.getName())) { + replace.add(c); + CSG b=c.clone().setRegenerate(c.getRegenerate()).syncProperties(c); + b.setIsHide(true); + back.add(b); + } + } + } + for(CSG c:replace) { + back.remove(c); + } + return back; + } + + public List getNames() { + return names; + } + + public Hide setNames(List names) { + this.names = names; + return this; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ICaDoodleOperationAdapterFactory.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ICaDoodleOperationAdapterFactory.java new file mode 100644 index 000000000..6ffa00870 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ICaDoodleOperationAdapterFactory.java @@ -0,0 +1,84 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import com.google.gson.*; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class ICaDoodleOperationAdapterFactory implements TypeAdapterFactory { + private final Map> typeRegistry = new HashMap<>(); + private final Map, String> classRegistry = new HashMap<>(); + + public ICaDoodleOperationAdapterFactory() { + registerType("AddFromFile", AddFromFile.class); + registerType("AddFromScript", AddFromScript.class); + registerType("Allign", Allign.class); + registerType("Delete", Delete.class); + registerType("Group", Group.class); + registerType("Hide", Hide.class); + registerType("Lock", Lock.class); + registerType("Mirror", Mirror.class); + registerType("MoveCenter", MoveCenter.class); + registerType("Paste", Paste.class); + registerType("Resize", Resize.class); + registerType("Show", Show.class); + registerType("ToHole", ToHole.class); + registerType("ToSolid", ToSolid.class); + registerType("UnGroup", UnGroup.class); + registerType("UnLock", UnLock.class); + registerType("Sweep", Sweep.class); + + } + + private void registerType(String typeName, Class clazz) { + typeRegistry.put(typeName, clazz); + classRegistry.put(clazz, typeName); + } + + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ICaDoodleOpperation.class.isAssignableFrom(type.getRawType())) { + return null; + } + + final TypeAdapter jsonElementAdapter = gson.getAdapter(JsonElement.class); + + return new TypeAdapter() { + @Override + public void write(JsonWriter out, T value) throws IOException { + JsonObject jsonObject = new JsonObject(); + String typeName = classRegistry.get(value.getClass()); + if (typeName == null) { + throw new JsonParseException("Unknown class: " + value.getClass()); + } + jsonObject.addProperty("type", typeName); + @SuppressWarnings("unchecked") + TypeAdapter delegateAdapter = (TypeAdapter) gson.getDelegateAdapter(ICaDoodleOperationAdapterFactory.this, TypeToken.get((Class) value.getClass())); + JsonElement dataElement = delegateAdapter.toJsonTree(value); + jsonObject.add("data", dataElement); + jsonElementAdapter.write(out, jsonObject); + } + + @Override + public T read(JsonReader in) throws IOException { + JsonObject jsonObject = jsonElementAdapter.read(in).getAsJsonObject(); + JsonElement typeElement = jsonObject.get("type"); + JsonElement dataElement = jsonObject.get("data"); + String typeName = typeElement.getAsString(); + Class clazz = typeRegistry.get(typeName); + if (clazz == null) { + throw new JsonParseException("Unknown type: " + typeName); + } + TypeAdapter delegateAdapter = gson.getDelegateAdapter(ICaDoodleOperationAdapterFactory.this, TypeToken.get(clazz)); + com.neuronrobotics.sdk.common.Log.error("JSON Parsing "+typeName); + return (T) delegateAdapter.fromJsonTree(dataElement); + } + }.nullSafe(); + } + + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ICaDoodleOpperation.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ICaDoodleOpperation.java new file mode 100644 index 000000000..74d1afe7c --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ICaDoodleOpperation.java @@ -0,0 +1,11 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.List; + +import eu.mihosoft.vrl.v3d.CSG; + +public interface ICaDoodleOpperation { + + public String getType(); + public List process(List incoming); +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ICaDoodleStateUpdate.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ICaDoodleStateUpdate.java new file mode 100644 index 000000000..f2d888c19 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ICaDoodleStateUpdate.java @@ -0,0 +1,17 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.List; + +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +import eu.mihosoft.vrl.v3d.CSG; + +public interface ICaDoodleStateUpdate { + public void onUpdate(List currentState, ICaDoodleOpperation source,CaDoodleFile file ); + public void onSaveSuggestion(); + public void onInitializationDone(); + public void onInitializationStart(); + public void onRegenerateDone(); + public void onRegenerateStart(); + public void onWorkplaneChange(TransformNR newWP); +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ICadoodleRecursiveEvent.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ICadoodleRecursiveEvent.java new file mode 100644 index 000000000..5511804e1 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ICadoodleRecursiveEvent.java @@ -0,0 +1,9 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.ArrayList; + +import eu.mihosoft.vrl.v3d.CSG; + +public interface ICadoodleRecursiveEvent { + public ArrayList process(CSG incoming,int depth); +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Lock.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Lock.java new file mode 100644 index 000000000..ff2e3e41f --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Lock.java @@ -0,0 +1,48 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.Expose; + +import eu.mihosoft.vrl.v3d.CSG; + +public class Lock implements ICaDoodleOpperation { + @Expose (serialize = true, deserialize = true) + private List names = new ArrayList(); + @Override + public String getType() { + return "Lock"; + } + + @Override + public List process(List incoming) { + ArrayList replace = new ArrayList(); + ArrayList back = new ArrayList(); + back.addAll(incoming); + for(CSG c: incoming) { + for(String name:names) { + if(name.contentEquals(c.getName())) { + replace.add(c); + CSG b=c.clone().setRegenerate(c.getRegenerate()).syncProperties(c); + b.setIsLock(true); + back.add(b); + } + } + } + for(CSG c:replace) { + back.remove(c); + } + return back; + } + + public List getNames() { + return names; + } + + public Lock setNames(List names) { + this.names = names; + return this; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Mirror.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Mirror.java new file mode 100644 index 000000000..832ffb7d7 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Mirror.java @@ -0,0 +1,155 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import com.google.gson.annotations.Expose; +import com.neuronrobotics.bowlerstudio.physics.TransformFactory; +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.Transform; + +public class Mirror implements ICaDoodleOpperation { + @Expose(serialize = true, deserialize = true) + private MirrorOrentation location; + @Expose(serialize = true, deserialize = true) + private List names = new ArrayList(); + @Expose(serialize = true, deserialize = true) + private TransformNR workplane = null; + @Expose(serialize = true, deserialize = true) + protected String name = null; + private int index; + public String getName() { + if (name == null) { + setName(RandomStringFactory.generateRandomString()); + } + return name; + } + + public void setName(String name) { + this.name = name; + } + @Override + public String getType() { + return "Move Center"; + } + + private CSG sync(CSG incoming, CSG c) { + return c.syncProperties(incoming).setName(incoming.getName()).setColor(incoming.getColor()); + } + + @Override + public List process(List incoming) { + ArrayList back = new ArrayList(); + back.addAll(incoming); + index = 0; + for (String name : names) { + for (CSG csg : incoming) { + if(!csg.getName().contentEquals(name)) + continue; + CSG base = csg.transformed(TransformFactory.nrToCSG(getWorkplane()).inverse()); + Transform mirroringCenter = new Transform().movex(base.getCenterX()).movey(base.getCenterY()) + .movez(base.getCenterZ()); + Transform sc = new Transform(); + if (location == MirrorOrentation.x) { + sc=new Transform().scaleX(-1); + } + if (location == MirrorOrentation.y) { + sc=new Transform().scaleY(-1); + } + if (location == MirrorOrentation.z) { + sc=new Transform().scaleZ(-1); + } + Transform scale=sc; + + CaDoodleFile.applyToAllConstituantElements(false, name, back, (incoming1, depth) -> { + ArrayList b = new ArrayList<>(); + Transform inverse = TransformFactory.nrToCSG(getWorkplane()).inverse(); + CSG t = incoming1.transformed(inverse); + CSG centered = t.transformed(mirroringCenter.inverse()); + centered = centered.transformed(scale); + centered = centered.transformed(mirroringCenter); + Transform wp = TransformFactory.nrToCSG(getWorkplane()); + centered = centered.transformed(wp); + CSG tf = centered.setName(name).syncProperties(incoming1); + sync(incoming1, tf); + MoveCenter.set(getName()+(index++) , tf, inverse); + MoveCenter.set(getName()+(index++) , tf, mirroringCenter.inverse()); + MoveCenter.set(getName()+(index++) , tf, scale); + MoveCenter.set(getName()+(index++) , tf, mirroringCenter); + MoveCenter.set(getName()+(index++) , tf, wp); + b.add(tf); + return b; + }, 1); + } + } + return back; +// back.addAll(incoming +// .stream() +// .map(csg->{ +// +// for(String name:names) { +// if(csg.isLock()) +// continue; +// if(csg.getName().contentEquals(name)) +// return mirror(csg, name) +// ; +// } +// return csg; +// }) +// .collect(Collectors.toCollection(ArrayList::new)) +// ); +// return back; + } + + private CSG mirror(CSG csg, String name) { + CSG t = csg.transformed(TransformFactory.nrToCSG(getWorkplane()).inverse()); + Transform mirroringCenter = new Transform().movex(t.getCenterX()).movex(t.getCenterY()).movez(t.getCenterZ()); + + CSG centered = t.transformed(mirroringCenter.inverse()); + if (location == MirrorOrentation.x) { + centered = centered.mirrorx(); + } + if (location == MirrorOrentation.y) { + centered = centered.mirrory(); + } + if (location == MirrorOrentation.z) { + centered = centered.mirrorz(); + } + centered = centered.transformed(mirroringCenter); + centered = centered.transformed(TransformFactory.nrToCSG(getWorkplane())); + return centered.setName(name).syncProperties(csg); + } + + public MirrorOrentation getLocation() { + return location; + } + + public Mirror setLocation(MirrorOrentation location) { + this.location = location; + return this; + } + + public List getNames() { + return names; + } + + public Mirror setNames(List names) { + this.names = names; + return this; + } + + public TransformNR getWorkplane() { + if (workplane == null) + workplane = new TransformNR(); + return workplane; + } + + public Mirror setWorkplane(TransformNR workplane) { + this.workplane = workplane; + return this; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/MirrorOrentation.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/MirrorOrentation.java new file mode 100644 index 000000000..ee3456c57 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/MirrorOrentation.java @@ -0,0 +1,5 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +public enum MirrorOrentation { + x,y,z; +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/MoveCenter.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/MoveCenter.java new file mode 100644 index 000000000..0cf6df401 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/MoveCenter.java @@ -0,0 +1,131 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import com.google.gson.annotations.Expose; +import com.neuronrobotics.bowlerstudio.physics.TransformFactory; +import com.neuronrobotics.bowlerstudio.vitamins.VitaminBomManager; +import com.neuronrobotics.sdk.addons.kinematics.VitaminLocation; +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.PropertyStorage; +import eu.mihosoft.vrl.v3d.Transform; + +public class MoveCenter implements ICaDoodleOpperation { + @Expose(serialize = true, deserialize = true) + private TransformNR location = new TransformNR(); + @Expose(serialize = true, deserialize = true) + private List names = new ArrayList(); + @Expose(serialize = true, deserialize = true) + protected String name = null; + + public String getName() { + if (name == null) { + setName(RandomStringFactory.generateRandomString()); + } + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String getType() { + return "Move Center"; + } + public static void set(String name, CSG c, TransformNR tf) { + set(name,c,TransformFactory.nrToCSG(tf)); + } + public static void set(String name, CSG c, Transform tf) { + if (tf == null) + throw new NullPointerException(); + if (name == null) + throw new NullPointerException(); + if (c == null) + throw new NullPointerException(); + PropertyStorage storage = c.getStorage(); + Optional o = storage.getValue("TFSet"); + ArrayList tfs = null; + if (!o.isPresent()) { + tfs = new ArrayList(); + storage.set("TFSet", tfs); + } else { + tfs = (ArrayList) o.get(); + } + boolean contains = false; + for (String s : tfs) { + if (s.contentEquals(name)) { + contains = true; + break; + } + } + storage.set(name, tf); + if (!contains) + tfs.add(name); + } + + public static Transform getTotalOffset(CSG c) { + Transform nrToCSG = new Transform(); + PropertyStorage storage = c.getStorage(); + Optional o = storage.getValue("TFSet"); + if (o.isPresent()) { + Transform start = new Transform(); + ArrayList tfs = (ArrayList) o.get(); + for (String s : tfs) { + try { + Transform transTmp = new Transform().apply((Transform) storage.getValue(s).get()); + start = transTmp.apply(start); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + nrToCSG = start; + } + return nrToCSG; + } + + @Override + public List process(List incoming) { + ArrayList back = new ArrayList(); + back.addAll(incoming); + + CaDoodleFile.applyToAllConstituantElements(false, names, back, new ICadoodleRecursiveEvent() { + @Override + public ArrayList process(CSG incoming, int depth) { + Transform nrToCSG2 = TransformFactory.nrToCSG(location); + CSG tmpToAdd = incoming.transformed(nrToCSG2).syncProperties(incoming).setName(incoming.getName()); + ArrayList b = new ArrayList<>(); + b.add(tmpToAdd); + set(getName(), tmpToAdd, location); + return b; + } + },1); + + return back; + } + + public TransformNR getLocation() { + return location; + } + + public MoveCenter setLocation(TransformNR location) { + this.location = location; + return this; + } + + public List getNames() { + return names; + } + + public MoveCenter setNames(List names) { + this.names = names; + return this; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Paste.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Paste.java new file mode 100644 index 000000000..6e9cdf35e --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Paste.java @@ -0,0 +1,145 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.io.File; +import java.nio.file.NoSuchFileException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import com.google.gson.annotations.Expose; +import com.neuronrobotics.bowlerstudio.physics.TransformFactory; +import com.neuronrobotics.bowlerstudio.vitamins.VitaminBomManager; +import com.neuronrobotics.sdk.addons.kinematics.VitaminLocation; +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.Transform; +import eu.mihosoft.vrl.v3d.parametrics.CSGDatabase; +import eu.mihosoft.vrl.v3d.parametrics.Parameter; + +public class Paste extends AbstractAddFrom implements ICaDoodleOpperation { + @Expose(serialize = true, deserialize = true) + private TransformNR location = new TransformNR(); + @Expose(serialize = true, deserialize = true) + private List names = new ArrayList(); +// @Expose(serialize = true, deserialize = true) +// public double offset = 10; + private int index; + private HashMap cpMap = new HashMap(); + + @Override + public String getType() { + return "Paste"; + } + + @Override + public List process(List incoming) { + ArrayList back = new ArrayList(); + back.addAll(incoming); + index = 1; + cpMap.clear(); + + CaDoodleFile.applyToAllConstituantElements(false, names, back, new ICadoodleRecursiveEvent() { + @Override + public ArrayList process(CSG ic, int depth) { + ArrayList copyPasteMoved = copyPasteMoved(back, ic,depth); + return copyPasteMoved; + } + },1); + + for (String from : cpMap.keySet()) { + CSG source = CaDoodleFile.getByName(back, from); + if (source.isGroupResult()) { + ArrayList c = constituants(back, from); + if(c.size()<2) + throw new RuntimeException("A group result must have at least 2 constituants!"); + String newGroupName = CaDoodleFile.getByName(back, cpMap.get(from)).getName(); + for (String s : c) { + CSG dest = CaDoodleFile.getByName(back, s); + dest.removeGroupMembership(from); + dest.addGroupMembership(newGroupName); + } + } + } + return back; + } + + private ArrayList constituants(ArrayList b, String name) { + ArrayList c = new ArrayList(); + for (String ky:cpMap.keySet()) { + CSG byName = CaDoodleFile.getByName(b,ky); + String name2 = cpMap.get(ky); + CSG byName2 = CaDoodleFile.getByName(b,name2); + for(CSG csg:Arrays.asList(byName,byName2)){ + if (csg.checkGroupMembership(name)) { + // only add objects that were created by this operation + if (csg.getName().contains(getName())) + c.add(csg.getName()); + } + } + } + return c; + } + + + + private ArrayList copyPasteMoved(ArrayList back, CSG c, int depth) { + String prevName = c.getName(); + String name = getName() +( index == 0 ? "" : "_" + index); + CSG clone = c.clone(); + clone.setRegenerate(c.getRegenerate()).setName(name); + clone.getStorage().set("PreviousName", prevName); + Transform nrToCSG = MoveCenter.getTotalOffset(c); + CSG newOne = null; + if (CaDoodleVitamin.isVitamin(c)) { + CSG regenerate = clone.getRegenerate().regenerate(clone); + newOne = regenerate.transformed(nrToCSG); + newOne.setRegenerate(regenerate.getRegenerate()); + }else { + newOne = clone; + newOne.setRegenerate(c.getRegenerate()); + } + newOne.syncProperties(c).setName(name); + index++; + getNamesAdded().add(name); + ArrayList b = new ArrayList<>(); + b.add(c); + b.add(newOne); + //System.out.println("Copy "+c.getName()+" to "+newOne.getName()); + cpMap.put(c.getName(), newOne.getName()); + return b; + } + + public TransformNR getLocation() { + return location; + } + + public Paste setLocation(TransformNR location) { + this.location = location; + return this; + } + + public List getNames() { + return names; + } + + public Paste setNames(List names) { + this.names = names; + return this; + } + +// public Paste setOffset(double offset) { +// this.offset = offset; +// return this; +// } + + @Override + public File getFile() throws NoSuchFileException { + throw new NoSuchFileException(null); + } +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/RandomStringFactory.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/RandomStringFactory.java new file mode 100644 index 000000000..5c3d03e06 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/RandomStringFactory.java @@ -0,0 +1,86 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.Random; + +import com.google.gson.annotations.Expose; +import com.neuronrobotics.bowlerstudio.assets.ConfigurationDatabase; + +public class RandomStringFactory { + @Expose (serialize = false, deserialize = false) + private static final String CHAR_POOL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + @Expose (serialize = false, deserialize = false) + private static final int STRING_LENGTH = 10; + + public static String[] adjectives = { + "Effervescent", "Zestful", "Vivacious", "Ebullient", "Sprightly", + "Exuberant", "Jocund", "Mirthful", "Zippy", "Gleeful", + "Buoyant", "Chipper", "Peppy", "Perky", "Jaunty", + "Blithe", "Joyous", "Spirited", "Vibrant", "Lively", + "Zealous", "Jubilant", "Merry", "Elated", "Euphoric", + "Bubbly", "Chirpy", "Animated", "Bouncy", "Energetic", + "Frisky", "Sparkling", "Vivid", "Zappy", "Zippy", + "Snappy", "Peppy", "Effulgent", "Radiant", "Luminous", + "Beaming", "Glowing", "Incandescent", "Resplendent", "Lustrous", + "Glistening", "Scintillating", "Efflorescent", "Blooming", "Flourishing", + "Thriving", "Burgeoning", "Prolific", "Teeming", + "Abundant", "Plentiful", "Bountiful", "Copious", "Profuse", + "Exuberant", "Luxuriant", "Lush", "Verdant", "Fertile", + "Productive", "Fruitful", "Generative", "Creative", "Imaginative", + "Inventive", "Ingenious", "Clever", "Brilliant", "Dazzling", + "Bright", "Luminous", "Radiant", "Gleaming", "Glittering", + "Sparkling", "Twinkling", "Shimmering", "Glowing", "Beaming", + "Effulgent", "Resplendent", "Splendid", "Magnificent", + "Majestic", "Grand", "Glorious", "Superb", "Marvelous", + "Wonderful", "Fantastic", "Fabulous", "Astounding", "Amazing" + }; + + public static String[] creaturesMachines = { + "Dragon", "Robot", "Unicorn", "Cyborg", "Griffin", + "Automaton", "Phoenix", "Mech", "Kraken", + "Chimera", "Golem", "Pegasus", "Android", "Hydra", + "Centaur", "Drone", "Sphinx", "Exosuit", "Minotaur", + "Cyclops", "Hologram", "Werewolf", "Nanobot", "Gorgon", + "Replicant", "Banshee", "Hovercraft", "Basilisk", "Jetpack", + "Gargoyle", "Teleporter", "Forcefield", + "Submarine", "Cerberus", "Hoverboard", "Siren", "Skycycle", + "Yeti", "Hoverbike", "Sasquatch", "Hyperloop", "Thunderbird", + "Gyrocopter", "Leviathan", "Airship", "Behemoth", "Starship", + "Colossus", "Monowheel", "Titan", "Rocketship", "Gremlin", + "Hovercar", "Imp", "Zeppelin", "Ogre", "Monorail", + "Troll", "Gnome", "Leprechaun", + "Hyperpod", "Fairy", "Gyrocar", "Elf", "Ornithopter", + "Hoversuit", "Specter", "Levitator", "Phantom", + "Telekinetic", "Goblin", "Gravicycle", "Dwarf", + "Jetbike", "Hobgoblin", "Ekranoplan", + "Aerotrain", "Sprite", "Maglev", "Aerosled", + "Cybertooth", "Ifrit", "Warpod", "Elemental", + "Hoversled", "Goliath", "Warpcraft", "Juggernaut", "Vortexer" + }; + + private static int index = ((Double) ConfigurationDatabase.get( + "CaDoodle", + "projectNameIndex", + (Math.random()*creaturesMachines.length))).intValue(); + + + public static String getNextRandomName() { + index++; + if(index>=creaturesMachines.length) + index=0; + ConfigurationDatabase.put("CaDoodle", "projectNameIndex", index); + return adjectives[(int) (Math.random()*adjectives.length)]+"_"+creaturesMachines[index]; + } + + public static String generateRandomString() { + Random random = new Random(); + StringBuilder stringBuilder = new StringBuilder(STRING_LENGTH); + + for (int i = 0; i < STRING_LENGTH; i++) { + int randomIndex = random.nextInt(CHAR_POOL.length()); + stringBuilder.append(CHAR_POOL.charAt(randomIndex)); + } + + return getNextRandomName()+"_"+stringBuilder.toString(); + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Resize.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Resize.java new file mode 100644 index 000000000..00b277046 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Resize.java @@ -0,0 +1,242 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.stream.Collectors; + +import com.google.gson.annotations.Expose; +import com.neuronrobotics.bowlerstudio.creature.IMobileBaseUI; +import com.neuronrobotics.bowlerstudio.physics.TransformFactory; +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +import eu.mihosoft.vrl.v3d.Bounds; +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.Transform; +import eu.mihosoft.vrl.v3d.Vector3d; + +public class Resize implements ICaDoodleOpperation { + + @Expose(serialize = true, deserialize = true) + private List names = new ArrayList(); + + @Expose(serialize = true, deserialize = true) + private TransformNR height = null; + @Expose(serialize = true, deserialize = true) + private TransformNR leftFront = null; + @Expose(serialize = true, deserialize = true) + private TransformNR rightRear = null; + @Expose(serialize = true, deserialize = true) + private TransformNR workplane = new TransformNR(); + @Expose(serialize = false, deserialize = false) + private IMobileBaseUI debug; + + @Override + public String getType() { + return "Resize"; + } + private class ResizeEvent{ + Transform scaleZ; + Transform scale; + double movez; + double movey; + double movex; + } + + public Bounds getSellectedBounds(List incoming) { + Vector3d min = null; + Vector3d max = null; + for (CSG i : incoming) { + CSG c=i.transformed(TransformFactory.nrToCSG(getWorkplane().inverse())); + Vector3d min2 = c.getBounds().getMin().clone(); + Vector3d max2 = c.getBounds().getMax().clone(); + if (min == null) + min = min2; + if (max == null) + max = max2; + if (min2.x < min.x) + min.x = min2.x; + if (min2.y < min.y) + min.y = min2.y; + if (min2.z < min.z) + min.z = min2.z; + if (max.x < max2.x) + max.x = max2.x; + if (max.y < max2.y) + max.y = max2.y; + if (max.z < max2.z) + max.z = max2.z; + } + if(min==null||max==null) { + System.out.println("Found bounds to be null "); + + throw new RuntimeException("Min and max can not be null"); + } + return new Bounds(min, max); + } + @Override + public List process(List incoming) { + ArrayList back = new ArrayList(); + back.addAll(incoming); + HashMap groupsProcessed = new HashMap<>(); + ArrayList selected = new ArrayList(); + for(CSG c:incoming) { + if(c.isLock()) + continue; + for (String name : names) { + if(c.getName().contentEquals(name)) { + selected.add(c); + } + } + } + Bounds b = getSellectedBounds(selected); + + for (String name : names) { + resizeByName(name,back,groupsProcessed,b); + } + return back; + } + + private void resizeByName(String name, ArrayList back, HashMap groupsProcessed,Bounds bounds) { + for (int i = 0; i < back.size(); i++) { + CSG starting = back.get(i); + if ( starting.getName().contentEquals(name) ){ + double zScale = height.getZ()-bounds.getMin().z; + double scalez = zScale/ (bounds.getMax().z-bounds.getMin().z); + + + Transform scaleZ =new Transform().scaleZ(scalez); + CSG transformed = starting.transformed(TransformFactory.nrToCSG(getWorkplane().inverse())); + if(debug!=null) { + debug.setCsg(transformed, null); + } + CSG resizeUp = transformed + .transformed(scaleZ); + if(debug!=null) { + debug.setCsg(resizeUp, null); + } + double zMove = -(bounds.getMin().z*scalez)+bounds.getMin().z; + resizeUp=resizeUp + .movez(zMove); + if(debug!=null) { + debug.setCsg(resizeUp, null); + } + double xdimen = Math.abs(leftFront.getX()-rightRear.getX()); + double ydimen = Math.abs(leftFront.getY()-rightRear.getY()); + double scalex = xdimen/ (bounds.getMax().x-bounds.getMin().x); + double scaley = ydimen/ (bounds.getMax().y-bounds.getMin().y); + double x = rightRear.getX(); + double y = rightRear.getY(); + + if(leftFront.getX() back, + HashMap groupsProcessed) { + for (int i = 0; i < back.size(); i++) { + CSG c = back.get(i); + if(c.isInGroup() && c.checkGroupMembership(name) ) { + + ResizeEvent ev =groupsProcessed.get(name); + CSG transformed = c.transformed(TransformFactory.nrToCSG(getWorkplane().inverse())); + if(debug!=null) { + debug.setCsg(transformed, null); + } + CSG gc = transformed + .transformed(ev.scaleZ); + gc=gc + .movez(ev.movez); + gc=gc.transformed(ev.scale); + gc=gc + .movex(ev.movex) + .movey(ev.movey) + .transformed(TransformFactory.nrToCSG(getWorkplane())); + gc.syncProperties(c).setName(c.getName()); + back.set(i, gc); + if( c.isGroupResult()) { + groupsProcessed.put(c.getName(), ev); + processCompositMembers(c.getName(),back,groupsProcessed); + } + } + } + } + + public Resize setResize(TransformNR h, TransformNR lf, TransformNR rr) { + height = h; + leftFront = lf; + rightRear = rr; + if(Math.abs(lf.getZ()-rr.getZ())>0.00001) { + throw new RuntimeException("The control points of the corners must be at the same Z value \n"+lf.toSimpleString()+"\n"+rr.toSimpleString()); + } + if(rightRear.getY()>=leftFront.getY() && rightRear.getX()>=leftFront.getX()) + return setResize(h,rr,lf);// they were swapped, just fix it and move along +// if(rightRear.getY()>=leftFront.getY() || rightRear.getX()>=leftFront.getX()) +// throw new RuntimeException("Scale must be positive!"); + return this; + } + + public List getNames() { + return names; + } + + public Resize setNames(List names) { + this.names = names; + return this; + } + public TransformNR getWorkplane() { + if(workplane==null) + workplane=new TransformNR(); + return workplane; + } + public Resize setWorkplane(TransformNR workplane) { + this.workplane = workplane; + return this; + } + public Resize setDebugger(IMobileBaseUI engine) { + this.debug = engine; + return this; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Show.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Show.java new file mode 100644 index 000000000..8471fc03c --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Show.java @@ -0,0 +1,48 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.Expose; + +import eu.mihosoft.vrl.v3d.CSG; + +public class Show implements ICaDoodleOpperation { + @Expose (serialize = true, deserialize = true) + private List names = new ArrayList(); + @Override + public String getType() { + return "Show"; + } + + @Override + public List process(List incoming) { + ArrayList replace = new ArrayList(); + ArrayList back = new ArrayList(); + back.addAll(incoming); + for(CSG c: incoming) { + for(String name:names) { + if(name.contentEquals(c.getName())) { + replace.add(c); + CSG b=c.clone().setRegenerate(c.getRegenerate()).syncProperties(c); + b.setIsHide(false); + back.add(b); + } + } + } + for(CSG c:replace) { + back.remove(c); + } + return back; + } + + public List getNames() { + return names; + } + + public Show setNames(List names) { + this.names = names; + return this; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/StoragbeBounds.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/StoragbeBounds.java new file mode 100644 index 000000000..9e438cc1a --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/StoragbeBounds.java @@ -0,0 +1,57 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import com.google.gson.annotations.Expose; + +import eu.mihosoft.vrl.v3d.Bounds; +import eu.mihosoft.vrl.v3d.Vector3d; + +public class StoragbeBounds { + /** + * The x coordinate. + */ + @Expose (serialize = true, deserialize = true) + public double minx; + + /** + * The y coordinate. + */ + @Expose (serialize = true, deserialize = true) + public double miny; + + /** + * The z coordinate. + */ + @Expose (serialize = true, deserialize = true) + public double minz; + /** + * The x coordinate. + */ + @Expose (serialize = true, deserialize = true) + public double maxx; + + /** + * The y coordinate. + */ + @Expose (serialize = true, deserialize = true) + public double maxy; + + /** + * The z coordinate. + */ + @Expose (serialize = true, deserialize = true) + public double maxz; + public StoragbeBounds(Bounds b) { + minx=b.getMin().x; + miny=b.getMin().y; + minz=b.getMin().z; + maxx=b.getMax().x; + maxy=b.getMax().y; + maxz=b.getMax().z; + } + public Bounds getBounds() { + Vector3d min = new Vector3d(minx, miny, minz); + Vector3d max = new Vector3d(maxx, maxy, maxz); + return new Bounds(min, max); + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Sweep.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Sweep.java new file mode 100644 index 000000000..4dd898a6d --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/Sweep.java @@ -0,0 +1,261 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import com.google.gson.annotations.Expose; +import com.neuronrobotics.bowlerstudio.physics.TransformFactory; +import com.neuronrobotics.bowlerstudio.scripting.DownloadManager; +import com.neuronrobotics.bowlerstudio.scripting.ScriptingEngine; +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +import eu.mihosoft.vrl.v3d.Bounds; +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.Extrude; +import eu.mihosoft.vrl.v3d.Plane; +import eu.mihosoft.vrl.v3d.Polygon; +import eu.mihosoft.vrl.v3d.Transform; +import eu.mihosoft.vrl.v3d.Vector3d; +import eu.mihosoft.vrl.v3d.ext.org.poly2tri.PolygonUtil; +import eu.mihosoft.vrl.v3d.parametrics.CSGDatabase; +import eu.mihosoft.vrl.v3d.parametrics.LengthParameter; +import eu.mihosoft.vrl.v3d.parametrics.Parameter; +import eu.mihosoft.vrl.v3d.parametrics.StringParameter; +import eu.mihosoft.vrl.v3d.svg.SVGLoad; +import javafx.scene.paint.Color; + +public class Sweep extends AbstractAddFrom { + @Expose(serialize = true, deserialize = true) + private TransformNR location = null; + private static ArrayList options = new ArrayList(); + private static ArrayList nopt = new ArrayList(); + @Expose(serialize = true, deserialize = true) + private Boolean preventBoM = false; + + private LengthParameter z = null; + private LengthParameter rad = null; + private LengthParameter step = null; + private LengthParameter angle = null; + + public Sweep set(File source) throws Exception { + if (!source.getName().toLowerCase().endsWith(".svg")) + throw new Exception("Sweep can only take files with the .svg extention"); + System.out.println("Saving Local Copy of "+source.getAbsolutePath()); + AddFromFile.toLocal(source, getName()); + try { + getFile(); + } catch (Exception ex) { + ex.printStackTrace(); + } + return this; + } + + @Override + public String getType() { + // TODO Auto-generated method stub + return "Sweep"; + } + + public CSG sweep(Polygon p, String name, Bounds b) { + double sweepTot = angle(name).getMM(); + double d = sweepTot / 360; + int steps = (int) (steps(name).getMM() * d); + double angle = sweepTot / steps; + Parameter zp = zoffset(name); + double z = zp.getMM() * d / steps; + double radius = radius(name).getMM(); + if (angle < 0) + angle = -angle; + Transform centerandAllignedPolygon = new Transform().movex(-b.getMinX()).movey(-b.getMinY()); + Transform increment = new Transform().rotY(-angle).movey(z); + Transform radiusT = new Transform().movex(radius); + Polygon transformedP = p.transformed(centerandAllignedPolygon); + return Extrude.sweep(transformedP, increment, radiusT, steps).rotx(-90).setName(name); + } + + private LengthParameter radius(String name) { + String key = name + "_CaDoodle_Rad"; + if (rad == null) + rad = new LengthParameter(key, 10.0, nopt); + if(rad.getMM()<0) + rad.setMM(0); + return rad; + } + + private LengthParameter zoffset(String name) { + String key = name + "_CaDoodle_Z-per"; + if (z == null) + z = new LengthParameter(key, 0.0, nopt); + return z; + } + + private LengthParameter steps(String name) { + String key = name + "_CaDoodle_Step"; + if (step == null) + step = new LengthParameter(key, 30.0, nopt); + if(step.getMM()<3) + step.setMM(3); + return step; + } + + private LengthParameter angle(String name) { + String key = name + "_CaDoodle_Angle"; + if (angle == null) + angle = new LengthParameter(key, 360.0, nopt); + if (angle.getMM()<0.001) + angle.setMM(0.001); + return angle; + } + + + + @Override + public List process(List incoming) { + nameIndex = 0; + ArrayList back = new ArrayList(); + back.addAll(incoming); + if (getName() == null) { + + } + try { +// ArrayListargs = new ArrayList<>(); +// args.addAll(Arrays.asList(getName() )); + ArrayList collect = new ArrayList<>(); + File file = getFile(); + if (!file.exists()) { + throw new RuntimeException("Failed to find file"); + } + + ArrayList args = new ArrayList<>(); + args.addAll(Arrays.asList(name)); + HashMap configs = new HashMap(); + configs.put("name", name); + configs.put("PreventBomAdd", preventBoM); + args.add(configs); + // List flattenedCSGs = ScriptingEngine.flaten(file, CSG.class, args); + SVGLoad s = new SVGLoad(file.toURI()); + HashMap> polygons = s.toPolygons(); + Object[] array = polygons.keySet().toArray(); + int j = 0; + Bounds b = getBounds(polygons); + for (int i = 0; i < array.length; i++) { + String key = (String) array[i]; + for (Polygon P : polygons.get(key)) { + + String orderedName = getOrderedName(); + CSG processedCSG = processGiven(P, b, j++, orderedName); + collect.add(processedCSG); + } + } + + back.addAll(collect); + } catch (Exception e) { + e.printStackTrace(); + } + return back; + } + + public Bounds getBounds(HashMap> polygons) { + Vector3d min = null; + Vector3d max = null; + // TickToc.tic("getSellectedBounds "+incoming.size()); + for (String s : polygons.keySet()) + for (Polygon csg : polygons.get(s)) { + + Bounds b = csg.getBounds(); + Vector3d min2 = b.getMin().clone(); + Vector3d max2 = b.getMax().clone(); + if (min == null) + min = min2; + if (max == null) + max = max2; + if (min2.x < min.x) + min.x = min2.x; + if (min2.y < min.y) + min.y = min2.y; + if (min2.z < min.z) + min.z = min2.z; + if (max.x < max2.x) + max.x = max2.x; + if (max.y < max2.y) + max.y = max2.y; + if (max.z < max2.z) + max.z = max2.z; + // TickToc.tic("Bounds for "+c.getName()); + } + + return new Bounds(min, max); + } + + @Override + public File getFile() throws NoSuchFileException { + return AddFromFile.getFile(name); + } + + private CSG processGiven(Polygon p, Bounds b, int j, String name) { + Color c = p.getColor(); + if (c == null) + c = Color.ROSYBROWN; + boolean hole = p.isHole(); + CSG csg = sweep(p, name, b); + + Transform nrToCSG = TransformFactory.nrToCSG(getLocation()); + String pathname; + try { + pathname = getFile().getAbsolutePath(); + } catch (NoSuchFileException e) { + throw new RuntimeException(e); + } + + StringParameter parameter = new StringParameter(name + "_CaDoodle_File", pathname, options); + Parameter steps = steps(name); + Parameter angle = angle(name); + Parameter z = zoffset(name); + Parameter radius = radius(name); + parameter.setStrValue(pathname); + CSG processedCSG = csg.transformed(nrToCSG).syncProperties(csg).setParameter(parameter).setParameter(steps) + .setParameter(angle).setParameter(z).setParameter(radius).setColor(c).setIsHole(hole) + .setRegenerate(previous -> { + try { + File file = getFile(); + String fileLocation = file.getAbsolutePath(); + com.neuronrobotics.sdk.common.Log.error("Regenerating " + fileLocation); + return processGiven(p, b, j, name); + } catch (Exception e) { + e.printStackTrace(); + } + return previous; + }).setName(name); + MoveCenter.set(getName(), processedCSG, nrToCSG); + return processedCSG; + } + + public TransformNR getLocation() { + if (location == null) + location = new TransformNR(); + return location; + } + + public Sweep setLocation(TransformNR location) { + this.location = location; + return this; + } + + public Boolean getPreventBoM() { + return preventBoM; + } + + public Sweep setPreventBoM(Boolean preventBoM) { + this.preventBoM = preventBoM; + return this; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ToHole.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ToHole.java new file mode 100644 index 000000000..323f37ed1 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ToHole.java @@ -0,0 +1,50 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.Expose; + +import eu.mihosoft.vrl.v3d.CSG; + +public class ToHole implements ICaDoodleOpperation { + @Expose (serialize = true, deserialize = true) + private List names = new ArrayList(); + @Override + public String getType() { + return "To Hole"; + } + + @Override + public List process(List incoming) { + ArrayList replace = new ArrayList(); + ArrayList back = new ArrayList(); + back.addAll(incoming); + for(CSG c: incoming) { + if(c.isLock()) + continue; + for(String name:names) { + if(name.contentEquals(c.getName())) { + replace.add(c); + CSG b=c.clone().setRegenerate(c.getRegenerate()).syncProperties(c); + b.setIsHole(true); + back.add(b); + } + } + } + for(CSG c:replace) { + back.remove(c); + } + return back; + } + + public List getNames() { + return names; + } + + public ToHole setNames(List names) { + this.names = names; + return this; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ToSolid.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ToSolid.java new file mode 100644 index 000000000..7900166b2 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/ToSolid.java @@ -0,0 +1,78 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.Expose; + +import eu.mihosoft.vrl.v3d.CSG; +import javafx.scene.paint.Color; + +public class ToSolid implements ICaDoodleOpperation { + @Expose (serialize = true, deserialize = true) + private List names = new ArrayList(); + @Expose (serialize = true, deserialize = true) + private double r=1.0; + @Expose (serialize = true, deserialize = true) + private double g=0; + @Expose (serialize = true, deserialize = true) + private double b=0; + @Expose (serialize = true, deserialize = true) + private double a=1.0; + @Expose (serialize = true, deserialize = true) + private boolean useColor=false; + + @Override + public String getType() { + return "To Solid"; + } + + @Override + public List process(List incoming) { + ArrayList replace = new ArrayList(); + ArrayList back = new ArrayList(); + back.addAll(incoming); + for(CSG c: incoming) { + if(c.isLock()) + continue; + for(String name:names) { + if(name.contentEquals(c.getName())) { + replace.add(c); + CSG t=c.clone().setRegenerate(c.getRegenerate()).syncProperties(c); + t.setIsHole(false); + if(useColor) { + t.setColor(getColor()); + } + back.add(t); + } + } + } + for(CSG c:replace) { + back.remove(c); + } + return back; + } + + public List getNames() { + return names; + } + + public ToSolid setNames(List names) { + this.names = names; + return this; + } + + public Color getColor() { + return new Color(r,g,b,a); + } + + public ToSolid setColor(Color color) { + r=color.getRed(); + g=color.getGreen(); + b=color.getBlue(); + a=color.getOpacity(); + useColor=true; + return this; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/UnGroup.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/UnGroup.java new file mode 100644 index 000000000..927745215 --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/UnGroup.java @@ -0,0 +1,65 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.io.File; +import java.nio.file.NoSuchFileException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import com.google.gson.annotations.Expose; + +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.Transform; + +public class UnGroup implements ICaDoodleOpperation { + @Expose(serialize = true, deserialize = true) + private List names = new ArrayList(); + + @Override + public String getType() { + return "Un-Group"; + } + @Override + public List process(List incoming) { + ArrayList back = new ArrayList(); + back.addAll(incoming); + + for (CSG csg : incoming) { + for (String name : names) { + if (csg.isGroupResult()) + if (csg.getName().contentEquals(name)) { + back.remove(csg); + } + if (csg.isInGroup()) { + if (csg.checkGroupMembership(name)) { + // release this object from the group + Transform nrToCSG = MoveCenter.getTotalOffset(csg); + CSG transformed=csg; + if(CaDoodleVitamin.isVitamin(csg)) { + CSG regenerate = csg.getRegenerate().regenerate(csg); + transformed = regenerate.transformed(nrToCSG); + } + CSG readd= transformed.setRegenerate(csg.getRegenerate()).syncProperties(csg).setName(csg.getName()); + + readd.removeGroupMembership(name); + back.remove(csg); + back.add(readd); + } + } + + } + } + + return back; + } + + public List getNames() { + return names; + } + + public UnGroup setNames(List names) { + this.names = names; + return this; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/UnLock.java b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/UnLock.java new file mode 100644 index 000000000..8f12e0bbf --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/scripting/cadoodle/UnLock.java @@ -0,0 +1,48 @@ +package com.neuronrobotics.bowlerstudio.scripting.cadoodle; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.Expose; + +import eu.mihosoft.vrl.v3d.CSG; + +public class UnLock implements ICaDoodleOpperation { + @Expose (serialize = true, deserialize = true) + private List names = new ArrayList(); + @Override + public String getType() { + return "Un-Lock"; + } + + @Override + public List process(List incoming) { + ArrayList replace = new ArrayList(); + ArrayList back = new ArrayList(); + back.addAll(incoming); + for(CSG c: incoming) { + for(String name:names) { + if(name.contentEquals(c.getName())) { + replace.add(c); + CSG b=c.clone().setRegenerate(c.getRegenerate()).syncProperties(c); + b.setIsLock(false); + back.add(b); + } + } + } + for(CSG c:replace) { + back.remove(c); + } + return back; + } + + public List getNames() { + return names; + } + + public UnLock setNames(List names) { + this.names = names; + return this; + } + +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/sequence/SequenceEvent.java b/src/main/java/com/neuronrobotics/bowlerstudio/sequence/SequenceEvent.java index 656d87d9b..1af6e3ce9 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/sequence/SequenceEvent.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/sequence/SequenceEvent.java @@ -77,7 +77,7 @@ public void setMsDuration(int msDuration) { @Override public void done(InterpolationMoveState state) { - // TODO Auto-generated method stub + // Auto-generated method stub } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/sequence/TimeSequence.java b/src/main/java/com/neuronrobotics/bowlerstudio/sequence/TimeSequence.java index 125339cc0..9b591be87 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/sequence/TimeSequence.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/sequence/TimeSequence.java @@ -90,7 +90,7 @@ public void execute(String content) throws Exception { } public void runSequence() throws Exception { - System.out.println("Initialize Sequence"); + com.neuronrobotics.sdk.common.Log.error("Initialize Sequence"); ScriptingEngine.gitScriptRun(getUrl(), getFile()); HashMap devices = getDevices(); @@ -103,13 +103,13 @@ public void runSequence() throws Exception { for (String mine : devices.keySet()) { for (String key : getDevicesInSequence()) if (mine.contentEquals(key)) { - System.out.println("Found Device " + key); + com.neuronrobotics.sdk.common.Log.error("Found Device " + key); HashMap devSeq = getSequence(key); Thread t = new Thread(() -> { for (int i = 0; i < finalDur && !Thread.interrupted(); i++) { SequenceEvent event = devSeq.get("" + i); if (event != null) { - System.out.println(key + " Execute @ " + i); + com.neuronrobotics.sdk.common.Log.error(key + " Execute @ " + i); event.execute((DHParameterKinematics) devices.get(key)); } try { @@ -122,7 +122,7 @@ public void runSequence() throws Exception { threads.add(t); } } - System.out.println("Running sequence"); + com.neuronrobotics.sdk.common.Log.error("Running sequence"); for (Thread t : threads) { t.start(); } @@ -135,7 +135,7 @@ public void runSequence() throws Exception { t.interrupt(); } } - System.out.println( + com.neuronrobotics.sdk.common.Log.error( "Running complete, took " + (System.currentTimeMillis() - start) + " expcted " + getDuration()); } @@ -163,7 +163,7 @@ private void addWavFileRun(ArrayList threads) throws InvalidRemoteExcept while (audioClip.isRunning() && !Thread.interrupted()) { double pos = (double) audioClip.getMicrosecondPosition() / 1000.0; double percent = pos / len * 100.0; - // System.out.println("Current " + pos + " Percent = " + percent); + // com.neuronrobotics.sdk.common.Log.error("Current " + pos + " Percent = " + percent); ThreadUtil.wait(10); } } catch (Throwable t) { @@ -172,7 +172,7 @@ private void addWavFileRun(ArrayList threads) throws InvalidRemoteExcept audioClip.stop(); audioClip.close(); ((AudioInputStream) audioStream).close(); - System.out.println("Audio clip exited "+getWavurl()+" : "+getWavfile()); + com.neuronrobotics.sdk.common.Log.error("Audio clip exited "+getWavurl()+" : "+getWavfile()); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/util/FileChangeWatcher.java b/src/main/java/com/neuronrobotics/bowlerstudio/util/FileChangeWatcher.java index 04581edf3..7d9325e36 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/util/FileChangeWatcher.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/util/FileChangeWatcher.java @@ -41,7 +41,7 @@ import com.neuronrobotics.bowlerstudio.IssueReportingExceptionHandler; -// TODO: Auto-generated Javadoc +// Auto-generated Javadoc /** * The Class FileChangeWatcher. */ @@ -114,7 +114,7 @@ public static FileChangeWatcher watch(File fileToWatch) throws IOException { String path = fileToWatch.getAbsolutePath(); if (activeListener.get(path) == null) { activeListener.put(path, new FileChangeWatcher(fileToWatch)); - System.err.println("Adding file to listening " + fileToWatch.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Adding file to listening " + fileToWatch.getAbsolutePath()); } return activeListener.get(path); } @@ -130,14 +130,14 @@ public static FileChangeWatcher watch(File fileToWatch) throws IOException { private FileChangeWatcher(File fileToWatch) throws IOException { this.setFileToWatch(fileToWatch); - //System.err.println("\n\n\n\tWatching "+fileToWatch.getAbsolutePath()+"\n\n\n"); + //com.neuronrobotics.sdk.common.Log.error("\n\n\n\tWatching "+fileToWatch.getAbsolutePath()+"\n\n\n"); this.watcher = FileSystems.getDefault().newWatchService(); this.keys = new HashMap(); Path dir = Paths.get(fileToWatch.getParent()); if (recursive) { System.out.format("Scanning %s ...\n", dir); registerAll(dir); - System.out.println("Done."); + com.neuronrobotics.sdk.common.Log.error("Done."); } else { register(dir); } @@ -149,7 +149,7 @@ public void run() { while (run) { try { - //System.err.println("Checking File: " + getFileToWatch().getAbsolutePath()); + //com.neuronrobotics.sdk.common.Log.error("Checking File: " + getFileToWatch().getAbsolutePath()); watch(); } catch (Exception ex) { ex.printStackTrace(); @@ -158,7 +158,7 @@ public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } @@ -270,7 +270,7 @@ public void watch() { Path dir = keys.get(key); if (dir == null) { - System.err.println("WatchKey not recognized!!"); + com.neuronrobotics.sdk.common.Log.error("WatchKey not recognized!!"); return; } @@ -292,7 +292,7 @@ public void watch() { } // print out event // System.out.format("%s: %s\n", event.kind().name(), child); - System.err.println("File Changed: " + getFileToWatch().getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("File Changed: " + getFileToWatch().getAbsolutePath()); for (int i = 0; i < listeners.size(); i++) { listeners.get(i).onFileChange(child.toFile(), event); @@ -300,7 +300,7 @@ public void watch() { // overwrites } } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } @@ -354,10 +354,10 @@ public void close() { //new Exception("File watcher closed " + fileToWatch.getAbsolutePath()).printStackTrace(); this.run = false; try { - System.err.println("Closing watcher for "+fileToWatch.getAbsolutePath()); + com.neuronrobotics.sdk.common.Log.error("Closing watcher for "+fileToWatch.getAbsolutePath()); watcher.close(); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } activeListener.remove(fileToWatch.getAbsolutePath()); diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/util/FileWatchDeviceWrapper.java b/src/main/java/com/neuronrobotics/bowlerstudio/util/FileWatchDeviceWrapper.java index e08bcf155..24f7019ff 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/util/FileWatchDeviceWrapper.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/util/FileWatchDeviceWrapper.java @@ -16,19 +16,19 @@ public static FileChangeWatcher watch(BowlerAbstractDevice device, File code,IFi @Override public void onDisconnect(BowlerAbstractDevice arg0) { - // TODO Auto-generated method stub + // Auto-generated method stub watcher.removeIFileChangeListener(cadWatcher); } @Override public void onConnect(BowlerAbstractDevice arg0) { - // TODO Auto-generated method stub + // Auto-generated method stub } }); return watcher; } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block //BowlerStudioController.highlightException(code, e); } return null; diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/util/GeometrySimplification.java b/src/main/java/com/neuronrobotics/bowlerstudio/util/GeometrySimplification.java new file mode 100644 index 000000000..a2f155d6c --- /dev/null +++ b/src/main/java/com/neuronrobotics/bowlerstudio/util/GeometrySimplification.java @@ -0,0 +1,77 @@ +package com.neuronrobotics.bowlerstudio.util; + +import static com.neuronrobotics.bowlerstudio.scripting.DownloadManager.legacySystemRun; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import com.neuronrobotics.bowlerstudio.scripting.BlenderLoader; +import com.neuronrobotics.bowlerstudio.scripting.DownloadManager; + +import eu.mihosoft.vrl.v3d.CSG; + +public class GeometrySimplification { + /** + * Re-mesh the CSG to a voxelated mesh + * @param incoming the incoming CSG + * @param MMVoxel the mm dimentions of the voxel + * @return a re-meshed CSG + * @throws Exception + */ + public static CSG remesh(CSG incoming, double MMVoxel) throws Exception { + return BlenderLoader.remesh(incoming, MMVoxel); + } + /** + * RE-mesh an STL file in place + * This modifys the original STL + * @param stlout the file in which he STL is stored + * @param MMVoxel the mm dimention of the voxels + * @throws Exception + */ + public static void remeshSTLFile(File stlout,double MMVoxel) throws Exception { + BlenderLoader.remeshSTLFile(stlout, MMVoxel); + } + /** + * Simplify an SVG file + * @param incoming the incoming SVG file + * @param threshhold the threshhold value (default is 0.002 + * @return A new SVG file that is changed + */ + public static File simplifySVG(File incoming) { + return simplifySVG(incoming,0.002); + } + /** + * Simplify an SVG file + * @param incoming the incoming SVG file + * @param threshhold the threshhold value (default is 0.002 + * @return A new SVG file that is changed + */ + public static File simplifySVG(File incoming, double threshhold) { + try { + File inkscape = DownloadManager.getConfigExecutable("inkscape", null); + File svg = File.createTempFile(incoming.getName(), ".svg"); + List args = Arrays.asList( + inkscape.getAbsolutePath(), + "--actions", + "\"select-all:all;path-simplify:threshold=" + threshhold+ ";;export-overwrite;export-do;quit-inkscape\"", + incoming.getAbsolutePath() + ); + legacySystemRun(null, inkscape.getAbsoluteFile().getParentFile(), System.out, args); + args = Arrays.asList( + inkscape.getAbsolutePath(), + "--export-plain-svg", + "--export-type=svg", + "--vacuum-defs", + "--export-filename="+svg.getAbsolutePath(), + incoming.getAbsolutePath() + ); + legacySystemRun(null, inkscape.getAbsoluteFile().getParentFile(), System.out, args); + return svg; + } catch (Exception e) { + // Auto-generated catch block + e.printStackTrace(); + } + return incoming; + } +} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/util/IFileChangeListener.java b/src/main/java/com/neuronrobotics/bowlerstudio/util/IFileChangeListener.java index 38fcf66ed..d4a066c2e 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/util/IFileChangeListener.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/util/IFileChangeListener.java @@ -3,7 +3,7 @@ import java.io.File; import java.nio.file.WatchEvent; -// TODO: Auto-generated Javadoc +// Auto-generated Javadoc /** * The listener interface for receiving IFileChange events. * The class that is interested in processing a IFileChange diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/IVitamin.java b/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/IVitamin.java deleted file mode 100644 index 3587c27f0..000000000 --- a/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/IVitamin.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.neuronrobotics.bowlerstudio.vitamins; - -import eu.mihosoft.vrl.v3d.CSG; - -public interface IVitamin { - - public CSG toCSG(); -} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/MicroServo.java b/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/MicroServo.java deleted file mode 100644 index 01adb41cf..000000000 --- a/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/MicroServo.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.neuronrobotics.bowlerstudio.vitamins; - -import java.io.File; -import java.io.IOException; - -import com.neuronrobotics.imageprovider.NativeResource; - -import eu.mihosoft.vrl.v3d.CSG; -import eu.mihosoft.vrl.v3d.STL; -import eu.mihosoft.vrl.v3d.Transform; - -public class MicroServo implements IVitamin { - - private static CSG servoModel; - - static { - - try { - File stl = NativeResource.inJarLoad(IVitamin.class, "hxt900-servo.stl"); - servoModel = STL.file(stl.toPath()); - servoModel = servoModel.transformed(new Transform().translateZ(-19.3)); - servoModel = servoModel.transformed(new Transform().translateX(5.4)); - -// stl = NativeResource.inJarLoad(IVitamin.class ,"arm.stl"); -// servoModel=servoModel.union(STL.file(stl.toPath())); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Override - public CSG toCSG() { - return servoModel.clone(); - } - -} diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/Purchasing.java b/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/Purchasing.java index 021b93e6e..addaf30f8 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/Purchasing.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/Purchasing.java @@ -81,8 +81,8 @@ public static void saveDatabase(String type) throws Exception { "Pushing changed Database");//commit message } catch (org.eclipse.jgit.api.errors.TransportException ex) { - System.out.println("You need to fork " + getGitRpoDatabase() + " to have permission to save"); - System.out.println( + com.neuronrobotics.sdk.common.Log.error("You need to fork " + getGitRpoDatabase() + " to have permission to save"); + com.neuronrobotics.sdk.common.Log.error( "You do not have permission to push to this repo, change the GIT repo to your fork with setGitRpoDatabase(String gitRpoDatabase) "); throw ex; } @@ -184,7 +184,7 @@ public static ArrayList listVitaminTypes() { } } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } return types; diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/VitaminBomManager.java b/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/VitaminBomManager.java index 5fbb34120..f18dd7d42 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/VitaminBomManager.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/VitaminBomManager.java @@ -29,29 +29,28 @@ import javafx.scene.paint.Color; public class VitaminBomManager { - public static final String MANUFACTURING_BOM_BASE = "manufacturing/bom"; - public static final String MANUFACTURING_BOM_JSON = MANUFACTURING_BOM_BASE + ".json"; - public static final String MANUFACTURING_BOM_CSV = MANUFACTURING_BOM_BASE + ".csv"; + private static final String MANUFACTURING_BOM_BASE = "manufacturing/BillOfMaterials"; + private static final String MANUFACTURING_BOM_JSON = getManufacturingBomBase() + ".json"; + private static final String MANUFACTURING_BOM_CSV = getManufacturingBomBase() + ".csv"; private static boolean saving = false; -// private class VitaminLocation { -// String name; -// String type; -// String size; -// TransformNR pose; -// } - Type type = new TypeToken>>() { }.getType(); - Gson gson = new GsonBuilder().disableHtmlEscaping() - .excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create(); + Gson gson = new GsonBuilder().disableHtmlEscaping().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting() + .create(); private HashMap> database = null;// - private String baseURL; + private String baseURL = null; + private File baseWorkspaceFile; public VitaminBomManager(String url) throws IOException { + this(ScriptingEngine.getRepositoryCloneDirectory(url)); baseURL = url; - File baseWorkspaceFile = ScriptingEngine.getRepositoryCloneDirectory(baseURL); - File bom = new File(baseWorkspaceFile.getAbsolutePath() + "/" + MANUFACTURING_BOM_JSON); + + } + + public VitaminBomManager(File parentFile) { + baseWorkspaceFile = parentFile; + File bom = getBomFile(); if (!bom.exists()) { if (!bom.getParentFile().exists()) { bom.getParentFile().mkdir(); @@ -59,7 +58,7 @@ public VitaminBomManager(String url) throws IOException { try { bom.createNewFile(); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } else { @@ -68,41 +67,69 @@ public VitaminBomManager(String url) throws IOException { try { bytes = Files.readAllBytes(bom.toPath()); source = new String(bytes, "UTF-8"); - if(source.length()>0) + if (source.length() > 0) database = gson.fromJson(source, type); } catch (Exception ex) { ex.printStackTrace(); } } - if(database==null) { - database=new HashMap>(); + if (database == null) { + database = new HashMap>(); save(); } } - -// public void set(String name, String type, String size, TransformNR location) { -// VitaminLocation newElement = getElement(name); -// if (newElement == null) { -// newElement = new VitaminLocation(name,type,size,location); -// } -// newElement.setLocation(location); -// newElement.setSize(size); -// newElement.setType(type); -// addVitamin(newElement); -// // newElement.url=(String) getConfiguration(name).get("source"); -// } - - public void addVitamin(VitaminLocation newElement) { + public File getBomCsv() { + return new File(baseWorkspaceFile.getAbsolutePath() + "/" + getManufacturingBomCsv()); + } + public File getBomFile() { + return new File(baseWorkspaceFile.getAbsolutePath() + "/" + getManufacturingBomJson()); + } + public VitaminLocation getByName(String name) { + for(String keys:database.keySet()) { + ArrayList arrayList = database.get(keys); + for (int i = 0; i < arrayList.size(); i++) { + VitaminLocation vl = arrayList.get(i); + if(vl.getName().contentEquals(name)) { + return vl; + } + } + } + return null; + } + public VitaminBomManager addVitamin(VitaminLocation newElement) { + return addVitamin(newElement,true); + } + public VitaminBomManager addVitamin(VitaminLocation newElement, boolean save) { + for(String keys:database.keySet()) { + ArrayList arrayList = database.get(keys); + for (int i = 0; i < arrayList.size(); i++) { + VitaminLocation vl = arrayList.get(i); + if(vl.getName().contentEquals(newElement.getName())) { + arrayList.remove(vl); + break; + } + } + } String key = newElement.getType() + ":" + newElement.getSize(); // synchronized (database) { if (database.get(key) == null) { database.put(key, new ArrayList()); } - boolean toAdd=!database.get(key).contains(newElement); + ArrayList arrayList = database.get(key); + + boolean toAdd = !arrayList.contains(newElement); + for (int i = 0; i < arrayList.size(); i++) { + VitaminLocation loc = arrayList.get(i); + if(loc.getName().contentEquals(newElement.getName())) { + arrayList.set(i,newElement); + return this; + } + } if (toAdd) - database.get(key).add(newElement); + arrayList.add(newElement); // } - save(); + if(save)save(); + return this; } public CSG get(String name) { @@ -111,7 +138,8 @@ public CSG get(String name) { throw new RuntimeException("Vitamin must be defined before it is used: " + name); try { - CSG transformed = MobileBaseCadManager.vitaminMakeCSG(e).transformed(TransformFactory.nrToCSG(e.getLocation())); + CSG transformed = MobileBaseCadManager.vitaminMakeCSG(e) + .transformed(TransformFactory.nrToCSG(e.getLocation())); transformed.setManufacturing(incominng -> { return null; }); @@ -119,7 +147,7 @@ public CSG get(String name) { return transformed; } catch (Exception e1) { - // TODO Auto-generated catch block + // Auto-generated catch block e1.printStackTrace(); } return null; @@ -130,11 +158,11 @@ public TransformNR getCoMLocation(String name) { try { double x = (double) getConfiguration(name).get("massCentroidX"); double y = (double) getConfiguration(name).get("massCentroidY"); - + double z = (double) getConfiguration(name).get("massCentroidZ"); return e.getLocation().copy().translateX(x).translateY(y).translateZ(z); - }catch(Exception ex) { + } catch (Exception ex) { return e.getLocation().copy(); } } @@ -142,28 +170,29 @@ public TransformNR getCoMLocation(String name) { public double getMassKg(String name) { try { return (double) getConfiguration(name).get("massKg"); - }catch(Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); return 0.001; } } - public Map getConfiguration(String name) throws Exception{ + public Map getConfiguration(String name) throws Exception { VitaminLocation e = getElement(name); if (e == null) throw new RuntimeException("Vitamin must be defined before it is used: " + name); - if(e.isScript()) + if (e.isScript()) throw new RuntimeException("Script Vitamins do not have configurations"); return Vitamins.getConfiguration(e.getType(), e.getSize()); } - private VitaminLocation getElement(String name) { + public VitaminLocation getElement(String name) { // synchronized (database) { for (String testName : database.keySet()) { ArrayList list = database.get(testName); for (VitaminLocation el : list) { - if (el.getName().contentEquals(name)) + String name2 = el.getName(); + if (name2.contentEquals(name)) return el; } } @@ -171,13 +200,14 @@ private VitaminLocation getElement(String name) { return null; } - public void clear() { + public VitaminBomManager clear() { // synchronized (database) { database.clear(); // } + return this; } - private void saveLocal() { + private synchronized void saveLocal() { saving = true; String csv = "name,qty,source,unit price (USD)\n"; String content = null; @@ -190,49 +220,43 @@ private void saveLocal() { if (list.size() > 0) { VitaminLocation e = list.get(0); String size = database.get(key).size() + ""; - String URL =null; - Object object =null; - if(!e.isScript()) + String URL = null; + Object object = null; + if (!e.isScript()) try { Map configuration = getConfiguration(e.getName()); - URL=(String) configuration.get("source"); - object= configuration.get("price"); - }catch(Exception ex) { + URL = (String) configuration.get("source"); + object = configuration.get("price"); + } catch (Exception ex) { ex.printStackTrace(); } - if(URL==null) { - URL="http://commonwealthrobotics.com"; + if (URL == null) { + URL = "http://commonwealthrobotics.com"; } - if(object==null) - object="0.01"; - - csv += key + "," + size + "," + URL +","+object+ "\n"; - } else { - System.out.println("Failure on " + key); - } - } + if (object == null) + object = "0.01"; - try { - String current = ScriptingEngine.codeFromGit(baseURL, MANUFACTURING_BOM_CSV)[0]; - String currentJ = ScriptingEngine.codeFromGit(baseURL, MANUFACTURING_BOM_JSON)[0]; - if (current.contentEquals(csv) && currentJ.contentEquals(content)) { - //System.out.println("No update, BoM current"); - saving = false; - return; - } - } catch (Exception e1) { - // file doesnt exist + csv += key + "," + size + "," + URL + "," + object + "\n"; + } } + if (baseURL != null) + try { + String current = ScriptingEngine.codeFromGit(baseURL, getManufacturingBomCsv())[0]; + String currentJ = ScriptingEngine.codeFromGit(baseURL, getManufacturingBomJson())[0]; + if (current.contentEquals(csv) && currentJ.contentEquals(content)) { + // com.neuronrobotics.sdk.common.Log.error("No update, BoM current"); + saving = false; + return; + } + } catch (Exception e1) { + // file doesnt exist + } try { - write(MANUFACTURING_BOM_JSON, content); - write(MANUFACTURING_BOM_CSV, csv); -// ScriptingEngine.commit(baseURL, ScriptingEngine.getBranch(baseURL), MANUFACTURING_BOM_JSON, content, -// "Save Bill Of Material", true); -// ScriptingEngine.commit(baseURL, ScriptingEngine.getBranch(baseURL), MANUFACTURING_BOM_CSV, csv, -// "Save Bill Of Material", true); + write(getManufacturingBomJson(), content); + write(getManufacturingBomCsv(), csv); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } saving = false; @@ -241,7 +265,7 @@ private void saveLocal() { private void write(String file, String content) throws InvalidRemoteException, TransportException, GitAPIException, IOException { - File f = ScriptingEngine.fileFromGit(baseURL, file); + File f = new File(baseWorkspaceFile.getAbsolutePath() + "/" + file); if (!f.getParentFile().exists()) f.getParentFile().mkdir(); if (!f.exists()) { @@ -252,25 +276,52 @@ private void write(String file, String content) writer.close(); } - public void save() { + public VitaminBomManager save() { saveLocal(); + return this; } - public void loadBaseVitamins(MobileBase base) { - for(VitaminLocation v:base.getVitamins()) { + public VitaminBomManager loadBaseVitamins(MobileBase base) { + for (VitaminLocation v : base.getVitamins()) { addVitamin(v); } - for(DHParameterKinematics k:base.getAllDHChains()) { - for(int i=0;i arrayList = database.get(keys); + for (int i = 0; i < arrayList.size(); i++) { + VitaminLocation vl = arrayList.get(i); + if(vl.getName().contentEquals(loc.getName())) { + arrayList.remove(vl); + return; + } + } + } } } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/Vitamins.java b/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/Vitamins.java index 237788740..3d76161b9 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/Vitamins.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/vitamins/Vitamins.java @@ -1,20 +1,25 @@ package com.neuronrobotics.bowlerstudio.vitamins; import java.io.File; +import java.io.FileInputStream; import java.io.IOException; -import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; import com.neuronrobotics.sdk.common.Log; import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.Cube; import eu.mihosoft.vrl.v3d.STL; import eu.mihosoft.vrl.v3d.Transform; +import eu.mihosoft.vrl.v3d.ext.openjfx.importers.obj.ObjImporter; import eu.mihosoft.vrl.v3d.parametrics.LengthParameter; import eu.mihosoft.vrl.v3d.parametrics.StringParameter; +import javafx.scene.paint.Color; import com.neuronrobotics.bowlerstudio.BowlerKernel; import com.neuronrobotics.bowlerstudio.IssueReportingExceptionHandler; @@ -50,24 +55,26 @@ public class Vitamins { private static String jsonRootDir = "json/"; - private static final Map fileLastLoaded = new HashMap(); - private static final Map>> databaseSet = new HashMap>>(); - private static final String defaultgitRpoDatabase = "https://github.com/madhephaestus/Hardware-Dimensions.git"; - private static String gitRpoDatabase = defaultgitRpoDatabase; + private static final Map fileLastLoaded = new ConcurrentHashMap(); + private static final Map>> databaseSet = new ConcurrentHashMap>>(); + private static final String sourceRepo = "CommonWealthRobotics/Hardware-Dimensions"; + private static final String defaultGit = "https://github.com/" + getSourcerepo() + ".git"; + private static String gitRpoDatabase = defaultGit; // Create the type, this tells GSON what datatypes to instantiate when parsing // and saving the json - private static Type TT_mapStringString = new TypeToken>>() { + private static Type TT_mapStringString = new TypeToken>>() { }.getType(); // chreat the gson object, this is the parsing factory private static Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); private static boolean checked; - private static HashMap changeListeners = new HashMap(); + private static ConcurrentHashMap changeListeners = new ConcurrentHashMap(); + public static void clear() { - System.out.println("Vitamins Database Cleraing, reloading files"); - for(String keys:databaseSet.keySet()) { - HashMap> data = databaseSet.get(keys); - for(String key2:data.keySet()) { - HashMap data2 = data.get(key2); + com.neuronrobotics.sdk.common.Log.error("Vitamins Database Cleraing, reloading files"); + for (String keys : databaseSet.keySet()) { + ConcurrentHashMap> data = databaseSet.get(keys); + for (String key2 : data.keySet()) { + ConcurrentHashMap data2 = data.get(key2); data2.clear(); } data.clear(); @@ -75,16 +82,21 @@ public static void clear() { databaseSet.clear(); fileLastLoaded.clear(); } + public static CSG get(File resource) { - return get(resource,false); + return get(resource, false); } + public static CSG get(File resource, boolean forceRefresh) { - if (fileLastLoaded.get(resource.getAbsolutePath()) == null||forceRefresh) { + if (fileLastLoaded.get(resource.getAbsolutePath()) == null || forceRefresh) { // forces the first time the files is accessed by the application tou pull an // update try { - fileLastLoaded.put(resource.getAbsolutePath(), STL.file(resource.toPath())); + if(resource.getName().toLowerCase().endsWith(".stl")) + fileLastLoaded.put(resource.getAbsolutePath(), STL.file(resource.toPath())); +// if(resource.getName().toLowerCase().endsWith(".obj")) +// fileLastLoaded.put(resource.getAbsolutePath(), new ObjImporter(new FileInputStream(resource)).); // try { // FileChangeWatcher f = FileChangeWatcher.watch(resource); // f.addIFileChangeListener(new IFileChangeListener() { @@ -101,16 +113,17 @@ public static CSG get(File resource, boolean forceRefresh) { // } // }); // } catch (IOException e) { -// // TODO Auto-generated catch block +// // Auto-generated catch block // e.printStackTrace(); // } } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } + CSG csg = fileLastLoaded.get(resource.getAbsolutePath()); - return fileLastLoaded.get(resource.getAbsolutePath()).clone(); + return csg.clone().setRegenerate(csg.getRegenerate()).syncProperties(csg); } public static CSG get(String type, String id, String purchasingVariant) throws Exception { @@ -129,7 +142,7 @@ public static CSG get(String type, String id, String purchasingVariant) throws E } catch (Exception e) { e.printStackTrace(); - gitRpoDatabase = defaultgitRpoDatabase; + setGitRepoDatabase(gitRpoDatabase); clear(); return get(type, id); } @@ -137,7 +150,7 @@ public static CSG get(String type, String id, String purchasingVariant) throws E } CSG vitToGet = fileLastLoaded.get(type + id); - // System.err.println("Loading "+vitToGet); + // com.neuronrobotics.sdk.common.Log.error("Loading "+vitToGet); return vitToGet; } @@ -151,38 +164,32 @@ public static boolean isGitURL(String text2) { } catch (Exception ex) { if (!text2.startsWith("git@")) { ex.printStackTrace(); - return false ; + return false; } } return true; } + public static void flatten(ArrayList flat, Object o) { - if(CSG.class.isInstance(o)) - flat.add((CSG)o); - if(List.class.isInstance(o)) { - for(Object ob:(List)o) { - flatten(flat,ob); - } - } - + ScriptingEngine.flatten(flat, o); } - + public static CSG get(String type, String id) throws Exception { - if(isGitURL(type)) { - Object o =ScriptingEngine.gitScriptRun(type, id); - ArrayList flat= new ArrayList(); - Vitamins.flatten(flat,o); - return CSG.unionAll( flat); + if (isGitURL(type)) { + Object o = ScriptingEngine.gitScriptRun(type, id); + ArrayList flat = new ArrayList(); + Vitamins.flatten(flat, o); + return CSG.unionAll(flat); } return get(type, id, 0); } private static CSG get(String type, String id, int depthGauge) throws Exception { String key = type + id; + Map script = getMeta(type); try { CSG newVitamin = null; - Map script = getMeta(type); StringParameter size = new StringParameter(type + " Default", id, Vitamins.listVitaminSizes(type)); size.setStrValue(id); Object file = script.get("scriptGit"); @@ -196,20 +203,20 @@ private static CSG get(String type, String id, int depthGauge) throws Exception repostring.toString(), // file to load servoMeasurments); Map configuration = Vitamins.getConfiguration(type, id); - newVitamin.setName(type +"-"+ id); + newVitamin.setName(type + "-" + id); newVitamin.setManufacturing(incoming -> null); try { Transform com = new Transform() - .movex(Double.parseDouble(configuration.get("massCentroidX").toString())) - .movey(Double.parseDouble(configuration.get("massCentroidY").toString())) - .movez(Double.parseDouble(configuration.get("massCentroidZ").toString())); + .movex(Double.parseDouble(configuration.get("massCentroidX").toString())) + .movey(Double.parseDouble(configuration.get("massCentroidY").toString())) + .movez(Double.parseDouble(configuration.get("massCentroidZ").toString())); newVitamin.getStorage().set("massKg", configuration.get("massKg")); newVitamin.getStorage().set("massCentroid", com); - + return newVitamin; - }catch(Exception ex) { - //System.err.println(type +"-"+ id+" Failed"); - //ex.printStackTrace(); + } catch (Exception ex) { + // com.neuronrobotics.sdk.common.Log.error(type +"-"+ id+" Failed"); + // ex.printStackTrace(); return newVitamin; } } else { @@ -218,205 +225,220 @@ private static CSG get(String type, String id, int depthGauge) throws Exception } } catch (Exception e) { e.printStackTrace(); - gitRpoDatabase = defaultgitRpoDatabase; + setGitRepoDatabase(gitRpoDatabase); + //ScriptingEngine.deleteRepo(script.get("scriptGit").toString()); clear(); if (depthGauge < 2) { return get(type, id, depthGauge + 1); } else { - return null; + return new Cube(20).toCSG().setColor(Color.RED); } } } + public static String getScriptGitURL(String type) { Map script = getMeta(type); - - + return script.get("scriptGit").toString(); } + + public static void loadAllScriptFiles() { + for (String type : listVitaminTypes()) { + getScriptFile(type); + } + } + public static File getScriptFile(String type) { Map script = getMeta(type); - + try { return ScriptingEngine.fileFromGit(script.get("scriptGit").toString(), script.get("scriptFile").toString()); } catch (InvalidRemoteException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } catch (TransportException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } catch (GitAPIException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } return null; } public static Map getMeta(String type) { - return getConfigurationRW(type, "meta"); + return getConfiguration(type, "meta"); } public static void setScript(String type, String git, String file) throws Exception { setParameter(type, "meta", "scriptGit", git); setParameter(type, "meta", "scriptFile", file); } - - public static Map getConfiguration(String type, String id){ - return Collections.unmodifiableMap(getConfigurationRW( type, id)); + + public static Map getConfiguration(String type, String id) { + ConcurrentHashMap> database = getDatabase(type); + if (id== null) { + id=Vitamins.listVitaminSizes(type).get(0); + } + + ConcurrentHashMap ConcurrentHashMap = database.get(id); + Object[] array = ConcurrentHashMap.keySet().toArray(); + for (int i = 0; i < array.length; i++) { + String key = (String) array[i]; + sanatize(key, ConcurrentHashMap); + } + return Collections.unmodifiableMap(ConcurrentHashMap); } - public static void putMeasurment(String type, String size,String measurementName, Object measurmentValue) { - getConfigurationRW(type,size).put(measurementName, measurmentValue); + + public static void putMeasurment(String type, String size, String measurementName, Object measurmentValue) { + ConcurrentHashMap configurationRW = getConfigurationRW(type, size); + configurationRW.put(measurementName, measurmentValue); + sanatize(measurementName, configurationRW); } - public static Object getMeasurement(String type, String size,String measurementName) { - return getConfigurationRW(type,size).get(measurementName); + + public static Object getMeasurement(String type, String size, String measurementName) { + return getConfigurationRW(type, size).get(measurementName); } - public static HashMap getConfigurationRW(String type, String id) { - HashMap> database = getDatabase(type); - if (database.get(id) == null) { - database.put(id, new HashMap()); + + public static ConcurrentHashMap getConfigurationRW(String type, String id) { + ConcurrentHashMap> database = getDatabase(type); + if (id == null) { + id=Vitamins.listVitaminSizes(type).get(0); } - for(int j=0;j<5;j++) { - try { - HashMap hashMap = database.get(id); - Object[] array = hashMap.keySet().toArray(); - for (int i=0;i ConcurrentHashMap = database.get(id); + if(ConcurrentHashMap == null) { + ConcurrentHashMap=new ConcurrentHashMap (); + + database.put(id, ConcurrentHashMap); + } + Object[] array = ConcurrentHashMap.keySet().toArray(); + for (int i = 0; i < array.length; i++) { + String key = (String) array[i]; + sanatize(key, ConcurrentHashMap); } - return new HashMap(); + return ConcurrentHashMap; + } public static String makeJson(String type) { return gson.toJson(getDatabase(type), TT_mapStringString); } - public static void saveDatabase(String type) throws Exception { + public static boolean saveDatabase(String type) throws Exception { // Save contents and publish them String jsonString = makeJson(type); try { - //new Exception().printStackTrace(); - ScriptingEngine.pushCodeToGit(getGitRepoDatabase(), // git repo, change this if you fork this demo - ScriptingEngine.getFullBranch(getGitRepoDatabase()), // branch or tag + // new Exception().printStackTrace(); + String gitRepoDatabase = getGitRepoDatabase(); + ScriptingEngine.pushCodeToGit(gitRepoDatabase, // git repo, change this if you fork this demo + null, // branch or tag getRootFolder() + type + ".json", // local path to the file in git jsonString, // content of the file - "Making changes to "+type+" by "+PasswordManager.getUsername()+"\n\nAuto-save inside com.neuronrobotics.bowlerstudio.vitamins.Vitamins inside bowler-scripting-kernel");// commit message - //System.err.println(jsonString); - System.out.println("Database saved "+getVitaminFile(type,null,false).getAbsolutePath()); - } catch (org.eclipse.jgit.api.errors.TransportException ex) { - System.out.println("You need to fork " + defaultgitRpoDatabase + " to have permission to save"); - System.out.println( - "You do not have permission to push to this repo, change the GIT repo to your fork with setGitRpoDatabase(String gitRpoDatabase) "); + "Making changes to " + type + " by " + PasswordManager.getUsername() + + "\n\nAuto-save inside com.neuronrobotics.bowlerstudio.vitamins.Vitamins inside bowler-scripting-kernel");// commit + // message + // com.neuronrobotics.sdk.common.Log.error(jsonString); + com.neuronrobotics.sdk.common.Log.error("Database saved " + getVitaminFile(type, null, false).getAbsolutePath()); + } catch (Exception ex) { + if(ex.getMessage().contains("Cannot commit on a repo with state: MERGING")) { + ScriptingEngine.deleteRepo(getGitRepoDatabase()); + saveDatabase(type); + return true; + } + ex.printStackTrace(); throw ex; } - + return true; } - public static void saveDatabaseForkIfMissing(String type) throws Exception { + + public static void saveDatabaseForkIfMissing(String type,String username) throws Exception { org.kohsuke.github.GitHub github = PasswordManager.getGithub(); - GHRepository repo = github.getRepository("madhephaestus/Hardware-Dimensions"); + GHRepository repo = github.getRepository(getSourcerepo()); + GHRepository newRepo; try { - saveDatabase(type); - } catch (org.eclipse.jgit.api.errors.TransportException ex) { - System.err.println("Forked repo is missing!"); - - GHRepository newRepo = repo.fork(); - Thread.sleep(6000); - Vitamins.gitRpoDatabase = newRepo.getGitTransportUrl().replaceAll("git://", "https://"); - saveDatabase(type); - - } - if(PasswordManager.getUsername().contentEquals("madhephaestus")) - return; - try { - GHRepository myrepo = github.getRepository(PasswordManager.getUsername()+"/Hardware-Dimensions"); - List asList1 = myrepo.queryPullRequests().state(GHIssueState.OPEN).head("madhephaestus:master") - .list().asList(); - Thread.sleep(200);// Some asynchronus delay here, not sure why... - if(asList1.size()==0) { - try { - GHPullRequest request = myrepo.createPullRequest("Update from source", - "madhephaestus:master", - "master", - "## Upstream add vitamins", - false, false); - if(request!=null) { - processSelfPR(request); - } - }catch(org.kohsuke.github.HttpException ex) { - // no commits have been made to master - } - - }else { - processSelfPR(asList1.get(0)); - } - String head = PasswordManager.getUsername()+":master"; - List asList = repo.queryPullRequests() - .state(GHIssueState.OPEN) - .head(head) - .list().asList(); - if(asList.size()==0) { - System.err.println("Creating PR for "+head); - GHPullRequest request = repo.createPullRequest("User Added vitamins to "+type, - head, - "master", - "## User added vitamins", - true, true); + newRepo=github.getRepository(username+"/Hardware-Dimensions"); + String newURL = newRepo.getGitTransportUrl().replaceAll("git://", "https://"); + ScriptingEngine.pull(newURL); + ArrayList files = ScriptingEngine.filesInGit(newURL); + if(type!=null) + saveDatabase(type); + } catch (Exception ex) { + ex.printStackTrace(); + com.neuronrobotics.sdk.common.Log.error("Forked repo is missing!"); + + newRepo = github.getRepository(getSourcerepo()).fork(); + while(true) { try { - BowlerKernel.upenURL(request.getHtmlUrl().toURI()); - } catch (URISyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + Thread.sleep(6000); + String newURL = newRepo.getGitTransportUrl().replaceAll("git://", "https://"); + Vitamins.setGitRepoDatabase(newURL); + break; + }catch(Exception exc) { + System.err.println("Waiting for repo to finish forking"); + exc.printStackTrace(); } - }else { - } - }catch(Exception ex) { - new IssueReportingExceptionHandler().uncaughtException(Thread.currentThread(),ex); + saveDatabase(type); + } - + +// try { +// GHRepository myrepo = github.getRepository(username+ "/Hardware-Dimensions"); +// List asList1 = myrepo.queryPullRequests().state(GHIssueState.OPEN) +// .head("madhephaestus:master").list().asList(); +// Thread.sleep(200);// Some asynchronus delay here, not sure why... +// if (asList1.size() == 0) { +// try { +// GHPullRequest request = myrepo.createPullRequest("Update from source", "madhephaestus:master", +// "master", "## Upstream add vitamins", false, false); +// if (request != null) { +// processSelfPR(request); +// } +// } catch (org.kohsuke.github.HttpException ex) { +// // no commits have been made to master +// } +// +// } else { +// processSelfPR(asList1.get(0)); +// } +// +// } catch (Exception ex) { +// new IssueReportingExceptionHandler().uncaughtException(Thread.currentThread(), ex); +// } } private static void processSelfPR(GHPullRequest request) throws IOException { - if(request== null) + if (request == null) return; try { if (request.getMergeable()) { request.merge("Auto Merging Master"); reLoadDatabaseFromFiles(); - System.out.println("Merged Hardware-Dimensions madhephaestus:master into "+PasswordManager.getUsername()+":master"); + com.neuronrobotics.sdk.common.Log.error("Merged Hardware-Dimensions madhephaestus:master into " + + PasswordManager.getUsername() + ":master"); } else { try { BowlerKernel.upenURL(request.getHtmlUrl().toURI()); } catch (URISyntaxException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } - }catch(java.lang.NullPointerException ex) { + } catch (java.lang.NullPointerException ex) { ex.printStackTrace(); } } + public static void newVitamin(String type, String id) throws Exception { - HashMap> database = getDatabase(type); + ConcurrentHashMap> database = getDatabase(type); if (database.keySet().size() > 0) { String exampleKey = null; for (String key : database.keySet()) { @@ -441,15 +463,15 @@ public static void newVitamin(String type, String id) throws Exception { public static void setParameter(String type, String id, String parameterName, Object parameter) throws Exception { - HashMap config = getConfigurationRW(type, id); + ConcurrentHashMap config = getConfigurationRW(type, id); config.put(parameterName, parameter); - sanatize(parameterName, config); + sanatize(parameterName, config); // saveDatabase(type); } - private static void sanatize(String parameterName, HashMap config) { - Object parameter=config.get(parameterName); + private static void sanatize(String parameterName, ConcurrentHashMap config) { + Object parameter = config.get(parameterName); try { config.put(parameterName, Double.parseDouble(parameter.toString())); } catch (NumberFormatException ex) { @@ -457,7 +479,7 @@ private static void sanatize(String parameterName, HashMap conf } } - public static HashMap> getDatabase(String type) { + public static ConcurrentHashMap> getDatabase(String type) { if (databaseSet.get(type) == null) { // we are using the default vitamins configuration // https://github.com/madhephaestus/Hardware-Dimensions.git @@ -469,40 +491,39 @@ public static HashMap> getDatabase(String type) // attempt to load the JSON file from the GIt Repo and pars the JSON string File f; try { - - Runnable onChange=null; - if(changeListeners.get(type)==null) { - changeListeners.put(type,() -> { + + Runnable onChange = null; + if (changeListeners.get(type) == null) { + changeListeners.put(type, () -> { // If the file changes, clear the database and load the new data - System.out.println("Re-loading "+type); - databaseSet.put(type,null); + com.neuronrobotics.sdk.common.Log.error("Re-loading " + type); + databaseSet.put(type, null); new RuntimeException().printStackTrace(); }); - onChange=changeListeners.get(type); + onChange = changeListeners.get(type); } - - - f = getVitaminFile(type,onChange,true); - HashMap> database; - if(f.exists()) { - + f = getVitaminFile(type, onChange, true); + + ConcurrentHashMap> database; + if (f.exists()) { + inPut = FileUtils.openInputStream(f); - + jsonString = IOUtils.toString(inPut); inPut.close(); - System.out.println("JSON loading Loading "+type+" "+jsonString.length()); + com.neuronrobotics.sdk.common.Log.error("JSON loading Loading " + type + " " + jsonString.length()); // perfoem the GSON parse database = gson.fromJson(jsonString, TT_mapStringString); - if(database==null) + if (database == null) throw new RuntimeException("Database failed to read"); - }else { - database=new HashMap>(); + } else { + database = new ConcurrentHashMap>(); } databaseSet.put(type, database); for (String key : databaseSet.get(type).keySet()) { - HashMap conf = database.get(key); + ConcurrentHashMap conf = database.get(key); for (String confKey : conf.keySet()) { try { double num = Double.parseDouble(conf.get(confKey).toString()); @@ -517,7 +538,7 @@ public static HashMap> getDatabase(String type) } catch (Exception e) { e.printStackTrace(); - databaseSet.put(type, new HashMap>()); + databaseSet.put(type, new ConcurrentHashMap>()); } } return databaseSet.get(type); @@ -526,12 +547,11 @@ public static HashMap> getDatabase(String type) public static File getVitaminFile(String type, Runnable onChange, boolean oneShot) throws InvalidRemoteException, TransportException, GitAPIException, IOException { - - - File f= ScriptingEngine.fileFromGit(getGitRepoDatabase(), // git repo, change this if you fork this demo + + File f = ScriptingEngine.fileFromGit(getGitRepoDatabase(), // git repo, change this if you fork this demo getRootFolder() + type + ".json"// File from within the Git repo ); - if(onChange!=null) { + if (onChange != null) { // FileChangeWatcher watcher = FileChangeWatcher.watch(f); // watcher.addIFileChangeListener((fileThatChanged, event) -> { // onChange.run(); @@ -543,36 +563,40 @@ public static File getVitaminFile(String type, Runnable onChange, boolean oneSho private static String getRootFolder() { return getJsonRootDir(); } - public static ArrayList listVitaminActuators() { - ArrayList actuators = new ArrayList(); - + + public static CopyOnWriteArrayList listVitaminActuators() { + CopyOnWriteArrayList actuators = new CopyOnWriteArrayList(); + for (String vitaminsType : Vitamins.listVitaminTypes()) { - if (isActuator( vitaminsType)) + if (isActuator(vitaminsType)) actuators.add(vitaminsType); } return actuators; } - public static ArrayList listVitaminShafts() { - ArrayList actuators = new ArrayList(); + + public static CopyOnWriteArrayList listVitaminShafts() { + CopyOnWriteArrayList actuators = new CopyOnWriteArrayList(); for (String vitaminsType : Vitamins.listVitaminTypes()) { - if (isShaft( vitaminsType)) + if (isShaft(vitaminsType)) actuators.add(vitaminsType); } return actuators; } - + public static boolean isShaft(String vitaminsType) { Map meta = Vitamins.getMeta(vitaminsType); if (meta != null && meta.containsKey("shaft")) return true; return false; } + public static boolean isActuator(String vitaminsType) { Map meta = Vitamins.getMeta(vitaminsType); if (meta != null && meta.containsKey("actuator")) return true; return false; } + public static void setIsShaft(String type) { Vitamins.getMeta(type).remove("motor"); Vitamins.getMeta(type).put("shaft", "true"); @@ -582,12 +606,14 @@ public static void setIsActuator(String type) { Vitamins.getMeta(type).remove("shaft"); Vitamins.getMeta(type).put("actuator", "true"); } - public static ArrayList listVitaminTypes() { - ArrayList types = new ArrayList(); + public static CopyOnWriteArrayList listVitaminTypes() { + + CopyOnWriteArrayList types = new CopyOnWriteArrayList(); File folder; - try { - folder = new File(ScriptingEngine.getRepositoryCloneDirectory(getGitRepoDatabase()).getAbsoluteFile()+"/"+getRootFolder()); + try { + folder = new File(ScriptingEngine.getRepositoryCloneDirectory(getGitRepoDatabase()).getAbsoluteFile() + "/" + + getRootFolder()); File[] listOfFiles = folder.listFiles(); for (File f : listOfFiles) { @@ -597,7 +623,7 @@ public static ArrayList listVitaminTypes() { } } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } Collections.sort(types); @@ -607,7 +633,7 @@ public static ArrayList listVitaminTypes() { public static ArrayList listVitaminSizes(String type) { ArrayList types = new ArrayList(); - HashMap> database = getDatabase(type); + ConcurrentHashMap> database = getDatabase(type); Set keys = database.keySet(); for (Iterator iterator = keys.iterator(); iterator.hasNext();) { String s = iterator.next(); @@ -621,24 +647,24 @@ public static ArrayList listVitaminSizes(String type) { return types; } - public static String getGitRepoDatabase() { + public static String getGitRepoDatabase() { if (!checked) { checked = true; try { if (PasswordManager.getUsername() != null) { - //ScriptingEngine.setAutoupdate(true); + // ScriptingEngine.setAutoupdate(true); org.kohsuke.github.GitHub github = PasswordManager.getGithub(); try { - GHRepository repo =github.getRepository(PasswordManager.getLoginID() + "/Hardware-Dimensions" ); - if(repo!=null) { + GHRepository repo = github.getRepository(PasswordManager.getLoginID() + "/Hardware-Dimensions"); + if (repo != null) { String myAssets = repo.getGitTransportUrl().replaceAll("git://", "https://"); - // System.out.println("Using my version of Viamins: "+myAssets); + // com.neuronrobotics.sdk.common.Log.error("Using my version of Viamins: "+myAssets); setGitRepoDatabase(myAssets); - }else { + } else { throw new org.kohsuke.github.GHFileNotFoundException(); } - }catch(Exception ex) { - setGitRepoDatabase(defaultgitRpoDatabase); + } catch (Exception ex) { + setGitRepoDatabase(defaultGit); } } } catch (Exception ex) { @@ -657,26 +683,27 @@ public static String getGitRepoDatabase() { } public static void reLoadDatabaseFromFiles() { - + setGitRepoDatabase(getGitRepoDatabase()); try { ScriptingEngine.pull(getGitRepoDatabase()); - }catch (CheckoutConflictException|NoHeadException e) { + } catch (CheckoutConflictException | NoHeadException e) { ScriptingEngine.deleteRepo(getGitRepoDatabase()); try { ScriptingEngine.pull(getGitRepoDatabase()); } catch (Exception e1) { - // TODO Auto-generated catch block + // Auto-generated catch block e1.printStackTrace(); } - }catch (Exception e) { + } catch (Exception e) { new IssueReportingExceptionHandler().uncaughtException(Thread.currentThread(), e); } listVitaminTypes(); - + } + public static void setGitRepoDatabase(String gitRpoDatabase) { - Vitamins.gitRpoDatabase = gitRpoDatabase; + Vitamins.gitRpoDatabase=gitRpoDatabase; databaseSet.clear(); fileLastLoaded.clear(); @@ -691,6 +718,8 @@ public static void setJsonRootDir(String jsonRootDir) throws IOException { setGitRepoDatabase(getGitRepoDatabase()); } - + public static String getSourcerepo() { + return sourceRepo; + } } diff --git a/src/main/java/com/neuronrobotics/imageprovider/AbstractImageProvider.java b/src/main/java/com/neuronrobotics/imageprovider/AbstractImageProvider.java index 0f3eb2a3c..d31e4ae06 100644 --- a/src/main/java/com/neuronrobotics/imageprovider/AbstractImageProvider.java +++ b/src/main/java/com/neuronrobotics/imageprovider/AbstractImageProvider.java @@ -41,7 +41,7 @@ public abstract class AbstractImageProvider extends NonBowlerDevice { @Override public void onAsyncResponse(BowlerDatagram data) { - // TODO Auto-generated method stub + // Auto-generated method stub } diff --git a/src/main/java/com/neuronrobotics/imageprovider/NativeResource.java b/src/main/java/com/neuronrobotics/imageprovider/NativeResource.java index 386e61518..df8f74a95 100644 --- a/src/main/java/com/neuronrobotics/imageprovider/NativeResource.java +++ b/src/main/java/com/neuronrobotics/imageprovider/NativeResource.java @@ -40,7 +40,7 @@ private void inJarLoad(String name)throws UnsatisfiedLinkError, NativeResourceEx loadResource(resourceLocation); testNativeCode(); } catch (IOException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } @@ -49,8 +49,8 @@ private void inJarLoad(String name)throws UnsatisfiedLinkError, NativeResourceEx public static File inJarLoad(Class inputClass, String name) throws IOException{ InputStream resourceSource = inputClass.getResourceAsStream(name); File resourceLocation = prepResourceLocation(name); - //System.out.println("Resource selected "+resourceSource); - //System.out.println("Resource target "+resourceLocation); + //com.neuronrobotics.sdk.common.Log.error("Resource selected "+resourceSource); + //com.neuronrobotics.sdk.common.Log.error("Resource target "+resourceLocation); copyResource(resourceSource, resourceLocation); return resourceLocation; @@ -58,8 +58,8 @@ public static File inJarLoad(Class inputClass, String name) throws IOException{ public static File inJarLoad(InputStream inputStream, String name) throws IOException{ InputStream resourceSource = inputStream; File resourceLocation = prepResourceLocation(name); - //System.out.println("Resource selected "+resourceSource); - //System.out.println("Resource target "+resourceLocation); + //com.neuronrobotics.sdk.common.Log.error("Resource selected "+resourceSource); + //com.neuronrobotics.sdk.common.Log.error("Resource target "+resourceLocation); copyResource(resourceSource, resourceLocation); return resourceLocation; @@ -99,17 +99,17 @@ private InputStream locateResource(String name) { } } }else{ - System.err.println("Can't load native file: "+name+" for os arch: "+ getOsArch()); + com.neuronrobotics.sdk.common.Log.error("Can't load native file: "+name+" for os arch: "+ getOsArch()); return null; } - //System.out.println("Loading "+file); + //com.neuronrobotics.sdk.common.Log.error("Loading "+file); return getClass().getResourceAsStream(file); } private void loadResource(File resource) { if(!resource.canRead()) throw new RuntimeException("Cant open JNI file: "+resource.getAbsolutePath()); - //System.out.println("Loading: "+resource.getAbsolutePath()); + //com.neuronrobotics.sdk.common.Log.error("Loading: "+resource.getAbsolutePath()); System.load(resource.getAbsolutePath()); } @@ -190,13 +190,13 @@ public static File prepResourceLocation(String fileName) throws NativeResourceEx if(fd == null || !fd.canRead()) { throw new NativeResourceException("Unable to deploy native resource"); } - //System.out.println("Local file: "+fd.getAbsolutePath()); + //com.neuronrobotics.sdk.common.Log.error("Local file: "+fd.getAbsolutePath()); return fd; } public static boolean is64Bit() { - ////System.out.println("Arch: "+getOsArch()); + ////com.neuronrobotics.sdk.common.Log.error("Arch: "+getOsArch()); return getOsArch().startsWith("x86_64") || getOsArch().startsWith("amd64"); } public static boolean isARM() { @@ -210,7 +210,7 @@ public static boolean isCortexA8(){ return false; } public static boolean isWindows() { - ////System.out.println("OS name: "+getOsName()); + ////com.neuronrobotics.sdk.common.Log.error("OS name: "+getOsName()); return getOsName().toLowerCase().startsWith("windows") ||getOsName().toLowerCase().startsWith("microsoft") || getOsName().toLowerCase().startsWith("ms"); } diff --git a/src/main/java/com/neuronrobotics/imageprovider/StaticFileProvider.java b/src/main/java/com/neuronrobotics/imageprovider/StaticFileProvider.java index 9a59e90e4..8de2ffc35 100644 --- a/src/main/java/com/neuronrobotics/imageprovider/StaticFileProvider.java +++ b/src/main/java/com/neuronrobotics/imageprovider/StaticFileProvider.java @@ -27,19 +27,19 @@ protected boolean captureNewImage(BufferedImage imageData) { @Override public void disconnectDeviceImp() { - // TODO Auto-generated method stub + // Auto-generated method stub } @Override public boolean connectDeviceImp() { - // TODO Auto-generated method stub + // Auto-generated method stub return false; } @Override public ArrayList getNamespacesImp() { - // TODO Auto-generated method stub + // Auto-generated method stub return null; } diff --git a/src/main/java/com/neuronrobotics/imageprovider/URLImageProvider.java b/src/main/java/com/neuronrobotics/imageprovider/URLImageProvider.java index c58ab1480..b1c835c5f 100644 --- a/src/main/java/com/neuronrobotics/imageprovider/URLImageProvider.java +++ b/src/main/java/com/neuronrobotics/imageprovider/URLImageProvider.java @@ -29,19 +29,19 @@ protected boolean captureNewImage(BufferedImage imageData) { @Override public void disconnectDeviceImp() { - // TODO Auto-generated method stub + // Auto-generated method stub } @Override public boolean connectDeviceImp() { - // TODO Auto-generated method stub + // Auto-generated method stub return false; } @Override public ArrayList getNamespacesImp() { - // TODO Auto-generated method stub + // Auto-generated method stub return null; } diff --git a/src/main/java/com/neuronrobotics/imageprovider/VirtualCameraFactory.java b/src/main/java/com/neuronrobotics/imageprovider/VirtualCameraFactory.java index df52cef36..fda1614d6 100644 --- a/src/main/java/com/neuronrobotics/imageprovider/VirtualCameraFactory.java +++ b/src/main/java/com/neuronrobotics/imageprovider/VirtualCameraFactory.java @@ -8,11 +8,11 @@ public class VirtualCameraFactory { @Override public AbstractImageProvider getVirtualCamera() { - // TODO Auto-generated method stub + // Auto-generated method stub try { return new URLImageProvider(new URL("http://commonwealthrobotics.com/img/AndrewHarrington/2014-09-15-86.jpg")); } catch (MalformedURLException e) { - // TODO Auto-generated catch block + // Auto-generated catch block throw new RuntimeException(e); } } diff --git a/src/main/java/com/neuronrobotics/sdk/addons/gamepad/BowlerJInputDevice.java b/src/main/java/com/neuronrobotics/sdk/addons/gamepad/BowlerJInputDevice.java index a22dab883..3b0c58726 100644 --- a/src/main/java/com/neuronrobotics/sdk/addons/gamepad/BowlerJInputDevice.java +++ b/src/main/java/com/neuronrobotics/sdk/addons/gamepad/BowlerJInputDevice.java @@ -17,7 +17,7 @@ import eu.mihosoft.vrl.v3d.JavaFXInitializer; -// TODO: Auto-generated Javadoc +// Auto-generated Javadoc /** * The Class BowlerJInputDevice. */ @@ -96,7 +96,7 @@ private void setControllerByName(List names) { controller = c; break; } else - System.out.println("Non match: " + c.getName() + " " + n); + com.neuronrobotics.sdk.common.Log.error("Non match: " + c.getName() + " " + n); } } } @@ -149,12 +149,12 @@ public void run() { setControllerByName(searches); break; } catch (Throwable t) { - System.out.println("BowlerJInputDevice Waiting for device to be availible"); + com.neuronrobotics.sdk.common.Log.error("BowlerJInputDevice Waiting for device to be availible"); t.printStackTrace(); try { Thread.sleep(1000); } catch (InterruptedException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } @@ -227,7 +227,7 @@ public String getControllerName() { * @param controller the new controller */ public void setController(Controller controller) { - System.out.println("Found! " + controller.getName()); + com.neuronrobotics.sdk.common.Log.error("Found! " + controller.getName()); this.name = controller.getName(); controller.poll(); EventQueue queue = controller.getEventQueue(); @@ -277,7 +277,7 @@ public void addListeners(IGameControlEvent l) { */ @Override public ArrayList getNamespacesImp() { - // TODO Auto-generated method stub + // Auto-generated method stub return new ArrayList(); } @@ -322,13 +322,13 @@ public static void main(String[] args) throws InterruptedException { BowlerJInputDevice g = new BowlerJInputDevice("X-Box","Gamesir","Dragon"); // g.connect(); // Connect to it. g.addListeners((name, value) -> { - System.out.println(g); + com.neuronrobotics.sdk.common.Log.error(g); }); while (g.isAvailable()) Thread.sleep(100); - System.out.println("Controller clean exit"); + com.neuronrobotics.sdk.common.Log.error("Controller clean exit"); } catch (Throwable t) { - System.out.println("Waiting for device to be availible"); + com.neuronrobotics.sdk.common.Log.error("Waiting for device to be availible"); t.printStackTrace(); Thread.sleep(1000); } diff --git a/src/main/java/com/neuronrobotics/sdk/addons/gamepad/ControllerEnvironment.java b/src/main/java/com/neuronrobotics/sdk/addons/gamepad/ControllerEnvironment.java index 97ecc7cbc..58fd47170 100644 --- a/src/main/java/com/neuronrobotics/sdk/addons/gamepad/ControllerEnvironment.java +++ b/src/main/java/com/neuronrobotics/sdk/addons/gamepad/ControllerEnvironment.java @@ -96,7 +96,7 @@ protected static void libfix() { File test = new File(absolutePathToDirectory); if (!test.isDirectory()) absolutePathToDirectory = test.getParentFile().getAbsolutePath(); - // System.out.println("Setting net.java.games.input.librarypath : + // com.neuronrobotics.sdk.common.Log.error("Setting net.java.games.input.librarypath : // "+absolutePathToDirectory); System.setProperty("net.java.games.input.librarypath", absolutePathToDirectory); } diff --git a/src/main/java/com/neuronrobotics/sdk/addons/gamepad/JogTrainerWidget.java b/src/main/java/com/neuronrobotics/sdk/addons/gamepad/JogTrainerWidget.java index 4063b50d3..4d0c861af 100644 --- a/src/main/java/com/neuronrobotics/sdk/addons/gamepad/JogTrainerWidget.java +++ b/src/main/java/com/neuronrobotics/sdk/addons/gamepad/JogTrainerWidget.java @@ -98,7 +98,7 @@ public void handle(ActionEvent event) { List maps = PersistantControllerMap.getDefaultMaps(); int i = 0; - System.out.println("There are "+maps.size()+" rows"); + com.neuronrobotics.sdk.common.Log.error("There are "+maps.size()+" rows"); for (i = 0; i < maps.size(); i++) { String map = maps.get(i); @@ -194,10 +194,10 @@ public void onEvent(String name, float value) { values.put(name,value); timeOfLastAxisSet.put(name, System.currentTimeMillis()); if(abs>0.2) - System.out.println("value for "+name+" seems noisy "+value+" most recent was "+values.get(name)); + com.neuronrobotics.sdk.common.Log.error("value for "+name+" seems noisy "+value+" most recent was "+values.get(name)); return; }else { - System.out.println("Value changed! "+name+" "+float1+" to "+value); + com.neuronrobotics.sdk.common.Log.error("Value changed! "+name+" "+float1+" to "+value); values.put(name, value); timeOfLastAxisSet.put(name, System.currentTimeMillis()); } @@ -205,8 +205,8 @@ public void onEvent(String name, float value) { for(String s:listOfMappedAxis) { if(s.contentEquals(name)) { - System.out.println("mapping skipped for "+name); - System.out.println(gameController); + com.neuronrobotics.sdk.common.Log.error("mapping skipped for "+name); + com.neuronrobotics.sdk.common.Log.error(gameController); return;// This axis name is already mapped and will not be mapped again } } @@ -216,7 +216,7 @@ public void onEvent(String name, float value) { } axisWaiting=name; - System.out.println("Adding Axis "+name); + com.neuronrobotics.sdk.common.Log.error("Adding Axis "+name); listOfMappedAxis.add(name); timeOfLastAxisSet.put(name,System.currentTimeMillis()); @@ -236,17 +236,17 @@ public void onEvent(String name, float value) { } public static void run(BowlerJInputDevice c) { - //System.out.println("Launching Controller mapping"); + //com.neuronrobotics.sdk.common.Log.error("Launching Controller mapping"); BowlerKernel.runLater(new Runnable() { @Override public void run() { - //System.out.println("Creating stage"); + //com.neuronrobotics.sdk.common.Log.error("Creating stage"); Stage s = new Stage(); new Thread() { public void run() { JogTrainerWidget controller = new JogTrainerWidget(c); try { - //System.out.println("Loading FXML"); + //com.neuronrobotics.sdk.common.Log.error("Loading FXML"); controller.start(s); } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/CoreScheduler.java b/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/CoreScheduler.java index 060cf9b9f..452fa9ff8 100644 --- a/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/CoreScheduler.java +++ b/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/CoreScheduler.java @@ -19,7 +19,7 @@ import com.neuronrobotics.sdk.dyio.DyIO; import com.neuronrobotics.sdk.dyio.peripherals.ServoChannel; import com.neuronrobotics.sdk.util.ThreadUtil; -// TODO: Auto-generated Javadoc +// Auto-generated Javadoc /** * The Class CoreScheduler. @@ -117,10 +117,10 @@ public void loadFromFile(File f){ } catch (IOException e) { throw new RuntimeException(e); } - //System.out.println("Parsing File..."); + //com.neuronrobotics.sdk.common.Log.error("Parsing File..."); NodeList nList = doc.getElementsByTagName("ServoOutputSequenceGroup"); for (int temp = 0; temp < nList.getLength(); temp++) { - //System.out.println("Leg # "+temp); + //com.neuronrobotics.sdk.common.Log.error("Leg # "+temp); Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; @@ -134,7 +134,7 @@ public void loadFromFile(File f){ setLoopTime(Integer.parseInt(getTagValue("loopTime",eElement))); NodeList links = eElement.getElementsByTagName("ServoOutputSequence"); for (int i = 0; i < links.getLength(); i++) { - //System.out.println("\tLink # "+i); + //com.neuronrobotics.sdk.common.Log.error("\tLink # "+i); Node lNode = links.item(i); if (lNode.getNodeType() == Node.ELEMENT_NODE) { Element lElement = (Element) lNode; @@ -158,7 +158,7 @@ public void loadFromFile(File f){ int current = data[j]; int after = data[j+1]; if(current == 0 &&before!=0 && after!=0){ - System.out.println("Smoothing xml"); + com.neuronrobotics.sdk.common.Log.error("Smoothing xml"); data[j]=(before+after)/2; } } @@ -177,10 +177,10 @@ public void loadFromFile(File f){ } }else{ - //System.out.println("Not Element Node"); + //com.neuronrobotics.sdk.common.Log.error("Not Element Node"); } } - System.out.println("Populated Scheduler"); + com.neuronrobotics.sdk.common.Log.error("Populated Scheduler"); } /** @@ -193,7 +193,7 @@ public void loadFromFile(File f){ private static String getTagValue(String sTag, Element eElement){ NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes(); Node nValue = (Node) nlList.item(0); - //System.out.println("\t\t"+sTag+" = "+nValue.getNodeValue()); + //com.neuronrobotics.sdk.common.Log.error("\t\t"+sTag+" = "+nValue.getNodeValue()); return nValue.getNodeValue(); } @@ -209,7 +209,7 @@ public void setAudioFile(File f) { filename=f.getAbsolutePath(); mp3 = new SequencerWAV(f.getAbsolutePath()); msDuration = mp3.getTrackLength(); - System.out.println("Setting track length: "+msDuration); + com.neuronrobotics.sdk.common.Log.error("Setting track length: "+msDuration); setSequenceParams( msDuration, 0); } @@ -259,7 +259,7 @@ public boolean isPlaying() { * @return the servo output schedule channel */ public ServoOutputScheduleChannel addServoChannel(int dyIOChannel){ - System.out.println("Adding DyIO channel: "+dyIOChannel); + com.neuronrobotics.sdk.common.Log.error("Adding DyIO channel: "+dyIOChannel); ServoChannel srv = new ServoChannel(getDyIO().getChannel(dyIOChannel)); srv.SetPosition(srv.getValue()); srv.flush(); @@ -290,7 +290,7 @@ public void removeServoOutputScheduleChannel(ServoOutputScheduleChannel s){ public void setSequenceParams(int setpoint,long StartOffset){ msDuration=setpoint; this.StartOffset=StartOffset; - //System.out.println("Starting scheduler setpoint="+setpoint+" offset="+StartOffset); + //com.neuronrobotics.sdk.common.Log.error("Starting scheduler setpoint="+setpoint+" offset="+StartOffset); if(getSt()==null) setSt(new SchedulerThread(msDuration,StartOffset)); if(mp3!=null) @@ -475,14 +475,14 @@ public void run(){ } flushTime = System.currentTimeMillis()-start; if(flushTime>getLoopTime()){ - System.err.println("Flush took:"+flushTime+ " and loop time="+getLoopTime()); + com.neuronrobotics.sdk.common.Log.error("Flush took:"+flushTime+ " and loop time="+getLoopTime()); flushTime=getLoopTime(); } }else{ try { Thread.sleep(10); } catch (InterruptedException e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); } } @@ -543,7 +543,7 @@ private class SchedulerThread extends Thread{ public SchedulerThread(double ms,final long so){ time = ms; StartOffset=so; - //System.out.println("Slider value of init="+StartOffset); + //com.neuronrobotics.sdk.common.Log.error("Slider value of init="+StartOffset); if(mp3!=null) { mp3.setCurrentTime((int) (StartOffset)); } @@ -556,7 +556,7 @@ public SchedulerThread(double ms,final long so){ * Play step. */ public void playStep(){ - //System.out.println("Stepping scheduler"); + //com.neuronrobotics.sdk.common.Log.error("Stepping scheduler"); boolean playing; long current; if(mp3==null){ @@ -580,7 +580,7 @@ public void playStep(){ * @see java.lang.Thread#run() */ public void run(){ - //System.out.println("Starting timer"); + //com.neuronrobotics.sdk.common.Log.error("Starting timer"); do{ do{ while(pause){ @@ -590,7 +590,7 @@ public void run(){ long start = System.currentTimeMillis(); playStep(); ThreadUtil.wait(getLoopTime()); - //System.out.println("Flush took "+(System.currentTimeMillis()-start)); + //com.neuronrobotics.sdk.common.Log.error("Flush took "+(System.currentTimeMillis()-start)); }while(isRun()); setCurrentTime(0); setPause(true); diff --git a/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/ISchedulerListener.java b/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/ISchedulerListener.java index 2e0bf7a53..ad8d642e9 100644 --- a/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/ISchedulerListener.java +++ b/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/ISchedulerListener.java @@ -1,6 +1,6 @@ package com.neuronrobotics.sdk.dyio.sequencer; -// TODO: Auto-generated Javadoc +// Auto-generated Javadoc /** * The listener interface for receiving IScheduler events. * The class that is interested in processing a IScheduler diff --git a/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/SequencerWAV.java b/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/SequencerWAV.java index c0be2082f..7aa805860 100644 --- a/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/SequencerWAV.java +++ b/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/SequencerWAV.java @@ -30,7 +30,7 @@ public SequencerWAV(String filename) { } catch (Exception e) { - System.out.println("Problem playing file " + filename+"\r\n"); + com.neuronrobotics.sdk.common.Log.error("Problem playing file " + filename+"\r\n"); //e.printStackTrace(); throw new RuntimeException(e); } @@ -139,12 +139,12 @@ public static void main(String[] args) { SequencerWAV mp3 = new SequencerWAV("track.mp3"); mp3.play(); - System.out.println("Track length= "+mp3.getTrackLength()); + com.neuronrobotics.sdk.common.Log.error("Track length= "+mp3.getTrackLength()); while(mp3.isPlaying() ){ - System.out.println("Current "+mp3.getCurrentTime() +" Percent = "+mp3.getPercent()); + com.neuronrobotics.sdk.common.Log.error("Current "+mp3.getCurrentTime() +" Percent = "+mp3.getPercent()); ThreadUtil.wait(100); } - System.out.println("Finished "+mp3.getCurrentTime()+" of "+mp3.getTrackLength()); + com.neuronrobotics.sdk.common.Log.error("Finished "+mp3.getCurrentTime()+" of "+mp3.getTrackLength()); System.exit(0); //mediaPlayer. diff --git a/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/ServoOutputScheduleChannel.java b/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/ServoOutputScheduleChannel.java index e652b09b2..6e3cd30df 100644 --- a/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/ServoOutputScheduleChannel.java +++ b/src/main/java/com/neuronrobotics/sdk/dyio/sequencer/ServoOutputScheduleChannel.java @@ -7,7 +7,7 @@ import com.neuronrobotics.sdk.dyio.peripherals.IServoPositionUpdateListener; import com.neuronrobotics.sdk.dyio.peripherals.ServoChannel; -// TODO: Auto-generated Javadoc +// Auto-generated Javadoc /** * The Class ServoOutputScheduleChannel. */ @@ -79,7 +79,7 @@ public int getChannelNumber(){ * Pause recording. */ public void pauseRecording(){ - System.out.println("pausing recording"); + com.neuronrobotics.sdk.common.Log.error("pausing recording"); if(input != null) input.removeAnalogInputListener(this); setRecording(false); @@ -91,7 +91,7 @@ public void pauseRecording(){ public void resumeRecording(){ if(input==null) initInput(); - System.out.println("resuming recording"); + com.neuronrobotics.sdk.common.Log.error("resuming recording"); setRecording(true); } @@ -117,7 +117,7 @@ private void initInput() { } if(input.getChannel().getChannelNumber() != analogInputChannelNumber) { - System.out.println("Re-Setting analog input channel: "+analogInputChannelNumber); + com.neuronrobotics.sdk.common.Log.error("Re-Setting analog input channel: "+analogInputChannelNumber); input.removeAllAnalogInputListeners(); input=new AnalogInputChannel(output.getChannel().getDevice().getChannel(analogInputChannelNumber),true); } @@ -149,7 +149,7 @@ public void onTimeUpdate(double ms) { //output.SetPosition(data.get(index).input); - //System.out.println("Setting servo "+getChannelNumber()+" value="+getCurrentValue()); + //com.neuronrobotics.sdk.common.Log.error("Setting servo "+getChannelNumber()+" value="+getCurrentValue()); } @@ -161,7 +161,7 @@ public void setIntervalTime(int msInterval, int totalTime) { setInterval(msInterval); int slices = totalTime/msInterval; if(data.size()==0){ - System.out.println("Setting up sample data: "+msInterval+"ms for: "+totalTime); + com.neuronrobotics.sdk.common.Log.error("Setting up sample data: "+msInterval+"ms for: "+totalTime); data = new ArrayList(); setCurrentTargetValue(getCurrentValue()); if(getCurrentTargetValue()>getOutputMax()){ @@ -186,14 +186,14 @@ public void setIntervalTime(int msInterval, int totalTime) { public void onAnalogValueChange(AnalogInputChannel chan, double value) { double centerOffset =getInputCenter()-(512*getInputScale()); - //System.out.println("Center Offset="+centerOffset); + //com.neuronrobotics.sdk.common.Log.error("Center Offset="+centerOffset); double scaled = (value*getInputScale()); double recentered = (scaled+centerOffset); setCurrentTargetValue((int) recentered ); - //System.out.println("Analog value="+(int)value+" scaled="+(int)scaled +" recentered="+(int)recentered); + //com.neuronrobotics.sdk.common.Log.error("Analog value="+(int)value+" scaled="+(int)scaled +" recentered="+(int)recentered); if(getCurrentTargetValue()>getOutputMax()){ setCurrentTargetValue(getOutputMax()); } @@ -383,7 +383,7 @@ public void setData(int[] data2) { * Start test. */ public void startTest() { - System.out.println("Starting test for output: "+getChannelNumber()); + com.neuronrobotics.sdk.common.Log.error("Starting test for output: "+getChannelNumber()); initInput(); directTester = new Tester(); directTester.start(); @@ -463,7 +463,7 @@ public void flush(){ * @param analogInputChannelNumber the new analog input channel number */ public void setAnalogInputChannelNumber(int analogInputChannelNumber) { - //System.out.println("Setting analog input number: "+analogInputChannelNumber); + //com.neuronrobotics.sdk.common.Log.error("Setting analog input number: "+analogInputChannelNumber); this.analogInputChannelNumber = analogInputChannelNumber; } @@ -499,12 +499,12 @@ private class Tester extends Thread { * @see java.lang.Thread#run() */ public void run() { - //System.out.println("Starting Test"); + //com.neuronrobotics.sdk.common.Log.error("Starting Test"); while(running) { flush(); try {Thread.sleep((long) getInterval());} catch (InterruptedException e) {} } - //System.out.println("Test Done"); + //com.neuronrobotics.sdk.common.Log.error("Test Done"); } /** @@ -520,7 +520,7 @@ public void kill() { */ @Override public void onReset() { - // TODO Auto-generated method stub + // Auto-generated method stub } @@ -529,7 +529,7 @@ public void onReset() { */ @Override public void onPlay() { - // TODO Auto-generated method stub + // Auto-generated method stub } @@ -538,7 +538,7 @@ public void onPlay() { */ @Override public void onPause() { - // TODO Auto-generated method stub + // Auto-generated method stub } diff --git a/test/java/src/junit/bowler/BlenderLoadingTest.java b/test/java/src/junit/bowler/BlenderLoadingTest.java index de97fbbdc..2212461cd 100644 --- a/test/java/src/junit/bowler/BlenderLoadingTest.java +++ b/test/java/src/junit/bowler/BlenderLoadingTest.java @@ -5,8 +5,10 @@ import org.junit.Test; import com.neuronrobotics.bowlerstudio.scripting.ScriptingEngine; +import com.neuronrobotics.bowlerstudio.util.GeometrySimplification; import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.Cube; public class BlenderLoadingTest { @@ -17,7 +19,12 @@ public void test() throws Exception { "TestRepo4.blend"); if(loaded.getPolygons().size()!=12) fail("Failed to load polygon!"); - System.out.println("Blender file loaded num polys: "+loaded.getPolygons().size()); + com.neuronrobotics.sdk.common.Log.error("Blender file loaded num polys: "+loaded.getPolygons().size()); + CSG cube = new Cube(100).toCSG(); + CSG remeshed = GeometrySimplification.remesh(cube, 10.0); + if(remeshed.getPolygons().size()!=1452) + fail("Blender failed to remesh"); + com.neuronrobotics.sdk.common.Log.error("Remeshing produced: "+remeshed.getPolygons().size()); } } diff --git a/test/java/src/junit/bowler/GitHub.java b/test/java/src/junit/bowler/GitHub.java index 6c4288779..8f79f00b5 100644 --- a/test/java/src/junit/bowler/GitHub.java +++ b/test/java/src/junit/bowler/GitHub.java @@ -25,7 +25,7 @@ public class GitHub { public void test() throws Exception { //ScriptingEngine.login(); // String remoteURI = "https://github.com/madhephaestusdemo/WalkTest_madhephaestusdemo.git"; -// System.out.println(ScriptingEngine.getRepositoryCloneDirectory(remoteURI)); +// com.neuronrobotics.sdk.common.Log.error(ScriptingEngine.getRepositoryCloneDirectory(remoteURI)); // ScriptingEngine.pull(remoteURI); //ScriptingEngine.fork("https://github.com/madhephaestus/6dofServoArm.git", "forktest6dof", "testing yo!"); @@ -37,46 +37,46 @@ public void test() throws Exception { } ScriptingEngine.setAutoupdate(true); } catch (Exception ex) { - System.out.println("User not logged in, test can not run"); + com.neuronrobotics.sdk.common.Log.error("User not logged in, test can not run"); } org.kohsuke.github.GitHub github = ScriptingEngine.getGithub(); while (github == null) { github = ScriptingEngine.getGithub(); ThreadUtil.wait(2000); - System.out.println("Waiting for github"); + com.neuronrobotics.sdk.common.Log.error("Waiting for github"); } Map orgs = github.getMyOrganizations(); for (String org : orgs.keySet()) { - System.out.println("Org: " + org); + com.neuronrobotics.sdk.common.Log.error("Org: " + org); GHOrganization ghorg = orgs.get(org); Map repos = ghorg.getRepositories(); for (String orgRepo : repos.keySet()) { - System.out.println("\tRepo " + org + " " + orgRepo); + com.neuronrobotics.sdk.common.Log.error("\tRepo " + org + " " + orgRepo); } } Map> teams = github.getMyTeams(); for (String team : teams.keySet()) { - System.out.println("Team " + team); + com.neuronrobotics.sdk.common.Log.error("Team " + team); Set ghteam = teams.get(team); for (GHTeam ghT : ghteam) { - System.out.println("\tGHTeam " + ghT.getName()); + com.neuronrobotics.sdk.common.Log.error("\tGHTeam " + ghT.getName()); Map repos = ghT.getRepositories(); for (String repoName : repos.keySet()) { - System.out.println("\t\tGHTeam " + ghT.getName() + " repo " + repoName); + com.neuronrobotics.sdk.common.Log.error("\t\tGHTeam " + ghT.getName() + " repo " + repoName); } } } GHMyself self = github.getMyself(); Map myPublic = self.getAllRepositories(); for (String myRepo : myPublic.keySet()) { - System.out.println("Repo " + myRepo); + com.neuronrobotics.sdk.common.Log.error("Repo " + myRepo); GHRepository ghrepo = myPublic.get(myRepo); // if(ghrepo.getOwnerName().contains("demo")) - System.out.println("\tOwner: " + ghrepo.getOwnerName() + " " + myRepo); + com.neuronrobotics.sdk.common.Log.error("\tOwner: " + ghrepo.getOwnerName() + " " + myRepo); } PagedIterable watching = self.listSubscriptions(); for (GHRepository g : watching) { - System.out.println("Watching " + g.getOwnerName() + " " + g.getFullName()); + com.neuronrobotics.sdk.common.Log.error("Watching " + g.getOwnerName() + " " + g.getFullName()); } String gitURL ="https://github.com/madhephaestus/clojure-utils.git"; ArrayList listofFiles = ScriptingEngine.filesInGit(gitURL, @@ -84,39 +84,39 @@ public void test() throws Exception { if (listofFiles.size() == 0) fail(); for (String s : listofFiles) { - System.out.println("Files " + s); + com.neuronrobotics.sdk.common.Log.error("Files " + s); } String asstsRepo="https://github.com/madhephaestus/BowlerStudioImageAssets.git"; // https://github.com/madhephaestus/BowlerStudioImageAssets.git ScriptingEngine.deleteRepo(asstsRepo); List call = ScriptingEngine.listBranches(asstsRepo); - System.out.println("Branches # " + call.size()); + com.neuronrobotics.sdk.common.Log.error("Branches # " + call.size()); if (call.size() > 0) { for (Ref ref : call) { - System.out.println("Branch: Ref= " + ref + " name= " + ref.getName() + " ID = " + ref.getObjectId().getName()); } + com.neuronrobotics.sdk.common.Log.error("Branch: Ref= " + ref + " name= " + ref.getName() + " ID = " + ref.getObjectId().getName()); } } else { fail(); } ScriptingEngine.checkout(asstsRepo, call.get(0).getName()); call = ScriptingEngine.listLocalBranches(asstsRepo); - System.out.println("Local Branches # " + call.size()); + com.neuronrobotics.sdk.common.Log.error("Local Branches # " + call.size()); if (call.size() > 0) { for (Ref ref : call) { - System.out.println("Branch: Ref= " + ref + " name= " + ref.getName() + " ID = " + ref.getObjectId().getName()); + com.neuronrobotics.sdk.common.Log.error("Branch: Ref= " + ref + " name= " + ref.getName() + " ID = " + ref.getObjectId().getName()); } } else { fail(); } - //System.out.println("Creating branch # " ); + //com.neuronrobotics.sdk.common.Log.error("Creating branch # " ); // ScriptingEngine.newBranch(asstsRepo, "0.20.0"); // try{ // ScriptingEngine.deleteBranch(asstsRepo, "0.20.0"); // }catch(Exception e){ // e.printStackTrace(); // } - System.out.println("Current Branch # " + ScriptingEngine.getFullBranch(asstsRepo)); + com.neuronrobotics.sdk.common.Log.error("Current Branch # " + ScriptingEngine.getFullBranch(asstsRepo)); */ } diff --git a/test/java/src/junit/bowler/JettyTest.java b/test/java/src/junit/bowler/JettyTest.java index cc9c62433..09b6af59a 100644 --- a/test/java/src/junit/bowler/JettyTest.java +++ b/test/java/src/junit/bowler/JettyTest.java @@ -38,7 +38,7 @@ public void startJetty() throws Exception { ScriptingEngine.setupAnyonmous(); // ScriptingEngine.setAutoupdate(true); } catch (Exception ex) { - System.out.println("User not logged in, test can not run"); + com.neuronrobotics.sdk.common.Log.error("User not logged in, test can not run"); } File indexOfTutorial = ScriptingEngine .fileFromGit("https://github.com/CommonWealthRobotics/CommonWealthRobotics.github.io.git", @@ -55,7 +55,7 @@ public void startJetty() throws Exception { ResourceHandler resource_handler = new ResourceHandler(); resource_handler.setDirectoriesListed(true); resource_handler.setWelcomeFiles(new String[]{"index.html"}); - System.out.println("Serving " + indexOfTutorial.getParent()); + com.neuronrobotics.sdk.common.Log.error("Serving " + indexOfTutorial.getParent()); resource_handler.setResourceBase(indexOfTutorial.getParent()); HandlerList handlers = new HandlerList(); @@ -75,7 +75,7 @@ public void test() throws InvalidRemoteException, TransportException, GitAPIExce try { java.io.InputStream url = new URL(HOME_Local_URL).openStream(); try { - System.out.println(org.apache.commons.io.IOUtils.toString(url)); + com.neuronrobotics.sdk.common.Log.error(org.apache.commons.io.IOUtils.toString(url)); } finally { org.apache.commons.io.IOUtils.closeQuietly(url); } diff --git a/test/java/src/junit/bowler/JsonTester.java b/test/java/src/junit/bowler/JsonTester.java index 9bce704ad..a37cf9c45 100644 --- a/test/java/src/junit/bowler/JsonTester.java +++ b/test/java/src/junit/bowler/JsonTester.java @@ -25,20 +25,20 @@ public void test() throws Exception { ScriptingEngine.setupAnyonmous(); //ScriptingEngine.setAutoupdate(true); }catch (Exception ex){ - System.out.println("User not logged in, test can not run"); + com.neuronrobotics.sdk.common.Log.error("User not logged in, test can not run"); } File f = ScriptingEngine .fileFromGit( "https://github.com/madhephaestus/BowlerStudioExampleRobots.git",// git repo, change this if you fork this demo "exampleRobots.json"// File from within the Git repo ); - System.out.println("File: "+f); + com.neuronrobotics.sdk.common.Log.error("File: "+f); HashMap> map = (HashMap>) ScriptingEngine .inlineFileScriptRun(f, null); for(String menuTitle:map.keySet()){ HashMap script = map.get(menuTitle); - System.out.println((String)script.get("scriptGit")); - System.out.println((String)script.get("scriptFile")); ; + com.neuronrobotics.sdk.common.Log.error((String)script.get("scriptGit")); + com.neuronrobotics.sdk.common.Log.error((String)script.get("scriptFile")); ; } */ diff --git a/test/java/src/junit/bowler/MobileBaseLoading.java b/test/java/src/junit/bowler/MobileBaseLoading.java index 4c024e94e..da933afdf 100644 --- a/test/java/src/junit/bowler/MobileBaseLoading.java +++ b/test/java/src/junit/bowler/MobileBaseLoading.java @@ -25,13 +25,13 @@ public void test() throws Exception { IMobileBaseUI mobileBaseUI = new IMobileBaseUI() { @Override public void setAllCSG(Collection collection, File file) { - System.out.println("Setting CSG's # " +collection.size()); + com.neuronrobotics.sdk.common.Log.error("Setting CSG's # " +collection.size()); numCSG=collection.size(); } @Override public void addCSG(Collection collection, File file) { - System.out.println("Adding CSG's # " +collection.size()); + com.neuronrobotics.sdk.common.Log.error("Adding CSG's # " +collection.size()); } @@ -55,7 +55,7 @@ public void setSelectedCsg(Collection collection) { @Override public void progressUpdate(int currentIndex, int finalIndex, String type, CSG intermediateShape) { - // TODO Auto-generated method stub + // Auto-generated method stub } }); @@ -68,10 +68,10 @@ public void progressUpdate(int currentIndex, int finalIndex, String type, CSG in // MobileBaseCadManager.get(mobileBase).getUi(). DeviceManager.addConnection(mobileBase, mobileBase.getScriptingName()); mobileBaseCadManager.generateCad(); - System.out.println("Waiting for cad to generate"); + com.neuronrobotics.sdk.common.Log.error("Waiting for cad to generate"); ThreadUtil.wait(1000); while (MobileBaseCadManager.get(mobileBase).getProcesIndictor().get() < 1 ) { - //System.out.println("Waiting: " + MobileBaseCadManager.get(mobileBase).getProcesIndictor().get()); + //com.neuronrobotics.sdk.common.Log.error("Waiting: " + MobileBaseCadManager.get(mobileBase).getProcesIndictor().get()); ThreadUtil.wait(1000); } if(numCSG==0) diff --git a/test/java/src/junit/bowler/MuJoCoBowlerIntegrationTest.java b/test/java/src/junit/bowler/MuJoCoBowlerIntegrationTest.java index 4929bc94c..6e8a13fd7 100644 --- a/test/java/src/junit/bowler/MuJoCoBowlerIntegrationTest.java +++ b/test/java/src/junit/bowler/MuJoCoBowlerIntegrationTest.java @@ -26,7 +26,7 @@ public void test() throws Exception { // JavaFXInitializer.go(); // } catch (Throwable t) { // t.printStackTrace(); -// System.err.println("ERROR No UI engine availible"); +// com.neuronrobotics.sdk.common.Log.error("ERROR No UI engine availible"); // } // ArrayList bases = new ArrayList<>(); // ArrayList free =new ArrayList<>(); @@ -39,7 +39,7 @@ public void test() throws Exception { // terrain= (ArrayList) ScriptingEngine.gitScriptRun( // "https://github.com/madhephaestus/VexHighStakes2024.git", // "field.groovy"); -// System.out.println("Parts size = "+parts.size()); +// com.neuronrobotics.sdk.common.Log.error("Parts size = "+parts.size()); // //terrain.add(new Cube(10000,10000,100).toCSG().toZMax()); // free.addAll(parts); // MuJoCoPhysicsManager manager = new MuJoCoPhysicsManager("javaCadTest", bases, free, terrain, new File("./physicsTest")); @@ -58,7 +58,7 @@ public void test() throws Exception { // } // fail("Real time broken! "+took+" instead of expected "+manager.getCurrentSimulationTimeSeconds()); // }else { -// System.out.println("Time "+now); +// com.neuronrobotics.sdk.common.Log.error("Time "+now); // } // long timeSinceStart = System.currentTimeMillis()-start; // double sec = ((double)timeSinceStart)/1000.0; @@ -67,7 +67,7 @@ public void test() throws Exception { // } // } // manager.close(); -// System.out.println("Success!"); +// com.neuronrobotics.sdk.common.Log.error("Success!"); } diff --git a/test/java/src/junit/bowler/MuJoCoTest.java b/test/java/src/junit/bowler/MuJoCoTest.java index d50485a33..f24d1a8ce 100644 --- a/test/java/src/junit/bowler/MuJoCoTest.java +++ b/test/java/src/junit/bowler/MuJoCoTest.java @@ -9,12 +9,11 @@ public class MuJoCoTest { @Test public void test() { - System.out.println("mujocoJNILoadTest"); - System.out.println(System.getProperty("org.bytedeco.javacpp.logger.debug")); + com.neuronrobotics.sdk.common.Log.error("mujocoJNILoadTest"); System.setProperty("org.bytedeco.javacpp.logger.debug", "true"); MuJoCoLib lib = new MuJoCoLib(); - System.out.println("Starting " + MuJoCoLib.mj_versionString().getString()); + com.neuronrobotics.sdk.common.Log.error("Starting " + MuJoCoLib.mj_versionString().getString()); } } diff --git a/test/java/src/junit/bowler/PyTorchResNetTest.java b/test/java/src/junit/bowler/PyTorchResNetTest.java index 8bf336a04..013fb4de5 100644 --- a/test/java/src/junit/bowler/PyTorchResNetTest.java +++ b/test/java/src/junit/bowler/PyTorchResNetTest.java @@ -20,13 +20,13 @@ public class PyTorchResNetTest { // @Test // public void testResNet() throws Exception { -// System.err.println(Thread.currentThread().getStackTrace()[1].getMethodName()); +// com.neuronrobotics.sdk.common.Log.error(Thread.currentThread().getStackTrace()[1].getMethodName()); // // } // // @Test // public void testretinaface() throws Exception { -// System.err.println(Thread.currentThread().getStackTrace()[1].getMethodName()); +// com.neuronrobotics.sdk.common.Log.error(Thread.currentThread().getStackTrace()[1].getMethodName()); // // BufferedImage bimg = ImageIO.read(new URL(imageUrl)); // @@ -43,7 +43,7 @@ public class PyTorchResNetTest { // // @Test // public void testUltraNet() throws Exception { -// System.err.println(Thread.currentThread().getStackTrace()[1].getMethodName()); +// com.neuronrobotics.sdk.common.Log.error(Thread.currentThread().getStackTrace()[1].getMethodName()); // // BufferedImage bimg = ImageIO.read(new URL(imageUrl)); // @@ -82,12 +82,12 @@ private static void saveBoundingBoxImage(Image img, DetectedObjects detection, S Path imagePath = outputDir.resolve(type + ".png").toAbsolutePath(); img.save(Files.newOutputStream(imagePath), "png"); - System.out.println("Face detection result image has been saved in: {} " + imagePath); + com.neuronrobotics.sdk.common.Log.error("Face detection result image has been saved in: {} " + imagePath); } // @Test public void testYolo() throws Exception { - System.err.println(Thread.currentThread().getStackTrace()[1].getMethodName()); + com.neuronrobotics.sdk.common.Log.error(Thread.currentThread().getStackTrace()[1].getMethodName()); Predictor predictor = PredictorFactory.imageContentsFactory(ImagePredictorType.yolov5); for (int i = 0; i < 3; i++) { @@ -101,7 +101,7 @@ public void testYolo() throws Exception { // // @Test // public void testFeatures() throws Exception { -// System.err.println(Thread.currentThread().getStackTrace()[1].getMethodName()); +// com.neuronrobotics.sdk.common.Log.error(Thread.currentThread().getStackTrace()[1].getMethodName()); // BufferedImage img = ImageIO.read(new URL(imageUrl)); // BufferedImage img2 = ImageIO.read(new URL(image2URL)); // BufferedImage img3 = ImageIO.read(new URL(image3URL)); @@ -112,12 +112,12 @@ public void testYolo() throws Exception { // float[] back3 = predictor.predict(ImageFactory.getInstance().fromImage(img3)); // float[] back4 = predictor.predict(ImageFactory.getInstance().fromImage(ImageIO.read(new URL(notme)))); // -// System.out.println(" Comprair 1 to 2 " + PredictorFactory.calculSimilarFaceFeature(back, back2)); -// System.out.println(" Comprair 1 to 3 " + PredictorFactory.calculSimilarFaceFeature(back, back3)); -// System.out.println(" Comprair 2 to 3 " + PredictorFactory.calculSimilarFaceFeature(back2, back3)); -// System.out.println(" Comprair 1 to 4 " + PredictorFactory.calculSimilarFaceFeature(back, back4)); +// com.neuronrobotics.sdk.common.Log.error(" Comprair 1 to 2 " + PredictorFactory.calculSimilarFaceFeature(back, back2)); +// com.neuronrobotics.sdk.common.Log.error(" Comprair 1 to 3 " + PredictorFactory.calculSimilarFaceFeature(back, back3)); +// com.neuronrobotics.sdk.common.Log.error(" Comprair 2 to 3 " + PredictorFactory.calculSimilarFaceFeature(back2, back3)); +// com.neuronrobotics.sdk.common.Log.error(" Comprair 1 to 4 " + PredictorFactory.calculSimilarFaceFeature(back, back4)); // -// System.out.println(Arrays.toString(back)); +// com.neuronrobotics.sdk.common.Log.error(Arrays.toString(back)); // // } diff --git a/test/java/src/junit/bowler/TTSTest.java b/test/java/src/junit/bowler/TTSTest.java index 7ad42e4b0..0dcfd42bd 100644 --- a/test/java/src/junit/bowler/TTSTest.java +++ b/test/java/src/junit/bowler/TTSTest.java @@ -20,8 +20,8 @@ public void TTSText() { @Override public void update(double percentage, AudioStatus status) { - // TODO Auto-generated method stub - System.out.println(percentage+" "+status.toString()); + // Auto-generated method stub + com.neuronrobotics.sdk.common.Log.error(percentage+" "+status.toString()); } }; //BowlerKernel.speak("Coqui one text to speech", 200, 0, 800, 1.0, 1.0,sp); @@ -34,7 +34,7 @@ public void update(double percentage, AudioStatus status) { // for(int i=800;i<(800+CoquiDockerManager.getNummberOfOptions());i++) { // BowlerKernel.speak("Coqui " + i + " text to speech", 200, 0, i, 1.0, 1.0,null); -// System.out.println("\n\nVoice finished"); +// com.neuronrobotics.sdk.common.Log.error("\n\nVoice finished"); // } } diff --git a/test/java/src/junit/bowler/TestCaDoodleWorkflow.java b/test/java/src/junit/bowler/TestCaDoodleWorkflow.java new file mode 100644 index 000000000..780a0ebd5 --- /dev/null +++ b/test/java/src/junit/bowler/TestCaDoodleWorkflow.java @@ -0,0 +1,232 @@ +package junit.bowler; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import org.junit.Test; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import com.neuronrobotics.bowlerstudio.scripting.ScriptingEngine; + +import java.lang.reflect.Type; + +import com.neuronrobotics.bowlerstudio.scripting.cadoodle.AddFromScript; +import com.neuronrobotics.bowlerstudio.scripting.cadoodle.CaDoodleFile; +import com.neuronrobotics.bowlerstudio.scripting.cadoodle.Group; +import com.neuronrobotics.bowlerstudio.scripting.cadoodle.MoveCenter; +import com.neuronrobotics.bowlerstudio.scripting.cadoodle.Paste; +import com.neuronrobotics.bowlerstudio.scripting.cadoodle.Resize; +import com.neuronrobotics.bowlerstudio.scripting.cadoodle.ToHole; +import com.neuronrobotics.bowlerstudio.scripting.cadoodle.ToSolid; +import com.neuronrobotics.bowlerstudio.scripting.cadoodle.UnGroup; +import com.neuronrobotics.sdk.addons.kinematics.math.RotationNR; +import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR; + +import eu.mihosoft.vrl.v3d.CSG; +import javafx.scene.paint.Color; + +public class TestCaDoodleWorkflow { + + @Test + public void test() throws Exception { + CaDoodleFile cf = new CaDoodleFile() + .setSelf(new File("Test.doodle")) + .setProjectName("A Test Project"); + + String jsonContent = cf.toJson(); + com.neuronrobotics.sdk.common.Log.error(jsonContent); + + AddFromScript cube1 = new AddFromScript() + .set("https://github.com/madhephaestus/CaDoodle-Example-Objects.git", + "sphere.groovy"); + AddFromScript cube2 = new AddFromScript() + .set("https://github.com/madhephaestus/CaDoodle-Example-Objects.git", + "sphere.groovy"); + cf.addOpperation(cube1).join(); + Listback= cf.getCurrentState(); + if(back.size()!=1) + fail("Adding a cube should have added one!"); + String nameOne = back.get(0).getName(); + cf.addOpperation(cube2).join();; + back=cf.getCurrentState(); + if(back.size()!=2) + fail("Adding a cube should have added one more!"); + String nameTwo = back.get(1).getName(); + if(nameOne.contentEquals(nameTwo)) + fail("Names must be unique!"); + com.neuronrobotics.sdk.common.Log.error("Name one : "+nameOne ); + com.neuronrobotics.sdk.common.Log.error("Name two : "+nameTwo ); + double distaance =10; + MoveCenter move = new MoveCenter() + .setLocation(new TransformNR(distaance,0,0)) + .setNames(Arrays.asList(nameTwo)) + ; + cf.addOpperation(move).join();; + back=cf.getCurrentState(); + if(back.size()!=2) + fail("Same number of objects after"); + double centerX = back.get(1).getCenterX(); + if(centerX!=distaance) + fail("Move failed "); + if(back.get(0).getCenterX()!=0) + fail("Move misapplied "); + jsonContent = cf.toJson(); + //com.neuronrobotics.sdk.common.Log.error(jsonContent); + cf.save(); + CaDoodleFile loaded = CaDoodleFile.fromFile(cf.getSelf()); + if(!MoveCenter.class.isInstance(loaded.getOpperations().get(2))) { + fail("Third Opperation is supposed to be a move"); + } + if(!AddFromScript.class.isInstance(loaded.getOpperations().get(1))) { + fail(" Opperation is supposed to be a AddFromScript"); + } + if(!AddFromScript.class.isInstance(loaded.getOpperations().get(0))) { + fail(" Opperation is supposed to be a AddFromScript"); + } + loaded.back(); + MoveCenter move2 = new MoveCenter() + .setLocation(new TransformNR(distaance,distaance,0)) + .setNames(Arrays.asList(nameOne)) + ; + MoveCenter move3 = new MoveCenter() + .setLocation(new TransformNR(0,0,0,new RotationNR(0,45,0))) + .setNames(Arrays.asList(nameOne)) + ; + loaded.addOpperation(move3).join();; + back=loaded.getCurrentState(); + loaded.addOpperation(move2).join();; + back=loaded.getCurrentState(); + double centerX2 = back.get(1).getCenterX(); + if(centerX2!=distaance) + fail("Move failed "); + if(back.get(1).getCenterY()!=distaance) + fail("Move failed "); + ToHole hole= new ToHole().setNames(Arrays.asList(nameOne)); + loaded.addOpperation(hole).join();; + back=loaded.getCurrentState(); + Group group = new Group().setNames(Arrays.asList(nameOne,nameTwo)); + loaded.addOpperation(group).join();; + back=loaded.getCurrentState(); + if(back.size()!=3) + fail("Group Failed "); + if(!back.get(0).isInGroup()) { + fail("THis should not be in a group anymore"); + } + if(!back.get(1).isInGroup()) { + fail("THis should not be in a group anymore"); + } + if(back.get(2).isInGroup()) { + fail("THis should not be in a group anymore"); + } + if(!back.get(2).isGroupResult()) { + fail("THis should be aa group result"); + } + String groupName = back.get(2).getName(); + com.neuronrobotics.sdk.common.Log.error("Group Name : "+groupName); + TransformNR height = new TransformNR(0,0,40); + TransformNR leftFront = new TransformNR(40,80,0); + TransformNR rightRear = new TransformNR(-10,10,0); + Resize resize = new Resize() + .setResize(height, leftFront, rightRear) + .setNames(Arrays.asList(groupName)) + ; + loaded.addOpperation(resize).join();; + back=loaded.getCurrentState(); + ToSolid solid = new ToSolid() + .setNames(Arrays.asList(groupName)) + .setColor(Color.BLUE); + loaded.addOpperation(solid).join();; + back=loaded.getCurrentState(); + UnGroup ug = new UnGroup().setNames(Arrays.asList(groupName)); + loaded.addOpperation(ug).join();; + back=loaded.getCurrentState(); + if(back.get(0).isInGroup()) { + fail("THis should not be in a group anymore"); + } + if(back.get(1).isInGroup()) { + fail("THis should not be in a group anymore"); + } + + + loaded.addOpperation( + new Group() + .setNames(Arrays.asList(nameOne,nameTwo)) + ).join();; + back=loaded.getCurrentState(); + List cacheOfGroup = loaded.getCurrentState(); + + String newGroupName = cacheOfGroup.get(cacheOfGroup.size()-1).getName(); + + loaded.addOpperation( + new Paste().setNames(Arrays.asList(newGroupName))).join();; + back=loaded.getCurrentState(); + ArrayList selectAll = new ArrayList(); + for(CSG c:back) { + if(c.isGroupResult()) + selectAll.add(c.getName()); + } + loaded.addOpperation( + new UnGroup().setNames(selectAll)).join();; + back=loaded.getCurrentState(); + if(back.get(0).isInGroup()) { + fail("THis should not be in a group anymore"); + } + if(back.get(1).isInGroup()) { + fail("THis should not be in a group anymore"); + } + if(back.get(2).isInGroup()) { + fail("THis should not be in a group anymore"); + } + if(back.get(3).isInGroup()) { + fail("THis should not be in a group anymore"); + } + ToHole h= new ToHole().setNames(Arrays.asList(nameTwo)); + loaded.addOpperation(h).join();; + back=loaded.getCurrentState(); + loaded.save(); + + for(int i=0;i<3;i++) { + loaded.back(); + } + List goBackResult = loaded.getCurrentState(); + back=goBackResult; + if(goBackResult.size()!=3) { + fail(" Number of elements after back incorrect!"); + } + if(back.get(2).isInGroup()) { + fail("THis should not be in a group anymore"); + } + if(!back.get(2).isGroupResult()) { + fail("THis should be a group result"); + } + if(!back.get(0).isInGroup()) { + fail("This should be in a group"); + } + if(!back.get(1).isInGroup()) { + fail("This should be in a group"); + } + + loaded.save(); + + String before = loaded.toJson(); + loaded=CaDoodleFile.fromJsonString(before); + String after =loaded.toJson(); + if(!before.contentEquals(after)) + fail("Load and export mismatch"); + loaded.setSelf(cf.getSelf()); + + com.neuronrobotics.sdk.common.Log.error(after); + + + + + } + +} diff --git a/test/java/src/junit/bowler/TestCheckout.java b/test/java/src/junit/bowler/TestCheckout.java index f37599d55..5279fb1da 100644 --- a/test/java/src/junit/bowler/TestCheckout.java +++ b/test/java/src/junit/bowler/TestCheckout.java @@ -25,14 +25,14 @@ public void test() throws IOException, GitAPIException { try { String []name = select.getName().split("/"); String myName = name[name.length-1]; - System.out.println("Selecting Branch\r\n"+url+" \t\t"+myName); + com.neuronrobotics.sdk.common.Log.error("Selecting Branch\r\n"+url+" \t\t"+myName); String was = ScriptingEngine.getBranch(url); ScriptingEngine.checkout(url, myName); String s = ScriptingEngine.getBranch(url); assertTrue("Changing from "+was+" to "+myName+" got "+s,myName.contains(s)); } catch (Exception e) { - // TODO Auto-generated catch block + // Auto-generated catch block e.printStackTrace(); fail(); } diff --git a/test/java/src/junit/bowler/WekaTester.java b/test/java/src/junit/bowler/WekaTester.java index 8a8e1d385..86b42f7c0 100644 --- a/test/java/src/junit/bowler/WekaTester.java +++ b/test/java/src/junit/bowler/WekaTester.java @@ -8,7 +8,7 @@ public class WekaTester { @Test public void test() { - //TODO + } }