com.jme3.scene.Node

Here are the examples of the java api com.jme3.scene.Node taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

311 Examples 7

19 Source : GreebleSkel.java
with Apache License 2.0
from twak

public clreplaced GreebleSkel {

    private static final double TILE_UV_SCALE = 0.4;

    private static final String TILE_TEXTURED = "tile_textured";

    private static final String TILE = "tile";

    private static final String BRICK = "brick";

    public static final String TILE_JPG = "tile.jpg";

    public static final String BRICK_JPG = "brick.jpg";

    public static final String Appearance = "appearance";

    Tweed tweed;

    Node node = new Node();

    OnClick onClick;

    GreebleGrid greebleGrid;

    // boolean isTextured = false;
    // DRectangle roofBounds;
    private MiniRoof miniroof;

    public static float[] BLANK_ROOF = new float[] { 0 / 255f, 170 / 255f, 255 / 255f, 1.0f }, BLANK_WALL = new float[] { 255 / 255f, 170 / 255f, 0 / 255f, 1.0f };

    SuperFace sf;

    public Map<SuperEdge, Face> occluderLookup;

    public GreebleSkel(Tweed tweed, SuperFace sf) {
        this.tweed = tweed;
        this.sf = sf;
    }

    public Node showSkeleton(Output output, OnClick onClick, MiniRoof roof) {
        this.onClick = onClick;
        this.miniroof = roof;
        createMesh(output);
        return node;
    }

    private void createMesh(Output output) {
        float[] roofColor = BLANK_ROOF;
        if (output.faces == null)
            return;
        roofColor = Colourz.toF4(miniroof.roofTexApp.color);
        Set<MiniFacade> allMFs = new HashSet<>();
        for (Face f : output.faces.values()) {
            WallTag wt = ((WallTag) GreebleHelper.getTag(f.profile, WallTag.clreplaced));
            if (wt != null) {
                if (wt.miniFacade != null)
                    allMFs.add(wt.miniFacade);
            }
        }
        if (tweed != null)
            for (MiniFacade mf : allMFs) {
                mf.facadeTexApp.resetPostProcessState();
                mf.featureGen.valueList().stream().forEach(r -> r.panesLabelApp.renderedOnFacade = false);
            }
        List<List<Face>> chains = Campz.findChains(output);
        // give each minifacade a chance to update its features based on the skeleton result
        if (tweed != null)
            for (List<Face> chain : chains) {
                Set<WallTag> opt = chain.stream().flatMap(f -> f.profile.stream()).filter(tag -> tag instanceof WallTag).map(t -> (WallTag) t).collect(Collectors.toSet());
                for (WallTag wt : opt) {
                    MiniFacade mf = wt.miniFacade;
                    PostProcessState pps = mf.facadeTexApp.postState;
                    Edge e = chain.get(0).edge;
                    Line megafacade = new Line(e.end.x, e.end.y, e.start.x, e.start.y);
                    double mfl = megafacade.length();
                    Vector2d dir = megafacade.dir();
                    if (dir.length() == 0)
                        continue;
                    LinearForm3D lf = new LinearForm3D(new Vector3d(-dir.y, dir.x, 0), e.start);
                    for (Face f : chain) for (Loop<Point2d> face : projectTo(megafacade, mfl, lf, f)) if (GreebleHelper.getTag(f.profile, WallTag.clreplaced) != null)
                        pps.wallFaces.add(face);
                    else
                        pps.roofFaces.add(face);
                    if (occluderLookup != null)
                        for (Object o : wt.occlusions) {
                            Face f = occluderLookup.get(o);
                            if (f != null)
                                pps.occluders.addAll(projectTo(megafacade, mfl, lf, f));
                        }
                    mf.width = chain.get(0).edge.length();
                }
            }
        for (MiniFacade mf : allMFs) {
            PostProcessState pps = mf.facadeTexApp.postState;
            pps.outerWallRect = GreebleHelper.findRect(pps.wallFaces);
            mf.featureGen.update();
        }
        if (// just calculating dormer locations
        tweed != null)
            greebleGrid = new GreebleGrid(tweed, new MMeshBuilderCache());
        // generate geometry for each face
        for (List<Face> chain : chains) {
            Optional<Tag> opt = chain.stream().flatMap(f -> f.profile.stream()).filter(tag -> tag instanceof WallTag).findAny();
            WallTag wt = null;
            MiniFacade mf2 = null;
            Set<QuadF> processedFeatures = new HashSet<>();
            Line megafacade = new Line();
            if (opt.isPresent() && (wt = (WallTag) opt.get()).miniFacade != null) {
                mf2 = wt.miniFacade;
                {
                    Edge e = chain.get(0).edge;
                    // we might rotate the facade to apply a set of features to a different side of the building.
                    megafacade.set(e.end.x, e.end.y, e.start.x, e.start.y);
                }
                if (false && TweedSettings.settings.snapFacadeWidth) {
                    mf2 = new MiniFacade(wt.miniFacade);
                    mf2.facadeTexApp = wt.miniFacade.facadeTexApp;
                    mf2.facadeLabelApp = wt.miniFacade.facadeLabelApp;
                    mf2.facadeSuperApp = wt.miniFacade.facadeSuperApp;
                    // move/scale mf horizontally from mean-image-location to mesh-facade-location
                    double[] meshSE = findSE(wt.miniFacade, megafacade, chain);
                    mf2.scaleX(meshSE[0], meshSE[1]);
                }
                mf2.featureGen.values().stream().flatMap(k -> k.stream()).map(r -> new QuadF(r, megafacade)).forEach(q -> processedFeatures.add(q));
            }
            for (QuadF q1 : processedFeatures) q1.original.panesLabelApp.coveringRoof = new Loop<>();
            if (tweed != null) {
                Set<QuadF> allFeatures = new LinkedHashSet<>();
                allFeatures.addAll(processedFeatures);
                for (Face f : chain) try {
                    face(f, mf2, processedFeatures, megafacade);
                } catch (Throwable th) {
                    th.printStackTrace();
                }
                allFeatures.removeAll(processedFeatures);
                for (QuadF q1 : allFeatures) {
                    if (q1.foundAll())
                        if (q1.original.getFeat() == Feature.WINDOW || q1.original.getFeat() == Feature.SHOP || q1.original.getFeat() == Feature.DOOR) {
                            q1.original.panesLabelApp.renderedOnFacade = true;
                        }
                }
            }
            if ((wt != null && sf.buildingApp.createDormers && !wt.miniFacade.facadeLabelApp.disableDormers) || TweedSettings.settings.createDormers) {
                Iterator<QuadF> quit = processedFeatures.iterator();
                while (quit.hasNext()) {
                    QuadF w = quit.next();
                    if (w.original.getFeat() == Feature.DOOR && w.foundAll())
                        w.original.panesLabelApp.renderedOnFacade = true;
                    else if ((w.original.getFeat() == Feature.WINDOW || w.original.getFeat() == Feature.SHOP) && w.foundAll()) {
                        w.original.panesLabelApp.renderedOnFacade = true;
                        w.original.panesLabelApp.coveringRoof = new Loop<Point2d>();
                        if (greebleGrid != null)
                            greebleGrid.createDormerWindow(miniroof, w, greebleGrid.mbs.WOOD, greebleGrid.mbs.GLreplaced, (float) w.original.attachedHeight.get(Feature.SILL).depth, (float) w.original.attachedHeight.get(Feature.SILL).d, (float) w.original.attachedHeight.get(Feature.CORNICE).d, 0.6, 0.9);
                        quit.remove();
                    }
                }
            }
            if (greebleGrid != null) {
                addFloor(greebleGrid.mbs, sf);
                // edges( output, roofColor );
                // output per-material objects
                greebleGrid.mbs.attachAll(tweed, node, new ClickMe() {

                    @Override
                    public void clicked(Object data) {
                        try {
                            SwingUtilities.invokeAndWait(new Runnable() {

                                @Override
                                public void run() {
                                    selected(output, node, findSuperEdge(output, chain), data instanceof Spatial ? (((Object[]) ((Spatial) data).getUserData(Appearance))[0]) : null);
                                }
                            });
                        } catch (Throwable th) {
                            th.printStackTrace();
                        }
                    }
                });
            }
        }
    }

    private void addFloor(MMeshBuilderCache mbs, SuperFace sf2) {
        MatMeshBuilder faceColor = greebleGrid.mbs.get(BRICK + sf2.hashCode(), Colourz.to4(GreebleSkel.BLANK_WALL), sf2);
        Loop<Point2d> pts = sf2.toLoop();
        Matrix4d mat = new Matrix4d();
        mat.setIdenreplacedy();
        faceColor.add(pts.singleton(), mat);
    }

    private LoopL<Point2d> projectTo(Line megafacade, double mfl, LinearForm3D lf, Face f) {
        if (f == null)
            return new LoopL<>();
        return f.points.new Map<Point2d>() {

            @Override
            public Point2d map(Loopable<Point3d> input) {
                Point3d i = input.get();
                Point3d inSpace = lf.project(i);
                Point2d onGround = new Point2d(inSpace.x, inSpace.y);
                return new Point2d(megafacade.findPPram(onGround) * mfl, inSpace.z);
            }
        }.run();
    }

    public interface OnClick {

        void selected(Output output, Node node, SuperEdge superEdge, Object ha);
    }

    private void selected(Output output, Node out, SuperEdge superEdge, Object ha) {
        if (onClick != null)
            onClick.selected(output, out, superEdge, ha);
    }

    private SuperEdge findSuperEdge(Output output, List<Face> chain) {
        ColumnProperties col = ((PlanSkeleton) output.skeleton).getDefiningColumn(chain.get(0).edge);
        if (col == null)
            return null;
        Bar bar = col.defBar;
        SETag set = ((SETag) GreebleHelper.getTag(bar.tags, SETag.clreplaced));
        return set == null ? null : set.se;
    }

    private static double[] findSE(MiniFacade mf, Line l, List<Face> chain) {
        double mlen = l.length();
        double lowest = Double.MAX_VALUE;
        Face bestFace = null;
        for (Face f : chain) {
            double[] bounds = Loopz.minMax(f.getLoopL());
            if (bounds[5] - bounds[4] > 1 && bounds[4] < lowest) {
                bestFace = f;
                lowest = bounds[4];
            }
        }
        if (bestFace == null)
            // !
            return new double[] { mf.left, mf.left + mf.width };
        List<Double> params = bestFace.getLoopL().streamE().map(p3 -> l.findPPram(new Point2d(p3.x, p3.y))).collect(Collectors.toList());
        double[] out = new double[] { params.stream().mapToDouble(x -> x).min().getAsDouble() * mlen, params.stream().mapToDouble(x -> x).max().getAsDouble() * mlen };
        // if good, stretch whole minifacade to mesh
        if (Mathz.inRange((out[1] - out[0]) / (mf.width), 0.66, 1.4))
            return out;
        // else snap to the closest of start/end
        if (l.fromPPram(out[0] / mlen).distance(l.fromPPram(mf.left / mlen)) > l.fromPPram(out[1] / mlen).distance(l.fromPPram((mf.left + mf.width) / mlen)))
            return new double[] { out[1] - mf.width, out[1] };
        else
            return new double[] { out[0], out[0] + mf.width };
    }

    private void face(Face f, MiniFacade mf, Set<QuadF> features, Line megafacade) {
        MatMeshBuilder faceColor = greebleGrid.mbs.ERROR;
        WallTag wt = null;
        for (Tag t : f.profile) {
            if (t instanceof WallTag) {
                wt = ((WallTag) t);
                FacadeTexApp mfa = mf.facadeTexApp;
                if (mfa.texture == null)
                    faceColor = greebleGrid.mbs.get(BRICK + mfa.hashCode(), mfa.color, mf);
                else
                    switch(mfa.appMode) {
                        case Off:
                            faceColor = greebleGrid.mbs.get(BRICK + mfa.hashCode(), mfa.color, mf);
                            break;
                        case Bitmap:
                            faceColor = greebleGrid.mbs.getTexture("brick_" + mfa.hashCode(), BRICK_JPG, mf);
                            break;
                        case Net:
                            faceColor = greebleGrid.mbs.getTexture("wall_" + mfa.texture + mfa.hashCode(), mfa.texture, mf);
                            break;
                    }
            } else if (t instanceof RoofTag) {
                RoofTag rt = (RoofTag) t;
                RoofTexApp ra = miniroof.roofTexApp;
                switch(ra.appMode) {
                    case Off:
                        faceColor = greebleGrid.mbs.get(TILE, ra.color, miniroof);
                        break;
                    case Bitmap:
                        faceColor = greebleGrid.mbs.getTexture(TILE_TEXTURED, TILE_JPG, miniroof);
                        break;
                    case Net:
                    case Parent:
                        if (ra.texture == null)
                            faceColor = greebleGrid.mbs.get(TILE, ra.color, miniroof);
                        else {
                            String texture = ra.getTexture(rt);
                            faceColor = greebleGrid.mbs.getTexture("roof_" + texture, texture, miniroof);
                        }
                        break;
                }
            }
        }
        if (f.edge.getPlaneNormal().angle(new Vector3d(0, 0, 1)) < 0.1)
            wt = null;
        for (Loop<Point3d> ll : f.getLoopL()) {
            for (Loopable<Point3d> lll : ll.loopableIterator()) if (lll.get().distance(lll.getNext().get()) > 200)
                return;
        }
        for (Loop<LPoint3d> ll : GreebleHelper.findPerimeter(f)) {
            mapTo2d(f, ll, mf, wt, features, faceColor, megafacade);
        }
    }

    protected static clreplaced QuadF {

        // potential window - either recessed, dormer (if a corner is between faces) , or deleted (if a corner outside all faces in chain)
        Point3d[] corners = new Point3d[4], found = new Point3d[4];

        public FRect original;

        public QuadF(FRect rect, Line megafacade) {
            this.original = rect;
            double mLen = megafacade.length();
            Point2d l = megafacade.fromPPram(rect.x / mLen), r = megafacade.fromPPram((rect.x + rect.width) / mLen);
            corners[0] = Pointz.to3(l, rect.y);
            corners[1] = Pointz.to3(l, rect.y + rect.height);
            corners[2] = Pointz.to3(r, rect.y + rect.height);
            corners[3] = Pointz.to3(r, rect.y);
        }

        public boolean foundAll() {
            return found[0] != null && found[1] != null && found[2] != null && found[3] != null;
        }

        public boolean project(Matrix4d to2d, Matrix4d to3d, Loop<? extends Point2d> facade, LinearForm3D facePlane, Vector3d perp) {
            boolean allInside = true;
            for (int i = 0; i < 4; i++) {
                // Point3d proj = new Point3d(corners[i]);
                Point3d sec = facePlane.collide(corners[i], perp);
                if (sec != null) {
                    to2d.transform(sec);
                    boolean inside = Loopz.inside(new Point2d(sec.x, sec.z), facade);
                    allInside &= inside;
                    if (inside) {
                        sec.y = 0;
                        to3d.transform(sec);
                        found[i] = sec;
                    }
                }
            }
            return allInside;
        }

        public void setBounds(Matrix4d to2d, FRect bounds) {
            List<Point2d> envelop = new ArrayList<>();
            for (int i = 0; i < 4; i++) {
                Point3d tmp = new Point3d(corners[i]);
                to2d.transform(tmp);
                envelop.add(Pointz.to2XZ(tmp));
            }
            bounds.setFrom(new DRectangle(envelop));
        }
    }

    protected void mapTo2d(Face f, Loop<LPoint3d> ll, MiniFacade mf, WallTag wallTag, Set<QuadF> features, MatMeshBuilder faceMaterial, Line megafacade) {
        Matrix4d to2dXY = new Matrix4d();
        FacadeTexApp fta = null;
        if (mf != null)
            fta = mf.facadeTexApp;
        Vector3d up = f.edge.uphill, along = f.edge.direction(), out = f.edge.getPlaneNormal();
        along.normalize();
        to2dXY.setRow(2, up.x, up.y, up.z, 0);
        to2dXY.setRow(1, out.x, out.y, out.z, 0);
        to2dXY.setRow(0, -along.x, -along.y, -along.z, 0);
        Point3d bottomS = f.definingSE.iterator().next().getStart(f), bottomE = f.definingSE.iterator().next().getEnd(f);
        if (bottomS == null || bottomE == null)
            return;
        Point3d start = new Point3d(bottomS);
        Point3d end = new Point3d(bottomE);
        to2dXY.m33 = 1;
        to2dXY.transform(start);
        to2dXY.m03 = -start.x;
        to2dXY.m13 = -start.y;
        to2dXY.m23 = -start.z;
        start = new Point3d(bottomS);
        to2dXY.transform(start);
        to2dXY.transform(end);
        Loop<LPoint2d> flat = GreebleHelper.to2dLoop(GreebleHelper.transform(ll, to2dXY), 1);
        Matrix4d to3d = new Matrix4d(to2dXY);
        to3d.invert();
        {
            // face in z-up, we're in y-up
            double[] one = new double[4], two = new double[4];
            to3d.getRow(1, one);
            to3d.getRow(2, two);
            to3d.setRow(1, two);
            to3d.setRow(2, one);
        }
        // now in jme space
        Matrix4d to2d = new Matrix4d(to3d);
        to2d.invert();
        FeatureGenerator toRecess = new FeatureGenerator((MiniFacade) null);
        LinearForm3D facePlane = new LinearForm3D(new Vector3d(out.x, out.z, out.y), new Point3d(bottomS.x, bottomS.z, bottomS.y));
        LoopL<Point2d> sides = null;
        DRectangle facadeRect = null;
        if (wallTag != null) {
            sides = GreebleHelper.findRectagle(flat, Pointz.to2XZ(start), Pointz.to2XZ(end));
            // if (flat.count() ==5 ) {
            // 
            // Plot.closeLast();
            // PaintThing.debug.clear();
            // PaintThing.debug (Color.red, 1f, sides.get( 0 ));
            // PaintThing.debug (Color.orange, 1f, sides.get( 1 ));
            // PaintThing.debug (Color.yellow, 1f, sides.get( 2 ));
            // new Plot(new Point2d());
            // }
            if (mf != null) {
                if (sides != null)
                    facadeRect = GreebleHelper.findRect(sides.remove(0));
            }
        }
        DRectangle uvs = GreebleGrid.ZERO_ONE_UVS;
        if (mf != null) {
            if (fta.textureUVs == TextureUVs.Square) {
                uvs = new DRectangle(fta.postState.outerWallRect);
                {
                    // for faces not at the bottom, move to the bottom's uv space
                    Face f2 = f;
                    while (f2.parent != null) f2 = f2.parent;
                    Point3d bottomS2 = new Point3d(f2.definingSE.iterator().next().getStart(f2));
                    to2dXY.transform(bottomS2);
                    uvs.x += bottomS2.x;
                    uvs.y -= bottomS.z;
                }
            } else if (fta.textureUVs == TextureUVs.Rectangle) {
                uvs = fta.textureRect;
            }
            if (fta.texture == null)
                uvs = null;
        }
        List<DRectangle> floors = new ArrayList();
        List<MatMeshBuilder> materials = new ArrayList();
        boolean isGroundFloor = wallTag != null && facadeRect != null && mf != null && (f.definingCorners.isEmpty() || f.definingCorners.iterator().next().z < 1);
        if (wallTag != null && facadeRect != null && mf != null && isGroundFloor && mf.groundFloorHeight > 0 && facadeRect.x < mf.groundFloorHeight && facadeRect.getMaxX() > mf.groundFloorHeight) {
            floors.addAll(facadeRect.splitY(mf.groundFloorHeight));
            MatMeshBuilder gfm = greebleGrid.mbs.get(BRICK, Colourz.toF4(mf.facadeTexApp.groundFloorColor));
            for (Loop<Point2d> loop : sides) {
                Loop<Point2d>[] cut = Loopz.cutConvex(loop, new LinearForm(0, 1, mf.groundFloorHeight));
                faceMaterial.add(cut[1].singleton(), to3d);
                LoopL<Point2d> pts = cut[0].singleton();
                gfm.add(pts, GreebleHelper.wallUVs(pts, fta.postState.outerWallRect), to3d);
            }
            materials.add(gfm);
            materials.add(faceMaterial);
        } else {
            floors.add(facadeRect);
            materials.add(faceMaterial);
            if (sides != null && !sides.isEmpty())
                faceMaterial.add(sides, uvs == null ? null : GreebleHelper.wallUVs(sides, uvs), to3d);
        }
        for (int j = 0; j < floors.size(); j++) {
            DRectangle floorRect = floors.get(j);
            MatMeshBuilder m = materials.get(j);
            Iterator<QuadF> quit = features.iterator();
            while (quit.hasNext()) {
                QuadF n = quit.next();
                if (n.project(to2d, to3d, flat, facePlane, new Vector3d(along.y, 0, -along.x)) && wallTag != null && floorRect != null && toRecess != null) {
                    // set the vertical bounds, so we can just render in 2d
                    FRect bounds = new FRect(n.original, n.original.panesLabelApp, n.original.panesTexApp, null);
                    n.setBounds(to2d, bounds);
                    if (floorRect.contains(bounds)) {
                        toRecess.put(n.original.getFeat(), bounds);
                        quit.remove();
                    }
                }
            }
            if (floorRect == null || wallTag == null || toRecess == null || mf == null) {
                greebleRoof(f, ll, faceMaterial, start, end, flat, to3d, to2d);
            } else if (fta.texture == null)
                greebleGrid.buildGrid(floorRect, to3d, toRecess, mf, m, wallTag);
            else {
                greebleGrid.textureGrid(floorRect, uvs, to3d, toRecess, mf);
            }
        }
    }

    private void greebleRoof(Face f, Loop<LPoint3d> ll, MatMeshBuilder faceMaterial, Point3d start, Point3d end, Loop<LPoint2d> flat, Matrix4d to3d, Matrix4d to2d) {
        LoopL<LPoint2d> loop = flat.singleton();
        LoopL<Point2d> roofUVs;
        RoofTexApp ra = miniroof.roofTexApp;
        RoofSuperApp rsa = miniroof.roofSuperApp;
        switch(ra.appMode) {
            default:
                roofUVs = GreebleHelper.roofPitchUVs(loop, Pointz.to2XZ(start), Pointz.to2XZ(end), TILE_UV_SCALE);
                break;
            case Net:
                if (ra.texture != null && ra.textureUVs == TextureUVs.Square)
                    roofUVs = GreebleHelper.roofPitchUVs(loop, Pointz.to2XZ(start), Pointz.to2XZ(end), TILE_UV_SCALE);
                else if (rsa.appMode == TextureMode.Net && rsa.textures != null && ra.textureUVs == TextureUVs.Zero_One) {
                    roofUVs = GreebleHelper.zeroOneRoofUVs(loop, Pointz.to2XZ(end), Pointz.to2XZ(start));
                } else
                    roofUVs = GreebleHelper.wholeRoofUVs(ll.singleton(), ra.textureRect == null ? new DRectangle(0, 0, 1, 1) : ra.textureRect);
                break;
            case Bitmap:
                roofUVs = GreebleHelper.roofPitchUVs(loop, Pointz.to2XZ(start), Pointz.to2XZ(end), TILE_UV_SCALE);
                break;
        }
        faceMaterial.add(loop, roofUVs, to3d);
        for (FCircle feature : miniroof.getGreebles(f)) {
            Point3d onRoof = f.edge.linearForm.collide(new Point3d(feature.loc.x, feature.loc.y, 0), Mathz.Z_UP);
            onRoof.set(onRoof.x, onRoof.z, onRoof.y);
            to2d.transform(onRoof);
            DRectangle r = feature.toRect();
            r.x = onRoof.x - r.width / 2;
            r.y = onRoof.z - r.height / 2;
            switch(feature.f) {
                case Chimney:
                    greebleGrid.createChimney(onRoof, miniroof, feature, f.edge.projectDown().dir(), f.edge.linearForm, sf.buildingApp.chimneyTexture);
                    break;
                case Velux:
                    if (feature.veluxTextureApp.texture == null)
                        greebleGrid.createWindow(r, to3d, null, greebleGrid.mbs.WOOD, greebleGrid.mbs.GLreplaced, 0.09, -1, -1, -1, 2, 2);
                    else {
                        double zOff = -0.08;
                        GreebleGrid.createWindowFromPanes(new ArrayList<DRectangle>(), r, r, to3d, greebleGrid.mbs.getTexture("velux_" + feature.veluxTextureApp.texture + "_" + r.hashCode(), feature.veluxTextureApp.texture, miniroof), zOff + 0.05, zOff, true);
                    }
                    break;
            }
        }
    }

    public void edges(Output output, float[] roofColor) {
        MatMeshBuilder mmb;
        RoofTexApp a = miniroof.roofTexApp;
        switch(a.appMode) {
            case Off:
            default:
                mmb = greebleGrid.mbs.get(TILE, roofColor, miniroof);
                break;
            case Bitmap:
                mmb = greebleGrid.mbs.getTexture(TILE_TEXTURED, TILE_JPG, miniroof);
                break;
            case Net:
                return;
        }
        GreebleEdge.roowWallGreeble(output, greebleGrid.mbs.get(TILE, roofColor, miniroof), mmb, greebleGrid.mbs.get(BRICK, new float[] { 1, 0, 0, 1 }), TILE_UV_SCALE);
        for (Face f : output.faces.values()) GreebleEdge.roofGreeble(f, greebleGrid.mbs.get(TILE, roofColor));
    }
}

19 Source : GreebleSkel.java
with Apache License 2.0
from twak

private void selected(Output output, Node out, SuperEdge superEdge, Object ha) {
    if (onClick != null)
        onClick.selected(output, out, superEdge, ha);
}

19 Source : MoveTool.java
with Apache License 2.0
from twak

public clreplaced MoveTool extends Tool {

    Handle currentDraggingHandle = null;

    // new HashSet<>();
    Node currentHandles = new Node();

    Tweed tweed;

    public MoveTool(Tweed tweed) {
        super(tweed);
    }

    @Override
    public void activate(Tweed tweed) {
        this.tweed = tweed;
        tweed.getRootNode().attachChild(currentHandles);
    }

    @Override
    public void deactivate() {
        currentHandles.removeFromParent();
    }

    @Override
    public void clear() {
        for (Spatial currentHandle : currentHandles.getChildren()) currentHandle.removeFromParent();
    }

    @Override
    public void clickedOn(Spatial target, Vector3f vector3f, Vector2f cursorPosition) {
        clear();
        if (target != null) {
            currentHandles.setLocalTranslation(new Vector3f());
            currentHandles.attachChild(new MoveHandle(tweed, 0, target));
            currentHandles.attachChild(new MoveHandle(tweed, 1, target));
            currentHandles.attachChild(new MoveHandle(tweed, 2, target));
            currentHandles.attachChild(new RotHandle(tweed, target));
            currentHandles.attachChild(new ScaleHandle(tweed, target));
        }
    }

    @Override
    public void dragging(Vector2f screen, Vector3f d3) {
        currentDraggingHandle.dragging(screen);
    }

    @Override
    public void dragStart(Geometry target, Vector2f screen, Vector3f world) {
        currentDraggingHandle = (Handle) target.getUserData(Tweed.CLICK);
        currentDraggingHandle.dragStart(screen);
    }

    @Override
    public boolean isDragging() {
        return currentDraggingHandle != null;
    }

    @Override
    public void dragEnd() {
        currentDraggingHandle.dragEnd();
        currentDraggingHandle = null;
    }

    @Override
    public String getName() {
        return "move";
    }
}

