com.jme3.math.Vector2f Java Examples

The following examples show how to use com.jme3.math.Vector2f. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TerrainTestModifyHeight.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void simpleUpdate(float tpf){
    Vector3f intersection = getWorldIntersection();
    updateHintText(intersection);
    
    if (raiseTerrain){
        
        if (intersection != null) {
            adjustHeight(intersection, 64, tpf * 60);
        }
    }else if (lowerTerrain){
        if (intersection != null) {
            adjustHeight(intersection, 64, -tpf * 60);
        }
    }
    
    if (terrain != null && intersection != null) {
        float h = terrain.getHeight(new Vector2f(intersection.x, intersection.z));
        Vector3f tl = terrain.getWorldTranslation();
        marker.setLocalTranslation(tl.add(new Vector3f(intersection.x, h, intersection.z)) );
        markerNormal.setLocalTranslation(tl.add(new Vector3f(intersection.x, h, intersection.z)) );
        
        Vector3f normal = terrain.getNormal(new Vector2f(intersection.x, intersection.z));
        ((Arrow)markerNormal.getMesh()).setArrowExtent(normal);
    }
}
 
Example #2
Source File: IosTouchHandler.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void actionDown(int pointerId, long time, float x, float y) {
    logger.log(Level.FINE, "Inject input pointer: {0}, time: {1}, x: {2}, y: {3}", 
            new Object[]{pointerId, time, x, y});
    float jmeX = iosInput.getJmeX(x);
    float jmeY = iosInput.invertY(iosInput.getJmeY(y));
    TouchEvent touch = iosInput.getFreeTouchEvent();
    touch.set(TouchEvent.Type.DOWN, jmeX, jmeY, 0, 0);
    touch.setPointerId(pointerId);//TODO: pointer ID
    touch.setTime(time);
    touch.setPressure(1.0f);
    //touch.setPressure(event.getPressure(pointerIndex)); //TODO: preassure

    lastPositions.put(pointerId, new Vector2f(jmeX, jmeY));

    processEvent(touch);
}
 
Example #3
Source File: ChangeHeightTerrainToolControl.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Notify about changing height by the point in the terrain.
 *
 * @param terrain the terrain.
 * @param point   the point.
 */
@JmeThread
protected void change(@NotNull final Terrain terrain, @NotNull final Vector2f point) {

    final Node terrainNode = (Node) terrain;
    final Vector3f scale = terrainNode.getWorldScale();

    final int halfSize = terrain.getTerrainSize() / 2;
    final int x = Math.round((point.x / scale.x) + halfSize);
    final int z = Math.round((point.y / scale.z) + halfSize);

    final HeightPoint heightPoint = new HeightPoint(point.getX(), point.getY(), x, z);

    final ObjectDictionary<Terrain, ObjectDictionary<HeightPoint, Float>> originalHeight = getOriginalHeight();
    final ObjectDictionary<HeightPoint, Float> terrainHeights = originalHeight.get(terrain, DICTIONARY_FACTORY);
    if (terrainHeights.containsKey(heightPoint)) {
        return;
    }

    final float height = terrain.getHeightmapHeight(point);
    terrainHeights.put(heightPoint, height);
}
 
Example #4
Source File: SimplePlayerAttackBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void onAction(String name, boolean isPressed, float tpf) {
    operation = name;
    if (isPressed) {
        supportedOperations.get(operation).setEnabled(true);
        Vector2f click2d = MonkeyBrainsAppState.getInstance().getApp().getInputManager().getCursorPosition();
        Vector3f click3d = agent.getCamera().getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0f).clone();
        Vector3f dir = agent.getCamera().getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 1f).subtractLocal(click3d).normalizeLocal();
        Ray ray = new Ray(click3d, dir);
        Plane ground = new Plane(Vector3f.UNIT_Y, 0);
        Vector3f groundpoint = new Vector3f();
        ray.intersectsWherePlane(ground, groundpoint);
        ((SimpleAttackBehavior) supportedOperations.get(operation)).setTarget(groundpoint);
    } else {
        operation = null;
    }
}
 
