test_texturing.py 46 KB
Newer Older
1
# Copyright (c) Meta Platforms, Inc. and affiliates.
Patrick Labatut's avatar
Patrick Labatut committed
2
3
4
5
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
facebook-github-bot's avatar
facebook-github-bot committed
6
7
8


import unittest
9

facebook-github-bot's avatar
facebook-github-bot committed
10
11
12
import torch
import torch.nn.functional as F
from pytorch3d.renderer.mesh.rasterizer import Fragments
Nikhila Ravi's avatar
Nikhila Ravi committed
13
from pytorch3d.renderer.mesh.textures import (
14
    _list_to_padded_wrapper,
Nikhila Ravi's avatar
Nikhila Ravi committed
15
16
17
    TexturesAtlas,
    TexturesUV,
    TexturesVertex,
18
19
)
from pytorch3d.renderer.mesh.utils import (
20
    pack_rectangles,
21
    pack_unique_rectangles,
22
    Rectangle,
Nikhila Ravi's avatar
Nikhila Ravi committed
23
)
24
from pytorch3d.structures import list_to_packed, Meshes, packed_to_list
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
25
26
27

from .common_testing import TestCaseMixin
from .test_meshes import init_mesh
facebook-github-bot's avatar
facebook-github-bot committed
28
29


Nikhila Ravi's avatar
Nikhila Ravi committed
30
31
32
33
34
35
36
37
38
39
40
41
def tryindex(self, index, tex, meshes, source):
    tex2 = tex[index]
    meshes2 = meshes[index]
    tex_from_meshes = meshes2.textures
    for item in source:
        basic = source[item][index]
        from_texture = getattr(tex2, item + "_padded")()
        from_meshes = getattr(tex_from_meshes, item + "_padded")()
        if isinstance(index, int):
            basic = basic[None]

        if len(basic) == 0:
42
43
            self.assertEqual(len(from_texture), 0)
            self.assertEqual(len(from_meshes), 0)
Nikhila Ravi's avatar
Nikhila Ravi committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
        else:
            self.assertClose(basic, from_texture)
            self.assertClose(basic, from_meshes)
            self.assertEqual(from_texture.ndim, getattr(tex, item + "_padded")().ndim)
            item_list = getattr(tex_from_meshes, item + "_list")()
            self.assertEqual(basic.shape[0], len(item_list))
            for i, elem in enumerate(item_list):
                self.assertClose(elem, basic[i])


class TestTexturesVertex(TestCaseMixin, unittest.TestCase):
    def test_sample_vertex_textures(self):
        """
        This tests both interpolate_vertex_colors as well as
        interpolate_face_attributes.
        """
        verts = torch.randn((4, 3), dtype=torch.float32)
        faces = torch.tensor([[2, 1, 0], [3, 1, 0]], dtype=torch.int64)
        vert_tex = torch.tensor(
            [[0, 1, 0], [0, 1, 1], [1, 1, 0], [1, 1, 1]], dtype=torch.float32
        )
        verts_features = vert_tex
        tex = TexturesVertex(verts_features=[verts_features])
        mesh = Meshes(verts=[verts], faces=[faces], textures=tex)
        pix_to_face = torch.tensor([0, 1], dtype=torch.int64).view(1, 1, 1, 2)
        barycentric_coords = torch.tensor(
            [[0.5, 0.3, 0.2], [0.3, 0.6, 0.1]], dtype=torch.float32
        ).view(1, 1, 1, 2, -1)
        expected_vals = torch.tensor(
            [[0.5, 1.0, 0.3], [0.3, 1.0, 0.9]], dtype=torch.float32
        ).view(1, 1, 1, 2, -1)
        fragments = Fragments(
            pix_to_face=pix_to_face,
            bary_coords=barycentric_coords,
            zbuf=torch.ones_like(pix_to_face),
            dists=torch.ones_like(pix_to_face),
        )
        # sample_textures calls interpolate_vertex_colors
        texels = mesh.sample_textures(fragments)
        self.assertTrue(torch.allclose(texels, expected_vals[None, :]))

    def test_sample_vertex_textures_grad(self):
        verts = torch.randn((4, 3), dtype=torch.float32)
        faces = torch.tensor([[2, 1, 0], [3, 1, 0]], dtype=torch.int64)
        vert_tex = torch.tensor(
            [[0, 1, 0], [0, 1, 1], [1, 1, 0], [1, 1, 1]],
            dtype=torch.float32,
            requires_grad=True,
        )
        verts_features = vert_tex
        tex = TexturesVertex(verts_features=[verts_features])
        mesh = Meshes(verts=[verts], faces=[faces], textures=tex)
        pix_to_face = torch.tensor([0, 1], dtype=torch.int64).view(1, 1, 1, 2)
        barycentric_coords = torch.tensor(
            [[0.5, 0.3, 0.2], [0.3, 0.6, 0.1]], dtype=torch.float32
        ).view(1, 1, 1, 2, -1)
        fragments = Fragments(
            pix_to_face=pix_to_face,
            bary_coords=barycentric_coords,
            zbuf=torch.ones_like(pix_to_face),
            dists=torch.ones_like(pix_to_face),
        )
        grad_vert_tex = torch.tensor(
            [[0.3, 0.3, 0.3], [0.9, 0.9, 0.9], [0.5, 0.5, 0.5], [0.3, 0.3, 0.3]],
            dtype=torch.float32,
        )
        texels = mesh.sample_textures(fragments)
        texels.sum().backward()
        self.assertTrue(hasattr(vert_tex, "grad"))
        self.assertTrue(torch.allclose(vert_tex.grad, grad_vert_tex[None, :]))

    def test_textures_vertex_init_fail(self):
        # Incorrect sized tensors
        with self.assertRaisesRegex(ValueError, "verts_features"):
            TexturesVertex(verts_features=torch.rand(size=(5, 10)))

        # Not a list or a tensor
        with self.assertRaisesRegex(ValueError, "verts_features"):
            TexturesVertex(verts_features=(1, 1, 1))

124
125
126
127
128
129
130
131
132
133
    def test_faces_verts_textures(self):
        device = torch.device("cuda:0")
        verts = torch.randn((2, 4, 3), dtype=torch.float32, device=device)
        faces = torch.tensor(
            [[[2, 1, 0], [3, 1, 0]], [[1, 3, 0], [2, 1, 3]]],
            dtype=torch.int64,
            device=device,
        )

        # define TexturesVertex
134
        verts_texture = torch.rand(verts.shape, device=device)
135
136
137
138
139
140
141
142
143
144
145
146
147
148
        textures = TexturesVertex(verts_features=verts_texture)

        # compute packed faces
        ff = faces.unbind(0)
        faces_packed = torch.cat([ff[0], ff[1] + verts.shape[1]])

        # face verts textures
        faces_verts_texts = textures.faces_verts_textures_packed(faces_packed)

        verts_texts_packed = torch.cat(verts_texture.unbind(0))
        faces_verts_texts_packed = verts_texts_packed[faces_packed]

        self.assertClose(faces_verts_texts_packed, faces_verts_texts)

