Saturday, January 11, 2025

चरैवेति..... चरैवेति... CHARAIVETI... CHARAIVETI - my journey through the wilderness of Computer Graphics - Rotational transformation...


Source Code - python script...


import FreeCAD
import FreeCADGui
import Part
from PySide2.QtWidgets import QApplication, QVBoxLayout, QLabel, QLineEdit, QPushButton, QWidget


class RotationApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Rotation in Computer Graphics")
        self.setGeometry(100, 100, 300, 250)

        layout = QVBoxLayout()

        # Instruction label
        self.label_info = QLabel("Select an object or create one for rotation:")
        layout.addWidget(self.label_info)

        # Button to create a default cube
        self.create_button = QPushButton("Create Cube")
        self.create_button.clicked.connect(self.create_cube)
        layout.addWidget(self.create_button)

        # Input fields for rotation angles
        self.label_x = QLabel("Rotation Angle (X-axis):")
        layout.addWidget(self.label_x)
        self.input_x = QLineEdit("0")
        layout.addWidget(self.input_x)

        self.label_y = QLabel("Rotation Angle (Y-axis):")
        layout.addWidget(self.label_y)
        self.input_y = QLineEdit("0")
        layout.addWidget(self.input_y)

        self.label_z = QLabel("Rotation Angle (Z-axis):")
        layout.addWidget(self.label_z)
        self.input_z = QLineEdit("0")
        layout.addWidget(self.input_z)

        # Buttons
        self.apply_button = QPushButton("Apply Rotation")
        self.apply_button.clicked.connect(self.apply_rotation)
        layout.addWidget(self.apply_button)

        self.reset_button = QPushButton("Reset Rotation")
        self.reset_button.clicked.connect(self.reset_rotation)
        layout.addWidget(self.reset_button)

        self.setLayout(layout)

    def create_cube(self):
        """Create a default cube if no object exists."""
        doc = FreeCAD.ActiveDocument
        if not doc:
            doc = FreeCAD.newDocument("RotationDemo")

        cube = Part.makeBox(10, 10, 10)
        obj = doc.addObject("Part::Feature", "Cube")
        obj.Shape = cube
        doc.recompute()
        FreeCADGui.Selection.clearSelection()
        FreeCADGui.Selection.addSelection(obj)
        FreeCAD.Console.PrintMessage("Cube created and selected.\n")

    def get_selected_object(self):
        """Get the currently selected object in FreeCAD."""
        selected = FreeCADGui.Selection.getSelection()
        if len(selected) == 0:
            FreeCAD.Console.PrintMessage("No object selected!\n")
            return None
        return selected[0]

    def apply_rotation(self):
        """Apply rotation to the selected object."""
        obj = self.get_selected_object()
        if not obj:
            return

        try:
            # Get rotation angles from input fields
            angle_x = float(self.input_x.text())
            angle_y = float(self.input_y.text())
            angle_z = float(self.input_z.text())
        except ValueError:
            FreeCAD.Console.PrintMessage("Invalid input! Please enter numeric values.\n")
            return

        from math import radians
        angle_x = radians(angle_x)
        angle_y = radians(angle_y)
        angle_z = radians(angle_z)

        # Create rotation matrices
        rotation_x = FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), angle_x)
        rotation_y = FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), angle_y)
        rotation_z = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), angle_z)

        # Combine rotations
        combined_rotation = rotation_x.multiply(rotation_y).multiply(rotation_z)

        # Update object's Placement
        current_placement = obj.Placement
        new_rotation = combined_rotation.multiply(current_placement.Rotation)
        obj.Placement = FreeCAD.Placement(current_placement.Base, new_rotation)

        FreeCAD.ActiveDocument.recompute()
        FreeCAD.Console.PrintMessage(
            f"Applied rotation: X={self.input_x.text()}°, Y={self.input_y.text()}°, Z={self.input_z.text()}°\n"
        )

    def reset_rotation(self):
        """Reset the rotation of the selected object."""
        obj = self.get_selected_object()
        if not obj:
            return

        obj.Placement = FreeCAD.Placement(obj.Placement.Base, FreeCAD.Rotation())
        FreeCAD.ActiveDocument.recompute()
        FreeCAD.Console.PrintMessage("Rotation reset to default.\n")


# Run the application
if __name__ == "__main__":
    if not FreeCADGui.activeWorkbench():
        FreeCADGui.showMainWindow()

    app = QApplication.instance()
    if app is None:
        app = QApplication([])

    window = RotationApp()
    window.show()



 Rotational transformation is a fundamental operation in computer graphics, enabling the manipulation of objects by rotating them around a fixed point or axis. This transformation is crucial in a wide array of applications, from 3D modeling and animation to virtual reality and game development. Understanding rotational transformations requires knowledge of geometric principles, trigonometric functions, and matrix algebra, which form the backbone of this operation.

What is Rotational Transformation?

Rotational transformation involves changing the orientation of an object while maintaining its shape and size. This operation pivots the object around a fixed point, often referred to as the center of rotation, or an axis in 3D space. The rotation can occur in two or three dimensions and is defined by:

  • Angle of Rotation: Specifies the degree of rotation, typically in degrees or radians.
  • Direction: Clockwise or counterclockwise in 2D, and along the X, Y, or Z-axis in 3D.

Rotational transformations preserve the object's geometric properties, such as distances and angles, making them rigid transformations.


Mathematical Representation

2D Rotation

In two dimensions, rotation around the origin is achieved using a rotation matrix. The new coordinates (x,y)(x', y') of a point after rotation by an angle θ\theta are derived as:

[xy]=[cosθsinθsinθcosθ][xy]

Where:

  • (x,y)(x, y) are the original coordinates.
  • (x,y)(x', y') are the transformed coordinates.
  • θ\theta is the angle of rotation.

3D Rotation

In three dimensions, rotation is more complex as it can occur around any of the principal axes. The rotation matrices for the X, Y, and Z-axes are:

  • X-axis:
[1000cosθsinθ0sinθcosθ]\begin{bmatrix} 1 & 0 & 0 \\ 0 & \cos \theta & -\sin \theta \\ 0 & \sin \theta & \cos \theta \end{bmatrix}
  • Y-axis:
[cosθ0sinθ010sinθ0cosθ]\begin{bmatrix} \cos \theta & 0 & \sin \theta \\ 0 & 1 & 0 \\ -\sin \theta & 0 & \cos \theta \end{bmatrix}
  • Z-axis:
[cosθsinθ0sinθcosθ0001]\begin{bmatrix} \cos \theta & -\sin \theta & 0 \\ \sin \theta & \cos \theta & 0 \\ 0 & 0 & 1 \end{bmatrix}

To achieve rotation around an arbitrary axis, more advanced techniques like quaternions or axis-angle representation are used.

Applications of Rotational Transformation

1. 3D Modeling and Animation

Rotation is essential for animating objects, creating realistic movements, and positioning objects in 3D scenes. For example, a car wheel's rotation is simulated using rotational transformation.

2. Virtual Reality and Augmented Reality

In VR and AR, objects must be rotated dynamically based on user input or device orientation to ensure an immersive experience.

3. Robotics

Rotational transformations are used in robotics to calculate the movement of joints and arms, enabling precise control of robotic mechanisms.

4. Game Development

Rotations are fundamental in game engines for camera movement, object rotations, and character animations.

5. Simulation and Visualization

In simulations, such as flight or driving simulators, rotational transformations are used to model realistic object behaviors.

No comments: