Java Code Examples for java.nio.FloatBuffer#array()

The following examples show how to use java.nio.FloatBuffer#array() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SmoothFilter.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public FloatBuffer filter(float sx, float sy, float base, FloatBuffer buffer, int size) {
	float[] data = buffer.array();
	float[] retval = new float[data.length];

	for (int y = this.radius; y < size - this.radius; y++) {
		for (int x = this.radius; x < size - this.radius; x++) {
			int idx = y * size + x;
			float n = 0;
			for (int i = -this.radius; i < this.radius + 1; i++) {
				for (int j = -this.radius; j < this.radius + 1; j++) {
					n += data[(y + i) * size + x + j];
				}
			}
			retval[idx] = this.effect * n / (4 * this.radius * (this.radius + 1) + 1) + (1 - this.effect) * data[idx];
		}
	}

	return FloatBuffer.wrap(retval);
}
 
Example 2
Source File: Horizon.java    From Muzesto with GNU General Public License v3.0 6 votes vote down vote up
private float[] byteToFloat(byte[] input) {
    ByteBuffer buffer = ByteBuffer.wrap(input);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    FloatBuffer floatBuffer = FloatBuffer.allocate(input.length / bytesPerSample);
    switch (bytesPerSample) {
        case 1:
            for (int i = 0; i < floatBuffer.capacity(); i++) {
                floatBuffer.put(buffer.get(i * bytesPerSample));
            }
            return floatBuffer.array();
        case 2:
            for (int i = 0; i < floatBuffer.capacity(); i++) {
                floatBuffer.put(buffer.getShort(i * bytesPerSample));
            }
            return floatBuffer.array();
        case 4:
            for (int i = 0; i < floatBuffer.capacity(); i++) {
                floatBuffer.put(buffer.getInt(i * bytesPerSample));
            }
            return floatBuffer.array();

    }
    return null;
}
 
Example 3
Source File: SmoothFilter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public FloatBuffer filter(float sx, float sy, float base, FloatBuffer buffer, int size) {
	float[] data = buffer.array();
	float[] retval = new float[data.length];

	for (int y = this.radius; y < size - this.radius; y++) {
		for (int x = this.radius; x < size - this.radius; x++) {
			int idx = y * size + x;
			float n = 0;
			for (int i = -this.radius; i < this.radius + 1; i++) {
				for (int j = -this.radius; j < this.radius + 1; j++) {
					n += data[(y + i) * size + x + j];
				}
			}
			retval[idx] = this.effect * n / (4 * this.radius * (this.radius + 1) + 1) + (1 - this.effect) * data[idx];
		}
	}

	return FloatBuffer.wrap(retval);
}
 
Example 4
Source File: ThriftBmiBridge.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static float[] bufferToFloatArray(ByteBuffer buffer) {
	buffer.order(ByteOrder.nativeOrder());
	FloatBuffer floats = buffer.asFloatBuffer();

	if (floats.hasArray()) {
		return floats.array();
	} else {
		float[] resultArray = new float[floats.capacity()];
		floats.get(resultArray);
		return resultArray;
	}
}
 
Example 5
Source File: FilteredBasis.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public FloatBuffer clip(FloatBuffer buf, int origSize, int newSize, int offset) {
	FloatBuffer result = FloatBuffer.allocate(newSize * newSize);

	float[] orig = buf.array();
	for (int i = offset; i < offset + newSize; i++) {
		result.put(orig, i * origSize + offset, newSize);
	}

	return result;
}
 
Example 6
Source File: FractalTileLoader.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private HeightMap getHeightMapAt(Vector3f location) {
    AbstractHeightMap heightmap = null;
    
    FloatBuffer buffer = this.base.getBuffer(location.x * (this.quadSize - 1), location.z * (this.quadSize - 1), 0, this.quadSize);

    float[] arr = buffer.array();
    for (int i = 0; i < arr.length; i++) {
        arr[i] = arr[i] * this.heightScale;
    }
    heightmap = new FloatBufferHeightMap(buffer);
    heightmap.load();
    return heightmap;
}
 
