Java Code Examples for com.jme3.util.TempVars#release()

The following examples show how to use com.jme3.util.TempVars#release() . 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: AnimControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Internal use only.
 */
@Override
protected void controlUpdate(float tpf) {
    if (skeleton != null) {
        skeleton.reset(); // reset skeleton to bind pose
    }

    TempVars vars = TempVars.get();
    for (int i = 0; i < channels.size(); i++) {
        channels.get(i).update(tpf, vars);
    }
    vars.release();

    if (skeleton != null) {
        skeleton.updateWorldVectors();
    }
}
 
Example 2
Source File: BetterCharacterControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test whether the character is on the ground, by means of a ray test.
 */
protected void checkOnGround() {
    TempVars vars = TempVars.get();
    Vector3f location = vars.vect1;
    Vector3f rayVector = vars.vect2;
    float height = getFinalHeight();
    location.set(localUp).multLocal(height).addLocal(this.location);
    rayVector.set(localUp).multLocal(-height - 0.1f).addLocal(location);
    List<PhysicsRayTestResult> results = space.rayTest(location, rayVector);
    vars.release();
    for (PhysicsRayTestResult physicsRayTestResult : results) {
        if (!physicsRayTestResult.getCollisionObject().equals(rigidBody)) {
            onGround = true;
            return;
        }
    }
    onGround = false;
}
 
Example 3
Source File: BIHTree.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int sortTriangles(int l, int r, float split, int axis) {
    int pivot = l;
    int j = r;

    TempVars vars = TempVars.get();

    Vector3f v1 = vars.vect1,
            v2 = vars.vect2,
            v3 = vars.vect3;

    while (pivot <= j) {
        getTriangle(pivot, v1, v2, v3);
        v1.addLocal(v2).addLocal(v3).multLocal(FastMath.ONE_THIRD);
        if (v1.get(axis) > split) {
            swapTriangles(pivot, j);
            --j;
        } else {
            ++pivot;
        }
    }

    vars.release();
    pivot = (pivot == l && j < pivot) ? j : pivot;
    return pivot;
}
 
Example 4
Source File: CameraControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void controlUpdate(float tpf) {
    if (spatial != null && camera != null) {
        switch (controlDir) {
            case SpatialToCamera:
                camera.setLocation(spatial.getWorldTranslation());
                camera.setRotation(spatial.getWorldRotation());
                break;
            case CameraToSpatial:
                // set the localtransform, so that the worldtransform would be equal to the camera's transform.
                // Location:
                TempVars vars = TempVars.get();

                Vector3f vecDiff = vars.vect1.set(camera.getLocation()).subtractLocal(spatial.getWorldTranslation());
                spatial.setLocalTranslation(vecDiff.addLocal(spatial.getLocalTranslation()));

                // Rotation:
                Quaternion worldDiff = vars.quat1.set(camera.getRotation()).subtractLocal(spatial.getWorldRotation());
                spatial.setLocalRotation(worldDiff.addLocal(spatial.getLocalRotation()));
                vars.release();
                break;
        }
    }
}
 
Example 5
Source File: DebugShapeFactory.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Create a debug spatial from the specified collision shape.
 * <p>
 * This is mostly used internally. To attach a debug shape to a physics
 * object, call <code>attachDebugShape(AssetManager manager);</code> on it.
 *
 * @param collisionShape the shape to visualize (may be null, unaffected)
 * @return a new tree of geometries, or null
 */
public static Spatial getDebugShape(CollisionShape collisionShape) {
    if (collisionShape == null) {
        return null;
    }
    Spatial debugShape;
    if (collisionShape instanceof CompoundCollisionShape) {
        CompoundCollisionShape shape = (CompoundCollisionShape) collisionShape;
        List<ChildCollisionShape> children = shape.getChildren();
        Node node = new Node("DebugShapeNode");
        for (Iterator<ChildCollisionShape> it = children.iterator(); it.hasNext();) {
            ChildCollisionShape childCollisionShape = it.next();
            CollisionShape ccollisionShape = childCollisionShape.shape;
            Geometry geometry = createDebugShape(ccollisionShape);

            // apply translation
            geometry.setLocalTranslation(childCollisionShape.location);

            // apply rotation
            TempVars vars = TempVars.get();                
            Matrix3f tempRot = vars.tempMat3;

            tempRot.set(geometry.getLocalRotation());
            childCollisionShape.rotation.mult(tempRot, tempRot);
            geometry.setLocalRotation(tempRot);

            vars.release();

            node.attachChild(geometry);
        }
        debugShape = node;
    } else {
        debugShape = createDebugShape(collisionShape);
    }
    if (debugShape == null) {
        return null;
    }
    debugShape.updateGeometricState();
    return debugShape;
}
 
