sexta-feira, 5 de dezembro de 2025

UEFN Verse SG: Creating a Scene Graph component

In this article, we will create a simple Scene Graph component that will help us understand the relationship between entity, component, and Prefab.

Our component will generate a sort of platform bridge. It will have two fields that will be used to define the number of platforms generated and the distance between them.

The image below shows the platform bridge that will be generated:


We'll use UEFN's modeling mode to create a mesh that will serve as the platform. Change the editor to Modeling mode:


In the modeling panel, select the Cylinder shape:


Change the Cylinder Height to 50 and select a material. I chose the MI_Japanese_Wooden_Floor material.


Click on the level to position the mesh, and then click the Accept button to create the mesh.



In the Content Drawer, you'll see that a folder called Meshes has been created inside your project folder. Access the folder, select the mesh, and press F2 to rename it. Rename the Static Mesh to Platform_cylinder. Double-click the mesh to open the static mesh editor.

We need to add collision to the mesh. Let's use a simple shape. In the Collision menu, choose the Add Box Simplified Collision option. Save and close the editor.


It is necessary to compile the Verse code in order to create the mesh component in Verse that represents the mesh we created. To compile, go to the menu Verse > Compile Verse Code.


Now let's create the Prefab that will represent a platform. Access the Content Drawer, select your project folder, and right-click on an empty space to open the menu. Select Entity Prefab Definition and name this as Prefab_platform.



Double-click the Prefab_platform that was created to open the Prefab editor. In the Details tab, click the +Component button and select the transform_component. This component is necessary to define the position, rotation, and scale of the entity at the level.


Add another component and select the mesh_component. The mesh components available in the project will be displayed. Select the Platform_cylinder that we created.


The image below from the Prefab editor shows what the Prefab_platform looks like.



Save the Prefab and close the Prefab editor.

When we create a Prefab, UEFN creates a Verse class from this Prefab and registers it in the Assets.digest.verse file. This allows the creation of Prefab instances directly in the Verse code.

The next step is to create the Scene Graph component, which will generate multiple instances of Prefab_platform in different positions and add them to the entity that owns the component.

Open Verse Explorer, right-click on the project name, and select the option Add new Verse file to project.

Choose the Scene Graph Component template and name it platform_row_component. Click the Create Empty button.


Double-click the platform_row_component file to open it in Visual Studio Code.

Copy the Verse code below into the platform_row_component file:

using { /Verse.org }
using { /Verse.org/Native }
using { /Verse.org/SceneGraph }
using { /Verse.org/Simulation }
using { /Verse.org/SpatialMath }

platform_row_component<public> := class<final_super>(component):

    @editable
    NumberOfPlatforms<public>:int = 10

    @editable
    PlatformDistance<public>:float = 300.0

    OnBeginSimulation<override>():void =
        # Run OnBeginSimulation from the parent class
        (super:)OnBeginSimulation()

        for (Index := 0..NumberOfPlatforms - 1):
            Position := vector3{Forward := PlatformDistance * Index}

            NewPlatform := Prefab_platform{}

            NewPlatform.SetLocalTransform( transform{Translation := Position} )
            
            Entity.AddEntities( array{NewPlatform} )        
             
    OnSimulate<override>()<suspends>:void =
        Print("OnSimulate")


Let's analyze this code piece by piece. The line below declares that platform_row_component is a class that inherits from the component class. In other words, component is the parent class and is also known as the superclass.

platform_row_component<public> := class<final_super>(component): 

The <public> specifier indicates that the class will be available everywhere. The <final_super> specifier is a requirement of the Scene Graph to ensure the integrity of the system of entities and components.

Our component has two fields that can be edited directly in UEFN to configure the generation of the platform bridge.
    @editable
    NumberOfPlatforms<public>:int = 10

    @editable
    PlatformDistance<public>:float = 300.0

These fields use the <public> specifier to make them visible to other components. In Scene Graph programming, interaction between components is very common, so using constants with <public> access facilitates access to this data without the risk of it being modified by other components.

The Scene Graph component template code provides two functions where you can place the code that will be executed when the simulation starts:
  •  OnBeginSimulation<override>( ) : This function executes and completes immediately. Ideal for component preparation code that will only be executed once.
  •  OnSimulate<override>()<suspends> The <suspends> specifier indicates that this is an asynchronous function, meaning its completion does not need to be immediate. For example, here you can place code that makes the component wait for player interaction.