Example #5
Source File: EditorUtil.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Get the angle between these points.
 *
 * @param center the center.
 * @param first  the first point.
 * @param second the second point.
 * @return the angle between these points.
 */
@FromAnyThread
public static float getAngle(
        @NotNull Vector2f center,
        @NotNull Vector2f first,
        @NotNull Vector2f second
) {

    var x = center.getX();
    var y = center.getY();

    var ax = first.getX() - x;
    var ay = first.getY() - y;
    var bx = second.getX() - x;
    var by = second.getY() - y;

    var delta = (float) ((ax * bx + ay * by) / Math.sqrt((ax * ax + ay * ay) * (bx * bx + by * by)));

    if (delta > 1.0) {
        return 0.0F;
    } else if (delta < -1.0) {
        return 180.0F;
    }

    return (float) toDegrees(acos(delta));
}
 
Example #6
Source File: TestParallax.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void setupFloor() {
    mat = assetManager.loadMaterial("Textures/Terrain/BrickWall/BrickWall2.j3m");
    mat.getTextureParam("DiffuseMap").getTextureValue().setWrap(WrapMode.Repeat);
    mat.getTextureParam("NormalMap").getTextureValue().setWrap(WrapMode.Repeat);
    mat.setFloat("Shininess", 0);

    Node floorGeom = (Node) assetManager.loadAsset("Models/WaterTest/WaterTest.mesh.xml");
    Geometry g = ((Geometry) floorGeom.getChild(0));
    g.getMesh().scaleTextureCoordinates(new Vector2f(10, 10));
    TangentBinormalGenerator.generate(floorGeom);
    floorGeom.setLocalTranslation(0, 22, 0);
    floorGeom.setLocalScale(100);

    floorGeom.setMaterial(mat);        
    rootNode.attachChild(floorGeom);
}
 
Example #7
Source File: TestWriteToTexture.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void initOpenCL1() {
    clContext = context.getOpenCLContext();
    clQueue = clContext.createQueue().register();
    programCache = new ProgramCache(clContext);
    //create kernel
    String cacheID = getClass().getName()+".Julia";
    Program program = programCache.loadFromCache(cacheID);
    if (program == null) {
        LOG.info("Program not loaded from cache, create from sources instead");
        program = clContext.createProgramFromSourceFiles(assetManager, "jme3test/opencl/JuliaSet.cl");
        program.build();
        programCache.saveToCache(cacheID, program);
    }
    program.register();
    kernel = program.createKernel("JuliaSet").register();
    C = new Vector2f(0.12f, -0.2f);
}
 
Example #8
Source File: BufferUtils.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Generate a new FloatBuffer using the given array of Vector2f objects.
 * The FloatBuffer will be 2 * data.length long and contain the vector data
 * as data[0].x, data[0].y, data[1].x... etc.
 *
 * @param data array of Vector2f objects to place into a new FloatBuffer
 */
public static FloatBuffer createFloatBuffer(Vector2f... data) {
    if (data == null) {
        return null;
    }
    FloatBuffer buff = createFloatBuffer(2 * data.length);
    for (int x = 0; x < data.length; x++) {
        if (data[x] != null) {
            buff.put(data[x].x).put(data[x].y);
        } else {
            buff.put(0).put(0);
        }
    }
    buff.flip();
    return buff;
}
 
Example #9
Source File: TerrainCameraController.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Find where on the terrain the mouse intersects.
 */
protected Vector3f getTerrainCollisionPoint() {

    if (editorController.getTerrain(null) == null) {
        return null;
    }

    CollisionResults results = new CollisionResults();
    Ray ray = new Ray();
    Vector3f pos = cam.getWorldCoordinates(new Vector2f(mouseX, mouseY), 0).clone();
    Vector3f dir = cam.getWorldCoordinates(new Vector2f(mouseX, mouseY), 0.3f).clone();
    dir.subtractLocal(pos).normalizeLocal();
    ray.setOrigin(pos);
    ray.setDirection(dir);
    editorController.getTerrain(null).collideWith(ray, results);
    if (results == null) {
        return null;
    }
    final CollisionResult result = results.getClosestCollision();
    if (result == null) {
        return null;
    }
    return result.getContactPoint();
}
 
