Java Code Examples for com.jme3.math.Vector3f#add()

The following examples show how to use com.jme3.math.Vector3f#add() . 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: AlignmentBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @see AbstractSteeringBehaviour#calculateSteering()
 */
@Override
protected Vector3f calculateRawSteering() {
    // steering accumulator and count of neighbors, both initially zero
    Vector3f steering = new Vector3f();
    int realNeighbors = 0;
    // for each of the other vehicles...
    for (GameEntity gameEntity : neighbours) {
        if (this.agent.inBoidNeighborhood(gameEntity, this.agent.getRadius() * 3, this.maxDistance, this.maxAngle)) {
            // accumulate sum of neighbor's positions
            steering = steering.add(gameEntity.fordwardVector());
            realNeighbors++;
        }
    }
    // divide by neighbors, subtract off current position to get error-correcting direction
    if (realNeighbors > 0) {
        steering = steering.divide(realNeighbors);
        steering = this.agent.offset(steering);
    }
    return steering;
}
 
Example 2
Source File: CohesionBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @see AbstractSteeringBehavior#calculateSteering()
 */
@Override
protected Vector3f calculateRawSteering() {
    // steering accumulator and count of neighbors, both initially zero
    Vector3f steering = new Vector3f();
    int realNeighbors = 0;

    // for each of the other vehicles...
    for (GameEntity neighbour : this.neighbours) {
        if (this.agent.inBoidNeighborhood(neighbour, this.agent.getRadius() * 3, this.maxDistance, this.maxAngle)) {
            // accumulate sum of neighbor's positions
            steering = steering.add(neighbour.getLocalTranslation());
            realNeighbors++;
        }
    }

    // divide by neighbors, subtract off current position to get error-correcting direction
    if (realNeighbors > 0) {
        steering = steering.divide(realNeighbors);
        steering = this.agent.offset(steering);
    }
    return steering;
}
 
Example 3
Source File: BalancedCompoundSteeringBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Calculates the total force if it is not calculated.
 */
protected void calculateTotalForce() {
    if (numberOfPartialForcesAlreadyCalculated == 0) {
        Vector3f totalForceAux = new Vector3f();

        //We do not want to modify the current pointer
        steerBehaviorsLayerList.steerBehaviorsLayerNode currentPointer = this.behaviors.getPointer();

        behaviors.moveAtBeginning();

        while (!behaviors.nullPointer()) {
            Vector3f partial = behaviors.getBehavior().calculateSteering();
            partialForces.add(partial);
            totalForceAux = totalForceAux.add(partial);
            behaviors.moveNext();
        }

        //Restore the previous pointer
        this.behaviors.setPointer(currentPointer);
        this.totalForce = totalForceAux;
    }

}
 
Example 4
Source File: SkeletonWire.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * The method updates the geometry according to the poitions of the bones.
 */
public void updateGeometry() {
    VertexBuffer vb = this.getBuffer(Type.Position);
    FloatBuffer posBuf = this.getFloatBuffer(Type.Position);
    posBuf.clear();
    for (int i = 0; i < skeleton.getBoneCount(); ++i) {
        Bone bone = skeleton.getBone(i);
        Vector3f head = bone.getModelSpacePosition();

        posBuf.put(head.getX()).put(head.getY()).put(head.getZ());
        if (boneLengths != null) {
            Vector3f tail = head.add(bone.getModelSpaceRotation().mult(Vector3f.UNIT_Y.mult(boneLengths.get(i))));
            posBuf.put(tail.getX()).put(tail.getY()).put(tail.getZ());
        }
    }
    posBuf.flip();
    vb.updateData(posBuf);

    this.updateBound();
}
 
Example 5
Source File: WallApproachBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @see AbstractStrengthSteeringBehavior#calculateRawSteering()
 */
@Override
protected Vector3f calculateRawSteering() {
    Vector3f steer = new Vector3f();

    Vector3f aproximatedSurfaceLocationDir = this.approximateSurfaceLocation();

    if (aproximatedSurfaceLocationDir != null) {
        Vector3f surfaceLocation = this.surfaceLocation(aproximatedSurfaceLocationDir);

        if (surfaceLocation != null) {
            Vector3f extraOffset = this.agent.offset(surfaceLocation).negate().normalize().mult(this.offsetToMaintain);

            SeekBehavior seek = new SeekBehavior(this.agent, surfaceLocation.add(extraOffset));
            steer = seek.calculateRawSteering();
        }
    }

    return steer;
}
 
