Java 3D LWJGL Gitbook~第14章 – 法線マッピング~

第14章 - 法線マッピング

この章では、3D モデルの外観を劇的に改善するテクニックについて説明します。ここまでで、複雑な 3D モデルにテクスチャを適用できるようになりましたが、実際のオブジェクトがどのように見えるかにはまだほど遠い状態です。現実世界の表面は完全に平らではなく、現在の 3D モデルにはない不完全さがあります。

よりリアルなシーンをレンダリングするために、法線マップを使用します。現実世界の平らな表面を見ると、光が反射する方法によって、遠くからでもこれらの欠陥が見えることがわかります。3D シーンでは、平らな表面には欠陥がなく、テクスチャを適用できますが、光が反射する方法は変更しません。それが違いを生むものです。

三角形の数を増やしてモデルの詳細を増やし、それらの不完全さを反映することを考えるかもしれませんが、パフォーマンスは低下します。必要なのは、表面での光の反射方法を変更してリアリズムを高める方法です。これは法線マッピング技術で達成されます。

つまるところは、「光がどのように反射するかを見ることができます。」というところの実装を追加した内容の記事になります。

サンプルコードの実行

コンセプト

プレーン サーフェスの例に戻りましょう。平面は、四角形を形成する 2 つの三角形によって定義できます。ライティングの章で覚えていると思いますが、光がどのように反射するかをモデル化する要素はサーフェス法線です。この場合、サーフェス全体に対して単一の法線があり、サーフェスの各フラグメントは、光がそれらにどのように影響するかを計算するときに同じ法線を使用します。これを次の図に示します。

サーフェスの各フラグメントの法線を変更できれば、サーフェスの不完全性をモデル化して、より現実的な方法でレンダリングできます。これを次の図に示します。

これを実現する方法は、サーフェスの法線を保存する別のテクスチャをロードすることです。通常のテクスチャの各ピクセルには、
X, Y, Z。 RGB 値として格納された法線の座標。次のテクスチャを使用してクワッドを描画してみましょう。

上の画像の法線マップ テクスチャの例を次に示します。

ご覧のとおり、元のテクスチャに色変換を適用したかのようです。各ピクセルは、色成分を使用して法線情報を格納します。通常、法線マップを表示するときに目にすることの 1 つは、支配的な色が青色になる傾向があることです。これは、法線が正の方向を指しているという事実によるものです。

Z軸。のZコンポーネントは通常、よりもはるかに高い値を持ちますXとY法線が表面の外を指しているため、平らな表面用のもの。
以来 X, Y, Z座標が RGB にマッピングされると、青のコンポーネントもより高い値になります。

したがって、法線マップを使用してオブジェクトをレンダリングするには、追加のテクスチャが必要であり、フラグメントをレンダリングするときにそれを使用して適切な法線値を取得します。

実装

通常、法線マップはそのように定義されず、いわゆるタンジェント スペースで定義されます。接線空間は、モデルの各三角形にローカルな座標系です。その座標空間では、X軸は常にサーフェスの外を指します。これが、向かい合った面を持つ複雑なモデルであっても、法線マップが通常青みがかっている理由です。接空間を処理するには、ノルム、アル、タンジェント、バイタンジェント ベクトルが必要です。すでに法線ベクトルがあり、接線ベクトルと従接線ベクトルは法線ベクトルに垂直なベクトルです。これらのベクトルTBNは、シェーダーで使用している座標系の接空間にあるデータを使用できるようにする行列を計算するために必要です。

ここで、この側面に関する優れたチュートリアルを確認できます

したがって、最初のステップは、ModelLoaderタンジェントおよびバイタンジェント情報を含む、クラスをロードする法線マッピングのサポートを追加することです。assimp のモデル読み込みフラグを設定するときに、これを含めたことを思い出してください: aiProcess_CalcTangentSpace. このフラグを使用すると、タンジェント データとバイタンジェント データを自動的に計算できます。

このprocessMaterialメソッドでは、まず法線マップ テクスチャの存在を照会します。その場合は、そのテクスチャを読み込み、そのテクスチャ パスをマテリアルに関連付けます。

public class ModelLoader {
    ...
    private static Material processMaterial(AIMaterial aiMaterial, String modelDir, TextureCache textureCache) {
        ...
        try (MemoryStack stack = MemoryStack.stackPush()) {
            ...
            AIString aiNormalMapPath = AIString.calloc(stack);
            Assimp.aiGetMaterialTexture(aiMaterial, aiTextureType_NORMALS, 0, aiNormalMapPath, (IntBuffer) null,
                    null, null, null, null, null);
            String normalMapPath = aiNormalMapPath.dataString();
            if (normalMapPath != null && normalMapPath.length() > 0) {
                material.setNormalMapPath(modelDir + File.separator + new File(normalMapPath).getName());
                textureCache.createTexture(material.getNormalMapPath());
            }
            return material;
        }
    }
    ...
}

このprocessMeshメソッドでは、タンジェントとバイタンジェントのデータもロードする必要があります。

public class ModelLoader {
    ...
    private static Mesh processMesh(AIMesh aiMesh) {
        ...
        float[] tangents = processTangents(aiMesh, normals);
        float[] bitangents = processBitangents(aiMesh, normals);
        ...
        return new Mesh(vertices, normals, tangents, bitangents, textCoords, indices);
    }
    ...
}

processTangentsおよびメソッドは、processBitangents法線をロードするものと非常によく似ています。

public class ModelLoader {
    ...
    private static float[] processBitangents(AIMesh aiMesh, float[] normals) {

        AIVector3D.Buffer buffer = aiMesh.mBitangents();
        float[] data = new float[buffer.remaining() * 3];
        int pos = 0;
        while (buffer.remaining() > 0) {
            AIVector3D aiBitangent = buffer.get();
            data[pos++] = aiBitangent.x();
            data[pos++] = aiBitangent.y();
            data[pos++] = aiBitangent.z();
        }

        // Assimp may not calculate tangents with models that do not have texture coordinates. Just create empty values
        if (data.length == 0) {
            data = new float[normals.length];
        }
        return data;
    }
    ...
    private static float[] processTangents(AIMesh aiMesh, float[] normals) {

        AIVector3D.Buffer buffer = aiMesh.mTangents();
        float[] data = new float[buffer.remaining() * 3];
        int pos = 0;
        while (buffer.remaining() > 0) {
            AIVector3D aiTangent = buffer.get();
            data[pos++] = aiTangent.x();
            data[pos++] = aiTangent.y();
            data[pos++] = aiTangent.z();
        }

        // Assimp may not calculate tangents with models that do not have texture coordinates. Just create empty values
        if (data.length == 0) {
            data = new float[normals.length];
        }
        return data;
    }
    ...
}

ご覧のとおり、新しいデータを保持するためにクラスも変更する必要がありMeshますMaterial。Meshクラスから始めましょう:

public class Mesh {
    ...
    public Mesh(float[] positions, float[] normals, float[] tangents, float[] bitangents, float[] textCoords, int[] indices) {
        try (MemoryStack stack = MemoryStack.stackPush()) {
            ...
            // Tangents VBO
            vboId = glGenBuffers();
            vboIdList.add(vboId);
            FloatBuffer tangentsBuffer = stack.callocFloat(tangents.length);
            tangentsBuffer.put(0, tangents);
            glBindBuffer(GL_ARRAY_BUFFER, vboId);
            glBufferData(GL_ARRAY_BUFFER, tangentsBuffer, GL_STATIC_DRAW);
            glEnableVertexAttribArray(2);
            glVertexAttribPointer(2, 3, GL_FLOAT, false, 0, 0);

            // Bitangents VBO
            vboId = glGenBuffers();
            vboIdList.add(vboId);
            FloatBuffer bitangentsBuffer = stack.callocFloat(bitangents.length);
            bitangentsBuffer.put(0, bitangents);
            glBindBuffer(GL_ARRAY_BUFFER, vboId);
            glBufferData(GL_ARRAY_BUFFER, bitangentsBuffer, GL_STATIC_DRAW);
            glEnableVertexAttribArray(3);
            glVertexAttribPointer(3, 3, GL_FLOAT, false, 0, 0);

            // Texture coordinates VBO
            ...
            glEnableVertexAttribArray(4);
            glVertexAttribPointer(4, 2, GL_FLOAT, false, 0, 0);
            ...
        }
    }
    ...
}

タンジェント データとバイタンジェント データ (法線データと同様の構造に従う) 用に 2 つの新しい VBO を作成し、テクスチャ座標 VBO の位置を更新する必要があります。

クラスにはMaterial、法線マッピング テクスチャ パスへのパスを含める必要があります。

public class Material {
    ...
    private String normalMapPath;
    ...
    public String getNormalMapPath() {
        return normalMapPath;
    }
    ...
    public void setNormalMapPath(String normalMapPath) {
        this.normalMapPath = normalMapPath;
    }
    ...
}

次に、シーンの頂点シェーダー ( scene.vert)から始めて、シェーダーを変更する必要があります。

#version 330

layout (location=0) in vec3 position;
layout (location=1) in vec3 normal;
layout (location=2) in vec3 tangent;
layout (location=3) in vec3 bitangent;
layout (location=4) in vec2 texCoord;

out vec3 outPosition;
out vec3 outNormal;
out vec3 outTangent;
out vec3 outBitangent;
out vec2 outTextCoord;

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

void main()
{
    mat4 modelViewMatrix = viewMatrix * modelMatrix;
    vec4 mvPosition =  modelViewMatrix * vec4(position, 1.0);
    gl_Position   = projectionMatrix * mvPosition;
    outPosition   = mvPosition.xyz;
    outNormal     = normalize(modelViewMatrix * vec4(normal, 0.0)).xyz;
    outTangent    = normalize(modelViewMatrix * vec4(tangent, 0)).xyz;
    outBitangent  = normalize(modelViewMatrix * vec4(bitangent, 0)).xyz;
    outTextCoord  = texCoord;
}

ご覧のとおり、bitangent と tangent に関連付けられた新しい入力データを定義する必要があります。法線を処理したのと同じ方法でこれらの要素を変換し、そのデータを入力としてフラグメント シェーダーに渡します ( scene.frag)。

#version 330
...
in vec3 outTangent;
in vec3 outBitangent;
...
struct Material
{
    vec4 ambient;
    vec4 diffuse;
    vec4 specular;
    float reflectance;
    int hasNormalMap;
};
...
uniform sampler2D normalSampler;
...

頂点シェーダーからの新しい入力を定義することから始めます。Materialこれには、使用可能な法線マップがあるかどうかを通知する構造体の追加要素が含まれます ( hasNormalMap)。また、法線マップ テクスチャの新しいユニフォームを追加します ( normalSampler))。次のステップは、法線マップ テクスチャに基づいて法線を更新する関数を定義することです。

...
...
vec3 calcNormal(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textCoords) {
    mat3 TBN = mat3(tangent, bitangent, normal);
    vec3 newNormal = texture(normalSampler, textCoords).rgb;
    newNormal = normalize(newNormal * 2.0 - 1.0);
    newNormal = normalize(TBN * newNormal);
    return newNormal;
}

void main() {
    vec4 text_color = texture(txtSampler, outTextCoord);
    vec4 ambient = calcAmbient(ambientLight, text_color + material.ambient);
    vec4 diffuse = text_color + material.diffuse;
    vec4 specular = text_color + material.specular;

    vec3 normal = outNormal;
    if (material.hasNormalMap > 0) {
        normal = calcNormal(outNormal, outTangent, outBitangent, outTextCoord);
    }

    vec4 diffuseSpecularComp = calcDirLight(diffuse, specular, dirLight, outPosition, normal);

    for (int i=0; i<MAX_POINT_LIGHTS; i++) {
        if (pointLights[i].intensity > 0) {
            diffuseSpecularComp += calcPointLight(diffuse, specular, pointLights[i], outPosition, normal);
        }
    }

    for (int i=0; i<MAX_SPOT_LIGHTS; i++) {
        if (spotLights[i].pl.intensity > 0) {
            diffuseSpecularComp += calcSpotLight(diffuse, specular, spotLights[i], outPosition, normal);
        }
    }
    fragColor = ambient + diffuseSpecularComp;

    if (fog.activeFog == 1) {
        fragColor = calcFog(outPosition, fragColor, fog, ambientLight.color, dirLight);
    }
}

このcalcNormal関数は次のパラメータを取ります。

  • 頂点法線。
  • 頂点接線。
  • 頂点バイタンジェント。
  • テクスチャ座標。
    その関数で最初に行うことは、TBN 行列を計算することです。その後、法線マップ テクスチャから法線値を取得し、TBN マトリックスを使用して接線空間からビュー空間に渡します。取得する色は通常の座標ですが、RGB 値として保存されるため、範囲 [0, 1] に含まれることを思い出してください。[-1, 1] の範囲になるように変換する必要があるため、2 を掛けて 1 を引くだけです。
    最後に、マテリアルが法線マップ テクスチャを定義する場合にのみ、その関数を使用します。

SceneRenderシェーダーで使用する新しい法線を作成して使用するには、クラスも変更する必要があります。

public class SceneRender {
    ...
    private void createUniforms() {
        ...
        uniformsMap.createUniform("normalSampler");
        ...
        uniformsMap.createUniform("material.hasNormalMap");
        ...
    }
    public void render(Scene scene) {
        ...
        uniformsMap.setUniform("normalSampler", 1);
        ...
        for (Model model : models) {
            ...
            for (Material material : model.getMaterialList()) {
                ...
                String normalMapPath = material.getNormalMapPath();
                boolean hasNormalMapPath = normalMapPath != null;
                uniformsMap.setUniform("material.hasNormalMap", hasNormalMapPath ? 1 : 0);
                ...
                if (hasNormalMapPath) {
                    Texture normalMapTexture = textureCache.getTexture(normalMapPath);
                    glActiveTexture(GL_TEXTURE1);
                    normalMapTexture.bind();
                }
                ...
            }
        }
        ...
    }
    ...    
}

Main最後のステップは、この効果を示すためにクラスを更新することです。法線マップが関連付けられている場合と関連付けられていない場合の 2 つのクワッドをロードします。また、左矢印と右矢印を使用して光の角度を制御し、効果を示します。