The code for generating the platform bridge is in the OnBeginSimulation<override> function. Right at the beginning of this function, we have the following line of code:
    (super:)OnBeginSimulation()

The component class, which is used as a superclass for the components, has an OnBeginSimulation() function that requires some configuration code to be executed. The (super:) indicates that the OnBeginSimulation() function to be executed is from the superclass.

The for expression is used to repeat its code block for each platform that will be generated. The value of Index is modified for each iteration of the for loop. The first value is 0 and the last value will be NumberOfPlatforms - 1.
    for (Index := 0..NumberOfPlatforms - 1): 

Inside the for loop, the Index value is used to calculate the position where the new Prefab_platform instance will be created.

Position := vector3{Forward := PlatformDistance * Index} 

This position is relative to the position of the entity that will contain our component. The platforms will be created following the Forward axis. To change the direction in which the platform bridge will be created, simply rotate the entity at the level.

Note: Since version 36.00, UEFN has used the LUF coordinate system. In this system, the coordinate axes are Left, Up, and Forward. To learn more about LUF, please refer to this Epic Games documentation: 

Left-Up-Forward Coordinate System


The constant NewPlatform stores a new instance of our Prefab_platform:

NewPlatform := Prefab_platform{} 


The SetLocalTransform() function specifies the platform relative transformation. In our example, you only need to set the Translation field of the transform. Rotation and scale use the default values.

NewPlatform.SetLocalTransform( transform{Translation := Position} ) 


The new instance of Prefab_platform needs to be added to the entity that contains our component. The component class has the constant Entity, which is a reference to this entity. The AddEntities function adds an array of entities to an entity. Therefore, it was necessary to create an array containing the instance referenced by NewPlatform.

Entity.AddEntities( array{NewPlatform} )


These actions are repeated for each iteration of the for loop.

Save the file and compile the Verse code using the Verse > Compile Verse Code option from the UEFN menu.

To complete this example, we need to add an entity at the level and add our platform_row_component to this entity. Follow these steps:

1. In UEFN, access the Place Actors panel. If the panel is not visible, access it in the top Window menu.

2. In Place Actors, select the Entities category and drag an entity to the level. In the Outliner tab, rename this new entity to PlatformBridge for easier identification.

3.  In the Details tab, click the +Component button and select our platform_row_component.


4. In the Details tab, you can modify the values ​​that are used in generating the platform bridge.


5. Position the entity slightly above the floor level to prevent the platform bridge from being created on the floor.


Save the level and load it in Fortnite by clicking the Launch Session button to see the platform bridge generated by our component.


Note: Unfortunately, the collision of platforms generated by the Verse code is not working correctly. My idea with this example was for the player to jump on the platforms to get across a chasm. However, the player is unable to stand on the platform.

The created Prefab is correct. If we add an instance of the Prefab directly to the level using UEFN, the collision works correctly and the player can stand on the platform.

I researched this situation online and confirmed that the Verse code is correct. I found the following item on an Epic Games page about Scene Graph issues:




This is the problem that must be occurring with our example. Scene Graph is still in Beta and they should fix this problem soon.
(December 2025) 


Table of Contents Verse  

UEFN Verse SG: Criando um componente Scene Graph

Neste artigo vamos criar um simples componente Scene Graph que irá nos ajudar a entender a relação entre entidade, componente e Prefab.

O nosso componente irá gerar uma espécie de ponte de plataformas. Ele terá dois campos que serão usados para definir o número de plataformas geradas e a distância entre elas.

A imagem abaixo mostra a ponte de plataformas que será gerada:


Vamos usar o modo de modelagem do UEFN para criar uma mesh que será a plataforma. Mude o editor para modo Modeling:


No painel de modelagem, seleciona a forma Cylinder:


Mude a altura (Height) do Cylinder para 50 e selecione algum material. Eu escolhi o material MI_Japanese_Wooden_Floor.


Clique no nível para posicionar o mesh e depois clique no botão Accept para criar o mesh.



