Ejemplo n.º 1
0
 public Object initTest(TestEnvironment env, Result result) {
   Context ctx = new Context();
   ctx.bimg = ((BufImg) env.getModifier(bufimgsrcroot)).getImage();
   if (env.isEnabled(doRenderTo)) {
     Graphics2D g2d = ctx.bimg.createGraphics();
     g2d.setColor(Color.white);
     g2d.fillRect(3, 0, 1, 1);
     g2d.dispose();
   }
   if (env.isEnabled(doRenderFrom)) {
     GraphicsConfiguration cfg =
         GraphicsEnvironment.getLocalGraphicsEnvironment()
             .getDefaultScreenDevice()
             .getDefaultConfiguration();
     VolatileImage vimg = cfg.createCompatibleVolatileImage(8, 1);
     vimg.validate(cfg);
     Graphics2D g2d = vimg.createGraphics();
     for (int i = 0; i < 100; i++) {
       g2d.drawImage(ctx.bimg, 0, 0, null);
     }
     g2d.dispose();
     vimg.flush();
   }
   result.setUnits(1);
   result.setUnitName(getUnitName());
   return ctx;
 }
Ejemplo n.º 2
0
  private VolatileImage loadFromFile(String filename) throws ImageLoadException {
    try {

      BufferedImage bimage = ImageIO.read(new File(filename));
      VolatileImage vimage =
          createVolatileImage(bimage.getWidth(), bimage.getHeight(), Transparency.TRANSLUCENT);
      Graphics2D g = null;

      try {
        g = vimage.createGraphics();
        g.setComposite(AlphaComposite.Src);

        g.setColor(new Color(0, 0, 0, 0));
        g.fillRect(0, 0, vimage.getWidth(), vimage.getHeight());

        g.drawImage(bimage, null, 0, 0);
      } finally {
        g.dispose();
      }

      return vimage;
    } catch (Exception e) {
      throw new ImageLoadException("Impossible de charger une image � " + filename, e);
    }
  }
Ejemplo n.º 3
0
  private void actualizaTodo() {
    if (!this.controlador.dibujarEscenario()) {
      return;
    }
    int ancho = this.controlador.getAnchoEscenario() * this.pixelesUnidad;
    int alto = this.controlador.getAltoEscenario() * this.pixelesUnidad;
    if ((ancho <= 0) || (alto <= 0)) {
      System.err.println(
          "Error gráfico: el escenario tiene dimensiones negativas. No se actualiza");
      return;
    }
    if ((this.anchoEscenario != ancho) || (this.altoEscenario != alto)) {
      this.anchoEscenario = ancho;
      this.altoEscenario = alto;
      redimensionar();
    }
    Graphics2D original = (Graphics2D) this.escenario.getGraphics();
    VolatileImage buffer = createVolatileImage(this.anchoEscenario, this.altoEscenario);
    Graphics grafico = buffer.getGraphics();

    grafico.setPaintMode();
    grafico.setColor(this.colorSuelo);
    grafico.fillRect(0, 0, this.escenario.getWidth(), this.escenario.getHeight());

    int diametroX = this.controlador.getAnchoEscenario() / 2;
    int diametroY = this.controlador.getAltoEscenario() / 2;
    IRegion region = calcularRegion(diametroX, diametroY);
    IPunto origen = region.getPosicionInferiorIzquierda();

    dibujarCeldas(grafico, region, origen);
    dibujarEntidades(grafico, region, origen);

    original.drawImage(buffer, 0, 0, this);
  }