149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
    def test_submeshes(self):
        # define TexturesVertex
        verts_features = torch.tensor(
            [
                [1, 0, 0],
                [1, 0, 0],
                [1, 0, 0],
                [1, 0, 0],
                [0, 1, 0],
                [0, 1, 0],
                [0, 1, 0],
                [0, 1, 0],
            ],
            dtype=torch.float32,
        )

        textures = TexturesVertex(
            verts_features=[verts_features, verts_features, verts_features]
        )
        subtextures = textures.submeshes(
            [
                [
                    torch.LongTensor([0, 2, 3]),
                    torch.LongTensor(list(range(8))),
                ],
                [],
                [
                    torch.LongTensor([4]),
                ],
            ],
            None,
        )

        subtextures_features = subtextures.verts_features_list()

        self.assertEqual(len(subtextures_features), 3)
        self.assertTrue(
            torch.equal(
                subtextures_features[0],
                torch.FloatTensor([[1, 0, 0], [1, 0, 0], [1, 0, 0]]),
            )
        )
        self.assertTrue(torch.equal(subtextures_features[1], verts_features))
        self.assertTrue(
            torch.equal(subtextures_features[2], torch.FloatTensor([[0, 1, 0]]))
        )

Nikhila Ravi's avatar
Nikhila Ravi committed
196
197
    def test_clone(self):
        tex = TexturesVertex(verts_features=torch.rand(size=(10, 100, 128)))
198
        tex.verts_features_list()
Nikhila Ravi's avatar
Nikhila Ravi committed
199
200
201
202
        tex_cloned = tex.clone()
        self.assertSeparate(
            tex._verts_features_padded, tex_cloned._verts_features_padded
        )
203
        self.assertClose(tex._verts_features_padded, tex_cloned._verts_features_padded)
Nikhila Ravi's avatar
Nikhila Ravi committed
204
        self.assertSeparate(tex.valid, tex_cloned.valid)
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
        self.assertTrue(tex.valid.eq(tex_cloned.valid).all())
        for i in range(tex._N):
            self.assertSeparate(
                tex._verts_features_list[i], tex_cloned._verts_features_list[i]
            )
            self.assertClose(
                tex._verts_features_list[i], tex_cloned._verts_features_list[i]
            )

    def test_detach(self):
        tex = TexturesVertex(
            verts_features=torch.rand(size=(10, 100, 128), requires_grad=True)
        )
        tex.verts_features_list()
        tex_detached = tex.detach()
        self.assertFalse(tex_detached._verts_features_padded.requires_grad)
        self.assertClose(
            tex_detached._verts_features_padded, tex._verts_features_padded
        )
        for i in range(tex._N):
            self.assertClose(
                tex._verts_features_list[i], tex_detached._verts_features_list[i]
            )
            self.assertFalse(tex_detached._verts_features_list[i].requires_grad)
Nikhila Ravi's avatar
Nikhila Ravi committed
229
230
231

    def test_extend(self):
        B = 10
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
232
        mesh = init_mesh(B, 30, 50)
Nikhila Ravi's avatar
Nikhila Ravi committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
        V = mesh._V
        tex_uv = TexturesVertex(verts_features=torch.randn((B, V, 3)))
        tex_mesh = Meshes(
            verts=mesh.verts_padded(), faces=mesh.faces_padded(), textures=tex_uv
        )
        N = 20
        new_mesh = tex_mesh.extend(N)

        self.assertEqual(len(tex_mesh) * N, len(new_mesh))

        tex_init = tex_mesh.textures
        new_tex = new_mesh.textures

        for i in range(len(tex_mesh)):
            for n in range(N):
                self.assertClose(
                    tex_init.verts_features_list()[i],
                    new_tex.verts_features_list()[i * N + n],
                )
                self.assertClose(
                    tex_init._num_faces_per_mesh[i],
                    new_tex._num_faces_per_mesh[i * N + n],
                )

        self.assertAllSeparate(
            [tex_init.verts_features_padded(), new_tex.verts_features_padded()]
        )

        with self.assertRaises(ValueError):
            tex_mesh.extend(N=-1)

    def test_padded_to_packed(self):
        # Case where each face in the mesh has 3 unique uv vertex indices
        # - i.e. even if a vertex is shared between multiple faces it will
        # have a unique uv coordinate for each face.
        num_verts_per_mesh = [9, 6]
        D = 10
        verts_features_list = [torch.rand(v, D) for v in num_verts_per_mesh]
        verts_features_packed = list_to_packed(verts_features_list)[0]
        verts_features_list = packed_to_list(verts_features_packed, num_verts_per_mesh)
        tex = TexturesVertex(verts_features=verts_features_list)

        # This is set inside Meshes when textures is passed as an input.
        # Here we set _num_faces_per_mesh and _num_verts_per_mesh explicity.
        tex1 = tex.clone()
        tex1._num_verts_per_mesh = num_verts_per_mesh
        verts_packed = tex1.verts_features_packed()
        verts_verts_list = tex1.verts_features_list()
        verts_padded = tex1.verts_features_padded()

        for f1, f2 in zip(verts_verts_list, verts_features_list):
            self.assertTrue((f1 == f2).all().item())

        self.assertTrue(verts_packed.shape == (sum(num_verts_per_mesh), D))
        self.assertTrue(verts_padded.shape == (2, 9, D))

        # Case where num_verts_per_mesh is not set and textures
        # are initialized with a padded tensor.
        tex2 = TexturesVertex(verts_features=verts_padded)
        verts_packed = tex2.verts_features_packed()
        verts_list = tex2.verts_features_list()

        # Packed is just flattened padded as num_verts_per_mesh
        # has not been provided.
        self.assertTrue(verts_packed.shape == (9 * 2, D))

        for i, (f1, f2) in enumerate(zip(verts_list, verts_features_list)):
            n = num_verts_per_mesh[i]
            self.assertTrue((f1[:n] == f2).all().item())

    def test_getitem(self):
        N = 5
        V = 20
Nikhila Ravi's avatar
Nikhila Ravi committed
306
        source = {"verts_features": torch.randn(size=(N, V, 128))}
Nikhila Ravi's avatar
Nikhila Ravi committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
        tex = TexturesVertex(verts_features=source["verts_features"])

        verts = torch.rand(size=(N, V, 3))
        faces = torch.randint(size=(N, 10, 3), high=V)
        meshes = Meshes(verts=verts, faces=faces, textures=tex)

        tryindex(self, 2, tex, meshes, source)
        tryindex(self, slice(0, 2, 1), tex, meshes, source)
        index = torch.tensor([1, 0, 1, 0, 0], dtype=torch.bool)
        tryindex(self, index, tex, meshes, source)
        index = torch.tensor([0, 0, 0, 0, 0], dtype=torch.bool)
        tryindex(self, index, tex, meshes, source)
        index = torch.tensor([1, 2], dtype=torch.int64)
        tryindex(self, index, tex, meshes, source)
        tryindex(self, [2, 4], tex, meshes, source)

Nikhila Ravi's avatar
Nikhila Ravi committed
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
    def test_sample_textures_error(self):
        N = 5
        V = 20
        verts = torch.rand(size=(N, V, 3))
        faces = torch.randint(size=(N, 10, 3), high=V)
        tex = TexturesVertex(verts_features=torch.randn(size=(N, 10, 128)))

        # Verts features have the wrong number of verts
        with self.assertRaisesRegex(ValueError, "do not match the dimensions"):
            Meshes(verts=verts, faces=faces, textures=tex)

        # Verts features have the wrong batch dim
        tex = TexturesVertex(verts_features=torch.randn(size=(1, V, 128)))
        with self.assertRaisesRegex(ValueError, "do not match the dimensions"):
            Meshes(verts=verts, faces=faces, textures=tex)

        meshes = Meshes(verts=verts, faces=faces)
        meshes.textures = tex

        # Cannot use the texture attribute set on meshes for sampling
        # textures if the dimensions don't match
        with self.assertRaisesRegex(ValueError, "do not match the dimensions"):
            meshes.sample_textures(None)

