ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/wrapBSDF.c
Revision: 2.23
Committed: Wed Apr 3 23:50:25 2019 UTC (5 years ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.22: +19 -2 lines
Log Message:
Added check for duplicate component input

File Contents

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