Esempio n. 1
0
  protected void read(DataInputStream s) {
    try {
      ref = new WeakReference<DataBuffer>(this, Nd4j.bufferRefQueue());
      referencing = Collections.synchronizedSet(new HashSet<String>());
      dirty = new AtomicBoolean(false);
      allocationMode = AllocationMode.valueOf(s.readUTF());
      length = s.readInt();
      Type t = Type.valueOf(s.readUTF());
      if (t == Type.DOUBLE) {
        if (allocationMode == AllocationMode.HEAP) {
          if (this.dataType() == Type.FLOAT) { // DataBuffer type
            // double -> float
            floatData = new float[length()];
          } else if (this.dataType() == Type.DOUBLE) {
            // double -> double
            doubleData = new double[length()];
          } else {
            // double -> int
            intData = new int[length()];
          }
          for (int i = 0; i < length(); i++) {
            put(i, s.readDouble());
          }
        } else {
          wrappedBuffer = ByteBuffer.allocateDirect(length() * getElementSize());
          wrappedBuffer.order(ByteOrder.nativeOrder());
          for (int i = 0; i < length(); i++) {
            put(i, s.readDouble());
          }
        }
      } else {
        if (allocationMode == AllocationMode.HEAP) {
          if (this.dataType() == Type.FLOAT) { // DataBuffer type
            // float -> float
            floatData = new float[length()];
          } else if (this.dataType() == Type.DOUBLE) {
            // float -> double
            doubleData = new double[length()];
          } else {
            // float-> int
            intData = new int[length()];
          }
          for (int i = 0; i < length(); i++) {
            put(i, s.readFloat());
          }
        } else {
          wrappedBuffer = ByteBuffer.allocateDirect(length() * getElementSize());
          wrappedBuffer.order(ByteOrder.nativeOrder());
          for (int i = 0; i < length(); i++) {
            put(i, s.readFloat());
          }
        }
      }

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Esempio n. 2
0
  /**
   * Create a data buffer from the given length
   *
   * @param buffer
   * @param length
   */
  public BaseDataBuffer(ByteBuffer buffer, int length) {
    allocationMode = Nd4j.alloc;
    this.length = length;
    buffer.order(ByteOrder.nativeOrder());
    if (allocationMode() == AllocationMode.DIRECT) {
      this.wrappedBuffer = buffer;
    } else if (dataType() == Type.INT) {
      intData = new int[length];
      IntBuffer intBuffer = buffer.asIntBuffer();
      for (int i = 0; i < length; i++) {
        intData[i] = intBuffer.get(i);
      }
    } else if (dataType() == Type.DOUBLE) {
      doubleData = new double[length];
      DoubleBuffer doubleBuffer = buffer.asDoubleBuffer();
      for (int i = 0; i < length; i++) {
        doubleData[i] = doubleBuffer.get(i);
      }

    } else if (dataType() == Type.FLOAT) {
      floatData = new float[length];
      FloatBuffer floatBuffer = buffer.asFloatBuffer();
      for (int i = 0; i < length; i++) {
        floatData[i] = floatBuffer.get(i);
      }
    }
  }
  /**
   * Tries to start server with given parameters.
   *
   * @param hostAddr Host on which server should be bound.
   * @param port Port on which server should be bound.
   * @param lsnr Server message listener.
   * @param parser Server message parser.
   * @param sslCtx SSL context in case if SSL is enabled.
   * @param cfg Configuration for other parameters.
   * @return {@code True} if server successfully started, {@code false} if port is used and server
   *     was unable to start.
   */
  private boolean startTcpServer(
      InetAddress hostAddr,
      int port,
      GridNioServerListener<GridClientMessage> lsnr,
      GridNioParser parser,
      @Nullable SSLContext sslCtx,
      GridConfiguration cfg) {
    try {
      GridNioFilter codec = new GridNioCodecFilter(parser, log, false);

      GridNioFilter[] filters;

      if (sslCtx != null) {
        GridNioSslFilter sslFilter = new GridNioSslFilter(sslCtx, log);

        boolean auth = cfg.isRestTcpSslClientAuth();

        sslFilter.wantClientAuth(auth);

        sslFilter.needClientAuth(auth);

        filters = new GridNioFilter[] {codec, sslFilter};
      } else filters = new GridNioFilter[] {codec};

      srv =
          GridNioServer.<GridClientMessage>builder()
              .address(hostAddr)
              .port(port)
              .listener(lsnr)
              .logger(log)
              .selectorCount(cfg.getRestTcpSelectorCount())
              .gridName(ctx.gridName())
              .tcpNoDelay(cfg.isRestTcpNoDelay())
              .directBuffer(cfg.isRestTcpDirectBuffer())
              .byteOrder(ByteOrder.nativeOrder())
              .socketSendBufferSize(cfg.getRestTcpSendBufferSize())
              .socketReceiveBufferSize(cfg.getRestTcpReceiveBufferSize())
              .sendQueueLimit(cfg.getRestTcpSendQueueLimit())
              .filters(filters)
              .build();

      srv.idleTimeout(cfg.getRestIdleTimeout());

      srv.start();

      ctx.ports().registerPort(port, GridPortProtocol.TCP, getClass());

      return true;
    } catch (GridException e) {
      if (log.isDebugEnabled())
        log.debug(
            "Failed to start " + name() + " protocol on port " + port + ": " + e.getMessage());

      return false;
    }
  }
Esempio n. 4
0
  /**
   * @param data
   * @param copy
   */
  public BaseDataBuffer(int[] data, boolean copy) {
    allocationMode = Nd4j.alloc;
    if (allocationMode == AllocationMode.HEAP) {
      if (copy) intData = ArrayUtil.copy(data);
      else this.intData = data;

    } else {
      wrappedBuffer = ByteBuffer.allocateDirect(4 * data.length);
      wrappedBuffer.order(ByteOrder.nativeOrder());
      IntBuffer buffer = wrappedBuffer.asIntBuffer();
      for (int i = 0; i < data.length; i++) {
        buffer.put(i, data[i]);
      }
    }
    length = data.length;
  }
Esempio n. 5
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;
  }
Esempio n. 6
0
  /**
   * Instantiate a buffer with the given length
   *
   * @param length the length of the buffer
   */
  protected BaseDataBuffer(int length) {
    this.length = length;
    allocationMode = Nd4j.alloc;
    if (length < 0) throw new IllegalArgumentException("Unable to create a buffer of length <= 0");

    ref = new WeakReference<DataBuffer>(this, Nd4j.bufferRefQueue());
    if (allocationMode == AllocationMode.HEAP) {
      if (length >= Integer.MAX_VALUE)
        throw new IllegalArgumentException(
            "Length of data buffer can not be > Integer.MAX_VALUE for heap (array based storage) allocation");
      if (dataType() == Type.DOUBLE) doubleData = new double[length];
      else if (dataType() == Type.FLOAT) floatData = new float[length];
    } else {
      if (length * getElementSize() < 0)
        throw new IllegalArgumentException(
            "Unable to create buffer of length " + length + " due to negative length specified");
      wrappedBuffer =
          ByteBuffer.allocateDirect(getElementSize() * length).order(ByteOrder.nativeOrder());
    }
  }
Esempio n. 7
0
  /**
   * @param data
   * @param copy
   */
  public BaseDataBuffer(double[] data, boolean copy) {
    allocationMode = Nd4j.alloc;
    if (allocationMode == AllocationMode.HEAP) {
      if (copy) {
        doubleData = ArrayUtil.copy(data);
      } else {
        this.doubleData = data;
      }
    } else {
      wrappedBuffer = ByteBuffer.allocateDirect(8 * data.length);
      wrappedBuffer.order(ByteOrder.nativeOrder());
      DoubleBuffer buffer = wrappedBuffer.asDoubleBuffer();
      for (int i = 0; i < data.length; i++) {
        buffer.put(i, data[i]);
      }
    }

    length = data.length;
    underlyingLength = data.length;
  }
Esempio n. 8
0
 private static int biTypePF(int biType) {
   ByteOrder byteOrder = ByteOrder.nativeOrder();
   switch (biType) {
     case BufferedImage.TYPE_3BYTE_BGR:
       return TJ.PF_BGR;
     case BufferedImage.TYPE_4BYTE_ABGR:
     case BufferedImage.TYPE_4BYTE_ABGR_PRE:
       return TJ.PF_XBGR;
     case BufferedImage.TYPE_BYTE_GRAY:
       return TJ.PF_GRAY;
     case BufferedImage.TYPE_INT_BGR:
       if (byteOrder == ByteOrder.BIG_ENDIAN) return TJ.PF_XBGR;
       else return TJ.PF_RGBX;
     case BufferedImage.TYPE_INT_RGB:
       if (byteOrder == ByteOrder.BIG_ENDIAN) return TJ.PF_XRGB;
       else return TJ.PF_BGRX;
     case BufferedImage.TYPE_INT_ARGB:
     case BufferedImage.TYPE_INT_ARGB_PRE:
       if (byteOrder == ByteOrder.BIG_ENDIAN) return TJ.PF_ARGB;
       else return TJ.PF_BGRA;
   }
   return 0;
 }
 static {
   m_logger = Logger.getLogger((Class) JOrbisStream.class);
   m_bigEndian = (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN);
 }
Esempio n. 10
0
  public void mainloop() {

    while (!client.isConnected()) {
      try {
        System.out.println("Connecting to " + hostname + ":" + port);
        client.connect(hostname, port);
      } catch (IOException e) {
      }
      if (!client.isConnected()) {
        System.out.println("Couldn't connect. waiting");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          run = false;
          System.exit(-1);
        }
      }
    }

    // Load the header information in one go into a bytebuffer
    byte[] rawbytebuf = new byte[BUFFERSIZE];

    int n = 0;

    try {
      n = headerReader.read(rawbytebuf);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // Byte-buffer used to parse the byte-stream. Force native ordering
    ByteBuffer hdrBuf = ByteBuffer.wrap(rawbytebuf, 0, n);
    hdrBuf.order(ByteOrder.nativeOrder());
    Header hdr = new Header(hdrBuf);
    if (VERB > 0) {
      System.out.println("Sending header: " + hdr.toString());
    }
    hdr.nSamples = 0; // reset number of samples to 0

    try {
      client.putHeader(hdr);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // Interval between sending samples to the buffer
    int pktSamples = hdr.nChans * blockSize; // number data samples in each buffer packet
    int pktBytes = pktSamples * DataType.wordSize[hdr.dataType];
    int nsamp = 0; // sample counter
    int nblk = 0;
    int nevent = 0;
    byte[] samples = new byte[pktBytes];

    // Size of the event header: type,type_numel,val,val_numel,sample,offset,duration,bufsz
    int evtHdrSz = DataType.wordSize[DataType.INT32] * 8;
    byte[] evtRawBuf = new byte[BUFFERSIZE]; // buffer to hold complete event structure

    // Byte-buffer used to parse the byte-stream. Force native ordering
    ByteBuffer evtBuf = ByteBuffer.wrap(evtRawBuf);
    evtBuf.order(ByteOrder.nativeOrder());
    int payloadSz = 0;
    int evtSample = 0;
    int evtSz = 0;
    long sample_ms = 0;
    long starttime_ms = java.lang.System.currentTimeMillis();
    long elapsed_ms = 0;
    long print_ms = 0;

    // Now do the data forwarding
    boolean eof = false;

    while (!eof
        && run) { // The run switch allows control of stopping the thread and getting out of the
      // loop
      // Read one buffer packets worth of samples
      // increment the cursor position
      if (VERB > 0 && elapsed_ms > print_ms + 500) {
        print_ms = elapsed_ms;
        System.out.println(
            nblk
                + " "
                + nsamp
                + " "
                + nevent
                + " "
                + (elapsed_ms / 1000)
                + " (blk,samp,event,sec)\r");
      }

      // read and write the samples
      try {
        n = dataReader.read(samples);
      } catch (IOException e) {
        e.printStackTrace();
      }
      if (n <= 0) {
        eof = true;
        break;
      } // stop if run out of samples

      try {
        client.putRawData(blockSize, hdr.nChans, hdr.dataType, samples);
      } catch (IOException e) {
        e.printStackTrace();
      }

      // update the sample count
      nsamp += blockSize;
      while (evtSample <= nsamp) {
        if (evtSample > 0) { // send the current event
          try {
            client.putRawEvent(evtRawBuf, 0, evtSz);
          } catch (IOException e) {
            e.printStackTrace();
          }
          nevent++;
        }

        // read the next event
        try {
          n = eventReader.read(evtRawBuf, 0, evtHdrSz); // read the fixed size header
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (n <= 0) {
          eof = true;
          break;
        }
        evtSample = ((ByteBuffer) evtBuf.position(4 * 4)).getInt(); // sample index for this event
        payloadSz = ((ByteBuffer) evtBuf.position(4 * 7)).getInt(); // payload size for this event
        evtSz = evtHdrSz + payloadSz;

        // read the variable part
        try {
          n = eventReader.read(evtRawBuf, evtHdrSz, payloadSz);
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (n <= 0) {
          eof = true;
          break;
        }

        // print the event we just read
        if (VERB > 1) {
          ByteBuffer tmpev = ByteBuffer.wrap(evtRawBuf, 0, evtSz);
          tmpev.order(evtBuf.order());
          BufferEvent evt = new BufferEvent(tmpev);
          System.out.println("Read Event: " + evt);
        }
      }

      // sleep until the next packet should be send OR EOF
      /*when to send the next sample */
      sample_ms = (long) ((float) (nsamp * 1000) / hdr.fSample / (float) speedup);
      elapsed_ms = java.lang.System.currentTimeMillis() - starttime_ms; // current time
      if (sample_ms > elapsed_ms)
        try {
          Thread.sleep(sample_ms - elapsed_ms);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      nblk++;
    }

    stop();
  }
Esempio n. 11
0
  /**
   * 描画用マテリアル情報をMQOデータから作成
   *
   * @param mqomat MQOファイルから読み込んだマテリアル情報
   * @param i_mqomat MQOファイルのマテリアル番号
   * @param mqoObjs MQOファイルのオブジェクト情報
   * @param vn 頂点法線配列
   * @return 描画用マテリアル情報
   */
  private GLMaterial makeMats(
      GL10 gl, material mqomat, int i_mqomat, objects mqoObjs, KGLPoint[] vn) {
    GLMaterial ret = new GLMaterial();
    ArrayList<KGLPoint> apv = new ArrayList<KGLPoint>();
    ArrayList<KGLPoint> apn = new ArrayList<KGLPoint>();
    ArrayList<KGLPoint> apuv = new ArrayList<KGLPoint>();
    ArrayList<KGLPoint> apc = new ArrayList<KGLPoint>();
    KGLPoint wpoint = null;
    boolean uvValid = false;
    boolean colValid = false;
    KGLPoint fn;
    float s;
    for (int f = 0; f < mqoObjs.face.length; f++) {
      if (mqoObjs.face[f].M == null) {
        continue;
      }
      if (mqoObjs.face[f].M != i_mqomat) continue;

      fn =
          calcNormal(
              mqoObjs.vertex, mqoObjs.face[f].V[0], mqoObjs.face[f].V[1], mqoObjs.face[f].V[2]);
      for (int v = 0; v < 3; v++) {
        apv.add(mqoObjs.vertex[mqoObjs.face[f].V[v]]);
        // apv.add(new KGLPoint(mqoObjs.vertex[mqoObjs.face[f].V[v]])) ;
        s =
            (float)
                Math.acos(
                    fn.X() * vn[mqoObjs.face[f].V[v]].X()
                        + fn.Y() * vn[mqoObjs.face[f].V[v]].Y()
                        + fn.Z() * vn[mqoObjs.face[f].V[v]].Z());
        if (mqoObjs.data.facet < s) {
          apn.add(fn);
        } else {
          apn.add(vn[mqoObjs.face[f].V[v]]);
        }
        wpoint = new KGLPoint(2);
        if (mqoObjs.face[f].UV == null) {
          wpoint.set_UV(0, 0);
        } else {
          wpoint.set_UV(mqoObjs.face[f].UV[v * 2 + 0], mqoObjs.face[f].UV[v * 2 + 1]);
          uvValid = true;
        }
        apuv.add(wpoint);
        wpoint = new KGLPoint(4);
        if (mqoObjs.face[f].COL == null) {
          if (mqomat.data.col == null) {
            wpoint.set_COLOR(1.0f, 1.0f, 1.0f, 1.0f);
          } else {
            wpoint.set_COLOR(
                mqomat.data.col[0], mqomat.data.col[1], mqomat.data.col[2], mqomat.data.col[3]);
          }
        } else {
          wpoint.set_COLOR(
              mqoObjs.face[f].COL[v * 4 + 0],
              mqoObjs.face[f].COL[v * 4 + 1],
              mqoObjs.face[f].COL[v * 4 + 2],
              mqoObjs.face[f].COL[v * 4 + 3]);
          colValid = true;
        }
        apc.add(wpoint);
      }
    }
    ret.texID = texPool.getGLTexture(gl, mqomat.data.tex, mqomat.data.aplane, false);
    // @@@ reload 用
    if (ret.texID != 0) {
      ret.texName = mqomat.data.tex;
      ret.alphaTexName = mqomat.data.aplane;
    } else {
      ret.texName = null;
      ret.alphaTexName = null;
    }

    if (apv.size() == 0) return null;
    uvValid &= (ret.texID != 0);
    ret.name = mqomat.name;
    // uvValid = false ;
    KGLPoint[] wfv = null;
    KGLPoint[] wfn = null;
    KGLPoint[] wft = null;
    KGLPoint[] wfc = null;
    wfv = apv.toArray(new KGLPoint[0]);
    wfn = apn.toArray(new KGLPoint[0]);
    wft = apuv.toArray(new KGLPoint[0]);
    wfc = apc.toArray(new KGLPoint[0]);
    ret.vertex_num = wfv.length;

    // @@@ interleaveFormat は無いので分ける
    ret.uvValid = uvValid;
    ret.colValid = colValid;

    ret.vertexBuffer = ByteBuffer.allocateDirect(ret.vertex_num * 3 * 4);
    ret.vertexBuffer.order(ByteOrder.nativeOrder());
    ret.vertexBuffer.position(0);

    ret.normalBuffer = ByteBuffer.allocateDirect(ret.vertex_num * 3 * 4);
    ret.normalBuffer.order(ByteOrder.nativeOrder());
    ret.normalBuffer.position(0);

    if (uvValid) {
      ret.uvBuffer = ByteBuffer.allocateDirect(ret.vertex_num * 2 * 4);
      ret.uvBuffer.order(ByteOrder.nativeOrder());
      ret.uvBuffer.position(0);
    }
    if (colValid) {
      ret.colBuffer = ByteBuffer.allocateDirect(ret.vertex_num * 4 * 4);
      ret.colBuffer.order(ByteOrder.nativeOrder());
      ret.colBuffer.position(0);
    }

    // Log.i("KGLMetaseq", "vertex_num: "+ ret.vertex_num);

    for (int v = 0; v < ret.vertex_num; v++) {
      ret.vertexBuffer.putFloat(wfv[v].X());
      ret.vertexBuffer.putFloat(wfv[v].Y());
      ret.vertexBuffer.putFloat(wfv[v].Z());

      ret.normalBuffer.putFloat(wfn[v].X());
      ret.normalBuffer.putFloat(wfn[v].Y());
      ret.normalBuffer.putFloat(wfn[v].Z());

      if (uvValid) {
        ret.uvBuffer.putFloat(wft[v].U());
        ret.uvBuffer.putFloat(wft[v].V());
      }
      if (colValid) {
        ret.colBuffer.putFloat(wfc[v].R());
        ret.colBuffer.putFloat(wfc[v].G());
        ret.colBuffer.putFloat(wfc[v].B());
        ret.colBuffer.putFloat(wfc[v].A());
      }
    }
    if (mqomat.data.col != null) {
      ret.color = new float[mqomat.data.col.length];
      for (int c = 0; c < mqomat.data.col.length; c++) {
        ret.color[c] = mqomat.data.col[c];
      }
      if (mqomat.data.dif != null) {
        ret.dif = new float[mqomat.data.col.length];
        for (int c = 0; c < mqomat.data.col.length; c++) {
          ret.dif[c] = mqomat.data.dif * mqomat.data.col[c];
        }
        // KEICHECK difでアルファ値を1未満にすると透明度が変化する?
        ret.dif[3] = mqomat.data.col[3];
      }
      if (mqomat.data.amb != null) {
        ret.amb = new float[mqomat.data.col.length];
        for (int c = 0; c < mqomat.data.col.length; c++) {
          ret.amb[c] = mqomat.data.amb * mqomat.data.col[c];
        }
      }
      if (mqomat.data.emi != null) {
        ret.emi = new float[mqomat.data.col.length];
        for (int c = 0; c < mqomat.data.col.length; c++) {
          ret.emi[c] = mqomat.data.emi * mqomat.data.col[c];
        }
      }
      if (mqomat.data.spc != null) {
        ret.spc = new float[mqomat.data.col.length];
        for (int c = 0; c < mqomat.data.col.length; c++) {
          ret.spc[c] = mqomat.data.spc * mqomat.data.col[c];
        }
      }
    }
    if (mqomat.data.pow != null) {
      ret.power = new float[1];
      ret.power[0] = mqomat.data.pow;
    }
    ret.shadeMode_IsSmooth = true; // defaultはtrue
    if (mqoObjs.data.shading == 0) ret.shadeMode_IsSmooth = false;

    return ret;
  }
 protected static CharBuffer newCharBuffer(int numElements) {
   ByteBuffer bb = ByteBuffer.allocateDirect((Character.SIZE / 8) * numElements);
   bb.order(ByteOrder.nativeOrder());
   return bb.asCharBuffer();
 }
Esempio n. 13
0
 // sets the nio wrapped buffer (allows to be overridden for other use cases like cuda)
 protected void setNioBuffer() {
   wrappedBuffer = ByteBuffer.allocateDirect(elementSize * length);
   wrappedBuffer.order(ByteOrder.nativeOrder());
 }