19 Source : AlignTool.java
with Apache License 2.0
from twak

public clreplaced AlignTool extends Tool {

    boolean dragging = false;

    long lastClick = 0;

    Node markers = new Node();

    MiniGen toAlign = null;

    Vector3f[] alignMarkers = new Vector3f[2], otherMarkers = new Vector3f[2];

    double vOffset = 0;

    public AlignTool(Tweed tweed) {
        super(tweed);
    }

    @Override
    public void activate(Tweed tweedApp) {
        super.activate(tweedApp);
        this.tweed = tweedApp;
        tweedApp.getRootNode().attachChild(markers);
    }

    @Override
    public void deactivate() {
        super.deactivate();
        showMarkers();
        markers.removeFromParent();
    }

    @Override
    public void clickedOn(Spatial target, Vector3f loc, Vector2f cursorPosition) {
        if (target == null)
            return;
        if (System.currentTimeMillis() - lastClick > 500) {
            System.out.println(target + " " + loc);
            Vector3f[] locs;
            Object[] gens = target.getUserData(Gen.clreplaced.getSimpleName());
            if (gens != null && gens[0] instanceof MiniGen) {
                locs = alignMarkers;
                toAlign = (MiniGen) gens[0];
                System.out.println("loc1 " + loc);
                toAlign.gNode.getLocalTransform().transformInverseVector(loc, loc);
                // loc = m.mult(loc);
                System.out.println("loc2 " + loc);
            } else
                locs = otherMarkers;
            int toMove = -1;
            for (int i = 0; i < locs.length; i++) {
                if (locs[i] == null) {
                    toMove = i;
                    break;
                }
                if (toMove == -1 || locs[i].distance(loc) < locs[toMove].distance(loc))
                    toMove = i;
            }
            locs[toMove] = loc;
            if (alignMarkers[0] != null && alignMarkers[1] != null && otherMarkers[0] != null && otherMarkers[1] != null)
                doAlign();
            showMarkers();
            lastClick = System.currentTimeMillis();
        }
    }

    private void doAlign() {
        if (alignMarkers[0] == null || alignMarkers[1] == null || otherMarkers[0] == null || otherMarkers[1] == null) {
            Jz.showOptionPane(null, "click meshes to create align markers");
            return;
        }
        Matrix4d toOrigin = buildFrame(alignMarkers);
        toOrigin.invert();
        Matrix4d o = buildFrame(otherMarkers);
        toOrigin.mul(o, toOrigin);
        toOrigin.m13 += vOffset;
        Transform t = new Transform();
        t.fromTransformMatrix(Jme3z.toJme(toOrigin));
        toAlign.moveTo(t);
    // System.out.println ( "bounds "+ toAlign.gNode.getWorldBound() );
    }

    private Matrix4d buildFrame(Vector3f[] locs) {
        Vector3f dir0 = new Vector3f(locs[1]);
        dir0 = dir0.subtract(locs[0]);
        dir0.y = 0;
        // dir.normalize();
        Vector3f dir1 = new Vector3f(0, dir0.length(), 0);
        Vector3f dir2 = new Vector3f(-dir0.z, 0, dir0.x);
        Matrix4d out = new Matrix4d();
        out.setRow(0, toArray(dir2));
        out.setRow(1, toArray(dir1));
        out.setRow(2, toArray(dir0));
        out.m03 = locs[0].x;
        out.m13 = 0;
        out.m23 = locs[0].z;
        out.m33 = 1;
        if (false) {
            Point3d a = new Point3d(0, 0, 0);
            Point3d b = new Point3d(0, 0, 1);
            out.transform(a);
            out.transform(b);
            System.out.println(a + " >>><<< " + b);
            System.out.println(locs[0] + " <<<>>> " + locs[1]);
        }
        return out;
    }

    private double[] toArray(Vector3f v) {
        return new double[] { v.x, v.y, v.z, 0 };
    }

    private void showMarkers() {
        tweed.enqueue(new // run after toAlign's local transofrm has been updated!
        Runnable() {

            @Override
            public void run() {
                for (Spatial s : markers.getChildren()) s.removeFromParent();
                Vector3f[] targetMarkers;
                if (toAlign != null) {
                    Transform toTarget = toAlign.gNode.getLocalTransform();
                    targetMarkers = new Vector3f[alignMarkers.length];
                    for (int i = 0; i < alignMarkers.length; i++) {
                        if (alignMarkers[i] != null) {
                            targetMarkers[i] = new Vector3f();
                            toTarget.transformVector(alignMarkers[i], targetMarkers[i]);
                        }
                    }
                } else
                    targetMarkers = new Vector3f[2];
                int cc = 4;
                for (Vector3f[] a : new Vector3f[][] { otherMarkers, targetMarkers }) {
                    Color c = Rainbow.getColour(cc++);
                    for (Vector3f v : a) {
                        if (v != null) {
                            Cylinder handleOne = new Cylinder(2, 3, 0.05f, 500f, true);
                            handleOne.setMode(Mode.Lines);
                            Geometry g1 = new Geometry("h1", handleOne);
                            Material mat1 = new Material(tweed.getreplacedetManager(), "Common/MatDefs/Misc/Unshaded.j3md");
                            mat1.setColor("Color", new ColorRGBA(c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, 1f));
                            g1.setMaterial(mat1);
                            Vector3f pos = new Vector3f(v);
                            pos = pos.add(0, 250, 0);
                            g1.setLocalTranslation(pos);
                            g1.setLocalRotation(new Quaternion(new float[] { FastMath.PI / 2, 0, 0 }));
                            markers.attachChild(g1);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void dragStart(Geometry target, Vector2f cursorPosition, Vector3f world) {
        dragging = true;
    }

    @Override
    public void dragEnd() {
        dragging = false;
    }

    @Override
    public boolean isDragging() {
        return dragging;
    }

    @Override
    public String getName() {
        return "align";
    }

    @Override
    public void getUI(JPanel p) {
        p.setLayout(new ListDownLayout());
        JButton w = new JButton("save alignment");
        w.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                toAlign.save();
            }
        });
        JButton swap = new JButton("swap");
        swap.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Vector3f tmp = alignMarkers[0];
                alignMarkers[0] = alignMarkers[1];
                alignMarkers[1] = tmp;
                tweed.enqueue(new Runnable() {

                    @Override
                    public void run() {
                        doAlign();
                    }
                });
            }
        });
        JFormattedTextField tf = new JFormattedTextField(new NumberFormatter());
        tf.setValue(vOffset);
        tf.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                vOffset = ((Number) tf.getValue()).doubleValue();
                doAlign();
            }
        });
        p.add(w);
        p.add(swap);
        p.add(new JLabel("height offset:"));
        p.add(tf);
    }
}

19 Source : ResultsGen.java
with Apache License 2.0
from twak

@Override
public void calculate() {
    synchronized (toAdd) {
        for (MeshFile block : toAdd) {
            if (block != null) {
                Node n = rendered.get(block.file);
                if (n != null)
                    n.removeFromParent();
                rendered.remove(block.file);
                SkelGen sg = new SkelGen(tweed);
                sg.block = block.mesh;
                sg.parentNode = gNode;
                sg.calculate();
                ResultsGen.this.gNode.attachChild(sg.gNode);
                rendered.put(block.file, sg.gNode);
            }
        }
        toAdd.clear();
    }
    System.out.println(" before: " + plansIn.get() + " after " + plansOut.get());
    gNode.updateModelBound();
    gNode.updateGeometricState();
    super.calculate();
}

19 Source : ProfileGen.java
with Apache License 2.0
from twak

@Override
public void calculate() {
    for (Spatial s : gNode.getChildren()) s.removeFromParent();
    for (Node n : addOnJmeThread) gNode.attachChild(n);
    gNode.updateGeometricState();
    gNode.updateModelBound();
    super.calculate();
}

19 Source : ChunkPager.java
with BSD 3-Clause "New" or "Revised" License
from rvandoosselaer

/**
 * A pager implementation that pages the meshes of the chunks around the given location. Attaching chunks that are in
 * range and detaching them when they are out of range, from the given node.
 *
 * @author rvandoosselaer
 */
@Slf4j
public clreplaced ChunkPager extends Pager<Node> {

    @Getter
    private final Node node;

    public ChunkPager(@NonNull Node node, @NonNull ChunkManager chunkManager) {
        super(chunkManager);
        this.node = node;
        this.gridSize = BlocksConfig.getInstance().getGrid();
    }

    @Override
    protected Node createPage(Chunk chunk) {
        return chunk.getNode();
    }

    @Override
    protected void detachPage(Node page) {
        if (log.isTraceEnabled()) {
            log.trace("Detaching {} from {}", page, node);
        }
        node.detachChild(page);
    }

    @Override
    protected void attachPage(Node page) {
        if (log.isTraceEnabled()) {
            log.trace("Attaching {} to {}", page, node);
        }
        node.attachChild(page);
    }
}

19 Source : ChunkPager.java
with BSD 3-Clause "New" or "Revised" License
from rvandoosselaer

@Override
protected void detachPage(Node page) {
    if (log.isTraceEnabled()) {
        log.trace("Detaching {} from {}", page, node);
    }
    node.detachChild(page);
}

19 Source : ChunkPager.java
with BSD 3-Clause "New" or "Revised" License
from rvandoosselaer

@Override
protected void attachPage(Node page) {
    if (log.isTraceEnabled()) {
        log.trace("Attaching {} to {}", page, node);
    }
    node.attachChild(page);
}

19 Source : MemoryDebugState.java
with BSD 3-Clause "New" or "Revised" License
from rvandoosselaer

/**
 * @author rvandoosselaer
 */
public clreplaced MemoryDebugState extends BaseAppState {

    private static final int MB = 1024 * 1024;

    private Node node;

    private Container container;

    private Label heapLabel;

    private Label directLabel;

    @Override
    protected void initialize(Application app) {
        container = new Container(new SpringGridLayout(Axis.Y, Axis.X, FillMode.Even, FillMode.Even));
        container.setBackground(new QuadBackgroundComponent(new ColorRGBA(0, 0, 0, 0.9f)));
        container.addChild(new Label("Memory", new ElementId(Container.ELEMENT_ID).child("replacedle")));
        Container heap = container.addChild(new Container(new SpringGridLayout(Axis.X, Axis.Y, FillMode.Last, FillMode.Even), new ElementId(Container.ELEMENT_ID).child("entry")));
        heap.addChild(new Label("heap: "));
        heapLabel = heap.addChild(new Label(getHeapString()));
        heapLabel.setTextHAlignment(HAlignment.Right);
        Container direct = container.addChild(new Container(new SpringGridLayout(Axis.X, Axis.Y, FillMode.Last, FillMode.Even), new ElementId(Container.ELEMENT_ID).child("entry")));
        direct.addChild(new Label("direct: "));
        directLabel = direct.addChild(new Label(getDirectString()));
        directLabel.setTextHAlignment(HAlignment.Right);
        refreshLayout();
    }

    @Override
    protected void cleanup(Application app) {
    }

    @Override
    protected void onEnable() {
        if (node == null) {
            node = ((SimpleApplication) getApplication()).getGuiNode();
        }
        node.attachChild(container);
    }

    @Override
    protected void onDisable() {
        container.removeFromParent();
    }

    @Override
    public void update(float tpf) {
        heapLabel.setText(getHeapString());
        directLabel.setText(getDirectString());
        refreshLayout();
    }

    private String getDirectString() {
        return String.format("%d MB / %d objects", MemoryUtils.getDirectMemoryUsage() / MB, MemoryUtils.getDirectMemoryCount());
    }

    private String getHeapString() {
        return String.format("%d MB / %d MB", getUsedHeap() / MB, getTotalHeap() / MB);
    }

    private void refreshLayout() {
        container.setLocalTranslation(getApplication().getCamera().getWidth() - container.getPreferredSize().x, getApplication().getCamera().getHeight(), 1);
    }

    private long getTotalHeap() {
        return Runtime.getRuntime().totalMemory();
    }

    private long getUsedHeap() {
        return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    }
}

19 Source : LightingState.java
with BSD 3-Clause "New" or "Revised" License
from rvandoosselaer

/**
 * @author rvandoosselaer
 */
@Getter
public clreplaced LightingState extends BaseAppState {

    private final ColorRGBA ambientLightColor = new ColorRGBA(0.25f, 0.25f, 0.25f, 1);

    private final ColorRGBA directionalLightColor = new ColorRGBA(1.5f, 1.5f, 1.5f, 1);

    private final Vector3f directionalLightDir = new Vector3f(-0.2f, -1, -0.2f).normalizeLocal();

    private Node node;

    private AmbientLight ambientLight;

    private DirectionalLight directionalLight;

    @Setter
    private boolean updateDirection;

    @Override
    protected void initialize(Application app) {
        app.getRenderManager().setPreferredLightMode(TechniqueDef.LightMode.SinglePreplaced);
        app.getRenderManager().setSinglePreplacedLightBatchSize(2);
        ambientLight = new AmbientLight(ambientLightColor);
        if (updateDirection) {
            setDirectionalLightDir(app.getCamera().getDirection());
        }
        directionalLight = new DirectionalLight(directionalLightDir, directionalLightColor);
    }

    @Override
    protected void cleanup(Application app) {
    }

    @Override
    protected void onEnable() {
        if (node == null) {
            node = ((SimpleApplication) getApplication()).getRootNode();
        }
        attachLights();
    }

    @Override
    protected void onDisable() {
        detachLights();
    }

    @Override
    public void update(float tpf) {
        if (updateDirection) {
            setDirectionalLightDir(getApplication().getCamera().getDirection());
        }
    }

    public void setAmbientLightColor(@NonNull ColorRGBA color) {
        this.ambientLightColor.set(color);
    }

    public void setDirectionalLightColor(@NonNull ColorRGBA color) {
        this.directionalLightColor.set(color);
    }

    public void setDirectionalLightDir(@NonNull Vector3f direction) {
        this.directionalLightDir.set(direction).normalizeLocal();
        refreshDirectionalLight();
    }

    public void setNode(@NonNull Node node) {
        if (this.node != null) {
            detachLights();
        }
        this.node = node;
        attachLights();
    }

    protected void attachLights() {
        node.addLight(ambientLight);
        node.addLight(directionalLight);
    }

    protected void detachLights() {
        node.removeLight(ambientLight);
        node.removeLight(directionalLight);
    }

    protected void refreshDirectionalLight() {
        if (directionalLight != null) {
            directionalLight.setDirection(directionalLightDir);
        }
    }
}

19 Source : LightingState.java
with BSD 3-Clause "New" or "Revised" License
from rvandoosselaer

public void setNode(@NonNull Node node) {
    if (this.node != null) {
        detachLights();
    }
    this.node = node;
    attachLights();
}

19 Source : BlockBuilder.java
with BSD 3-Clause "New" or "Revised" License
from rvandoosselaer

/**
 * An application where you can add and remove blocks. Place a block using the left mouse button, remove a block using
 * the right mouse button.
 *
 * Default key mappings:
 * print camera position:            c
 * print direct memory information:  m
 * toggle wireframe:                 p
 * toggle profiler:                  F6
 *
 * @author rvandoosselaer
 */
public clreplaced BlockBuilder extends SimpleApplication implements ActionListener {

    private Node chunkNode;

    private Geometry addPlaceholder;

    private Geometry removePlaceholder;

    private ChunkManager chunkManager;

    private BlockRegistry blockRegistry;

    public static void main(String[] args) {
        LogAdapter.initialize();
        BlockBuilder blockBuilder = new BlockBuilder();
        blockBuilder.start();
    }

    public BlockBuilder() {
        super(new StatsAppState(), new FlyCamAppState(), new DebugKeysAppState(), new LightingState(), new WireframeState(), new PostProcessingState(), new BasicProfilerState(false), new MemoryDebugState());
    }

    @Override
    public void simpleInitApp() {
        GuiGlobals.initialize(this);
        BaseStyles.loadGlreplacedStyle();
        GuiGlobals.getInstance().getStyles().setDefaultStyle("glreplaced");
        BlocksConfig.initialize(replacedetManager);
        BlocksConfig.getInstance().setGrid(new Vec3i(3, 1, 3));
        blockRegistry = BlocksConfig.getInstance().getBlockRegistry();
        chunkManager = ChunkManager.builder().generator(new FlatTerrainGenerator(blockRegistry.get(BlockIds.GRreplaced))).build();
        chunkNode = new Node("chunk-node");
        stateManager.attachAll(new ChunkManagerState(chunkManager), new ChunkPagerState(chunkNode, chunkManager));
        hideCursor();
        createCrossHair();
        createBlockPointers();
        inputManager.addMapping("add-block", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
        inputManager.addMapping("remove-block", new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));
        inputManager.addListener(this, "add-block", "remove-block");
        rootNode.attachChild(chunkNode);
        viewPort.setBackgroundColor(new ColorRGBA(0.5f, 0.6f, 0.7f, 1.0f));
        flyCam.setMoveSpeed(10f);
        cam.setLocation(new Vector3f(0, 10f, 20));
        cam.lookAt(new Vector3f(16, 0, 16), Vector3f.UNIT_Y);
    }

    @Override
    public void simpleUpdate(float tpf) {
        CollisionResult result = getCollisionResult();
        updatePlaceholders(result);
    }

    @Override
    public void onAction(String name, boolean isPressed, float tpf) {
        if ("add-block".equals(name) && isPressed) {
            addBlock();
        } else if ("remove-block".equals(name) && isPressed) {
            removeBlock();
        }
    }

    private void createCrossHair() {
        Label label = new Label("+");
        label.setColor(ColorRGBA.White);
        Camera cam = getCamera();
        int width = cam.getWidth();
        int height = cam.getHeight();
        label.setLocalTranslation((width / 2) - (label.getPreferredSize().getX() / 2), (height / 2) + (label.getPreferredSize().getY() / 2), label.getLocalTranslation().getZ());
        guiNode.attachChild(label);
    }

    private void hideCursor() {
        GuiGlobals.getInstance().setCursorEventsEnabled(false);
        inputManager.setCursorVisible(false);
    }

    private void createBlockPointers() {
        Material removePlaceholderMaterial = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        removePlaceholderMaterial.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha);
        removePlaceholderMaterial.setColor("Color", new ColorRGBA(1, 0, 0, 0.2f));
        removePlaceholder = new Geometry("remove-placeholder", new Box(0.505f, 0.505f, 0.505f));
        removePlaceholder.setMaterial(removePlaceholderMaterial);
        removePlaceholder.setQueueBucket(RenderQueue.Bucket.Transparent);
        removePlaceholder.setLocalScale(BlocksConfig.getInstance().getBlockScale());
        Material addPlaceholderMaterial = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        addPlaceholderMaterial.setColor("Color", ColorRGBA.Yellow);
        addPlaceholder = new Geometry("add-placeholder", new WireBox(0.5f, 0.5f, 0.5f));
        addPlaceholder.setMaterial(addPlaceholderMaterial);
        addPlaceholder.setQueueBucket(RenderQueue.Bucket.Transparent);
        addPlaceholder.setLocalScale(BlocksConfig.getInstance().getBlockScale());
    }

    private CollisionResult getCollisionResult() {
        CollisionResults collisionResults = new CollisionResults();
        Ray ray = new Ray(cam.getLocation(), cam.getDirection());
        chunkNode.collideWith(ray, collisionResults);
        return collisionResults.size() > 0 ? collisionResults.getClosestCollision() : null;
    }

    private void updatePlaceholders(CollisionResult result) {
        if (result != null) {
            Vec3i pointingLocation = ChunkManager.getBlockLocation(result);
            Vector3f offset = new Vector3f(0.5f, 0.5f, 0.5f);
            removePlaceholder.setLocalTranslation(pointingLocation.toVector3f().addLocal(offset).multLocal(BlocksConfig.getInstance().getBlockScale()));
            if (removePlaceholder.getParent() == null) {
                rootNode.attachChild(removePlaceholder);
            }
            Vec3i placingLocation = ChunkManager.getNeighbourBlockLocation(result);
            addPlaceholder.setLocalTranslation(placingLocation.toVector3f().addLocal(offset).multLocal(BlocksConfig.getInstance().getBlockScale()));
            if (addPlaceholder.getParent() == null) {
                rootNode.attachChild(addPlaceholder);
            }
        } else {
            addPlaceholder.removeFromParent();
            removePlaceholder.removeFromParent();
        }
    }

    private void addBlock() {
        Vector3f blockLocation = addPlaceholder.getWorldTranslation();
        chunkManager.addBlock(blockLocation.subtract(0.5f, 0.5f, 0.5f), blockRegistry.get(BlockIds.GRreplaced));
    }

    private void removeBlock() {
        Vector3f blockLocation = removePlaceholder.getWorldTranslation();
        chunkManager.removeBlock(blockLocation.subtract(0.5f, 0.5f, 0.5f));
    }
}

19 Source : TestSimpleWater.java
with Apache License 2.0
from neuroph

/**
 * @author normenhansen
 */
public clreplaced TestSimpleWater extends SimpleApplication implements ActionListener {

    Material mat;

    Spatial waterPlane;

    Geometry lightSphere;

    SimpleWaterProcessor waterProcessor;

    Node sceneNode;

    boolean useWater = true;

    private Vector3f lightPos = new Vector3f(33, 12, -29);

    public static void main(String[] args) {
        TestSimpleWater app = new TestSimpleWater();
        app.start();
    }

    @Override
    public void simpleInitApp() {
        initInput();
        initScene();
        // create processor
        waterProcessor = new SimpleWaterProcessor(replacedetManager);
        waterProcessor.setReflectionScene(sceneNode);
        waterProcessor.setDebug(true);
        viewPort.addProcessor(waterProcessor);
        waterProcessor.setLightPosition(lightPos);
        // create water quad
        // waterPlane = waterProcessor.createWaterGeometry(100, 100);
        waterPlane = (Spatial) replacedetManager.loadModel("Models/WaterTest/WaterTest.mesh.xml");
        waterPlane.setMaterial(waterProcessor.getMaterial());
        waterPlane.setLocalScale(40);
        waterPlane.setLocalTranslation(-5, 0, 5);
        rootNode.attachChild(waterPlane);
    }

    private void initScene() {
        // init cam location
        cam.setLocation(new Vector3f(0, 10, 10));
        cam.lookAt(Vector3f.ZERO, Vector3f.UNIT_Y);
        // init scene
        sceneNode = new Node("Scene");
        mat = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat.setTexture("ColorMap", replacedetManager.loadTexture("Interface/Logo/Monkey.jpg"));
        Box b = new Box(1, 1, 1);
        Geometry geom = new Geometry("Box", b);
        geom.setMaterial(mat);
        sceneNode.attachChild(geom);
        // load sky
        sceneNode.attachChild(SkyFactory.createSky(replacedetManager, "Textures/Sky/Bright/BrightSky.dds", false));
        rootNode.attachChild(sceneNode);
        // add lightPos Geometry
        Sphere lite = new Sphere(8, 8, 3.0f);
        lightSphere = new Geometry("lightsphere", lite);
        lightSphere.setMaterial(mat);
        lightSphere.setLocalTranslation(lightPos);
        rootNode.attachChild(lightSphere);
    }

    protected void initInput() {
        flyCam.setMoveSpeed(3);
        // init input
        inputManager.addMapping("use_water", new KeyTrigger(KeyInput.KEY_O));
        inputManager.addListener(this, "use_water");
        inputManager.addMapping("lightup", new KeyTrigger(KeyInput.KEY_T));
        inputManager.addListener(this, "lightup");
        inputManager.addMapping("lightdown", new KeyTrigger(KeyInput.KEY_G));
        inputManager.addListener(this, "lightdown");
        inputManager.addMapping("lightleft", new KeyTrigger(KeyInput.KEY_H));
        inputManager.addListener(this, "lightleft");
        inputManager.addMapping("lightright", new KeyTrigger(KeyInput.KEY_K));
        inputManager.addListener(this, "lightright");
        inputManager.addMapping("lightforward", new KeyTrigger(KeyInput.KEY_U));
        inputManager.addListener(this, "lightforward");
        inputManager.addMapping("lightback", new KeyTrigger(KeyInput.KEY_J));
        inputManager.addListener(this, "lightback");
    }

    @Override
    public void simpleUpdate(float tpf) {
        fpsText.setText("Light Position: " + lightPos.toString() + " Change Light position with [U], [H], [J], [K] and [T], [G] Turn off water with [O]");
        lightSphere.setLocalTranslation(lightPos);
        waterProcessor.setLightPosition(lightPos);
    }

    public void onAction(String name, boolean value, float tpf) {
        if (name.equals("use_water") && value) {
            if (!useWater) {
                useWater = true;
                waterPlane.setMaterial(waterProcessor.getMaterial());
            } else {
                useWater = false;
                waterPlane.setMaterial(mat);
            }
        } else if (name.equals("lightup") && value) {
            lightPos.y++;
        } else if (name.equals("lightdown") && value) {
            lightPos.y--;
        } else if (name.equals("lightleft") && value) {
            lightPos.x--;
        } else if (name.equals("lightright") && value) {
            lightPos.x++;
        } else if (name.equals("lightforward") && value) {
            lightPos.z--;
        } else if (name.equals("lightback") && value) {
            lightPos.z++;
        }
    }
}

19 Source : TestSaveGame.java
with Apache License 2.0
from neuroph

public void simpleInitApp() {
    // node that is used to store player data
    Node myPlayer = new Node();
    myPlayer.setName("PlayerNode");
    myPlayer.setUserData("name", "Mario");
    myPlayer.setUserData("health", 100.0f);
    myPlayer.setUserData("points", 0);
    // the actual model would be attached to this node
    Spatial model = (Spatial) replacedetManager.loadModel("Models/Oto/Oto.mesh.xml");
    myPlayer.attachChild(model);
    // before saving the game, the model should be detached so its not saved along with the node
    myPlayer.detachAllChildren();
    SaveGame.saveGame("mycompany/mygame", "savegame_001", myPlayer);
    // later the game is loaded again
    Node player = (Node) SaveGame.loadGame("mycompany/mygame", "savegame_001");
    player.attachChild(model);
    rootNode.attachChild(player);
    // and the data is available
    System.out.println("Name: " + player.getUserData("name"));
    System.out.println("Health: " + player.getUserData("health"));
    System.out.println("Points: " + player.getUserData("points"));
    AmbientLight al = new AmbientLight();
    rootNode.addLight(al);
// note you can also implement your own clreplacedes that implement the Savable interface.
}

19 Source : TerrainTestCollision.java
with Apache License 2.0
from neuroph

/**
 * Creates a terrain object and a collision node to go with it. Then
 * drops several balls from the sky that collide with the terrain
 * and roll around.
 * Left click to place a sphere on the ground where the crosshairs intersect the terrain.
 * Hit keys 1 or 2 to raise/lower the terrain at that spot.
 *
 * @author Brent Owens
 */