Example 6
Source File: SkeletonPoints.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * The method updates the geometry according to the positions of the bones.
 */
public void updateGeometry() {
    VertexBuffer vb = this.getBuffer(Type.Position);
    FloatBuffer posBuf = this.getFloatBuffer(Type.Position);
    posBuf.clear();
    for (int i = 0; i < skeleton.getBoneCount(); ++i) {
        Bone bone = skeleton.getBone(i);
        Vector3f head = bone.getModelSpacePosition();

        posBuf.put(head.getX()).put(head.getY()).put(head.getZ());
        if (boneLengths != null) {
            Vector3f tail = head.add(bone.getModelSpaceRotation().mult(Vector3f.UNIT_Y.mult(boneLengths.get(i))));
            posBuf.put(tail.getX()).put(tail.getY()).put(tail.getZ());
        }
    }
    posBuf.flip();
    vb.updateData(posBuf);

    this.updateBound();
}
 
Example 7
Source File: TriangulatedTexture.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * This method returns an envelope of a minimal rectangle, that is set
 * in 3D space, and contains the given triangle.
 * 
 * @param triangle
 *            the triangle
 * @return a rectangle minimum and maximum point and height and width
 */
private RectangleEnvelope getTriangleEnvelope(Vector3f v1, Vector3f v2, Vector3f v3) {
    Vector3f h = v3.subtract(v1);// the height of the resulting rectangle
    Vector3f temp = v2.subtract(v1);

    float field = 0.5f * h.cross(temp).length();// the field of the rectangle: Field = 0.5 * ||h x temp||
    if (field <= 0.0f) {
        return new RectangleEnvelope(v1);// return single point envelope
    }

    float cosAlpha = h.dot(temp) / (h.length() * temp.length());// the cosinus of angle betweenh and temp

    float triangleHeight = 2 * field / h.length();// the base of the height is the h vector
    // now calculate the distance between v1 vertex and the point where
    // the above calculated height 'touches' the base line (it can be
    // settled outside the h vector)
    float x = Math.abs((float) Math.sqrt(FastMath.clamp(temp.lengthSquared() - triangleHeight * triangleHeight, 0, Float.MAX_VALUE))) * Math.signum(cosAlpha);
    // now get the height base point
    Vector3f xPoint = v1.add(h.normalize().multLocal(x));

    // get the minimum point of the envelope
    Vector3f min = x < 0 ? xPoint : v1;
    if (x < 0) {
        h = v3.subtract(min);
    } else if (x > h.length()) {
        h = xPoint.subtract(min);
    }

    Vector3f envelopeWidth = v2.subtract(xPoint);
    return new RectangleEnvelope(min, envelopeWidth, h);
}
 
Example 8
Source File: ModelPerformer.java    From OpenRTS with MIT License 5 votes vote down vote up
private Point3D getBoneWorldPos(ModelActor actor, Point3D actorPos, double actorYaw, String boneName) {
	Spatial s = actor.getViewElements().spatial;
	Vector3f modelSpacePos = s.getControl(AnimControl.class).getSkeleton().getBone(boneName).getModelSpacePosition();
	Quaternion q = actor.getViewElements().spatial.getLocalRotation();
	modelSpacePos = q.mult(modelSpacePos);
	modelSpacePos.multLocal(s.getLocalScale());
	modelSpacePos = modelSpacePos.add(s.getLocalTranslation());
	// float scale
	// Point2D p2D = Translator.toPoint2D(modelSpacePos);
	// p2D = p2D.getRotation(actorYaw+Angle.RIGHT);
	// Point3D p3D = new Point3D(p2D.getMult(DEFAULT_SCALE), modelSpacePos.z*DEFAULT_SCALE, 1);
	// p3D = p3D.getAddition(actorPos);
	// return p3D;
	return TranslateUtil.toPoint3D(modelSpacePos);
}
 
