}
я хочу добавить несколько доп объектов в мое окно: функию перерасчета нормалей. Для этого надо в окне сделать 9 полей, куда пользователь будет вводить углы разворота, координаты переноса и масштаб. обрабаатывать должна функция - affineTransformations(). которая в свою очередь должна перерасчитывать нормали:
package com.cgvsu.render_engine;
import com.cgvsu.math.*;
import static java.lang.Math.*;
public class GraphicConveyor {
code
/**
* Аффинные преобразования
* она кстати уникальная для каждого объекта... пупупу
*
* @return {@code Matrix4f} - матрица из локальной системы координат в мировую
*/
public static Matrix4f rotateScaleTranslate(Vector3f rotate, Vector3f scale, Vector3f translate) {
Matrix4f r = calculateRotate(rotate.getX(),rotate.getY(), rotate.getZ());
Matrix4f s = calculateScale(scale.getX(),scale.getY(), scale.getZ());
Matrix4f t = calculateTranslate(new Vector3f(translate.getX(),translate.getY(), translate.getZ()));
t.multiply(r);
t.multiply(s);
return new Matrix4f(t);
}
/**
* Аффинные преобразования - увеличение/уменьшение объекта
*
* @param vector3f вектор переноса
* @return {@code Matrix4f} - матрица переноса
*/
public static Matrix4f calculateTranslate(Vector3f vector3f) {
return calculateTranslate(new Vector4f(vector3f.getX(),vector3f.getY(),vector3f.getZ(),1));
}
private static Matrix4f calculateTranslate(Vector4f vector) {
Matrix4f res = new Matrix4f(1);
for (int i = 0; i < res.getElements().length-1; i++) {
res.setElement(i, 3, vector.getNum(i));
}
return res;
}
public static Matrix4f Rotate(float alpha, float beta, float gamma) {
return calculateRotate(alpha, beta, gamma);
}
// мб потом почитаю что такое кватернион и немного переделаю код, пока пусть так будет
private static Matrix4f calculateRotate(float alpha, float beta, float gamma) {
// вокруг x
float[] rotateX = new float[]{
1, 0, 0, 0,
0, (float) cos(alpha), (float) sin(alpha), 0,
0, (float) -sin(alpha), (float) cos(alpha), 0,
0, 0, 0, 1
};
// вокруг y
float[] rotateY = new float[]{
(float) cos(beta), 0, (float) sin(beta), 0,
0, 1, 0, 0,
(float) -sin(beta), 0, (float) cos(beta), 0,
0, 0, 0, 1
};
// вокруг z
float[] rotateZ = new float[]{
(float) cos(gamma), (float) sin(gamma), 0, 0,
(float) -sin(gamma), (float) cos(gamma), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
};
Matrix4f rotateAboutX = new Matrix4f(rotateX);
Matrix4f rotateAboutY = new Matrix4f(rotateY);
Matrix4f rotateAboutZ = new Matrix4f(rotateZ);
// сначала крутим вокруг x, потом y, потом z (да, в реале умножаем сначала Z, потом ыгрик, потом х (а) - плохо)
rotateAboutZ.multiply(rotateAboutY);
rotateAboutZ.multiply(rotateAboutX);
return rotateAboutZ;
}
/**
* Аффинные преобразования - увеличение/уменьшение объекта
*
* @param scaleX растяжение по x
* @param scaleY растяжение по y
* @param scaleZ растяжение по z
* @return {@code Matrix4f} - матрица растяжения (по факту просто по главной диагонали будут стоять не 1, а растяжение наше)
*/
public static Matrix4f calculateScale(float scaleX, float scaleY, float scaleZ) {
float[] scale = new float[]{scaleX, scaleY, scaleZ};
return calculateScale(scale);
}
// надо еще продумать, как обновлять это все... наверное, потом придумаю... надеюсь, молюсь...
private static Matrix4f calculateScale(float[] scale) {
Matrix4f result = new Matrix4f(1);
for (int i = 0; i < scale.length; i++) {
result.setElement(i, i, scale[i]);
}
return result;
}
public static Matrix4f lookAt(Vector3f eye, Vector3f target) {
return lookAt(eye, target, new Vector3f(0F, 1.0F, 0F));
}
/**
* Система корд камеры +перевод всех объектов сцены в систему координат камеры
*
* @param eye ее позиция в мировых координатах
* @param target куда смотрит наша камера
* @param up единичный вектор для y - основа будущих корд камеры
* @return {@code Matrix4f} - матрица прямоугольной системы координат камеры, записанная в мировых координатах сцены.
*/
private static Matrix4f lookAt(Vector3f eye, Vector3f target, Vector3f up) {
Vector3f resultX = new Vector3f();
Vector3f resultY = new Vector3f();
Vector3f resultZ = new Vector3f();
resultZ.sub(target, eye);
resultX = up.cross(resultZ);
resultY = resultZ.cross(resultX);
resultX.normalize();
resultY.normalize();
resultZ.normalize();
float[] matrix = new float[]{
resultX.getX(), resultY.getX(), resultZ.getX(), 0,
resultX.getY(), resultY.getY(), resultZ.getY(), 0,
resultX.getZ(), resultY.getZ(), resultZ.getZ(), 0,
-resultX.dot(eye), -resultY.dot(eye), -resultZ.dot(eye), 1};
return new Matrix4f(matrix);
}
/**
* Матрица перспективы.
*
* @param fov угол обзора
* @param aspectRatio соотношение сторон экрана
* @param nearPlane ближний план
* @param farPlane дальний план
* @return {@code Matrix4f} - матрица перспективы.
*/
public static Matrix4f perspective(
final float fov,
final float aspectRatio,
final float nearPlane,
final float farPlane) {
float tangentMinusOnDegree = (float) (1.0F / (tan(fov * 0.5F))); // fov задается как половина от всего угла
float[] res = {
tangentMinusOnDegree / aspectRatio, 0, 0, 0,
0, tangentMinusOnDegree, 0, 0,
0, 0, (farPlane + nearPlane) / (farPlane - nearPlane), 1.0F,
0, 0, 2 * (nearPlane * farPlane) / (nearPlane - farPlane), 0
};
return new Matrix4f(res);
}
/**
* Получаем последний вектор нормализованный вектор v для трансформации вершины и отображения последней на экране
*
* @param matrix P*V*M
* @param vertex корды точки?
* @return {@code Vector3f} - нормализованный конечный вектор (скорее всего, нормаль к вершине).
*/
public static Vector3f multiplyMatrix4ByVector3(final Matrix4f matrix, final Vector3f vertex) {
Vector4f res = matrix.multiply(new Vector4f(vertex.getX(), vertex.getY(), vertex.getZ(), 1));
float w = res.getW();
return new Vector3f(res.getX() / w, res.getY() / w, res.getZ() / w);
}
/**
* Получаем последний вектор нормализованный вектор v для трансформации вершины и отображения последней на экране
*
* @param width ширина
* @param height высота
* @param vertex нормаль вершины
* @return {@code Point2f} - получаем корды точки на экране.
*/
public static Point2f vertexToPoint(final Vector3f vertex, final int width, final int height) {
return new Point2f(vertex.getX() * width + width / 2.0F, -vertex.getY() * height + height / 2.0F);
}
}
To achieve your goal of adding rotation, translation, and scaling capabilities to your JavaFX application, you'll need to modify your user interface to include input fields for these transformations and update your affineTransformations() method to apply these transformations to your model and recalculate the normals.
Here's a step-by-step guide to help you implement this functionality:
1. Modify the FXML to Include Input Fields
First, you'll need to add nine TextField elements to your FXML file for the rotation angles, translation coordinates, and scale factors.
The GridPane is used to neatly arrange the input fields and labels.
Each TextField has an fx:id so it can be accessed in your controller.
The Apply Transformations button will call the affineTransformations() method when clicked.
The Canvas position is adjusted (layoutX="220.0") to prevent overlap with the input fields.
2. Update the Controller to Handle Input Fields
In your controller (GuiController), you need to declare the @FXML variables corresponding to the TextField elements and update the affineTransformations() method to read the inputs and apply transformations.
Parsing Input Values: We parse the text from each TextField and convert it to a float. For rotation angles, we convert degrees to radians since trigonometric functions in Java use radians.
Applying Transformations: We call a new method applyTransformations() on the mesh object to apply the transformations.
Recalculating Normals: After transforming the mesh, we recalculate the normals by calling mesh.recalculateNormals().
Redrawing the Scene: We clear the canvas and call RenderEngine.render() to redraw the transformed model.
3. Update the Model Class to Apply Transformations
You'll need to add a method to your Model class to apply the transformations to the vertices.
Updated Model Class (Model.java)
java
package com.cgvsu.model;
import com.cgvsu.math.Matrix4f;
import com.cgvsu.math.Vector3f;
import com.cgvsu.render_engine.GraphicConveyor;
public class Model {
// Existing fields ...
// Apply transformations to the model's vertices
public void applyTransformations(Vector3f rotation, Vector3f scale, Vector3f translation) {
// Calculate the transformation matrix
Matrix4f transformationMatrix = GraphicConveyor.rotateScaleTranslate(rotation, scale, translation);
// Apply the transformation matrix to each vertex
for (int i = 0; i < vertices.size(); i++) {
Vector3f vertex = vertices.get(i);
Vector3f transformedVertex = GraphicConveyor.multiplyMatrix4ByVector3(transformationMatrix, vertex);
vertices.set(i, transformedVertex);
}
}
// Recalculate normals
public void recalculateNormals() {
// Clear existing normals
normals.clear();
// For each face, calculate the normal
for (Face face : faces) {
Vector3f v0 = vertices.get(face.getVertexIndices().get(0));
Vector3f v1 = vertices.get(face.getVertexIndices().get(1));
Vector3f v2 = vertices.get(face.getVertexIndices().get(2));
Vector3f edge1 = v1.subtract(v0);
Vector3f edge2 = v2.subtract(v0);
Vector3f normal = edge1.cross(edge2).normalize();
// Add normal to the list
normals.add(normal);
// Update the face normal index
face.getNormalIndices().clear();
face.getNormalIndices().add(normals.size() - 1);
face.getNormalIndices().add(normals.size() - 1);
face.getNormalIndices().add(normals.size() - 1);
}
}
}
Notes:
applyTransformations: This method applies the transformation matrix to each vertex in the mesh.
recalculateNormals: This method recalculates the normals based on the transformed vertices.
4. Implement the Recalculation of Normals
The recalculateNormals() method calculates the normals for the transformed mesh. This is crucial for rendering the model correctly, especially if you have lighting calculations based on normals.
Explanation:
Clearing Normals: We clear the existing normals because they are no longer valid after the transformation.
Calculating Normals: For each face in the model, we retrieve the vertices that make up the face, calculate two edge vectors, and compute the cross product to find the normal.
Normalizing: The resulting normal vector is normalized to make it a unit vector.
Updating Faces: We update the normal indices in each face to reference the newly calculated normals.
5. Ensure Thread Safety and UI Responsiveness
Since transformations and rendering can be computationally intensive, ensure that long-running tasks are executed on a background thread if necessary to keep the UI responsive.
6. Test the Application
After implementing the above changes, test your application by:
Loading a model.
Entering values in the input fields for rotation, translation, and scaling.
Clicking the Apply Transformations button.
Observing the transformed model and verifying that the normals are recalculated correctly.
Additional Tips
Input Validation: Consider adding more robust input validation and user feedback mechanisms to handle invalid inputs gracefully.
Default Values: You might want to set default values in the input fields to avoid NumberFormatException when the fields are empty.
UI Enhancements: For better user experience, you can organize the input fields using additional UI elements like TitledPane, Separator, or adjust the layout to suit your application's design.
Continuous Updates: If you want the transformations to be applied in real-time as the user changes the input values, you can add listeners to the TextField elements.
Conclusion
By following these steps, you should be able to add the desired functionality to your JavaFX application, allowing users to input rotation angles, translation coordinates, and scale factors, apply these transformations to the model, and recalculate the normals accordingly.
If you encounter any issues or have further questions, feel free to ask!