public class Main implements IAppLogic {
    ...
    public static void main(String[] args) {
        ...
        Engine gameEng = new Engine("chapter-14", new Window.WindowOptions(), main);
        ...
    }
    ...
    public void init(Window window, Scene scene, Render render) {
        String wallNoNormalsModelId = "quad-no-normals-model";
        Model quadModelNoNormals = ModelLoader.loadModel(wallNoNormalsModelId, "resources/models/wall/wall_nonormals.obj",
                scene.getTextureCache());
        scene.addModel(quadModelNoNormals);

        Entity wallLeftEntity = new Entity("wallLeftEntity", wallNoNormalsModelId);
        wallLeftEntity.setPosition(-3f, 0, 0);
        wallLeftEntity.setScale(2.0f);
        wallLeftEntity.updateModelMatrix();
        scene.addEntity(wallLeftEntity);

        String wallModelId = "quad-model";
        Model quadModel = ModelLoader.loadModel(wallModelId, "resources/models/wall/wall.obj",
                scene.getTextureCache());
        scene.addModel(quadModel);

        Entity wallRightEntity = new Entity("wallRightEntity", wallModelId);
        wallRightEntity.setPosition(3f, 0, 0);
        wallRightEntity.setScale(2.0f);
        wallRightEntity.updateModelMatrix();
        scene.addEntity(wallRightEntity);

        SceneLights sceneLights = new SceneLights();
        sceneLights.getAmbientLight().setIntensity(0.2f);
        DirLight dirLight = sceneLights.getDirLight();
        dirLight.setPosition(1, 1, 0);
        dirLight.setIntensity(1.0f);
        scene.setSceneLights(sceneLights);

        Camera camera = scene.getCamera();
        camera.moveUp(5.0f);
        camera.addRotation((float) Math.toRadians(90), 0);

        lightAngle = -35;
    }
        ...
    public void input(Window window, Scene scene, long diffTimeMillis, boolean inputConsumed) {
        float move = diffTimeMillis * MOVEMENT_SPEED;
        Camera camera = scene.getCamera();
        if (window.isKeyPressed(GLFW_KEY_W)) {
            camera.moveForward(move);
        } else if (window.isKeyPressed(GLFW_KEY_S)) {
            camera.moveBackwards(move);
        }
        if (window.isKeyPressed(GLFW_KEY_A)) {
            camera.moveLeft(move);
        } else if (window.isKeyPressed(GLFW_KEY_D)) {
            camera.moveRight(move);
        }
        if (window.isKeyPressed(GLFW_KEY_LEFT)) {
            lightAngle -= 2.5f;
            if (lightAngle < -90) {
                lightAngle = -90;
            }
        } else if (window.isKeyPressed(GLFW_KEY_RIGHT)) {
            lightAngle += 2.5f;
            if (lightAngle > 90) {
                lightAngle = 90;
            }
        }

        MouseInput mouseInput = window.getMouseInput();
        if (mouseInput.isRightButtonPressed()) {
            Vector2f displVec = mouseInput.getDisplVec();
            camera.addRotation((float) Math.toRadians(-displVec.x * MOUSE_SENSITIVITY), (float) Math.toRadians(-displVec.y * MOUSE_SENSITIVITY));
        }

        SceneLights sceneLights = scene.getSceneLights();
        DirLight dirLight = sceneLights.getDirLight();
        double angRad = Math.toRadians(lightAngle);
        dirLight.getDirection().x = (float) Math.sin(angRad);
        dirLight.getDirection().y = (float) Math.cos(angRad);
    }
    ...
}

結果を次の図に示します。
ご覧のとおり、通常のテクスチャが適用されたクワッドは、よりボリュームのある印象を与えます。本質的には、他のクワッドと同じように平らな面ですが、光がどのように反射するかを見ることができます。

Java 3D LWJGL Gitbook ~第13章 霧~

第13章 霧

この章では、ゲーム エンジンでフォグ エフェクトを作成する方法を確認します。その効果を使用して、遠くのオブジェクトが薄暗くなり、濃霧に消えていくように見える様子をシミュレートします。

コンセプト

まず、フォグを定義する属性を調べてみましょう。1つ目は霧の色です。現実の世界では、霧は灰色ですが、この効果を使用して、さまざまな色の霧が侵入する広い領域をシミュレートできます。アトリビュートはフォグの密度です。

したがって、フォグ エフェクトを適用するには、3D シーン オブジェクトがカメラから遠く離れている限り、フォグ カラーにフェードする方法を見つける必要があります。カメラに近いオブジェクトは霧の影響を受けませんが、遠くにあるオブジェクトは区別できません。そのため、その効果をシミュレートするために、フォグ カラーと各フラグメント カラーをブレンドするために使用できる係数を計算できる必要があります。その要因は、カメラまでの距離に依存する必要があります。

その要因を呼びましょう
フォググファクター
、その範囲を 0 から 1 に設定します。
フォググファクター
が 1 の場合、オブジェクトがフォグの影響を受けない、つまり近くのオブジェクトであることを意味します。とき
フォググファクター
値が 0 の場合、オブジェクトが完全にフォグに隠れることを意味します。

したがって、フォグ カラーの計算に必要な式は次のとおりです。

フォグ カラーの計算に必要な式

finalColor = ( 1 fogfactor ) fogColor + fogFactor fragmentColor

霧効果を適用した結果の色です。
フォグ カラーとフラグメント カラーのブレンド方法を制御するパラメータです。基本的にオブジェクトの可視性を制御します。
霧の色です。
フォグ効果を適用していないフラグメントの色です。
次に、計算方法を見つける必要があります
距離にもよる。さまざまなモデルを選択できますが、最初のモデルは線形モデルを使用することです。これは、距離が与えられると、fogFactor 値を直線的に変化させるモデルです。

線形モデルは、次のパラメーターによって定義できます。

: フォグ エフェクトが適用され始める距離。fogStart
: フォグ エフェクトが最大値に達する距離。fogFinish
: カメラまでの距離。distance

fogFactor = ( fofFinish distace ) ( fogFinish fogStart )

以下の距離にあるオブジェクトの場合
単に設定するだけです

. 次のグラフは、
距離で変わります。

線形モデルは計算が簡単ですが、あまり現実的ではなく、霧の密度が考慮されていません。実際には、霧はより滑らかに成長する傾向があります。したがって、次の適切なモデルは指数モデルです。そのモデルの式は次のとおりです。
作用する新しい変数は次のとおりです。

フォグの厚さまたは密度をモデル化します。
これは、霧が距離とともに増加する速度を制御するために使用されます。
次の図は、指数のさまざまな値に対する上記の式の 2 つのグラフを示しています (青い線は $$2$$、

このコードでは、指数の値を 2 に設定する数式を使用します (別の値を使用するように例を簡単に変更できます)。

実装

理論が説明されたので、それを実践することができます。scene.frag必要なすべての変数がそこにあるので、シーン フラグメント シェーダー ( ) にエフェクトを実装します。フォグ属性をモデル化する構造体を定義することから始めます。

基本的な処理は以下の通りです。

  1. Fogクラスを作成
  2. Fogモデルのロード
  3. シーンへの描画を行う

今回の「フォグ」に関しては、エフェクトという形のモデル?を追加しているので、シェーダーとのやり取りが多くなっています。

...
struct Fog
{
    int activeFog;
    vec3 color;
    float density;
};
...

このactiveアトリビュートは、フォグ エフェクトを有効または無効にするために使用されます。フォグは、 という名前の別のユニフォームを介してシェーダーに渡されfogます。

...
uniform Fog fog;
...

calcFogこのように定義されているという名前の関数を作成します。

...
vec4 calcFog(vec3 pos, vec4 color, Fog fog, vec3 ambientLight, DirLight dirLight) {
    vec3 fogColor = fog.color * (ambientLight + dirLight.color * dirLight.intensity);
    float distance = length(pos);
    float fogFactor = 1.0 / exp((distance * fog.density) * (distance * fog.density));
    fogFactor = clamp(fogFactor, 0.0, 1.0);

    vec3 resultColor = mix(fogColor, color.xyz, fogFactor);
    return vec4(resultColor.xyz, color.w);
}
...

ご覧のとおり、最初に頂点までの距離を計算します。頂点座標はpos変数で定義されており、長さを計算するだけです。次に、指数が 2 の指数モデルを使用してフォグ ファクターを計算します (これは、2 倍するのと同じです)。fogFactor間の範囲にクランプします
0と1
機能を使用しmixます。GLSL では、mix関数はフォグ カラーとフラグメント カラー (変数で定義color) をブレンドするために使用されます。これは、次の方程式を適用することと同じです。

resultColor = ( 1 fogFacor ) fog . color + fogFacor color

また、元の色の透明度である w コンポーネントも保持します。フラグメントはその透過性レベルを維持する必要があるため、このコンポーネントが影響を受けることは望ましくありません。

フラグメント シェーダーの最後で、すべてのライト エフェクトを適用した後、フォグがアクティブな場合は、返された値をフラグメント カラーに割り当てるだけです。

...
    if (fog.activeFog == 1) {
        fragColor = calcFog(outPosition, fragColor, fog, ambientLight.color, dirLight);
    }
...

Fogフォグ属性を含む別の POJO (Plain Old Java Object)という名前の新しいクラスも作成します。

package org.lwjglb.engine.scene;

import org.joml.Vector3f;

public class Fog {

    private boolean active;
    private Vector3f color;
    private float density;

    public Fog() {
        active = false;
        color = new Vector3f();
    }

    public Fog(boolean active, Vector3f color, float density) {
        this.color = color;
        this.density = density;
        this.active = active;
    }

    public Vector3f getColor() {
        return color;
    }

    public float getDensity() {
        return density;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public void setColor(Vector3f color) {
        this.color = color;
    }

    public void setDensity(float density) {
        this.density = density;
    }
}

Fogクラスにインスタンスを追加しますScene。

public class Scene {
    ...
    private Fog fog;
    ...
    public Scene(int width, int height) {
        ...
        fog = new Fog();
    }
    ...
    public Fog getFog() {
        return fog;
    }
    ...
    public void setFog(Fog fog) {
        this.fog = fog;
    }
    ...
}

ここで、これらすべての要素をクラスに設定する必要があります。最初に、構造SceneRenderに均一な値を設定します。Fog

public class SceneRender {
    ...
    private void createUniforms() {
        ...
        uniformsMap.createUniform("fog.activeFog");
        uniformsMap.createUniform("fog.color");
        uniformsMap.createUniform("fog.density");
    }
    ...
}

このrenderメソッドでは、最初にブレンドを有効にしてからFogユニフォームを設定する必要があります。

public class SceneRender {
    ...
     public void render(Scene scene) {
        glEnable(GL_BLEND);
        glBlendEquation(GL_FUNC_ADD);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        shaderProgram.bind();
        ...
        Fog fog = scene.getFog();
        uniformsMap.setUniform("fog.activeFog", fog.isActive() ? 1 : 0);
        uniformsMap.setUniform("fog.color", fog.getColor());
        uniformsMap.setUniform("fog.density", fog.getDensity());
        ...
        shaderProgram.unbind();
        glDisable(GL_BLEND);
    }
    ...
}

最後に、Main霧を設定するようにクラスを変更し、霧の効果を示すためにスケーリングされた地形として単一のクワッドを使用します。

public class Main implements IAppLogic {
    ...
    public static void main(String[] args) {
        ...
        Engine gameEng = new Engine("chapter-13", new Window.WindowOptions(), main);
        ...
    }
    ...
    public void init(Window window, Scene scene, Render render) {
        String terrainModelId = "terrain";
        Model terrainModel = ModelLoader.loadModel(terrainModelId, "resources/models/terrain/terrain.obj",
                scene.getTextureCache());
        scene.addModel(terrainModel);
        Entity terrainEntity = new Entity("terrainEntity", terrainModelId);
        terrainEntity.setScale(100.0f);
        terrainEntity.updateModelMatrix();
        scene.addEntity(terrainEntity);

        SceneLights sceneLights = new SceneLights();
        AmbientLight ambientLight = sceneLights.getAmbientLight();
        ambientLight.setIntensity(0.5f);
        ambientLight.setColor(0.3f, 0.3f, 0.3f);

        DirLight dirLight = sceneLights.getDirLight();
        dirLight.setPosition(0, 1, 0);
        dirLight.setIntensity(1.0f);
        scene.setSceneLights(sceneLights);

        SkyBox skyBox = new SkyBox("resources/models/skybox/skybox.obj", scene.getTextureCache());
        skyBox.getSkyBoxEntity().setScale(50);
        scene.setSkyBox(skyBox);

        scene.setFog(new Fog(true, new Vector3f(0.5f, 0.5f, 0.5f), 0.95f));

        scene.getCamera().moveUp(0.1f);
    }
    ...
    public void update(Window window, Scene scene, long diffTimeMillis) {
        // Nothing to be done here
    }
}

強調すべき重要な点の 1 つは、霧の色を賢く選択する必要があるということです。スカイボックスがなく固定色の背景がある場合、これはさらに重要です。霧の色をクリアの色と同じになるように設定する必要があります。スカイボックスをレンダリングするコードのコメントを外してサンプルを再実行すると、このような結果が得られます。

ようなものが表示されるはずです。

Java 3D LWJGL Gitbook~ 第12章 スカイボックス ~

第12章 スカイボックス

この章では、スカイ ボックスの作成方法について説明します。スカイボックスを使用すると、背景を設定して、3D 世界がより広いという錯覚を与えることができます。その背景はカメラの位置を包み込み、空間全体を覆います。ここで使用するテクニックは、3D シーンの周りに表示される大きな立方体を作成することです。つまり、カメラ位置の中心が立方体の中心になります。その立方体の側面は、画像が連続した風景のように見える方法でマッピングされる丘、青い空、雲のテクスチャでラップされます。

参照するドキュメントとプログラムソースへのリンクは以下になります。

サンプルコードの実行結果

スカイボックス

次の図は、スカイボックスの概念を示しています。

スカイ ボックスを作成するプロセスは、次の手順に要約できます。

・大きなキューブを作成します。
エッジのない巨大な風景を見ているような錯覚を与えるテクスチャを適用します。
・立方体をレンダリングして、側面が遠くにあり、原点がカメラの中心にくるようにします。
SkyBoxスカイ ボックス キューブ (テクスチャ付き) とテクスチャ キャッシュへの参照を含む 3D モデルへのパスを受け取るコンストラクタで名前を付けた新しいクラスを作成することから始めます。このクラスはそのモデルをロードし、そのモデルにEntity関連付けられたインスタンスを作成します。SkyBoxクラスの定義は以下の通りです。

package org.lwjglb.engine.scene;

import org.lwjglb.engine.graph.*;

public class SkyBox {

    private Entity skyBoxEntity;
    private Model skyBoxModel;

    public SkyBox(String skyBoxModelPath, TextureCache textureCache) {
        skyBoxModel = ModelLoader.loadModel("skybox-model", skyBoxModelPath, textureCache);
        skyBoxEntity = new Entity("skyBoxEntity-entity", skyBoxModel.getId());
    }

    public Entity getSkyBoxEntity() {
        return skyBoxEntity;
    }

    public Model getSkyBoxModel() {
        return skyBoxModel;
    }
}

SkyBoxクラスへの参照をクラスに保存しますScene。

public class Scene {
    ...
    private SkyBox skyBox;
    ...
    public SkyBox getSkyBox() {
        return skyBox;
    }
    ...
    public void setSkyBox(SkyBox skyBox) {
        this.skyBox = skyBox;
    }
    ...
}

次のステップは、スカイ ボックス用の頂点シェーダーとフラグメント シェーダーの別のセットを作成することです。しかし、既にあるシーン シェーダーを再利用してみませんか? 答えは、実際には、必要なシェーダーはそれらのシェーダーの簡略化されたバージョンであるということです。たとえば、スカイ ボックスにはライトを適用しません。以下に、スカイ ボックスの頂点シェーダーを示します ( skybox.vert)。

#version 330

layout (location=0) in vec3 position;
layout (location=1) in vec3 normal;
layout (location=2) in vec2 texCoord;

out vec2 outTextCoord;

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

void main()
{
    gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0);
    outTextCoord = texCoord;
}

まだモデル マトリックスを使用していることがわかります。スカイボックスをスケーリングするため、モデル マトリックスが必要です。開始時にスカイ ボックスをモデル化する立方体のサイズを大きくし、モデルとビュー マトリックスを乗算する必要がない他の実装がいくつか見られる場合があります。このアプローチを選択したのは、より柔軟で、実行時にスカイボックスのサイズを変更できるためですが、必要に応じて他のアプローチに簡単に切り替えることができます。

フラグメント シェーダー ( skybox.frag) も非常に単純で、テクスチャまたは拡散色から色を取得するだけです。

#version 330

in vec2 outTextCoord;
out vec4 fragColor;

uniform vec4 diffuse;
uniform sampler2D txtSampler;
uniform int hasTexture;

void main()
{
    if (hasTexture == 1) {
        fragColor = texture(txtSampler, outTextCoord);
    } else {
        fragColor = diffuse;
    }
}

SkyBoxRenderこれらのシェーダーを使用してレンダリングを実行する名前の新しいクラスを作成します。クラスは、シェーダー プログラムを作成し、必要なユニフォームをセットアップすることから始まります。

package org.lwjglb.engine.graph;

import org.joml.Matrix4f;
import org.lwjglb.engine.scene.*;

import java.util.*;

import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.glBindVertexArray;

public class SkyBoxRender {

    private ShaderProgram shaderProgram;

    private UniformsMap uniformsMap;

    private Matrix4f viewMatrix;

    public SkyBoxRender() {
        List<ShaderProgram.ShaderModuleData> shaderModuleDataList = new ArrayList<>();
        shaderModuleDataList.add(new ShaderProgram.ShaderModuleData("resources/shaders/skybox.vert", GL_VERTEX_SHADER));
        shaderModuleDataList.add(new ShaderProgram.ShaderModuleData("resources/shaders/skybox.frag", GL_FRAGMENT_SHADER));
        shaderProgram = new ShaderProgram(shaderModuleDataList);
        viewMatrix = new Matrix4f();
        createUniforms();
    }
    ...
}

次のステップでは、グローバルなレンダリング メソッドで呼び出されるスカイボックスの新しいレンダリング メソッドを作成します。

public class SkyBoxRender {
    ...
    public void render(Scene scene) {
        SkyBox skyBox = scene.getSkyBox();
        if (skyBox == null) {
            return;
        }
        shaderProgram.bind();

        uniformsMap.setUniform("projectionMatrix", scene.getProjection().getProjMatrix());
        viewMatrix.set(scene.getCamera().getViewMatrix());
        viewMatrix.m30(0);
        viewMatrix.m31(0);
        viewMatrix.m32(0);
        uniformsMap.setUniform("viewMatrix", viewMatrix);
        uniformsMap.setUniform("txtSampler", 0);

        Model skyBoxModel = skyBox.getSkyBoxModel();
        Entity skyBoxEntity = skyBox.getSkyBoxEntity();
        TextureCache textureCache = scene.getTextureCache();
        for (Material material : skyBoxModel.getMaterialList()) {
            Texture texture = textureCache.getTexture(material.getTexturePath());
            glActiveTexture(GL_TEXTURE0);
            texture.bind();

            uniformsMap.setUniform("diffuse", material.getDiffuseColor());
            uniformsMap.setUniform("hasTexture", texture.getTexturePath().equals(TextureCache.DEFAULT_TEXTURE) ? 0 : 1);

            for (Mesh mesh : material.getMeshList()) {
                glBindVertexArray(mesh.getVaoId());

                uniformsMap.setUniform("modelMatrix", skyBoxEntity.getModelMatrix());
                glDrawElements(GL_TRIANGLES, mesh.getNumVertices(), GL_UNSIGNED_INT, 0);
            }
        }

        glBindVertexArray(0);

        shaderProgram.unbind();
    }
}

関連するユニフォームにそのデータをロードする前に、ビュー マトリックスを変更していることがわかります。カメラを動かすとき、実際に行っていることは世界全体を動かしていることを忘れないでください。したがって、ビュー マトリックスをそのまま乗算すると、カメラが移動するとスカイボックスが移動します。しかし、これは必要ありません。(0, 0, 0) の原点座標に貼り付けたいのです。これは、平行移動の増分を含むビュー マトリックスの部分 ( m30、m31およびm32コンポーネント)。スカイ ボックスは原点に固定する必要があるため、ビュー マトリックスの使用をまったく避けることができると考えるかもしれません。その場合、スカイボックスがカメラと一緒に回転しないことがわかりますが、これは私たちが望んでいるものではありません。回転する必要がありますが、平行移動は必要ありません。スカイボックスをレンダリングするには、ユニフォームをセットアップし、スカイ ボックスに関連付けられた立方体をレンダリングします。

クラスでは、Renderクラスをインスタンス化しSkyBoxRender、render メソッドを呼び出すだけです。

public class Render {
    ...
    private SkyBoxRender skyBoxRender;
    ...

    public Render(Window window) {
        ...
        skyBoxRender = new SkyBoxRender();
    }

    public void render(Window window, Scene scene) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glViewport(0, 0, window.getWidth(), window.getHeight());

        skyBoxRender.render(scene);
        sceneRender.render(scene);
        guiRender.render(scene);
    }
    ...
}