Ejemplo n.º 4
0
 /**
  * Performs the native flip operation for the given target Component.
  *
  * <p>REMIND: we should really not get here because that would mean that a FLIP BufferStrategy has
  * been created, and one could only be created if accelerated pipeline is present but in some rare
  * (and transitional) cases it may happen that the accelerated graphics device may have a default
  * graphics configuraiton, so this is just a precaution.
  */
 public void flip(
     WComponentPeer peer,
     Component target,
     VolatileImage backBuffer,
     int x1,
     int y1,
     int x2,
     int y2,
     BufferCapabilities.FlipContents flipAction) {
   if (flipAction == BufferCapabilities.FlipContents.COPIED
       || flipAction == BufferCapabilities.FlipContents.UNDEFINED) {
     Graphics g = peer.getGraphics();
     try {
       g.drawImage(backBuffer, x1, y1, x2, y2, x1, y1, x2, y2, null);
     } finally {
       g.dispose();
     }
   } else if (flipAction == BufferCapabilities.FlipContents.BACKGROUND) {
     Graphics g = backBuffer.getGraphics();
     try {
       g.setColor(target.getBackground());
       g.fillRect(0, 0, backBuffer.getWidth(), backBuffer.getHeight());
     } finally {
       g.dispose();
     }
   }
   // the rest of the flip actions are not supported
 }
 /**
  * Renders the image at the proper size into <code>bgImage</code>. This method assumes that <code>
  * bgImage</code> is not <code>null</code>.
  *
  * @param width The width of the volatile image to render into.
  * @param height The height of the volatile image to render into.
  * @param hint The scaling hint to use.
  */
 protected void renderImage(int width, int height, int hint) {
   Image master = getMasterImage();
   if (master != null) {
     do {
       Image i = master.getScaledInstance(width, height, hint);
       tracker.addImage(i, 1);
       try {
         tracker.waitForID(1);
       } catch (InterruptedException e) {
         e.printStackTrace();
         bgImage = null;
         return;
       } finally {
         tracker.removeImage(i, 1);
       }
       bgImage.getGraphics().drawImage(i, 0, 0, null);
       tracker.addImage(bgImage, 0);
       try {
         tracker.waitForID(0);
       } catch (InterruptedException e) {
         e.printStackTrace();
         bgImage = null;
         return;
       } finally {
         tracker.removeImage(bgImage, 0);
       }
     } while (bgImage.contentsLost());
   } // End of if (master!=null).
   else {
     bgImage = null;
   }
 }
 /**
  * Returns a {@link VolatileImage} with a data layout and color model compatible with this <code>
  * GraphicsConfiguration</code>, using the specified image capabilities and transparency value. If
  * the <code>caps</code> parameter is null, it is effectively ignored and this method will create
  * a VolatileImage without regard to <code>ImageCapabilities</code> constraints.
  *
  * <p>The returned <code>VolatileImage</code> has a layout and color model that is closest to this
  * native device configuration and can therefore be optimally blitted to this device.
  *
  * @param width the width of the returned <code>VolatileImage</code>
  * @param height the height of the returned <code>VolatileImage</code>
  * @param caps the image capabilities
  * @param transparency the specified transparency mode
  * @return a <code>VolatileImage</code> whose data layout and color model is compatible with this
  *     <code>GraphicsConfiguration</code>.
  * @see Transparency#OPAQUE
  * @see Transparency#BITMASK
  * @see Transparency#TRANSLUCENT
  * @throws IllegalArgumentException if the transparency is not a valid value
  * @exception AWTException if the supplied image capabilities could not be met by this graphics
  *     configuration
  * @see Component#createVolatileImage(int, int)
  * @since 1.5
  */
 public VolatileImage createCompatibleVolatileImage(
     int width, int height, ImageCapabilities caps, int transparency) throws AWTException {
   VolatileImage vi = new Container().createVolatileImage(width, height, caps);
   if (caps != null && caps.isAccelerated() && !vi.getCapabilities().isAccelerated()) {
     throw new AWTException(
         "Supplied image capabilities could not " + "be met by this graphics configuration.");
   }
   return vi;
 }
 /**
  * Paints the image at the specified location. This method assumes scaling has already been done,
  * and simply paints the background image "as-is."
  *
  * @param g The graphics context.
  * @param x The x-coordinate at which to paint.
  * @param y The y-coordinate at which to paint.
  */
 protected void paintImage(Graphics g, int x, int y) {
   if (bgImage != null) {
     do {
       int rc = bgImage.validate(null); // getGraphicsConfiguration());
       if (rc == VolatileImage.IMAGE_RESTORED) {
         // FIXME:  If the image needs to be restored are its width
         // and height still valid??  If not, we'll need to cache
         // these values...
         renderImage(bgImage.getWidth(), bgImage.getHeight(), getScalingHint());
       }
       g.drawImage(bgImage, x, y, null);
     } while (bgImage.contentsLost());
   }
 }
