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

The following examples show how to use com.jme3.math.Vector3f#multLocal() . 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: BoneContext.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * This method builds the bone. It recursively builds the bone's children.
 * 
 * @param bones
 *            a list of bones where the newly created bone will be added
 * @param objectToArmatureMatrix
 *            object to armature transformation matrix
 * @param blenderContext
 *            the blender context
 * @return newly created bone
 */
public Bone buildBone(List<Bone> bones, Matrix4f objectToArmatureMatrix, BlenderContext blenderContext) {
    Long boneOMA = boneStructure.getOldMemoryAddress();
    bone = new Bone(boneName);
    bones.add(bone);
    blenderContext.addLoadedFeatures(boneOMA, boneName, boneStructure, bone);

    Vector3f poseLocation = restMatrix.toTranslationVector();
    Quaternion rotation = restMatrix.toRotationQuat().normalizeLocal();
    Vector3f scale = restMatrix.toScaleVector();
    if (parent == null) {
        Quaternion rotationQuaternion = objectToArmatureMatrix.toRotationQuat().normalizeLocal();
        scale.multLocal(objectToArmatureMatrix.toScaleVector());
        rotationQuaternion.multLocal(poseLocation.addLocal(objectToArmatureMatrix.toTranslationVector()));
        rotation.multLocal(rotationQuaternion);
    }

    bone.setBindTransforms(poseLocation, rotation, scale);
    for (BoneContext child : children) {
        bone.addChild(child.buildBone(bones, objectToArmatureMatrix, blenderContext));
    }

    return bone;
}
 
Example 2
Source File: FlyByCamera.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Translate the camera left or forward by the specified amount.
 *
 * @param value translation amount
 * @param sideways true&rarr;left, false&rarr;forward
 */
protected void moveCamera(float value, boolean sideways){
    Vector3f vel = new Vector3f();
    Vector3f pos = cam.getLocation().clone();

    if (sideways){
        cam.getLeft(vel);
    }else{
        cam.getDirection(vel);
    }
    vel.multLocal(value * moveSpeed);

    if (motionAllowed != null)
        motionAllowed.checkMotionAllowed(pos, vel);
    else
        pos.addLocal(vel);

    cam.setLocation(pos);
}
 
Example 3
Source File: TestReverb.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void simpleUpdate(float tpf) {
  time += tpf;

  if (time > nextTime) {
    Vector3f v = new Vector3f();
    v.setX(FastMath.nextRandomFloat());
    v.setY(FastMath.nextRandomFloat());
    v.setZ(FastMath.nextRandomFloat());
    v.multLocal(40, 2, 40);
    v.subtractLocal(20, 1, 20);

    audioSource.setLocalTranslation(v);
    audioSource.playInstance();
    time = 0;
    nextTime = FastMath.nextRandomFloat() * 2 + 0.5f;
  }
}
 
Example 4
Source File: Arrow.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
     * Sets the arrow's extent.
     * This will modify the buffers on the mesh.
     * 
     * @param extent the arrow's extent.
     */
    public void setArrowExtent(Vector3f extent) {
        float len = extent.length();
//        Vector3f dir = extent.normalize();

        tempQuat.lookAt(extent, Vector3f.UNIT_Y);
        tempQuat.normalizeLocal();

        VertexBuffer pvb = getBuffer(Type.Position);
        FloatBuffer buffer = (FloatBuffer)pvb.getData(); 
        buffer.rewind();
        for (int i = 0; i < positions.length; i += 3) {
            Vector3f vec = tempVec.set(positions[i],
                    positions[i + 1],
                    positions[i + 2]);
            vec.multLocal(len);
            tempQuat.mult(vec, vec);

            buffer.put(vec.x);
            buffer.put(vec.y);
            buffer.put(vec.z);
        }
        
        pvb.updateData(buffer);

        updateBound();
        updateCounts();
    }
 
Example 5
Source File: AdvancedAbstractEditor3DPart.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Move a camera to direction.
 *
 * @param value the value to move.
 */
