Beispiel #1
0
    public circle(float r) {
      transMatrix = new float[16];
      int sides = 24;
      vertexCoords = new float[sides * 3];
      double angle = 2 * Math.PI / sides;

      for (int i = 0; i < sides; i++) {
        vertexCoords[3 * i] = (float) (Math.cos(i * angle) * r);
        vertexCoords[3 * i + 1] = (float) (Math.sin(i * angle) * r);
        vertexCoords[3 * i + 2] = 0f;
      }
      vertexCount = vertexCoords.length / COORDS_PER_VERTEX;
      vertexStride = COORDS_PER_VERTEX * 4;
      ByteBuffer bb = ByteBuffer.allocateDirect(vertexCoords.length * 4);
      bb.order(ByteOrder.nativeOrder());
      vertexBuffer = bb.asFloatBuffer();
      vertexBuffer.put(vertexCoords);
      vertexBuffer.position(0);
      int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
      int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);

      mProgram = GLES20.glCreateProgram(); // create empty OpenGL Program
      GLES20.glAttachShader(mProgram, vertexShader); // add the vertex shader to program
      GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
      GLES20.glLinkProgram(mProgram); // create OpenGL program executables
    }
Beispiel #2
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));
  }
Beispiel #3
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 #4
0
 public void fellipse(Coord c, Coord r, int a1, int a2) {
   st.set(cur2d);
   apply();
   gl.glBegin(GL.GL_TRIANGLE_FAN);
   vertex(c);
   for (int i = a1; i <= a2; i += 5) {
     double a = (i * Math.PI * 2) / 360.0;
     vertex(c.add((int) (Math.cos(a) * r.x), -(int) (Math.sin(a) * r.y)));
   }
   gl.glEnd();
   checkerr();
 }
Beispiel #5
0
  public void prect(Coord c, Coord ul, Coord br, double a) {
    st.set(cur2d);
    apply();
    gl.glEnable(GL2.GL_POLYGON_SMOOTH);
    gl.glBegin(GL.GL_TRIANGLE_FAN);
    vertex(c);
    vertex(c.add(0, ul.y));
    double p2 = Math.PI / 2;
    all:
    {
      float tc;

      tc = (float) (Math.tan(a) * -ul.y);
      if ((a > p2) || (tc > br.x)) {
        vertex(c.x + br.x, c.y + ul.y);
      } else {
        vertex(c.x + tc, c.y + ul.y);
        break all;
      }

      tc = (float) (Math.tan(a - (Math.PI / 2)) * br.x);
      if ((a > p2 * 2) || (tc > br.y)) {
        vertex(c.x + br.x, c.y + br.y);
      } else {
        vertex(c.x + br.x, c.y + tc);
        break all;
      }

      tc = (float) (-Math.tan(a - Math.PI) * br.y);
      if ((a > p2 * 3) || (tc < ul.x)) {
        vertex(c.x + ul.x, c.y + br.y);
      } else {
        vertex(c.x + tc, c.y + br.y);
        break all;
      }

      tc = (float) (-Math.tan(a - (3 * Math.PI / 2)) * -ul.x);
      if ((a > p2 * 4) || (tc < ul.y)) {
        vertex(c.x + ul.x, c.y + ul.y);
      } else {
        vertex(c.x + ul.x, c.y + tc);
        break all;
      }

      tc = (float) (Math.tan(a) * -ul.y);
      vertex(c.x + tc, c.y + ul.y);
    }
    gl.glEnd();
    gl.glDisable(GL2.GL_POLYGON_SMOOTH);
    checkerr();
  }
Beispiel #6
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;
  }
  public String createUID() {
    Long num;
    String uid;

    uid = "";
    num = new Date().getTime();
    while (num > 0) {
      uid += UIDMap[(int) (num % 62)];
      num /= 62;
    }

    uid += Math.round(Math.random() * 9.0);

    return uid;
  }
Beispiel #8
0
  public static void main(String args[]) throws Exception {
    FloatBuffer buffer = FloatBuffer.allocate(10);

    for (int i = 0; i < buffer.capacity(); ++i) {
      float f = (float) Math.sin((((float) i) / 10) * (2 * Math.PI));
      buffer.put(f);
    }

    /** flip()源码: */
    //		public final Buffer flip() {
    //        	limit = position;
    //        	position = 0;
    //        	mark = -1;
    //        	return this;
    //    	}
    /**
     * 反转缓冲区。首先将限制设置为当前位置,然后将位置设置为 0。 如果已定义了标记,则丢弃该标记。 常与compact方法一起使用。 通常情况下,在准备从缓冲区中读取数据时调用flip方法。
     */
    buffer.flip();

    while (buffer.hasRemaining()) {
      float f = buffer.get();
      System.out.println(f);
    }
  }