スカイ ボックスを最初にレンダリングしていることがわかります。これは、シーンに透明度のある 3D モデルがある場合、それらを (黒い背景ではなく) スカイボックスとブレンドしたいという事実によるものです。

最後に、このMainクラスでは、シーンにスカイ ボックスを設定し、タイルのセットを作成して、無限の地形の錯覚を与えます。カメラの位置に合わせて移動するタイルのチャンクが常に表示されるように設定します。

public class Main implements IAppLogic {
    ...
    private static final int NUM_CHUNKS = 4;

    private Entity[][] terrainEntities;

    public static void main(String[] args) {
        ...
        Engine gameEng = new Engine("chapter-12", new Window.WindowOptions(), main);
        ...
    }
    ...

    @Override
    public void init(Window window, Scene scene, Render render) {
        String quadModelId = "quad-model";
        Model quadModel = ModelLoader.loadModel("quad-model", "resources/models/quad/quad.obj",
                scene.getTextureCache());
        scene.addModel(quadModel);

        int numRows = NUM_CHUNKS * 2 + 1;
        int numCols = numRows;
        terrainEntities = new Entity[numRows][numCols];
        for (int j = 0; j < numRows; j++) {
            for (int i = 0; i < numCols; i++) {
                Entity entity = new Entity("TERRAIN_" + j + "_" + i, quadModelId);
                terrainEntities[j][i] = entity;
                scene.addEntity(entity);
            }
        }

        SceneLights sceneLights = new SceneLights();
        sceneLights.getAmbientLight().setIntensity(0.2f);
        scene.setSceneLights(sceneLights);

        SkyBox skyBox = new SkyBox("resources/models/skybox/skybox.obj", scene.getTextureCache());
        skyBox.getSkyBoxEntity().setScale(50);
        scene.setSkyBox(skyBox);

        scene.getCamera().moveUp(0.1f);

        updateTerrain(scene);
    }

    @Override
    public void input(Window window, Scene scene, long diffTimeMillis, boolean inputConsumed) {
        float move = diffTimeMillis * MOVEMENT_SPEED;
        Camera camera = scene.getCamera();
        if (window.isKeyPressed(GLFW_KEY_W)) {
            camera.moveForward(move);
        } else if (window.isKeyPressed(GLFW_KEY_S)) {
            camera.moveBackwards(move);
        }
        if (window.isKeyPressed(GLFW_KEY_A)) {
            camera.moveLeft(move);
        } else if (window.isKeyPressed(GLFW_KEY_D)) {
            camera.moveRight(move);
        }

        MouseInput mouseInput = window.getMouseInput();
        if (mouseInput.isRightButtonPressed()) {
            Vector2f displVec = mouseInput.getDisplVec();
            camera.addRotation((float) Math.toRadians(-displVec.x * MOUSE_SENSITIVITY), (float) Math.toRadians(-displVec.y * MOUSE_SENSITIVITY));
        }
    }

    @Override
    public void update(Window window, Scene scene, long diffTimeMillis) {
        updateTerrain(scene);
    }
        public void updateTerrain(Scene scene) {
        int cellSize = 10;
        Camera camera = scene.getCamera();
        Vector3f cameraPos = camera.getPosition();
        int cellCol = (int) (cameraPos.x / cellSize);
        int cellRow = (int) (cameraPos.z / cellSize);

        int numRows = NUM_CHUNKS * 2 + 1;
        int numCols = numRows;
        int zOffset = -NUM_CHUNKS;
        float scale = cellSize / 2.0f;
        for (int j = 0; j < numRows; j++) {
            int xOffset = -NUM_CHUNKS;
            for (int i = 0; i < numCols; i++) {
                Entity entity = terrainEntities[j][i];
                entity.setScale(scale);
                entity.setPosition((cellCol + xOffset) * 2.0f, 0, (cellRow + zOffset) * 2.0f);
                entity.getModelMatrix().identity().scale(scale).translate(entity.getPosition());
                xOffset++;
            }
            zOffset++;
        }
    }
}

Java 3D LWJGL GitBook 〜Chapter11:ライト~

第11章 - ライト

この章では、3D ゲーム エンジンにライトを追加する方法を学習します。複雑さを除けば、膨大な量のコンピューター リソースが必要になるため、物理的に完全なライト モデルは実装しません。代わりに、適切な結果を提供する近似を実装します。フォン シェーディング (Bui Tuong Phong によって開発された) という名前のアルゴリズムを使用します。指摘すべきもう 1 つの重要な点は、ライトのみをモデル化し、それらのライトによって生成されるシャドウをモデル化しないことです (これは別の章で行います)。

参照するドキュメントとプログラムソースへのリンクは以下になります。

ライトの考え方(理論編)

はじめに、ライトの考え方に関しての記述があり、その後実装に関しての記述があります。

そして、「モデル読み込みの変更」の項目部分がとても重要に思えます。大まかに次のような変更を行っています。

  1. ライトクラスの作成=ライトのモデル(データクラス)を作成する
  2. Sceneクラスにライトクラスを格納する
  3. ModelLoader(3DModelの読み込みクラス)の変更
    ・法線データの読み込み
    ・アンビエント カラー、スペキュラ カラー、光沢係数を取得
  4. 上記の変更に伴い修正する必要があるクラスの修正

ImGuiに関して

このサンプルコードでは、ImGuiの実装部分はライトコントロールクラスに実装されています。
次のように、IGuiInstanceインターフェースを実装(implements)しているクラスがImGuiをコントロールするクラスになります。

class XXX implements IGuiInstance

そして、IAppLogicインターフェースの実装クラス=Mainクラスで入力があったときに何かしらの処理をする予定だと思いますが、このサンプルでは何も実装していませんでした。

サンプルプログラムの実行結果

いくつかの概念

始める前に、いくつかのライト タイプを定義しましょう。

  • ・ポイント ライト: このタイプのライトは、空間内の 1 点から全方向に均一に放出される光源をモデル化します。
  • ・スポット ライト: このタイプのライトは、空間内の 1 点から放射される光源をモデル化しますが、すべての方向に放射するのではなく、円錐に制限されます。
  • ・指向性ライト: このタイプのライトは、太陽から受け取る光をモデル化します。3D 空間内のすべてのオブジェクトは、特定の方向から来る平行* ・光線ライトに当てられます。オブジェクトが近くにあるか遠くにあるかに関係なく、すべてのレイ ライトは同じ角度でオブジェクトに影響を与えます。
  • ・環境光: このタイプの光は、空間のあらゆる場所から来て、すべてのオブジェクトを同じように照らします。

したがって、ライトをモデル化するには、ライトのタイプ、その位置、および色などのその他のパラメータを考慮する必要があります。もちろん、レイ ライトの影響を受けたオブジェクトが光を吸収および反射する方法も考慮する必要があります。