No Content Drawer, veja que foi criada a pasta Meshes dentro da pasta do seu projeto. Acesse a pasta, selecione o mesh e pressione F2 pra renomear. Renomeie o Static Mesh para Platform_cylinder. De dois cliques no mesh para abrir o static mesh editor.

Precisamos adicionar colisão na mesh. Vamos usar uma forma simples. No menu Collision, escolha a opção Add Box Simplified Collision. Salve e feche o editor.


É necessário compilar o código verse para que seja criada o mesh component em Verse que representa o mesh que criamos.  Para compilar acesse o menu Verse > Compile Verse Code.


Agora vamos criar o Prefab que representará uma plataforma. Acesse o Content Drawer, selecione a pasta do seu projeto e clique com o botão direito e um espaço vazio para abrir o menu. Selecione Entity Prefab Definition e coloque o nome Prefab_platform para este Prefab.



Dê dois cliques no
Prefab_platform que foi criado para abrir o editor de Prefab. Na aba Details, clique no botão +Component e selecione o transform_component. Este componente é necessário para definir a posição, rotação e escala da entidade no nível.


Adicione outro componente e selecione o mesh_component. Serão exibidos os mesh_components disponíveis no projeto. Selecione o Platform_cylinder que criamos.


A imagem abaixo do editor do Prefab mostra como ficou o Prefab_platform.



Salve o Prefab e feche o editor Prefab.

Quando criamos um Prefab, o UEFN cria uma classe Verse deste Prefab e registra no arquivo Assets.digest.verse. Isto permite a criação de instâncias do Prefab direto no código Verse.

O próximo passo é a criação do componente Scene Graph que irá gerar várias instâncias do Prefab_platform em posições diferentes e adicioná-las à entidade que possui o componente. 

Abra o Verse Explorer, clique com o botão-direito no nome do projeto e escolha a opção Add new Verse file to project

Escolha o template Scene Graph Component e coloque o nome platform_row_component. Clique no botão Create Empty.


Dê um duplo clique no arquivo platform_row_component para abri-lo no Visual Studio Code.

Copie o código Verse abaixo para o componente platform_row_component:

using { /Verse.org }
using { /Verse.org/Native }
using { /Verse.org/SceneGraph }
using { /Verse.org/Simulation }
using { /Verse.org/SpatialMath }

platform_row_component<public> := class<final_super>(component):

    @editable
    NumberOfPlatforms<public>:int = 10

    @editable
    PlatformDistance<public>:float = 300.0

    OnBeginSimulation<override>():void =
        # Run OnBeginSimulation from the parent class
        (super:)OnBeginSimulation()

        for (Index := 0..NumberOfPlatforms - 1):
            Position := vector3{Forward := PlatformDistance * Index}

            NewPlatform := Prefab_platform{}

            NewPlatform.SetLocalTransform( transform{Translation := Position} )
            
            Entity.AddEntities( array{NewPlatform} )        
             
    OnSimulate<override>()<suspends>:void =
        Print("OnSimulate")


Vamos analisar este código por partes. A linha abaixo está declarando que platform_row_component é uma classe que herda da classe component. Ou seja, component é a classe pai e também é conhecida como a superclasse.

platform_row_component<public> := class<final_super>(component): 

O especificador <public> indica que a classe estará disponível em toda parte. O especificador <final_super> é uma exigência do Scene Graph para garantir a integridade do sistema de entidades e componentes.

O nosso componente possui dois campos que podem ser editados direto no UEFN para configurar a geração da ponte de plataformas.
    @editable
    NumberOfPlatforms<public>:int = 10

    @editable
    PlatformDistance<public>:float = 300.0

Estes campos usam o especificador <public> para que fiquem visíveis para outros componentes. Na programação com Scene Graph, a interação entre componentes  é muito comum, por isso o uso de constantes com acesso <public> facilita o acesso a estes dados sem correr o risco deles serem modificados por outros componentes.

O código de template do Scene Graph componente traz duas funções onde você pode colocar o código que será executado ao iniciar a simulação:
  •  OnBeginSimulation<override>( ) : Esta função tem execução e conclusão imediata. Ideal para códigos de preparação do componente que serão executados somente um vez. 
  •  OnSimulate<override>()<suspends> : O especificador <suspends> indica que esta é uma função assíncrona, ou seja sua conclusão não precisa ser imediata. Por exemplo, aqui você pode colocar um código que faz o componente aguardar uma interação do jogador.

