Usar ArrayMesh

Este tutorial presentará los fundamentos del uso de un ArrayMesh.

Para ello, utilizaremos la función add_surface_from_arrays(), que toma hasta cinco parámetros. Los dos primeros son obligatorios, mientras que los últimos tres son opcionales.

El primer parámetro es el PrimitiveType, un concepto de OpenGL que instruye a la GPU cómo organizar el primitivo basado en los vértices proporcionados, es decir, si representan triángulos, líneas, puntos, etc. Véase Mesh.PrimitiveType para ver las opciones disponibles.

The second parameter, arrays, is the actual Array that stores the mesh information. The array is a normal Godot array that is constructed with empty brackets []. It stores a Packed**Array (e.g. PackedVector3Array, PackedInt32Array, etc.) for each type of information that will be used to build the surface.

Los posibles elementos de los arrays se enumeran a continuación, junto con la posición que deben tener dentro de arrays. Véase Mesh.ArrayType para obtener una lista completa.

Index

Mesh.ArrayType Enum

Tipo de array

0

ARRAY_VERTEX

PackedVector3Array o PackedVector2Array

1

ARRAY_NORMAL

PackedVector3Array

2

ARRAY_TANGENT

PackedFloat32Array or PackedFloat64Array of groups of 4 floats. The first 3 floats determine the tangent, and the last float the binormal direction as -1 or 1.

3

ARRAY_COLOR

PackedColorArray

4

ARRAY_TEX_UV

PackedVector2Array o PackedVector3Array

5

ARRAY_TEX_UV2

PackedVector2Array o PackedVector3Array

10

ARRAY_BONES

PackedFloat32Array of groups of 4 floats or PackedInt32Array of groups of 4 ints. Each group lists indexes of 4 bones that affects a given vertex.

11

ARRAY_WEIGHTS

PackedFloat32Array or PackedFloat64Array of groups of 4 floats. Each float lists the amount of weight the corresponding bone in ARRAY_BONES has on a given vertex.

12

ARRAY_INDEX

PackedInt32Array

En la mayoría de casos, al crear un mesh, lo definimos pro las posiciones de sus vertices. Por lo tanto, generalmente se requiere el arreglo de indices (en el indice 0) mientras que el arreglo de índices (en el índice 12) es opcional y solo se utilizará si se incluye. También es posible crear una mesh solo con el arreglo de índices y sin el arreglo de vértices, pero eso está más allá del alcance de este tutorial.

All the other arrays carry information about the vertices. They are optional and will only be used if included. Some of these arrays (e.g. ARRAY_COLOR) use one entry per vertex to provide extra information about vertices. They must have the same size as the vertex array. Other arrays (e.g. ARRAY_TANGENT) use four entries to describe a single vertex. These must be exactly four times larger than the vertex array.

For normal usage, the last three parameters in add_surface_from_arrays() are typically left empty.

Setting up the ArrayMesh

In the editor, create a MeshInstance3D and add an ArrayMesh to it in the Inspector. Normally, adding an ArrayMesh in the editor is not useful, but in this case it allows us to access the ArrayMesh from code without creating one.

Next, add a script to the MeshInstance3D.

Dentro de _ready(), crea un nuevo Array.

var surface_array = []

Este será el arreglo en el que guardaremos la información de la superficie; contendrá todos los arrays de datos que la superficie necesita. Godot espera que tenga un tamaño de Mesh.ARRAY_MAX, así que redimensiona el arreglo en consecuencia.

var surface_array = []
surface_array.resize(Mesh.ARRAY_MAX)

A continuación, crea los arreglos para cada tipo de datos que utilizarás.

var verts = PackedVector3Array()
var uvs = PackedVector2Array()
var normals = PackedVector3Array()
var indices = PackedInt32Array()

Una vez que hayas llenado tus arreglos de datos con tu geometría, puedes crear una malla agregando cada arreglo a surface_array y luego comprometiéndolo a la malla.

surface_array[Mesh.ARRAY_VERTEX] = verts
surface_array[Mesh.ARRAY_TEX_UV] = uvs
surface_array[Mesh.ARRAY_NORMAL] = normals
surface_array[Mesh.ARRAY_INDEX] = indices

# No blendshapes, lods, or compression used.
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, surface_array)

Nota

En este ejemplo, utilizamos Mesh.PRIMITIVE_TRIANGLES, pero puedes utilizar cualquier tipo de primitiva disponible en la malla.

A continuación se muestra el código completo:

extends MeshInstance3D

func _ready():
    var surface_array = []
    surface_array.resize(Mesh.ARRAY_MAX)

    # PackedVector**Arrays for mesh construction.
    var verts = PackedVector3Array()
    var uvs = PackedVector2Array()
    var normals = PackedVector3Array()
    var indices = PackedInt32Array()

    #######################################
    ## Insert code here to generate mesh ##
    #######################################

    # Assign arrays to surface array.
    surface_array[Mesh.ARRAY_VERTEX] = verts
    surface_array[Mesh.ARRAY_TEX_UV] = uvs
    surface_array[Mesh.ARRAY_NORMAL] = normals
    surface_array[Mesh.ARRAY_INDEX] = indices

    # Create mesh surface from mesh array.
    # No blendshapes, lods, or compression used.
    mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, surface_array)