Example 6
Source File: BIHTree.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private int collideWithRay(Ray r,
        Matrix4f worldMatrix,
        BoundingVolume worldBound,
        CollisionResults results) {

    TempVars vars = TempVars.get();
    try {
        CollisionResults boundResults = vars.collisionResults;
        boundResults.clear();
        worldBound.collideWith(r, boundResults);
        if (boundResults.size() > 0) {
            float tMin = boundResults.getClosestCollision().getDistance();
            float tMax = boundResults.getFarthestCollision().getDistance();

            if (tMax <= 0) {
                tMax = Float.POSITIVE_INFINITY;
            } else if (tMin == tMax) {
                tMin = 0;
            }

            if (tMin <= 0) {
                tMin = 0;
            }

            if (r.getLimit() < Float.POSITIVE_INFINITY) {
                tMax = Math.min(tMax, r.getLimit());
                if (tMin > tMax){
                    return 0;
                }
            }

//            return root.intersectBrute(r, worldMatrix, this, tMin, tMax, results);
            return root.intersectWhere(r, worldMatrix, this, tMin, tMax, results);
        }
        return 0;
    } finally {
        vars.release();
    }
}
 
Example 7
Source File: Line.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Calculate the squared distance from this line to the specified point.
 *
 * @param point location vector of the input point (not null, unaffected)
 * @return the square of the minimum distance (&ge;0)
 */
public float distanceSquared(Vector3f point) {
    TempVars vars = TempVars.get();

    Vector3f compVec1 = vars.vect1;
    Vector3f compVec2 = vars.vect2;

    point.subtract(origin, compVec1);
    float lineParameter = direction.dot(compVec1);
    origin.add(direction.mult(lineParameter, compVec2), compVec2);
    compVec2.subtract(point, compVec1);
    float len = compVec1.lengthSquared();
    vars.release();
    return len;
}
 
Example 8
Source File: TestTempVars.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void methodThatUsesTempVars() {
    TempVars vars = TempVars.get();
    {
        vars.vect1.set(0.1f, 0.2f, 0.3f);
        sumCompute.addLocal(vars.vect1);
    }
    vars.release();
}
 
Example 9
Source File: TestTempVars.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void recursiveMethod(int recurse) {
    TempVars vars = TempVars.get();
    {
        vars.vect1.set(0.1f, 0.2f, 0.3f);

        if (recurse < 4) {
            recursiveMethod(recurse + 1);
        }

        sumCompute.addLocal(vars.vect1);
    }
    vars.release();
}
 
Example 10
Source File: Skeleton.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Compute the skinning matrices for each bone of the skeleton that would be used to transform vertices of associated meshes
 * @return the pre-existing matrices
 */
public Matrix4f[] computeSkinningMatrices() {
    TempVars vars = TempVars.get();
    for (int i = 0; i < boneList.length; i++) {
        boneList[i].getOffsetTransform(skinningMatrixes[i], vars.quat1, vars.vect1, vars.vect2, vars.tempMat3);
    }
    vars.release();
    return skinningMatrixes;
}
 
Example 11
Source File: Spatial.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Rotates the spatial by the xAngle, yAngle and zAngle angles (in radians),
 * (aka pitch, yaw, roll) in the local coordinate space.
 *
 * @return The spatial on which this method is called, e.g <code>this</code>.
 */
public Spatial rotate(float xAngle, float yAngle, float zAngle) {
    TempVars vars = TempVars.get();
    Quaternion q = vars.quat1;
    q.fromAngles(xAngle, yAngle, zAngle);
    rotate(q);
    vars.release();

    return this;
}
 