O código de geração da ponte de plataforma está na função OnBeginSimulation<override>. Logo no início desta função, temos a seguinte linha de código:
    (super:)OnBeginSimulation()

A classe component que é usada como superclasse dos componentes, possui a função OnBeginSimulation() que deve ter algum código de configuração que deve ser executado. O (super:) indica que a função OnBeginSimulation() que será executada é a da superclasse.

A expressão for é usada para repetir o seu bloco de código para cada plataforma que será gerada. O valor de Index é modificado para cada iteração do for. O primeiro valor é 0 e o último valor será NumberOfPlatforms - 1.
    for (Index := 0..NumberOfPlatforms - 1): 

Dentro do laço for é usado o valor de Index para calcular a posição onde a nova instância do Prefab_platform será criada.

Position := vector3{Forward := PlatformDistance * Index} 

Esta posição é relativa à posição da entidade que terá o nosso componente. As plataformas serão criadas seguindo o eixo Forward. Para mudar a direção que a ponte de plataformas será criada, basta rotacionar a entidade no nível.

Nota: Desde a versão 36.00, a UEFN passou a usar o sistema de coordenada LUF. Neste sistema os eixos de coordenadas são Left, Up e Forward. Para saber mais sobre o LUF, acesse esta documentação da Epic Games:

Left-Up-Forward Coordinate System


A constante NewPlatform armazena uma nova instância do nosso Prefab_platform:

NewPlatform := Prefab_platform{} 


A função SetLocalTransform() especifica a transformação relativa da plataforma. Em nosso exemplo, só precisa definir o campo Translation do transform. A rotação e escala usam os valores padrões.

NewPlatform.SetLocalTransform( transform{Translation := Position} ) 


A nova instância do Prefab_platform precisa ser adicionada à entidade que contém o nosso componente. A classe component possui a constante Entity que é uma referência à esta entidade. A função AddEntities adiciona um array de entidades à uma entidade. Por isso foi preciso criar um array contendo a instância referenciada por NewPlatform.

Entity.AddEntities( array{NewPlatform} )


Estas ações são repetidas para cada iteração do laço for.

Salve o arquivo e compile o código Verse usando a opção Verse > Compile Verse Code do menu do UEFN. 

Para concluir este exemplo é preciso adicionar uma entidade ao nível e adicionar o nosso componente platform_row_component à esta entidade. Siga estes passos:

1. No UEFN, acesse o painel Place Actors. Se o painel não estiver visível, acesse ele pelo menu superior Window.

2. Em Place Actors, selecione a categoria Entities e arraste o entity para o nível. Na aba Outliner, renomeie esta nova entidade para PlatformBridge para facilitar a identificação.

3.  Na aba Details, clique no botão +Component e selecione o nosso componente platform_row_component.


4. Na aba Details, você pode modificar os valores que são usados na geração da ponte de plataformas.


5. Posicione a entidade um pouco acima do piso do nível para evitar que a ponte de plataformas seja criada no piso.


Salve o nível e carregue no Fortnite clicando no botão Launch Session para ver a ponte de plataformas gerada pelo nosso componente. 


Nota: Infelizmente, não está funcionando corretamente a colisão das plataformas que foram geradas pelo código Verse. A minha ideia com este exemplo era para o jogador pular nas plataformas para conseguir passar por algum abismo. Só que o jogador não consegue ficar em cima da plataforma. 

O Prefab criado está correto. Se adicionarmos uma instância do Prefab direto no nível pelo UEFN, a colisão funciona corretamente e o jogador consegue ficar em cima da plataforma.

Pesquisei na internet sobre essa situação e confirmei que o código Verse está correto. Encontrei em uma página da Epic Games sobre problemas do Scene Graph o seguinte item:



Este é o problema que deve estar ocorrendo com nosso exemplo. O Scene Graph ainda está em Beta e logo eles devem corrigir este problema.
(Dezembro de 2025) 










domingo, 16 de novembro de 2025

UEFN Verse SG: Introduction to Scene Graph

This is the first in a series of articles related to the Scene Graph system in UEFN.