Ejemplo n.º 8
0
  /** Performs the native GLX flip operation for the given target Component. */
  @Override
  public void flip(
      X11ComponentPeer peer,
      Component target,
      VolatileImage xBackBuffer,
      int x1,
      int y1,
      int x2,
      int y2,
      BufferCapabilities.FlipContents flipAction) {
    if (flipAction == BufferCapabilities.FlipContents.COPIED) {
      SurfaceManager vsm = SurfaceManager.getManager(xBackBuffer);
      SurfaceData sd = vsm.getPrimarySurfaceData();

      if (sd instanceof GLXVSyncOffScreenSurfaceData) {
        GLXVSyncOffScreenSurfaceData vsd = (GLXVSyncOffScreenSurfaceData) sd;
        SurfaceData bbsd = vsd.getFlipSurface();
        Graphics2D bbg = new SunGraphics2D(bbsd, Color.black, Color.white, null);
        try {
          bbg.drawImage(xBackBuffer, 0, 0, null);
        } finally {
          bbg.dispose();
        }
      } else {
        Graphics g = peer.getGraphics();
        try {
          g.drawImage(xBackBuffer, x1, y1, x2, y2, x1, y1, x2, y2, null);
        } finally {
          g.dispose();
        }
        return;
      }
    } else if (flipAction == BufferCapabilities.FlipContents.PRIOR) {
      // not supported by GLX...
      return;
    }

    OGLSurfaceData.swapBuffers(peer.getContentWindow());

    if (flipAction == BufferCapabilities.FlipContents.BACKGROUND) {
      Graphics g = xBackBuffer.getGraphics();
      try {
        g.setColor(target.getBackground());
        g.fillRect(0, 0, xBackBuffer.getWidth(), xBackBuffer.getHeight());
      } finally {
        g.dispose();
      }
    }
  }
Ejemplo n.º 9
0
  private VolatileImage createVolatileImage(int width, int height, int transparency) {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsConfiguration gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
    VolatileImage image = null;

    image = gc.createCompatibleVolatileImage(width, height, transparency);

    int valid = image.validate(gc);

    if (valid == VolatileImage.IMAGE_INCOMPATIBLE) {
      image = this.createVolatileImage(width, height, transparency);
      return image;
    }

    return image;
  }
Ejemplo n.º 10
0
  public void initialize() {

    // openLevelFile images:
    try {
      boxSpriteSheet = ImageIO.read(new File("ItemContainer.png"));
      coinSpriteSheet = ImageIO.read(new File("Coin.png"));
    } catch (Exception e) {
    }

    if (openLevelFile == false) {
      try {
        loadLevel(initLevel);
      } catch (Exception e) {
        System.out.println(e);
      }
    } else {
      loadLevel(FileOpenDialog("Open ..."));
    }

    // create tile layer:
    renderTileLayer();

    // create bg layer:
    backgroundLayer = new VolatileImage[backgroundImage.length];

    // render layer:
    for (int i = 0; i < backgroundImage.length; i++) {
      renderBackgroundLayer(0);
      renderBackgroundLayer(1);
    }

    // create hardware accellerated rendering layer:
    renderImage =
        this.getGraphicsConfiguration()
            .createCompatibleVolatileImage(
                loadedLevel.getWidth() * 16,
                loadedLevel.getHeight() * 16,
                Transparency.TRANSLUCENT);
    Graphics2D g2d = renderImage.createGraphics();
    g2d.setComposite(AlphaComposite.Src);

    // Clear the image.
    g2d.setColor(new Color(0, 0, 0, 0));
    g2d.fillRect(0, 0, renderImage.getWidth(), renderImage.getHeight());
    g2d.setBackground(new Color(0, 0, 0, 0));
  }
Ejemplo n.º 11
0
 Plot() {
   componentDim = new Dimension(PLOT_W, PLOT_H * paths.length);
   backImg =
       GraphicsEnvironment.getLocalGraphicsEnvironment()
           .getDefaultScreenDevice()
           .getDefaultConfiguration()
           .createCompatibleVolatileImage(componentDim.width, componentDim.height);
   backG = backImg.getGraphics();
 }
