Search in sources :

Example 1 with Material

use of org.rajawali3d.materials.Material in project Rajawali by Rajawali.

the class RajawaliVRExampleRenderer method initScene.

@Override
public void initScene() {
    DirectionalLight light = new DirectionalLight(0.2f, -1f, 0f);
    light.setPower(.7f);
    getCurrentScene().addLight(light);
    light = new DirectionalLight(0.2f, 1f, 0f);
    light.setPower(1f);
    getCurrentScene().addLight(light);
    getCurrentCamera().setFarPlane(1000);
    getCurrentScene().setBackgroundColor(0xdddddd);
    createTerrain();
    try {
        getCurrentScene().setSkybox(R.drawable.posx, R.drawable.negx, R.drawable.posy, R.drawable.negy, R.drawable.posz, R.drawable.negz);
        LoaderAWD loader = new LoaderAWD(getContext().getResources(), getTextureManager(), R.raw.space_cruiser);
        loader.parse();
        Material cruiserMaterial = new Material();
        cruiserMaterial.setDiffuseMethod(new DiffuseMethod.Lambert());
        cruiserMaterial.setColorInfluence(0);
        cruiserMaterial.enableLighting(true);
        cruiserMaterial.addTexture(new Texture("spaceCruiserTex", R.drawable.space_cruiser_4_color_1));
        Object3D spaceCruiser = loader.getParsedObject();
        spaceCruiser.setMaterial(cruiserMaterial);
        spaceCruiser.setZ(-6);
        spaceCruiser.setY(1);
        getCurrentScene().addChild(spaceCruiser);
        spaceCruiser = spaceCruiser.clone(true);
        spaceCruiser.setZ(-12);
        spaceCruiser.setY(-3);
        spaceCruiser.setRotY(180);
        getCurrentScene().addChild(spaceCruiser);
        loader = new LoaderAWD(getContext().getResources(), getTextureManager(), R.raw.dark_fighter);
        loader.parse();
        Material darkFighterMaterial = new Material();
        darkFighterMaterial.setDiffuseMethod(new DiffuseMethod.Lambert());
        darkFighterMaterial.setColorInfluence(0);
        darkFighterMaterial.enableLighting(true);
        darkFighterMaterial.addTexture(new Texture("darkFighterTex", R.drawable.dark_fighter_6_color));
        Object3D darkFighter = loader.getParsedObject();
        darkFighter.setMaterial(darkFighterMaterial);
        darkFighter.setZ(-6);
        getCurrentScene().addChild(darkFighter);
        CatmullRomCurve3D path = new CatmullRomCurve3D();
        path.addPoint(new Vector3(0, -5, -10));
        path.addPoint(new Vector3(10, -5, 0));
        path.addPoint(new Vector3(0, -4, 8));
        path.addPoint(new Vector3(-16, -6, 0));
        path.isClosedCurve(true);
        SplineTranslateAnimation3D anim = new SplineTranslateAnimation3D(path);
        anim.setDurationMilliseconds(44000);
        anim.setRepeatMode(RepeatMode.INFINITE);
        // -- orient to path
        anim.setOrientToPath(true);
        anim.setTransformable3D(darkFighter);
        getCurrentScene().registerAnimation(anim);
        anim.play();
        loader = new LoaderAWD(getContext().getResources(), getTextureManager(), R.raw.capital);
        loader.parse();
        Material capitalMaterial = new Material();
        capitalMaterial.setDiffuseMethod(new DiffuseMethod.Lambert());
        capitalMaterial.setColorInfluence(0);
        capitalMaterial.enableLighting(true);
        capitalMaterial.addTexture(new Texture("capitalTex", R.drawable.hullw));
        capitalMaterial.addTexture(new NormalMapTexture("capitalNormTex", R.drawable.hulln));
        capital = loader.getParsedObject();
        capital.setMaterial(capitalMaterial);
        capital.setScale(18);
        getCurrentScene().addChild(capital);
        path = new CatmullRomCurve3D();
        path.addPoint(new Vector3(0, 13, 34));
        path.addPoint(new Vector3(34, 13, 0));
        path.addPoint(new Vector3(0, 13, -34));
        path.addPoint(new Vector3(-34, 13, 0));
        path.isClosedCurve(true);
        anim = new SplineTranslateAnimation3D(path);
        anim.setDurationMilliseconds(60000);
        anim.setRepeatMode(RepeatMode.INFINITE);
        anim.setOrientToPath(true);
        anim.setTransformable3D(capital);
        getCurrentScene().registerAnimation(anim);
        anim.play();
    } catch (Exception e) {
        e.printStackTrace();
    }
    lookatSphere = new Sphere(1, 12, 12);
    Material sphereMaterial = new Material();
    sphereMaterial.setDiffuseMethod(new DiffuseMethod.Lambert());
    sphereMaterial.enableLighting(true);
    lookatSphere.setMaterial(sphereMaterial);
    lookatSphere.setColor(Color.YELLOW);
    lookatSphere.setPosition(0, 0, -6);
    getCurrentScene().addChild(lookatSphere);
    initAudio();
}
Also used : LoaderAWD(org.rajawali3d.loader.LoaderAWD) Material(org.rajawali3d.materials.Material) Vector3(org.rajawali3d.math.vector.Vector3) NormalMapTexture(org.rajawali3d.materials.textures.NormalMapTexture) Texture(org.rajawali3d.materials.textures.Texture) NormalMapTexture(org.rajawali3d.materials.textures.NormalMapTexture) SplineTranslateAnimation3D(org.rajawali3d.animation.SplineTranslateAnimation3D) TextureException(org.rajawali3d.materials.textures.ATexture.TextureException) Object3D(org.rajawali3d.Object3D) Sphere(org.rajawali3d.primitives.Sphere) CatmullRomCurve3D(org.rajawali3d.curves.CatmullRomCurve3D) DirectionalLight(org.rajawali3d.lights.DirectionalLight) DiffuseMethod(org.rajawali3d.materials.methods.DiffuseMethod)