Example #10
Source File: OptionPanelState.java    From Lemur with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 *  Modally shows the specified OptionPanel in the guiNode as defined by
 *  getGuiNode().  An invisible blocker geometry is placed behind it
 *  to catch all mouse events until the panel is closed.  The option 
 *  panel will be visible until the user clicks a response or until 
 *  close() is called. 
 */
public void show( OptionPanel panel ) {
    if( this.current != null ) {
        current.close();
    }
    
    this.current = panel;
 
    Vector2f screen = getState(PopupState.class).getGuiSize();
    Vector3f pref = current.getPreferredSize();
    
    Vector3f pos = new Vector3f(screen.x, screen.y, 0).multLocal(0.5f);
    pos.x -= pref.x * 0.5f;
    pos.y += pref.y * 0.5f;
    current.setLocalTranslation(pos);
    
    getState(PopupState.class).showModalPopup(current);
}
 
Example #11
Source File: Slider.java    From Lemur with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void cursorButtonEvent( CursorButtonEvent event, Spatial target, Spatial capture ) {
    if( event.getButtonIndex() != MouseInput.BUTTON_LEFT )
        return;

    //if( capture != null && capture != target )
    //    return;

    event.setConsumed();
    if( event.isPressed() ) {
        drag = new Vector2f(event.getX(), event.getY());
        startPercent = model.getPercent();
    } else {
        // Dragging is done.
        drag = null;
    }
}
 
Example #12
Source File: TerrainQuad.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected TerrainQuad(String name, int patchSize, int quadSize,
                        Vector3f scale, float[] heightMap, int totalSize,
                        Vector2f offset, float offsetAmount)
{
    super(name);
    
    if (heightMap == null)
        heightMap = generateDefaultHeightMap(quadSize);
    
    if (!FastMath.isPowerOfTwo(quadSize - 1)) {
        throw new RuntimeException("size given: " + quadSize + "  Terrain quad sizes may only be (2^N + 1)");
    }
    if (FastMath.sqrt(heightMap.length) > quadSize) {
        Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Heightmap size is larger than the terrain size. Make sure your heightmap image is the same size as the terrain!");
    }
    
    this.offset = offset;
    this.offsetAmount = offsetAmount;
    this.totalSize = totalSize;
    this.size = quadSize;
    this.patchSize = patchSize;
    this.stepScale = scale;
    split(patchSize, heightMap);
}
 
Example #13
Source File: LODGeomap.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get the triangle that the point is on.
 * 
 * @param x coordinate in local space to the geomap
 * @param z coordinate in local space to the geomap
 * @return triangle in local space to the geomap
 */
protected Triangle getTriangleAtPoint(float x, float z) {
    Triangle[] triangles = getGridTrianglesAtPoint(x, z);
    if (triangles == null) {
        //System.out.println("x,z: " + x + "," + z);
        return null;
    }
    Vector2f point = new Vector2f(x, z);
    Vector2f t1 = new Vector2f(triangles[0].get1().x, triangles[0].get1().z);
    Vector2f t2 = new Vector2f(triangles[0].get2().x, triangles[0].get2().z);
    Vector2f t3 = new Vector2f(triangles[0].get3().x, triangles[0].get3().z);

    if (0 != FastMath.pointInsideTriangle(t1, t2, t3, point)) {
        return triangles[0];
    }

    t1.set(triangles[1].get1().x, triangles[1].get1().z);
    t1.set(triangles[1].get2().x, triangles[1].get2().z);
    t1.set(triangles[1].get3().x, triangles[1].get3().z);

    if (0 != FastMath.pointInsideTriangle(t1, t2, t3, point)) {
        return triangles[1];
    }

    return null;
}
 
Example #14
Source File: OBJLoader.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected Vector2f readVector2(){
        Vector2f v = new Vector2f();

        String line = scan.nextLine().trim();
        String[] split = line.split(" ");
        v.setX( Float.parseFloat(split[0]) );
        v.setY( Float.parseFloat(split[1]) );

//        v.setX(scan.nextFloat());
//        if (scan.hasNextFloat()){
//            v.setY(scan.nextFloat());
//            if (scan.hasNextFloat()){
//                scan.nextFloat(); // ignore
//            }
//        }

        return v;
    }
 