Ejemplo n.º 12
0
  /** @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#paintComponent(java.awt.Graphics) */
  public void paintComponent(Graphics g) {
    //		long t1 = System.currentTimeMillis();

    VolatileImage image = createVolatileImage();
    Graphics gh = image.createGraphics();
    gh.setColor(getLayoutControl().getBackground());
    gh.fillRect(0, 0, image.getWidth(), image.getHeight());

    getLayoutControl().getLayoutDraw().drawRectangle((Graphics2D) gh);
    gh.drawImage(getLayoutControl().getImage(), 0, 0, null);
    gh.drawImage(getLayoutControl().getImgRuler(), 0, 0, null);
    //		long t2 = System.currentTimeMillis();

    //		BufferedImage img = getLayoutControl().getImage();
    //		BufferedImage imgRuler=getLayoutControl().getImgRuler();
    //		g.drawImage(img, 0, 0, getLayoutControl());
    //		g.drawImage(imgRuler, 0, 0, getLayoutControl());
    gh.setColor(Color.black);
    gh.setXORMode(Color.white);

    // Borramos el anterior
    Rectangle r = new Rectangle();

    // Dibujamos el actual
    if (dragged
        && (getLayoutControl().getFirstPoint() != null)
        && (getLayoutControl().getLastPoint() != null)) {
      r.setFrameFromDiagonal(getLayoutControl().getFirstPoint(), getLayoutControl().getLastPoint());
      gh.drawRect(r.x, r.y, r.width, r.height);
    }
    IFFrame[] frames = getLayoutControl().getLayoutContext().getFFrameSelected();
    for (int i = 0; i < frames.length; i++) {
      gh.setColor(Color.black);
      frames[i].drawHandlers((Graphics2D) gh);
    }
    gh.setPaintMode();
    //		getLayoutControl().drawCursor(gh);
    g.drawImage(image, 0, 0, null);
    //		long t3 = System.currentTimeMillis();
    //		System.out.println("t1 = " + (t2-t1) + " t2=" + (t3-t2));

  }
Ejemplo n.º 13
0
  public void paint_scaled(Graphics g) {

    // Skip if not needed:
    if (usingMenu) {
      return;
    }

    if (scaleMode == SCALE_HW2X) {

      // 2X Hardware accellerated scaling.
      if (g != null && img != null && vimg != null) {

        // Draw BufferedImage into accellerated image:
        vimg.getGraphics().drawImage(img, 0, 0, null);

        // Draw accellerated image scaled:
        g.drawImage(vimg, 0, 0, width * 2, height * 2, null);
      }

    } else if (scaleMode == SCALE_HW3X) {

      // 3X Hardware accellerated scaling.
      if (g != null && img != null && vimg != null) {

        // Draw BufferedImage into accellerated image:
        vimg.getGraphics().drawImage(img, 0, 0, null);

        // Draw accellerated image scaled:
        g.drawImage(vimg, 0, 0, width * 3, height * 3, null);
      }

    } else {

      // 2X Software scaling.
      if (g != null && img != null) {

        // Draw big BufferedImage directly:
        g.drawImage(img, 0, 0, width * 2, height * 2, null);
      }
    }
  }
Ejemplo n.º 14
0
  public void render(Graphics2D g) {
    do {
      do {
        g = (Graphics2D) strategy.getDrawGraphics();
        g.setRenderingHints(renderingHints);
        vi = createVolatileImage(getWidth(), getHeight());
        bi =
            GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getDefaultScreenDevice()
                .getDefaultConfiguration()
                .createCompatibleImage(getWidth(), getHeight());
        vi.getGraphics().fillRect(0, 0, vi.getWidth(), vi.getHeight());

        for (Renderable renderable : Window.objects) {
          if (renderable.getShouldDestroy()) Window.objects.remove(renderable);
          if (renderable.isVisible()) renderable.render((Graphics2D) vi.getGraphics());
        }

        bi.getGraphics().drawImage(vi.getSnapshot(), 0, 0, getWidth(), getHeight(), null);
        bi = vi.getSnapshot();
        // gaussian.filter(bi, bi);
        // glow.filter(bi, bi);
        // motionBlur.filter(bi, bi);
        g.drawImage(bi, 0, 0, getWidth(), getHeight(), null);
        g.dispose();
        Toolkit.getDefaultToolkit().sync();
      } while (strategy.contentsRestored());
      strategy.show();
    } while (strategy.contentsLost());
  }