Example 7
Source File: PerturbFilter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public FloatBuffer filter(float sx, float sy, float base, FloatBuffer data, int workSize) {
	float[] arr = data.array();
	int origSize = (int) Math.ceil(workSize / (2 * this.magnitude + 1));
	int offset = (workSize - origSize) / 2;
	Logger.getLogger(PerturbFilter.class.getCanonicalName()).info(
			"Found origSize : " + origSize + " and offset: " + offset + " for workSize : " + workSize + " and magnitude : "
					+ this.magnitude);
	float[] retval = new float[workSize * workSize];
	float[] perturbx = new FractalSum().setOctaves(8).setScale(5f).getBuffer(sx, sy, base, workSize).array();
	float[] perturby = new FractalSum().setOctaves(8).setScale(5f).getBuffer(sx, sy, base + 1, workSize).array();
	for (int y = 0; y < workSize; y++) {
		for (int x = 0; x < workSize; x++) {
			// Perturb our coordinates
			float noisex = perturbx[y * workSize + x];
			float noisey = perturby[y * workSize + x];

			int px = (int) (origSize * noisex * this.magnitude);
			int py = (int) (origSize * noisey * this.magnitude);

			float c00 = arr[this.wrap(y - py, workSize) * workSize + this.wrap(x - px, workSize)];
			float c01 = arr[this.wrap(y - py, workSize) * workSize + this.wrap(x + px, workSize)];
			float c10 = arr[this.wrap(y + py, workSize) * workSize + this.wrap(x - px, workSize)];
			float c11 = arr[this.wrap(y + py, workSize) * workSize + this.wrap(x + px, workSize)];

			float c0 = ShaderUtils.mix(c00, c01, noisex);
			float c1 = ShaderUtils.mix(c10, c11, noisex);
			retval[y * workSize + x] = ShaderUtils.mix(c0, c1, noisey);
		}
	}
	return FloatBuffer.wrap(retval);
}
 
Example 8
Source File: FilteredBasis.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public FloatBuffer clip(FloatBuffer buf, int origSize, int newSize, int offset) {
	FloatBuffer result = FloatBuffer.allocate(newSize * newSize);

	float[] orig = buf.array();
	for (int i = offset; i < offset + newSize; i++) {
		result.put(orig, i * origSize + offset, newSize);
	}

	return result;
}
 
Example 9
Source File: FloatPointer.java    From tapir with MIT License 5 votes vote down vote up
/**
 * For direct buffers, calls {@link Pointer#Pointer(Buffer)}, while for buffers
 * backed with an array, allocates enough memory for the array and copies it.
 *
 * @param buffer the Buffer to reference or copy
 * @see #put(float[])
 */
public FloatPointer(FloatBuffer buffer) {
    super(buffer);
    if (buffer != null && buffer.hasArray()) {
        float[] array = buffer.array();
        allocateArray(array.length);
        put(array);
        position(buffer.position());
        limit(buffer.limit());
    }
}
 
Example 10
Source File: FractalTileLoader.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private HeightMap getHeightMapAt(Vector3f location) {
    AbstractHeightMap heightmap = null;
    
    FloatBuffer buffer = this.base.getBuffer(location.x * (this.quadSize - 1), location.z * (this.quadSize - 1), 0, this.quadSize);

    float[] arr = buffer.array();
    for (int i = 0; i < arr.length; i++) {
        arr[i] = arr[i] * this.heightScale;
    }
    heightmap = new FloatBufferHeightMap(buffer);
    heightmap.load();
    return heightmap;
}
 
