Repository: pygfx/pygfx
Pull request #234 (2022-01-14 13:29:32)

Polyhedrons
This adds new built-in geometry generator functions:

* Tetrahedron
* Octahedron
* Icosahedron
* Dodecahedron

The functions include radius and subdivision parameters, everything is vectorized. Particularly the triangle subdivision feature was pretty tricky to get right!

I didn't expose the polyhedron generator itself via the public api (`gfx.polyhedron_geometry`) since it isn't very friendly (you need to provide seed vertex and index buffers) but users can still import it directly to use it if they want to.

Other changes:

* Since I ported the approach from three.js to vectorized numpy code I figured I should move our copy of their license to a more generic location
* Added unit tests for the polyhedron generator functions
* Promoted numerical numpy warnings to errors in the test suite

Screenshot of the example:

![image](https://user-images.githubusercontent.com/1882046/149523146-d6724db5-1cdf-41d9-990c-3975ed3f9e4a.png)

Alternative rendering with phong material and no texture mapping:

![image](https://user-images.githubusercontent.com/1882046/149524787-9d9b7a95-213f-4659-86f2-72401bfac244.png)


almarklein: Nice! What do the subdivisions do? the same as for the cube?

There's this trick where you take the minimal polyhedron (the Tetrahedron?), then subdivide each face into two triangles, and push the new vertices to the unit sphere. You then repeat this process `n` times, and you get the mesh for a sphere that is uniformly sampled (as opposed to the very uneven size of the faces in a long-lat sphere). Texture mapping does not really work with such a sphere, but you need much less vertices to get a round-appearing mesh. Anyway, probably something for another day.
Korijn: > Nice! What do the subdivisions do? the same as for the cube?

Sort of, yes! In the example screenshot you can see on the left an icosahedron that has been subdivided twice. 

> There's this trick where you take the minimal polyhedron (the Tetrahedron?), then subdivide each face into two triangles, and push the new vertices to the unit sphere. You then repeat this process `n` times, and you get the mesh for a sphere that is uniformly sampled (as opposed to the very uneven size of the faces in a long-lat sphere). Texture mapping does not really work with such a sphere, but you need much less vertices to get a round-appearing mesh. Anyway, probably something for another day.

I think that's equivalent to what is shown here!

Except everything is vectorized, no for loops and list pushing here :)

Korijn: Face orientation fixed, looks good at subdivisions=0:

![image](https://user-images.githubusercontent.com/1882046/149734122-c2a0f684-6bb1-412b-ab5b-6b855ee713e5.png)

Korijn: I added an example to show how subdivision works, it's equivalent to what I see here https://threejs.org/docs/?q=tetra#api/en/geometries/TetrahedronGeometry

It's clearly not equivalent to what you mentioned earlier, by the way.

So I'm satisfied with this PR for now.
almarklein: > It's clearly not equivalent to what you mentioned earlier, by the way.

That's odd ... how else could one subdivide? Could it be that the subdivision results in an uneven distribution because in between the subdivisions the vertices are not normalized so that they're on the unit sphere? Maybe something to look at later.

Anyway, LGTM!
Korijn: > > It's clearly not equivalent to what you mentioned earlier, by the way.
> 
> That's odd ... how else could one subdivide? Could it be that the subdivision results in an uneven distribution because in between the subdivisions the vertices are not normalized so that they're on the unit sphere? Maybe something to look at later.
> 
> Anyway, LGTM!

Yeah I think it could be fixed by using some other formula than linspace, probably something involved pi :) but let's save it for later

Patch:
diff --git a/examples/geometry_polyhedron.py b/examples/geometry_polyhedron.py
new file mode 100644
index 0000000..bcfd935
--- /dev/null
+++ b/examples/geometry_polyhedron.py
@@ -0,0 +1,44 @@
+"""
+Example showing multiple rotating polyhedrons.
+"""
+
+from wgpu.gui.auto import WgpuCanvas, run
+import pygfx as gfx
+
+
+canvas = WgpuCanvas()
+renderer = gfx.renderers.WgpuRenderer(canvas)
+scene = gfx.Scene()
+
+material = gfx.MeshPhongMaterial()
+geometries = [
+    gfx.tetrahedron_geometry(),
+    gfx.octahedron_geometry(),
+    gfx.icosahedron_geometry(),
+    gfx.dodecahedron_geometry(),
+]
+
+polyhedrons = [gfx.Mesh(geometries[i], material) for i in range(5)]
+for i, polyhedron in enumerate(polyhedrons):
+    polyhedron.position.set(6 - i * 3, 0, 0)
+    scene.add(polyhedron)
+
+background = gfx.Background(None, gfx.BackgroundMaterial((0, 1, 0, 1), (0, 1, 1, 1)))
+scene.add(background)
+
+camera = gfx.PerspectiveCamera(70, 16 / 9)
+camera.position.z = 10
+
+
+def animate():
+    for polyhedron in polyhedrons:
+        rot = gfx.linalg.Quaternion().set_from_euler(gfx.linalg.Euler(0.01, 0.02))
+        polyhedron.rotation.multiply(rot)
+
+    renderer.render(scene, camera)
+    canvas.request_draw()
+
+
+if __name__ == "__main__":
+    canvas.request_draw(animate)
+    run()
diff --git a/examples/geometry_polyhedron_subdivisions.py b/examples/geometry_polyhedron_subdivisions.py
new file mode 100644
index 0000000..7e38b57
--- /dev/null
+++ b/examples/geometry_polyhedron_subdivisions.py
@@ -0,0 +1,23 @@
+"""
+Example showing subdivided polyhedrons.
+"""
+
+import pygfx as gfx
+
+
+scene = gfx.Scene()
+
+material = gfx.MeshBasicMaterial(wireframe=True, side="FRONT")
+geometries = [gfx.tetrahedron_geometry(subdivisions=i) for i in range(4)]
+
+for i, geometry in enumerate(geometries):
+    polyhedron = gfx.Mesh(geometry, material)
+    polyhedron.position.set(6 - i * 3, 0, 0)
+    scene.add(polyhedron)
+
+background = gfx.Background(None, gfx.BackgroundMaterial((0, 1, 0, 1), (0, 1, 1, 1)))
+scene.add(background)
+
+
+if __name__ == "__main__":
+    gfx.show(scene, up=gfx.linalg.Vector3(0, 0, 1))
diff --git a/pygfx/__init__.py b/pygfx/__init__.py
index 615f576..c7fd000 100644
--- a/pygfx/__init__.py
+++ b/pygfx/__init__.py
@@ -16,3 +16,31 @@ from .utils.show import show
 
 __version__ = "0.1.5"
 version_info = tuple(map(int, __version__.split(".")))
+
+
+# Elements of this library are derived from three.js, original license
+# at time of writing copied here:
+# ---
+# The MIT License
+#
+# Copyright © 2010-2022 three.js authors
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+# ---
+# End of original license copy.
diff --git a/pygfx/geometries/__init__.py b/pygfx/geometries/__init__.py
index 3a79dd9..143737e 100644
--- a/pygfx/geometries/__init__.py
+++ b/pygfx/geometries/__init__.py
@@ -6,6 +6,12 @@ from ._compat import trimesh_geometry
 from ._cylinder import cylinder_geometry, cone_geometry
 from ._sphere import sphere_geometry
 from ._plane import plane_geometry
+from ._polyhedron import (
+    octahedron_geometry,
+    icosahedron_geometry,
+    dodecahedron_geometry,
+    tetrahedron_geometry,
+)
 from ._toroidal import torus_knot_geometry, klein_bottle_geometry
 
 # Define __all__ for e.g. Sphinx
diff --git a/pygfx/geometries/_polyhedron.py b/pygfx/geometries/_polyhedron.py
new file mode 100644
index 0000000..e4f29b5
--- /dev/null
+++ b/pygfx/geometries/_polyhedron.py
@@ -0,0 +1,345 @@
+import numpy as np
+
+from ._base import Geometry
+
+
+def tetrahedron_geometry(radius=1.0, subdivisions=0):
+    """Create geometry representing a tetrahedron, centered
+    around the origin.
+
+    The vertices lie on the surface of a sphere of the
+    given radius. The faces are optionally subdivided
+    if subdivisions>0.
+
+    Parameters:
+        radius (int): The vertices lie on the surface of a sphere
+            with this radius.
+        subdivisions (int): The amount of times the tetrahedron
+            faces will be subdivided, where 0 (the default)
+            means no subdivision.
+    """
+    positions = np.array(
+        [
+            [1, 1, 1],
+            [-1, -1, 1],
+            [-1, 1, -1],
+            [1, -1, -1],
+        ],
+        dtype=np.float32,
+    )
+
+    indices = np.array(
+        [
+            [2, 0, 1],
+            [0, 2, 3],
+            [1, 0, 3],
+            [2, 1, 3],
+        ],
+        dtype=np.int32,
+    )
+
+    return polyhedron_geometry(positions, indices, radius, subdivisions)
+
+
+def octahedron_geometry(radius=1.0, subdivisions=0):
+    """Create geometry representing a octahedron, centered
+    around the origin.
+
+    The vertices lie on the surface of a sphere of the
+    given radius. The faces are optionally subdivided
+    if subdivisions>0.
+
+    Parameters:
+        radius (float): The vertices lie on the surface of a sphere
+            with this radius.
+        subdivisions (int): The amount of times the
+            faces will be subdivided, where 0 (the default)
+            means no subdivision.
+    """
+    positions = np.array(
+        [
+            [1, 0, 0],
+            [-1, 0, 0],
+            [0, 1, 0],
+            [0, -1, 0],
+            [0, 0, 1],
+            [0, 0, -1],
+        ],
+        dtype=np.float32,
+    )
+
+    indices = np.array(
+        [
+            [0, 4, 2],
+            [0, 3, 4],
+            [0, 5, 3],
+            [0, 2, 5],
+            [1, 5, 2],
+            [1, 3, 5],
+            [1, 4, 3],
+            [1, 2, 4],
+        ],
+        dtype=np.int32,
+    )
+
+    return polyhedron_geometry(positions, indices, radius, subdivisions)
+
+
+def icosahedron_geometry(radius=1.0, subdivisions=0):
+    """Create geometry representing a icosahedron, centered
+    around the origin.
+
+    The vertices lie on the surface of a sphere of the
+    given radius. The faces are optionally subdivided
+    if subdivisions>0.
+
+    Parameters:
+        radius (float): The vertices lie on the surface of a sphere
+            with this radius.
+        subdivisions (int): The amount of times the
+            faces will be subdivided, where 0 (the default)
+            means no subdivision.
+    """
+    t = (1 + np.sqrt(5)) / 2
+
+    positions = np.array(
+        [
+            [-1, t, 0],
+            [1, t, 0],
+            [-1, -t, 0],
+            [1, -t, 0],
+            [0, -1, t],
+            [0, 1, t],
+            [0, -1, -t],
+            [0, 1, -t],
+            [t, 0, -1],
+            [t, 0, 1],
+            [-t, 0, -1],
+            [-t, 0, 1],
+        ],
+        dtype=np.float32,
+    )
+
+    indices = np.array(
+        [
+            [0, 5, 11],
+            [0, 1, 5],
+            [0, 7, 1],
+            [0, 10, 7],
+            [0, 11, 10],
+            [1, 9, 5],
+            [5, 4, 11],
+            [11, 2, 10],
+            [10, 6, 7],
+            [7, 8, 1],
+            [3, 4, 9],
+            [3, 2, 4],
+            [3, 6, 2],
+            [3, 8, 6],
+            [3, 9, 8],
+            [4, 5, 9],
+            [2, 11, 4],
+            [6, 10, 2],
+            [8, 7, 6],
+            [9, 1, 8],
+        ],
+        dtype=np.int32,
+    )
+
+    return polyhedron_geometry(positions, indices, radius, subdivisions)
+
+
+def dodecahedron_geometry(radius=1.0, subdivisions=0):
+    """Create geometry representing a dodecahedron, centered
+    around the origin.
+
+    The vertices lie on the surface of a sphere of the
+    given radius. The faces are optionally subdivided
+    if subdivisions>0.
+
+    Parameters:
+        radius (float): The vertices lie on the surface of a sphere
+            with this radius.
+        subdivisions (int): The amount of times the
+            faces will be subdivided, where 0 (the default)
+            means no subdivision.
+    """
+    t = (1 + np.sqrt(5)) / 2
+    r = 1 / t
+
+    positions = np.array(
+        [
+            [-1, -1, -1],
+            [-1, -1, 1],
+            [-1, 1, -1],
+            [-1, 1, 1],
+            [1, -1, -1],
+            [1, -1, 1],
+            [1, 1, -1],
+            [1, 1, 1],
+            [0, -r, -t],
+            [0, -r, t],
+            [0, r, -t],
+            [0, r, t],
+            [-r, -t, 0],
+            [-r, t, 0],
+            [r, -t, 0],
+            [r, t, 0],
+            [-t, 0, -r],
+            [t, 0, -r],
+            [-t, 0, r],
+            [t, 0, r],
+        ],
+        dtype=np.float32,
+    )
+
+    indices = np.array(
+        [
+            [3, 7, 11],
+            [3, 15, 7],
+            [3, 13, 15],
+            [7, 17, 19],
+            [7, 6, 17],
+            [7, 15, 6],
+            [17, 8, 4],
+            [17, 10, 8],
+            [17, 6, 10],
+            [8, 16, 0],
+            [8, 2, 16],
+            [8, 10, 2],
+            [0, 1, 12],
+            [0, 18, 1],
+            [0, 16, 18],
+            [6, 2, 10],
+            [6, 13, 2],
+            [6, 15, 13],
+            [2, 18, 16],
+            [2, 3, 18],
+            [2, 13, 3],
+            [18, 9, 1],
+            [18, 11, 9],
+            [18, 3, 11],
+            [4, 12, 14],
+            [4, 0, 12],
+            [4, 8, 0],
+            [11, 5, 9],
+            [11, 19, 5],
+            [11, 7, 19],
+            [19, 14, 5],
+            [19, 4, 14],
+            [19, 17, 4],
+            [1, 14, 12],
+            [1, 5, 14],
+            [1, 9, 5],
+        ],
+        dtype=np.int32,
+    )
+
+    return polyhedron_geometry(positions, indices, radius, subdivisions)
+
+
+def polyhedron_geometry(
+    positions: np.ndarray, indices: np.ndarray, radius: float, subdivisions: int
+):
+    """Procedurally generate geometry representing a polyhedron, centered
+    around the origin.
+
+    The vertices lie on the surface of a sphere of the
+    given radius. The faces are optionally subdivided
+    if subdivisions>0.
+
+    Parameters:
+        positions (ndarray): The vertices used to initialize polyhedron
+            generation.
+        indices (ndarray): The face index used to initialize polyhedron
+            generation.
+        radius (float): The vertices lie on the surface of a sphere
+            with this radius.
+        subdivisions (int): The amount of times the
+            faces will be subdivided, where 0 (the default)
+            means no subdivision.
+    """
+    # subdivide faces
+    faces = positions[indices]
+    a = faces[..., 0, :]
+    ab = faces[..., 1, :] - a  # face winding convention
+    ac = faces[..., 2, :] - a
+
+    # assume we're creating a grid for vectorization purposes
+    # and throw out half at the end...
+    n = subdivisions + 2
+    # set up the grid to have origin in the top right
+    # so we can use numpy's upper triangle indexing
+    i = np.linspace(1.0, 0.0, n, dtype=np.float32)
+    j = np.linspace(0.0, 1.0, n, dtype=np.float32)
+    alpha, beta = np.meshgrid(i, j)
+    # grid shape is (n_faces, 3, n, n)
+    grid = a[..., None, None] + alpha * ab[..., None, None] + beta * ac[..., None, None]
+
+    # zero out all the elements in the lower corner of the grid
+    # in other words those positions which lie outside of the original face
+    grid = np.triu(grid)
+
+    # normalize the positions so they lie on the surface a sphere
+    # grid shape is (n_faces, n, n, 3)
+    grid = np.moveaxis(grid, 1, 3)
+    # keeping nan's so we can filter by that later
+    with np.errstate(invalid="ignore"):
+        grid /= np.linalg.norm(grid, axis=-1)[..., None]
+
+    # create an index array for a single face's plane of quads
+    indices = np.arange(n ** 2, dtype=np.uint32).reshape((n, n))
+    index = np.empty((n - 1, n - 1, 2, 3), dtype=np.uint32)
+    index[:, :, 0, 0] = indices[np.arange(n - 1)[:, None], np.arange(n - 1)[None, :]]
+    # the remainder of the indices for every panel are relative
+    # note that they are constructed such that the diagonal aligns
+    # with that of np.triu; otherwise we get nan vertices in all
+    # faces that include the diagonal
+    index[:, :, 0, 1] = index[:, :, 0, 0] + 1
+    index[:, :, 0, 2] = index[:, :, 0, 0] + n + 1
+    index[:, :, 1, 0] = index[:, :, 0, 0] + n + 1
+    index[:, :, 1, 1] = index[:, :, 1, 0] - 1
+    index[:, :, 1, 2] = index[:, :, 1, 0] - n - 1
+
+    # now index the grid
+    grid = grid.reshape(grid.shape[0], -1, grid.shape[-1])
+    # we get (n_faces, n-1, n-1, 2, 3 vertices, xyz)
+    faces = grid[:, index]
+    # and we reshape to get our new list of triangles
+    faces = faces.reshape(-1, 3, 3)
+    # filter out any triangles that contain nan elements
+    nan_index = np.any(np.isnan(faces), axis=(-1, -2))
+    faces = faces[~nan_index]
+    positions = faces.reshape(-1, 3)
+
+    # now that we have our subdivided faces with duplicated vertices
+    # we can compute normals
+    a = faces[..., 0, :]
+    ab = faces[..., 1, :] - a  # face winding convention
+    ac = faces[..., 2, :] - a
+    face_normals = np.cross(ab, ac)
+    face_normals /= np.linalg.norm(face_normals, axis=-1)[..., None]
+    normals = np.broadcast_to(face_normals[..., None, :], faces.shape)
+
+    # and our texcoords via spherical coordinates
+    # NOTE: if the initial faces straddle the boundary between 2pi back to 0
+    # you will get a weird seam. that can be handled but we don't do so for now
+    x, y, z = np.moveaxis(faces, -1, 0)
+    uu = np.arctan2(y, x) / (np.pi * 2)
+    vv = np.arccos(z) / np.pi
+    texcoords = np.stack([uu, vv], axis=-1)
+
+    # after all this, scale the points to the radius
+    # we don't do this earlier so we can rely on the assumption that vectors
+    # are normalized there
+    faces *= radius
+
+    # technically if meshmaterial didn't require an index buffer we could leave this out
+    indices = np.arange(positions.size, dtype=np.int32).reshape(-1, 3)
+
+    return Geometry(
+        indices=indices,
+        positions=positions,
+        normals=normals.reshape(-1, 3),
+        texcoords=texcoords.reshape(-1, 2),
+    )
diff --git a/pygfx/linalg/__init__.py b/pygfx/linalg/__init__.py
index 6ba0480..dad5566 100644
--- a/pygfx/linalg/__init__.py
+++ b/pygfx/linalg/__init__.py
@@ -1,31 +1,5 @@
 # flake8: noqa
 
-# Most of this module is derived from three.js, original license at time of writing copied below:
-# ---
-# The MIT License
-#
-# Copyright © 2010-2020 three.js authors
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-# ---
-# End of original license copy.
-
 from .utils import *
 from .cylindrical import *
 from .euler import *


Test patch:
diff --git a/conftest.py b/conftest.py
index 642c564..396683c 100644
--- a/conftest.py
+++ b/conftest.py
@@ -10,3 +10,13 @@ def predictable_random_numbers():
     see http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.random.seed.html
     """
     np.random.seed(0)
+
+
+@pytest.fixture(autouse=True, scope="session")
+def numerical_exceptions():
+    """
+    Ensure any numerical errors raise a warning in our test suite
+    The point is that we enforce such cases to be handled explicitly in our code
+    Preferably using local `with np.errstate(...)` constructs
+    """
+    np.seterr(all="raise")
diff --git a/tests/geometries/test_polyhedron.py b/tests/geometries/test_polyhedron.py
new file mode 100644
index 0000000..f24d763
--- /dev/null
+++ b/tests/geometries/test_polyhedron.py
@@ -0,0 +1,44 @@
+import numpy as np
+
+from pygfx.geometries import (
+    dodecahedron_geometry,
+    octahedron_geometry,
+    icosahedron_geometry,
+    tetrahedron_geometry,
+)
+
+
+def test_polyhedrons():
+    for nr_faces, factory in [
+        [4, tetrahedron_geometry],
+        [8, octahedron_geometry],
+        [20, icosahedron_geometry],
+        [36, dodecahedron_geometry],
+    ]:
+        g = factory()
+        assert hasattr(g, "indices")
+        assert hasattr(g, "positions")
+        assert hasattr(g, "normals")
+        assert hasattr(g, "texcoords")
+        assert g.positions.data.dtype == np.float32
+        assert g.normals.data.dtype == np.float32
+        assert g.texcoords.data.dtype == np.float32
+        assert g.indices.data.dtype == np.int32
+        assert g.positions.data.shape == (nr_faces * 3, 3)
+        assert g.positions.data.shape == g.normals.data.shape
+        assert g.positions.data.shape == g.indices.data.shape
+        assert g.positions.data.shape[:-1] + (2,) == g.texcoords.data.shape
+        assert np.allclose(np.linalg.norm(g.positions.data, axis=-1), 1)
+
+
+def test_octahedron_radius():
+    for radius in np.arange(5) + 1:
+        g = octahedron_geometry(radius=radius)
+
+        assert np.allclose(np.linalg.norm(g.positions.data, axis=-1), radius)
+
+
+def test_octahedron_subdivision():
+    for subdivisions in range(5):
+        g = octahedron_geometry(subdivisions=subdivisions)
+        assert g.positions.data.shape[0] == (subdivisions + 1) ** 2 * 8 * 3