Example 12
Source File: BoundingBox.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public BoundingVolume transform(Matrix4f trans, BoundingVolume store) {
    BoundingBox box;
    if (store == null || store.getType() != Type.AABB) {
        box = new BoundingBox();
    } else {
        box = (BoundingBox) store;
    }
    TempVars vars = TempVars.get();

    float w = trans.multProj(center, box.center);
    box.center.divideLocal(w);

    Matrix3f transMatrix = vars.tempMat3;
    trans.toRotationMatrix(transMatrix);

    // Make the rotation matrix all positive to get the maximum x/y/z extent
    transMatrix.absoluteLocal();

    vars.vect1.set(xExtent, yExtent, zExtent);
    transMatrix.mult(vars.vect1, vars.vect1);

    // Assign the biggest rotations after scales.
    box.xExtent = FastMath.abs(vars.vect1.getX());
    box.yExtent = FastMath.abs(vars.vect1.getY());
    box.zExtent = FastMath.abs(vars.vect1.getZ());

    vars.release();

    return box;
}
 
Example 13
Source File: Quaternion.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * <code>toRotationMatrix</code> converts this quaternion to a rotational
 * matrix. The result is stored in result. 4th row and 4th column values are
 * untouched. Note: the result is created from a normalized version of this quat.
 * Note that this method will preserve the scale of the given matrix
 *
 * @param result
 *            The Matrix4f to store the result in.
 * @return the rotation matrix representation of this quaternion.
 */
public Matrix4f toRotationMatrix(Matrix4f result) {
    TempVars tempv = TempVars.get();
    Vector3f originalScale = tempv.vect1;

    result.toScaleVector(originalScale);
    result.setScale(1, 1, 1);
    float norm = norm();
    // we explicitly test norm against one here, saving a division
    // at the cost of a test and branch.  Is it worth it?
    float s = (norm == 1f) ? 2f : (norm > 0f) ? 2f / norm : 0;

    // compute xs/ys/zs first to save 6 multiplications, since xs/ys/zs
    // will be used 2-4 times each.
    float xs = x * s;
    float ys = y * s;
    float zs = z * s;
    float xx = x * xs;
    float xy = x * ys;
    float xz = x * zs;
    float xw = w * xs;
    float yy = y * ys;
    float yz = y * zs;
    float yw = w * ys;
    float zz = z * zs;
    float zw = w * zs;

    // using s=2/norm (instead of 1/norm) saves 9 multiplications by 2 here
    result.m00 = 1 - (yy + zz);
    result.m01 = (xy - zw);
    result.m02 = (xz + yw);
    result.m10 = (xy + zw);
    result.m11 = 1 - (xx + zz);
    result.m12 = (yz - xw);
    result.m20 = (xz - yw);
    result.m21 = (yz + xw);
    result.m22 = 1 - (xx + yy);

    result.setScale(originalScale);

    tempv.release();

    return result;
}
 
Example 14
Source File: KinematicRagdollControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Update this control in Ragdoll mode, based on Bullet physics.
 *
 * @param tpf the time interval between frames (in seconds, &ge;0)
 */
protected void ragDollUpdate(float tpf) {
    TempVars vars = TempVars.get();
    Quaternion tmpRot1 = vars.quat1;
    Quaternion tmpRot2 = vars.quat2;

    for (PhysicsBoneLink link : boneLinks.values()) {

        Vector3f position = vars.vect1;

        //retrieving bone position in physics world space
        Vector3f p = link.rigidBody.getMotionState().getWorldLocation();
        //transforming this position with inverse transforms of the model
        targetModel.getWorldTransform().transformInverseVector(p, position);

        //retrieving bone rotation in physics world space
        Quaternion q = link.rigidBody.getMotionState().getWorldRotationQuat();

        //multiplying this rotation by the initialWorld rotation of the bone,
        //then transforming it with the inverse world rotation of the model
        tmpRot1.set(q).multLocal(link.initalWorldRotation);
        tmpRot2.set(targetModel.getWorldRotation()).inverseLocal().mult(tmpRot1, tmpRot1);
        tmpRot1.normalizeLocal();

        //if the bone is the root bone, we apply the physic's transform to the model, so its position and rotation are correctly updated
        if (link.bone.getParent() == null) {

            //offsetting the physic's position/rotation by the root bone inverse model space position/rotaion
            modelPosition.set(p).subtractLocal(link.bone.getBindPosition());
            targetModel.getParent().getWorldTransform().transformInverseVector(modelPosition, modelPosition);
            modelRotation.set(q).multLocal(tmpRot2.set(link.bone.getBindRotation()).inverseLocal());


            //applying transforms to the model
            targetModel.setLocalTranslation(modelPosition);

            targetModel.setLocalRotation(modelRotation);

            //Applying computed transforms to the bone
            link.bone.setUserTransformsInModelSpace(position, tmpRot1);

        } else {
            //some bones of the skeleton might not be associated with a collision shape.
            //So we update them recusively
            RagdollUtils.setTransform(link.bone, position, tmpRot1, false, boneList);
        }
    }
    vars.release();
}
 