Example 11
Source File: HydraulicErodeFilter.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public FloatBuffer filter(float sx, float sy, float base, FloatBuffer buffer, int workSize) {
	float[] ga = buffer.array();
	// float[] wa = this.waterMap.getBuffer(sx, sy, base, workSize).array();
	// float[] sa = this.sedimentMap.getBuffer(sx, sy, base,
	// workSize).array();
	float[] wt = new float[workSize * workSize];
	float[] st = new float[workSize * workSize];

	int[] idxrel = { -workSize - 1, -workSize + 1, workSize - 1, workSize + 1 };

	// step 1. water arrives and step 2. captures material
	for (int y = 0; y < workSize; y++) {
		for (int x = 0; x < workSize; x++) {
			int idx = y * workSize + x;
			float wtemp = this.Kr; // * wa[idx];
			float stemp = this.Ks; // * sa[idx];
			if (wtemp > 0) {
				wt[idx] += wtemp;
				if (stemp > 0) {
					ga[idx] -= stemp * wt[idx];
					st[idx] += stemp * wt[idx];
				}
			}

			// step 3. water is transported to it's neighbours
			float a = ga[idx] + wt[idx];
			// float[] aj = new float[idxrel.length];
			float amax = 0;
			int amaxidx = -1;
			float ac = 0;
			float dtotal = 0;

			for (int j = 0; j < idxrel.length; j++) {
				if (idx + idxrel[j] > 0 && idx + idxrel[j] < workSize) {
					float at = ga[idx + idxrel[j]] + wt[idx + idxrel[j]];
					if (a - at > a - amax) {
						dtotal += at;
						amax = at;
						amaxidx = j;
						ac++;
					}
				}
			}

			float aa = (dtotal + a) / (ac + 1);
			// for (int j = 0; j < idxrel.length; j++) {
			// if (idx + idxrel[j] > 0 && idx + idxrel[j] < workSize && a -
			// aj[j] > 0) {
			if (amaxidx > -1) {
				float dwj = Math.min(wt[idx], a - aa) * (a - amax) / dtotal;
				float dsj = st[idx] * dwj / wt[idx];
				wt[idx] -= dwj;
				st[idx] -= dsj;
				wt[idx + idxrel[amaxidx]] += dwj;
				st[idx + idxrel[amaxidx]] += dsj;
			}
			// }

			// step 4. water evaporates and deposits material
			wt[idx] = wt[idx] * (1 - this.Ke);
			if (wt[idx] < this.T) {
				wt[idx] = 0;
			}
			float smax = this.Kc * wt[idx];
			if (st[idx] > smax) {
				ga[idx] += st[idx] - smax;
				st[idx] -= st[idx] - smax;
			}
		}
	}

	return buffer;
}
 
Example 12
Source File: PrimitiveSolids.java    From Robot-Overlord-App with GNU General Public License v2.0 4 votes vote down vote up
/**
 * draw a sphere with a given radius.
 * TODO expose quality parameters?
 * TODO generate a sphere once as a model, return that.
 * See https://www.gamedev.net/forums/topic/537269-procedural-sphere-creation/4469427/
 * @param gl2
 * @param radius
 */
static public void drawSphere(GL2 gl2,double radius) {
	int width = 32;
	int height = 16;
	
	double theta, phi;
	int i, j, t;

	int nvec = (height-2)* width + 2;
	int ntri = (height-2)*(width-1)*2;

	FloatBuffer vertices = FloatBuffer.allocate(nvec * 3);
	IntBuffer indexes = IntBuffer.allocate(ntri * 3);

	float [] dat = vertices.array();
	int   [] idx = indexes.array();
	
	for( t=0, j=1; j<height-1; j++ ) {
		for(i=0; i<width; i++ )  {
			theta = (double)(j)/(double)(height-1) * Math.PI;
			phi   = (double)(i)/(double)(width-1 ) * Math.PI*2;

			dat[t++] = (float)( Math.sin(theta) * Math.cos(phi));
			dat[t++] = (float)( Math.cos(theta));
			dat[t++] = (float)(-Math.sin(theta) * Math.sin(phi));
		}
	}
	dat[t++]= 0;
	dat[t++]= 1;
	dat[t++]= 0;
	dat[t++]= 0;
	dat[t++]=-1;
	dat[t++]= 0;
	
	for( t=0, j=0; j<height-3; j++ ) {
		for(      i=0; i<width-1; i++ )  {
			idx[t++] = (j  )*width + i  ;
			idx[t++] = (j+1)*width + i+1;
			idx[t++] = (j  )*width + i+1;
			idx[t++] = (j  )*width + i  ;
			idx[t++] = (j+1)*width + i  ;
			idx[t++] = (j+1)*width + i+1;
		}
	}
	for( i=0; i<width-1; i++ )  {
		idx[t++] = (height-2)*width;
		idx[t++] = i;
		idx[t++] = i+1;
		idx[t++] = (height-2)*width+1;
		idx[t++] = (height-3)*width + i+1;
		idx[t++] = (height-3)*width + i;
	}

	int NUM_BUFFERS=1;
	int[] VBO = new int[NUM_BUFFERS];
	gl2.glGenBuffers(NUM_BUFFERS, VBO, 0);
	gl2.glBindBuffer(GL2.GL_ARRAY_BUFFER, VBO[0]);
    // Write out vertex buffer to the currently bound VBO.
	int s=(Float.SIZE/8);  // bits per float / bits per byte = bytes per float
    gl2.glBufferData(GL2.GL_ARRAY_BUFFER, dat.length*s, vertices, GL2.GL_STATIC_DRAW);
    
    
	gl2.glEnableClientState(GL2.GL_VERTEX_ARRAY);
	gl2.glVertexPointer(3,GL2.GL_FLOAT,0,0);
	
	gl2.glEnableClientState(GL2.GL_NORMAL_ARRAY);
	gl2.glNormalPointer(GL2.GL_FLOAT,0,0);

	gl2.glPushMatrix();
	gl2.glScaled(radius,radius,radius);
	gl2.glDrawElements(GL2.GL_TRIANGLES, ntri*3, GL2.GL_UNSIGNED_INT, indexes );
	gl2.glPopMatrix();
	
	gl2.glDisableClientState(GL2.GL_NORMAL_ARRAY);
	gl2.glDisableClientState(GL2.GL_VERTEX_ARRAY);
	
	gl2.glDeleteBuffers(NUM_BUFFERS, VBO, 0);
}
 
