Certainly! To implement dynamic lighting in your RenderEngine, we'll follow these steps:
-
Define the applyLighting Method:
- This method will compute the lighting factor based on the vertex normal and the light direction.
- It will return a brightness factor that can be used to adjust the color of each pixel.
-
Integrate applyLighting into the Rendering Pipeline:
- Modify the
rasterizeTriangle method to utilize the applyLighting method when the enableLighting flag is true.
- Ensure that lighting calculations are performed per pixel by interpolating normals and applying the lighting factor.
-
Ensure Proper Normalization:
- Since you mentioned that the normals are already normalized, we'll proceed under that assumption. However, it's good practice to normalize the light direction to ensure accurate lighting calculations.
Below is the complete implementation with detailed explanations:
1. Define the applyLighting Method
Add the following method to your RenderEngine class. This method calculates the brightness factor based on the dot product of the normal and the light direction, scaled by the lightingCoefficient.
/**
* Applies lighting based on the vertex normal and light direction.
*
* @param normal The normalized normal vector of the vertex.
* @return A brightness factor between (1 - lightingCoefficient) and 1.
*/
private double applyLighting(Vector3f normal) {
// Ensure the light direction is normalized
Vector3f normalizedLightDir = lightDirection.normalize();
// Calculate the dot product between the normal and light direction
double dotProduct = normal.dot(normalizedLightDir);
// Clamp the dot product to [0, 1] to ensure no negative lighting
double l = Math.max(0.0, dotProduct);
// Calculate the brightness factor using the lighting coefficient
double brightness = (1 - lightingCoefficient) + lightingCoefficient * l;
return brightness;
}
2. Integrate applyLighting into the Rendering Pipeline
Modify the rasterizeTriangle method to utilize the applyLighting method when lighting is enabled. Here's the updated method with comments explaining each step:
/**
* Performs rasterization of a triangle and updates the graphics context with lighting.
*
* @param points Screen coordinates of the triangle's vertices.
* @param normals Normal vectors at each vertex.
* @param zValues Depth values for each vertex.
* @param zBuffer Z-buffer for depth testing.
* @param graphicsContext The JavaFX graphics context for drawing.
*/
private void rasterizeTriangle(Point2f[] points, Vector3f[] normals, float[] zValues, float[][] zBuffer, GraphicsContext graphicsContext) {
// Define base colors for the vertices (optional, can be replaced with texture colors)
Color colorA = Color.RED;
Color colorB = Color.BLACK;
Color colorC = Color.BLUE;
// Determine the bounding box of the triangle
int minX = clamp((int) Math.floor(Math.min(points[0].getX(), Math.min(points[1].getX(), points[2].getX()))), 0, zBuffer.length - 1);
int maxX = clamp((int) Math.ceil(Math.max(points[0].getX(), Math.max(points[1].getX(), points[2].getX()))), 0, zBuffer.length - 1);
int minY = clamp((int) Math.floor(Math.min(points[0].getY(), Math.min(points[1].getY(), points[2].getY()))), 0, zBuffer[0].length - 1);
int maxY = clamp((int) Math.ceil(Math.max(points[0].getY(), Math.max(points[1].getY(), points[2].getY()))), 0, zBuffer[0].length - 1);
for (int x = minX; x <= maxX; x++) {
for (int y = minY; y <= maxY; y++) {
// Calculate barycentric coordinates for the current pixel
float[] barycentric = calculateBarycentricCoordinates(points, x, y);
float lambda0 = barycentric[0];
float lambda1 = barycentric[1];
float lambda2 = barycentric[2];
// Check if the pixel is inside the triangle
if (isInsideTriangle(lambda0, lambda1, lambda2)) {
// Interpolate the depth value
float depth = interpolate(lambda0, lambda1, lambda2, zValues);
// Depth test
if (depth < zBuffer[x][y]) {
zBuffer[x][y] = depth;
// Interpolate the normal vector
Vector3f interpolatedNormal = new Vector3f(
lambda0 * normals[0].getX() + lambda1 * normals[1].getX() + lambda2 * normals[2].getX(),
lambda0 * normals[0].getY() + lambda1 * normals[1].getY() + lambda2 * normals[2].getY(),
lambda0 * normals[0].getZ() + lambda1 * normals[1].getZ() + lambda2 * normals[2].getZ()
).normalize(); // Ensure the interpolated normal is normalized
// Calculate the lighting brightness factor
double brightness = 1.0;
if (enableLighting) {
brightness = applyLighting(interpolatedNormal);
}
// Interpolate the base color (optional)
Color baseColor = interpolateColor(lambda0, lambda1, lambda2, colorA, colorB, colorC);
// Apply the brightness factor to the base color
Color finalColor = new Color(
clamp(baseColor.getRed() * brightness),
clamp(baseColor.getGreen() * brightness),
clamp(baseColor.getBlue() * brightness),
baseColor.getOpacity()
);
// Set the final color to the pixel
graphicsContext.getPixelWriter().setColor(x, y, finalColor);
}
}
}
}
}
3. Additional Helper Methods
Ensure that the following helper methods are properly defined in your RenderEngine class. These methods assist in color interpolation and normalization.
a. Color Interpolation
This method interpolates the color based on barycentric coordinates. You can customize the base colors as needed.
/**
* Interpolates the color of a pixel inside the triangle based on barycentric coordinates.
*
* @param lambda0 Barycentric coordinate λ0.
* @param lambda1 Barycentric coordinate λ1.
* @param lambda2 Barycentric coordinate λ2.
* @param colorA Color at the first vertex.
* @param colorB Color at the second vertex.
* @param colorC Color at the third vertex.
* @return Interpolated Color.
*/
private Color interpolateColor(float lambda0, float lambda1, float lambda2, Color colorA, Color colorB, Color colorC) {
double red = lambda0 * colorA.getRed() + lambda1 * colorB.getRed() + lambda2 * colorC.getRed();
double green = lambda0 * colorA.getGreen() + lambda1 * colorB.getGreen() + lambda2 * colorC.getGreen();
double blue = lambda0 * colorA.getBlue() + lambda1 * colorB.getBlue() + lambda2 * colorC.getBlue();
return new Color(clamp(red), clamp(green), clamp(blue), 1.0);
}
b. Vector Normalization
Ensure your Vector3f class has a normalize method. Here's a simple implementation:
public class Vector3f {
private double x, y, z;
// Existing constructors and methods...
/**
* Normalizes the vector.
*
* @return A new normalized Vector3f.
*/
public Vector3f normalize() {
double length = Math.sqrt(x * x + y * y + z * z);
if (length == 0) return new Vector3f(0, 0, 0);
return new Vector3f(x / length, y / length, z / length);
}
// Dot product method
public double dot(Vector3f other) {
return this.x * other.x + this.y * other.y + this.z * other.z;
}
// Getters and setters...
}
4. Usage Example
Here's how you can enable lighting and render your model with lighting applied:
// Create an instance of RenderEngine
RenderEngine renderEngine = new RenderEngine();
// Enable lighting
renderEngine.setEnableLighting(true);
// Configure other rendering options as needed
renderEngine.setEnableFill(true);
renderEngine.setEnableWireframe(false);
renderEngine.setEnableTexture(false);
// Set up camera, model, and other parameters
Camera camera = new Camera();
// Initialize camera parameters...
Model model = new Model();
// Load model vertices, polygons, normals, and texture...
// Set lighting parameters (optional)
renderEngine.setLightingDirection(new Vector3f(1, -1, -1)); // Example light direction
renderEngine.setLightingCoefficient(0.5);
// Render the model
GraphicsContext gc = canvas.getGraphicsContext2D();
int width = (int) canvas.getWidth();
int height = (int) canvas.getHeight();
renderEngine.render(gc, camera, model, width, height);
5. Complete RenderEngine Class with Lighting Integration
For clarity, here's the complete RenderEngine class incorporating the applyLighting method and the necessary modifications:
package com.cgvsu.render_engine;
import com.cgvsu.math.Matrix4f;
import com.cgvsu.math.Point2f;
import com.cgvsu.math.Vector2f;
import com.cgvsu.math.Vector3f;
import com.cgvsu.model.Model;
import com.cgvsu.model.Polygon;
import com.cgvsu.model.Texture;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import static com.cgvsu.render_engine.GraphicConveyor.multiplyMatrix4ByVector3;
import static com.cgvsu.render_engine.GraphicConveyor.scaleRotateTranslate;
/**
* Класс для рендеринга 3D моделей с использованием графического контекста JavaFX.
*/
public class RenderEngine {
private boolean enableFill = true; // Заливка полигона
private boolean enableWireframe = false; // Отрисовка каркаса
private boolean enableTexture = false; // Наложение текстур
private boolean enableLighting = false; // Включение освещения
private Vector3f lightDirection = new Vector3f(0, 0, -1);
private double lightingCoefficient = 0.5; // Коэффициент освещения (k)
/**
* Устанавливает режим заливки.
*
* @param enableFill true для заливки, false для отключения.
*/
public void setEnableFill(boolean enableFill) {
this.enableFill = enableFill;
}
/**
* Устанавливает режим отрисовки каркаса.
*
* @param enableWireframe true для включения, false для отключения.
*/
public void setEnableWireframe(boolean enableWireframe) {
this.enableWireframe = enableWireframe;
}
/**
* Устанавливает режим наложения текстур.
*
* @param enableTexture true для включения, false для отключения.
*/
public void setEnableTexture(boolean enableTexture) {
this.enableTexture = enableTexture;
}
/**
* Устанавливает режим освещения.
*
* @param enableLighting true для включения, false для отключения.
*/
public void setEnableLighting(boolean enableLighting) {
this.enableLighting = enableLighting;
}
/**
* Устанавливает направление освещения.
*
* @param lightDirection Вектор направления света.
*/
public void setLightingDirection(Vector3f lightDirection) {
this.lightDirection = lightDirection;
}
/**
* Устанавливает коэффициент освещения.
*
* @param lightingCoefficient Коэффициент освещения (k).
*/
public void setLightingCoefficient(double lightingCoefficient) {
this.lightingCoefficient = lightingCoefficient;
}
/**
* Вычисляет матрицу модель-представление-проекция с учетом камеры и трансформаций модели.
*
* @param camera Объект камеры, содержащий матрицы вида и проекции.
* @param rotate Вектор поворота модели.
* @param scale Вектор масштабирования модели.
* @param translate Вектор переноса модели.
* @return Матрица модель-представление-проекция.
*/
private Matrix4f calculateModelViewProjectionMatrix(Camera camera, Vector3f rotate, Vector3f scale, Vector3f translate) {
Matrix4f modelMatrix = scaleRotateTranslate(rotate, scale, translate);
Matrix4f viewMatrix = camera.getViewMatrix();
Matrix4f projectionMatrix = camera.getProjectionMatrix();
modelMatrix.transposition();
viewMatrix.transposition();
projectionMatrix.transposition();
Matrix4f mvpMatrix = new Matrix4f(projectionMatrix);
mvpMatrix.multiply(viewMatrix);
mvpMatrix.multiply(modelMatrix);
return mvpMatrix;
}
/**
* Инициализирует Z-буфер заданными размерами.
*
* @param width Ширина экрана.
* @param height Высота экрана.
* @return Двумерный массив Z-буфера, заполненный максимальными значениями глубины.
*/
private float[][] initializeZBuffer(int width, int height) {
float[][] zBuffer = new float[width][height];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
zBuffer[x][y] = Float.MAX_VALUE;
}
}
return zBuffer;
}
/**
* Выполняет рендеринг 3D модели на графическом контексте.
*
* @param graphicsContext Графический контекст JavaFX для рисования.
* @param camera Объект камеры, определяющий вид и проекцию.
* @param model Модель для рендеринга.
* @param width Ширина области рендеринга.
* @param height Высота области рендеринга.
*/
public void render(GraphicsContext graphicsContext, Camera camera, Model model, int width, int height) {
float[][] zBuffer = initializeZBuffer(width, height);
Matrix4f mvpMatrix = calculateModelViewProjectionMatrix(camera, model.getRotate(), model.getScale(), model.getTranslate());
Texture texture = model.getTexture();
for (Polygon polygon : model.getPolygons()) {
renderPolygon(graphicsContext, polygon, mvpMatrix, width, height, zBuffer, model, texture);
}
if (enableWireframe) {
renderWireframe(graphicsContext, model, mvpMatrix, width, height, zBuffer);
}
}
/**
* Рендерит отдельный многоугольник на графическом контексте.
*
* @param graphicsContext Графический контекст для рисования.
* @param polygon Многоугольник для рендеринга.
* @param mvpMatrix Матрица модель-представление-проекция.
* @param width Ширина области рендеринга.
* @param height Высота области рендеринга.
* @param zBuffer Z-буфер для отслеживания глубины пикселей.
* @param model Модель, содержащая вершины.
* @param texture Текстура модели.
*/
private void renderPolygon(GraphicsContext graphicsContext, Polygon polygon, Matrix4f mvpMatrix,
int width, int height, float[][] zBuffer, Model model, Texture texture) {
int[] vertexIndices = polygon.getVertexIndices().stream().mapToInt(Integer::intValue).toArray();
int[] textureIndices = polygon.getTextureVertexIndices().stream().mapToInt(Integer::intValue).toArray();
Point2f[] screenPoints = new Point2f[vertexIndices.length];
float[] zValues = new float[vertexIndices.length];
Vector2f[] textureCoords = new Vector2f[vertexIndices.length];
Vector3f[] normals = new Vector3f[vertexIndices.length];
for (int i = 0; i < vertexIndices.length; i++) {
Vector3f transformedVertex = transformVertex(model, vertexIndices[i], mvpMatrix);
screenPoints[i] = vertexToPoint(transformedVertex, width, height);
zValues[i] = transformedVertex.getZ();
if (enableTexture && textureIndices.length == vertexIndices.length && texture != null) {
Vector2f texCoord = model.getTextureVertices().get(textureIndices[i]);
textureCoords[i] = texCoord;
}
// Retrieve the normal for the current vertex
normals[i] = model.getNormals().get(vertexIndices[i]).normalize();
}
if (enableTexture && textureCoords.length == vertexIndices.length && texture != null) {
rasterizeTriangleWithTexture(screenPoints, zValues, textureCoords, zBuffer, graphicsContext, texture, normals);
} else if (enableFill) {
rasterizeTriangle(screenPoints, normals, zValues, zBuffer, graphicsContext);
}
}
/**
* Растеризирует треугольник с текстурированием и освещением.
*
* @param points Координаты точек треугольника на экране.
* @param zValues Значения глубины для каждой вершины.
* @param textureCoords Текстурные координаты для каждой вершины.
* @param zBuffer Z-буфер для отслеживания глубины пикселей.
* @param graphicsContext Графический контекст для рисования.
* @param texture Текстура модели.
* @param normals Нормали для каждой вершины.
*/
private void rasterizeTriangleWithTexture(Point2f[] points, float[] zValues, Vector2f[] textureCoords,
float[][] zBuffer, GraphicsContext graphicsContext, Texture texture, Vector3f[] normals) {
if (texture == null) {
System.err.println("Текстура не задана для модели.");
return;
}
int minX = clamp((int) Math.floor(Math.min(points[0].getX(), Math.min(points[1].getX(), points[2].getX()))), 0, zBuffer.length - 1);
int maxX = clamp((int) Math.ceil(Math.max(points[0].getX(), Math.max(points[1].getX(), points[2].getX()))), 0, zBuffer.length - 1);
int minY = clamp((int) Math.floor(Math.min(points[0].getY(), Math.min(points[1].getY(), points[2].getY()))), 0, zBuffer[0].length - 1);
int maxY = clamp((int) Math.ceil(Math.max(points[0].getY(), Math.max(points[1].getY(), points[2].getY()))), 0, zBuffer[0].length - 1);
for (int x = minX; x <= maxX; x++) {
for (int y = minY; y <= maxY; y++) {
float[] barycentric = calculateBarycentricCoordinates(points, x, y);
float lambda0 = barycentric[0];
float lambda1 = barycentric[1];
float lambda2 = barycentric[2];
if (isInsideTriangle(lambda0, lambda1, lambda2)) {
float depth = interpolate(lambda0, lambda1, lambda2, zValues);
if (depth < zBuffer[x][y]) {
zBuffer[x][y] = depth;
// Interpolate texture coordinates
float u = lambda0 * textureCoords[0].getX() + lambda1 * textureCoords[1].getX() + lambda2 * textureCoords[2].getX();
float v = lambda0 * textureCoords[0].getY() + lambda1 * textureCoords[1].getY() + lambda2 * textureCoords[2].getY();
// Fetch the color from the texture
Color textureColor = texture.getColor(u, v);
// Interpolate the normal vector
Vector3f interpolatedNormal = new Vector3f(
lambda0 * normals[0].getX() + lambda1 * normals[1].getX() + lambda2 * normals[2].getX(),
lambda0 * normals[0].getY() + lambda1 * normals[1].getY() + lambda2 * normals[2].getY(),
lambda0 * normals[0].getZ() + lambda1 * normals[1].getZ() + lambda2 * normals[2].getZ()
).normalize();
// Calculate the lighting brightness factor
double brightness = 1.0;
if (enableLighting) {
brightness = applyLighting(interpolatedNormal);
}
// Apply the brightness factor to the texture color
Color finalColor = new Color(
clamp(textureColor.getRed() * brightness),
clamp(textureColor.getGreen() * brightness),
clamp(textureColor.getBlue() * brightness),
textureColor.getOpacity()
);
// Set the final color to the pixel
graphicsContext.getPixelWriter().setColor(x, y, finalColor);
}
}
}
}
}
/**
* Выполняет растеризацию треугольника и обновляет графический контекст.
* Добавлено простейшее диффузное освещение.
*
* @param points Координаты точек треугольника на экране.
* @param normals Нормали для каждой вершины треугольника.
* @param zValues Значения глубины для каждой вершины.
* @param zBuffer Z-буфер для отслеживания глубины пикселей.
* @param graphicsContext Графический контекст для рисования.
*/
private void rasterizeTriangle(Point2f[] points, Vector3f[] normals, float[] zValues, float[][] zBuffer, GraphicsContext graphicsContext) {
// Define base colors for the vertices (optional)
Color colorA = Color.RED;
Color colorB = Color.BLACK;
Color colorC = Color.BLUE;
// Determine the bounding box of the triangle
int minX = clamp((int) Math.floor(Math.min(points[0].getX(), Math.min(points[1].getX(), points[2].getX()))), 0, zBuffer.length - 1);
int maxX = clamp((int) Math.ceil(Math.max(points[0].getX(), Math.max(points[1].getX(), points[2].getX()))), 0, zBuffer.length - 1);
int minY = clamp((int) Math.floor(Math.min(points[0].getY(), Math.min(points[1].getY(), points[2].getY()))), 0, zBuffer[0].length - 1);
int maxY = clamp((int) Math.ceil(Math.max(points[0].getY(), Math.max(points[1].getY(), points[2].getY()))), 0, zBuffer[0].length - 1);
for (int x = minX; x <= maxX; x++) {
for (int y = minY; y <= maxY; y++) {
// Calculate barycentric coordinates for the current pixel
float[] barycentric = calculateBarycentricCoordinates(points, x, y);
float lambda0 = barycentric[0];
float lambda1 = barycentric[1];
float lambda2 = barycentric[2];
// Check if the pixel is inside the triangle
if (isInsideTriangle(lambda0, lambda1, lambda2)) {
// Interpolate the depth value
float depth = interpolate(lambda0, lambda1, lambda2, zValues);
// Depth test
if (depth < zBuffer[x][y]) {
zBuffer[x][y] = depth;
// Interpolate the normal vector
Vector3f interpolatedNormal = new Vector3f(
lambda0 * normals[0].getX() + lambda1 * normals[1].getX() + lambda2 * normals[2].getX(),
lambda0 * normals[0].getY() + lambda1 * normals[1].getY() + lambda2 * normals[2].getY(),
lambda0 * normals[0].getZ() + lambda1 * normals[1].getZ() + lambda2 * normals[2].getZ()
).normalize(); // Ensure the interpolated normal is normalized
// Calculate the lighting brightness factor
double brightness = 1.0;
if (enableLighting) {
brightness = applyLighting(interpolatedNormal);
}
// Interpolate the base color (optional)
Color baseColor = interpolateColor(lambda0, lambda1, lambda2, colorA, colorB, colorC);
// Apply the brightness factor to the base color
Color finalColor = new Color(
clamp(baseColor.getRed() * brightness),
clamp(baseColor.getGreen() * brightness),
clamp(baseColor.getBlue() * brightness),
baseColor.getOpacity()
);
// Set the final color to the pixel
graphicsContext.getPixelWriter().setColor(x, y, finalColor);
}
}
}
}
}
/**
* Выполняет отрисовку каркаса модели (wireframe) без заливки.
*
* @param graphicsContext Графический контекст для рисования.
* @param model Модель для рендеринга.
* @param mvpMatrix Матрица модель-представление-проекция.
* @param width Ширина области рендеринга.
* @param height Высота области рендеринга.
* @param zBuffer Z-буфер для отслеживания глубины пикселей.
*/
private void renderWireframe(GraphicsContext graphicsContext, Model model, Matrix4f mvpMatrix, int width, int height, float[][] zBuffer) {
for (Polygon polygon : model.getPolygons()) {
int[] vertexIndices = polygon.getVertexIndices().stream().mapToInt(Integer::intValue).toArray();
Point2f[] screenPoints = new Point2f[vertexIndices.length];
float[] zValues = new float[vertexIndices.length];
for (int i = 0; i < vertexIndices.length; i++) {
Vector3f transformedVertex = transformVertex(model, vertexIndices[i], mvpMatrix);
screenPoints[i] = vertexToPoint(transformedVertex, width, height);
zValues[i] = transformedVertex.getZ();
}
// Draw lines between vertices
for (int i = 0; i < vertexIndices.length; i++) {
int next = (i + 1) % vertexIndices.length;
drawLine(graphicsContext, screenPoints[i], screenPoints[next], zValues[i], zValues[next], zBuffer);
}
}
}
/**
* Рисует линию между двумя точками с учетом Z-буфера.
*
* @param gc Графический контекст.
* @param p1 Первая точка.
* @param p2 Вторая точка.
* @param z1 Глубина первой точки.
* @param z2 Глубина второй точки.
* @param zBuffer Z-буфер.
*/
private void drawLine(GraphicsContext gc, Point2f p1, Point2f p2, float z1, float z2, float[][] zBuffer) {
int x0 = (int) p1.getX();
int y0 = (int) p1.getY();
int x1 = (int) p2.getX();
int y1 = (int) p2.getY();
int dx = Math.abs(x1 - x0);
int dy = Math.abs(y1 - y0);
int sx = x0 < x1 ? 1 : -1;
int sy = y0 < y1 ? 1 : -1;
int err = dx - dy;
while (true) {
if (x0 >= 0 && x0 < zBuffer.length && y0 >= 0 && y0 < zBuffer[0].length) {
float depth = interpolateDepth(x0, y0, p1, p2, z1, z2);
if (depth < zBuffer[x0][y0]) {
zBuffer[x0][y0] = depth;
gc.getPixelWriter().setColor(x0, y0, Color.BLACK);
}
}
if (x0 == x1 && y0 == y1) break;
int e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x0 += sx;
}
if (e2 < dx) {
err += dx;
y0 += sy;
}
}
}
/**
* Интерполирует глубину для пикселя в линии.
*
* @param x Координата X пикселя.
* @param y Координата Y пикселя.
* @param p1 Первая точка линии.
* @param p2 Вторая точка линии.
* @param z1 Глубина первой точки.
* @param z2 Глубина второй точки.
* @return Интерполированная глубина.
*/
private float interpolateDepth(int x, int y, Point2f p1, Point2f p2, float z1, float z2) {
float totalDistance = (float) Math.hypot(p2.getX() - p1.getX(), p2.getY() - p1.getY());
float currentDistance = (float) Math.hypot(x - p1.getX(), y - p1.getY());
return z1 + (z2 - z1) * (currentDistance / totalDistance);
}
/**
* Преобразует вершину в экранные координаты.
*
* @param vertex Вершина в пространстве камеры.
* @param width Ширина экрана.
* @param height Высота экрана.
* @return Точка на экране.
*/
private Point2f vertexToPoint(Vector3f vertex, int width, int height) {
float x = (float) ((vertex.getX() + 1) * 0.5 * width);
float y = (float) ((1 - (vertex.getY() + 1) * 0.5) * height); // Инвертирование Y
return new Point2f(x, y);
}
/**
* Применяет трансформацию к вершине модели.
*
* @param model Модель, содержащая вершины.
* @param vertexIndex Индекс вершины в модели.
* @param mvpMatrix Матрица модель-представление-проекция.
* @return Трансформированная вершина.
*/
private Vector3f transformVertex(Model model, int vertexIndex, Matrix4f mvpMatrix) {
Vector3f vertex = model.getVertices().get(vertexIndex);
return multiplyMatrix4ByVector3(mvpMatrix, vertex); // Предполагается, что эта функция реализована
}
/**
* Вычисляет барицентрические координаты точки относительно треугольника.
*
* @param points Координаты вершин треугольника.
* @param x Координата X точки.
* @param y Координата Y точки.
* @return Массив из трех барицентрических координат.
*/
private float[] calculateBarycentricCoordinates(Point2f[] points, int x, int y) {
float denom = ((points[1].getY() - points[2].getY()) * (points[0].getX() - points[2].getX()) +
(points[2].getX() - points[1].getX()) * (points[0].getY() - points[2].getY()));
float lambda0 = ((points[1].getY() - points[2].getY()) * (x - points[2].getX()) +
(points[2].getX() - points[1].getX()) * (y - points[2].getY())) / denom;
float lambda1 = ((points[2].getY() - points[0].getY()) * (x - points[2].getX()) +
(points[0].getX() - points[2].getX()) * (y - points[2].getY())) / denom;
float lambda2 = 1.0f - lambda0 - lambda1;
return new float[]{lambda0, lambda1, lambda2};
}
/**
* Проверяет, находится ли точка внутри треугольника на основе барицентрических координат.
*
* @param lambda0 Барицентрическая координата λ0.
* @param lambda1 Барицентрическая координата λ1.
* @param lambda2 Барицентрическая координата λ2.
* @return {@code true}, если точка внутри треугольника, иначе {@code false}.
*/
private boolean isInsideTriangle(float lambda0, float lambda1, float lambda2) {
return lambda0 >= 0 && lambda1 >= 0 && lambda2 >= 0;
}
/**
* Интерполирует значение по заданным весам.
*
* @param lambda0 Барицентрическая координата λ0.
* @param lambda1 Барицентрическая координата λ1.
* @param lambda2 Барицентрическая координата λ2.
* @param values Массив значений для интерполяции.
* @return Интерполированное значение.
*/
private float interpolate(float lambda0, float lambda1, float lambda2, float[] values) {
return (float) (lambda0 * values[0] + lambda1 * values[1] + lambda2 * values[2]);
}
/**
* Ограничивает значение в диапазоне [0, 1].
*
* @param value Исходное значение.
* @return Ограниченное значение.
*/
private double clamp(double value) {
return Math.max(0.0, Math.min(1.0, value));
}
/**
* Ограничивает значение между min и max.
*
* @param value Исходное значение.
* @param min Минимальное значение.
* @param max Максимальное значение.
* @return Ограниченное значение.
*/
private int clamp(int value, int min, int max) {
return Math.max(min, Math.min(max, value));
}
/**
* Интерполирует глубину для пикселя внутри треугольника.
*
* @param lambda0 Барицентрическая координата λ0.
* @param lambda1 Барицентрическая координата λ1.
* @param lambda2 Барицентрическая координата λ2.
* @param zValues Массив значений глубины для вершин.
* @return Интерполированная глубина.
*/
private float interpolateDepth(float lambda0, float lambda1, float lambda2, float[] zValues) {
return lambda0 * zValues[0] + lambda1 * zValues[1] + lambda2 * zValues[2];
}
/**
* Метод для применения освещения.
*
* @param normal Нормализованный нормаль к вершине.
* @return Коэффициент яркости после применения освещения.
*/
private double applyLighting(Vector3f normal) {
// Normalize light direction to ensure accurate calculations
Vector3f normalizedLightDir = lightDirection.normalize();
// Calculate the dot product between the normal and light direction
double dotProduct = normal.dot(normalizedLightDir);
// Clamp the dot product to [0, 1] to ensure no negative lighting
double l = Math.max(0.0, dotProduct);
// Calculate the brightness factor using the lighting coefficient
double brightness = (1 - lightingCoefficient) + lightingCoefficient * l;
return brightness;
}
}
6. Notes and Best Practices
-
Normalization: Ensure that both the normals and the light direction are normalized. This is crucial for accurate lighting calculations.
-
Lighting Coefficient: Adjust the lightingCoefficient to control the intensity of the lighting effect. A higher value means more influence from the lighting, while a lower value retains more of the base color.
-
Performance Considerations: Per-pixel lighting can be computationally intensive, especially for high-resolution models. Consider optimizing the rasterization and lighting calculations or implementing more efficient shading techniques if performance becomes an issue.
-
Extensibility: This implementation uses basic diffuse lighting. You can extend it to include specular highlights, multiple light sources, ambient lighting, and more advanced shading models like Phong or Blinn-Phong.
-
Texture and Lighting Interaction: When both texture and lighting are enabled, the final color is a combination of the texture color and the lighting brightness. Ensure that textures are appropriately mapped and that lighting calculations enhance the visual realism of the textured model.
By following this implementation, your RenderEngine will conditionally apply lighting to your 3D models during rendering based on the enableLighting flag. The lighting will be calculated per pixel using the interpolated normals, resulting in a smooth and realistic shading effect.