Example 15
Source File: KinematicRagdollControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
     * Update this control in Kinematic mode, based on bone animation tracks.
     *
     * @param tpf the time interval between frames (in seconds, &ge;0)
     */
    protected void kinematicUpdate(float tpf) {
        //the ragdoll does not have control, so the keyframed animation updates the physics position of the physics bonces
        TempVars vars = TempVars.get();
        Quaternion tmpRot1 = vars.quat1;
        Quaternion tmpRot2 = vars.quat2;
        Vector3f position = vars.vect1;
        for (PhysicsBoneLink link : boneLinks.values()) {
//            if(link.usedbyIK){
//                continue;
//            }
            //if blended control this means, keyframed animation is updating the skeleton,
            //but to allow smooth transition, we blend this transformation with the saved position of the ragdoll
            if (blendedControl) {
                Vector3f position2 = vars.vect2;
                //initializing tmp vars with the start position/rotation of the ragdoll
                position.set(link.startBlendingPos);
                tmpRot1.set(link.startBlendingRot);

                //interpolating between ragdoll position/rotation and keyframed position/rotation
                tmpRot2.set(tmpRot1).nlerp(link.bone.getModelSpaceRotation(), blendStart / blendTime);
                position2.set(position).interpolateLocal(link.bone.getModelSpacePosition(), blendStart / blendTime);
                tmpRot1.set(tmpRot2);
                position.set(position2);

                //update bone transforms
                RagdollUtils.setTransform(link.bone, position, tmpRot1, true, boneList);
            }
            //setting skeleton transforms to the ragdoll
            matchPhysicObjectToBone(link, position, tmpRot1);
            modelPosition.set(targetModel.getLocalTranslation());
        }

        //time control for blending
        if (blendedControl) {
            blendStart += tpf;
            if (blendStart > blendTime) {
                blendedControl = false;
            }
        }
        vars.release();
    }
 