Example #15
Source File: TerrainQuad.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void setHeight(List<Vector2f> xz, List<Float> height, boolean overrideHeight) {
    if (xz.size() != height.size())
        throw new IllegalArgumentException("Both lists must be the same length!");

    int halfSize = totalSize / 2;

    List<LocationHeight> locations = new ArrayList<LocationHeight>();

    // offset
    for (int i=0; i<xz.size(); i++) {
        int x = Math.round((xz.get(i).x / getWorldScale().x) + halfSize);
        int z = Math.round((xz.get(i).y / getWorldScale().z) + halfSize);
        if (!isInside(x, z))
            continue;
        locations.add(new LocationHeight(x,z,height.get(i)));
    }

    setHeight(locations, overrideHeight); // adjust height of the actual mesh

    // signal that the normals need updating
    for (int i=0; i<xz.size(); i++)
        setNormalRecalcNeeded(xz.get(i) );
}
 
Example #16
Source File: Vector2fPropertyEditor.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void setAsText(String text) throws IllegalArgumentException {
    text = text.replace('[', ' ');
    text = text.replace(']', ' ');
    String[] values = text.split(",");
    if (values.length != 2) {
        throw (new IllegalArgumentException("String not correct"));
    }
    float[] floats = new float[2];
    for (int i = 0; i < values.length; i++) {
        String string = values[i];
        floats[i] = Float.parseFloat(string);
    }
    Vector2f old = new Vector2f();
    old.set(vector);
    vector.set(floats[0], floats[1]);
    notifyListeners(old, vector);
}
 
Example #17
Source File: CartoonSSAO.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void initFilter(AssetManager manager, RenderManager renderManager, ViewPort vp, int w, int h) {
    this.renderManager = renderManager;
    this.viewPort = vp;

    int screenWidth = Math.round(w / downsample);
    int screenHeight = Math.round(h / downsample);

    normalPass = new Pass();
    normalPass.init(renderManager.getRenderer(), screenWidth, screenHeight, Format.RGBA8, Format.Depth);

    frustumNearFar = new Vector2f();

    float farY = (vp.getCamera().getFrustumTop() / vp.getCamera().getFrustumNear()) * vp.getCamera().getFrustumFar();
    float farX = farY * (screenWidth / (float) screenHeight);
    frustumCorner = new Vector3f(farX, farY, vp.getCamera().getFrustumFar());
    frustumNearFar.x = vp.getCamera().getFrustumNear();
    frustumNearFar.y = vp.getCamera().getFrustumFar();

    //ssao Pass
    material = new Material(manager, "Common/MatDefs/VR/CartoonSSAO.j3md");
    material.setTexture("Normals", normalPass.getRenderedTexture());        

    material.setVector3("FrustumCorner", frustumCorner);
    material.setVector2("FrustumNearFar", frustumNearFar);
    material.setFloat("Distance", applyDistance);
    if( useOutline == false ) material.setBoolean("disableOutline", true);
    if( instancedRendering ) material.setBoolean("useInstancing", true);
}
 
Example #18
Source File: PaintTerrainToolControl.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Paint texture.
 *
 * @param input the editing input.
 * @param contactPoint the contact point.
 */
