ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/wrapBSDF.c
Revision: 2.22
Committed: Tue Feb 14 19:58:37 2017 UTC (5 years, 9 months ago) by greg
Content type: text/plain
Branch: MAIN
CVS Tags: rad5R2, rad5R1
Changes since 2.21: +3 -2 lines
Log Message:
Added "d" nickname for device type

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.22 static const char RCSid[] = "$Id: wrapBSDF.c,v 2.21 2016/10/14 00:54:22 greg Exp $";
3 greg 2.1 #endif
4     /*
5 greg 2.2 * Wrap BSDF data in valid WINDOW XML file
6 greg 2.1 *
7 greg 2.2 * G. Ward February 2015
8 greg 2.1 */
9    
10 schorsch 2.20 #include "platform.h"
11 greg 2.1 #include <ctype.h>
12     #include "rtio.h"
13 greg 2.17 #include "paths.h"
14 greg 2.1 #include "ezxml.h"
15     #include "bsdf.h"
16     #include "bsdf_m.h"
17     /* XML template file names */
18     const char def_template[] = "minimalBSDFt.xml";
19 greg 2.3 const char win6_template[] = "WINDOW6BSDFt.xml";
20 greg 2.1
21     const char stdin_name[] = "<stdin>";
22     /* input files (can be stdin_name) */
23     const char *xml_input = NULL;
24     /* unit for materials & geometry */
25 greg 2.2 const char *attr_unit = "meter";
26 greg 2.1 const char legal_units[] = "meter|foot|inch|centimeter|millimeter";
27     /* system materials & geometry */
28     const char *mgf_geometry = NULL;
29 greg 2.16 /* comment list */
30     #define MAXCOMM 30
31     const char *commlist[MAXCOMM];
32     int ncomm = 0;
33 greg 2.6 /* angle bases */
34 greg 2.1 enum { ABdefault=-1, ABklemsFull=0, ABklemsHalf, ABklemsQuarter,
35     ABtensorTree3, ABtensorTree4, ABend };
36    
37     int angle_basis = ABdefault;
38    
39 greg 2.7 int correct_solid_angle = 0;
40    
41     const char *klems_basis_name[] = {
42     "LBNL/Klems Full",
43     "LBNL/Klems Half",
44     "LBNL/Klems Quarter",
45     };
46 greg 2.1 /* field IDs and nicknames */
47     struct s_fieldID {
48     char nickName[4];
49 greg 2.3 short has_unit;
50     short win_need;
51 greg 2.1 const char *fullName;
52     } XMLfieldID[] = {
53 greg 2.3 {"m", 0, 1, "Manufacturer"},
54     {"n", 0, 1, "Name"},
55 greg 2.22 {"d", 0, 0, "DeviceType"},
56 greg 2.3 {"c", 0, 0, "ThermalConductivity"},
57     {"ef", 0, 0, "EmissivityFront"},
58     {"eb", 0, 0, "EmissivityBack"},
59     {"tir", 0, 0, "TIR"},
60     {"eo", 0, 0, "EffectiveOpennessFraction"},
61     {"t", 1, 1, "Thickness"},
62     {"h", 1, 0, "Height"},
63     {"w", 1, 0, "Width"},
64     {"\0", 0, 0, NULL} /* terminator */
65 greg 2.1 };
66     /* field assignments */
67 greg 2.22 #define MAXASSIGN 16
68 greg 2.1 const char *field_assignment[MAXASSIGN];
69     int nfield_assign = 0;
70     #define FASEP ';'
71     /* data file(s) & spectra */
72     enum { DTtransForward, DTtransBackward, DTreflForward, DTreflBackward };
73    
74 greg 2.11 enum { DSsolar=-1, DSnir=-2, DSxbar31=-3, DSvisible=-4, DSzbar31=-5,
75     DSuprime=-6, DSvprime=-7 };
76 greg 2.1
77     #define MAXFILES 20
78    
79     struct s_dfile {
80     const char *fname; /* input data file name */
81     short type; /* BSDF data type */
82     short spectrum; /* BSDF sensor spectrum */
83     } data_file[MAXFILES];
84    
85     int ndataf = 0; /* number of data files */
86    
87 greg 2.18 int unlink_datafiles = 0; /* unlink data files when done */
88    
89 greg 2.1 const char *spectr_file[MAXFILES]; /* custom spectral curve input */
90    
91     const char top_level_name[] = "WindowElement";
92    
93 greg 2.3 static char basis_definition[][256] = {
94 greg 2.1
95 greg 2.4 "\t<DataDefinition>\n"
96 greg 2.1 "\t\t<IncidentDataStructure>Columns</IncidentDataStructure>\n"
97     "\t\t<AngleBasis>\n"
98     "\t\t\t<AngleBasisName>LBNL/Klems Full</AngleBasisName>\n"
99 greg 2.4 "\t\t\t</AngleBasis>\n"
100     "\t</DataDefinition>\n",
101 greg 2.1
102 greg 2.4 "\t<DataDefinition>\n"
103 greg 2.1 "\t\t<IncidentDataStructure>Columns</IncidentDataStructure>\n"
104     "\t\t<AngleBasis>\n"
105     "\t\t\t<AngleBasisName>LBNL/Klems Half</AngleBasisName>\n"
106 greg 2.4 "\t\t\t</AngleBasis>\n"
107     "\t</DataDefinition>\n",
108 greg 2.1
109 greg 2.4 "\t<DataDefinition>\n"
110 greg 2.1 "\t\t<IncidentDataStructure>Columns</IncidentDataStructure>\n"
111     "\t\t<AngleBasis>\n"
112     "\t\t\t<AngleBasisName>LBNL/Klems Quarter</AngleBasisName>\n"
113 greg 2.4 "\t\t\t</AngleBasis>\n"
114     "\t</DataDefinition>\n",
115 greg 2.1
116 greg 2.4 "\t<DataDefinition>\n"
117     "\t\t<IncidentDataStructure>TensorTree3</IncidentDataStructure>\n"
118     "\t</DataDefinition>\n",
119    
120     "\t<DataDefinition>\n"
121     "\t\t<IncidentDataStructure>TensorTree4</IncidentDataStructure>\n"
122     "\t</DataDefinition>\n",
123 greg 2.1 };
124    
125     /* Copy data from file descriptor to stdout and close */
126     static int
127     copy_and_close(int fd)
128     {
129     int ok = 1;
130     char buf[8192];
131     int n;
132    
133     if (fd < 0)
134     return 0;
135     while ((n = read(fd, buf, sizeof(buf))) > 0)
136     if (write(fileno(stdout), buf, n) != n) {
137     ok = 0;
138     break;
139     }
140     ok &= (n == 0);
141     close(fd);
142     return ok;
143     }
144    
145     /* Allocate and assign string from file or stream */
146     static char *
147     input2str(const char *inpspec)
148     {
149     FILE *fp = NULL;
150     char *str;
151     int len, pos, n;
152    
153     if (inpspec == NULL || !*inpspec)
154     return "";
155     if (inpspec == stdin_name) { /* read from stdin */
156     fp = stdin;
157 greg 2.2 } else if (inpspec[0] == '!') { /* read from command */
158 greg 2.1 fp = popen(inpspec+1, "r");
159     if (fp == NULL) {
160     fprintf(stderr, "Cannot start process '%s'\n",
161 greg 2.2 inpspec);
162 greg 2.1 return "";
163     }
164     } else { /* else load file */
165     int fd = open(inpspec, O_RDONLY);
166     if (fd < 0) {
167     fprintf(stderr, "%s: cannot open\n", inpspec);
168     return "";
169     }
170 schorsch 2.20 #if !defined(_WIN32) && !defined(_WIN64)
171     /* XXX somehow broken on Windows */
172 greg 2.1 len = lseek(fd, 0L, SEEK_END);
173 greg 2.3 if (len > 0) {
174     lseek(fd, 0L, SEEK_SET);
175     str = (char *)malloc(len+1);
176     if (str == NULL) {
177     close(fd);
178     goto memerr;
179     }
180     if (read(fd, str, len) != len) {
181     fprintf(stderr, "%s: read error\n", inpspec);
182     free(str);
183     close(fd);
184     return "";
185     }
186     str[len] = '\0';
187 greg 2.1 close(fd);
188 greg 2.3 return str;
189 greg 2.1 }
190 greg 2.12 #endif
191 greg 2.3 fp = fdopen(fd, "r"); /* not a regular file */
192 greg 2.1 }
193     /* reading from stream */
194     str = (char *)malloc((len=8192)+1);
195     if (str == NULL)
196     goto memerr;
197     pos = 0;
198     while ((n = read(fileno(fp), str+pos, len-pos)) > 0)
199     if ((pos += n) >= len) { /* need more space? */
200     str = (char *)realloc(str, (len += len>>2) + 1);
201     if (str == NULL)
202     goto memerr;
203     }
204     if (n < 0) {
205     fprintf(stderr, "%s: read error\n", inpspec);
206     free(str);
207     str = "";
208     } else { /* tidy up result */
209     str[pos] = '\0';
210     str = (char *)realloc(str, (len=pos)+1);
211     if (str == NULL)
212     goto memerr;
213     }
214 greg 2.2 if (inpspec[0] != '!')
215 greg 2.1 fclose(fp);
216     else if (pclose(fp))
217 greg 2.2 fprintf(stderr, "Error running command '%s'\n", inpspec);
218 greg 2.1 return str;
219     memerr:
220     fprintf(stderr, "%s: error allocating memory\n", inpspec);
221     if (fp != NULL)
222 greg 2.2 (inpspec[0] == '!') ? pclose(fp) : fclose(fp);
223 greg 2.1 return "";
224     }
225    
226     /* Make material assignments in field_assignment to XML fields */
227     static int
228     mat_assignments(const char *caller, const char *fn, ezxml_t wtl)
229     {
230     int i;
231    
232     wtl = ezxml_child(wtl, "Material");
233     if (wtl == NULL) {
234     fprintf(stderr, "%s: missing <Material> tag\n", fn);
235     return 0;
236     }
237     for (i = 0; i < nfield_assign; i++) {
238     const char *fnext = field_assignment[i];
239     for ( ; ; ) {
240 greg 2.5 int added = 0;
241 greg 2.1 ezxml_t fld;
242     char sbuf[512];
243     int j;
244    
245     while (isspace(*fnext))
246     ++fnext;
247     if (!*fnext)
248     break;
249 greg 2.3 for (j = 0; *fnext != '=' && !isspace(*fnext); ) {
250 greg 2.1 if (!*fnext | (*fnext == FASEP) |
251     (j >= sizeof(sbuf)-1)) {
252     fprintf(stderr,
253     "%s: bad tag name in assignment '%s'\n",
254     caller, field_assignment[i]);
255     return 0;
256     }
257     sbuf[j++] = *fnext++;
258     }
259 greg 2.2 sbuf[j] = '\0'; /* check known field */
260 greg 2.1 for (j = 0; XMLfieldID[j].nickName[0]; j++)
261 greg 2.2 if (!strcasecmp(sbuf, XMLfieldID[j].nickName) ||
262     !strcasecmp(sbuf, XMLfieldID[j].fullName)) {
263 greg 2.1 strcpy(sbuf, XMLfieldID[j].fullName);
264     break;
265     }
266     /* check if tag exists */
267     fld = ezxml_child(wtl, sbuf);
268     if (fld == NULL) { /* otherwise, create one */
269 greg 2.3 if (!XMLfieldID[j].nickName[0])
270     fprintf(stderr,
271     "%s: warning - adding tag <%s>\n",
272     fn, sbuf);
273 greg 2.5 ezxml_add_txt(wtl, "\t");
274 greg 2.1 fld = ezxml_add_child_d(wtl, sbuf, strlen(wtl->txt));
275 greg 2.5 ++added;
276 greg 2.1 }
277     if (XMLfieldID[j].has_unit)
278     ezxml_set_attr(fld, "unit", attr_unit);
279 greg 2.3 XMLfieldID[j].win_need = 0;
280 greg 2.1 while (isspace(*fnext))
281     ++fnext;
282     if (*fnext++ != '=') {
283     fprintf(stderr,
284     "%s: missing '=' in assignment '%s'\n",
285     caller, field_assignment[i]);
286     return 0;
287     }
288 greg 2.3 for (j = 0; *fnext && *fnext != FASEP; ) {
289 greg 2.1 if (j >= sizeof(sbuf)-1) {
290     fprintf(stderr,
291     "%s: field too long in '%s'\n",
292     caller, field_assignment[i]);
293     return 0;
294     }
295     sbuf[j++] = *fnext++;
296     }
297     sbuf[j] = '\0';
298     ezxml_set_txt_d(fld, sbuf);
299 greg 2.5 if (added)
300     ezxml_add_txt(wtl, "\n\t");
301 greg 2.1 fnext += (*fnext == FASEP);
302     }
303     }
304 greg 2.3 /* check required WINDOW settings */
305     if (xml_input == win6_template)
306     for (i = 0; XMLfieldID[i].nickName[0]; i++)
307     if (XMLfieldID[i].win_need &&
308 greg 2.10 !ezxml_txt(ezxml_child(wtl,XMLfieldID[i].fullName))[0])
309 greg 2.3 fprintf(stderr,
310 greg 2.10 "%s: warning - missing '%s' assignment for WINDOW <%s>\n",
311 greg 2.3 caller, XMLfieldID[i].nickName,
312     XMLfieldID[i].fullName);
313 greg 2.10 return 1;
314 greg 2.1 }
315    
316     /* Complete angle basis specification */
317     static int
318     finish_angle_basis(ezxml_t ab)
319     {
320     const char *bn = ezxml_txt(ezxml_child(ab, "AngleBasisName"));
321     int i, n = nabases;
322     char buf[32];
323    
324     if (!*bn) {
325     fputs("Internal error - missing <AngleBasisName>!\n", stderr);
326     return 0;
327     }
328     while (n-- > 0)
329     if (!strcasecmp(bn, abase_list[n].name))
330     break;
331     if (n < 0) {
332     fprintf(stderr, "Internal error - unknown angle basis '%s'", bn);
333     return 0;
334     }
335     for (i = 0; abase_list[n].lat[i].nphis; i++) {
336     ezxml_t tb, abb = ezxml_add_child(ab, "AngleBasisBlock",
337     strlen(ab->txt));
338     sprintf(buf, "%g", i ?
339     .5*(abase_list[n].lat[i].tmin + abase_list[n].lat[i+1].tmin) :
340     .0);
341 greg 2.4 ezxml_add_txt(abb, "\n\t\t\t\t");
342 greg 2.1 ezxml_set_txt_d(ezxml_add_child(abb,"Theta",strlen(abb->txt)), buf);
343     sprintf(buf, "%d", abase_list[n].lat[i].nphis);
344 greg 2.4 ezxml_add_txt(abb, "\n\t\t\t\t");
345 greg 2.1 ezxml_set_txt_d(ezxml_add_child(abb,"nPhis",strlen(abb->txt)), buf);
346 greg 2.4 ezxml_add_txt(abb, "\n\t\t\t\t");
347 greg 2.1 tb = ezxml_add_child(abb, "ThetaBounds", strlen(abb->txt));
348 greg 2.4 ezxml_add_txt(tb, "\n\t\t\t\t\t");
349 greg 2.1 sprintf(buf, "%g", abase_list[n].lat[i].tmin);
350 greg 2.4 ezxml_set_txt_d(ezxml_add_child(tb,"LowerTheta",strlen(tb->txt)), buf);
351     ezxml_add_txt(tb, "\n\t\t\t\t\t");
352 greg 2.1 sprintf(buf, "%g", abase_list[n].lat[i+1].tmin);
353 greg 2.4 ezxml_set_txt_d(ezxml_add_child(tb,"UpperTheta",strlen(tb->txt)), buf);
354     ezxml_add_txt(tb, "\n\t\t\t\t");
355     ezxml_add_txt(abb, "\n\t\t\t");
356     ezxml_add_txt(ab, "\n\t\t\t");
357 greg 2.1 }
358     return 1;
359     }
360    
361     /* Determine our angle basis from current tags */
362     static int
363     determine_angle_basis(const char *fn, ezxml_t wtl)
364     {
365     const char *ids;
366     int i;
367    
368     wtl = ezxml_child(wtl, "DataDefinition");
369     if (wtl == NULL)
370     return -1;
371     ids = ezxml_txt(ezxml_child(wtl, "IncidentDataStructure"));
372 greg 2.4 if (!ids[0])
373 greg 2.1 return -1;
374     for (i = 0; i < ABend; i++) {
375     ezxml_t parsed = ezxml_parse_str(basis_definition[i],
376     strlen(basis_definition[i]));
377     int match = 0;
378     if (!strcmp(ids, ezxml_txt(ezxml_child(parsed,
379     "IncidentDataStructure")))) {
380     const char *abn0 = ezxml_txt(
381     ezxml_child(ezxml_child(wtl,
382     "AngleBasis"), "AngleBasisName"));
383     const char *abn1 = ezxml_txt(
384     ezxml_child(ezxml_child(parsed,
385     "AngleBasis"), "AngleBasisName"));
386     match = !strcmp(abn0, abn1);
387     }
388     ezxml_free(parsed);
389     if (match)
390     return i;
391     }
392     return -1;
393     }
394    
395 greg 2.7 /* Filter Klems angle basis, factoring out incident projected solid angle */
396 greg 2.6 static int
397     filter_klems_matrix(FILE *fp)
398     {
399 greg 2.7 const char *bn = klems_basis_name[angle_basis];
400 greg 2.6 int i, j, n = nabases;
401     /* get angle basis */
402     while (n-- > 0)
403     if (!strcasecmp(bn, abase_list[n].name))
404     break;
405     if (n < 0)
406     return 0;
407     /* read/correct/write matrix */
408     for (i = 0; i < abase_list[n].nangles; i++) {
409 greg 2.21 const double corr = 1./io_getohm(i, &abase_list[n]);
410 greg 2.6 for (j = 0; j < abase_list[n].nangles; j++) {
411     double d;
412     if (fscanf(fp, "%lf", &d) != 1)
413     return 0;
414 greg 2.7 if (d < -1e-3) {
415     fputs("Negative BSDF data!\n", stderr);
416     return 0;
417     }
418 greg 2.21 printf(" %.3e", d*corr*(d > 0));
419 greg 2.6 }
420     fputc('\n', stdout);
421     }
422 greg 2.7 while ((i = getc(fp)) != EOF)
423     if (!isspace(i)) {
424     fputs("Unexpected data past EOF\n", stderr);
425     return 0;
426     }
427     return 1; /* all is good */
428 greg 2.6 }
429    
430 greg 2.1 /* Write out BSDF data block with surrounding tags */
431     static int
432     writeBSDFblock(const char *caller, struct s_dfile *df)
433     {
434 greg 2.7 int correct_klems = correct_solid_angle;
435 greg 2.1 char *cp;
436    
437     puts("\t<WavelengthData>");
438     puts("\t\t<LayerNumber>System</LayerNumber>");
439     switch (df->spectrum) {
440     case DSvisible:
441     puts("\t\t<Wavelength unit=\"Integral\">Visible</Wavelength>");
442 greg 2.7 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
443 greg 2.1 puts("\t\t<DetectorSpectrum>ASTM E308 1931 Y.dsp</DetectorSpectrum>");
444     break;
445     case DSxbar31:
446     puts("\t\t<Wavelength unit=\"Integral\">CIE-X</Wavelength>");
447 greg 2.14 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
448 greg 2.1 puts("\t\t<DetectorSpectrum>ASTM E308 1931 X.dsp</DetectorSpectrum>");
449     break;
450     case DSzbar31:
451     puts("\t\t<Wavelength unit=\"Integral\">CIE-Z</Wavelength>");
452 greg 2.14 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
453 greg 2.1 puts("\t\t<DetectorSpectrum>ASTM E308 1931 Z.dsp</DetectorSpectrum>");
454     break;
455 greg 2.11 case DSuprime:
456 greg 2.13 puts("\t\t<Wavelength unit=\"Integral\">CIE-u</Wavelength>");
457 greg 2.14 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
458 greg 2.11 break;
459     case DSvprime:
460 greg 2.13 puts("\t\t<Wavelength unit=\"Integral\">CIE-v</Wavelength>");
461 greg 2.14 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
462 greg 2.11 break;
463 greg 2.1 case DSsolar:
464     puts("\t\t<Wavelength unit=\"Integral\">Solar</Wavelength>");
465 greg 2.14 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
466 greg 2.1 puts("\t\t<DetectorSpectrum>None</DetectorSpectrum>");
467     break;
468     case DSnir:
469     puts("\t\t<Wavelength unit=\"Integral\">NIR</Wavelength>");
470 greg 2.14 puts("\t\t<SourceSpectrum>PLACE_HOLDER</SourceSpectrum>");
471 greg 2.1 puts("\t\t<DetectorSpectrum>PLACE_HOLDER</DetectorSpectrum>");
472     break;
473     default:
474     cp = strrchr(spectr_file[df->spectrum], '.');
475     if (cp != NULL)
476     *cp = '\0';
477     printf("\t\t<Wavelength unit=\"Integral\">%s</Wavelength>\n",
478     spectr_file[df->spectrum]);
479     if (cp != NULL)
480     *cp = '.';
481 greg 2.14 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
482 greg 2.1 printf("\t\t<DetectorSpectrum>%s</DetectorSpectrum>\n",
483     spectr_file[df->spectrum]);
484     break;
485     }
486     puts("\t\t<WavelengthDataBlock>");
487     fputs("\t\t\t<WavelengthDataDirection>", stdout);
488     switch (df->type) {
489     case DTtransForward:
490     fputs("Transmission Front", stdout);
491     break;
492     case DTtransBackward:
493     fputs("Transmission Back", stdout);
494     break;
495     case DTreflForward:
496     fputs("Reflection Front", stdout);
497     break;
498     case DTreflBackward:
499     fputs("Reflection Back", stdout);
500     break;
501     default:
502     fprintf(stderr, "%s: internal - bad BSDF type (%d)\n", caller, df->type);
503     return 0;
504     }
505     puts("</WavelengthDataDirection>");
506     switch (angle_basis) {
507     case ABklemsFull:
508     case ABklemsHalf:
509     case ABklemsQuarter:
510 greg 2.7 fputs("\t\t\t<ColumnAngleBasis>", stdout);
511     fputs(klems_basis_name[angle_basis], stdout);
512     puts("</ColumnAngleBasis>");
513     fputs("\t\t\t<RowAngleBasis>", stdout);
514     fputs(klems_basis_name[angle_basis], stdout);
515     puts("</RowAngleBasis>");
516 greg 2.1 break;
517     case ABtensorTree3:
518     case ABtensorTree4:
519     puts("\t\t\t<AngleBasis>LBNL/Shirley-Chiu</AngleBasis>");
520 greg 2.7 correct_klems = 0;
521 greg 2.1 break;
522     default:
523     fprintf(stderr, "%s: bad angle basis (%d)\n", caller, angle_basis);
524     return 0;
525     }
526     puts("\t\t\t<ScatteringDataType>BTDF</ScatteringDataType>");
527     puts("\t\t\t<ScatteringData>");
528     fflush(stdout);
529 greg 2.7 if (correct_klems) { /* correct Klems matrix data */
530 greg 2.6 FILE *fp = stdin;
531     if (df->fname[0] == '!')
532     fp = popen(df->fname+1, "r");
533     else if (df->fname != stdin_name)
534     fp = fopen(df->fname, "r");
535     if (fp == NULL) {
536     fprintf(stderr, "%s: cannot open '%s'\n",
537     caller, df->fname);
538     return 0;
539     }
540     if (!filter_klems_matrix(fp)) {
541     fprintf(stderr, "%s: Klems data error from '%s'\n",
542     caller, df->fname);
543     return 0;
544     }
545     if (df->fname[0] != '!') {
546     fclose(fp);
547     } else if (pclose(fp)) {
548     fprintf(stderr, "%s: error running '%s'\n",
549     caller, df->fname);
550     return 0;
551     }
552     } else if (df->fname == stdin_name) {
553 greg 2.1 copy_and_close(fileno(stdin));
554 greg 2.2 } else if (df->fname[0] != '!') {
555 greg 2.1 if (!copy_and_close(open(df->fname, O_RDONLY))) {
556     fprintf(stderr, "%s: error reading from '%s'\n",
557     caller, df->fname);
558     return 0;
559     }
560     } else if (system(df->fname+1)) {
561 greg 2.2 fprintf(stderr, "%s: error running '%s'\n", caller, df->fname);
562 greg 2.1 return 0;
563     }
564     puts("\t\t\t</ScatteringData>");
565     puts("\t\t</WavelengthDataBlock>");
566     puts("\t</WavelengthData>");
567     return 1;
568     }
569    
570     /* Write out XML, interpolating BSDF data block(s) */
571     static int
572     writeBSDF(const char *caller, ezxml_t fl)
573     {
574 greg 2.2 char *xml = ezxml_toxml(fl); /* store XML in string */
575 greg 2.1 int ei, i;
576     /* locate trailer */
577     for (ei = strlen(xml)-strlen("</Layer></Optical></WindowElement>");
578     ei >= 0; ei--)
579     if (!strncmp(xml+ei, "</Layer>", 8))
580     break;
581     if (ei < 0) {
582     fprintf(stderr, "%s: internal - cannot find trailer\n",
583     caller);
584     free(xml);
585     return 0;
586     }
587 greg 2.15 puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
588 greg 2.16 for (i = 0; i < ncomm; i++)
589     printf("<!-- %s -->\n", commlist[i]);
590 greg 2.1 fflush(stdout); /* write previous XML info. */
591     if (write(fileno(stdout), xml, ei) != ei) {
592     free(xml);
593     return 0;
594     }
595     for (i = 0; i < ndataf; i++) /* interpolate new data */
596     if (!writeBSDFblock(caller, &data_file[i])) {
597     free(xml);
598     return 0;
599     }
600     fputs(xml+ei, stdout); /* write trailer */
601 greg 2.2 free(xml); /* free string */
602 greg 2.4 fputc('\n', stdout);
603 greg 2.18 if (fflush(stdout) != 0)
604     return 0;
605     /* unlink data files if req. */
606     for (i = ndataf*(unlink_datafiles != 0); i--; )
607     if (data_file[i].fname != stdin_name &&
608     data_file[i].fname[0] != '!')
609     unlink(data_file[i].fname);
610 greg 2.19 if (unlink_datafiles > 1 && mgf_geometry != NULL &&
611     mgf_geometry != stdin_name &&
612     mgf_geometry[0] != '!')
613     unlink(mgf_geometry);
614 greg 2.18 return 1;
615 greg 2.1 }
616    
617     /* Insert BSDF data into XML wrapper */
618     static int
619     wrapBSDF(const char *caller)
620     {
621 greg 2.2 const char *xml_path = xml_input;
622 greg 2.1 ezxml_t fl, wtl;
623     /* load previous XML/template */
624 greg 2.2 if (xml_input == stdin_name) {
625     fl = ezxml_parse_fp(stdin);
626     } else if (xml_input[0] == '!') {
627     FILE *pfp = popen(xml_input+1, "r");
628     if (pfp == NULL) {
629     fprintf(stderr, "%s: cannot start process '%s'\n",
630     caller, xml_input);
631     return 0;
632     }
633     fl = ezxml_parse_fp(pfp);
634     if (pclose(pfp)) {
635     fprintf(stderr, "%s: error running '%s'\n",
636     caller, xml_input);
637     return 0;
638     }
639     } else {
640     xml_path = getpath((char *)xml_input, getrlibpath(), R_OK);
641     if (xml_path == NULL) {
642     fprintf(stderr, "%s: cannot find XML file named '%s'\n",
643     caller, xml_input==NULL ? "NULL" : xml_input);
644     return 0;
645     }
646     fl = ezxml_parse_file(xml_path);
647 greg 2.1 }
648     if (fl == NULL) {
649 greg 2.2 fprintf(stderr, "%s: cannot load XML '%s'\n", caller, xml_path);
650 greg 2.1 return 0;
651     }
652     if (ezxml_error(fl)[0]) {
653 greg 2.2 fprintf(stderr, "%s: error in XML '%s': %s\n", caller, xml_path,
654 greg 2.1 ezxml_error(fl));
655     goto failure;
656     }
657     if (strcmp(ezxml_name(fl), top_level_name)) {
658     fprintf(stderr, "%s: top level in XML '%s' not '%s'\n",
659     caller, xml_path, top_level_name);
660     goto failure;
661     }
662     wtl = ezxml_child(fl, "FileType");
663     if (wtl != NULL && strcmp(ezxml_txt(wtl), "BSDF")) {
664     fprintf(stderr, "%s: wrong FileType in XML '%s' (must be 'BSDF')",
665     caller, xml_path);
666     goto failure;
667     }
668     wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
669     if (wtl == NULL) {
670     fprintf(stderr, "%s: no optical layers in XML '%s'",
671     caller, xml_path);
672     goto failure;
673     }
674     /* make material assignments */
675 greg 2.3 if (!mat_assignments(caller, xml_path, wtl))
676 greg 2.1 goto failure;
677     if (mgf_geometry != NULL) { /* add geometry if specified */
678     ezxml_t geom = ezxml_child(wtl, "Geometry");
679     if (geom == NULL)
680 greg 2.3 geom = ezxml_add_child(wtl, "Geometry", strlen(wtl->txt));
681 greg 2.1 ezxml_set_attr(geom, "format", "MGF");
682     geom = ezxml_child(geom, "MGFblock");
683     if (geom == NULL) {
684     geom = ezxml_child(wtl, "Geometry");
685 greg 2.3 geom = ezxml_add_child(geom, "MGFblock", 0);
686 greg 2.1 }
687     ezxml_set_attr(geom, "unit", attr_unit);
688     ezxml_set_txt(geom, input2str(mgf_geometry));
689     if (geom->txt[0])
690     ezxml_set_flag(geom, EZXML_TXTM);
691     }
692     /* check basis */
693     if (angle_basis != ABdefault) {
694 greg 2.4 size_t offset = 0;
695 greg 2.1 ezxml_t ab, dd = ezxml_child(wtl, "DataDefinition");
696 greg 2.4 if (dd != NULL) {
697     offset = dd->off;
698 greg 2.5 if (dd->child != NULL)
699     fprintf(stderr,
700 greg 2.1 "%s: warning - replacing existing <DataDefinition> in '%s'\n",
701     caller, xml_path);
702 greg 2.4 ezxml_remove(dd);
703     } else
704     offset = strlen(wtl->txt);
705     dd = ezxml_insert(ezxml_parse_str(basis_definition[angle_basis],
706 greg 2.1 strlen(basis_definition[angle_basis])),
707 greg 2.4 wtl, offset);
708 greg 2.1 if ((ab = ezxml_child(dd, "AngleBasis")) != NULL &&
709     !finish_angle_basis(ab))
710     goto failure;
711     } else if ((angle_basis = determine_angle_basis(xml_path, wtl)) < 0) {
712     fprintf(stderr, "%s: need -a option to set angle basis\n",
713     caller);
714     goto failure;
715     }
716     /* write & add BSDF data blocks */
717     if (!writeBSDF(caller, fl))
718     goto failure;
719     ezxml_free(fl); /* all done */
720     return 1;
721     failure:
722     ezxml_free(fl);
723     return 0;
724     }
725    
726     /* Report usage and exit */
727     static void
728     UsageExit(const char *pname)
729     {
730     fputs("Usage: ", stderr);
731     fputs(pname, stderr);
732 greg 2.11 fputs(" [-W][-c][-a {kf|kh|kq|t3|t4}][-u unit][-g geom][-f 'x=string;y=string']", stderr);
733 greg 2.16 fputs(" [-s spectr][-tb inp][-tf inp][-rb inp][-rf inp][-C comm]", stderr);
734 greg 2.2 fputs(" [input.xml]\n", stderr);
735 greg 2.1 exit(1);
736     }
737    
738     /* Load XML file and use to wrap BSDF data (or modify fields) */
739     int
740     main(int argc, char *argv[])
741     {
742     int cur_spectrum = DSvisible;
743     int ncust_spec = 0;
744     int used_stdin = 0;
745     int units_set = 0;
746     int i;
747     /* get/check arguments */
748     for (i = 1; i < argc && argv[i][0] == '-'; i++) {
749     switch (argv[i][1]) {
750     case 'W': /* customize for WINDOW 6 output */
751     xml_input = win6_template;
752     continue;
753     case 'f': /* field assignment(s) */
754     if (++i >= argc)
755     UsageExit(argv[0]);
756     if (nfield_assign >= MAXASSIGN) {
757     fprintf(stderr, "%s: too many -f options",
758     argv[0]);
759     return 1;
760     }
761     field_assignment[nfield_assign++] = argv[i];
762     continue;
763     case 'u': /* unit */
764     if (++i >= argc)
765     UsageExit(argv[0]);
766     if (units_set++) {
767     fprintf(stderr, "%s: only one -u option allowed\n",
768     argv[0]);
769     return 1;
770     }
771 greg 2.2 if (strstr(legal_units, argv[i]) == NULL) {
772     fprintf(stderr, "%s: -u unit must be one of (%s)\n",
773 greg 2.1 argv[0], legal_units);
774     return 1;
775     }
776     attr_unit = argv[i];
777     continue;
778 greg 2.18 case 'U': /* unlink data files when done */
779 greg 2.19 unlink_datafiles = 1 + (argv[i][2] == 'U');
780 greg 2.18 continue;
781 greg 2.1 case 'a': /* angle basis */
782     if (++i >= argc)
783     UsageExit(argv[0]);
784     if (angle_basis != ABdefault) {
785     fprintf(stderr, "%s: only one -a option allowed\n",
786     argv[0]);
787     return 1;
788     }
789     if (!strcasecmp(argv[i], "kf"))
790     angle_basis = ABklemsFull;
791     else if (!strcasecmp(argv[i], "kh"))
792     angle_basis = ABklemsHalf;
793     else if (!strcasecmp(argv[i], "kq"))
794     angle_basis = ABklemsQuarter;
795     else if (!strcasecmp(argv[i], "t3"))
796     angle_basis = ABtensorTree3;
797     else if (!strcasecmp(argv[i], "t4"))
798     angle_basis = ABtensorTree4;
799     else
800     UsageExit(argv[0]);
801     continue;
802 greg 2.7 case 'c': /* correct solid angle */
803 greg 2.9 correct_solid_angle = 1;
804 greg 2.7 continue;
805 greg 2.16 case 'C': /* comment */
806     if (ncomm >= MAXCOMM) {
807     fprintf(stderr, "%s: too many comments\n",
808     argv[0]);
809     return 1;
810     }
811     if (strchr(argv[++i], '>') != NULL) {
812     fprintf(stderr, "%s: illegal character in comment\n",
813     argv[0]);
814     return 1;
815     }
816     commlist[ncomm++] = argv[i];
817     continue;
818 greg 2.1 case 't': /* transmission */
819     if (i >= argc-1)
820     UsageExit(argv[0]);
821     if (ndataf >= MAXFILES) {
822     fprintf(stderr, "%s: too many data files\n",
823     argv[0]);
824     return 1;
825     }
826     if (!strcmp(argv[i], "-tf"))
827     data_file[ndataf].type = DTtransForward;
828     else if (!strcmp(argv[i], "-tb"))
829     data_file[ndataf].type = DTtransBackward;
830     else
831     UsageExit(argv[0]);
832     if (!strcmp(argv[++i], "-")) {
833     if (used_stdin++) UsageExit(argv[i]);
834     argv[i] = (char *)stdin_name;
835     }
836     data_file[ndataf].fname = argv[i];
837     data_file[ndataf].spectrum = cur_spectrum;
838     ndataf++;
839     continue;
840     case 'r': /* reflection */
841     if (i >= argc-1)
842     UsageExit(argv[0]);
843     if (ndataf >= MAXFILES) {
844     fprintf(stderr, "%s: too many data files\n",
845     argv[0]);
846     return 1;
847     }
848     if (!strcmp(argv[i], "-rf"))
849     data_file[ndataf].type = DTreflForward;
850     else if (!strcmp(argv[i], "-rb"))
851     data_file[ndataf].type = DTreflBackward;
852     else
853     UsageExit(argv[0]);
854     if (!strcmp(argv[++i], "-")) {
855     if (used_stdin++) UsageExit(argv[i]);
856     argv[i] = (char *)stdin_name;
857     }
858     data_file[ndataf].fname = argv[i];
859 greg 2.8 data_file[ndataf].spectrum = cur_spectrum;
860     ndataf++;
861 greg 2.1 continue;
862     case 's': /* spectrum name or input file */
863     if (++i >= argc)
864     UsageExit(argv[0]);
865     if (!strcasecmp(argv[i], "Solar"))
866     cur_spectrum = DSsolar;
867     else if (!strcasecmp(argv[i], "Visible") ||
868     !strcasecmp(argv[i], "CIE-Y"))
869     cur_spectrum = DSvisible;
870     else if (!strcasecmp(argv[i], "CIE-X"))
871     cur_spectrum = DSxbar31;
872     else if (!strcasecmp(argv[i], "CIE-Z"))
873     cur_spectrum = DSzbar31;
874 greg 2.11 else if (!strcasecmp(argv[i], "CIE-u"))
875     cur_spectrum = DSuprime;
876     else if (!strcasecmp(argv[i], "CIE-v"))
877     cur_spectrum = DSvprime;
878 greg 2.1 else if (!strcasecmp(argv[i], "NIR"))
879     cur_spectrum = DSnir;
880     else {
881     if (!strcmp(argv[i], "-")) {
882     fprintf(stderr,
883     "%s: cannot read spectra from stdin",
884     argv[0]);
885     return 1;
886     }
887     cur_spectrum = ncust_spec;
888     spectr_file[ncust_spec++] = argv[i];
889     }
890     continue;
891     case 'g': /* MGF geometry file */
892     if (i >= argc-1)
893     UsageExit(argv[0]);
894     if (mgf_geometry != NULL) {
895     fprintf(stderr, "%s: only one -g option allowed\n",
896     argv[0]);
897     return 1;
898     }
899     if (!strcmp(argv[++i], "-")) {
900     if (used_stdin++) UsageExit(argv[i]);
901     argv[i] = (char *)stdin_name;
902     }
903     mgf_geometry = argv[i];
904     continue;
905     case '\0': /* input XML from stdin */
906     break;
907     default:
908     UsageExit(argv[0]);
909     break;
910     }
911     break;
912     }
913     doneOptions: /* get XML input */
914     if (i >= argc) {
915     if (xml_input == NULL)
916     xml_input = def_template;
917     } else if ((i < argc-1) | (xml_input != NULL)) {
918     fprintf(stderr, "%s: only one XML input allowed\n", argv[0]);
919     UsageExit(argv[0]);
920     } else if (!strcmp(argv[i], "-")) {
921     if (used_stdin++) UsageExit(argv[0]);
922     xml_input = stdin_name;
923     } else {
924     xml_input = argv[i];
925     }
926     /* wrap it! */
927     return !wrapBSDF(argv[0]);
928     }