Example 13
Source File: ThermalErodeFilter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public FloatBuffer filter(float sx, float sy, float base, FloatBuffer buffer, int workSize) {
	float[] ga = buffer.array();
	float[] sa = new float[workSize * workSize];

	int[] idxrel = { -workSize - 1, -workSize + 1, workSize - 1, workSize + 1 };

	for (int y = 0; y < workSize; y++) {
		for (int x = 0; x < workSize; x++) {
			int idx = y * workSize + x;
			ga[idx] += sa[idx];
			sa[idx] = 0;

			float[] deltas = new float[idxrel.length];
			float deltaMax = this.talus;
			float deltaTotal = 0;

			for (int j = 0; j < idxrel.length; j++) {
				if (idx + idxrel[j] > 0 && idx + idxrel[j] < ga.length) {
					float dj = ga[idx] - ga[idx + idxrel[j]];
					if (dj > this.talus) {
						deltas[j] = dj;
						deltaTotal += dj;
						if (dj > deltaMax) {
							deltaMax = dj;
						}
					}
				}
			}

			for (int j = 0; j < idxrel.length; j++) {
				if (deltas[j] != 0) {
					float d = this.c * (deltaMax - this.talus) * deltas[j] / deltaTotal;
					if (d > ga[idx] + sa[idx]) {
						d = ga[idx] + sa[idx];
					}
					sa[idx] -= d;
					sa[idx + idxrel[j]] += d;
				}
				deltas[j] = 0;
			}
		}
	}

	return buffer;
}
 
Example 14
Source File: SkeletonControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void softwareSkinUpdate(Mesh mesh, Matrix4f[] offsetMatrices) {
        int maxWeightsPerVert = mesh.getMaxNumWeights();
        int fourMinusMaxWeights = 4 - maxWeightsPerVert;

        // NOTE: This code assumes the vertex buffer is in bind pose
        // resetToBind() has been called this frame
        VertexBuffer vb = mesh.getBuffer(VertexBuffer.Type.Position);
        FloatBuffer fvb = (FloatBuffer) vb.getData();
        fvb.rewind();

        VertexBuffer nb = mesh.getBuffer(VertexBuffer.Type.Normal);
        FloatBuffer fnb = (FloatBuffer) nb.getData();
        fnb.rewind();

        // get boneIndexes and weights for mesh
        ByteBuffer ib = (ByteBuffer) mesh.getBuffer(VertexBuffer.Type.BoneIndex).getData();
        FloatBuffer wb = (FloatBuffer) mesh.getBuffer(VertexBuffer.Type.BoneWeight).getData();

        ib.rewind();
        wb.rewind();

        float[] weights = wb.array();
        byte[] indices = ib.array();
        int idxWeights = 0;

        TempVars vars = TempVars.get();
        float[] posBuf = vars.skinPositions;
        float[] normBuf = vars.skinNormals;

        int iterations = (int) FastMath.ceil(fvb.capacity() / ((float) posBuf.length));
        int bufLength = posBuf.length * 3;
        for (int i = iterations - 1; i >= 0; i--) {
            // read next set of positions and normals from native buffer
            bufLength = Math.min(posBuf.length, fvb.remaining());
            fvb.get(posBuf, 0, bufLength);
            fnb.get(normBuf, 0, bufLength);
            int verts = bufLength / 3;
            int idxPositions = 0;

            // iterate vertices and apply skinning transform for each effecting bone
            for (int vert = verts - 1; vert >= 0; vert--) {
                float nmx = normBuf[idxPositions];
                float vtx = posBuf[idxPositions++];
                float nmy = normBuf[idxPositions];
                float vty = posBuf[idxPositions++];
                float nmz = normBuf[idxPositions];
                float vtz = posBuf[idxPositions++];

                float rx = 0, ry = 0, rz = 0, rnx = 0, rny = 0, rnz = 0;

                for (int w = maxWeightsPerVert - 1; w >= 0; w--) {
                    float weight = weights[idxWeights];
                    Matrix4f mat = offsetMatrices[indices[idxWeights++]];

                    rx += (mat.m00 * vtx + mat.m01 * vty + mat.m02 * vtz + mat.m03) * weight;
                    ry += (mat.m10 * vtx + mat.m11 * vty + mat.m12 * vtz + mat.m13) * weight;
                    rz += (mat.m20 * vtx + mat.m21 * vty + mat.m22 * vtz + mat.m23) * weight;

                    rnx += (nmx * mat.m00 + nmy * mat.m01 + nmz * mat.m02) * weight;
                    rny += (nmx * mat.m10 + nmy * mat.m11 + nmz * mat.m12) * weight;
                    rnz += (nmx * mat.m20 + nmy * mat.m21 + nmz * mat.m22) * weight;
                }

                idxWeights += fourMinusMaxWeights;

                idxPositions -= 3;
                normBuf[idxPositions] = rnx;
                posBuf[idxPositions++] = rx;
                normBuf[idxPositions] = rny;
                posBuf[idxPositions++] = ry;
                normBuf[idxPositions] = rnz;
                posBuf[idxPositions++] = rz;
            }


            fvb.position(fvb.position() - bufLength);
            fvb.put(posBuf, 0, bufLength);
            fnb.position(fnb.position() - bufLength);
            fnb.put(normBuf, 0, bufLength);
        }

        vb.updateData(fvb);
        nb.updateData(fnb);

//        mesh.updateBound();
    }
 