@JmeThread
private void paintTexture(@NotNull final PaintingInput input, @NotNull final Vector3f contactPoint) {

    final Texture alphaTexture = getAlphaTexture();
    if (alphaTexture == null) {
        return;
    }

    final LocalObjects local = getLocalObjects();
    final Spatial terrainNode = notNull(getPaintedModel());
    final Terrain terrain = (Terrain) terrainNode;
    final Image image = alphaTexture.getImage();

    final Vector3f worldTranslation = terrainNode.getWorldTranslation();
    final Vector3f localPoint = contactPoint.subtract(worldTranslation, local.nextVector());
    final Vector3f localScale = terrainNode.getLocalScale();
    final Vector2f uv = getPointPercentagePosition(terrain, localPoint, localScale, local.nextVector2f());
    final Vector2f temp = local.nextVector2f();
    final ColorRGBA color = local.nextColor();

    final int layer = getLayer();

    // get the radius of the brush in pixel-percent
    float brushSize = getBrushSize() / (terrain.getTerrainSize() * localScale.getX());
    float brushPower = getBrushPower();

    if (input == PaintingInput.MOUSE_SECONDARY) {
        brushPower *= -1;
    }

    // selectedTextureIndex/4 is an int floor, do not simplify the equation
    final ObjectFloatObjectConsumer<ColorRGBA, Boolean> colorFunction = COLOR_FUNCTIONS[layer - ((layer / 4) * 4)];

    doPaintAction(colorFunction, image, uv, temp, color, brushSize, false, brushPower);

    image.setUpdateNeeded();
}
 
Example #19
Source File: TriangulatedTexture.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * This method triangulates the given flat texture. The given texture is not
 * changed.
 * 
 * @param texture2d
 *            the texture to be triangulated
 * @param uvs
 *            the UV coordinates for each face
 */
public TriangulatedTexture(Texture2D texture2d, List<Vector2f> uvs, BlenderContext blenderContext) {
    maxTextureSize = blenderContext.getBlenderKey().getMaxTextureSize();
    faceTextures = new TreeSet<TriangleTextureElement>(new Comparator<TriangleTextureElement>() {
        public int compare(TriangleTextureElement o1, TriangleTextureElement o2) {
            return o1.faceIndex - o2.faceIndex;
        }
    });
    int facesCount = uvs.size() / 3;
    for (int i = 0; i < facesCount; ++i) {
        faceTextures.add(new TriangleTextureElement(i, texture2d.getImage(), uvs, true, blenderContext));
    }
    this.format = texture2d.getImage().getFormat();
}
 
Example #20
Source File: ComposerCameraController.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void checkDragged(int button, boolean pressed) {
    if (button == 0) {
        toolController.doEditToolDraggedPrimary(new Vector2f(mouseX, mouseY), pressed, cam);
    } else if (button == 1) {
        toolController.doEditToolDraggedSecondary(new Vector2f(mouseX, mouseY), pressed, cam);
    }
}
 
Example #21
Source File: TangentBinormalGenerator.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void generate(Mesh mesh, boolean approxTangents, boolean splitMirrored) {        
    int[] index = new int[3];
    Vector3f[] v = new Vector3f[3];
    Vector2f[] t = new Vector2f[3];
    for (int i = 0; i < 3; i++) {
        v[i] = new Vector3f();
        t[i] = new Vector2f();
    }
    
    if (mesh.getBuffer(Type.Normal) == null) {
        throw new IllegalArgumentException("The given mesh has no normal data!");
    }
    
     List<VertexData> vertices;
    switch (mesh.getMode()) {
        case Triangles:
            vertices = processTriangles(mesh, index, v, t, splitMirrored);
            if(splitMirrored){
                splitVertices(mesh, vertices, splitMirrored);
            }
            break;
        case TriangleStrip:
            vertices = processTriangleStrip(mesh, index, v, t);
            break;
        case TriangleFan:
            vertices = processTriangleFan(mesh, index, v, t);
            break;
        default:
            throw new UnsupportedOperationException(
                    mesh.getMode() + " is not supported.");
    }
    
    processTriangleData(mesh, vertices, approxTangents,splitMirrored);

    //if the mesh has a bind pose, we need to generate the bind pose for the tangent buffer
    TangentUtils.generateBindPoseTangentsIfNecessary(mesh);
}
 
