| 65 | |
| 66 | |
| 67 | public class PSurfaceFX implements PSurface { |
| 68 | PApplet sketch; |
| 69 | |
| 70 | PGraphicsFX2D fx; |
| 71 | Stage stage; |
| 72 | Canvas canvas; |
| 73 | |
| 74 | final Animation animation; |
| 75 | float frameRate = 60; |
| 76 | |
| 77 | private SynchronousQueue<Throwable> drawExceptionQueue = new SynchronousQueue<>(); |
| 78 | |
| 79 | public PSurfaceFX(PGraphicsFX2D graphics) { |
| 80 | fx = graphics; |
| 81 | canvas = new ResizableCanvas(); |
| 82 | |
| 83 | // set up main drawing loop |
| 84 | KeyFrame keyFrame = new KeyFrame(Duration.millis(1000), |
| 85 | new EventHandler<ActionEvent>() { |
| 86 | public void handle(ActionEvent event) { |
| 87 | long startNanoTime = System.nanoTime(); |
| 88 | try { |
| 89 | sketch.handleDraw(); |
| 90 | } catch (Throwable e) { |
| 91 | // Let exception handler thread crash with our exception |
| 92 | drawExceptionQueue.offer(e); |
| 93 | // Stop animating right now so nothing runs afterwards |
| 94 | // and crash frame can be for example traced by println() |
| 95 | animation.stop(); |
| 96 | return; |
| 97 | } |
| 98 | long drawNanos = System.nanoTime() - startNanoTime; |
| 99 | |
| 100 | if (sketch.exitCalled()) { |
| 101 | // using Platform.runLater() didn't work |
| 102 | // Platform.runLater(new Runnable() { |
| 103 | // public void run() { |
| 104 | // instead of System.exit(), safely shut down JavaFX this way |
| 105 | Platform.exit(); |
| 106 | // } |
| 107 | // }); |
| 108 | } |
| 109 | if (sketch.frameCount > 5) { |
| 110 | animation.setRate(-PApplet.min(1e9f / drawNanos, frameRate)); |
| 111 | } |
| 112 | } |
| 113 | }); |
| 114 | animation = new Timeline(keyFrame); |
| 115 | animation.setCycleCount(Animation.INDEFINITE); |
| 116 | |
| 117 | // key frame has duration of 1 second, so the rate of the animation |
| 118 | // should be set to frames per second |
| 119 | |
| 120 | // setting rate to negative so that event fires at the start of |
| 121 | // the key frame and first frame is drawn immediately |
| 122 | animation.setRate(-frameRate); |
| 123 | } |
| 124 | |