Example 15
Source File: HydraulicErodeFilter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public FloatBuffer filter(float sx, float sy, float base, FloatBuffer buffer, int workSize) {
	float[] ga = buffer.array();
	// float[] wa = this.waterMap.getBuffer(sx, sy, base, workSize).array();
	// float[] sa = this.sedimentMap.getBuffer(sx, sy, base,
	// workSize).array();
	float[] wt = new float[workSize * workSize];
	float[] st = new float[workSize * workSize];

	int[] idxrel = { -workSize - 1, -workSize + 1, workSize - 1, workSize + 1 };

	// step 1. water arrives and step 2. captures material
	for (int y = 0; y < workSize; y++) {
		for (int x = 0; x < workSize; x++) {
			int idx = y * workSize + x;
			float wtemp = this.Kr; // * wa[idx];
			float stemp = this.Ks; // * sa[idx];
			if (wtemp > 0) {
				wt[idx] += wtemp;
				if (stemp > 0) {
					ga[idx] -= stemp * wt[idx];
					st[idx] += stemp * wt[idx];
				}
			}

			// step 3. water is transported to its neighbours
			float a = ga[idx] + wt[idx];
			// float[] aj = new float[idxrel.length];
			float amax = 0;
			int amaxidx = -1;
			float ac = 0;
			float dtotal = 0;

			for (int j = 0; j < idxrel.length; j++) {
				if (idx + idxrel[j] > 0 && idx + idxrel[j] < workSize) {
					float at = ga[idx + idxrel[j]] + wt[idx + idxrel[j]];
					if (a - at > a - amax) {
						dtotal += at;
						amax = at;
						amaxidx = j;
						ac++;
					}
				}
			}

			float aa = (dtotal + a) / (ac + 1);
			// for (int j = 0; j < idxrel.length; j++) {
			// if (idx + idxrel[j] > 0 && idx + idxrel[j] < workSize && a -
			// aj[j] > 0) {
			if (amaxidx > -1) {
				float dwj = Math.min(wt[idx], a - aa) * (a - amax) / dtotal;
				float dsj = st[idx] * dwj / wt[idx];
				wt[idx] -= dwj;
				st[idx] -= dsj;
				wt[idx + idxrel[amaxidx]] += dwj;
				st[idx + idxrel[amaxidx]] += dsj;
			}
			// }

			// step 4. water evaporates and deposits material
			wt[idx] = wt[idx] * (1 - this.Ke);
			if (wt[idx] < this.T) {
				wt[idx] = 0;
			}
			float smax = this.Kc * wt[idx];
			if (st[idx] > smax) {
				ga[idx] += st[idx] - smax;
				st[idx] -= st[idx] - smax;
			}
		}
	}

	return buffer;
}
 