Example 9
Source File: WorldOfInception.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void scaleAsParent(float percent, Vector3f playerPos, Vector3f dist) {
    float scale = mapValue(percent, 1.0f, poiRadius);
    Vector3f distToHorizon = dist.subtract(dist.normalize());
    Vector3f offLocation = playerPos.add(distToHorizon);
    Vector3f rootOff = offLocation.mult(scale).negate();
    rootOff.addLocal(dist);
    debugTools.setGreenArrow(Vector3f.ZERO, offLocation);
    getRootNode().setLocalScale(scale);
    getRootNode().setLocalTranslation(rootOff);
}
 
Example 10
Source File: WorldOfInception.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void scaleAsChild(float percent, Vector3f dist) {
    float childScale = mapValue(percent, 1.0f / poiRadius, 1);
    Vector3f distToHorizon = dist.normalize();
    Vector3f scaledDistToHorizon = distToHorizon.mult(childScale * poiRadius);
    Vector3f rootOff = dist.add(scaledDistToHorizon);
    debugTools.setBlueArrow(Vector3f.ZERO, rootOff);
    getRootNode().setLocalScale(childScale);
    getRootNode().setLocalTranslation(rootOff);
    //prepare player position already
    Vector3f playerPosition = dist.normalize().mult(-poiRadius);
    setPlayerPosition(playerPosition);
}
 
Example 11
Source File: SphereWanderBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Metod for changing target position.
 *
 * @param tpf time per frame
 */
protected void changeTargetPosition(float tpf) {
    time -= tpf;
    Vector3f forward;

    if (this.agent.getVelocity() != null) {
        forward = this.agent.getVelocity().normalize();
    } else {
        forward = this.agent.fordwardVector();
    }

    if (forward.equals(Vector3f.UNIT_Y)) {
        forward = forward.add(new Vector3f(0, 0, SphereWanderBehavior.SIDE_REFERENCE_OFFSET));
    }

    //Update sphere position  
    this.wanderSphere.setCenter(this.agent.getLocalTranslation().add(forward.mult(SphereWanderBehavior.OFFSET_DISTANCE + this.agent.getRadius() + this.sphereRadius)));

    if (time <= 0) {
        this.calculateNewRandomDir();
        time = timeInterval;
    }

    Vector3f sideVector = forward.cross(Vector3f.UNIT_Y).normalize();
    Vector3f rayDir = (this.agent.offset(wanderSphere.getCenter())).add(sideVector.mult(this.randomDirection.x));//.add(Vector3f.UNIT_Y.mult(this.randomDirection.y));       

    Ray ray = new Ray(this.agent.getLocalTranslation(), rayDir);
    CollisionResults results = new CollisionResults();
    this.wanderSphere.collideWith(ray, results);

    CollisionResult collisionResult = results.getCollision(1); //The collision with the second hemisphere
    this.targetPosition = collisionResult.getContactPoint();
}
 
Example 12
Source File: TestGimpactShape.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void dropTest2(Vector3f offset) {
    offset = offset.add(18, 6, -18);
    attachTestObject(new Torus(16, 16, 0.3f, 0.8f), new Vector3f(12f, 0f, 5f).add(offset), 3);
    attachTestObject(new PQTorus(3f, 5f, 0.8f, 0.2f, 96, 16), new Vector3f(0, 0, 0).add(offset), 10);
}
 
Example 13
Source File: TestGimpactShape.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void dropTest1(Vector3f offset) {
    offset = offset.add(-18, 6, -18);
    attachTestObject(new Torus(16, 16, 0.15f, 0.5f), new Vector3f(-12f, 0f, 5f).add(offset), 1);
    attachTestObject(new PQTorus(2f, 3f, 0.6f, 0.2f, 48, 16), new Vector3f(0, 0, 0).add(offset), 5);

}
 