public clreplaced TerrainTestCollision extends SimpleApplication {

    TerrainQuad terrain;

    Node terrainPhysicsNode;

    Material matRock;

    Material matWire;

    boolean wireframe = false;

    protected BitmapText hintText;

    PointLight pl;

    Geometry lightMdl;

    Geometry collisionMarker;

    private BulletAppState bulletAppState;

    Geometry collisionSphere;

    Geometry collisionBox;

    Geometry selectedCollisionObject;

    public static void main(String[] args) {
        TerrainTestCollision app = new TerrainTestCollision();
        app.start();
    }

    @Override
    public void initialize() {
        super.initialize();
        loadHintText();
        initCrossHairs();
    }

    @Override
    public void simpleInitApp() {
        bulletAppState = new BulletAppState();
        bulletAppState.setThreadingType(BulletAppState.ThreadingType.PARALLEL);
        stateManager.attach(bulletAppState);
        setupKeys();
        matRock = new Material(replacedetManager, "Common/MatDefs/Terrain/Terrain.j3md");
        matRock.setTexture("Alpha", replacedetManager.loadTexture("Textures/Terrain/splat/alphamap.png"));
        Texture heightMapImage = replacedetManager.loadTexture("Textures/Terrain/splat/mountains512.png");
        Texture grreplaced = replacedetManager.loadTexture("Textures/Terrain/splat/grreplaced.jpg");
        grreplaced.setWrap(WrapMode.Repeat);
        matRock.setTexture("Tex1", grreplaced);
        matRock.setFloat("Tex1Scale", 64f);
        Texture dirt = replacedetManager.loadTexture("Textures/Terrain/splat/dirt.jpg");
        dirt.setWrap(WrapMode.Repeat);
        matRock.setTexture("Tex2", dirt);
        matRock.setFloat("Tex2Scale", 32f);
        Texture rock = replacedetManager.loadTexture("Textures/Terrain/splat/road.jpg");
        rock.setWrap(WrapMode.Repeat);
        matRock.setTexture("Tex3", rock);
        matRock.setFloat("Tex3Scale", 128f);
        matWire = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        matWire.getAdditionalRenderState().setWireframe(true);
        matWire.setColor("Color", ColorRGBA.Green);
        AbstractHeightMap heightmap = null;
        try {
            heightmap = new ImageBasedHeightMap(heightMapImage.getImage(), 0.25f);
            heightmap.load();
        } catch (Exception e) {
        }
        terrain = new TerrainQuad("terrain", 65, 513, heightmap.getHeightMap());
        TerrainLodControl control = new TerrainLodControl(terrain, getCamera());
        // patch size, and a multiplier
        control.setLodCalculator(new DistanceLodCalculator(65, 2.7f));
        terrain.addControl(control);
        terrain.setMaterial(matRock);
        terrain.setLocalScale(new Vector3f(2, 2, 2));
        // unlock it so we can edit the height
        terrain.setLocked(false);
        rootNode.attachChild(terrain);
        /**
         * Create PhysicsRigidBodyControl for collision
         */
        terrain.addControl(new RigidBodyControl(0));
        bulletAppState.getPhysicsSpace().addAll(terrain);
        // Add 5 physics spheres to the world, with random sizes and positions
        // let them drop from the sky
        for (int i = 0; i < 5; i++) {
            float r = (float) (8 * Math.random());
            Geometry sphere = new Geometry("cannonball", new Sphere(10, 10, r));
            sphere.setMaterial(matWire);
            // random position
            float x = (float) (20 * Math.random()) - 40;
            // random position
            float y = (float) (20 * Math.random()) - 40;
            // random position
            float z = (float) (20 * Math.random()) - 40;
            sphere.setLocalTranslation(new Vector3f(x, 100 + y, z));
            sphere.addControl(new RigidBodyControl(new SphereCollisionShape(r), 2));
            rootNode.attachChild(sphere);
            bulletAppState.getPhysicsSpace().add(sphere);
        }
        collisionBox = new Geometry("collisionBox", new Box(2, 2, 2));
        collisionBox.setModelBound(new BoundingBox());
        collisionBox.setLocalTranslation(new Vector3f(20, 95, 30));
        collisionBox.setMaterial(matWire);
        rootNode.attachChild(collisionBox);
        selectedCollisionObject = collisionBox;
        DirectionalLight dl = new DirectionalLight();
        dl.setDirection(new Vector3f(1, -0.5f, -0.1f).normalizeLocal());
        dl.setColor(new ColorRGBA(0.50f, 0.40f, 0.50f, 1.0f));
        rootNode.addLight(dl);
        cam.setLocation(new Vector3f(0, 25, -10));
        cam.lookAtDirection(new Vector3f(0, -1, 0).normalizeLocal(), Vector3f.UNIT_Y);
    }

    public void loadHintText() {
        hintText = new BitmapText(guiFont, false);
        hintText.setSize(guiFont.getCharSet().getRenderedSize());
        hintText.setLocalTranslation(0, getCamera().getHeight(), 0);
        // hintText.setText("Hit T to switch to wireframe");
        hintText.setText("");
        guiNode.attachChild(hintText);
    }

    protected void initCrossHairs() {
        // guiFont = replacedetManager.loadFont("Interface/Fonts/Default.fnt");
        BitmapText ch = new BitmapText(guiFont, false);
        ch.setSize(guiFont.getCharSet().getRenderedSize() * 2);
        // crosshairs
        ch.setText("+");
        // center
        ch.setLocalTranslation(settings.getWidth() / 2 - guiFont.getCharSet().getRenderedSize() / 3 * 2, settings.getHeight() / 2 + ch.getLineHeight() / 2, 0);
        guiNode.attachChild(ch);
    }

    private void setupKeys() {
        flyCam.setMoveSpeed(50);
        inputManager.addMapping("wireframe", new KeyTrigger(KeyInput.KEY_T));
        inputManager.addListener(actionListener, "wireframe");
        inputManager.addMapping("Lefts", new KeyTrigger(KeyInput.KEY_H));
        inputManager.addMapping("Rights", new KeyTrigger(KeyInput.KEY_K));
        inputManager.addMapping("Ups", new KeyTrigger(KeyInput.KEY_U));
        inputManager.addMapping("Downs", new KeyTrigger(KeyInput.KEY_J));
        inputManager.addMapping("Forwards", new KeyTrigger(KeyInput.KEY_Y));
        inputManager.addMapping("Backs", new KeyTrigger(KeyInput.KEY_I));
        inputManager.addListener(actionListener, "Lefts");
        inputManager.addListener(actionListener, "Rights");
        inputManager.addListener(actionListener, "Ups");
        inputManager.addListener(actionListener, "Downs");
        inputManager.addListener(actionListener, "Forwards");
        inputManager.addListener(actionListener, "Backs");
        inputManager.addMapping("shoot", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
        inputManager.addListener(actionListener, "shoot");
        inputManager.addMapping("cameraDown", new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));
        inputManager.addListener(actionListener, "cameraDown");
    }

    @Override
    public void update() {
        super.update();
    }

    private void createCollisionMarker() {
        Sphere s = new Sphere(6, 6, 1);
        collisionMarker = new Geometry("collisionMarker");
        collisionMarker.setMesh(s);
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat.setColor("Color", ColorRGBA.Orange);
        collisionMarker.setMaterial(mat);
        rootNode.attachChild(collisionMarker);
    }

    private ActionListener actionListener = new ActionListener() {

        public void onAction(String binding, boolean keyPressed, float tpf) {
            if (binding.equals("wireframe") && !keyPressed) {
                wireframe = !wireframe;
                if (!wireframe) {
                    terrain.setMaterial(matWire);
                } else {
                    terrain.setMaterial(matRock);
                }
            } else if (binding.equals("shoot") && !keyPressed) {
                Vector3f origin = cam.getWorldCoordinates(new Vector2f(settings.getWidth() / 2, settings.getHeight() / 2), 0.0f);
                Vector3f direction = cam.getWorldCoordinates(new Vector2f(settings.getWidth() / 2, settings.getHeight() / 2), 0.3f);
                direction.subtractLocal(origin).normalizeLocal();
                Ray ray = new Ray(origin, direction);
                CollisionResults results = new CollisionResults();
                int numCollisions = terrain.collideWith(ray, results);
                if (numCollisions > 0) {
                    CollisionResult hit = results.getClosestCollision();
                    if (collisionMarker == null) {
                        createCollisionMarker();
                    }
                    Vector2f loc = new Vector2f(hit.getContactPoint().x, hit.getContactPoint().z);
                    float height = terrain.getHeight(loc);
                    System.out.println("collide " + hit.getContactPoint() + ", height: " + height + ", distance: " + hit.getDistance());
                    collisionMarker.setLocalTranslation(new Vector3f(hit.getContactPoint().x, height, hit.getContactPoint().z));
                }
            } else if (binding.equals("cameraDown") && !keyPressed) {
                getCamera().lookAtDirection(new Vector3f(0, -1, 0), Vector3f.UNIT_Y);
            } else if (binding.equals("Lefts") && !keyPressed) {
                Vector3f oldLoc = selectedCollisionObject.getLocalTranslation().clone();
                selectedCollisionObject.move(-0.5f, 0, 0);
                testCollision(oldLoc);
            } else if (binding.equals("Rights") && !keyPressed) {
                Vector3f oldLoc = selectedCollisionObject.getLocalTranslation().clone();
                selectedCollisionObject.move(0.5f, 0, 0);
                testCollision(oldLoc);
            } else if (binding.equals("Forwards") && !keyPressed) {
                Vector3f oldLoc = selectedCollisionObject.getLocalTranslation().clone();
                selectedCollisionObject.move(0, 0, 0.5f);
                testCollision(oldLoc);
            } else if (binding.equals("Backs") && !keyPressed) {
                Vector3f oldLoc = selectedCollisionObject.getLocalTranslation().clone();
                selectedCollisionObject.move(0, 0, -0.5f);
                testCollision(oldLoc);
            } else if (binding.equals("Ups") && !keyPressed) {
                Vector3f oldLoc = selectedCollisionObject.getLocalTranslation().clone();
                selectedCollisionObject.move(0, 0.5f, 0);
                testCollision(oldLoc);
            } else if (binding.equals("Downs") && !keyPressed) {
                Vector3f oldLoc = selectedCollisionObject.getLocalTranslation().clone();
                selectedCollisionObject.move(0, -0.5f, 0);
                testCollision(oldLoc);
            }
        }
    };

    private void testCollision(Vector3f oldLoc) {
        if (terrain.collideWith(selectedCollisionObject.getWorldBound(), new CollisionResults()) > 0) {
            selectedCollisionObject.setLocalTranslation(oldLoc);
        }
    }
}

19 Source : TerrainGridAlphaMapTest.java
with Apache License 2.0
from neuroph

public clreplaced TerrainGridAlphaMapTest extends SimpleApplication {

    private TerrainGrid terrain;

    private float grreplacedScale = 64;

    private float dirtScale = 16;

    private float rockScale = 128;

    private boolean usePhysics = false;

    public static void main(final String[] args) {
        TerrainGridAlphaMapTest app = new TerrainGridAlphaMapTest();
        app.start();
    }

    private CharacterControl player3;

    private FractalSum base;

    private PerturbFilter perturb;

    private OptimizedErode therm;

    private SmoothFilter smooth;

    private IterativeFilter iterate;

    private Material material;

    private Material matWire;

    @Override
    public void simpleInitApp() {
        DirectionalLight sun = new DirectionalLight();
        sun.setColor(ColorRGBA.White);
        sun.setDirection(new Vector3f(-1, -1, -1).normalizeLocal());
        rootNode.addLight(sun);
        AmbientLight al = new AmbientLight();
        al.setColor(ColorRGBA.White.mult(1.3f));
        rootNode.addLight(al);
        File file = new File("TerrainGridTestData.zip");
        if (!file.exists()) {
            replacedetManager.registerLocator("http://jmonkeyengine.googlecode.com/files/TerrainGridTestData.zip", HttpZipLocator.clreplaced);
        } else {
            replacedetManager.registerLocator("TerrainGridTestData.zip", ZipLocator.clreplaced);
        }
        this.flyCam.setMoveSpeed(100f);
        ScreenshotAppState state = new ScreenshotAppState();
        this.stateManager.attach(state);
        // TERRAIN TEXTURE material
        material = new Material(replacedetManager, "Common/MatDefs/Terrain/TerrainLighting.j3md");
        material.setBoolean("useTriPlanarMapping", false);
        // material.setBoolean("isTerrainGrid", true);
        material.setFloat("Shininess", 0.0f);
        // GRreplaced texture
        Texture grreplaced = replacedetManager.loadTexture("Textures/Terrain/splat/grreplaced.jpg");
        grreplaced.setWrap(WrapMode.Repeat);
        material.setTexture("DiffuseMap", grreplaced);
        material.setFloat("DiffuseMap_0_scale", grreplacedScale);
        // DIRT texture
        Texture dirt = replacedetManager.loadTexture("Textures/Terrain/splat/dirt.jpg");
        dirt.setWrap(WrapMode.Repeat);
        material.setTexture("DiffuseMap_1", dirt);
        material.setFloat("DiffuseMap_1_scale", dirtScale);
        // ROCK texture
        Texture rock = replacedetManager.loadTexture("Textures/Terrain/splat/road.jpg");
        rock.setWrap(WrapMode.Repeat);
        material.setTexture("DiffuseMap_2", rock);
        material.setFloat("DiffuseMap_2_scale", rockScale);
        // WIREFRAME material
        matWire = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        matWire.getAdditionalRenderState().setWireframe(true);
        matWire.setColor("Color", ColorRGBA.Green);
        this.base = new FractalSum();
        this.base.setRoughness(0.7f);
        this.base.setFrequency(1.0f);
        this.base.setAmplitude(1.0f);
        this.base.setLacunarity(2.12f);
        this.base.setOctaves(8);
        this.base.setScale(0.02125f);
        this.base.addModulator(new NoiseModulator() {

            @Override
            public float value(float... in) {
                return ShaderUtils.clamp(in[0] * 0.5f + 0.5f, 0, 1);
            }
        });
        FilteredBasis ground = new FilteredBasis(this.base);
        this.perturb = new PerturbFilter();
        this.perturb.setMagnitude(0.119f);
        this.therm = new OptimizedErode();
        this.therm.setRadius(5);
        this.therm.setTalus(0.011f);
        this.smooth = new SmoothFilter();
        this.smooth.setRadius(1);
        this.smooth.setEffect(0.7f);
        this.iterate = new IterativeFilter();
        this.iterate.addPreFilter(this.perturb);
        this.iterate.addPostFilter(this.smooth);
        this.iterate.setFilter(this.therm);
        this.iterate.sereplacederations(1);
        ground.addPreFilter(this.iterate);
        this.terrain = new TerrainGrid("terrain", 33, 257, new FractalTileLoader(ground, 256));
        this.terrain.setMaterial(this.material);
        this.terrain.setLocalTranslation(0, 0, 0);
        this.terrain.setLocalScale(2f, 1f, 2f);
        this.rootNode.attachChild(this.terrain);
        TerrainLodControl control = new TerrainGridLodControl(this.terrain, this.getCamera());
        // patch size, and a multiplier
        control.setLodCalculator(new DistanceLodCalculator(33, 2.7f));
        this.terrain.addControl(control);
        final BulletAppState bulletAppState = new BulletAppState();
        stateManager.attach(bulletAppState);
        this.getCamera().setLocation(new Vector3f(0, 256, 0));
        this.viewPort.setBackgroundColor(new ColorRGBA(0.7f, 0.8f, 1f, 1f));
        if (usePhysics) {
            CapsuleCollisionShape capsuleShape = new CapsuleCollisionShape(0.5f, 1.8f, 1);
            player3 = new CharacterControl(capsuleShape, 0.5f);
            player3.setJumpSpeed(20);
            player3.setFallSpeed(10);
            player3.setGravity(10);
            player3.setPhysicsLocation(new Vector3f(cam.getLocation().x, 256, cam.getLocation().z));
            bulletAppState.getPhysicsSpace().add(player3);
        }
        terrain.addListener(new TerrainGridListener() {

            public void gridMoved(Vector3f newCenter) {
            }

            public void tileAttached(Vector3f cell, TerrainQuad quad) {
                Texture alpha = null;
                try {
                    alpha = replacedetManager.loadTexture("TerrainAlphaTest/alpha_" + (int) cell.x + "_" + (int) cell.z + ".png");
                } catch (Exception e) {
                    alpha = replacedetManager.loadTexture("TerrainAlphaTest/alpha_default.png");
                }
                quad.getMaterial().setTexture("AlphaMap", alpha);
                if (usePhysics) {
                    quad.addControl(new RigidBodyControl(new HeightfieldCollisionShape(quad.getHeightMap(), terrain.getLocalScale()), 0));
                    bulletAppState.getPhysicsSpace().add(quad);
                }
                updateMarkerElevations();
            }

            public void tileDetached(Vector3f cell, TerrainQuad quad) {
                if (usePhysics) {
                    if (quad.getControl(RigidBodyControl.clreplaced) != null) {
                        bulletAppState.getPhysicsSpace().remove(quad);
                        quad.removeControl(RigidBodyControl.clreplaced);
                    }
                }
                updateMarkerElevations();
            }
        });
        this.initKeys();
        markers = new Node();
        rootNode.attachChild(markers);
        createMarkerPoints(1);
    }

    Node markers;

    private void createMarkerPoints(float count) {
        Node center = createAxisMarker(10);
        markers.attachChild(center);
        float xS = (count - 1) * terrain.getTerrainSize() - (terrain.getTerrainSize() / 2);
        float zS = (count - 1) * terrain.getTerrainSize() - (terrain.getTerrainSize() / 2);
        float xSi = xS;
        float zSi = zS;
        for (int x = 0; x < count * 2; x++) {
            for (int z = 0; z < count * 2; z++) {
                Node m = createAxisMarker(5);
                m.setLocalTranslation(xSi, 0, zSi);
                markers.attachChild(m);
                zSi += terrain.getTerrainSize();
            }
            zSi = zS;
            xSi += terrain.getTerrainSize();
        }
    }

    private void updateMarkerElevations() {
        for (Spatial s : markers.getChildren()) {
            float h = terrain.getHeight(new Vector2f(s.getLocalTranslation().x, s.getLocalTranslation().z));
            s.setLocalTranslation(s.getLocalTranslation().x, h + 1, s.getLocalTranslation().z);
        }
    }

    private void initKeys() {
        // You can map one or several inputs to one named action
        this.inputManager.addMapping("Lefts", new KeyTrigger(KeyInput.KEY_A));
        this.inputManager.addMapping("Rights", new KeyTrigger(KeyInput.KEY_D));
        this.inputManager.addMapping("Ups", new KeyTrigger(KeyInput.KEY_W));
        this.inputManager.addMapping("Downs", new KeyTrigger(KeyInput.KEY_S));
        this.inputManager.addMapping("Jumps", new KeyTrigger(KeyInput.KEY_SPACE));
        this.inputManager.addListener(this.actionListener, "Lefts");
        this.inputManager.addListener(this.actionListener, "Rights");
        this.inputManager.addListener(this.actionListener, "Ups");
        this.inputManager.addListener(this.actionListener, "Downs");
        this.inputManager.addListener(this.actionListener, "Jumps");
    }

    private boolean left;

    private boolean right;

    private boolean up;

    private boolean down;

    private final ActionListener actionListener = new ActionListener() {

        @Override
        public void onAction(final String name, final boolean keyPressed, final float tpf) {
            if (name.equals("Lefts")) {
                if (keyPressed) {
                    TerrainGridAlphaMapTest.this.left = true;
                } else {
                    TerrainGridAlphaMapTest.this.left = false;
                }
            } else if (name.equals("Rights")) {
                if (keyPressed) {
                    TerrainGridAlphaMapTest.this.right = true;
                } else {
                    TerrainGridAlphaMapTest.this.right = false;
                }
            } else if (name.equals("Ups")) {
                if (keyPressed) {
                    TerrainGridAlphaMapTest.this.up = true;
                } else {
                    TerrainGridAlphaMapTest.this.up = false;
                }
            } else if (name.equals("Downs")) {
                if (keyPressed) {
                    TerrainGridAlphaMapTest.this.down = true;
                } else {
                    TerrainGridAlphaMapTest.this.down = false;
                }
            } else if (name.equals("Jumps")) {
                TerrainGridAlphaMapTest.this.player3.jump();
            }
        }
    };

    private final Vector3f walkDirection = new Vector3f();

    @Override
    public void simpleUpdate(final float tpf) {
        Vector3f camDir = this.cam.getDirection().clone().multLocal(0.6f);
        Vector3f camLeft = this.cam.getLeft().clone().multLocal(0.4f);
        this.walkDirection.set(0, 0, 0);
        if (this.left) {
            this.walkDirection.addLocal(camLeft);
        }
        if (this.right) {
            this.walkDirection.addLocal(camLeft.negate());
        }
        if (this.up) {
            this.walkDirection.addLocal(camDir);
        }
        if (this.down) {
            this.walkDirection.addLocal(camDir.negate());
        }
        if (usePhysics) {
            this.player3.setWalkDirection(this.walkDirection);
            this.cam.setLocation(this.player3.getPhysicsLocation());
        }
    }

    protected Node createAxisMarker(float arrowSize) {
        Material redMat = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        redMat.getAdditionalRenderState().setWireframe(true);
        redMat.setColor("Color", ColorRGBA.Red);
        Material greenMat = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        greenMat.getAdditionalRenderState().setWireframe(true);
        greenMat.setColor("Color", ColorRGBA.Green);
        Material blueMat = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        blueMat.getAdditionalRenderState().setWireframe(true);
        blueMat.setColor("Color", ColorRGBA.Blue);
        Node axis = new Node();
        // create arrows
        Geometry arrowX = new Geometry("arrowX", new Arrow(new Vector3f(arrowSize, 0, 0)));
        arrowX.setMaterial(redMat);
        Geometry arrowY = new Geometry("arrowY", new Arrow(new Vector3f(0, arrowSize, 0)));
        arrowY.setMaterial(greenMat);
        Geometry arrowZ = new Geometry("arrowZ", new Arrow(new Vector3f(0, 0, arrowSize)));
        arrowZ.setMaterial(blueMat);
        axis.attachChild(arrowX);
        axis.attachChild(arrowY);
        axis.attachChild(arrowZ);
        // axis.setModelBound(new BoundingBox());
        return axis;
    }
}

19 Source : TestLodGeneration.java
with Apache License 2.0
from neuroph

public clreplaced TestLodGeneration extends SimpleApplication {

    public static void main(String[] args) {
        TestLodGeneration app = new TestLodGeneration();
        app.start();
    }

    boolean wireFrame = false;

    float reductionvalue = 0.0f;

    private int lodLevel = 0;

    private Node model;

    private BitmapText hudText;

    private List<Geometry> listGeoms = new ArrayList<Geometry>();

    private ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(5);

    private AnimChannel ch;

    public void simpleInitApp() {
        DirectionalLight dl = new DirectionalLight();
        dl.setDirection(new Vector3f(-1, -1, -1).normalizeLocal());
        rootNode.addLight(dl);
        AmbientLight al = new AmbientLight();
        al.setColor(ColorRGBA.White.mult(0.6f));
        rootNode.addLight(al);
        // model = (Node) replacedetManager.loadModel("Models/Sinbad/Sinbad.mesh.xml");
        model = (Node) replacedetManager.loadModel("Models/Jaime/Jaime.j3o");
        BoundingBox b = ((BoundingBox) model.getWorldBound());
        model.setLocalScale(1.2f / (b.getYExtent() * 2));
        // model.setLocalTranslation(0,-(b.getCenter().y - b.getYExtent())* model.getLocalScale().y, 0);
        for (Spatial spatial : model.getChildren()) {
            if (spatial instanceof Geometry) {
                listGeoms.add((Geometry) spatial);
            }
        }
        ChaseCamera chaseCam = new ChaseCamera(cam, inputManager);
        model.addControl(chaseCam);
        chaseCam.setLookAtOffset(b.getCenter());
        chaseCam.setDefaultDistance(5);
        chaseCam.setMinVerticalRotation(-FastMath.HALF_PI + 0.01f);
        chaseCam.setZoomSensitivity(0.5f);
        // ch = model.getControl(AnimControl.clreplaced).createChannel();
        // ch.setAnim("Wave");
        SkeletonControl c = model.getControl(SkeletonControl.clreplaced);
        if (c != null) {
            c.setEnabled(false);
        }
        reductionvalue = 0.80f;
        lodLevel = 1;
        for (final Geometry geometry : listGeoms) {
            LodGenerator lodGenerator = new LodGenerator(geometry);
            lodGenerator.bakeLods(LodGenerator.TriangleReductionMethod.PROPORTIONAL, reductionvalue);
            geometry.setLodLevel(lodLevel);
        }
        rootNode.attachChild(model);
        flyCam.setEnabled(false);
        guiFont = replacedetManager.loadFont("Interface/Fonts/Default.fnt");
        hudText = new BitmapText(guiFont, false);
        hudText.setSize(guiFont.getCharSet().getRenderedSize());
        hudText.setText(computeNbTri() + " tris");
        hudText.setLocalTranslation(cam.getWidth() / 2, hudText.getLineHeight(), 0);
        guiNode.attachChild(hudText);
        inputManager.addListener(new ActionListener() {

            public void onAction(String name, boolean isPressed, float tpf) {
                if (isPressed) {
                    if (name.equals("plus")) {
                        // lodLevel++;
                        // for (Geometry geometry : listGeoms) {
                        // if (geometry.getMesh().getNumLodLevels() <= lodLevel) {
                        // lodLevel = 0;
                        // }
                        // geometry.setLodLevel(lodLevel);
                        // }
                        // jaimeText.setText(computeNbTri() + " tris");
                        reductionvalue += 0.05f;
                        updateLod();
                    }
                    if (name.equals("minus")) {
                        // lodLevel--;
                        // for (Geometry geometry : listGeoms) {
                        // if (lodLevel < 0) {
                        // lodLevel = geometry.getMesh().getNumLodLevels() - 1;
                        // }
                        // geometry.setLodLevel(lodLevel);
                        // }
                        // jaimeText.setText(computeNbTri() + " tris");
                        reductionvalue -= 0.05f;
                        updateLod();
                    }
                    if (name.equals("wireFrame")) {
                        wireFrame = !wireFrame;
                        for (Geometry geometry : listGeoms) {
                            geometry.getMaterial().getAdditionalRenderState().setWireframe(wireFrame);
                        }
                    }
                }
            }

            private void updateLod() {
                reductionvalue = FastMath.clamp(reductionvalue, 0.0f, 1.0f);
                makeLod(LodGenerator.TriangleReductionMethod.PROPORTIONAL, reductionvalue, 1);
            }
        }, "plus", "minus", "wireFrame");
        inputManager.addMapping("plus", new KeyTrigger(KeyInput.KEY_ADD));
        inputManager.addMapping("minus", new KeyTrigger(KeyInput.KEY_SUBTRACT));
        inputManager.addMapping("wireFrame", new KeyTrigger(KeyInput.KEY_SPACE));
    }

    @Override
    public void simpleUpdate(float tpf) {
    // model.rotate(0, tpf, 0);
    }

    private int computeNbTri() {
        int nbTri = 0;
        for (Geometry geometry : listGeoms) {
            if (geometry.getMesh().getNumLodLevels() > 0) {
                nbTri += geometry.getMesh().getLodLevel(lodLevel).getNumElements();
            } else {
                nbTri += geometry.getMesh().getTriangleCount();
            }
        }
        return nbTri;
    }

    @Override
    public void destroy() {
        super.destroy();
        exec.shutdown();
    }

    private void makeLod(final LodGenerator.TriangleReductionMethod method, final float value, final int ll) {
        exec.execute(new Runnable() {

            public void run() {
                for (final Geometry geometry : listGeoms) {
                    LodGenerator lODGenerator = new LodGenerator(geometry);
                    final VertexBuffer[] lods = lODGenerator.computeLods(method, value);
                    enqueue(new Callable<Void>() {

                        public Void call() throws Exception {
                            geometry.getMesh().setLodLevels(lods);
                            lodLevel = 0;
                            if (geometry.getMesh().getNumLodLevels() > ll) {
                                lodLevel = ll;
                            }
                            geometry.setLodLevel(lodLevel);
                            hudText.setText(computeNbTri() + " tris");
                            return null;
                        }
                    });
                }
            }
        });
    }
}

