Ejemplo n.º 1
0
  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();
  }
Ejemplo n.º 2
0
  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));
  }
Ejemplo n.º 3
0
  /** Main function called by run() every loop. */
  public void tick() {
    long var1 = System.nanoTime();
    ++this.tickCounter;

    if (this.startProfiling) {
      this.startProfiling = false;
      this.theProfiler.profilingEnabled = true;
      this.theProfiler.clearProfiling();
    }

    this.theProfiler.startSection("root");
    this.updateTimeLightAndEntities();

    if (var1 - this.nanoTimeSinceStatusRefresh >= 5000000000L) {
      this.nanoTimeSinceStatusRefresh = var1;
      this.statusResponse.setPlayerCountData(
          new ServerStatusResponse.PlayerCountData(
              this.getMaxPlayers(), this.getCurrentPlayerCount()));
      GameProfile[] var3 = new GameProfile[Math.min(this.getCurrentPlayerCount(), 12)];
      int var4 =
          MathHelper.getRandomIntegerInRange(
              this.random, 0, this.getCurrentPlayerCount() - var3.length);

      for (int var5 = 0; var5 < var3.length; ++var5) {
        var3[var5] =
            ((EntityPlayerMP) this.serverConfigManager.playerEntityList.get(var4 + var5))
                .getGameProfile();
      }

      Collections.shuffle(Arrays.asList(var3));
      this.statusResponse.getPlayerCountData().setPlayers(var3);
    }

    if (this.tickCounter % 900 == 0) {
      this.theProfiler.startSection("save");
      this.serverConfigManager.saveAllPlayerData();
      this.saveAllWorlds(true);
      this.theProfiler.endSection();
    }

    this.theProfiler.startSection("tallying");
    this.tickTimeArray[this.tickCounter % 100] = System.nanoTime() - var1;
    this.theProfiler.endSection();
    this.theProfiler.startSection("snooper");

    if (!this.usageSnooper.isSnooperRunning() && this.tickCounter > 100) {
      this.usageSnooper.startSnooper();
    }

    if (this.tickCounter % 6000 == 0) {
      this.usageSnooper.addMemoryStatsToSnooper();
    }

    this.theProfiler.endSection();
    this.theProfiler.endSection();
  }
Ejemplo n.º 4
0
  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()