Nikhila Ravi's avatar
Nikhila Ravi committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410

class TestTexturesAtlas(TestCaseMixin, unittest.TestCase):
    def test_sample_texture_atlas(self):
        N, F, R = 1, 2, 2
        verts = torch.randn((4, 3), dtype=torch.float32)
        faces = torch.tensor([[2, 1, 0], [3, 1, 0]], dtype=torch.int64)
        faces_atlas = torch.rand(size=(N, F, R, R, 3))
        tex = TexturesAtlas(atlas=faces_atlas)
        mesh = Meshes(verts=[verts], faces=[faces], textures=tex)
        pix_to_face = torch.tensor([0, 1], dtype=torch.int64).view(1, 1, 1, 2)
        barycentric_coords = torch.tensor(
            [[0.5, 0.3, 0.2], [0.3, 0.6, 0.1]], dtype=torch.float32
        ).view(1, 1, 1, 2, -1)
        expected_vals = torch.tensor(
            [[0.5, 1.0, 0.3], [0.3, 1.0, 0.9]], dtype=torch.float32
        )
        expected_vals = torch.zeros((1, 1, 1, 2, 3), dtype=torch.float32)
        expected_vals[..., 0, :] = faces_atlas[0, 0, 0, 1, ...]
        expected_vals[..., 1, :] = faces_atlas[0, 1, 1, 0, ...]

        fragments = Fragments(
            pix_to_face=pix_to_face,
            bary_coords=barycentric_coords,
            zbuf=torch.ones_like(pix_to_face),
            dists=torch.ones_like(pix_to_face),
        )
        texels = mesh.textures.sample_textures(fragments)
        self.assertTrue(torch.allclose(texels, expected_vals))

    def test_textures_atlas_grad(self):
        N, F, R = 1, 2, 2
        verts = torch.randn((4, 3), dtype=torch.float32)
        faces = torch.tensor([[2, 1, 0], [3, 1, 0]], dtype=torch.int64)
        faces_atlas = torch.rand(size=(N, F, R, R, 3), requires_grad=True)
        tex = TexturesAtlas(atlas=faces_atlas)
        mesh = Meshes(verts=[verts], faces=[faces], textures=tex)
        pix_to_face = torch.tensor([0, 1], dtype=torch.int64).view(1, 1, 1, 2)
        barycentric_coords = torch.tensor(
            [[0.5, 0.3, 0.2], [0.3, 0.6, 0.1]], dtype=torch.float32
        ).view(1, 1, 1, 2, -1)
        fragments = Fragments(
            pix_to_face=pix_to_face,
            bary_coords=barycentric_coords,
            zbuf=torch.ones_like(pix_to_face),
            dists=torch.ones_like(pix_to_face),
        )
        texels = mesh.textures.sample_textures(fragments)
        grad_tex = torch.rand_like(texels)
        grad_expected = torch.zeros_like(faces_atlas)
        grad_expected[0, 0, 0, 1, :] = grad_tex[..., 0:1, :]
        grad_expected[0, 1, 1, 0, :] = grad_tex[..., 1:2, :]
        texels.backward(grad_tex)
        self.assertTrue(hasattr(faces_atlas, "grad"))
        self.assertTrue(torch.allclose(faces_atlas.grad, grad_expected))

    def test_textures_atlas_init_fail(self):
        # Incorrect sized tensors
        with self.assertRaisesRegex(ValueError, "atlas"):
            TexturesAtlas(atlas=torch.rand(size=(5, 10, 3)))

        # Not a list or a tensor
        with self.assertRaisesRegex(ValueError, "atlas"):
            TexturesAtlas(atlas=(1, 1, 1))

411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
    def test_faces_verts_textures(self):
        device = torch.device("cuda:0")
        N, F, R = 2, 2, 8
        num_faces = torch.randint(low=1, high=F, size=(N,))
        faces_atlas = [
            torch.rand(size=(num_faces[i].item(), R, R, 3), device=device)
            for i in range(N)
        ]
        tex = TexturesAtlas(atlas=faces_atlas)

        # faces_verts naive
        faces_verts = []
        for n in range(N):
            ff = num_faces[n].item()
            temp = torch.zeros(ff, 3, 3)
            for f in range(ff):
                t0 = faces_atlas[n][f, 0, -1]  # for v0, bary = (1, 0)
                t1 = faces_atlas[n][f, -1, 0]  # for v1, bary = (0, 1)
                t2 = faces_atlas[n][f, 0, 0]  # for v2, bary = (0, 0)
                temp[f, 0] = t0
                temp[f, 1] = t1
                temp[f, 2] = t2
            faces_verts.append(temp)
        faces_verts = torch.cat(faces_verts, 0)

        self.assertClose(faces_verts, tex.faces_verts_textures_packed().cpu())

Nikhila Ravi's avatar
Nikhila Ravi committed
438
439
    def test_clone(self):
        tex = TexturesAtlas(atlas=torch.rand(size=(1, 10, 2, 2, 3)))
440
        tex.atlas_list()
Nikhila Ravi's avatar
Nikhila Ravi committed
441
442
        tex_cloned = tex.clone()
        self.assertSeparate(tex._atlas_padded, tex_cloned._atlas_padded)
443
        self.assertClose(tex._atlas_padded, tex_cloned._atlas_padded)
Nikhila Ravi's avatar
Nikhila Ravi committed
444
        self.assertSeparate(tex.valid, tex_cloned.valid)
445
446
447
448
449
450
451
452
453
454
455
456
457
458
        self.assertTrue(tex.valid.eq(tex_cloned.valid).all())
        for i in range(tex._N):
            self.assertSeparate(tex._atlas_list[i], tex_cloned._atlas_list[i])
            self.assertClose(tex._atlas_list[i], tex_cloned._atlas_list[i])

    def test_detach(self):
        tex = TexturesAtlas(atlas=torch.rand(size=(1, 10, 2, 2, 3), requires_grad=True))
        tex.atlas_list()
        tex_detached = tex.detach()
        self.assertFalse(tex_detached._atlas_padded.requires_grad)
        self.assertClose(tex_detached._atlas_padded, tex._atlas_padded)
        for i in range(tex._N):
            self.assertFalse(tex_detached._atlas_list[i].requires_grad)
            self.assertClose(tex._atlas_list[i], tex_detached._atlas_list[i])
Nikhila Ravi's avatar
Nikhila Ravi committed
459
460
461

    def test_extend(self):
        B = 10
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
462
        mesh = init_mesh(B, 30, 50)