The code that goes in the middle can be whatever you want. Below we will present some example code for generating shapes, starting with a rectangle.

Generar un rectángulo

Since we are using Mesh.PRIMITIVE_TRIANGLES to render, we will construct a rectangle with triangles.

A rectangle is formed by two triangles sharing four vertices. For our example, we will create a rectangle with its top left point at (0, 0, 0) with a width and length of one as shown below:

A rectangle made of two triangles sharing four vertices.

To draw this rectangle, define the coordinates of each vertex in the verts array.

verts = PackedVector3Array([
        Vector3(0, 0, 0),
        Vector3(0, 0, 1),
        Vector3(1, 0, 0),
        Vector3(1, 0, 1),
    ])

The uvs array helps describe where parts of a texture should go onto the mesh. The values range from 0 to 1. Depending on your texture, you may want to change these values.

uvs = PackedVector2Array([
        Vector2(0, 0),
        Vector2(1, 0),
        Vector2(0, 1),
        Vector2(1, 1),
    ])

The normals array is used to describe the direction the vertices face and is used in lighting calculations. For this example, we will default to the Vector3.UP direction.

normals = PackedVector3Array([
        Vector3.UP,
        Vector3.UP,
        Vector3.UP,
        Vector3.UP,
    ])

The indices array defines the order vertices are drawn. Godot renders in a clockwise direction, meaning that we must specify the vertices of a triangle we want to draw in clockwise order.

For example, to draw the first triangle, we will want to draw the vertices (0, 0, 0), (1, 0, 0), and (0, 0, 1) in that order. This is the same as drawing vert[0], vert[2], and vert[1], i.e., indices 0, 2, and 1, in the verts array. These index values are what the indices array defines.

Index

verts[Index]

uvs[Index]

normals[Index]

0

(0, 0, 0)

(0, 0)

Vector3.UP

1

(0, 0, 1)

(1, 0)

Vector3.UP

2

(1, 0, 0)

(0, 1)

Vector3.UP

3

(1, 0, 1)

(1, 1)

Vector3.UP

indices = PackedInt32Array([
        0, 2, 1, # Draw the first triangle.
        2, 3, 1, # Draw the second triangle.
    ])

Put together, the rectangle generation code looks like:

extends MeshInstance3D

func _ready():

  # Insert setting up the PackedVector**Arrays here.

  verts = PackedVector3Array([
          Vector3(0, 0, 0),
          Vector3(0, 0, 1),
          Vector3(1, 0, 0),
          Vector3(1, 0, 1),
      ])

  uvs = PackedVector2Array([
          Vector2(0, 0),
          Vector2(1, 0),
          Vector2(0, 1),
          Vector2(1, 1),
      ])

  normals = PackedVector3Array([
          Vector3.UP,
          Vector3.UP,
          Vector3.UP,
          Vector3.UP,
      ])

  indices = PackedInt32Array([
          0, 2, 1,
          2, 3, 1,
      ])

  # Insert committing to the ArrayMesh here.

For a more complex example, see the sphere generation section below.

Generar una esfera

Aquí tienes un ejemplo de código para generar una esfera. Aunque el código está presentado en GDScript, no hay nada específico de Godot en el enfoque para generarlo. Esta implementación no tiene nada en particular que ver con ArrayMeshes y es simplemente un enfoque genérico para generar una esfera. Si tienes dificultades para entenderlo o quieres aprender más sobre geometría procedural en general, puedes utilizar cualquier tutorial que encuentres en línea.

extends MeshInstance3D

var rings = 50
var radial_segments = 50
var radius = 1

func _ready():

    # Insert setting up the PackedVector**Arrays here.

    # Vertex indices.
    var thisrow = 0
    var prevrow = 0
    var point = 0

    # Loop over rings.
    for i in range(rings + 1):
        var v = float(i) / rings
        var w = sin(PI * v)
        var y = cos(PI * v)

        # Loop over segments in ring.
        for j in range(radial_segments + 1):
            var u = float(j) / radial_segments
            var x = sin(u * PI * 2.0)
            var z = cos(u * PI * 2.0)
            var vert = Vector3(x * radius * w, y * radius, z * radius * w)
            verts.append(vert)
            normals.append(vert.normalized())
            uvs.append(Vector2(u, v))
            point += 1

            # Create triangles in ring using indices.
            if i > 0 and j > 0:
                indices.append(prevrow + j - 1)
                indices.append(prevrow + j)
                indices.append(thisrow + j - 1)

                indices.append(prevrow + j)
                indices.append(thisrow + j)
                indices.append(thisrow + j - 1)

        prevrow = thisrow
        thisrow = point

  # Insert committing to the ArrayMesh here.

Guardar

Finalmente, podemos utilizar la clase ResourceSaver para guardar la ArrayMesh. Esto es útil cuando queremos generar una malla y luego utilizarla posteriormente sin tener que volver a generarla.

# Saves mesh to a .tres file with compression enabled.
ResourceSaver.save(mesh, "res://sphere.tres", ResourceSaver.FLAG_COMPRESS)