フォン シェーディング アルゴリズムは、モデルの各ポイント、つまりすべての頂点の光の効果をモデル化します。これがローカル イルミネーション シミュレーションと呼ばれる理由であり、このアルゴリズムが影を計算しない理由です。頂点が光をブロックするオブジェクトの背後にあるかどうかを考慮せずに、すべての頂点に適用される光を計算するだけです。 . 後の章でこの欠点を克服します。しかし、そのため、非常に優れた効果を提供するシンプルで高速なアルゴリズムです。ここでは、材料を深く考慮しない単純化したバージョンを使用します。

Phong アルゴリズムは、ライティングの 3 つのコンポーネントを考慮します。

3 つのコンポーネント

  • ・環境光: どこからでも来る光をモデル化します。これは、光が当たっていない領域を (必要な強度で) 照らすのに役立ちます。これは背景光のようなものです。
  • ・拡散反射率: 光源に面している表面がより明るいことを考慮します。
  • ・鏡面反射率: 研磨面または金属面で光がどのように反射するかをモデル化します。

最後に取得したいのは、フラグメントに割り当てられた色を掛けて、受ける光に応じてその色を明るくまたは暗く設定する係数です。コンポーネントに名前を付けましょう

つけた名前

  • A: アンビエント
  • D: 拡散反射光
  • S: スペキュラ

実際、これらのコンポーネントは色であり、各光コンポーネントが寄与する色コンポーネントです。これは、光コンポーネントがある程度の強度を提供するだけでなく、モデルの色を変更できるという事実によるものです。フラグメント シェーダーでは、その明るい色を元のフラグメント カラー (テクスチャまたはベース カラーから取得) で乗算するだけです。

アンビエント、ディフューズ、スペキュラー コンポーネントで使用される、同じマテリアルに異なる色を割り当てることもできます。したがって、これらのコンポーネントは、マテリアルに関連付けられた色によって調整されます。マテリアルにテクスチャがある場合は、コンポーネントごとに 1 つのテクスチャを使用します。

したがって、非テクスチャ マテリアルの最終的な色は次のようになります。

L = A anbientColor + D diffuseColor + S specularColor

テクスチャ マテリアルの最終的な色は次のようになります。

L = A textureColor + D textureColor + S textureColor

法線

法線は、ライトを操作するときの ket 要素です。まず定義しましょう。平面の法線は、長さが 1 に等しい平面に垂直なベクトルです。

上の図からわかるように、平面には 2 つの法線があります。どちらを使用する必要がありますか? 3D グラフィックスの法線は照明に使用されるため、光源に向けられた法線を選択する必要があります。言い換えれば、モデルの外面から突き出ている法線を選択する必要があります。

3D モデルがある場合、ポリゴン、この場合は三角形で構成されます。各三角形は 3 つの頂点で構成されます。三角形の法線ベクトルは、長さが 1 に等しい三角形の表面に垂直なベクトルになります。

頂点法線は特定の頂点に関連付けられており、周囲の三角形の法線の組み合わせです (もちろん、その長さは 1 です)。ここでは、3D メッシュの頂点モデルを確認できます (ウィキペディアから取得) 。

拡散反射率

拡散反射率について話しましょう。これは、光源に対して垂直に面している面が、より間接的な角度で光を受けている面よりも明るく見えるという事実をモデル化しています。これらのオブジェクトはより多くの光を受け取り、光の密度 (このように呼びましょう) が高くなります。

しかし、これをどのように計算するのでしょうか。ここで、まず法線の使用を開始します。前の図の 3 点の法線を描きましょう。ご覧のとおり、各ポイントの法線は、各ポイントの接平面に垂直なベクトルになります。光源から来る光線を描く代わりに、各点から光の点へのベクトルを描きます (つまり、反対方向)。

ご覧のとおり、に関連付けられている法線

、名前付き

P1, N1

等しい角度を持つ

P1, 0

光源を指すベクトルを使用します。その表面は光源に対して垂直であり、一番明るいポイントになります。

P1

関連付けられている法線

P2

、名前付き

N2

、光源を指すベクトルと約 30 度の角度を持っているため、より暗い黄褐色になるはずです。

P1, P3

. 最後に、関連付けられている法線

P3

、名前付き

N3

も光源を指すベクトルに平行ですが、2 つのベクトルは反対方向です。

P3

は、光源を指すベクトルと 180 度の角度を持ち、まったく光を取得しないはずです。
したがって、点に到達する光の強度を決定するための適切なアプローチがあるようです。これは、光源を指すベクトルで法線を形成する角度に関連しています。これをどのように計算できますか?

内積という算術演算

内積という算術演算を使用できます。この操作は 2 つのベクトルを取り、それらの間の角度が鋭角の場合は正の数値 (スカラー) を生成し、それらの間の角度が広い場合は負の数値を生成します。両方のベクトルが正規化されている場合、つまり両方の長さが 1 の場合、内積は次のようになります。

-1 と 1

両方のベクトルがまったく同じ方向 (角度) を向いている場合、内積は 1 になります。
); そうなる 0 両方のベクトルが正方形の角度を形成する場合、それは -1
両方のベクトルが反対方向を指している場合。2 つのベクトルを定義しましょう。

v1 と v2

、そしてみましょう

alpha

それらの間の角度になります。内積は次の式で定義されます。

両方のベクトルが正規化されている場合、それらの長さ、モジュールは 1 に等しいため、内積はそれらの間の角度の余弦に等しくなります。この操作を使用して、拡散反射率コンポーネントを計算します。

したがって、光源を指すベクトルを計算する必要があります。これをどのように行うのですか?各点の位置 (頂点の位置) と光源の位置があります。まず、両方の座標が同じ座標空間にある必要があります。簡単にするために、それらが両方ともワールド座標空間にあると仮定しましょう。これらの位置は、頂点位置 ($$VP$$) と光源 ($$VS$$) を指すベクトルの座標です。次の図に示します。

差し引くと

V

探しているベクトルを取得します

L

これで、光源を指すベクトルと法線の間の内積を計算できます。この積は、表面の明るさをモデル化するためにその関係を最初に提案した Johann Lambert にちなんで、Lambert 項と呼ばれます。

計算方法をまとめてみます。次の変数を定義します。

計算方法をまとめ

vPos: モデル ビュー空間座標での頂点の位置。

lPos: ビュー空間座標でのライトの位置。

intensity: 光の強度 (0 から 1)。

lColor: 光の色。

normal: 頂点法線。

まず、現在の位置から光源を指すベクトルを計算する必要があります。

toLightDirection = lPos - vPos

. その操作の結果は正規化する必要があります。

次に、拡散係数 (スカラー) を計算する必要があります。

defuseFuctor = normal - toLightDirection

2 つのベクトル間の内積として計算されます。-1と1両方のベクトルを正規化する必要があります。色は間にある必要があります0と1
したがって、値がより低い場合0 に設定します。
最後に、拡散係数と光の強度によって光の色を調整する必要があります。

color = diffuseColor * lColor * diffuseColor * intensity

鏡面成分

鏡面反射光コンポーネントを検討する前に、まず光がどのように反射されるかを調べる必要があります。光が表面に当たると、その一部が吸収され、他の部分が反射されます。物理の授業で思い出したように、反射とは、光が物体から跳ね返ることです。

もちろん、表面は完全に磨かれているわけではなく、近くで見ると多くの欠陥が見られます。それに加えて、多くのレイ ライト (実際にはフォトン) があり、そのサーフェスに影響を与え、さまざまな角度で反射します。したがって、私たちが見ているのは、表面から反射された光線のようなものです。つまり、光は表面に当たると拡散します。これが、前に説明した拡散コンポーネントです。

しかし、金属などの研磨された表面に光が当たると、光の拡散が低下し、その表面に当たるとほとんどが反対方向に反射されます。

これはスペキュラ コンポーネントがモデル化するものであり、マテリアルの特性に依存します。鏡面反射率に関しては、カメラが適切な位置にある場合、つまり反射光が放出される領域にある場合にのみ、反射光が見えることに注意することが重要です。

鏡面反射の背後にあるメカニズムが説明されたので、その成分を計算する準備が整いました。まず、光源から頂点を指すベクトルが必要です。ディフューズ コンポーネントを計算していたとき、正反対の、光源を指すベクトルを計算しました。toLightDirectionですので、次のように計算してみましょう。

fromLightDirection = -(toLightDirection)

次に、衝撃による反射光を計算する必要があります。fromLightDirection
法線を考慮してサーフェスに挿入します。reflectまさにそれを行うGLSL 関数があります。そう、

reflectedLight = reflect(toLightSource, normal)

カメラを指すベクトルも必要です。名前を付けましょうcameraDirection
となり、カメラ位置と頂点位置の差として計算されます。

cameraDirection = cameraPos - vPos

. カメラ位置ベクトルと頂点位置は同じ座標系にある必要があり、結果のベクトルを正規化する必要があります。次の図は、これまでに計算した主なコンポーネントをスケッチしたものです。

次に、私たちが見る光の強度を計算する必要があります。specularFactor
. このコンポーネントは、cameraDirection
そしてそのreflectedLight
ベクトルは平行で同じ方向を指し、反対方向を指している場合はより低い値を取ります。これを計算するために、内積が再び役に立ちます。そう

specularFactor = cameraDirection - reflectedLight

. この値が間にあることのみが必要です0と1
それよりも低い場合0
に設定されます。
カメラが反射光円錐を指している場合、この光はより強くなければならないことも考慮する必要があります。これは、specularFactorという名前のパラメーターにspecularPower

specularFactor = specularFactor specularPower

最後に、マテリアルの反射率をモデル化する必要があります。これは、光が反射した場合の強度も変調します。これは、reflectance という名前の別のパラメーターで行われます。したがって、鏡面反射光コンポーネントの色は次のようになります。

specularColor * lColor * refrectance * specularFactor * intensity

減衰

これで、アンビエント ライトを使用してポイント ライトをモデル化するのに役立つ 3 つのコンポーネントを計算する方法がわかりました。しかし、オブジェクトが反射する光は光源からの距離に依存しないため、ライト モデルはまだ完全ではありません。つまり、光の減衰をシミュレートする必要があります。

減衰は、距離と光の関数です。光の強さは距離の二乗に反比例します。光はそのエネルギーを球の表面に沿って伝搬し、その半径は光が移動した距離と同じであり、球の表面はその半径の 2 乗に比例するため、この事実は簡単に視覚化できます。減衰係数は次の式で計算できます。

