// sceneGraph.c

#include "sceneGraph.h"
#include <stdlib.h>

SceneNode* createSceneNode() {
    SceneNode* node = (SceneNode*)malloc(sizeof(SceneNode));
    identity(&node->transformation);
    identity(&node->worldTransformation);
    node->render = NULL;
    node->children = NULL;
    node->numChildren = 0;
    return node;
}

void addChild(SceneNode* parent, SceneNode* child) {
    parent->children = (SceneNode**)realloc(parent->children, sizeof(SceneNode*) * (parent->numChildren + 1));
    parent->children[parent->numChildren] = child;
    parent->numChildren++;
}

void updateSceneNode(SceneNode* node, mat4* parentTransformation) {
    multiply(&node->worldTransformation, parentTransformation, &node->transformation);
    for (int i = 0; i < node->numChildren; i++) {
        updateSceneNode(node->children[i], &node->worldTransformation);
    }
}

void renderSceneNode(SceneNode* node) {
    if (node->render) {
        node->render(node);
    }
    for (int i = 0; i < node->numChildren; i++) {
        renderSceneNode(node->children[i]);
    }
}

void freeSceneNode(SceneNode* node) {
    for (int i = 0; i < node->numChildren; i++) {
        freeSceneNode(node->children[i]);
    }
    free(node->children);
    free(node);
}