@JmeThread
private void moveDirectionCamera(final float value, final boolean isAction, final boolean isPressed, final int key) {

    if (!canCameraMove()) {
        return;
    } else if (isAction && isPressed) {
        startCameraMoving(key);
    } else if (isAction) {
        finishCameraMoving(key, false);
    }

    if (!isCameraMoving() || isAction) {
        return;
    }

    final EditorCamera editorCamera = getEditorCamera();
    if (editorCamera == null) {
        return;
    }

    final Camera camera = EditorUtil.getGlobalCamera();
    final Node nodeForCamera = getNodeForCamera();

    final LocalObjects local = LocalObjects.get();
    final Vector3f direction = camera.getDirection(local.nextVector());
    direction.multLocal(value * cameraSpeed);
    direction.addLocal(nodeForCamera.getLocalTranslation());

    nodeForCamera.setLocalTranslation(direction);
}
 
Example 6
Source File: TangentBinormalGenerator.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Mesh genNormalLines(Mesh mesh, float scale) {
    FloatBuffer vertexBuffer = (FloatBuffer) mesh.getBuffer(Type.Position).getData();
    FloatBuffer normalBuffer = (FloatBuffer) mesh.getBuffer(Type.Normal).getData();
    
    ColorRGBA originColor = ColorRGBA.White;
    ColorRGBA normalColor = ColorRGBA.Blue;
    
    Mesh lineMesh = new Mesh();
    lineMesh.setMode(Mesh.Mode.Lines);
    
    Vector3f origin = new Vector3f();
    Vector3f point = new Vector3f();
    
    FloatBuffer lineVertex = BufferUtils.createFloatBuffer(vertexBuffer.limit() * 2);
    FloatBuffer lineColor = BufferUtils.createFloatBuffer(vertexBuffer.limit() / 3 * 4 * 2);
    
    for (int i = 0; i < vertexBuffer.limit() / 3; i++) {
        populateFromBuffer(origin, vertexBuffer, i);
        populateFromBuffer(point, normalBuffer, i);
        
        int index = i * 2;
        
        setInBuffer(origin, lineVertex, index);
        setInBuffer(originColor, lineColor, index);
        
        point.multLocal(scale);
        point.addLocal(origin);
        setInBuffer(point, lineVertex, index + 1);
        setInBuffer(normalColor, lineColor, index + 1);
    }
    
    lineMesh.setBuffer(Type.Position, 3, lineVertex);
    lineMesh.setBuffer(Type.Color, 4, lineColor);
    
    lineMesh.setStatic();
    //lineMesh.setInterleaved();
    return lineMesh;
}
 
Example 7
Source File: EmitterSphereShape.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void getRandomPoint(Vector3f store) {
    do {
        store.x = (FastMath.nextRandomFloat() * 2f - 1f);
        store.y = (FastMath.nextRandomFloat() * 2f - 1f);
        store.z = (FastMath.nextRandomFloat() * 2f - 1f);
    } while (store.lengthSquared() > 1);
    store.multLocal(radius);
    store.addLocal(center);
}
 
Example 8
Source File: SilentTangentBinormalGenerator.java    From OpenRTS with MIT License 5 votes vote down vote up
public static Mesh genNormalLines(Mesh mesh, float scale) {
	FloatBuffer vertexBuffer = (FloatBuffer) mesh.getBuffer(Type.Position).getData();
	FloatBuffer normalBuffer = (FloatBuffer) mesh.getBuffer(Type.Normal).getData();

	ColorRGBA originColor = ColorRGBA.White;
	ColorRGBA normalColor = ColorRGBA.Blue;

	Mesh lineMesh = new Mesh();
	lineMesh.setMode(Mesh.Mode.Lines);

	Vector3f origin = new Vector3f();
	Vector3f point = new Vector3f();

	FloatBuffer lineVertex = BufferUtils.createFloatBuffer(vertexBuffer.limit() * 2);
	FloatBuffer lineColor = BufferUtils.createFloatBuffer(vertexBuffer.limit() / 3 * 4 * 2);

	for (int i = 0; i < vertexBuffer.limit() / 3; i++) {
		populateFromBuffer(origin, vertexBuffer, i);
		populateFromBuffer(point, normalBuffer, i);

		int index = i * 2;

		setInBuffer(origin, lineVertex, index);
		setInBuffer(originColor, lineColor, index);

		point.multLocal(scale);
		point.addLocal(origin);
		setInBuffer(point, lineVertex, index + 1);
		setInBuffer(normalColor, lineColor, index + 1);
	}

	lineMesh.setBuffer(Type.Position, 3, lineVertex);
	lineMesh.setBuffer(Type.Color, 4, lineColor);

	lineMesh.setStatic();
	// lineMesh.setInterleaved();
	return lineMesh;
}
 
