I would like to create a new type of node for the M3G so I can display text as another Transformable. My first approach to achieve so has been to extend from Group (I don't mind to have chindren ) and then create my own render method that I will call after the whole scene has been rendered.
My problem comes when I want to emulate the M3G rendering pipeline. This is what I do:
1.- Get active camera's transform and invert it.
2.- Get active camera's projection transform.
3.- Get the group's transform (my node's transform)
4.- Postmultiply the inverted active camera's transform by the group's transform. Let's call it modelViewTransform.
5.- PostMultiply the active camera's projection transform by the new modelViewTransform. Let's call it projectedTransform.
6.- Extract the position from the final projectedTransform using it's matrix: x = matrix, y = matrix, z = matrix
Should I divide each x and y by the z right to obtain the final x and y to draw the text shouldn't I? I even use the Graphics3D viewport values to obtain the final x and y to draw the text.
Well... I think that I have the theory right but the thing is that I cannot obtain the correct results. If I have the new TextNode in the same position as my Mesh nodes, it should be drawn in the same visual position but it doesn't. I must have something wrong. Anyone could help me?
Here you go the code for rendering the text:
public class TextNode extends Group
private Font font = null;
private int color = 0xFFFFFFFF;
private int x = 0, y = 0;
private String text = "";
private int anchor = Graphics.BASELINE | Graphics.HCENTER;
private Transform cameraTransform = new Transform();
private Transform textTransform = new Transform();
private Transform projectionTransform = new Transform();
private float textMatrix = new float;
public void render(Graphics g)
Graphics3D g3D = Graphics3D.getInstance();
// Get the camera transform, the projection transform and this Transformable's transform
Camera camera = g3D.getCamera(cameraTransform);
// Invert the camera transform
// Multiply the inverted camera transform by the text transform
// Multiply the projection transform by the result of the last multiplication
// Retrieve the final camera inverted and projected matrix
// Extract the position from the matrix
float x = textMatrix;
float y = textMatrix;
float z = textMatrix;
// Get the viewport information
int viewportX = g3D.getViewportX();
int viewportY = g3D.getViewportY();
int viewportWidth = g3D.getViewportWidth();
int viewportHeight = g3D.getViewportHeight();
// Calculate the final 2D position where to render the text
this.x = viewportX + (viewportWidth >> 1) + (int)(x / z);
this.y = viewportY + (viewportHeight >> 1) - (int)(y / z);
// Render the text
g.drawString(text, this.x, this.y, anchor);