forked from AcademySoftwareFoundation/OpenImageIO
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtexturesys.cpp
More file actions
2732 lines (2429 loc) · 108 KB
/
texturesys.cpp
File metadata and controls
2732 lines (2429 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
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
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
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
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2008 Larry Gritz and the other authors and contributors.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the software's owners nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(This is the Modified BSD License)
*/
#include <cmath>
#include <string>
#include <sstream>
#include <cstring>
#include <list>
#include <OpenEXR/half.h>
#include <OpenEXR/ImathMatrix.h>
#include <OpenImageIO/dassert.h>
#include <OpenImageIO/typedesc.h>
#include <OpenImageIO/varyingref.h>
#include <OpenImageIO/ustring.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/thread.h>
#include <OpenImageIO/fmath.h>
#include <OpenImageIO/simd.h>
#include <OpenImageIO/filter.h>
#include <OpenImageIO/optparser.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/texture.h>
#include <OpenImageIO/imagecache.h>
#include <OpenImageIO/imagebuf.h>
#include <OpenImageIO/imagebufalgo.h>
#include <boost/random.hpp>
#include "imagecache_pvt.h"
#include "texture_pvt.h"
#define TEX_FAST_MATH 1
OIIO_NAMESPACE_BEGIN
using namespace pvt;
using namespace simd;
namespace { // anonymous
// We would like shared_texturesys to be a shared_ptr so that it is
// automatically deleted when the app exists, but because it contains a
// reference to an ImageCache, we get into the "destruction order fiasco."
// The only easy way to fix this is to make shared_texturesys be an ordinary
// pointer and just let it leak (who cares? the app is done, and it only
// contains a few hundred bytes).
static TextureSystemImpl *shared_texturesys = NULL;
static spin_mutex shared_texturesys_mutex;
static EightBitConverter<float> uchar2float;
static vfloat4 u8scale (1.0f/255.0f);
static vfloat4 u16scale (1.0f/65535.0f);
OIIO_FORCEINLINE vfloat4 uchar2float4 (const unsigned char *c) {
return vfloat4(c) * u8scale;
}
OIIO_FORCEINLINE vfloat4 ushort2float4 (const unsigned short *s) {
return vfloat4(s) * u16scale;
}
OIIO_FORCEINLINE vfloat4 half2float4 (const half *h) {
return vfloat4(h);
}
static const OIIO_SIMD4_ALIGN vbool4 channel_masks[5] = {
vbool4(false, false, false, false),
vbool4(true, false, false, false),
vbool4(true, true, false, false),
vbool4(true, true, true, false),
vbool4(true, true, true, true),
};
} // end anonymous namespace
TextureSystem *
TextureSystem::create (bool shared)
{
if (shared) {
// They requested a shared texture system. If a shared one already
// exists, just return it, otherwise record the new texture system.
spin_lock guard (shared_texturesys_mutex);
if (! shared_texturesys)
shared_texturesys = new TextureSystemImpl(ImageCache::create(true));
#if 0
std::cerr << " shared TextureSystem is "
<< (void *)shared_texturesys << "\n";
#endif
return shared_texturesys;
}
// Doesn't need a shared cache
TextureSystemImpl *ts = new TextureSystemImpl (ImageCache::create(false));
#if 0
std::cerr << "creating new ImageCache " << (void *)ts << "\n";
#endif
return ts;
}
void
TextureSystem::destroy (TextureSystem *x, bool teardown_imagecache)
{
// std::cerr << "Destroying TS " << (void *)x << "\n";
if (! x)
return;
TextureSystemImpl *impl = (TextureSystemImpl *) x;
if (teardown_imagecache) {
ImageCache::destroy (impl->m_imagecache, true);
impl->m_imagecache = NULL;
}
spin_lock guard (shared_texturesys_mutex);
if (impl == shared_texturesys) {
// This is the shared TS, so don't really delete it.
} else {
// Not a shared cache, we are the only owner, so truly destroy it.
delete x;
}
}
void
TextureSystem::destroy (TextureSystem *x)
{
destroy (x, false);
}
namespace pvt { // namespace pvt
// Wrap functions wrap 'coord' around 'width', and return true if the
// result is a valid pixel coordinate, false if black should be used
// instead.
bool
TextureSystemImpl::wrap_periodic_sharedborder (int &coord, int origin, int width)
{
// Like periodic, but knowing that the first column and last are
// actually the same position, so we essentially skip the last
// column in the next cycle.
if (width <= 2) {
coord = origin; // special case -- just 1 pixel wide
} else {
coord -= origin;
coord %= (width-1);
if (coord < 0) // Fix negative values
coord += width;
coord += origin;
}
return true;
}
const TextureSystemImpl::wrap_impl TextureSystemImpl::wrap_functions[] = {
// Must be in same order as Wrap enum
wrap_black, wrap_black, wrap_clamp, wrap_periodic, wrap_mirror,
wrap_periodic_pow2, wrap_periodic_sharedborder
};
simd::vbool4
wrap_black_simd (simd::vint4 &coord_, const simd::vint4& origin,
const simd::vint4& width)
{
simd::vint4 coord (coord_);
return (coord >= origin) & (coord < (width+origin));
}
simd::vbool4
wrap_clamp_simd (simd::vint4 &coord_, const simd::vint4& origin,
const simd::vint4& width)
{
simd::vint4 coord (coord_);
coord = simd::blend (coord, origin, coord < origin);
coord = simd::blend (coord, (origin+width-1), coord >= (origin+width));
coord_ = coord;
return simd::vbool4::True();
}
simd::vbool4
wrap_periodic_simd (simd::vint4 &coord_, const simd::vint4& origin,
const simd::vint4& width)
{
simd::vint4 coord (coord_);
coord = coord - origin;
coord = coord % width;
coord = simd::blend (coord, coord+width, coord < 0);
coord = coord + origin;
coord_ = coord;
return simd::vbool4::True();
}
simd::vbool4
wrap_periodic_pow2_simd (simd::vint4 &coord_, const simd::vint4& origin,
const simd::vint4& width)
{
simd::vint4 coord (coord_);
// DASSERT (ispow2(width));
coord = coord - origin;
coord = coord & (width - 1); // Shortcut periodic if we're sure it's a pow of 2
coord = coord + origin;
coord_ = coord;
return simd::vbool4::True();
}
simd::vbool4
wrap_mirror_simd (simd::vint4 &coord_, const simd::vint4& origin,
const simd::vint4& width)
{
simd::vint4 coord (coord_);
coord = coord - origin;
coord = simd::blend (coord, -1 - coord, coord < 0);
simd::vint4 iter = coord / width; // Which iteration of the pattern?
coord -= iter * width;
// Odd iterations -- flip the sense
coord = blend (coord, (width - 1) - coord, (iter & 1) != 0);
// DASSERT_MSG (coord >= 0 && coord < width,
// "width=%d, origin=%d, result=%d", width, origin, coord);
coord += origin;
coord_ = coord;
return simd::vbool4::True();
}
simd::vbool4
wrap_periodic_sharedborder_simd (simd::vint4 &coord_, const simd::vint4& origin,
const simd::vint4& width)
{
// Like periodic, but knowing that the first column and last are
// actually the same position, so we essentially skip the last
// column in the next cycle.
simd::vint4 coord (coord_);
coord = coord - origin;
coord = coord % (width-1);
coord += blend (simd::vint4(origin), width+origin, coord < 0); // Fix negative values
coord = blend (coord, origin, width <= 2); // special case -- just 1 pixel wide
coord_ = coord;
return true;
}
typedef simd::vbool4 (*wrap_impl_simd) (simd::vint4 &coord, const simd::vint4& origin,
const simd::vint4& width);
const wrap_impl_simd wrap_functions_simd[] = {
// Must be in same order as Wrap enum
wrap_black_simd, wrap_black_simd, wrap_clamp_simd,
wrap_periodic_simd, wrap_mirror_simd, wrap_periodic_pow2_simd,
wrap_periodic_sharedborder_simd
};
const char *
texture_format_name (TexFormat f)
{
static const char * texture_format_names[] = {
// MUST match the order of TexFormat
"unknown", "Plain Texture", "Volume Texture",
"Shadow", "CubeFace Shadow", "Volume Shadow",
"LatLong Environment", "CubeFace Environment",
""
};
return texture_format_names[(int)f];
}
const char *
texture_type_name (TexFormat f)
{
static const char * texture_type_names[] = {
// MUST match the order of TexFormat
"unknown", "Plain Texture", "Volume Texture",
"Shadow", "Shadow", "Shadow",
"Environment", "Environment",
""
};
return texture_type_names[(int)f];
}
TextureSystemImpl::TextureSystemImpl (ImageCache *imagecache)
: hq_filter(NULL)
{
m_imagecache = (ImageCacheImpl *) imagecache;
init ();
}
void
TextureSystemImpl::init ()
{
m_Mw2c.makeIdentity();
m_gray_to_rgb = false;
m_flip_t = false;
m_max_tile_channels = 5;
delete hq_filter;
hq_filter = Filter1D::create ("b-spline", 4);
m_statslevel = 0;
// Allow environment variable to override default options
const char *options = getenv ("OPENIMAGEIO_TEXTURE_OPTIONS");
if (options)
attribute ("options", options);
#if 0
unit_test_texture ();
#endif
}
TextureSystemImpl::~TextureSystemImpl ()
{
printstats ();
ImageCache::destroy (m_imagecache);
m_imagecache = NULL;
delete hq_filter;
}
std::string
TextureSystemImpl::getstats (int level, bool icstats) const
{
// Merge all the threads
ImageCacheStatistics stats;
m_imagecache->mergestats (stats);
std::ostringstream out;
out.imbue (std::locale::classic()); // Force "C" locale with '.' decimal
bool anytexture = (stats.texture_queries + stats.texture3d_queries +
stats.shadow_queries + stats.environment_queries);
if (level > 0 && anytexture) {
out << "OpenImageIO Texture statistics\n";
std::string opt;
#define BOOLOPT(name) if (m_##name) opt += #name " "
#define INTOPT(name) opt += Strutil::format(#name "=%d ", m_##name)
#define STROPT(name) if (m_##name.size()) opt += Strutil::format(#name "=\"%s\" ", m_##name)
INTOPT(gray_to_rgb);
INTOPT(flip_t);
INTOPT(max_tile_channels);
#undef BOOLOPT
#undef INTOPT
#undef STROPT
out << " Options: " << Strutil::wordwrap(opt,75,12) << "\n";
out << " Queries/batches : \n";
out << " texture : " << stats.texture_queries
<< " queries in " << stats.texture_batches << " batches\n";
out << " texture 3d : " << stats.texture3d_queries
<< " queries in " << stats.texture3d_batches << " batches\n";
out << " shadow : " << stats.shadow_queries
<< " queries in " << stats.shadow_batches << " batches\n";
out << " environment : " << stats.environment_queries
<< " queries in " << stats.environment_batches << " batches\n";
out << " Interpolations :\n";
out << " closest : " << stats.closest_interps << "\n";
out << " bilinear : " << stats.bilinear_interps << "\n";
out << " bicubic : " << stats.cubic_interps << "\n";
if (stats.aniso_queries)
out << Strutil::format (" Average anisotropic probes : %.3g\n",
(double)stats.aniso_probes/(double)stats.aniso_queries);
else
out << Strutil::format (" Average anisotropic probes : 0\n");
out << Strutil::format (" Max anisotropy in the wild : %.3g\n",
stats.max_aniso);
if (icstats)
out << "\n";
}
if (icstats)
out << m_imagecache->getstats (level);
return out.str();
}
void
TextureSystemImpl::printstats () const
{
if (m_statslevel == 0)
return;
std::cout << getstats (m_statslevel, false) << "\n\n";
}
void
TextureSystemImpl::reset_stats ()
{
ASSERT (m_imagecache);
m_imagecache->reset_stats ();
}
bool
TextureSystemImpl::attribute (string_view name, TypeDesc type,
const void *val)
{
if (name == "options" && type == TypeDesc::STRING) {
return optparser (*this, *(const char **)val);
}
if (name == "worldtocommon" && (type == TypeMatrix ||
type == TypeDesc(TypeDesc::FLOAT,16))) {
m_Mw2c = *(const Imath::M44f *)val;
m_Mc2w = m_Mw2c.inverse();
return true;
}
if (name == "commontoworld" && (type == TypeMatrix ||
type == TypeDesc(TypeDesc::FLOAT,16))) {
m_Mc2w = *(const Imath::M44f *)val;
m_Mw2c = m_Mc2w.inverse();
return true;
}
if ((name == "gray_to_rgb" || name == "grey_to_rgb") &&
(type == TypeInt)) {
m_gray_to_rgb = *(const int *)val;
return true;
}
if (name == "flip_t" && type == TypeInt) {
m_flip_t = *(const int *)val;
return true;
}
if (name == "m_max_tile_channels" && type == TypeInt) {
m_max_tile_channels = *(const int *)val;
return true;
}
if (name == "statistics:level" && type == TypeInt) {
m_statslevel = *(const int *)val;
// DO NOT RETURN! pass the same message to the image cache
}
// Maybe it's meant for the cache?
return m_imagecache->attribute (name, type, val);
}
bool
TextureSystemImpl::getattribute (string_view name, TypeDesc type,
void *val) const
{
if (name == "worldtocommon" && (type == TypeMatrix ||
type == TypeDesc(TypeDesc::FLOAT,16))) {
*(Imath::M44f *)val = m_Mw2c;
return true;
}
if (name == "commontoworld" && (type == TypeMatrix ||
type == TypeDesc(TypeDesc::FLOAT,16))) {
*(Imath::M44f *)val = m_Mc2w;
return true;
}
if ((name == "gray_to_rgb" || name == "grey_to_rgb") &&
(type == TypeInt)) {
*(int *)val = m_gray_to_rgb;
return true;
}
if (name == "flip_t" && type == TypeInt) {
*(int *)val = m_flip_t;
return true;
}
if (name == "m_max_tile_channels" && type == TypeInt) {
*(int *)val = m_max_tile_channels;
return true;
}
// If not one of these, maybe it's an attribute meant for the image cache?
return m_imagecache->getattribute (name, type, val);
return false;
}
std::string
TextureSystemImpl::resolve_filename (const std::string &filename) const
{
return m_imagecache->resolve_filename (filename);
}
bool
TextureSystemImpl::get_texture_info (ustring filename, int subimage,
ustring dataname, TypeDesc datatype, void *data)
{
bool ok = m_imagecache->get_image_info (filename, subimage, 0,
dataname, datatype, data);
if (! ok) {
std::string err = m_imagecache->geterror();
if (!err.empty())
error ("%s", err);
}
return ok;
}
bool
TextureSystemImpl::get_texture_info (TextureHandle *texture_handle,
Perthread *thread_info, int subimage,
ustring dataname, TypeDesc datatype, void *data)
{
bool ok = m_imagecache->get_image_info ((ImageCache::ImageHandle *)texture_handle,
(ImageCache::Perthread *)thread_info,
subimage, 0,
dataname, datatype, data);
if (! ok) {
std::string err = m_imagecache->geterror();
if (!err.empty())
error ("%s", err);
}
return ok;
}
bool
TextureSystemImpl::get_imagespec (ustring filename, int subimage,
ImageSpec &spec)
{
bool ok = m_imagecache->get_imagespec (filename, spec, subimage);
if (! ok) {
std::string err = m_imagecache->geterror();
if (!err.empty())
error ("%s", err);
}
return ok;
}
bool
TextureSystemImpl::get_imagespec (TextureHandle *texture_handle,
Perthread *thread_info, int subimage,
ImageSpec &spec)
{
bool ok = m_imagecache->get_imagespec ((ImageCache::ImageHandle *)texture_handle,
(ImageCache::Perthread *)thread_info,
spec, subimage);
if (! ok) {
std::string err = m_imagecache->geterror();
if (!err.empty())
error ("%s", err);
}
return ok;
}
const ImageSpec *
TextureSystemImpl::imagespec (ustring filename, int subimage)
{
const ImageSpec *spec = m_imagecache->imagespec (filename, subimage);
if (! spec)
error ("%s", m_imagecache->geterror());
return spec;
}
const ImageSpec *
TextureSystemImpl::imagespec (TextureHandle *texture_handle,
Perthread *thread_info, int subimage)
{
const ImageSpec *spec =
m_imagecache->imagespec ((ImageCache::ImageHandle *)texture_handle,
(ImageCache::Perthread *)thread_info, subimage);
if (! spec) {
std::string err = m_imagecache->geterror();
if (!err.empty())
error ("%s", err);
}
return spec;
}
bool
TextureSystemImpl::get_texels (ustring filename, TextureOpt &options,
int miplevel, int xbegin, int xend,
int ybegin, int yend, int zbegin, int zend,
int chbegin, int chend,
TypeDesc format, void *result)
{
PerThreadInfo *thread_info = m_imagecache->get_perthread_info ();
TextureFile *texfile = find_texturefile (filename, thread_info);
if (! texfile) {
error ("Texture file \"%s\" not found", filename);
return false;
}
return get_texels ((TextureHandle *)texfile, (Perthread *)thread_info,
options, miplevel, xbegin, xend,
ybegin, yend, zbegin, zend, chbegin, chend,
format, result);
}
bool
TextureSystemImpl::get_texels (TextureHandle *texture_handle_,
Perthread *thread_info_, TextureOpt &options,
int miplevel, int xbegin, int xend,
int ybegin, int yend, int zbegin, int zend,
int chbegin, int chend,
TypeDesc format, void *result)
{
PerThreadInfo *thread_info = m_imagecache->get_perthread_info((PerThreadInfo *)thread_info_);
TextureFile *texfile = verify_texturefile ((TextureFile *)texture_handle_, thread_info);
if (! texfile) {
error ("Invalid texture handle NULL");
return false;
}
if (texfile->broken()) {
if (texfile->errors_should_issue())
error ("Invalid texture file \"%s\"", texfile->filename());
return false;
}
int subimage = options.subimage;
if (subimage < 0 || subimage >= texfile->subimages()) {
error ("get_texel asked for nonexistant subimage %d of \"%s\"",
subimage, texfile->filename());
return false;
}
if (miplevel < 0 || miplevel >= texfile->miplevels(subimage)) {
if (texfile->errors_should_issue())
error ("get_texel asked for nonexistant MIP level %d of \"%s\"",
miplevel, texfile->filename());
return false;
}
const ImageSpec &spec (texfile->spec(subimage, miplevel));
// FIXME -- this could be WAY more efficient than starting from
// scratch for each pixel within the rectangle. Instead, we should
// grab a whole tile at a time and memcpy it rapidly. But no point
// doing anything more complicated (not to mention bug-prone) until
// somebody reports this routine as being a bottleneck.
int nchannels = chend - chbegin;
int actualchannels = Imath::clamp (spec.nchannels - chbegin, 0, nchannels);
int tile_chbegin = 0, tile_chend = spec.nchannels;
if (spec.nchannels > m_max_tile_channels) {
// For files with many channels, narrow the range we cache
tile_chbegin = chbegin;
tile_chend = chbegin+actualchannels;
}
TileID tileid (*texfile, subimage, miplevel, 0, 0, 0,
tile_chbegin, tile_chend);
size_t formatchannelsize = format.size();
size_t formatpixelsize = nchannels * formatchannelsize;
size_t scanlinesize = (xend-xbegin) * formatpixelsize;
size_t zplanesize = (yend-ybegin) * scanlinesize;
bool ok = true;
for (int z = zbegin; z < zend; ++z) {
if (z < spec.z || z >= (spec.z+std::max(spec.depth,1))) {
// nonexistant planes
memset (result, 0, zplanesize);
result = (void *) ((char *) result + zplanesize);
continue;
}
tileid.z (z - ((z - spec.z) % std::max (1, spec.tile_depth)));
for (int y = ybegin; y < yend; ++y) {
if (y < spec.y || y >= (spec.y+spec.height)) {
// nonexistant scanlines
memset (result, 0, scanlinesize);
result = (void *) ((char *) result + scanlinesize);
continue;
}
tileid.y (y - ((y - spec.y) % spec.tile_height));
for (int x = xbegin; x < xend; ++x) {
if (x < spec.x || x >= (spec.x+spec.width)) {
// nonexistant columns
memset (result, 0, formatpixelsize);
result = (void *) ((char *) result + formatpixelsize);
continue;
}
tileid.x (x - ((x - spec.x) % spec.tile_width));
ok &= find_tile (tileid, thread_info);
TileRef &tile (thread_info->tile);
const char *data;
if (tile && (data = (const char *)tile->data (x, y, z, chbegin))) {
convert_types (texfile->datatype(subimage), data,
format, result, actualchannels);
for (int c = actualchannels; c < nchannels; ++c)
convert_types (TypeDesc::FLOAT, &options.fill, format,
(char *)result+c*formatchannelsize, 1);
} else {
memset (result, 0, formatpixelsize);
}
result = (void *) ((char *) result + formatpixelsize);
}
}
}
if (! ok) {
std::string err = m_imagecache->geterror();
if (! err.empty())
error ("%s", err);
}
return ok;
}
std::string
TextureSystemImpl::geterror () const
{
std::string e;
std::string *errptr = m_errormessage.get ();
if (errptr) {
e = *errptr;
errptr->clear ();
}
return e;
}
void
TextureSystemImpl::append_error (const std::string& message) const
{
std::string *errptr = m_errormessage.get ();
if (! errptr) {
errptr = new std::string;
m_errormessage.reset (errptr);
}
ASSERT (errptr != NULL);
ASSERT (errptr->size() < 1024*1024*16 &&
"Accumulated error messages > 16MB. Try checking return codes!");
if (errptr->size())
*errptr += '\n';
*errptr += message;
}
// Implementation of invalidate -- just invalidate the image cache.
void
TextureSystemImpl::invalidate (ustring filename)
{
m_imagecache->invalidate (filename);
}
// Implementation of invalidate -- just invalidate the image cache.
void
TextureSystemImpl::invalidate_all (bool force)
{
m_imagecache->invalidate_all (force);
}
bool
TextureSystemImpl::missing_texture (TextureOpt &options, int nchannels,
float *result, float *dresultds,
float *dresultdt, float *dresultdr)
{
for (int c = 0; c < nchannels; ++c) {
if (options.missingcolor)
result[c] = options.missingcolor[c];
else
result[c] = options.fill;
if (dresultds) dresultds[c] = 0;
if (dresultdt) dresultdt[c] = 0;
if (dresultdr) dresultdr[c] = 0;
}
if (options.missingcolor) {
// don't treat it as an error if missingcolor was supplied
(void) geterror (); // eat the error
return true;
} else {
return false;
}
}
void
TextureSystemImpl::fill_gray_channels (const ImageSpec &spec,
int nchannels, float *result,
float *dresultds, float *dresultdt,
float *dresultdr)
{
int specchans = spec.nchannels;
if (specchans == 1 && nchannels >= 3) {
// Asked for RGB or RGBA, texture was just R...
// copy the one channel to G and B
*(simd::vfloat4 *)result = simd::shuffle<0,0,0,3>(*(simd::vfloat4 *)result);
if (dresultds) {
*(simd::vfloat4 *)dresultds = simd::shuffle<0,0,0,3>(*(simd::vfloat4 *)dresultds);
*(simd::vfloat4 *)dresultdt = simd::shuffle<0,0,0,3>(*(simd::vfloat4 *)dresultdt);
if (dresultdr)
*(simd::vfloat4 *)dresultdr = simd::shuffle<0,0,0,3>(*(simd::vfloat4 *)dresultdr);
}
} else if (specchans == 2 && nchannels == 4 && spec.alpha_channel == 1) {
// Asked for RGBA, texture was RA
// Shuffle into RRRA
*(simd::vfloat4 *)result = simd::shuffle<0,0,0,1>(*(simd::vfloat4 *)result);
if (dresultds) {
*(simd::vfloat4 *)dresultds = simd::shuffle<0,0,0,1>(*(simd::vfloat4 *)dresultds);
*(simd::vfloat4 *)dresultdt = simd::shuffle<0,0,0,1>(*(simd::vfloat4 *)dresultdt);
if (dresultdr)
*(simd::vfloat4 *)dresultdr = simd::shuffle<0,0,0,1>(*(simd::vfloat4 *)dresultdr);
}
}
}
bool
TextureSystemImpl::texture (ustring filename, TextureOptions &options,
Runflag *runflags, int beginactive, int endactive,
VaryingRef<float> s, VaryingRef<float> t,
VaryingRef<float> dsdx, VaryingRef<float> dtdx,
VaryingRef<float> dsdy, VaryingRef<float> dtdy,
int nchannels, float *result,
float *dresultds, float *dresultdt)
{
Perthread *thread_info = get_perthread_info();
TextureHandle *texture_handle = get_texture_handle (filename, thread_info);
return texture (texture_handle, thread_info, options,
runflags, beginactive, endactive,
s, t, dsdx, dtdx, dsdy, dtdy,
nchannels, result, dresultds, dresultdt);
}
bool
TextureSystemImpl::texture (TextureHandle *texture_handle,
Perthread *thread_info, TextureOptions &options,
Runflag *runflags, int beginactive, int endactive,
VaryingRef<float> s, VaryingRef<float> t,
VaryingRef<float> dsdx, VaryingRef<float> dtdx,
VaryingRef<float> dsdy, VaryingRef<float> dtdy,
int nchannels, float *result,
float *dresultds, float *dresultdt)
{
if (! texture_handle)
return false;
bool ok = true;
result += beginactive*nchannels;
if (dresultds) {
dresultds += beginactive*nchannels;
dresultdt += beginactive*nchannels;
}
for (int i = beginactive; i < endactive; ++i) {
if (runflags[i]) {
TextureOpt opt (options, i);
ok &= texture (texture_handle, thread_info,
opt, s[i], t[i], dsdx[i], dtdx[i],
dsdy[i], dtdy[i], nchannels,
result, dresultds, dresultdt);
}
result += nchannels;
if (dresultds) {
dresultds += nchannels;
dresultdt += nchannels;
}
}
return ok;
}
bool
TextureSystemImpl::texture (ustring filename, TextureOpt &options,
float s, float t, float dsdx, float dtdx,
float dsdy, float dtdy,
int nchannels, float *result,
float *dresultds, float *dresultdt)
{
PerThreadInfo *thread_info = m_imagecache->get_perthread_info ();
TextureFile *texturefile = find_texturefile (filename, thread_info);
return texture ((TextureHandle *)texturefile, (Perthread *)thread_info,
options, s, t, dsdx, dtdx, dsdy, dtdy,
nchannels, result, dresultds, dresultdt);
}
bool
TextureSystemImpl::texture (TextureHandle *texture_handle_,
Perthread *thread_info_, TextureOpt &options,
float s, float t, float dsdx, float dtdx,
float dsdy, float dtdy,
int nchannels, float *result,
float *dresultds, float *dresultdt)
{
// Handle >4 channel lookups by recursion.
if (nchannels > 4) {
int save_firstchannel = options.firstchannel;
while (nchannels) {
int n = std::min (nchannels, 4);
bool ok = texture (texture_handle_, thread_info_, options,
s, t, dsdx, dtdx, dsdy, dtdy, n /* chans */,
result, dresultds, dresultdt);
if (! ok)
return false;
result += n;
if (dresultds) dresultds += n;
if (dresultdt) dresultdt += n;
options.firstchannel += n;
nchannels -= n;
}
options.firstchannel = save_firstchannel; // restore what we changed
return true;
}
static const texture_lookup_prototype lookup_functions[] = {
// Must be in the same order as Mipmode enum
&TextureSystemImpl::texture_lookup,
&TextureSystemImpl::texture_lookup_nomip,
&TextureSystemImpl::texture_lookup_trilinear_mipmap,
&TextureSystemImpl::texture_lookup_trilinear_mipmap,
&TextureSystemImpl::texture_lookup
};
texture_lookup_prototype lookup = lookup_functions[(int)options.mipmode];
PerThreadInfo *thread_info = m_imagecache->get_perthread_info((PerThreadInfo *)thread_info_);
TextureFile *texturefile = (TextureFile *)texture_handle_;
if (texturefile->is_udim())
texturefile = m_imagecache->resolve_udim (texturefile, s, t);
texturefile = verify_texturefile (texturefile, thread_info);
ImageCacheStatistics &stats (thread_info->m_stats);
++stats.texture_batches;
++stats.texture_queries;
if (! texturefile || texturefile->broken())
return missing_texture (options, nchannels, result, dresultds, dresultdt);
if (options.subimagename) {
// If subimage was specified by name, figure out its index.
int s = m_imagecache->subimage_from_name (texturefile, options.subimagename);
if (s < 0) {
error ("Unknown subimage \"%s\" in texture \"%s\"",
options.subimagename, texturefile->filename());
return false;
}
options.subimage = s;
options.subimagename.clear();
}