Epic Games and many developers have emphasized the importance of the Scene Graph system, but for some developers or newcomers to UEFN, the benefits of learning and using Scene Graph may not be so clear.

First of all, the Scene Graph system does not replace the Creative Device system that has been available in UEFN since its launch. Let's compare the two systems:

  • Creative Device System: This is a high-level system focused on gameplay programming that allows for the manipulation of devices.
  • Scene Graph System: This is a low-level system that allows the use of the Verse language to manipulate the entities that make up the scene and to program custom components.

Through Scene Graph, Epic Games is providing developers with new tools that expand the possibilities of what can be built in UEFN.

Epic Games has made it clear that the Verse language and the Scene Graph system will be the cornerstones of programming in Unreal Engine 6. UEFN is a great lab to practice these concepts before the release of Unreal Engine 6. 

The Scene Graph is a structure that represents the elements of a scene in a hierarchical way and has these three fundamental concepts:

  • Entity: It is a container where components are placed. An entity can also contain other entities.
  • Component: This is what gives life to an entity. An entity can contain several components to define its physical, visual, and behavioral aspects. New components can be programmed using the Verse language.
  • Prefab: It is used to group a hierarchy of entities and components into a class and store it as a project asset. Multiple instances of a Prefab can be added at the level, and the Prefab class can be used directly in Verse code.


In this article, we will look at a basic workflow that involves these three concepts. It is very important that these concepts are clear before delving deeper into the study of the Scene Graph.

The first step is to create an empty entity at the level. This is done from the Place Actors tab, which can be opened in the top Window menu.

In the category icons on the left, select Entities and drag the entity into the level.


In the Details tab, you'll see that the entity added to the level has a transform_component, which is used to define the entity's location within the level.


Click the +Component button to add more components. A list of available components will be displayed. Some component types are abstract and require you to choose a subclass. For example, select mesh_component.


The static meshes available as mesh_component are the basic shapes listed below. Select the cone.



Fortnite's Static Meshes and FAB assets are not compatible with Scene Graph in UEFN. This is an important and sometimes frustrating point for those starting out with Scene Graph.

To use custom Static Meshes, you need to import a 3D mesh file such as an .fbx or create one using the UEFN modeling tools.

Now let's add another mesh_component to the entity that was created. However, if you click on +Component you will see that the mesh_component no longer appears in the component list. This happens because an entity can only have one component of each type.

We will need to create a child entity to add the mesh_component to this new entity. In the Outliner tab, right-click on the entity that was created and select Add Entity > entity:


In the Details tab of the child entity, click the +Component button and select mesh_component > cube. This cube will be used as the tabletop, so change the Scale of the UP axis (green) to 0.1.


In the level editor, use the green arrow to position the tabletop on top of the cone:


The next step is to convert this hierarchy of entities and components into a Prefab. It will be stored as a project Asset. This will allow instances of this Prefab to be added at the level using the level editor or Verse code.

In the Outliner tab, right-click the parent entity and select Save As Prefab... :



On the next screen, enter a name for your Prefab. I chose Prefab_Table. Then click the Create entity Class button.


The Prefab editor will display our new Prefab for editing. Close the Prefab editor and access the Content Drawer to view the created Prefab asset. In my example, the UEFN editor created a folder with the same name as the project folder:


Drag and drop the Prefab within the level to create new instances:


In this article, we'll stop here. In the next articles, we'll look at Entities, Components, and Prefabs in more detail. We'll also learn how to program our own component using Verse.


Table of Contents Verse 


UEFN Verse SG: Introdução ao Scene Graph

Este é o primeiro de uma série de artigos relacionados ao sistema de Scene Graph no UEFN.

A Epic Games e muitos desenvolvedores tem ressaltado a importância do sistema de Scene Graph, mas para alguns desenvolvedores ou novatos no UEFN talvez não seja tão claro quais são os benefícios de aprender e utilizar o Scene Graph.

Em primeiro lugar o sistema de Scene Graph não substitui o sistema de Creative Device que está disponível no UEFN desde seu lançamento. Vamos comparar os dois sistemas:

  • Sistema de Creative Device: É um sistema de alto nível voltado para a programação de gameplay que permite a manipulação dos dispositivos.
  • Sistema de Scene Graph: É um sistema de baixo nível que permite o uso da linguagem Verse para manipular as entidades que compõem a cena e programar componentes personalizados.