Beispiel #9
0
 private int mipMapWidth(int map) {
   int width = getWidth();
   for (int i = 0; i < map; i++) {
     width >>= 1;
   }
   return Math.max(width, 1);
 }
Beispiel #10
0
  /**
   * sends data from buffer.
   *
   * <p>precondition: sendbb is in put mode post condition: sendbb is in put mode
   */
  private void sendFromBuffer() {
    aa(this, isSender(), "nonsender can't write");
    aa(this, isConnected() || isClosurePending(), "needs to be established can't write");

    // switch sendbb to get mode
    sendbb.flip();
    p(this, 3, "Sending from buffer. bb flipped.");
    int payloadLength = Math.min(Transport.MAX_PAYLOAD_SIZE, sendbb.limit());
    p(this, 4, "Max Payload size: " + Transport.MAX_PAYLOAD_SIZE);
    p(this, 4, "payloadlen: " + payloadLength);
    dumpState(4);

    if (roomForPacket(payloadLength) && payloadLength > 0) {
      byte[] payload = new byte[payloadLength];
      sendbb.get(payload);

      Transport t = makeTransport(Transport.DATA, seqNum, payload);
      tcpMan.sendData(this.tsid, t);

      p(this, 3, "Write: converting to packet: " + TCPManager.bytesToString(payload));

      // only increment the seqNum if a packet is sent
      seqNum += payloadLength;
    }

    // switch back to put mode
    sendbb.compact();
    dumpState(4);
    if (isClosurePending() && sendbb.position() == 0) release();
  }
 private boolean openSeekable() {
   final Info initialInfo = new Info();
   final Comment initialComment = new Comment();
   this.m_chunkSize = Math.min(8500, (int) length(this.m_vorbisStream));
   final Page page = new Page();
   final int[] testSerialno = {0};
   final int ret = this.fetchHeaders(initialInfo, initialComment, testSerialno, null);
   final int serialno = testSerialno[0];
   final int dataOffset = (int) this.m_offset;
   this.m_oggStreamState.clear();
   if (ret < 0) {
     return false;
   }
   seek(this.m_vorbisStream, 0L, 1);
   this.m_offset = tell(this.m_vorbisStream);
   final long end = this.getPreviousPage(page);
   if (page.serialno() != serialno) {
     if (this.bisectForwardSerialno(0L, 0L, end + 1L, serialno, 0) < 0) {
       return false;
     }
   } else if (this.bisectForwardSerialno(0L, end, end + 1L, serialno, 0) < 0) {
     return false;
   }
   this.prefetchAllHeaders(initialInfo, initialComment, dataOffset);
   this.rawSeek(this.m_dataOffsets[0]);
   return true;
 }