1.0 / (atConstant + atLinar * dist + atExponent * dist 2

減衰をシミュレートするには、その減衰係数を最終的な色で乗算するだけです。

指向性ライト

指向性照明は、すべて同じ方向から来る平行光線によってすべてのオブジェクトに当たります。太陽のように遠くにあるが強度の高い光源をモデル化します。

ディレクショナル ライトのもう 1 つの特徴は、減衰の影響を受けないことです。太陽光についてもう一度考えてみてください。太陽光線が当たったすべてのオブジェクトは、同じ強度で照らされます。太陽からの距離が非常に大きいため、オブジェクトの位置は関係ありません。実際、ディレクショナル ライトは無限遠に配置された光源としてモデル化されており、減衰の影響を受けた場合、どのオブジェクトにも影響しません (その色の寄与は0)。
それに加えて、ディレクショナル ライトは、ディフューズ コンポーネントとスペキュラ コンポーネントによっても構成されます。ポイント ライトとの唯一の違いは、位置ではなく方向があり、減衰の影響を受けないことです。ディレクショナル ライトの方向アトリビュートに戻り、3D ワールド全体の太陽の動きをモデリングしていると想像してください。北が増加する z 軸に向かって配置されていると仮定すると、次の図は、夜明け、日中、および夕暮れ時の光源の方向を示しています。

スポットライト

ここで、ポイント ライトに非常に似ているスポット ライトを実装しますが、放射されるライトは 3D コーンに制限されます。焦点から出る光、またはすべての方向に放射しないその他の光源をモデル化します。スポット ライトはポイント ライトと同じアトリビュートを持ちますが、円錐角度と円錐方向という 2 つの新しいパラメータが追加されています。

スポット ライトの影響は、いくつかの例外を除いて、ポイント ライトと同じ方法で計算されます。頂点位置から光源を指すベクトルがライト コーン内に含まれないポイントは、ポイント ライトの影響を受けません。

光円錐の内側にあるかどうかをどのように計算しますか? 光源からのベクトルとコーン方向ベクトル (どちらも正規化されています) の間で内積を再度行う必要があります。

間の内積:LとCベクトルは次の通りです。

L C = | L | | C | C o s ( α )

. スポット ライトの定義でカットオフ角度のコサインを格納すると、内積がその値よりも大きい場合、それがライト コーンの内側にあることがわかります (コサイン グラフを思い出してください。
角度はα、余弦は0、角度が小さいほど余弦が大きくなります)。1
2 番目の違いは、円錐ベクトルから遠く離れたポイントは、より少ない光を受け取ります。つまり、減衰が高くなります。これを計算するにはいくつかの方法があります。減衰に次の係数を掛けることにより、単純なアプローチを選択します。

1 ( 1 C o s ( α ) ) / ( 1 C o s ( c u t O f f A n g l e )

(フラグメント シェーダーでは角度ではなく、カットオフ角度のコサインを使用します。上記の式が 0 から 1 までの値を生成することを確認できます。角度がカットオフ角度と等しい場合は 0、角度が等しい場合は 1 です。 0)。

スポット ライトのサンプル

ライト クラスの実装

モデルというのはここでは、GetterとSetterを持っているデータクラスのことを指していると思ってよさそうです。

データクラスに関して

フィールド変数とGetter, Setterを持ったクラスは具体的に次のようなものです。
下のクラスは、「身長(tall)」というデータを持った、データクラスです。

public class Body {
    /** 整数で身長を表す */
    private int tall;
    /** Getter */
    public int getTall() { return tall;}
    /** Setter */
    public void setTall(int tall) {this.tall = tall}
}

PointLightクラス

まず、さまざまなタイプのライトをモデル化する一連のクラスを作成することから始めましょう。ポイント ライトをモデル化するクラスから始めます。

package org.lwjglb.engine.scene.lights;

import org.joml.Vector3f;

public class PointLight {

    private Attenuation attenuation;
    private Vector3f color;
    private float intensity;
    private Vector3f position;

    public PointLight(Vector3f color, Vector3f position, float intensity) {
        attenuation = new Attenuation(0, 0, 1);
        this.color = color;
        this.position = position;
        this.intensity = intensity;
    }

    public Attenuation getAttenuation() {
        return attenuation;
    }

    public Vector3f getColor() {
        return color;
    }

    public float getIntensity() {
        return intensity;
    }

    public Vector3f getPosition() {
        return position;
    }

    public void setAttenuation(Attenuation attenuation) {
        this.attenuation = attenuation;
    }

    public void setColor(Vector3f color) {
        this.color = color;
    }

    public void setColor(float r, float g, float b) {
        color.set(r, g, b);
    }

    public void setIntensity(float intensity) {
        this.intensity = intensity;
    }

    public void setPosition(float x, float y, float z) {
        position.set(x, y, z);
    }

    public static class Attenuation {

        private float constant;
        private float exponent;
        private float linear;

        public Attenuation(float constant, float linear, float exponent) {
            this.constant = constant;
            this.linear = linear;
            this.exponent = exponent;
        }

        public float getConstant() {
            return constant;
        }

        public float getExponent() {
            return exponent;
        }

        public float getLinear() {
            return linear;
        }

        public void setConstant(float constant) {
            this.constant = constant;
        }

        public void setExponent(float exponent) {
            this.exponent = exponent;
        }

        public void setLinear(float linear) {
            this.linear = linear;
        }
    }
}

ご覧のとおり、ポイント ライトは、色、強度、位置、および減衰モデルによって定義されます。
環境光は、色と強度だけで定義されます。

AmbientLightクラス

package org.lwjglb.engine.scene.lights;

import org.joml.Vector3f;

public class AmbientLight {

    private Vector3f color;

    private float intensity;

    public AmbientLight(float intensity, Vector3f color) {
        this.intensity = intensity;
        this.color = color;
    }

    public AmbientLight() {
        this(1.0f, new Vector3f(1.0f, 1.0f, 1.0f));
    }

    public Vector3f getColor() {
        return color;
    }

    public float getIntensity() {
        return intensity;
    }

    public void setColor(Vector3f color) {
        this.color = color;
    }

    public void setColor(float r, float g, float b) {
        color.set(r, g, b);
    }

    public void setIntensity(float intensity) {
        this.intensity = intensity;
    }
}

DirLightクラス

指向性ライトは次のように定義されます。

package org.lwjglb.engine.scene.lights;

import org.joml.Vector3f;

public class DirLight {

    private Vector3f color;

    private Vector3f direction;

    private float intensity;

    public DirLight(Vector3f color, Vector3f direction, float intensity) {
        this.color = color;
        this.direction = direction;
        this.intensity = intensity;
    }

    public Vector3f getColor() {
        return color;
    }

    public Vector3f getDirection() {
        return direction;
    }

    public float getIntensity() {
        return intensity;
    }

    public void setColor(Vector3f color) {
        this.color = color;
    }

    public void setColor(float r, float g, float b) {
        color.set(r, g, b);
    }

    public void setDirection(Vector3f direction) {
        this.direction = direction;
    }

    public void setIntensity(float intensity) {
        this.intensity = intensity;
    }

    public void setPosition(float x, float y, float z) {
        direction.set(x, y, z);
    }
}

SpotLightクラス

最後に、スポット ライトには、ポイント ライト リファレンスとライト コーン パラメータが含まれます。

package org.lwjglb.engine.scene.lights;

import org.joml.Vector3f;

public class SpotLight {

    private Vector3f coneDirection;
    private float cutOff;
    private float cutOffAngle;
    private PointLight pointLight;

    public SpotLight(PointLight pointLight, Vector3f coneDirection, float cutOffAngle) {
        this.pointLight = pointLight;
        this.coneDirection = coneDirection;
        this.cutOffAngle = cutOffAngle;
        setCutOffAngle(cutOffAngle);
    }

    public Vector3f getConeDirection() {
        return coneDirection;
    }

    public float getCutOff() {
        return cutOff;
    }

    public float getCutOffAngle() {
        return cutOffAngle;
    }

    public PointLight getPointLight() {
        return pointLight;
    }

    public void setConeDirection(float x, float y, float z) {
        coneDirection.set(x, y, z);
    }

    public void setConeDirection(Vector3f coneDirection) {
        this.coneDirection = coneDirection;
    }

    public final void setCutOffAngle(float cutOffAngle) {
        this.cutOffAngle = cutOffAngle;
        cutOff = (float) Math.cos(Math.toRadians(cutOffAngle));
    }

    public void setPointLight(PointLight pointLight) {
        this.pointLight = pointLight;
    }
}

SceneLightsクラス

すべてのライトは Scene クラスに格納されます。そのために、すべてのタイプのライトへの参照を格納する という名前の新しいクラスを作成しSceneLightsます (1 つのアンビエント ライト インスタンスと 1 つのディレクショナル ライトのみが必要であることに注意してください)。

package org.lwjglb.engine.scene.lights;

import org.joml.Vector3f;

import java.util.*;

public class SceneLights {

    private AmbientLight ambientLight;
    private DirLight dirLight;
    private List<PointLight> pointLights;
    private List<SpotLight> spotLights;

    public SceneLights() {
        ambientLight = new AmbientLight();
        pointLights = new ArrayList<>();
        spotLights = new ArrayList<>();
        dirLight = new DirLight(new Vector3f(1, 1, 1), new Vector3f(0, 1, 0), 1.0f);
    }

    public AmbientLight getAmbientLight() {
        return ambientLight;
    }

    public DirLight getDirLight() {
        return dirLight;
    }

    public List<PointLight> getPointLights() {
        return pointLights;
    }

    public List<SpotLight> getSpotLights() {
        return spotLights;
    }

    public void setSpotLights(List<SpotLight> spotLights) {
        this.spotLights = spotLights;
    }
}

Sceneクラス

クラスSceneLightsには次の参照があります。Scene

public class Scene {
    ...
    private SceneLights sceneLights;
    ...
    public SceneLights getSceneLights() {
        return sceneLights;
    }
    ...
    public void setSceneLights(SceneLights sceneLights) {
        this.sceneLights = sceneLights;
    }
}

モデル読み込みの変更

ModelLoaderクラスを次のように変更する必要があります。

・マテリアルのより多くのプロパティ、特にアンビエント カラー、スペキュラ カラー、光沢係数を取得します。
・各メッシュの法線データを読み込みます。
マテリアルのより多くのプロパティを取得するには、processMaterialメソッドを変更する必要があります。

ModelLoaderクラス

public class ModelLoader {
    ...
    private static Material processMaterial(AIMaterial aiMaterial, String modelDir, TextureCache textureCache) {
        Material material = new Material();
        try (MemoryStack stack = MemoryStack.stackPush()) {
            AIColor4D color = AIColor4D.create();

            int result = aiGetMaterialColor(aiMaterial, AI_MATKEY_COLOR_AMBIENT, aiTextureType_NONE, 0,
                    color);
            if (result == aiReturn_SUCCESS) {
                material.setAmbientColor(new Vector4f(color.r(), color.g(), color.b(), color.a()));
            }

            result = aiGetMaterialColor(aiMaterial, AI_MATKEY_COLOR_DIFFUSE, aiTextureType_NONE, 0,
                    color);
            if (result == aiReturn_SUCCESS) {
                material.setDiffuseColor(new Vector4f(color.r(), color.g(), color.b(), color.a()));
            }

            result = aiGetMaterialColor(aiMaterial, AI_MATKEY_COLOR_SPECULAR, aiTextureType_NONE, 0,
                    color);
            if (result == aiReturn_SUCCESS) {
                material.setSpecularColor(new Vector4f(color.r(), color.g(), color.b(), color.a()));
            }
            float reflectance = 0.0f;
            float[] shininessFactor = new float[]{0.0f};
            int[] pMax = new int[]{1};
            result = aiGetMaterialFloatArray(aiMaterial, AI_MATKEY_SHININESS_STRENGTH, aiTextureType_NONE, 0, shininessFactor, pMax);
            if (result != aiReturn_SUCCESS) {
                reflectance = shininessFactor[0];
            }
            material.setReflectance(reflectance);

            AIString aiTexturePath = AIString.calloc(stack);
            aiGetMaterialTexture(aiMaterial, aiTextureType_DIFFUSE, 0, aiTexturePath, (IntBuffer) null,
                    null, null, null, null, null);
            String texturePath = aiTexturePath.dataString();
            if (texturePath != null && texturePath.length() > 0) {
                material.setTexturePath(modelDir + File.separator + new File(texturePath).getName());
                textureCache.createTexture(material.getTexturePath());
                material.setDiffuseColor(Material.DEFAULT_COLOR);
            }

            return material;
        }
    }
    ...

ご覧のとおり、プロパティを取得することでマテリアルのアンビエント カラーを取得しAI_MATKEY_COLOR_AMBIENTます。プロパティを使用してスペキュラー カラーを取得しAI_MATKEY_COLOR_SPECULARます。光沢はAI_MATKEY_SHININESS_STRENGTHフラグを使用して照会されます。

法線をロードするには、という名前の新しいメソッドを作成し、メソッドprocessNormalsで呼び出す必要がありますprocessMesh。

public class ModelLoader {
    ...
    private static Mesh processMesh(AIMesh aiMesh) {
        float[] vertices = processVertices(aiMesh);
        float[] normals = processNormals(aiMesh);
        float[] textCoords = processTextCoords(aiMesh);
        int[] indices = processIndices(aiMesh);

        // Texture coordinates may not have been populated. We need at least the empty slots
        if (textCoords.length == 0) {
            int numElements = (vertices.length / 3) * 2;
            textCoords = new float[numElements];
        }

        return new Mesh(vertices, normals, textCoords, indices);
    }

    private static float[] processNormals(AIMesh aiMesh) {
        AIVector3D.Buffer buffer = aiMesh.mNormals();
        float[] data = new float[buffer.remaining() * 3];
        int pos = 0;
        while (buffer.remaining() > 0) {
            AIVector3D normal = buffer.get();
            data[pos++] = normal.x();
            data[pos++] = normal.y();
            data[pos++] = normal.z();
        }
        return data;
    }
    ...
}

Materialクラス

ご覧のとおり、新しい情報を格納するためにMaterialおよびMeshクラスも変更する必要があります。クラスの変更点は次のMaterialとおりです。

public class Material {
    ...
    private Vector4f ambientColor;
    ...
    private float reflectance;
    private Vector4f specularColor;
    ...
    public Material() {
        ...
        ambientColor = DEFAULT_COLOR;
        ...
    } 
    ...
    public Vector4f getAmbientColor() {
        return ambientColor;
    }
    ...
    public float getReflectance() {
        return reflectance;
    }

    public Vector4f getSpecularColor() {
        return specularColor;
    }
    ...
    public void setAmbientColor(Vector4f ambientColor) {
        this.ambientColor = ambientColor;
    }
    ...
    public void setReflectance(float reflectance) {
        this.reflectance = reflectance;
    }

    public void setSpecularColor(Vector4f specularColor) {
        this.specularColor = specularColor;
    }
    ...
}

Meshクラス

Meshクラスは法線データの新しい float 配列を受け入れるようになり、そのために新しい VBO を作成します。

public class Mesh {
    ...
    public Mesh(float[] positions, float[] normals, float[] textCoords, int[] indices) {
        ...
            // Normals VBO
            vboId = glGenBuffers();
            vboIdList.add(vboId);
            FloatBuffer normalsBuffer = stack.callocFloat(normals.length);
            normalsBuffer.put(0, normals);
            glBindBuffer(GL_ARRAY_BUFFER, vboId);
            glBufferData(GL_ARRAY_BUFFER, normalsBuffer, GL_STATIC_DRAW);
            glEnableVertexAttribArray(1);
            glVertexAttribPointer(1, 3, GL_FLOAT, false, 0, 0);

            // Texture coordinates VBO
            ...
            glEnableVertexAttribArray(2);
            glVertexAttribPointer(2, 2, GL_FLOAT, false, 0, 0);

            // Index VBO
            ...
        ...
    }
    ...
}

ライトでレンダリングする

レンダリング中にライトを使用する時が来ました。シェーダー、特に頂点シェーダー ( scene.vert)から始めましょう。

#version 330

layout (location=0) in vec3 position;
layout (location=1) in vec3 normal;
layout (location=2) in vec2 texCoord;

out vec3 outPosition;
out vec3 outNormal;
out vec2 outTextCoord;

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

void main()
{
    mat4 modelViewMatrix = viewMatrix * modelMatrix;
    vec4 mvPosition =  modelViewMatrix * vec4(position, 1.0);
    gl_Position = projectionMatrix * mvPosition;
    outPosition = mvPosition.xyz;
    outNormal = normalize(modelViewMatrix * vec4(normal, 0.0)).xyz;
    outTextCoord = texCoord;
}

ご覧のとおり、別の入力属性として通常のデータがあり、そのデータをフラグメント シェーダーに渡すだけです。フラグメント シェーダーの説明を続ける前に、強調しなければならない非常に重要な概念があります。mvVertexNormal上記のコードから、変数には頂点法線が含まれ、モデル ビュー空間座標に変換されることがわかります。これは、 に頂点位置を掛けることnormalによって行われます。modelViewMatrixただし、微妙な違いがあります。その頂点法線の w コンポーネントは、行列を乗算する前に 0 に設定されます。vec4(vertexNormal, 0.0). なぜこれを行うのですか?法線を回転およびスケーリングしたいが、平行移動したくないため、関心があるのはその方向だけであり、その位置には関心がありません。これは w コンポーネントを 0 に設定することで実現され、同次座標を使用する利点の 1 つです。w コンポーネントを設定することで、適用される変換を制御できます。行列の乗算を手動で行うことができ、これが発生する理由を確認できます。

フラグメント シェーダーの変更scene.fragは非常に複雑です。1 つずつステップを進めていきましょう。

<scene.frag>

#version 330

const int MAX_POINT_LIGHTS = 5;
const int MAX_SPOT_LIGHTS = 5;
const float SPECULAR_POWER = 10;

in vec3 outPosition;
in vec3 outNormal;
in vec2 outTextCoord;

out vec4 fragColor;
...

最初に、サポートするポント ライトとスポット ライトの最大数に対する定数の最大値を定義します。これらのライトのデータは、コンパイル時に適切に定義されたサイズを持つ必要があるユニフォームの配列として渡されるため、これが必要です。また、頂点シェーダーから通常のデータを受け取っていることもわかります。その後、ライト データをモデル化する構造体を定義します。

...
struct Attenuation
{
    float constant;
    float linear;
    float exponent;
};
struct Material
{
    vec4 ambient;
    vec4 diffuse;
    vec4 specular;
    float reflectance;
};
struct AmbientLight
{
    float factor;
    vec3 color;
};
struct PointLight {
    vec3 position;
    vec3 color;
    float intensity;
    Attenuation att;
};
struct SpotLight
{
    PointLight pl;
    vec3 conedir;
    float cutoff;
};
struct DirLight
{
    vec3 color;
    vec3 direction;
    float intensity;
};
...

その後、ライト データの新しいユニフォームを定義します。

...
uniform sampler2D txtSampler;
uniform Material material;
uniform AmbientLight ambientLight;
uniform PointLight pointLights[MAX_POINT_LIGHTS];
uniform SpotLight spotLights[MAX_SPOT_LIGHTS];
uniform DirLight dirLight
...

次に、周囲光から始めて、各ライト タイプの効果を計算する関数をいくつか定義します。

...
vec4 calcAmbient(AmbientLight ambientLight, vec4 ambient) {
    return vec4(ambientLight.factor * ambientLight.color, 1) * ambient;
}
...

ご覧のとおり、マテリアルのアンビエント カラーに適用される係数によってアンビエント ライトの色を変調するだけです。ここで、さまざまな種類のライトに対してカラー ライトを計算する方法を定義する関数を定義します。

...
vec4 calcLightColor(vec4 diffuse, vec4 specular, vec3 lightColor, float light_intensity, vec3 position, vec3 to_light_dir, vec3 normal) {
    vec4 diffuseColor = vec4(0, 0, 0, 1);
    vec4 specColor = vec4(0, 0, 0, 1);

    // Diffuse Light
    float diffuseFactor = max(dot(normal, to_light_dir), 0.0);
    diffuseColor = diffuse * vec4(lightColor, 1.0) * light_intensity * diffuseFactor;

    // Specular Light
    vec3 camera_direction = normalize(-position);
    vec3 from_light_dir = -to_light_dir;
    vec3 reflected_light = normalize(reflect(from_light_dir, normal));
    float specularFactor = max(dot(camera_direction, reflected_light), 0.0);
    specularFactor = pow(specularFactor, SPECULAR_POWER);
    specColor = specular * light_intensity  * specularFactor * material.reflectance * vec4(lightColor, 1.0);

    return (diffuseColor + specColor);
}
...

前のコードは比較的単純で、拡散コンポーネントの色を計算し、鏡面コンポーネントの別の色を計算し、処理中の頂点への移動中に光が受ける減衰によって変調します。これで、各タイプのライトに対して呼び出される関数を定義できます。ポイント ライトから始めます。

...
vec4 calcPointLight(vec4 diffuse, vec4 specular, PointLight light, vec3 position, vec3 normal) {
    vec3 light_direction = light.position - position;
    vec3 to_light_dir  = normalize(light_direction);
    vec4 light_color = calcLightColor(diffuse, specular, light.color, light.intensity, position, to_light_dir, normal);

    // Apply Attenuation
    float distance = length(light_direction);
    float attenuationInv = light.att.constant + light.att.linear * distance +
    light.att.exponent * distance * distance;
    return light_color / attenuationInv;
}
...

ご覧のとおり、光の方向を (法線として) 計算し、その情報を使用して、マテリアルの拡散色と反射色、光の色、強度、位置、方向、および法線方向を使用して、光の色を計算します。 . その後、減衰を適用します。スポット ライトの機能は次のとおりです。

...
vec4 calcSpotLight(vec4 diffuse, vec4 specular, SpotLight light, vec3 position, vec3 normal) {
    vec3 light_direction = light.pl.position - position;
    vec3 to_light_dir  = normalize(light_direction);
    vec3 from_light_dir  = -to_light_dir;
    float spot_alfa = dot(from_light_dir, normalize(light.conedir));

    vec4 color = vec4(0, 0, 0, 0);

    if (spot_alfa > light.cutoff)
    {
        color = calcPointLight(diffuse, specular, light.pl, position, normal);
        color *= (1.0 - (1.0 - spot_alfa)/(1.0 - light.cutoff));
    }
    return color;
}
...

手順は、光の円錐の内側にいるかどうかを制御する必要があることを除いて、ポイント ライトに似ています。先に説明したように、円錐状の光の内側にも減衰を適用する必要があります。最後に、ディレクショナル ライトの関数を以下に定義します。

...
vec4 calcDirLight(vec4 diffuse, vec4 specular, DirLight light, vec3 position, vec3 normal) {
    return calcLightColor(diffuse, specular, light.color, light.intensity, position, normalize(light.direction), normal);
}
...

SceneRenderクラス

この場合、光の方向はすでにわかっており、減衰がないため、光の位置を考慮する必要はありません。最後に、mainメソッドでは、最終的なフラグメント カラーの拡散鏡面コンポーネントに寄与するさまざまなライト タイプを反復処理します。

public class SceneRender {

    private static final int MAX_POINT_LIGHTS = 5;
    private static final int MAX_SPOT_LIGHTS = 5;
    ...
    private void createUniforms() {
        ...
        uniformsMap.createUniform("material.ambient");
        uniformsMap.createUniform("material.diffuse");
        uniformsMap.createUniform("material.specular");
        uniformsMap.createUniform("material.reflectance");
        uniformsMap.createUniform("ambientLight.factor");
        uniformsMap.createUniform("ambientLight.color");

        for (int i = 0; i < MAX_POINT_LIGHTS; i++) {
            String name = "pointLights[" + i + "]";
            uniformsMap.createUniform(name + ".position");
            uniformsMap.createUniform(name + ".color");
            uniformsMap.createUniform(name + ".intensity");
            uniformsMap.createUniform(name + ".att.constant");
            uniformsMap.createUniform(name + ".att.linear");
            uniformsMap.createUniform(name + ".att.exponent");
        }
        for (int i = 0; i < MAX_SPOT_LIGHTS; i++) {
            String name = "spotLights[" + i + "]";
            uniformsMap.createUniform(name + ".pl.position");
            uniformsMap.createUniform(name + ".pl.color");
            uniformsMap.createUniform(name + ".pl.intensity");
            uniformsMap.createUniform(name + ".pl.att.constant");
            uniformsMap.createUniform(name + ".pl.att.linear");
            uniformsMap.createUniform(name + ".pl.att.exponent");
            uniformsMap.createUniform(name + ".conedir");
            uniformsMap.createUniform(name + ".cutoff");
        }

        uniformsMap.createUniform("dirLight.color");
        uniformsMap.createUniform("dirLight.direction");
        uniformsMap.createUniform("dirLight.intensity");
    }
    ...
}

配列を使用している場合、リストの各要素に対してユニフォームを作成する必要があります。たとえば、pointLights
pointLights[0]、などの統一された名前の配列を作成する必要がありますpointLights[1]。もちろん、これは構造体の属性にも変換されるため、、などになりpointLights[0].colorますpointLights[1], color。

ダー呼び出しごとにライトのユニフォームを更新する新しいメソッドを作成します。このメソッドにupdateLightsは次のように名前が付けられ、定義されます。

public class SceneRender {
    ...
    private void updateLights(Scene scene) {
        Matrix4f viewMatrix = scene.getCamera().getViewMatrix();

        SceneLights sceneLights = scene.getSceneLights();
        AmbientLight ambientLight = sceneLights.getAmbientLight();
        uniformsMap.setUniform("ambientLight.factor", ambientLight.getIntensity());
        uniformsMap.setUniform("ambientLight.color", ambientLight.getColor());

        DirLight dirLight = sceneLights.getDirLight();
        Vector4f auxDir = new Vector4f(dirLight.getDirection(), 0);
        auxDir.mul(viewMatrix);
        Vector3f dir = new Vector3f(auxDir.x, auxDir.y, auxDir.z);
        uniformsMap.setUniform("dirLight.color", dirLight.getColor());
        uniformsMap.setUniform("dirLight.direction", dir);
        uniformsMap.setUniform("dirLight.intensity", dirLight.getIntensity());

        List<PointLight> pointLights = sceneLights.getPointLights();
        int numPointLights = pointLights.size();
        PointLight pointLight;
        for (int i = 0; i < MAX_POINT_LIGHTS; i++) {
            if (i < numPointLights) {
                pointLight = pointLights.get(i);
            } else {
                pointLight = null;
            }
            String name = "pointLights[" + i + "]";
            updatePointLight(pointLight, name, viewMatrix);
        }

        List<SpotLight> spotLights = sceneLights.getSpotLights();
        int numSpotLights = spotLights.size();
        SpotLight spotLight;
        for (int i = 0; i < MAX_SPOT_LIGHTS; i++) {
            if (i < numSpotLights) {
                spotLight = spotLights.get(i);
            } else {
                spotLight = null;
            }
            String name = "spotLights[" + i + "]";
            updateSpotLight(spotLight, name, viewMatrix);
        }
    }
    ...
}

コードは非常に単純です。環境光をディレクショナル ライト ユニフォームに設定することから始め、その後、配列の各要素のユニフォームを設定する専用のメソッドを持つポイント ライトとスポット ライトを反復処理します。

public class SceneRender {
    ...
    private void updatePointLight(PointLight pointLight, String prefix, Matrix4f viewMatrix) {
        Vector4f aux = new Vector4f();
        Vector3f lightPosition = new Vector3f();
        Vector3f color = new Vector3f();
        float intensity = 0.0f;
        float constant = 0.0f;
        float linear = 0.0f;
        float exponent = 0.0f;
        if (pointLight != null) {
            aux.set(pointLight.getPosition(), 1);
            aux.mul(viewMatrix);
            lightPosition.set(aux.x, aux.y, aux.z);
            color.set(pointLight.getColor());
            intensity = pointLight.getIntensity();
            PointLight.Attenuation attenuation = pointLight.getAttenuation();
            constant = attenuation.getConstant();
            linear = attenuation.getLinear();
            exponent = attenuation.getExponent();
        }
        uniformsMap.setUniform(prefix + ".position", lightPosition);
        uniformsMap.setUniform(prefix + ".color", color);
        uniformsMap.setUniform(prefix + ".intensity", intensity);
        uniformsMap.setUniform(prefix + ".att.constant", constant);
        uniformsMap.setUniform(prefix + ".att.linear", linear);
        uniformsMap.setUniform(prefix + ".att.exponent", exponent);
    }

    private void updateSpotLight(SpotLight spotLight, String prefix, Matrix4f viewMatrix) {
        PointLight pointLight = null;
        Vector3f coneDirection = new Vector3f();
        float cutoff = 0.0f;
        if (spotLight != null) {
            coneDirection = spotLight.getConeDirection();
            cutoff = spotLight.getCutOff();
            pointLight = spotLight.getPointLight();
        }

        uniformsMap.setUniform(prefix + ".conedir", coneDirection);
        uniformsMap.setUniform(prefix + ".conedir", cutoff);
        updatePointLight(pointLight, prefix + ".pl", viewMatrix);
    }
    ...
}

すでに述べたように、これらのライトの座標はビュー スペース内にある必要があります。通常、ワールド空間座標でライト座標を設定するため、シェーダーで使用できるようにするには、それらをビュー マトリックスで乗算する必要があります。最後に、メソッドを更新してrenderメソッドを呼び出しupdateLights、モデル マテリアルの新しい要素を適切に設定する必要があります。

public class SceneRender {
    ...
    public void render(Scene scene) {
        ...
        updateLights(scene);
        ...
        for (Model model : models) {
            List<Entity> entities = model.getEntitiesList();

            for (Material material : model.getMaterialList()) {
                uniformsMap.setUniform("material.ambient", material.getAmbientColor());
                uniformsMap.setUniform("material.diffuse", material.getDiffuseColor());
                uniformsMap.setUniform("material.specular", material.getSpecularColor());
                uniformsMap.setUniform("material.reflectance", material.getReflectance());
                ...
            }
        }
        ...
    }
    ...
}

UniformsMapクラス

UniformsMapまた、float と 3D ベクトルの値を設定するためのユニフォームを作成するためのメソッドのペアをクラスに追加する必要があります。

public class UniformsMap {
    ...
    public void setUniform(String uniformName, float value) {
        glUniform1f(getUniformLocation(uniformName), value);
    }

    public void setUniform(String uniformName, Vector3f value) {
        glUniform3f(getUniformLocation(uniformName), value.x, value.y, value.z);
    }
    ...
}

ライトコントロール

最後のステップは、Mainクラスでライトを使用することです。ただし、その前に、Imgui を使用して GUI を作成し、ライト パラメータを制御する要素をいくつか提供します。という名前の新しいクラスでこれを行いますLightControls。コードは長すぎますが、理解するのは非常に簡単です。GUI コントロールから値を取得するための一連の属性と、必要なパネルとウィジェットを描画するためのメソッドを設定するだけで済みます。

package org.lwjglb.game;

import imgui.*;
import imgui.flag.ImGuiCond;
import org.joml.*;
import org.lwjglb.engine.*;
import org.lwjglb.engine.scene.Scene;
import org.lwjglb.engine.scene.lights.*;

public class LightControls implements IGuiInstance {

    private float[] ambientColor;
    private float[] ambientFactor;
    private float[] dirConeX;
    private float[] dirConeY;
    private float[] dirConeZ;
    private float[] dirLightColor;
    private float[] dirLightIntensity;
    private float[] dirLightX;
    private float[] dirLightY;
    private float[] dirLightZ;
    private float[] pointLightColor;
    private float[] pointLightIntensity;
    private float[] pointLightX;
    private float[] pointLightY;
    private float[] pointLightZ;
    private float[] spotLightColor;
    private float[] spotLightCuttoff;
    private float[] spotLightIntensity;
    private float[] spotLightX;
    private float[] spotLightY;
    private float[] spotLightZ;

    public LightControls(Scene scene) {
        SceneLights sceneLights = scene.getSceneLights();
        AmbientLight ambientLight = sceneLights.getAmbientLight();
        Vector3f color = ambientLight.getColor();

        ambientFactor = new float[]{ambientLight.getIntensity()};
        ambientColor = new float[]{color.x, color.y, color.z};

        PointLight pointLight = sceneLights.getPointLights().get(0);
        color = pointLight.getColor();
        Vector3f pos = pointLight.getPosition();
        pointLightColor = new float[]{color.x, color.y, color.z};
        pointLightX = new float[]{pos.x};
        pointLightY = new float[]{pos.y};
        pointLightZ = new float[]{pos.z};
        pointLightIntensity = new float[]{pointLight.getIntensity()};

        SpotLight spotLight = sceneLights.getSpotLights().get(0);
        pointLight = spotLight.getPointLight();
        color = pointLight.getColor();
        pos = pointLight.getPosition();
        spotLightColor = new float[]{color.x, color.y, color.z};
        spotLightX = new float[]{pos.x};
        spotLightY = new float[]{pos.y};
        spotLightZ = new float[]{pos.z};
        spotLightIntensity = new float[]{pointLight.getIntensity()};
        spotLightCuttoff = new float[]{spotLight.getCutOffAngle()};
        Vector3f coneDir = spotLight.getConeDirection();
        dirConeX = new float[]{coneDir.x};
        dirConeY = new float[]{coneDir.y};
        dirConeZ = new float[]{coneDir.z};

        DirLight dirLight = sceneLights.getDirLight();
        color = dirLight.getColor();
        pos = dirLight.getDirection();
        dirLightColor = new float[]{color.x, color.y, color.z};
        dirLightX = new float[]{pos.x};
        dirLightY = new float[]{pos.y};
        dirLightZ = new float[]{pos.z};
        dirLightIntensity = new float[]{dirLight.getIntensity()};
    }

    @Override
    public void drawGui() {
        ImGui.newFrame();
        ImGui.setNextWindowPos(0, 0, ImGuiCond.Always);
        ImGui.setNextWindowSize(450, 400);

        ImGui.begin("Lights controls");
        if (ImGui.collapsingHeader("Ambient Light")) {
            ImGui.sliderFloat("Ambient factor", ambientFactor, 0.0f, 1.0f, "%.2f");
            ImGui.colorEdit3("Ambient color", ambientColor);
        }

        if (ImGui.collapsingHeader("Point Light")) {
            ImGui.sliderFloat("Point Light - x", pointLightX, -10.0f, 10.0f, "%.2f");
            ImGui.sliderFloat("Point Light - y", pointLightY, -10.0f, 10.0f, "%.2f");
            ImGui.sliderFloat("Point Light - z", pointLightZ, -10.0f, 10.0f, "%.2f");
            ImGui.colorEdit3("Point Light color", pointLightColor);
            ImGui.sliderFloat("Point Light Intensity", pointLightIntensity, 0.0f, 1.0f, "%.2f");
        }

        if (ImGui.collapsingHeader("Spot Light")) {
            ImGui.sliderFloat("Spot Light - x", spotLightX, -10.0f, 10.0f, "%.2f");
            ImGui.sliderFloat("Spot Light - y", spotLightY, -10.0f, 10.0f, "%.2f");
            ImGui.sliderFloat("Spot Light - z", spotLightZ, -10.0f, 10.0f, "%.2f");
            ImGui.colorEdit3("Spot Light color", spotLightColor);
            ImGui.sliderFloat("Spot Light Intensity", spotLightIntensity, 0.0f, 1.0f, "%.2f");
            ImGui.separator();
            ImGui.sliderFloat("Spot Light cutoff", spotLightCuttoff, 0.0f, 360.0f, "%2.f");
            ImGui.sliderFloat("Dir cone - x", dirConeX, -1.0f, 1.0f, "%.2f");
            ImGui.sliderFloat("Dir cone - y", dirConeY, -1.0f, 1.0f, "%.2f");
            ImGui.sliderFloat("Dir cone - z", dirConeZ, -1.0f, 1.0f, "%.2f");
        }

        if (ImGui.collapsingHeader("Dir Light")) {
            ImGui.sliderFloat("Dir Light - x", dirLightX, -1.0f, 1.0f, "%.2f");
            ImGui.sliderFloat("Dir Light - y", dirLightY, -1.0f, 1.0f, "%.2f");
            ImGui.sliderFloat("Dir Light - z", dirLightZ, -1.0f, 1.0f, "%.2f");
            ImGui.colorEdit3("Dir Light color", dirLightColor);
            ImGui.sliderFloat("Dir Light Intensity", dirLightIntensity, 0.0f, 1.0f, "%.2f");
        }

        ImGui.end();
        ImGui.endFrame();
        ImGui.render();
    }
    ...
}

最後に、GUI 入力を処理するメソッドが必要です。ここでは、マウスの状態に基づいて Imgui を更新し、入力が GUI コントロールによって消費されたかどうかを確認します。その場合、ユーザー入力に従ってクラスの属性を入力するだけです。

public class LightControls implements IGuiInstance {
    ...
    @Override
    public boolean handleGuiInput(Scene scene, Window window) {
        ImGuiIO imGuiIO = ImGui.getIO();
        MouseInput mouseInput = window.getMouseInput();
        Vector2f mousePos = mouseInput.getCurrentPos();
        imGuiIO.setMousePos(mousePos.x, mousePos.y);
        imGuiIO.setMouseDown(0, mouseInput.isLeftButtonPressed());
        imGuiIO.setMouseDown(1, mouseInput.isRightButtonPressed());

        boolean consumed = imGuiIO.getWantCaptureMouse() || imGuiIO.getWantCaptureKeyboard();
        if (consumed) {
            SceneLights sceneLights = scene.getSceneLights();
            AmbientLight ambientLight = sceneLights.getAmbientLight();
            ambientLight.setIntensity(ambientFactor[0]);
            ambientLight.setColor(ambientColor[0], ambientColor[1], ambientColor[2]);

            PointLight pointLight = sceneLights.getPointLights().get(0);
            pointLight.setPosition(pointLightX[0], pointLightY[0], pointLightZ[0]);
            pointLight.setColor(pointLightColor[0], pointLightColor[1], pointLightColor[2]);
            pointLight.setIntensity(pointLightIntensity[0]);

            SpotLight spotLight = sceneLights.getSpotLights().get(0);
            pointLight = spotLight.getPointLight();
            pointLight.setPosition(spotLightX[0], spotLightY[0], spotLightZ[0]);
            pointLight.setColor(spotLightColor[0], spotLightColor[1], spotLightColor[2]);
            pointLight.setIntensity(spotLightIntensity[0]);
            spotLight.setCutOffAngle(spotLightColor[0]);
            spotLight.setConeDirection(dirConeX[0], dirConeY[0], dirConeZ[0]);

            DirLight dirLight = sceneLights.getDirLight();
            dirLight.setPosition(dirLightX[0], dirLightY[0], dirLightZ[0]);
            dirLight.setColor(dirLightColor[0], dirLightColor[1], dirLightColor[2]);
            dirLight.setIntensity(dirLightIntensity[0]);
        }
        return consumed;
    }
}

Mainクラス

最後のステップは、Mainクラスを更新してライトを作成し、以前のメソッドdrawGuiとhandleGuiInputメソッドを削除することです (LightControlsクラスでの処理は省略します)。

public class Main implements IAppLogic {
    ...
    private LightControls lightControls;

    public static void main(String[] args) {
        ...
        Engine gameEng = new Engine("chapter-11", new Window.WindowOptions(), main);
        ...
    }
    ...
    public void init(Window window, Scene scene, Render render) {
        Model cubeModel = ModelLoader.loadModel("cube-model", "resources/models/cube/cube.obj",
                scene.getTextureCache());
        scene.addModel(cubeModel);

        cubeEntity = new Entity("cube-entity", cubeModel.getId());
        cubeEntity.setPosition(0, 0f, -2);
        cubeEntity.updateModelMatrix();
        scene.addEntity(cubeEntity);

        SceneLights sceneLights = new SceneLights();
        sceneLights.getAmbientLight().setIntensity(0.3f);
        scene.setSceneLights(sceneLights);
        sceneLights.getPointLights().add(new PointLight(new Vector3f(1, 1, 1),
                new Vector3f(0, 0, -1.4f), 1.0f));

        Vector3f coneDir = new Vector3f(0, 0, -1);
        sceneLights.getSpotLights().add(new SpotLight(new PointLight(new Vector3f(1, 1, 1),
                new Vector3f(0, 0, -1.4f), 0.0f), coneDir, 140.0f));

        lightControls = new LightControls(scene);
        scene.setGuiInstance(lightControls);
    }
    ...
    @Override
    public void update(Window window, Scene scene, long diffTimeMillis) {
        // Nothing to be done here
    }
}

最後に、これに似たものを見ることができます。

Java 3D LWJGL 改造 〜Imgui を使用した GUI 描画を作成する〜

Imgui を使用した GUI 描画を改造

依然学習したLWJGL Gitbookをヒントにして現在実装しているテキストRPGのLWJGL化を行いたいと考えております。

現状のテキストRPG

上の動画にあるように、コマンドプロンプトなどのCUIで実行する前提で作成しています。しかし、表示する内容として余計なものが多すぎると感じています。
なので、LWJGLを使用してウィンドウから起動できるように改造しようと考えております。

しかし、学習を開始してからいろいろと上手くいかない状況になり。。。
Imguiを単体で使用することにしました。ちょうどImguiのjavaバインディングがあったのでそちらを使用します。

【参照するドキュメント一覧】

1.LWJGLのGitbook

  1. テキストRPGのドキュメント
  2. Imguiのドキュメント
  3. ImguiのJavaDoc
  4. Imguiのチュートリアル

Imguiの実装に関して(Java Binding)

この動画を参照しました。

動画の参照ページ

Imguiのセットアップ

  1. こちらのサイトより「java-libraries.zip」をダウンロードします。
  2. imgui-app-X.XX.X-all.jarをプロジェクトから参照できるように設定します。
  3. 下のコードをコピペします。参照先はこちらです。
    
    import imgui.ImGui;
    import imgui.app.Application;

public class Main extends Application {
@Override
protected void configure(Configuration config) {
config.setTitle("Dear ImGui is Awesome!");
}

@Override
public void process() {
    ImGui.text("Hello, World!");
}

public static void main(String[] args) {
    launch(new Main());
}

}


自分が作成したクラスは次のようになっています。(ImguiMain.java)
```java
package jp.zenryoku.imgui;

import imgui.ImGui;
import imgui.app.Application;
import imgui.app.Configuration;

/** ImGuiの学習用メインクラス */
public class ImguiMain extends Application {
    @Override
    protected void configure(Configuration config) {
        config.setTitle("Dear ImGui is Awesome!");
    }

    @Override
    public void process() {
        ImGui.text("Hello, World!");
    }

    public static void main(String[] args) {
        launch(new ImguiMain());
    }
}

書いて動かしてみた動画です。

どこから学習するか?

チュートリアルの動画など見ましたが、結局のところImguiを基本文法の学習時と同じように学んだほうが早いと判断しました。
具体的には次のようなところを学びます。

  1. Imguiでハローワールド(これは、上記で実施済み)
  2. 同様に、ハローワールドを改造する。参考ページはこちら
  3. こちらのFAQを見ながらやりたいことを実行する

まずは、実行したのが2の参考ページを見ながら作成したコードを見てください。

public class ImguiMain extends Application {
    @Override
    protected void configure(Configuration config) {
        config.setTitle("Dear ImGui is Awesome!");
    }

    @Override
    public void process() {
        // Windowその1
        ImGui.begin("Title A");
        ImGui.text("Hello, World!");
        ImGui.end();

        // Windowその2
        ImGui.begin("Title B");
        ImGui.text("A nice World!");
        ImGui.end();
    }

    public static void main(String[] args) {
        launch(new ImguiMain());
    }
}

ここから、基本を学びます。参照先はこちらのページにあるものを見ます。

ImGui::ShowDemoWindow()はどこに?

上の参照先にある記事を読むと、「デモコードをみて理解してね」とあるのでそれを見るようにします。

  1. デモ・コードに移動します。
  2. 下のような画面で247行目からのプログラムがそうです。

ImGui::ShowDemoWindow()を読む

289-302行目では、デモウィンドウを表示するメソッドが呼ばれているようです。しかし、どのようにウィンドウを作成するのかわからないので細かく見ません。

330-334行目にあるコードが参考になりそうです。

    // We specify a default position/size in case there's no data in the .ini file.
    // We only do it to make the demo applications a little more welcoming, but typically this isn't required.
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
    ImGui::SetNextWindowPos(ImVec2(main_viewport->WorkPos.x + 650, main_viewport->WorkPos.y + 20), ImGuiCond_FirstUseEver);
    ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver);

上記のコードは、メソッド呼び出しを行っているだけなので、プログラムを動かしてみるのが早そうです。というわけでコードを書いて実行します。
ここでもポイントは、呼び出しているメソッド(関数 or ファンクション)の名前がC言語と変わっているかどうか?です。

<動かしてみる>

Javaのデモ・コードをみる

上記の「参照先はこちらのページ」にもあるように、デモ・コードから基本を学びます。
実際のプログラムは、ImGui::ShowDemoWindow();に実装しているようです。

しかし、上記のでもコードはC/C++なので、Javaでのサンプルコードが欲しいところ。。。
そんなわけで、見つけました。サンプルはGithubにありました。

ImGui Java-bindingがありました。

まずは、Mainクラスを参照します。

中身を読んでみたところ、同じディレクトリにあるクラスがすべて必要なようなのでこのクラスたちをダウンロードしてきます。

このページにある下のような部分をクリック

ダウンロードしてきたファイルを展開して、次のディレクトリに各ファイルがあります。

  • imgui-java/example/src/main/java/: 実行するJavaファイル
  • imgui-java/example/src/main/resources/: 使用するファイル(Tahoma.ttfなど)

実行してみた!

コードを書いてみる

ここで、サンプルコードをいじって書いたコードを紹介します。
ほぼ、Mainクラスをコピーしたものですが、process()メソッドの中身を書き換えて下のように修正、実行しました。

    @Override
    public void process() {
        if (ImGui.begin("Stories", ImGuiWindowFlags.AlwaysAutoResize)) {
            ImGui.text("Hello, World! " + FontAwesomeIcons.Smile);
            ImGui.sameLine();
            ImGui.text(String.valueOf(count));
            ExampleImGuiColorTextEdit.show(new ImBoolean(true));
        }
        ImGui.end();
    }

キーポイントになるのは「ExampleImGuiColorTextEdit.show(new ImBoolean(true));」の部分です。
ExampleImGuiColorTextEditクラスのstaticメソッド「show()」を呼び出しています。
早速、クラスの中身を見ます。

import imgui.ImGui;
import imgui.extension.texteditor.TextEditor;
import imgui.extension.texteditor.TextEditorLanguageDefinition;
import imgui.flag.ImGuiWindowFlags;
import imgui.type.ImBoolean;

import java.util.HashMap;
import java.util.Map;

public class ExampleImGuiColorTextEdit {
    private static final TextEditor EDITOR = new TextEditor();

    static {
        TextEditorLanguageDefinition lang = TextEditorLanguageDefinition.c();

        String[] ppnames = {
            "NULL", "PM_REMOVE",
            "ZeroMemory", "DXGI_SWAP_EFFECT_DISCARD", "D3D_FEATURE_LEVEL", "D3D_DRIVER_TYPE_HARDWARE", "WINAPI", "D3D11_SDK_VERSION", "assert"};
        String[] ppvalues = {
            "#define NULL ((void*)0)",
            "#define PM_REMOVE (0x0001)",
            "Microsoft's own memory zapper function\n(which is a macro actually)\nvoid ZeroMemory(\n\t[in] PVOID  Destination,\n\t[in] SIZE_T Length\n); ",
            "enum DXGI_SWAP_EFFECT::DXGI_SWAP_EFFECT_DISCARD = 0",
            "enum D3D_FEATURE_LEVEL",
            "enum D3D_DRIVER_TYPE::D3D_DRIVER_TYPE_HARDWARE  = ( D3D_DRIVER_TYPE_UNKNOWN + 1 )",
            "#define WINAPI __stdcall",
            "#define D3D11_SDK_VERSION (7)",
            " #define assert(expression) (void)(                                                  \n" +
                "    (!!(expression)) ||                                                              \n" +
                "    (_wassert(_CRT_WIDE(#expression), _CRT_WIDE(__FILE__), (unsigned)(__LINE__)), 0) \n" +
                " )"
        };

        // Adding custom preproc identifiers
        Map<String, String> preprocIdentifierMap = new HashMap<>();
        for (int i = 0; i < ppnames.length; ++i) {
            preprocIdentifierMap.put(ppnames[i], ppvalues[i]);
        }
        lang.setPreprocIdentifiers(preprocIdentifierMap);

        String[] identifiers = {
            "HWND", "HRESULT", "LPRESULT","D3D11_RENDER_TARGET_VIEW_DESC", "DXGI_SWAP_CHAIN_DESC","MSG","LRESULT","WPARAM", "LPARAM","UINT","LPVOID",
                "ID3D11Device", "ID3D11DeviceContext", "ID3D11Buffer", "ID3D11Buffer", "ID3D10Blob", "ID3D11VertexShader", "ID3D11InputLayout", "ID3D11Buffer",
                "ID3D10Blob", "ID3D11PixelShader", "ID3D11SamplerState", "ID3D11ShaderResourceView", "ID3D11RasterizerState", "ID3D11BlendState", "ID3D11DepthStencilState",
                "IDXGISwapChain", "ID3D11RenderTargetView", "ID3D11Texture2D", "TextEditor" };
        String[] idecls = {
            "typedef HWND_* HWND", "typedef long HRESULT", "typedef long* LPRESULT", "struct D3D11_RENDER_TARGET_VIEW_DESC", "struct DXGI_SWAP_CHAIN_DESC",
                "typedef tagMSG MSG\n * Message structure","typedef LONG_PTR LRESULT","WPARAM", "LPARAM","UINT","LPVOID",
                "ID3D11Device", "ID3D11DeviceContext", "ID3D11Buffer", "ID3D11Buffer", "ID3D10Blob", "ID3D11VertexShader", "ID3D11InputLayout", "ID3D11Buffer",
                "ID3D10Blob", "ID3D11PixelShader", "ID3D11SamplerState", "ID3D11ShaderResourceView", "ID3D11RasterizerState", "ID3D11BlendState", "ID3D11DepthStencilState",
                "IDXGISwapChain", "ID3D11RenderTargetView", "ID3D11Texture2D", "class TextEditor" };

        // Adding custom identifiers
        Map<String, String> identifierMap = new HashMap<>();
        for (int i = 0; i < ppnames.length; ++i) {
            identifierMap.put(identifiers[i], idecls[i]);
        }
        lang.setIdentifiers(identifierMap);

        EDITOR.setLanguageDefinition(lang);

        // Adding error markers
        Map<Integer, String> errorMarkers = new HashMap<>();
        errorMarkers.put(1, "Expected '>'");
        EDITOR.setErrorMarkers(errorMarkers);

        EDITOR.setTextLines(new String[]{
            "#include <iostream",
            "",
            "int main() {",
            "   std::cout << \"Hello, World!\" << std::endl;",
            "}"
        });
    }
    public static void show(final ImBoolean showImColorTextEditWindow) {
        ImGui.setNextWindowSize(500, 400);
        if (ImGui.begin("Text Editor", showImColorTextEditWindow,
                ImGuiWindowFlags.HorizontalScrollbar | ImGuiWindowFlags.MenuBar)) {
            if (ImGui.beginMenuBar()) {
                if (ImGui.beginMenu("File")) {
                    if (ImGui.menuItem("Save")) {
                        String textToSave = EDITOR.getText();
                        /// save text....
                    }

                    ImGui.endMenu();
                }
                if (ImGui.beginMenu("Edit")) {
                    final boolean ro = EDITOR.isReadOnly();
                    if (ImGui.menuItem("Read-only mode", "", ro)) {
                        EDITOR.setReadOnly(!ro);
                    }

                    ImGui.separator();

                    if (ImGui.menuItem("Undo", "ALT-Backspace", !ro && EDITOR.canUndo())) {
                        EDITOR.undo(1);
                    }
                    if (ImGui.menuItem("Redo", "Ctrl-Y", !ro && EDITOR.canRedo())) {
                        EDITOR.redo(1);
                    }

                    ImGui.separator();

                    if (ImGui.menuItem("Copy", "Ctrl-C", EDITOR.hasSelection())) {
                        EDITOR.copy();
                    }
                    if (ImGui.menuItem("Cut", "Ctrl-X", !ro && EDITOR.hasSelection())) {
                        EDITOR.cut();
                    }
                    if (ImGui.menuItem("Delete", "Del", !ro && EDITOR.hasSelection())) {
                        EDITOR.delete();
                    }
                    if (ImGui.menuItem("Paste", "Ctrl-V", !ro && ImGui.getClipboardText() != null)) {
                        EDITOR.paste();
                    }

                    ImGui.endMenu();
                }

                ImGui.endMenuBar();
            }

            int cposX = EDITOR.getCursorPositionLine();
            int cposY = EDITOR.getCursorPositionColumn();

            String overwrite = EDITOR.isOverwrite() ? "Ovr" : "Ins";
            String canUndo = EDITOR.canUndo() ? "*" : " ";

            ImGui.text(cposX + "/" + cposY + " " + EDITOR.getTotalLines() + " lines | " + overwrite + " | " + canUndo);

            EDITOR.render("TextEditor");

            ImGui.end();
        }
    }
}

処理の中身を見ていると「ImGui.XXX()」のメソッドを呼び出している処理がほとんどです。
つまり、ほぼ、ImGuiクラスで画面の作成を行っているということです。ということは、JavaDocを見れば何とかなりそうです。

ImGuiでテキストエリア

JavaDocを見ながら、なんとか作成しました。実行結果は下のようになりました。

プログラムは、元のコードから変更しました。
<Main.java>

    @Override
    public void process() {
        ExampleImGuiColorTextEdit.show(new ImBoolean(false));
    }

元々は、ImGui.begin()を使用して、メニューバーを追加する処理を行っていましたが、これを削除して「ExampleImGuiColorTextEdit」クラスのshow()メソッドで定義している処理を呼び出すだけに修正しました。

<ExampleImGuiColorTextEdit.java>

public class ExampleImGuiColorTextEdit {
    private static final TextEditor EDITOR = new TextEditor();
    private static final String SEP = System.lineSeparator();

    static {
        TextEditorLanguageDefinition lang = TextEditorLanguageDefinition.c();

        String[] ppnames = {
            "NULL", "PM_REMOVE",
            "ZeroMemory", "DXGI_SWAP_EFFECT_DISCARD", "D3D_FEATURE_LEVEL", "D3D_DRIVER_TYPE_HARDWARE", "WINAPI", "D3D11_SDK_VERSION", "assert"};
        String[] ppvalues = {
            "#define NULL ((void*)0)",
            "#define PM_REMOVE (0x0001)",
            "Microsoft's own memory zapper function\n(which is a macro actually)\nvoid ZeroMemory(\n\t[in] PVOID  Destination,\n\t[in] SIZE_T Length\n); ",
            "enum DXGI_SWAP_EFFECT::DXGI_SWAP_EFFECT_DISCARD = 0",
            "enum D3D_FEATURE_LEVEL",
            "enum D3D_DRIVER_TYPE::D3D_DRIVER_TYPE_HARDWARE  = ( D3D_DRIVER_TYPE_UNKNOWN + 1 )",
            "#define WINAPI __stdcall",
            "#define D3D11_SDK_VERSION (7)",
            " #define assert(expression) (void)(                                                  \n" +
                "    (!!(expression)) ||                                                              \n" +
                "    (_wassert(_CRT_WIDE(#expression), _CRT_WIDE(__FILE__), (unsigned)(__LINE__)), 0) \n" +
                " )"
        };

        // Adding custom preproc identifiers
        Map<String, String> preprocIdentifierMap = new HashMap<>();
        for (int i = 0; i < ppnames.length; ++i) {
            preprocIdentifierMap.put(ppnames[i], ppvalues[i]);
        }
        lang.setPreprocIdentifiers(preprocIdentifierMap);

        String[] identifiers = {
            "HWND", "HRESULT", "LPRESULT","D3D11_RENDER_TARGET_VIEW_DESC", "DXGI_SWAP_CHAIN_DESC","MSG","LRESULT","WPARAM", "LPARAM","UINT","LPVOID",
                "ID3D11Device", "ID3D11DeviceContext", "ID3D11Buffer", "ID3D11Buffer", "ID3D10Blob", "ID3D11VertexShader", "ID3D11InputLayout", "ID3D11Buffer",
                "ID3D10Blob", "ID3D11PixelShader", "ID3D11SamplerState", "ID3D11ShaderResourceView", "ID3D11RasterizerState", "ID3D11BlendState", "ID3D11DepthStencilState",
                "IDXGISwapChain", "ID3D11RenderTargetView", "ID3D11Texture2D", "TextEditor" };
        String[] idecls = {
            "typedef HWND_* HWND", "typedef long HRESULT", "typedef long* LPRESULT", "struct D3D11_RENDER_TARGET_VIEW_DESC", "struct DXGI_SWAP_CHAIN_DESC",
                "typedef tagMSG MSG\n * Message structure","typedef LONG_PTR LRESULT","WPARAM", "LPARAM","UINT","LPVOID",
                "ID3D11Device", "ID3D11DeviceContext", "ID3D11Buffer", "ID3D11Buffer", "ID3D10Blob", "ID3D11VertexShader", "ID3D11InputLayout", "ID3D11Buffer",
                "ID3D10Blob", "ID3D11PixelShader", "ID3D11SamplerState", "ID3D11ShaderResourceView", "ID3D11RasterizerState", "ID3D11BlendState", "ID3D11DepthStencilState",
                "IDXGISwapChain", "ID3D11RenderTargetView", "ID3D11Texture2D", "class TextEditor" };

        // Adding custom identifiers
        Map<String, String> identifierMap = new HashMap<>();
        for (int i = 0; i < ppnames.length; ++i) {
            identifierMap.put(identifiers[i], idecls[i]);
        }
        lang.setIdentifiers(identifierMap);

        EDITOR.setLanguageDefinition(lang);
    }

    public static void show(final ImBoolean showImColorTextEditWindow) {
        ImGui.setNextWindowSize(500, 400);
        if (ImGui.begin("Story", showImColorTextEditWindow)) {
            int cposX = EDITOR.getCursorPositionLine();
            int cposY = EDITOR.getCursorPositionColumn();

            String overwrite = EDITOR.isOverwrite() ? "Ovr" : "Ins";
            String canUndo = EDITOR.canUndo() ? "*" : " ";
            EDITOR.setReadOnly(true);

            //ImGui.text(cposX + "/" + cposY + " " + EDITOR.getTotalLines() + " lines | " + overwrite + " | " + canUndo);

            // 実装部分
            EDITOR.setText("GoodMorning" + SEP + "Hello World");
            EDITOR.render("TextEditor");

            ImGui.end();
        }
    }
}

同様に、メニューバー内に設定する文字列、Saveをクリックしたときの処理(処理内容はなし)が定義してありましたが、それを削除。
Mainクラスでshow(true)としていた部分をshow(false)に変更して、赤いラインを表示しないようにしました。

これで、目的の文字表示領域を作成することができました。

ImGui + TextRPG

テキストRPGを作成中でしたので、これを単体の画面で実行できるようにしたいと思っていたので、ImGuiは格好のライブラリです。
LWJGLを実行しないと実現できないと思っていましたが、ImGuiで事足りそうです。

TextRPGに関して、現状の考えとしてはImGuiをメインにして追加でLWJGLを実行したいと考えています。

TextRPGとは、下の動画のようなものです。これは、コマンドプロンプトで実行しているので「ゲーム」って感じがしない。。。と思っていたところです。