Example 16
Source File: OptimizedErode.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public FloatBuffer filter(float sx, float sy, float base, FloatBuffer buffer, int size) {
	float[] tmp = buffer.array();
	float[] retval = new float[tmp.length];

	for (int y = this.radius + 1; y < size - this.radius; y++) {
		for (int x = this.radius + 1; x < size - this.radius; x++) {
			int idx = y * size + x;
			float h = tmp[idx];

			float horizAvg = 0;
			int horizCount = 0;
			float vertAvg = 0;
			int vertCount = 0;

			boolean horizT = false;
			boolean vertT = false;

			for (int i = 0; i >= -this.radius; i--) {
				int idxV = (y + i) * size + x;
				int idxVL = (y + i - 1) * size + x;
				int idxH = y * size + x + i;
				int idxHL = y * size + x + i - 1;
				float hV = tmp[idxV];
				float hH = tmp[idxH];

				if (Math.abs(h - hV) > this.talus && Math.abs(h - tmp[idxVL]) > this.talus || vertT) {
					vertT = true;
				} else {
					if (Math.abs(h - hV) <= this.talus) {
						vertAvg += hV;
						vertCount++;
					}
				}

				if (Math.abs(h - hH) > this.talus && Math.abs(h - tmp[idxHL]) > this.talus || horizT) {
					horizT = true;
				} else {
					if (Math.abs(h - hH) <= this.talus) {
						horizAvg += hH;
						horizCount++;
					}
				}
			}

			retval[idx] = 0.5f * (vertAvg / (vertCount > 0 ? vertCount : 1) + horizAvg / (horizCount > 0 ? horizCount : 1));
		}
	}
	return FloatBuffer.wrap(retval);
}
 
Example 17
Source File: ThermalErodeFilter.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public FloatBuffer filter(float sx, float sy, float base, FloatBuffer buffer, int workSize) {
	float[] ga = buffer.array();
	float[] sa = new float[workSize * workSize];

	int[] idxrel = { -workSize - 1, -workSize + 1, workSize - 1, workSize + 1 };

	for (int y = 0; y < workSize; y++) {
		for (int x = 0; x < workSize; x++) {
			int idx = y * workSize + x;
			ga[idx] += sa[idx];
			sa[idx] = 0;

			float[] deltas = new float[idxrel.length];
			float deltaMax = this.talus;
			float deltaTotal = 0;

			for (int j = 0; j < idxrel.length; j++) {
				if (idx + idxrel[j] > 0 && idx + idxrel[j] < ga.length) {
					float dj = ga[idx] - ga[idx + idxrel[j]];
					if (dj > this.talus) {
						deltas[j] = dj;
						deltaTotal += dj;
						if (dj > deltaMax) {
							deltaMax = dj;
						}
					}
				}
			}

			for (int j = 0; j < idxrel.length; j++) {
				if (deltas[j] != 0) {
					float d = this.c * (deltaMax - this.talus) * deltas[j] / deltaTotal;
					if (d > ga[idx] + sa[idx]) {
						d = ga[idx] + sa[idx];
					}
					sa[idx] -= d;
					sa[idx + idxrel[j]] += d;
				}
				deltas[j] = 0;
			}
		}
	}

	return buffer;
}
 