Beispiel #12
0
 private int mipMapHeight(int map) {
   int height = getHeight();
   for (int i = 0; i < map; i++) {
     height >>= 1;
   }
   return Math.max(height, 1);
 }
  /**
   * @param placeNameServiceSet the set of PlaceNameService objects that PlaceNameLayer will render.
   * @throws IllegalArgumentException if {@link
   *     gov.nasa.worldwind.layers.placename.PlaceNameServiceSet} is null
   */
  public PlaceNameLayer(PlaceNameServiceSet placeNameServiceSet) {
    if (placeNameServiceSet == null) {
      String message = Logging.getMessage("nullValue.PlaceNameServiceSetIsNull");
      Logging.logger().fine(message);
      throw new IllegalArgumentException(message);
    }

    //
    this.placeNameServiceSet = placeNameServiceSet.deepCopy();
    for (int i = 0; i < this.placeNameServiceSet.getServiceCount(); i++) {
      // todo do this for long as well and pick min
      int calc1 =
          (int)
              (PlaceNameService.TILING_SECTOR.getDeltaLatDegrees()
                  / this.placeNameServiceSet
                      .getService(i)
                      .getTileDelta()
                      .getLatitude()
                      .getDegrees());
      int numLevels = (int) Math.log(calc1);
      navTiles.add(
          new NavigationTile(
              this.placeNameServiceSet.getService(i),
              PlaceNameService.TILING_SECTOR,
              numLevels,
              "top"));
    }

    if (!WorldWind.getMemoryCacheSet().containsCache(Tile.class.getName())) {
      long size = Configuration.getLongValue(AVKey.PLACENAME_LAYER_CACHE_SIZE, 2000000L);
      MemoryCache cache = new BasicMemoryCache((long) (0.85 * size), size);
      cache.setName("Placename Tiles");
      WorldWind.getMemoryCacheSet().addCache(Tile.class.getName(), cache);
    }
  }
  /**
   * 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);
    }
  }
Beispiel #15
0
  private void updateLoader() {
    if (NavigineApp.Navigation == null) return;

    // Log.d(TAG, String.format(Locale.ENGLISH, "Update loader: %d", mLoader));

    long timeNow = DateTimeUtils.currentTimeMillis();
    if (mLoader < 0) return;

    int status = LocationLoader.checkLocationLoader(mLoader);
    if (status < 100) {
      if ((Math.abs(timeNow - mLoaderTime) > LOADER_TIMEOUT / 3 && status == 0)
          || (Math.abs(timeNow - mLoaderTime) > LOADER_TIMEOUT)) {
        mListView.setVisibility(View.GONE);
        mStatusLabel.setVisibility(View.VISIBLE);
        mStatusLabel.setText("Loading timeout!\nPlease, check your internet connection!");
        Log.d(TAG, String.format(Locale.ENGLISH, "Load stopped on timeout!"));
        LocationLoader.stopLocationLoader(mLoader);
        mLoader = -1;
      } else {
        mListView.setVisibility(View.GONE);
        mStatusLabel.setVisibility(View.VISIBLE);
        mStatusLabel.setText(String.format(Locale.ENGLISH, "Loading content (%d%%)", status));
      }
    } else {
      Log.d(TAG, String.format(Locale.ENGLISH, "Load finished with result: %d", status));
      LocationLoader.stopLocationLoader(mLoader);
      mLoader = -1;

      if (status == 100) {
        parseMapsXml();
        if (mInfoList.isEmpty()) {
          mListView.setVisibility(View.GONE);
          mStatusLabel.setVisibility(View.VISIBLE);
          mStatusLabel.setText("No locations available");
        } else {
          mListView.setVisibility(View.VISIBLE);
          mStatusLabel.setVisibility(View.GONE);
        }
      } else {
        mListView.setVisibility(View.GONE);
        mStatusLabel.setVisibility(View.VISIBLE);
        mStatusLabel.setText("Error loading!\nPlease, check your ID!");
      }
    }
  }
Beispiel #16
0
 public void write(byte b[], int off, int len) throws IOException {
   while (len > 0) {
     if (buf.remaining() == 0) decode(false);
     int sz = Math.min(buf.remaining(), len);
     buf.put(b, off, sz);
     off += sz;
     len -= sz;
   }
 }
 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);
   }
 }
 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;
 }
Beispiel #19
0
  /**
   * Read from the socket up to len bytes into the buffer buf starting at position pos.
   *
   * @param buf byte[] the buffer
   * @param pos int starting position in buffer
   * @param len int number of bytes to read
   * @return int on success, the number of bytes read, which may be smaller than len; on failure, -1
   */
  public int read(byte[] buf, int pos, int len) {
    aa(this, isReceiver(), "nonreceiver socket reading");
    aa(this, state == State.ESTABLISHED, "attempting to read from closed socket");

    recvbb.flip();
    int bytesCopied = Math.min(recvbb.limit(), len);
    recvbb.get(buf, pos, bytesCopied);
    recvbb.compact();

    return bytesCopied;
  }
 public void updateViewports(final Viewport leftViewport, final Viewport rightViewport) {
   leftViewport.setViewport(
       Math.round(this.mLeftEyeViewport.x * this.mXPxPerTanAngle * this.mResolutionScale),
       Math.round(this.mLeftEyeViewport.y * this.mYPxPerTanAngle * this.mResolutionScale),
       Math.round(this.mLeftEyeViewport.width * this.mXPxPerTanAngle * this.mResolutionScale),
       Math.round(this.mLeftEyeViewport.height * this.mYPxPerTanAngle * this.mResolutionScale));
   rightViewport.setViewport(
       Math.round(this.mRightEyeViewport.x * this.mXPxPerTanAngle * this.mResolutionScale),
       Math.round(this.mRightEyeViewport.y * this.mYPxPerTanAngle * this.mResolutionScale),
       Math.round(this.mRightEyeViewport.width * this.mXPxPerTanAngle * this.mResolutionScale),
       Math.round(this.mRightEyeViewport.height * this.mYPxPerTanAngle * this.mResolutionScale));
   this.mViewportsChanged = false;
 }