19 Source : TestUserData.java
with Apache License 2.0
from neuroph

public void simpleInitApp() {
    Node scene = (Node) replacedetManager.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));
    }
}

19 Source : TestFBOPassthrough.java
with Apache License 2.0
from neuroph

/**
 * Demonstrates FrameBuffer usage.
 * The scene is first rendered to an FB with a texture attached,
 * the texture is then rendered onto the screen in ortho mode.
 *
 * @author Kirill
 */
public clreplaced TestFBOPreplacedthrough extends SimpleApplication {

    private Node fbNode = new Node("Framebuffer Node");

    private FrameBuffer fb;

    public static void main(String[] args) {
        TestFBOPreplacedthrough app = new TestFBOPreplacedthrough();
        app.start();
    }

    @Override
    public void simpleInitApp() {
        int w = settings.getWidth();
        int h = settings.getHeight();
        // setup framebuffer
        fb = new FrameBuffer(w, h, 1);
        Texture2D fbTex = new Texture2D(w, h, Format.RGBA8);
        fb.setDepthBuffer(Format.Depth);
        fb.setColorTexture(fbTex);
        // setup framebuffer's scene
        Sphere sphMesh = new Sphere(20, 20, 1);
        Material solidColor = replacedetManager.loadMaterial("Common/Materials/RedColor.j3m");
        Geometry sphere = new Geometry("sphere", sphMesh);
        sphere.setMaterial(solidColor);
        fbNode.attachChild(sphere);
        // setup main scene
        Picture p = new Picture("Picture");
        p.setPosition(0, 0);
        p.setWidth(w);
        p.setHeight(h);
        p.setTexture(replacedetManager, fbTex, false);
        rootNode.attachChild(p);
    }

    @Override
    public void simpleUpdate(float tpf) {
        fbNode.updateLogicalState(tpf);
        fbNode.updateGeometricState();
    }

    @Override
    public void simpleRender(RenderManager rm) {
        Renderer r = rm.getRenderer();
        // do FBO rendering
        r.setFrameBuffer(fb);
        // FBO uses current camera
        rm.setCamera(cam, false);
        r.clearBuffers(true, true, true);
        rm.renderScene(fbNode, viewPort);
        rm.flushQueue(viewPort);
        // go back to default rendering and let
        // SimpleApplication render the default scene
        r.setFrameBuffer(null);
    }
}

19 Source : TestBillboard.java
with Apache License 2.0
from neuroph

/**
 * @author Kirill Vainer
 */
public clreplaced TestBillboard extends SimpleApplication {

    public void simpleInitApp() {
        flyCam.setMoveSpeed(10);
        Quad q = new Quad(2, 2);
        Geometry g = new Geometry("Quad", q);
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat.setColor("Color", ColorRGBA.Blue);
        g.setMaterial(mat);
        Quad q2 = new Quad(1, 1);
        Geometry g3 = new Geometry("Quad2", q2);
        Material mat2 = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat2.setColor("Color", ColorRGBA.Yellow);
        g3.setMaterial(mat2);
        g3.setLocalTranslation(.5f, .5f, .01f);
        Box b = new Box(new Vector3f(0, 0, 3), .25f, .5f, .25f);
        Geometry g2 = new Geometry("Box", b);
        g2.setMaterial(mat);
        Node bb = new Node("billboard");
        BillboardControl control = new BillboardControl();
        bb.addControl(control);
        bb.attachChild(g);
        bb.attachChild(g3);
        n = new Node("parent");
        n.attachChild(g2);
        n.attachChild(bb);
        rootNode.attachChild(n);
        n2 = new Node("parentParent");
        n2.setLocalTranslation(Vector3f.UNIT_X.mult(5));
        n2.attachChild(n);
        rootNode.attachChild(n2);
    // rootNode.attachChild(bb);
    // rootNode.attachChild(g2);
    }

    Node n;

    Node n2;

    @Override
    public void simpleUpdate(float tpf) {
        super.simpleUpdate(tpf);
        n.rotate(0, tpf, 0);
        n.move(0.1f * tpf, 0, 0);
        n2.rotate(0, 0, -tpf);
    }

    public static void main(String[] args) {
        TestBillboard app = new TestBillboard();
        app.start();
    }
}

19 Source : TestBlenderObjectAnim.java
with Apache License 2.0
from neuroph

/**
 * This method finds a node of a given name.
 * @param rootNode the root node to search
 * @param name the name of the searched node
 * @return the found node or null
 */
private Spatial findNode(Node rootNode, String name) {
    if (name.equals(rootNode.getName())) {
        return rootNode;
    }
    return rootNode.getChild(name);
}

19 Source : TestPointLightShadows.java
with Apache License 2.0
from neuroph

public clreplaced TestPointLightShadows extends SimpleApplication {

    public static final int SHADOWMAP_SIZE = 512;

    public static void main(String[] args) {
        TestPointLightShadows app = new TestPointLightShadows();
        app.start();
    }

    Node lightNode;

    PointLightShadowRenderer plsr;

    PointLightShadowFilter plsf;

    @Override
    public void simpleInitApp() {
        flyCam.setMoveSpeed(10);
        cam.setLocation(new Vector3f(0.040581334f, 1.7745866f, 6.155161f));
        cam.setRotation(new Quaternion(4.3868728E-5f, 0.9999293f, -0.011230096f, 0.0039059948f));
        Node scene = (Node) replacedetManager.loadModel("Models/Test/CornellBox.j3o");
        scene.setShadowMode(RenderQueue.ShadowMode.CastAndReceive);
        rootNode.attachChild(scene);
        rootNode.getChild("Cube").setShadowMode(RenderQueue.ShadowMode.Receive);
        lightNode = (Node) rootNode.getChild("Lamp");
        Geometry lightMdl = new Geometry("Light", new Sphere(10, 10, 0.1f));
        // Geometry  lightMdl = new Geometry("Light", new Box(.1f,.1f,.1f));
        lightMdl.setMaterial(replacedetManager.loadMaterial("Common/Materials/RedColor.j3m"));
        lightMdl.setShadowMode(RenderQueue.ShadowMode.Off);
        lightNode.attachChild(lightMdl);
        // lightMdl.setLocalTranslation(lightNode.getLocalTranslation());
        Geometry box = new Geometry("box", new Box(0.2f, 0.2f, 0.2f));
        // Geometry  lightMdl = new Geometry("Light", new Box(.1f,.1f,.1f));
        box.setMaterial(replacedetManager.loadMaterial("Common/Materials/RedColor.j3m"));
        box.setShadowMode(RenderQueue.ShadowMode.CastAndReceive);
        rootNode.attachChild(box);
        box.setLocalTranslation(-1f, 0.5f, -2);
        plsr = new PointLightShadowRenderer(replacedetManager, SHADOWMAP_SIZE);
        plsr.setLight((PointLight) scene.getLocalLightList().get(0));
        plsr.setEdgeFilteringMode(EdgeFilteringMode.PCF4);
        // plsr.setFlushQueues(false);
        // plsr.displayFrustum();
        plsr.displayDebug();
        viewPort.addProcessor(plsr);
        // PointLight pl = new PointLight();
        // pl.setPosition(new Vector3f(0, 0.5f, 0));
        // pl.setRadius(5);
        // rootNode.addLight(pl);
        // 
        // Geometry lightMdl2 = new Geometry("Light2", new Sphere(10, 10, 0.1f));
        // //Geometry  lightMdl = new Geometry("Light", new Box(.1f,.1f,.1f));
        // lightMdl2.setMaterial(replacedetManager.loadMaterial("Common/Materials/RedColor.j3m"));
        // lightMdl2.setShadowMode(RenderQueue.ShadowMode.Off);
        // rootNode.attachChild(lightMdl2);
        // lightMdl2.setLocalTranslation(pl.getPosition());
        // PointLightShadowRenderer plsr2 = new PointLightShadowRenderer(replacedetManager, 512);
        // plsr2.setShadowIntensity(0.3f);
        // plsr2.setLight(pl);
        // plsr2.setEdgeFilteringMode(EdgeFilteringMode.PCF4);
        // //   plsr.displayDebug();
        // viewPort.addProcessor(plsr2);
        plsf = new PointLightShadowFilter(replacedetManager, SHADOWMAP_SIZE);
        plsf.setLight((PointLight) scene.getLocalLightList().get(0));
        plsf.setEdgeFilteringMode(EdgeFilteringMode.PCF4);
        plsf.setEnabled(false);
        FilterPostProcessor fpp = new FilterPostProcessor(replacedetManager);
        fpp.addFilter(plsf);
        viewPort.addProcessor(fpp);
        ShadowTestUIManager uiMan = new ShadowTestUIManager(replacedetManager, plsr, plsf, guiNode, inputManager, viewPort);
    }

    @Override
    public void simpleUpdate(float tpf) {
    // lightNode.move(FastMath.cos(tpf) * 0.4f, 0, FastMath.sin(tpf) * 0.4f);
    }
}

19 Source : TestManyLights.java
with Apache License 2.0
from neuroph

@Override
public void simpleInitApp() {
    flyCam.setMoveSpeed(10);
    Node scene = (Node) replacedetManager.loadModel("Scenes/ManyLights/Main.scene");
    rootNode.attachChild(scene);
// guiNode.setCullHint(CullHint.Always);
}

19 Source : TestLightNode.java
with Apache License 2.0
from neuroph

public clreplaced TestLightNode extends SimpleApplication {

    float angle;

    Node movingNode;

    public static void main(String[] args) {
        TestLightNode app = new TestLightNode();
        app.start();
    }

    @Override
    public void simpleInitApp() {
        Torus torus = new Torus(10, 6, 1, 3);
        // Torus torus = new Torus(50, 30, 1, 3);
        Geometry g = new Geometry("Torus Geom", torus);
        g.rotate(-FastMath.HALF_PI, 0, 0);
        g.center();
        // g.move(0, 1, 0);
        Material mat = new Material(replacedetManager, "Common/MatDefs/Light/Lighting.j3md");
        mat.setFloat("Shininess", 32f);
        mat.setBoolean("UseMaterialColors", true);
        mat.setColor("Ambient", ColorRGBA.Black);
        mat.setColor("Diffuse", ColorRGBA.White);
        mat.setColor("Specular", ColorRGBA.White);
        // mat.setBoolean("VertexLighting", true);
        // mat.setBoolean("LowQuality", true);
        g.setMaterial(mat);
        rootNode.attachChild(g);
        Geometry lightMdl = new Geometry("Light", new Sphere(10, 10, 0.1f));
        lightMdl.setMaterial(replacedetManager.loadMaterial("Common/Materials/RedColor.j3m"));
        movingNode = new Node("lightParentNode");
        movingNode.attachChild(lightMdl);
        rootNode.attachChild(movingNode);
        PointLight pl = new PointLight();
        pl.setColor(ColorRGBA.Green);
        pl.setRadius(4f);
        rootNode.addLight(pl);
        LightNode lightNode = new LightNode("pointLight", pl);
        movingNode.attachChild(lightNode);
        DirectionalLight dl = new DirectionalLight();
        dl.setColor(ColorRGBA.Red);
        dl.setDirection(new Vector3f(0, 1, 0));
        rootNode.addLight(dl);
    }

    @Override
    public void simpleUpdate(float tpf) {
        // cam.setLocation(new Vector3f(5.0347548f, 6.6481347f, 3.74853f));
        // cam.setRotation(new Quaternion(-0.19183293f, 0.80776674f, -0.37974006f, -0.40805697f));
        angle += tpf;
        angle %= FastMath.TWO_PI;
        movingNode.setLocalTranslation(new Vector3f(FastMath.cos(angle) * 3f, 2, FastMath.sin(angle) * 3f));
    }
}

19 Source : TestJoystick.java
with Apache License 2.0
from neuroph

public clreplaced TestJoystick extends SimpleApplication {

    private Joystick viewedJoystick;

    private GamepadView gamepad;

    private Node joystickInfo;

    private float yInfo = 0;

    public static void main(String[] args) {
        TestJoystick app = new TestJoystick();
        AppSettings settings = new AppSettings(true);
        settings.setUseJoysticks(true);
        app.setSettings(settings);
        app.start();
    }

    @Override
    public void simpleInitApp() {
        Joystick[] joysticks = inputManager.getJoysticks();
        if (joysticks == null)
            throw new IllegalStateException("Cannot find any joysticks!");
        try {
            PrintWriter out = new PrintWriter(new FileWriter("joysticks-" + System.currentTimeMillis() + ".txt"));
            dumpJoysticks(joysticks, out);
            out.close();
        } catch (IOException e) {
            throw new RuntimeException("Error writing joystick dump", e);
        }
        int gamepadSize = cam.getHeight() / 2;
        float scale = gamepadSize / 512.0f;
        gamepad = new GamepadView();
        gamepad.setLocalTranslation(cam.getWidth() - gamepadSize - (scale * 20), 0, 0);
        gamepad.setLocalScale(scale, scale, scale);
        guiNode.attachChild(gamepad);
        joystickInfo = new Node("joystickInfo");
        joystickInfo.setLocalTranslation(0, cam.getHeight(), 0);
        guiNode.attachChild(joystickInfo);
        // Add a raw listener because it's eisier to get all joystick events
        // this way.
        inputManager.addRawInputListener(new JoystickEventListener());
    }

    protected void dumpJoysticks(Joystick[] joysticks, PrintWriter out) {
        for (Joystick j : joysticks) {
            out.println("Joystick[" + j.getJoyId() + "]:" + j.getName());
            out.println("  buttons:" + j.getButtonCount());
            for (JoystickButton b : j.getButtons()) {
                out.println("   " + b);
            }
            out.println("  axes:" + j.getAxisCount());
            for (JoystickAxis axis : j.getAxes()) {
                out.println("   " + axis);
            }
        }
    }

    protected void addInfo(String info, int column) {
        BitmapText t = new BitmapText(guiFont);
        t.setText(info);
        t.setLocalTranslation(column * 200, yInfo, 0);
        joystickInfo.attachChild(t);
        yInfo -= t.getHeight();
    }

    protected void setViewedJoystick(Joystick stick) {
        if (this.viewedJoystick == stick)
            return;
        if (this.viewedJoystick != null) {
            joystickInfo.detachAllChildren();
        }
        this.viewedJoystick = stick;
        if (this.viewedJoystick != null) {
            // Draw the hud
            yInfo = 0;
            addInfo("Joystick:\"" + stick.getName() + "\"  id:" + stick.getJoyId(), 0);
            yInfo -= 5;
            float ySave = yInfo;
            // Column one for the buttons
            addInfo("Buttons:", 0);
            for (JoystickButton b : stick.getButtons()) {
                addInfo(" '" + b.getName() + "' id:'" + b.getLogicalId() + "'", 0);
            }
            yInfo = ySave;
            // Column two for the axes
            addInfo("Axes:", 1);
            for (JoystickAxis a : stick.getAxes()) {
                addInfo(" '" + a.getName() + "' id:'" + a.getLogicalId() + "' replacedog:" + a.isreplacedog(), 1);
            }
        }
    }

    /**
     *  Easier to watch for all button and axis events with a raw input listener.
     */
    protected clreplaced JoystickEventListener implements RawInputListener {

        public void onJoyAxisEvent(JoyAxisEvent evt) {
            setViewedJoystick(evt.getAxis().getJoystick());
            gamepad.setAxisValue(evt.getAxis(), evt.getValue());
        }

        public void onJoyButtonEvent(JoyButtonEvent evt) {
            setViewedJoystick(evt.getButton().getJoystick());
            gamepad.setButtonValue(evt.getButton(), evt.isPressed());
        }

        public void beginInput() {
        }

        public void endInput() {
        }

        public void onMouseMotionEvent(MouseMotionEvent evt) {
        }

        public void onMouseButtonEvent(MouseButtonEvent evt) {
        }

        public void onKeyEvent(KeyInputEvent evt) {
        }

        public void onTouchEvent(TouchEvent evt) {
        }
    }

    protected clreplaced GamepadView extends Node {

        float xAxis = 0;

        float yAxis = 0;

        float zAxis = 0;

        float zRotation = 0;

        float lastPovX = 0;

        float lastPovY = 0;

        Geometry leftStick;

        Geometry rightStick;

        Map<String, ButtonView> buttons = new HashMap<String, ButtonView>();

        public GamepadView() {
            super("gamepad");
            // Sizes naturally for the texture size.  All positions will
            // be in that space because it's easier.
            int size = 512;
            Material m = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
            m.setTexture("ColorMap", replacedetManager.loadTexture("Interface/Joystick/gamepad-buttons.png"));
            m.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
            Geometry buttonPanel = new Geometry("buttons", new Quad(size, size));
            buttonPanel.setLocalTranslation(0, 0, -1);
            buttonPanel.setMaterial(m);
            attachChild(buttonPanel);
            m = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
            m.setTexture("ColorMap", replacedetManager.loadTexture("Interface/Joystick/gamepad-frame.png"));
            m.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
            Geometry frame = new Geometry("frame", new Quad(size, size));
            frame.setMaterial(m);
            attachChild(frame);
            m = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
            m.setTexture("ColorMap", replacedetManager.loadTexture("Interface/Joystick/gamepad-stick.png"));
            m.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
            leftStick = new Geometry("leftStick", new Quad(64, 64));
            leftStick.setMaterial(m);
            attachChild(leftStick);
            rightStick = new Geometry("leftStick", new Quad(64, 64));
            rightStick.setMaterial(m);
            attachChild(rightStick);
            // A "standard" mapping... fits a majority of my game pads
            addButton(JoystickButton.BUTTON_0, 371, 512 - 176, 42, 42);
            addButton(JoystickButton.BUTTON_1, 407, 512 - 212, 42, 42);
            addButton(JoystickButton.BUTTON_2, 371, 512 - 248, 42, 42);
            addButton(JoystickButton.BUTTON_3, 334, 512 - 212, 42, 42);
            // Front buttons  Some of these have the top ones and the bottoms ones flipped.
            addButton(JoystickButton.BUTTON_4, 67, 512 - 111, 95, 21);
            addButton(JoystickButton.BUTTON_5, 348, 512 - 111, 95, 21);
            addButton(JoystickButton.BUTTON_6, 67, 512 - 89, 95, 21);
            addButton(JoystickButton.BUTTON_7, 348, 512 - 89, 95, 21);
            // Select and start buttons
            addButton(JoystickButton.BUTTON_8, 206, 512 - 198, 48, 30);
            addButton(JoystickButton.BUTTON_9, 262, 512 - 198, 48, 30);
            // Joystick push buttons
            addButton(JoystickButton.BUTTON_10, 147, 512 - 300, 75, 70);
            addButton(JoystickButton.BUTTON_11, 285, 512 - 300, 75, 70);
            // Fake button highlights for the POV axes
            // 
            // +Y
            // -X  +X
            // -Y
            // 
            addButton("POV +Y", 96, 512 - 174, 40, 38);
            addButton("POV +X", 128, 512 - 208, 40, 38);
            addButton("POV -Y", 96, 512 - 239, 40, 38);
            addButton("POV -X", 65, 512 - 208, 40, 38);
            resetPositions();
        }

        private void addButton(String name, float x, float y, float width, float height) {
            ButtonView b = new ButtonView(name, x, y, width, height);
            attachChild(b);
            buttons.put(name, b);
        }

        public void setAxisValue(JoystickAxis axis, float value) {
            System.out.println("Axis:" + axis.getName() + "=" + value);
            if (axis == axis.getJoystick().getXAxis()) {
                setXAxis(value);
            } else if (axis == axis.getJoystick().getYAxis()) {
                setYAxis(-value);
            } else if (axis == axis.getJoystick().getAxis(JoystickAxis.Z_AXIS)) {
                // Note: in the above condition, we could check the axis name but
                // I have at least one joystick that reports 2 "Z Axis" axes.
                // In this particular case, the first one is the right one so
                // a name based lookup will find the proper one.  It's a problem
                // because the erroneous axis sends a constant stream of values.
                setZAxis(value);
            } else if (axis == axis.getJoystick().getAxis(JoystickAxis.Z_ROTATION)) {
                setZRotation(-value);
            } else if (axis == axis.getJoystick().getPovXAxis()) {
                if (lastPovX < 0) {
                    setButtonValue("POV -X", false);
                } else if (lastPovX > 0) {
                    setButtonValue("POV +X", false);
                }
                if (value < 0) {
                    setButtonValue("POV -X", true);
                } else if (value > 0) {
                    setButtonValue("POV +X", true);
                }
                lastPovX = value;
            } else if (axis == axis.getJoystick().getPovYAxis()) {
                if (lastPovY < 0) {
                    setButtonValue("POV -Y", false);
                } else if (lastPovY > 0) {
                    setButtonValue("POV +Y", false);
                }
                if (value < 0) {
                    setButtonValue("POV -Y", true);
                } else if (value > 0) {
                    setButtonValue("POV +Y", true);
                }
                lastPovY = value;
            }
        }

        public void setButtonValue(JoystickButton button, boolean isPressed) {
            System.out.println("Button:" + button.getName() + "=" + (isPressed ? "Down" : "Up"));
            setButtonValue(button.getLogicalId(), isPressed);
        }

        protected void setButtonValue(String name, boolean isPressed) {
            ButtonView view = buttons.get(name);
            if (view != null) {
                if (isPressed) {
                    view.down();
                } else {
                    view.up();
                }
            }
        }

        public void setXAxis(float f) {
            xAxis = f;
            resetPositions();
        }

        public void setYAxis(float f) {
            yAxis = f;
            resetPositions();
        }

        public void setZAxis(float f) {
            zAxis = f;
            resetPositions();
        }

        public void setZRotation(float f) {
            zRotation = f;
            resetPositions();
        }

        private void resetPositions() {
            float xBase = 155;
            float yBase = 212;
            Vector2f dir = new Vector2f(xAxis, yAxis);
            float length = Math.min(1, dir.length());
            dir.normalizeLocal();
            float angle = dir.getAngle();
            float x = FastMath.cos(angle) * length * 10;
            float y = FastMath.sin(angle) * length * 10;
            leftStick.setLocalTranslation(xBase + x, yBase + y, 0);
            xBase = 291;
            dir = new Vector2f(zAxis, zRotation);
            length = Math.min(1, dir.length());
            dir.normalizeLocal();
            angle = dir.getAngle();
            x = FastMath.cos(angle) * length * 10;
            y = FastMath.sin(angle) * length * 10;
            rightStick.setLocalTranslation(xBase + x, yBase + y, 0);
        }
    }

    protected clreplaced ButtonView extends Node {

        private int state = 0;

        private Material material;

        private ColorRGBA hilite = new ColorRGBA(0.0f, 0.75f, 0.75f, 0.5f);

        public ButtonView(String name, float x, float y, float width, float height) {
            super("Button:" + name);
            setLocalTranslation(x, y, -0.5f);
            material = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
            material.setColor("Color", hilite);
            material.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
            Geometry g = new Geometry("highlight", new Quad(width, height));
            g.setMaterial(material);
            attachChild(g);
            resetState();
        }

        private void resetState() {
            if (state <= 0) {
                setCullHint(CullHint.Always);
            } else {
                setCullHint(CullHint.Dynamic);
            }
            System.out.println(getName() + " state:" + state);
        }

        public void down() {
            state++;
            resetState();
        }

        public void up() {
            state--;
            resetState();
        }
    }
}

19 Source : TestCameraNode.java
with Apache License 2.0
from neuroph

/**
 * A 3rd-person camera node follows a target (teapot).  Follow the teapot with
 * WASD keys, rotate by dragging the mouse.
 */
