【Filament】自定义Blinn Phong光照模型

news2024/11/16 3:44:54

1 前言

        光照元素主要有环境光(ambient)、漫反射光(diffuse)、镜面反射光(specular),基础的光照模型主要有兰伯特(Lambert)光照模型、冯氏(Phong)光照模型和改进的冯氏(Blinn Phong)光照模型。

        Lambert 光照模型只包含漫反射光的计算,Phong 光照模型和 Blinn Phong 光照模型都包含环境光、漫反射光、镜面反射光的计算,两者的区别在与镜面反射光的计算,Phong 光照模型根据反向量和观察向量计算镜面反射光,Blinn Phong 光照模型根据半向量和法向量计算镜面反射光。

        Blinn Phong 光照模型中环境光、漫反射光、镜面反射光的计算如下。

vec3 ambientColor() { // 环境光
	vec3 ambient = materialParams.ambientColor * materialParams.albedo;
	return ambient;
}

vec3 diffuseColor(vec3 normal, vec3 lightDir) { // 漫反射光
	float factor = max(dot(normal, lightDir), 0.0);
	vec3 diffuse = factor * materialParams.lightColor * materialParams.albedo;
	return diffuse;
}

vec3 specularColor(vec3 normal, vec3 lightDir, vec3 viewDire) { // 镜面反射光
	vec3 halfVec = normalize(lightDir + viewDire); // 半向量
	float factor = pow(max(dot(normal, halfVec), 0.0), materialParams.gloss);
	vec3 specular = factor * materialParams.lightColor * materialParams.specularStrength;
	return specular;
}

        最终的渲染颜色由以上三种光的颜色叠加而成,如下。

material.baseColor = vec4(ambient + diffuse + specular, 1);

2 自定义光照

        本文项目结构如下,完整代码资源 → Filament自定义Blinn Phong光照模型。

2.1 基础类

        为方便读者将注意力聚焦在 Filament 的输入上,轻松配置复杂的环境依赖逻辑,笔者仿照 OpenGL ES 的写法,抽出了 FLSurfaceView、BaseModel、Mesh、MaterialUtils 和 MeshUtils 类。FLSurfaceView 与 GLSurfaceView 的功能类似,承载了渲染环境配置;BaseModel 用于管理模型的网格和材质;Mesh 用于管理模型的顶点属性;MaterialUtils 和 MeshUtils 中分别提供了一些材质和网格相关的工具。

        build.gradle

...
android {
    ...
    aaptOptions { // 在应用程序打包过程中不压缩的文件
        noCompress 'filamat', 'ktx'
    }
}
 
dependencies {
    implementation fileTree(dir: '../libs', include: ['*.aar'])
    ...
}

        说明:在项目根目录下的 libs 目录中,需要放入以下 aar 文件,它们源自Filament环境搭建中编译生成的 aar。

        FLSurfaceView.java

package com.zhyan8.customlight.filament.base;

import android.content.Context;
import android.graphics.Point;
import android.view.Choreographer;
import android.view.Surface;
import android.view.SurfaceView;

import com.google.android.filament.Camera;
import com.google.android.filament.Engine;
import com.google.android.filament.EntityManager;
import com.google.android.filament.Filament;
import com.google.android.filament.Renderer;
import com.google.android.filament.Scene;
import com.google.android.filament.Skybox;
import com.google.android.filament.SwapChain;
import com.google.android.filament.View;
import com.google.android.filament.Viewport;
import com.google.android.filament.android.DisplayHelper;
import com.google.android.filament.android.FilamentHelper;
import com.google.android.filament.android.UiHelper;

import java.util.ArrayList;

/**
 * Filament中待渲染的SurfaceView
 * 功能可以类比OpenGL ES中的GLSurfaceView
 * 用于创建Filament的渲染环境
 */
public class FLSurfaceView extends SurfaceView {
    public static int RENDERMODE_WHEN_DIRTY = 0; // 用户请求渲染才渲染一帧
    public static int RENDERMODE_CONTINUOUSLY = 1; // 持续渲染
    protected int mRenderMode = RENDERMODE_CONTINUOUSLY; // 渲染模式
    protected Choreographer mChoreographer; // 消息控制
    protected DisplayHelper mDisplayHelper; // 管理Display(可以监听分辨率或刷新率的变化)
    protected UiHelper mUiHelper; // 管理SurfaceView、TextureView、SurfaceHolder
    protected Engine mEngine; // 引擎(跟踪用户创建的资源, 管理渲染线程和硬件渲染器)
    protected Renderer mRenderer; // 渲染器(用于操作系统窗口, 生成绘制命令, 管理帧延时)
    protected Scene mScene; // 场景(管理渲染对象、灯光)
    protected View mView; // 存储渲染数据(View是Renderer操作的对象)
    protected Camera mCamera; // 相机(视角管理)
    protected Point mDesiredSize; // 渲染分辨率
    protected float[] mSkyboxColor; // 背景颜色
    protected SwapChain mSwapChain; // 操作系统的本地可渲染表面(native renderable surface, 通常是一个window或view)
    protected FrameCallback mFrameCallback = new FrameCallback(); // 帧回调
    protected ArrayList<RenderCallback> mRenderCallbacks; // 每一帧渲染前的回调(一般用于处理模型变换、相机变换等)

    static {
        Filament.init();
    }

    public FLSurfaceView(Context context) {
        super(context);
        mChoreographer = Choreographer.getInstance();
        mDisplayHelper = new DisplayHelper(context);
        mRenderCallbacks = new ArrayList<>();
    }

    public void init() { // 初始化
        setupSurfaceView();
        setupFilament();
        setupView();
        setupScene();
    }

    public void setRenderMode(int renderMode) { // 设置渲染模式
        mRenderMode = renderMode;
    }

    public void addRenderCallback(RenderCallback renderCallback) { // 添加渲染回调
        if (renderCallback != null) {
            mRenderCallbacks.add(renderCallback);
        }
    }

    public void requestRender() { // 请求渲染
        mChoreographer.postFrameCallback(mFrameCallback);
    }

    public void onResume() { // 恢复
        mChoreographer.postFrameCallback(mFrameCallback);
    }

    public void onPause() { // 暂停
        mChoreographer.removeFrameCallback(mFrameCallback);
    }

    public void onDestroy() { // 销毁Filament环境
        mChoreographer.removeFrameCallback(mFrameCallback);
        mRenderCallbacks.clear();
        mUiHelper.detach();
        mEngine.destroyRenderer(mRenderer);
        mEngine.destroyView(mView);
        mEngine.destroyScene(mScene);
        mEngine.destroyCameraComponent(mCamera.getEntity());
        EntityManager entityManager = EntityManager.get();
        entityManager.destroy(mCamera.getEntity());
        mEngine.destroy();
    }

    protected void setupScene() { // 设置Scene参数
    }