Example 9
Source File: Arrow.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
     * Sets the arrow's extent.
     * This will modify the buffers on the mesh.
     * 
     * @param extent the arrow's extent.
     */
    public void setArrowExtent(Vector3f extent) {
        float len = extent.length();
//        Vector3f dir = extent.normalize();

        tempQuat.lookAt(extent, Vector3f.UNIT_Y);
        tempQuat.normalizeLocal();

        VertexBuffer pvb = getBuffer(Type.Position);
        FloatBuffer buffer = (FloatBuffer)pvb.getData(); 
        buffer.rewind();
        for (int i = 0; i < positions.length; i += 3) {
            Vector3f vec = tempVec.set(positions[i],
                    positions[i + 1],
                    positions[i + 2]);
            vec.multLocal(len);
            tempQuat.mult(vec, vec);

            buffer.put(vec.x);
            buffer.put(vec.y);
            buffer.put(vec.z);
        }
        
        pvb.updateData(buffer);

        updateBound();
        updateCounts();
    }
 
Example 10
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 11
Source File: BoneLink.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Calculate the local bone transform to match the physics transform of the
 * rigid body.
 *
 * @param storeResult storage for the result (modified if not null)
 * @return the calculated bone transform (in local coordinates, either
 * storeResult or a new transform, not null)
 */
private Transform localBoneTransform(Transform storeResult) {
    Transform result
            = (storeResult == null) ? new Transform() : storeResult;
    Vector3f location = result.getTranslation();
    Quaternion orientation = result.getRotation();
    Vector3f scale = result.getScale();
    /*
     * Start with the rigid body's transform in physics/world coordinates.
     */
    PhysicsRigidBody body = getRigidBody();
    body.getPhysicsLocation(result.getTranslation());
    body.getPhysicsRotation(result.getRotation());
    result.setScale(body.getCollisionShape().getScale());
    /*
     * Convert to mesh coordinates.
     */
    Transform worldToMesh = getControl().meshTransform(null).invert();
    result.combineWithParent(worldToMesh);
    /*
     * Convert to the bone's local coordinate system by factoring out the
     * parent bone's transform.
     */
    Joint parentBone = getBone().getParent();
    RagUtils.meshToLocal(parentBone, result);
    /*
     * Subtract the body's local offset, rotated and scaled.
     */
    Vector3f parentOffset = localOffset(null);
    parentOffset.multLocal(scale);
    orientation.mult(parentOffset, parentOffset);
    location.subtractLocal(parentOffset);

    return result;
}
 
Example 12
Source File: TorsoLink.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Calculate the local bone transform to match the physics transform of the
 * rigid body.
 *
 * @param storeResult storage for the result (modified if not null)
 * @return the calculated bone transform (in local coordinates, either
 * storeResult or a new transform, not null)
 */
private Transform localBoneTransform(Transform storeResult) {
    Transform result
            = (storeResult == null) ? new Transform() : storeResult;
    Vector3f location = result.getTranslation();
    Quaternion orientation = result.getRotation();
    Vector3f scale = result.getScale();
    /*
     * Start with the rigid body's transform in physics/world coordinates.
     */
    PhysicsRigidBody body = getRigidBody();
    body.getPhysicsLocation(result.getTranslation());
    body.getPhysicsRotation(result.getRotation());
    result.setScale(body.getCollisionShape().getScale());
    /*
     * Convert to mesh coordinates.
     */
    Transform worldToMesh = getControl().meshTransform(null).invert();
    result.combineWithParent(worldToMesh);
    /*
     * Subtract the body's local offset, rotated and scaled.
     */
    Vector3f meshOffset = localOffset(null);
    meshOffset.multLocal(scale);
    orientation.mult(meshOffset, meshOffset);
    location.subtractLocal(meshOffset);

    return result;
}
 