public clreplaced TestCameraNode extends SimpleApplication implements replacedogListener, ActionListener {

    private Geometry teaGeom;

    private Node teaNode;

    CameraNode camNode;

    boolean rotate = false;

    Vector3f direction = new Vector3f();

    public static void main(String[] args) {
        TestCameraNode app = new TestCameraNode();
        AppSettings s = new AppSettings(true);
        s.setFrameRate(100);
        app.setSettings(s);
        app.start();
    }

    public void simpleInitApp() {
        // load a teapot model
        teaGeom = (Geometry) replacedetManager.loadModel("Models/Teapot/Teapot.obj");
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/ShowNormals.j3md");
        teaGeom.setMaterial(mat);
        // create a node to attach the geometry and the camera node
        teaNode = new Node("teaNode");
        teaNode.attachChild(teaGeom);
        rootNode.attachChild(teaNode);
        // create a floor
        mat = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat.setTexture("ColorMap", replacedetManager.loadTexture("Interface/Logo/Monkey.jpg"));
        Geometry ground = new Geometry("ground", new Quad(50, 50));
        ground.setLocalRotation(new Quaternion().fromAngleAxis(-FastMath.HALF_PI, Vector3f.UNIT_X));
        ground.setLocalTranslation(-25, -1, 25);
        ground.setMaterial(mat);
        rootNode.attachChild(ground);
        // creating the camera Node
        camNode = new CameraNode("CamNode", cam);
        // Setting the direction to Spatial to camera, this means the camera will copy the movements of the Node
        camNode.setControlDir(ControlDirection.SpatialToCamera);
        // attaching the camNode to the teaNode
        teaNode.attachChild(camNode);
        // setting the local translation of the cam node to move it away from the teanNode a bit
        camNode.setLocalTranslation(new Vector3f(-10, 0, 0));
        // setting the camNode to look at the teaNode
        camNode.lookAt(teaNode.getLocalTranslation(), Vector3f.UNIT_Y);
        // disable the default 1st-person flyCam (don't forget this!!)
        flyCam.setEnabled(false);
        registerInput();
    }

    public void registerInput() {
        inputManager.addMapping("moveForward", new KeyTrigger(keyInput.KEY_UP), new KeyTrigger(keyInput.KEY_W));
        inputManager.addMapping("moveBackward", new KeyTrigger(keyInput.KEY_DOWN), new KeyTrigger(keyInput.KEY_S));
        inputManager.addMapping("moveRight", new KeyTrigger(keyInput.KEY_RIGHT), new KeyTrigger(keyInput.KEY_D));
        inputManager.addMapping("moveLeft", new KeyTrigger(keyInput.KEY_LEFT), new KeyTrigger(keyInput.KEY_A));
        inputManager.addMapping("toggleRotate", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
        inputManager.addMapping("rotateRight", new MouseAxisTrigger(MouseInput.AXIS_X, true));
        inputManager.addMapping("rotateLeft", new MouseAxisTrigger(MouseInput.AXIS_X, false));
        inputManager.addListener(this, "moveForward", "moveBackward", "moveRight", "moveLeft");
        inputManager.addListener(this, "rotateRight", "rotateLeft", "toggleRotate");
    }

    public void onreplacedog(String name, float value, float tpf) {
        // computing the normalized direction of the cam to move the teaNode
        direction.set(cam.getDirection()).normalizeLocal();
        if (name.equals("moveForward")) {
            direction.multLocal(5 * tpf);
            teaNode.move(direction);
        }
        if (name.equals("moveBackward")) {
            direction.multLocal(-5 * tpf);
            teaNode.move(direction);
        }
        if (name.equals("moveRight")) {
            direction.crossLocal(Vector3f.UNIT_Y).multLocal(5 * tpf);
            teaNode.move(direction);
        }
        if (name.equals("moveLeft")) {
            direction.crossLocal(Vector3f.UNIT_Y).multLocal(-5 * tpf);
            teaNode.move(direction);
        }
        if (name.equals("rotateRight") && rotate) {
            teaNode.rotate(0, 5 * tpf, 0);
        }
        if (name.equals("rotateLeft") && rotate) {
            teaNode.rotate(0, -5 * tpf, 0);
        }
    }

    public void onAction(String name, boolean keyPressed, float tpf) {
        // toggling rotation on or off
        if (name.equals("toggleRotate") && keyPressed) {
            rotate = true;
            inputManager.setCursorVisible(false);
        }
        if (name.equals("toggleRotate") && !keyPressed) {
            rotate = false;
            inputManager.setCursorVisible(true);
        }
    }
}

19 Source : HelloPicking.java
with Apache License 2.0
from neuroph

/**
 * Sample 8 - how to let the user pick (select) objects in the scene
 * using the mouse or key presses. Can be used for shooting, opening doors, etc.
 */
public clreplaced HelloPicking extends SimpleApplication {

    public static void main(String[] args) {
        HelloPicking app = new HelloPicking();
        app.start();
    }

    private Node shootables;

    private Geometry mark;

    @Override
    public void simpleInitApp() {
        // a "+" in the middle of the screen to help aiming
        initCrossHairs();
        // load custom key mappings
        initKeys();
        // a red sphere to mark the hit
        initMark();
        /**
         * create four colored boxes and a floor to shoot at:
         */
        shootables = new Node("Shootables");
        rootNode.attachChild(shootables);
        shootables.attachChild(makeCube("a Dragon", -2f, 0f, 1f));
        shootables.attachChild(makeCube("a tin can", 1f, -2f, 0f));
        shootables.attachChild(makeCube("the Sheriff", 0f, 1f, -2f));
        shootables.attachChild(makeCube("the Deputy", 1f, 0f, -4f));
        shootables.attachChild(makeFloor());
        shootables.attachChild(makeCharacter());
    }

    /**
     * Declaring the "Shoot" action and mapping to its triggers.
     */
    private void initKeys() {
        inputManager.addMapping("Shoot", // trigger 1: spacebar
        new KeyTrigger(KeyInput.KEY_SPACE), // trigger 2: left-button click
        new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
        inputManager.addListener(actionListener, "Shoot");
    }

    /**
     * Defining the "Shoot" action: Determine what was hit and how to respond.
     */
    private ActionListener actionListener = new ActionListener() {

        public void onAction(String name, boolean keyPressed, float tpf) {
            if (name.equals("Shoot") && !keyPressed) {
                // 1. Reset results list.
                CollisionResults results = new CollisionResults();
                // 2. Aim the ray from cam loc to cam direction.
                Ray ray = new Ray(cam.getLocation(), cam.getDirection());
                // 3. Collect intersections between Ray and Shootables in results list.
                shootables.collideWith(ray, results);
                // 4. Print the results
                System.out.println("----- Collisions? " + results.size() + "-----");
                for (int i = 0; i < results.size(); i++) {
                    // For each hit, we know distance, impact point, name of geometry.
                    float dist = results.getCollision(i).getDistance();
                    Vector3f pt = results.getCollision(i).getContactPoint();
                    String hit = results.getCollision(i).getGeometry().getName();
                    System.out.println("* Collision #" + i);
                    System.out.println("  You shot " + hit + " at " + pt + ", " + dist + " wu away.");
                }
                // 5. Use the results (we mark the hit object)
                if (results.size() > 0) {
                    // The closest collision point is what was truly hit:
                    CollisionResult closest = results.getClosestCollision();
                    // Let's interact - we mark the hit with a red dot.
                    mark.setLocalTranslation(closest.getContactPoint());
                    rootNode.attachChild(mark);
                } else {
                    // No hits? Then remove the red mark.
                    rootNode.detachChild(mark);
                }
            }
        }
    };

    /**
     * A cube object for target practice
     */
    protected Geometry makeCube(String name, float x, float y, float z) {
        Box box = new Box(1, 1, 1);
        Geometry cube = new Geometry(name, box);
        cube.setLocalTranslation(x, y, z);
        Material mat1 = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat1.setColor("Color", ColorRGBA.randomColor());
        cube.setMaterial(mat1);
        return cube;
    }

    /**
     * A floor to show that the "shot" can go through several objects.
     */
    protected Geometry makeFloor() {
        Box box = new Box(15, .2f, 15);
        Geometry floor = new Geometry("the Floor", box);
        floor.setLocalTranslation(0, -4, -5);
        Material mat1 = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat1.setColor("Color", ColorRGBA.Gray);
        floor.setMaterial(mat1);
        return floor;
    }

    /**
     * A red ball that marks the last spot that was "hit" by the "shot".
     */
    protected void initMark() {
        Sphere sphere = new Sphere(30, 30, 0.2f);
        mark = new Geometry("BOOM!", sphere);
        Material mark_mat = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mark_mat.setColor("Color", ColorRGBA.Red);
        mark.setMaterial(mark_mat);
    }

    /**
     * A centred plus sign to help the player aim.
     */
    protected void initCrossHairs() {
        setDisplayStatView(false);
        guiFont = replacedetManager.loadFont("Interface/Fonts/Default.fnt");
        BitmapText ch = new BitmapText(guiFont, false);
        ch.setSize(guiFont.getCharSet().getRenderedSize() * 2);
        // crosshairs
        ch.setText("+");
        // center
        ch.setLocalTranslation(settings.getWidth() / 2 - ch.getLineWidth() / 2, settings.getHeight() / 2 + ch.getLineHeight() / 2, 0);
        guiNode.attachChild(ch);
    }

    protected Spatial makeCharacter() {
        // load a character from jme3test-test-data
        Spatial golem = replacedetManager.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;
    }
}

19 Source : HelloNode.java
with Apache License 2.0
from neuroph

@Override
public void simpleInitApp() {
    /**
     * create a blue box at coordinates (1,-1,1)
     */
    Box box1 = new Box(1, 1, 1);
    Geometry blue = new Geometry("Box", box1);
    blue.setLocalTranslation(new Vector3f(1, -1, 1));
    Material mat1 = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    mat1.setColor("Color", ColorRGBA.Blue);
    blue.setMaterial(mat1);
    /**
     * create a red box straight above the blue one at (1,3,1)
     */
    Box box2 = new Box(1, 1, 1);
    Geometry red = new Geometry("Box", box2);
    red.setLocalTranslation(new Vector3f(1, 3, 1));
    Material mat2 = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    mat2.setColor("Color", ColorRGBA.Red);
    red.setMaterial(mat2);
    /**
     * Create a pivot node at (0,0,0) and attach it to the root node
     */
    Node pivot = new Node("pivot");
    // put this node in the scene
    rootNode.attachChild(pivot);
    /**
     * Attach the two boxes to the *pivot* node. (And transitively to the root node.)
     */
    pivot.attachChild(blue);
    pivot.attachChild(red);
    /**
     * Rotate the pivot node: Note that both boxes have rotated!
     */
    pivot.rotate(.4f, .4f, 0f);
}

19 Source : HelloAnimation.java
with Apache License 2.0
from neuroph

/**
 * Sample 7 - how to load an OgreXML model and play an animation,
 * using channels, a controller, and an AnimEventListener.
 */
public clreplaced HelloAnimation extends SimpleApplication implements AnimEventListener {

    Node player;

    private AnimChannel channel;

    private AnimControl control;

    public static void main(String[] args) {
        HelloAnimation app = new HelloAnimation();
        app.start();
    }

    @Override
    public void simpleInitApp() {
        viewPort.setBackgroundColor(ColorRGBA.LightGray);
        initKeys();
        /**
         * Add a light source so we can see the model
         */
        DirectionalLight dl = new DirectionalLight();
        dl.setDirection(new Vector3f(-0.1f, -1f, -1).normalizeLocal());
        rootNode.addLight(dl);
        /**
         * Load a model that contains animation
         */
        player = (Node) replacedetManager.loadModel("Models/Oto/Oto.mesh.xml");
        player.setLocalScale(0.5f);
        rootNode.attachChild(player);
        /**
         * Create a controller and channels.
         */
        control = player.getControl(AnimControl.clreplaced);
        control.addListener(this);
        channel = control.createChannel();
        channel.setAnim("stand");
    }

    /**
     * Use this listener to trigger something after an animation is done.
     */
    public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) {
        if (animName.equals("Walk")) {
            /**
             * After "walk", reset to "stand".
             */
            channel.setAnim("stand", 0.50f);
            channel.setLoopMode(LoopMode.DontLoop);
            channel.setSpeed(1f);
        }
    }

    /**
     * Use this listener to trigger something between two animations.
     */
    public void onAnimChange(AnimControl control, AnimChannel channel, String animName) {
    // unused
    }

    /**
     * Custom Keybindings: Mapping a named action to a key input.
     */
    private void initKeys() {
        inputManager.addMapping("Walk", new KeyTrigger(KeyInput.KEY_SPACE));
        inputManager.addListener(actionListener, "Walk");
    }

    /**
     * Definining the named action that can be triggered by key inputs.
     */
    private ActionListener actionListener = new ActionListener() {

        public void onAction(String name, boolean keyPressed, float tpf) {
            if (name.equals("Walk") && !keyPressed) {
                if (!channel.getAnimationName().equals("Walk")) {
                    /**
                     * Play the "walk" animation!
                     */
                    channel.setAnim("Walk", 0.50f);
                    channel.setLoopMode(LoopMode.Loop);
                }
            }
        }
    };
}

19 Source : CubeField.java
with Apache License 2.0
from neuroph

/**
 * @author Kyle "bonechilla" Williams
 */
public clreplaced CubeField extends SimpleApplication implements replacedogListener {

    public static void main(String[] args) {
        CubeField app = new CubeField();
        app.start();
    }

    private BitmapFont defaultFont;

    private boolean START;

    private int difficulty, Score, colorInt, highCap, lowCap, diffHelp;

    private Node player;

    private Geometry fcube;

    private ArrayList<Geometry> cubeField;

    private ArrayList<ColorRGBA> obstacleColors;

    private float speed, coreTime, coreTime2;

    private float camAngle = 0;

    private BitmapText fpsScoreText, pressStart;

    private boolean solidBox = true;

    private Material playerMaterial;

    private Material floorMaterial;

    private float fpsRate = 1000f / 1f;

    /**
     * Initializes game
     */
    @Override
    public void simpleInitApp() {
        Logger.getLogger("com.jme3").setLevel(Level.WARNING);
        flyCam.setEnabled(false);
        setDisplayStatView(false);
        Keys();
        defaultFont = replacedetManager.loadFont("Interface/Fonts/Default.fnt");
        pressStart = new BitmapText(defaultFont, false);
        fpsScoreText = new BitmapText(defaultFont, false);
        loadText(fpsScoreText, "Current Score: 0", defaultFont, 0, 2, 0);
        loadText(pressStart, "PRESS ENTER", defaultFont, 0, 5, 0);
        player = createPlayer();
        rootNode.attachChild(player);
        cubeField = new ArrayList<Geometry>();
        obstacleColors = new ArrayList<ColorRGBA>();
        gameReset();
    }

    /**
     * Used to reset cubeField
     */
    private void gameReset() {
        Score = 0;
        lowCap = 10;
        colorInt = 0;
        highCap = 40;
        difficulty = highCap;
        for (Geometry cube : cubeField) {
            cube.removeFromParent();
        }
        cubeField.clear();
        if (fcube != null) {
            fcube.removeFromParent();
        }
        fcube = createFirstCube();
        obstacleColors.clear();
        obstacleColors.add(ColorRGBA.Orange);
        obstacleColors.add(ColorRGBA.Red);
        obstacleColors.add(ColorRGBA.Yellow);
        renderer.setBackgroundColor(ColorRGBA.White);
        speed = lowCap / 400f;
        coreTime = 20.0f;
        coreTime2 = 10.0f;
        diffHelp = lowCap;
        player.setLocalTranslation(0, 0, 0);
    }

    @Override
    public void simpleUpdate(float tpf) {
        camTakeOver(tpf);
        if (START) {
            gameLogic(tpf);
        }
        colorLogic();
    }

    /**
     * Forcefully takes over Camera adding functionality and placing it behind the character
     * @param tpf Tickes Per Frame
     */
    private void camTakeOver(float tpf) {
        cam.setLocation(player.getLocalTranslation().add(-8, 2, 0));
        cam.lookAt(player.getLocalTranslation(), Vector3f.UNIT_Y);
        Quaternion rot = new Quaternion();
        rot.fromAngleNormalAxis(camAngle, Vector3f.UNIT_Z);
        cam.setRotation(cam.getRotation().mult(rot));
        camAngle *= FastMath.pow(.99f, fpsRate * tpf);
    }

    @Override
    public void requestClose(boolean esc) {
        if (!esc) {
            System.out.println("The game was quit.");
        } else {
            System.out.println("Player has Collided. Final Score is " + Score);
        }
        context.destroy(false);
    }

    /**
     * Randomly Places a cube on the map between 30 and 90 paces away from player
     */
    private void randomizeCube() {
        Geometry cube = fcube.clone();
        int playerX = (int) player.getLocalTranslation().getX();
        int playerZ = (int) player.getLocalTranslation().getZ();
        // float x = FastMath.nextRandomInt(playerX + difficulty + 10, playerX + difficulty + 150);
        float x = FastMath.nextRandomInt(playerX + difficulty + 30, playerX + difficulty + 90);
        float z = FastMath.nextRandomInt(playerZ - difficulty - 50, playerZ + difficulty + 50);
        cube.getLocalTranslation().set(x, 0, z);
        // playerX+difficulty+30,playerX+difficulty+90
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        if (!solidBox) {
            mat.getAdditionalRenderState().setWireframe(true);
        }
        mat.setColor("Color", obstacleColors.get(FastMath.nextRandomInt(0, obstacleColors.size() - 1)));
        cube.setMaterial(mat);
        rootNode.attachChild(cube);
        cubeField.add(cube);
    }

    private Geometry createFirstCube() {
        Vector3f loc = player.getLocalTranslation();
        loc.addLocal(4, 0, 0);
        Box b = new Box(loc, 1, 1, 1);
        Geometry geom = new Geometry("Box", b);
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat.setColor("Color", ColorRGBA.Blue);
        geom.setMaterial(mat);
        return geom;
    }

    private Node createPlayer() {
        Dome b = new Dome(Vector3f.ZERO, 10, 100, 1);
        Geometry playerMesh = new Geometry("Box", b);
        playerMaterial = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        playerMaterial.setColor("Color", ColorRGBA.Red);
        playerMesh.setMaterial(playerMaterial);
        playerMesh.setName("player");
        Box floor = new Box(Vector3f.ZERO.add(playerMesh.getLocalTranslation().getX(), playerMesh.getLocalTranslation().getY() - 1, 0), 100, 0, 100);
        Geometry floorMesh = new Geometry("Box", floor);
        floorMaterial = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        floorMaterial.setColor("Color", ColorRGBA.LightGray);
        floorMesh.setMaterial(floorMaterial);
        floorMesh.setName("floor");
        Node playerNode = new Node();
        playerNode.attachChild(playerMesh);
        playerNode.attachChild(floorMesh);
        return playerNode;
    }

    /**
     * If Game is Lost display Score and Reset the Game
     */
    private void gameLost() {
        START = false;
        loadText(pressStart, "You lost! Press enter to try again.", defaultFont, 0, 5, 0);
        gameReset();
    }

    /**
     * Core Game Logic
     */
    private void gameLogic(float tpf) {
        // Subtract difficulty level in accordance to speed every 10 seconds
        if (timer.getTimeInSeconds() >= coreTime2) {
            coreTime2 = timer.getTimeInSeconds() + 10;
            if (difficulty <= lowCap) {
                difficulty = lowCap;
            } else if (difficulty > lowCap) {
                difficulty -= 5;
                diffHelp += 1;
            }
        }
        if (speed < .1f) {
            speed += .000001f * tpf * fpsRate;
        }
        player.move(speed * tpf * fpsRate, 0, 0);
        if (cubeField.size() > difficulty) {
            cubeField.remove(0);
        } else if (cubeField.size() != difficulty) {
            randomizeCube();
        }
        if (cubeField.isEmpty()) {
            requestClose(false);
        } else {
            for (int i = 0; i < cubeField.size(); i++) {
                // better way to check collision
                Geometry playerModel = (Geometry) player.getChild(0);
                Geometry cubeModel = cubeField.get(i);
                cubeModel.updateGeometricState();
                BoundingVolume pVol = playerModel.getWorldBound();
                BoundingVolume vVol = cubeModel.getWorldBound();
                if (pVol.intersects(vVol)) {
                    gameLost();
                    return;
                }
                // Remove cube if 10 world units behind player
                if (cubeField.get(i).getLocalTranslation().getX() + 10 < player.getLocalTranslation().getX()) {
                    cubeField.get(i).removeFromParent();
                    cubeField.remove(cubeField.get(i));
                }
            }
        }
        Score += fpsRate * tpf;
        fpsScoreText.setText("Current Score: " + Score);
    }

    /**
     * Sets up the keyboard bindings
     */
    private void Keys() {
        inputManager.addMapping("START", new KeyTrigger(KeyInput.KEY_RETURN));
        inputManager.addMapping("Left", new KeyTrigger(KeyInput.KEY_LEFT));
        inputManager.addMapping("Right", new KeyTrigger(KeyInput.KEY_RIGHT));
        inputManager.addListener(this, "START", "Left", "Right");
    }

    public void onreplacedog(String binding, float value, float tpf) {
        if (binding.equals("START") && !START) {
            START = true;
            guiNode.detachChild(pressStart);
            System.out.println("START");
        } else if (START == true && binding.equals("Left")) {
            player.move(0, 0, -(speed / 2f) * value * fpsRate);
            camAngle -= value * tpf;
        } else if (START == true && binding.equals("Right")) {
            player.move(0, 0, (speed / 2f) * value * fpsRate);
            camAngle += value * tpf;
        }
    }

    /**
     * Determines the colors of the player, floor, obstacle and background
     */
    private void colorLogic() {
        if (timer.getTimeInSeconds() >= coreTime) {
            colorInt++;
            coreTime = timer.getTimeInSeconds() + 20;
            switch(colorInt) {
                case 1:
                    obstacleColors.clear();
                    solidBox = false;
                    obstacleColors.add(ColorRGBA.Green);
                    renderer.setBackgroundColor(ColorRGBA.Black);
                    playerMaterial.setColor("Color", ColorRGBA.White);
                    floorMaterial.setColor("Color", ColorRGBA.Black);
                    break;
                case 2:
                    obstacleColors.set(0, ColorRGBA.Black);
                    solidBox = true;
                    renderer.setBackgroundColor(ColorRGBA.White);
                    playerMaterial.setColor("Color", ColorRGBA.Gray);
                    floorMaterial.setColor("Color", ColorRGBA.LightGray);
                    break;
                case 3:
                    obstacleColors.set(0, ColorRGBA.Pink);
                    break;
                case 4:
                    obstacleColors.set(0, ColorRGBA.Cyan);
                    obstacleColors.add(ColorRGBA.Magenta);
                    renderer.setBackgroundColor(ColorRGBA.Gray);
                    floorMaterial.setColor("Color", ColorRGBA.Gray);
                    playerMaterial.setColor("Color", ColorRGBA.White);
                    break;
                case 5:
                    obstacleColors.remove(0);
                    renderer.setBackgroundColor(ColorRGBA.Pink);
                    solidBox = false;
                    playerMaterial.setColor("Color", ColorRGBA.White);
                    break;
                case 6:
                    obstacleColors.set(0, ColorRGBA.White);
                    solidBox = true;
                    renderer.setBackgroundColor(ColorRGBA.Black);
                    playerMaterial.setColor("Color", ColorRGBA.Gray);
                    floorMaterial.setColor("Color", ColorRGBA.LightGray);
                    break;
                case 7:
                    obstacleColors.set(0, ColorRGBA.Green);
                    renderer.setBackgroundColor(ColorRGBA.Gray);
                    playerMaterial.setColor("Color", ColorRGBA.Black);
                    floorMaterial.setColor("Color", ColorRGBA.Orange);
                    break;
                case 8:
                    obstacleColors.set(0, ColorRGBA.Red);
                    floorMaterial.setColor("Color", ColorRGBA.Pink);
                    break;
                case 9:
                    obstacleColors.set(0, ColorRGBA.Orange);
                    obstacleColors.add(ColorRGBA.Red);
                    obstacleColors.add(ColorRGBA.Yellow);
                    renderer.setBackgroundColor(ColorRGBA.White);
                    playerMaterial.setColor("Color", ColorRGBA.Red);
                    floorMaterial.setColor("Color", ColorRGBA.Gray);
                    colorInt = 0;
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * Sets up a BitmapText to be displayed
     * @param txt the Bitmap Text
     * @param text the
     * @param font the font of the text
     * @param x
     * @param y
     * @param z
     */
    private void loadText(BitmapText txt, String text, BitmapFont font, float x, float y, float z) {
        txt.setSize(font.getCharSet().getRenderedSize());
        txt.setLocalTranslation(txt.getLineWidth() * x, txt.getLineHeight() * y, z);
        txt.setText(text);
        guiNode.attachChild(txt);
    }
}

19 Source : TestSoftParticles.java
with Apache License 2.0
from neuroph

/**
 * @author Nehon
 */
public clreplaced TestSoftParticles extends SimpleApplication {

    private boolean softParticles = true;

    private FilterPostProcessor fpp;

    private TranslucentBucketFilter tbf;

    private Node particleNode;

    public static void main(String[] args) {
        TestSoftParticles app = new TestSoftParticles();
        app.start();
    }

    @Override
    public void simpleInitApp() {
        cam.setLocation(new Vector3f(-7.2221026f, 4.1183004f, 7.759811f));
        cam.setRotation(new Quaternion(0.06152846f, 0.91236454f, -0.1492115f, 0.37621948f));
        flyCam.setMoveSpeed(10);
        // -------- floor
        Box b = new Box(Vector3f.ZERO, 10, 0.1f, 10);
        Geometry geom = new Geometry("Box", b);
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat.setColor("Color", ColorRGBA.Gray);
        mat.setTexture("ColorMap", replacedetManager.loadTexture("Interface/Logo/Monkey.jpg"));
        geom.setMaterial(mat);
        rootNode.attachChild(geom);
        Box b2 = new Box(Vector3f.ZERO, 1, 1, 1);
        Geometry geom2 = new Geometry("Box", b2);
        Material mat2 = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat2.setColor("Color", ColorRGBA.DarkGray);
        geom2.setMaterial(mat2);
        rootNode.attachChild(geom2);
        geom2.setLocalScale(0.1f, 0.2f, 1);
        fpp = new FilterPostProcessor(replacedetManager);
        tbf = new TranslucentBucketFilter(true);
        fpp.addFilter(tbf);
        viewPort.addProcessor(fpp);
        particleNode = new Node("particleNode");
        rootNode.attachChild(particleNode);
        createParticles();
        inputManager.addListener(new ActionListener() {

            public void onAction(String name, boolean isPressed, float tpf) {
                if (isPressed && name.equals("toggle")) {
                    // tbf.setEnabled(!tbf.isEnabled());
                    softParticles = !softParticles;
                    if (softParticles) {
                        viewPort.addProcessor(fpp);
                    } else {
                        viewPort.removeProcessor(fpp);
                    }
                }
            }
        }, "toggle");
        inputManager.addMapping("toggle", new KeyTrigger(KeyInput.KEY_SPACE));
        // emit again
        inputManager.addListener(new ActionListener() {

            public void onAction(String name, boolean isPressed, float tpf) {
                if (isPressed && name.equals("refire")) {
                    // fpp.removeFilter(tbf); // <-- add back in to fix
                    particleNode.detachAllChildren();
                    createParticles();
                // fpp.addFilter(tbf);
                }
            }
        }, "refire");
        inputManager.addMapping("refire", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
    }

    private void createParticles() {
        Material material = new Material(replacedetManager, "Common/MatDefs/Misc/Particle.j3md");
        material.setTexture("Texture", replacedetManager.loadTexture("Effects/Explosion/flame.png"));
        // 
        material.setFloat("Softness", 3f);
        // Fire
        ParticleEmitter fire = new ParticleEmitter("Fire", ParticleMesh.Type.Triangle, 30);
        fire.setMaterial(material);
        fire.setShape(new EmitterSphereShape(Vector3f.ZERO, 0.1f));
        fire.setImagesX(2);
        // 2x2 texture animation
        fire.setImagesY(2);
        // red
        fire.setEndColor(new ColorRGBA(1f, 0f, 0f, 1f));
        // yellow
        fire.setStartColor(new ColorRGBA(1f, 1f, 0f, 0.5f));
        fire.setStartSize(0.6f);
        fire.setEndSize(0.01f);
        fire.setGravity(0, -0.3f, 0);
        fire.setLowLife(0.5f);
        fire.setHighLife(3f);
        fire.setLocalTranslation(0, 0.2f, 0);
        particleNode.attachChild(fire);
        ParticleEmitter smoke = new ParticleEmitter("Smoke", ParticleMesh.Type.Triangle, 30);
        smoke.setMaterial(material);
        smoke.setShape(new EmitterSphereShape(Vector3f.ZERO, 5));
        smoke.setImagesX(1);
        // 2x2 texture animation
        smoke.setImagesY(1);
        // dark gray
        smoke.setStartColor(new ColorRGBA(0.1f, 0.1f, 0.1f, 1f));
        // gray
        smoke.setEndColor(new ColorRGBA(0.5f, 0.5f, 0.5f, 0.3f));
        smoke.setStartSize(3f);
        smoke.setEndSize(5f);
        smoke.setGravity(0, -0.001f, 0);
        smoke.setLowLife(100f);
        smoke.setHighLife(100f);
        smoke.setLocalTranslation(0, 0.1f, 0);
        smoke.emitAllParticles();
        particleNode.attachChild(smoke);
    }
}

19 Source : TestExplosionEffect.java
with Apache License 2.0
from neuroph

public clreplaced TestExplosionEffect extends SimpleApplication {

    private float time = 0;

    private int state = 0;

    private Node explosionEffect = new Node("explosionFX");

    private ParticleEmitter flame, flash, spark, roundspark, smoketrail, debris, shockwave;

    private static final int COUNT_FACTOR = 1;

    private static final float COUNT_FACTOR_F = 1f;

    private static final boolean POINT_SPRITE = true;

    private static final Type EMITTER_TYPE = POINT_SPRITE ? Type.Point : Type.Triangle;

    public static void main(String[] args) {
        TestExplosionEffect app = new TestExplosionEffect();
        app.start();
    }

    private void createFlame() {
        flame = new ParticleEmitter("Flame", EMITTER_TYPE, 32 * COUNT_FACTOR);
        flame.setSelectRandomImage(true);
        flame.setStartColor(new ColorRGBA(1f, 0.4f, 0.05f, (float) (1f / COUNT_FACTOR_F)));
        flame.setEndColor(new ColorRGBA(.4f, .22f, .12f, 0f));
        flame.setStartSize(1.3f);
        flame.setEndSize(2f);
        flame.setShape(new EmitterSphereShape(Vector3f.ZERO, 1f));
        flame.setParticlesPerSec(0);
        flame.setGravity(0, -5, 0);
        flame.setLowLife(.4f);
        flame.setHighLife(.5f);
        flame.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 7, 0));
        flame.getParticleInfluencer().setVelocityVariation(1f);
        flame.setImagesX(2);
        flame.setImagesY(2);
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/Particle.j3md");
        mat.setTexture("Texture", replacedetManager.loadTexture("Effects/Explosion/flame.png"));
        mat.setBoolean("PointSprite", POINT_SPRITE);
        flame.setMaterial(mat);
        explosionEffect.attachChild(flame);
    }

    private void createFlash() {
        flash = new ParticleEmitter("Flash", EMITTER_TYPE, 24 * COUNT_FACTOR);
        flash.setSelectRandomImage(true);
        flash.setStartColor(new ColorRGBA(1f, 0.8f, 0.36f, (float) (1f / COUNT_FACTOR_F)));
        flash.setEndColor(new ColorRGBA(1f, 0.8f, 0.36f, 0f));
        flash.setStartSize(.1f);
        flash.setEndSize(3.0f);
        flash.setShape(new EmitterSphereShape(Vector3f.ZERO, .05f));
        flash.setParticlesPerSec(0);
        flash.setGravity(0, 0, 0);
        flash.setLowLife(.2f);
        flash.setHighLife(.2f);
        flash.setInitialVelocity(new Vector3f(0, 5f, 0));
        flash.setVelocityVariation(1);
        flash.setImagesX(2);
        flash.setImagesY(2);
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/Particle.j3md");
        mat.setTexture("Texture", replacedetManager.loadTexture("Effects/Explosion/flash.png"));
        mat.setBoolean("PointSprite", POINT_SPRITE);
        flash.setMaterial(mat);
        explosionEffect.attachChild(flash);
    }

    private void createRoundSpark() {
        roundspark = new ParticleEmitter("RoundSpark", EMITTER_TYPE, 20 * COUNT_FACTOR);
        roundspark.setStartColor(new ColorRGBA(1f, 0.29f, 0.34f, (float) (1.0 / COUNT_FACTOR_F)));
        roundspark.setEndColor(new ColorRGBA(0, 0, 0, (float) (0.5f / COUNT_FACTOR_F)));
        roundspark.setStartSize(1.2f);
        roundspark.setEndSize(1.8f);
        roundspark.setShape(new EmitterSphereShape(Vector3f.ZERO, 2f));
        roundspark.setParticlesPerSec(0);
        roundspark.setGravity(0, -.5f, 0);
        roundspark.setLowLife(1.8f);
        roundspark.setHighLife(2f);
        roundspark.setInitialVelocity(new Vector3f(0, 3, 0));
        roundspark.setVelocityVariation(.5f);
        roundspark.setImagesX(1);
        roundspark.setImagesY(1);
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/Particle.j3md");
        mat.setTexture("Texture", replacedetManager.loadTexture("Effects/Explosion/roundspark.png"));
        mat.setBoolean("PointSprite", POINT_SPRITE);
        roundspark.setMaterial(mat);
        explosionEffect.attachChild(roundspark);
    }

    private void createSpark() {
        spark = new ParticleEmitter("Spark", Type.Triangle, 30 * COUNT_FACTOR);
        spark.setStartColor(new ColorRGBA(1f, 0.8f, 0.36f, (float) (1.0f / COUNT_FACTOR_F)));
        spark.setEndColor(new ColorRGBA(1f, 0.8f, 0.36f, 0f));
        spark.setStartSize(.5f);
        spark.setEndSize(.5f);
        spark.setFacingVelocity(true);
        spark.setParticlesPerSec(0);
        spark.setGravity(0, 5, 0);
        spark.setLowLife(1.1f);
        spark.setHighLife(1.5f);
        spark.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 20, 0));
        spark.getParticleInfluencer().setVelocityVariation(1);
        spark.setImagesX(1);
        spark.setImagesY(1);
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/Particle.j3md");
        mat.setTexture("Texture", replacedetManager.loadTexture("Effects/Explosion/spark.png"));
        spark.setMaterial(mat);
        explosionEffect.attachChild(spark);
    }

    private void createSmokeTrail() {
        smoketrail = new ParticleEmitter("SmokeTrail", Type.Triangle, 22 * COUNT_FACTOR);
        smoketrail.setStartColor(new ColorRGBA(1f, 0.8f, 0.36f, (float) (1.0f / COUNT_FACTOR_F)));
        smoketrail.setEndColor(new ColorRGBA(1f, 0.8f, 0.36f, 0f));
        smoketrail.setStartSize(.2f);
        smoketrail.setEndSize(1f);
        // smoketrail.setShape(new EmitterSphereShape(Vector3f.ZERO, 1f));
        smoketrail.setFacingVelocity(true);
        smoketrail.setParticlesPerSec(0);
        smoketrail.setGravity(0, 1, 0);
        smoketrail.setLowLife(.4f);
        smoketrail.setHighLife(.5f);
        smoketrail.setInitialVelocity(new Vector3f(0, 12, 0));
        smoketrail.setVelocityVariation(1);
        smoketrail.setImagesX(1);
        smoketrail.setImagesY(3);
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/Particle.j3md");
        mat.setTexture("Texture", replacedetManager.loadTexture("Effects/Explosion/smoketrail.png"));
        smoketrail.setMaterial(mat);
        explosionEffect.attachChild(smoketrail);
    }

    private void createDebris() {
        debris = new ParticleEmitter("Debris", Type.Triangle, 15 * COUNT_FACTOR);
        debris.setSelectRandomImage(true);
        debris.setRandomAngle(true);
        debris.setRotateSpeed(FastMath.TWO_PI * 4);
        debris.setStartColor(new ColorRGBA(1f, 0.59f, 0.28f, (float) (1.0f / COUNT_FACTOR_F)));
        debris.setEndColor(new ColorRGBA(.5f, 0.5f, 0.5f, 0f));
        debris.setStartSize(.2f);
        debris.setEndSize(.2f);
        // debris.setShape(new EmitterSphereShape(Vector3f.ZERO, .05f));
        debris.setParticlesPerSec(0);
        debris.setGravity(0, 12f, 0);
        debris.setLowLife(1.4f);
        debris.setHighLife(1.5f);
        debris.setInitialVelocity(new Vector3f(0, 15, 0));
        debris.setVelocityVariation(.60f);
        debris.setImagesX(3);
        debris.setImagesY(3);
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/Particle.j3md");
        mat.setTexture("Texture", replacedetManager.loadTexture("Effects/Explosion/Debris.png"));
        debris.setMaterial(mat);
        explosionEffect.attachChild(debris);
    }

    private void createShockwave() {
        shockwave = new ParticleEmitter("Shockwave", Type.Triangle, 1 * COUNT_FACTOR);
        // shockwave.setRandomAngle(true);
        shockwave.setFaceNormal(Vector3f.UNIT_Y);
        shockwave.setStartColor(new ColorRGBA(.48f, 0.17f, 0.01f, (float) (.8f / COUNT_FACTOR_F)));
        shockwave.setEndColor(new ColorRGBA(.48f, 0.17f, 0.01f, 0f));
        shockwave.setStartSize(0f);
        shockwave.setEndSize(7f);
        shockwave.setParticlesPerSec(0);
        shockwave.setGravity(0, 0, 0);
        shockwave.setLowLife(0.5f);
        shockwave.setHighLife(0.5f);
        shockwave.setInitialVelocity(new Vector3f(0, 0, 0));
        shockwave.setVelocityVariation(0f);
        shockwave.setImagesX(1);
        shockwave.setImagesY(1);
        Material mat = new Material(replacedetManager, "Common/MatDefs/Misc/Particle.j3md");
        mat.setTexture("Texture", replacedetManager.loadTexture("Effects/Explosion/shockwave.png"));
        shockwave.setMaterial(mat);
        explosionEffect.attachChild(shockwave);
    }

    @Override
    public void simpleInitApp() {
        createFlame();
        createFlash();
        createSpark();
        createRoundSpark();
        createSmokeTrail();
        createDebris();
        createShockwave();
        explosionEffect.setLocalScale(0.5f);
        renderManager.preloadScene(explosionEffect);
        cam.setLocation(new Vector3f(0, 3.5135868f, 10));
        cam.setRotation(new Quaternion(1.5714673E-4f, 0.98696727f, -0.16091813f, 9.6381607E-4f));
        rootNode.attachChild(explosionEffect);
    }

    @Override
    public void simpleUpdate(float tpf) {
        time += tpf / speed;
        if (time > 1f && state == 0) {
            flash.emitAllParticles();
            spark.emitAllParticles();
            smoketrail.emitAllParticles();
            debris.emitAllParticles();
            shockwave.emitAllParticles();
            state++;
        }
        if (time > 1f + .05f / speed && state == 1) {
            flame.emitAllParticles();
            roundspark.emitAllParticles();
            state++;
        }
        // rewind the effect
        if (time > 5 / speed && state == 2) {
            state = 0;
            time = 0;
            flash.killAllParticles();
            spark.killAllParticles();
            smoketrail.killAllParticles();
            debris.killAllParticles();
            flame.killAllParticles();
            roundspark.killAllParticles();
            shockwave.killAllParticles();
        }
    }
}

19 Source : TestMousePick.java
with Apache License 2.0
from neuroph

public clreplaced TestMousePick extends SimpleApplication {

    public static void main(String[] args) {
        TestMousePick app = new TestMousePick();
        app.start();
    }

    Node shootables;

    Geometry mark;

    @Override
    public void simpleInitApp() {
        flyCam.setEnabled(false);
        // a red sphere to mark the hit
        initMark();
        /**
         * create four colored boxes and a floor to shoot at:
         */
        shootables = new Node("Shootables");
        rootNode.attachChild(shootables);
        shootables.attachChild(makeCube("a Dragon", -2f, 0f, 1f));
        shootables.attachChild(makeCube("a tin can", 1f, -2f, 0f));
        shootables.attachChild(makeCube("the Sheriff", 0f, 1f, -2f));
        shootables.attachChild(makeCube("the Deputy", 1f, 0f, -4f));
        shootables.attachChild(makeFloor());
        shootables.attachChild(makeCharacter());
    }

    @Override
    public void simpleUpdate(float tpf) {
        Vector3f origin = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.0f);
        Vector3f direction = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.3f);
        direction.subtractLocal(origin).normalizeLocal();
        Ray ray = new Ray(origin, direction);
        CollisionResults results = new CollisionResults();
        shootables.collideWith(ray, results);
        // System.out.println("----- Collisions? " + results.size() + "-----");
        // for (int i = 0; i < results.size(); i++) {
        // // For each hit, we know distance, impact point, name of geometry.
        // float dist = results.getCollision(i).getDistance();
        // Vector3f pt = results.getCollision(i).getWorldContactPoint();
        // String hit = results.getCollision(i).getGeometry().getName();
        // System.out.println("* Collision #" + i);
        // System.out.println("  You shot " + hit + " at " + pt + ", " + dist + " wu away.");
        // }
        if (results.size() > 0) {
            CollisionResult closest = results.getClosestCollision();
            mark.setLocalTranslation(closest.getContactPoint());
            Quaternion q = new Quaternion();
            q.lookAt(closest.getContactNormal(), Vector3f.UNIT_Y);
            mark.setLocalRotation(q);
            rootNode.attachChild(mark);
        } else {
            rootNode.detachChild(mark);
        }
    }

    /**
     * A cube object for target practice
     */
    protected Geometry makeCube(String name, float x, float y, float z) {
        Box box = new Box(new Vector3f(x, y, z), 1, 1, 1);
        Geometry cube = new Geometry(name, box);
        Material mat1 = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat1.setColor("Color", ColorRGBA.randomColor());
        cube.setMaterial(mat1);
        return cube;
    }

    /**
     * A floor to show that the "shot" can go through several objects.
     */
    protected Geometry makeFloor() {
        Box box = new Box(new Vector3f(0, -4, -5), 15, .2f, 15);
        Geometry floor = new Geometry("the Floor", box);
        Material mat1 = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat1.setColor("Color", ColorRGBA.Gray);
        floor.setMaterial(mat1);
        return floor;
    }

    /**
     * A red ball that marks the last spot that was "hit" by the "shot".
     */
    protected void initMark() {
        Arrow arrow = new Arrow(Vector3f.UNIT_Z.mult(2f));
        arrow.setLineWidth(3);
        // Sphere sphere = new Sphere(30, 30, 0.2f);
        mark = new Geometry("BOOM!", arrow);
        // mark = new Geometry("BOOM!", sphere);
        Material mark_mat = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mark_mat.setColor("Color", ColorRGBA.Red);
        mark.setMaterial(mark_mat);
    }

    protected Spatial makeCharacter() {
        // load a character from jme3test-test-data
        Spatial golem = replacedetManager.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).normalizeLocal());
        golem.addLight(sun);
        return golem;
    }
}