Example 18
Source File: TestCustomAnim.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void simpleInitApp() {

	AmbientLight al = new AmbientLight();
	rootNode.addLight(al);

	DirectionalLight dl = new DirectionalLight();
	dl.setDirection(Vector3f.UNIT_XYZ.negate());
	rootNode.addLight(dl);

	Box box = new Box(1, 1, 1);

	VertexBuffer weightsHW = new VertexBuffer(Type.HWBoneWeight);
	VertexBuffer indicesHW = new VertexBuffer(Type.HWBoneIndex);
	indicesHW.setUsage(Usage.CpuOnly);
	weightsHW.setUsage(Usage.CpuOnly);
	box.setBuffer(weightsHW);
	box.setBuffer(indicesHW);

	// Setup bone weight buffer
	FloatBuffer weights = FloatBuffer.allocate(box.getVertexCount() * 4);
	VertexBuffer weightsBuf = new VertexBuffer(Type.BoneWeight);
	weightsBuf.setupData(Usage.CpuOnly, 4, Format.Float, weights);
	box.setBuffer(weightsBuf);

	// Setup bone index buffer
	ByteBuffer indices = ByteBuffer.allocate(box.getVertexCount() * 4);
	VertexBuffer indicesBuf = new VertexBuffer(Type.BoneIndex);
	indicesBuf.setupData(Usage.CpuOnly, 4, Format.UnsignedByte, indices);
	box.setBuffer(indicesBuf);

	// Create bind pose buffers
	box.generateBindPose();

	// Create skeleton
	bone = new Joint("root");
	bone.setLocalTransform(new Transform(Vector3f.ZERO, Quaternion.IDENTITY, Vector3f.UNIT_XYZ));
	armature = new Armature(new Joint[] { bone });

	// Assign all verticies to bone 0 with weight 1
	for (int i = 0; i < box.getVertexCount() * 4; i += 4) {
		// assign vertex to bone index 0
		indices.array()[i + 0] = 0;
		indices.array()[i + 1] = 0;
		indices.array()[i + 2] = 0;
		indices.array()[i + 3] = 0;

		// set weight to 1 only for first entry
		weights.array()[i + 0] = 1;
		weights.array()[i + 1] = 0;
		weights.array()[i + 2] = 0;
		weights.array()[i + 3] = 0;
	}

	// Maximum number of weights per bone is 1
	box.setMaxNumWeights(1);

	// Create model
	Geometry geom = new Geometry("box", box);
	geom.setMaterial(assetManager.loadMaterial("Textures/Terrain/BrickWall/BrickWall.j3m"));
	Node model = new Node("model");
	model.attachChild(geom);

	// Create skeleton control
	SkinningControl skinningControl = new SkinningControl(armature);
	model.addControl(skinningControl);

	rootNode.attachChild(model);
}
 
Example 19
Source File: SkeletonControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Method to apply skinning transforms to a mesh's buffers
 *
 * @param mesh the mesh
 * @param offsetMatrices the offset matices to apply
 */
private void applySkinning(Mesh mesh, Matrix4f[] offsetMatrices) {
    int maxWeightsPerVert = mesh.getMaxNumWeights();
    if (maxWeightsPerVert <= 0) {
        throw new IllegalStateException("Max weights per vert is incorrectly set!");
    }
    int fourMinusMaxWeights = 4 - maxWeightsPerVert;

    // NOTE: This code assumes the vertex buffer is in bind pose
    // resetToBind() has been called this frame
    VertexBuffer vb = mesh.getBuffer(Type.Position);
    FloatBuffer fvb = (FloatBuffer) vb.getData();
    fvb.rewind();

    VertexBuffer nb = mesh.getBuffer(Type.Normal);
    FloatBuffer fnb = (FloatBuffer) nb.getData();
    fnb.rewind();

    // get boneIndexes and weights for mesh
    IndexBuffer ib = IndexBuffer.wrapIndexBuffer(mesh.getBuffer(Type.BoneIndex).getData());
    FloatBuffer wb = (FloatBuffer) mesh.getBuffer(Type.BoneWeight).getData();

    wb.rewind();

    float[] weights = wb.array();
    int idxWeights = 0;

    TempVars vars = TempVars.get();

    float[] posBuf = vars.skinPositions;
    float[] normBuf = vars.skinNormals;

    int iterations = (int) FastMath.ceil(fvb.limit() / ((float) posBuf.length));
    int bufLength = posBuf.length;
    for (int i = iterations - 1; i >= 0; i--) {
        // read next set of positions and normals from native buffer
        bufLength = Math.min(posBuf.length, fvb.remaining());
        fvb.get(posBuf, 0, bufLength);
        fnb.get(normBuf, 0, bufLength);
        int verts = bufLength / 3;
        int idxPositions = 0;

        // iterate vertices and apply skinning transform for each effecting bone
        for (int vert = verts - 1; vert >= 0; vert--) {
            // Skip this vertex if the first weight is zero.
            if (weights[idxWeights] == 0) {
                idxPositions += 3;
                idxWeights += 4;
                continue;
            }

            float nmx = normBuf[idxPositions];
            float vtx = posBuf[idxPositions++];
            float nmy = normBuf[idxPositions];
            float vty = posBuf[idxPositions++];
            float nmz = normBuf[idxPositions];
            float vtz = posBuf[idxPositions++];

            float rx = 0, ry = 0, rz = 0, rnx = 0, rny = 0, rnz = 0;

            for (int w = maxWeightsPerVert - 1; w >= 0; w--) {
                float weight = weights[idxWeights];
                Matrix4f mat = offsetMatrices[ib.get(idxWeights++)];

                rx += (mat.m00 * vtx + mat.m01 * vty + mat.m02 * vtz + mat.m03) * weight;
                ry += (mat.m10 * vtx + mat.m11 * vty + mat.m12 * vtz + mat.m13) * weight;
                rz += (mat.m20 * vtx + mat.m21 * vty + mat.m22 * vtz + mat.m23) * weight;

                rnx += (nmx * mat.m00 + nmy * mat.m01 + nmz * mat.m02) * weight;
                rny += (nmx * mat.m10 + nmy * mat.m11 + nmz * mat.m12) * weight;
                rnz += (nmx * mat.m20 + nmy * mat.m21 + nmz * mat.m22) * weight;
            }

            idxWeights += fourMinusMaxWeights;

            idxPositions -= 3;
            normBuf[idxPositions] = rnx;
            posBuf[idxPositions++] = rx;
            normBuf[idxPositions] = rny;
            posBuf[idxPositions++] = ry;
            normBuf[idxPositions] = rnz;
            posBuf[idxPositions++] = rz;
        }

        fvb.position(fvb.position() - bufLength);
        fvb.put(posBuf, 0, bufLength);
        fnb.position(fnb.position() - bufLength);
        fnb.put(normBuf, 0, bufLength);
    }

    vars.release();

    vb.updateData(fvb);
    nb.updateData(fnb);

}
 