Ejemplo n.º 5
0
  /**
   * 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;
  }
Ejemplo n.º 6
0
 public static void analysis(Vector X, Supplier<double[]> function) {
   long start = System.nanoTime();
   double[] r = function.get();
   long end = System.nanoTime();
   System.out.println("Time:" + (end - start) / 1000000f + "ms");
   Vector R = new Vector(r);
   System.out.println("Norm2:" + X.sub(R).getNorm2());
   pw.print(",");
   pw.print((end - start) / 1000000f);
   pw.print(",");
   pw.print(X.sub(R).getNorm2());
   pw.println();
   pw.flush();
 }
Ejemplo n.º 7
0
  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);
      }
    }
  /**
   * Capture a part of the desktop screen using <tt>java.awt.Robot</tt>.
   *
   * @param x x position to start capture
   * @param y y position to start capture
   * @param width capture width
   * @param height capture height
   * @return <tt>BufferedImage</tt> of a part of the desktop screen or null if Robot problem
   */
  public BufferedImage captureScreen(int x, int y, int width, int height) {
    BufferedImage img = null;
    Rectangle rect = null;

    if (robot == null) {
      /* Robot has not been created so abort */
      return null;
    }

    if (logger.isInfoEnabled()) logger.info("Begin capture: " + System.nanoTime());
    rect = new Rectangle(x, y, width, height);
    img = robot.createScreenCapture(rect);
    if (logger.isInfoEnabled()) logger.info("End capture: " + System.nanoTime());

    return img;
  }
  /** 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();
    }
  }
 private void msgHandler(
     final DirectBuffer buffer, final int offset, final int length, final Header header) {
   if (buffer.getByte(offset) == (byte) 'p') {
     timestamps[buffer.getInt(offset + 1)] = System.nanoTime() - buffer.getLong(offset + 5);
   } else {
     warmups++;
   }
 }
Ejemplo n.º 12
0
  /**
   * Blocks and reads into a <tt>Buffer</tt> from this <tt>PullBufferStream</tt>.
   *
   * @param buffer the <tt>Buffer</tt> this <tt>PullBufferStream</tt> is to read into
   * @throws IOException if an I/O error occurs while this <tt>PullBufferStream</tt> reads into the
   *     specified <tt>Buffer</tt>
   * @see AbstractVideoPullBufferStream#doRead(Buffer)
   */
  @Override
  protected void doRead(Buffer buffer) throws IOException {
    /*
     * Determine the Format in which we're expected to output. We cannot
     * rely on the Format always being specified in the Buffer because it is
     * not its responsibility, the DataSource of this ImageStream knows the
     * output Format.
     */
    Format format = buffer.getFormat();

    if (format == null) {
      format = getFormat();
      if (format != null) buffer.setFormat(format);
    }

    if (format instanceof AVFrameFormat) {
      Object o = buffer.getData();
      AVFrame frame;

      if (o instanceof AVFrame) frame = (AVFrame) o;
      else {
        frame = new AVFrame();
        buffer.setData(frame);
      }

      AVFrameFormat avFrameFormat = (AVFrameFormat) format;
      Dimension size = avFrameFormat.getSize();
      ByteBuffer data = readScreenNative(size);

      if (data != null) {
        if (frame.avpicture_fill(data, avFrameFormat) < 0) {
          data.free();
          throw new IOException("avpicture_fill");
        }
      } else {
        /*
         * This can happen when we disconnect a monitor from computer
         * before or during grabbing.
         */
        throw new IOException("Failed to grab screen.");
      }
    } else {
      byte[] bytes = (byte[]) buffer.getData();
      Dimension size = ((VideoFormat) format).getSize();

      bytes = readScreen(bytes, size);

      buffer.setData(bytes);
      buffer.setOffset(0);
      buffer.setLength(bytes.length);
    }

    buffer.setHeader(null);
    buffer.setTimeStamp(System.nanoTime());
    buffer.setSequenceNumber(seqNo);
    buffer.setFlags(Buffer.FLAG_SYSTEM_TIME | Buffer.FLAG_LIVE_DATA);
    seqNo++;
  }
Ejemplo n.º 13
0
  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()));
    }
  }
Ejemplo n.º 14
0
  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;
    }
Ejemplo n.º 16
0
 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()
Ejemplo n.º 17
0
  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();
    }
  }
  public int onNext() {
    while (pub.tryClaim(buffer.capacity(), bufferClaim) < 0L) {}

    final MutableDirectBuffer buffer = bufferClaim.buffer();
    final int offset = bufferClaim.offset();
    buffer.putByte(offset, (byte) 'p');
    buffer.putInt(offset + 1, msgCount++);
    buffer.putLong(offset + 5, System.nanoTime());
    bufferClaim.commit();
    return msgLen;
  }
Ejemplo n.º 19
0
    CExplode(double x, double y) {
      for (int i = 0; i < particles.length; i++) {
        // particles[i][0] = new Ellipse2D.Double(x, y, 10, 10);
        particles[i][0] =
            new Arc2D.Double(
                x - 25, y - 25, 50, 50, 360 / particles.length * i, 360 / particles.length * 2, 0);
        particles[i][1] = rand.nextDouble() + rand.nextInt(3) - 1;
        particles[i][2] = rand.nextDouble() + rand.nextInt(3) - 1;

        created = System.nanoTime();
      }
    }