Nikhila Ravi's avatar
Nikhila Ravi committed
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
        F = mesh._F
        tex_uv = TexturesAtlas(atlas=torch.randn((B, F, 2, 2, 3)))
        tex_mesh = Meshes(
            verts=mesh.verts_padded(), faces=mesh.faces_padded(), textures=tex_uv
        )
        N = 20
        new_mesh = tex_mesh.extend(N)

        self.assertEqual(len(tex_mesh) * N, len(new_mesh))

        tex_init = tex_mesh.textures
        new_tex = new_mesh.textures

        for i in range(len(tex_mesh)):
            for n in range(N):
                self.assertClose(
                    tex_init.atlas_list()[i], new_tex.atlas_list()[i * N + n]
                )
                self.assertClose(
                    tex_init._num_faces_per_mesh[i],
                    new_tex._num_faces_per_mesh[i * N + n],
                )

        self.assertAllSeparate([tex_init.atlas_padded(), new_tex.atlas_padded()])

        with self.assertRaises(ValueError):
            tex_mesh.extend(N=-1)

    def test_padded_to_packed(self):
        # Case where each face in the mesh has 3 unique uv vertex indices
        # - i.e. even if a vertex is shared between multiple faces it will
        # have a unique uv coordinate for each face.
        R = 2
        N = 20
        num_faces_per_mesh = torch.randint(size=(N,), low=0, high=30)
        atlas_list = [torch.rand(f, R, R, 3) for f in num_faces_per_mesh]
        tex = TexturesAtlas(atlas=atlas_list)

        # This is set inside Meshes when textures is passed as an input.
        # Here we set _num_faces_per_mesh explicity.
        tex1 = tex.clone()
        tex1._num_faces_per_mesh = num_faces_per_mesh.tolist()
        atlas_packed = tex1.atlas_packed()
        atlas_list_new = tex1.atlas_list()
        atlas_padded = tex1.atlas_padded()

        for f1, f2 in zip(atlas_list_new, atlas_list):
            self.assertTrue((f1 == f2).all().item())

        sum_F = num_faces_per_mesh.sum()
        max_F = num_faces_per_mesh.max().item()
        self.assertTrue(atlas_packed.shape == (sum_F, R, R, 3))
        self.assertTrue(atlas_padded.shape == (N, max_F, R, R, 3))

        # Case where num_faces_per_mesh is not set and textures
        # are initialized with a padded tensor.
        atlas_list_padded = _list_to_padded_wrapper(atlas_list)
        tex2 = TexturesAtlas(atlas=atlas_list_padded)
        atlas_packed = tex2.atlas_packed()
        atlas_list_new = tex2.atlas_list()

        # Packed is just flattened padded as num_faces_per_mesh
        # has not been provided.
        self.assertTrue(atlas_packed.shape == (N * max_F, R, R, 3))

        for i, (f1, f2) in enumerate(zip(atlas_list_new, atlas_list)):
            n = num_faces_per_mesh[i]
            self.assertTrue((f1[:n] == f2).all().item())

    def test_getitem(self):
        N = 5
        V = 20
Nikhila Ravi's avatar
Nikhila Ravi committed
535
536
        F = 10
        source = {"atlas": torch.randn(size=(N, F, 4, 4, 3))}
Nikhila Ravi's avatar
Nikhila Ravi committed
537
538
539
        tex = TexturesAtlas(atlas=source["atlas"])

        verts = torch.rand(size=(N, V, 3))
Nikhila Ravi's avatar
Nikhila Ravi committed
540
        faces = torch.randint(size=(N, F, 3), high=V)
Nikhila Ravi's avatar
Nikhila Ravi committed
541
542
543
544
545
546
547
548
549
550
551
552
        meshes = Meshes(verts=verts, faces=faces, textures=tex)

        tryindex(self, 2, tex, meshes, source)
        tryindex(self, slice(0, 2, 1), tex, meshes, source)
        index = torch.tensor([1, 0, 1, 0, 0], dtype=torch.bool)
        tryindex(self, index, tex, meshes, source)
        index = torch.tensor([0, 0, 0, 0, 0], dtype=torch.bool)
        tryindex(self, index, tex, meshes, source)
        index = torch.tensor([1, 2], dtype=torch.int64)
        tryindex(self, index, tex, meshes, source)
        tryindex(self, [2, 4], tex, meshes, source)

Nikhila Ravi's avatar
Nikhila Ravi committed
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
    def test_sample_textures_error(self):
        N = 1
        V = 20
        F = 10
        verts = torch.rand(size=(5, V, 3))
        faces = torch.randint(size=(5, F, 3), high=V)
        meshes = Meshes(verts=verts, faces=faces)

        # TexturesAtlas have the wrong batch dim
        tex = TexturesAtlas(atlas=torch.randn(size=(1, F, 4, 4, 3)))
        with self.assertRaisesRegex(ValueError, "do not match the dimensions"):
            Meshes(verts=verts, faces=faces, textures=tex)

        # TexturesAtlas have the wrong number of faces
        tex = TexturesAtlas(atlas=torch.randn(size=(N, 15, 4, 4, 3)))
        with self.assertRaisesRegex(ValueError, "do not match the dimensions"):
            Meshes(verts=verts, faces=faces, textures=tex)

        meshes = Meshes(verts=verts, faces=faces)
        meshes.textures = tex

        # Cannot use the texture attribute set on meshes for sampling
        # textures if the dimensions don't match
        with self.assertRaisesRegex(ValueError, "do not match the dimensions"):
            meshes.sample_textures(None)

579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
    def test_submeshes(self):
        N = 2
        V = 5
        F = 5
        tex = TexturesAtlas(
            atlas=torch.arange(N * F * 4 * 4 * 3, dtype=torch.float32).reshape(
                N, F, 4, 4, 3
            )
        )

        verts = torch.rand(size=(N, V, 3))
        faces = torch.randint(size=(N, F, 3), high=V)
        mesh = Meshes(verts=verts, faces=faces, textures=tex)

        sub_faces = [
            [torch.tensor([0, 2]), torch.tensor([1, 2])],
            [],
        ]
        subtex = mesh.submeshes(sub_faces).textures
        subtex_faces = subtex.atlas_list()

        self.assertEqual(len(subtex_faces), 2)
        self.assertClose(
            subtex_faces[0].flatten().msort(),
            torch.cat(
                (
                    torch.arange(4 * 4 * 3, dtype=torch.float32),
                    torch.arange(96, 96 + 4 * 4 * 3, dtype=torch.float32),
                ),
                0,
            ),
        )

Nikhila Ravi's avatar
Nikhila Ravi committed
612
613

class TestTexturesUV(TestCaseMixin, unittest.TestCase):
614
615
616
617
    def setUp(self) -> None:
        super().setUp()
        torch.manual_seed(42)

Nikhila Ravi's avatar
Nikhila Ravi committed
618
    def test_sample_textures_uv(self):
facebook-github-bot's avatar
facebook-github-bot committed
619
620
621
622
        barycentric_coords = torch.tensor(
            [[0.5, 0.3, 0.2], [0.3, 0.6, 0.1]], dtype=torch.float32
        ).view(1, 1, 1, 2, -1)
        dummy_verts = torch.zeros(4, 3)
623
        vert_uvs = torch.tensor([[1, 0], [0, 1], [1, 1], [0, 0]], dtype=torch.float32)
facebook-github-bot's avatar
facebook-github-bot committed
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
        face_uvs = torch.tensor([[0, 1, 2], [1, 2, 3]], dtype=torch.int64)
        interpolated_uvs = torch.tensor(
            [[0.5 + 0.2, 0.3 + 0.2], [0.6, 0.3 + 0.6]], dtype=torch.float32
        )

        # Create a dummy texture map
        H = 2
        W = 2
        x = torch.linspace(0, 1, W).view(1, W).expand(H, W)
        y = torch.linspace(0, 1, H).view(H, 1).expand(H, W)
        tex_map = torch.stack([x, y], dim=2).view(1, H, W, 2)
        pix_to_face = torch.tensor([0, 1], dtype=torch.int64).view(1, 1, 1, 2)
        fragments = Fragments(
            pix_to_face=pix_to_face,
            bary_coords=barycentric_coords,
            zbuf=pix_to_face,
            dists=pix_to_face,
        )
Nikhila Ravi's avatar
Nikhila Ravi committed
642