Ejemplo n.º 15
0
    public void rebuild() {
      backG.setColor(Color.BLACK);
      backG.fillRect(0, 0, backImg.getWidth(), backImg.getHeight());

      for (int z = 0; z < paths.length; z++) {
        Path path = paths[z];

        double[] d = path.getCoords(animPos);
        if (path instanceof MemoryPath) {
          MemoryPath mp = (MemoryPath) path;
          for (int i = 1 - mp.getMemorySize(); i <= 0; i++) {
            int col = 0xff0000 + (0x110000 * i);
            d = mp.getPreviousCoords(i);
            backG.setColor(new Color(col));
            backG.fillRect((int) (d[0] - 2), (int) (d[1] - 2), 5, 5);
          }
        } else {
          backG.setColor(Color.RED);
          backG.fillRect((int) (d[0] - 2), (int) (d[1] - 2), 5, 5);
        }
      }

      this.repaint();
    }
Ejemplo n.º 16
0
  public VolatileImage renderTileLayer() {
    // create hardware accellerated tile layer (Volatile Image)
    tileLayer =
        this.getGraphicsConfiguration()
            .createCompatibleVolatileImage(
                loadedLevel.getWidth() * 16,
                loadedLevel.getHeight() * 16,
                Transparency.TRANSLUCENT);
    Graphics2D g2d = tileLayer.createGraphics();
    g2d.setComposite(AlphaComposite.Src);

    // Clear the image.
    g2d.setColor(new Color(0, 0, 0, 0));
    g2d.fillRect(0, 0, tileLayer.getWidth(), tileLayer.getHeight());
    g2d.setBackground(new Color(0, 0, 0, 0));

    g2d.setColor(new Color(1f, 1f, 1f, 1f));

    for (int i = 0; i < numberOfTiles; i++) {
      tile[i].draw(g2d, this);
    }

    return tileLayer;
  }
Ejemplo n.º 17
0
  public void render(double alpha) {
    BufferStrategy bs = getBufferStrategy();
    if (bs == null) {
      createBufferStrategy(2);
      bs = getBufferStrategy();
    }

    if (image == null) image = createVolatileImage(WIDTH, HEIGHT);

    if (bs != null) {
      Graphics2D g = image.createGraphics();
      Graphics2D clone = (Graphics2D) g.create();
      renderGame(g, clone, alpha);
      g.dispose();

      Graphics gg = bs.getDrawGraphics();
      gg.drawImage(image, 0, 0, WIDTH * 2, HEIGHT * 2, 0, 0, WIDTH, HEIGHT, null);
      gg.dispose();
      bs.show();
    }
  }
 private static void test(BufferedImage bi, int type) throws IOException {
   GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
   GraphicsConfiguration gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
   VolatileImage vi = gc.createCompatibleVolatileImage(511, 255, type);
   BufferedImage gold = gc.createCompatibleImage(511, 255, type);
   // draw to compatible Image
   Graphics2D big = gold.createGraphics();
   // force scaled blit
   big.drawImage(bi, 7, 11, 127, 111, 7, 11, 127 * 2, 111, null);
   big.dispose();
   // draw to volatile image
   BufferedImage snapshot;
   while (true) {
     vi.validate(gc);
     if (vi.validate(gc) != VolatileImage.IMAGE_OK) {
       try {
         Thread.sleep(100);
       } catch (final InterruptedException ignored) {
       }
       continue;
     }
     Graphics2D vig = vi.createGraphics();
     // force scaled blit
     vig.drawImage(bi, 7, 11, 127, 111, 7, 11, 127 * 2, 111, null);
     vig.dispose();
     snapshot = vi.getSnapshot();
     if (vi.contentsLost()) {
       try {
         Thread.sleep(100);
       } catch (final InterruptedException ignored) {
       }
       continue;
     }
     break;
   }
   // validate images
   for (int x = 7; x < 127; ++x) {
     for (int y = 11; y < 111; ++y) {
       if (gold.getRGB(x, y) != snapshot.getRGB(x, y)) {
         ImageIO.write(gold, "png", new File("gold.png"));
         ImageIO.write(snapshot, "png", new File("bi.png"));
         throw new RuntimeException("Test failed.");
       }
     }
   }
 }