Ejemplo n.º 20
0
 public void run() {
   init();
   long start;
   long elapsed;
   long wait;
   // game loop
   while (running) {
     start = System.nanoTime(); // time stamp
     update();
     draw();
     drawToScreen();
     elapsed = System.nanoTime() - start;
     wait = targetTime - elapsed / 1000000;
     if (wait < 0) wait = 5;
     try {
       Thread.sleep(wait);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Ejemplo n.º 21
0
  // Binary search.
  public boolean contains(String word) {
    int low = 0;
    int high = words.size() - 1;

    long time = System.nanoTime();

    while (low <= high) {
      int mid = (low + high) / 2;
      int diff = words.get(mid).compareTo(word);
      if (diff == 0) {
        avgLookupTime =
            avgLookupTime * (avgIndex - 1) / avgIndex + (System.nanoTime() - time) / avgIndex;
        avgIndex++;
        return true;
      } else if (diff < 0) {
        low = mid + 1;
      } else {
        high = mid - 1;
      }
    }
    return false;
  }
Ejemplo n.º 22
0
  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()
Ejemplo n.º 23
0
  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);
  }
Ejemplo n.º 24
0
 boolean render(Graphics2D map) {
   double diff = (System.nanoTime() - created) / 1000 / 1000;
   if (diff > timeAlive) return true;
   map.setColor(new Color(100, 100, 100, (int) (255 - (diff / timeAlive * 250))));
   for (int i = 0; i < particles.length; i++) {
     RectangularShape tmp = (RectangularShape) particles[i][0];
     double xD = (Double) particles[i][1];
     double yD = (Double) particles[i][2];
     tmp.setFrame(
         (double) tmp.getX() + xD / delta,
         (double) tmp.getY() + yD / delta,
         tmp.getWidth(),
         tmp.getHeight());
     map.draw(tmp);
   }
   return false;
 }
    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;
        }
      }
    }
Ejemplo n.º 26
0
 public void refreshColor() {
   Random random;
   long randomValue = (long) (System.nanoTime() * Math.pow(id + 1, 2) + 31);
   random = new Random(randomValue);
   color =
       Color.getHSBColor(
           random.nextFloat() * 1.3f, random.nextFloat() * 2.5f, random.nextFloat() * 4.4f);
   while ((color.getBlue() < 5 && color.getGreen() < 5 && color.getRed() < 5)
       || (color.getBlue() + 5 < Color.MAGENTA.getBlue()
           && color.getBlue() - 5 > Color.MAGENTA.getBlue()
           && color.getGreen() + 5 < Color.MAGENTA.getGreen()
           && color.getGreen() - 5 > Color.MAGENTA.getGreen()
           && color.getRed() + 5 < Color.MAGENTA.getRed()
           && color.getRed() - 5 > Color.MAGENTA.getRed())) {
     color =
         Color.getHSBColor(
             random.nextFloat() * 1.3f, random.nextFloat() * 2.5f, random.nextFloat() * 4.4f);
   }
 }
Ejemplo n.º 27
0
  public void update() {

    // update position
    getNextPosition();
    checkTileMapCollision();

    // slugger turns around if it hits a wall or is about to fall off a cliff
    calculateCorners(x, ydest + 1);
    if (!bottomLeft) {
      left = false;
      right = facingRight = true;
    }
    if (!bottomRight) {
      left = true;
      right = facingRight = false;
    }

    setPosition(xtemp, ytemp);

    if (dx == 0) {
      left = !left;
      right = !right;
      facingRight = !facingRight;
    }

    // check flinching
    if (flinching) {
      long elapsed = (System.nanoTime() - flinchTimer) / 1000000;
      if (elapsed > 400) {
        flinching = false;
      }
    }

    // update animation
    animation.update();
  }
Ejemplo n.º 28
0
/**
 * Diese Klasse stellt die Oberklasse aller darstellbaren Objekte dar.
 *
 * @author Robert Giacinto
 */
public abstract class AbstractShape implements Shape {

  private static final Logger log = LoggerFactory.getLogger(AbstractShape.class);
  private Animation animation;
  private Node node;
  protected String label = getClass().getSimpleName() + " - " + System.nanoTime();
  protected BoundingBox boundingBox = new BoundingBox();
  protected RGBColor color = new RGBColor(0, 0, 0);
  protected Material material = new Material();

  @Override
  public Color getColor() {
    return color.toColor();
  }