Beispiel #21
0
 private void testRecoveryWithBadMessageSize(List<Record> records, int size) throws IOException {
   LogSegment seg = this.store.log().lastSegment();
   writeToOffset(seg.file(), seg.file().length(), ByteBuffer.allocate(4).putInt(size).array());
   // now add some message bytes, but not enough
   if (size > 0)
     writeToOffset(
         seg.file(), seg.file().length(), ByteBuffer.allocate(Math.min(size - 1, 256)).array());
   this.store.close();
   this.store = new HashStore(config);
   assertEquals("Same records should be present after close and re-open", records, records(store));
 }
Beispiel #22
0
        public void run() {
          if (NavigineApp.Navigation == null) return;

          long timeNow = DateTimeUtils.currentTimeMillis();

          String userHash = NavigineApp.Settings.getString("user_hash", "");
          if (userHash.length() == 0) return;

          if (mLoader >= 0) updateLoader();

          if (Math.abs(timeNow - mUpdateLocationLoadersTime) > 1000) updateLocationLoaders();
        }
 private EyeViewport initViewportForEye(final FieldOfView fov, final float xOffset) {
   final float left = (float) Math.tan(Math.toRadians(fov.getLeft()));
   final float right = (float) Math.tan(Math.toRadians(fov.getRight()));
   final float bottom = (float) Math.tan(Math.toRadians(fov.getBottom()));
   final float top = (float) Math.tan(Math.toRadians(fov.getTop()));
   final EyeViewport vp = new EyeViewport();
   vp.x = xOffset;
   vp.y = 0.0f;
   vp.width = left + right;
   vp.height = bottom + top;
   vp.eyeX = left + xOffset;
   vp.eyeY = bottom;
   return vp;
 }
Beispiel #24
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};
  }
Beispiel #25
0
  @Override
  public boolean equals(Object o) {
    if (o instanceof DataBuffer) {
      DataBuffer d = (DataBuffer) o;
      if (d.length() != length()) return false;
      for (int i = 0; i < length(); i++) {
        double eps = Math.abs(getDouble(i) - d.getDouble(i));
        if (eps > Nd4j.EPS_THRESHOLD) return false;
      }
    }

    return true;
  }
Beispiel #26
0
  /**
   * Update the player
   *
   * @param input user input
   * @param enemy person to check for guns
   */
  public void update(S2DInput input, Enemy enemy) {
    if (health <= 0) {
      isDead = true;
    } else {
      if (isDead == true) {
        world.set(spawn.x, spawn.y);
        gun.resetClip();
        isDead = false;
      }

      if (input.getKey(KeyEvent.VK_W)
          || input.getKey(KeyEvent.VK_S)
          || input.getKey(KeyEvent.VK_A)
          || input.getKey(KeyEvent.VK_D)) {
        moving = true;

        boolean[] sides = new boolean[4];
        if (S2DBoundingBox.intersectAA(man.getBoundingBox(), Map.getBounds())) {
          sides = S2DBoundingBox.intersectBA2(man.getBoundingBox(), Map.getBounds(), .20);
        }

        if (input.getKey(KeyEvent.VK_W) && !sides[S2DBoundingBox.TOPBOUND]) {
          world.add(0, -5);
        }
        if (input.getKey(KeyEvent.VK_S) && !sides[S2DBoundingBox.BOTTOMBOUND]) {
          world.add(0, 5);
        }
        if (input.getKey(KeyEvent.VK_A) && !sides[S2DBoundingBox.LEFTBOUND]) {
          world.add(-5, 0);
        }
        if (input.getKey(KeyEvent.VK_D) && !sides[S2DBoundingBox.RIGHTBOUND]) {
          world.add(5, 0);
        }
      } else {
        moving = false;
      }

      double relativeLocX = (double) (input.getMouseLocation().x) - (double) (Const.SCE_WIDTH / 2);
      double relativeLocY = (double) (input.getMouseLocation().y) - (double) (Const.SCE_HEIGHT / 2);
      radians = Math.atan2(relativeLocY, relativeLocX) + Math.PI / 2;

      gun.update(input, enemy);
    }
  }