    protected void onResized(int width, int height) { // Surface尺寸变化时回调
        double zoom = 1;
        double aspect = (double) width / (double) height;
        mCamera.setProjection(Camera.Projection.ORTHO,
                -aspect * zoom, aspect * zoom, -zoom, zoom, 0, 1000);
    }

    private void setupSurfaceView() { // 设置SurfaceView
        mUiHelper = new UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK);
        mUiHelper.setRenderCallback(new SurfaceCallback());
        if (mDesiredSize != null) {
            mUiHelper.setDesiredSize(mDesiredSize.x, mDesiredSize.y);
        }
        mUiHelper.attachTo(this);
    }

    private void setupFilament() { // 设置Filament参数
        mEngine = Engine.create();
        // mEngine = (new Engine.Builder()).featureLevel(Engine.FeatureLevel.FEATURE_LEVEL_0).build();
        mRenderer = mEngine.createRenderer();
        mScene = mEngine.createScene();
        mView = mEngine.createView();
        mCamera = mEngine.createCamera(mEngine.getEntityManager().create());
    }

    private void setupView() { // 设置View参数
        float[] color = mSkyboxColor != null ? mSkyboxColor : new float[] {0, 0, 0, 1};
        Skybox skybox = (new Skybox.Builder()).color(color).build(mEngine);
        mScene.setSkybox(skybox);
        if (mEngine.getActiveFeatureLevel() == Engine.FeatureLevel.FEATURE_LEVEL_0) {
            mView.setPostProcessingEnabled(false); // FEATURE_LEVEL_0不支持post-processing
        }
        mView.setCamera(mCamera);
        mView.setScene(mScene);

        View.DynamicResolutionOptions options = new View.DynamicResolutionOptions();
        options.enabled = true;
        mView.setDynamicResolutionOptions(options);
    }

    /**
     * 帧回调
     */
    private class FrameCallback implements Choreographer.FrameCallback {
        @Override
        public void doFrame(long frameTimeNanos) { // 渲染每帧数据
            if (mRenderMode == RENDERMODE_CONTINUOUSLY) {
                mChoreographer.postFrameCallback(this); // 请求下一帧
            }
            mRenderCallbacks.forEach(callback -> callback.onCall());
            if (mUiHelper.isReadyToRender()) {
                if (mRenderer.beginFrame(mSwapChain, frameTimeNanos)) {
                    mRenderer.render(mView);
                    mRenderer.endFrame();
                }
            }
        }
    }

    /**
     * Surface回调
     */
    private class SurfaceCallback implements UiHelper.RendererCallback {
        @Override
        public void onNativeWindowChanged(Surface surface) { // Native窗口改变时回调
            if (mSwapChain != null) {
                mEngine.destroySwapChain(mSwapChain);
            }
            long flags = mUiHelper.getSwapChainFlags();
            if (mEngine.getActiveFeatureLevel() == Engine.FeatureLevel.FEATURE_LEVEL_0) {
                if (SwapChain.isSRGBSwapChainSupported(mEngine)) {
                    flags = flags | SwapChain.CONFIG_SRGB_COLORSPACE;
                }
            }
            mSwapChain = mEngine.createSwapChain(surface, flags);
            mDisplayHelper.attach(mRenderer, getDisplay());
        }

        @Override
        public void onDetachedFromSurface() { // 解绑Surface时回调
            mDisplayHelper.detach();
            if (mSwapChain != null) {
                mEngine.destroySwapChain(mSwapChain);
                mEngine.flushAndWait();
                mSwapChain = null;
            }
        }

        @Override
        public void onResized(int width, int height) { // Surface尺寸变化时回调
            mView.setViewport(new Viewport(0, 0, width, height));
            FilamentHelper.synchronizePendingFrames(mEngine);
            FLSurfaceView.this.onResized(width, height);
        }
    }

    /**
     * 每一帧渲染前的回调
     * 一般用于处理模型变换、相机变换等
     */
    public interface RenderCallback {
        void onCall();
    }
}

        BaseModel.java

package com.zhyan8.loadmodel.filament.base;
 
import android.content.Context;
 
import com.google.android.filament.Engine;
import com.google.android.filament.EntityManager;
import com.google.android.filament.Material;
import com.google.android.filament.MaterialInstance;
import com.google.android.filament.RenderableManager;
import com.google.android.filament.RenderableManager.PrimitiveType;
import com.google.android.filament.Texture;
import com.google.android.filament.TransformManager;
import com.zhyan8.loadmodel.filament.utils.MaterialUtils;
import com.zhyan8.loadmodel.filament.base.Mesh.Part;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * 模型基类
 * 管理模型的网格、材质、渲染id
 */
public class BaseModel {
    private static String TAG = "BaseModel";
    protected Context mContext; // 上下文
    protected Engine mEngine; // Filament引擎
    protected TransformManager mTransformManager; // 模型变换管理器
    protected Mesh mMesh; // 模型网格
    protected Material[] mMaterials; // 模型材质
    protected MaterialInstance[] mMaterialInstances; // 模型材质实例
    protected Map<String, MaterialInstance> mMaterialMap = new HashMap<>(); // 材质名->材质
    protected Texture[] mTextures; // 纹理
    protected int mRenderable; // 渲染id
    protected int mTransformComponent; // 模型变换组件的id
    protected FLSurfaceView.RenderCallback mRenderCallback; // 每一帧渲染前的回调(一般用于处理模型变换、相机变换等)
 
    public BaseModel(Context context, Engine engine) {
        mContext = context;
        mEngine = engine;
        mTransformManager = mEngine.getTransformManager();
    }
 
    public int getRenderable() { // 获取渲染id
        return mRenderable;
    }
 
    public FLSurfaceView.RenderCallback getRenderCallback() { // 获取渲染回调
        return mRenderCallback;
    }
 
    public void destroy() { // 销毁模型
        mMaterialMap.clear();
        mEngine.destroyEntity(mRenderable);
        if (mMesh != null) {
            mMesh.destroy();
        }
        if (mTextures != null) {
            for (int i = 0; i < mTextures.length; i++) {
                mEngine.destroyTexture(mTextures[i]);
            }
        }
        if (mMaterialInstances != null) {
            for (int i = 0; i < mMaterialInstances.length; i++) {
                mEngine.destroyMaterialInstance(mMaterialInstances[i]);
            }
        }
        if (mMaterials != null) {
            for (int i = 0; i < mMaterials.length; i++) {
                mEngine.destroyMaterial(mMaterials[i]);
            }
        }
        EntityManager entityManager = EntityManager.get();
        entityManager.destroy(mRenderable);
    }
 