Example 16
Source File: SkinningControl.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 17
Source File: LODGeomap.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public FloatBuffer writeNormalArray(FloatBuffer store, Vector3f scale) {
    if (!isLoaded()) {
        throw new NullPointerException();
    }

    if (store != null) {
        if (store.remaining() < getWidth() * getHeight() * 3) {
            throw new BufferUnderflowException();
        }
    } else {
        store = BufferUtils.createFloatBuffer(getWidth() * getHeight() * 3);
    }
    store.rewind();

    TempVars vars = TempVars.get();
    
    Vector3f rootPoint = vars.vect1;
    Vector3f rightPoint = vars.vect2;
    Vector3f leftPoint = vars.vect3;
    Vector3f topPoint = vars.vect4;
    Vector3f bottomPoint = vars.vect5;
    
    Vector3f tmp1 = vars.vect6;

    // calculate normals for each polygon
    for (int r = 0; r < getHeight(); r++) {
        for (int c = 0; c < getWidth(); c++) {

            rootPoint.set(0, getValue(c, r), 0);
            Vector3f normal = vars.vect8;

            if (r == 0) { // first row
                if (c == 0) { // first column
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    getNormal(bottomPoint, rootPoint, rightPoint, scale, normal);
                } else if (c == getWidth() - 1) { // last column
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    getNormal(leftPoint, rootPoint, bottomPoint, scale, normal);
                } else { // all middle columns
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    
                    normal.set( getNormal(leftPoint, rootPoint, bottomPoint, scale, tmp1) );
                    normal.addLocal( getNormal(bottomPoint, rootPoint, rightPoint, scale, tmp1) );
                }
            } else if (r == getHeight() - 1) { // last row
                if (c == 0) { // first column
                    topPoint.set(0, getValue(c, r - 1), -1);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    getNormal(rightPoint, rootPoint, topPoint, scale, normal);
                } else if (c == getWidth() - 1) { // last column
                    topPoint.set(0, getValue(c, r - 1), -1);
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    getNormal(topPoint, rootPoint, leftPoint, scale, normal);
                } else { // all middle columns
                    topPoint.set(0, getValue(c, r - 1), -1);
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    
                    normal.set( getNormal(topPoint, rootPoint, leftPoint, scale, tmp1) );
                    normal.addLocal( getNormal(rightPoint, rootPoint, topPoint, scale, tmp1) );
                }
            } else { // all middle rows
                if (c == 0) { // first column
                    topPoint.set(0, getValue(c, r - 1), -1);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    
                    normal.set( getNormal(rightPoint, rootPoint, topPoint, scale, tmp1) );
                    normal.addLocal( getNormal(bottomPoint, rootPoint, rightPoint, scale, tmp1) );
                } else if (c == getWidth() - 1) { // last column
                    topPoint.set(0, getValue(c, r - 1), -1);
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);

                    normal.set( getNormal(topPoint, rootPoint, leftPoint, scale, tmp1) );
                    normal.addLocal( getNormal(leftPoint, rootPoint, bottomPoint, scale, tmp1) );
                } else { // all middle columns
                    topPoint.set(0, getValue(c, r - 1), -1);
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    
                    normal.set( getNormal(topPoint,  rootPoint, leftPoint, scale, tmp1 ) );
                    normal.addLocal( getNormal(leftPoint, rootPoint, bottomPoint, scale, tmp1) );
                    normal.addLocal( getNormal(bottomPoint, rootPoint, rightPoint, scale, tmp1) );
                    normal.addLocal( getNormal(rightPoint, rootPoint, topPoint, scale, tmp1) );
                }
            }
            normal.normalizeLocal();
            BufferUtils.setInBuffer(normal, store, (r * getWidth() + c)); // save the normal
        }
    }
    vars.release();
    
    return store;
}
 