Através do Scene Graph, a Epic Games está fornecendo para os desenvolvedores novas ferramentas que expandem as possibilidades do que pode ser construído no UEFN.

A Epic Games já deixou claro que a linguagem Verse e o sistema de Scene Graph serão os pilares da programação na Unreal Engine 6. O UEFN é um ótimo laboratório para praticar estes conceitos antes do lançamento da Unreal Engine 6. 

O Scene Graph é uma estrutura que representa os elementos da cena de uma forma hierárquica e possui estes três conceitos fundamentais:

  • Entidade: É um container onde são colocados os componentes. Uma Entidade também pode conter outras entidades.
  • Componente: Isto é o que dá vida à uma entidade. Uma entidade pode conter vários componentes para definir seus aspectos físicos, visuais e comportamentais. Novos componentes podem ser programados usando a linguagem Verse.
  • Prefab: É usado para agrupar uma hierarquia de entidades e componentes em uma classe e guardar como um Asset do projeto. É possível adicionar várias instâncias de um Prefab no nível e usar a classe do Prefab diretamente no código Verse.


Neste artigo veremos um workflow básico que envolve estes três conceitos. É muito importante que estes conceitos estejam bem claros antes de aprofundar no estudo do Scene Graph.

O primeiro passo é criar uma entidade vazia no nível. Isto é feito a partir da aba Place Actors que pode ser aberta no menu superior Window

Nos ícones de categorias na esquerda selecione Entities e arraste o entity para dentro do nível.


Veja na aba Details que a entidade que foi adicionada ao nível tem um transform_component que é usado para definir a localização da entidade no nível. 


Clique no botão +Component para adicionar outros componentes. Será exibida uma listagem dos componentes disponíveis. Alguns tipos de componentes são abstratos e é preciso escolher uma subclasse dele. Por exemplo, selecione o mesh_component.


As Static Meshes disponíveis como mesh_component são as formas básicas listadas abaixo. Selecione o cone.


As Static Meshes do Fortnite e os assets do FAB não são compatíveis com Scene Graph no UEFN. Este é um ponto importante e às vezes frustrante para quem está iniciando com Scene Graph.

Para usarmos Static Meshes customizadas é preciso importar um arquivo de malha 3d como .fbx ou criar um usando as ferramentas de modelagem do UEFN.

Agora vamos adicionar outro mesh_component à entidade que foi criada. Entretanto, se você clicar no +Component verá que o mesh_component não aparece mais na listagem de componentes. Isto acontece porque uma entidade só pode ter um componente de cada tipo. 

Será necessário criar uma entidade filha para adicionar o mesh_component nesta nova entidade. Na aba Outliner, clique com o botão direito na entidade que foi criada e selecione Add Entity > entity


Na aba Details da entidade filha, clique no botão +Component e selecione mesh_component > cube. Este cubo será usado como o tampo de uma mesa por isso altere o Scale do eixo UP (verde) para 0.1 :


No editor de nível, use a seta verde para posicionar o tampo da mesa no topo do cone:


O próximo passo é converter esta hierarquia de entidades e componentes em um Prefab. Ele será armazenada como um Asset do projeto. Isto permitirá a adição de instâncias deste Prefab no nível usando o editor de nível ou código Verse.

Na aba Outliner, clique com o botão direito na entidade pai e selecione Save As Prefab... :


Na tela seguinte, insira um nome para o seu Prefab. Eu escolhi Prefab_Table. Depois clique no botão Create entity Class.


O editor de Prefab será exibido com o nosso novo Prefab para edição. Feche o editor de Prefab e acesse o Content Drawer para visualizar o asset do Prefab que foi criado. No meu exemplo o editor UEFN criou uma pasta com o mesmo nome da pasta do projeto:


Arraste o Prefab e solte dentro do nível para criar novas instâncias:


Neste artigo vamos parar por aqui. Nos próximos artigos veremos as Entidades, Componentes e Prefab em mais detalhes. Também vamos aprender como programar nosso próprio componente usando Verse.

 

Sumário Verse