    protected int getRenderable(PrimitiveType primitiveType) { // 获取渲染id
        int renderable = EntityManager.get().create();
        List<Part> parts = mMesh.getParts();
        List<String> materialNames = mMesh.getMaterialNames();
        RenderableManager.Builder builder = new RenderableManager.Builder(parts.size()).boundingBox(mMesh.getBox());
        for (int i = 0; i < parts.size(); i++) {
            Part part = parts.get(i);
            builder.geometry(i, primitiveType, mMesh.getVertexBuffer(), mMesh.getIndexBuffer(),
                            part.offset, part.minIndex, part.maxIndex, part.indexCount);
            MaterialInstance material = getMaterialInstance(materialNames, part.materialID);
            builder.material(i, material);
        }
        builder.build(mEngine, renderable);
        return renderable;
    }
 
    protected Material[] loadMaterials(String materialPath) { // 加载材质
        Material material = MaterialUtils.loadMaterial(mContext, mEngine, materialPath);
        if (material != null) {
            return new Material[] {material};
        }
        return null;
    }
 
    protected Material[] loadMaterials(String[] materialPaths) { // 加载材质
        Material[] materials = new Material[materialPaths.length];
        for (int i = 0; i < materials.length; i++) {
            materials[i] = MaterialUtils.loadMaterial(mContext, mEngine, materialPaths[i]);
        }
        return materials;
    }
 
    protected MaterialInstance[] getMaterialInstance(Material[] materials) { // 获取材质实例
        MaterialInstance[] materialInstances = new MaterialInstance[materials.length];
        for (int i = 0; i < materials.length; i++) {
            materialInstances[i] = materials[i].createInstance();
        }
        return materialInstances;
    }
 
    protected MaterialInstance[] getMaterialInstance(Material material, int count) { // 获取材质实例
        MaterialInstance[] materialInstances = new MaterialInstance[count];
        for (int i = 0; i < count; i++) {
            materialInstances[i] = material.createInstance();
        }
        return materialInstances;
    }
 
    private MaterialInstance getMaterialInstance(List<String> materialNames, int materialID) { // 获取材质
        MaterialInstance material = null;
        if (materialNames != null && materialNames.size() > materialID && materialID >= 0) {
            String name = materialNames.get(materialID);
            if (mMaterialMap.containsKey(name)) {
                material = mMaterialMap.get(name);
            }
        }
        if (material == null && mMaterialMap.containsKey("DefaultMaterial")) {
            material = mMaterialMap.get("DefaultMaterial");
        }
        return material;
    }
}

        Mesh.java

package com.zhyan8.customlight.filament.base;

import com.google.android.filament.Box;
import com.google.android.filament.Engine;
import com.google.android.filament.IndexBuffer;
import com.google.android.filament.VertexBuffer;
import com.google.android.filament.VertexBuffer.AttributeType;
import com.google.android.filament.VertexBuffer.VertexAttribute;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;

/**
 * 网格
 * 用于管理模型的顶点属性和顶点索引
 */
public class Mesh {
    private Engine mEngine; // Filament引擎
    private VertexBuffer mVertexBuffer; // 顶点属性缓存
    private IndexBuffer mIndexBuffer; // 顶点索引缓存
    private List<Part> mParts; // 子网格信息
    private Box mBox; // 渲染区域
    private List<String> mMaterialNames; // 材质名

    public Mesh(Engine engine) {
        mEngine = engine;
    }

    public Mesh(Engine engine, float[] vertices, short[] indices, List<Part> parts, Box box, List<String> materialNames) {
        mEngine = engine;
        setVertices(vertices);
        setIndices(indices);
        setParts(parts, indices.length);
        setBox(box);
        mMaterialNames = materialNames;
    }

    public Mesh(Engine engine, VertexBuffer vrtexBuffer, IndexBuffer indexBuffer, List<Part> parts, Box box, List<String> materialNames) {
        mEngine = engine;
        mVertexBuffer = vrtexBuffer;
        mIndexBuffer = indexBuffer;
        mParts = parts;
        setBox(box);
        mMaterialNames = materialNames;
    }

    public Mesh(Engine engine, VertexPosCol[] vertices, short[] indices, List<Part> parts, Box box, List<String> materialNames) {
        mEngine = engine;
        setVertices(vertices);
        setIndices(indices);
        setParts(parts, indices.length);
        setBox(box);
        mMaterialNames = materialNames;
    }

    public Mesh(Engine engine, VertexPosUV[] vertices, short[] indices, List<Part> parts, Box box, List<String> materialNames) {
        mEngine = engine;
        setVertices(vertices);
        setIndices(indices);
        setParts(parts, indices.length);
        setBox(box);
        mMaterialNames = materialNames;
    }

    public void setVertices(float[] vertices) { // 设置顶点属性
        mVertexBuffer = getVertexBuffer(vertices);
    }

    public void setVertices(VertexPosCol[] vertices) { // 设置顶点属性
        mVertexBuffer = getVertexBuffer(vertices);
    }

    public void setVertices(VertexPosUV[] vertices) { // 设置顶点属性
        mVertexBuffer = getVertexBuffer(vertices);
    }

    public void setIndices(short[] indices) { // 设置顶点索引
        mIndexBuffer = getIndexBuffer(indices);
    }

    public void setParts(List<Part> parts, int count) { // 设置顶点索引
        if (parts == null || parts.size() == 0) {
            mParts = new ArrayList<>();
            mParts.add(new Part(0, count, 0, count - 1));
        } else {
            mParts = parts;
        }
    }

    public void setBox(Box box) { // 渲染区域
        if (box == null) {
            mBox = new Box(0, 0, 0, 1, 1, 1);
        } else {
            mBox = box;
        }
    }

    public VertexBuffer getVertexBuffer() { // 获取顶点属性缓存
        return mVertexBuffer;
    }

    public IndexBuffer getIndexBuffer() { // 获取顶点索引缓存
        return mIndexBuffer;
    }

    public List<Part> getParts() { // 获取顶点索引缓存
        return mParts;
    }

    public Box getBox() {
        return mBox;
    }

    public List<String> getMaterialNames() {
        return mMaterialNames;
    }

    public void destroy() {
        mEngine.destroyVertexBuffer(mVertexBuffer);
        mEngine.destroyIndexBuffer(mIndexBuffer);
        if (mParts != null) {
            mParts.clear();
        }
        if (mMaterialNames != null) {
            mMaterialNames.clear();
        }
    }