Example 2 with Material

use of org.rajawali3d.materials.Material in project Rajawali by Rajawali.

the class RajawaliVRExampleRenderer method createTerrain.

public void createTerrain() {
    //
    // -- Load a bitmap that represents the terrain. Its color values will
    //    be used to generate heights.
    //
    Bitmap bmp = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.terrain);
    try {
        SquareTerrain.Parameters terrainParams = SquareTerrain.createParameters(bmp);
        // -- set terrain scale
        terrainParams.setScale(4f, 54f, 4f);
        // -- the number of plane subdivisions
        terrainParams.setDivisions(128);
        // -- the number of times the textures should be repeated
        terrainParams.setTextureMult(4);
        //
        // -- Terrain colors can be set by manually specifying base, middle and
        //    top colors.
        //
        // --  terrainParams.setBasecolor(Color.argb(255, 0, 0, 0));
        //     terrainParams.setMiddleColor(Color.argb(255, 200, 200, 200));
        //     terrainParams.setUpColor(Color.argb(255, 0, 30, 0));
        //
        // -- However, for this example we'll use a bitmap
        //
        terrainParams.setColorMapBitmap(bmp);
        //
        // -- create the terrain
        //
        terrain = TerrainGenerator.createSquareTerrainFromBitmap(terrainParams, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
    //
    // -- The bitmap won't be used anymore, so get rid of it.
    //
    bmp.recycle();
    //
    // -- A normal map material will give the terrain a bit more detail.
    //
    Material material = new Material();
    material.enableLighting(true);
    material.useVertexColors(true);
    material.setDiffuseMethod(new DiffuseMethod.Lambert());
    try {
        Texture groundTexture = new Texture("ground", R.drawable.ground);
        groundTexture.setInfluence(.5f);
        material.addTexture(groundTexture);
        material.addTexture(new NormalMapTexture("groundNormalMap", R.drawable.groundnor));
        material.setColorInfluence(0);
    } catch (TextureException e) {
        e.printStackTrace();
    }
    //
    // -- Blend the texture with the vertex colors
    //
    material.setColorInfluence(.5f);
    terrain.setY(-100);
    terrain.setMaterial(material);
    getCurrentScene().addChild(terrain);
}
Also used : Bitmap(android.graphics.Bitmap) TextureException(org.rajawali3d.materials.textures.ATexture.TextureException) SquareTerrain(org.rajawali3d.terrain.SquareTerrain) DiffuseMethod(org.rajawali3d.materials.methods.DiffuseMethod) Material(org.rajawali3d.materials.Material) NormalMapTexture(org.rajawali3d.materials.textures.NormalMapTexture) Texture(org.rajawali3d.materials.textures.Texture) NormalMapTexture(org.rajawali3d.materials.textures.NormalMapTexture) TextureException(org.rajawali3d.materials.textures.ATexture.TextureException)

Example 3 with Material

use of org.rajawali3d.materials.Material in project Rajawali by Rajawali.

the class LoaderMD2 method parse.

public LoaderMD2 parse() throws ParsingException {
    super.parse();
    BufferedInputStream stream = null;
    if (mFile == null) {
        InputStream fileIn = mResources.openRawResource(mResourceId);
        stream = new BufferedInputStream(fileIn);
    } else {
        try {
            stream = new BufferedInputStream(new FileInputStream(mFile));
        } catch (FileNotFoundException e) {
            RajLog.e("[" + getClass().getCanonicalName() + "] Could not find file.");
            throw new ParsingException(e);
        }
    }
    mObject = new VertexAnimationObject3D();
    mObject.setFps(10);
    mHeader = new MD2Header();
    try {
        mHeader.parse(stream);
        mFrames = new Stack<IAnimationFrame>();
        for (int i = 0; i < mHeader.numFrames; ++i) mFrames.add(new VertexAnimationFrame());
        byte[] bytes = new byte[mHeader.offsetEnd - 68];
        stream.read(bytes);
        getMaterials(stream, bytes);
        float[] texCoords = getTexCoords(stream, bytes);
        getFrames(stream, bytes);
        getTriangles(stream, bytes, texCoords);
        mObject.setFrames(mFrames);
        IAnimationFrame firstFrame = mFrames.get(0);
        Material material = new Material();
        material.enableLighting(true);
        material.setDiffuseMethod(new DiffuseMethod.Lambert());
        material.addPlugin(new VertexAnimationMaterialPlugin());
        mObject.getGeometry().copyFromGeometry3D(firstFrame.getGeometry());
        mObject.setData(firstFrame.getGeometry().getVertexBufferInfo(), firstFrame.getGeometry().getNormalBufferInfo(), mTextureCoords, null, mIndices, false);
        mObject.setMaterial(material);
        mObject.setColor(0xffffffff);
        if (mTexture != null) {
            material.addTexture(new Texture(mCurrentTextureName, mTexture));
            material.setColorInfluence(0);
        }
        stream.close();
    } catch (Exception e) {
        throw new ParsingException(e);
    }
    mObject.isContainer(false);
    mRootObject = mObject;
    return this;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) LittleEndianDataInputStream(org.rajawali3d.util.LittleEndianDataInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IAnimationFrame(org.rajawali3d.animation.mesh.IAnimationFrame) FileNotFoundException(java.io.FileNotFoundException) Material(org.rajawali3d.materials.Material) Texture(org.rajawali3d.materials.textures.Texture) FileInputStream(java.io.FileInputStream) VertexAnimationMaterialPlugin(org.rajawali3d.materials.plugins.VertexAnimationMaterialPlugin) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) BufferedInputStream(java.io.BufferedInputStream) VertexAnimationObject3D(org.rajawali3d.animation.mesh.VertexAnimationObject3D) DiffuseMethod(org.rajawali3d.materials.methods.DiffuseMethod) VertexAnimationFrame(org.rajawali3d.animation.mesh.VertexAnimationFrame)

Example 4 with Material

use of org.rajawali3d.materials.Material in project Rajawali by Rajawali.

the class BlockMeshInstance method parseBlock.

public void parseBlock(AWDLittleEndianDataInputStream dis, BlockHeader blockHeader) throws Exception {
    // Parse scene block
    RajLog.d("Parsing SceneGraph Block at position: " + dis.getPosition());
    mSceneGraphBlock = new SceneGraphBlock();
    mSceneGraphBlock.readGraphData(blockHeader, dis);
    // Block id for geometry
    mGeometryID = dis.readUnsignedInt();
    // Lookup the geometry or create it if it does not exist.
    final BlockHeader geomHeader = blockHeader.blockHeaders.get((short) mGeometryID);
    if (geomHeader == null) {
        mGeometry = new Object3D(mSceneGraphBlock.lookupName);
    } else {
        if (geomHeader.parser == null || !(geomHeader.parser instanceof ABaseObjectBlockParser))
            throw new ParsingException("Invalid block reference.");
        mGeometry = ((ABaseObjectBlockParser) geomHeader.parser).getBaseObject3D().clone(false, true);
        mGeometry.setName(mSceneGraphBlock.lookupName);
    }
    // Apply the materials
    final int materialCount = dis.readUnsignedShort();
    final Material[] materials = new Material[materialCount];
    for (int i = 0; i < materialCount; ++i) {
        final long materialID = dis.readUnsignedInt();
        if (materialID == 0) {
            materials[i] = getDefaultMaterial();
            materials[i].addTexture(getDefaultTexture());
        } else {
            final BlockHeader materialHeader = blockHeader.blockHeaders.get((short) materialID);
            if (materialHeader == null || materialHeader.parser == null || !(materialHeader.parser instanceof ATextureBlockParser))
                throw new ParsingException("Invalid block reference " + materialID);
            materials[i] = ((ATextureBlockParser) materialHeader.parser).getMaterial();
        }
    }
    // mesh instance properties; does it cast a shadow?
    AwdProperties properties = dis.readProperties(EXPECTED_PROPS);
    mCastsShadow = (boolean) properties.get(PROP_CASTS_SHADOW, true);
    final Matrix4 matrix = new Matrix4(mSceneGraphBlock.transformMatrix);
    // Set translation
    mGeometry.setPosition(matrix.getTranslation());
    // Set scale
    final Vector3 scale = matrix.getScaling();
    mGeometry.setScale(scale.y, scale.x, scale.z);
    // Set rotation
    mGeometry.setOrientation(new Quaternion().fromMatrix(matrix));
    int m = 0;
    if (!mGeometry.isContainer())
        mGeometry.setMaterial(materials[m++]);
    for (int i = 0; i < mGeometry.getNumChildren(); i++) mGeometry.getChildAt(i).setMaterial(materials[Math.min(materials.length - 1, m++)]);
    // ignore user properties, skip to end of block
    dis.skip(blockHeader.blockEnd - dis.getPosition());
}
Also used : Quaternion(org.rajawali3d.math.Quaternion) Material(org.rajawali3d.materials.Material) Vector3(org.rajawali3d.math.vector.Vector3) AwdProperties(org.rajawali3d.loader.LoaderAWD.AwdProperties) Matrix4(org.rajawali3d.math.Matrix4) Object3D(org.rajawali3d.Object3D) ParsingException(org.rajawali3d.loader.ParsingException) BlockHeader(org.rajawali3d.loader.LoaderAWD.BlockHeader)

Example 5 with Material

use of org.rajawali3d.materials.Material in project Rajawali by Rajawali.

the class Object3D method render.

/**
	 * Renders the object
	 *
	 * @param camera The camera
	 * @param vpMatrix {@link Matrix4} The view-projection matrix
	 * @param projMatrix {@link Matrix4} The projection matrix
	 * @param vMatrix {@link Matrix4} The view matrix
	 * @param parentMatrix {@link Matrix4} This object's parent matrix
	 * @param sceneMaterial The scene-wide Material to use, if any.
	 */
public void render(Camera camera, final Matrix4 vpMatrix, final Matrix4 projMatrix, final Matrix4 vMatrix, final Matrix4 parentMatrix, Material sceneMaterial) {
    if (isDestroyed() || (!mIsVisible && !mRenderChildrenAsBatch) || isZeroScale()) {
        return;
    }
    if (parentMatrix != null) {
        if (mParentMatrix == null) {
            mParentMatrix = new Matrix4();
        }
        mParentMatrix.setAll(parentMatrix);
    }
    Material material = sceneMaterial == null ? mMaterial : sceneMaterial;
    preRender();
    // -- move view matrix transformation first
    boolean modelMatrixWasRecalculated = onRecalculateModelMatrix(parentMatrix);
    // -- calculate model view matrix;
    mMVMatrix.setAll(vMatrix).multiply(mMMatrix);
    //Create MVP Matrix from View-Projection Matrix
    mMVPMatrix.setAll(vpMatrix).multiply(mMMatrix);
    // Transform the bounding volumes if they exist
    if (mGeometry.hasBoundingBox())
        getBoundingBox().transform(getModelMatrix());
    if (mGeometry.hasBoundingSphere())
        mGeometry.getBoundingSphere().transform(getModelMatrix());
    // only if mFrustrumTest == true it check frustum
    mIsInFrustum = true;
    if (mFrustumTest && mGeometry.hasBoundingBox()) {
        BoundingBox bbox = getBoundingBox();
        if (!camera.getFrustum().boundsInFrustum(bbox)) {
            mIsInFrustum = false;
        }
    }
    if (!mIsContainerOnly && mIsInFrustum) {
        mPMatrix = projMatrix;
        if (mDoubleSided) {
            GLES20.glDisable(GLES20.GL_CULL_FACE);
        } else {
            GLES20.glEnable(GLES20.GL_CULL_FACE);
            if (mBackSided) {
                GLES20.glCullFace(GLES20.GL_FRONT);
            } else {
                GLES20.glCullFace(GLES20.GL_BACK);
                GLES20.glFrontFace(GLES20.GL_CCW);
            }
        }
        if (mEnableBlending) {
            GLES20.glEnable(GLES20.GL_BLEND);
            GLES20.glBlendFunc(mBlendFuncSFactor, mBlendFuncDFactor);
        }
        if (!mEnableDepthTest)
            GLES20.glDisable(GLES20.GL_DEPTH_TEST);
        else {
            GLES20.glEnable(GLES20.GL_DEPTH_TEST);
            GLES20.glDepthFunc(GLES20.GL_LESS);
        }
        GLES20.glDepthMask(mEnableDepthMask);
        if (!mIsPartOfBatch) {
            if (material == null) {
                RajLog.e("[" + this.getClass().getName() + "] This object can't render because there's no material attached to it.");
                /*throw new RuntimeException(
							"This object can't render because there's no material attached to it.");*/
                if (mEnableBlending) {
                    GLES20.glDisable(GLES20.GL_BLEND);
                }
                if (mDoubleSided) {
                    GLES20.glEnable(GLES20.GL_CULL_FACE);
                } else if (mBackSided) {
                    GLES20.glCullFace(GLES20.GL_BACK);
                }
                if (!mEnableDepthTest) {
                    GLES20.glEnable(GLES20.GL_DEPTH_TEST);
                    GLES20.glDepthFunc(GLES20.GL_LESS);
                }
                return;
            }
            material.useProgram();
            setShaderParams(camera);
            material.bindTextures();
            if (mGeometry.hasTextureCoordinates())
                material.setTextureCoords(mGeometry.getTexCoordBufferInfo());
            if (mGeometry.hasNormals())
                material.setNormals(mGeometry.getNormalBufferInfo());
            if (mMaterial.usingVertexColors())
                material.setVertexColors(mGeometry.getColorBufferInfo());
            material.setVertices(mGeometry.getVertexBufferInfo());
        }
        material.setCurrentObject(this);
        if (mOverrideMaterialColor) {
            material.setColor(mColor);
        }
        material.applyParams();
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
        material.setMVPMatrix(mMVPMatrix);
        material.setModelMatrix(mMMatrix);
        material.setModelViewMatrix(mMVMatrix);
        if (mIsVisible) {
            int bufferType = mGeometry.getIndexBufferInfo().bufferType == Geometry3D.BufferType.SHORT_BUFFER ? GLES20.GL_UNSIGNED_SHORT : GLES20.GL_UNSIGNED_INT;
            GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle);
            GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), bufferType, 0);
            GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
        }
        if (!mIsPartOfBatch && !mRenderChildrenAsBatch && sceneMaterial == null) {
            material.unbindTextures();
        }
        material.unsetCurrentObject(this);
        if (mEnableBlending) {
            GLES20.glDisable(GLES20.GL_BLEND);
        }
        if (mDoubleSided) {
            GLES20.glEnable(GLES20.GL_CULL_FACE);
        } else if (mBackSided) {
            GLES20.glCullFace(GLES20.GL_BACK);
        }
        if (!mEnableDepthTest) {
            GLES20.glEnable(GLES20.GL_DEPTH_TEST);
            GLES20.glDepthFunc(GLES20.GL_LESS);
        }
    }
    if (mShowBoundingVolume) {
        if (mGeometry.hasBoundingBox())
            getBoundingBox().drawBoundingVolume(camera, vpMatrix, projMatrix, vMatrix, mMMatrix);
        if (mGeometry.hasBoundingSphere())
            mGeometry.getBoundingSphere().drawBoundingVolume(camera, vpMatrix, projMatrix, vMatrix, mMMatrix);
    }
    // Draw children without frustum test
    for (int i = 0, j = mChildren.size(); i < j; i++) {
        Object3D child = mChildren.get(i);
        if (mRenderChildrenAsBatch || mIsPartOfBatch) {
            child.setPartOfBatch(true);
        }
        if (modelMatrixWasRecalculated)
            child.markModelMatrixDirty();
        child.render(camera, vpMatrix, projMatrix, vMatrix, mMMatrix, sceneMaterial);
    }
    if (mRenderChildrenAsBatch && sceneMaterial == null) {
        material.unbindTextures();
    }
}
Also used : BoundingBox(org.rajawali3d.bounds.BoundingBox) Material(org.rajawali3d.materials.Material) Matrix4(org.rajawali3d.math.Matrix4)

