Friday, January 17, 2025

Translation in Computer graphics...

Please watch the following video of the translation used in freeCAD...




Translation is a fundamental transformation in computer graphics that moves an object from one position to another in a 2D or 3D space. Unlike other transformations such as scaling or rotation, translation preserves the shape and orientation of the object, altering only its position.


Key Concepts

  1. Definition: Translation involves shifting all points of an object by the same distance in a specified direction.

  2. Translation Vector: A translation is defined by a vector T=(tx,ty,tz)T = (t_x, t_y, t_z), where:

    • txt_x: Translation along the x-axis.
    • tyt_y: Translation along the y-axis.
    • tzt_z: Translation along the z-axis (for 3D graphics).
  3. Transformation Matrix: Translation is represented using a homogeneous coordinate matrix to allow for consistent matrix multiplication.

    • For 2D translation:

      T=[10tx01ty001]T = \begin{bmatrix} 1 & 0 & t_x \\ 0 & 1 & t_y \\ 0 & 0 & 1 \end{bmatrix}
    • For 3D translation:

      T=[100tx010ty001tz0001]T = \begin{bmatrix} 1 & 0 & 0 & t_x \\ 0 & 1 & 0 & t_y \\ 0 & 0 & 1 & t_z \\ 0 & 0 & 0 & 1 \end{bmatrix}
  4. Point Translation: A point P(x,y)P(x, y) (in 2D) or P(x,y,z)P(x, y, z) (in 3D) is translated by multiplying its homogeneous coordinate vector with the translation matrix:

    P=TPP' = T \cdot P
    • Where PP is the original point, PP' is the translated point, and TT is the translation matrix.

Example

2D Translation:

Suppose a point P(2,3)P(2, 3) is translated by T(4,5)T(4, 5):

T=[104015001],P=[231]T = \begin{bmatrix} 1 & 0 & 4 \\ 0 & 1 & 5 \\ 0 & 0 & 1 \end{bmatrix}, P = \begin{bmatrix} 2 \\ 3 \\ 1 \end{bmatrix} P=TP=[104015001][231]=[681]P' = T \cdot P = \begin{bmatrix} 1 & 0 & 4 \\ 0 & 1 & 5 \\ 0 & 0 & 1 \end{bmatrix} \cdot \begin{bmatrix} 2 \\ 3 \\ 1 \end{bmatrix} = \begin{bmatrix} 6 \\ 8 \\ 1 \end{bmatrix}

The new point is P(6,8)P'(6, 8).


Applications

  • Moving objects: Shifting the position of objects in animations, games, or simulations.
  • Camera movement: Adjusting the viewpoint in a scene.
  • Path planning: Moving objects along a trajectory.

Translation in 3D Graphics

For 3D, the process is similar but includes the z-dimension. A cube or other 3D model can be moved in any direction by applying a 3D translation matrix.


Translation is a cornerstone of computer graphics, forming the basis for more complex transformations like scaling, rotation, and perspective transformations. It plays a critical role in rendering, animation, and interactive graphics!

Here's the Python script for experimenting with translation using freeCAD.

import FreeCAD
import FreeCADGui
from PySide2 import QtWidgets

class TranslationApp(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("3D Translation in FreeCAD")
        self.setGeometry(300, 300, 300, 200)
        
        # UI Components
        layout = QtWidgets.QVBoxLayout()
        
        # Create a cube button
        self.create_cube_btn = QtWidgets.QPushButton("Create Cube")
        self.create_cube_btn.clicked.connect(self.create_cube)
        layout.addWidget(self.create_cube_btn)
        
        # Translation input fields
        self.tx_input = QtWidgets.QLineEdit()
        self.tx_input.setPlaceholderText("Translation X")
        layout.addWidget(self.tx_input)
        
        self.ty_input = QtWidgets.QLineEdit()
        self.ty_input.setPlaceholderText("Translation Y")
        layout.addWidget(self.ty_input)
        
        self.tz_input = QtWidgets.QLineEdit()
        self.tz_input.setPlaceholderText("Translation Z")
        layout.addWidget(self.tz_input)
        
        # Apply translation button
        self.apply_translation_btn = QtWidgets.QPushButton("Apply Translation")
        self.apply_translation_btn.clicked.connect(self.apply_translation)
        layout.addWidget(self.apply_translation_btn)
        
        # Reset button
        self.reset_btn = QtWidgets.QPushButton("Reset Cube Position")
        self.reset_btn.clicked.connect(self.reset_position)
        layout.addWidget(self.reset_btn)
        
        self.setLayout(layout)
        self.obj = None  # Store the created object

    def create_cube(self):
        """Creates a cube in FreeCAD."""
        if not FreeCAD.ActiveDocument:
            FreeCAD.newDocument("TranslationDemo")
        else:
            FreeCAD.ActiveDocument.clearAllObjects()
        
        self.obj = FreeCAD.ActiveDocument.addObject("Part::Box", "Cube")
        self.obj.Length = 10
        self.obj.Width = 10
        self.obj.Height = 10
        FreeCAD.ActiveDocument.recompute()
        FreeCADGui.ActiveDocument.ActiveView.setAnimationEnabled(True)
        QtWidgets.QMessageBox.information(self, "Cube Created", "A cube has been created.")

    def apply_translation(self):
        """Applies translation to the cube."""
        if self.obj is None:
            QtWidgets.QMessageBox.warning(self, "Error", "Create a cube first!")
            return
        
        try:
            tx = float(self.tx_input.text())
            ty = float(self.ty_input.text())
            tz = float(self.tz_input.text())
            
            # Apply translation
            translation_vector = FreeCAD.Vector(tx, ty, tz)
            self.obj.Placement.Base += translation_vector
            
            FreeCAD.ActiveDocument.recompute()
            QtWidgets.QMessageBox.information(self, "Success", f"Translated by ({tx}, {ty}, {tz})")
        except ValueError:
            QtWidgets.QMessageBox.warning(self, "Invalid Input", "Please enter valid numbers for translation.")

    def reset_position(self):
        """Resets the cube's position to the origin."""
        if self.obj is None:
            QtWidgets.QMessageBox.warning(self, "Error", "Create a cube first!")
            return
        
        self.obj.Placement.Base = FreeCAD.Vector(0, 0, 0)
        FreeCAD.ActiveDocument.recompute()
        QtWidgets.QMessageBox.information(self, "Position Reset", "Cube position reset to origin.")

# Main function to run the UI
def show_translation_app():
    window = TranslationApp()
    window.setParent(FreeCADGui.getMainWindow(), QtCore.Qt.Window)
    window.show()

# Run the application
show_translation_app()


No comments: