public void run() { long lastTime = System.nanoTime(); long timer = System.currentTimeMillis(); final double ns = 1000000000.0 / 60.0; double delta = 0; int frames = 0; int updates = 0; // setFocusable(true); requestFocus(); while (running) { long now = System.nanoTime(); delta += (now - lastTime) / ns; lastTime = now; while (delta >= 1) { update(); updates++; delta--; } // Renderiza tudo na tela render(); // Calcula FPS frames++; if ((System.currentTimeMillis() - timer) > 1000) { timer += 1000; // T�tulo do jogo frame.setTitle(title + " | " + updates + " ups / " + frames + " fps "); updates = 0; frames = 0; } } stop(); }
public static void main(String[] args) { JFrame frame = new JFrame("Maze View"); Random random = new Random(); long startTime = System.nanoTime(); MazeNode maze = MazeNode.generate(random, 100, 100); System.out.println("Gen : " + elapsedMs(startTime) + "ms"); startTime = System.nanoTime(); int sx = 0; // random.nextInt(maze.width); int sy = 0; // random.nextInt(maze.height); int dx = maze.width - 1; // random.nextInt(maze.width); int dy = maze.height - 1; // random.nextInt(maze.height); Path path = PathSolver.solve(maze, sx, sy, dx, dy); System.out.println("Solve : " + elapsedMs(startTime) + "ms"); int pathSize = 0; PathCell pathIt = path.first; while (pathIt != null) { pathSize++; pathIt = pathIt.next; } System.out.println("Path Size: " + pathSize); frame.add(new JScrollPane(new MazeView(maze, sx, sy, dx, dy, path))); frame.setSize(500, 500); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); SwingUtilities.invokeLater(() -> frame.setVisible(true)); }
public void run() /* The frames of the animation are drawn inside the while loop. */ { long beforeTime, afterTime, timeDiff, sleepTime; long overSleepTime = 0L; int noDelays = 0; long excess = 0L; gameStartTime = System.nanoTime(); beforeTime = gameStartTime; running = true; while (running) { gameUpdate(); gameRender(); paintScreen(); afterTime = System.nanoTime(); timeDiff = afterTime - beforeTime; sleepTime = (period - timeDiff) - overSleepTime; if (sleepTime > 0) { // some time left in this cycle try { Thread.sleep(sleepTime / 1000000L); // nano -> ms } catch (InterruptedException ex) { } overSleepTime = (System.nanoTime() - afterTime) - sleepTime; } else { // sleepTime <= 0; the frame took longer than the period excess -= sleepTime; // store excess time value overSleepTime = 0L; if (++noDelays >= NO_DELAYS_PER_YIELD) { Thread.yield(); // give another thread a chance to run noDelays = 0; } } beforeTime = System.nanoTime(); /* If frame animation is taking too long, update the game state without rendering it, to get the updates/sec nearer to the required FPS. */ int skips = 0; while ((excess > period) && (skips < MAX_FRAME_SKIPS)) { excess -= period; gameUpdate(); // update state but don't render skips++; } } System.exit(0); // so window disappears } // end of run()
public void launch() { try { long time = System.nanoTime(); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); monitor = new ProgressMonitor(); monitor.setMaximum(5); updateState(BootstrapState.UPDATE_CHECK); { CountDownLatch latch = new CountDownLatch(2); runTask(TaskBootstrapUpdateCheck.class, latch); runTask(TaskInstallerUpdateCheck.class, latch); latch.await(); } updateState(BootstrapState.LOAD_DEPENDENCIES); { runTask(TaskLoadDependencies.class); } updateState(BootstrapState.DOWNLOAD); { runTask(TaskDownload.class); } updateState(BootstrapState.SETUP_ENVIRONMENT); { runTask(TaskCheckJavaVersion.class); runTask(TaskBuildClasspath.class); } System.out.println( "Took " + ((System.nanoTime() - time) / 1000000f) + "ms to launch installer"); updateState(BootstrapState.START_INSTALLER); { runTask(TaskLaunchInstaller.class); } updateState(BootstrapState.FINISHED); } catch (BootstrapException ex) { handleException(ex); System.exit(2); } catch (Exception ex) { handleException(ex); System.exit(-1); } finally { monitor.close(); } }
/** * Sets one or more icons for the Display. * * <ul> * <li>On Windows you should supply at least one 16x16 icon and one 32x32. * <li>Linux (and similar platforms) expect one 32x32 icon. * <li>Mac OS X should be supplied one 128x128 icon * </ul> * * The implementation will use the supplied ByteBuffers with image data in RGBA and perform any * conversions nescesarry for the specific platform. * * @param icons Array of icons in RGBA mode * @return number of icons used. */ public int setIcon(ByteBuffer[] icons) { boolean done_small = false; boolean done_large = false; int used = 0; int small_icon_size = 16; int large_icon_size = 32; for (ByteBuffer icon : icons) { int size = icon.limit() / 4; if ((((int) Math.sqrt(size)) == small_icon_size) && (!done_small)) { long small_new_icon = createIcon(small_icon_size, small_icon_size, icon.asIntBuffer()); sendMessage(hwnd, WM_SETICON, ICON_SMALL, small_new_icon); freeSmallIcon(); small_icon = small_new_icon; used++; done_small = true; } if ((((int) Math.sqrt(size)) == large_icon_size) && (!done_large)) { long large_new_icon = createIcon(large_icon_size, large_icon_size, icon.asIntBuffer()); sendMessage(hwnd, WM_SETICON, ICON_BIG, large_new_icon); freeLargeIcon(); large_icon = large_new_icon; used++; done_large = true; // Problem: The taskbar icon won't update until Windows sends a WM_GETICON to our window // proc and we reply. But this method is usually called // on init and it might take a while before the next call to nUpdate (because of resources // being loaded, etc). So we wait for the next // WM_GETICON message (usually received about 100ms after WM_SETICON) to make sure the // taskbar icon has updated before we return to the user. // (We wouldn't need to do this if the event loop was running continuously on its own // thread.) iconsLoaded = false; // Track how long the wait takes and give up at 500ms, just in case. long time = System.nanoTime(); long MAX_WAIT = 500L * 1000L * 1000L; while (true) { nUpdate(); if (iconsLoaded || MAX_WAIT < System.nanoTime() - time) break; Thread.yield(); } } } return used; }
public void run() { long lastTime = System.nanoTime(); double nsPerTick = 1000000000D / 60D; int ticks = 0; int frames = 0; long lastTimer = System.currentTimeMillis(); double delta = 0; init(); while (Game.isRunning()) { long now = System.nanoTime(); delta += (now - lastTime) / nsPerTick; lastTime = now; boolean shouldRender = false; while (delta >= 1) { ticks++; tick(); delta -= 1; shouldRender = true; } try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } if (shouldRender) { frames++; render(); } if (System.currentTimeMillis() - lastTimer >= 1000) { lastTimer += 1000; getFrame() .setTitle( "JavaGame - Version " + WordUtils.capitalize(game_Version).substring(1, game_Version.length())); fps = frames; tps = ticks; frames = 0; ticks = 0; } } }
@Override public void newImageUpdate(JSONObject tags) { if (tags == null) { return; } updateLabels(tags); try { if (vad_.acquisitionIsRunning() && vad_.getNextWakeTime() > 0) { final long nextImageTime = vad_.getNextWakeTime(); if (System.nanoTime() / 1000000 < nextImageTime) { final java.util.Timer timer = new java.util.Timer("Next frame display"); TimerTask task = new TimerTask() { public void run() { double timeRemainingS = (nextImageTime - System.nanoTime() / 1000000) / 1000; if (timeRemainingS > 0 && vad_.acquisitionIsRunning()) { setStatusLabel( "Next frame: " + NumberUtils.doubleToDisplayString(1 + timeRemainingS) + " s"); } else { timer.cancel(); setStatusLabel(""); } } }; timer.schedule(task, 2000, 100); } } } catch (Exception ex) { ReportingUtils.logError(ex); } }
/** Example panel. Animate an example file (E short) and play a tone (D long). */ public static void main(String[] args) { try { JFrame f = new JFrame(AnimationPanel.class.getName()); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); AnimationRenderer ani = new AnimationRenderer(); final AnimationPanel view = new AnimationPanel(ani); f.getContentPane().add(view, BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); File file = new File("datafiles/examples/vis/es_.txt"); final AnimationSequence animation = AnimationParser.parseFile(file); String filename = NotesEnum.D.toString().toLowerCase() + "_" + DurationEnum.LONG.codeString() + ".wav"; // System.out.printf("sound clip filename = %s\n", filename); File dir = new File("datafiles/examples/aud"); final Playable audio = SoundClip.findPlayable(filename, dir, false); Runnable r = new Runnable() { @Override public void run() { audio.play(); } }; long currentTime = System.nanoTime(); ani.setAnimationSource( new AnimationSource() { public AnimationSequence getAnimationSequence() { return animation; } public int getNumPoints() { return 5; } public float getDiskRadius() { return 0.3f; } public boolean isConnected() { return true; } }); ani.setNanoStartTime(currentTime); SwingUtilities.invokeLater(r); } catch (Throwable ex) { ex.printStackTrace(); } }
public void render() { try { int regionBufferSize = 0; int[] regionBuffer = null; Kdu_dims newRegion = new Kdu_dims(); long kduRenderStart = System.nanoTime(); while (compositor.Process(100000, newRegion)) { Kdu_coords newOffset = newRegion.Access_pos(); Kdu_coords newSize = newRegion.Access_size(); newOffset.Subtract(viewDims.Access_pos()); int newPixels = newSize.Get_x() * newSize.Get_y(); if (newPixels == 0) continue; else if (newPixels > regionBufferSize) { regionBufferSize = newPixels; regionBuffer = new int[regionBufferSize]; } compositorBuffer.Get_region(newRegion, regionBuffer); imagePanel.putRegion( viewSize.Get_x(), viewSize.Get_y(), newSize.Get_x(), newSize.Get_y(), newOffset.Get_x(), newOffset.Get_y(), regionBuffer); } long kduRenderEnd = System.nanoTime(); System.out.printf( "Processed using %d concurrent threads of execution in %.4fms\n", threadEnv.Get_num_threads(), (kduRenderEnd - kduRenderStart) * 1e-6); imagePanel.repaint(); } catch (KduException e) { System.err.printf( "Caught exception '%s'; code '%s'\n", e.getMessage(), Integer.toHexString(e.Get_kdu_exception_code())); } }
public BasicGUI() { KeyHandler kHandler = new KeyHandler(); this.addKeyListener(kHandler); this.setLayout(new BorderLayout()); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(1004, 628); WorldEditState worldEditState = new WorldEditState(-1, 768, 256); gameMachine.addState(worldEditState); UnitMovementState unitMovementState = new UnitMovementState(-1, worldEditState); gameMachine.addState(unitMovementState); gameMachine.rotateState(); this.add(gameMachine.getCurrentState().getGUIComponent(), BorderLayout.CENTER); this.setResizable(false); this.setLocation(100, 100); this.setVisible(true); MouseHandler mHandler = new MouseHandler(); gameMachine.getCurrentState().getGUIComponent().addMouseListener(mHandler); double MAXFPS = 1000000000 / 30.0f; // should stand for 30 frames per second double currentTime, elapsedTime = 0.0; while (isRunning) { currentTime = System.nanoTime(); gameMachine.updateCurrentState(elapsedTime / 1000000); // change nanoseconds to milliseconds gameMachine.renderCurrentState(); elapsedTime = System.nanoTime() - currentTime; // System.out.println(elapsedTime / 1000000); // If it took less than the fps to render and update, sleep for the rest of the time if (elapsedTime < MAXFPS) { int milliElapsedTime = (int) ((MAXFPS - elapsedTime) / 1000000); try { Thread.sleep(milliElapsedTime); } catch (InterruptedException e) { e.printStackTrace(); } } this.requestFocus(); } }
AnimationState(final State startState, final long milliseconds, boolean isForwardAndReverse) { assert startState != null && milliseconds > 0; assert SwingUtilities.isEventDispatchThread(); this.startState = startState; this.duration = milliseconds * 1000000; this.startTime = System.nanoTime(); this.isForwardAndReverse = isForwardAndReverse; progress = 0f; }
public void run() { init(); long lastTime = System.nanoTime(); final double amountOfTicks = 60D; double ns = 1_000_000_000 / amountOfTicks; double delta = 0; while (running) { long now = System.nanoTime(); delta += (now - lastTime) / ns; lastTime = now; // only update 60 times per second if (delta >= 1) { tick(); delta--; } // draw all objects onto screen render(); } }
private void reportStats(Graphics g) // Report the number of hits, and time spent playing { if (!gameOver) // stop incrementing the timer once the game is over timeSpentInGame = (int) ((System.nanoTime() - gameStartTime) / 1000000000L); // ns --> secs g.setColor(Color.red); g.setFont(msgsFont); g.drawString("Hits: " + numHits + "/" + MAX_HITS, 15, 25); g.drawString("Time: " + timeSpentInGame + " secs", 15, 50); g.setColor(Color.black); } // end of reportStats()
public void sequenceEnded(String imageName) // called by ImagesPlayer when the explosion animation finishes { showExplosion = false; explosionPlayer.restartAt(0); // reset animation for next time if (numHits >= MAX_HITS) { gameOver = true; score = (int) ((System.nanoTime() - gameStartTime) / 1000000000L); clipsLoader.play("applause", false); } } // end of sequenceEnded()
IdeRootPane( ActionManagerEx actionManager, UISettings uiSettings, DataManager dataManager, final Application application, final String[] commandLineArgs, IdeFrame frame) { myActionManager = actionManager; myUISettings = uiSettings; updateToolbar(); myContentPane.add(myNorthPanel, BorderLayout.NORTH); myStatusBarCustomComponentFactories = application.getExtensions(StatusBarCustomComponentFactory.EP_NAME); myApplication = application; createStatusBar(frame); updateStatusBarVisibility(); myContentPane.add(myStatusBar, BorderLayout.SOUTH); myUISettingsListener = new MyUISettingsListenerImpl(); setJMenuBar(new IdeMenuBar(actionManager, dataManager)); final Ref<Boolean> willOpenProject = new Ref<Boolean>(Boolean.FALSE); final AppLifecycleListener lifecyclePublisher = application.getMessageBus().syncPublisher(AppLifecycleListener.TOPIC); lifecyclePublisher.appFrameCreated(commandLineArgs, willOpenProject); LOG.info( "App initialization took " + (System.nanoTime() - PluginManager.startupStart) / 1000000 + " ms"); PluginManager.dumpPluginClassStatistics(); if (!willOpenProject.get()) { showWelcomeScreen(); lifecyclePublisher.welcomeScreenDisplayed(); } myGlassPane = new IdeGlassPaneImpl(this); setGlassPane(myGlassPane); myGlassPaneInitialized = true; myGlassPane.setVisible(false); Disposer.register(application, myDisposable); }
public void run() { try { // System.out.println("right before the while loop of the thread"); // layeredPane.add(background,99); while (true) { startTime = System.nanoTime(); try { // System.out.println("before Sleep"); Thread.sleep(30); // System.out.println("after sleep"); } catch (InterruptedException e) { e.printStackTrace(); } panel.remove(layeredPane); Iterator<PlayerMob> allPlayers = players.iterator(); PlayerMob aPlayer = null; while (allPlayers.hasNext()) { aPlayer = (PlayerMob) allPlayers.next(); // System.out.println("INTHELOOP:info.getUsername ="******" // myChat.getUsername ="******"for loop index catch"); continue; }*/ } } catch (NullPointerException ed) { System.err.println("for loop null catch"); startDrawingPanelThread(); } catch (Exception ev) { System.err.println("for loop catch"); ev.printStackTrace(); } }
private void updateProgress() { assert SwingUtilities.isEventDispatchThread(); if (isDone()) { return; } long currentTime = System.nanoTime(); progress = ((float) (currentTime - startTime)) / duration; progress = Math.max(progress, 0); // in case time was reset if (progress >= 1) { progress = 1; if (isForwardAndReverse) { startTime = currentTime; progress = 0; isForward = !isForward; } } }
/** Called via reflection */ @SuppressWarnings({"UnusedDeclaration", "HardCodedStringLiteral"}) protected static void start( final String mainClass, final String methodName, final String[] args) { startupStart = System.nanoTime(); Main.setFlags(args); if (!Main.isHeadless()) { UIUtil.initDefaultLAF(); } ThreadGroup threadGroup = new ThreadGroup("Idea Thread Group") { @Override public void uncaughtException(Thread t, Throwable e) { processException(e); } }; Runnable runnable = new Runnable() { @Override public void run() { try { ClassUtilCore.clearJarURLCache(); Class<?> aClass = Class.forName(mainClass); Method method = aClass.getDeclaredMethod(methodName, ArrayUtil.EMPTY_STRING_ARRAY.getClass()); method.setAccessible(true); Object[] argsArray = {args}; method.invoke(null, argsArray); } catch (Throwable t) { throw new StartupAbortedException(t); } } }; new Thread(threadGroup, runnable, "Idea Main Thread").start(); }
public void run() { long lastTime = System.nanoTime(); double unprocessed = 0; int frames = 0; long lastTimer1 = System.currentTimeMillis(); try { init(); } catch (Exception e) { e.printStackTrace(); return; } // if (!isMultiplayer) { // createLevel(); // } int toTick = 0; long lastRenderTime = System.nanoTime(); int min = 999999999; int max = 0; while (running) { if (!this.hasFocus()) { keys.release(); } double nsPerTick = 1000000000.0 / framerate; boolean shouldRender = false; while (unprocessed >= 1) { toTick++; unprocessed -= 1; } int tickCount = toTick; if (toTick > 0 && toTick < 3) { tickCount = 1; } if (toTick > 20) { toTick = 20; } for (int i = 0; i < tickCount; i++) { toTick--; // long before = System.nanoTime(); tick(); // long after = System.nanoTime(); // System.out.println("Tick time took " + (after - before) * // 100.0 / nsPerTick + "% of the max time"); shouldRender = true; } // shouldRender = true; BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); continue; } if (shouldRender) { frames++; Graphics g = bs.getDrawGraphics(); Random lastRandom = TurnSynchronizer.synchedRandom; TurnSynchronizer.synchedRandom = null; render(g); TurnSynchronizer.synchedRandom = lastRandom; long renderTime = System.nanoTime(); int timePassed = (int) (renderTime - lastRenderTime); if (timePassed < min) { min = timePassed; } if (timePassed > max) { max = timePassed; } lastRenderTime = renderTime; } long now = System.nanoTime(); unprocessed += (now - lastTime) / nsPerTick; lastTime = now; try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } if (shouldRender) { if (bs != null) { bs.show(); } } if (System.currentTimeMillis() - lastTimer1 > 1000) { lastTimer1 += 1000; fps = frames; frames = 0; } } }
public void actionPerformed(ActionEvent e) { String NameItem = (((JMenuItem) e.getSource()).getText()); if (NameItem == "Load File") { // all files disabled fc.setAcceptAllFileFilterUsed(false); // only XML files FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter("xml files (*.xml)", "xml"); fc.setFileFilter(xmlfilter); // Set Directory!! fc.setCurrentDirectory(new java.io.File("data")); // Open XML fc.setDialogTitle("Open XML"); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String FileLocation = file.getPath(); textArea.setText(""); // textArea.setText(FileLocation + "\n" + "\n"); // Parse XML xmlParser parser = new xmlParser(); final ContainerSetXml containers; try { long time = System.nanoTime(); containers = parser.parse(FileLocation); System.out.println( "It took" + (System.nanoTime() - time) + "ns to parse the xml file"); // new Thread for display next container after some time Thread t = new Thread() { public void run() { for (ContainerXml c : containers.containers) { DateFormat dateFormat = new SimpleDateFormat(" HH:mm:ss"); Calendar now = Calendar.getInstance(); String Time = "[" + dateFormat.format(now.getTime()) + "]"; textArea.append(Time + " " + c.id + " " + c.ownerName + "\n"); textArea.setCaretPosition(textArea.getDocument().getLength()); try { sleep(150); // milliseconds } catch (InterruptedException ex) { } } } }; t.start(); // call back run() } catch (Exception ex) { System.out.println(ex); } } } else if (NameItem == "Start server") { // server.start() launches server.run() in a new thread // Meaning server.start won't freeze the gui anymore server.start(6666); } else if (NameItem == "Login to ftp") { FtpLoginView ftpLoginView = new FtpLoginView(server); ftpLoginView.display(); String name = ftpLoginView.name; String password = ftpLoginView.name; // server.login() is called in ftpLoginView } else if (NameItem == "About") { JOptionPane.showMessageDialog( null, "Mede mogelijk gemaakt door Groep 5!", "About", JOptionPane.INFORMATION_MESSAGE); } else if (NameItem == "Help") { JOptionPane.showMessageDialog( null, "Moet nog ingevuld worden!", "Help", JOptionPane.INFORMATION_MESSAGE); } else if (NameItem == "Quit") { System.exit(0); } else if (NameItem == "Restart server") { server.restart(6666); } else if (NameItem == "Stop server") { server.stop(); } }
private void jButtonSOLVEActionPerformed(java.awt.event.ActionEvent evt) throws IOException { System.out.println("solving"); // DEBUG // BufferedReader in = new BufferedReader(new // FileReader("C:\\Users\\Rainer\\Desktop\\2013 FALL\\CAP 4621 - Artificial // Intelligence\\Project\\InitialBoard.txt")); // // try{ // in = new BufferedReader(new FileReader("C:\\Users\\Rainer\\Desktop\\2013 // FALL\\CAP 4621 - Artificial Intelligence\\Project\\InitialBoard.txt")); // // }catch (FileNotFoundException e){ // System.out.println(e.getCause()); // System.out.println("Error loading initial board"); // } // // int [] boardRows = new int [15]; // // //---------------- // String text = in.readLine(); // // StringTokenizer tokenizer = new StringTokenizer(text," "); // // int boardSize = 0; // while (tokenizer.hasMoreElements()){ // boardRows[boardSize] = Integer.parseInt(tokenizer.nextToken()); // boardSize++; // } // // int []newBoard = new int[boardSize*boardSize+1]; // System.arraycopy(boardRows, 0, newBoard, 1, boardSize); // // int index = 0; // while (in.ready()) { // index++; // text = in.readLine(); // // tokenizer = new StringTokenizer(text," "); // int pos = 0; // while (tokenizer.hasMoreElements()){ // pos++; // newBoard[index*boardSize+pos] = // Integer.parseInt(tokenizer.nextToken()); // } // } // // this.jFrameFileChooser.setVisible(false); // // this.boardPanel.s // // gameInitialBoard = new Board(newBoard, boardSize); // gameBoard = new Board(newBoard, boardSize); // init(); // // END DEBUG long startTime = System.nanoTime(); this.gameBoard.solveBoard(); long endTime = System.nanoTime(); double time = (endTime - startTime) / 100000000.0; System.out.println("Excecution time: " + time + " seconds"); // jPanelSolvedBoard jPanelSolvedBoard.removeAll(); jPanelSolvedBoard.setLayout( new GridLayout(gameBoard.boardSize, gameBoard.boardSize)); // Set layout solvedCells = new JTextField[gameBoard.boardSize * gameBoard.boardSize + 1]; for (int i = 1; i <= gameBoard.boardSize * gameBoard.boardSize; i++) { solvedCells[i] = new JTextField(); solvedCells[i].setHorizontalAlignment(JTextField.CENTER); solvedCells[i].setFont(new Font("Agency FB", Font.BOLD, 24)); // Add elements to the grid content pane jPanelSolvedBoard.add(solvedCells[i]); String ch = Integer.toString(this.gameBoard.cells[i]); solvedCells[i].setText(ch); solvedCells[i].setEditable(false); } // gameBoard.out(); jPanelSolvedBoard.setVisible(true); this.jPanelSolvedBoard.repaint(); this.jFrameSolvedBoard.setVisible(true); this.jFrameSolvedBoard.pack(); // }
public class BallDetector extends Thread { Context ctx; Device kinect; JFrame controlFrame; JFrame colorFrame; JFrame depthFrame; // JImage rgbJim; // JImage depthJim; JButton startTracking; JButton resetProjectile; JButton resetDepth; boolean tracking = false; boolean log = false; ParameterGUI pg; BufferedImage rgbImg; BufferedImage depthImg; Statistics BALL; boolean[] validImageValue; static double x_param = 0d; static int y_param = 0; LCM lcm; final boolean colorAnalyze = false; final boolean colorAnalyze2 = true; boolean display = false; volatile long globalTime = 0; volatile long startTime = System.nanoTime(); final boolean verbose = false; volatile boolean newImage = false; public Point3D botStart; BallTracker finder; KinectRGBVideo colorStream; Object colorMonitor; KinectDepthVideo depthStream; Object depthMonitor; BallDetector(boolean _display) { ctx = Freenect.createContext(); if (ctx.numDevices() > 0) { kinect = ctx.openDevice(0); } else { System.err.println("WARNING: No kinects detected"); return; } display = _display; controlFrame = new JFrame("Controls"); controlFrame.setLayout(new GridLayout(5, 1)); controlFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pg = new ParameterGUI(); pg.addIntSlider("maxDepth", "max depth", 800, 2047, 1050); pg.addIntSlider("blobThresh", "blob thresh", 1, 500, 125); pg.addIntSlider("thresh", "thresh", 1, 100, 10); pg.addIntSlider("frames", "frames", 1, 1000, 1); pg.addListener( new ParameterListener() { public void parameterChanged(ParameterGUI _pg, String name) { if (name.equals("thresh")) { KinectDepthVideo.THRESH = _pg.gi(name); } else if (name.equals("frames")) { KinectDepthVideo.MAX_FRAMES = _pg.gi(name); } else if (name.equals("maxDepth")) { KinectDepthVideo.MAX_DEPTH = _pg.gi(name); } } }); controlFrame.add(pg, 0, 0); startTracking = new JButton("Start Tracking Balls"); startTracking.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (!tracking) { tracking = true; colorStream.pause(); depthStream.pause(); startTracking.setText("Stop Tracking"); } else { tracking = false; colorStream.resume(); depthStream.resume(); startTracking.setText("Start Tracking Balls"); } } }); controlFrame.add(startTracking, 1, 0); resetProjectile = new JButton("Reset Projectile"); resetProjectile.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { lcm.publish("6_RESET", "reset"); } catch (IOException ex) { System.out.println("can't publish reset"); } } }); controlFrame.add(resetProjectile, 2, 0); resetDepth = new JButton("Reset Depth Avgs"); resetDepth.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { DepthClearer ic = new DepthClearer(pg); ic.start(); } }); controlFrame.add(resetDepth, 3, 0); JPanel scoreButtons = new JPanel(new GridLayout(1, 3)); JButton addHuman = new JButton("human++"); addHuman.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { lcm.publish("6_SCORE_HUMAN", "bish"); } catch (IOException ex) { System.out.println("can't publish score"); } } }); JButton addRobot = new JButton("robot++"); addRobot.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { lcm.publish("6_SCORE_ROBOT", "bish"); } catch (IOException ex) { System.out.println("can't publish score"); } } }); JButton resetScores = new JButton("reset scores"); resetScores.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { lcm.publish("6_SCORE_RESET", "bish"); } catch (IOException ex) { System.out.println("can't publish score"); } } }); scoreButtons.add(addHuman, 0, 0); scoreButtons.add(addRobot, 0, 1); scoreButtons.add(resetScores, 0, 2); controlFrame.add(scoreButtons, 4, 0); controlFrame.setSize(800, 600); controlFrame.setVisible(true); colorFrame = new JFrame("color feed"); colorMonitor = new Object(); colorStream = new KinectRGBVideo(kinect, colorMonitor, display); colorFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); colorFrame.addWindowListener(new RGBClose()); colorFrame.setSize(KinectVideo.WIDTH, KinectVideo.HEIGHT); colorFrame.setContentPane(colorStream); colorFrame.setVisible(true); depthFrame = new JFrame("depth feed"); depthMonitor = new Object(); depthStream = new KinectDepthVideo(kinect, depthMonitor, display); depthFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); depthFrame.setSize(KinectVideo.WIDTH, KinectVideo.HEIGHT); depthFrame.setContentPane(depthStream); depthFrame.setVisible(true); rgbImg = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB); depthImg = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB); validImageValue = new boolean[KinectVideo.WIDTH * KinectVideo.HEIGHT]; try { lcm = new LCM("udpm://239.255.76.67:7667?ttl=1"); } catch (IOException e) { lcm = LCM.getSingleton(); } BALL = new Statistics(); finder = new BallTracker(KinectVideo.WIDTH, KinectVideo.HEIGHT, false); if (display) { depthImg = depthStream.getFrame(); rgbImg = colorStream.getFrame(); } // get robot position from click depthStream.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent e) { Point botPix = e.getPoint(); botStart = depthStream.getWorldCoords(botPix); botStart.z += 0.08; System.out.println("botStart: " + botStart.toString()); depthStream.showSubtraction(); depthStream.botLoc = botPix; } }); DepthClearer ic = new DepthClearer(pg); ic.start(); } // stops rgb feed if user closes rgb window public class RGBClose implements WindowListener { public void windowClosing(WindowEvent e) { kinect.stopVideo(); colorFrame.dispose(); } public void windowOpened(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} } public void run() { while (true) { BALL = null; ball_t ballLCM = new ball_t(); synchronized (depthMonitor) { try { depthMonitor.wait(); } catch (Exception e) { e.printStackTrace(); } } ballLCM.nanoTime = depthStream.latestTimestamp; ArrayList<Statistics> blobs; depthStream.getReadLock().lock(); try { blobs = finder.analyze2(depthStream.getValidImageArray()); } finally { depthStream.getReadLock().unlock(); } Statistics ball = null; Statistics robot = null; int minSize = pg.gi("blobThresh"); // find robot and ball by blob size Collections.sort(blobs, ComparatorFactory.getStatisticsCompareSize()); // find robot and ball by y pixel // Collections.sort(blobs, ComparatorFactory.getStatisticsCompareYPix()); // if (tracking) { // System.out.println("num blobs: " + blobs.size()); // System.out.println("biggest blob size: " + blobs.get(0).N); // } // for (Statistics blob : blobs) { // if (blob.N > 10) { // System.out.println("blob size: " + blob.N); // } // else { // break; // } // } if (blobs.size() == 1) { Statistics first = blobs.get(0); if (first.N > minSize) { ball = first; } } else if (blobs.size() >= 2) { Statistics first = blobs.get(0); Statistics second = blobs.get(1); if (first.N > minSize) { ball = first; } if (second.N > minSize) { robot = first; ball = second; } } // System.out.println("balls points " + depthStream.trajectory.size()); // if not tracking keep kv.depthStream.trajectory to just one index if (!tracking) { depthStream.trajectory.clear(); } if (ball != null) { depthStream.trajectory.add(ball); Point depthPix = ball.center(); Point depthCoord = new Point(); depthCoord.x = depthPix.x - KinectVideo.C_X; depthCoord.y = KinectVideo.C_Y - depthPix.y; // System.out.println("avg depth " + ball.Uz()); // get depth from average depth of blob double realDepth = raw_depth_to_meters(ball.Uz()); Point3D coord = depthStream.getWorldCoords(depthCoord, realDepth); if (depthPix != null) { for (int y = depthPix.y - 3; y < depthPix.y + 3; y++) { for (int x = depthPix.x - 3; x < depthPix.x + 3; x++) { try { depthImg.setRGB(x, y, 0xFFFF0000); } catch (Exception e) { // System.out.println(x + " " + y); } ; } } // if (tracking) { // //save image // depthStream.getReadLock().lock(); // try { // File imgFile = new File("image" + ballNum++ + ".png"); // try { // ImageIO.write(depthImg, "png", imgFile); // } // catch(Exception e) { // System.out.println("can't save img"); // } // } // finally { // depthStream.getReadLock().unlock(); // } // } if (tracking) { ballLCM.x = coord.x; ballLCM.y = coord.y; ballLCM.z = coord.z; // if(tracking) System.out.println("updating new ball (" + System.currentTimeMillis() + ")"); // if (ballLCM.x > CatchController.TARGET_MAX_X) lcm.publish("6_BALL", ballLCM); // else // System.out.println("ball past target zone"); } } } } } public float raw_depth_to_meters(int raw_depth) { if (raw_depth < 2047) { return (1.0f / (raw_depth * -0.0030711016f + 3.3309495161f)) + .05f; } return 0; } // utility functions to copy/paste later public int getDepth(ByteBuffer bb, int index) { int depth = 0; byte byte1 = bb.get(index * 2); byte byte2 = bb.get(index * 2 + 1); depth = byte2 & 0x3; depth = depth << 8; depth = depth | (byte1 & 0xFF); return depth & 0x3FF; } public void setLog(boolean b) { log = b; } public class DepthClearer extends Thread { ParameterGUI pg; public DepthClearer(ParameterGUI _pg) { pg = _pg; } // set max_frames to 1 for 5 seconds then move up to 200 public void run() { pg.si("frames", 1); try { Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } for (int i = 1; i <= 100; i++) { pg.si("frames", 2 * i); try { Thread.sleep(10); } catch (Exception e) { e.printStackTrace(); } } } } public void plotProjection(ArrayList<double[]> pballs) { for (int i = 0; i < pballs.size(); i++) { double xyzt[] = pballs.get(i); // switch y and z; double temp = xyzt[2]; xyzt[2] = xyzt[1]; xyzt[1] = temp; Point3D realWorld = new Point3D(xyzt[0], xyzt[1], xyzt[2]); // Point pixCoords = depthgetPixFromWorld(realWorld); // depthImg.setRGB(pixCoords.x,pixCoords.y,0xFFFFFFFF); } } public static void main(String[] args) { // Projectile proj = new Projectile(); BallDetector kv = new BallDetector(true); // for(int i = 0; i < args.length; i++) // { // if(args[i].equals("log")) // kv.setLog(true); // } kv.start(); } }
private static long elapsedMs(long startTime) { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); }
public void contextAction() throws Exception { final ThreadReferenceProxyImpl thread = myDebuggerContext.getThreadProxy(); try { if (!getSuspendContext().getDebugProcess().getSuspendManager().isSuspended(thread)) { DebuggerInvocationUtil.swingInvokeLater( getProject(), new Runnable() { public void run() { try { myFramesListener.setEnabled(false); synchronized (myFramesList) { final DefaultListModel model = myFramesList.getModel(); model.clear(); model.addElement( new Object() { public String toString() { return DebuggerBundle.message("frame.panel.frames.not.available"); } }); myFramesList.setSelectedIndex(0); } } finally { myFramesListener.setEnabled(true); } } }); return; } } catch (ObjectCollectedException e) { return; } List<StackFrameProxyImpl> frames; try { frames = thread.frames(); } catch (EvaluateException e) { frames = Collections.emptyList(); } final StackFrameProxyImpl contextFrame = myDebuggerContext.getFrameProxy(); final EvaluationContextImpl evaluationContext = myDebuggerContext.createEvaluationContext(); final DebuggerManagerThreadImpl managerThread = myDebuggerContext.getDebugProcess().getManagerThread(); final MethodsTracker tracker = new MethodsTracker(); final int totalFramesCount = frames.size(); int index = 0; final long timestamp = System.nanoTime(); for (StackFrameProxyImpl stackFrameProxy : frames) { managerThread.schedule( new AppendFrameCommand( getSuspendContext(), stackFrameProxy, evaluationContext, tracker, index++, stackFrameProxy.equals(contextFrame), totalFramesCount, timestamp)); } }