Example #22
Source File: TerrainTestModifyHeight.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void adjustHeight(Vector3f loc, float radius, float height) {

        // offset it by radius because in the loop we iterate through 2 radii
        int radiusStepsX = (int) (radius / terrain.getLocalScale().x);
        int radiusStepsZ = (int) (radius / terrain.getLocalScale().z);

        float xStepAmount = terrain.getLocalScale().x;
        float zStepAmount = terrain.getLocalScale().z;
        long start = System.currentTimeMillis();
        List<Vector2f> locs = new ArrayList<Vector2f>();
        List<Float> heights = new ArrayList<Float>();
        
        for (int z = -radiusStepsZ; z < radiusStepsZ; z++) {
            for (int x = -radiusStepsX; x < radiusStepsX; x++) {

                float locX = loc.x + (x * xStepAmount);
                float locZ = loc.z + (z * zStepAmount);

                if (isInRadius(locX - loc.x, locZ - loc.z, radius)) {
                    // see if it is in the radius of the tool
                    float h = calculateHeight(radius, height, locX - loc.x, locZ - loc.z);
                    locs.add(new Vector2f(locX, locZ));
                    heights.add(h);
                }
            }
        }

        terrain.adjustHeight(locs, heights);
        //System.out.println("Modified "+locs.size()+" points, took: " + (System.currentTimeMillis() - start)+" ms");
        terrain.updateModelBound();
    }
 
Example #23
Source File: TerrainQuad.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the interpolated height of the terrain at the specified point.
 * @param xz the location to get the height for
 * @return Float.NAN if the value does not exist, or the coordinates are outside of the terrain
 */
@Override
public float getHeight(Vector2f xz) {
    // offset
    float x = ((xz.x - getWorldTranslation().x) / getWorldScale().x) + (totalSize-1) / 2f;
    float z = ((xz.y - getWorldTranslation().z) / getWorldScale().z) + (totalSize-1) / 2f;
    if (!isInside((int)x, (int)z))
        return Float.NaN;
    float height = getHeight((int)x, (int)z, (x%1f), (z%1f));
    height *= getWorldScale().y;
    return height;
}
 
Example #24
Source File: TriangulatedTexture.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * This method alters the images to fit them into UV coordinates of the
 * given target texture.
 * 
 * @param targetTexture
 *            the texture to whose UV coordinates we fit current images
 * @param blenderContext
 *            the blender context
 */
public void castToUVS(TriangulatedTexture targetTexture, BlenderContext blenderContext) {
    int[] sourceSize = new int[2], targetSize = new int[2];
    ImageLoader imageLoader = new ImageLoader();
    TextureHelper textureHelper = blenderContext.getHelper(TextureHelper.class);
    for (TriangleTextureElement entry : faceTextures) {
        TriangleTextureElement targetFaceTextureElement = targetTexture.getFaceTextureElement(entry.faceIndex);
        Vector2f[] dest = targetFaceTextureElement.uv;

        // get the sizes of the source and target images
        sourceSize[0] = entry.image.getWidth();
        sourceSize[1] = entry.image.getHeight();
        targetSize[0] = targetFaceTextureElement.image.getWidth();
        targetSize[1] = targetFaceTextureElement.image.getHeight();

        // create triangle transformation
        AffineTransform affineTransform = textureHelper.createAffineTransform(entry.uv, dest, sourceSize, targetSize);

        // compute the result texture
        BufferedImage sourceImage = ImageToAwt.convert(entry.image, false, true, 0);

        BufferedImage targetImage = new BufferedImage(targetSize[0], targetSize[1], sourceImage.getType());
        Graphics2D g = targetImage.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(sourceImage, affineTransform, null);
        g.dispose();

        Image output = imageLoader.load(targetImage, false);
        entry.image = output;
        entry.uv[0].set(dest[0]);
        entry.uv[1].set(dest[1]);
        entry.uv[2].set(dest[2]);
    }
}
 
Example #25
Source File: SceneEditTool.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private CollisionResult pick(Camera cam, Vector2f mouseLoc, Node node) {
    CollisionResults results = new CollisionResults();
    Ray ray = new Ray();
    Vector3f pos = cam.getWorldCoordinates(mouseLoc, 0).clone();
    Vector3f dir = cam.getWorldCoordinates(mouseLoc, 0.1f).clone();
    dir.subtractLocal(pos).normalizeLocal();
    ray.setOrigin(pos);
    ray.setDirection(dir);
    node.collideWith(ray, results);
    CollisionResult result = results.getClosestCollision();
    return result;
}
 