Example 14
Source File: TestGimpactShape.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void initializeNewTest() {
    testScale.setText("Object scale: " + String.format("%.1f", scaleMod));
    solverNumIterationsTxt.setText("Solver Iterations: " + solverNumIterations);

    bulletAppState = new BulletAppState();
    bulletAppState.setDebugEnabled(true);
    stateManager.attach(bulletAppState);
    bulletAppState.getPhysicsSpace().setSolverNumIterations(solverNumIterations);

    float floorSize = 80;
    //Left side test - GImpact objects collide with MeshCollisionShape floor
    Vector3f leftFloorPos = new Vector3f(-41, -5, -10);
    Vector3f leftFloorCenter = leftFloorPos.add(floorSize / 2, 0, floorSize / 2);

    dropTest1(leftFloorCenter);
    dropTest2(leftFloorCenter);
    dropPot(leftFloorCenter);
    dropSword(leftFloorCenter);
    dropSign(leftFloorCenter);
    dropRocket(leftFloorCenter);

    Geometry leftFloor = PhysicsTestHelper.createMeshTestFloor(assetManager, floorSize, leftFloorPos);
    addObject(leftFloor);

    //Right side test - GImpact objects collide with GImpact floor
    Vector3f rightFloorPos = new Vector3f(41, -5, -10);
    Vector3f rightFloorCenter = rightFloorPos.add(floorSize / 2, 0, floorSize / 2);

    dropTest1(rightFloorCenter);
    dropTest2(rightFloorCenter);
    dropPot(rightFloorCenter);
    dropSword(rightFloorCenter);
    dropSign(rightFloorCenter);
    dropRocket(rightFloorCenter);

    Geometry rightFloor = PhysicsTestHelper.createGImpactTestFloor(assetManager, floorSize, rightFloorPos);
    addObject(rightFloor);

    //Hide physics debug visualization for floors
    BulletDebugAppState bulletDebugAppState = stateManager.getState(BulletDebugAppState.class);
    bulletDebugAppState.setFilter((Object obj) -> {
        return !(obj.equals(rightFloor.getControl(RigidBodyControl.class))
            || obj.equals(leftFloor.getControl(RigidBodyControl.class)));
    });
}
 
Example 15
Source File: PathFollowBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * @see AbstractStrengthSteeringBehavior#calculateRawSteering()
 */
@Override
protected Vector3f calculateRawSteering() {
    Vector3f steer = new Vector3f();

    if (active) {
        //Start to follow from the beginning
        if (this.nextSpineJoint < 0) {
            this.nextSpineJoint = 0;
        }

        if (this.nextSpineJoint < this.orderedPointsList.size()) {
            //Calculate the next exit
            Vector3f exitNormal;
            if (this.nextSpineJoint == 0) {
                exitNormal = this.orderedPointsList.get(this.nextSpineJoint + 1).subtract(this.orderedPointsList.get(this.nextSpineJoint));
            } else {
                exitNormal = this.orderedPointsList.get(this.nextSpineJoint).subtract(this.orderedPointsList.get(this.nextSpineJoint - 1));
            }

            this.nextExit = new Plane();
            this.nextExit.setOriginNormal(
                    this.orderedPointsList.get(this.nextSpineJoint),
                    exitNormal);

            Vector3f posProjection = this.nextExit.getClosestPoint(this.agent.getLocalTranslation());
            float distanceToCenter = posProjection.subtract(this.orderedPointsList.get(this.nextSpineJoint)).length();
            //chaeck if the agent is outside the path
            if (distanceToCenter > this.pathRadius) {
                //Move to the next spine and inside the path
                Vector3f moveToSpine = this.agent.offset(this.orderedPointsList.get(this.nextSpineJoint)).normalize();
                Vector3f moveToCenter = this.orderedPointsList.get(this.nextSpineJoint).subtract(posProjection).normalize();
                steer = moveToSpine.add(moveToCenter);
            } else {
                //Move through the path
                Vector3f moveThroughPathSteer = exitNormal.normalize();

                Vector3f predictedPos = this.agent.getPredictedPosition();
                Vector3f predictedOffsetFromNextCenter = predictedPos.subtract(this.orderedPointsList.get(this.nextSpineJoint));
                Vector3f projectionIntoSpine = this.orderedPointsList.get(this.nextSpineJoint).add(
                        exitNormal.mult(predictedOffsetFromNextCenter.dot(exitNormal) / exitNormal.lengthSquared()));

                Vector3f predictedOffset = predictedPos.subtract(projectionIntoSpine);
                Vector3f predictedOffsetFromSurface = predictedOffset.subtract(predictedOffset.normalize().mult(this.pathRadius));

                //Path containment
                if (predictedOffset.length() > this.pathRadius) {
                    moveThroughPathSteer = moveThroughPathSteer.add(predictedOffsetFromSurface.mult(cohesionStrength));
                }

                steer = moveThroughPathSteer;

                if (this.nextExit.whichSide(this.agent.getLocalTranslation()) == Side.Positive) {
                    this.nextSpineJoint++;
                }
            }
        } else {
            //The path has ended
            this.active = false;
        }
    }

    return steer;
}
 
