Beispiel #1
0
 /**
  * Calculates the percentage for the given value in the range denoted by the given lower and upper
  * bounds.
  *
  * @param aValue the value;
  * @param aLowerBound the lower bound of the range;
  * @param aUpperBound the upper bound of the range.
  * @return the percentage (= value * 100.0 / range).
  */
 public static int getPercentage(final int aValue, final int aLowerBound, final int aUpperBound) {
   int range;
   int value = aValue;
   if (aLowerBound > aUpperBound) {
     range = aLowerBound - aUpperBound;
     value = Math.max(0, value - aUpperBound);
   } else {
     range = aUpperBound - aLowerBound;
     value = Math.max(0, value - aLowerBound);
   }
   return getPercentage(value, range);
 }
Beispiel #2
0
 private int mipMapHeight(int map) {
   int height = getHeight();
   for (int i = 0; i < map; i++) {
     height >>= 1;
   }
   return Math.max(height, 1);
 }
Beispiel #3
0
 private int mipMapWidth(int map) {
   int width = getWidth();
   for (int i = 0; i < map; i++) {
     width >>= 1;
   }
   return Math.max(width, 1);
 }
Beispiel #4
0
  /**
   * Calculates the percentage for the given value in the given range.
   *
   * @param aValue the value;
   * @param aRange the range (zero-based).
   * @return the percentage (= value * 100.0 / aRange).
   */
  public static int getPercentage(final long aValue, final long aRange) {
    double value = 0.0;
    if (aRange != 0) {
      value = aValue * 100.0 / aRange;
    }

    return (int) Math.max(0.0, Math.min(100.0, value));
  }
 private int processPacket(final boolean readPage) {
   while (true) {
     if (this.m_decodeReady) {
       final int result = this.m_oggStreamState.packetout(this.m_oggPacket);
       if (result > 0) {
         long granulepos = this.m_oggPacket.granulepos;
         if (this.m_block.synthesis(this.m_oggPacket) == 0) {
           this.m_dspState.synthesis_blockin(this.m_block);
           if (granulepos != -1L) {
             final int link = this.m_vorbisStream.isSeekable() ? this.m_currentLink : 0;
             final int samples = this.m_dspState.synthesis_pcmout(null, null);
             granulepos = Math.max(0L, granulepos - samples);
             for (int i = 0; i < link; ++i) {
               granulepos += this.m_pcmLengths[i];
             }
             this.m_pcmOffset = granulepos;
           }
           return 1;
         }
       }
     }
     if (!readPage) {
       return 0;
     }
     if (this.getNextPage(this.m_oggPage, -1L) < 0) {
       return 0;
     }
     if (this.m_decodeReady && this.m_currentSerialno != this.m_oggPage.serialno()) {
       this.decodeClear();
     }
     if (!this.m_decodeReady) {
       if (this.m_vorbisStream.isSeekable()) {
         this.m_currentSerialno = this.m_oggPage.serialno();
         int j;
         for (j = 0; j < this.m_links && this.m_serialnos[j] != this.m_currentSerialno; ++j) {}
         if (j == this.m_links) {
           return -1;
         }
         this.m_currentLink = j;
         this.m_oggStreamState.init(this.m_currentSerialno);
         this.m_oggStreamState.reset();
       } else {
         final int[] serialnos = {0};
         final int ret =
             this.fetchHeaders(this.m_info[0], this.m_comments[0], serialnos, this.m_oggPage);
         this.m_currentSerialno = serialnos[0];
         if (ret != 0) {
           return ret;
         }
         ++this.m_currentLink;
       }
       this.makeDecodeReady();
     }
     this.m_oggStreamState.pagein(this.m_oggPage);
   }
 }