19 Source : TestSweepTest.java
with Apache License 2.0
from neuroph

/**
 * A spatial moves and sweeps its next movement for obstacles before moving
 * there Run this example with Vsync enabled
 *
 * @author
 * @wezrule
 */
public clreplaced TestSweepTest extends SimpleApplication {

    private BulletAppState bulletAppState = new BulletAppState();

    private CapsuleCollisionShape obstacleCollisionShape = new CapsuleCollisionShape(0.3f, 0.5f);

    private CapsuleCollisionShape capsuleCollisionShape = new CapsuleCollisionShape(1f, 1f);

    private Node capsule;

    private Node obstacle;

    private float dist = .5f;

    public static void main(String[] args) {
        new TestSweepTest().start();
    }

    @Override
    public void simpleInitApp() {
        stateManager.attach(bulletAppState);
        capsule = new Node("capsule");
        capsule.move(-2, 0, 0);
        capsule.addControl(new RigidBodyControl(capsuleCollisionShape, 1));
        capsule.getControl(RigidBodyControl.clreplaced).setKinematic(true);
        bulletAppState.getPhysicsSpace().add(capsule);
        rootNode.attachChild(capsule);
        obstacle = new Node("obstacle");
        obstacle.move(2, 0, 0);
        RigidBodyControl bodyControl = new RigidBodyControl(obstacleCollisionShape, 0);
        obstacle.addControl(bodyControl);
        bulletAppState.getPhysicsSpace().add(obstacle);
        rootNode.attachChild(obstacle);
        bulletAppState.getPhysicsSpace().enableDebug(replacedetManager);
    }

    @Override
    public void simpleUpdate(float tpf) {
        float move = tpf * 1;
        List<PhysicsSweepTestResult> sweepTest = bulletAppState.getPhysicsSpace().sweepTest(capsuleCollisionShape, new Transform(capsule.getWorldTranslation()), new Transform(capsule.getWorldTranslation().add(dist, 0, 0)));
        if (sweepTest.size() > 0) {
            PhysicsSweepTestResult get = sweepTest.get(0);
            PhysicsCollisionObject collisionObject = get.getCollisionObject();
            fpsText.setText("Almost colliding with " + collisionObject.getUserObject().toString());
        } else {
            // if the sweep is clear then move the spatial
            capsule.move(move, 0, 0);
        }
    }
}

19 Source : TestSimplePhysics.java
with Apache License 2.0
from neuroph

@Override
public void simpleInitApp() {
    bulletAppState = new BulletAppState();
    stateManager.attach(bulletAppState);
    bulletAppState.getPhysicsSpace().enableDebug(replacedetManager);
    // Add a physics sphere to the world
    Node physicsSphere = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new SphereCollisionShape(1), 1);
    physicsSphere.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(3, 6, 0));
    rootNode.attachChild(physicsSphere);
    getPhysicsSpace().add(physicsSphere);
    // Add a physics sphere to the world using the collision shape from sphere one
    Node physicsSphere2 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, physicsSphere.getControl(RigidBodyControl.clreplaced).getCollisionShape(), 1);
    physicsSphere2.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(4, 8, 0));
    rootNode.attachChild(physicsSphere2);
    getPhysicsSpace().add(physicsSphere2);
    // Add a physics box to the world
    Node physicsBox = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new BoxCollisionShape(new Vector3f(1, 1, 1)), 1);
    physicsBox.getControl(RigidBodyControl.clreplaced).setFriction(0.1f);
    physicsBox.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(.6f, 4, .5f));
    rootNode.attachChild(physicsBox);
    getPhysicsSpace().add(physicsBox);
    // Add a physics cylinder to the world
    Node physicsCylinder = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new CylinderCollisionShape(new Vector3f(1f, 1f, 1.5f)), 1);
    physicsCylinder.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(2, 2, 0));
    rootNode.attachChild(physicsCylinder);
    getPhysicsSpace().add(physicsCylinder);
    // an obstacle mesh, does not move (mreplaced=0)
    Node node2 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new MeshCollisionShape(new Sphere(16, 16, 1.2f)), 0);
    node2.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(2.5f, -4, 0f));
    rootNode.attachChild(node2);
    getPhysicsSpace().add(node2);
    // the floor mesh, does not move (mreplaced=0)
    Node node3 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new PlaneCollisionShape(new Plane(new Vector3f(0, 1, 0), 0)), 0);
    node3.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(0f, -6, 0f));
    rootNode.attachChild(node3);
    getPhysicsSpace().add(node3);
// Join the physics objects with a Point2Point joint
// PhysicsPoint2PointJoint joint=new PhysicsPoint2PointJoint(physicsSphere, physicsBox, new Vector3f(-2,0,0), new Vector3f(2,0,0));
// PhysicsHingeJoint joint=new PhysicsHingeJoint(physicsSphere, physicsBox, new Vector3f(-2,0,0), new Vector3f(2,0,0), Vector3f.UNIT_Z,Vector3f.UNIT_Z);
// getPhysicsSpace().add(joint);
}

19 Source : TestRagdollCharacter.java
with Apache License 2.0
from neuroph

/**
 * @author normenhansen
 */
public clreplaced TestRagdollCharacter extends SimpleApplication implements AnimEventListener, ActionListener {

    BulletAppState bulletAppState;

    Node model;

    KinematicRagdollControl ragdoll;

    boolean leftStrafe = false, rightStrafe = false, forward = false, backward = false, leftRotate = false, rightRotate = false;

    AnimControl animControl;

    AnimChannel animChannel;

    public static void main(String[] args) {
        TestRagdollCharacter app = new TestRagdollCharacter();
        app.start();
    }

    public void simpleInitApp() {
        setupKeys();
        bulletAppState = new BulletAppState();
        bulletAppState.setEnabled(true);
        stateManager.attach(bulletAppState);
        // bulletAppState.getPhysicsSpace().enableDebug(replacedetManager);
        PhysicsTestHelper.createPhysicsTestWorld(rootNode, replacedetManager, bulletAppState.getPhysicsSpace());
        initWall(2, 1, 1);
        setupLight();
        cam.setLocation(new Vector3f(-8, 0, -4));
        cam.lookAt(new Vector3f(4, 0, -7), Vector3f.UNIT_Y);
        model = (Node) replacedetManager.loadModel("Models/Sinbad/Sinbad.mesh.xml");
        model.lookAt(new Vector3f(0, 0, -1), Vector3f.UNIT_Y);
        model.setLocalTranslation(4, 0, -7f);
        ragdoll = new KinematicRagdollControl(0.5f);
        model.addControl(ragdoll);
        getPhysicsSpace().add(ragdoll);
        speed = 1.3f;
        rootNode.attachChild(model);
        AnimControl control = model.getControl(AnimControl.clreplaced);
        animChannel = control.createChannel();
        animChannel.setAnim("IdleTop");
        control.addListener(this);
    }

    private void setupLight() {
        DirectionalLight dl = new DirectionalLight();
        dl.setDirection(new Vector3f(-0.1f, -0.7f, -1).normalizeLocal());
        dl.setColor(new ColorRGBA(1f, 1f, 1f, 1.0f));
        rootNode.addLight(dl);
    }

    private PhysicsSpace getPhysicsSpace() {
        return bulletAppState.getPhysicsSpace();
    }

    private void setupKeys() {
        inputManager.addMapping("Rotate Left", new KeyTrigger(KeyInput.KEY_H));
        inputManager.addMapping("Rotate Right", new KeyTrigger(KeyInput.KEY_K));
        inputManager.addMapping("Walk Forward", new KeyTrigger(KeyInput.KEY_U));
        inputManager.addMapping("Walk Backward", new KeyTrigger(KeyInput.KEY_J));
        inputManager.addMapping("Slice", new KeyTrigger(KeyInput.KEY_SPACE), new KeyTrigger(KeyInput.KEY_RETURN));
        inputManager.addListener(this, "Strafe Left", "Strafe Right");
        inputManager.addListener(this, "Rotate Left", "Rotate Right");
        inputManager.addListener(this, "Walk Forward", "Walk Backward");
        inputManager.addListener(this, "Slice");
    }

    public void initWall(float bLength, float bWidth, float bHeight) {
        Box brick = new Box(Vector3f.ZERO, bLength, bHeight, bWidth);
        brick.scaleTextureCoordinates(new Vector2f(1f, .5f));
        Material mat2 = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        TextureKey key = new TextureKey("Textures/Terrain/BrickWall/BrickWall.jpg");
        key.setGenerateMips(true);
        Texture tex = replacedetManager.loadTexture(key);
        mat2.setTexture("ColorMap", tex);
        float startpt = bLength / 4;
        float height = -5;
        for (int j = 0; j < 15; j++) {
            for (int i = 0; i < 4; i++) {
                Vector3f ori = new Vector3f(i * bLength * 2 + startpt, bHeight + height, -10);
                Geometry reBoxg = new Geometry("brick", brick);
                reBoxg.setMaterial(mat2);
                reBoxg.setLocalTranslation(ori);
                // for geometry with sphere mesh the physics system automatically uses a sphere collision shape
                reBoxg.addControl(new RigidBodyControl(1.5f));
                reBoxg.setShadowMode(ShadowMode.CastAndReceive);
                reBoxg.getControl(RigidBodyControl.clreplaced).setFriction(0.6f);
                this.rootNode.attachChild(reBoxg);
                this.getPhysicsSpace().add(reBoxg);
            }
            startpt = -startpt;
            height += 2 * bHeight;
        }
    }

    public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) {
        if (channel.getAnimationName().equals("SliceHorizontal")) {
            channel.setLoopMode(LoopMode.DontLoop);
            channel.setAnim("IdleTop", 5);
            channel.setLoopMode(LoopMode.Loop);
        }
    }

    public void onAnimChange(AnimControl control, AnimChannel channel, String animName) {
    }

    public void onAction(String binding, boolean value, float tpf) {
        if (binding.equals("Rotate Left")) {
            if (value) {
                leftRotate = true;
            } else {
                leftRotate = false;
            }
        } else if (binding.equals("Rotate Right")) {
            if (value) {
                rightRotate = true;
            } else {
                rightRotate = false;
            }
        } else if (binding.equals("Walk Forward")) {
            if (value) {
                forward = true;
            } else {
                forward = false;
            }
        } else if (binding.equals("Walk Backward")) {
            if (value) {
                backward = true;
            } else {
                backward = false;
            }
        } else if (binding.equals("Slice")) {
            if (value) {
                animChannel.setAnim("SliceHorizontal");
                animChannel.setSpeed(0.3f);
            }
        }
    }

    @Override
    public void simpleUpdate(float tpf) {
        if (forward) {
            model.move(model.getLocalRotation().multLocal(new Vector3f(0, 0, 1)).multLocal(tpf));
        } else if (backward) {
            model.move(model.getLocalRotation().multLocal(new Vector3f(0, 0, 1)).multLocal(-tpf));
        } else if (leftRotate) {
            model.rotate(0, tpf, 0);
        } else if (rightRotate) {
            model.rotate(0, -tpf, 0);
        }
        fpsText.setText(cam.getLocation() + "/" + cam.getRotation());
    }
}

19 Source : TestRagDoll.java
with Apache License 2.0
from neuroph

/**
 * @author normenhansen
 */
public clreplaced TestRagDoll extends SimpleApplication implements ActionListener {

    private BulletAppState bulletAppState = new BulletAppState();

    private Node ragDoll = new Node();

    private Node shoulders;

    private Vector3f upforce = new Vector3f(0, 200, 0);

    private boolean applyForce = false;

    public static void main(String[] args) {
        TestRagDoll app = new TestRagDoll();
        app.start();
    }

    @Override
    public void simpleInitApp() {
        bulletAppState = new BulletAppState();
        stateManager.attach(bulletAppState);
        bulletAppState.getPhysicsSpace().enableDebug(replacedetManager);
        inputManager.addMapping("Pull ragdoll up", new MouseButtonTrigger(0));
        inputManager.addListener(this, "Pull ragdoll up");
        PhysicsTestHelper.createPhysicsTestWorld(rootNode, replacedetManager, bulletAppState.getPhysicsSpace());
        createRagDoll();
    }

    private void createRagDoll() {
        shoulders = createLimb(0.2f, 1.0f, new Vector3f(0.00f, 1.5f, 0), true);
        Node uArmL = createLimb(0.2f, 0.5f, new Vector3f(-0.75f, 0.8f, 0), false);
        Node uArmR = createLimb(0.2f, 0.5f, new Vector3f(0.75f, 0.8f, 0), false);
        Node lArmL = createLimb(0.2f, 0.5f, new Vector3f(-0.75f, -0.2f, 0), false);
        Node lArmR = createLimb(0.2f, 0.5f, new Vector3f(0.75f, -0.2f, 0), false);
        Node body = createLimb(0.2f, 1.0f, new Vector3f(0.00f, 0.5f, 0), false);
        Node hips = createLimb(0.2f, 0.5f, new Vector3f(0.00f, -0.5f, 0), true);
        Node uLegL = createLimb(0.2f, 0.5f, new Vector3f(-0.25f, -1.2f, 0), false);
        Node uLegR = createLimb(0.2f, 0.5f, new Vector3f(0.25f, -1.2f, 0), false);
        Node lLegL = createLimb(0.2f, 0.5f, new Vector3f(-0.25f, -2.2f, 0), false);
        Node lLegR = createLimb(0.2f, 0.5f, new Vector3f(0.25f, -2.2f, 0), false);
        join(body, shoulders, new Vector3f(0f, 1.4f, 0));
        join(body, hips, new Vector3f(0f, -0.5f, 0));
        join(uArmL, shoulders, new Vector3f(-0.75f, 1.4f, 0));
        join(uArmR, shoulders, new Vector3f(0.75f, 1.4f, 0));
        join(uArmL, lArmL, new Vector3f(-0.75f, .4f, 0));
        join(uArmR, lArmR, new Vector3f(0.75f, .4f, 0));
        join(uLegL, hips, new Vector3f(-.25f, -0.5f, 0));
        join(uLegR, hips, new Vector3f(.25f, -0.5f, 0));
        join(uLegL, lLegL, new Vector3f(-.25f, -1.7f, 0));
        join(uLegR, lLegR, new Vector3f(.25f, -1.7f, 0));
        ragDoll.attachChild(shoulders);
        ragDoll.attachChild(body);
        ragDoll.attachChild(hips);
        ragDoll.attachChild(uArmL);
        ragDoll.attachChild(uArmR);
        ragDoll.attachChild(lArmL);
        ragDoll.attachChild(lArmR);
        ragDoll.attachChild(uLegL);
        ragDoll.attachChild(uLegR);
        ragDoll.attachChild(lLegL);
        ragDoll.attachChild(lLegR);
        rootNode.attachChild(ragDoll);
        bulletAppState.getPhysicsSpace().addAll(ragDoll);
    }

    private Node createLimb(float width, float height, Vector3f location, boolean rotate) {
        int axis = rotate ? PhysicsSpace.AXIS_X : PhysicsSpace.AXIS_Y;
        CapsuleCollisionShape shape = new CapsuleCollisionShape(width, height, axis);
        Node node = new Node("Limb");
        RigidBodyControl rigidBodyControl = new RigidBodyControl(shape, 1);
        node.setLocalTranslation(location);
        node.addControl(rigidBodyControl);
        return node;
    }

    private PhysicsJoint join(Node A, Node B, Vector3f connectionPoint) {
        Vector3f pivotA = A.worldToLocal(connectionPoint, new Vector3f());
        Vector3f pivotB = B.worldToLocal(connectionPoint, new Vector3f());
        ConeJoint joint = new ConeJoint(A.getControl(RigidBodyControl.clreplaced), B.getControl(RigidBodyControl.clreplaced), pivotA, pivotB);
        joint.setLimit(1f, 1f, 0);
        return joint;
    }

    public void onAction(String string, boolean bln, float tpf) {
        if ("Pull ragdoll up".equals(string)) {
            if (bln) {
                shoulders.getControl(RigidBodyControl.clreplaced).activate();
                applyForce = true;
            } else {
                applyForce = false;
            }
        }
    }

    @Override
    public void simpleUpdate(float tpf) {
        if (applyForce) {
            shoulders.getControl(RigidBodyControl.clreplaced).applyForce(upforce, Vector3f.ZERO);
        }
    }
}