Example 13
Source File: ConstraintDefinitionDistLimit.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void bake(Transform ownerTransform, Transform targetTransform, float influence) {
    if (this.getOwner() instanceof Bone && ((Bone) this.getOwner()).getParent() != null) {
        // distance limit does not work on bones who have parent
        return;
    }

    Vector3f v = ownerTransform.getTranslation().subtract(targetTransform.getTranslation());
    float currentDistance = v.length();

    switch (mode) {
        case LIMITDIST_INSIDE:
            if (currentDistance >= dist) {
                v.normalizeLocal();
                v.multLocal(dist + (currentDistance - dist) * (1.0f - influence));
                ownerTransform.getTranslation().set(v.addLocal(targetTransform.getTranslation()));
            }
            break;
        case LIMITDIST_ONSURFACE:
            if (currentDistance > dist) {
                v.normalizeLocal();
                v.multLocal(dist + (currentDistance - dist) * (1.0f - influence));
                ownerTransform.getTranslation().set(v.addLocal(targetTransform.getTranslation()));
            } else if (currentDistance < dist) {
                v.normalizeLocal().multLocal(dist * influence);
                ownerTransform.getTranslation().set(targetTransform.getTranslation().add(v));
            }
            break;
        case LIMITDIST_OUTSIDE:
            if (currentDistance <= dist) {
                v = targetTransform.getTranslation().subtract(ownerTransform.getTranslation()).normalizeLocal().multLocal(dist * influence);
                ownerTransform.getTranslation().set(targetTransform.getTranslation().add(v));
            }
            break;
        default:
            throw new IllegalStateException("Unknown distance limit constraint mode: " + mode);
    }
}
 
Example 14
Source File: AdvancedAbstractEditor3DPart.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Move a camera to side.
 *
 * @param value the value to move.
 */
@JmeThread
private void moveSideCamera(final float value, final boolean isAction, final boolean isPressed, final int key) {

    if (!canCameraMove()) {
        return;
    } else if (isAction && isPressed) {
        startCameraMoving(key);
    } else if (isAction) {
        finishCameraMoving(key, false);
    }

    if (!isCameraMoving() || isAction) {
        return;
    }

    final EditorCamera editorCamera = getEditorCamera();
    if (editorCamera == null) {
        return;
    }

    final Camera camera = EditorUtil.getGlobalCamera();
    final Node nodeForCamera = getNodeForCamera();

    final LocalObjects local = LocalObjects.get();
    final Vector3f left = camera.getLeft(local.nextVector());
    left.multLocal(value * cameraSpeed);
    left.addLocal(nodeForCamera.getLocalTranslation());

    nodeForCamera.setLocalTranslation(left);
}
 
Example 15
Source File: TestLightScattering.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
    public void simpleInitApp() {
        // put the camera in a bad position
        cam.setLocation(new Vector3f(55.35316f, -0.27061665f, 27.092093f));
        cam.setRotation(new Quaternion(0.010414706f, 0.9874893f, 0.13880467f, -0.07409228f));
//        cam.setDirection(new Vector3f(0,-0.5f,1.0f));
//        cam.setLocation(new Vector3f(0, 300, -500));
        //cam.setFrustumFar(1000);
        flyCam.setMoveSpeed(10);
        Material mat = assetManager.loadMaterial("Textures/Terrain/Rocky/Rocky.j3m");
        Spatial scene = assetManager.loadModel("Models/Terrain/Terrain.mesh.xml");
        TangentBinormalGenerator.generate(((Geometry)((Node)scene).getChild(0)).getMesh());
        scene.setMaterial(mat);
        scene.setShadowMode(ShadowMode.CastAndReceive);
        scene.setLocalScale(400);
        scene.setLocalTranslation(0, -10, -120);

        rootNode.attachChild(scene);

        // load sky
        rootNode.attachChild(SkyFactory.createSky(assetManager,
                "Textures/Sky/Bright/FullskiesBlueClear03.dds", 
                SkyFactory.EnvMapType.CubeMap));

        DirectionalLight sun = new DirectionalLight();
        Vector3f lightDir = new Vector3f(-0.12f, -0.3729129f, 0.74847335f);
        sun.setDirection(lightDir);
        sun.setColor(ColorRGBA.White.clone().multLocal(2));
        scene.addLight(sun);


        FilterPostProcessor fpp = new FilterPostProcessor(assetManager);
        int numSamples = getContext().getSettings().getSamples();
        if (numSamples > 0) {
            fpp.setNumSamples(numSamples);
        }
        Vector3f lightPos = lightDir.multLocal(-3000);
        LightScatteringFilter filter = new LightScatteringFilter(lightPos);
        LightScatteringUI ui = new LightScatteringUI(inputManager, filter);
        fpp.addFilter(filter);
        viewPort.addProcessor(fpp);
    }
 