Example 18
Source File: Bone.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Blends the given animation transform onto the bone's local transform.
 * <p>
 * Subsequent calls of this method stack up, with the final transformation
 * of the bone computed at {@link #updateModelTransforms() } which resets
 * the stack.
 * <p>
 * E.g. a single transform blend with weight = 0.5 followed by an
 * updateModelTransforms() call will result in final transform = transform * 0.5.
 * Two transform blends with weight = 0.5 each will result in the two
 * transforms blended together (nlerp) with blend = 0.5.
 * 
 * @param translation The translation to blend in
 * @param rotation The rotation to blend in
 * @param scale The scale to blend in
 * @param weight The weight of the transform to apply. Set to 1.0 to prevent
 * any other transform from being applied until updateModelTransforms().
 */
void blendAnimTransforms(Vector3f translation, Quaternion rotation, Vector3f scale, float weight) {
    if (userControl) {
        return;
    }
    
    if (weight == 0) {
        // Do not apply this transform at all.
        return;
    }

    if (currentWeightSum == 1){
        return; // More than 2 transforms are being blended
    } else if (currentWeightSum == -1 || currentWeightSum == 0) {
        // Set the transform fully
        localPos.set(bindPos).addLocal(translation);
        localRot.set(bindRot).multLocal(rotation);
        if (scale != null) {
            localScale.set(bindScale).multLocal(scale);
        }
        // Set the weight. It will be applied in updateModelTransforms().
        currentWeightSum = weight;
    } else {
        // The weight is already set. 
        // Blend in the new transform.
        TempVars vars = TempVars.get();

        Vector3f tmpV = vars.vect1;
        Vector3f tmpV2 = vars.vect2;
        Quaternion tmpQ = vars.quat1;
        
        tmpV.set(bindPos).addLocal(translation);
        localPos.interpolateLocal(tmpV, weight);

        tmpQ.set(bindRot).multLocal(rotation);
        localRot.nlerp(tmpQ, weight);

        if (scale != null) {
            tmpV2.set(bindScale).multLocal(scale);
            localScale.interpolateLocal(tmpV2, weight);
        }
    
        // Ensures no new weights will be blended in the future.
        currentWeightSum = 1;
        
        vars.release();
    }
}
 
Example 19
Source File: BetterCharacterControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Callback from Bullet, invoked just before the physics is stepped.
 *
 * @param space the space that is about to be stepped (not null)
 * @param tpf the time per physics step (in seconds, &ge;0)
 */
@Override
public void prePhysicsTick(PhysicsSpace space, float tpf) {
    checkOnGround();
    if (wantToUnDuck && checkCanUnDuck()) {
        setHeightPercent(1);
        wantToUnDuck = false;
        ducked = false;
    }
    TempVars vars = TempVars.get();

    Vector3f currentVelocity = vars.vect2.set(velocity);

    // Attenuate any existing X-Z motion.
    float existingLeftVelocity = velocity.dot(localLeft);
    float existingForwardVelocity = velocity.dot(localForward);
    Vector3f counter = vars.vect1;
    existingLeftVelocity = existingLeftVelocity * physicsDamping;
    existingForwardVelocity = existingForwardVelocity * physicsDamping;
    counter.set(-existingLeftVelocity, 0, -existingForwardVelocity);
    localForwardRotation.multLocal(counter);
    velocity.addLocal(counter);

    float designatedVelocity = walkDirection.length();
    if (designatedVelocity > 0) {
        Vector3f localWalkDirection = vars.vect1;
        //normalize walkdirection
        localWalkDirection.set(walkDirection).normalizeLocal();
        //check for the existing velocity in the desired direction
        float existingVelocity = velocity.dot(localWalkDirection);
        //calculate the final velocity in the desired direction
        float finalVelocity = designatedVelocity - existingVelocity;
        localWalkDirection.multLocal(finalVelocity);
        //add resulting vector to existing velocity
        velocity.addLocal(localWalkDirection);
    }
    if(currentVelocity.distance(velocity) > FastMath.ZERO_TOLERANCE) rigidBody.setLinearVelocity(velocity);
    if (jump) {
        //TODO: precalculate jump force
        Vector3f rotatedJumpForce = vars.vect1;
        rotatedJumpForce.set(jumpForce);
        rigidBody.applyImpulse(localForwardRotation.multLocal(rotatedJumpForce), Vector3f.ZERO);
        jump = false;
    }
    vars.release();
}
 
Example 20
Source File: DebugShapeFactory.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Creates a debug shape from the given collision shape. This is mostly used internally.<br>
 * To attach a debug shape to a physics object, call <code>attachDebugShape(AssetManager manager);</code> on it.
 * @param collisionShape
 * @return a new Spatial or null
 */
public static Spatial getDebugShape(CollisionShape collisionShape) {
    if (collisionShape == null) {
        return null;
    }
    Spatial debugShape;
    if (collisionShape instanceof CompoundCollisionShape) {
        CompoundCollisionShape shape = (CompoundCollisionShape) collisionShape;
        List<ChildCollisionShape> children = shape.getChildren();
        Node node = new Node("DebugShapeNode");
        for (Iterator<ChildCollisionShape> it = children.iterator(); it.hasNext();) {
            ChildCollisionShape childCollisionShape = it.next();
            CollisionShape ccollisionShape = childCollisionShape.shape;
            Geometry geometry = createDebugShape(ccollisionShape);

            // apply translation
            geometry.setLocalTranslation(childCollisionShape.location);

            // apply rotation
            TempVars vars = TempVars.get();

            Matrix3f tempRot = vars.tempMat3;

            tempRot.set(geometry.getLocalRotation());
            childCollisionShape.rotation.mult(tempRot, tempRot);
            geometry.setLocalRotation(tempRot);

            vars.release();

            node.attachChild(geometry);
        }
        debugShape = node;
    } else {
        debugShape = createDebugShape(collisionShape);
    }
    if (debugShape == null) {
        return null;
    }
    debugShape.updateGeometricState();
    return debugShape;
}