    private VertexBuffer getVertexBuffer(float[] values) { // 获取顶点属性缓存
        ByteBuffer vertexData = getByteBuffer(values);
        int vertexCount = values.length / 3;
        int vertexSize = Float.BYTES * 3;
        VertexBuffer vertexBuffer = new VertexBuffer.Builder()
                .bufferCount(1)
                .vertexCount(vertexCount)
                .attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize)
                .build(mEngine);
        vertexBuffer.setBufferAt(mEngine, 0, vertexData);
        return vertexBuffer;
    }

    private VertexBuffer getVertexBuffer(VertexPosCol[] values) { // 获取顶点属性缓存
        ByteBuffer vertexData = getByteBuffer(values);
        int vertexCount = values.length;
        int vertexSize = VertexPosCol.BYTES;
        VertexBuffer vertexBuffer = new VertexBuffer.Builder()
                .bufferCount(1)
                .vertexCount(vertexCount)
                .attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize)
                .attribute(VertexAttribute.COLOR,    0, AttributeType.UBYTE4, 3 * Float.BYTES, vertexSize)
                .normalized(VertexAttribute.COLOR)
                .build(mEngine);
        vertexBuffer.setBufferAt(mEngine, 0, vertexData);
        return vertexBuffer;
    }

    private VertexBuffer getVertexBuffer(VertexPosUV[] values) { // 获取顶点属性缓存
        ByteBuffer vertexData = getByteBuffer(values);
        int vertexCount = values.length;
        int vertexSize = VertexPosUV.BYTES;
        VertexBuffer vertexBuffer = new VertexBuffer.Builder()
                .bufferCount(1)
                .vertexCount(vertexCount)
                .attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize)
                .attribute(VertexAttribute.UV0,    0, AttributeType.FLOAT2, 3 * Float.BYTES, vertexSize)
                .build(mEngine);
        vertexBuffer.setBufferAt(mEngine, 0, vertexData);
        return vertexBuffer;
    }

    private IndexBuffer getIndexBuffer(short[] values) { // 获取顶点索引缓存
        ByteBuffer indexData = getByteBuffer(values);
        int indexCount = values.length;
        IndexBuffer indexBuffer = new IndexBuffer.Builder()
                .indexCount(indexCount)
                .bufferType(IndexBuffer.Builder.IndexType.USHORT)
                .build(mEngine);
        indexBuffer.setBuffer(mEngine, indexData);
        return indexBuffer;
    }

    private ByteBuffer getByteBuffer(float[] values) { // float数组转换为ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(values.length * Float.BYTES);
        byteBuffer.order(ByteOrder.nativeOrder());
        for (int i = 0; i < values.length; i++) {
            byteBuffer.putFloat(values[i]);
        }
        byteBuffer.flip();
        return byteBuffer;
    }

    private ByteBuffer getByteBuffer(short[] values) { // short数组转换为ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(values.length * Short.BYTES);
        byteBuffer.order(ByteOrder.nativeOrder());
        for (int i = 0; i < values.length; i++) {
            byteBuffer.putShort(values[i]);
        }
        byteBuffer.flip();
        return byteBuffer;
    }

    private ByteBuffer getByteBuffer(VertexPosCol[] values) { // VertexPosCol数组转换为ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(values.length * VertexPosCol.BYTES);
        byteBuffer.order(ByteOrder.nativeOrder());
        for (int i = 0; i < values.length; i++) {
            values[i].put(byteBuffer);
        }
        byteBuffer.flip();
        return byteBuffer;
    }

    private ByteBuffer getByteBuffer(VertexPosUV[] values) { // VertexPosUV数组转换为ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(values.length * VertexPosUV.BYTES);
        byteBuffer.order(ByteOrder.nativeOrder());
        for (int i = 0; i < values.length; i++) {
            values[i].put(byteBuffer);
        }
        byteBuffer.flip();
        return byteBuffer;
    }

    /**
     * 子网格信息
     */
    public static class Part {
        public int offset = 0;
        public int indexCount = 0;
        public int minIndex = 0;
        public int maxIndex = 0;
        public int materialID = -1;
        public Box aabb = new Box();

        public Part() {}

        public Part(int offset, int indexCount, int minIndex, int maxIndex) {
            this.offset = offset;
            this.indexCount = indexCount;
            this.minIndex = minIndex;
            this.maxIndex = maxIndex;
        }

        public Part(int offset, int indexCount, int minIndex, int maxIndex, int materialID, Box aabb) {
            this.offset = offset;
            this.indexCount = indexCount;
            this.minIndex = minIndex;
            this.maxIndex = maxIndex;
            this.materialID = materialID;
            this.aabb = aabb;
        }
    }

    /**
     * 顶点数据(位置+颜色)
     * 包含顶点位置和颜色
     */
    public static class VertexPosCol {
        public static int BYTES = 16;
        public float x;
        public float y;
        public float z;
        public int color;

        public VertexPosCol() {}

        public VertexPosCol(float x, float y, float z, int color) {
            this.x = x;
            this.y = y;
            this.z = z;
            this.color = color;
        }

        public ByteBuffer put(ByteBuffer buffer) { // VertexPosCol转换为ByteBuffer
            buffer.putFloat(x);
            buffer.putFloat(y);
            buffer.putFloat(z);
            buffer.putInt(color);
            return buffer;
        }
    }

    /**
     * 顶点数据(位置+纹理坐标)
     * 包含顶点位置和纹理坐标
     */
    public static class VertexPosUV {
        public static int BYTES = 20;
        public float x;
        public float y;
        public float z;
        public float u;
        public float v;

        public VertexPosUV() {}

        public VertexPosUV(float x, float y, float z, float u, float v) {
            this.x = x;
            this.y = y;
            this.z = z;
            this.u = u;
            this.v = v;
        }

        public ByteBuffer put(ByteBuffer buffer) { // VertexPosUV转换为ByteBuffer
            buffer.putFloat(x);
            buffer.putFloat(y);
            buffer.putFloat(z);
            buffer.putFloat(u);
            buffer.putFloat(v);
            return buffer;
        }
    }
}

        MaterialUtils.java

package com.zhyan8.customlight.filament.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.android.filament.Engine;
import com.google.android.filament.Material;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

/**
 * 材质工具类
 */
public class MaterialUtils {
    private static String TAG = "MaterialUtils";

    public static Material loadMaterial(Context context, Engine engine, String materialPath) { // 加载材质
        Buffer buffer = readUncompressedAsset(context, materialPath);
        if (buffer != null) {
            Material material = (new Material.Builder()).payload(buffer, buffer.remaining()).build(engine);
            material.compile(
                    Material.CompilerPriorityQueue.HIGH,
                    Material.UserVariantFilterBit.ALL,
                    new Handler(Looper.getMainLooper()),
                    () -> Log.i(TAG, "Material " + material.getName() + " compiled."));
            engine.flush();
            return material;
        }
        return null;
    }