Example 16
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 17
Source File: ShadowUtil.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Updates the points array to contain the frustum corners of the given
 * camera. The nearOverride and farOverride variables can be used to
 * override the camera's near/far values with own values.
 *
 * TODO: Reduce creation of new vectors
 *
 * @param viewCam
 * @param nearOverride
 * @param farOverride
 */
public static void updateFrustumPoints(Camera viewCam,
        float nearOverride,
        float farOverride,
        float scale,
        Vector3f[] points) {

    Vector3f pos = viewCam.getLocation();
    Vector3f dir = viewCam.getDirection();
    Vector3f up = viewCam.getUp();

    float depthHeightRatio = viewCam.getFrustumTop() / viewCam.getFrustumNear();
    float near = nearOverride;
    float far = farOverride;
    float ftop = viewCam.getFrustumTop();
    float fright = viewCam.getFrustumRight();
    float ratio = fright / ftop;

    float near_height;
    float near_width;
    float far_height;
    float far_width;

    if (viewCam.isParallelProjection()) {
        near_height = ftop;
        near_width = near_height * ratio;
        far_height = ftop;
        far_width = far_height * ratio;
    } else {
        near_height = depthHeightRatio * near;
        near_width = near_height * ratio;
        far_height = depthHeightRatio * far;
        far_width = far_height * ratio;
    }

    Vector3f right = dir.cross(up).normalizeLocal();

    Vector3f temp = new Vector3f();
    temp.set(dir).multLocal(far).addLocal(pos);
    Vector3f farCenter = temp.clone();
    temp.set(dir).multLocal(near).addLocal(pos);
    Vector3f nearCenter = temp.clone();

    Vector3f nearUp = temp.set(up).multLocal(near_height).clone();
    Vector3f farUp = temp.set(up).multLocal(far_height).clone();
    Vector3f nearRight = temp.set(right).multLocal(near_width).clone();
    Vector3f farRight = temp.set(right).multLocal(far_width).clone();

    points[0].set(nearCenter).subtractLocal(nearUp).subtractLocal(nearRight);
    points[1].set(nearCenter).addLocal(nearUp).subtractLocal(nearRight);
    points[2].set(nearCenter).addLocal(nearUp).addLocal(nearRight);
    points[3].set(nearCenter).subtractLocal(nearUp).addLocal(nearRight);

    points[4].set(farCenter).subtractLocal(farUp).subtractLocal(farRight);
    points[5].set(farCenter).addLocal(farUp).subtractLocal(farRight);
    points[6].set(farCenter).addLocal(farUp).addLocal(farRight);
    points[7].set(farCenter).subtractLocal(farUp).addLocal(farRight);

    if (scale != 1.0f) {
        // find center of frustum
        Vector3f center = new Vector3f();
        for (int i = 0; i < 8; i++) {
            center.addLocal(points[i]);
        }
        center.divideLocal(8f);

        Vector3f cDir = new Vector3f();
        for (int i = 0; i < 8; i++) {
            cDir.set(points[i]).subtractLocal(center);
            cDir.multLocal(scale - 1.0f);
            points[i].addLocal(cDir);
        }
    }
}
 