Beispiel #6
0
  int[] init(int... dimensions) {
    int size = dimensions.length > 0 ? dimensions[0] : 0;
    if (___subrecord___ == null) {
      final String[] indexPrefixes = {
        "", "s", "_", "Index", "Length", "Ref", "Header", "Info", "Table"
      };
      for (String indexPrefix : indexPrefixes) {
        try {
          ___subrecord___ =
              (Class<? extends Enum>)
                  Class.forName(getClass().getPackage().getName() + '.' + name() + indexPrefix);
          try {
            size = ___subrecord___.getField("___recordlen___").getInt(null);
          } catch (Exception e) {
          }
          break;
        } catch (ClassNotFoundException e) {
        }
      }
    }

    for (String vPrefixe1 :
        new String[] {
          "_", "", "$", "Value",
        }) {
      if (___valueclass___ != null) break;
      String suffix = vPrefixe1;
      for (String name1 :
          new String[] {
            name().toLowerCase(), name(),
          }) {
        if (___valueclass___ != null) break;
        final String trailName = name1;
        if (trailName.endsWith(suffix)) {
          for (String aPackage1 :
              new String[] {
                "", getClass().getPackage().getName() + ".", "java.lang.", "java.util.",
              })
            if (___valueclass___ == null) break;
            else
              try {
                ___valueclass___ = Class.forName(aPackage1 + name().replace(suffix, ""));
              } catch (ClassNotFoundException e) {
              }
        }
      }
    }

    int seek = dimensions.length > 1 ? dimensions[1] : ___recordlen___;
    ___recordlen___ = Math.max(___recordlen___, seek + size);
    return new int[] {size, seek};
  }
  /**
   * Read block from file.
   *
   * @param file - File to read.
   * @param off - Marker position in file to start read from if {@code -1} read last blockSz bytes.
   * @param blockSz - Maximum number of chars to read.
   * @param lastModified - File last modification time.
   * @return Read file block.
   * @throws IOException In case of error.
   */
  public static VisorFileBlock readBlock(File file, long off, int blockSz, long lastModified)
      throws IOException {
    RandomAccessFile raf = null;

    try {
      long fSz = file.length();
      long fLastModified = file.lastModified();

      long pos = off >= 0 ? off : Math.max(fSz - blockSz, 0);

      // Try read more that file length.
      if (fLastModified == lastModified && fSz != 0 && pos >= fSz)
        throw new IOException(
            "Trying to read file block with wrong offset: " + pos + " while file size: " + fSz);

      if (fSz == 0)
        return new VisorFileBlock(file.getPath(), pos, fLastModified, 0, false, EMPTY_FILE_BUF);
      else {
        int toRead = Math.min(blockSz, (int) (fSz - pos));

        byte[] buf = new byte[toRead];

        raf = new RandomAccessFile(file, "r");

        raf.seek(pos);

        int cntRead = raf.read(buf, 0, toRead);

        if (cntRead != toRead)
          throw new IOException(
              "Count of requested and actually read bytes does not match [cntRead="
                  + cntRead
                  + ", toRead="
                  + toRead
                  + ']');

        boolean zipped = buf.length > 512;

        return new VisorFileBlock(
            file.getPath(), pos, fSz, fLastModified, zipped, zipped ? zipBytes(buf) : buf);
      }
    } finally {
      U.close(raf, null);
    }
  }
 private void updateTextureAndDistortionMesh() {
   final ScreenParams screen = this.mHmd.getScreenParams();
   final CardboardDeviceParams cdp = this.mHmd.getCardboardDeviceParams();
   if (this.mProgramHolder == null) {
     this.mProgramHolder = this.createProgramHolder();
   }
   if (this.mProgramHolderAberration == null) {
     this.mProgramHolderAberration = (ProgramHolderAberration) this.createProgramHolder(true);
   }
   final float textureWidthTanAngle = this.mLeftEyeViewport.width + this.mRightEyeViewport.width;
   final float textureHeightTanAngle =
       Math.max(this.mLeftEyeViewport.height, this.mRightEyeViewport.height);
   final int[] maxTextureSize = {0};
   GLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_SIZE, maxTextureSize, 0);
   final int textureWidthPx =
       Math.min(Math.round(textureWidthTanAngle * this.mXPxPerTanAngle), maxTextureSize[0]);
   final int textureHeightPx =
       Math.min(Math.round(textureHeightTanAngle * this.mYPxPerTanAngle), maxTextureSize[0]);
   float xEyeOffsetTanAngleScreen =
       (screen.getWidthMeters() / 2.0f - cdp.getInterLensDistance() / 2.0f)
           / this.mMetersPerTanAngle;
   final float yEyeOffsetTanAngleScreen =
       (cdp.getVerticalDistanceToLensCenter() - screen.getBorderSizeMeters())
           / this.mMetersPerTanAngle;
   this.mLeftEyeDistortionMesh =
       this.createDistortionMesh(
           this.mLeftEyeViewport,
           textureWidthTanAngle,
           textureHeightTanAngle,
           xEyeOffsetTanAngleScreen,
           yEyeOffsetTanAngleScreen);
   xEyeOffsetTanAngleScreen =
       screen.getWidthMeters() / this.mMetersPerTanAngle - xEyeOffsetTanAngleScreen;
   this.mRightEyeDistortionMesh =
       this.createDistortionMesh(
           this.mRightEyeViewport,
           textureWidthTanAngle,
           textureHeightTanAngle,
           xEyeOffsetTanAngleScreen,
           yEyeOffsetTanAngleScreen);
   this.setupRenderTextureAndRenderbuffer(textureWidthPx, textureHeightPx);
   this.mFovsChanged = false;
 }
  public void build_bricks() {

    ImagePlus imp;
    ImagePlus orgimp;
    ImageStack stack;
    FileInfo finfo;

    if (lvImgTitle.isEmpty()) return;
    orgimp = WindowManager.getImage(lvImgTitle.get(0));
    imp = orgimp;

    finfo = imp.getFileInfo();
    if (finfo == null) return;

    int[] dims = imp.getDimensions();
    int imageW = dims[0];
    int imageH = dims[1];
    int nCh = dims[2];
    int imageD = dims[3];
    int nFrame = dims[4];
    int bdepth = imp.getBitDepth();
    double xspc = finfo.pixelWidth;
    double yspc = finfo.pixelHeight;
    double zspc = finfo.pixelDepth;
    double z_aspect = Math.max(xspc, yspc) / zspc;

    int orgW = imageW;
    int orgH = imageH;
    int orgD = imageD;
    double orgxspc = xspc;
    double orgyspc = yspc;
    double orgzspc = zspc;

    lv = lvImgTitle.size();
    if (filetype == "JPEG") {
      for (int l = 0; l < lv; l++) {
        if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) {
          IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE");
          return;
        }
      }
    }

    // calculate levels
    /*		int baseXY = 256;
    		int baseZ = 256;

    		if (z_aspect < 0.5) baseZ = 128;
    		if (z_aspect > 2.0) baseXY = 128;
    		if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect);
    		if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect);

    		IJ.log("Z_aspect: " + z_aspect);
    		IJ.log("BaseXY: " + baseXY);
    		IJ.log("BaseZ: " + baseZ);
    */

    int baseXY = 256;
    int baseZ = 128;
    int dbXY = Math.max(orgW, orgH) / baseXY;
    if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2;
    int dbZ = orgD / baseZ;
    if (orgD % baseZ > 0) dbZ *= 2;
    lv = Math.max(log2(dbXY), log2(dbZ)) + 1;

    int ww = orgW;
    int hh = orgH;
    int dd = orgD;
    for (int l = 0; l < lv; l++) {
      int bwnum = ww / baseXY;
      if (ww % baseXY > 0) bwnum++;
      int bhnum = hh / baseXY;
      if (hh % baseXY > 0) bhnum++;
      int bdnum = dd / baseZ;
      if (dd % baseZ > 0) bdnum++;

      if (bwnum % 2 == 0) bwnum++;
      if (bhnum % 2 == 0) bhnum++;
      if (bdnum % 2 == 0) bdnum++;

      int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0);
      int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0);
      int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0);

      bwlist.add(bw);
      bhlist.add(bh);
      bdlist.add(bd);

      IJ.log("LEVEL: " + l);
      IJ.log("  width: " + ww);
      IJ.log("  hight: " + hh);
      IJ.log("  depth: " + dd);
      IJ.log("  bw: " + bw);
      IJ.log("  bh: " + bh);
      IJ.log("  bd: " + bd);

      int xyl2 = Math.max(ww, hh) / baseXY;
      if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2;
      if (lv - 1 - log2(xyl2) <= l) {
        ww /= 2;
        hh /= 2;
      }
      IJ.log("  xyl2: " + (lv - 1 - log2(xyl2)));

      int zl2 = dd / baseZ;
      if (dd % baseZ > 0) zl2 *= 2;
      if (lv - 1 - log2(zl2) <= l) dd /= 2;
      IJ.log("  zl2: " + (lv - 1 - log2(zl2)));

      if (l < lv - 1) {
        lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1));
        IJ.selectWindow(lvImgTitle.get(0));
        IJ.run(
            "Scale...",
            "x=- y=- z=- width="
                + ww
                + " height="
                + hh
                + " depth="
                + dd
                + " interpolation=Bicubic average process create title="
                + lvImgTitle.get(l + 1));
      }
    }

    for (int l = 0; l < lv; l++) {
      IJ.log(lvImgTitle.get(l));
    }

    Document doc = newXMLDocument();
    Element root = doc.createElement("BRK");
    root.setAttribute("version", "1.0");
    root.setAttribute("nLevel", String.valueOf(lv));
    root.setAttribute("nChannel", String.valueOf(nCh));
    root.setAttribute("nFrame", String.valueOf(nFrame));
    doc.appendChild(root);

    for (int l = 0; l < lv; l++) {
      IJ.showProgress(0.0);

      int[] dims2 = imp.getDimensions();
      IJ.log(
          "W: "
              + String.valueOf(dims2[0])
              + " H: "
              + String.valueOf(dims2[1])
              + " C: "
              + String.valueOf(dims2[2])
              + " D: "
              + String.valueOf(dims2[3])
              + " T: "
              + String.valueOf(dims2[4])
              + " b: "
              + String.valueOf(bdepth));

      bw = bwlist.get(l).intValue();
      bh = bhlist.get(l).intValue();
      bd = bdlist.get(l).intValue();

      boolean force_pow2 = false;
      /*			if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true;

      			if(force_pow2){
      				//force pow2
      				if(Pow2(bw) > bw) bw = Pow2(bw)/2;
      				if(Pow2(bh) > bh) bh = Pow2(bh)/2;
      				if(Pow2(bd) > bd) bd = Pow2(bd)/2;
      			}

      			if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2;
      			if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2;
      			if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2;

      */
      if (bw > imageW) bw = imageW;
      if (bh > imageH) bh = imageH;
      if (bd > imageD) bd = imageD;

      if (bw <= 1 || bh <= 1 || bd <= 1) break;

      if (filetype == "JPEG" && (bw < 8 || bh < 8)) break;

      Element lvnode = doc.createElement("Level");
      lvnode.setAttribute("lv", String.valueOf(l));
      lvnode.setAttribute("imageW", String.valueOf(imageW));
      lvnode.setAttribute("imageH", String.valueOf(imageH));
      lvnode.setAttribute("imageD", String.valueOf(imageD));
      lvnode.setAttribute("xspc", String.valueOf(xspc));
      lvnode.setAttribute("yspc", String.valueOf(yspc));
      lvnode.setAttribute("zspc", String.valueOf(zspc));
      lvnode.setAttribute("bitDepth", String.valueOf(bdepth));
      root.appendChild(lvnode);

      Element brksnode = doc.createElement("Bricks");
      brksnode.setAttribute("brick_baseW", String.valueOf(bw));
      brksnode.setAttribute("brick_baseH", String.valueOf(bh));
      brksnode.setAttribute("brick_baseD", String.valueOf(bd));
      lvnode.appendChild(brksnode);

      ArrayList<Brick> bricks = new ArrayList<Brick>();
      int mw, mh, md, mw2, mh2, md2;
      double tx0, ty0, tz0, tx1, ty1, tz1;
      double bx0, by0, bz0, bx1, by1, bz1;
      for (int k = 0; k < imageD; k += bd) {
        if (k > 0) k--;
        for (int j = 0; j < imageH; j += bh) {
          if (j > 0) j--;
          for (int i = 0; i < imageW; i += bw) {
            if (i > 0) i--;
            mw = Math.min(bw, imageW - i);
            mh = Math.min(bh, imageH - j);
            md = Math.min(bd, imageD - k);

            if (force_pow2) {
              mw2 = Pow2(mw);
              mh2 = Pow2(mh);
              md2 = Pow2(md);
            } else {
              mw2 = mw;
              mh2 = mh;
              md2 = md;
            }

            if (filetype == "JPEG") {
              if (mw2 < 8) mw2 = 8;
              if (mh2 < 8) mh2 = 8;
            }

            tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2);
            ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2);
            tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2);

            tx1 = 1.0d - 0.5d / mw2;
            if (mw < bw) tx1 = 1.0d;
            if (imageW - i == bw) tx1 = 1.0d;

            ty1 = 1.0d - 0.5d / mh2;
            if (mh < bh) ty1 = 1.0d;
            if (imageH - j == bh) ty1 = 1.0d;

            tz1 = 1.0d - 0.5d / md2;
            if (md < bd) tz1 = 1.0d;
            if (imageD - k == bd) tz1 = 1.0d;

            bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW;
            by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH;
            bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD;

            bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d);
            if (imageW - i == bw) bx1 = 1.0d;

            by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d);
            if (imageH - j == bh) by1 = 1.0d;

            bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d);
            if (imageD - k == bd) bz1 = 1.0d;

            int x, y, z;
            x = i - (mw2 - mw);
            y = j - (mh2 - mh);
            z = k - (md2 - md);
            bricks.add(
                new Brick(
                    x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1,
                    by1, bz1));
          }
        }
      }

      Element fsnode = doc.createElement("Files");
      lvnode.appendChild(fsnode);

      stack = imp.getStack();

      int totalbricknum = nFrame * nCh * bricks.size();
      int curbricknum = 0;
      for (int f = 0; f < nFrame; f++) {
        for (int ch = 0; ch < nCh; ch++) {
          int sizelimit = bdsizelimit * 1024 * 1024;
          int bytecount = 0;
          int filecount = 0;
          int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8);
          byte[] packed_data = new byte[pd_bufsize];
          String base_dataname =
              basename
                  + "_Lv"
                  + String.valueOf(l)
                  + "_Ch"
                  + String.valueOf(ch)
                  + "_Fr"
                  + String.valueOf(f);
          String current_dataname = base_dataname + "_data" + filecount;

          Brick b_first = bricks.get(0);
          if (b_first.z_ != 0) IJ.log("warning");
          int st_z = b_first.z_;
          int ed_z = b_first.z_ + b_first.d_;
          LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>();
          for (int s = st_z; s < ed_z; s++)
            iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));

          //					ImagePlus test;
          //					ImageStack tsst;
          //					test = NewImage.createByteImage("test", imageW, imageH, imageD,
          // NewImage.FILL_BLACK);
          //					tsst = test.getStack();
          for (int i = 0; i < bricks.size(); i++) {
            Brick b = bricks.get(i);

            if (ed_z > b.z_ || st_z < b.z_ + b.d_) {
              if (b.z_ > st_z) {
                for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst();
                st_z = b.z_;
              } else if (b.z_ < st_z) {
                IJ.log("warning");
                for (int s = st_z - 1; s > b.z_; s--)
                  iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                st_z = b.z_;
              }

              if (b.z_ + b.d_ > ed_z) {
                for (int s = ed_z; s < b.z_ + b.d_; s++)
                  iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                ed_z = b.z_ + b.d_;
              } else if (b.z_ + b.d_ < ed_z) {
                IJ.log("warning");
                for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast();
                ed_z = b.z_ + b.d_;
              }
            } else {
              IJ.log("warning");
              iplist.clear();
              st_z = b.z_;
              ed_z = b.z_ + b.d_;
              for (int s = st_z; s < ed_z; s++)
                iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
            }

            if (iplist.size() != b.d_) {
              IJ.log("Stack Error");
              return;
            }

            //						int zz = st_z;

            int bsize = 0;
            byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
            Iterator<ImageProcessor> ipite = iplist.iterator();
            while (ipite.hasNext()) {

              //							ImageProcessor tsip = tsst.getProcessor(zz+1);

              ImageProcessor ip = ipite.next();
              ip.setRoi(b.x_, b.y_, b.w_, b.h_);
              if (bdepth == 8) {
                byte[] data = (byte[]) ip.crop().getPixels();
                System.arraycopy(data, 0, bdata, bsize, data.length);
                bsize += data.length;
              } else if (bdepth == 16) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                short[] data = (short[]) ip.crop().getPixels();
                for (short e : data) buffer.putShort(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              } else if (bdepth == 32) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                float[] data = (float[]) ip.crop().getPixels();
                for (float e : data) buffer.putFloat(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              }
            }

            String filename =
                basename
                    + "_Lv"
                    + String.valueOf(l)
                    + "_Ch"
                    + String.valueOf(ch)
                    + "_Fr"
                    + String.valueOf(f)
                    + "_ID"
                    + String.valueOf(i);

            int offset = bytecount;
            int datasize = bdata.length;

            if (filetype == "RAW") {
              int dummy = -1;
              // do nothing
            }
            if (filetype == "JPEG" && bdepth == 8) {
              try {
                DataBufferByte db = new DataBufferByte(bdata, datasize);
                Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null);
                BufferedImage img =
                    new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY);
                img.setData(raster);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
                String format = "jpg";
                Iterator<javax.imageio.ImageWriter> iter =
                    ImageIO.getImageWritersByFormatName("jpeg");
                javax.imageio.ImageWriter writer = iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality((float) jpeg_quality * 0.01f);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(img, null, null), iwp);
                // ImageIO.write(img, format, baos);
                bdata = baos.toByteArray();
                datasize = bdata.length;
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
            if (filetype == "ZLIB") {
              byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
              Deflater compresser = new Deflater();
              compresser.setInput(bdata);
              compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
              compresser.setStrategy(Deflater.DEFAULT_STRATEGY);
              compresser.finish();
              datasize = compresser.deflate(tmpdata);
              bdata = tmpdata;
              compresser.end();
            }

            if (bytecount + datasize > sizelimit && bytecount > 0) {
              BufferedOutputStream fis = null;
              try {
                File file = new File(directory + current_dataname);
                fis = new BufferedOutputStream(new FileOutputStream(file));
                fis.write(packed_data, 0, bytecount);
              } catch (IOException e) {
                e.printStackTrace();
                return;
              } finally {
                try {
                  if (fis != null) fis.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  return;
                }
              }
              filecount++;
              current_dataname = base_dataname + "_data" + filecount;
              bytecount = 0;
              offset = 0;
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            } else {
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            }

            Element filenode = doc.createElement("File");
            filenode.setAttribute("filename", current_dataname);
            filenode.setAttribute("channel", String.valueOf(ch));
            filenode.setAttribute("frame", String.valueOf(f));
            filenode.setAttribute("brickID", String.valueOf(i));
            filenode.setAttribute("offset", String.valueOf(offset));
            filenode.setAttribute("datasize", String.valueOf(datasize));
            filenode.setAttribute("filetype", String.valueOf(filetype));

            fsnode.appendChild(filenode);

            curbricknum++;
            IJ.showProgress((double) (curbricknum) / (double) (totalbricknum));
          }
          if (bytecount > 0) {
            BufferedOutputStream fis = null;
            try {
              File file = new File(directory + current_dataname);
              fis = new BufferedOutputStream(new FileOutputStream(file));
              fis.write(packed_data, 0, bytecount);
            } catch (IOException e) {
              e.printStackTrace();
              return;
            } finally {
              try {
                if (fis != null) fis.close();
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
          }
        }
      }

      for (int i = 0; i < bricks.size(); i++) {
        Brick b = bricks.get(i);
        Element bricknode = doc.createElement("Brick");
        bricknode.setAttribute("id", String.valueOf(i));
        bricknode.setAttribute("st_x", String.valueOf(b.x_));
        bricknode.setAttribute("st_y", String.valueOf(b.y_));
        bricknode.setAttribute("st_z", String.valueOf(b.z_));
        bricknode.setAttribute("width", String.valueOf(b.w_));
        bricknode.setAttribute("height", String.valueOf(b.h_));
        bricknode.setAttribute("depth", String.valueOf(b.d_));
        brksnode.appendChild(bricknode);

        Element tboxnode = doc.createElement("tbox");
        tboxnode.setAttribute("x0", String.valueOf(b.tx0_));
        tboxnode.setAttribute("y0", String.valueOf(b.ty0_));
        tboxnode.setAttribute("z0", String.valueOf(b.tz0_));
        tboxnode.setAttribute("x1", String.valueOf(b.tx1_));
        tboxnode.setAttribute("y1", String.valueOf(b.ty1_));
        tboxnode.setAttribute("z1", String.valueOf(b.tz1_));
        bricknode.appendChild(tboxnode);

        Element bboxnode = doc.createElement("bbox");
        bboxnode.setAttribute("x0", String.valueOf(b.bx0_));
        bboxnode.setAttribute("y0", String.valueOf(b.by0_));
        bboxnode.setAttribute("z0", String.valueOf(b.bz0_));
        bboxnode.setAttribute("x1", String.valueOf(b.bx1_));
        bboxnode.setAttribute("y1", String.valueOf(b.by1_));
        bboxnode.setAttribute("z1", String.valueOf(b.bz1_));
        bricknode.appendChild(bboxnode);
      }

      if (l < lv - 1) {
        imp = WindowManager.getImage(lvImgTitle.get(l + 1));
        int[] newdims = imp.getDimensions();
        imageW = newdims[0];
        imageH = newdims[1];
        imageD = newdims[3];
        xspc = orgxspc * ((double) orgW / (double) imageW);
        yspc = orgyspc * ((double) orgH / (double) imageH);
        zspc = orgzspc * ((double) orgD / (double) imageD);
        bdepth = imp.getBitDepth();
      }
    }

    File newXMLfile = new File(directory + basename + ".vvd");
    writeXML(newXMLfile, doc);

    for (int l = 1; l < lv; l++) {
      imp = WindowManager.getImage(lvImgTitle.get(l));
      imp.changes = false;
      imp.close();
    }
  }
  private void updateSubImageImpl(
      TextureData data,
      int newTarget,
      int mipmapLevel,
      int dstx,
      int dsty,
      int srcx,
      int srcy,
      int width,
      int height)
      throws GLException {
    GL gl = GLU.getCurrentGL();
    data.setHaveEXTABGR(gl.isExtensionAvailable("GL_EXT_abgr"));
    data.setHaveGL12(gl.isExtensionAvailable("GL_VERSION_1_2"));

    Buffer buffer = data.getBuffer();
    if (buffer == null && data.getMipmapData() == null) {
      // Assume user just wanted to get the Texture object allocated
      return;
    }

    int rowlen = data.getRowLength();
    int dataWidth = data.getWidth();
    int dataHeight = data.getHeight();
    if (data.getMipmapData() != null) {
      // Compute the width, height and row length at the specified mipmap level
      // Note we do not support specification of the row length for
      // mipmapped textures at this point
      for (int i = 0; i < mipmapLevel; i++) {
        width = Math.max(width / 2, 1);
        height = Math.max(height / 2, 1);

        dataWidth = Math.max(dataWidth / 2, 1);
        dataHeight = Math.max(dataHeight / 2, 1);
      }
      rowlen = 0;
      buffer = data.getMipmapData()[mipmapLevel];
    }

    // Clip incoming rectangles to what is available both on this
    // texture and in the incoming TextureData
    if (srcx < 0) {
      width += srcx;
      srcx = 0;
    }
    if (srcy < 0) {
      height += srcy;
      srcy = 0;
    }
    // NOTE: not sure whether the following two are the correct thing to do
    if (dstx < 0) {
      width += dstx;
      dstx = 0;
    }
    if (dsty < 0) {
      height += dsty;
      dsty = 0;
    }

    if (srcx + width > dataWidth) {
      width = dataWidth - srcx;
    }
    if (srcy + height > dataHeight) {
      height = dataHeight - srcy;
    }
    if (dstx + width > texWidth) {
      width = texWidth - dstx;
    }
    if (dsty + height > texHeight) {
      height = texHeight - dsty;
    }

    checkCompressedTextureExtensions(data);

    if (data.isDataCompressed()) {
      gl.glCompressedTexSubImage2D(
          newTarget,
          mipmapLevel,
          dstx,
          dsty,
          width,
          height,
          data.getInternalFormat(),
          buffer.remaining(),
          buffer);
    } else {
      int[] align = new int[1];
      int[] rowLength = new int[1];
      int[] skipRows = new int[1];
      int[] skipPixels = new int[1];
      gl.glGetIntegerv(GL.GL_UNPACK_ALIGNMENT, align, 0); // save alignment
      gl.glGetIntegerv(GL.GL_UNPACK_ROW_LENGTH, rowLength, 0); // save row length
      gl.glGetIntegerv(GL.GL_UNPACK_SKIP_ROWS, skipRows, 0); // save skipped rows
      gl.glGetIntegerv(GL.GL_UNPACK_SKIP_PIXELS, skipPixels, 0); // save skipped pixels
      gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, data.getAlignment());
      if (DEBUG && VERBOSE) {
        System.out.println("Row length  = " + rowlen);
        System.out.println("skip pixels = " + srcx);
        System.out.println("skip rows   = " + srcy);
        System.out.println("dstx        = " + dstx);
        System.out.println("dsty        = " + dsty);
        System.out.println("width       = " + width);
        System.out.println("height      = " + height);
      }
      gl.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, rowlen);
      gl.glPixelStorei(GL.GL_UNPACK_SKIP_ROWS, srcy);
      gl.glPixelStorei(GL.GL_UNPACK_SKIP_PIXELS, srcx);

      gl.glTexSubImage2D(
          newTarget,
          mipmapLevel,
          dstx,
          dsty,
          width,
          height,
          data.getPixelFormat(),
          data.getPixelType(),
          buffer);
      gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, align[0]); // restore alignment
      gl.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, rowLength[0]); // restore row length
      gl.glPixelStorei(GL.GL_UNPACK_SKIP_ROWS, skipRows[0]); // restore skipped rows
      gl.glPixelStorei(GL.GL_UNPACK_SKIP_PIXELS, skipPixels[0]); // restore skipped pixels
    }
  }
  /**
   * Updates the content area of the specified target of this texture using the data in the given
   * image. In general this is intended for construction of cube maps.
   *
   * @throws GLException if no OpenGL context was current or if any OpenGL-related errors occurred
   */
  public void updateImage(TextureData data, int target) throws GLException {
    GL gl = GLU.getCurrentGL();

    imgWidth = data.getWidth();
    imgHeight = data.getHeight();
    aspectRatio = (float) imgWidth / (float) imgHeight;
    mustFlipVertically = data.getMustFlipVertically();

    int texTarget = 0;
    int texParamTarget = this.target;

    // See whether we have automatic mipmap generation support
    boolean haveAutoMipmapGeneration =
        (gl.isExtensionAvailable("GL_VERSION_1_4")
            || gl.isExtensionAvailable("GL_SGIS_generate_mipmap"));

    // Indicate to the TextureData what functionality is available
    data.setHaveEXTABGR(gl.isExtensionAvailable("GL_EXT_abgr"));
    data.setHaveGL12(gl.isExtensionAvailable("GL_VERSION_1_2"));

    // Note that automatic mipmap generation doesn't work for
    // GL_ARB_texture_rectangle
    if ((!isPowerOfTwo(imgWidth) || !isPowerOfTwo(imgHeight)) && !haveNPOT(gl)) {
      haveAutoMipmapGeneration = false;
    }

    boolean expandingCompressedTexture = false;
    if (data.getMipmap() && !haveAutoMipmapGeneration) {
      // GLU always scales the texture's dimensions to be powers of
      // two. It also doesn't really matter exactly what the texture
      // width and height are because the texture coords are always
      // between 0.0 and 1.0.
      imgWidth = nextPowerOfTwo(imgWidth);
      imgHeight = nextPowerOfTwo(imgHeight);
      texWidth = imgWidth;
      texHeight = imgHeight;
      texTarget = GL.GL_TEXTURE_2D;
    } else if ((isPowerOfTwo(imgWidth) && isPowerOfTwo(imgHeight)) || haveNPOT(gl)) {
      if (DEBUG) {
        if (isPowerOfTwo(imgWidth) && isPowerOfTwo(imgHeight)) {
          System.err.println("Power-of-two texture");
        } else {
          System.err.println("Using GL_ARB_texture_non_power_of_two");
        }
      }

      texWidth = imgWidth;
      texHeight = imgHeight;
      texTarget = GL.GL_TEXTURE_2D;
    } else if (haveTexRect(gl) && !data.isDataCompressed()) {
      // GL_ARB_texture_rectangle does not work for compressed textures
      if (DEBUG) {
        System.err.println("Using GL_ARB_texture_rectangle");
      }

      texWidth = imgWidth;
      texHeight = imgHeight;
      texTarget = GL.GL_TEXTURE_RECTANGLE_ARB;
    } else {
      // If we receive non-power-of-two compressed texture data and
      // don't have true hardware support for compressed textures, we
      // can fake this support by producing an empty "compressed"
      // texture image, using glCompressedTexImage2D with that to
      // allocate the texture, and glCompressedTexSubImage2D with the
      // incoming data.
      if (data.isDataCompressed()) {
        if (data.getMipmapData() != null) {

          // We don't currently support expanding of compressed,
          // mipmapped non-power-of-two textures to the nearest power
          // of two; the obvious port of the non-mipmapped code didn't
          // work
          throw new GLException(
              "Mipmapped non-power-of-two compressed textures only supported on OpenGL 2.0 hardware (GL_ARB_texture_non_power_of_two)");
        }

        expandingCompressedTexture = true;
      }

      if (DEBUG) {
        System.err.println("Expanding texture to power-of-two dimensions");
      }

      if (data.getBorder() != 0) {
        throw new RuntimeException(
            "Scaling up a non-power-of-two texture which has a border won't work");
      }
      texWidth = nextPowerOfTwo(imgWidth);
      texHeight = nextPowerOfTwo(imgHeight);
      texTarget = GL.GL_TEXTURE_2D;
    }

    texParamTarget = texTarget;
    setImageSize(imgWidth, imgHeight, texTarget);

    if (target != 0) {
      // Allow user to override auto detection and skip bind step (for
      // cubemap construction)
      texTarget = target;
      if (this.target == 0) {
        throw new GLException("Override of target failed; no target specified yet");
      }
      texParamTarget = this.target;
      gl.glBindTexture(texParamTarget, texID);
    } else {
      gl.glBindTexture(texTarget, texID);
    }

    if (data.getMipmap() && !haveAutoMipmapGeneration) {
      int[] align = new int[1];
      gl.glGetIntegerv(GL.GL_UNPACK_ALIGNMENT, align, 0); // save alignment
      gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, data.getAlignment());

      if (data.isDataCompressed()) {
        throw new GLException("May not request mipmap generation for compressed textures");
      }

      try {
        GLU glu = new GLU();
        glu.gluBuild2DMipmaps(
            texTarget,
            data.getInternalFormat(),
            data.getWidth(),
            data.getHeight(),
            data.getPixelFormat(),
            data.getPixelType(),
            data.getBuffer());
      } finally {
        gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, align[0]); // restore alignment
      }
    } else {
      checkCompressedTextureExtensions(data);
      Buffer[] mipmapData = data.getMipmapData();
      if (mipmapData != null) {
        int width = texWidth;
        int height = texHeight;
        for (int i = 0; i < mipmapData.length; i++) {
          if (data.isDataCompressed()) {
            // Need to use glCompressedTexImage2D directly to allocate and fill this image
            // Avoid spurious memory allocation when possible
            gl.glCompressedTexImage2D(
                texTarget,
                i,
                data.getInternalFormat(),
                width,
                height,
                data.getBorder(),
                mipmapData[i].remaining(),
                mipmapData[i]);
          } else {
            // Allocate texture image at this level
            gl.glTexImage2D(
                texTarget,
                i,
                data.getInternalFormat(),
                width,
                height,
                data.getBorder(),
                data.getPixelFormat(),
                data.getPixelType(),
                null);
            updateSubImageImpl(data, texTarget, i, 0, 0, 0, 0, data.getWidth(), data.getHeight());
          }

          width = Math.max(width / 2, 1);
          height = Math.max(height / 2, 1);
        }
      } else {
        if (data.isDataCompressed()) {
          if (!expandingCompressedTexture) {
            // Need to use glCompressedTexImage2D directly to allocate and fill this image
            // Avoid spurious memory allocation when possible
            gl.glCompressedTexImage2D(
                texTarget,
                0,
                data.getInternalFormat(),
                texWidth,
                texHeight,
                data.getBorder(),
                data.getBuffer().capacity(),
                data.getBuffer());
          } else {
            ByteBuffer buf =
                DDSImage.allocateBlankBuffer(texWidth, texHeight, data.getInternalFormat());
            gl.glCompressedTexImage2D(
                texTarget,
                0,
                data.getInternalFormat(),
                texWidth,
                texHeight,
                data.getBorder(),
                buf.capacity(),
                buf);
            updateSubImageImpl(data, texTarget, 0, 0, 0, 0, 0, data.getWidth(), data.getHeight());
          }
        } else {
          if (data.getMipmap() && haveAutoMipmapGeneration) {
            // For now, only use hardware mipmapping for uncompressed 2D
            // textures where the user hasn't explicitly specified
            // mipmap data; don't know about interactions between
            // GL_GENERATE_MIPMAP and glCompressedTexImage2D
            gl.glTexParameteri(texParamTarget, GL.GL_GENERATE_MIPMAP, GL.GL_TRUE);
            usingAutoMipmapGeneration = true;
          }

          gl.glTexImage2D(
              texTarget,
              0,
              data.getInternalFormat(),
              texWidth,
              texHeight,
              data.getBorder(),
              data.getPixelFormat(),
              data.getPixelType(),
              null);
          updateSubImageImpl(data, texTarget, 0, 0, 0, 0, 0, data.getWidth(), data.getHeight());
        }
      }
    }

    int minFilter = (data.getMipmap() ? GL.GL_LINEAR_MIPMAP_LINEAR : GL.GL_LINEAR);
    int magFilter = GL.GL_LINEAR;
    int wrapMode = (gl.isExtensionAvailable("GL_VERSION_1_2") ? GL.GL_CLAMP_TO_EDGE : GL.GL_CLAMP);

    // REMIND: figure out what to do for GL_TEXTURE_RECTANGLE_ARB
    if (texTarget != GL.GL_TEXTURE_RECTANGLE_ARB) {
      gl.glTexParameteri(texParamTarget, GL.GL_TEXTURE_MIN_FILTER, minFilter);
      gl.glTexParameteri(texParamTarget, GL.GL_TEXTURE_MAG_FILTER, magFilter);
      gl.glTexParameteri(texParamTarget, GL.GL_TEXTURE_WRAP_S, wrapMode);
      gl.glTexParameteri(texParamTarget, GL.GL_TEXTURE_WRAP_T, wrapMode);
      if (this.target == GL.GL_TEXTURE_CUBE_MAP) {
        gl.glTexParameteri(texParamTarget, GL.GL_TEXTURE_WRAP_R, wrapMode);
      }
    }

    // Don't overwrite target if we're loading e.g. faces of a cube
    // map
    if ((this.target == 0)
        || (this.target == GL.GL_TEXTURE_2D)
        || (this.target == GL.GL_TEXTURE_RECTANGLE_ARB)) {
      this.target = texTarget;
    }

    // This estimate will be wrong for cube maps
    estimatedMemorySize = data.getEstimatedMemorySize();
  }
 private static float clamp(final float val, final float min, final float max) {
   return Math.max(min, Math.min(max, val));
 }
Beispiel #13
0
 public static void intersect(Rect r1, Rect r2, Rect dst) {
   dst.top = Math.max(r1.top, r2.top);
   dst.bottom = Math.min(r1.bottom, r2.bottom);
   dst.left = Math.max(r1.left, r2.left);
   dst.right = Math.min(r1.right, r2.right);
 }