Ejemplo n.º 19
0
  public VolatileImage render() {

    Graphics2D g2d = renderImage.createGraphics();

    try {

      // Draw background layer:
      for (int i = 0; i < backgroundLayer.length; i++) {
        g2d.drawImage(
            backgroundLayer[i],
            -(int) (camera.position.x * Math.pow(0.5, backgroundLayer.length - i)),
            -(int) (camera.position.y * Math.pow(0.5, backgroundLayer.length - i))
                + backgroundLayer[i].getHeight(this)
                - backgroundLayer[i].getHeight(this) / (i + 1),
            this);
      }

    } catch (Exception e) {
    }

    // Draw Tiles: (new)
    try {
      g2d.drawImage(
          tileLayer,
          camera.center.x - camera.position.x,
          camera.center.y - camera.position.y,
          this);
    } catch (Exception e) {
    }

    // Draw all kinds of Sprites:

    try {
      int a = 0;

      while (sprite[a] != null) {
        // Play Animation for sprite:
        if (sprite[a].animation.plays == true) {
          sprite[a].getAnimation().nextFrame();
        }

        // -- Draw sprite:
        g2d.drawImage(
            sprite[a].img,
            /*X1*/ sprite[a].posx
                + ((sprite[a].flipH - 1) / (-2)) * sprite[a].size.width /*camera*/
                - camera.position.x
                + camera.center.x, /*Y1*/
            sprite[a].posy
                + ((sprite[a].flipV - 1) / (-2)) * sprite[a].size.height /*camera*/
                - camera.position.y
                + camera.center.y,
            /*X2*/ sprite[a].posx
                + sprite[a].size.width * sprite[a].flipH
                + ((sprite[a].flipH - 1) / (-2)) * sprite[a].size.width /*camera*/
                - camera.position.x
                + camera.center.x, /*Y2*/
            sprite[a].posy
                + sprite[a].size.height * sprite[a].flipV
                + ((sprite[a].flipV - 1) / (-2)) * sprite[a].size.height /*camera*/
                - camera.position.y
                + camera.center.y, // destination
            sprite[a].getAnimation().col * sprite[a].size.width,
            sprite[a].getAnimation().row * sprite[a].size.height, // source
            (sprite[a].getAnimation().col + 1) * sprite[a].size.width,
            (sprite[a].getAnimation().row + 1) * sprite[a].size.height,
            this);

        a++;
      }
    } catch (Exception e) {
      g2d.drawString("Error drawing a Sprite", 20, 20);
    }

    // Draw "GUI":
    g2d.drawImage(coinSpriteSheet, 16, 16, 32, 32, 0, 0, 16, 16, this);
    g2d.setColor(Color.BLACK);
    g2d.drawString("x " + collectedCoins, 32, 30);
    g2d.setColor(Color.WHITE);
    g2d.drawString("x " + collectedCoins, 32, 29);

    if (showSpritePos == true) {
      for (int i = 0; i < numberOfSprites; i++) {
        g2d.setColor(Color.red);
        g2d.drawRect(
            /*X1*/ sprite[i].posx /*camera*/ - camera.position.x + camera.center.x, /*Y1*/
            sprite[i].posy /*camera*/ - camera.position.y + camera.center.y,
            1,
            1);
        g2d.setColor(Color.black);
      }
    }

    if (showSpriteNum == true) {
      for (int i = 0; i < numberOfSprites; i++) {
        g2d.setColor(Color.black);
        g2d.drawString(
            "" + i, /*X1*/
            sprite[i].posx /*camera*/ - camera.position.x + camera.center.x, /*Y1*/
            sprite[i].posy /*camera*/ - camera.position.y + camera.center.y);
        g2d.setColor(Color.white);
        g2d.drawString(
            "" + i, /*X1*/
            sprite[i].posx /*camera*/ - camera.position.x + camera.center.x, /*Y1*/
            sprite[i].posy /*camera*/ - camera.position.y + camera.center.y - 1);
      }
    }

    if (showSpritePos == true) {
      for (int i = 0; i < numberOfTiles; i++) {
        g2d.setColor(Color.red);
        g2d.drawRect(
            /*X1*/ tile[i].posx
                + ((tile[i].flipH - 1) / (-2)) * tile[i].size.width /*camera*/
                - camera.position.x
                + camera.center.x, /*Y1*/
            tile[i].posy
                + ((tile[i].flipV - 1) / (-2)) * tile[i].size.height /*camera*/
                - camera.position.y
                + camera.center.y,
            1,
            1);
        g2d.setColor(Color.black);
      }
    }

    if (showCamera == true) {
      g2d.setColor(Color.red);
      g2d.drawLine(
          0,
          camera.prefHeight - camera.position.y + camera.center.y,
          loadedLevel.getWidth() * 16,
          camera.prefHeight - camera.position.y + camera.center.y);
      g2d.setColor(new Color(1, 0, 0, 0.33f));
      g2d.fillRect(
          0,
          camera.prefHeight - camera.position.y + camera.tolerance,
          loadedLevel.getWidth() * 16,
          camera.tolerance);
      g2d.setColor(new Color(0, 1, 0, 0.33f));
      g2d.fillRect(
          camera.center.x - camera.position.x + camera.center.x,
          camera.center.y - camera.position.y + camera.center.y,
          camera.bounds.width - 2 * camera.center.x,
          camera.bounds.height);
      g2d.setColor(Color.green);
      g2d.drawLine(
          camera.center.x - camera.position.x + camera.center.x,
          0,
          camera.center.x - camera.position.x + camera.center.x,
          999);
      g2d.drawLine(
          camera.bounds.width - camera.center.x - camera.position.x + camera.center.x,
          0,
          camera.bounds.width - camera.center.x - camera.position.x + camera.center.x,
          999);
    }

    return renderImage;
  }