Example 18
Source File: BasicShadowRenderer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
    public void postQueue(RenderQueue rq) {
        for (Spatial scene : viewPort.getScenes()) {
            ShadowUtil.getGeometriesInCamFrustum(scene, viewPort.getCamera(), ShadowMode.Receive, lightReceivers);
        }

        // update frustum points based on current camera
        Camera viewCam = viewPort.getCamera();
        ShadowUtil.updateFrustumPoints(viewCam,
                viewCam.getFrustumNear(),
                viewCam.getFrustumFar(),
                1.0f,
                points);

        Vector3f frustaCenter = new Vector3f();
        for (Vector3f point : points) {
            frustaCenter.addLocal(point);
        }
        frustaCenter.multLocal(1f / 8f);

        // update light direction
        shadowCam.setProjectionMatrix(null);
        shadowCam.setParallelProjection(true);
//        shadowCam.setFrustumPerspective(45, 1, 1, 20);

        shadowCam.lookAtDirection(direction, Vector3f.UNIT_Y);
        shadowCam.update();
        shadowCam.setLocation(frustaCenter);
        shadowCam.update();
        shadowCam.updateViewProjection();

        // render shadow casters to shadow map
        ShadowUtil.updateShadowCamera(viewPort, lightReceivers, shadowCam, points, shadowOccluders, shadowMapSize);
        if (shadowOccluders.size() == 0) {
            noOccluders = true;
            return;
        } else {
            noOccluders = false;
        }            
        
        Renderer r = renderManager.getRenderer();
        renderManager.setCamera(shadowCam, false);
        renderManager.setForcedMaterial(preshadowMat);

        r.setFrameBuffer(shadowFB);
        r.clearBuffers(true, true, true);
        viewPort.getQueue().renderShadowQueue(shadowOccluders, renderManager, shadowCam, true);
        r.setFrameBuffer(viewPort.getOutputFrameBuffer());

        renderManager.setForcedMaterial(null);
        renderManager.setCamera(viewCam, false);
    }
 
Example 19
Source File: BasicShadowRenderer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void postQueue(RenderQueue rq) {
        GeometryList occluders = rq.getShadowQueueContent(ShadowMode.Cast);
        if (occluders.size() == 0) {
            noOccluders = true;
            return;
        } else {
            noOccluders = false;
        }

        GeometryList receivers = rq.getShadowQueueContent(ShadowMode.Receive);

        // update frustum points based on current camera
        Camera viewCam = viewPort.getCamera();
        ShadowUtil.updateFrustumPoints(viewCam,
                viewCam.getFrustumNear(),
                viewCam.getFrustumFar(),
                1.0f,
                points);

        Vector3f frustaCenter = new Vector3f();
        for (Vector3f point : points) {
            frustaCenter.addLocal(point);
        }
        frustaCenter.multLocal(1f / 8f);

        // update light direction
        shadowCam.setProjectionMatrix(null);
        shadowCam.setParallelProjection(true);
//        shadowCam.setFrustumPerspective(45, 1, 1, 20);

        shadowCam.lookAtDirection(direction, Vector3f.UNIT_Y);
        shadowCam.update();
        shadowCam.setLocation(frustaCenter);
        shadowCam.update();
        shadowCam.updateViewProjection();

        // render shadow casters to shadow map
        ShadowUtil.updateShadowCamera(occluders, receivers, shadowCam, points);

        Renderer r = renderManager.getRenderer();
        renderManager.setCamera(shadowCam, false);
        renderManager.setForcedMaterial(preshadowMat);

        r.setFrameBuffer(shadowFB);
        r.clearBuffers(false, true, false);
        viewPort.getQueue().renderShadowQueue(ShadowMode.Cast, renderManager, shadowCam, true);
        r.setFrameBuffer(viewPort.getOutputFrameBuffer());

        renderManager.setForcedMaterial(null);
        renderManager.setCamera(viewCam, false);
    }
 
Example 20
Source File: BufferUtils.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Multiply and store a Vector3f in-buffer.
 *
 * @param toMult
 *            the vector to multiply against
 * @param buf
 *            the buffer to find the Vector3f within
 * @param index
 *            the position (in terms of vectors, not floats) of the vector
 *            to multiply
 */
public static void multInBuffer(Vector3f toMult, FloatBuffer buf, int index) {
    TempVars vars = TempVars.get();
    Vector3f tempVec3 = vars.vect1;
    populateFromBuffer(tempVec3, buf, index);
    tempVec3.multLocal(toMult);
    setInBuffer(tempVec3, buf, index);
    vars.release();
}