Example 16
Source File: TriangulatedTexture.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Constructor that creates an image element from the 3D texture
 * (generated texture). It computes a flat smallest rectangle that can
 * hold a (3D) triangle defined by the given UV coordinates. Then it
 * defines the image pixels for points in 3D space that define the
 * calculated rectangle.
 * 
 * @param faceIndex
 *            the face index this image refers to
 * @param boundingBox
 *            the bounding box of the mesh
 * @param texture
 *            the texture that allows to compute a pixel value in 3D
 *            space
 * @param uv
 *            the UV coordinates of the mesh
 * @param blenderContext
 *            the blender context
 */
public TriangleTextureElement(int faceIndex, BoundingBox boundingBox, GeneratedTexture texture, Vector3f[] uv, int[] uvIndices, BlenderContext blenderContext) {
    this.faceIndex = faceIndex;

    // compute the face vertices from the UV coordinates
    float width = boundingBox.getXExtent() * 2;
    float height = boundingBox.getYExtent() * 2;
    float depth = boundingBox.getZExtent() * 2;

    Vector3f min = boundingBox.getMin(null);
    Vector3f v1 = min.add(uv[uvIndices[0]].x * width, uv[uvIndices[0]].y * height, uv[uvIndices[0]].z * depth);
    Vector3f v2 = min.add(uv[uvIndices[1]].x * width, uv[uvIndices[1]].y * height, uv[uvIndices[1]].z * depth);
    Vector3f v3 = min.add(uv[uvIndices[2]].x * width, uv[uvIndices[2]].y * height, uv[uvIndices[2]].z * depth);

    // get the rectangle envelope for the triangle
    RectangleEnvelope envelope = this.getTriangleEnvelope(v1, v2, v3);

    // create the result image
    Format imageFormat = texture.getImage().getFormat();
    int imageWidth = (int) (envelope.width * blenderContext.getBlenderKey().getGeneratedTexturePPU());
    if (imageWidth == 0) {
        imageWidth = 1;
    }
    int imageHeight = (int) (envelope.height * blenderContext.getBlenderKey().getGeneratedTexturePPU());
    if (imageHeight == 0) {
        imageHeight = 1;
    }
    ByteBuffer data = BufferUtils.createByteBuffer(imageWidth * imageHeight * (imageFormat.getBitsPerPixel() >> 3));
    image = new Image(texture.getImage().getFormat(), imageWidth, imageHeight, data);

    // computing the pixels
    PixelInputOutput pixelWriter = PixelIOFactory.getPixelIO(imageFormat);
    TexturePixel pixel = new TexturePixel();
    float[] uvs = new float[3];
    Vector3f point = new Vector3f(envelope.min);
    Vector3f vecY = new Vector3f();
    Vector3f wDelta = new Vector3f(envelope.w).multLocal(1.0f / imageWidth);
    Vector3f hDelta = new Vector3f(envelope.h).multLocal(1.0f / imageHeight);
    for (int x = 0; x < imageWidth; ++x) {
        for (int y = 0; y < imageHeight; ++y) {
            this.toTextureUV(boundingBox, point, uvs);
            texture.getPixel(pixel, uvs[0], uvs[1], uvs[2]);
            pixelWriter.write(image, 0, pixel, x, y);
            point.addLocal(hDelta);
        }

        vecY.addLocal(wDelta);
        point.set(envelope.min).addLocal(vecY);
    }

    // preparing UV coordinates for the flatted texture
    this.uv = new Vector2f[3];
    this.uv[0] = new Vector2f(FastMath.clamp(v1.subtract(envelope.min).length(), 0, Float.MAX_VALUE) / envelope.height, 0);
    Vector3f heightDropPoint = v2.subtract(envelope.w);// w is directed from the base to v2
    this.uv[1] = new Vector2f(1, heightDropPoint.subtractLocal(envelope.min).length() / envelope.height);
    this.uv[2] = new Vector2f(0, 1);
}
 
Example 17
Source File: JMonkeyEngineTest.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
@Test
public void testVector() {
    Vector3f v = Vector3f.UNIT_X;
    v = v.add(0f, 2f, 0f);
    v.normalizeLocal();
}