19 Source : TestQ3.java
with Apache License 2.0
from neuroph

public clreplaced TestQ3 extends SimpleApplication implements ActionListener {

    private BulletAppState bulletAppState;

    private Node gameLevel;

    private PhysicsCharacter player;

    private Vector3f walkDirection = new Vector3f();

    private static boolean useHttp = false;

    private boolean left = false, right = false, up = false, down = false;

    public static void main(String[] args) {
        File file = new File("quake3level.zip");
        if (!file.exists()) {
            useHttp = true;
        }
        TestQ3 app = new TestQ3();
        app.start();
    }

    public void simpleInitApp() {
        bulletAppState = new BulletAppState();
        stateManager.attach(bulletAppState);
        flyCam.setMoveSpeed(100);
        setupKeys();
        this.cam.setFrustumFar(2000);
        DirectionalLight dl = new DirectionalLight();
        dl.setColor(ColorRGBA.White.clone().multLocal(2));
        dl.setDirection(new Vector3f(-1, -1, -1).normalize());
        rootNode.addLight(dl);
        AmbientLight am = new AmbientLight();
        am.setColor(ColorRGBA.White.mult(2));
        rootNode.addLight(am);
        // load the level from zip or http zip
        if (useHttp) {
            replacedetManager.registerLocator("http://jmonkeyengine.googlecode.com/files/quake3level.zip", HttpZipLocator.clreplaced);
        } else {
            replacedetManager.registerLocator("quake3level.zip", ZipLocator.clreplaced);
        }
        // create the geometry and attach it
        MaterialList matList = (MaterialList) replacedetManager.loadreplacedet("Scene.material");
        OgreMeshKey key = new OgreMeshKey("main.meshxml", matList);
        gameLevel = (Node) replacedetManager.loadreplacedet(key);
        gameLevel.setLocalScale(0.1f);
        // add a physics control, it will generate a MeshCollisionShape based on the gameLevel
        gameLevel.addControl(new RigidBodyControl(0));
        player = new PhysicsCharacter(new SphereCollisionShape(5), .01f);
        player.setJumpSpeed(20);
        player.setFallSpeed(30);
        player.setGravity(30);
        player.setPhysicsLocation(new Vector3f(60, 10, -60));
        rootNode.attachChild(gameLevel);
        getPhysicsSpace().addAll(gameLevel);
        getPhysicsSpace().add(player);
    }

    private PhysicsSpace getPhysicsSpace() {
        return bulletAppState.getPhysicsSpace();
    }

    @Override
    public void simpleUpdate(float tpf) {
        Vector3f camDir = cam.getDirection().clone().multLocal(0.6f);
        Vector3f camLeft = cam.getLeft().clone().multLocal(0.4f);
        walkDirection.set(0, 0, 0);
        if (left)
            walkDirection.addLocal(camLeft);
        if (right)
            walkDirection.addLocal(camLeft.negate());
        if (up)
            walkDirection.addLocal(camDir);
        if (down)
            walkDirection.addLocal(camDir.negate());
        player.setWalkDirection(walkDirection);
        cam.setLocation(player.getPhysicsLocation());
    }

    private void setupKeys() {
        inputManager.addMapping("Lefts", new KeyTrigger(KeyInput.KEY_A));
        inputManager.addMapping("Rights", new KeyTrigger(KeyInput.KEY_D));
        inputManager.addMapping("Ups", new KeyTrigger(KeyInput.KEY_W));
        inputManager.addMapping("Downs", new KeyTrigger(KeyInput.KEY_S));
        inputManager.addMapping("Space", new KeyTrigger(KeyInput.KEY_SPACE));
        inputManager.addListener(this, "Lefts");
        inputManager.addListener(this, "Rights");
        inputManager.addListener(this, "Ups");
        inputManager.addListener(this, "Downs");
        inputManager.addListener(this, "Space");
    }

    public void onAction(String binding, boolean value, float tpf) {
        if (binding.equals("Lefts")) {
            if (value)
                left = true;
            else
                left = false;
        } else if (binding.equals("Rights")) {
            if (value)
                right = true;
            else
                right = false;
        } else if (binding.equals("Ups")) {
            if (value)
                up = true;
            else
                up = false;
        } else if (binding.equals("Downs")) {
            if (value)
                down = true;
            else
                down = false;
        } else if (binding.equals("Space")) {
            player.jump();
        }
    }
}

19 Source : TestPhysicsReadWrite.java
with Apache License 2.0
from neuroph

/**
 * This is a basic Test of jbullet-jme functions
 *
 * @author normenhansen
 */
public clreplaced TestPhysicsReadWrite extends SimpleApplication {

    private BulletAppState bulletAppState;

    private Node physicsRootNode;

    public static void main(String[] args) {
        TestPhysicsReadWrite app = new TestPhysicsReadWrite();
        app.start();
    }

    @Override
    public void simpleInitApp() {
        bulletAppState = new BulletAppState();
        stateManager.attach(bulletAppState);
        bulletAppState.getPhysicsSpace().enableDebug(replacedetManager);
        physicsRootNode = new Node("PhysicsRootNode");
        rootNode.attachChild(physicsRootNode);
        // Add a physics sphere to the world
        Node physicsSphere = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new SphereCollisionShape(1), 1);
        physicsSphere.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(3, 6, 0));
        rootNode.attachChild(physicsSphere);
        getPhysicsSpace().add(physicsSphere);
        // Add a physics sphere to the world using the collision shape from sphere one
        Node physicsSphere2 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, physicsSphere.getControl(RigidBodyControl.clreplaced).getCollisionShape(), 1);
        physicsSphere2.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(4, 8, 0));
        rootNode.attachChild(physicsSphere2);
        getPhysicsSpace().add(physicsSphere2);
        // Add a physics box to the world
        Node physicsBox = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new BoxCollisionShape(new Vector3f(1, 1, 1)), 1);
        physicsBox.getControl(RigidBodyControl.clreplaced).setFriction(0.1f);
        physicsBox.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(.6f, 4, .5f));
        rootNode.attachChild(physicsBox);
        getPhysicsSpace().add(physicsBox);
        // Add a physics cylinder to the world
        Node physicsCylinder = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new CylinderCollisionShape(new Vector3f(1f, 1f, 1.5f)), 1);
        physicsCylinder.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(2, 2, 0));
        rootNode.attachChild(physicsCylinder);
        getPhysicsSpace().add(physicsCylinder);
        // an obstacle mesh, does not move (mreplaced=0)
        Node node2 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new MeshCollisionShape(new Sphere(16, 16, 1.2f)), 0);
        node2.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(2.5f, -4, 0f));
        rootNode.attachChild(node2);
        getPhysicsSpace().add(node2);
        // the floor mesh, does not move (mreplaced=0)
        Node node3 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new PlaneCollisionShape(new Plane(new Vector3f(0, 1, 0), 0)), 0);
        node3.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(0f, -6, 0f));
        rootNode.attachChild(node3);
        getPhysicsSpace().add(node3);
        // Join the physics objects with a Point2Point joint
        HingeJoint joint = new HingeJoint(physicsSphere.getControl(RigidBodyControl.clreplaced), physicsBox.getControl(RigidBodyControl.clreplaced), new Vector3f(-2, 0, 0), new Vector3f(2, 0, 0), Vector3f.UNIT_Z, Vector3f.UNIT_Z);
        getPhysicsSpace().add(joint);
        // save and load the physicsRootNode
        try {
            // remove all physics objects from physics space
            getPhysicsSpace().removeAll(physicsRootNode);
            physicsRootNode.removeFromParent();
            // export to byte array
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            BinaryExporter.getInstance().save(physicsRootNode, bout);
            // import from byte array
            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
            BinaryImporter imp = BinaryImporter.getInstance();
            imp.setreplacedetManager(replacedetManager);
            Node newPhysicsRootNode = (Node) imp.load(bin);
            // add all physics objects to physics space
            getPhysicsSpace().addAll(newPhysicsRootNode);
            rootNode.attachChild(newPhysicsRootNode);
        } catch (IOException ex) {
            Logger.getLogger(TestPhysicsReadWrite.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private PhysicsSpace getPhysicsSpace() {
        return bulletAppState.getPhysicsSpace();
    }

    @Override
    public void simpleUpdate(float tpf) {
    // TODO: add update code
    }

    @Override
    public void simpleRender(RenderManager rm) {
    // TODO: add render code
    }
}

19 Source : TestPhysicsHingeJoint.java
with Apache License 2.0
from neuroph

public void setupJoint() {
    Node holderNode = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new BoxCollisionShape(new Vector3f(.1f, .1f, .1f)), 0);
    holderNode.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(0f, 0, 0f));
    rootNode.attachChild(holderNode);
    getPhysicsSpace().add(holderNode);
    Node hammerNode = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new BoxCollisionShape(new Vector3f(.3f, .3f, .3f)), 1);
    hammerNode.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(0f, -1, 0f));
    rootNode.attachChild(hammerNode);
    getPhysicsSpace().add(hammerNode);
    joint = new HingeJoint(holderNode.getControl(RigidBodyControl.clreplaced), hammerNode.getControl(RigidBodyControl.clreplaced), Vector3f.ZERO, new Vector3f(0f, -1, 0f), Vector3f.UNIT_Z, Vector3f.UNIT_Z);
    getPhysicsSpace().add(joint);
}

19 Source : TestPhysicsCharacter.java
with Apache License 2.0
from neuroph

/**
 * A walking physical character followed by a 3rd person camera. (No animation.)
 * @author normenhansen, zathras
 */
public clreplaced TestPhysicsCharacter extends SimpleApplication implements ActionListener {

    private BulletAppState bulletAppState;

    private CharacterControl physicsCharacter;

    private Node characterNode;

    private CameraNode camNode;

    boolean rotate = false;

    private Vector3f walkDirection = new Vector3f(0, 0, 0);

    private Vector3f viewDirection = new Vector3f(0, 0, 0);

    boolean leftStrafe = false, rightStrafe = false, forward = false, backward = false, leftRotate = false, rightRotate = false;

    public static void main(String[] args) {
        TestPhysicsCharacter app = new TestPhysicsCharacter();
        app.start();
    }

    private void setupKeys() {
        inputManager.addMapping("Strafe Left", new KeyTrigger(KeyInput.KEY_Q), new KeyTrigger(KeyInput.KEY_Z));
        inputManager.addMapping("Strafe Right", new KeyTrigger(KeyInput.KEY_E), new KeyTrigger(KeyInput.KEY_X));
        inputManager.addMapping("Rotate Left", new KeyTrigger(KeyInput.KEY_A), new KeyTrigger(KeyInput.KEY_LEFT));
        inputManager.addMapping("Rotate Right", new KeyTrigger(KeyInput.KEY_D), new KeyTrigger(KeyInput.KEY_RIGHT));
        inputManager.addMapping("Walk Forward", new KeyTrigger(KeyInput.KEY_W), new KeyTrigger(KeyInput.KEY_UP));
        inputManager.addMapping("Walk Backward", new KeyTrigger(KeyInput.KEY_S), new KeyTrigger(KeyInput.KEY_DOWN));
        inputManager.addMapping("Jump", new KeyTrigger(KeyInput.KEY_SPACE), new KeyTrigger(KeyInput.KEY_RETURN));
        inputManager.addMapping("Shoot", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
        inputManager.addListener(this, "Strafe Left", "Strafe Right");
        inputManager.addListener(this, "Rotate Left", "Rotate Right");
        inputManager.addListener(this, "Walk Forward", "Walk Backward");
        inputManager.addListener(this, "Jump", "Shoot");
    }

    @Override
    public void simpleInitApp() {
        // activate physics
        bulletAppState = new BulletAppState();
        stateManager.attach(bulletAppState);
        // init a physical test scene
        PhysicsTestHelper.createPhysicsTestWorldSoccer(rootNode, replacedetManager, bulletAppState.getPhysicsSpace());
        setupKeys();
        // Add a physics character to the world
        physicsCharacter = new CharacterControl(new CapsuleCollisionShape(0.5f, 1.8f), .1f);
        physicsCharacter.setPhysicsLocation(new Vector3f(0, 1, 0));
        characterNode = new Node("character node");
        Spatial model = replacedetManager.loadModel("Models/Sinbad/Sinbad.mesh.xml");
        model.scale(0.25f);
        characterNode.addControl(physicsCharacter);
        getPhysicsSpace().add(physicsCharacter);
        rootNode.attachChild(characterNode);
        characterNode.attachChild(model);
        // set forward camera node that follows the character
        camNode = new CameraNode("CamNode", cam);
        camNode.setControlDir(ControlDirection.SpatialToCamera);
        camNode.setLocalTranslation(new Vector3f(0, 1, -5));
        camNode.lookAt(model.getLocalTranslation(), Vector3f.UNIT_Y);
        characterNode.attachChild(camNode);
        // disable the default 1st-person flyCam (don't forget this!!)
        flyCam.setEnabled(false);
    }

    @Override
    public void simpleUpdate(float tpf) {
        Vector3f camDir = cam.getDirection().mult(0.2f);
        Vector3f camLeft = cam.getLeft().mult(0.2f);
        camDir.y = 0;
        camLeft.y = 0;
        viewDirection.set(camDir);
        walkDirection.set(0, 0, 0);
        if (leftStrafe) {
            walkDirection.addLocal(camLeft);
        } else if (rightStrafe) {
            walkDirection.addLocal(camLeft.negate());
        }
        if (leftRotate) {
            viewDirection.addLocal(camLeft.mult(0.02f));
        } else if (rightRotate) {
            viewDirection.addLocal(camLeft.mult(0.02f).negate());
        }
        if (forward) {
            walkDirection.addLocal(camDir);
        } else if (backward) {
            walkDirection.addLocal(camDir.negate());
        }
        physicsCharacter.setWalkDirection(walkDirection);
        physicsCharacter.setViewDirection(viewDirection);
    }

    public void onAction(String binding, boolean value, float tpf) {
        if (binding.equals("Strafe Left")) {
            if (value) {
                leftStrafe = true;
            } else {
                leftStrafe = false;
            }
        } else if (binding.equals("Strafe Right")) {
            if (value) {
                rightStrafe = true;
            } else {
                rightStrafe = false;
            }
        } else if (binding.equals("Rotate Left")) {
            if (value) {
                leftRotate = true;
            } else {
                leftRotate = false;
            }
        } else if (binding.equals("Rotate Right")) {
            if (value) {
                rightRotate = true;
            } else {
                rightRotate = false;
            }
        } else if (binding.equals("Walk Forward")) {
            if (value) {
                forward = true;
            } else {
                forward = false;
            }
        } else if (binding.equals("Walk Backward")) {
            if (value) {
                backward = true;
            } else {
                backward = false;
            }
        } else if (binding.equals("Jump")) {
            physicsCharacter.jump();
        }
    }

    private PhysicsSpace getPhysicsSpace() {
        return bulletAppState.getPhysicsSpace();
    }

    @Override
    public void simpleRender(RenderManager rm) {
    // TODO: add render code
    }
}

19 Source : TestLocalPhysics.java
with Apache License 2.0
from neuroph

@Override
public void simpleInitApp() {
    bulletAppState = new BulletAppState();
    stateManager.attach(bulletAppState);
    bulletAppState.getPhysicsSpace().enableDebug(replacedetManager);
    // Add a physics sphere to the world
    Node physicsSphere = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new SphereCollisionShape(1), 1);
    physicsSphere.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(3, 6, 0));
    physicsSphere.getControl(RigidBodyControl.clreplaced).setApplyPhysicsLocal(true);
    rootNode.attachChild(physicsSphere);
    getPhysicsSpace().add(physicsSphere);
    // Add a physics sphere to the world using the collision shape from sphere one
    Node physicsSphere2 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, physicsSphere.getControl(RigidBodyControl.clreplaced).getCollisionShape(), 1);
    physicsSphere2.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(4, 8, 0));
    physicsSphere2.getControl(RigidBodyControl.clreplaced).setApplyPhysicsLocal(true);
    rootNode.attachChild(physicsSphere2);
    getPhysicsSpace().add(physicsSphere2);
    // Add a physics box to the world
    Node physicsBox = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new BoxCollisionShape(new Vector3f(1, 1, 1)), 1);
    physicsBox.getControl(RigidBodyControl.clreplaced).setFriction(0.1f);
    physicsBox.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(.6f, 4, .5f));
    physicsBox.getControl(RigidBodyControl.clreplaced).setApplyPhysicsLocal(true);
    rootNode.attachChild(physicsBox);
    getPhysicsSpace().add(physicsBox);
    // Add a physics cylinder to the world
    Node physicsCylinder = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new CylinderCollisionShape(new Vector3f(1f, 1f, 1.5f)), 1);
    physicsCylinder.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(2, 2, 0));
    physicsCylinder.getControl(RigidBodyControl.clreplaced).setApplyPhysicsLocal(true);
    rootNode.attachChild(physicsCylinder);
    getPhysicsSpace().add(physicsCylinder);
    // an obstacle mesh, does not move (mreplaced=0)
    Node node2 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new MeshCollisionShape(new Sphere(16, 16, 1.2f)), 0);
    node2.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(2.5f, -4, 0f));
    node2.getControl(RigidBodyControl.clreplaced).setApplyPhysicsLocal(true);
    rootNode.attachChild(node2);
    getPhysicsSpace().add(node2);
    // the floor mesh, does not move (mreplaced=0)
    Node node3 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new PlaneCollisionShape(new Plane(new Vector3f(0, 1, 0), 0)), 0);
    node3.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(0f, -6, 0f));
    node3.getControl(RigidBodyControl.clreplaced).setApplyPhysicsLocal(true);
    rootNode.attachChild(node3);
    getPhysicsSpace().add(node3);
// Join the physics objects with a Point2Point joint
// PhysicsPoint2PointJoint joint=new PhysicsPoint2PointJoint(physicsSphere, physicsBox, new Vector3f(-2,0,0), new Vector3f(2,0,0));
// PhysicsHingeJoint joint=new PhysicsHingeJoint(physicsSphere, physicsBox, new Vector3f(-2,0,0), new Vector3f(2,0,0), Vector3f.UNIT_Z,Vector3f.UNIT_Z);
// getPhysicsSpace().add(joint);
}

19 Source : TestKinematicAddToPhysicsSpaceIssue.java
with Apache License 2.0
from neuroph

@Override
public void simpleInitApp() {
    bulletAppState = new BulletAppState();
    stateManager.attach(bulletAppState);
    bulletAppState.getPhysicsSpace().enableDebug(replacedetManager);
    // Add a physics sphere to the world
    Node physicsSphere = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new SphereCollisionShape(1), 1);
    physicsSphere.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(3, 6, 0));
    rootNode.attachChild(physicsSphere);
    // Setting the rigidBody to kinematic before adding it to the physic space
    physicsSphere.getControl(RigidBodyControl.clreplaced).setKinematic(true);
    // adding it to the physic space
    getPhysicsSpace().add(physicsSphere);
    // Making it not kinematic again, it should fall under gravity, it doesn't
    physicsSphere.getControl(RigidBodyControl.clreplaced).setKinematic(false);
    // Add a physics sphere to the world using the collision shape from sphere one
    Node physicsSphere2 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new SphereCollisionShape(1), 1);
    physicsSphere2.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(5, 6, 0));
    rootNode.attachChild(physicsSphere2);
    // Adding the rigid body to physic space
    getPhysicsSpace().add(physicsSphere2);
    // making it kinematic
    physicsSphere2.getControl(RigidBodyControl.clreplaced).setKinematic(false);
    // Making it not kinematic again, it works properly, the rigidbody is affected by grvity.
    physicsSphere2.getControl(RigidBodyControl.clreplaced).setKinematic(false);
    // an obstacle mesh, does not move (mreplaced=0)
    Node node2 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new MeshCollisionShape(new Sphere(16, 16, 1.2f)), 0);
    node2.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(2.5f, -4, 0f));
    rootNode.attachChild(node2);
    getPhysicsSpace().add(node2);
    // the floor mesh, does not move (mreplaced=0)
    Node node3 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new PlaneCollisionShape(new Plane(new Vector3f(0, 1, 0), 0)), 0);
    node3.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(0f, -6, 0f));
    rootNode.attachChild(node3);
    getPhysicsSpace().add(node3);
}

19 Source : TestGhostObject.java
with Apache License 2.0
from neuroph

private void initGhostObject() {
    Vector3f halfExtents = new Vector3f(3, 4.2f, 1);
    ghostControl = new GhostControl(new BoxCollisionShape(halfExtents));
    Node node = new Node("Ghost Object");
    node.addControl(ghostControl);
    rootNode.attachChild(node);
    getPhysicsSpace().add(ghostControl);
}

19 Source : TestGhostObject.java
with Apache License 2.0
from neuroph

@Override
public void simpleInitApp() {
    bulletAppState = new BulletAppState();
    stateManager.attach(bulletAppState);
    bulletAppState.getPhysicsSpace().enableDebug(replacedetManager);
    // Mesh to be shared across several boxes.
    Box boxGeom = new Box(Vector3f.ZERO, 1f, 1f, 1f);
    // CollisionShape to be shared across several boxes.
    CollisionShape shape = new BoxCollisionShape(new Vector3f(1, 1, 1));
    Node physicsBox = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, shape, 1);
    physicsBox.setName("box0");
    physicsBox.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(.6f, 4, .5f));
    rootNode.attachChild(physicsBox);
    getPhysicsSpace().add(physicsBox);
    Node physicsBox1 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, shape, 1);
    physicsBox1.setName("box1");
    physicsBox1.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(0, 40, 0));
    rootNode.attachChild(physicsBox1);
    getPhysicsSpace().add(physicsBox1);
    Node physicsBox2 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new BoxCollisionShape(new Vector3f(1, 1, 1)), 1);
    physicsBox2.setName("box0");
    physicsBox2.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(.5f, 80, -.8f));
    rootNode.attachChild(physicsBox2);
    getPhysicsSpace().add(physicsBox2);
    // the floor, does not move (mreplaced=0)
    Node node = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new BoxCollisionShape(new Vector3f(100, 1, 100)), 0);
    node.setName("floor");
    node.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(0f, -6, 0f));
    rootNode.attachChild(node);
    getPhysicsSpace().add(node);
    initGhostObject();
}

19 Source : TestFancyCar.java
with Apache License 2.0
from neuroph