Ejemplo n.º 20
0
  public EvaluationInfo run1(int currentTrial, int totalNumberOfTrials) {
    running = true;
    adjustFPS();
    EvaluationInfo evaluationInfo = new EvaluationInfo();

    VolatileImage image = null;
    Graphics g = null;
    Graphics og = null;

    image = createVolatileImage(320, 240);
    g = getGraphics();
    og = image.getGraphics();

    if (!GlobalOptions.VisualizationOn) {
      String msgClick = "Vizualization is not available";
      drawString(og, msgClick, 160 - msgClick.length() * 4, 110, 1);
      drawString(og, msgClick, 160 - msgClick.length() * 4, 110, 7);
    }

    addFocusListener(this);

    // Remember the starting time
    long tm = System.currentTimeMillis();
    long tick = tm;
    int marioStatus = Mario.STATUS_RUNNING;

    // mario = ((LevelScene) levelScene).mario;
    int totalActionsPerfomed = 0;
    // TODO: Manage better place for this:
    levelScene.mario.resetCoins();

    while (
    /*Thread.currentThread() == animator*/ running) {
      // Display the next frame of animation.
      //                repaint();

      MDPTraining.train(this);

      levelScene.tick();
      if (gameViewer != null && gameViewer.getContinuousUpdatesState()) gameViewer.tick();

      float alpha = 0;

      //            og.setColor(Color.RED);
      if (GlobalOptions.VisualizationOn) {
        og.fillRect(0, 0, 320, 240);
        levelScene.render(og, alpha);
      }

      if (agent instanceof ServerAgent && !((ServerAgent) agent).isAvailable()) {
        System.err.println("Agent became unavailable. Simulation Stopped");
        running = false;
        break;
      }

      boolean[] action = agent.getAction(this /*DummyEnvironment*/);
      if (action != null) {
        for (int i = 0; i < Environment.numberOfButtons; ++i)
          if (action[i]) {
            ++totalActionsPerfomed;
            break;
          }
      } else {
        System.err.println("Null Action received. Skipping simulation...");
        stop();
      }

      // Apply action;
      //            levelScene.keys = action;
      ((LevelScene) levelScene).mario.keys = action;
      ((LevelScene) levelScene).mario.cheatKeys = cheatAgent.getAction(null);

      if (GlobalOptions.VisualizationOn) {

        String msg = "Agent: " + agent.getName();
        LevelScene.drawStringDropShadow(og, msg, 0, 7, 5);

        msg = "Selected Actions: ";
        LevelScene.drawStringDropShadow(og, msg, 0, 8, 6);

        msg = "";
        if (action != null) {
          for (int i = 0; i < Environment.numberOfButtons; ++i)
            msg += (action[i]) ? levelScene.keysStr[i] : "      ";
        } else msg = "NULL";
        drawString(og, msg, 6, 78, 1);

        if (!this.hasFocus() && tick / 4 % 2 == 0) {
          String msgClick = "CLICK TO PLAY";
          //                    og.setColor(Color.YELLOW);
          //                    og.drawString(msgClick, 320 + 1, 20 + 1);
          drawString(og, msgClick, 160 - msgClick.length() * 4, 110, 1);
          drawString(og, msgClick, 160 - msgClick.length() * 4, 110, 7);
        }
        og.setColor(Color.DARK_GRAY);
        LevelScene.drawStringDropShadow(og, "FPS: ", 33, 2, 7);
        LevelScene.drawStringDropShadow(
            og, ((GlobalOptions.FPS > 99) ? "\\infty" : GlobalOptions.FPS.toString()), 33, 3, 7);

        msg =
            totalNumberOfTrials == -2
                ? ""
                : currentTrial
                    + "("
                    + ((totalNumberOfTrials == -1) ? "\\infty" : totalNumberOfTrials)
                    + ")";

        LevelScene.drawStringDropShadow(og, "Trial:", 33, 4, 7);
        LevelScene.drawStringDropShadow(og, msg, 33, 5, 7);

        if (width != 320 || height != 240) {
          g.drawImage(image, 0, 0, 640 * 2, 480 * 2, null);
        } else {
          g.drawImage(image, 0, 0, null);
        }
      } else {
        // Win or Die without renderer!! independently.
        marioStatus = ((LevelScene) levelScene).mario.getStatus();
        if (marioStatus != Mario.STATUS_RUNNING) stop();
      }
      // Delay depending on how far we are behind.
      if (delay > 0)
        try {
          tm += delay;
          Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
        } catch (InterruptedException e) {
          break;
        }
      // Advance the frame
      frame++;
    }
    // =========
    evaluationInfo.agentType = agent.getClass().getSimpleName();
    evaluationInfo.agentName = agent.getName();
    evaluationInfo.marioStatus = levelScene.mario.getStatus();
    evaluationInfo.livesLeft = levelScene.mario.lives;
    evaluationInfo.lengthOfLevelPassedPhys = levelScene.mario.x;
    evaluationInfo.lengthOfLevelPassedCells = levelScene.mario.mapX;
    evaluationInfo.totalLengthOfLevelCells = levelScene.level.getWidthCells();
    evaluationInfo.totalLengthOfLevelPhys = levelScene.level.getWidthPhys();
    evaluationInfo.timeSpentOnLevel = levelScene.getStartTime();
    evaluationInfo.timeLeft = levelScene.getTimeLeft();
    evaluationInfo.totalTimeGiven = levelScene.getTotalTime();
    evaluationInfo.numberOfGainedCoins = levelScene.mario.coins;
    //        evaluationInfo.totalNumberOfCoins   = -1 ; // TODO: total Number of coins.
    evaluationInfo.totalActionsPerfomed =
        totalActionsPerfomed; // Counted during the play/simulation process
    evaluationInfo.totalFramesPerfomed = frame;
    evaluationInfo.marioMode = levelScene.mario.getMode();
    evaluationInfo.killsTotal = levelScene.mario.world.killedCreaturesTotal;
    //        evaluationInfo.Memo = "Number of attempt: " + Mario.numberOfAttempts;
    if (agent instanceof ServerAgent
        && levelScene.mario.keys
            != null /*this will happen if client quits unexpectedly in case of Server mode*/)
      ((ServerAgent) agent).integrateEvaluationInfo(evaluationInfo);
    return evaluationInfo;
  }