Example #26
Source File: TerrainGrid.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void adjustHeight(List<Vector2f> xz, List<Float> height) {
    Vector3f currentGridLocation = getCurrentCell().mult(getLocalScale()).multLocal(quadSize - 1);
    for (Vector2f vect : xz) {
        vect.x -= currentGridLocation.x;
        vect.y -= currentGridLocation.z;
    }
    super.adjustHeight(xz, height);
}
 
Example #27
Source File: MoveTool.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) {
    if (!pressed) {
        setDefaultAxisMarkerColors();
        pickedPlane = null; // mouse released, reset selection
        offset = null;
        if (wasDragging) {
            actionPerformed(new MoveUndo(toolController.getSelectedSpatial(), startLoc, lastLoc));
            wasDragging = false;
        }
    }
}
 
Example #28
Source File: TerrainTestModifyHeight.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private float calculateHeight(float radius, float heightFactor, float x, float z) {
    // find percentage for each 'unit' in radius
    Vector2f point = new Vector2f(x, z);
    float val = point.length() / radius;
    val = 1 - val;
    if (val <= 0) {
        val = 0;
    }
    return heightFactor * val;
}
 
Example #29
Source File: HDRRenderer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Material createLumShader(int srcW, int srcH, int bufW, int bufH, int mode,
                            int iters, Texture tex){
    Material mat = new Material(manager, "Common/MatDefs/Hdr/LogLum.j3md");
    
    Vector2f blockSize = new Vector2f(1f / bufW, 1f / bufH);
    Vector2f pixelSize = new Vector2f(1f / srcW, 1f / srcH);
    Vector2f blocks = new Vector2f();
    float numPixels = Float.POSITIVE_INFINITY;
    if (iters != -1){
        do {
            pixelSize.multLocal(2);
            blocks.set(blockSize.x / pixelSize.x,
                       blockSize.y / pixelSize.y);
            numPixels = blocks.x * blocks.y;
        } while (numPixels > iters);
    }else{
        blocks.set(blockSize.x / pixelSize.x,
                   blockSize.y / pixelSize.y);
        numPixels = blocks.x * blocks.y;
    }

    mat.setBoolean("Blocks", true);
    if (mode == LUMMODE_ENCODE_LUM)
        mat.setBoolean("EncodeLum", true);
    else if (mode == LUMMODE_DECODE_LUM)
        mat.setBoolean("DecodeLum", true);

    mat.setTexture("Texture", tex);
    mat.setVector2("BlockSize", blockSize);
    mat.setVector2("PixelSize", pixelSize);
    mat.setFloat("NumPixels", numPixels);

    return mat;
}
 
Example #30
Source File: SilentTangentBinormalGenerator.java    From OpenRTS with MIT License 5 votes vote down vote up
private static List<VertexData> processTriangles(Mesh mesh, int[] index, Vector3f[] v, Vector2f[] t, boolean splitMirrored) {
	IndexBuffer indexBuffer = mesh.getIndexBuffer();
	FloatBuffer vertexBuffer = (FloatBuffer) mesh.getBuffer(Type.Position).getData();
	if (mesh.getBuffer(Type.TexCoord) == null) {
		throw new IllegalArgumentException("Can only generate tangents for " + "meshes with texture coordinates");
	}

	FloatBuffer textureBuffer = (FloatBuffer) mesh.getBuffer(Type.TexCoord).getData();

	List<VertexData> vertices = initVertexData(vertexBuffer.limit() / 3);

	for (int i = 0; i < indexBuffer.size() / 3; i++) {
		for (int j = 0; j < 3; j++) {
			index[j] = indexBuffer.get(i * 3 + j);
			populateFromBuffer(v[j], vertexBuffer, index[j]);
			populateFromBuffer(t[j], textureBuffer, index[j]);
		}

		TriangleData triData = processTriangle(index, v, t);
		if (splitMirrored) {
			triData.setIndex(index);
			triData.triangleOffset = i * 3;
		}
		if (triData != null) {
			vertices.get(index[0]).triangles.add(triData);
			vertices.get(index[1]).triangles.add(triData);
			vertices.get(index[2]).triangles.add(triData);
		}
	}

	return vertices;
}