Aggregations

Material (org.rajawali3d.materials.Material)25 Vector3 (org.rajawali3d.math.vector.Vector3)9 DiffuseMethod (org.rajawali3d.materials.methods.DiffuseMethod)7 Texture (org.rajawali3d.materials.textures.Texture)6 TextureException (org.rajawali3d.materials.textures.ATexture.TextureException)5 Object3D (org.rajawali3d.Object3D)4 ShadowMapMaterial (org.rajawali3d.postprocessing.materials.ShadowMapMaterial)4 Cube (org.rajawali3d.primitives.Cube)4 ParsingException (org.rajawali3d.loader.ParsingException)3 NormalMapTexture (org.rajawali3d.materials.textures.NormalMapTexture)3 DirectionalLight (org.rajawali3d.lights.DirectionalLight)2 AwdProperties (org.rajawali3d.loader.LoaderAWD.AwdProperties)2 SpecularMethod (org.rajawali3d.materials.methods.SpecularMethod)2 ATexture (org.rajawali3d.materials.textures.ATexture)2 CubeMapTexture (org.rajawali3d.materials.textures.CubeMapTexture)2 Matrix4 (org.rajawali3d.math.Matrix4)2 ScreenQuad (org.rajawali3d.primitives.ScreenQuad)2 Sphere (org.rajawali3d.primitives.Sphere)2 AFrameTask (org.rajawali3d.renderer.AFrameTask)2 RenderTarget (org.rajawali3d.renderer.RenderTarget)2