public void startDrag(Vector3f v3f) { dragPoint = new Vector2f(); dragPoint.setX(v3f.getX()); dragPoint.setY(v3f.getZ()); dragPositions.clear(); if (moveSmooth == false) { for (int i = 0; i < getSelectionCircles().size(); i++) { Vector2f v2f = new Vector2f(); v2f.x = getSelectionCircles().get(i).getDoodad().getLocation().getX(); v2f.y = getSelectionCircles().get(i).getDoodad().getLocation().getZ(); dragPositions.add(v2f); } } for (int i = 0; i < getSelectionCircles().size(); i++) { Vector2f v2f = new Vector2f(); v2f.x = getSelectionCircles().get(i).getDoodad().getLocation().getX(); v2f.y = getSelectionCircles().get(i).getDoodad().getLocation().getZ(); dragStartPositions.add(v2f); } }
/** * Generate a collision shape for a prop. * * @param propType the type of the prop (not null) * @param relativeSize the prop's size relative to standard (>0) * @param parts (not null) * @return a new instance */ private CollisionShape createShape(String propType, float relativeSize, List<Spatial> parts) { assert propType != null; assert relativeSize > 0f : relativeSize; assert parts != null; assert !parts.isEmpty(); if ("barrel".equals(propType)) { /* * Generate a cylindrical shape aligned with the Y-axis. */ float halfHeight = 0.5f * relativeSize; // meters float radius = 0.472f * relativeSize; // meters Vector3f halfExtents = new Vector3f(radius, halfHeight, radius); float scaleFactor = scene.getScaleFactor(); halfExtents.divideLocal(scaleFactor); CollisionShape shape = new CylinderCollisionShape(halfExtents, PhysicsSpace.AXIS_Y); return shape; } /* * Generate a compound shape composed of GImpact shapes, * one for each geometry. */ CompoundCollisionShape shape = new CompoundCollisionShape(); for (Spatial part : parts) { Geometry geometry = (Geometry) part; Mesh mesh = geometry.getMesh(); CollisionShape partShape = new GImpactCollisionShape(mesh); Vector3f scale = part.getWorldScale(); partShape.setScale(scale); shape.addChildShape(partShape, Vector3f.ZERO); } return shape; }
public void onAnalog(String name, float value, float tpf) { if ((Boolean) player.getUserData("alive")) { if (name.equals("mousePick")) { // shoot Bullet if (System.currentTimeMillis() - bulletCooldown > 83f) { bulletCooldown = System.currentTimeMillis(); Vector3f aim = getAimDirection(); Vector3f offset = new Vector3f(aim.y / 3, -aim.x / 3, 0); // init bullet 1 Spatial bullet = getSpatial("Bullet"); Vector3f finalOffset = aim.add(offset).mult(30); Vector3f trans = player.getLocalTranslation().add(finalOffset); bullet.setLocalTranslation(trans); bullet.addControl( new BulletControl( aim, settings.getWidth(), settings.getHeight(), particleManager, grid)); bulletNode.attachChild(bullet); // init bullet 2 Spatial bullet2 = getSpatial("Bullet"); finalOffset = aim.add(offset.negate()).mult(30); trans = player.getLocalTranslation().add(finalOffset); bullet2.setLocalTranslation(trans); bullet2.addControl( new BulletControl( aim, settings.getWidth(), settings.getHeight(), particleManager, grid)); bulletNode.attachChild(bullet2); sound.shoot(); } } } }
/** * Returns true iff the node contains at least one intersection, after sampling at the MaxDepth * level. */ public static boolean containsIntersection( OctreeNode octreeNode, int maxDepth, ArrayList<Primitive> primitives) { // First off, check if the node is null. if (octreeNode == null) { return false; } // Subdivide to the finest possible level. // The subdivision level equals 2^n, where n is max-current depth. int divisionLevel = 1 << (maxDepth - octreeNode.getDepth()); Vector3f startPoint = octreeNode.getMinBound(); Vector3f offset = octreeNode.getMaxBound().subtract(startPoint).divideLocal(divisionLevel); boolean sign = getValueAt(startPoint, primitives) > 0; Vector3f currentPoint = new Vector3f(); for (int i = 0; i < divisionLevel + 1; i++) { for (int j = 0; j < divisionLevel + 1; j++) { for (int k = 0; k < divisionLevel + 1; k++) { currentPoint.x = startPoint.x + i * offset.x; currentPoint.y = startPoint.y + j * offset.y; currentPoint.z = startPoint.z + k * offset.z; if (getValueAt(currentPoint, primitives) > 0 != sign) { return true; } } } } return false; }
/** * <code>rotateUpTo</code> is a utility function that alters the local rotation to point the Y * axis in the direction given by newUp. * * @param newUp the up vector to use - assumed to be a unit vector. */ public void rotateUpTo(Vector3f newUp) { TempVars vars = TempVars.get(); Vector3f compVecA = vars.vect1; Quaternion q = vars.quat1; // First figure out the current up vector. Vector3f upY = compVecA.set(Vector3f.UNIT_Y); Quaternion rot = localTransform.getRotation(); rot.multLocal(upY); // get angle between vectors float angle = upY.angleBetween(newUp); // figure out rotation axis by taking cross product Vector3f rotAxis = upY.crossLocal(newUp).normalizeLocal(); // Build a rotation quat and apply current local rotation. q.fromAngleNormalAxis(angle, rotAxis); q.mult(rot, rot); vars.release(); setTransformRefresh(); }
public double flt(Vector3f point, Vector3f A, Vector3f B) { Vector3f vec_b = B; Vector3f vec_a = A.subtract(vec_b); double L = vec_a.length(); return L * f1(point, A, B) - ft(point, A, B); }
@Override public void update(float tpf) { entities.applyChanges(); for (Entity e : entities) { // if the entity is off one side or the // other then teleport it Position pos = e.get(Position.class); Vector3f loc = pos.getLocation(); boolean changed = false; if (loc.x < min.x) { loc.x += max.x - min.x; changed = true; } else if (loc.x > max.x) { loc.x -= max.x - min.x; changed = true; } if (loc.y < min.y) { loc.y += max.y - min.y; changed = true; } else if (loc.y > max.y) { loc.y -= max.y - min.y; changed = true; } if (changed) { e.set(new Position(loc, pos.getFacing())); } } }
/** * Create a prop, add it to the scene with its base at the insertion point, and pick it. Assumes * that the application is in world-building mode. * * @param propType which kind of prop to add (not null) * @param relativeSize the prop's size relative to standard (>0) */ private void addAsPick(String propType, float relativeSize) { assert propType != null; assert relativeSize > 0f : relativeSize; /* * Create the prop. */ Node node = create(propType, relativeSize); /* * The new prop is to be the ONLY picked spatial, so unpick the rest. */ PickablesNode pickables = scene.getWorld().getPickables(); pickables.clearPick(); /* * Add and pick the prop. */ pickables.add(node); SpatialProperties.setPicked(node, true); /* * Initialize the prop's position. */ Cursor3DIndicator cursor3D = scene.getIndicators().getCursor3D(); Vector3f baseLocation = cursor3D.getWorldLocation(); float baseY = MySpatial.getMinY(node); Vector3f centerLocation = baseLocation.add(0f, -baseY, 0f); MySpatial.setWorldLocation(node, centerLocation); }
@Override protected void serialize(int i, Vector3f store) { int j = i * getTupleSize(); array[j] = store.getX(); array[j + 1] = store.getY(); array[j + 2] = store.getZ(); }
@Override public void simpleUpdate(float tpf) { Vector3f intersection = getWorldIntersection(); updateHintText(intersection); if (raiseTerrain) { if (intersection != null) { adjustHeight(intersection, 64, tpf * 60); } } else if (lowerTerrain) { if (intersection != null) { adjustHeight(intersection, 64, -tpf * 60); } } if (terrain != null && intersection != null) { float h = terrain.getHeight(new Vector2f(intersection.x, intersection.z)); Vector3f tl = terrain.getWorldTranslation(); marker.setLocalTranslation(tl.add(new Vector3f(intersection.x, h, intersection.z))); markerNormal.setLocalTranslation(tl.add(new Vector3f(intersection.x, h, intersection.z))); Vector3f normal = terrain.getNormal(new Vector2f(intersection.x, intersection.z)); ((Arrow) markerNormal.getMesh()).setArrowExtent(normal); } }
@SuppressWarnings("unused") private double cauchy(Vector3f point, Vector3f center) { Vector3f vec_r = point.subtract(center); double s = 0.85; // 0.85 - example on thesis; //kernel width double r_2 = vec_r.lengthSquared(); return 1.0 / ((1 + s * s * r_2) * (1 + s * s * r_2)); }
@Override public void getRandomPoint(Vector3f store) { do { store.x = (FastMath.nextRandomFloat() * 2f - 1f) * radius; store.y = (FastMath.nextRandomFloat() * 2f - 1f) * radius; store.z = (FastMath.nextRandomFloat() * 2f - 1f) * radius; } while (store.distance(center) > radius); }
/** * Warp into the scene on the nav mesh, finding the nearest cell. The currentCell and position3d * are updated and this new position is returned. This updates the state of the path finder! * * @return the new position in the nearest cell */ public Vector3f warp(Vector3f newPos) { Vector3f newPos2d = new Vector3f(newPos.x, 0, newPos.z); currentCell = navMesh.findClosestCell(newPos2d); currentPos3d.set(navMesh.snapPointToCell(currentCell, newPos2d)); currentPos3d.setY(newPos.getY()); currentPos.set(currentPos3d.getX(), currentPos3d.getZ()); return currentPos3d; }
/** * A variation of Hermite where a velocity is given only for the first point. It interpolates P0 * at t=0 and P1 at t=1. P(t) = (t^2 - 2*t + 1) * P0 + (-t^2 + 2*t) * P1 + (t^2 - t) * T0 * * @param P0 * @param T0 * @param P1 * @param t * @return */ private static Vector3f quadraticHermite(Vector3f P0, Vector3f T0, Vector3f P1, float t) { float t2 = t * t; Vector3f P = new Vector3f(); P.scaleAdd(t2 - 2 * t + 1, P0, P); P.scaleAdd(-t2 + 2 * t, P1, P); P.scaleAdd(t2 - t, T0, P); return P; }
/** * This method applies the variation to the particle with already set velocity. * * @param particle the particle to be affected */ protected void applyVelocityVariation(Particle particle) { particle.velocity.set(initialVelocity); temp.set(FastMath.nextRandomFloat(), FastMath.nextRandomFloat(), FastMath.nextRandomFloat()); temp.multLocal(2f); temp.subtractLocal(1f, 1f, 1f); temp.multLocal(initialVelocity.length()); particle.velocity.interpolate(temp, velocityVariation); }
/** * Centers the spatial in the origin of the world bound. * * @return The spatial on which this method is called, e.g <code>this</code>. */ public Spatial center() { Vector3f worldTrans = getWorldTranslation(); Vector3f worldCenter = getWorldBound().getCenter(); Vector3f absTrans = worldTrans.subtract(worldCenter); setLocalTranslation(absTrans); return this; }
protected void computeRandomSpawnPoint(Flight flight) { Vector3f position = new Vector3f( randomSpawnGenerator.nextInt(7000) - 3500, randomSpawnGenerator.nextInt(7000) - 3500, randomSpawnGenerator.nextInt(7000) - 3500); Quaternion rotation = new Quaternion(); rotation.lookAt(position.negate(), Vector3f.UNIT_Z); flight.setSpawn(new Spawn(position, rotation)); }
@Override public void onPreUpdate(float tpf) { Vector3f delta = velocity.mult(tpf); Vector3f pos = movedNode.getLocalTranslation().clone(); smal.checkMotionAllowed(pos, delta, normal); movedNode.setLocalTranslation(pos.add(delta)); velocity.set(0, 0, 0); normalAligned.rotateUpTo(normal); }
/** * Method for calculating new velocity of agent based on steering vector. * * @see AbstractSteeringBehavior#calculateSteering() * @return The new velocity for this agent based on steering vector */ protected Vector3f calculateNewVelocity() { agent.setAcceleration(calculateSteering().mult(1 / agentTotalMass())); velocity = velocity.add(agent.getAcceleration()); agent.setVelocity(velocity); if (velocity.length() > agent.getMaxMoveSpeed()) { velocity = velocity.normalize().mult(agent.getMaxMoveSpeed()); } return velocity; }
public double f1(Vector3f point, Vector3f A, Vector3f B) { // ****** basic parameters ****** Vector3f vec_b = B; Vector3f vec_a = A.subtract(vec_b); Vector3f vec_r = point; double L = vec_a.length(); Vector3f vec_d = vec_r.subtract(vec_b); double d = vec_d.length(); double h = vec_d.dot(vec_a.normalize()); // terms double s2 = s * s; double h2 = h * h; double lmh = L - h; double d2 = d * d; double p2 = 1 + s2 * (d2 - h2); double p = Math.sqrt(p2); double ww = p2 + s2 * h2; double qq = p2 + s2 * lmh * lmh; double sdp = s / p; double tpp = 2.0 * p2; double sp = s * p; double term = Math.atan(sdp * h) + Math.atan(sdp * lmh); return (h / ww + lmh / qq) / tpp + term / (tpp * sp); }
/** * Using this slot's camera, construct a pick ray for the specified screen coordinates. * * @param screenLocation screen coordinates (in pixels, measured from the lower left, not null, * unaffected) * @return new instance */ @Override public Ray pickRay(Vector2f screenLocation) { Validate.nonNull(screenLocation, "screen location"); Vector3f startLocation = cam.getWorldCoordinates(screenLocation, 0f); Vector3f farPoint = cam.getWorldCoordinates(screenLocation, 1f); Vector3f direction = farPoint.subtract(startLocation).normalizeLocal(); Ray result = new Ray(startLocation, direction); return result; }
private Vector3f getSpawnPosition() { Vector3f pos; do { pos = new Vector3f( new Random().nextInt(settings.getWidth()), new Random().nextInt(settings.getHeight()), 0); } while (pos.distanceSquared(player.getLocalTranslation()) < 8000); return pos; }
/** * Hermite interpolation of the points P0 to P1 at time t=0 to t=1 with the specified velocities * T0 and T1. * * @param P0 * @param T0 * @param P1 * @param T1 * @param t * @return */ private static Vector3f cubicHermite( Vector3f P0, Vector3f T0, Vector3f P1, Vector3f T1, float t) { float t2 = t * t; float t3 = t2 * t; Vector3f P = new Vector3f(); P.scaleAdd(2 * t3 - 3 * t2 + 1, P0, P); P.scaleAdd(t3 - 2 * t2 + t, T0, P); P.scaleAdd(-2 * t3 + 3 * t2, P1, P); P.scaleAdd(t3 - t2, T1, P); return P; }
private boolean lastCameraLocationsTheSame(List<Vector3f> locations) { boolean theSame = true; for (Vector3f l : locations) { for (Vector3f v : lastCameraLocations) { if (!v.equals(l)) { theSame = false; return false; } } } return theSame; }
public void rotateToPoint(Vector3f v3f) { for (int i = 0; i < getSelectionCircles().size(); i++) { Doodad d = getSelectionCircles().get(i).getDoodad(); Vector3f location = d.getLocation(); float rotation = (float) Math.atan2( (float) (v3f.getX() - location.getX()), (float) (v3f.getZ() - location.getZ())); d.setRotation(rotation); d.updateRotation(); } }
private void computeLength() { int M = 16; Vector3f old = null; float length = 0; for (int i = 0; i <= M; ++i) { Vector3f v = interpolate(i / (float) M).position; if (old != null) { length += old.distance(v); } old = v; } stepLength = length; }
public boolean calculateLod( TerrainPatch patch, List<Vector3f> locations, HashMap<String, UpdatedTerrainPatch> updates) { if (turnOffLod) { // set to full detail int prevLOD = patch.getLod(); UpdatedTerrainPatch utp = updates.get(patch.getName()); if (utp == null) { utp = new UpdatedTerrainPatch(patch); updates.put(utp.getName(), utp); } utp.setNewLod(0); utp.setPreviousLod(prevLOD); // utp.setReIndexNeeded(true); return true; } float[] lodEntropies = patch.getLodEntropies(); float cameraConstant = getCameraConstant(cam, pixelError); Vector3f patchPos = getCenterLocation(patch); // vector from camera to patch // Vector3f toPatchDir = locations.get(0).subtract(patchPos).normalizeLocal(); // float facing = cam.getDirection().dot(toPatchDir); float distance = patchPos.distance(locations.get(0)); // go through each lod level to find the one we are in for (int i = 0; i <= patch.getMaxLod(); i++) { if (distance < lodEntropies[i] * cameraConstant || i == patch.getMaxLod()) { boolean reIndexNeeded = false; if (i != patch.getLod()) { reIndexNeeded = true; // System.out.println("lod change: "+lod+" > "+i+" dist: // "+distance); } int prevLOD = patch.getLod(); UpdatedTerrainPatch utp = updates.get(patch.getName()); if (utp == null) { utp = new UpdatedTerrainPatch(patch); // save in here, do not update actual variables updates.put(utp.getName(), utp); } utp.setNewLod(i); utp.setPreviousLod(prevLOD); // utp.setReIndexNeeded(reIndexNeeded); return reIndexNeeded; } } return false; }
/** * Interpolates unspecified translation values for objectIndex from start to end. * * @param objectIndex Index to interpolate. * @param startPosIndex Starting translation index. * @param endPosIndex Ending translation index. */ private void fillVecs(int objectIndex, int startPosIndex, int endPosIndex) { keyframes.get(startPosIndex).look[objectIndex].getTranslation(unSyncbeginPos); keyframes.get(endPosIndex).look[objectIndex].getTranslation(unSyncendPos); float startTime = keyframes.get(startPosIndex).time; float endTime = keyframes.get(endPosIndex).time; float delta = endTime - startTime; Vector3f tempVec = new Vector3f(); for (int i = startPosIndex + 1; i < endPosIndex; i++) { float thisTime = keyframes.get(i).time; tempVec.interpolate(unSyncbeginPos, unSyncendPos, (thisTime - startTime) / delta); keyframes.get(i).look[objectIndex].setTranslation(tempVec); } }
private boolean maxDistanceExceeded(Vector3f vehiclePos) { // get box's position on xz-plane (ignore y component) Vector3f followBoxPosition = getPosition(); followBoxPosition.setY(0); // get vehicle's position on xz-plane (ignore y component) Vector3f vehiclePosition = vehiclePos; vehiclePosition.setY(0); // distance between box and vehicle float currentDistance = followBoxPosition.distance(vehiclePosition); // report whether maximum distance is exceeded return currentDistance > maxDistance; }
@Override protected void initialize(Application app) { ed = getState(EntityDataState.class).getEntityData(); entities = ed.getEntities(Position.class, ModelType.class); // Calculate how big min/max needs to be to incorporate // the full view + margin at z = 0 Camera cam = app.getCamera(); float z = cam.getViewToProjectionZ(cam.getLocation().z); Vector3f worldMin = cam.getWorldCoordinates(new Vector2f(0, 0), z); Vector3f worldMax = cam.getWorldCoordinates(new Vector2f(cam.getWidth(), cam.getHeight()), z); min = worldMin.addLocal(-margin, -margin, 0); max = worldMax.addLocal(margin, margin, 0); }