    private static Buffer readUncompressedAsset(Context context, String assetPath) { // 加载资源
        ByteBuffer dist = null;
        try {
            AssetFileDescriptor fd = context.getAssets().openFd(assetPath);
            try(FileInputStream fis = fd.createInputStream()) {
                dist = ByteBuffer.allocate((int) fd.getLength());
                try (ReadableByteChannel src = Channels.newChannel(fis)) {
                    src.read(dist);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (dist != null) {
            return dist.rewind();
        }
        return null;
    }
}

        MeshUtils.java

package com.zhyan8.customlight.filament.utils;

import android.content.Context;
import android.util.Log;

import com.google.android.filament.Box;
import com.google.android.filament.Engine;
import com.google.android.filament.IndexBuffer;
import com.google.android.filament.VertexBuffer;
import com.google.android.filament.VertexBuffer.AttributeType;
import com.zhyan8.customlight.filament.base.Mesh;
import com.zhyan8.customlight.filament.base.Mesh.Part;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 材质工具类
 */
public class MeshUtils {
    private static final String FILAMESH_FILE_IDENTIFIER = "FILAMESH";
    private static final long HEADER_FLAG_SNORM16_UV = 0x2L;
    private static final long MAX_UINT32 = 4294967295L;

    public static Mesh loadMesh(Context context, Engine engine, String meshPath) {
        try (InputStream inputStream = context.getAssets().open(meshPath)) {
            Header header = readHeader(inputStream);
            ReadableByteChannel channel = Channels.newChannel(inputStream);
            ByteBuffer vertexBufferData = readSizedData(channel, header.verticesSizeInBytes);
            ByteBuffer indexBufferData = readSizedData(channel, header.indicesSizeInBytes);
            List<Part> parts = readParts(header, inputStream);
            List<String> materialNames = readMaterials(inputStream);

            VertexBuffer vertexBuffer = createVertexBuffer(engine, header, vertexBufferData);
            IndexBuffer indexBuffer = createIndexBuffer(engine, header, indexBufferData);
            return new Mesh(engine, vertexBuffer, indexBuffer, parts, header.aabb, materialNames);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Header readHeader(InputStream input) { // 读取文件头信息
        Header header = new Header();
        if (!readMagicNumber(input)) {
            Log.e("Filament", "Invalid filamesh file.");
            return header;
        }
        header.versionNumber = readUIntLE(input);
        header.parts = readUIntLE(input);
        header.aabb = new Box(
                readFloat32LE(input), readFloat32LE(input), readFloat32LE(input),
                readFloat32LE(input), readFloat32LE(input), readFloat32LE(input));
        header.flags = readUIntLE(input);
        header.posOffset = readUIntLE(input);
        header.positionStride = readUIntLE(input);
        header.tangentOffset = readUIntLE(input);
        header.tangentStride = readUIntLE(input);
        header.colorOffset = readUIntLE(input);
        header.colorStride = readUIntLE(input);
        header.uv0Offset = readUIntLE(input);
        header.uv0Stride = readUIntLE(input);
        header.uv1Offset = readUIntLE(input);
        header.uv1Stride = readUIntLE(input);
        header.totalVertices = readUIntLE(input);
        header.verticesSizeInBytes = readUIntLE(input);
        header.indices16Bit = readUIntLE(input);
        header.totalIndices = readUIntLE(input);
        header.indicesSizeInBytes = readUIntLE(input);
        header.valid = true;
        return header;
    }

    private static ByteBuffer readSizedData(ReadableByteChannel channel, int sizeInBytes) { // 读取模型顶点数据
        ByteBuffer buffer = ByteBuffer.allocateDirect(sizeInBytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        try {
            channel.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        buffer.flip();
        return buffer;
    }

    private static List<Part> readParts(Header header, InputStream input) { // 读取子网格属性
        List<Part> parts = new ArrayList<>(header.parts);
        for (int i = 0; i < header.parts; i++) {
            Part p = new Part();
            p.offset = readUIntLE(input);
            p.indexCount = readUIntLE(input);
            p.minIndex = readUIntLE(input);
            p.maxIndex = readUIntLE(input);
            p.materialID = readUIntLE(input);
            float minX = readFloat32LE(input);
            float minY = readFloat32LE(input);
            float minZ = readFloat32LE(input);
            float maxX = readFloat32LE(input);
            float maxY = readFloat32LE(input);
            float maxZ = readFloat32LE(input);
            p.aabb = new Box(minX, minY, minZ, maxX, maxY, maxZ);
            parts.add(p);
        }
        return parts;
    }

    private static boolean readMagicNumber(InputStream input) { // 读取魔法数字, 用于判断是否是有效的filamesh文件
        byte[] temp = new byte[FILAMESH_FILE_IDENTIFIER.length()];
        int bytesRead = 0;
        try {
            bytesRead = input.read(temp);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (bytesRead != FILAMESH_FILE_IDENTIFIER.length()) {
            return false;
        }
        String tempS = new String(temp, Charset.forName("UTF-8"));
        return tempS.equals(FILAMESH_FILE_IDENTIFIER);
    }

    private static List<String> readMaterials(InputStream input) { // 读取材质
        int numMaterials = readUIntLE(input);
        List<String> materials = new ArrayList<>(numMaterials);
        for (int i = 0; i < numMaterials; i++) {
            int dataLength = readUIntLE(input);
            byte[] data = new byte[dataLength];
            try {
                input.read(data);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                input.skip(1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            materials.add(new String(data, Charset.forName("UTF-8")));
        }
        return materials;
    }

    private static IndexBuffer createIndexBuffer(Engine engine, Header header, ByteBuffer data) { // 创建顶点索引缓冲
        IndexBuffer.Builder.IndexType indexType = (header.indices16Bit != 0) ?
                IndexBuffer.Builder.IndexType.USHORT : IndexBuffer.Builder.IndexType.UINT;
        IndexBuffer buffer = new IndexBuffer.Builder()
                .bufferType(indexType)
                .indexCount(header.totalIndices)
                .build(engine);
        buffer.setBuffer(engine, data);
        return buffer;
    }

    private static VertexBuffer createVertexBuffer(Engine engine, Header header, ByteBuffer data) { // 创建顶点属性缓冲
        AttributeType uvType = uvType(header);
        VertexBuffer.Builder vertexBufferBuilder = new VertexBuffer.Builder()
                .bufferCount(1)
                .vertexCount(header.totalVertices)
                .normalized(VertexBuffer.VertexAttribute.COLOR)
                .normalized(VertexBuffer.VertexAttribute.TANGENTS)
                .attribute(VertexBuffer.VertexAttribute.POSITION, 0, VertexBuffer.AttributeType.HALF4, header.posOffset, header.positionStride)
                .attribute(VertexBuffer.VertexAttribute.TANGENTS, 0, AttributeType.SHORT4, header.tangentOffset, header.tangentStride)
                .attribute(VertexBuffer.VertexAttribute.COLOR, 0, AttributeType.UBYTE4, header.colorOffset, header.colorStride)
                .attribute(VertexBuffer.VertexAttribute.UV0, 0, uvType, header.uv0Offset, header.uv0Stride);
        if (header.uv1Offset != MAX_UINT32 && header.uv1Stride != MAX_UINT32) {
            vertexBufferBuilder
                    .attribute(VertexBuffer.VertexAttribute.UV1, 0, uvType, header.uv1Offset, header.uv1Stride)
                    .normalized(VertexBuffer.VertexAttribute.UV1, true);
        }
        VertexBuffer buffer = vertexBufferBuilder.build(engine);
        buffer.setBufferAt(engine, 0, data);
        return buffer;
    }

    private static AttributeType uvType(Header header) { // UV坐标的精度类型
        if ((header.flags & HEADER_FLAG_SNORM16_UV) != 0L) {
            return AttributeType.SHORT2;
        }
        return AttributeType.HALF2;
    }

    private static int readIntLE(InputStream input) { // 获取输入流中Little Endian格式的整数
        try {
            return (input.read() & 0xff) |
                    ((input.read() & 0xff) << 8) |
                    ((input.read() & 0xff) << 16) |
                    ((input.read() & 0xff) << 24);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private static int readUIntLE(InputStream input) { // 获取输入流中Little Endian格式的无符号整数
        return (int) (readIntLE(input) & 0xFFFFFFFFL);
    }

    private static float readFloat32LE(InputStream input) { // 获取输入流中Little Endian格式的浮点数
        byte[] bytes = new byte[4];
        try {
            input.read(bytes, 0, 4);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();
    }
}

/**
 * 网格文件头
 */
class Header {
    boolean valid = false;
    int versionNumber = 0;
    int parts = 0;
    Box aabb = new Box();
    int flags = 0;
    int posOffset = 0;
    int positionStride = 0;
    int tangentOffset = 0;
    int tangentStride = 0;
    int colorOffset = 0;
    int colorStride = 0;
    int uv0Offset = 0;
    int uv0Stride = 0;
    int uv1Offset = 0;
    int uv1Stride = 0;
    int totalVertices = 0;
    int verticesSizeInBytes = 0;
    int indices16Bit = 0;
    int totalIndices = 0;
    int indicesSizeInBytes = 0;
}

2.2 业务类

        MainActivity.java

package com.zhyan8.customlight;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.zhyan8.customlight.filament.base.FLSurfaceView;

public class MainActivity extends AppCompatActivity {
    private FLSurfaceView mFLSurfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFLSurfaceView = new MyFLSurfaceView(this);
        setContentView(mFLSurfaceView);
        mFLSurfaceView.init();
        mFLSurfaceView.setRenderMode(FLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }

    @Override
    public void onResume() {
        super.onResume();
        mFLSurfaceView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mFLSurfaceView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mFLSurfaceView.onDestroy();
    }
}

        MyFLSurfaceView.java

package com.zhyan8.customlight;

import android.content.Context;

import com.google.android.filament.Camera;
import com.zhyan8.customlight.filament.base.BaseModel;
import com.zhyan8.customlight.filament.base.FLSurfaceView;

public class MyFLSurfaceView extends FLSurfaceView {
    private BaseModel mMyModel;
    public MyFLSurfaceView(Context context) {
        super(context);
    }

    public void init() {
        mSkyboxColor = new float[] {0.35f, 0.35f, 0.35f, 1};
        super.init();
    }

    @Override
    public void onDestroy() {
        mMyModel.destroy();
        super.onDestroy();
    }

    @Override
    protected void setupScene() { // 设置Scene参数
        mMyModel = new MyModel(getContext(), mEngine);
        mScene.addEntity(mMyModel.getRenderable());
        addRenderCallback(mMyModel.getRenderCallback());
    }

    @Override
    protected void onResized(int width, int height) {
        double aspect = (double) width / (double) height;
        mCamera.setProjection(45.0, aspect, 0.1, 1000.0, Camera.Fov.VERTICAL);
        float[] eye = new float[] {1.5f, 1f, 7.5f}; // cube
        //float[] eye = new float[] {1.5f, 1f, 500f}; // spider_bot
        //float[] eye = new float[] {1.5f, 1f, 10f}; // shader_ball
        float[] center = new float[] {0, 0, 0};
        float[] up = new float[] {0, 1, 0};
        mCamera.lookAt(eye[0], eye[1], eye[2],center[0], center[1], center[2], up[0], up[1], up[2]);
    }
}

        MyModel.java

package com.zhyan8.customlight;

import android.content.Context;
import android.opengl.Matrix;

import com.google.android.filament.Engine;
import com.google.android.filament.MaterialInstance;
import com.google.android.filament.RenderableManager.PrimitiveType;
import com.zhyan8.customlight.filament.base.BaseModel;
import com.zhyan8.customlight.filament.utils.MeshUtils;

public class MyModel extends BaseModel {
    private String mMaterialPath = "materials/custom_light.filamat";
    private String mMeshPath = "models/cube.filamesh";
    //private String mMeshPath = "models/spider_bot.filamesh";
    //private String mMeshPath = "models/shader_ball.filamesh";

    private float[] mModelMatrix; // 模型变换矩阵
    private float[] mRotateAxis; // 旋转轴
    private float mRotateAgree = 0; // 旋转角度

    public MyModel(Context context, Engine engine) {
        super(context, engine);
        init();
    }

    private void init() {
        mMaterials = loadMaterials(mMaterialPath);
        mMaterialInstances = getMaterialInstance(mMaterials);
        setupMaterial(mMaterialInstances[0]);
        mMaterialMap.put("DefaultMaterial", mMaterialInstances[0]);
        mMesh = MeshUtils.loadMesh(mContext, mEngine, mMeshPath);
        mRenderable = getRenderable(PrimitiveType.TRIANGLES);
        mTransformComponent = mTransformManager.getInstance(mRenderable);
        mRenderCallback = () -> renderCallback();
        mModelMatrix = new float[16];
        mRotateAxis = new float[] { 0.5f, 1f, 1f };
    }

    private void setupMaterial(MaterialInstance materialInstance) {
        materialInstance.setParameter("albedo", 0.7f, 0.1f, 0.2f); // 模型颜色
        materialInstance.setParameter("ambientColor", 0.2f, 0.2f, 0.2f); // 环境光颜色
        materialInstance.setParameter("lightPos", 100f, 500f, 50f); // 灯光位置
        materialInstance.setParameter("lightColor", 0.9f, 0.9f, 0.9f); // 灯光颜色
        materialInstance.setParameter("specularStrength", 0.1f); // 镜面反射光强度
        materialInstance.setParameter("gloss", 4f); // 镜面反射光泽度
    }

    private void renderCallback() {
        mRotateAgree = (mRotateAgree + 1) % 360;
        mRotateAxis[0] = mRotateAgree / 180f - 1;
        mRotateAxis[1] = (float) Math.sin(mRotateAgree / 180f * Math.PI * 0.7f);
        mRotateAxis[2] = (float) Math.cos(mRotateAgree / 180f * Math.PI * 0.5f);
        Matrix.setRotateM(mModelMatrix, 0, mRotateAgree, mRotateAxis[0], mRotateAxis[1], mRotateAxis[2]);
        mTransformManager.setTransform(mTransformComponent, mModelMatrix);
    }
}

        custom_light.mat

material {
    name : custom_light,

    shadingModel : unlit, // 禁用所有lighting
    // 自定义变量参数
    parameters : [
        {
            type : float3,
            name : albedo // 模型颜色
        },
        {
            type : float3,
            name : ambientColor // 环境光颜色
        },
        {
            type : float3,
            name : lightPos // 灯光位置
        },
        {
            type : float3,
            name : lightColor // 灯光颜色
        },
        {
            type : float,
            name : specularStrength // 镜面反射光强度
        },
        {
            type : float,
            name : gloss  // 镜面反射光泽度
        }
    ],
    // 顶点着色器入参MaterialVertexInputs中需要的顶点属性
    requires : [
        tangents
    ]
}

fragment {
    vec3 ambientColor() { // 环境光
        vec3 ambient = materialParams.ambientColor * materialParams.albedo;
        return ambient;
    }

    vec3 diffuseColor(vec3 normal, vec3 lightDir) { // 漫反射光
        float factor = max(dot(normal, lightDir), 0.0);
        vec3 diffuse = factor * materialParams.lightColor * materialParams.albedo;
        return diffuse;
    }

    vec3 specularColor(vec3 normal, vec3 lightDir, vec3 viewDire) { // 镜面反射光(Blinn Phong 光照模型)
        vec3 halfVec = normalize(lightDir + viewDire); // 半向量
        float factor = pow(max(dot(normal, halfVec), 0.0), materialParams.gloss);
        vec3 specular = factor * materialParams.lightColor * materialParams.specularStrength;
        return specular;
    }

    void material(inout MaterialInputs material) {
        prepareMaterial(material); // 在方法返回前必须回调该函数
        vec3 pos = getWorldPosition(); // 顶点的世界坐标
        vec3 normal = normalize(getWorldNormalVector()); // 法线向量
        vec3 lightDir = normalize(materialParams.lightPos - pos); // 顶点指向光源的向量
        vec3 viewDire = normalize(getWorldCameraPosition() - pos); // 顶点指向相机的向量
        vec3 ambient = ambientColor();
        vec3 diffuse = diffuseColor(normal, lightDir);
        vec3 specular = specularColor(normal, lightDir, viewDire);
        material.baseColor = vec4(ambient + diffuse + specular, 1);
    }
}

        说明:custom_light 材质实现了 Blinn Phong 光照模型。 

        cube.obj

# 正方体模型
 
# 顶点位置
v 1.0 1.0 -1.0   # V1
v 1.0 -1.0 -1.0  # V2
v 1.0 1.0 1.0    # V3
v 1.0  -1.0 1.0  # V4
v -1.0 1.0 -1.0  # V5
v -1.0 -1.0 -1.0 # V6
v -1.0 1.0 1.0   # V7
v -1.0 -1.0 1.0  # V8
 
# 纹理坐标
vt 0.0 0.0  # VT1
vt 1.0 0.0  # VT2
vt 1.0 1.0  # VT3
vt 0.0 1.0  # VT4
 
# 法线
vn 0.0 1.0 0.0   # VN1 (上面法线)
vn 0.0 0.0 1.0   # VN2 (背面法线)
vn -1.0 0.0 0.0  # VN3 (左面法线)
vn 0.0 -1.0 0.0  # VN4 (下面法线)
vn 1.0 0.0 0.0   # VN5 (右面法线)
vn 0.0 0.0 -1.0  # VN6 (前面法线)
 
# 面(v/vt/vn)
f 1/1/1 5/2/1 7/3/1
f 1/1/1 7/3/1 3/4/1
f 4/1/2 3/2/2 7/3/2
f 4/1/2 7/3/2 8/4/2
f 8/1/3 7/2/3 5/3/3
f 8/1/3 5/3/3 6/4/3
f 6/1/4 2/2/4 4/3/4
f 6/1/4 4/3/4 8/4/4
f 2/1/5 1/2/5 3/3/5
f 2/1/5 3/3/5 4/4/5
f 6/1/6 5/2/6 1/3/6
f 6/1/6 1/3/6 2/4/6

        transform.bat

@echo off
setlocal enabledelayedexpansion
 
echo transform materials
set "srcMatDir=../src/main/raw/materials"
set "distMatDir=../src/main/assets/materials"
 
for %%f in ("%srcMatDir%\*.mat") do (
	set "matfile=%%~nf"
	matc -p mobile -a opengl -o "!matfile!.filamat" "%%f"
    move "!matfile!.filamat" "%distMatDir%\!matfile!.filamat"
)
 
echo transform mesh
set "srcMeshDir=../src/main/raw/models"
set "distMeshDir=../src/main/assets/models"
 
for %%f in ("%srcMeshDir%\*.obj" "%srcMeshDir%\*.fbx") do (
	set "meshfile=%%~nf"
	filamesh "%%f" "!meshfile!.filamesh"
    move "!meshfile!.filamesh" "%distMeshDir%\!meshfile!.filamesh"
)
 
echo Processing complete.
pause

        说明:需要将 matc.exe 文件、filamesh.exe 文件与 transform.bat 文件放在同一个目录下面,matc.exe 和 filamesh.exe 源自Filament环境搭建中编译生成的 exe 文件。双击 transform.bat 文件,会自动将 /src/main/raw/materials 下面的所有 mat 文件全部转换为 filamat 文件,并移到 /src/main/assets/materials/ 目录下面,同时自动将 /src/main/raw/models下面的所有 obj 或 fbx 文件全部转换为 filamesh 文件,并移到 /src/main/assets/models/ 目录下面。

        加载 cube 模型运行效果如下。

        加载 spider_bot 模型运行效果如下。

        加载 shader_ball 模型运行效果如下。 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1360414.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Vue3+React18+TS4】1-1 : 课程介绍与学习指南

本书目录&#xff1a;点击进入 一、为什么做这样一门课程? 二、本门课的亮点有哪些? 2.1、轻松驾驭 2.2、体系系统 2.3、高效快捷 2.4、融合贯通 三、课程内容包括哪些? 四、项目实战 《在线考勤系统》 五、课适合哪些同学? 一、为什么做这样一门课程? 近十年内前端…

RocketMQ源码 发送消息源码分析

前言 DefaultMQProducer 是默认生产者组件&#xff0c;是生产者客户端中&#xff0c;绝大部分关于生产者和broker、nameSrv进行网络通信的功能入口。其中&#xff0c;包含发送各种形式&#xff08;同步、异步、事务、顺序&#xff09;的消息&#xff0c;针对发送消息部分的实现…

Vue页面传值:Props属性与$emit事件的应用介绍

一、vue页面传值 在Vue页面中传值有多种方式&#xff0c;简单介绍以下两种 通过props属性传递值&#xff1a;父组件在子组件上定义props属性&#xff0c;子组件通过props接收父组件传递的值。通过$emit触发事件传递值&#xff1a;子组件通过$emit方法触发一个自定义事件&#…

Meshlab界面和菜单初步认识

文章目录 界面认识菜单 界面认识 顾名思义&#xff0c;MeshLab即网格实验室&#xff0c;用于处理三维对象&#xff0c;并有着针对网格基于网格操作的各种工具&#xff0c;是一个功能强大的三维几何处理系统。因其开源&#xff0c;直接搜官网下载即可。安装过程无坑&#xff0c…

pycharm调整漂亮的颜色主题

主题样式&#xff1a; 一、设置主题为白色 二、pycharm 如何设置字体颜色 打开pycharm编辑器&#xff0c;file > settings > editor > color scheme > python > 你也可以直接用我资源中的配置好的文件

癌症早筛2023:翻越大山,仍是漫漫征途

撕开一盒试剂盒&#xff0c;拿出采样工具&#xff0c;在采集测试样本后混入试剂&#xff0c;再用试纸测试自身对某种病原体的感染情况。过去一段时间&#xff0c;这个方式帮助很多人尽早明确了新冠、流感、支原体的感染状况&#xff0c;从而加速对症治疗。 也因此&#xff0c;…

计算机进入BIOS - Win/Linux

计算机进入BIOS - Win/Linux 快捷键方法&#xff08;通用&#xff09;Win系统方法Linux系统方法 快捷键方法&#xff08;通用&#xff09; 此方法为通用方法&#xff0c;适用于任何型号的计算机&#xff0c;包括台式机和笔记本&#xff0c;也包括Win系统和Linux系统。 进入BI…

FA2016AA (MHz范围晶体单元超小型低轮廓贴片) 汽车

随着科技的不断发展&#xff0c;智能汽车逐渐成为人们出行的首选。而其中&#xff0c;频率范围在19.2 MHz ~ 54 MHz的晶体单元超小型低轮廓贴片&#xff08;FA2016AA&#xff09;为汽车打造更智能、更舒适、更安全的出行体验。FA2016AA贴片的外形尺寸为2.0 1.6 0.5 mm&#x…

【UnityShader入门精要学习笔记】(2)GPU流水线

本系列为作者学习UnityShader入门精要而作的笔记&#xff0c;内容将包括&#xff1a; 书本中句子照抄 个人批注项目源码一堆新手会犯的错误潜在的太监断更&#xff0c;有始无终 总之适用于同样开始学习Shader的同学们进行有取舍的参考。 文章目录 上节复习GPU流水线顶点着色…

bat批处理文件_命令汇总(2)

文章目录 1、换行2、返回上一级目录cd..3、隐藏指令回显echo off4、开启指令回显echo on5、用关闭echo off指令本身的回显6、echo提示信息 1、换行 cd.. echo. echo. echo. pause2、返回上一级目录cd… 3、隐藏指令回显echo off echo off echo hello1 echo hello2 pause4、开…

【学习笔记】1、数字逻辑概论

1.1 数字信号 数字信号&#xff0c;在时间和数值上均是离散的。数字信号的表达方式&#xff1a;二值数字逻辑和逻辑电平描述的数字波形。 &#xff08;1&#xff09; 数字波形的两种类型 数值信号又称为“二值信号”。数字波形又称为“二值位形图”。 什么是一拍 一定的时…

计算机网络期末知识汇总

一、计算机网络概述 1.Internet 的中文译名并不统一。 现有的 Internet 译名有两种&#xff1a; 因特网&#xff0c;这个译名是全国科学技术名词审定委员会推荐的&#xff0c;但却长期未得 到推广&#xff1b; 互联网&#xff0c;这是目前流行最广的、事实上的标准译名。现…

原生微信小程序AR(扫描指定图片显示glb模型)

效果 ar案例视频 准备&#xff1a;需要准备要扫描的图片地址和扫描成功后显示的模型 1.在components创建组件 index.js文件代码 Component({properties: {title: {type: String,value: ,},intro: {type: String,value: ,},hint: {type: String,value: ,},code: {type: String…

呼叫 Mac 用户 | Navicat Premium 原生支持在搭载 Apple Silicon 芯片的电脑上使用

作为桌面端数据库管理开发软件&#xff0c;Navicat Premium 与 Navicat for MongoDB 16.3 (或更高版本) 已原生支持搭载 Apple Silicon 芯片的 Mac 电脑上使用。这是一次重要的技术改进&#xff0c;通过原生技术将大幅提升 Mac 用户在使用 Navicat 过程中的响应速度、流畅性以及…

[C#]使用OpenCvSharp实现二维码图像增强超分辨率

【官方框架地址】 github.com/shimat/opencvsharp 【算法介绍】 借助于opencv自带sr.prototxt和sr.caffemodel实现对二维码图像增强 【效果展示】 【实现部分代码】 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin…

C++结合OpenCV:图像的基本表示方法

1.二值图像 二值图像是指仅仅包含黑色和白色两种颜色的图像。在计算机中&#xff0c;通过一个栅格状排列的数据集&#xff08;矩阵&#xff09;来表示和处理图像。例如&#xff0c;图1是一个字母A的图像&#xff0c;计算机在处理该图像时&#xff0c;会首先将其划分为一个个的小…

C# OpenCvSharp DNN FreeYOLO 人脸检测

目录 效果 模型信息 项目 代码 下载 C# OpenCvSharp DNN FreeYOLO 人脸检测 效果 模型信息 Inputs ------------------------- name&#xff1a;input tensor&#xff1a;Float[1, 3, 192, 320] --------------------------------------------------------------- Outp…

文章解读与仿真程序复现思路——电网技术EI\CSCD\北大核心《考虑多元不确定性和备用需求的微电网双层鲁棒容量规划》

本专栏栏目提供文章与程序复现思路&#xff0c;具体已有的论文与论文源程序可翻阅本博主免费的专栏栏目《论文与完整程序》 这个标题涉及微电网&#xff08;Microgrid&#xff09;的双层鲁棒容量规划&#xff0c;考虑了多元不确定性和备用需求。让我们逐步解读这个标题&#xf…

【AI视野·今日NLP 自然语言处理论文速览 第六十六期】Tue, 31 Oct 2023

AI视野今日CS.NLP 自然语言处理论文速览 Tue, 31 Oct 2023 (showing first 100 of 141 entries) Totally 100 papers &#x1f449;上期速览✈更多精彩请移步主页 Daily Computation and Language Papers The Eval4NLP 2023 Shared Task on Prompting Large Language Models a…

箭头函数 - JavaScript的新宠儿

&#x1f4e2; 鸿蒙专栏&#xff1a;想学鸿蒙的&#xff0c;冲 &#x1f4e2; C语言专栏&#xff1a;想学C语言的&#xff0c;冲 &#x1f4e2; VUE专栏&#xff1a;想学VUE的&#xff0c;冲这里 &#x1f4e2; CSS专栏&#xff1a;想学CSS的&#xff0c;冲这里 &#x1f4…