643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
        for align_corners in [True, False]:
            tex = TexturesUV(
                maps=tex_map,
                faces_uvs=[face_uvs],
                verts_uvs=[vert_uvs],
                align_corners=align_corners,
            )
            meshes = Meshes(verts=[dummy_verts], faces=[face_uvs], textures=tex)
            mesh_textures = meshes.textures
            texels = mesh_textures.sample_textures(fragments)

            # Expected output
            pixel_uvs = interpolated_uvs * 2.0 - 1.0
            pixel_uvs = pixel_uvs.view(2, 1, 1, 2)
            tex_map_ = torch.flip(tex_map, [1]).permute(0, 3, 1, 2)
            tex_map_ = torch.cat([tex_map_, tex_map_], dim=0)
            expected_out = F.grid_sample(
                tex_map_, pixel_uvs, align_corners=align_corners, padding_mode="border"
            )
            self.assertTrue(torch.allclose(texels.squeeze(), expected_out.squeeze()))
facebook-github-bot's avatar
facebook-github-bot committed
663

Nikhila Ravi's avatar
Nikhila Ravi committed
664
    def test_textures_uv_init_fail(self):
Nikhila Ravi's avatar
Nikhila Ravi committed
665
666
        # Maps has wrong shape
        with self.assertRaisesRegex(ValueError, "maps"):
