ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/Development/ray/src/rt/RcontribSimulManager.cpp
Revision: 2.21
Committed: Mon Oct 27 18:38:32 2025 UTC (9 days, 22 hours ago) by greg
Branch: MAIN
CVS Tags: HEAD
Changes since 2.20: +23 -3 lines
Log Message:
fix(rxfluxmtx,rxcontrib): initial truncation of forced output overwrite

File Contents

# Content
1 #ifndef lint
2 static const char RCSid[] = "$Id: RcontribSimulManager.cpp,v 2.20 2025/10/25 18:01:23 greg Exp $";
3 #endif
4 /*
5 * RcontribSimulManager.cpp
6 *
7 * Rcontrib simulation manager implementation
8 *
9 * Created by Greg Ward on 10/17/2024.
10 */
11
12 #include <unistd.h>
13 #include <ctype.h>
14 #include "platform.h"
15 #include "selcall.h"
16 #include "RcontribSimulManager.h"
17 #include "func.h"
18 #include "resolu.h"
19 #include "source.h"
20
21 char RCCONTEXT[] = "RC.";
22
23 extern const char HDRSTR[];
24 extern const char BIGEND[];
25 extern const char FMTSTR[];
26
27 // new/exclusive, overwrite if exists, or recover data
28 int RSDOflags[] = {RDSwrite|RDSexcl|RDSextend, RDSwrite|RDSextend,
29 RDSread|RDSwrite};
30
31 static const char ROWZEROSTR[] = "NROWS=0000000000000000\n";
32 #define LNROWSTR 6
33
34 // Modifier channel for recording contributions (no constructor/destructor)
35 struct RcontribMod {
36 RcontribOutput * opl; // pointer to first output channel
37 char * params; // parameters string
38 EPNODE * binv; // bin expression (NULL if 1 bin)
39 int nbins; // bin count this modifier
40 int coffset; // column offset in bytes
41 DCOLORV cbin[1]; // bin accumulator (extends struct)
42 /// Access specific (spectral) color bin
43 DCOLORV * operator[](int n) {
44 if ((n < 0) | (n >= nbins)) return NULL;
45 return cbin + n*NCSAMP;
46 }
47 };
48
49 // Struct used to assign record calculation to child
50 struct RowAssignment {
51 uint32 row; // row to do
52 uint32 ac; // accumulation count
53 };
54
55 static const char ROW_DONE[] = "ROW FINISHED\n";
56
57 // allocate rcontrib accumulator
58 static RcontribMod *
59 NewRcMod(const char *prms, const char *binexpr, int ncbins)
60 {
61 if (binexpr && !*binexpr) binexpr = NULL;
62 if (!prms) prms = "";
63 if ((ncbins > 1) & !binexpr) {
64 error(USER, "missing bin expression");
65 return NULL;
66 }
67 if (ncbins < 1) ncbins = 1;
68
69 RcontribMod * mp = (RcontribMod *)ecalloc(1, sizeof(RcontribMod) +
70 sizeof(DCOLORV)*(NCSAMP*ncbins-1) +
71 strlen(prms)+1);
72
73 if (binexpr) { // get/check bin expression
74 mp->binv = eparse(const_cast<char *>(binexpr));
75 if (mp->binv->type == NUM) { // constant expression (0)?
76 if ((int)evalue(mp->binv) != 0) {
77 sprintf(errmsg, "illegal non-zero constant for bin (%s)",
78 binexpr);
79 error(USER, errmsg);
80 }
81 if (ncbins > 1) {
82 sprintf(errmsg, "bad bin count (%d should be 1)", ncbins);
83 error(USER, errmsg);
84 }
85 epfree(mp->binv, true);
86 mp->binv = NULL;
87 prms = "";
88 ncbins = 1;
89 }
90 }
91 mp->params = strcpy((char *)(mp->cbin + ncbins*NCSAMP), prms);
92 mp->nbins = ncbins;
93 return mp;
94 }
95
96 // Free an RcontribMod (public for RcontribSimulManager constructor)
97 void
98 FreeRcMod(void *p)
99 {
100 if (!p) return;
101 EPNODE * bep = (*(RcontribMod *)p).binv;
102 if (bep) epfree(bep, true);
103 efree(p);
104 }
105
106 // Get format identifier
107 const char *
108 formstr(int f)
109 {
110 switch (f) {
111 case 'a': return("ascii");
112 case 'f': return("float");
113 case 'd': return("double");
114 case 'c': return(NCSAMP==3 ? COLRFMT : SPECFMT);
115 }
116 return("unknown");
117 }
118
119 // Standard file data share function
120 RdataShare *
121 fileDataShare(const char *name, RCOutputOp op, size_t siz)
122 {
123 if (op == RCOrecover && access(name, R_OK|W_OK) < 0) {
124 sprintf(errmsg, "cannot recover from '%s'", name);
125 error(SYSTEM, errmsg);
126 return NULL;
127 }
128 RdataShare * rds = new RdataShareFile(name, RSDOflags[op],
129 siz*(op != RCOforce));
130
131 if (!rds || (op == RCOforce && rds->Resize(siz) < siz)) {
132 delete rds;
133 sprintf(errmsg, "cannot create %lu byte output file '%s'",
134 (unsigned long)siz, name);
135 error(SYSTEM, errmsg);
136 return NULL;
137 }
138 return rds;
139 }
140
141 // Memory-mapped data share function
142 RdataShare *
143 mapDataShare(const char *name, RCOutputOp op, size_t siz)
144 {
145 if (op == RCOrecover && access(name, R_OK|W_OK) < 0) {
146 sprintf(errmsg, "cannot recover from '%s'", name);
147 error(SYSTEM, errmsg);
148 return NULL;
149 }
150 RdataShare * rds = new RdataShareMap(name, RSDOflags[op],
151 siz*(op != RCOforce));
152
153 if (!rds || (op == RCOforce && rds->Resize(siz) < siz)) {
154 delete rds;
155 sprintf(errmsg, "cannot create %lu byte output map '%s'",
156 (unsigned long)siz, name);
157 error(SYSTEM, errmsg);
158 return NULL;
159 }
160 return rds;
161 }
162
163 // Set output format ('f', 'd', or 'c')
164 bool
165 RcontribSimulManager::SetDataFormat(int ty)
166 {
167 if (outList) {
168 error(INTERNAL, "cannot call SetDataFormat() after AddModifier()");
169 return false;
170 }
171 switch (ty) {
172 case 'f':
173 dsiz = sizeof(float)*NCSAMP;
174 break;
175 case 'd':
176 dsiz = sizeof(double)*NCSAMP;
177 break;
178 case 'c':
179 dsiz = LSCOLR;
180 break;
181 default:
182 sprintf(errmsg, "unsupported output format '%c'", ty);
183 error(INTERNAL, errmsg);
184 return false;
185 }
186 dtyp = ty;
187 return true;
188 }
189
190 // static call-back for rcontrib ray-tracing
191 int
192 RcontribSimulManager::RctCall(RAY *r, void *cd)
193 {
194 if (!r->ro || r->ro->omod == OVOID) // hit nothing?
195 return 0;
196 // shadow ray not on source?
197 if (r->rsrc >= 0 && source[r->rsrc].so != r->ro)
198 return 0;
199
200 const char * mname = objptr(r->ro->omod)->oname;
201 RcontribSimulManager * rcp = (RcontribSimulManager *)cd;
202 RcontribMod * mp = (RcontribMod *)lu_find(&rcp->modLUT,mname)->data;
203 if (!mp)
204 return 0; // not in our modifier list
205
206 int bi = 0; // get bin index
207 if (mp->binv) {
208 worldfunc(RCCONTEXT, r);
209 set_eparams(mp->params);
210 double bval = evalue(mp->binv);
211 if (bval <= -.5)
212 return 0; // silently ignore negative bin index
213 bi = int(bval + .5);
214 }
215 DCOLORV * dvp = (*mp)[bi];
216 if (!dvp) {
217 sprintf(errmsg, "bad bin number for '%s' (%d ignored)", mname, bi);
218 error(WARNING, errmsg);
219 return 0;
220 }
221 SCOLOR contr;
222 raycontrib(contr, r, PRIMARY); // compute coefficient
223 if (rcp->HasFlag(RCcontrib))
224 smultscolor(contr, r->rcol); // -> value contribution
225
226 for (int i = 0; i < NCSAMP; i++)
227 *dvp++ += contr[i]; // accumulate color/spectrum
228 return 1;
229 }
230
231 // check for given format type in string, return last char position
232 static int
233 hasFormat(const char *tst, const char *match)
234 {
235 static const char allPoss[] = "%diouxXfFeEgGaAcsb";
236 const char * s = tst;
237 while (*s) {
238 if (*s++ != '%')
239 continue;
240 while (!strchr(allPoss, *s))
241 s++;
242 if (strchr(match, *s))
243 break;
244 s++;
245 }
246 return (*s != '\0')*(s - tst);
247 }
248
249 // Add a modifier and arguments, opening output file(s)
250 bool
251 RcontribSimulManager::AddModifier(const char *modn, const char *outspec,
252 const char *prms, const char *binval, int bincnt)
253 {
254 if (!modn | !outspec || !*modn | !*outspec) {
255 error(WARNING, "ignoring bad call to AddModifier()");
256 return false;
257 }
258 if (*outspec == '!') {
259 error(USER, "command output not supported by RcontribSimulManager");
260 return false;
261 }
262 if (!nChan) { // initial call?
263 if ((xres < 0) | (yres <= 0)) {
264 error(USER, "xres, yres must be set before first modifier");
265 return false;
266 }
267 if (!SetDataFormat(dtyp))
268 return false;
269 nChan = NCSAMP;
270 } else if (nChan != NCSAMP) {
271 error(USER, "# spectral channels must be fixed in AddModifier()");
272 return false;
273 }
274 if (Ready()) {
275 error(INTERNAL, "call to AddModifier() after PrepOutput()");
276 return false;
277 }
278 LUENT * lp = lu_find(&modLUT, modn);
279 if (lp->data) {
280 sprintf(errmsg, "duplicate modifier '%s'", modn);
281 error(USER, errmsg);
282 return false;
283 }
284 if (!lp->key) // create new entry
285 lp->key = strcpy((char *)emalloc(strlen(modn)+1), modn);
286
287 RcontribMod * mp = NewRcMod(prms, binval, bincnt);
288 if (!mp) return false;
289 lp->data = (char *)mp;
290 const int modndx = hasFormat(outspec, "sb");
291 const int binndx = hasFormat(outspec, "diouxX");
292 int bin0 = 0;
293 char fnbuf[512];
294 if (!modndx || (binndx > 0) & (modndx > binndx))
295 sprintf(fnbuf, outspec, bin0, modn);
296 else
297 sprintf(fnbuf, outspec, modn, bin0);
298 RcontribOutput * olast = NULL;
299 RcontribOutput * op;
300 for (op = outList; op; op = (olast=op)->next) {
301 if (strcmp(op->GetName(), fnbuf))
302 continue;
303 if (modndx) { // this ain't right
304 sprintf(errmsg, "output name collision for '%s'", fnbuf);
305 error(USER, errmsg);
306 return false;
307 }
308 if ((binndx > 0) & (xres > 0)) {
309 sprintf(fnbuf, outspec, ++bin0);
310 continue; // each bin goes to another image
311 }
312 mp->coffset = op->rowBytes; // else add to what's there
313 break;
314 }
315 if (!op) { // create new output channel?
316 op = new RcontribOutput(fnbuf);
317 if (olast) olast->next = op;
318 else outList = op;
319 }
320 mp->opl = op; // first (maybe only) output channel
321 if (modndx) // remember modifier if part of name
322 op->omod = lp->key;
323 if (binndx) { // append output image/bin list
324 op->rowBytes += dsiz;
325 op->obin = bin0;
326 for (bincnt = 1; bincnt < mp->nbins; bincnt++) {
327 if (!modndx || (binndx > 0) & (modndx > binndx))
328 sprintf(fnbuf, outspec, bin0+bincnt, modn);
329 else
330 sprintf(fnbuf, outspec, modn, bin0+bincnt);
331 if (!op->next) {
332 olast = op;
333 olast->next = op = new RcontribOutput(fnbuf);
334 if (modndx) op->omod = lp->key;
335 op->obin = bin0+bincnt;
336 } else {
337 op = op->next;
338 CHECK(op->obin != bin0+bincnt, CONSISTENCY,
339 "bin number mismatch in AddModifier()");
340 }
341 CHECK(op->rowBytes != mp->coffset, CONSISTENCY,
342 "row offset mismatch in AddModifier()");
343 op->rowBytes += dsiz;
344 }
345 } else // else send all results to this channel
346 op->rowBytes += mp->nbins*dsiz;
347 return true;
348 }
349
350 // Add a file of modifiers with associated arguments
351 bool
352 RcontribSimulManager::AddModFile(const char *modfn, const char *outspec,
353 const char *prms,
354 const char *binval, int bincnt)
355 {
356 char * path = getpath(const_cast<char *>(modfn),
357 getrlibpath(), R_OK);
358 FILE * fp;
359 if (!path || !(fp = fopen(path, "r"))) {
360 sprintf(errmsg, "cannot %s modifier file '%s'",
361 path ? "open" : "find", modfn);
362 error(SYSTEM, errmsg);
363 return false;
364 }
365 char mod[MAXSTR];
366 while (fgetword(mod, sizeof(mod), fp))
367 if (!AddModifier(mod, outspec, prms, binval, bincnt)) {
368 fclose(fp);
369 return false;
370 }
371 fclose(fp);
372 return true;
373 }
374
375 // call-back to check if modifier has been loaded
376 static int
377 checkModExists(const LUENT *lp, void *p)
378 {
379 OBJECT mod = modifier(lp->key);
380
381 if ((mod != OVOID) & (mod < nsceneobjs))
382 return 1;
383
384 sprintf(errmsg, "tracked modifier '%s' not found in main scene", lp->key);
385 error(WARNING, errmsg);
386 return 0;
387 }
388
389 // Prepare output channels and return # completed rows
390 int
391 RcontribSimulManager::PrepOutput()
392 {
393 if (!outList || !RtraceSimulManager::Ready()) {
394 error(INTERNAL, "PrepOutput() called before octree & modifiers set");
395 return -1;
396 }
397 if (!cdsF) {
398 error(INTERNAL, "missing RdataShare constructor call (cdsF)");
399 return -1;
400 }
401 if (lu_doall(&modLUT, checkModExists, NULL) < 0)
402 return -1;
403
404 outList->nRows = yres * (xres + !xres); // all outputs have same #rows
405 int remWarnings = 20;
406 for (RcontribOutput *op = outList; op; op = op->next) {
407 if (op->rData) {
408 error(INTERNAL, "output channel already open in PrepOutput()");
409 return -1;
410 }
411 op->nRows = outList->nRows;
412 op->rData = (*cdsF)(op->ofname, outOp,
413 GetHeadLen()+1024 + op->nRows*op->rowBytes);
414 freeqstr(op->ofname); op->ofname = NULL;
415 if (outOp == RCOrecover) {
416 int rd = op->CheckHeader(this);
417 if (rd < 0)
418 return -1;
419 if (rd >= op->nRows) {
420 if (remWarnings > 0) {
421 sprintf(errmsg, "recovered output '%s' is complete",
422 op->GetName());
423 error(WARNING, --remWarnings ? errmsg : "etc...");
424 }
425 rd = op->nRows;
426 }
427 if (!rInPos | (rInPos > rd)) rInPos = rd;
428 } else if (!op->NewHeader(this))
429 return -1;
430 // make sure there's room
431 if (op->rData->GetSize() < op->begData + op->nRows*op->rowBytes &&
432 !op->rData->Resize(op->begData + op->nRows*op->rowBytes))
433 return -1; // calls error() for us
434 }
435 rowsDone.NewBitMap(outList->nRows); // create row completion map
436 rowsDone.ClearBits(0, rInPos, true);
437 return nrDone = rInPos;
438 }
439
440 // Create header in open write-only channel
441 bool
442 RcontribOutput::NewHeader(const RcontribSimulManager *rcp)
443 {
444 int headlim = rcp->GetHeadLen() + 1024;
445 char * hdr = (char *)rData->GetMemory(0, headlim, 0);
446 int esiz;
447 const int etyp = rcp->GetFormat(&esiz);
448
449 strcpy(hdr, HDRSTR);
450 strcat(hdr, "RADIANCE\n");
451 begData = strlen(hdr);
452 strcpy(hdr+begData, rcp->GetHeadStr());
453 begData += rcp->GetHeadLen();
454 if (omod) {
455 sprintf(hdr+begData, "MODIFIER=%s\n", omod);
456 begData += strlen(hdr+begData);
457 }
458 if (obin >= 0) {
459 sprintf(hdr+begData, "BIN=%d\n", obin);
460 begData += strlen(hdr+begData);
461 }
462 strcpy(hdr+begData, ROWZEROSTR);
463 rowCountPos = begData+LNROWSTR;
464 begData += sizeof(ROWZEROSTR)-1;
465 if (!rcp->xres | (rowBytes > esiz)) {
466 sprintf(hdr+begData, "NCOLS=%d\n", int(rowBytes/esiz));
467 begData += strlen(hdr+begData);
468 }
469 sprintf(hdr+begData, "%s%d\n", NCOMPSTR, NCSAMP);
470 begData += strlen(hdr+begData);
471 if (NCSAMP > 3) {
472 sprintf(hdr+begData, "%s %g %g %g %g\n", WLSPLTSTR,
473 WLPART[0], WLPART[1], WLPART[2], WLPART[3]);
474 begData += strlen(hdr+begData);
475 }
476 if (etyp != 'c') {
477 sprintf(hdr+begData, "%s%d\n", BIGEND, nativebigendian());
478 begData += strlen(hdr+begData);
479 }
480 int align = 0;
481 switch (etyp) {
482 case 'f':
483 align = sizeof(float);
484 break;
485 case 'd':
486 align = sizeof(double);
487 break;
488 case 'c':
489 break;
490 default:
491 error(INTERNAL, "unsupported data type in NewHeader()");
492 return false;
493 }
494 strcpy(hdr+begData, FMTSTR); // write format string
495 begData += strlen(hdr+begData);
496 strcpy(hdr+begData, formstr(etyp));
497 begData += strlen(hdr+begData);
498 if (align) // align data at end of header
499 while ((begData+2) % align)
500 hdr[begData++] = ' ';
501 hdr[begData++] = '\n'; // EOL for data format
502 hdr[begData++] = '\n'; // end of nominal header
503 if ((rcp->xres > 0) & (rowBytes == esiz)) { // tack on resolution string?
504 sprintf(hdr+begData, PIXSTDFMT, rcp->yres, rcp->xres);
505 begData += strlen(hdr+begData);
506 }
507 return rData->ReleaseMemory(hdr, RDSwrite);
508 }
509
510 // find string argument in header for named variable
511 static const char *
512 findArgs(const char *hdr, const char *vnm, int len)
513 {
514 const char * npos = strnstr(hdr, vnm, len);
515
516 if (!npos) return NULL;
517
518 npos += strlen(vnm); // find start of (first) argument
519 len -= npos - hdr;
520 while (len-- > 0 && (*npos == '=') | isspace(*npos))
521 if (*npos++ == '\n')
522 return NULL;
523
524 return (len >= 0) ? npos : NULL;
525 }
526
527 // Load and check header in read/write channel
528 int
529 RcontribOutput::CheckHeader(const RcontribSimulManager *rcp)
530 {
531 int esiz;
532 const int etyp = rcp->GetFormat(&esiz);
533 const int maxlen = rcp->GetHeadLen() + 1024;
534 char * hdr = (char *)rData->GetMemory(0, maxlen, RDSread);
535 const char * cp;
536 // find end of header
537 if (!hdr || !(cp = strnstr(hdr, "\n\n", maxlen))) {
538 sprintf(errmsg, "cannot find end of header in '%s'", GetName());
539 error(USER, errmsg);
540 return -1;
541 }
542 begData = cp - hdr + 1; // increment again at end
543 // check # components
544 if (((cp = findArgs(hdr, NCOMPSTR, begData)) ? atoi(cp) : 3) != NCSAMP) {
545 sprintf(errmsg, "expected %s%d in '%s'", NCOMPSTR, NCSAMP, GetName());
546 error(USER, errmsg);
547 return -1;
548 }
549 // check format
550 if (!(cp = findArgs(hdr, FMTSTR, begData)) ||
551 strncmp(cp, formstr(etyp), strlen(formstr(etyp)))) {
552 sprintf(errmsg, "expected %s%s in '%s'", FMTSTR, formstr(etyp), GetName());
553 error(USER, errmsg);
554 return -1;
555 }
556 // check #columns
557 if ((cp = findArgs(hdr, "NCOLS=", begData)) ? (atoi(cp)*esiz != rowBytes)
558 : (!rcp->xres | (rowBytes > esiz))) {
559 sprintf(errmsg, "expected NCOLS=%d in '%s'", int(rowBytes/esiz), GetName());
560 error(USER, errmsg);
561 return -1;
562 }
563 // find row count
564 if (!(cp = findArgs(hdr, "NROWS=", begData))) {
565 sprintf(errmsg, "missing NROWS in '%s'", GetName());
566 error(USER, errmsg);
567 return -1;
568 }
569 rowCountPos = cp - hdr;
570 int rlast = atoi(cp);
571 begData++; // advance past closing EOL
572 if ((rcp->xres > 0) & (rowBytes == esiz)) { // check/skip resolution string?
573 char rbuf[64];
574 sprintf(rbuf, PIXSTDFMT, rcp->yres, rcp->xres);
575 int rlen = strlen(rbuf);
576 if (strncmp(rbuf, hdr+begData, rlen)) {
577 sprintf(errmsg, "bad resolution string in '%s'", GetName());
578 error(USER, errmsg);
579 return -1;
580 }
581 begData += rlen;
582 }
583 // XXX assume the rest is OK: endianness, wavelength splits, modifier, bin
584 return rData->ReleaseMemory(hdr, 0) ? rlast : -1;
585 }
586
587 // Rewind calculation (previous results unchanged)
588 bool
589 RcontribSimulManager::ResetRow(int r)
590 {
591 if (!rowsDone.Length() | (0 > r) | (r >= rInPos)) {
592 error(WARNING, "ignoring bad call to ResetRow()");
593 return (r == rInPos);
594 }
595 FlushQueue(); // finish current and reset
596 for (RcontribOutput *op = outList; op; op = op->next)
597 if (!op->SetRowsDone(r))
598 return false;
599
600 rowsDone.ClearBits(r, rInPos-r, false);
601 nrDone = rInPos = r;
602 return true;
603 }
604
605 // call-back for averaging each modifier's contributions to assigned channel(s)
606 static int
607 putModContrib(const LUENT *lp, void *p)
608 {
609 RcontribMod * mp = (RcontribMod *)lp->data;
610 const RcontribSimulManager * rcp = (const RcontribSimulManager *)p;
611 const double sca = 1./rcp->accum;
612 const DCOLORV * dvp = mp->cbin;
613 RcontribOutput * op = mp->opl;
614 int i, n;
615
616 switch (rcp->GetFormat()) { // conversion based on output type
617 case 'd': {
618 double * dvo = (double *)op->InsertionP(mp->coffset);
619 for (n = mp->nbins; n--; ) {
620 for (i = 0; i < NCSAMP; i++)
621 *dvo++ = *dvp++ * sca;
622 if ((op->obin >= 0) & (n > 0))
623 dvo = (double *)(op = op->Next())->InsertionP(mp->coffset);
624 }
625 } break;
626 case 'f': {
627 float * fvo = (float *)op->InsertionP(mp->coffset);
628 for (n = mp->nbins; n--; ) {
629 for (i = 0; i < NCSAMP; i++)
630 *fvo++ = float(*dvp++ * sca);
631 if ((op->obin >= 0) & (n > 0))
632 fvo = (float *)(op = op->Next())->InsertionP(mp->coffset);
633 }
634 } break;
635 case 'c': {
636 COLRV * cvo = (COLRV *)op->InsertionP(mp->coffset);
637 for (n = mp->nbins; n--; ) {
638 SCOLOR scol;
639 for (i = 0; i < NCSAMP; i++)
640 scol[i] = COLORV(*dvp++ * sca);
641 scolor_scolr(cvo, scol);
642 cvo += LSCOLR;
643 if ((op->obin >= 0) & (n > 0))
644 cvo = (COLRV *)(op = op->Next())->InsertionP(mp->coffset);
645 }
646 } break;
647 default:
648 error(CONSISTENCY, "unsupported output type in putModContrib()");
649 return -1;
650 }
651 // clear for next tally
652 memset(mp->cbin, 0, sizeof(DCOLORV)*NCSAMP*mp->nbins);
653 return 1;
654 }
655
656 // Add a ray/bundle to compute next record
657 int
658 RcontribSimulManager::ComputeRecord(const FVECT orig_direc[])
659 {
660 if (!Ready())
661 return 0;
662 if (rInPos >= outList->nRows) {
663 error(WARNING, "ComputeRecord() called after last record");
664 return 0;
665 }
666 if (nkids > 0) { // in parent process?
667 int k = GetChild(false); // updates output rows
668 if (k < 0) return -1; // someone died?
669 RowAssignment rass;
670 rass.row = kidRow[k] = rInPos++;
671 rass.ac = accum;
672 if (write(kid[k].w, &rass, sizeof(rass)) != sizeof(rass) ||
673 writebuf(kid[k].w, orig_direc, sizeof(FVECT)*2*accum)
674 != sizeof(FVECT)*2*accum) {
675 error(SYSTEM, "cannot write to child; dead process?");
676 return -1;
677 }
678 return accum; // tracing/output happens in child
679 }
680 if (NCSAMP != nChan) {
681 error(INTERNAL, "number of color channels must remain fixed");
682 return -1;
683 }
684 // actual work is done here...
685 if (EnqueueBundle(orig_direc, accum) < 0)
686 return -1;
687
688 RcontribOutput * op; // prepare output buffers
689 for (op = outList; op; op = op->next)
690 if (!op->GetRow(rInPos))
691 return -1;
692 // convert averages & clear
693 if (lu_doall(&modLUT, putModContrib, this) < 0)
694 return -1;
695 // write buffers
696 for (op = outList; op; op = op->next)
697 op->DoneRow();
698
699 if (!nkids) // update row if solo process
700 UpdateRowsDone(rInPos++); // XXX increment here is critical
701
702 return accum;
703 }
704
705 // Get next available child, returning index or -1 if forceWait & idling
706 int
707 RcontribSimulManager::GetChild(bool forceWait)
708 {
709 if (nkids <= 0)
710 return -1;
711 // take inventory
712 int pn, n = 0;
713 fd_set readset, errset;
714 FD_ZERO(&readset); FD_ZERO(&errset);
715 for (pn = nkids; pn--; ) {
716 if (kidRow[pn] < 0) { // child already ready?
717 if (forceWait) continue;
718 return pn; // good enough
719 }
720 FD_SET(kid[pn].r, &readset); // will check on this one
721 FD_SET(kid[pn].r, &errset);
722 if (kid[pn].r >= n)
723 n = kid[pn].r + 1;
724 }
725 if (!n) // every child is idle?
726 return -1;
727 // wait on "busy" child(ren)
728 while ((n = select(n, &readset, NULL, &errset, NULL)) <= 0)
729 if (errno != EINTR) {
730 error(SYSTEM, "select call failed in GetChild()");
731 return -1;
732 }
733 char buf[sizeof(ROW_DONE)] = "X";
734 pn = -1; // get flags set by select
735 for (n = nkids; n--; )
736 if (kidRow[n] >= 0 &&
737 FD_ISSET(kid[n].r, &readset) |
738 FD_ISSET(kid[n].r, &errset)) {
739 // check for error
740 if (FD_ISSET(kid[n].r, &errset) ||
741 read(kid[n].r, buf, sizeof(ROW_DONE)) <= 0 ||
742 memcmp(buf, ROW_DONE, sizeof(ROW_DONE)))
743 return -1;
744 // update output row counts
745 UpdateRowsDone(kidRow[n]);
746 kidRow[n] = -1; // flag child available
747 pn = n;
748 }
749 return pn;
750 }
751
752 // Update row completion bitmap and update outputs (does not change rInPos)
753 bool
754 RcontribSimulManager::UpdateRowsDone(int r)
755 {
756 if (!rowsDone.TestAndSet(r)) {
757 error(WARNING, "redundant call to UpdateRowsDone()");
758 return false;
759 }
760 GetRowFinished();
761 if (nrDone <= r)
762 return true; // nothing to update, yet
763 for (RcontribOutput *op = outList; op; op = op->next)
764 if (!op->SetRowsDone(nrDone))
765 return false;
766 return true; // up-to-date
767 }
768
769 // Run rcontrib child process (never returns)
770 void
771 RcontribSimulManager::RunChild()
772 {
773 FVECT * vecList = NULL;
774 RowAssignment rass;
775 ssize_t nr;
776
777 accum = 0;
778 errno = 0;
779 while ((nr = read(0, &rass, sizeof(rass))) == sizeof(rass)) {
780 if (!rass.ac) {
781 error(CONSISTENCY, "bad accumulator count in child");
782 exit(1);
783 }
784 if (rass.ac > accum) {
785 efree(vecList);
786 vecList = (FVECT *)emalloc(sizeof(FVECT)*2*rass.ac);
787 }
788 accum = rass.ac;
789 rInPos = rass.row;
790
791 if (readbuf(0, vecList, sizeof(FVECT)*2*accum) !=
792 sizeof(FVECT)*2*accum)
793 break;
794
795 if (ComputeRecord(vecList) <= 0)
796 exit(1);
797 // signal this row is done
798 if (write(1, ROW_DONE, sizeof(ROW_DONE)) != sizeof(ROW_DONE))
799 exit(1);
800 }
801 if (nr) {
802 error(SYSTEM, "read error in child process");
803 exit(1);
804 }
805 exit(0);
806 }
807
808 // Add child processes as indicated
809 bool
810 RcontribSimulManager::StartKids(int n2go)
811 {
812 if ((n2go <= 0) | (nkids + n2go <= 1))
813 return false;
814
815 if (!nkids)
816 cow_memshare(); // preload objects
817
818 n2go += nkids; // => desired brood size
819 kid = (SUBPROC *)erealloc(kid, sizeof(SUBPROC)*n2go);
820 kidRow = (int32 *)erealloc(kidRow, sizeof(int32)*n2go);
821
822 fflush(stdout); // shouldn't use, anyway
823 while (nkids < n2go) {
824 kid[nkids] = sp_inactive;
825 int rv = open_process(&kid[nkids], NULL);
826 if (!rv) { // in child process?
827 while (nkids-- > 0) {
828 close(kid[nkids].r);
829 close(kid[nkids].w);
830 }
831 free(kid); free(kidRow);
832 kid = NULL; kidRow = NULL;
833 RunChild(); // should never return
834 _exit(1);
835 }
836 if (rv < 0) {
837 error(SYSTEM, "cannot fork worker process");
838 return false;
839 }
840 kidRow[nkids++] = -1; // newborn is ready
841 }
842 return true;
843 }
844
845 // Reap the indicated number of children (all if 0)
846 int
847 RcontribSimulManager::StopKids(int n2end)
848 {
849 if (nkids <= 0)
850 return 0;
851 FlushQueue();
852 int status = 0;
853 if (!n2end | (n2end >= nkids)) { // end all subprocesses?
854 status = close_processes(kid, nkids);
855 free(kid); free(kidRow);
856 kid = NULL; kidRow = NULL;
857 nkids = 0;
858 } else { // else shrink family
859 int st;
860 while (n2end-- > 0)
861 if ((st = close_process(&kid[--nkids])) > 0)
862 status = st;
863 // could call realloc(), but it hardly matters
864 }
865 if (status) {
866 sprintf(errmsg, "non-zero (%d) status from child", status);
867 error(WARNING, errmsg);
868 }
869 return status;
870 }
871
872 // Set number of computation threads (0 => #cores)
873 int
874 RcontribSimulManager::SetThreadCount(int nt)
875 {
876 if (!Ready()) {
877 error(INTERNAL, "must call PrepOutput() before SetThreadCount()");
878 return 0;
879 }
880 if (nt < 0)
881 return NThreads();
882 if (!nt) nt = GetNCores();
883 int status = 0;
884 if (nt == 1)
885 status = StopKids();
886 else if (nt < nkids)
887 status = StopKids(nkids-nt);
888 else if (nt > nkids)
889 StartKids(nt-nkids);
890 if (status) {
891 sprintf(errmsg, "non-zero (%d) status from child", status);
892 error(WARNING, errmsg);
893 }
894 return NThreads();
895 }