public clreplaced TestFancyCar extends SimpleApplication implements ActionListener {

    private BulletAppState bulletAppState;

    private VehicleControl player;

    private VehicleWheel fr, fl, br, bl;

    private Node node_fr, node_fl, node_br, node_bl;

    private float wheelRadius;

    private float steeringValue = 0;

    private float accelerationValue = 0;

    private Node carNode;

    public static void main(String[] args) {
        TestFancyCar app = new TestFancyCar();
        app.start();
    }

    private void setupKeys() {
        inputManager.addMapping("Lefts", new KeyTrigger(KeyInput.KEY_H));
        inputManager.addMapping("Rights", new KeyTrigger(KeyInput.KEY_K));
        inputManager.addMapping("Ups", new KeyTrigger(KeyInput.KEY_U));
        inputManager.addMapping("Downs", new KeyTrigger(KeyInput.KEY_J));
        inputManager.addMapping("Space", new KeyTrigger(KeyInput.KEY_SPACE));
        inputManager.addMapping("Reset", new KeyTrigger(KeyInput.KEY_RETURN));
        inputManager.addListener(this, "Lefts");
        inputManager.addListener(this, "Rights");
        inputManager.addListener(this, "Ups");
        inputManager.addListener(this, "Downs");
        inputManager.addListener(this, "Space");
        inputManager.addListener(this, "Reset");
    }

    @Override
    public void simpleInitApp() {
        bulletAppState = new BulletAppState();
        stateManager.attach(bulletAppState);
        // bulletAppState.getPhysicsSpace().enableDebug(replacedetManager);
        if (settings.getRenderer().startsWith("LWJGL")) {
            BasicShadowRenderer bsr = new BasicShadowRenderer(replacedetManager, 512);
            bsr.setDirection(new Vector3f(-0.5f, -0.3f, -0.3f).normalizeLocal());
            viewPort.addProcessor(bsr);
        }
        cam.setFrustumFar(150f);
        flyCam.setMoveSpeed(10);
        setupKeys();
        PhysicsTestHelper.createPhysicsTestWorld(rootNode, replacedetManager, bulletAppState.getPhysicsSpace());
        // setupFloor();
        buildPlayer();
        DirectionalLight dl = new DirectionalLight();
        dl.setDirection(new Vector3f(-0.5f, -1f, -0.3f).normalizeLocal());
        rootNode.addLight(dl);
        dl = new DirectionalLight();
        dl.setDirection(new Vector3f(0.5f, -0.1f, 0.3f).normalizeLocal());
        rootNode.addLight(dl);
    }

    private PhysicsSpace getPhysicsSpace() {
        return bulletAppState.getPhysicsSpace();
    }

    // public void setupFloor() {
    // Material mat = replacedetManager.loadMaterial("Textures/Terrain/BrickWall/BrickWall.j3m");
    // mat.getTextureParam("DiffuseMap").getTextureValue().setWrap(WrapMode.Repeat);
    // //        mat.getTextureParam("NormalMap").getTextureValue().setWrap(WrapMode.Repeat);
    // //        mat.getTextureParam("ParallaxMap").getTextureValue().setWrap(WrapMode.Repeat);
    // 
    // Box floor = new Box(Vector3f.ZERO, 140, 1f, 140);
    // floor.scaleTextureCoordinates(new Vector2f(112.0f, 112.0f));
    // Geometry floorGeom = new Geometry("Floor", floor);
    // floorGeom.setShadowMode(ShadowMode.Receive);
    // floorGeom.setMaterial(mat);
    // 
    // PhysicsNode tb = new PhysicsNode(floorGeom, new MeshCollisionShape(floorGeom.getMesh()), 0);
    // tb.setLocalTranslation(new Vector3f(0f, -6, 0f));
    // //        tb.attachDebugShape(replacedetManager);
    // rootNode.attachChild(tb);
    // getPhysicsSpace().add(tb);
    // }
    private Geometry findGeom(Spatial spatial, String name) {
        if (spatial instanceof Node) {
            Node node = (Node) spatial;
            for (int i = 0; i < node.getQuanreplacedy(); i++) {
                Spatial child = node.getChild(i);
                Geometry result = findGeom(child, name);
                if (result != null) {
                    return result;
                }
            }
        } else if (spatial instanceof Geometry) {
            if (spatial.getName().startsWith(name)) {
                return (Geometry) spatial;
            }
        }
        return null;
    }

    private void buildPlayer() {
        // 200=f1 car
        float stiffness = 120.0f;
        // (lower than damp!)
        float compValue = 0.2f;
        float dampValue = 0.3f;
        final float mreplaced = 400;
        // Load model and get chreplacedis Geometry
        carNode = (Node) replacedetManager.loadModel("Models/Ferrari/Car.scene");
        carNode.setShadowMode(ShadowMode.Cast);
        Geometry chasis = findGeom(carNode, "Car");
        BoundingBox box = (BoundingBox) chasis.getModelBound();
        // Create a hull collision shape for the chreplacedis
        CollisionShape carHull = CollisionShapeFactory.createDynamicMeshShape(chasis);
        // Create a vehicle control
        player = new VehicleControl(carHull, mreplaced);
        carNode.addControl(player);
        // Setting default values for wheels
        player.setSuspensionCompression(compValue * 2.0f * FastMath.sqrt(stiffness));
        player.setSuspensionDamping(dampValue * 2.0f * FastMath.sqrt(stiffness));
        player.setSuspensionStiffness(stiffness);
        player.setMaxSuspensionForce(10000);
        // Create four wheels and add them at their locations
        // note that our fancy car actually goes backwards..
        Vector3f wheelDirection = new Vector3f(0, -1, 0);
        Vector3f wheelAxle = new Vector3f(-1, 0, 0);
        Geometry wheel_fr = findGeom(carNode, "WheelFrontRight");
        wheel_fr.center();
        box = (BoundingBox) wheel_fr.getModelBound();
        wheelRadius = box.getYExtent();
        float back_wheel_h = (wheelRadius * 1.7f) - 1f;
        float front_wheel_h = (wheelRadius * 1.9f) - 1f;
        player.addWheel(wheel_fr.getParent(), box.getCenter().add(0, -front_wheel_h, 0), wheelDirection, wheelAxle, 0.2f, wheelRadius, true);
        Geometry wheel_fl = findGeom(carNode, "WheelFrontLeft");
        wheel_fl.center();
        box = (BoundingBox) wheel_fl.getModelBound();
        player.addWheel(wheel_fl.getParent(), box.getCenter().add(0, -front_wheel_h, 0), wheelDirection, wheelAxle, 0.2f, wheelRadius, true);
        Geometry wheel_br = findGeom(carNode, "WheelBackRight");
        wheel_br.center();
        box = (BoundingBox) wheel_br.getModelBound();
        player.addWheel(wheel_br.getParent(), box.getCenter().add(0, -back_wheel_h, 0), wheelDirection, wheelAxle, 0.2f, wheelRadius, false);
        Geometry wheel_bl = findGeom(carNode, "WheelBackLeft");
        wheel_bl.center();
        box = (BoundingBox) wheel_bl.getModelBound();
        player.addWheel(wheel_bl.getParent(), box.getCenter().add(0, -back_wheel_h, 0), wheelDirection, wheelAxle, 0.2f, wheelRadius, false);
        player.getWheel(2).setFrictionSlip(4);
        player.getWheel(3).setFrictionSlip(4);
        rootNode.attachChild(carNode);
        getPhysicsSpace().add(player);
    }

    public void onAction(String binding, boolean value, float tpf) {
        if (binding.equals("Lefts")) {
            if (value) {
                steeringValue += .5f;
            } else {
                steeringValue += -.5f;
            }
            player.steer(steeringValue);
        } else if (binding.equals("Rights")) {
            if (value) {
                steeringValue += -.5f;
            } else {
                steeringValue += .5f;
            }
            player.steer(steeringValue);
        } else // note that our fancy car actually goes backwards..
        if (binding.equals("Ups")) {
            if (value) {
                accelerationValue -= 800;
            } else {
                accelerationValue += 800;
            }
            player.accelerate(accelerationValue);
            player.setCollisionShape(CollisionShapeFactory.createDynamicMeshShape(findGeom(carNode, "Car")));
        } else if (binding.equals("Downs")) {
            if (value) {
                player.brake(40f);
            } else {
                player.brake(0f);
            }
        } else if (binding.equals("Reset")) {
            if (value) {
                System.out.println("Reset");
                player.setPhysicsLocation(Vector3f.ZERO);
                player.setPhysicsRotation(new Matrix3f());
                player.setLinearVelocity(Vector3f.ZERO);
                player.setAngularVelocity(Vector3f.ZERO);
                player.resetSuspension();
            } else {
            }
        }
    }

    @Override
    public void simpleUpdate(float tpf) {
        cam.lookAt(carNode.getWorldTranslation(), Vector3f.UNIT_Y);
    }
}

19 Source : TestCollisionGroups.java
with Apache License 2.0
from neuroph

@Override
public void simpleInitApp() {
    bulletAppState = new BulletAppState();
    stateManager.attach(bulletAppState);
    bulletAppState.getPhysicsSpace().enableDebug(replacedetManager);
    // Add a physics sphere to the world
    Node physicsSphere = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new SphereCollisionShape(1), 1);
    physicsSphere.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(3, 6, 0));
    rootNode.attachChild(physicsSphere);
    getPhysicsSpace().add(physicsSphere);
    // Add a physics sphere to the world
    Node physicsSphere2 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new SphereCollisionShape(1), 1);
    physicsSphere2.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(4, 8, 0));
    physicsSphere2.getControl(RigidBodyControl.clreplaced).addCollideWithGroup(PhysicsCollisionObject.COLLISION_GROUP_02);
    rootNode.attachChild(physicsSphere2);
    getPhysicsSpace().add(physicsSphere2);
    // an obstacle mesh, does not move (mreplaced=0)
    Node node2 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new MeshCollisionShape(new Sphere(16, 16, 1.2f)), 0);
    node2.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(2.5f, -4, 0f));
    node2.getControl(RigidBodyControl.clreplaced).setCollisionGroup(PhysicsCollisionObject.COLLISION_GROUP_02);
    node2.getControl(RigidBodyControl.clreplaced).setCollideWithGroups(PhysicsCollisionObject.COLLISION_GROUP_02);
    rootNode.attachChild(node2);
    getPhysicsSpace().add(node2);
    // the floor, does not move (mreplaced=0)
    Node node3 = PhysicsTestHelper.createPhysicsTestNode(replacedetManager, new MeshCollisionShape(new Box(Vector3f.ZERO, 100f, 0.2f, 100f)), 0);
    node3.getControl(RigidBodyControl.clreplaced).setPhysicsLocation(new Vector3f(0f, -6, 0f));
    rootNode.attachChild(node3);
    getPhysicsSpace().add(node3);
}

19 Source : TestBoneRagdoll.java
with Apache License 2.0
from neuroph

/**
 * PHYSICS RAGDOLLS ARE NOT WORKING PROPERLY YET!
 * @author normenhansen
 */
public clreplaced TestBoneRagdoll extends SimpleApplication implements RagdollCollisionListener, AnimEventListener {

    private BulletAppState bulletAppState;

    Material matBullet;

    Node model;

    KinematicRagdollControl ragdoll;

    float bulletSize = 1f;

    Material mat;

    Material mat3;

    private Sphere bullet;

    private SphereCollisionShape bulletCollisionShape;

    public static void main(String[] args) {
        TestBoneRagdoll app = new TestBoneRagdoll();
        app.start();
    }

    public void simpleInitApp() {
        initCrossHairs();
        initMaterial();
        cam.setLocation(new Vector3f(0.26924422f, 6.646658f, 22.265987f));
        cam.setRotation(new Quaternion(-2.302544E-4f, 0.99302495f, -0.117888905f, -0.0019395084f));
        bulletAppState = new BulletAppState();
        bulletAppState.setEnabled(true);
        stateManager.attach(bulletAppState);
        bullet = new Sphere(32, 32, 1.0f, true, false);
        bullet.setTextureMode(TextureMode.Projected);
        bulletCollisionShape = new SphereCollisionShape(1.0f);
        // bulletAppState.getPhysicsSpace().enableDebug(replacedetManager);
        PhysicsTestHelper.createPhysicsTestWorld(rootNode, replacedetManager, bulletAppState.getPhysicsSpace());
        setupLight();
        model = (Node) replacedetManager.loadModel("Models/Sinbad/Sinbad.mesh.xml");
        // model.setLocalRotation(new Quaternion().fromAngleAxis(FastMath.HALF_PI, Vector3f.UNIT_X));
        // debug view
        AnimControl control = model.getControl(AnimControl.clreplaced);
        SkeletonDebugger skeletonDebug = new SkeletonDebugger("skeleton", control.getSkeleton());
        Material mat2 = new Material(getreplacedetManager(), "Common/MatDefs/Misc/Unshaded.j3md");
        mat2.getAdditionalRenderState().setWireframe(true);
        mat2.setColor("Color", ColorRGBA.Green);
        mat2.getAdditionalRenderState().setDepthTest(false);
        skeletonDebug.setMaterial(mat2);
        skeletonDebug.setLocalTranslation(model.getLocalTranslation());
        // Note: PhysicsRagdollControl is still TODO, constructor will change
        ragdoll = new KinematicRagdollControl(0.5f);
        setupSinbad(ragdoll);
        ragdoll.addCollisionListener(this);
        model.addControl(ragdoll);
        float eighth_pi = FastMath.PI * 0.125f;
        ragdoll.setJointLimit("Waist", eighth_pi, eighth_pi, eighth_pi, eighth_pi, eighth_pi, eighth_pi);
        ragdoll.setJointLimit("Chest", eighth_pi, eighth_pi, 0, 0, eighth_pi, eighth_pi);
        // Oto's head is almost rigid
        // ragdoll.setJointLimit("head", 0, 0, eighth_pi, -eighth_pi, 0, 0);
        getPhysicsSpace().add(ragdoll);
        speed = 1.3f;
        rootNode.attachChild(model);
        // rootNode.attachChild(skeletonDebug);
        flyCam.setMoveSpeed(50);
        animChannel = control.createChannel();
        animChannel.setAnim("Dance");
        control.addListener(this);
        inputManager.addListener(new ActionListener() {

            public void onAction(String name, boolean isPressed, float tpf) {
                if (name.equals("toggle") && isPressed) {
                    Vector3f v = new Vector3f();
                    v.set(model.getLocalTranslation());
                    v.y = 0;
                    model.setLocalTranslation(v);
                    Quaternion q = new Quaternion();
                    float[] angles = new float[3];
                    model.getLocalRotation().toAngles(angles);
                    q.fromAngleAxis(angles[1], Vector3f.UNIT_Y);
                    model.setLocalRotation(q);
                    if (angles[0] < 0) {
                        animChannel.setAnim("StandUpBack");
                        ragdoll.blendToKinematicMode(0.5f);
                    } else {
                        animChannel.setAnim("StandUpFront");
                        ragdoll.blendToKinematicMode(0.5f);
                    }
                }
                if (name.equals("bullet+") && isPressed) {
                    bulletSize += 0.1f;
                }
                if (name.equals("bullet-") && isPressed) {
                    bulletSize -= 0.1f;
                }
                if (name.equals("stop") && isPressed) {
                    ragdoll.setEnabled(!ragdoll.isEnabled());
                    ragdoll.setRagdollMode();
                }
                if (name.equals("shoot") && !isPressed) {
                    Geometry bulletg = new Geometry("bullet", bullet);
                    bulletg.setMaterial(matBullet);
                    bulletg.setLocalTranslation(cam.getLocation());
                    bulletg.setLocalScale(bulletSize);
                    bulletCollisionShape = new SphereCollisionShape(bulletSize);
                    RigidBodyControl bulletNode = new RigidBodyControl(bulletCollisionShape, bulletSize * 10);
                    bulletNode.setCcdMotionThreshold(0.001f);
                    bulletNode.setLinearVelocity(cam.getDirection().mult(80));
                    bulletg.addControl(bulletNode);
                    rootNode.attachChild(bulletg);
                    getPhysicsSpace().add(bulletNode);
                }
                if (name.equals("boom") && !isPressed) {
                    Geometry bulletg = new Geometry("bullet", bullet);
                    bulletg.setMaterial(matBullet);
                    bulletg.setLocalTranslation(cam.getLocation());
                    bulletg.setLocalScale(bulletSize);
                    bulletCollisionShape = new SphereCollisionShape(bulletSize);
                    BombControl bulletNode = new BombControl(replacedetManager, bulletCollisionShape, 1);
                    bulletNode.setForceFactor(8);
                    bulletNode.setExplosionRadius(20);
                    bulletNode.setCcdMotionThreshold(0.001f);
                    bulletNode.setLinearVelocity(cam.getDirection().mult(180));
                    bulletg.addControl(bulletNode);
                    rootNode.attachChild(bulletg);
                    getPhysicsSpace().add(bulletNode);
                }
            }
        }, "toggle", "shoot", "stop", "bullet+", "bullet-", "boom");
        inputManager.addMapping("toggle", new KeyTrigger(KeyInput.KEY_SPACE));
        inputManager.addMapping("shoot", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
        inputManager.addMapping("boom", new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));
        inputManager.addMapping("stop", new KeyTrigger(KeyInput.KEY_H));
        inputManager.addMapping("bullet-", new KeyTrigger(KeyInput.KEY_COMMA));
        inputManager.addMapping("bullet+", new KeyTrigger(KeyInput.KEY_PERIOD));
    }

    private void setupLight() {
        // AmbientLight al = new AmbientLight();
        // al.setColor(ColorRGBA.White.mult(1));
        // rootNode.addLight(al);
        DirectionalLight dl = new DirectionalLight();
        dl.setDirection(new Vector3f(-0.1f, -0.7f, -1).normalizeLocal());
        dl.setColor(new ColorRGBA(1f, 1f, 1f, 1.0f));
        rootNode.addLight(dl);
    }

    private PhysicsSpace getPhysicsSpace() {
        return bulletAppState.getPhysicsSpace();
    }

    public void initMaterial() {
        matBullet = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        TextureKey key2 = new TextureKey("Textures/Terrain/Rock/Rock.PNG");
        key2.setGenerateMips(true);
        Texture tex2 = replacedetManager.loadTexture(key2);
        matBullet.setTexture("ColorMap", tex2);
    }

    protected void initCrossHairs() {
        guiFont = replacedetManager.loadFont("Interface/Fonts/Default.fnt");
        BitmapText ch = new BitmapText(guiFont, false);
        ch.setSize(guiFont.getCharSet().getRenderedSize() * 2);
        // crosshairs
        ch.setText("+");
        // center
        ch.setLocalTranslation(settings.getWidth() / 2 - guiFont.getCharSet().getRenderedSize() / 3 * 2, settings.getHeight() / 2 + ch.getLineHeight() / 2, 0);
        guiNode.attachChild(ch);
    }

    public void collide(Bone bone, PhysicsCollisionObject object, PhysicsCollisionEvent event) {
        if (object.getUserObject() != null && object.getUserObject() instanceof Geometry) {
            Geometry geom = (Geometry) object.getUserObject();
            if ("Floor".equals(geom.getName())) {
                return;
            }
        }
        ragdoll.setRagdollMode();
    }

    private void setupSinbad(KinematicRagdollControl ragdoll) {
        ragdoll.addBoneName("Ulna.L");
        ragdoll.addBoneName("Ulna.R");
        ragdoll.addBoneName("Chest");
        ragdoll.addBoneName("Foot.L");
        ragdoll.addBoneName("Foot.R");
        ragdoll.addBoneName("Hand.R");
        ragdoll.addBoneName("Hand.L");
        ragdoll.addBoneName("Neck");
        ragdoll.addBoneName("Root");
        ragdoll.addBoneName("Stomach");
        ragdoll.addBoneName("Waist");
        ragdoll.addBoneName("Humerus.L");
        ragdoll.addBoneName("Humerus.R");
        ragdoll.addBoneName("Thigh.L");
        ragdoll.addBoneName("Thigh.R");
        ragdoll.addBoneName("Calf.L");
        ragdoll.addBoneName("Calf.R");
        ragdoll.addBoneName("Clavicle.L");
        ragdoll.addBoneName("Clavicle.R");
    }

    float elTime = 0;

    boolean forward = true;

    AnimControl animControl;

    AnimChannel animChannel;

    Vector3f direction = new Vector3f(0, 0, 1);

    Quaternion rotate = new Quaternion().fromAngleAxis(FastMath.PI / 8, Vector3f.UNIT_Y);

    boolean dance = true;

    @Override
    public void simpleUpdate(float tpf) {
    // System.out.println(((BoundingBox) model.getWorldBound()).getYExtent());
    // elTime += tpf;
    // if (elTime > 3) {
    // elTime = 0;
    // if (dance) {
    // rotate.multLocal(direction);
    // }
    // if (Math.random() > 0.80) {
    // dance = true;
    // animChannel.setAnim("Dance");
    // } else {
    // dance = false;
    // animChannel.setAnim("RunBase");
    // rotate.fromAngleAxis(FastMath.QUARTER_PI * ((float) Math.random() - 0.5f), Vector3f.UNIT_Y);
    // rotate.multLocal(direction);
    // }
    // }
    // if (!ragdoll.hasControl() && !dance) {
    // if (model.getLocalTranslation().getZ() < -10) {
    // direction.z = 1;
    // direction.normalizeLocal();
    // } else if (model.getLocalTranslation().getZ() > 10) {
    // direction.z = -1;
    // direction.normalizeLocal();
    // }
    // if (model.getLocalTranslation().getX() < -10) {
    // direction.x = 1;
    // direction.normalizeLocal();
    // } else if (model.getLocalTranslation().getX() > 10) {
    // direction.x = -1;
    // direction.normalizeLocal();
    // }
    // model.move(direction.multLocal(tpf * 8));
    // direction.normalizeLocal();
    // model.lookAt(model.getLocalTranslation().add(direction), Vector3f.UNIT_Y);
    // }
    }

    public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) {
        // if(channel.getAnimationName().equals("StandUpFront")){
        // channel.setAnim("Dance");
        // }
        if (channel.getAnimationName().equals("StandUpBack") || channel.getAnimationName().equals("StandUpFront")) {
            channel.setLoopMode(LoopMode.DontLoop);
            channel.setAnim("IdleTop", 5);
            channel.setLoopMode(LoopMode.Loop);
        }
    // if(channel.getAnimationName().equals("IdleTop")){
    // channel.setAnim("StandUpFront");
    // }
    }

    public void onAnimChange(AnimControl control, AnimChannel channel, String animName) {
    }
}

19 Source : TestBetterCharacter.java
with Apache License 2.0
from neuroph

/**
 * A walking physical character followed by a 3rd person camera. (No animation.)
 *
 * @author normenhansen, zathras
 */
public clreplaced TestBetterCharacter extends SimpleApplication implements ActionListener {

    private BulletAppState bulletAppState;

    private BetterCharacterControl physicsCharacter;

    private Node characterNode;

    private CameraNode camNode;

    boolean rotate = false;

    private Vector3f walkDirection = new Vector3f(0, 0, 0);

    private Vector3f viewDirection = new Vector3f(0, 0, 1);

    boolean leftStrafe = false, rightStrafe = false, forward = false, backward = false, leftRotate = false, rightRotate = false;

    private Vector3f normalGravity = new Vector3f(0, -9.81f, 0);

    private Geometry planet;

    public static void main(String[] args) {
        TestBetterCharacter app = new TestBetterCharacter();
        AppSettings settings = new AppSettings(true);
        settings.setRenderer(AppSettings.LWJGL_OPENGL2);
        settings.setAudioRenderer(AppSettings.LWJGL_OPENAL);
        app.setSettings(settings);
        app.start();
    }

    @Override
    public void simpleInitApp() {
        // setup keyboard mapping
        setupKeys();
        // activate physics
        bulletAppState = new BulletAppState();
        stateManager.attach(bulletAppState);
        bulletAppState.setDebugEnabled(true);
        // init a physics test scene
        PhysicsTestHelper.createPhysicsTestWorldSoccer(rootNode, replacedetManager, bulletAppState.getPhysicsSpace());
        PhysicsTestHelper.createBallShooter(this, rootNode, bulletAppState.getPhysicsSpace());
        setupPlanet();
        // Create a node for the character model
        characterNode = new Node("character node");
        characterNode.setLocalTranslation(new Vector3f(4, 5, 2));
        // Add a character control to the node so we can add other things and
        // control the model rotation
        physicsCharacter = new BetterCharacterControl(0.3f, 2.5f, 8f);
        characterNode.addControl(physicsCharacter);
        getPhysicsSpace().add(physicsCharacter);
        // Load model, attach to character node
        Node model = (Node) replacedetManager.loadModel("Models/Jaime/Jaime.j3o");
        model.setLocalScale(1.50f);
        characterNode.attachChild(model);
        // Add character node to the rootNode
        rootNode.attachChild(characterNode);
        // Set forward camera node that follows the character, only used when
        // view is "locked"
        camNode = new CameraNode("CamNode", cam);
        camNode.setControlDir(ControlDirection.SpatialToCamera);
        camNode.setLocalTranslation(new Vector3f(0, 2, -6));
        Quaternion quat = new Quaternion();
        // These coordinates are local, the camNode is attached to the character node!
        quat.lookAt(Vector3f.UNIT_Z, Vector3f.UNIT_Y);
        camNode.setLocalRotation(quat);
        characterNode.attachChild(camNode);
        // Disable by default, can be enabled via keyboard shortcut
        camNode.setEnabled(false);
    }

    @Override
    public void simpleUpdate(float tpf) {
        // Apply planet gravity to character if close enough (see below)
        checkPlanetGravity();
        // Get current forward and left vectors of model by using its rotation
        // to rotate the unit vectors
        Vector3f modelForwardDir = characterNode.getWorldRotation().mult(Vector3f.UNIT_Z);
        Vector3f modelLeftDir = characterNode.getWorldRotation().mult(Vector3f.UNIT_X);
        // WalkDirection is global!
        // You *can* make your character fly with this.
        walkDirection.set(0, 0, 0);
        if (leftStrafe) {
            walkDirection.addLocal(modelLeftDir.mult(3));
        } else if (rightStrafe) {
            walkDirection.addLocal(modelLeftDir.negate().multLocal(3));
        }
        if (forward) {
            walkDirection.addLocal(modelForwardDir.mult(3));
        } else if (backward) {
            walkDirection.addLocal(modelForwardDir.negate().multLocal(3));
        }
        physicsCharacter.setWalkDirection(walkDirection);
        // ViewDirection is local to characters physics system!
        // The final world rotation depends on the gravity and on the state of
        // setApplyPhysicsLocal()
        if (leftRotate) {
            Quaternion rotateL = new Quaternion().fromAngleAxis(FastMath.PI * tpf, Vector3f.UNIT_Y);
            rotateL.multLocal(viewDirection);
        } else if (rightRotate) {
            Quaternion rotateR = new Quaternion().fromAngleAxis(-FastMath.PI * tpf, Vector3f.UNIT_Y);
            rotateR.multLocal(viewDirection);
        }
        physicsCharacter.setViewDirection(viewDirection);
        fpsText.setText("Touch da ground = " + physicsCharacter.isOnGround());
        if (!lockView) {
            cam.lookAt(characterNode.getWorldTranslation().add(new Vector3f(0, 2, 0)), Vector3f.UNIT_Y);
        }
    }

    private void setupPlanet() {
        Material material = new Material(replacedetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        material.setTexture("ColorMap", replacedetManager.loadTexture("Interface/Logo/Monkey.jpg"));
        // immovable sphere with mesh collision shape
        Sphere sphere = new Sphere(64, 64, 20);
        planet = new Geometry("Sphere", sphere);
        planet.setMaterial(material);
        planet.setLocalTranslation(30, -15, 30);
        planet.addControl(new RigidBodyControl(new MeshCollisionShape(sphere), 0));
        rootNode.attachChild(planet);
        getPhysicsSpace().add(planet);
    }

    private void checkPlanetGravity() {
        Vector3f planetDist = planet.getWorldTranslation().subtract(characterNode.getWorldTranslation());
        if (planetDist.length() < 24) {
            physicsCharacter.setGravity(planetDist.normalizeLocal().multLocal(9.81f));
        } else {
            physicsCharacter.setGravity(normalGravity);
        }
    }

    private PhysicsSpace getPhysicsSpace() {
        return bulletAppState.getPhysicsSpace();
    }

    public void onAction(String binding, boolean value, float tpf) {
        if (binding.equals("Strafe Left")) {
            if (value) {
                leftStrafe = true;
            } else {
                leftStrafe = false;
            }
        } else if (binding.equals("Strafe Right")) {
            if (value) {
                rightStrafe = true;
            } else {
                rightStrafe = false;
            }
        } else if (binding.equals("Rotate Left")) {
            if (value) {
                leftRotate = true;
            } else {
                leftRotate = false;
            }
        } else if (binding.equals("Rotate Right")) {
            if (value) {
                rightRotate = true;
            } else {
                rightRotate = false;
            }
        } else if (binding.equals("Walk Forward")) {
            if (value) {
                forward = true;
            } else {
                forward = false;
            }
        } else if (binding.equals("Walk Backward")) {
            if (value) {
                backward = true;
            } else {
                backward = false;
            }
        } else if (binding.equals("Jump")) {
            physicsCharacter.jump();
        } else if (binding.equals("Duck")) {
            if (value) {
                physicsCharacter.setDucked(true);
            } else {
                physicsCharacter.setDucked(false);
            }
        } else if (binding.equals("Lock View")) {
            if (value && lockView) {
                lockView = false;
            } else if (value && !lockView) {
                lockView = true;
            }
            flyCam.setEnabled(!lockView);
            camNode.setEnabled(lockView);
        }
    }

    private boolean lockView = false;

    private void setupKeys() {
        inputManager.addMapping("Strafe Left", new KeyTrigger(KeyInput.KEY_U), new KeyTrigger(KeyInput.KEY_Z));
        inputManager.addMapping("Strafe Right", new KeyTrigger(KeyInput.KEY_O), new KeyTrigger(KeyInput.KEY_X));
        inputManager.addMapping("Rotate Left", new KeyTrigger(KeyInput.KEY_J), new KeyTrigger(KeyInput.KEY_LEFT));
        inputManager.addMapping("Rotate Right", new KeyTrigger(KeyInput.KEY_L), new KeyTrigger(KeyInput.KEY_RIGHT));
        inputManager.addMapping("Walk Forward", new KeyTrigger(KeyInput.KEY_I), new KeyTrigger(KeyInput.KEY_UP));
        inputManager.addMapping("Walk Backward", new KeyTrigger(KeyInput.KEY_K), new KeyTrigger(KeyInput.KEY_DOWN));
        inputManager.addMapping("Jump", new KeyTrigger(KeyInput.KEY_F), new KeyTrigger(KeyInput.KEY_SPACE));
        inputManager.addMapping("Duck", new KeyTrigger(KeyInput.KEY_G), new KeyTrigger(KeyInput.KEY_LSHIFT), new KeyTrigger(KeyInput.KEY_RSHIFT));
        inputManager.addMapping("Lock View", new KeyTrigger(KeyInput.KEY_RETURN));
        inputManager.addListener(this, "Strafe Left", "Strafe Right");
        inputManager.addListener(this, "Rotate Left", "Rotate Right");
        inputManager.addListener(this, "Walk Forward", "Walk Backward");
        inputManager.addListener(this, "Jump", "Duck", "Lock View");
    }

    @Override
    public void simpleRender(RenderManager rm) {
    }
}

See More Examples