Beispiel #27
0
  private void updateLocationLoaders() {
    if (NavigineApp.Navigation == null) return;

    long timeNow = DateTimeUtils.currentTimeMillis();
    mUpdateLocationLoadersTime = timeNow;

    synchronized (mLoaderMap) {
      Iterator<Map.Entry<String, LoaderState>> iter = mLoaderMap.entrySet().iterator();
      while (iter.hasNext()) {
        Map.Entry<String, LoaderState> entry = iter.next();

        LoaderState loader = entry.getValue();
        if (loader.state < 100) {
          loader.timeLabel = timeNow;
          if (loader.type == DOWNLOAD) loader.state = LocationLoader.checkLocationLoader(loader.id);
          if (loader.type == UPLOAD) loader.state = LocationLoader.checkLocationUploader(loader.id);
        } else if (loader.state == 100) {
          String archivePath = NavigineApp.Navigation.getArchivePath();
          String locationFile =
              LocationLoader.getLocationFile(NavigineApp.AppContext, loader.location);
          if (archivePath != null && archivePath.equals(locationFile)) {
            Log.d(TAG, "Reloading archive " + archivePath);
            if (NavigineApp.Navigation.loadArchive(archivePath)) {
              SharedPreferences.Editor editor = NavigineApp.Settings.edit();
              editor.putString("map_file", archivePath);
              editor.commit();
            }
          }
          if (loader.type == DOWNLOAD) LocationLoader.stopLocationLoader(loader.id);
          if (loader.type == UPLOAD) LocationLoader.stopLocationUploader(loader.id);
          iter.remove();
        } else {
          // Load failed
          if (Math.abs(timeNow - loader.timeLabel) > 5000) {
            if (loader.type == DOWNLOAD) LocationLoader.stopLocationLoader(loader.id);
            if (loader.type == UPLOAD) LocationLoader.stopLocationUploader(loader.id);
            iter.remove();
          }
        }
      }
    }
    updateLocalVersions();
    mAdapter.updateList();
  }
Beispiel #28
0
  private static WAVData readFromStream(AudioInputStream aIn)
      throws UnsupportedAudioFileException, IOException {
    ReadableByteChannel aChannel = Channels.newChannel(aIn);
    AudioFormat fmt = aIn.getFormat();
    int numChannels = fmt.getChannels();
    int bits = fmt.getSampleSizeInBits();
    int format = AL_FORMAT_MONO8;

    if ((bits == 8) && (numChannels == 1)) {
      format = AL_FORMAT_MONO8;
    } else if ((bits == 16) && (numChannels == 1)) {
      format = AL_FORMAT_MONO16;
    } else if ((bits == 8) && (numChannels == 2)) {
      format = AL_FORMAT_STEREO8;
    } else if ((bits == 16) && (numChannels == 2)) {
      format = AL_FORMAT_STEREO16;
    }

    int freq = Math.round(fmt.getSampleRate());
    int size = aIn.available();
    ByteBuffer buffer = ByteBuffer.allocateDirect(size);
    while (buffer.remaining() > 0) {
      aChannel.read(buffer);
    }
    buffer.rewind();

    // Must byte swap on big endian platforms
    // Thanks to swpalmer on javagaming.org forums for hint at fix
    if ((bits == 16) && (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN)) {
      int len = buffer.remaining();
      for (int i = 0; i < len; i += 2) {
        byte a = buffer.get(i);
        byte b = buffer.get(i + 1);
        buffer.put(i, b);
        buffer.put(i + 1, a);
      }
    }

    WAVData result = new WAVData(buffer, format, size, freq, false);
    aIn.close();

    return result;
  }
Beispiel #29
0
  /**
   * Write to the socket up to len bytes from the buffer buf starting at position pos.
   *
   * @param buf byte[] the buffer to write from
   * @param pos int starting position in buffer
   * @param len int number of bytes to write
   * @return int on success, the number of bytes written, which may be smaller than len; on failure,
   *     -1
   */
  public int write(byte[] buf, int pos, int len) {
    aa(this, isSender(), "nonsender can't write");
    aa(this, isConnected(), "nonsender can't write");

    // fill buffer
    p(
        this,
        3,
        "write called"); // \n\t buf = " + TCPManager.bytesToString(buf)); p(this, 4, "sendbb
                         // position: " + sendbb.position());
    dumpState(4);
    // p(this, 4, "sendbb limit: " + sendbb.limit());
    // p(this, 4, "sendbb remaining: " + sendbb.remaining());
    // p(this, 4, "sendbb size: " + sendbb.capacity());

    int bytesCopied = Math.min(sendbb.remaining(), len);
    sendbb.put(buf, pos, bytesCopied);
    p(this, 3, "bytes copied: " + bytesCopied);

    // try to send as much as possible
    sendFromBuffer();
    return bytesCopied;
  }
Beispiel #30
0
 /**
  * Returns the largest bit-value that is set to '1' of a given mask value.
  *
  * <p>E.g., for a mask value of 128, the result will be 7, while for a mask value of 3, the value
  * will be 1.
  *
  * @param aMaskValue the mask value to return the bit-index of.
  * @return the largest bit-value that is set to '1' of a given mask value, zero-based.
  */
 public static int getBitIndex(final int aMaskValue) {
   return (int) Math.floor(Math.log(aMaskValue) / Math.log(2));
 }