/** * Sets an object to animate. The object's index is <code>index</code> and it's parent index is * <code>parentIndex</code>. A parent index of -1 indicates it has no parent. * * @param objChange The spatial that will be updated by this SpatialTransformer. * @param index The index of that spatial in this transformer's array * @param parentIndex The parentIndex in this transformer's array for this Spatial */ public void setObject(Spatial objChange, int index, int parentIndex) { toChange[index] = objChange; pivots[index].setTranslation(objChange.getLocalTranslation()); pivots[index].setScale(objChange.getLocalScale()); pivots[index].setRotationQuaternion(objChange.getLocalRotation()); parentIndexes[index] = parentIndex; }
private void createBlackHole() { Spatial blackHole = getSpatial("Black Hole"); blackHole.setLocalTranslation(getSpawnPosition()); blackHole.addControl(new BlackHoleControl(particleManager, grid)); blackHole.setUserData("active", false); blackHoleNode.attachChild(blackHole); }
/** * Removes all physics controls and joints in the given spatial from the physics space (e.g. * before saving to disk) - recursive if node * * @param spatial the rootnode containing the physics objects */ public void removeAll(Spatial spatial) { if (spatial.getControl(RigidBodyControl.class) != null) { RigidBodyControl physicsNode = spatial.getControl(RigidBodyControl.class); // remove joints with physicsNode as BodyA List<PhysicsJoint> joints = physicsNode.getJoints(); for (Iterator<PhysicsJoint> it1 = joints.iterator(); it1.hasNext(); ) { PhysicsJoint physicsJoint = it1.next(); if (physicsNode.equals(physicsJoint.getBodyA())) { removeJoint(physicsJoint); // remove(physicsJoint.getBodyB()); } } remove(physicsNode); } else if (spatial.getControl(PhysicsControl.class) != null) { remove(spatial); } // recursion if (spatial instanceof Node) { List<Spatial> children = ((Node) spatial).getChildren(); for (Iterator<Spatial> it = children.iterator(); it.hasNext(); ) { Spatial spat = it.next(); removeAll(spat); } } }
private void createSeeker() { Spatial seeker = getSpatial("Seeker"); seeker.setLocalTranslation(getSpawnPosition()); seeker.addControl(new SeekerControl(player)); seeker.setUserData("active", false); enemyNode.attachChild(seeker); }
private void createWanderer() { Spatial wanderer = getSpatial("Wanderer"); wanderer.setLocalTranslation(getSpawnPosition()); wanderer.addControl(new WandererControl(settings.getWidth(), settings.getHeight())); wanderer.setUserData("active", false); enemyNode.attachChild(wanderer); }
private void manage(Entity e, float elapsedTime) { Model model = e.get(Model.class); if (!model.isCreated()) return; PlanarStance stance = e.get(PlanarStance.class); Spatial s = SpatialPool.models.get(e.getId()); // translation s.setLocalTranslation(TranslateUtil.toVector3f(stance.getCoord().get3D(stance.getElevation()))); // rotation Quaternion r = new Quaternion(); Point3D pu = stance.getUpVector(); Point3D pv = stance.getPlanarVector(); Vector3f u = TranslateUtil.toVector3f(pu).normalize(); Vector3f v = TranslateUtil.toVector3f(pv).normalize(); r.lookAt(v, u); // we correct the pitch of the unit because the direction is always flatten // this is only to follow the terrain relief double angle = Math.acos(pu.getDotProduct(pv) / (pu.getNorm() * pv.getNorm())); r = r.mult( new Quaternion() .fromAngles( (float) (-angle + AngleUtil.RIGHT + model.getPitchFix()), (float) (model.getRollFix()), (float) (model.getYawFix()))); s.setLocalRotation(r); }
/** * 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; }
/** * issues a command with a location target to the selected entities * * @param command * @param location */ private void doCommand(int command, Vector3f location) { for (Iterator<Spatial> it = selectedEntities.iterator(); it.hasNext(); ) { Spatial spatial1 = it.next(); CommandControl commandControl = spatial1.getControl(CommandControl.class); if (commandControl == null) { return; } try { Command commandInst = commands.get(command).newInstance(); commandInst.setPriority(10); commandControl.clearCommands(); commandControl.initializeCommand(commandInst); Command.TargetResult info = commandInst.setTargetLocation(location); if (info == Command.TargetResult.Accept || info == Command.TargetResult.AcceptEnemy || info == Command.TargetResult.AcceptFriendly) { commandControl.addCommand(commandInst); } } catch (InstantiationException ex) { Logger.getLogger(UserCommandControl.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(UserCommandControl.class.getName()).log(Level.SEVERE, null, ex); } } }
@Override public void simpleUpdate(float tpf) { time += tpf; int random = rand.nextInt(2000); float mult1 = 1.0f; float mult2 = 1.0f; if (random < 500) { mult1 = 1.0f; mult2 = 1.0f; } else if (random < 1000) { mult1 = -1.0f; mult2 = 1.0f; } else if (random < 1500) { mult1 = 1.0f; mult2 = -1.0f; } else if (random <= 2000) { mult1 = -1.0f; mult2 = -1.0f; } box = batchNode.getChild("Box" + random); if (box != null) { Vector3f v = box.getLocalTranslation(); box.setLocalTranslation( v.x + FastMath.sin(time * mult1) * 20, v.y + (FastMath.sin(time * mult1) * FastMath.cos(time * mult1) * 20), v.z + FastMath.cos(time * mult2) * 20); } terrain.setLocalRotation(new Quaternion().fromAngleAxis(time, Vector3f.UNIT_Y)); }
private void randomizeTransform(Spatial spat) { spat.setLocalTranslation( (float) Math.random() * 10, (float) Math.random() * 10, (float) Math.random() * 10); spat.setLocalTranslation( (float) Math.random() * 10, (float) Math.random() * 10, (float) Math.random() * 10); spat.setLocalScale( (float) Math.random() * 2, (float) Math.random() * 2, (float) Math.random() * 2); }
public void changeStackAmount(int amount) { stacks = amount; int entityId = targetInterface.getSpatial().getUserData(UserData.ENTITY_ID); CmdBuffStacks cmdStacks = new CmdBuffStacks(entityId, buffId, stacks); Spatial spatial = targetInterface.getSpatial(); ServerFog fog = spatial.getControl(CEntityVariable.class).getAwareness().getFog(); fog.addCommand(spatial, cmdStacks); }
@Override public void simpleInitApp() { testRect = new Rect(50, 50, 200, 200); s_TreeNode = new Node(); s_AssetManager = assetManager; s_StateManager = stateManager; s_InputManager = inputManager; ObjectHelper.LoadObjectHelper(); ItemInformation.InitItemInfo(); mouseInput.setCursorVisible(true); flyCam.setEnabled(false); bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); mainScene = new Scene(); mainScene.initScene(rootNode, viewPort); sun = new Sun(); sun.initSun(rootNode, viewPort, cam); inventory = new Inventory(this, guiNode, rootNode, cam, mainScene.sceneModel); Spatial mushroom = assetManager.loadModel("Models/MushroomAnim2/mushroom.mesh.xml"); mushroom.rotate(0, 77, 0); player = new PlayerNode(mushroom, inputManager, cam, mainScene.sceneModel); player.getCharacterControl().setPhysicsLocation(new Vector3f(0, 4f, 0)); rootNode.attachChild(player); bulletAppState.getPhysicsSpace().add(player); Spatial model = ObjectHelper.AddModel(new Vector3f(5, 0, 5), "tree"); Spatial model1 = ObjectHelper.AddModel(new Vector3f(5, 0, 8), "rock"); s_TreeNode.attachChild(model1); s_TreeNode.attachChild(model); rootNode.attachChild(s_TreeNode); bulletAppState.getPhysicsSpace().enableDebug(assetManager); hudText = new BitmapText(guiFont, false); hudText.setSize(guiFont.getCharSet().getRenderedSize()); hudText.setColor(ColorRGBA.White); hudText.setLocalTranslation(300, hudText.getLineHeight(), 0); guiNode.attachChild(hudText); /*Material mat = new Material(getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.setColor("Color", new ColorRGBA(1, 0, 0, 0.5f)); mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); for(int i = 0; i < 40; i++){ Geometry geo = new Geometry("Rect", new Quad(38, 38)); geo.setMaterial(mat); geo.setLocalTranslation(new Vector3f(inventory.inventorySlots[i].rect.x, inventory.inventorySlots[i].rect.y, 0)); guiNode.attachChild(geo); }*/ }
public void registerAllAndroidDevicesInScenario() { List<Spatial> devices = SpatialUtils.getSpatialsByRole(app.getRootNode(), "AndroidDevice"); for (Spatial device : devices) { String id = device.getUserData("ID"); if (id != null) { addDevice(id, (Node) device); } } }
@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); }
/** * Visit each scene graph element ordered by BFS * * @param visitor */ public void breadthFirstTraversal(SceneGraphVisitor visitor) { Queue<Spatial> queue = new LinkedList<Spatial>(); queue.add(this); while (!queue.isEmpty()) { Spatial s = queue.poll(); visitor.visit(s); s.breadthFirstTraversal(visitor, queue); } }
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(); } } } }
public void simpleInitApp() { Node scene = (Node) assetManager.loadModel("Scenes/DotScene/DotScene.scene"); System.out.println("Scene: " + scene); Spatial testNode = scene.getChild("TestNode"); System.out.println("TestNode: " + testNode); for (String key : testNode.getUserDataKeys()) { System.out.println("Property " + key + " = " + testNode.getUserData(key)); } }
private Spatial constructPillar(Node node, Point p, Quaternion quat) { Spatial part = assetManager.loadModel(getPillarResource()); resetAndMoveSpatial(part, new Point(0, 0), p); if (quat != null) { part.rotate(quat); } node.attachChild(part); return part; }
public static Spatial findSpatialByControl(Spatial sp, Class<? extends Control> aClass) { if (sp.getControl(aClass) == null) { if (sp.getParent() != null) { return findSpatialByControl(sp.getParent(), aClass); } else { return null; } } else { return sp; } }
/** * Create a prop without adding it to the scene. * * @param propType which kind of prop to add (not null) * @param relativeSize the prop's size relative to standard (>0) * @return a new node to represent the prop, or null if the model is invalid */ private Node create(String propType, float relativeSize) { assert propType != null; assert relativeSize > 0f : relativeSize; Node propNode = loadModel(propType); Node modelNode = (Node) propNode.getChild(0); List<Spatial> parts = modelNode.getChildren(); /* * Texture each part of the prop and specify its hardness. */ for (Spatial part : parts) { String partName = part.getName(); if (!(part instanceof Geometry)) { logger.log(Level.SEVERE, "Prop part {0} is not a geometry.", MyString.quote(partName)); return null; } String materialName = material(partName); SpatialProperties.setHardness(part, materialName); Material material = Assets.loadBlockMaterial(materialName); part.setMaterial(material); } /* * Set the scale factor. */ float scaleFactor = scene.getScaleFactor(); float modelScale = relativeSize / scaleFactor; propNode.setLocalScale(modelScale); assert getRelativeSize(propNode) == relativeSize : relativeSize; /* * Set other properties. */ propNode.setShadowMode(RenderQueue.ShadowMode.CastAndReceive); /* * Give the prop a physics control. */ CollisionShape shape = createShape(propType, relativeSize, parts); float mass = calculateMass(propType, relativeSize); RigidBodyControl rigidBodyControl = new RigidBodyControl(shape, mass); propNode.addControl(rigidBodyControl); /* * Configure the physics control. */ rigidBodyControl.setFriction(friction); scene.getWorld().getPhysics().addObject(rigidBodyControl); /* * Give the prop a PickedControl. */ SpatialProperties.setPickType(propNode, pickType); PickedControl pickedControl = new PickedControl(); propNode.addControl(pickedControl); return propNode; }
/** * Duplicate a prop. Duplicating differs from cloning because the duplicate gets a unique name and * any descendants of the duplicate get renamed to match. Besides, cloning doesn't work well on * physics controls. * * @param originalProp which prop to duplicate (not null) * @return the new prop */ public Node duplicate(Spatial originalProp) { String name = originalProp.getName(); logger.log(Level.INFO, "duplicating prop {0}", MyString.quote(name)); String propType = SpatialProperties.getPrefixType(originalProp); float relativeSize = originalProp.getWorldScale().x; Vector3f centerLocation = MySpatial.getWorldLocation(originalProp); Quaternion orientation = MySpatial.getWorldOrientation(originalProp); Node result = add(propType, relativeSize, centerLocation, orientation); return result; }
protected Spatial makeCharacter() { // load a character from jme3test-test-data Spatial golem = assetManager.loadModel("Models/Oto/Oto.mesh.xml"); golem.scale(0.5f); golem.setLocalTranslation(-1.0f, -1.5f, -0.6f); // We must add a light to make the model visible DirectionalLight sun = new DirectionalLight(); sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f)); golem.addLight(sun); return golem; }
public static float getHeight(Vector2f position) { // Search for a TerrainQuad that corresponds to the specified position for (Spatial spatial : Terrain.node.getChildren()) { Terrain terrain = spatial.getControl(Terrain.class); if (terrain != null) { float result = terrain.quad.getHeight(position); if (result != Float.NaN) return result; } } // Return NaN if no TerrainQuad underlies the requested position return Float.NaN; }
public void destroy() { CmdBuff buffCommand = generateBuffCommand(false); if (buffCommand != null) { Spatial spatial = targetInterface.getSpatial(); ServerFog fog = spatial.getControl(CEntityVariable.class).getAwareness().getFog(); fog.addCommand(spatial, buffCommand); } for (EndEventListener endHandler : buffEndHandlers) { endHandler.buffEnded(); } }
public void simpleInitApp() { renderManager.setAlphaToCoverage(true); cam.setLocation(new Vector3f(0.14914267f, 0.58147097f, 4.7686534f)); cam.setRotation(new Quaternion(-0.0044764364f, 0.9767943f, 0.21314798f, 0.020512417f)); // cam.setLocation(new Vector3f(2.0606942f, 3.20342f, 6.7860126f)); // cam.setRotation(new Quaternion(-0.017481906f, 0.98241085f, -0.12393151f, // -0.13857932f)); viewPort.setBackgroundColor(ColorRGBA.DarkGray); Quad q = new Quad(20, 20); q.scaleTextureCoordinates(Vector2f.UNIT_XY.mult(5)); Geometry geom = new Geometry("floor", q); Material mat = assetManager.loadMaterial("Textures/Terrain/Pond/Pond.j3m"); geom.setMaterial(mat); geom.rotate(-FastMath.HALF_PI, 0, 0); geom.center(); geom.setShadowMode(ShadowMode.Receive); rootNode.attachChild(geom); // create the geometry and attach it Spatial teaGeom = assetManager.loadModel("Models/Tree/Tree.mesh.j3o"); teaGeom.setQueueBucket(Bucket.Transparent); teaGeom.setShadowMode(ShadowMode.Cast); makeToonish(teaGeom); AmbientLight al = new AmbientLight(); al.setColor(ColorRGBA.White.mult(2)); rootNode.addLight(al); DirectionalLight dl1 = new DirectionalLight(); dl1.setDirection(new Vector3f(1, -1, 1).normalizeLocal()); dl1.setColor(new ColorRGBA(0.965f, 0.949f, 0.772f, 1f).mult(0.7f)); rootNode.addLight(dl1); DirectionalLight dl = new DirectionalLight(); dl.setDirection(new Vector3f(-1, -1, -1).normalizeLocal()); dl.setColor(new ColorRGBA(0.965f, 0.949f, 0.772f, 1f).mult(0.7f)); rootNode.addLight(dl); rootNode.attachChild(teaGeom); FilterPostProcessor fpp = new FilterPostProcessor(assetManager); CartoonEdgeFilter toon = new CartoonEdgeFilter(); toon.setEdgeWidth(0.5f); toon.setEdgeIntensity(1.0f); toon.setNormalThreshold(0.8f); fpp.addFilter(toon); viewPort.addProcessor(fpp); }
@Override public void simpleInitApp() { // sun DirectionalLight dl = new DirectionalLight(); dl.setDirection(new Vector3f(-0.1f, -1f, -1).normalizeLocal()); dl.setColor(ColorRGBA.Orange); rootNode.addLight(dl); // ambient light AmbientLight al = new AmbientLight(); al.setColor(new ColorRGBA(0.1f, 0.1f, 0.1f, 1.0f)); rootNode.addLight(al); // floor Material textureMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); textureMat.setTexture("ColorMap", assetManager.loadTexture("myAssets/Textures/woodFloor.jpg")); Box floor = new Box(Vector3f.ZERO, 20.0f, 0.01f, 20.0f); Geometry floorGeom = new Geometry("Floor", floor); floorGeom.setMaterial(textureMat); rootNode.attachChild(floorGeom); // object Spatial tree = assetManager.loadModel("Models/Tree/Tree.mesh.j3o"); tree.setQueueBucket(Bucket.Transparent); rootNode.attachChild(tree); // projector PApplet applet = new ColorBarsPApplet(); PAppletProjectorNode projectorNode = new PAppletProjectorNode("projector0", assetManager, applet, 200, 200, true); rootNode.attachChild(projectorNode); rootNode.attachChild( projectorNode .getFrustmMdel()); // if you don't want to see frustum, please don't attach it to // rootNode. // projector should be added to TextureProjectorRenderer, and TextureProjectorRenderer should be // added to ViewPort. TextureProjectorRenderer ptr = new TextureProjectorRenderer(assetManager); ptr.getTextureProjectors().add(projectorNode.getProjector()); viewPort.addProcessor(ptr); // projector is a kind of Shadow, and following processes are necessary for Shadow Rendering. floorGeom.setShadowMode(ShadowMode.Receive); tree.setShadowMode(ShadowMode.CastAndReceive); // tree makes and receives shadow projectorNode.setLocalTranslation(new Vector3f(0, 10, 0)); // move the projector, projectorNode.lookAt( new Vector3f(0, 0, 0), Vector3f.UNIT_X); // and make it to look at where you want. // cam cam.setLocation(Vector3f.UNIT_XYZ.mult(10.0f)); // camera moves to 10, 10, 10 cam.lookAt(Vector3f.ZERO, Vector3f.UNIT_Y); // and looks at 0,0,0. }
public void getChildMap(List<Spatial> res, Node parent, Node n, String name, boolean raypick) { for (Spatial child : n.getChildren()) { if (child instanceof Node) { getChildMap(res, parent, (Node) child, name, raypick); } if (child.getName() != null && child.getName().startsWith(name)) { if (raypick && child instanceof Geometry) { child.setUserData(ENTITY_GEOMETRY_REFERENCE, parent); } res.add(child); } } }
/** Indicate that the bounding of this spatial has changed and that a refresh is required. */ protected void setBoundRefresh() { refreshFlags |= RF_BOUND; Spatial p = parent; while (p != null) { if ((p.refreshFlags & RF_BOUND) != 0) { return; } p.refreshFlags |= RF_BOUND; p = p.parent; } }
public void onAction(String name, boolean isPressed, float tpf) { if ((Boolean) player.getUserData("alive")) { if (name.equals("up")) { player.getControl(PlayerControl.class).up = isPressed; } else if (name.equals("down")) { player.getControl(PlayerControl.class).down = isPressed; } else if (name.equals("left")) { player.getControl(PlayerControl.class).left = isPressed; } else if (name.equals("right")) { player.getControl(PlayerControl.class).right = isPressed; } } }
private void killPlayer() { player.removeFromParent(); player.getControl(PlayerControl.class).reset(); player.setUserData("alive", false); player.setUserData("dieTime", System.currentTimeMillis()); enemyNode.detachAllChildren(); blackHoleNode.detachAllChildren(); particleManager.playerExplosion(player.getLocalTranslation()); if (!hud.removeLife()) { hud.endGame(); gameOver = true; } }