  @Override
  public void setColor(Color color) {
    float[] colors = color.getColorComponents(null);
    this.color = new RGBColor(colors[0], colors[1], colors[2]);
  }

  @Override
  public void setColor(RGBColor color) {
    this.color = color;
  }

  @Override
  public String getLabel() {
    return label;
  }

  @Override
  public void update() {
    if (animation != null) {
      animation.update();
    }
  }

  @Override
  public void updateBoundingBox(Matrix transform) {
    boundingBox.updateBox(transform);
  }

  @Override
  public void setAnimation(Animation animation) {
    this.animation = animation;
  }

  @Override
  public Animation getAnimation() {
    return animation;
  }

  @Override
  public Node getNode() {
    return node;
  }

  @Override
  public void setNode(Node node) {
    this.node = node;
  }

  @Override
  public BoundingBox getBoundingBox() {
    return boundingBox;
  }

  @Override
  public boolean hit(Ray ray, ShadingInfo shadingInfo) {
    return false;
  }

  @Override
  public Material getMaterial() {
    return material;
  }

  @Override
  public void setMaterial(Material material) {
    this.material = material;
  }

  @Override
  public void render(Renderer renderer) {
    // Leere Implementierung. Sollte von Unterklassen mit Inhalt gefüllt werden,
    // wenn sie durch einen Renderer darstellbar sein sollen.
  }
}
Ejemplo n.º 29
0
  public void updateTimeLightAndEntities() {
    this.theProfiler.startSection("jobs");
    Queue var1 = this.futureTaskQueue;

    synchronized (this.futureTaskQueue) {
      while (!this.futureTaskQueue.isEmpty()) {
        try {
          ((FutureTask) this.futureTaskQueue.poll()).run();
        } catch (Throwable var9) {
          logger.fatal(var9);
        }
      }
    }

    this.theProfiler.endStartSection("levels");
    int var11;

    for (var11 = 0; var11 < this.worldServers.length; ++var11) {
      long var2 = System.nanoTime();

      if (var11 == 0 || this.getAllowNether()) {
        WorldServer var4 = this.worldServers[var11];
        this.theProfiler.startSection(var4.getWorldInfo().getWorldName());

        if (this.tickCounter % 20 == 0) {
          this.theProfiler.startSection("timeSync");
          this.serverConfigManager.sendPacketToAllPlayersInDimension(
              new S03PacketTimeUpdate(
                  var4.getTotalWorldTime(),
                  var4.getWorldTime(),
                  var4.getGameRules().getGameRuleBooleanValue("doDaylightCycle")),
              var4.provider.getDimensionId());
          this.theProfiler.endSection();
        }

        this.theProfiler.startSection("tick");
        CrashReport var6;

        try {
          var4.tick();
        } catch (Throwable var8) {
          var6 = CrashReport.makeCrashReport(var8, "Exception ticking world");
          var4.addWorldInfoToCrashReport(var6);
          throw new ReportedException(var6);
        }

        try {
          var4.updateEntities();
        } catch (Throwable var7) {
          var6 = CrashReport.makeCrashReport(var7, "Exception ticking world entities");
          var4.addWorldInfoToCrashReport(var6);
          throw new ReportedException(var6);
        }

        this.theProfiler.endSection();
        this.theProfiler.startSection("tracker");
        var4.getEntityTracker().updateTrackedEntities();
        this.theProfiler.endSection();
        this.theProfiler.endSection();
      }

      this.timeOfLastDimensionTick[var11][this.tickCounter % 100] = System.nanoTime() - var2;
    }

    this.theProfiler.endStartSection("connection");
    this.getNetworkSystem().networkTick();
    this.theProfiler.endStartSection("players");
    this.serverConfigManager.onTick();
    this.theProfiler.endStartSection("tickables");

    for (var11 = 0; var11 < this.playersOnline.size(); ++var11) {
      ((IUpdatePlayerListBox) this.playersOnline.get(var11)).update();
    }

    this.theProfiler.endSection();
  }
Ejemplo n.º 30
0
 private static double phase() {
   return System.nanoTime() / period * 1e-9 % 1;
 }