Example 20
Source File: JTensor.java    From zoltar with Apache License 2.0 4 votes vote down vote up
/**
 * Create a new {@link JTensor} instance by extracting data from the underlying {@link Tensor} and
 * closing it afterwards.
 */
public static JTensor create(final Tensor<?> tensor) {
  final JTensor jt;
  try {
    switch (tensor.dataType()) {
      case STRING:
        if (tensor.numDimensions() == 0) {
          final String value = new String(tensor.bytesValue(), UTF_8);
          jt =
              new AutoValue_JTensor(
                  tensor.dataType(), tensor.numDimensions(), tensor.shape(), value);
        } else {
          final int[] dimensions = toIntExact(tensor.shape());
          final Object byteArray =
              tensor.copyTo(Array.newInstance(byte[].class, toIntExact(tensor.shape())));
          jt =
              new AutoValue_JTensor(
                  tensor.dataType(),
                  tensor.numDimensions(),
                  tensor.shape(),
                  toStringArray(byteArray, tensor.numElements(), dimensions));
        }
        break;
      case INT32:
        final IntBuffer intBuf = IntBuffer.allocate(tensor.numElements());
        tensor.writeTo(intBuf);
        jt =
            new AutoValue_JTensor(
                tensor.dataType(), tensor.numDimensions(), tensor.shape(), intBuf.array());
        break;
      case INT64:
        final LongBuffer longBuf = LongBuffer.allocate(tensor.numElements());
        tensor.writeTo(longBuf);
        jt =
            new AutoValue_JTensor(
                tensor.dataType(), tensor.numDimensions(), tensor.shape(), longBuf.array());
        break;
      case FLOAT:
        final FloatBuffer floatBuf = FloatBuffer.allocate(tensor.numElements());
        tensor.writeTo(floatBuf);
        jt =
            new AutoValue_JTensor(
                tensor.dataType(), tensor.numDimensions(), tensor.shape(), floatBuf.array());
        break;
      case DOUBLE:
        final DoubleBuffer doubleBuf = DoubleBuffer.allocate(tensor.numElements());
        tensor.writeTo(doubleBuf);
        jt =
            new AutoValue_JTensor(
                tensor.dataType(), tensor.numDimensions(), tensor.shape(), doubleBuf.array());
        break;
      case BOOL:
        final boolean[] array = new boolean[tensor.numElements()];
        tensor.copyTo(array);
        jt =
            new AutoValue_JTensor(
                tensor.dataType(), tensor.numDimensions(), tensor.shape(), array);
        break;
      default:
        throw new IllegalStateException("Unsupported data type " + tensor.dataType());
    }
  } finally {
    tensor.close();
  }

  return jt;
}