3D object does not show original colors using obj file in QML

Viewed 487

I am trying to show simple 3D car using following QML:

import QtQuick 2.2 as QQ2
import Qt3D.Core 2.0
import Qt3D.Render 2.0
import Qt3D.Input 2.0
import Qt3D.Extras 2.0

Entity {
    id: sceneRoot

    Camera {
        id: camera
        projectionType: CameraLens.PerspectiveProjection
        fieldOfView: 45
        aspectRatio: 16/9
        nearPlane : 0.1
        farPlane : 500.0
        position: Qt.vector3d( 0.0, 0.0, -40.0 )
        upVector: Qt.vector3d( 0.0, 1.0, 0.0 )
        viewCenter: Qt.vector3d( 0.0, 0.0, 0.0 )
    }

    OrbitCameraController {
        camera: camera
    }

    components: [
        RenderSettings {
            activeFrameGraph: ForwardRenderer {
                clearColor: Qt.rgba(0, 0.5, 1, 1)
                camera: camera
            }
        },
        // Event Source will be set by the Qt3DQuickWindow
        InputSettings { }
    ]
    Mesh{
        id: sphereMesh
        source: "qrc:/../../../../../Desktop/Qt-3d/assets/55z27frcahz4P911GT/Porsche_911_GT2.obj"
    }

    PhongMaterial {
        id : spherematerial
        shininess: 1
    }

    Transform {
        id: sphereTransform
        property real userAngle: 0.0
        scale: sceneRoot.scale
         rotation: fromAxisAndAngle(Qt.vector3d(0, 1, 0), 45)
        matrix: {
            var m = Qt.matrix4x4();
            m.rotate(userAngle, Qt.vector3d(0, 1, 0));
//            m.translate(Qt.vector3d(0, 0, 20));
            return m;
        }
    }

    QQ2.NumberAnimation {
        target: sphereTransform
        property: "userAngle"
        duration: 10000
        from: 0
        to: 360

        loops: QQ2.Animation.Infinite
        running: true
    }

    Entity {
        id: sphereEntity
        
        components: [ sphereMesh, spherematerial, sphereTransform ]
    }
}

However, when exeucuted this code, I can see the 3D car rotating. But it does not contain the original colors from the 3D object. It is showing the default colors for the 3D car. How can I get the original colors?

  1. Do I need to use Texture with the material? If Yes, how to do that?
  2. Do I need to use mtl file in QML? If yes, how to do that

Note that,

  1. I do not want to use Qt Quick 3D module for some reasons.
  2. Also, I not want to use Qt3DStudio
1 Answers

Loading a mesh using Qt3D::QMesh only loads the vertex data (vertices, normals, texture coordinates) but no textures and it doesn't add any Qt3DRender::QMaterials. You're adding a simple Qt3DExtras::QPhongMaterial which simply applies one color to the whole object.

If your object provides per-vertex-color-information you could try Qt3DExtras::QPerVertexColorMaterial.

If it doesn't work try Qt3DRender::QSceneLoader: there you set the URL to the model and it loads everything automatically and tries to apply the correct materials. Create it in place of the QMesh and also add it as a component.

Related