Nikhila Ravi's avatar
Nikhila Ravi committed
667
            TexturesUV(
Nikhila Ravi's avatar
Nikhila Ravi committed
668
                maps=torch.ones((5, 16, 16, 3, 4)),
Nikhila Ravi's avatar
Nikhila Ravi committed
669
670
                faces_uvs=torch.rand(size=(5, 10, 3)),
                verts_uvs=torch.rand(size=(5, 15, 2)),
Nikhila Ravi's avatar
Nikhila Ravi committed
671
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
672

Nikhila Ravi's avatar
Nikhila Ravi committed
673
674
        # faces_uvs has wrong shape
        with self.assertRaisesRegex(ValueError, "faces_uvs"):
Nikhila Ravi's avatar
Nikhila Ravi committed
675
            TexturesUV(
Nikhila Ravi's avatar
Nikhila Ravi committed
676
                maps=torch.ones((5, 16, 16, 3)),
Nikhila Ravi's avatar
Nikhila Ravi committed
677
678
                faces_uvs=torch.rand(size=(5, 10, 3, 3)),
                verts_uvs=torch.rand(size=(5, 15, 2)),
Nikhila Ravi's avatar
Nikhila Ravi committed
679
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
680

Nikhila Ravi's avatar
Nikhila Ravi committed
681
682
        # verts_uvs has wrong shape
        with self.assertRaisesRegex(ValueError, "verts_uvs"):
Nikhila Ravi's avatar
Nikhila Ravi committed
683
            TexturesUV(
Nikhila Ravi's avatar
Nikhila Ravi committed
684
                maps=torch.ones((5, 16, 16, 3)),
Nikhila Ravi's avatar
Nikhila Ravi committed
685
686
                faces_uvs=torch.rand(size=(5, 10, 3)),
                verts_uvs=torch.rand(size=(5, 15, 2, 3)),
Nikhila Ravi's avatar
Nikhila Ravi committed
687
688
            )

Nikhila Ravi's avatar
Nikhila Ravi committed
689
690
691
692
693
694
695
        # verts has different batch dim to faces
        with self.assertRaisesRegex(ValueError, "verts_uvs"):
            TexturesUV(
                maps=torch.ones((5, 16, 16, 3)),
                faces_uvs=torch.rand(size=(5, 10, 3)),
                verts_uvs=torch.rand(size=(8, 15, 2)),
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
696

Nikhila Ravi's avatar
Nikhila Ravi committed
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
        # maps has different batch dim to faces
        with self.assertRaisesRegex(ValueError, "maps"):
            TexturesUV(
                maps=torch.ones((8, 16, 16, 3)),
                faces_uvs=torch.rand(size=(5, 10, 3)),
                verts_uvs=torch.rand(size=(5, 15, 2)),
            )

        # verts on different device to faces
        with self.assertRaisesRegex(ValueError, "verts_uvs"):
            TexturesUV(
                maps=torch.ones((5, 16, 16, 3)),
                faces_uvs=torch.rand(size=(5, 10, 3)),
                verts_uvs=torch.rand(size=(5, 15, 2, 3), device="cuda"),
            )

        # maps on different device to faces
        with self.assertRaisesRegex(ValueError, "map"):
            TexturesUV(
                maps=torch.ones((5, 16, 16, 3), device="cuda"),
                faces_uvs=torch.rand(size=(5, 10, 3)),
                verts_uvs=torch.rand(size=(5, 15, 2)),
            )

721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
    def test_faces_verts_textures(self):
        device = torch.device("cuda:0")
        N, V, F, H, W = 2, 5, 12, 8, 8
        vert_uvs = torch.rand((N, V, 2), dtype=torch.float32, device=device)
        face_uvs = torch.randint(
            high=V, size=(N, F, 3), dtype=torch.int64, device=device
        )
        maps = torch.rand((N, H, W, 3), dtype=torch.float32, device=device)

        tex = TexturesUV(maps=maps, verts_uvs=vert_uvs, faces_uvs=face_uvs)

        # naive faces_verts_textures
        faces_verts_texs = []
        for n in range(N):
            temp = torch.zeros((F, 3, 3), device=device, dtype=torch.float32)
            for f in range(F):
                uv0 = vert_uvs[n, face_uvs[n, f, 0]]
                uv1 = vert_uvs[n, face_uvs[n, f, 1]]
                uv2 = vert_uvs[n, face_uvs[n, f, 2]]

                idx = torch.stack((uv0, uv1, uv2), dim=0).view(1, 1, 3, 2)  # 1x1x3x2
                idx = idx * 2.0 - 1.0
                imap = maps[n].view(1, H, W, 3).permute(0, 3, 1, 2)  # 1x3xHxW
                imap = torch.flip(imap, [2])

                texts = torch.nn.functional.grid_sample(
                    imap,
                    idx,
                    align_corners=tex.align_corners,
                    padding_mode=tex.padding_mode,
                )  # 1x3x1x3
                temp[f] = texts[0, :, 0, :].permute(1, 0)
            faces_verts_texs.append(temp)
        faces_verts_texs = torch.cat(faces_verts_texs, 0)

        self.assertClose(faces_verts_texs, tex.faces_verts_textures_packed())

Nikhila Ravi's avatar
Nikhila Ravi committed
758
759
760
761
762
763
    def test_clone(self):
        tex = TexturesUV(
            maps=torch.ones((5, 16, 16, 3)),
            faces_uvs=torch.rand(size=(5, 10, 3)),
            verts_uvs=torch.rand(size=(5, 15, 2)),
        )
764
765
        tex.faces_uvs_list()
        tex.verts_uvs_list()
Nikhila Ravi's avatar
Nikhila Ravi committed
766
767
        tex_cloned = tex.clone()
        self.assertSeparate(tex._faces_uvs_padded, tex_cloned._faces_uvs_padded)
768
        self.assertClose(tex._faces_uvs_padded, tex_cloned._faces_uvs_padded)
Nikhila Ravi's avatar
Nikhila Ravi committed
769
        self.assertSeparate(tex._verts_uvs_padded, tex_cloned._verts_uvs_padded)
770
        self.assertClose(tex._verts_uvs_padded, tex_cloned._verts_uvs_padded)
Nikhila Ravi's avatar
Nikhila Ravi committed
771
        self.assertSeparate(tex._maps_padded, tex_cloned._maps_padded)
772
        self.assertClose(tex._maps_padded, tex_cloned._maps_padded)
Nikhila Ravi's avatar
Nikhila Ravi committed
773
        self.assertSeparate(tex.valid, tex_cloned.valid)
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
        self.assertTrue(tex.valid.eq(tex_cloned.valid).all())
        for i in range(tex._N):
            self.assertSeparate(tex._faces_uvs_list[i], tex_cloned._faces_uvs_list[i])
            self.assertClose(tex._faces_uvs_list[i], tex_cloned._faces_uvs_list[i])
            self.assertSeparate(tex._verts_uvs_list[i], tex_cloned._verts_uvs_list[i])
            self.assertClose(tex._verts_uvs_list[i], tex_cloned._verts_uvs_list[i])
            # tex._maps_list is not use anywhere so it's not stored. We call it explicitly
            self.assertSeparate(tex.maps_list()[i], tex_cloned.maps_list()[i])
            self.assertClose(tex.maps_list()[i], tex_cloned.maps_list()[i])

    def test_detach(self):
        tex = TexturesUV(
            maps=torch.ones((5, 16, 16, 3), requires_grad=True),
            faces_uvs=torch.rand(size=(5, 10, 3)),
            verts_uvs=torch.rand(size=(5, 15, 2)),
        )
        tex.faces_uvs_list()
        tex.verts_uvs_list()
        tex_detached = tex.detach()
        self.assertFalse(tex_detached._maps_padded.requires_grad)
        self.assertClose(tex._maps_padded, tex_detached._maps_padded)
        self.assertFalse(tex_detached._verts_uvs_padded.requires_grad)
        self.assertClose(tex._verts_uvs_padded, tex_detached._verts_uvs_padded)
        self.assertFalse(tex_detached._faces_uvs_padded.requires_grad)
        self.assertClose(tex._faces_uvs_padded, tex_detached._faces_uvs_padded)
        for i in range(tex._N):
            self.assertFalse(tex_detached._verts_uvs_list[i].requires_grad)
            self.assertClose(tex._verts_uvs_list[i], tex_detached._verts_uvs_list[i])
            self.assertFalse(tex_detached._faces_uvs_list[i].requires_grad)
            self.assertClose(tex._faces_uvs_list[i], tex_detached._faces_uvs_list[i])
            # tex._maps_list is not use anywhere so it's not stored. We call it explicitly
            self.assertFalse(tex_detached.maps_list()[i].requires_grad)
            self.assertClose(tex.maps_list()[i], tex_detached.maps_list()[i])
Nikhila Ravi's avatar
Nikhila Ravi committed
807
808
809

    def test_extend(self):
        B = 5
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
810
        mesh = init_mesh(B, 30, 50)
Nikhila Ravi's avatar
Nikhila Ravi committed
811
812
813
814
815
816
817
818
819
820
821
822
823
        V = mesh._V
        num_faces = mesh.num_faces_per_mesh()
        num_verts = mesh.num_verts_per_mesh()
        faces_uvs_list = [torch.randint(size=(f, 3), low=0, high=V) for f in num_faces]
        verts_uvs_list = [torch.rand(v, 2) for v in num_verts]
        tex_uv = TexturesUV(
            maps=torch.ones((B, 16, 16, 3)),
            faces_uvs=faces_uvs_list,
            verts_uvs=verts_uvs_list,
        )
        tex_mesh = Meshes(
            verts=mesh.verts_list(), faces=mesh.faces_list(), textures=tex_uv
        )
Nikhila Ravi's avatar
Nikhila Ravi committed
824
        N = 2
Nikhila Ravi's avatar
Nikhila Ravi committed
825
826
827
828
829
830
831
        new_mesh = tex_mesh.extend(N)

        self.assertEqual(len(tex_mesh) * N, len(new_mesh))

        tex_init = tex_mesh.textures
        new_tex = new_mesh.textures

832
        new_tex_num_verts = new_mesh.num_verts_per_mesh()
Nikhila Ravi's avatar
Nikhila Ravi committed
833
834
        for i in range(len(tex_mesh)):
            for n in range(N):
835
                tex_nv = new_tex_num_verts[i * N + n]
Nikhila Ravi's avatar
Nikhila Ravi committed
836
                self.assertClose(
837
838
839
840
841
842
843
844
                    # The original textures were initialized using
                    # verts uvs list
                    tex_init.verts_uvs_list()[i],
                    # In the new textures, the verts_uvs are initialized
                    # from padded. The verts per mesh are not used to
                    # convert from padded to list. See TexturesUV for an
                    # explanation.
                    new_tex.verts_uvs_list()[i * N + n][:tex_nv, ...],
Nikhila Ravi's avatar
Nikhila Ravi committed
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
                )
                self.assertClose(
                    tex_init.faces_uvs_list()[i], new_tex.faces_uvs_list()[i * N + n]
                )
                self.assertClose(
                    tex_init.maps_padded()[i, ...], new_tex.maps_padded()[i * N + n]
                )
                self.assertClose(
                    tex_init._num_faces_per_mesh[i],
                    new_tex._num_faces_per_mesh[i * N + n],
                )

        self.assertAllSeparate(
            [
                tex_init.faces_uvs_padded(),
                new_tex.faces_uvs_padded(),
                tex_init.verts_uvs_padded(),
                new_tex.verts_uvs_padded(),
                tex_init.maps_padded(),
                new_tex.maps_padded(),
            ]
        )

        with self.assertRaises(ValueError):
            tex_mesh.extend(N=-1)

    def test_padded_to_packed(self):
Nikhila Ravi's avatar
Nikhila Ravi committed
872
873
874
        # Case where each face in the mesh has 3 unique uv vertex indices
        # - i.e. even if a vertex is shared between multiple faces it will
        # have a unique uv coordinate for each face.
Nikhila Ravi's avatar
Nikhila Ravi committed
875
        N = 2
Nikhila Ravi's avatar
Nikhila Ravi committed
876
877
878
879
880
        faces_uvs_list = [
            torch.tensor([[0, 1, 2], [3, 5, 4], [7, 6, 8]]),
            torch.tensor([[0, 1, 2], [3, 4, 5]]),
        ]  # (N, 3, 3)
        verts_uvs_list = [torch.ones(9, 2), torch.ones(6, 2)]
Nikhila Ravi's avatar
Nikhila Ravi committed
881
882
883
884

        num_faces_per_mesh = [f.shape[0] for f in faces_uvs_list]
        num_verts_per_mesh = [v.shape[0] for v in verts_uvs_list]
        tex = TexturesUV(
Nikhila Ravi's avatar
Nikhila Ravi committed
885
            maps=torch.ones((N, 16, 16, 3)),
Nikhila Ravi's avatar
Nikhila Ravi committed
886
887
            faces_uvs=faces_uvs_list,
            verts_uvs=verts_uvs_list,
Nikhila Ravi's avatar
Nikhila Ravi committed
888
889
890
891
892
        )

        # This is set inside Meshes when textures is passed as an input.
        # Here we set _num_faces_per_mesh and _num_verts_per_mesh explicity.
        tex1 = tex.clone()
Nikhila Ravi's avatar
Nikhila Ravi committed
893
894
        tex1._num_faces_per_mesh = num_faces_per_mesh
        tex1._num_verts_per_mesh = num_verts_per_mesh
Nikhila Ravi's avatar
Nikhila Ravi committed
895
        verts_list = tex1.verts_uvs_list()
Nikhila Ravi's avatar
Nikhila Ravi committed
896
        verts_padded = tex1.verts_uvs_padded()
Nikhila Ravi's avatar
Nikhila Ravi committed
897

Nikhila Ravi's avatar
Nikhila Ravi committed
898
899
900
901
        faces_list = tex1.faces_uvs_list()
        faces_padded = tex1.faces_uvs_padded()

        for f1, f2 in zip(faces_list, faces_uvs_list):
Nikhila Ravi's avatar
Nikhila Ravi committed
902
903
            self.assertTrue((f1 == f2).all().item())

Nikhila Ravi's avatar
Nikhila Ravi committed
904
905
        for f1, f2 in zip(verts_list, verts_uvs_list):
            self.assertTrue((f1 == f2).all().item())
Nikhila Ravi's avatar
Nikhila Ravi committed
906

Nikhila Ravi's avatar
Nikhila Ravi committed
907
908
        self.assertTrue(faces_padded.shape == (2, 3, 3))
        self.assertTrue(verts_padded.shape == (2, 9, 2))
Nikhila Ravi's avatar
Nikhila Ravi committed
909

Nikhila Ravi's avatar
Nikhila Ravi committed
910
911
912
913
914
915
916
        # Case where num_faces_per_mesh is not set and faces_verts_uvs
        # are initialized with a padded tensor.
        tex2 = TexturesUV(
            maps=torch.ones((N, 16, 16, 3)),
            verts_uvs=verts_padded,
            faces_uvs=faces_padded,
        )
Nikhila Ravi's avatar
Nikhila Ravi committed
917
918
919
        faces_list = tex2.faces_uvs_list()
        verts_list = tex2.verts_uvs_list()

Nikhila Ravi's avatar
Nikhila Ravi committed
920
921
922
        for i, (f1, f2) in enumerate(zip(faces_list, faces_uvs_list)):
            n = num_faces_per_mesh[i]
            self.assertTrue((f1[:n] == f2).all().item())
Nikhila Ravi's avatar
Nikhila Ravi committed
923

Nikhila Ravi's avatar
Nikhila Ravi committed
924
925
926
        for i, (f1, f2) in enumerate(zip(verts_list, verts_uvs_list)):
            n = num_verts_per_mesh[i]
            self.assertTrue((f1[:n] == f2).all().item())
Nikhila Ravi's avatar
Nikhila Ravi committed
927

Nikhila Ravi's avatar
Nikhila Ravi committed
928
929
    def test_to(self):
        tex = TexturesUV(
facebook-github-bot's avatar
facebook-github-bot committed
930
            maps=torch.ones((5, 16, 16, 3)),
Nikhila Ravi's avatar
Nikhila Ravi committed
931
932
            faces_uvs=torch.randint(size=(5, 10, 3), high=15),
            verts_uvs=torch.rand(size=(5, 15, 2)),
facebook-github-bot's avatar
facebook-github-bot committed
933
        )
Nikhila Ravi's avatar
Nikhila Ravi committed
934
935
        device = torch.device("cuda:0")
        tex = tex.to(device)
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
        self.assertEqual(tex._faces_uvs_padded.device, device)
        self.assertEqual(tex._verts_uvs_padded.device, device)
        self.assertEqual(tex._maps_padded.device, device)

    def test_mesh_to(self):
        tex_cpu = TexturesUV(
            maps=torch.ones((5, 16, 16, 3)),
            faces_uvs=torch.randint(size=(5, 10, 3), high=15),
            verts_uvs=torch.rand(size=(5, 15, 2)),
        )
        verts = torch.rand(size=(5, 15, 3))
        faces = torch.randint(size=(5, 10, 3), high=15)
        mesh_cpu = Meshes(faces=faces, verts=verts, textures=tex_cpu)
        cpu = torch.device("cpu")
        device = torch.device("cuda:0")
        tex = mesh_cpu.to(device).textures
        self.assertEqual(tex._faces_uvs_padded.device, device)
        self.assertEqual(tex._verts_uvs_padded.device, device)
        self.assertEqual(tex._maps_padded.device, device)
        self.assertEqual(tex_cpu._verts_uvs_padded.device, cpu)

        self.assertEqual(tex_cpu.device, cpu)
        self.assertEqual(tex.device, device)
facebook-github-bot's avatar
facebook-github-bot committed
959

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
960
961
962
    def test_getitem(self):
        N = 5
        V = 20
Nikhila Ravi's avatar
Nikhila Ravi committed
963
        F = 10
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
964
        source = {
Nikhila Ravi's avatar
Nikhila Ravi committed
965
            "maps": torch.rand(size=(N, 1, 1, 3)),
Nikhila Ravi's avatar
Nikhila Ravi committed
966
            "faces_uvs": torch.randint(size=(N, F, 3), high=V),
Nikhila Ravi's avatar
Nikhila Ravi committed
967
            "verts_uvs": torch.randn(size=(N, V, 2)),
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
968
        }
Nikhila Ravi's avatar
Nikhila Ravi committed
969
        tex = TexturesUV(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
970
971
972
973
974
975
            maps=source["maps"],
            faces_uvs=source["faces_uvs"],
            verts_uvs=source["verts_uvs"],
        )

        verts = torch.rand(size=(N, V, 3))
Nikhila Ravi's avatar
Nikhila Ravi committed
976
        faces = torch.randint(size=(N, F, 3), high=V)
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
977
978
        meshes = Meshes(verts=verts, faces=faces, textures=tex)

Nikhila Ravi's avatar
Nikhila Ravi committed
979
980
        tryindex(self, 2, tex, meshes, source)
        tryindex(self, slice(0, 2, 1), tex, meshes, source)
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
981
        index = torch.tensor([1, 0, 1, 0, 0], dtype=torch.bool)
Nikhila Ravi's avatar
Nikhila Ravi committed
982
        tryindex(self, index, tex, meshes, source)
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
983
        index = torch.tensor([0, 0, 0, 0, 0], dtype=torch.bool)
Nikhila Ravi's avatar
Nikhila Ravi committed
984
        tryindex(self, index, tex, meshes, source)
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
985
        index = torch.tensor([1, 2], dtype=torch.int64)
Nikhila Ravi's avatar
Nikhila Ravi committed
986
987
        tryindex(self, index, tex, meshes, source)
        tryindex(self, [2, 4], tex, meshes, source)
988

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
989
990
991
    def test_centers_for_image(self):
        maps = torch.rand(size=(1, 257, 129, 3))
        verts_uvs = torch.FloatTensor([[[0.25, 0.125], [0.5, 0.625], [0.5, 0.5]]])
992
993
994
        faces_uvs = torch.zeros(size=(1, 0, 3), dtype=torch.int64)
        tex = TexturesUV(maps=maps, faces_uvs=faces_uvs, verts_uvs=verts_uvs)

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
995
996
        expected = torch.FloatTensor([[32, 224], [64, 96], [64, 128]])
        self.assertClose(tex.centers_for_image(0), expected)
997

Nikhila Ravi's avatar
Nikhila Ravi committed
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
    def test_sample_textures_error(self):
        N = 1
        V = 20
        F = 10
        maps = torch.rand(size=(N, 1, 1, 3))
        verts_uvs = torch.randn(size=(N, V, 2))
        tex = TexturesUV(
            maps=maps,
            faces_uvs=torch.randint(size=(N, 15, 3), high=V),
            verts_uvs=verts_uvs,
        )
        verts = torch.rand(size=(5, V, 3))
        faces = torch.randint(size=(5, 10, 3), high=V)
        meshes = Meshes(verts=verts, faces=faces)

        # Wrong number of faces
        with self.assertRaisesRegex(ValueError, "do not match the dimensions"):
            Meshes(verts=verts, faces=faces, textures=tex)

        # Wrong batch dim for faces
        tex = TexturesUV(
            maps=maps,
            faces_uvs=torch.randint(size=(1, F, 3), high=V),
            verts_uvs=verts_uvs,
        )
        with self.assertRaisesRegex(ValueError, "do not match the dimensions"):
            Meshes(verts=verts, faces=faces, textures=tex)

        # Wrong batch dim for verts_uvs is not necessary to check as
        # there is already a check inside TexturesUV for a batch dim
        # mismatch with faces_uvs

        meshes = Meshes(verts=verts, faces=faces)
        meshes.textures = tex

        # Cannot use the texture attribute set on meshes for sampling
        # textures if the dimensions don't match
        with self.assertRaisesRegex(ValueError, "do not match the dimensions"):
            meshes.sample_textures(None)

Hassan Lotfi's avatar
Hassan Lotfi committed
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
    def test_submeshes(self):
        N = 2
        faces_uvs_list = [
            torch.LongTensor([[0, 1, 2], [3, 5, 4], [7, 6, 8]]),
            torch.LongTensor([[0, 1, 2], [3, 4, 5]]),
        ]
        verts_uvs_list = [
            torch.arange(18, dtype=torch.float32).reshape(9, 2),
            torch.ones(6, 2),
        ]
        tex = TexturesUV(
            maps=torch.rand((N, 16, 16, 3)),
            faces_uvs=faces_uvs_list,
            verts_uvs=verts_uvs_list,
        )

        sub_faces = [
            [torch.tensor([0, 1]), torch.tensor([1, 2])],
            [],
        ]

        mesh = Meshes(
            verts=[torch.rand(9, 3), torch.rand(6, 3)],
            faces=faces_uvs_list,
            textures=tex,
        )
        subtex = mesh.submeshes(sub_faces).textures
        subtex_faces = subtex.faces_uvs_padded()
        self.assertEqual(len(subtex_faces), 2)
        self.assertClose(
            subtex_faces[0],
            torch.tensor([[0, 1, 2], [3, 5, 4]]),
        )
        self.assertClose(
            subtex.verts_uvs_list()[0][subtex.faces_uvs_list()[0].flatten()]
            .flatten()
            .msort(),
            torch.arange(12, dtype=torch.float32),
        )
        self.assertClose(
            subtex.maps_padded(), tex.maps_padded()[:1].expand(2, -1, -1, -1)
        )

1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099

class TestRectanglePacking(TestCaseMixin, unittest.TestCase):
    def setUp(self) -> None:
        super().setUp()
        torch.manual_seed(42)

    def wrap_pack(self, sizes):
        """
        Call the pack_rectangles function, which we want to test,
        and return its outputs.
        Additionally makes some sanity checks on the output.
        """
        res = pack_rectangles(sizes)
        total = res.total_size
        self.assertGreaterEqual(total[0], 0)
        self.assertGreaterEqual(total[1], 0)
        mask = torch.zeros(total, dtype=torch.bool)
        seen_x_bound = False
        seen_y_bound = False
1100
1101
1102
1103
1104
1105
1106
1107
1108
        for (in_x, in_y), (out_x, out_y, flipped, is_first) in zip(
            sizes, res.locations
        ):
            self.assertTrue(is_first)
            self.assertGreaterEqual(out_x, 0)
            self.assertGreaterEqual(out_y, 0)
            placed_x, placed_y = (in_y, in_x) if flipped else (in_x, in_y)
            upper_x = placed_x + out_x
            upper_y = placed_y + out_y
1109
1110
1111
1112
1113
1114
            self.assertGreaterEqual(total[0], upper_x)
            if total[0] == upper_x:
                seen_x_bound = True
            self.assertGreaterEqual(total[1], upper_y)
            if total[1] == upper_y:
                seen_y_bound = True
1115
            already_taken = torch.sum(mask[out_x:upper_x, out_y:upper_y])
1116
            self.assertEqual(already_taken, 0)
1117
            mask[out_x:upper_x, out_y:upper_y] = 1
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
        self.assertTrue(seen_x_bound)
        self.assertTrue(seen_y_bound)

        self.assertTrue(torch.all(torch.sum(mask, dim=0, dtype=torch.int32) > 0))
        self.assertTrue(torch.all(torch.sum(mask, dim=1, dtype=torch.int32) > 0))
        return res

    def assert_bb(self, sizes, expected):
        """
        Apply the pack_rectangles function to sizes and verify the
        bounding box dimensions are expected.
        """
        self.assertSetEqual(set(self.wrap_pack(sizes).total_size), expected)

    def test_simple(self):
        self.assert_bb([(3, 4), (4, 3)], {6, 4})
Jeremy Reizenstein's avatar
lint  
Jeremy Reizenstein committed
1134
        self.assert_bb([(2, 2), (2, 4), (2, 2)], {4})
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159

        # many squares
        self.assert_bb([(2, 2)] * 9, {2, 18})

        # One big square and many small ones.
        self.assert_bb([(3, 3)] + [(1, 1)] * 2, {3, 4})
        self.assert_bb([(3, 3)] + [(1, 1)] * 3, {3, 4})
        self.assert_bb([(3, 3)] + [(1, 1)] * 4, {3, 5})
        self.assert_bb([(3, 3)] + [(1, 1)] * 5, {3, 5})
        self.assert_bb([(1, 1)] * 6 + [(3, 3)], {3, 5})
        self.assert_bb([(3, 3)] + [(1, 1)] * 7, {3, 6})

        # many identical rectangles
        self.assert_bb([(7, 190)] * 4 + [(190, 7)] * 4, {190, 56})

        # require placing the flipped version of a rectangle
        self.assert_bb([(1, 100), (5, 96), (4, 5)], {100, 6})

    def test_random(self):
        for _ in range(5):
            vals = torch.randint(size=(20, 2), low=1, high=18)
            sizes = []
            for j in range(vals.shape[0]):
                sizes.append((int(vals[j, 0]), int(vals[j, 1])))
            self.wrap_pack(sizes)
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185

    def test_all_identical(self):
        sizes = [Rectangle(xsize=61, ysize=82, identifier=1729)] * 3
        total_size, locations = pack_unique_rectangles(sizes)
        self.assertEqual(total_size, (61, 82))
        self.assertEqual(len(locations), 3)
        for i, (x, y, is_flipped, is_first) in enumerate(locations):
            self.assertEqual(x, 0)
            self.assertEqual(y, 0)
            self.assertFalse(is_flipped)
            self.assertEqual(is_first, i == 0)

    def test_one_different_id(self):
        sizes = [Rectangle(xsize=61, ysize=82, identifier=220)] * 3
        sizes.extend([Rectangle(xsize=61, ysize=82, identifier=284)] * 3)
        total_size, locations = pack_unique_rectangles(sizes)
        self.assertEqual(total_size, (82, 122))
        self.assertEqual(len(locations), 6)
        for i, (x, y, is_flipped, is_first) in enumerate(locations):
            self.assertTrue(is_flipped)
            self.assertEqual(is_first, i % 3 == 0)
            self.assertEqual(x, 0)
            if i < 3:
                self.assertEqual(y, 61)
            else:
                self.assertEqual(y, 0)