hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
d8b6230ada2548e7ee9b40845adf66f3bfb67f07
13,557
c
C
src/camera/camera_utils/camera_utils.c
rymdllama/IRISC-OBSW
a29ac2dd1ee71c9f90f2f715c4131513fc34c354
[ "MIT" ]
1
2019-10-20T10:44:41.000Z
2019-10-20T10:44:41.000Z
src/camera/camera_utils/camera_utils.c
rymdllama/IRISC-OBSW
a29ac2dd1ee71c9f90f2f715c4131513fc34c354
[ "MIT" ]
1
2019-04-22T12:10:45.000Z
2019-04-22T12:10:45.000Z
src/camera/camera_utils/camera_utils.c
rymdllama/IRISC-OBSW
a29ac2dd1ee71c9f90f2f715c4131513fc34c354
[ "MIT" ]
2
2019-09-04T10:37:19.000Z
2019-10-17T20:39:10.000Z
/* ----------------------------------------------------------------------------- * Component Name: Camera Utils * Parent Component: Camera * Author(s): Harald Magnusson * Purpose: Provide utilies for the use of ZWO ASI cameras. * * ----------------------------------------------------------------------------- */ #define _GNU_SOURCE #include <time.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <fitsio.h> #include <errno.h> #include <math.h> #include "global_utils.h" #include "camera_utils.h" static struct timespec start_time[2]; static char exp_start_datetime[2][20]; static int timeref[2]; static int write_img(unsigned short* buffer, ASI_CAMERA_INFO* cam_info, char* fn, struct timespec* exp_time); static void yflip(unsigned short* buffer, int width, int height); /* cam_setup: * Set up and initialize a given ZWO ASI camera. * * input: * cam_name specifies which camera to initialize: * 'n' for nir camera * 'g' for guiding camera * * output: * cam_info: info object for relevant camera * cam_name: name of camera for logging * * return: * SUCCESS: operation is successful * FAILURE: failure to set up camera, log written to stderr * ENODEV: incorrect camera name or camera disconnected */ int cam_setup(ASI_CAMERA_INFO* cam_info, char cam_name){ int ret, height, width; switch(cam_name){ case 'n': height = NIR_HEIGHT; width = NIR_WIDTH; break; case 'g': height = GUIDE_HEIGHT; width = GUIDE_WIDTH; break; default: logging(ERROR, "INIT", "Incorrect camera name: %c", cam_name); return FAILURE; } /* seems like this one has to be called */ ASIGetNumOfConnectedCameras(); /* identify the correct camera */ for(int ii=0; ii<2; ++ii){ ret = ASIGetCameraProperty(cam_info, ii); if(ret == ASI_ERROR_INVALID_INDEX){ return ENODEV; } if(cam_info->MaxHeight == height){ break; } } int id = cam_info->CameraID; /* opening and initializating */ ret = ASIOpenCamera(id); if(ret != ASI_SUCCESS){ logging(ERROR, "Camera", "Failed to open camera: %c. " "Return value: %d", cam_name, ret); return FAILURE; } ret = ASIInitCamera(id); if(ret != ASI_SUCCESS){ logging(ERROR, "Camera", "Failed to initialise camera: %c. Return value: %d", cam_name, ret); return FAILURE; } /* setting image format to 16 bit per pixel */ ret = ASISetROIFormat(id, width, height, 1, ASI_IMG_RAW16); if(ret != ASI_SUCCESS){ logging(ERROR, "Camera", "Failed to set image format for camera: %c. Return value: %d", cam_name, ret); return FAILURE; } return ASI_SUCCESS; } /* expose: * Start an exposure of a ZWO ASI camera. Call save_img to store store * image after exposure * * input: * id: camera id found in ASI_CAMERA_INFO * exp: the exposure time in microseconds * gain: the sensor gain * cam_name: name of camera for logging * * return: * SUCCESS: operation is successful * EREMOTEIO: starting exposure failed * EIO: setting camera control values failed * ENODEV: Camera not connected */ int expose(int id, int exp, int gain, char* cam_name){ int ret; /* set exposure time in micro sec */ ret = ASISetControlValue(id, ASI_EXPOSURE, exp, ASI_FALSE); if(ret == ASI_ERROR_INVALID_ID){ logging(ERROR, "Camera", "Camera disconnected when starting exposure: %s", cam_name); return ENODEV; } if(ret != ASI_SUCCESS){ logging(ERROR, "Camera", "Failed to set exposure time for %s camera.", cam_name); return EIO; } /* set sensor gain */ ret = ASISetControlValue(id, ASI_GAIN, gain, ASI_FALSE); if(ret != ASI_SUCCESS){ logging(ERROR, "Camera", "Failed to set sensor gain for %s camera.", cam_name); return EIO; } ffgstm(exp_start_datetime[id], &timeref[id], &ret); clock_gettime(CLOCK_REALTIME, &start_time[id]); ASIStartExposure(id, ASI_FALSE); if(ret != ASI_SUCCESS){ logging(ERROR, "Camera", "Failed to start exposure of %s camera.", cam_name); return EREMOTEIO; } return SUCCESS; } /* save_img: * save_img will first check if exposure is still ongoing or has failed and * return if that is the case. Otherwise the image will be fetched from the * camera and saved. * * input: * cam_info: info for relevant camera * fn: filename to save image as * cam_name: name of camera for logging * exp_time: calculated exposure time if the exposure was aborted, * NULL if not * * return: * SUCCESS: operation is successful * EXP_NOT_READY: exposure still ongoing, wait a bit and call again * EXP_FAILED: exposure failed and must be retried * FAILURE: saving the image failed, log written to stderr * EPERM: calling save_img beore starting exposure * ENOMEM: no memory available for image buffer * EIO: failed to fetch data from camera * ENODEV: camera disconnected * * TODO: System for file names and queueing up image for processing. */ int save_img(ASI_CAMERA_INFO* cam_info, char* fn, char* cam_name, struct timespec* exp_time){ int id = cam_info->CameraID, ret; /* check current exposure status */ ASI_EXPOSURE_STATUS exp_stat; ASIGetExpStatus(id, &exp_stat); switch(exp_stat){ case ASI_EXP_WORKING: return EXP_NOT_READY; case ASI_EXP_FAILED: logging(ERROR, "Camera", "Exposure of %s camera failed", cam_name); return EXP_FAILED; case ASI_EXP_IDLE: logging(ERROR, "Camera", "save_img called before starting exposure"); return EPERM; default: break; } /* buffer for bitmap */ int width = cam_info->MaxWidth; int height = cam_info->MaxHeight; int buffer_size = width*height*2; unsigned char* buffer = (unsigned char*) malloc(buffer_size); if(buffer == NULL){ logging(ERROR, "Camera", "Cannot allocate memory for image buffer"); return ENOMEM; } /* fetch data */ ret = ASIGetDataAfterExp(id, buffer, buffer_size); if(ret == ASI_ERROR_INVALID_ID){ logging(ERROR, "Camera", "Camera disconnected when fetching data: %s", cam_name); return ENODEV; } else if(ret != ASI_SUCCESS){ logging(ERROR, "Camera", "Failed to fetch data from %s camera.", cam_name); return EIO; } unsigned short* buff = (unsigned short*)buffer; for(int ii=0; ii<buffer_size/2; ++ii){ buff[ii] = buff[ii]>>4; } yflip(buff, width, height); ret = write_img(buff, cam_info, fn, exp_time); free(buffer); return ret; } /* write_img: * Writes a bitmap to a .fit image file using fitsio * * input: * buffer: a bitmap of size [height*width] * cam_info: camera info object for camera capturing the image * fn: filename to save image as * exp_time: calculated exposure time if the exposure was aborted * NULL if not * * return: * SUCCESS: operation is successful * FAILURE: write failed, fits error written to stderr */ static int write_img(unsigned short* buffer, ASI_CAMERA_INFO* cam_info, char* fn, struct timespec* exp_time){ fitsfile* fptr; int ret = 0; long fpixel=1, naxis=2, nelements; long naxes[2] = {cam_info->MaxWidth, cam_info->MaxHeight}; nelements = naxes[0] * naxes[1]; int fn_len = strlen(fn); char fn_f[fn_len+2]; fn_f[0] = '!'; for(int ii=0; ii<fn_len+1; ++ii){ fn_f[ii+1] = fn[ii]; } #ifdef CAMERA_DEBUG logging(DEBUG, "Camera", "saving image, filename: %s", fn_f); logging(DEBUG, "Camera", "creating file"); #endif fits_create_file(&fptr, fn_f, &ret); if(ret != 0){ fits_report_error(stderr, ret); return FAILURE; } #ifdef CAMERA_DEBUG logging(DEBUG, "Camera", "creating img"); #endif fits_create_img(fptr, SHORT_IMG, naxis, naxes, &ret); if(ret != 0){ fits_report_error(stderr, ret); return FAILURE; } #ifdef CAMERA_DEBUG logging(DEBUG, "Camera", "updating header"); #endif long exposure, gain; ASI_BOOL pb_auto = ASI_FALSE; if(exp_time != NULL){ exposure = exp_time->tv_sec * 1000000 + exp_time->tv_nsec / 1000; #ifdef CAMERA_DEBUG logging(DEBUG, "Camera", "aborted after exposing for %ld microseconds", exposure); #endif } else{ ASIGetControlValue(cam_info->CameraID, ASI_EXPOSURE, &exposure, &pb_auto); } fits_update_key(fptr, TLONG, "EXPOINUS", &exposure, "Exposure time in us", &ret); if(ret != 0){ fits_report_error(stderr, ret); return FAILURE; } ASIGetControlValue(cam_info->CameraID, ASI_GAIN, &gain, &pb_auto); fits_update_key(fptr, TLONG, "GAIN", &gain, "The ratio of output / input", &ret); if(ret != 0){ fits_report_error(stderr, ret); return FAILURE; } #ifdef CAMERA_DEBUG logging(DEBUG, "Camera", "writing image"); #endif fits_write_img(fptr, TSHORT, fpixel, nelements, buffer, &ret); if(ret != 0){ fits_report_error(stderr, ret); return FAILURE; } #ifdef CAMERA_DEBUG logging(DEBUG, "Camera", "writing data"); #endif fits_update_key(fptr, TSTRING, "DATE", exp_start_datetime[cam_info->CameraID], "Exposure start time (YYYY-MM-DDThh:mm:ss UTC)", &ret); if(ret != 0){ fits_report_error(stderr, ret); return FAILURE; } #ifdef CAMERA_DEBUG logging(DEBUG, "Camera", "writing checksum"); #endif fits_write_chksum(fptr, &ret); if(ret != 0){ fits_report_error(stderr, ret); return FAILURE; } #ifdef CAMERA_DEBUG logging(DEBUG, "Camera", "closing file"); #endif fits_close_file(fptr, &ret); if(ret != 0){ fits_report_error(stderr, ret); return FAILURE; } return SUCCESS; } /* yflip: * vertically flips a bitmap * * input: * width: pixel width of image * height: pixel height of image * buffer: a bitmap of size [height*width] */ static void yflip(unsigned short* buffer, int width, int height){ unsigned short (*buff)[width] = (unsigned short (*)[width])buffer; unsigned short tmp; for(int ii=0; ii<height/2; ++ii){ for(int jj=0; jj<width; ++jj){ tmp = buff[ii][jj]; buff[ii][jj] = buff[height-1-ii][jj]; buff[height-1-ii][jj] = tmp; } } } /* abort_exp: * Abort an ongoing exposure and save the image. * * input: * cam_info: info for relevant camera * fn: filename to save image as * cam_name: name of camera for logging * * return: * SUCCESS: operation is successful * EXP_FAILED: exposure failed and must be retried * FAILURE: saving the image failed, log written to stderr * EPERM: calling save_img beore starting exposure * ENOMEM: no memory available for image buffer * EIO: failed to fetch data from camera * ENODEV: camera disconnected */ int abort_exp(ASI_CAMERA_INFO* cam_info, char* fn, char* cam_name){ struct timespec stop_time, exp_time; logging(WARN, "Camera", "Aborting exposure of %s camera", cam_name); clock_gettime(CLOCK_REALTIME, &stop_time); int ret = ASIStopExposure(cam_info->CameraID); if(ret == ASI_ERROR_INVALID_ID){ logging(ERROR, "Camera", "Camera disconnected when aborting exposure: %s", cam_name); } else if(ret != SUCCESS){ logging(ERROR, "Camera", "Failed to abort exposure of %s camera", cam_name); } if(stop_time.tv_nsec < start_time[cam_info->CameraID].tv_nsec){ exp_time.tv_sec = stop_time.tv_sec - start_time[cam_info->CameraID].tv_sec - 1; exp_time.tv_nsec = stop_time.tv_nsec + 1000000000 - start_time[cam_info->CameraID].tv_nsec; } else{ exp_time.tv_sec = stop_time.tv_sec - start_time[cam_info->CameraID].tv_sec; exp_time.tv_nsec = stop_time.tv_nsec - start_time[cam_info->CameraID].tv_nsec; } return save_img(cam_info, fn, cam_name, &exp_time); } #if 0 // printing available controls, not necessary for functionality int cont_num; ASIGetNumOfControls(id, &cont_num); ASI_CONTROL_CAPS cont[1]; for(int i=0; i<cont_num; ++i){ ASIGetControlCaps(id, i, cont); printf("%s\n", cont->Name); printf("\t%s\n\n", cont->Description); if(i == 9){ //printf("%ld\n%ld\n%ld\n", cont->MaxValue, cont->MinValue, cont->DefaultValue); } } #endif double get_cam_temp(int id, char* cam_name){ long val; ASI_BOOL pbAuto; ASI_ERROR_CODE stat = ASIGetControlValue(id, ASI_TEMPERATURE, &val, &pbAuto); if(stat != ASI_SUCCESS){ logging(WARN, "Camera", "Failed to fetch temperature of %s camera sensor", cam_name); return NAN; } return (double)val/10; }
29.280778
99
0.606108
[ "object" ]
d8b6cb446820a0a26b87814069cde68244227cb4
1,640
h
C
common/dstage/synchronization.h
PeterVondras/DAS
72dd5223280ec121f998b4932cc6bf7e83187d46
[ "MIT" ]
null
null
null
common/dstage/synchronization.h
PeterVondras/DAS
72dd5223280ec121f998b4932cc6bf7e83187d46
[ "MIT" ]
null
null
null
common/dstage/synchronization.h
PeterVondras/DAS
72dd5223280ec121f998b4932cc6bf7e83187d46
[ "MIT" ]
null
null
null
#ifndef DANS02_DSTAGE_SYNCHRONIZATION_H #define DANS02_DSTAGE_SYNCHRONIZATION_H #include <memory> #include <shared_mutex> #include <unordered_map> #include <vector> namespace dans { // Thread safe object used for tracking if a job is purged. class PurgeState { public: PurgeState(); // Returns whether the this job is marked as purged. There is no guarantee // that this is accurate even at the time of return. bool IsPurged(); // If the job is not already purged, this will set it as purged and return // true. If another thread sets the the job purged, then it will return false. bool SetPurged(); private: // guards state of whether job has been purged. std::shared_timed_mutex _state_shared_mutex; bool _purged; }; // Connection class should be broken out into its own header and implementation // files. class Connection { public: // Explicitly deleting default and copy constructor. Connection() = delete; Connection(const Connection&) = delete; Connection(int socket); ~Connection(); int Socket(); // Shutdown read and write to a socket which will trigger epoll. void Shutdown(); void SetShutdown(); void Close(); bool IsClosed(); private: const int _socket; std::mutex _close_lock; bool _closed; bool _shutdown; }; // Thread safe counter. class Counter { public: Counter(int initial_value); // Returns new value of Count int Increment(); int Decrement(); int Count(); private: // guards state of whether job has been purged. std::shared_timed_mutex _state_shared_mutex; int _count; }; } // namespace dans #endif // DANS02_DSTAGE_SYNCHRONIZATION_H
23.428571
80
0.728049
[ "object", "vector" ]
d8c782e6e70a249e0b15d2e42f2c0b773501e31b
1,841
h
C
src/transactions/include/transacs_recorder.h
fadi-alkhoury/fisim
08d91973251c94b8ac60b1889b41ffa3ace0d8ad
[ "MIT" ]
null
null
null
src/transactions/include/transacs_recorder.h
fadi-alkhoury/fisim
08d91973251c94b8ac60b1889b41ffa3ace0d8ad
[ "MIT" ]
null
null
null
src/transactions/include/transacs_recorder.h
fadi-alkhoury/fisim
08d91973251c94b8ac60b1889b41ffa3ace0d8ad
[ "MIT" ]
null
null
null
#ifndef FISIM_TRANSACTIONS_PROCESSOR_H_ #define FISIM_TRANSACTIONS_PROCESSOR_H_ #include "types.h" #include <string> #include <vector> namespace fisim { namespace transacs { class TransacsRecorder final { public: struct Transac { Transac() = default; Transac(Id id, tAmount amount, std::string description); Id id; tAmount amount = 0.0; std::string description; }; struct MonthTransacs { std::vector<Transac> transacs; tAmount balance; ///< Balance after all transactions in the month }; using MonthlyRecords = std::vector<MonthTransacs>; void init(tUint nMonths, tAmount balance); void reserve(tUint nMonths); /// /// Starts a new month /// void startMonth(); /// /// Records one transaction /// void recordTransac(Id const& id, tAmount amount, std::string description = ""); /// /// Returns the balance after the last recorded transaction /// tAmount balance() const { return _monthlyRecords.back().balance; } /// /// Accessor for the recorded transactions /// MonthlyRecords const& monthlyRecords() const { return _monthlyRecords; } /// /// Transfers ownership to the caller /// MonthlyRecords release() { return std::move(_monthlyRecords); } /// /// Makes a checkpoint up to all completed transactions /// void makeCheckPoint(); /// /// Resets to the previously made checkpoint /// void resetToCheckPoint(); private: MonthlyRecords _monthlyRecords; tAmount _balanceInit; struct CheckPoint { tSize nMonth = 0u; tSize nTransacs = 0u; tAmount balance = 0.0; }; CheckPoint _checkPoint; }; } // namespace transacs } // namespace fisim #endif /* FISIM_TRANSACTIONS_PROCESSOR_H_ */
22.180723
83
0.640413
[ "vector" ]
d8cc1ad2669b71d50d046fb5fe4ac6987fa1ce2c
13,873
c
C
MultiSource/Benchmarks/VersaBench/dbms/deleteEntry.c
Nuullll/llvm-test-suite
afbdd0a9ee7770e074708b68b34a6a5312bb0b36
[ "Apache-2.0" ]
70
2019-01-15T03:03:55.000Z
2022-03-28T02:16:13.000Z
MultiSource/Benchmarks/VersaBench/dbms/deleteEntry.c
Nuullll/llvm-test-suite
afbdd0a9ee7770e074708b68b34a6a5312bb0b36
[ "Apache-2.0" ]
519
2020-09-15T07:40:51.000Z
2022-03-31T20:51:15.000Z
MultiSource/Benchmarks/VersaBench/dbms/deleteEntry.c
Nuullll/llvm-test-suite
afbdd0a9ee7770e074708b68b34a6a5312bb0b36
[ "Apache-2.0" ]
117
2020-06-24T13:11:04.000Z
2022-03-23T15:44:23.000Z
/* * Name: deleteEntry * Input: node of index, node * search index key, searchKey * search non-key list, searchNonKey * Output: update index node, node * boolean key adjustment flag, adjustmentFlag * Return: void * Description: The routine recursively descends index on each branch which * is consistent with the input search key values. At the leaf * level, the routine removes all data objects which are * consistent with both the input search key and non-key * values. The routine also removes empty nodes from the * index. The search over the index is performed in the same * manner as the query() routine which checks only the key * values for entries/branches at non-leaf nodes and both key * and non-key values for leaf nodes. An adjustment flag is * used to tell upper level nodes that a change has occurred in * lower nodes. If the flag is not set on return, no change * occurred, i.e., no data objects or nodes removed, and no * adjustments for the key or entry list need to be made. If * the flag is set on return, a change did occur and either the * index key needs to be changed or the node may need to be * removed. * Calls: consistentKey() * consistentNonKey() * deleteEntry() * deleteIndexEntry() * keysUnion() * System: * Author: M.L.Rivas * * Revision History: * * Date Name Revision * ------- --------------- ------------------------------ * 27May99 Matthew Rivas Created * * Copyright 1999, Atlantic Aerospace Electronics Corp. */ #include <assert.h> /* for assert() */ #include <stdlib.h> /* for free() and NULL definitions */ #include "dataManagement.h" /* for primitive type definitions */ #include "dataObject.h" /* for DataAttribute definition */ #include "errorMessage.h" /* for errorMessage() definition */ #include "index.h" /* for IndexNode and IndexEntry definitions */ #include "indexKey.h" /* for IndexKey definition */ /* * Function prototypes */ extern Boolean consistentKey( IndexKey *A, IndexKey *B ); extern Boolean consistentNonKey( Char *A, Char *B ); extern void keysUnion( IndexEntry *I, IndexKey *U ); void deleteEntry( IndexNode *node, /* current node of index */ IndexKey *searchKey, /* index key search values */ DataAttribute *searchNonKey, /* non-key search values */ Boolean *adjustmentFlag ) /* flag to adjust keys */ { /* beginning of deleteEntry() */ assert( node ); assert( searchKey ); assert( adjustmentFlag ); /* * Set key adjustment flag to FALSE until adjustment is necessary through a * delete or return flag. */ *adjustmentFlag = FALSE; /* * The routine is applied recursively so the current node may or may not be * a leaf node. If it is a leaf node, the child referenced by the entries * residing on the node are data objects. If it is not a leaf node, the * child referenced by the entries are other nodes. So if the current * level is not a leaf, recursively call the deleteEntry routine on each * consistent entry. */ if ( node->level > LEAF ) { IndexEntry *entry; /* temp entry for looping through list */ IndexEntry *prevEntry; /* previous entry for re-linking after delete */ /* * Loop through each entry on current node and call deleteEntry() for * each consistent child node. Note that only the key values are * available for consistency checks at any level greater than the LEAF * level. */ prevEntry = NULL; /* no previous entry for head of list */ entry = node->entries; /* set current entry to head of list */ while ( entry != NULL ) { /* loop through entries */ if ( consistentKey( &entry->key, searchKey ) == TRUE ) { Boolean tempAdjustFlag; /* flag to indicate adjustment in */ /* child node */ deleteEntry( entry->child.node, searchKey, searchNonKey, &tempAdjustFlag ); /* * After a return from the recursive deleteEntry call, the * index beneath this node is in one of three states: (1) No * entries were removed, thus no key adjustment is required, * (2) Some entries of the node were removed, but some are left * so need a key adjustment, and (3) All entries of the node * were removed, so no key adjustment (adjust what?) and * remove the entry (which also removes the empty node). The * first condition (1) does not cause any actions so there is * no check. The second(2) and third(3) conditions do require * actions, so they are checked and appropriate actions taken. */ if ( (entry->child.node)->entries == NULL ) { /* (3) */ IndexEntry *nextEntry; /* temp storage for delete */ nextEntry = entry->next; /* save entry for re-linking */ deleteIndexEntry( entry, /* delete current entry */ node->level ); entry = nextEntry; /* reset current entry */ *adjustmentFlag = TRUE; /* set adjustment flag */ /* * If the deleted entry was not the head of the list, need * to re-link the list, so set the prevEntry's next pointer * to current entry. If the deleted entry was the head of * the list, set the node->entries field to the current * entry. This allows the list to show as EMPTY if * necessary on return. */ if ( prevEntry != NULL ) { prevEntry->next = entry; } /* end of if prevEntry != NULL */ else { node->entries = entry; } /* end of if prevEntry == NULL */ } /* end of if entry->child.node.entries == NULL */ else if ( tempAdjustFlag == TRUE ) { /* (2) */ keysUnion( (entry->child.node)->entries, &(entry->key) ); *adjustmentFlag = TRUE; /* set adjustment flag */ /* * Loop to next entry and set previous entry. */ prevEntry = entry; entry = entry->next; } /* end of tempAdjustFlag == TRUE */ else { /* * Loop to next entry and set previous entry. */ prevEntry = entry; entry = entry->next; } /* end of tempAdjustFlag == TRUE */ } /* end of branch which is consistent */ else { /* * Loop to next entry and set previous entry. */ prevEntry = entry; entry = entry->next; } /* end of branch which is not consistent */ } /* end of loop for entry */ } /* end of if ( node->level > LEAF ) */ else { IndexEntry *entry; /* temp entry for looping through list */ IndexEntry *prevEntry; /* previous entry for re-linking after delete */ /* * Loop through each entry on current LEAF node and delete each data * object/entry which is consistent with the input search values. The * first consistency check is made on the key value. If the key values * are consistent, then the data object is checked for its non-key * values. A temporary upperBound value is set to prevent out-of-range * checks on the three types of data objects. */ prevEntry = NULL; /* no previous entry for head of list */ entry = node->entries; /* set current entry to head of list */ while ( entry != NULL ) { /* loop through entries */ if ( consistentKey( &entry->key, searchKey ) == TRUE ) { DataAttribute *temp; /* attribute for list loop */ DataObject *object; /* allows easier reading */ Int upperBound; /* prevents out-of-range */ Boolean acceptanceFlag; /* flag to output object */ object = entry->child.dataObject; /* convenience */ upperBound = 0; /* set upperBound */ if ( object->type == SMALL ) { /* to prevent */ upperBound = NUM_OF_SMALL_ATTRIBUTES; /* out-of-range */ } /* end of type == SMALL */ /* errors when */ else if ( object->type == MEDIUM ) { /* checking non- */ upperBound = NUM_OF_MEDIUM_ATTRIBUTES; /* key attributes */ } /* end of type == MEDIUM */ else if ( object->type == LARGE ) { upperBound = NUM_OF_LARGE_ATTRIBUTES; } /* end of type == LARGE */ /* * The loop checks each value of the non-key search list and * compares that value for that specific attribute code to the * value stored in the data object. If all of the attributes * are consistent, the flag is set to TRUE at the end of the * loop. If any of the attributes are not consistent, the flag * is set to FALSE and the loop exits and the next entry is * checked. */ acceptanceFlag = TRUE; temp = searchNonKey; while ( temp != NULL && acceptanceFlag == TRUE ) { if ( temp->code < upperBound ) { acceptanceFlag = consistentNonKey( object->attributes[ temp->code ].value.nonKey, temp->attribute.value.nonKey ); } /* end of code < upperBound */ temp = temp->next; } /* end of loop through non-key search value list */ /* * If the acceptance flag is set, the data object should be * removed. If a data object is removed, the adjustment flag is * set which notifies the routine calling deleteEntry() for * this node that something happened at this level which causes * a node removal or key adjustment. Care must be taken to * properly re-link the node.entries list. */ if ( acceptanceFlag == FALSE ) { /* * Loop to next entry and set previous entry. */ prevEntry = entry; entry = entry->next; } /* end of acceptanceFlag == TRUE */ else { IndexEntry *nextEntry; /* next entry in list */ nextEntry = entry->next; /* save entry for re-linking */ deleteIndexEntry( entry, /* delete current entry */ LEAF ); entry = nextEntry; /* reset current entry */ *adjustmentFlag = TRUE; /* set adjustment flag */ /* * If the deleted entry was not the head of the list, need * to re-link the list, so set the prevEntry's next pointer * to current entry. If the deleted entry was the head of * the list, set the node->entries field to the current * entry. This allows the list to show as EMPTY if * necessary on return. */ if ( prevEntry != NULL ) { prevEntry->next = entry; } /* end of if prevEntry != NULL */ else { node->entries = entry; } /* end of if prevEntry == NULL */ } /* end of acceptanceFlag == FALSE */ } /* end of if consistentKey == TRUE */ else { /* * Loop to next entry and set previous entry. */ prevEntry = entry; entry = entry->next; } /* end of if consistentKey == FALSE */ } /* end of loop for entry */ } /* end of if ( node->level == LEAF ) */ return; } /* end deleteEntry() */
51.003676
81
0.48425
[ "object" ]
d8d3e6ffcf47c217d8cd9634cd9ca3698598268a
3,665
h
C
libs/cgv_gl/gl/render_info.h
IXDdev/IXD_engine
497c1fee90e486c19debc5347b740b56b1fef416
[ "BSD-3-Clause" ]
11
2017-09-30T12:21:55.000Z
2021-04-29T21:31:57.000Z
libs/cgv_gl/gl/render_info.h
IXDdev/IXD_engine
497c1fee90e486c19debc5347b740b56b1fef416
[ "BSD-3-Clause" ]
2
2017-07-11T11:20:08.000Z
2018-03-27T12:09:02.000Z
libs/cgv_gl/gl/render_info.h
IXDdev/IXD_engine
497c1fee90e486c19debc5347b740b56b1fef416
[ "BSD-3-Clause" ]
24
2018-03-27T11:46:16.000Z
2021-05-01T20:28:34.000Z
#pragma once #include <vector> #include <cgv/render/context.h> #include <cgv/render/vertex_buffer.h> #include <cgv/render/shader_program.h> #include <cgv/render/attribute_array_binding.h> #include <cgv/render/textured_material.h> #include "lib_begin.h" namespace cgv { namespace render { enum DrawCallType { RCT_ARRAYS, RCT_INDEXED, RCT_ARRAYS_INSTANCED, RCT_INDEXED_INSTANCED }; enum AlphaMode { AM_OPAQUE = 0, AM_MASK = 1, AM_BLEND = 2, AM_MASK_AND_BLEND = 3 }; enum VertexAttributeID { VA_BY_NAME = -1, VA_POSITION, VA_NORMAL, VA_TEXCOORD, VA_COLOR }; struct vertex_attribute { VertexAttributeID vertex_attribute_id; std::string name; type_descriptor element_type; uint32_t vbo_index; size_t byte_offset; size_t element_count; uint32_t stride; }; struct CGV_API attribute_array { std::vector<vertex_attribute> vas; attribute_array_binding* aab_ptr; shader_program* prog; void add_attribute(type_descriptor element_type, uint32_t vbo_index, size_t byte_offset, size_t element_count, uint32_t stride, VertexAttributeID vertex_attribute_id, std::string name = ""); }; struct draw_call { AlphaMode alpha_mode; float alpha_cutoff; DrawCallType draw_call_type; PrimitiveType primitive_type; uint32_t material_index; uint32_t aa_index; uint32_t vertex_offset; uint32_t count; cgv::type::info::TypeId index_type; void* indices; uint32_t instance_count; shader_program* prog; }; /** the mesh_render_info structure manages vertex buffer objects for attribute and element buffers as well as an attribute array binding object. The vertex buffer can be constructed from a simple mesh and the attribute array binding is bound to a specific shader program which defines the attribute locations. */ class CGV_API render_info : public render_types { public: /// define index type typedef cgv::type::uint32_type idx_type; protected: /// store materials std::vector<textured_material*> materials; /// store textures std::vector<texture*> textures; /// store buffers std::vector<vertex_buffer*> vbos; /// store attribute bindings std::vector<attribute_array> aas; /// store vector of render calls std::vector<draw_call> draw_calls; /// perform a single render call void draw(context& ctx, const draw_call& dc, const draw_call* prev_dc = 0, const draw_call* next_dc = 0, bool use_materials = true); public: /// set vbo and vbe types render_info(); /// give read access to materials const std::vector<textured_material*>& get_materials() const; /// give read access to vbos const std::vector<vertex_buffer*>& get_vbos() const; /// give read access to aabs const std::vector<attribute_array>& get_aas() const; /// give read access to texture const std::vector<texture*>& get_textures() const; /// give read access to draw calls const std::vector<draw_call>& get_draw_calls() const; /// give write access to materials std::vector<textured_material*>& ref_materials(); /// give write access to vbos std::vector<vertex_buffer*>& ref_vbos(); /// give write access to aabs std::vector<attribute_array>& ref_aas(); /// give write access to texture std::vector<texture*>& ref_textures(); /// give write access to draw calls std::vector<draw_call>& ref_draw_calls(); /// bind all or specific aa to the passed shader program virtual bool bind(context& ctx, shader_program& prog, bool force_success, int aa_index = -1); /// execute all draw calls void draw_all(context& ctx, bool skip_opaque = false, bool skip_blended = false, bool use_materials = true); /// destruct render mesh info and free vertex buffer objects void destruct(cgv::render::context& ctx); }; } } #include <cgv/config/lib_end.h>
29.087302
133
0.758799
[ "mesh", "render", "object", "vector" ]
d8eba8185b6510b2cee9535014154fe22fb2ef1f
589
h
C
QingDao/Common/QDFunction.h
hccgk/QDdemo
740158d9851f12ee5676142368c3084761f4a95c
[ "MIT" ]
null
null
null
QingDao/Common/QDFunction.h
hccgk/QDdemo
740158d9851f12ee5676142368c3084761f4a95c
[ "MIT" ]
null
null
null
QingDao/Common/QDFunction.h
hccgk/QDdemo
740158d9851f12ee5676142368c3084761f4a95c
[ "MIT" ]
null
null
null
// // QDFunction.h // QingDao // // Created by 何川 on 15/11/23. // Copyright © 2015年 hechuan. All rights reserved. // #import <Foundation/Foundation.h> @interface QDFunction : NSObject +(void)saveValue:(BOOL)vale forKey:(NSString *)key; //返回一个时间戳 + (NSString *)getTime; + (NSString *)signMD5String:(NSArray *)array; + (BOOL)getBooleaValueFromKey:(NSString *)key; + (id)getObjectValueFromKey:(NSString *)key; + (void)saveObjectValue:(id)object withKey:(NSString *)key; + (void)saveUserInfo:(NSDictionary *)dic; + (void)saveBooleanValue:(BOOL)boolean withKey:(NSString *)key; @end
21.814815
63
0.713073
[ "object" ]
d8eeca18654eca37f71bcd369cf4fc27ae09de42
6,793
h
C
FrameDX/Device/Device.h
RyanTorant/FrameDX
1e28c76da8eafb4ef3a9d495130ee6adc4c5c72f
[ "MIT" ]
3
2018-04-06T01:02:32.000Z
2020-05-17T00:35:47.000Z
FrameDX/Device/Device.h
RyanTorant/FrameDX
1e28c76da8eafb4ef3a9d495130ee6adc4c5c72f
[ "MIT" ]
null
null
null
FrameDX/Device/Device.h
RyanTorant/FrameDX
1e28c76da8eafb4ef3a9d495130ee6adc4c5c72f
[ "MIT" ]
null
null
null
#pragma once #include "../Core/Core.h" #include "../Texture/Texture.h" #include "../Core/Log.h" #include "../Core/PipelineState.h" namespace FrameDX { class Device { public: Device() { D3DDevice = nullptr; ImmediateContext = nullptr; SwapChain = nullptr; IsPipelineStateValid = false; } // There can only be ONE keyboard callback function on the entire program, that's why it's static static function<void(WPARAM,KeyAction)> KeyboardCallback; static function<void(WPARAM,int,int)> MouseCallback; struct Description { Description() { AdapterIndex = 0; ComputeOnly = false; WindowDescription.Name = L"FrameDX"; WindowDescription.SizeX = 0; WindowDescription.SizeY = 0; WindowDescription.Fullscreen = false; SwapChainDescription.IsStereo = false; SwapChainDescription.BufferCount = 3; SwapChainDescription.SwapType = DXGI_SWAP_EFFECT_DISCARD; SwapChainDescription.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; SwapChainDescription.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; SwapChainDescription.Flags = 0; SwapChainDescription.VSync = false; SwapChainDescription.ScanlineOrder = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; SwapChainDescription.ScalingNewAPI = DXGI_SCALING_STRETCH; SwapChainDescription.BackbufferAccessFlags = DXGI_USAGE_RENDER_TARGET_OUTPUT; SwapChainDescription.BackbufferDescription.MSAACount = 1; SwapChainDescription.BackbufferDescription.MSAAQuality = 0; } // If the index is -1 all the devices will be listed on the console and the user must select one int AdapterIndex; // Compute only devices only create the D3D device and immediate context. bool ComputeOnly; // ------------------------ // The following variables are only valid if ComputeOnly == false struct { wstring Name; // If any of the size variables equals 0 then the size is computed from the screen size uint32_t SizeX; uint32_t SizeY; bool Fullscreen; } WindowDescription; struct { // If any of the size variables equals 0 then the size is computed from the window size Texture2D::Description BackbufferDescription; bool IsStereo; uint32_t BufferCount; DXGI_SWAP_EFFECT SwapType; DXGI_MODE_SCALING Scaling; DXGI_SCALING ScalingNewAPI; DXGI_ALPHA_MODE AlphaMode; DXGI_MODE_SCANLINE_ORDER ScanlineOrder; uint32_t Flags; bool VSync; DXGI_USAGE BackbufferAccessFlags; } SwapChainDescription; } Desc; StatusCode Start(const Description& CreationParameters); ID3D11Device * GetDevice() { return D3DDevice; } #define __GET_DEVICE_DECL(v) ID3D11Device ## v * GetDevice##v(bool LogWrongVersion = true) {\ if(LogWrongVersion && LogAssertAndContinue(DeviceVersion >= v,LogCategory::Error)) return nullptr;\ return (ID3D11Device ## v *)D3DDevice; } __GET_DEVICE_DECL(1); __GET_DEVICE_DECL(2); __GET_DEVICE_DECL(3); __GET_DEVICE_DECL(4); __GET_DEVICE_DECL(5); ID3D11DeviceContext * GetImmediateContext(){ return ImmediateContext; }; #define __GET_CONTEXT_DECL(v) ID3D11DeviceContext ## v * GetImmediateContext##v(bool LogWrongVersion = true) {\ if(LogWrongVersion && LogAssertAndContinue(ContextVersion >= v,LogCategory::Error)) return nullptr;\ return (ID3D11DeviceContext ## v *)ImmediateContext; } __GET_CONTEXT_DECL(1); __GET_CONTEXT_DECL(2); __GET_CONTEXT_DECL(3); __GET_CONTEXT_DECL(4); IDXGISwapChain * GetSwapChain(){ return SwapChain; }; #define __GET_SWAP_DECL(v) IDXGISwapChain ## v * GetSwapChain##v(bool LogWrongVersion = true) {\ if(LogWrongVersion && LogAssertAndContinue(SwapChainVersion >= v,LogCategory::Error)) return nullptr;\ return (IDXGISwapChain ## v *)SwapChain; } __GET_SWAP_DECL(1); uint32_t GetDeviceVersion() { return DeviceVersion; } uint32_t GetContextVersion() { return ContextVersion; } uint32_t GetSwapChainVersion() { return SwapChainVersion; } // Wraps a PeekMessage loop, and calls f on idle time // The function returns true if it should continue void EnterMainLoop(function<bool(double)> LoopBody); Texture2D * GetBackbuffer(){ return &Backbuffer; } Texture2D * GetZBuffer(){ return &ZBuffer; } // Binds a new state // Automatically unbinds resources that have an in/out conflict (bound before as uav and then as srv or vice versa) // It stores the state to check if it changed, so it won't detect changes done directly. // This DOES NOT prevent in/out conflicts in the provided pipeline state, it ONLY prevents it compared to the old state // Null pointers are ignored. If you want to set something to null, you have to do it manually void BindPipelineState(const PipelineState& NewState); PipelineState GetCurrentPipelineStateCopy() { return CurrentPipelineState; } // Should be the last release called // Not using a destructor because I can't know the order they'll be destructed void Release(); HWND GetWindowHandle() { return WindowHandle; } // Maps the provided buffer and copies the value template<typename T> StatusCode UpdateBuffer(ID3D11Buffer* Buffer, const T& Value) { D3D11_MAPPED_SUBRESOURCE mapped; ZeroMemory(&mapped, sizeof(D3D11_MAPPED_SUBRESOURCE)); LogCheckWithReturn(ImmediateContext->Map(Buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped), LogCategory::Error); memcpy(mapped.pData, &Value, sizeof(T)); ImmediateContext->Unmap(Buffer, 0); return StatusCode::Ok; } template<typename T> StatusCode UpdateBufferFromVector(ID3D11Buffer* Buffer, const std::vector<T>& Data) { D3D11_MAPPED_SUBRESOURCE mapped; ZeroMemory(&mapped, sizeof(D3D11_MAPPED_SUBRESOURCE)); LogCheckWithReturn(ImmediateContext->Map(Buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped), LogCategory::Error); memcpy(mapped.pData, Data.data(), sizeof(T)*Data.size()); ImmediateContext->Unmap(Buffer, 0); return StatusCode::Ok; } private: // Used to keep track of the bound state enum class UAVStage { Compute, OutputMerger }; unordered_multimap<ID3D11Resource*, ShaderStage> SRVBoundResources; unordered_multimap<ID3D11Resource*, UAVStage> UAVBoundResources; unordered_set<ID3D11Resource*> RTVBoundResources; PipelineState CurrentPipelineState; bool IsPipelineStateValid; static LRESULT WINAPI InternalMessageProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); ID3D11Device * D3DDevice; ID3D11DeviceContext * ImmediateContext; int DeviceVersion; int ContextVersion; int SwapChainVersion; // Only valid if ComputeOnly == false IDXGISwapChain * SwapChain; Texture2D Backbuffer; Texture2D ZBuffer; HWND WindowHandle; std::chrono::time_point<std::chrono::high_resolution_clock> last_call_time; }; } #undef __GET_DEVICE_DECL #undef __GET_CONTEXT_DECL #undef __GET_SWAP_DECL
33.463054
121
0.748712
[ "vector" ]
d8f17f2fecfe05260026e0e6492a833bf177cea6
5,691
h
C
Include/CodeQOR/Instancing/SingletonInstancer.h
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Include/CodeQOR/Instancing/SingletonInstancer.h
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Include/CodeQOR/Instancing/SingletonInstancer.h
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//SingletonInstancer.h // Copyright Querysoft Limited 2013 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. //Singleton pattern template #ifndef CODEQOR_SINGLETON_INSTANCER_H_2 #define CODEQOR_SINGLETON_INSTANCER_H_2 #include "CodeQOR/instancing/sTOB.h" //------------------------------------------------------------------------------ //Declare a class to be a singleton //This prevents _Class from being created except by derived //classes or CTSingleton< _Class > #define __QOR_DECLARE_SINGLETON( _Class, _Policy ) \ \ friend class nsCodeQOR::CTSingletonInstancer< _Class, _Policy >; \ friend class typename mem_traits< _Class >::CTAllocator; \ protected: \ _Class(); \ virtual ~_Class(); //------------------------------------------------------------------------------ //Macro to singleton enable a class implementation //Include __QOR_IMPLEMENT_SINGLETON(class-name) in your class implementation #define __QOR_IMPLEMENT_SINGLETON( _Class, _Policy ) \ \ template<> _Class* nsCodeQOR::CTSingletonInstancer< _Class, _Policy >::m_pInstance = 0; \ template<> long nsCodeQOR::CTSingletonInstancer< _Class, _Policy >::m_lInstanceCount = 0; \ template<> _Policy::TThreadSyncSinglePrimitive nsCodeQOR::CTSingletonInstancer< _Class, _Policy >::m_Section; \ template<> mem_traits< _Class >::CSource nsCodeQOR::CTSingletonInstancer< _Class, _Policy >::m_Source; //Add __QOR_DECLARE_SINGLETON( source, class-name ); to your class declaration //declaring no other constructors or destructor. //Add __QOR_IMPLEMENT_SINGLETON( source, class-name) to your class implementation //and your class will only be able to be accessed as a singleton //Use nsCodeQOR::CTSingletonInstancer< source_type, class-name >::Instance() to get an pointer to a singleton //-------------------------------------------------------------------------------- namespace nsCodeQOR { //------------------------------------------------------------------------------ //Template for singleton instancing template< class T, class TPolicy > class CTSingletonInstancer { public: typedef typename TPolicy::TThreadSyncSinglePrimitive sectionType; typedef typename mem_traits< T >::CSource CTSource; //------------------------------------------------------------------------------ CTSingletonInstancer() { } //------------------------------------------------------------------------------ CTSingletonInstancer( const CTSingletonInstancer& src ) { *this = src; } //------------------------------------------------------------------------------ CTSingletonInstancer& operator = ( const CTSingletonInstancer& src ) { if( &src != this ) { } return *this; } //------------------------------------------------------------------------------ virtual ~CTSingletonInstancer() { } //------------------------------------------------------------------------------ //Get a pointer to the one instance T* Instance() { TPolicy::TThreadSyncSingleLock Lock( m_Section ); if( m_pInstance == 0 ) //If we don't have one then { byte* pMemory = m_Source.Source( sizeof( T ) ); m_pInstance = new( pMemory )( T ); //Create the one instance m_lInstanceCount = 1; //count the single reference } else { m_lInstanceCount++; } return m_pInstance; } //------------------------------------------------------------------------------ //Release a pointer to the one instance void Release( T* /*ignored*/ ) { TPolicy::TThreadSyncSingleLock Lock( m_Section ); m_lInstanceCount--; //decrement the reference count if( m_lInstanceCount <= 0 ) { //If no more references are held m_pInstance->~T(); //The one instance is deleted m_Source.Free( reinterpret_cast< byte* >( m_pInstance ), sizeof( T ) ); m_pInstance = 0; //reset pointer so re-creation can occur m_lInstanceCount = 0; //Reference count is reset to 0 } } //-------------------------------------------------------------------------------- CTSource& Source( void ) { return m_Source; } private: static sectionType m_Section;; static T* m_pInstance; static long m_lInstanceCount; static CTSource m_Source; }; }//nsCodeQOR #endif//CODEQOR_SINGLETON_INSTANCER_H_2
36.480769
111
0.601125
[ "object" ]
d8f68946e0c459ce1a5950840ea3b86625ed99d4
1,384
h
C
algorithms/medium/0851. Loud and Rich.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
algorithms/medium/0851. Loud and Rich.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
algorithms/medium/0851. Loud and Rich.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
// 851. Loud and Rich // Runtime: 476 ms, faster than 6.25% of C++ online submissions for Loud and Rich. // Memory Usage: 42.6 MB, less than 100.00% of C++ online submissions for Loud and Rich. class Solution { public: vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) { const int N = quiet.size(); vector<int> ans(N); for (int i = 0; i < N; ++i) ans[i] = i; vector<vector<int>> nodes(N, vector<int>()); vector<vector<int>> poorer(N, vector<int>()); for (auto& r : richer) { // money(r[0]) > money(r[1]) poorer[r[0]].push_back(r[1]); nodes[r[1]].push_back(r[0]); } unordered_set<int> s; for (int i = 0; i < N; ++i) { // money(i) > money(nodes[i][j]) if (nodes[i].empty()) { s.insert(i); } } while (!s.empty()) { unordered_set<int> t; for (int i : s) { // printf("%d ", i); // money(i) > money(nodes[i][j]) for (int j : poorer[i]) { if (quiet[ans[j]] > quiet[ans[i]]) ans[j] = ans[i]; t.insert(j); } } // cout << endl; swap(s, t); } return ans; } };
31.454545
88
0.422688
[ "vector" ]
d8fad4f80de7242a7396100469636ff8efad20c5
10,357
c
C
MontageLib/ArchiveList/montageArchiveList.c
lesomnus/dotnet-montage
18b6cf16e3dc6e70d59c7cc72d4f3726b0e19587
[ "BSD-3-Clause" ]
87
2015-06-02T14:08:22.000Z
2022-02-04T18:14:46.000Z
MontageLib/ArchiveList/montageArchiveList.c
lesomnus/dotnet-montage
18b6cf16e3dc6e70d59c7cc72d4f3726b0e19587
[ "BSD-3-Clause" ]
54
2015-10-24T19:39:20.000Z
2021-11-17T21:28:15.000Z
MontageLib/ArchiveList/montageArchiveList.c
lesomnus/dotnet-montage
18b6cf16e3dc6e70d59c7cc72d4f3726b0e19587
[ "BSD-3-Clause" ]
35
2015-10-30T16:25:23.000Z
2021-11-06T11:27:08.000Z
/* Module: mArchiveList.c Version Developer Date Change ------- --------------- ------- ----------------------- 1.0 John Good 14Dec04 Baseline code */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <strings.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <math.h> #include <mArchiveList.h> #include <montage.h> #define MAXLEN 20000 static char montage_msgstr[1024]; /*-***********************************************************************/ /* */ /* mArchiveList -- Given a location on the sky, archive name, and size */ /* in degrees contact the IRSA server to retreive a list of archive */ /* images. The list contains enough information to support mArchiveGet */ /* downloads. */ /* */ /* char *survey Data survey to search (e.g. 2MASS, SDSS, */ /* WISE, etc.) */ /* */ /* char *band Wavelength band (e.g. J for 2MASS, g for */ /* SDSS) */ /* */ /* char *locstr A (quoted if necessary) string containing */ /* a coordinate or the name of an object on */ /* the sky */ /* */ /* double width Image width in degrees */ /* double height Image height in degrees */ /* */ /* char *outfile Output FITS header file */ /* */ /* int debug Debugging output flag */ /* */ /*************************************************************************/ struct mArchiveListReturn *mArchiveList(char *survey, char *band, char *location, double width, double height, char *outfile, int debug) { int socket, port, count; double size; char line [MAXLEN]; char request [MAXLEN]; char base [MAXLEN]; char constraint[MAXLEN]; char server [MAXLEN]; char source [MAXLEN]; FILE *fout; char *ptr; char *proxy; char pserver [MAXLEN]; int pport; struct mArchiveListReturn *returnStruct; char *surveystr; char *bandstr; char *locstr; if(debug) { printf("DEBUG> survey: [%s]\n", survey); printf("DEBUG> band: [%s]\n", band); printf("DEBUG> location: [%s]\n", location); printf("DEBUG> width: %-g\n", width); printf("DEBUG> height: %-g\n", height); printf("DEBUG> outfile: [%s]\n", outfile); fflush(stdout); } /*******************************/ /* Initialize return structure */ /*******************************/ returnStruct = (struct mArchiveListReturn *)malloc(sizeof(struct mArchiveListReturn)); memset((void *)returnStruct, 0, sizeof(returnStruct)); returnStruct->status = 1; strcpy(returnStruct->msg, ""); /* Process command-line parameters */ strcpy(server, "montage-web.ipac.caltech.edu"); port = 80; strcpy(base, "/cgi-bin/ArchiveList/nph-archivelist?"); surveystr = mArchiveList_url_encode(survey); bandstr = mArchiveList_url_encode(band); locstr = mArchiveList_url_encode(location); size = sqrt(width*width + height*height); sprintf(constraint, "survey=%s+%s&location=%s&size=%.4f&units=deg&mode=TBL", surveystr, bandstr, locstr, size); free(surveystr); free(bandstr); free(locstr); fout = fopen(outfile, "w+"); if(fout == (FILE *)NULL) { sprintf(returnStruct->msg, "Can't open output file %s", outfile); return returnStruct; } /* Connect to the port on the host we want */ proxy = getenv("http_proxy"); if(proxy) { if(mArchiveList_parseUrl(proxy, pserver, &pport) > 0) { strcpy(returnStruct->msg, montage_msgstr); return returnStruct; } if(debug) { printf("DEBUG> proxy = [%s]\n", proxy); printf("DEBUG> pserver = [%s]\n", pserver); printf("DEBUG> pport = [%d]\n", pport); fflush(stdout); } socket = mArchiveList_tcp_connect(pserver, pport); } else socket = mArchiveList_tcp_connect(server, port); if(socket == 0) { strcpy(returnStruct->msg, montage_msgstr); return returnStruct; } /* Send a request for the file we want */ if(proxy) { sprintf(request, "GET http://%s:%d%s%s HTTP/1.0\r\n\r\n", server, port, base, constraint); } else { sprintf(request, "GET %s%s HTTP/1.0\r\nHOST: %s:%d\r\n\r\n", base, constraint, server, port); } if(debug) { printf("DEBUG> request = [%s]\n", request); fflush(stdout); } send(socket, request, strlen(request), 0); /* And read all the lines coming back */ count = 0; while(1) { /* Read lines returning from service */ if(mArchiveList_readline (socket, line) == 0) break; if(debug) { printf("DEBUG> return: [%s]\n", line); fflush(stdout); } if(count == 0 && strncmp(line, "HTTP", 4) == 0) continue; if(count == 0 && strncmp(line, "Content-type", 12) == 0) continue; if(count == 0 && strcmp(line, "\r\n") == 0) continue; if(count == 0 && strncmp(line, "{\"error\":\"", 10) == 0) { if(line[strlen(line)-1] == '\n') line[strlen(line)-1] = '\0'; ptr = line + 10; while(*ptr != '"' && *ptr != '\0') ++ptr; *ptr = '\0'; strcpy(returnStruct->msg, line+10); return returnStruct; } else { fprintf(fout, "%s", line); fflush(fout); if(line[0] != '|' && line[0] != '\\') ++count; } } fclose(fout); returnStruct->status = 0; sprintf(returnStruct->msg, "count=%d", count); sprintf(returnStruct->json, "{\"count\":%d}", count); returnStruct->count = count; return returnStruct; } /***********************************************/ /* This is the basic "make a connection" stuff */ /***********************************************/ int mArchiveList_tcp_connect(char *hostname, int port) { int sock_fd; struct hostent *host; struct sockaddr_in sin; if((host = gethostbyname(hostname)) == NULL) { printf("[struct stat=\"ERROR\", msg=\"Couldn't find host %s\"]\n", hostname); fflush(stdout); return(0); } if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { sprintf(montage_msgstr, "Couldn't create socket()"); return(0); } sin.sin_family = AF_INET; sin.sin_port = htons(port); bcopy(host->h_addr_list[0], &sin.sin_addr, host->h_length); if(connect(sock_fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) { sprintf(montage_msgstr, "%s: connect failed.", hostname); return(0); } return sock_fd; } /***************************************/ /* This routine reads a line at a time */ /* from a raw file descriptor */ /***************************************/ int mArchiveList_readline (int fd, char *line) { int n, rc = 0; char c ; for (n = 1 ; n < MAXLEN ; n++) { if ((rc == read (fd, &c, 1)) != 1) { *line++ = c ; if (c == '\n') break ; } else if (rc == 0) { if (n == 1) return 0 ; /* EOF */ else break ; /* unexpected EOF */ } else return -1 ; } *line = 0 ; return n ; } /**************************************/ /* This routine URL-encodes a string */ /**************************************/ static unsigned char hexchars[] = "0123456789ABCDEF"; char *mArchiveList_url_encode(char *s) { int len; register int i, j; unsigned char *str; len = strlen(s); str = (unsigned char *) malloc(3 * strlen(s) + 1); j = 0; for (i=0; i<len; ++i) { str[j] = (unsigned char) s[i]; if (str[j] == ' ') { str[j] = '+'; } else if ((str[j] < '0' && str[j] != '-' && str[j] != '.') || (str[j] < 'A' && str[j] > '9') || (str[j] > 'Z' && str[j] < 'a' && str[j] != '_') || (str[j] > 'z')) { str[j++] = '%'; str[j++] = hexchars[(unsigned char) s[i] >> 4]; str[j] = hexchars[(unsigned char) s[i] & 15]; } ++j; } str[j] = '\0'; return ((char *) str); } int mArchiveList_parseUrl(char *urlStr, char *hostStr, int *port) { char *hostPtr; char *portPtr; char *dataref; char save; if(strncmp(urlStr, "http://", 7) != 0) { sprintf(montage_msgstr, "Invalid URL string (must start 'http://')"); return 1; } hostPtr = urlStr + 7; dataref = hostPtr; while(1) { if(*dataref == ':' || *dataref == '/' || *dataref == '\0') break; ++dataref; } save = *dataref; *dataref = '\0'; strcpy(hostStr, hostPtr); *dataref = save; if(*dataref == ':') { portPtr = dataref+1; dataref = portPtr; while(1) { if(*dataref == '/' || *dataref == '\0') break; ++dataref; } *dataref = '\0'; *port = atoi(portPtr); *dataref = '/'; if(*port <= 0) { sprintf(montage_msgstr, "Illegal port number in URL"); return 1; } } return 0; }
23.326577
110
0.446654
[ "object" ]
d8fd277eb852e950a6206957b094e52c0585ab72
5,611
h
C
include/ntruhe.h
KULeuven-COSIC/FINAL
c6296ae5457ae6e61a9466a1497c6b0130460343
[ "MIT" ]
6
2022-01-21T13:15:35.000Z
2022-03-28T11:46:19.000Z
include/ntruhe.h
KULeuven-COSIC/FINAL
c6296ae5457ae6e61a9466a1497c6b0130460343
[ "MIT" ]
1
2022-03-24T21:09:18.000Z
2022-03-24T21:09:18.000Z
include/ntruhe.h
KULeuven-COSIC/FINAL
c6296ae5457ae6e61a9466a1497c6b0130460343
[ "MIT" ]
1
2022-01-24T07:27:50.000Z
2022-01-24T07:27:50.000Z
#ifndef NTRUHE #define NTRUHE #include "params.h" #include "keygen.h" class Ctxt_NTRU { public: std::vector<int> data; Ctxt_NTRU() { data.clear(); data.resize(parNTRU.n); } Ctxt_NTRU(const Ctxt_NTRU& ct); Ctxt_NTRU& operator=(const Ctxt_NTRU& ct); Ctxt_NTRU operator +(const Ctxt_NTRU& ct) const; Ctxt_NTRU operator -(const Ctxt_NTRU& ct) const; void operator -=(const Ctxt_NTRU& ct); }; /** * Switches a given ciphertext to a given modulus. * @param[in,out] ct ciphertext * @param[in] old_q old modulus * @param[in] new_q old modulus */ inline void modulo_switch_ntru(Ctxt_NTRU& ct, int old_q, int new_q) { std::vector<int>& a = ct.data; for (size_t i = 0; i < a.size(); i++) a[i] = int((a[i]*new_q)/old_q); } /** * Switches a given polynomial from q_base to modulus 2*N. * @param[in,out] poly polynomial */ inline void modulo_switch_to_boot(Ctxt_NTRU& poly) { modulo_switch_ntru(poly, parNTRU.q_base, Param::N2); } /** * Switches a given polynomial from q_boot to q_base. * @param[in,out] poly polynomial */ inline void modulo_switch_to_base_ntru(ModQPoly& poly) { modulo_switch(poly, q_boot, parNTRU.q_base); } /** * Computes the external product of a given polynomial ciphertext * with an NGS ciphertext in the FFT form * @param[in,out] poly polynomial ciphertext * @param[in] poly_vector NGS ciphertext * @param[in] b decomposition base, power of 2 * @param[in] shift bit shift to divide by b * @param[in] l decomposition length */ //void external_product(std::vector<long>& res, const std::vector<int>& poly, const std::vector<FFTPoly>& poly_vector, const int b, const int shift, const int l); class SchemeNTRU { SKey_base_NTRU sk_base; SKey_boot sk_boot; KSKey_NTRU ksk; BSKey_NTRU bk; Ctxt_NTRU ct_nand_const; Ctxt_NTRU ct_and_const; Ctxt_NTRU ct_or_const; Ctxt_NTRU ct_not_const; void mask_constant(Ctxt_NTRU& ct, int constant); inline void set_nand_const() { //clock_t start = clock(); mask_constant(ct_nand_const, parNTRU.nand_const); //cout << "Encryption of NAND: " << float(clock()-start)/CLOCKS_PER_SEC << endl; } inline void set_and_const() { //clock_t start = clock(); mask_constant(ct_and_const, parNTRU.and_const); //cout << "Encryption of AND: " << float(clock()-start)/CLOCKS_PER_SEC << endl; } inline void set_or_const() { //clock_t start = clock(); mask_constant(ct_or_const, parNTRU.or_const); //cout << "Encryption of OR: " << float(clock()-start)/CLOCKS_PER_SEC << endl; } inline void set_not_const() { encrypt(ct_not_const, 1); } public: SchemeNTRU() { KeyGen keygen(parNTRU); keygen.get_sk_base(sk_base); keygen.get_sk_boot(sk_boot); keygen.get_ksk(ksk,sk_base,sk_boot); keygen.get_bsk(bk,sk_base,sk_boot); set_nand_const(); set_and_const(); set_or_const(); set_not_const(); } /** * Encrypts a bit using matrix NTRU. * @param[out] ct ciphertext encrypting the input bit * @param[in] b bit to encrypt */ void encrypt(Ctxt_NTRU& ct, const int b) const; /** * Decrypts a bit using matrix NTRU. * @param[out] ct ciphertext encrypting a bit * @return b bit */ int decrypt(const Ctxt_NTRU& ct) const; /** * Performs key switching of a given ciphertext from a polynomial NTRU * to a matrix NTRU * @param[out] ct matrix NTRU ciphertext (vector of dimension n) * @param[in] poly polynomial ciphertext (vector of dimension N) */ void key_switch(Ctxt_NTRU& ct, const ModQPoly& poly) const; /** * Bootstrapps a given ciphertext * @param[in,out] ct ciphertext to bootstrap */ void bootstrap(Ctxt_NTRU& ct) const; /** * Computes the NAND gate of two given ciphertexts ct1 and ct2 * @param[out] ct_res encryptions of the outuput of the NAND gate * @param[in] ct_1 encryption of the first input bit * @param[in] ct_2 encryption of the second input bit */ void nand_gate(Ctxt_NTRU& ct_res, const Ctxt_NTRU& ct1, const Ctxt_NTRU& ct2) const; /** * Computes the AND gate of two given ciphertexts ct1 and ct2 * @param[out] ct_res encryptions of the outuput of the AND gate * @param[in] ct_1 encryption of the first input bit * @param[in] ct_2 encryption of the second input bit */ void and_gate(Ctxt_NTRU& ct_res, const Ctxt_NTRU& ct1, const Ctxt_NTRU& ct2) const; /** * Computes the OR gate of two given ciphertexts ct1 and ct2 * @param[out] ct_res encryptions of the outuput of the OR gate * @param[in] ct_1 encryption of the first input bit * @param[in] ct_2 encryption of the second input bit */ void or_gate(Ctxt_NTRU& ct_res, const Ctxt_NTRU& ct1, const Ctxt_NTRU& ct2) const; /** * Computes the XOR gate of two given ciphertexts ct1 and ct2 * @param[out] ct_res encryptions of the outuput of the XOR gate * @param[in] ct_1 encryption of the first input bit * @param[in] ct_2 encryption of the second input bit */ void xor_gate(Ctxt_NTRU& ct_res, const Ctxt_NTRU& ct1, const Ctxt_NTRU& ct2) const; /** * Computes the NOT gate of a given ciphertext ct * @param[out] ct_res encryption of the outuput of the NOT gate * @param[in] ct encryption of the input bit */ void not_gate(Ctxt_NTRU& ct_res, const Ctxt_NTRU& ct) const; }; #endif
28.774359
162
0.654072
[ "vector" ]
d8fd3f6c14c5d337087fd1d36d3985ff57b973d8
749
h
C
src/duke/engine/cache/LoadedPboCache.h
PaulDoessel/duke
ccead104bb856b6eec9bb44cad6fdb7a47e418c1
[ "MIT" ]
null
null
null
src/duke/engine/cache/LoadedPboCache.h
PaulDoessel/duke
ccead104bb856b6eec9bb44cad6fdb7a47e418c1
[ "MIT" ]
null
null
null
src/duke/engine/cache/LoadedPboCache.h
PaulDoessel/duke
ccead104bb856b6eec9bb44cad6fdb7a47e418c1
[ "MIT" ]
null
null
null
/* * PboCache.h * * Created on: Feb 11, 2013 * Author: Guillaume Chatelet */ #pragma once #include <duke/engine/cache/PboPackedFrame.h> #include <duke/engine/cache/TimelineIterator.h> #include <duke/gl/GlObjects.h> #include <duke/engine/cache/PboPool.h> #include <duke/NonCopyable.h> namespace duke { struct LoadedImageCache; struct LoadedPboCache: public noncopyable { bool get(const LoadedImageCache& imageCache, const MediaFrameReference& mfr, PboPackedFrame &pbo); private: void moveFront(const MediaFrameReference& mfr); void evictOneIfNecessary(); const size_t m_MaxCount = 10; PboPool m_PboPool; std::map<MediaFrameReference, PboPackedFrame> m_Map; std::vector<MediaFrameReference> m_Fifo; }; } /* namespace duke */
22.029412
99
0.755674
[ "vector" ]
2b04b25e69ae8542bde279f58fe29b942c23ae43
2,579
h
C
Graphics/GUI/SubGUI.h
SamirAroudj/BaseProject
50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d
[ "BSD-3-Clause" ]
null
null
null
Graphics/GUI/SubGUI.h
SamirAroudj/BaseProject
50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d
[ "BSD-3-Clause" ]
1
2019-06-19T15:55:25.000Z
2019-06-27T07:47:27.000Z
Graphics/GUI/SubGUI.h
SamirAroudj/BaseProject
50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d
[ "BSD-3-Clause" ]
1
2019-07-07T04:37:56.000Z
2019-07-07T04:37:56.000Z
/* * Copyright (C) 2017 by Author: Aroudj, Samir, born in Suhl, Thueringen, Germany * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the License.txt file for details. */ #ifndef _SUB_GUI_H_ #define _SUB_GUI_H_ #include <cassert> #include <vector> #include "Platform/DataTypes.h" #include "Graphics/RenderGroup.h" namespace Graphics { namespace GUI { /// Represents one part of the GUI, e.g. the GUI which is specific for a Player object class SubGUI { public: /** Creates a SubGUI object with a unique identifier and a specific maximum depth. @param identifier Sets the ID of this new SubGUI object. @param numOfLayers Defines how many layers the GUI creates. */ SubGUI(int32 identifier, uint32 numOfLayers); /** Destroys the SubGUI object and all of its layers which should be empty. */ ~SubGUI(); /** Adds an IRenderable object to a specific layer. @param renderable This object is rendered each time the layer it belongs to is rendered. @param layer Identifiers the layer the renderable is added to whereas 0 is the lowest layer which is occluded by all other layers. */ void add(const IRenderable &renderable, uint32 layer); /** Provides access to the ID of the SubGUI. @return The identifier that was used for creation is returned. */ int32 getID() const { return mIdentifier; } /** Removes an IRenderable object from the layer it belongs to if it is found. @param renderable It is removed from the SubGUI if it is found otherwise an assertion fails. @param layer This is the layer the renderable was added to previously. */ void remove(const IRenderable &renderable, uint32 layer); /** Renders all layers of the SubGUI object whereas layer 0 is rendered first and the layer with the highest number is the last one to be rendered. The layer number corresponds to the height of the layer whereas 0 means it is the lowest layer which is occluded by all other layers. Higher layer numbers mean that the GUI elements of the layer are closer to the viewer. */ void render() const; protected: std::vector<RenderGroup *> mRenderGroups; /// each render group is one layer of the SubGUI object int32 mIdentifier; /// identifies the SubGUI object private: /** Copy constructor is forbidden. */ SubGUI(const SubGUI &rhs) { assert(false); } /** Assignment operator is forbidden. */ SubGUI &operator =(const SubGUI &rhs) { assert(false); return *this; } }; } } #endif // _SUB_GUI_H_
37.376812
150
0.725863
[ "render", "object", "vector" ]
faf34848c9f09b78107f986d3912f59d728a65f9
22,458
c
C
src/process_options.c
AdamBromiley/rolymo
933a22b5d698c21c24fceca5356da362e53556a5
[ "MIT" ]
1
2020-07-07T13:32:47.000Z
2020-07-07T13:32:47.000Z
src/process_options.c
AdamBromiley/rolymo
933a22b5d698c21c24fceca5356da362e53556a5
[ "MIT" ]
null
null
null
src/process_options.c
AdamBromiley/rolymo
933a22b5d698c21c24fceca5356da362e53556a5
[ "MIT" ]
null
null
null
#include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <arpa/inet.h> #include <getopt.h> #include <netinet/in.h> #include "libgroot/include/log.h" #include "percy/include/parser.h" #include "process_options.h" #include "arg_ranges.h" #include "getopt_error.h" #include "image.h" #include "network_ctx.h" #include "parameters.h" #include "process_args.h" #include "program_ctx.h" #ifdef MP_PREC #include <mpfr.h> #endif const uint16_t PORT_DEFAULT = 7939; #ifdef MP_PREC static const char *GETOPT_STRING = ":Ac:g:G:i:j:l:m:M:o:p:r:s:tT:vx:Xz:"; #else static const char *GETOPT_STRING = ":c:g:G:i:j:l:m:M:o:p:r:s:tT:vx:Xz:"; #endif static const struct option LONG_OPTIONS[] = { #ifdef MP_PREC {"multiple", no_argument, NULL, 'A'}, /* Use multiple precision */ {"precision", required_argument, NULL, 'P'}, /* Specify number of bits to use for the MP significand */ #endif {"colour", required_argument, NULL, 'c'}, /* Colour scheme of PPM image */ {"worker", required_argument, NULL, 'g'}, /* Initialise as a worker for distributed computation */ {"master", required_argument, NULL, 'G'}, /* Initialise as a master for distributed computation */ {"iterations", required_argument, NULL, 'i'}, /* Maximum iteration count of function */ {"julia", required_argument, NULL, 'j'}, /* Plot a Julia set with specified constant */ {"log", no_argument, NULL, 'k'}, /* Output log to file */ {"log-file", required_argument, NULL, 'K'}, /* Specify filepath of log */ {"log-level", required_argument, NULL, 'l'}, /* Minimum log level to output */ {"min", required_argument, NULL, 'm'}, /* Range of complex numbers to plot */ {"max", required_argument, NULL, 'M'}, {"width", required_argument, NULL, 'r'}, /* Width and height of image */ {"height", required_argument, NULL, 's'}, {"threads", required_argument, NULL, 'T'}, /* Specify thread count */ {"centre", required_argument, NULL, 'x'}, /* Centre coordinate and magnification of plot */ {"extended", no_argument, NULL, 'X'}, /* Use extended precision */ {"memory", required_argument, NULL, 'z'}, /* Maximum memory usage in MB */ {"help", no_argument, NULL, 'h'}, /* Display help message and exit */ {0, 0, 0, 0} }; static int parsePrecisionMode(PrecisionMode *precision, int argc, char **argv); static int parseGlobalOptions(ProgramCTX *ctx, int argc, char **argv); static NetworkCTX * parseNetworkOptions(int argc, char **argv); static int parseDiscreteOptions(PlotCTX *p, int argc, char **argv); static int parseContinuousOptions(PlotCTX *p, int argc, char **argv); static PlotType parsePlotType(int argc, char **argv); static OutputType parseOutputType(int argc, char **argv); static int parseMagnification(PlotCTX *p, int argc, char **argv); /* Scan argv for invalid command-line options */ int validateOptions(int argc, char **argv) { optind = 0; while ((opt = getopt_long(argc, argv, GETOPT_STRING, LONG_OPTIONS, NULL)) != -1) { if (opt == '?') { /* If invalid option found */ opt = optopt; getoptErrorMessage(OPT_EOPT, argv[optind - 1]); return -1; } else if (opt == ':') { /* If missing option argument */ opt = optopt; getoptErrorMessage(OPT_ENOARG, NULL); return -1; } } return 0; } int processProgramOptions(ProgramCTX *ctx, NetworkCTX **network, int argc, char **argv) { if (!ctx || !network) return -1; if (initialiseProgramCTX(ctx)) return -1; switch (parseGlobalOptions(ctx, argc, argv)) { case 0: break; case 1: return 1; default: return -1; } *network = parseNetworkOptions(argc, argv); if (!(*network)) return -1; return 0; } PlotCTX * processPlotOptions(int argc, char **argv) { PlotCTX *p; PrecisionMode precision; PlotType plot = parsePlotType(argc, argv); OutputType output = parseOutputType(argc, argv); if (output == OUTPUT_NONE) return NULL; if (parsePrecisionMode(&precision, argc, argv)) return NULL; p = createPlotCTX(precision); if (initialisePlotCTX(p, plot, output)) return NULL; if (parseContinuousOptions(p, argc, argv) || parseDiscreteOptions(p, argc, argv)) return NULL; return p; } /* Do one getopt pass to set the precision (default is standard precision) */ static int parsePrecisionMode(PrecisionMode *precision, int argc, char **argv) { #ifdef MP_PREC unsigned long tempPrecision = 0; bool AFlag = false, PFlag = false, XFlag = false; #endif if (!precision) return -1; *precision = STD_PRECISION; optind = 0; while ((opt = getopt_long(argc, argv, GETOPT_STRING, LONG_OPTIONS, NULL)) != -1) { #ifdef MP_PREC ParseErr argError = PARSE_SUCCESS; #endif switch (opt) { #ifdef MP_PREC case 'A': /* Use multiple precision */ AFlag = true; if (XFlag) { fprintf(stderr, "%s: -%c: Option mutually exclusive with -%c\n", programName, opt, 'X'); getoptErrorMessage(OPT_NONE, NULL); return -1; } *precision = MUL_PRECISION; break; case 'P': /* Specify number of bits to use for the MP significand */ PFlag = true; if (XFlag) { fprintf(stderr, "%s: -%c: Option mutually exclusive with -%c\n", programName, opt, 'X'); getoptErrorMessage(OPT_NONE, NULL); return -1; } argError = uLongArg(&tempPrecision, optarg, (unsigned long) MP_BITS_MIN, (unsigned long) MP_BITS_MAX); if (argError != PARSE_SUCCESS) { break; } if (tempPrecision < MPFR_PREC_MIN || tempPrecision > MPFR_PREC_MAX) { mpfr_fprintf(stderr, "%s: -%c: Argument out of range, it must be between %Pu and %Pu\n", programName, opt, MPFR_PREC_MIN, MPFR_PREC_MAX); argError = PARSE_ERANGE; break; } break; #endif case 'X': /* Use extended precision */ #ifdef MP_PREC XFlag = true; if (AFlag || PFlag) { fprintf(stderr, "%s: -%c: Option mutually exclusive with -%c\n", programName, opt, (AFlag) ? 'A' : 'P'); getoptErrorMessage(OPT_NONE, NULL); return -1; } #endif *precision = EXT_PRECISION; break; default: break; } #ifdef MP_PREC if (argError == PARSE_ERANGE) /* Error message already outputted */ { getoptErrorMessage(OPT_NONE, NULL); return -1; } else if (argError != PARSE_SUCCESS) /* Error but no error message, yet */ { getoptErrorMessage(OPT_EARG, NULL); return -1; } #endif } #ifdef MP_PREC if (PFlag && !AFlag) { fprintf(stderr, "%s: -%c: Option must be used in conjunction with -%c\n", programName, 'P', 'A'); getoptErrorMessage(OPT_NONE, NULL); return -1; } else if (PFlag) { mpSignificandSize = (mpfr_prec_t) tempPrecision; } #endif return 0; } /* Parse options common to every mode of operation */ static int parseGlobalOptions(ProgramCTX *ctx, int argc, char **argv) { char tmpLogFilepath[sizeof(ctx->logFilepath)]; bool KFlag = false, vFlag = false; optind = 0; while ((opt = getopt_long(argc, argv, GETOPT_STRING, LONG_OPTIONS, NULL)) != -1) { ParseErr argError = PARSE_SUCCESS; unsigned long tempUL = 0; switch (opt) { char *endptr; case 'k': /* Output log to file */ ctx->logToFile = true; if (!vFlag) setLogVerbosity(false); break; case 'K': /* Specify filepath of log */ KFlag = true; ctx->logToFile = true; strncpy(tmpLogFilepath, optarg, sizeof(tmpLogFilepath)); tmpLogFilepath[sizeof(tmpLogFilepath) - 1] = '\0'; if (!vFlag) setLogVerbosity(false); break; case 'l': /* Minimum log level to output */ argError = uLongArg(&tempUL, optarg, LOG_LEVEL_MIN, LOG_LEVEL_MAX); setLogLevel((LogLevel) tempUL); break; case 'T': /* Specify thread count */ argError = uLongArg(&tempUL, optarg, THREAD_COUNT_MIN, THREAD_COUNT_MAX); ctx->threads = (unsigned int) tempUL; break; case 'v': /* Output log to stderr */ vFlag = true; setLogVerbosity(true); break; case 'z': /* Maximum memory usage in MB */ argError = stringToMemory(&ctx->mem, optarg, MEMORY_MIN, MEMORY_MAX, &endptr, MEM_MB); if (argError == PARSE_ERANGE || argError == PARSE_EMIN || argError == PARSE_EMAX) { fprintf(stderr, "%s: -%c: Argument out of range, it must be between %zu B and %zu B\n", programName, opt, MEMORY_MIN, MEMORY_MAX); argError = PARSE_ERANGE; } break; case 'h': /* Display help message and exit */ return 1; case ':': opt = optopt; getoptErrorMessage(OPT_ENOARG, NULL); return -1; default: break; } if (argError == PARSE_ERANGE) /* Error message already outputted */ { getoptErrorMessage(OPT_NONE, NULL); return -1; } else if (argError != PARSE_SUCCESS) /* Error but no error message, yet */ { getoptErrorMessage(OPT_EARG, NULL); return -1; } } if (KFlag) { strncpy(ctx->logFilepath, tmpLogFilepath, sizeof(ctx->logFilepath)); ctx->logFilepath[sizeof(ctx->logFilepath) - 1] = '\0'; } if (ctx->logToFile && openLog(ctx->logFilepath)) { fprintf(stderr, "%s: -%c: Failed to open log file\n", programName, opt); getoptErrorMessage(OPT_NONE, NULL); return -1; } return 0; } /* Determine role in distributed network (if any) and allocate network object */ static NetworkCTX * parseNetworkOptions(int argc, char **argv) { int numberOfWorkers = 0; char ipAddress[IP_ADDR_STR_LEN_MAX]; NetworkCTX *network = NULL; LANStatus mode = LAN_NONE; struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons(PORT_DEFAULT), }; optind = 0; while ((opt = getopt_long(argc, argv, GETOPT_STRING, LONG_OPTIONS, NULL)) != -1) { ParseErr argError = PARSE_SUCCESS; unsigned long tempUL = 0; switch (opt) { case 'g': /* Initialise as a worker for distributed computation */ if (mode != LAN_NONE) { fprintf(stderr, "%s: -%c: Option mutually exclusive with -%c\n", programName, opt, 'G'); getoptErrorMessage(OPT_NONE, NULL); return NULL; } if (validateIPAddress(optarg)) { getoptErrorMessage(OPT_EARG, NULL); return NULL; } strncpy(ipAddress, optarg, sizeof(ipAddress)); ipAddress[sizeof(ipAddress) - 1] = '\0'; if (inet_pton(AF_INET, ipAddress, &addr.sin_addr) != 1) { getoptErrorMessage(OPT_ERROR, NULL); return NULL; } mode = LAN_WORKER; break; case 'G': /* Initialise as a master for distributed computation */ if (mode != LAN_NONE) { fprintf(stderr, "%s: -%c: Option mutually exclusive with -%c\n", programName, opt, 'g'); getoptErrorMessage(OPT_NONE, NULL); return NULL; } argError = uLongArg(&tempUL, optarg, (unsigned int) WORKERS_MIN, (unsigned int) WORKERS_MAX); numberOfWorkers = (int) tempUL; addr.sin_addr.s_addr = htonl(INADDR_ANY); mode = LAN_MASTER; break; case 'p': /* Port number */ argError = uLongArg(&tempUL, optarg, PORT_MIN, PORT_MAX); addr.sin_port = htons((uint16_t) tempUL); break; default: break; } if (argError == PARSE_ERANGE) /* Error message already outputted */ { getoptErrorMessage(OPT_NONE, NULL); return NULL; } else if (argError != PARSE_SUCCESS) /* Error but no error message, yet */ { getoptErrorMessage(OPT_EARG, NULL); return NULL; } } network = createNetworkCTX(mode, numberOfWorkers, &addr); if (!network) return NULL; return network; } /* Get image parameters that are independent of the precision mode */ static int parseDiscreteOptions(PlotCTX *p, int argc, char **argv) { optind = 0; while ((opt = getopt_long(argc, argv, GETOPT_STRING, LONG_OPTIONS, NULL)) != -1) { ParseErr argError = PARSE_SUCCESS; unsigned long tempUL = 0; uintmax_t tempUIntMax = 0; switch (opt) { case 'c': /* Colour scheme of PPM image */ /* No enum value is negative or extends beyond ULONG_MAX (defined in colour.h) */ argError = uLongArg(&tempUL, optarg, 0UL, ULONG_MAX); p->colour.scheme = tempUL; /* Will return 1 if enum value of out range */ if (initialiseColourScheme(&p->colour, p->colour.scheme)) { fprintf(stderr, "%s: -%c: Invalid colour scheme\n", programName, opt); argError = PARSE_ERANGE; } break; case 'i': /* Maximum iteration count of function */ argError = uLongArg(&p->iterations, optarg, ITERATIONS_MIN, ITERATIONS_MAX); break; case 'o': /* Output image filename */ strncpy(p->plotFilepath, optarg, sizeof(p->plotFilepath)); p->plotFilepath[sizeof(p->plotFilepath) - 1] = '\0'; break; case 'r': /* Width of image */ argError = uIntMaxArg(&tempUIntMax, optarg, WIDTH_MIN, WIDTH_MAX); p->width = (size_t) tempUIntMax; break; case 's': /* Height of image */ argError = uIntMaxArg(&tempUIntMax, optarg, HEIGHT_MIN, HEIGHT_MAX); p->height = (size_t) tempUIntMax; break; default: break; } if (argError == PARSE_ERANGE) /* Error message already outputted */ { getoptErrorMessage(OPT_NONE, NULL); return -1; } else if (argError != PARSE_SUCCESS) /* Error but no error message, yet */ { getoptErrorMessage(OPT_EARG, NULL); return -1; } } return 0; } /* Get image parameters that are dependent on the precision mode */ static int parseContinuousOptions(PlotCTX *p, int argc, char **argv) { #ifdef MP_PREC initialiseArgRangesMP(); #endif if (parseMagnification(p, argc, argv)) return -1; optind = 0; while ((opt = getopt_long(argc, argv, GETOPT_STRING, LONG_OPTIONS, NULL)) != -1) { ParseErr argError = PARSE_SUCCESS; switch (opt) { case 'j': switch (p->precision) { case STD_PRECISION: argError = complexArg(&(p->c.c), optarg, C_MIN, C_MAX); break; case EXT_PRECISION: argError = complexArgExt(&(p->c.lc), optarg, C_MIN_EXT, C_MAX_EXT); break; #ifdef MP_PREC case MUL_PRECISION: argError = complexArgMP(p->c.mpc, optarg, C_MIN_MP, C_MAX_MP); break; #endif default: argError = PARSE_EERR; break; } break; case 'm': switch (p->precision) { case STD_PRECISION: argError = complexArg(&(p->minimum.c), optarg, COMPLEX_MIN, COMPLEX_MAX); break; case EXT_PRECISION: argError = complexArgExt(&(p->minimum.lc), optarg, COMPLEX_MIN_EXT, COMPLEX_MAX_EXT); break; #ifdef MP_PREC case MUL_PRECISION: argError = complexArgMP(p->minimum.mpc, optarg, NULL, NULL); break; #endif default: argError = PARSE_EERR; break; } break; case 'M': switch (p->precision) { case STD_PRECISION: argError = complexArg(&(p->maximum.c), optarg, COMPLEX_MIN, COMPLEX_MAX); break; case EXT_PRECISION: argError = complexArgExt(&(p->maximum.lc), optarg, COMPLEX_MIN_EXT, COMPLEX_MAX_EXT); break; #ifdef MP_PREC case MUL_PRECISION: argError = complexArgMP(p->maximum.mpc, optarg, NULL, NULL); break; #endif default: argError = PARSE_EERR; break; } break; default: break; } if (argError == PARSE_ERANGE) /* Error message already outputted */ { getoptErrorMessage(OPT_NONE, NULL); #ifdef MP_PREC freeArgRangesMP(); #endif return -1; } else if (argError != PARSE_SUCCESS) /* Error but no error message, yet */ { getoptErrorMessage(OPT_EARG, NULL); #ifdef MP_PREC freeArgRangesMP(); #endif return -1; } } #ifdef MP_PREC freeArgRangesMP(); #endif return 0; } /* Do one getopt pass to get the plot type */ static PlotType parsePlotType(int argc, char **argv) { PlotType plot = PLOT_MANDELBROT; optind = 0; while ((opt = getopt_long(argc, argv, GETOPT_STRING, LONG_OPTIONS, NULL)) != -1) { /* Plot a Julia set with specified constant */ if (opt == 'j') plot = PLOT_JULIA; } return plot; } /* Do one getopt pass to get the plot type (default is Mandelbrot) */ static OutputType parseOutputType(int argc, char **argv) { OutputType output = OUTPUT_PNM; bool oFlag = false, tFlag = false; optind = 0; while ((opt = getopt_long(argc, argv, GETOPT_STRING, LONG_OPTIONS, NULL)) != -1) { if (opt == 'o') /* Output image filename */ { if (tFlag) { fprintf(stderr, "%s: -%c: Option mutually exclusive with -%c\n", programName, opt, 't'); getoptErrorMessage(OPT_NONE, NULL); return OUTPUT_NONE; } oFlag = true; } else if (opt == 't') /* Output plot to stdout */ { if (oFlag) { fprintf(stderr, "%s: -%c: Option mutually exclusive with -%c\n", programName, opt, 'o'); getoptErrorMessage(OPT_NONE, NULL); return OUTPUT_NONE; } tFlag = true; output = OUTPUT_TERMINAL; } } return output; } /* Do one getopt pass to set the image centre and magnification amount */ static int parseMagnification(PlotCTX *p, int argc, char **argv) { optind = 0; while ((opt = getopt_long(argc, argv, GETOPT_STRING, LONG_OPTIONS, NULL)) != -1) { if (opt == 'x') /* Centre coordinate and magnification of plot */ { ParseErr argError = PARSE_EERR; if (p->precision == STD_PRECISION) { argError = magArg(p, optarg, COMPLEX_MIN, COMPLEX_MAX, MAGNIFICATION_MIN, MAGNIFICATION_MAX); } else if (p->precision == EXT_PRECISION) { argError = magArgExt(p, optarg, COMPLEX_MIN_EXT, COMPLEX_MAX_EXT, MAGNIFICATION_MIN, MAGNIFICATION_MAX); } #ifdef MP_PREC else if (p->precision == MUL_PRECISION) { argError = magArgMP(p, optarg, NULL, NULL, MAGNIFICATION_MIN_EXT, MAGNIFICATION_MAX_EXT); } #endif if (argError == PARSE_ERANGE) /* Error message already outputted */ { getoptErrorMessage(OPT_NONE, NULL); return -1; } else if (argError != PARSE_SUCCESS) /* Error but no error message, yet */ { getoptErrorMessage(OPT_EARG, NULL); return -1; } } } return 0; }
31.235049
129
0.515941
[ "object" ]
4f0d5bad4acd57342a18737089e60ea2268f048a
1,972
h
C
client/OAIEzsigntemplatepackage_createObject_v1_Response_mPayload.h
ezmaxinc/eZmax-SDK-cpp-qt5-client
70cc5ea2bccba1a7c192f88b15bee8225dbb3d01
[ "MIT" ]
null
null
null
client/OAIEzsigntemplatepackage_createObject_v1_Response_mPayload.h
ezmaxinc/eZmax-SDK-cpp-qt5-client
70cc5ea2bccba1a7c192f88b15bee8225dbb3d01
[ "MIT" ]
null
null
null
client/OAIEzsigntemplatepackage_createObject_v1_Response_mPayload.h
ezmaxinc/eZmax-SDK-cpp-qt5-client
70cc5ea2bccba1a7c192f88b15bee8225dbb3d01
[ "MIT" ]
null
null
null
/** * eZmax API Definition (Full) * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.7 * Contact: support-api@ezmax.ca * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ /* * OAIEzsigntemplatepackage_createObject_v1_Response_mPayload.h * * Payload for POST /1/object/ezsigntemplatepackage */ #ifndef OAIEzsigntemplatepackage_createObject_v1_Response_mPayload_H #define OAIEzsigntemplatepackage_createObject_v1_Response_mPayload_H #include <QJsonObject> #include <QList> #include "OAIEnum.h" #include "OAIObject.h" namespace OpenAPI { class OAIEzsigntemplatepackage_createObject_v1_Response_mPayload : public OAIObject { public: OAIEzsigntemplatepackage_createObject_v1_Response_mPayload(); OAIEzsigntemplatepackage_createObject_v1_Response_mPayload(QString json); ~OAIEzsigntemplatepackage_createObject_v1_Response_mPayload() override; QString asJson() const override; QJsonObject asJsonObject() const override; void fromJsonObject(QJsonObject json) override; void fromJson(QString jsonString) override; QList<qint32> getAPkiEzsigntemplatepackageId() const; void setAPkiEzsigntemplatepackageId(const QList<qint32> &a_pki_ezsigntemplatepackage_id); bool is_a_pki_ezsigntemplatepackage_id_Set() const; bool is_a_pki_ezsigntemplatepackage_id_Valid() const; virtual bool isSet() const override; virtual bool isValid() const override; private: void initializeModel(); QList<qint32> a_pki_ezsigntemplatepackage_id; bool m_a_pki_ezsigntemplatepackage_id_isSet; bool m_a_pki_ezsigntemplatepackage_id_isValid; }; } // namespace OpenAPI Q_DECLARE_METATYPE(OpenAPI::OAIEzsigntemplatepackage_createObject_v1_Response_mPayload) #endif // OAIEzsigntemplatepackage_createObject_v1_Response_mPayload_H
31.301587
93
0.807302
[ "object" ]
4f17808e2715670419c1a65297cf38c59ec26506
14,728
h
C
Project/Platformer/Source/PlayerMovement.h
Deklyn-Palmer/Kross-Engine-Game
6ea927a4ef2407334ac3bcb5f80bf82bfe5648be
[ "Apache-2.0" ]
null
null
null
Project/Platformer/Source/PlayerMovement.h
Deklyn-Palmer/Kross-Engine-Game
6ea927a4ef2407334ac3bcb5f80bf82bfe5648be
[ "Apache-2.0" ]
null
null
null
Project/Platformer/Source/PlayerMovement.h
Deklyn-Palmer/Kross-Engine-Game
6ea927a4ef2407334ac3bcb5f80bf82bfe5648be
[ "Apache-2.0" ]
null
null
null
#pragma once #include <Kross.h> #include "Health.h" #include "bgAudioManager.h" #include "DonutMovement.h" using namespace Kross; class PlayerMovement : public Script { public: PlayerMovement() { /* Every Script Must do this! */ m_Name = "PlayerMovement"; }; ~PlayerMovement() {}; Object* m_Gun = nullptr; Window* m_Window = nullptr; Health* m_Health = nullptr; Object* m_Camera = nullptr; Animator* m_Animator = nullptr; Rigidbody2D* m_RigidBody = nullptr; AudioPlayer* m_AudioPlayer = nullptr; TextRenderer* m_TextRenderer = nullptr; PlayerController* m_Controller = nullptr; SpriteRenderer* m_SpriteRenderer = nullptr; Vector2 m_GunOffset = Vector2(0.0f, -0.11f); Vector2 m_TextRendererOffset = Vector2(0.0f, 1.5f); std::vector<SpriteRenderer*> m_HealthRenderers = std::vector<SpriteRenderer*>(); std::vector<Sprite*> m_HealthSprites = std::vector<Sprite*>(); Object* m_TopBar = nullptr; Object* m_BottomBar = nullptr; Sprite* m_HitSprite = nullptr; std::vector<AudioPlayer*> m_AudioPlayers; int m_ControllerID = 0; float m_VelocityThreshold = 0.05f; float m_CameraShakeMagnitudeMax = 0.025f; float m_CameraShakeMagnitude = 0.0f; float m_ShakeCoolDownTime = 0.1f; float m_ShakeCoolDownTimeElapsed = 0.0f; float m_GracePeriodTime = 0.5f; float m_GracePeriodTimeElapsed = 0.0f; float m_EndGameTimer = 0.0f; float m_EndGameTimerMax = 5.0f; float m_EndGameTransitionTimer = 0.0f; float m_EndGameTransitionTimerMax = 1.5f; bool m_ShakeCamera = false; bool m_IsHurt = false; bool m_VisualHurt = false; bool m_MoveCinematicBars = false; bool m_EndTriggered = false; Script* Duplicate() override { return KROSS_NEW PlayerMovement(); } void Start() override { /* Grab All of the Local Components. */ m_Health = GetComponent<Health>(); m_Animator = GetComponent<Animator>(); m_RigidBody = GetComponent<Rigidbody2D>(); m_AudioPlayer = GetComponent<AudioPlayer>(); m_Controller = GetComponent<PlayerController>(); m_SpriteRenderer = GetComponent<SpriteRenderer>(); /* Grab External Object Related things. */ m_TextRenderer = SceneManager::GetScene()->FindObject("Text")->GetComponent<TextRenderer>(); m_Gun = SceneManager::GetScene()->FindObject("Gun"); m_Camera = SceneManager::GetScene()->GetCamera(); m_HitSprite = ResourceManager::GetResource<Sprite>("Marshall-Mellow3-2"); /* Get the Health Renderers. */ m_HealthRenderers.push_back(SceneManager::GetScene()->FindObject("UIHealth-0")->GetComponent<SpriteRenderer>()); m_HealthRenderers.push_back(SceneManager::GetScene()->FindObject("UIHealth-1")->GetComponent<SpriteRenderer>()); m_HealthRenderers.push_back(SceneManager::GetScene()->FindObject("UIHealth-2")->GetComponent<SpriteRenderer>()); m_HealthRenderers.push_back(SceneManager::GetScene()->FindObject("UIHealth-3")->GetComponent<SpriteRenderer>()); m_HealthRenderers.push_back(SceneManager::GetScene()->FindObject("UIHealth-4")->GetComponent<SpriteRenderer>()); m_HealthSprites.push_back(ResourceManager::GetResource<Sprite>("UI0-0")); m_HealthSprites.push_back(ResourceManager::GetResource<Sprite>("UI1-1")); m_HealthSprites.push_back(ResourceManager::GetResource<Sprite>("UI2-0")); m_AudioPlayers = GetComponents<AudioPlayer>(); /* End Scene Stuff. */ m_TopBar = SceneManager::GetScene()->FindObject("Bar-Top"); m_BottomBar = SceneManager::GetScene()->FindObject("Bar-Bottom"); /* Grab the Window. */ m_Window = Application::GetWindow(); /* See if a Controller is Connected. */ m_ControllerID = -1; //Input::GetAvalibleController(); } void Update() override { /* Create a Base Input Variable. */ Vector2 input = Vector2(0.0f); Vector2 jumpDir = Vector2(0.0f); /* if the Controller is Connected. */ if (Input::ControllerConnected(m_ControllerID)) { /* Grab it's Input. */ input = Vector2(Input::GetControllerAxis(m_ControllerID, Controller::LeftStickHorizontal, 0.1f), Input::GetControllerAxis(m_ControllerID, Controller::LeftStickVertical, 0.1f)); jumpDir = Vector2(0.0f, (float)Input::GetControllerButtonPressed(m_ControllerID, Controller::A)); } /* Use Keyboard and Mouse instead. */ else { /* Keep Checking if a Controller Gets Connected. */ m_ControllerID = Input::GetAvalibleController(); /* Grab the Input needed. */ input = Vector2(Input::GetAxis(Axis::KeyboardHorizontal), Input::GetAxis(Axis::KeyboardVertical)); jumpDir = Vector2(0.0f, (float)glm::sign(Input::GetKeyPressed(Key::Space) + Input::GetKeyPressed(Key::W) + Input::GetKeyPressed(Key::UpArrow))); } /* If the Object isn't at the End of a Level. */ if (!m_EndTriggered) { /* Move the Player. */ VisualUpdate(input); m_Controller->Move(input); RigidbodyState rbState = m_RigidBody->GetRigidbodyState(); if(rbState != RigidbodyState::Jumping && rbState != RigidbodyState::Falling && rbState != RigidbodyState::Underwater && jumpDir != Vector2(0.0f)) { m_AudioPlayers[0]->Play(); } m_Controller->Jump(jumpDir); } /* Lerp the Camera's Position to the Players. */ m_Camera->m_Transform->m_Position = Math::Lerp(m_Camera->m_Transform->m_Position, m_GameObject->m_Transform->m_Position, Time::GetDeltaTime() * 4.0f); /* --- GUN RELATED THINGS --- */ /* If the Gun Obejct Exists. */ if (m_Gun) { /* Grab the True Offset. */ Vector2 trueOffset; if (m_SpriteRenderer->GetFlipX()) { trueOffset = Vector2(-1.0f, 1.0f); } else { trueOffset = Vector2(1.0f, 1.0f); } /* Set the Guns Position based on the true offset. */ m_Gun->m_Transform->m_Position = m_GameObject->m_Transform->m_Position + (m_GunOffset * trueOffset); } /* -------------------------- */ /* ----- END GAME STUFF ----- */ if (!m_EndTriggered) { if (m_GameObject->m_Transform->m_Position.x > 154.0f && m_Health->GetHealth() > 0.0f) { m_TextRenderer->SetText("Level Cleared!"); m_MoveCinematicBars = true; m_EndTriggered = true; } else if(m_Health->GetHealth() <= 0.0f) { m_TextRenderer->SetText("Game Over!"); m_MoveCinematicBars = true; m_EndTriggered = true; } else if (SceneManager::GetScene()->GetName() == "Tute" && m_GameObject->m_Transform->m_Position.x > 29.9f) { m_TextRenderer->SetText("Tutorial Completed!"); m_MoveCinematicBars = true; m_EndTriggered = true; } if (SceneManager::GetScene()->GetName() != "Tute") { /* Clamp the Camera Position. */ m_Camera->m_Transform->m_Position.x = glm::clamp(m_Camera->m_Transform->m_Position.x, -1.25f, 215.75f); m_Camera->m_Transform->m_Position.y = glm::clamp(m_Camera->m_Transform->m_Position.y, -1.75f, 1.55f); } else { /* Clamp the Camera Position. */ m_Camera->m_Transform->m_Position.x = glm::clamp(m_Camera->m_Transform->m_Position.x, -1.25f, 26.5f); m_Camera->m_Transform->m_Position.y = glm::clamp(m_Camera->m_Transform->m_Position.y, -1.75f, 1.55f); } } else { /* End Game Timer. */ float t = m_EndGameTransitionTimer / m_EndGameTransitionTimerMax; if (m_EndGameTimer < m_EndGameTimerMax) m_EndGameTimer += Time::GetDeltaTime(); if (m_EndGameTransitionTimer < m_EndGameTransitionTimerMax) m_EndGameTransitionTimer += Time::GetDeltaTime(); /* Move The Bars to the Camera's Position to move. */ if (m_MoveCinematicBars) { m_TopBar->m_Transform->m_Position = m_Camera->m_Transform->m_Position + Vector2(0.0f, 5.0f); m_BottomBar->m_Transform->m_Position = m_Camera->m_Transform->m_Position + Vector2(0.0f, -5.0f); m_MoveCinematicBars = false; } /* Zoom Camera. */ Camera* camera = m_Camera->GetComponent<Camera>(); camera->SetSize(Math::Lerp(camera->GetSize(), 3.0f, t)); /* Change the Bar Colour. */ Colour barColour = Math::Lerp(Vector4(0.0f), Vector4(0.0f, 0.0f, 0.0f, 1.0f), t); m_TopBar->m_Transform->m_Position = Math::Lerp(m_TopBar->m_Transform->m_Position, m_Camera->m_Transform->m_Position + Vector2(0.0f, 1.25f), t); m_BottomBar->m_Transform->m_Position = Math::Lerp(m_BottomBar->m_Transform->m_Position, m_Camera->m_Transform->m_Position + Vector2(0.0f, -1.25f), t); m_BottomBar->GetComponent<SpriteRenderer>()->SetColour(barColour); m_TopBar->GetComponent<SpriteRenderer>()->SetColour(barColour); /* Move Text. */ m_TextRenderer->m_GameObject->m_Transform->m_Position = m_Camera->m_Transform->m_Position + Vector2(0.1f, 0.5f); /* Set Text Colour. */ Colour textColour = Math::Lerp(m_TextRenderer->GetColour(), Vector4(1.0f), t); m_TextRenderer->SetColour(textColour); /* End Level Transition. */ if (m_EndGameTimer >= m_EndGameTimerMax) { if (SceneManager::GetScene()->GetName() != "Tute") { leaveLevel = true; SceneManager::SetScene("Assets/Scenes/Menu.kscn"); } else { SceneManager::SetScene("Assets/Scenes/Main.kscn"); } } } /* --------------------------- */ /* Camera Shake. */ if (m_CameraShakeMagnitude > 0.0f) { m_Camera->m_Transform->m_Position.x += Random::GetRandomRange(-m_CameraShakeMagnitude, m_CameraShakeMagnitude); m_Camera->m_Transform->m_Position.y += Random::GetRandomRange(-m_CameraShakeMagnitude, m_CameraShakeMagnitude); } if (m_ShakeCamera) { m_CameraShakeMagnitude = m_CameraShakeMagnitudeMax; m_ShakeCoolDownTimeElapsed = 0.0f; } else { if (m_ShakeCoolDownTimeElapsed < m_ShakeCoolDownTime && m_CameraShakeMagnitude > 0.0f) { m_ShakeCoolDownTimeElapsed += Time::GetDeltaTime(); m_CameraShakeMagnitude = m_CameraShakeMagnitudeMax * (1.0f - (m_ShakeCoolDownTime / m_ShakeCoolDownTimeElapsed)); } else if (m_CameraShakeMagnitude <= 0.0f) { m_ShakeCoolDownTimeElapsed = 0.0f; } } /* --------- HEALTH ---------- */ if (m_Health) { float health = m_Health->GetHealth(); if (health >= 10.0f) m_HealthRenderers[4]->GetMaterial()->SetDiffuse(m_HealthSprites[0]); else if (health >= 9.0f) m_HealthRenderers[4]->GetMaterial()->SetDiffuse(m_HealthSprites[1]); else if (health <= 8.0f) m_HealthRenderers[4]->GetMaterial()->SetDiffuse(m_HealthSprites[2]); if (health >= 8.0f) m_HealthRenderers[3]->GetMaterial()->SetDiffuse(m_HealthSprites[0]); else if (health >= 7.0f) m_HealthRenderers[3]->GetMaterial()->SetDiffuse(m_HealthSprites[1]); else if (health <= 6.0f) m_HealthRenderers[3]->GetMaterial()->SetDiffuse(m_HealthSprites[2]); if (health >= 6.0f) m_HealthRenderers[2]->GetMaterial()->SetDiffuse(m_HealthSprites[0]); else if (health >= 5.0f) m_HealthRenderers[2]->GetMaterial()->SetDiffuse(m_HealthSprites[1]); else if (health <= 4.0f) m_HealthRenderers[2]->GetMaterial()->SetDiffuse(m_HealthSprites[2]); if (health >= 4.0f) m_HealthRenderers[1]->GetMaterial()->SetDiffuse(m_HealthSprites[0]); else if (health >= 3.0f) m_HealthRenderers[1]->GetMaterial()->SetDiffuse(m_HealthSprites[1]); else if (health <= 2.0f) m_HealthRenderers[1]->GetMaterial()->SetDiffuse(m_HealthSprites[2]); if (health >= 2.0f) m_HealthRenderers[0]->GetMaterial()->SetDiffuse(m_HealthSprites[0]); else if (health >= 1.0f) m_HealthRenderers[0]->GetMaterial()->SetDiffuse(m_HealthSprites[1]); else if (health <= 0.0f) m_HealthRenderers[0]->GetMaterial()->SetDiffuse(m_HealthSprites[2]); } /* --------------------------- */ if (!m_IsHurt) { for (b2ContactEdge* contact = m_RigidBody->GetBody()->GetContactList(); contact; contact = contact->next) { if (contact->contact->IsTouching()) { Object* obj = (Object*)contact->other->GetUserData(); if (obj == m_GameObject) continue; if (obj->GetName().find("Enemy") != std::string::npos) { if (DonutMovement* dm = obj->GetComponent<DonutMovement>()) { if (!dm->dead && Physics::GetCollisionNormal(contact->contact) != Vector2(0.0f, 1.0f)) { m_Health->TakeDamage(1.0f); Vector2 knockbackDirection = glm::normalize(m_GameObject->m_Transform->m_Position - obj->m_Transform->m_Position); m_RigidBody->OnApplyImpulse(knockbackDirection * 0.35f); m_AudioPlayers[2]->Play(); m_IsHurt = true; m_VisualHurt = true; break; } } } } } } else { if (m_GracePeriodTimeElapsed >= m_GracePeriodTime * 0.25f) m_VisualHurt = false; if (m_GracePeriodTimeElapsed < m_GracePeriodTime) m_GracePeriodTimeElapsed += Time::GetDeltaTime(); else { m_GracePeriodTimeElapsed = 0.0f; m_IsHurt = false; } } } /*! Moves the Player Based on Input. */ void VisualUpdate(Vector2 input) { /* Animation Setting.*/ if (!m_VisualHurt) { if (!m_Animator->GetCurrentAnimation()->IsPlaying()) { m_Animator->Play(); } /* If the Rigidbody's Velocity in the Vertical direction is inside of the threshold. */ if (m_RigidBody->GetBody()->GetLinearVelocity().y <= m_VelocityThreshold && m_RigidBody->GetBody()->GetLinearVelocity().y >= -m_VelocityThreshold) { /* If the Rigidbody's Velocity in the Horizontal direction is inside of the threshold. */ if (m_RigidBody->GetBody()->GetLinearVelocity().x <= m_VelocityThreshold && m_RigidBody->GetBody()->GetLinearVelocity().x >= -m_VelocityThreshold) { /* Set to the Idle Animation. */ m_Animator->SetCurrentAnimation(0); } /* If the Horizontal Velocity has breached the threshold. */ else { /* Set to the Walk Animation. */ m_Animator->SetCurrentAnimation(1); } } /* If the Vertical Velocity has breached the threshold. */ else { /* If moving upwards. */ if (m_RigidBody->GetBody()->GetLinearVelocity().y >= m_VelocityThreshold) { /* Set to the Jump Up Animation. */ m_Animator->SetCurrentAnimation(2); } /* If moving downwards. */ else if (m_RigidBody->GetBody()->GetLinearVelocity().y <= -m_VelocityThreshold) { /* Set to the Jump Down Animation. */ m_Animator->SetCurrentAnimation(3); } } } else { m_Animator->Pause(); m_SpriteRenderer->GetMaterial()->SetDiffuse(m_HitSprite); } /* Flip Based on the Input x Value. */ if (input.x > 0) { /* Face Right. */ m_SpriteRenderer->SetFlipX(false); } else if (input.x < 0) { /* Face Left. */ m_SpriteRenderer->SetFlipX(true); } } };
33.472727
180
0.661733
[ "object", "vector" ]
4f236d20feeb4af893e8ca3b10200c7e548f7f9f
5,687
h
C
aws-cpp-sdk-securityhub/include/aws/securityhub/model/AwsEcsServiceCapacityProviderStrategyDetails.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-securityhub/include/aws/securityhub/model/AwsEcsServiceCapacityProviderStrategyDetails.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-securityhub/include/aws/securityhub/model/AwsEcsServiceCapacityProviderStrategyDetails.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-02-28T21:36:42.000Z
2022-02-28T21:36:42.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/securityhub/SecurityHub_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace SecurityHub { namespace Model { /** * <p>Strategy item for the capacity provider strategy that the service * uses.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/securityhub-2018-10-26/AwsEcsServiceCapacityProviderStrategyDetails">AWS * API Reference</a></p> */ class AWS_SECURITYHUB_API AwsEcsServiceCapacityProviderStrategyDetails { public: AwsEcsServiceCapacityProviderStrategyDetails(); AwsEcsServiceCapacityProviderStrategyDetails(Aws::Utils::Json::JsonView jsonValue); AwsEcsServiceCapacityProviderStrategyDetails& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The minimum number of tasks to run on the capacity provider. Only one * strategy item can specify a value for <code>Base</code>.</p> <p>The value must * be between 0 and 100000.</p> */ inline int GetBase() const{ return m_base; } /** * <p>The minimum number of tasks to run on the capacity provider. Only one * strategy item can specify a value for <code>Base</code>.</p> <p>The value must * be between 0 and 100000.</p> */ inline bool BaseHasBeenSet() const { return m_baseHasBeenSet; } /** * <p>The minimum number of tasks to run on the capacity provider. Only one * strategy item can specify a value for <code>Base</code>.</p> <p>The value must * be between 0 and 100000.</p> */ inline void SetBase(int value) { m_baseHasBeenSet = true; m_base = value; } /** * <p>The minimum number of tasks to run on the capacity provider. Only one * strategy item can specify a value for <code>Base</code>.</p> <p>The value must * be between 0 and 100000.</p> */ inline AwsEcsServiceCapacityProviderStrategyDetails& WithBase(int value) { SetBase(value); return *this;} /** * <p>The short name of the capacity provider.</p> */ inline const Aws::String& GetCapacityProvider() const{ return m_capacityProvider; } /** * <p>The short name of the capacity provider.</p> */ inline bool CapacityProviderHasBeenSet() const { return m_capacityProviderHasBeenSet; } /** * <p>The short name of the capacity provider.</p> */ inline void SetCapacityProvider(const Aws::String& value) { m_capacityProviderHasBeenSet = true; m_capacityProvider = value; } /** * <p>The short name of the capacity provider.</p> */ inline void SetCapacityProvider(Aws::String&& value) { m_capacityProviderHasBeenSet = true; m_capacityProvider = std::move(value); } /** * <p>The short name of the capacity provider.</p> */ inline void SetCapacityProvider(const char* value) { m_capacityProviderHasBeenSet = true; m_capacityProvider.assign(value); } /** * <p>The short name of the capacity provider.</p> */ inline AwsEcsServiceCapacityProviderStrategyDetails& WithCapacityProvider(const Aws::String& value) { SetCapacityProvider(value); return *this;} /** * <p>The short name of the capacity provider.</p> */ inline AwsEcsServiceCapacityProviderStrategyDetails& WithCapacityProvider(Aws::String&& value) { SetCapacityProvider(std::move(value)); return *this;} /** * <p>The short name of the capacity provider.</p> */ inline AwsEcsServiceCapacityProviderStrategyDetails& WithCapacityProvider(const char* value) { SetCapacityProvider(value); return *this;} /** * <p>The relative percentage of the total number of tasks that should use the * capacity provider.</p> <p>If no weight is specified, the default value is 0. At * least one capacity provider must have a weight greater than 0.</p> <p>The value * can be between 0 and 1000.</p> */ inline int GetWeight() const{ return m_weight; } /** * <p>The relative percentage of the total number of tasks that should use the * capacity provider.</p> <p>If no weight is specified, the default value is 0. At * least one capacity provider must have a weight greater than 0.</p> <p>The value * can be between 0 and 1000.</p> */ inline bool WeightHasBeenSet() const { return m_weightHasBeenSet; } /** * <p>The relative percentage of the total number of tasks that should use the * capacity provider.</p> <p>If no weight is specified, the default value is 0. At * least one capacity provider must have a weight greater than 0.</p> <p>The value * can be between 0 and 1000.</p> */ inline void SetWeight(int value) { m_weightHasBeenSet = true; m_weight = value; } /** * <p>The relative percentage of the total number of tasks that should use the * capacity provider.</p> <p>If no weight is specified, the default value is 0. At * least one capacity provider must have a weight greater than 0.</p> <p>The value * can be between 0 and 1000.</p> */ inline AwsEcsServiceCapacityProviderStrategyDetails& WithWeight(int value) { SetWeight(value); return *this;} private: int m_base; bool m_baseHasBeenSet; Aws::String m_capacityProvider; bool m_capacityProviderHasBeenSet; int m_weight; bool m_weightHasBeenSet; }; } // namespace Model } // namespace SecurityHub } // namespace Aws
35.993671
154
0.685599
[ "model" ]
4f27a2b0a8e256d32b13b63989249aaf38df65b8
5,456
h
C
hackathon/zhi/snake_tracing_cmake/TracingView.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
8
2016-07-22T11:24:19.000Z
2021-04-10T04:22:31.000Z
Tracing/TheTracingSystem/TracingView.h
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
1
2016-12-03T05:33:13.000Z
2016-12-03T05:33:13.000Z
Tracing/TheTracingSystem/TracingView.h
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
7
2016-07-21T07:39:17.000Z
2020-01-29T02:03:27.000Z
/*========================================================================= Copyright 2009 Rensselaer Polytechnic Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ /*========================================================================= Program: Open Snake Tracing System Autohr: Yu Wang Email: wangy15@rpi.edu Language: C++ Date: $Date: $ Version: $Revision: 0.00 $ =========================================================================*/ #ifndef TRACINGVIEW_H #define TRACINGVIEW_H #include <QtGui> #include "ScatterView.h" #include "OpenSnakeTracer.h" struct EditValidation { float TP, FP, FN, precision, recall; int numBranch, numSplit, numDelete, numMerge; }; class TracingView : public QWidget { Q_OBJECT //Q_PROPERTY(QColor penColor READ penColor WRITE setPenColor) //Q_PROPERTY(QImage Image READ Image WRITE setImage) Q_PROPERTY(int zoomFactor READ zoomFactor WRITE setZoomFactor) public: TracingView(QWidget *parent = 0); void setPenColor(const QColor &newColor); void setZoomFactor(int newZoom); int zoomFactor() const { return zoom; } void drawSnakes(QPainter *painter); void drawSeedSnakes(QPainter *painter); void drawSelectedSnakes(QPainter *painter); void drawDeletedSnakes(QPainter *painter); void drawTracingSnakes(QPainter *painter); void drawSnakeTree(QPainter *painter); void drawSnakeTree_SWC(QPainter *painter); void drawInterestPoints(QPainter *painter); void drawClickedPoint(QPainter *painter); void drawSeedSnake(QPainter *painter); void drawSelectedSeeds(QPainter *painter); void drawSeeds(QPainter *painter); void drawSelection(QPainter *painter); void drawPath(QPainter *painter); void deselect(); vnl_vector<int> getSelectedSnakes(); void drawArrow( Point3D pt, Point3D ppt, double sze, const QPen& pen ); void setModel(QStandardItemModel *md, ObjectSelection * sels = NULL); QStandardItemModel *model; QSize sizeHint() const; public slots: void zoomIn(); void zoomOut(); void normalSize(); void setNormalCursor(); void setPickingCursor(); void setDisplayImage(const QImage &newImage); void setImage(ImageOperation *IM); void setSnakes(SnakeListClass *S); void setSeedSnakes(SnakeListClass *s); void setSnakeTree(SnakeTree *s); void setSnakeTree_SWC(SnakeTree_SWC *s); void setInterestPoints(PointList3D pl); void setMontageView(bool in); void removeSnakeTree(); void removeInterestPoints(); void SnakesChanged(); void SnakesChanged(int); void removeSnakes(); void changeLineWidth(int); bool rootSnakeSelected(); Point3D getClickedPoint(); PointList3D getContour(); void deleteSnake(EditValidation *edits); void mergeSnake(EditValidation *edits); void createBranch(EditValidation *edits); void splitSnake(EditValidation *edits); void deleteSeed(); void invertSelection(); void setTracingSnake(SnakeClass s); void displaySeed(bool value); void displaySnake(bool value); void displayColorLine(bool value); void selectRegion(); void vtk_mousePress(double *picked_point, bool ctrl_pressed); void sync_selections_I(); //synchronize the selections of different views void sync_selections_II(); //synchronize the selections of different views signals: void selected(const QItemSelection &, QItemSelectionModel::SelectionFlags); void result_drawed(); void result_drawed1(); void manual_seed(PointList3D seed); void manual_path(PointList3D seed); void point_clicked(Point3D pt); //void worms_changed( Worms); protected: void paintEvent(QPaintEvent *event); void mousePressEvent(QMouseEvent *event); void mouseDoubleClickEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void keyPressEvent(QKeyEvent *event ); void keyReleaseEvent(QKeyEvent *event ); private: void setImagePixel(const QPoint &pos, bool opaque); QRect pixelRect(int i, int j) const; ImageOperation *IM; SnakeListClass *SnakeList; SnakeListClass *SeedSnakes; SnakeClass snake; bool seed_display; bool snake_display; bool color_line_display; QColor curColor; QImage image; QImage display_image; bool tracing_snake; double zoom; ObjectSelection *snake_sels; ObjectSelection *snake_sels_table; //another selection for table and scatter plot ObjectSelection *seed_sels; Point3D click_point; PointList3D points; PointList3D contour; PointList3D path_points; int pathMode; // mode of picking path points PointList3D interest_points; bool interest_point_set; ObjectSelection *delete_sels; int selMode; QVector<QPoint> selectionRegion; //current boundary points for group selection SnakeTree *snake_tree; SnakeTree_SWC *snake_tree_swc; bool tree_set; bool tree_set_swc; bool montage_view; int radius_state; int LineWidth; //int iteration_num; }; #endif
27.417085
82
0.719941
[ "model" ]
4f2b99907890b3834bd53fb4040ea88492fdb939
720
h
C
kongxia/Views/User/chuzu/ZZRentDropdownMenuView.h
zuwome/kongxia
87f6f33410da1fedd315089c9a92917b5226125d
[ "MIT" ]
null
null
null
kongxia/Views/User/chuzu/ZZRentDropdownMenuView.h
zuwome/kongxia
87f6f33410da1fedd315089c9a92917b5226125d
[ "MIT" ]
1
2022-01-08T05:58:03.000Z
2022-01-08T05:58:03.000Z
kongxia/Views/User/chuzu/ZZRentDropdownMenuView.h
zuwome/kongxia
87f6f33410da1fedd315089c9a92917b5226125d
[ "MIT" ]
null
null
null
// // ZZRentDropdownMenuView.h // zuwome // // Created by angBiu on 16/6/15. // Copyright © 2016年 zz. All rights reserved. // /** * 选择地址下拉历史列表 */ #import <UIKit/UIKit.h> @class ZZRentDropdownModel; @protocol ZZRentDropdownMenuDelegate <NSObject> - (void)selectLocation:(ZZRentDropdownModel *)model; @end @interface ZZRentDropdownMenuView : UIView @property (nonatomic, weak) id<ZZRentDropdownMenuDelegate>delegate; @property (nonatomic, strong) ZZUser *user; - (instancetype)initWithFrame:(CGRect)frame user:(ZZUser *)user; @end @interface ZZRentDropdownMyLocationView : UIView @property (nonatomic, assign) double totalWidth; - (void)configureTitle:(NSString *)title distance:(double)distance; @end
19.459459
67
0.75
[ "model" ]
4f3136a414f6d144dbc8c0b0aa9d4320a90eb89f
2,325
h
C
Source/RobCoG/TestClasses/ForceFinger.h
yukilikespie/RobCoG_FleX-4.16
a6d1e8c0abb8ac1e36c5967cb886de8c154b2948
[ "BSD-3-Clause" ]
null
null
null
Source/RobCoG/TestClasses/ForceFinger.h
yukilikespie/RobCoG_FleX-4.16
a6d1e8c0abb8ac1e36c5967cb886de8c154b2948
[ "BSD-3-Clause" ]
null
null
null
Source/RobCoG/TestClasses/ForceFinger.h
yukilikespie/RobCoG_FleX-4.16
a6d1e8c0abb8ac1e36c5967cb886de8c154b2948
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017, Institute for Artificial Intelligence - University of Bremen #pragma once #include "CoreMinimal.h" #include "Animation/SkeletalMeshActor.h" #include "Components/ArrowComponent.h" #include "PhysicsEngine/ConstraintInstance.h" #include "Utilities/ForceFileWriter.h" #include "ForceFinger.generated.h" /** * */ UCLASS() class ROBCOG_API AForceFinger : public ASkeletalMeshActor { GENERATED_BODY() public: // Spring value to apply to the angular drive (Position strength) UPROPERTY(EditAnywhere, Category = "Finger|Drive Parameters") float Spring; // Damping value to apply to the angular drive (Velocity strength) UPROPERTY(EditAnywhere, Category = "Finger|Drive Parameters") float Damping; // Limit of the force that the angular drive can apply UPROPERTY(EditAnywhere, Category = "Finger|Drive Parameters") float ForceLimit; UPROPERTY(EditAnywhere, Category = "Finger|Force Parameters") bool bShowForceArrows; UPROPERTY(EditAnywhere, Category = "Finger|Force Logging") int32 NumberOfValuesToBeWritten; UPROPERTY(EditAnywhere, Category = "Finger|Force Logging") bool bLogForceIntoFile; AForceFinger(); // Called when the game starts or when spawned virtual void BeginPlay() override; // Called every frame virtual void Tick(float DeltaSeconds) override; private: FVector LastVelocity; FBodyInstance* MetacarpalBody; UArrowComponent* MetacarpalBodyArrow; FBodyInstance* ProximalBody; UArrowComponent* ProximalBodyArrow; FConstraintInstance* ProximalConstraint; UArrowComponent* ProximalForceArrow; FBodyInstance* IntermediateBody; UArrowComponent* IntermediateBodyArrow; FConstraintInstance* IntermediateConstraint; UArrowComponent* IntermediateForceArrow; FBodyInstance* DistalBody; UArrowComponent* DistalBodyArrow; FConstraintInstance* DistalConstraint; UArrowComponent* DistalForceArrow; TSharedPtr<ForceFileWriter> ForceFileWriterPtr; void InitializeOrientationTwistAndSwing(FConstraintInstance* Constraint, const FQuat & Quaternion); void InitializeVelocityTwistAndSwing(FConstraintInstance* Constraint, const FVector & Vector); void UpdateConstraintArrow(FConstraintInstance* const Constraint, UArrowComponent* const Arrow); void UpdateBodyArrow(FBodyInstance* const Body, UArrowComponent* const Arrow, const float DeltaTime); };
28.703704
102
0.805591
[ "vector" ]
4f32e4aba6d52c9ae9d67d15fa3a41705cc9b946
7,059
h
C
training/src/compiler/training/compiler/WorkflowDB.h
steelONIONknight/bolt
9bd3d08f2abb14435ca3ad0179889e48fa7e9b47
[ "MIT" ]
null
null
null
training/src/compiler/training/compiler/WorkflowDB.h
steelONIONknight/bolt
9bd3d08f2abb14435ca3ad0179889e48fa7e9b47
[ "MIT" ]
null
null
null
training/src/compiler/training/compiler/WorkflowDB.h
steelONIONknight/bolt
9bd3d08f2abb14435ca3ad0179889e48fa7e9b47
[ "MIT" ]
null
null
null
// Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef WORKFLOW_DB_H #define WORKFLOW_DB_H #include <training/system/Name.h> #include <unordered_map> #include "Workflow.h" namespace raul { /** * @brief Class to store information of tensor`s declaration * * Each tensor declaration is bound to layer and execution stage (forward, backward). * This information is stored into plain 1D array of TensorUsage and structured 3D table tensor name vs layer name vs `usage`. * `Usage` is an std::vector of size == 2 to store index from TensorUsage array. * * For example if tensor A from layer L used only in backward pass then [A][L][0] == std::numeric_limits<size_t>::max(), [A][L][1] == `index`. */ class WorkflowDB { public: struct TensorUsage { Name layerName; Name tensorName; WShape shape; ///< set for whole workflow (should be same) Workflow::Usage usage; ///< set for each usage location (might be different) Workflow::Mode mode; ///< set for each usage location (might be different) bool isOptimizeGraph; ///< set for whole workflow (should be same) bool isOptimizeMem; ///< set for whole workflow (should be same) bool isTrainable; ///< set for whole workflow (should be same) bool isZero; ///< set for each usage location (might be different) bool isCompress; ///< set for each usage location (might be different) LayerExecutionTarget layerExecutionTarget; }; WorkflowDB() : mTensorsTable{} , mLayersTable{} , mTensorNeeded{} { } /** * Cell of the 3d table * */ using DBCell = std::vector<size_t>; /** * 3d table of [tensor, layer, usage (forward | backward)] */ using TLTable = std::unordered_map<Name, std::unordered_map<Name, DBCell>>; /** * Check whether provided tensor with context is in database * * @param tensorName name of a tensor * @param layerName layer with the tensor * @param usage Training stage where tensor is used * @return true/false */ [[nodiscard]] bool isTensorExistsInTable(const Name& tensorName, const Name& layerName, Workflow::Usage usage) const; /** * Get table slice by key * * @param table target table * @param keyA search key * @return vector of names of the keys in the slice * * @tod(ck): is it really a slice? */ [[nodiscard]] Names getSlice(const TLTable& table, const Name& keyA) const; /** * Get cell of the search table (pair of indexes for forward and backward) * * @param table target table * @param keyA the first search key * @param keyB the second search key * @return Cell */ [[nodiscard]] DBCell getCell(const TLTable& table, const Name& keyA, const Name& keyB) const; /** * Return the first meet usage information of the tensor * * @param tensorName * @return */ [[nodiscard]] TensorUsage findFirstTensor(const Name& tensorName) const; /** * Check whether provided cell empty or not * * Function checks index stored in dictionary. If it goes out of array length * it means cell is empty. * * @param cell * @param usage * @return true/false * */ [[nodiscard]] bool isCellElementEmpty(const DBCell& cell, Workflow::Usage usage) const; /** * Check whether provided tensor declared in the database * * @param tensorName * @return true/false */ [[nodiscard]] bool isTensorDeclared(const Name& tensorName) const; /** * Getter to search table by tensor * @return Search table (read-only) * */ [[nodiscard]] const TLTable& getTensorsTable() const { return mTensorsTable; } /** * Getter to search table by tensor * @return Search table * */ TLTable& getTensorsTable() { return mTensorsTable; } /** * Getter to search table by layer * @return Search table (read-only) * */ [[nodiscard]] const TLTable& getLayersTable() const { return mLayersTable; } /** * Getter to search table by layer * @return Search table * */ TLTable& getLayersTable() { return mLayersTable; } /** * Getter to usage * * @param index Plain index * @return Usage (read-only) * */ [[nodiscard]] const TensorUsage& getUsage(size_t index) const; /** * Getter to usage * * @param index Plain index * @return Usage */ TensorUsage& getUsage(size_t index); /** * Add usage information to the workflow database * * @param usage Usage */ void addUsage(const TensorUsage& usage) { mTensorNeeded.push_back(usage); addTensorToTable(usage, mTensorsTable, usage.tensorName, usage.layerName); addTensorToTable(usage, mLayersTable, usage.layerName, usage.tensorName); } void chooseMaxShape(const Name& tensorName, WShape& shape); private: /** * Add usage information of the tensor to a search table * * @param tensorUsage usage of the tensor * @param table quick access table with structure [Tensor, Layer, Usage] or [Layer, Tensor, Usage] * @param keyA the first key in table (Tensor or Layer) * @param keyB the second key in table (Tensor or Layer) */ void addTensorToTable(const TensorUsage& tensorUsage, TLTable& table, const Name& keyA, const Name& keyB); void assignIndexes(const TensorUsage& tensorUsage, DBCell& indexes); private: TLTable mTensorsTable; ///< Search table: [Tensor, Layer, Usage] --> Index in storage aka mTensorNeeded TLTable mLayersTable; ///< Search table: [Layer, Tensor, Usage] --> Index in storage aka mTensorNeeded std::vector<TensorUsage> mTensorNeeded; ///< Storage of all workflow tensors }; } // raul namespace #endif // WORKFLOW_DB_H
33.140845
149
0.657884
[ "shape", "vector", "3d" ]
4f331b8af1fd44424dcc3cdf0de42b3ad643d7bd
380
h
C
FreelyHeath/Classes/consult/ResultViewController.h
XYGDeveloper/FreelyHealth_User
af0d8dbcf29bd39301292b299f331201c417a08c
[ "MIT" ]
1
2019-04-24T07:42:27.000Z
2019-04-24T07:42:27.000Z
FreelyHeath/Classes/consult/ResultViewController.h
XYGDeveloper/FreelyHealth_User
af0d8dbcf29bd39301292b299f331201c417a08c
[ "MIT" ]
null
null
null
FreelyHeath/Classes/consult/ResultViewController.h
XYGDeveloper/FreelyHealth_User
af0d8dbcf29bd39301292b299f331201c417a08c
[ "MIT" ]
null
null
null
// // ResultViewController.h // FreelyHeath // // Created by L on 2017/8/3. // Copyright © 2017年 深圳乐易住智能科技股份有限公司. All rights reserved. // #import <UIKit/UIKit.h> @class ASSModel; @interface ResultViewController : UIViewController @property (nonatomic,strong)NSString *id; @property (nonatomic,strong)ASSModel *model; @property (nonatomic,strong)NSString *redult; @end
16.521739
59
0.736842
[ "model" ]
4f3d24a7751335f41abf103c68fc2c8a27e48be4
1,090
h
C
include/RedRectangleTracker.h
DaxiongAI/Object-Tracking
b3070b60d843aa6b19243a99f1c074414f802b31
[ "BSD-3-Clause" ]
2
2020-04-07T06:45:55.000Z
2022-01-11T09:27:26.000Z
include/RedRectangleTracker.h
DaxiongAI/Object-Tracking
b3070b60d843aa6b19243a99f1c074414f802b31
[ "BSD-3-Clause" ]
null
null
null
include/RedRectangleTracker.h
DaxiongAI/Object-Tracking
b3070b60d843aa6b19243a99f1c074414f802b31
[ "BSD-3-Clause" ]
null
null
null
/* * File: RedRectangleTracker.h * Author: haikalpribadi * * Created on July 12, 2012, 6:58 PM */ #ifndef REDRECTANGLETRACKER_H #define REDRECTANGLETRACKER_H #include <ros/ros.h> #include <math.h> #include <image_transport/image_transport.h> #include <sensor_msgs/image_encodings.h> #include <cv_bridge/cv_bridge.h> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #define windowname "Square detection demo" class RedRectangleTracker { public: RedRectangleTracker(); virtual ~RedRectangleTracker(); private: ros::NodeHandle node_handle_; image_transport::ImageTransport img_transport_; image_transport::Subscriber img_sub_; int thresh, N; void imageCallback(const sensor_msgs::ImageConstPtr& message); double angle(cv::Point pt1, cv::Point pt2, cv::Point pt0); void findSquares(const cv::Mat& image, std::vector<std::vector<cv::Point> >& squares); void drawSquares(cv::Mat& image, const std::vector<std::vector<cv::Point> >& squares); }; #endif /* REDRECTANGLETRACKER_H */
27.25
90
0.737615
[ "vector" ]
4f3e18082d49a93630a4520127171e4da5e68036
15,960
h
C
ToolKit/Controls/Util/XTPMemFile.h
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
2
2018-03-30T06:40:08.000Z
2022-02-23T12:40:13.000Z
ToolKit/Controls/Util/XTPMemFile.h
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
null
null
null
ToolKit/Controls/Util/XTPMemFile.h
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
1
2020-08-11T05:48:02.000Z
2020-08-11T05:48:02.000Z
// XTPMemFile.h interface for the CXTPMemFile class. // // This file is a part of the XTREME CONTROLS MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// //{{AFX_CODEJOCK_PRIVATE #if !defined(__XTMEMFILE_H__) #define __XTMEMFILE_H__ //}}AFX_CODEJOCK_PRIVATE #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //=========================================================================== // Summary: // CXTPMemFile is a CMemFile derived class. It is used to create a CXTPMemFile // object to support memory files. // Remarks: // These memory files behave like disk files except that the file is stored // in RAM rather than on disk. A memory file is useful for fast temporary // storage or for transferring raw bytes or serialized objects between // independent processes. // // CXTPMemFile objects can automatically allocate their own memory, or you // can attach your own memory block to the CXTPMemFile object by calling // Attach. In either case, memory for growing the memory file automatically // is allocated in nGrowBytes-sized increments if 'nGrowBytes' is not zero. // // The memory block will automatically be deleted upon destruction of the // CXTPMemFile object if the memory was originally allocated by the CXTPMemFile // object. Otherwise, you are responsible for de-allocating the memory you // attached to the object. // // You can access the memory block through the pointer supplied when you // detach it from the CXTPMemFile object by calling Detach. // // The most common use of CXTPMemFile is to create a CXTPMemFile object and // use it by calling CFile member functions. Note that creating a CXTPMemFile // automatically opens it: you do not call CFile::Open, which is only used // for disk files. Because CXTPMemFile doesn't use a disk file, the data // member CFile::m_hFile is not used and has no meaning. // // The CFile member functions Duplicate, LockRange, and UnlockRange are // not implemented for CXTPMemFile. If you call these functions on a CXTPMemFile // object, you will get a CNotSupportedException. // // CXTPMemFile uses the run-time library functions malloc, realloc, and // free to allocate, reallocate, and deallocate memory and the intrinsic // memcpy to block copy memory when reading and writing. If you would like // to change this behavior or the behavior when CXTPMemFile grows a file, // derive your own class from CXTPMemFile and override the appropriate functions. //=========================================================================== class _XTP_EXT_CLASS CXTPMemFile : public CMemFile { public: //----------------------------------------------------------------------- // Summary: // Constructs a CXTPMemFile object. This overload opens an empty memory // file. Note that the file is opened by the constructor and that you // should not call CFile::Open. // Parameters: // nGrowBytes - The memory allocation increment in bytes. //----------------------------------------------------------------------- CXTPMemFile(UINT nGrowBytes = 1024); //----------------------------------------------------------------------- // Summary: // Constructs a CXTPMemFile object. This overload opens an empty memory // file. Note that the file is opened by the constructor and that you // should not call CFile::Open. // Parameters: // nGrowBytes - The memory allocation increment in bytes. // lpBuffer - Pointer to the buffer to be attached to CXTPMemFile. // nBufferSize - An integer that specifies the size of the buffer in bytes. //----------------------------------------------------------------------- CXTPMemFile(BYTE* lpBuffer, UINT nBufferSize, UINT nGrowBytes = 0); //----------------------------------------------------------------------- // Summary: // Constructs a CXTPMemFile object. This overload opens an empty memory // file. Note that the file is opened by the constructor and that you // should not call CFile::Open. // Parameters: // lpszFileName - A string that is the path to the desired file. The path can be relative, // absolute, or a network name (UNC). // uiOpenFlags - A UINT that defines the file's sharing and access mode. It specifies // the action to take when opening the file. You can combine options // by using the bitwise-OR (|) operator. One access permission and // one share option are required. The modeCreate and modeNoInherit modes // are optional. See the CFile constructor for a list of mode options. //----------------------------------------------------------------------- CXTPMemFile(LPCTSTR lpszFileName, UINT uiOpenFlags); //----------------------------------------------------------------------- // Summary: // Destroys a CXTPMemFile object, handles cleanup and deallocation //----------------------------------------------------------------------- virtual ~CXTPMemFile(); public: //----------------------------------------------------------------------- // Summary: // This member function forces any data remaining in the file buffer // to be written to the file. The use of Flush does not guarantee flushing // of CArchive buffers. If you are using an archive, call CArchive::Flush // first. //----------------------------------------------------------------------- virtual void Flush(); #if _MSC_VER > 1200 //MFC 7.0 using CMemFile::Open; #endif //----------------------------------------------------------------------- // Summary: // This member function opens and loads a physical File into memory. // Parameters: // lpszFileName - Specifies a NULL terminated string that is the path to the desired file. // nOpenFlags - Specifies a UINT that defines the sharing and access mode in the file. // It specifies the action to take when opening the file. You can combine // options by using the bitwise-OR (|) operator. One access permission // and one share option are required. The modeCreate and modeNoInherit // modes are optional. See the CFile constructor for a list of mode options. // pError - Specifies a pointer to an existing file-exception object that receives // the status of a failed operation. // Returns: // true if successful, or false if it fails. //----------------------------------------------------------------------- virtual BOOL Open(LPCTSTR lpszFileName, UINT nOpenFlags, CFileException* pError = NULL); //----------------------------------------------------------------------- // Summary: // This member function saves the contents of the memory to the disk // and closes it. //----------------------------------------------------------------------- virtual void Close(); //----------------------------------------------------------------------- // Summary: // This member function reads a string. // Parameters: // rString - A CString reference to an object to receive the string that is read. // Returns: // TRUE if successful, or FALSE if there is an error. //----------------------------------------------------------------------- virtual BOOL ReadString(CString& rString); //----------------------------------------------------------------------- // Summary: // This method writes data from a buffer to the file associated with // the CArchive object. The terminating null character, \0, is not written // to the file, nor is a newline character automatically written. // Parameters: // lpsz - Specifies a pointer to a buffer containing a null-terminated text // string. //----------------------------------------------------------------------- virtual void WriteString(LPCTSTR lpsz); #if _MSC_VER > 1200 //MFC 7.0 using CMemFile::Duplicate; #endif //MFC 7.0 //----------------------------------------------------------------------- // Summary: // This member function will initialize the CXTPMemFile object with // the information specified in the 'fDuplicate' object. // Parameters: // strDup - A NULL terminated string. // fDuplicate - A pointer to a valid CFile object. // Returns: // true if successful, otherwise returns false. //----------------------------------------------------------------------- virtual bool Duplicate(CFile* fDuplicate); virtual bool Duplicate(LPCTSTR strDup); // <combine CXTPMemFile::Duplicate@CFile* > //----------------------------------------------------------------------- // Summary: // This member function discards all changes to file since Open() or // last Flush(). // Returns: // true if successful, otherwise returns false. //----------------------------------------------------------------------- virtual bool Discard(); //----------------------------------------------------------------------- // Summary: // This member function inserts any File and returns the length of the actual // copied bytes. // Parameters: // fSrc - A pointer to a valid CFile object. // strSrc - Specifies a NULL terminated string that is the path to the desired // file. // dwSourcePos - Represents the source file position. // dwDestPos - Represents the destination file position. // dwBytes - Number of bytes to insert. // Returns: // A DWORD value that represents the length of the copied bytes. //----------------------------------------------------------------------- virtual DWORD Insert(CFile* fSrc, DWORD dwSourcePos, DWORD dwDestPos, DWORD dwBytes); virtual DWORD Insert(LPCTSTR strSrc, DWORD dwSourcePos, DWORD dwDestPos, DWORD dwBytes); // <combine CXTPMemFile::Insert@CFile*@DWORD@DWORD@DWORD> //----------------------------------------------------------------------- // Summary: // This member function extracts bytes to a file and returns the length // of the actual copied bytes. // Parameters: // fDest - A pointer to a valid CFile object. // strDest - Specifies a NULL terminated string that is the path to the desired // file. // dwStartPos - Represents the starting position. // dwBytes - Number of bytes to extract. // Returns: // A DWORD value that represents the length of the copied bytes. //----------------------------------------------------------------------- virtual DWORD Extract(CFile* fDest, DWORD dwStartPos, DWORD dwBytes); virtual DWORD Extract(LPCTSTR strDest, DWORD dwStartPos, DWORD dwBytes); // <combine CXTPMemFile::Extract@CFile*@DWORD@DWORD> //----------------------------------------------------------------------- // Summary: // This member function finds data in the file. // Parameters: // pData - Pointer to the buffer to receive the data found. // dwDataLen - Size of the data to find. // lStartPos - Starting position. // Returns: // A LONG data type. //----------------------------------------------------------------------- LONG FindData(void* pData, DWORD dwDataLen, LONG lStartPos); //----------------------------------------------------------------------- // Summary: // This member operator will initialize the CXTPMemFile object with // the object specified by 'fDup'. // Parameters: // fDup - A pointer to a valid CFile object. //----------------------------------------------------------------------- void operator=(CFile* fDup); //----------------------------------------------------------------------- // Summary: // This member operator will initialize the CXTPMemFile object with // the object specified by 'strDup'. // Parameters: // strDup - Specifies a NULL terminated string that is the path to the desired // file. //----------------------------------------------------------------------- void operator=(CString strDup); //----------------------------------------------------------------------- // Summary: // This member operator will adjust the file position. // Parameters: // dwFilePos - DWORD value that specifies file position. //----------------------------------------------------------------------- void operator=(DWORD dwFilePos); //----------------------------------------------------------------------- // Summary: // This member operator will append the CXTPMemFile object with the object // specified by 'fApp'. // Parameters: // fApp - A pointer to a valid CFile object. //----------------------------------------------------------------------- void operator+=(CFile* fApp); //----------------------------------------------------------------------- // Summary: // This member operator will append the CXTPMemFile object with the object // specified by 'strApp'. // Parameters: // strApp - Specifies a NULL terminated string that is the path to the desired // file. //----------------------------------------------------------------------- void operator+=(CString strApp); //----------------------------------------------------------------------- // Summary: // This member operator will perform indexing operations for the CXTPMemFile // object. Returns a BYTE data type. // Parameters: // dwFilePos - DWORD value that specifies file position. //----------------------------------------------------------------------- BYTE operator [](DWORD dwFilePos); protected: //----------------------------------------------------------------------- // Summary: // This member function loads the file into memory. // Returns: // true if successful, otherwise returns false. //----------------------------------------------------------------------- virtual bool Load(); //----------------------------------------------------------------------- // Summary: // This member function saves the file to disk. // Returns: // true if successful, otherwise returns false. //----------------------------------------------------------------------- virtual bool Save(); //----------------------------------------------------------------------- // Summary: // This member function imports the data of a CFile derived object // (operator=). // Parameters: // fImp - A pointer to a valid CFile object. // Returns: // true if successful, otherwise returns false. //----------------------------------------------------------------------- virtual bool Import(CFile* fImp); //----------------------------------------------------------------------- // Summary: // This member function appends a CFile derived object to the file // (operator+=). // Parameters: // fApp - A pointer to a valid CFile object. // Returns: // true if successful, otherwise returns false. //----------------------------------------------------------------------- virtual bool Append(CFile* fApp); private: // Unsupported APIs virtual CFile* Duplicate() const; private: UINT m_uiOpenFlags; bool m_bOpen; CFile m_File; }; #endif // #if !defined(__XTMEMFILE_H__)
45.084746
147
0.52381
[ "object" ]
4f44feead549f9d2168e5f29939ff3c1f39d8493
832
h
C
gtasa_render_hook_rt/forward_pbr_pipeline.h
HermanLederer/gtaRenderHook
2ce53ce954c2d298717119dd6d02a2e58fff3aed
[ "MIT" ]
null
null
null
gtasa_render_hook_rt/forward_pbr_pipeline.h
HermanLederer/gtaRenderHook
2ce53ce954c2d298717119dd6d02a2e58fff3aed
[ "MIT" ]
null
null
null
gtasa_render_hook_rt/forward_pbr_pipeline.h
HermanLederer/gtaRenderHook
2ce53ce954c2d298717119dd6d02a2e58fff3aed
[ "MIT" ]
null
null
null
#pragma once #include <Engine/Common/irenderingpipeline.h> namespace RHEngine { class IRenderingContext; class D3D11ConstantBuffer; class D3D11PrimitiveBatch; }; struct MaterialCB { float MaterialColor[4] = {1,1,1,1}; float Roughness=1.0f; float Metallness=0; float IOR; float Emmisivness; }; class ForwardPBRPipeline : public RHEngine::IRenderingPipeline { public: ForwardPBRPipeline(); virtual ~ForwardPBRPipeline() override; virtual void DrawMesh( RHEngine::IRenderingContext *context, RHEngine::IPrimitiveBatch *model ) override; private: MaterialCB mDefMaterialCBData{}; void *mMaterialCB = nullptr; void* mBaseVS = nullptr; void* mNoTexPS = nullptr; void* mTexPS = nullptr; void* mVertexDecl = nullptr; void* mSelectedPS = nullptr; };
22.486486
71
0.703125
[ "model" ]
62f70dc95ba5a029d86df626a3451cff75885e1b
6,092
h
C
core/src/main/cpp/io/MslVariant.h
sghill/msl
97f53d685389bab496df889d87ccdbd1e9728032
[ "Apache-2.0" ]
559
2015-01-01T14:47:49.000Z
2022-03-05T02:33:53.000Z
core/src/main/cpp/io/MslVariant.h
sghill/msl
97f53d685389bab496df889d87ccdbd1e9728032
[ "Apache-2.0" ]
141
2015-01-06T18:43:22.000Z
2020-09-27T02:21:21.000Z
core/src/main/cpp/io/MslVariant.h
sghill/msl
97f53d685389bab496df889d87ccdbd1e9728032
[ "Apache-2.0" ]
85
2015-03-04T19:10:35.000Z
2022-02-15T10:34:40.000Z
/** * Copyright (c) 2016-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef VARIANT_H_ #define VARIANT_H_ #include <Exception.h> #include <stddef.h> #include <StaticAssert.h> #include <memory> #include <typeinfo> #include <vector> namespace netflix { namespace msl { typedef std::vector<uint8_t> ByteArray; namespace io { class MslArray; class MslEncodable; class MslObject; class Variant; // Detect Variant type to trigger a STATIC_ASSERT if placed into a Variant. template<typename T> struct isVariant{ static const int value = false; }; template<> struct isVariant<Variant>{ static const int value = true; }; // Do-nothing class to indicate null Variants class Null {}; // List of specific types allowed in Variant. If any other type is used, it will // trigger a (compile time) STATIC_ASSERT. This list matches the types in the // visit method overloads in the VariantVisitor interface below. typedef std::vector<uint8_t> ByteArray; template<typename T> struct isAllowed{ static const int value = false; }; template<> struct isAllowed<Null>{ static const int value = true; }; template<> struct isAllowed<std::string>{ static const int value = true; }; template<> struct isAllowed<int32_t>{ static const int value = true; }; template<> struct isAllowed<bool>{ static const int value = true; }; template<> struct isAllowed<int64_t>{ static const int value = true; }; template<> struct isAllowed<double>{ static const int value = true; }; template<> struct isAllowed<std::shared_ptr<ByteArray>>{ static const int value = true; }; template<> struct isAllowed<std::shared_ptr<MslObject>>{ static const int value = true; }; template<> struct isAllowed<std::shared_ptr<MslArray>>{ static const int value = true; }; template<> struct isAllowed<std::shared_ptr<MslEncodable>>{ static const int value = true; }; struct VariantVisitor { virtual ~VariantVisitor() {} virtual void visit(const Null& x) = 0; virtual void visit(const std::string& x) = 0; virtual void visit(bool x) = 0; virtual void visit(int32_t x) = 0; virtual void visit(int64_t x) = 0; virtual void visit(double x) = 0; virtual void visit(std::shared_ptr<ByteArray> x) = 0; virtual void visit(std::shared_ptr<MslObject> x) = 0; virtual void visit(std::shared_ptr<MslArray> x) = 0; virtual void visit(std::shared_ptr<MslEncodable> x) = 0; }; namespace variantdetail { class B { public: virtual ~B() {} virtual size_t getHashCode() const = 0; virtual bool isEqual(const B* rhs) const = 0; virtual void accept(VariantVisitor& visitor) const = 0; }; // T must: 1. have copy ctor, 2. have operator==, and 3. not be a Variant template<typename T> class D : public B { public: virtual ~D() {} explicit D(const T& value) : hashCode_(typeid(value).hash_code()), value_(value) { STATIC_ASSERT(!isVariant<T>::value); STATIC_ASSERT(isAllowed<T>::value); } T value() const { return value_; } virtual size_t getHashCode() const {return hashCode_;}; virtual bool isEqual(const B* rhs) const { const D* d = dynamic_cast<const D*>(rhs); if (!d) return false; return value_ == d->value_; // invokes T's operator== } virtual void accept(VariantVisitor& visitor) const { visitor.visit(value_); } // default copy ctor and assignment operators ok private: const size_t hashCode_; const T value_; }; } // namespace variantdetail class Variant { public: // Default copy ctor and operator= are ok, they copy the member shared_ptr // with no_throw guarantee. // NOTE: Sharing semantics are intended: a copy of a Variant should point to // the same underlying object. template<typename T> bool isType() const { return (value_->getHashCode() == typeid(T).hash_code()); } template<typename T> T get() const { if (!isType<T>()) throw Exception(std::bad_cast()); return std::static_pointer_cast<variantdetail::D<T> >(value_)->value(); } template<typename T> T getOpt() const { if (!isType<T>()) return T(); return std::static_pointer_cast<variantdetail::D<T> >(value_)->value(); } size_t getHashCode() const { return value_->getHashCode(); } bool isNull() const { return isType<Null>(); } std::string toString() const; void accept(VariantVisitor& visitor) const; private: Variant(); // not implemented explicit Variant(std::shared_ptr<variantdetail::B> value) : value_(value) {} std::shared_ptr<variantdetail::B> value_; friend struct VariantFactory; friend bool operator==(const Variant&, const Variant&); }; struct VariantFactory { static Variant createNull() { return Variant(std::shared_ptr<variantdetail::B>(std::make_shared<variantdetail::D<Null>>(Null()))); } template<typename T> static Variant create(const T& value) { return Variant(std::shared_ptr<variantdetail::B>(std::make_shared<variantdetail::D<T>>(value))); } }; bool operator==(const Variant& a, const Variant& b); bool operator!=(const Variant& a, const Variant& b); bool operator==(const Null& a, const Null& b); bool operator==(std::shared_ptr<ByteArray> a, std::shared_ptr<ByteArray> b); bool operator==(std::shared_ptr<MslObject> a, std::shared_ptr<MslObject> b); bool operator==(std::shared_ptr<MslArray> a, std::shared_ptr<MslArray> b); //bool operator==(std::shared_ptr<MslEncodable> a, std::shared_ptr<MslEncodable> b); }}} /* namespace netflix::msl::io */ #endif /* VARIANT_H_ */
35.213873
108
0.694682
[ "object", "vector" ]
62f891d750339b6c496cb88c2ec05f269c3ce69b
11,868
c
C
lib/private/wlist.c
PiRSquared17/warc-tools
f200a5ed086159a1b1833f7361b35389b1ad1ef4
[ "Apache-2.0" ]
null
null
null
lib/private/wlist.c
PiRSquared17/warc-tools
f200a5ed086159a1b1833f7361b35389b1ad1ef4
[ "Apache-2.0" ]
null
null
null
lib/private/wlist.c
PiRSquared17/warc-tools
f200a5ed086159a1b1833f7361b35389b1ad1ef4
[ "Apache-2.0" ]
null
null
null
/* ------------------------------------------------------------------- */ /* Copyright (c) 2007-2008 Hanzo Archives Limited. */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* */ /* You may find more information about Hanzo Archives at */ /* */ /* http://www.hanzoarchives.com/ */ /* */ /* You may find more information about the WARC Tools project at */ /* */ /* http://code.google.com/p/warc-tools/ */ /* ------------------------------------------------------------------- */ /* * Portability header file */ #include <wport.h> /* * WARC default headers */ #include <wclass.h> /* bless, destroy, cassert, struct Class */ #include <wsign.h> /* CASSET macro */ #include <wlist.h> /* for class's prototypes */ #include <wlist.x> #include <wmem.h> /* wmalloc, wfree */ #include "wmisc.h" /* warc_bool_t ... */ #include <wcsafe.h> #define SIGN 2 /** * WARC WLNode internal structure */ struct WLNode { /*@{*/ void * object; /**< object node */ struct WLNode * next; /**< next object */ struct WLNode * prev; /**< previous object */ /*@}*/ }; #define MAKE_LNODE \ (wmalloc (sizeof (struct WLNode))) #define DELETE_LNODE(n) \ (wfree (n), n = NIL) /** * WARC WList class internal */ struct WList { const void * class; /*@{*/ struct WLNode * dummy; /**< dummy list node */ warc_u32_t cnt; /**< how many objects are there */ /*@}*/ }; #define DUMMY (self -> dummy) #define CNT (self -> cnt) /** * @param _self A WList object * @param o an object * * @return false if the operation succeeds, true if not * * WList : Treats the list as a stack, and pushes the * object onto the end of the list. */ WPUBLIC warc_bool_t WList_push (void * const _self, void * const o) { struct WList * const self = _self; struct WLNode * n = NIL; /* preconditions */ CASSERT (self); assert (o); /* can't add object identical to the container */ assert(self != o); /* create a new list node for the object "o" */ n = MAKE_LNODE; unless (n) return (WARC_TRUE); /* store the reference to "o" */ n -> object = o; /* add the node to the end of list */ DUMMY -> prev -> next = n; n -> prev = DUMMY -> prev; n -> next = DUMMY; DUMMY -> prev = n; /* reset list's counter */ ++ CNT; return (WARC_FALSE); } /** * @param _self a WList object * * @return a pointer object * * WList : Pops and returns the last object of the list, * shortening the list by one element. */ WPUBLIC void * WList_pop (void * const _self) { struct WList * const self = _self; struct WLNode * n = NIL; void * o = NIL; /* preconditions */ CASSERT (self); unless (CNT) return (NIL); /* get the last object */ n = DUMMY -> prev; DUMMY -> prev = n -> prev; n -> prev -> next = n -> next; o = n -> object; /* delete the list node */ DELETE_LNODE (n); /* reset list's counter */ -- CNT; return (o); } /** * @param _self a WList object * * @return a pointer object * * WList : Shifts the first object of the list off and * returns it, shortening the list by 1 and moving everything down. */ WPUBLIC void * WList_shift (void * const _self) { struct WList * const self = _self; struct WLNode * n = NIL; void * o = NIL; /* preconditions */ CASSERT (self); unless (CNT) return (NIL); /* get the first object */ n = DUMMY -> next; o = n -> object; DUMMY -> next = n -> next; n -> next -> prev = DUMMY; /* delete the list node */ DELETE_LNODE (n); /* reset list's counter */ -- CNT; return (o); } /** * @param _self a WList object * * @return false if the operation succeeds, true if not * * WList : Does the opposite of a "shift". Prepends the object to * the front of the list. */ WPUBLIC warc_bool_t WList_unshift (void * const _self, void * const o) { struct WList * const self = _self; struct WLNode * n = NIL; /* preconditions */ CASSERT (self); assert (o); /* can't add object identical to the container */ assert(self != o); /* create a new list node for the object "o" */ n = MAKE_LNODE; unless (n) return (WARC_TRUE); /* store the reference to "o" */ n -> object = o; /* add the node to the front of list */ DUMMY -> next -> prev = n; n -> next = DUMMY -> next; n -> prev = DUMMY; DUMMY -> next = n; /* reset list's counter */ ++ CNT; return (WARC_FALSE); } /** * @param _self a WList object * * @return how many objects * * Returns the list size */ WIPUBLIC warc_u32_t WList_size (const void * const _self) { const struct WList * const self = _self; /* preconditions */ CASSERT (self); return (CNT); } WPUBLIC const void * WList_getObjectFromNode (const void * const _self, void * _node) { const struct WList * const self = _self; struct WLNode * node = _node; /* empty list */ CASSERT (self); assert (node); unless (CNT) return (NIL); return (node -> object); } WPUBLIC void * WList_nextNode (const void * const _self, void * _node) { const struct WList * const self = _self; struct WLNode * node = _node; /* empty list */ CASSERT (self); assert (node); unless (CNT) return (NIL); return (node -> next); } WPUBLIC void * WList_firstNode (const void * const _self) { const struct WList * const self = _self; /* empty list */ CASSERT (self); unless (CNT) return (NIL); return (DUMMY -> next); } WPUBLIC void * WList_deleteNode (void * const _self, void * _node) { struct WList * const self = _self; struct WLNode * n = _node; void * o = NIL; /* empty list */ CASSERT (self); assert (n); unless (CNT) return (NIL); /* return the object and free its node */ o = n -> object; n -> next -> prev = n -> prev; n -> prev -> next = n -> next; DELETE_LNODE (n); -- CNT; return (o); } /** * @param _self a WList object * @param index index position in the list object (starting from 0) * * @return an object if succeeds, otherwise NIL * * Returns a constant reference to the object at index "i" in the list. * NIL is returned if empty list. */ WPRIVATE struct WLNode * gotoIndex (const void * const _self, const warc_u32_t index) { const struct WList * const self = _self; struct WLNode * node; warc_u32_t i; /* empty list */ unless (CNT) return (NIL); if (index > CNT) return (NIL); /* start from the first node */ i = 0; node = DUMMY -> next; while (i < index) { node = node -> next; ++ i; } return (node); } /** * @param _self A WList object * @param index index position in the list object (starting from 0) * * @return an object if succeeds, otherwise NIL * * Returns a constant reference to the object at index "i" in the list. * NIL is returned if empty list. */ WPUBLIC const void * WList_getElement (const void * const _self, const warc_u32_t index) { const struct WList * const self = _self; struct WLNode * n; /* preconditions */ CASSERT (self); /* position node on the target node */ n = gotoIndex (self, index); unless (n) return (NIL); return (n -> object); } /** * @param _self a WList object * @param index index position in the list object (starting from 0) * @param o a constant reference to an object * * @return a reference to the old object at index * * Returns the object at index "index" and replace it by object "o". * NIL is returned if empty list. */ WPUBLIC void * WList_setElement (void * const _self, const warc_u32_t index, void * const o) { struct WList * const self = _self; struct WLNode * n; void * old; /* preconditions */ CASSERT (self); assert (o); /* can't add object identical to the container */ assert(self != o); /* position node on the target node */ n = gotoIndex (self, index); unless (n) return (NIL); /* save the new object and return the old one */ old = n -> object; n -> object = o; return (old); } /** * @param _self a WList object * @param index index position in the list object (starting from 0) * @param o a constant reference to an object * * @return a reference to the old object at index * * Returns the object at index "index" and remove it from the list. * NIL is returned if empty list. */ WPUBLIC void * WList_remove (void * const _self, const warc_u32_t index) { struct WList * const self = _self; struct WLNode * n; void * o; /* preconditions */ CASSERT (self); /* position node on the target node */ n = gotoIndex (self, index); unless (n) return (NIL); /* return the object and free its node */ o = n -> object; n -> next -> prev = n -> prev; n -> prev -> next = n -> next; DELETE_LNODE (n); return (o); } /** * WList_constructor - create a new WList object instance * * @param _self WList class object * @param app constructor list parameters * * @return a valid WList object or NIL * * WARC List constructor */ WPRIVATE void * WList_constructor (void * _self, va_list * app) { struct WList * const self = _self; UNUSED (app); /* create dummy head node */ DUMMY = MAKE_LNODE; unless (DUMMY) return (NIL); /* set object's counter */ CNT = 0; /* link prev and next to dummy */ DUMMY -> prev = DUMMY -> next = DUMMY; return (self); } /** * @param _self WList object instance * * WARC List destructor */ WPRIVATE void * WList_destructor (void * _self) { struct WList * const self = _self; struct WLNode * n; /* preconditions */ CASSERT (self); /* destory all objects in the list */ n = DUMMY -> next; while (n != DUMMY) { n = n -> next; destroy (n -> prev -> object); DELETE_LNODE (n -> prev); } CNT = 0; /* free the dummy node */ if (DUMMY) DELETE_LNODE (DUMMY); return (self); } /** * WARC WList class */ static const struct Class _WList = { sizeof (struct WList), SIGN, WList_constructor, WList_destructor }; const void * WList = & _WList;
20.25256
76
0.541035
[ "object" ]
1a004772c34d246630f6fcc2f86a5deeae5adebd
55,875
h
C
game/shared/Angelscript/ScriptAPI/Entities/ASCBaseEntity.h
HLSources/HLEnhanced
7510a8f7049293b5094b9c6e14e0aa0869c8dba2
[ "Unlicense" ]
83
2016-06-10T20:49:23.000Z
2022-02-13T18:05:11.000Z
game/shared/Angelscript/ScriptAPI/Entities/ASCBaseEntity.h
HLSources/HLEnhanced
7510a8f7049293b5094b9c6e14e0aa0869c8dba2
[ "Unlicense" ]
26
2016-06-16T22:27:24.000Z
2019-04-30T19:25:51.000Z
game/shared/Angelscript/ScriptAPI/Entities/ASCBaseEntity.h
HLSources/HLEnhanced
7510a8f7049293b5094b9c6e14e0aa0869c8dba2
[ "Unlicense" ]
58
2016-06-10T23:52:33.000Z
2021-12-30T02:30:50.000Z
#ifndef GAME_SERVER_ANGELSCRIPT_SCRIPTAPI_ENTITIES_ASCBASEENTITY_H #define GAME_SERVER_ANGELSCRIPT_SCRIPTAPI_ENTITIES_ASCBASEENTITY_H #include <string> #include <angelscript.h> #include <Angelscript/util/ASUtil.h> /** * Registers types, constants, globals, etc used by entities. * @param engine Script engine. */ void RegisterScriptEntityDependencies( asIScriptEngine& engine ); /** * Class name for CBaseEntity in scripts. */ #define AS_CBASEENTITY_NAME "CBaseEntity" /** * Wrapper so scripts can call KeyValue. */ template<typename CLASS> bool CBaseEntity_KeyValue( CLASS* pThis, const std::string& szKeyName, const std::string& szValue ) { KeyValueData kvd; kvd.szKeyName = szKeyName.c_str(); kvd.szValue = szValue.c_str(); kvd.szClassName = pThis->GetClassname(); kvd.fHandled = false; pThis->KeyValue( &kvd ); return kvd.fHandled != 0; } std::string CBaseEntity_GetClassname( const CBaseEntity* pThis ); bool CBaseEntity_ClassnameIs( const CBaseEntity* pThis, const std::string& szClassname ); std::string CBaseEntity_GetGlobalName( const CBaseEntity* pThis ); void CBaseEntity_SetGlobalName( CBaseEntity* pThis, const std::string& szGlobalName ); std::string CBaseEntity_GetTargetname( const CBaseEntity* pThis ); void CBaseEntity_SetTargetname( CBaseEntity* pThis, const std::string& szTargetname ); std::string CBaseEntity_GetTarget( const CBaseEntity* pThis ); void CBaseEntity_SetTarget( CBaseEntity* pThis, const std::string& szTarget ); std::string CBaseEntity_GetNetName( const CBaseEntity* pThis ); void CBaseEntity_SetNetName( CBaseEntity* pThis, const std::string& szNetName ); std::string CBaseEntity_GetModelName( const CBaseEntity* pThis ); void CBaseEntity_SetModel( CBaseEntity* pThis, const std::string& szModelName ); #ifdef SERVER_DLL std::string CBaseEntity_GetViewModelName( const CBaseEntity* pThis ); void CBaseEntity_SetViewModelName( CBaseEntity* pThis, const std::string& szViewModelName ); #endif std::string CBaseEntity_GetWeaponModelName( const CBaseEntity* pThis ); void CBaseEntity_SetWeaponModelName( CBaseEntity* pThis, const std::string& szWeaponModelName ); std::string CBaseEntity_GetMessage( const CBaseEntity* pThis ); void CBaseEntity_SetMessage( CBaseEntity* pThis, const std::string& szMessage ); bool CBaseEntity_HasTarget( const CBaseEntity* pThis, const std::string& szTarget ); std::string CBaseEntity_TeamID( const CBaseEntity* pThis ); std::string CBaseEntity_GetNoise( const CBaseEntity* pThis ); void CBaseEntity_SetNoise( CBaseEntity* pThis, const std::string& szNoise ); std::string CBaseEntity_GetNoise1( const CBaseEntity* pThis ); void CBaseEntity_SetNoise1( CBaseEntity* pThis, const std::string& szNoise ); std::string CBaseEntity_GetNoise2( const CBaseEntity* pThis ); void CBaseEntity_SetNoise2( CBaseEntity* pThis, const std::string& szNoise ); std::string CBaseEntity_GetNoise3( const CBaseEntity* pThis ); void CBaseEntity_SetNoise3( CBaseEntity* pThis, const std::string& szNoise ); /** * Registers CBaseEntity methods and properties. * Uses templates to avoid virtual function calls in scripts whenever possible. * Remember to add new entities to the list of forward declared types in ASCBaseEntity.cpp * @param engine Script engine. * @param pszObjectName Name of the class to register object data for. * @tparam CLASS Concrete C++ class being registered. */ template<typename CLASS> inline void RegisterScriptCBaseEntity( asIScriptEngine& engine, const char* const pszObjectName ) { //Register casts to convert between entity types. as::RegisterCasts<CBaseEntity, CLASS>( engine, AS_CBASEENTITY_NAME, pszObjectName, &as::Cast_UpCast, &as::Cast_DownCast ); engine.RegisterObjectProperty( pszObjectName, "EHANDLE m_hGoalEnt", asOFFSET( CLASS, m_hGoalEnt ) ); engine.RegisterObjectProperty( pszObjectName, "CBaseEntity@ m_pLink", asOFFSET( CLASS, m_pLink ) ); engine.RegisterObjectMethod( pszObjectName, "string GetClassname() const", asFUNCTION( CBaseEntity_GetClassname ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool ClassnameIs(const string& in szClassname) const", asFUNCTION( CBaseEntity_ClassnameIs ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool HasGlobalName() const", asMETHOD( CLASS, HasGlobalName ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "string GetGlobalName() const", asFUNCTION( CBaseEntity_GetGlobalName ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void SetGlobalName(const string& in szGlobalName)", asFUNCTION( CBaseEntity_SetGlobalName ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void ClearGlobalName()", asMETHOD( CLASS, ClearGlobalName ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool HasTargetname() const", asMETHOD( CLASS, HasTargetname ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "string GetTargetname() const", asFUNCTION( CBaseEntity_GetTargetname ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void SetTargetname(const string& in szTargetname)", asFUNCTION( CBaseEntity_SetTargetname ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void ClearTargetname()", asMETHOD( CLASS, ClearTargetname ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool HasTarget() const", asMETHODPR( CLASS, HasTarget, () const, bool ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "string GetTarget() const", asFUNCTION( CBaseEntity_GetTarget ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void SetTarget(const string& in szTarget)", asFUNCTION( CBaseEntity_SetTarget ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void ClearTarget()", asMETHOD( CLASS, ClearTarget ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool HasNetName() const", asMETHOD( CLASS, HasNetName ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "string GetNetName() const", asFUNCTION( CBaseEntity_GetNetName ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void SetNetName(const string& in szNetName)", asFUNCTION( CBaseEntity_SetNetName ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void ClearNetName()", asMETHOD( CLASS, ClearNetName ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetAbsOrigin() const", asMETHOD( CLASS, GetAbsOrigin ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetAbsOrigin(const Vector& in vecOrigin)", asMETHOD( CLASS, SetAbsOrigin ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetOldOrigin() const", asMETHOD( CLASS, GetOldOrigin ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetOldOrigin(const Vector& in vecOrigin)", asMETHOD( CLASS, SetOldOrigin ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetAbsVelocity() const", asMETHOD( CLASS, GetAbsVelocity ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetAbsVelocity(const Vector& in vecVelocity)", asMETHOD( CLASS, SetAbsVelocity ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetBaseVelocity() const", asMETHOD( CLASS, GetBaseVelocity ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetBaseVelocity(const Vector& in vecVelocity)", asMETHOD( CLASS, SetBaseVelocity ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetMoveDir() const", asMETHOD( CLASS, GetMoveDir ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetMoveDir(const Vector& in vecMoveDir)", asMETHOD( CLASS, SetMoveDir ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetAbsAngles() const", asMETHOD( CLASS, GetAbsAngles ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetAbsAngles(const Vector& in vecAngles)", asMETHOD( CLASS, SetAbsAngles ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetAngularVelocity() const", asMETHOD( CLASS, GetAngularVelocity ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetAngularVelocity(const Vector& in vecVelocity)", asMETHOD( CLASS, SetAngularVelocity ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetPunchAngle() const", asMETHOD( CLASS, GetPunchAngle ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetPunchAngle(const Vector& in vecPunchAngle)", asMETHOD( CLASS, SetPunchAngle ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetViewAngle() const", asMETHOD( CLASS, GetViewAngle ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetViewAngle(const Vector& in vecViewAngle)", asMETHOD( CLASS, SetViewAngle ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "FixAngleMode GetFixAngleMode() const", asMETHOD( CLASS, GetFixAngleMode ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetFixAngleMode(const FixAngleMode mode)", asMETHOD( CLASS, SetFixAngleMode ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetIdealPitch() const", asMETHOD( CLASS, GetIdealPitch ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetIdealPitch(const float flIdealPitch)", asMETHOD( CLASS, SetIdealPitch ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetPitchSpeed() const", asMETHOD( CLASS, GetPitchSpeed ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetPitchSpeed(const float flPitchSpeed)", asMETHOD( CLASS, SetPitchSpeed ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetIdealYaw() const", asMETHOD( CLASS, GetIdealYaw ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetIdealYaw(const float flIdealYaw)", asMETHOD( CLASS, SetIdealYaw ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetYawSpeed() const", asMETHOD( CLASS, GetYawSpeed ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetYawSpeed(const float flYawSpeed)", asMETHOD( CLASS, SetYawSpeed ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetModelIndex() const", asMETHOD( CLASS, GetModelIndex ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetModelIndex(const int iModelIndex)", asMETHOD( CLASS, SetModelIndex ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool HasModel() const", asMETHOD( CLASS, HasModel ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "string GetModelName() const", asFUNCTION( CBaseEntity_GetModelName ), asCALL_CDECL_OBJFIRST ); //Not exposed: SetModelName. The engine handles it, if it's needed add a special handler for it. - Solokiller engine.RegisterObjectMethod( pszObjectName, "void SetModel(const string& in szModelName)", asFUNCTION( CBaseEntity_SetModel ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void ClearModel()", asMETHOD( CLASS, ClearModel ), asCALL_THISCALL ); #ifdef SERVER_DLL engine.RegisterObjectMethod( pszObjectName, "string GetViewModelName() const", asFUNCTION( CBaseEntity_GetViewModelName ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void SetViewModelName(const string& in szViewModelName)", asFUNCTION( CBaseEntity_SetViewModelName ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void ClearViewModelName()", asMETHOD( CLASS, ClearViewModelName ), asCALL_THISCALL ); #endif engine.RegisterObjectMethod( pszObjectName, "string GetWeaponModelName() const", asFUNCTION( CBaseEntity_GetWeaponModelName ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void SetWeaponModelName(const string& in szWeaponModelName)", asFUNCTION( CBaseEntity_SetWeaponModelName ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void ClearWeaponModelName()", asMETHOD( CLASS, ClearWeaponModelName ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetWeaponAnim() const", asMETHOD( CLASS, GetWeaponAnim ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetWeaponAnim(const int iWeaponAnim)", asMETHOD( CLASS, SetWeaponAnim ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool IsDucking() const", asMETHOD( CLASS, IsDucking ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetDucking(const bool bDucking)", asMETHOD( CLASS, SetDucking ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetStepSoundTime() const", asMETHOD( CLASS, GetStepSoundTime ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetStepSoundTime(const int iTime)", asMETHOD( CLASS, SetStepSoundTime ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetSwimSoundTime() const", asMETHOD( CLASS, GetSwimSoundTime ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetSwimSoundTime(const int iTime)", asMETHOD( CLASS, SetSwimSoundTime ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetDuckTime() const", asMETHOD( CLASS, GetDuckTime ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetDuckTime(const int iTime)", asMETHOD( CLASS, SetDuckTime ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool IsStepLeft() const", asMETHOD( CLASS, IsStepLeft ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetStepLeft(const bool bStepLeft)", asMETHOD( CLASS, SetStepLeft ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetFallVelocity() const", asMETHOD( CLASS, GetFallVelocity ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetFallVelocity(const float flFallVelocity)", asMETHOD( CLASS, SetFallVelocity ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetAbsMin() const", asMETHOD( CLASS, GetAbsMin ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetAbsMin(const Vector& in vecMin)", asMETHOD( CLASS, SetAbsMin ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetAbsMax() const", asMETHOD( CLASS, GetAbsMax ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetAbsMax(const Vector& in vecMax)", asMETHOD( CLASS, SetAbsMax ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetRelMin() const", asMETHOD( CLASS, GetRelMin ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetRelMin(const Vector& in vecMin)", asMETHOD( CLASS, SetRelMin ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetRelMax() const", asMETHOD( CLASS, GetRelMax ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetRelMax(const Vector& in vecMax)", asMETHOD( CLASS, SetRelMax ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetBounds() const", asMETHOD( CLASS, GetBounds ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetSize(const Vector& in vecSize)", asMETHODPR( CLASS, SetSize, ( const Vector& ), void ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetSize(const Vector& in vecMin, const Vector& in vecMax)", asMETHODPR( CLASS, SetSize, ( const Vector&, const Vector& ), void ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetLastThink() const", asMETHOD( CLASS, GetLastThink ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetLastThink(const float flLastThink)", asMETHOD( CLASS, SetLastThink ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetNextThink() const", asMETHOD( CLASS, GetNextThink ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetNextThink(const float flNextThink)", asMETHOD( CLASS, SetNextThink ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "MoveType GetMoveType() const", asMETHOD( CLASS, GetMoveType ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetMoveType(const MoveType moveType)", asMETHOD( CLASS, SetMoveType ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "Solid GetSolidType() const", asMETHOD( CLASS, GetSolidType ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetSolidType(const Solid solidType)", asMETHOD( CLASS, SetSolidType ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetSkin() const", asMETHOD( CLASS, GetSkin ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetSkin(const int iSkin)", asMETHOD( CLASS, SetSkin ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetBody() const", asMETHOD( CLASS, GetBody ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetBody(const int iBody)", asMETHOD( CLASS, SetBody ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const CEntBitSet& GetEffects() const", asMETHODPR( CLASS, GetEffects, () const, const CEntBitSet& ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CEntBitSet& GetEffects()", asMETHODPR( CLASS, GetEffects, (), CEntBitSet& ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetGravity() const", asMETHOD( CLASS, GetGravity ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetGravity(const float flGravity)", asMETHOD( CLASS, SetGravity ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetFriction() const", asMETHOD( CLASS, GetFriction ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetFriction(const float flFriction)", asMETHOD( CLASS, SetFriction ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetLightLevel() const", asMETHOD( CLASS, GetLightLevel ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetSequence() const", asMETHOD( CLASS, GetSequence ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetSequence(const int iSequence)", asMETHOD( CLASS, SetSequence ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetGaitSequence() const", asMETHOD( CLASS, GetGaitSequence ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetGaitSequence(const int iGaitSequence)", asMETHOD( CLASS, SetGaitSequence ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetFrame() const", asMETHOD( CLASS, GetFrame ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetFrame(const float flFrame)", asMETHOD( CLASS, SetFrame ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetAnimTime() const", asMETHOD( CLASS, GetAnimTime ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetAnimTime(const float flAnimTime)", asMETHOD( CLASS, SetAnimTime ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetFrameRate() const", asMETHOD( CLASS, GetFrameRate ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetFrameRate(const float flFrameRate)", asMETHOD( CLASS, SetFrameRate ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetScale() const", asMETHOD( CLASS, GetScale ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetScale(const float flScale)", asMETHOD( CLASS, SetScale ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "RenderMode GetRenderMode() const", asMETHOD( CLASS, GetRenderMode ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetRenderMode(const RenderMode renderMode)", asMETHOD( CLASS, SetRenderMode ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetRenderAmount() const", asMETHOD( CLASS, GetRenderAmount ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetRenderAmount(const float flRenderAmount)", asMETHOD( CLASS, SetRenderAmount ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetRenderColor() const", asMETHOD( CLASS, GetRenderColor ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetRenderColor(const Vector& in vecColor)", asMETHOD( CLASS, SetRenderColor ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "RenderFX GetRenderFX() const", asMETHOD( CLASS, GetRenderFX ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetRenderFX(const RenderFX renderFX)", asMETHOD( CLASS, SetRenderFX ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetHealth() const", asMETHOD( CLASS, GetHealth ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetHealth(const float flHealth)", asMETHOD( CLASS, SetHealth ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetMaxHealth() const", asMETHOD( CLASS, GetMaxHealth ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetMaxHealth(const float flMaxHealth)", asMETHOD( CLASS, SetMaxHealth ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetArmorAmount() const", asMETHOD( CLASS, GetArmorAmount ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetArmorAmount(const float flArmorAmount)", asMETHOD( CLASS, SetArmorAmount ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetArmorType() const", asMETHOD( CLASS, GetArmorType ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetArmorType(const float flArmorType)", asMETHOD( CLASS, SetArmorType ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetFrags() const", asMETHOD( CLASS, GetFrags ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetFrags(const float flFrags)", asMETHOD( CLASS, SetFrags ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const CEntBitSet& GetWeapons() const", asMETHODPR( CLASS, GetWeapons, () const, const CEntBitSet& ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CEntBitSet& GetWeapons()", asMETHODPR( CLASS, GetWeapons, (), CEntBitSet& ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "TakeDamageMode GetTakeDamageMode() const", asMETHOD( CLASS, GetTakeDamageMode ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetTakeDamageMode(const TakeDamageMode takeDamageMode)", asMETHOD( CLASS, SetTakeDamageMode ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "DeadFlag GetDeadFlag() const", asMETHOD( CLASS, GetDeadFlag ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetDeadFlag(const DeadFlag deadFlag)", asMETHOD( CLASS, SetDeadFlag ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const Vector& GetViewOffset() const", asMETHOD( CLASS, GetViewOffset ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "Vector& GetMutableViewOffset()", asMETHOD( CLASS, GetMutableViewOffset ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetViewOffset(const Vector& in vecViewOffset)", asMETHOD( CLASS, SetViewOffset ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const CEntBitSet& GetButtons() const", asMETHODPR( CLASS, GetButtons, () const, const CEntBitSet& ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CEntBitSet& GetButtons()", asMETHODPR( CLASS, GetButtons, (), CEntBitSet& ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const CEntBitSet& GetOldButtons() const", asMETHODPR( CLASS, GetOldButtons, () const, const CEntBitSet& ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CEntBitSet& GetOldButtons()", asMETHODPR( CLASS, GetOldButtons, (), CEntBitSet& ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetImpulse() const", asMETHODPR( CLASS, GetImpulse, () const, int ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetImpulse(const int iImpulse)", asMETHODPR( CLASS, SetImpulse, ( const int ), void ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const CEntBitSet& GetSpawnFlags() const", asMETHODPR( CLASS, GetSpawnFlags, () const, const CEntBitSet& ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CEntBitSet& GetSpawnFlags()", asMETHODPR( CLASS, GetSpawnFlags, (), CEntBitSet& ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "const CEntBitSet& GetFlags() const", asMETHODPR( CLASS, GetFlags, () const, const CEntBitSet& ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CEntBitSet& GetFlags()", asMETHODPR( CLASS, GetFlags, (), CEntBitSet& ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetColorMap() const", asMETHODPR( CLASS, GetColorMap, () const, int ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetColorMap(const int iColorMap)", asMETHODPR( CLASS, SetColorMap, ( const int ), void ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void GetColorMap( int& out iTopColor, int& out iBottomColor ) const", asMETHODPR( CLASS, GetColorMap, ( int&, int& ) const, void ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetColorMap(const int iTopColor, const int iBottomColor)", asMETHODPR( CLASS, SetColorMap, ( const int, const int ), void ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetTeamID() const", asMETHOD( CLASS, GetTeamID ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetTeamID(const int iTeamID)", asMETHOD( CLASS, SetTeamID ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int GetPlayerClass() const", asMETHOD( CLASS, GetPlayerClass ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetPlayerClass(const int iPlayerClass)", asMETHOD( CLASS, SetPlayerClass ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "WaterLevel GetWaterLevel() const", asMETHOD( CLASS, GetWaterLevel ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetWaterLevel(const WaterLevel waterLevel)", asMETHOD( CLASS, SetWaterLevel ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "Contents GetWaterType() const", asMETHOD( CLASS, GetWaterType ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetWaterType(const Contents waterType)", asMETHOD( CLASS, SetWaterType ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool HasMessage() const", asMETHOD( CLASS, HasMessage ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "string GetMessage() const", asFUNCTION( CBaseEntity_GetMessage ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void SetMessage(const string& in szMessage)", asFUNCTION( CBaseEntity_SetMessage ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void ClearMessage()", asMETHOD( CLASS, ClearMessage ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetSpeed() const", asMETHOD( CLASS, GetSpeed ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetSpeed(const float flSpeed)", asMETHOD( CLASS, SetSpeed ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetMaxSpeed() const", asMETHOD( CLASS, GetMaxSpeed ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetMaxSpeed(const float flMaxSpeed)", asMETHOD( CLASS, SetMaxSpeed ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetAirFinishedTime() const", asMETHOD( CLASS, GetAirFinishedTime ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetAirFinishedTime(const float flime)", asMETHOD( CLASS, SetAirFinishedTime ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetPainFinishedTime() const", asMETHOD( CLASS, GetPainFinishedTime ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetPainFinishedTime(const float flime)", asMETHOD( CLASS, SetPainFinishedTime ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetFOV() const", asMETHOD( CLASS, GetFOV ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetFOV(const float flFOV)", asMETHOD( CLASS, SetFOV ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GetDamage() const", asMETHOD( CLASS, GetDamage ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetDamage(const float flDamage)", asMETHOD( CLASS, SetDamage ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CBaseEntity@ GetOwner() const", asMETHODPR( CLASS, GetOwner, () const, CBaseEntity* ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CBaseEntity@ GetOwner()", asMETHODPR( CLASS, GetOwner, (), CBaseEntity* ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetOwner(CBaseEntity@ pOwner)", asMETHOD( CLASS, SetOwner ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CBaseEntity@ GetGroundEntity()", asMETHOD( CLASS, GetGroundEntity ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetGroundEntity(CBaseEntity@ pGroundEntity)", asMETHOD( CLASS, SetGroundEntity ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CBaseEntity@ GetChain()", asMETHOD( CLASS, GetChain ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetChain(CBaseEntity@ pEntity)", asMETHOD( CLASS, SetChain ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool HasNoise() const", asMETHOD( CLASS, HasNoise ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "string GetNoise() const", asFUNCTION( CBaseEntity_GetNoise ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void SetNoise(const string& in szNoise)", asFUNCTION( CBaseEntity_SetNoise ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void ClearNoise()", asMETHOD( CLASS, ClearNoise ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool HasNoise1() const", asMETHOD( CLASS, HasNoise1 ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "string GetNoise1() const", asFUNCTION( CBaseEntity_GetNoise1 ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void SetNoise1(const string& in szNoise)", asFUNCTION( CBaseEntity_SetNoise1 ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void ClearNoise1()", asMETHOD( CLASS, ClearNoise1 ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool HasNoise2() const", asMETHOD( CLASS, HasNoise2 ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "string GetNoise2() const", asFUNCTION( CBaseEntity_GetNoise2 ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void SetNoise2(const string& in szNoise)", asFUNCTION( CBaseEntity_SetNoise2 ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void ClearNoise2()", asMETHOD( CLASS, ClearNoise2 ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool HasNoise3() const", asMETHOD( CLASS, HasNoise3 ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "string GetNoise3() const", asFUNCTION( CBaseEntity_GetNoise3 ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void SetNoise3(const string& in szNoise)", asFUNCTION( CBaseEntity_SetNoise3 ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void ClearNoise3()", asMETHOD( CLASS, ClearNoise3 ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void KeyValue(KeyValueData@ pkvd)", asMETHOD( CLASS, KeyValue ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool KeyValue(const string& in szKeyName, const string& in szValue)", asFUNCTION( CBaseEntity_KeyValue<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "int ObjectCaps() const", asMETHOD( CLASS, ObjectCaps ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SetObjectCollisionBox()", asMETHOD( CLASS, SetObjectCollisionBox ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CBaseEntity@ Respawn()", asMETHOD( CLASS, Respawn ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int entindex() const", asMETHOD( CLASS, entindex ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void Think()", asMETHOD( CLASS, Think ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void Touch(CBaseEntity@ pOther)", asMETHOD( CLASS, Touch ), asCALL_THISCALL ); //Give flValue a default so people don't always have to type it. engine.RegisterObjectMethod( pszObjectName, "void Use(CBaseEntity@ pActivator, CBaseEntity@ pCaller, USE_TYPE useType, float flValue = 0)", asMETHOD( CLASS, Use ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void Blocked(CBaseEntity@ pOther)", asMETHOD( CLASS, Blocked ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "EntityClassification_t Classify()", asMETHOD( CLASS, Classify ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int BloodColor() const", asMETHOD( CLASS, BloodColor ), asCALL_THISCALL ); //Pointers and references are equivalent, so we don't need to update CBaseEntity's methods just yet. - Solokiller engine.RegisterObjectMethod( pszObjectName, "void TraceAttack(const CTakeDamageInfo& in info, Vector vecDir, TraceResult& in tr)", asMETHOD( CLASS, TraceAttack ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void TraceBleed(const CTakeDamageInfo& in info, Vector vecDir, TraceResult& in tr)", asMETHOD( CLASS, TraceBleed ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void TakeDamage(const CTakeDamageInfo& in info)", asMETHODPR( CLASS, TakeDamage, ( const CTakeDamageInfo& ), void ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void TakeDamage(CBaseEntity@ pInflictor, CBaseEntity@ pAttacker, float flDamage, int bitsDamageType)", asMETHODPR( CLASS, TakeDamage, ( CBaseEntity*, CBaseEntity*, float, int ), void ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void Killed(const CTakeDamageInfo& in info, GibAction gibAction)", asMETHOD( CLASS, Killed ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "float GiveHealth(float flHealth, int bitsDamageType)", asMETHOD( CLASS, GiveHealth ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool IsTriggered(const CBaseEntity@ pActivator) const", asMETHOD( CLASS, IsTriggered ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CBaseMonster@ MyMonsterPointer()", asMETHOD( CLASS, MyMonsterPointer ), asCALL_THISCALL ); //TODO: MySquadMonsterPointer probably won't exist for much longer so don't expose it. - Solokiller engine.RegisterObjectMethod( pszObjectName, "bool IsMoving() const", asMETHOD( CLASS, IsMoving ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void OverrideReset()", asMETHOD( CLASS, OverrideReset ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int DamageDecal(int bitsDamageType) const", asMETHOD( CLASS, DamageDecal ), asCALL_THISCALL ); //TODO: OnControls may be replaced with a better way so don't expose it. - Solokiller engine.RegisterObjectMethod( pszObjectName, "bool OnControls(CBaseEntity@ pTest) const", asMETHOD( CLASS, OnControls ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool IsAlive() const", asMETHOD( CLASS, IsAlive ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool IsBSPModel() const", asMETHOD( CLASS, IsBSPModel ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool ReflectGauss() const", asMETHOD( CLASS, ReflectGauss ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool HasTarget(const string& in szTarget) const", asFUNCTION( CBaseEntity_HasTarget ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool IsInWorld() const", asMETHOD( CLASS, IsInWorld ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool IsPlayer() const", asMETHOD( CLASS, IsPlayer ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool IsNetClient() const", asMETHOD( CLASS, IsNetClient ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "CBaseEntity@ GetNextTarget()", asMETHOD( CLASS, GetNextTarget ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SUB_Remove()", asMETHOD( CLASS, SUB_Remove ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SUB_DoNothing()", asMETHOD( CLASS, SUB_DoNothing ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SUB_StartFadeOut()", asMETHOD( CLASS, SUB_StartFadeOut ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SUB_FadeOut()", asMETHOD( CLASS, SUB_FadeOut ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SUB_CallUseToggle()", asMETHOD( CLASS, SUB_CallUseToggle ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool ShouldToggle(USE_TYPE useType, const bool bCurrentState) const", asMETHOD( CLASS, ShouldToggle ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void FireBullets(" "const uint uiShots," "Vector vecSrc, Vector vecDirShooting, Vector vecSpread," "float flDistance, int iBulletType," "int iTracerFreq = 4, int iDamage = 0, CBaseEntity@ pAttacker = null)", asMETHOD( CLASS, FireBullets ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void FireBulletsPlayer(" "const uint uiShots," "Vector vecSrc, Vector vecDirShooting, Vector vecSpread," "float flDistance, int iBulletType," "int iTracerFreq = 4, int iDamage = 0, CBaseEntity@ pAttacker = null, int shared_rand = 0)", asMETHOD( CLASS, FireBulletsPlayer ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void SUB_UseTargets(CBaseEntity@ pActivator, USE_TYPE useType, float flValue)", asMETHOD( CLASS, SUB_UseTargets ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool Intersects(CBaseEntity@ pOther) const", asMETHOD( CLASS, Intersects ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void MakeDormant()", asMETHOD( CLASS, MakeDormant ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool IsDormant() const", asMETHOD( CLASS, IsDormant ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool IsLockedByMaster() const", asMETHOD( CLASS, IsLockedByMaster ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "void DeathNotice(CBaseEntity@ pChild)", asMETHOD( CLASS, DeathNotice ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool BarnacleVictimGrabbed(CBaseEntity@ pBarnacle)", asMETHOD( CLASS, BarnacleVictimGrabbed ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "Vector Center() const", asMETHOD( CLASS, Center ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "Vector EyePosition() const", asMETHOD( CLASS, EyePosition ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "Vector EarPosition() const", asMETHOD( CLASS, EarPosition ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "Vector BodyTarget(const Vector& in vecPosSrc) const", asMETHOD( CLASS, Center ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "int Illumination() const", asMETHOD( CLASS, Illumination ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool FVisible(const CBaseEntity@ pEntity) const", asMETHODPR( CLASS, FVisible, ( const CBaseEntity* ) const, bool ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool FVisible(const Vector& in vecOrigin) const", asMETHODPR( CLASS, FVisible, ( const Vector& ) const, bool ), asCALL_THISCALL ); engine.RegisterObjectMethod( pszObjectName, "bool FBoxVisible(const CBaseEntity@ pTarget, Vector& out vecTargetOrigin, float flSize = 0.0f) const", asMETHOD( CLASS, FBoxVisible ), asCALL_THISCALL ); #ifdef SERVER_DLL //Available to all module types now. engine.RegisterObjectMethod( pszObjectName, "dictionary@ GetUserData() const", asMETHOD( CLASS, GetUserData ), asCALL_THISCALL ); #endif } inline void RegisterScriptCBaseEntity( asIScriptEngine& engine ) { RegisterScriptCBaseEntity<CBaseEntity>( engine, AS_CBASEENTITY_NAME ); } template<typename CLASS> void BaseEntity_OnCreate( CLASS* pThis ) { pThis->CLASS::OnCreate(); } template<typename CLASS> void BaseEntity_OnDestroy( CLASS* pThis ) { pThis->CLASS::OnDestroy(); } template<typename CLASS> void BaseEntity_UpdateOnRemove( CLASS* pThis ) { pThis->CLASS::UpdateOnRemove(); } template<typename CLASS> void BaseEntity_KeyValue( CLASS* pThis, KeyValueData* pkvd ) { pThis->CLASS::KeyValue( pkvd ); } /** * Wrapper so scripts can call KeyValue. */ template<typename CLASS> bool BaseEntity_KeyValue( CLASS* pThis, const std::string& szKeyName, const std::string& szValue ) { KeyValueData kvd; kvd.szKeyName = szKeyName.c_str(); kvd.szValue = szValue.c_str(); kvd.szClassName = pThis->GetClassname(); kvd.fHandled = false; pThis->CLASS::KeyValue( &kvd ); return kvd.fHandled != 0; } template<typename CLASS> void BaseEntity_Precache( CLASS* pThis ) { pThis->CLASS::Precache(); } template<typename CLASS> void BaseEntity_Spawn( CLASS* pThis ) { pThis->CLASS::Spawn(); } template<typename CLASS> void BaseEntity_Activate( CLASS* pThis ) { pThis->CLASS::Activate(); } template<typename CLASS> int BaseEntity_ObjectCaps( const CLASS* pThis ) { return pThis->CLASS::ObjectCaps(); } template<typename CLASS> void BaseEntity_SetObjectCollisionBox( CLASS* pThis ) { pThis->CLASS::SetObjectCollisionBox(); } template<typename CLASS> CBaseEntity* BaseEntity_Respawn( CLASS* pThis ) { return pThis->CLASS::Respawn(); } template<typename CLASS> void BaseEntity_Think( CLASS* pThis ) { pThis->CLASS::Think(); } template<typename CLASS> void BaseEntity_Touch( CLASS* pThis, CBaseEntity* pOther ) { pThis->CLASS::Touch( pOther ); } template<typename CLASS> void BaseEntity_Use( CLASS* pThis, CBaseEntity* pActivator, CBaseEntity* pCaller, USE_TYPE useType, float flValue ) { pThis->CLASS::Use( pActivator, pCaller, useType, flValue ); } template<typename CLASS> void BaseEntity_Blocked( CLASS* pThis, CBaseEntity* pOther ) { pThis->CLASS::Blocked( pOther ); } template<typename CLASS> EntityClassification_t BaseEntity_Classify( CLASS* pThis ) { return pThis->CLASS::Classify(); } template<typename CLASS> int BaseEntity_BloodColor( const CLASS* pThis ) { return pThis->CLASS::BloodColor(); } template<typename CLASS> void BaseEntity_TraceAttack( CLASS* pThis, const CTakeDamageInfo& info, Vector vecDir, TraceResult& tr ) { pThis->CLASS::TraceAttack( info, vecDir, tr ); } template<typename CLASS> void BaseEntity_TraceBleed( CLASS* pThis, const CTakeDamageInfo& info, Vector vecDir, TraceResult& tr ) { pThis->CLASS::TraceBleed( info, vecDir, tr ); } template<typename CLASS> void BaseEntity_OnTakeDamage( CLASS* pThis, const CTakeDamageInfo& info ) { pThis->CLASS::OnTakeDamage( info ); } template<typename CLASS> void BaseEntity_Killed( CLASS* pThis, const CTakeDamageInfo& info, GibAction gibAction ) { pThis->CLASS::Killed( info, gibAction ); } template<typename CLASS> float BaseEntity_GiveHealth( CLASS* pThis, float flHealth, int bitsDamageType ) { return pThis->CLASS::GiveHealth( flHealth, bitsDamageType ); } template<typename CLASS> bool BaseEntity_IsTriggered( const CLASS* pThis, const CBaseEntity* const pActivator ) { return pThis->CLASS::IsTriggered( pActivator ); } //TODO: MyMonsterPointer - Solokiller template<typename CLASS> bool BaseEntity_IsMoving( const CLASS* pThis ) { return pThis->CLASS::IsMoving(); } template<typename CLASS> void BaseEntity_OverrideReset( CLASS* pThis ) { pThis->CLASS::OverrideReset(); } template<typename CLASS> int BaseEntity_DamageDecal( const CLASS* pThis, int bitsDamageType ) { return pThis->CLASS::DamageDecal( bitsDamageType ); } template<typename CLASS> bool BaseEntity_OnControls( const CLASS* pThis, const CBaseEntity* const pTest ) { return pThis->CLASS::OnControls( pTest ); } template<typename CLASS> bool BaseEntity_IsAlive( const CLASS* pThis ) { return pThis->CLASS::IsAlive(); } template<typename CLASS> bool BaseEntity_IsBSPModel( const CLASS* pThis ) { return pThis->CLASS::IsBSPModel(); } template<typename CLASS> bool BaseEntity_ReflectGauss( const CLASS* pThis ) { return pThis->CLASS::ReflectGauss(); } template<typename CLASS> bool BaseEntity_HasTarget( const CLASS* pThis, string_t targetname ) { return pThis->CLASS::HasTarget( targetname ); } template<typename CLASS> bool BaseEntity_IsInWorld( const CLASS* pThis ) { return pThis->CLASS::IsInWorld(); } template<typename CLASS> std::string BaseEntity_TeamID( const CLASS* pThis ) { return pThis->CLASS::TeamID(); } template<typename CLASS> CBaseEntity* BaseEntity_GetNextTarget( CLASS* pThis ) { return pThis->CLASS::GetNextTarget(); } template<typename CLASS> bool BaseEntity_IsLockedByMaster( const CLASS* pThis ) { return pThis->CLASS::IsLockedByMaster(); } template<typename CLASS> void BaseEntity_DeathNotice( CLASS* pThis, CBaseEntity* pChild ) { pThis->CLASS::DeathNotice( pChild ); } template<typename CLASS> bool BaseEntity_BarnacleVictimGrabbed( CLASS* pThis, CBaseEntity* pBarnacle ) { return pThis->CLASS::BarnacleVictimGrabbed( pBarnacle ); } template<typename CLASS> Vector BaseEntity_Center( const CLASS* pThis ) { return pThis->CLASS::Center(); } template<typename CLASS> Vector BaseEntity_EyePosition( const CLASS* pThis ) { return pThis->CLASS::EyePosition(); } template<typename CLASS> Vector BaseEntity_EarPosition( const CLASS* pThis ) { return pThis->CLASS::EarPosition(); } template<typename CLASS> Vector BaseEntity_BodyTarget( const CLASS* pThis, const Vector& posSrc ) { return pThis->CLASS::BodyTarget( posSrc ); } template<typename CLASS> int BaseEntity_Illumination( const CLASS* pThis ) { return pThis->CLASS::Illumination(); } template<typename CLASS> bool BaseEntity_FVisible( const CLASS* pThis, const CBaseEntity* pEntity ) { return pThis->CLASS::FVisible( pEntity ); } template<typename CLASS> bool BaseEntity_FVisible( const CLASS* pThis, const Vector& vecOrigin ) { return pThis->CLASS::FVisible( vecOrigin ); } /** * Registers CBaseEntity methods for the BaseClass type for CLASS. * @param engine Script engine. * @param pszObjectName Name of the class to register. */ template<typename CLASS> void RegisterScriptBaseEntity( asIScriptEngine& engine, const char* const pszObjectName ) { engine.RegisterObjectType( pszObjectName, 0, asOBJ_REF | asOBJ_NOCOUNT ); engine.RegisterObjectMethod( pszObjectName, "void OnCreate()", asFUNCTION( BaseEntity_OnCreate<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void OnDestroy()", asFUNCTION( BaseEntity_OnDestroy<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void UpdateOnRemove()", asFUNCTION( BaseEntity_UpdateOnRemove<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void KeyValue(KeyValueData@ pkvd)", asFUNCTIONPR( BaseEntity_KeyValue<CLASS>, ( CLASS*, KeyValueData* ), void ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool KeyValue(const string& in szKey, const string& in szValue)", asFUNCTIONPR( BaseEntity_KeyValue<CLASS>, ( CLASS*, const std::string&, const std::string& ), bool ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void Precache()", asFUNCTION( BaseEntity_Precache<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void Spawn()", asFUNCTION( BaseEntity_Spawn<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void Activate()", asFUNCTION( BaseEntity_Activate<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "int ObjectCaps() const", asFUNCTION( BaseEntity_ObjectCaps<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void SetObjectCollisionBox()", asFUNCTION( BaseEntity_SetObjectCollisionBox<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "CBaseEntity@ Respawn()", asFUNCTION( BaseEntity_Respawn<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void Think()", asFUNCTION( BaseEntity_Think<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void Touch(CBaseEntity@ pOther)", asFUNCTION( BaseEntity_Touch<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void Use(CBaseEntity@ pActivator, CBaseEntity@ pCaller, USE_TYPE useType, float flValue)", asFUNCTION( BaseEntity_Use<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void Blocked(CBaseEntity@ pOther)", asFUNCTION( BaseEntity_Blocked<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "EntityClassification_t Classify()", asFUNCTION( BaseEntity_Classify<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "int BloodColor() const", asFUNCTION( BaseEntity_BloodColor<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void TraceAttack(const CTakeDamageInfo& in info, Vector vecDir, TraceResult& in tr)", asFUNCTION( BaseEntity_TraceAttack<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void TraceBleed(const CTakeDamageInfo& in info, Vector vecDir, TraceResult& in tr)", asFUNCTION( BaseEntity_TraceBleed<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void OnTakeDamage(const CTakeDamageInfo& in info)", asFUNCTION( BaseEntity_OnTakeDamage<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void Killed(const CTakeDamageInfo& in info, GibAction gibAction)", asFUNCTION( BaseEntity_Killed<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "float GiveHealth(float flHealth, int bitsDamageTypes)", asFUNCTION( BaseEntity_GiveHealth<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool IsTriggered(const CBaseEntity@ pActivator) const", asFUNCTION( BaseEntity_IsTriggered<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool IsMoving() const", asFUNCTION( BaseEntity_IsMoving<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void OverrideReset()", asFUNCTION( BaseEntity_OverrideReset<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "int DamageDecal(int bitsDamageType) const", asFUNCTION( BaseEntity_DamageDecal<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool OnControls(const CBaseEntity@ pTest) const", asFUNCTION( BaseEntity_OnControls<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool IsAlive() const", asFUNCTION( BaseEntity_IsAlive<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool IsBSPModel() const", asFUNCTION( BaseEntity_IsBSPModel<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool ReflectGauss() const", asFUNCTION( BaseEntity_ReflectGauss<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool HasTarget(string_t targetname) const", asFUNCTION( BaseEntity_HasTarget<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool IsInWorld() const", asFUNCTION( BaseEntity_IsInWorld<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "string TeamID() const", asFUNCTION( BaseEntity_TeamID<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "CBaseEntity@ GetNextTarget()", asFUNCTION( BaseEntity_GetNextTarget<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool IsLockedByMaster() const", asFUNCTION( BaseEntity_IsLockedByMaster<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "void DeathNotice(CBaseEntity@ pChild)", asFUNCTION( BaseEntity_DeathNotice<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool BarnacleVictimGrabbed(CBaseEntity@ pBarnacle)", asFUNCTION( BaseEntity_BarnacleVictimGrabbed<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "Vector Center() const", asFUNCTION( BaseEntity_Center<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "Vector EyePosition() const", asFUNCTION( BaseEntity_EyePosition<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "Vector EarPosition() const", asFUNCTION( BaseEntity_EarPosition<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "Vector BodyTarget(const Vector& in posSrc) const", asFUNCTION( BaseEntity_BodyTarget<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "int Illumination() const", asFUNCTION( BaseEntity_Illumination<CLASS> ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool FVisible(const CBaseEntity@ pEntity) const", asFUNCTIONPR( BaseEntity_FVisible<CLASS>, ( const CLASS*, const CBaseEntity* ), bool ), asCALL_CDECL_OBJFIRST ); engine.RegisterObjectMethod( pszObjectName, "bool FVisible(const Vector& in vecOrigin) const", asFUNCTIONPR( BaseEntity_FVisible<CLASS>, ( const CLASS*, const Vector& ), bool ), asCALL_CDECL_OBJFIRST ); } /** * Registers the BaseClass type for CBaseEntity: BaseEntity. */ inline void RegisterScriptBaseEntity( asIScriptEngine& engine ) { RegisterScriptBaseEntity<CBaseEntity>( engine, AS_CBASEENTITY_NAME + 1 ); } #endif //GAME_SERVER_ANGELSCRIPT_SCRIPTAPI_ENTITIES_ASCBASEENTITY_H
33.781741
128
0.773047
[ "object", "vector", "solid" ]
1a01c32e99e755e8b0ba32c4fbb19b75f5afd483
1,188
h
C
include/ecs_define.h
OttoX/Fomalhaut
2df91e90121488bb73c17a58e01a568d03140cc4
[ "MIT" ]
30
2018-01-09T14:34:19.000Z
2022-03-28T17:42:44.000Z
include/ecs_define.h
OttoX/Fomalhaut
2df91e90121488bb73c17a58e01a568d03140cc4
[ "MIT" ]
null
null
null
include/ecs_define.h
OttoX/Fomalhaut
2df91e90121488bb73c17a58e01a568d03140cc4
[ "MIT" ]
3
2018-05-10T13:27:34.000Z
2020-03-25T10:11:13.000Z
#pragma once #include <cstdint> #include <vector> #include <type_traits> #include <cassert> namespace ecs { using EntityID = uint32_t; using index_t = uint32_t; using ComponentIndexList = std::vector<index_t>; #define ECS_ASSERT(Expr, Msg) if(!(Expr)) throw std::runtime_error(Msg); #ifndef ECS_ASSERT #define ECS_ASSERT(Expr, Msg) assert(Expr && Msg) #pragma message("ECS_ASSERT defined!") #endif #define ECS_ASSERT_IS_CALLABLE(T) \ \ static_assert(details::is_callable<T>::value, "Provide a function or lambda expression"); #define ECS_ASSERT_IS_ENTITY(T) static_assert(std::is_same<class Entity, T>::value, #T " is not entity"); #define ECS_ASSERT_IS_COMPONENT(T) \ static_assert((std::is_base_of<BaseComponent, T>::value && !std::is_same<BaseComponent, T>::value), \ "Class type must be derived from BaseComponent"); #define ECS_ASSERT_IS_SYSTEM(T) \ static_assert((std::is_base_of<BaseSystem, T>::value && !std::is_same<BaseSystem, T>::value), \ #T " must be derived from BaseSystem"); }
33
105
0.627946
[ "vector" ]
1a0c37e36cb6796b5a8c32536195ea5dec3ad0f0
5,886
c
C
src/jni_lapack/c/QRDecomposition.c
zijzhao1996/JAMAJni
d61511646ebf726f17af4fd9d5c6aebe3d7b2182
[ "AAL" ]
1
2020-07-22T12:56:29.000Z
2020-07-22T12:56:29.000Z
src/jni_lapack/c/QRDecomposition.c
zijzhao1996/JAMAJni
d61511646ebf726f17af4fd9d5c6aebe3d7b2182
[ "AAL" ]
null
null
null
src/jni_lapack/c/QRDecomposition.c
zijzhao1996/JAMAJni
d61511646ebf726f17af4fd9d5c6aebe3d7b2182
[ "AAL" ]
null
null
null
#include <jni.h> #include <assert.h> #include <QRDecomposition.h> #include <stdlib.h> /* two functions that deal with matrix layout */ void CRswitch (double *in, double *out, int m, int n, int ldin, int ldout); void RCswitch (double *in, double *out, int m, int n, int ldin, int ldout); double *create_vectord (int dim); /* Calling fortran lapack from liblapack */ extern int dgeqrf_(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info); extern int dorgqr_(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info); extern int dgeqp3_(int *m, int *n, double *a, int *lda, int *jpvt, double *tau, double *work, int *lwork, int *info); #define jniRowMajor 101 #define jniColMajor 102 JNIEXPORT jint JNICALL Java_JAMAJni_jni_1lapack_QRDecomposition_dgeqrf (JNIEnv *env, jclass obj, jint layout, jint m, jint n, jdoubleArray ja, jint lda, jdoubleArray jtau, jdoubleArray jwork, jint lwork, jintArray jinfo) { double *a = (*env)-> GetDoubleArrayElements (env, ja, NULL); double *tau = (*env)-> GetDoubleArrayElements (env, jtau, NULL); double *work = (*env)-> GetDoubleArrayElements (env, jwork, NULL); int *info = (*env)-> GetIntArrayElements(env,jinfo,NULL); int result; if (layout == jniColMajor){ result = dgeqrf_(&m, &n, a, &lda, tau, work, &lwork, info); } else if (layout == jniRowMajor) { if (lda < n) { fprintf(stderr, "** Illegal value of lda for row-major layout\n"); return -1; } double *a_t = create_vectord(m*n); int lda_t = m; RCswitch(a, a_t, m, n, lda, lda_t); result = dgeqrf_(&m, &n, a_t, &lda_t, tau, work, &lwork, info); CRswitch(a_t, a, m, n, lda_t, lda); free(a_t); } else { fprintf(stderr, "** Illegal layout setting\n"); return -1; } (*env)-> ReleaseDoubleArrayElements (env, ja, a, 0); (*env)-> ReleaseDoubleArrayElements (env, jtau, tau, 0); (*env)-> ReleaseDoubleArrayElements (env, jwork, work, 0); (*env)-> ReleaseIntArrayElements (env, jinfo, info, 0); return result; } JNIEXPORT jint JNICALL Java_JAMAJni_jni_1lapack_QRDecomposition_dorgqr (JNIEnv *env, jclass obj, jint layout, jint m, jint n, jint k, jdoubleArray ja, jint lda, jdoubleArray jtau, jdoubleArray jwork, jint lwork, jintArray jinfo) { double *a = (*env)-> GetDoubleArrayElements (env, ja, NULL); double *tau = (*env)-> GetDoubleArrayElements (env, jtau, NULL); double *work = (*env)-> GetDoubleArrayElements (env, jwork, NULL); int *info = (*env)-> GetIntArrayElements(env,jinfo,NULL); int result; if (layout == jniColMajor) { result = dorgqr_(&m, &n, &k, a, &lda, tau, work, &lwork, info); } else if (layout == jniRowMajor) { if (lda < n) { fprintf(stderr, "** Illegal value of lda for row-major layout\n"); return -1; } double *a_t = create_vectord(m*n); int lda_t = m; RCswitch(a, a_t, m, n, lda, lda_t); result = dorgqr_(&m, &n, &k, a_t, &lda_t, tau, work, &lwork, info); CRswitch(a_t, a, m, n, lda_t, lda); free(a_t); } else { fprintf(stderr, "** Illegal layout setting\n"); return -1; } (*env)-> ReleaseDoubleArrayElements (env, ja, a, 0); (*env)-> ReleaseDoubleArrayElements (env, jtau, tau, JNI_ABORT); (*env)-> ReleaseDoubleArrayElements (env, jwork, work, 0); (*env)-> ReleaseIntArrayElements (env, jinfo, info, 0); return result; } JNIEXPORT jint JNICALL Java_JAMAJni_jni_1lapack_QRDecomposition_dgeqp3 (JNIEnv *env, jclass obj, jint layout, jint m, jint n, jdoubleArray ja, jint lda, jintArray jjpvt, jdoubleArray jtau, jdoubleArray jwork, jint lwork, jintArray jinfo) { double *a = (*env)-> GetDoubleArrayElements (env, ja, NULL); int *jpvt = (*env)-> GetIntArrayElements (env, jjpvt, NULL); double *tau = (*env)-> GetDoubleArrayElements (env, jtau, NULL); double *work = (*env)-> GetDoubleArrayElements (env, jwork, NULL); int *info = (*env)-> GetIntArrayElements(env,jinfo,NULL); int result; if (layout == jniColMajor){ result = dgeqp3_(&m, &n, a, &lda, jpvt, tau, work, &lwork, info); } else if (layout == jniRowMajor) { if (lda < n) { fprintf(stderr, "** Illegal value of lda for row-major layout\n"); return -1; } double *a_t = create_vectord(m*n); int lda_t = m; RCswitch(a, a_t, m, n, lda, lda_t); result = dgeqp3_(&m, &n, a_t, &lda_t, jpvt, tau, work, &lwork, info); CRswitch(a_t, a, m, n, lda_t, lda); free(a_t); } else {fprintf(stderr, "** Illegal layout setting\n"); return -1;} (*env)-> ReleaseDoubleArrayElements (env, ja, a, 0); (*env)-> ReleaseDoubleArrayElements (env, jtau, tau, 0); (*env)-> ReleaseDoubleArrayElements (env, jwork, work, 0); (*env)-> ReleaseIntArrayElements (env, jjpvt, jpvt, 0); (*env)-> ReleaseIntArrayElements (env, jinfo, info, 0); return result; } /* switch row-major and col-major*/ void RCswitch (double *in, double *out, int m, int n, int ldin, int ldout) { int i,j; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { out[j * ldout + i] = in[i * ldin + j]; } } } void CRswitch (double *in, double *out, int m, int n, int ldin, int ldout) { int i, j; for(i = 0; i < m; i++) { for( j = 0; j < n; j++) { out[i * ldout + j] = in[j * ldin + i]; } } } double *create_vectord (int dim) { double *vector; vector = (double *) malloc (dim * sizeof (double)); assert(vector); return vector; }
30.978947
79
0.589025
[ "vector" ]
1a1cb5863b7606ed195c7885b5988934b76d6962
1,627
h
C
libvmi/include/vmi/DecreeFile.h
trusslab/mousse
eb6ac492b15e2ca416a3b23bd4c4d115ae83b606
[ "MIT" ]
7
2020-04-27T03:53:16.000Z
2021-12-31T02:04:48.000Z
libvmi/include/vmi/DecreeFile.h
trusslab/mousse
eb6ac492b15e2ca416a3b23bd4c4d115ae83b606
[ "MIT" ]
null
null
null
libvmi/include/vmi/DecreeFile.h
trusslab/mousse
eb6ac492b15e2ca416a3b23bd4c4d115ae83b606
[ "MIT" ]
1
2020-07-15T05:19:28.000Z
2020-07-15T05:19:28.000Z
/// /// Copyright (C) 2014, Cyberhaven /// All rights reserved. /// /// Licensed under the Cyberhaven Research License Agreement. /// #ifndef VMI_DECREE_FILE_H #define VMI_DECREE_FILE_H #include "Decree.h" #include "ExecutableFile.h" namespace vmi { class DecreeFile : public ExecutableFile { private: std::string m_moduleName; uint64_t m_imageBase; uint64_t m_imageSize; uint64_t m_entryPoint; decree::DECREE32_hdr m_header; std::vector<decree::DECREE32_phdr> m_phdrs; Sections m_sections; bool initialize(void); int getSectionIndex(uint64_t va) const; protected: DecreeFile(FileProvider *file, bool loaded, uint64_t loadAddress); public: static ExecutableFile *get(FileProvider *file, bool loaded, uint64_t loadAddress); virtual ~DecreeFile(); virtual std::string getModuleName() const { return m_moduleName; } virtual uint64_t getImageBase() const { return m_imageBase; } virtual uint64_t getImageSize() const { return m_imageSize; } virtual uint64_t getEntryPoint() const { return m_entryPoint; } const Sections &getSections() const { return m_sections; } virtual bool getSymbolAddress(const std::string &name, uint64_t *address) { return false; } virtual bool getSourceInfo(uint64_t addr, std::string &source, uint64_t &line, std::string &function) { return false; } virtual unsigned getPointerSize() const { return sizeof(uint32_t); } virtual ssize_t read(void *buffer, size_t nbyte, off64_t offset) const; }; } #endif
20.858974
107
0.68531
[ "vector" ]
1a2e2271cd936d5a40966168e0318dc82947db2c
20,400
c
C
benchmarks/source/superh/sphinx3/src/libfbs/allphone.c
rhudson2802/sunflower-simulator
9f55e03c9d80c024a75029d0e842cc5c92f31c82
[ "BSD-3-Clause" ]
7
2016-05-07T13:38:33.000Z
2019-07-08T03:42:24.000Z
benchmarks/source/superh/sphinx3/src/libfbs/allphone.c
rhudson2802/sunflower-simulator
9f55e03c9d80c024a75029d0e842cc5c92f31c82
[ "BSD-3-Clause" ]
80
2019-08-27T14:43:46.000Z
2020-12-16T11:56:19.000Z
benchmarks/source/superh/sphinx3/src/libfbs/allphone.c
rhudson2802/sunflower-simulator
9f55e03c9d80c024a75029d0e842cc5c92f31c82
[ "BSD-3-Clause" ]
98
2019-08-30T14:29:16.000Z
2020-11-21T18:22:13.000Z
/* * allphone.c -- Allphone Viterbi decoding. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 02-Jun-97 M K Ravishankar (rkm@cs.cmu.edu) at Carnegie Mellon University * Added allphone lattice output. * * 14-Oct-96 M K Ravishankar (rkm@cs.cmu.edu) at Carnegie Mellon University * Started. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <libutil/libutil.h> #include <s3.h> #include "s3types.h" #include "mdef.h" #include "tmat.h" #include "logs3.h" #include "allphone.h" /* * SOME ASSUMPTIONS * - All phones (ciphones and triphones) have same HMM topology with n_state states. * - Initial state = state 0; final state = state n_state-1. * - Final state is a non-emitting state with no arcs out of it. * - Some form of Bakis topology (ie, no cycles, except for self-transitions). */ /* * Phone-HMM (PHMM) structure: Models a single unique <senone-sequence, tmat> pair. * Can represent several different triphones, but all with the same parent basephone. * (NOTE: Word-position attribute of triphone is ignored.) */ typedef struct phmm_s { s3pid_t pid; /* Phone id (temp. during init.) */ s3tmatid_t tmat; /* Transition matrix id for this PHMM */ s3cipid_t ci; /* Parent basephone for this PHMM */ s3frmid_t active; /* Latest frame in which this PHMM is/was active */ uint32 *lc; /* Set (bit-vector) of left context phones seen for this PHMM */ uint32 *rc; /* Set (bit-vector) of right context phones seen for this PHMM */ s3senid_t *sen; /* Senone-id sequence underlying this PHMM */ int32 *score; /* Total path score during Viterbi decoding */ struct history_s **hist; /* Viterbi history (for backtrace) */ int32 bestscore; /* Best state score in any frame */ int32 inscore; /* Incoming score from predecessor PHMMs */ struct history_s *inhist; /* History corresponding to inscore */ struct phmm_s *next; /* Next unique PHMM for same parent basephone */ struct plink_s *succlist; /* List of predecessor PHMM nodes */ } phmm_t; static phmm_t **ci_phmm; /* PHMM lists (for each CI phone) */ /* * List of links from a PHMM node to its successors; one link per successor. */ typedef struct plink_s { phmm_t *phmm; /* Successor PHMM node */ struct plink_s *next; /* Next link for parent PHMM node */ } plink_t; /* * History (paths) information at any point in allphone Viterbi search. */ typedef struct history_s { phmm_t *phmm; /* PHMM ending this path */ int32 score; /* Path score for this path */ s3frmid_t ef; /* End frame */ struct history_s *hist; /* Previous history entry */ struct history_s *next; /* Next in allocated list */ } history_t; static history_t **frm_hist; /* List of history nodes allocated in each frame */ static mdef_t *mdef; /* Model definition */ static tmat_t *tmat; /* Transition probability matrices */ static int32 lrc_size = 0; static int32 curfrm; /* Current frame */ static int32 beam; static int32 *score_scale; /* Score by which state scores scaled in each frame */ static phseg_t *phseg; static int32 **tp; /* Phone transition probabilities */ /* * Find PHMM node with same senone sequence and tmat id as the given triphone. * Return ptr to PHMM node if found, NULL otherwise. */ static phmm_t *phmm_lookup (s3pid_t pid) { phmm_t *p; phone_t *old, *new; int32 s; new = &(mdef->phone[pid]); for (p = ci_phmm[mdef->phone[pid].ci]; p; p = p->next) { old = &(mdef->phone[p->pid]); if (old->tmat == new->tmat) { for (s = 0; (s < mdef->n_emit_state) && (old->state[s] == new->state[s]); s++); if (s == mdef->n_emit_state) return p; } } return NULL; } static void lrc_set (uint32 *vec, int32 ci) { int32 i, j; assert (lrc_size > 0); /* If lc or rc not specified, set all flags */ if (NOT_CIPID(ci)) { for (i = 0; i < lrc_size; i++) vec[i] = (uint32) 0xffffffff; } else { i = (ci >> 5); j = ci - (i << 5); vec[i] |= (1 << j); } } static int32 lrc_is_set (uint32 *vec, int32 ci) { int32 i, j; i = (ci >> 5); j = ci - (i << 5); return (vec[i] & (1 << j)); } static int32 phmm_link ( void ) { s3cipid_t ci, rc; phmm_t *p, *p2; int32 *rclist; int32 i, n_link; plink_t *l; rclist = (int32 *) ckd_calloc (mdef->n_ciphone+1, sizeof(int32)); /* Create successor links between PHMM nodes */ n_link = 0; for (ci = 0; ci < mdef->n_ciphone; ci++) { for (p = ci_phmm[ci]; p; p = p->next) { /* Build rclist for p */ i = 0; for (rc = 0; rc < mdef->n_ciphone; rc++) { if (lrc_is_set (p->rc, rc)) rclist[i++] = rc; } rclist[i] = BAD_CIPID; /* For each rc in rclist, transition to PHMMs for rc if left context = ci */ for (i = 0; IS_CIPID(rclist[i]); i++) { for (p2 = ci_phmm[rclist[i]]; p2; p2 = p2->next) { if (lrc_is_set (p2->lc, ci)) { /* transition from p to p2 */ l = (plink_t *) listelem_alloc (sizeof(plink_t)); l->phmm = p2; l->next = p->succlist; p->succlist = l; n_link++; } } } } } ckd_free (rclist); return n_link; } static int32 phmm_build ( void ) { s3pid_t pid; phmm_t *p, **pid2phmm; s3cipid_t ci; int32 n_phmm, n_link; s3senid_t *sen; int32 *score; history_t **hist; uint32 *lc, *rc; int32 i, s; s3cipid_t *filler; E_INFO("Building PHMM net\n"); ci_phmm = (phmm_t **) ckd_calloc (mdef->n_ciphone, sizeof(phmm_t *)); pid2phmm = (phmm_t **) ckd_calloc (mdef->n_phone, sizeof(phmm_t *)); for (lrc_size = 32; lrc_size < mdef->n_ciphone; lrc_size += 32); lrc_size >>= 5; /* For each unique ciphone/triphone entry in mdef, create a PHMM node */ n_phmm = 0; for (pid = 0; pid < mdef->n_phone; pid++) { if ((p = phmm_lookup (pid)) == NULL) { /* No previous entry; create a new one */ p = (phmm_t *) listelem_alloc (sizeof(phmm_t)); p->pid = pid; p->tmat = mdef->phone[pid].tmat; p->ci = mdef->phone[pid].ci; p->succlist = NULL; p->next = ci_phmm[p->ci]; ci_phmm[p->ci] = p; n_phmm++; } pid2phmm[pid] = p; } /* Fill out rest of each PHMM node */ sen = (s3senid_t *) ckd_calloc (n_phmm * mdef->n_emit_state, sizeof(s3senid_t)); score = (int32 *) ckd_calloc (n_phmm * (mdef->n_emit_state+1), sizeof(int32)); hist = (history_t **) ckd_calloc (n_phmm * (mdef->n_emit_state+1), sizeof(history_t *)); lc = (uint32 *) ckd_calloc (n_phmm * lrc_size * 2, sizeof(uint32)); rc = lc + (n_phmm * lrc_size); for (ci = 0; ci < mdef->n_ciphone; ci++) { for (p = ci_phmm[ci]; p; p = p->next) { p->sen = sen; for (s = 0; s < mdef->n_emit_state; s++) p->sen[s] = mdef->phone[p->pid].state[s]; sen += mdef->n_emit_state; p->score = score; score += (mdef->n_emit_state + 1); p->hist = hist; hist += (mdef->n_emit_state + 1); p->lc = lc; lc += lrc_size; p->rc = rc; rc += lrc_size; } } /* Fill out lc and rc bitmaps (remember to map all fillers to each other!!) */ filler = (s3cipid_t *) ckd_calloc (mdef->n_ciphone + 1, sizeof(s3cipid_t)); i = 0; for (ci = 0; ci < mdef->n_ciphone; ci++) { if (mdef->ciphone[ci].filler) filler[i++] = ci; } filler[i] = BAD_CIPID; for (pid = 0; pid < mdef->n_phone; pid++) { p = pid2phmm[pid]; if (IS_CIPID(mdef->phone[pid].lc) && mdef->ciphone[mdef->phone[pid].lc].filler) { for (i = 0; IS_CIPID(filler[i]); i++) lrc_set (p->lc, filler[i]); } else lrc_set (p->lc, mdef->phone[pid].lc); if (IS_CIPID(mdef->phone[pid].rc) && mdef->ciphone[mdef->phone[pid].rc].filler) { for (i = 0; IS_CIPID(filler[i]); i++) lrc_set (p->rc, filler[i]); } else lrc_set (p->rc, mdef->phone[pid].rc); } ckd_free (pid2phmm); ckd_free (filler); /* Create links between PHMM nodes */ n_link = phmm_link (); E_INFO ("%d nodes, %d links\n", n_phmm, n_link); return 0; } static void phmm_dump ( void ) { s3cipid_t ci, lc, rc; phmm_t *p; plink_t *l; printf ("Nodes:\n"); for (ci = 0; ci < mdef->n_ciphone; ci++) { for (p = ci_phmm[ci]; p; p = p->next) { printf ("%5d\t%s", p->pid, mdef_ciphone_str (mdef, p->ci)); printf ("\tLC="); for (lc = 0; lc < mdef->n_ciphone; lc++) if (lrc_is_set (p->lc, lc)) printf (" %s", mdef_ciphone_str (mdef, lc)); printf ("\tRC="); for (rc = 0; rc < mdef->n_ciphone; rc++) if (lrc_is_set (p->rc, rc)) printf (" %s", mdef_ciphone_str (mdef, rc)); printf ("\n"); } } for (ci = 0; ci < mdef->n_ciphone; ci++) { for (p = ci_phmm[ci]; p; p = p->next) { printf ("%5d -> ", p->pid); for (l = p->succlist; l; l = l->next) printf (" %5d", l->phmm->pid); printf ("\n"); } } } /* * Check model tprob matrices that they conform to upper-diagonal assumption. */ static void chk_tp_uppertri ( void ) { int32 i, n_state, from, to; n_state = mdef->n_emit_state + 1; /* Check that each tmat is upper-triangular */ for (i = 0; i < tmat->n_tmat; i++) { for (to = 0; to < n_state-1; to++) for (from = to+1; from < n_state-1; from++) if (tmat->tp[i][from][to] > LOGPROB_ZERO) E_FATAL("HMM transition matrix not upper triangular\n"); } } int32 allphone_start_utt (char *uttid) { s3cipid_t ci; phmm_t *p; int32 s; for (ci = 0; ci < mdef->n_ciphone; ci++) { for (p = ci_phmm[ci]; p; p = p->next) { p->active = -1; p->inscore = LOGPROB_ZERO; p->bestscore = LOGPROB_ZERO; for (s = 0; s <= mdef->n_emit_state; s++) { p->score[s] = LOGPROB_ZERO; p->hist[s] = NULL; } } } curfrm = 0; /* Initialize start state of the SILENCE PHMM */ ci = mdef_ciphone_id (mdef, SILENCE_CIPHONE); if (NOT_CIPID(ci)) E_FATAL("Cannot find CI-phone %s\n", SILENCE_CIPHONE); for (p = ci_phmm[ci]; p && (p->pid != ci); p = p->next); if (! p) E_FATAL("Cannot find HMM for %s\n", SILENCE_CIPHONE); p->inscore = 0; p->inhist = NULL; p->active = curfrm; return 0; } static void phmm_eval (phmm_t *p, int32 *senscr) { int32 **tp; int32 nst, from, to, bestfrom, newscr, bestscr; history_t *besthist; nst = mdef->n_emit_state; tp = tmat->tp[p->tmat]; bestscr = LOGPROB_ZERO; /* Update state scores from last to first (assuming no backward transitions) */ for (to = nst-1; to >= 0; --to) { /* Find best incoming score to the "to" state from predecessor states */ bestfrom = LOGPROB_ZERO; for (from = to; from >= 0; from--) { if ((tp[from][to] > LOGPROB_ZERO) && (p->score[from] > LOGPROB_ZERO)) { newscr = p->score[from] + tp[from][to]; if (newscr > bestfrom) { bestfrom = newscr; besthist = p->hist[from]; } } } /* If looking at initial state, also consider incoming score */ if ((to == 0) && (p->inscore > bestfrom)) { bestfrom = p->inscore; besthist = p->inhist; } /* Update state score */ if (bestfrom > LOGPROB_ZERO) { p->score[to] = bestfrom + senscr[p->sen[to]]; p->hist[to] = besthist; if (p->score[to] > bestscr) bestscr = p->score[to]; } } /* Update non-emitting exit state score */ bestfrom = LOGPROB_ZERO; to = nst; for (from = nst-1; from >= 0; from--) { if ((tp[from][to] > LOGPROB_ZERO) && (p->score[from] > LOGPROB_ZERO)) { newscr = p->score[from] + tp[from][to]; if (newscr > bestfrom) { bestfrom = newscr; besthist = p->hist[from]; } } } p->score[to] = bestfrom; p->hist[to] = besthist; if (p->score[to] > bestscr) bestscr = p->score[to]; p->bestscore = bestscr; } /* Evaluate active PHMMs */ static int32 phmm_eval_all (int32 *senscr) { s3cipid_t ci; phmm_t *p; int32 best; best = LOGPROB_ZERO; for (ci = 0; ci < mdef->n_ciphone; ci++) { for (p = ci_phmm[ci]; p; p = p->next) { if (p->active == curfrm) { phmm_eval (p, senscr); if (p->bestscore > best) best = p->bestscore; } } } return best; } static void phmm_exit (int32 best) { s3cipid_t ci; phmm_t *p; int32 th, nf, nst, s; history_t *h; th = best + beam; frm_hist[curfrm] = NULL; nf = curfrm+1; nst = mdef->n_emit_state; for (ci = 0; ci < mdef->n_ciphone; ci++) { for (p = ci_phmm[ci]; p; p = p->next) { if (p->active == curfrm) { if (p->bestscore >= th) { /* Scale state scores to prevent underflow */ for (s = 0; s <= nst; s++) if (p->score[s] > LOGPROB_ZERO) p->score[s] -= best; /* Create lattice entry if exiting */ if (p->score[nst] >= beam) { /* beam, not th because scores scaled */ h = (history_t *) listelem_alloc (sizeof(history_t)); h->score = p->score[nst]; h->ef = curfrm; h->phmm = p; h->hist = p->hist[nst]; h->next = frm_hist[curfrm]; frm_hist[curfrm] = h; } /* Mark PHMM active in next frame */ p->active = nf; } else { /* Reset state scores */ for (s = 0; s <= nst; s++) { p->score[s] = LOGPROB_ZERO; p->hist[s] = NULL; } } } /* Reset incoming score in preparation for cross-PHMM transition */ p->inscore = LOGPROB_ZERO; } } } static void phmm_trans ( void ) { history_t *h; phmm_t *from, *to; plink_t *l; int32 newscore, nf; nf = curfrm+1; /* Transition from exited nodes to initial states of HMMs */ for (h = frm_hist[curfrm]; h; h = h->next) { from = h->phmm; for (l = from->succlist; l; l = l->next) { to = l->phmm; newscore = h->score + tp[from->ci][to->ci]; if ((newscore > beam) && (newscore > to->inscore)) { to->inscore = newscore; to->inhist = h; to->active = nf; } } } } int32 allphone_frame (int32 *senscr) { int32 bestscr; bestscr = phmm_eval_all (senscr); score_scale[curfrm] = bestscr; phmm_exit (bestscr); phmm_trans (); curfrm++; return 0; } /* Return accumulated score scale in frame range [sf..ef] */ static int32 seg_score_scale (int32 sf, int32 ef) { int32 scale, s; for (s = sf, scale = 0; s <= ef; s++, scale += score_scale[s]); return scale; } /* Phone lattice node */ typedef struct phlatnode_s { s3cipid_t ci; uint16 fef, lef; /* First and last end frame for this node */ struct phlatnode_s *next; } phlatnode_t; static void allphone_latdump (char *uttid, char *latdir) { int32 f, sf, score, latbeam, best, thresh, nnode; history_t *h; char filename[4096]; FILE *fp; float64 *f64arg; phlatnode_t **phlatnode, *p; f64arg = (float64 *) cmd_ln_access ("-phlatbeam"); latbeam = logs3 (*f64arg); sprintf (filename, "%s/%s.phlat", latdir, uttid); if ((fp = fopen(filename, "w")) == NULL) { E_ERROR("fopen(%s,w) failed\n", filename); return; } phlatnode = (phlatnode_t **) ckd_calloc (curfrm+1, sizeof(phlatnode_t)); for (f = 0; f < curfrm; f++) { /* Find best score for this frame and set pruning threshold */ best = (int32)0x80000000; for (h = frm_hist[f]; h; h = h->next) if (h->score > best) best = h->score; thresh = best + latbeam; for (h = frm_hist[f]; h; h = h->next) { /* Skip this node if below threshold */ if (h->score < thresh) continue; sf = h->hist ? h->hist->ef + 1 : 0; assert (h->ef == f); /* Find phlatnode for this <ci,sf> pair */ for (p = phlatnode[sf]; p && (p->ci != h->phmm->ci); p = p->next); if (! p) { p = (phlatnode_t *) listelem_alloc (sizeof(phlatnode_t)); p->next = phlatnode[sf]; phlatnode[sf] = p; p->ci = h->phmm->ci; p->fef = p->lef = h->ef; } assert (p->lef <= h->ef); p->lef = h->ef; #if 0 score = h->score; if (h->hist) score -= h->hist->score; score += seg_score_scale (sf, h->ef); fprintf (fp, "%4d %3d %12d %s\n", /* startfrm endfrm ciphone */ sf, h->ef - sf + 1, score, mdef_ciphone_str (mdef, h->phmm->ci)); #endif } } /* Write phone lattice; startframe, first end frame, last end frame, ciphone */ nnode = 0; for (f = 0; f <= curfrm; f++) { for (p = phlatnode[f]; p; p = p->next) { fprintf (fp, "%4d %4d %4d %s\n", f, p->fef, p->lef, mdef_ciphone_str (mdef, p->ci)); nnode++; } } E_INFO("%d phone lattice nodes written to %s\n", nnode, filename); /* Free phone lattice */ for (f = 0; f <= curfrm; f++) { for (p = phlatnode[f]; p; p = phlatnode[f]) { phlatnode[f] = p->next; listelem_free ((char *)p, sizeof(phlatnode_t)); } } ckd_free (phlatnode); fclose (fp); } phseg_t *allphone_end_utt (char *uttid) { history_t *h, *nexth, *besth; int32 f, best; phseg_t *s, *nexts; char *phlatdir; /* Free old phseg, if any */ for (s = phseg; s; s = nexts) { nexts = s->next; listelem_free ((char *)s, sizeof(phseg_t)); } phseg = NULL; /* Write phone lattice if specified */ if ((phlatdir = (char *) cmd_ln_access ("-phlatdir")) != NULL) allphone_latdump (uttid, phlatdir); /* Find most recent history nodes list */ for (f = curfrm-1; (f >= 0) && (frm_hist[f] == NULL); --f); if (f >= 0) { /* Find best of the most recent history nodes */ best = (int32) 0x80000000; for (h = frm_hist[f]; h; h = h->next) { if (h->score > best) { best = h->score; besth = h; } } /* Backtrace */ for (h = besth; h; h = h->hist) { s = (phseg_t *) listelem_alloc (sizeof(phseg_t)); s->ci = h->phmm->ci; s->sf = (h->hist) ? h->hist->ef + 1 : 0; s->ef = h->ef; s->score = h->score; if (h->hist) s->score -= h->hist->score; s->score += seg_score_scale (s->sf, s->ef); s->next = phseg; phseg = s; } } /* Free history nodes */ for (f = 0; f < curfrm; f++) { for (h = frm_hist[f]; h; h = nexth) { nexth = h->next; listelem_free ((char *) h, sizeof(history_t)); } frm_hist[f] = NULL; } return phseg; } static void phone_tp_init (char *file, float64 floor, float64 wt, float64 ip) { int32 i, j, ct, tot, inspen; FILE *fp; char p1[128], p2[128]; s3cipid_t pid1, pid2; float64 p; tp = (int32 **) ckd_calloc_2d (mdef->n_ciphone, mdef->n_ciphone, sizeof(int32)); inspen = logs3 (ip); if (! file) { for (i = 0; i < mdef->n_ciphone; i++) for (j = 0; j < mdef->n_ciphone; j++) tp[i][j] = inspen; return; } for (i = 0; i < mdef->n_ciphone; i++) for (j = 0; j < mdef->n_ciphone; j++) tp[i][j] = LOGPROB_ZERO; if ((fp = fopen(file, "r")) == NULL) E_FATAL("fopen(%s,r) failed\n", file); while (fscanf (fp, "%s %s %d %d", p1, p2, &ct, &tot) == 4) { pid1 = mdef_ciphone_id (mdef, p1); if (NOT_CIPID(pid1)) E_FATAL("Bad phone: %s\n", p1); pid2 = mdef_ciphone_id (mdef, p2); if (NOT_CIPID(pid2)) E_FATAL("Bad phone: %s\n", p2); if (tot > 0) p = ((float64)ct)/((float64)tot); else p = 0.0; if (p < floor) p = floor; tp[pid1][pid2] = (int32)(logs3(p) * wt) + inspen; } fclose (fp); } int32 allphone_init ( void ) { float64 *f64arg; char *file; float64 tpfloor, ip, wt; mdef = mdef_getmdef (); tmat = tmat_gettmat (); chk_tp_uppertri (); phmm_build (); file = (char *)cmd_ln_access("-phonetpfn"); if (! file) E_ERROR("-phonetpfn argument missing; assuming uniform transition probs\n"); tpfloor = *((float32 *) cmd_ln_access ("-phonetpfloor")); ip = *((float32 *) cmd_ln_access ("-inspen")); wt = *((float32 *) cmd_ln_access ("-phonetpwt")); phone_tp_init (file, tpfloor, wt, ip); f64arg = (float64 *) cmd_ln_access ("-beam"); beam = logs3 (*f64arg); E_INFO ("logs3(beam)= %d\n", beam); frm_hist = (history_t **) ckd_calloc (S3_MAX_FRAMES, sizeof(history_t *)); score_scale = (int32 *) ckd_calloc (S3_MAX_FRAMES, sizeof(int32)); phseg = NULL; return 0; }
25.341615
86
0.566569
[ "vector", "model", "3d" ]
1a4842956402e308426c0ed5ce5cc6042150361f
5,516
c
C
qemu/target/s390x/diag.c
hyunjoy/scripts
01114d3627730d695b5ebe61093c719744432ffa
[ "Apache-2.0" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
qemu/target/s390x/diag.c
hyunjoy/scripts
01114d3627730d695b5ebe61093c719744432ffa
[ "Apache-2.0" ]
1
2022-03-29T02:30:28.000Z
2022-03-30T03:40:46.000Z
qemu/target/s390x/diag.c
hyunjoy/scripts
01114d3627730d695b5ebe61093c719744432ffa
[ "Apache-2.0" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
/* * S390x DIAG instruction helper functions * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include "qemu/osdep.h" #include "cpu.h" #include "internal.h" #include "exec/address-spaces.h" #include "hw/watchdog/wdt_diag288.h" #include "sysemu/cpus.h" #include "hw/s390x/ipl.h" #include "hw/s390x/s390-virtio-ccw.h" #include "hw/s390x/pv.h" #include "kvm_s390x.h" int handle_diag_288(CPUS390XState *env, uint64_t r1, uint64_t r3) { uint64_t func = env->regs[r1]; uint64_t timeout = env->regs[r1 + 1]; uint64_t action = env->regs[r3]; Object *obj; DIAG288State *diag288; DIAG288Class *diag288_class; if (r1 % 2 || action != 0) { return -1; } /* Timeout must be more than 15 seconds except for timer deletion */ if (func != WDT_DIAG288_CANCEL && timeout < 15) { return -1; } obj = object_resolve_path_type("", TYPE_WDT_DIAG288, NULL); if (!obj) { return -1; } diag288 = DIAG288(obj); diag288_class = DIAG288_GET_CLASS(diag288); return diag288_class->handle_timer(diag288, func, timeout); } static int diag308_parm_check(CPUS390XState *env, uint64_t r1, uint64_t addr, uintptr_t ra, bool write) { /* Handled by the Ultravisor */ if (s390_is_pv()) { return 0; } if ((r1 & 1) || (addr & ~TARGET_PAGE_MASK)) { s390_program_interrupt(env, PGM_SPECIFICATION, ra); return -1; } if (!address_space_access_valid(&address_space_memory, addr, sizeof(IplParameterBlock), write, MEMTXATTRS_UNSPECIFIED)) { s390_program_interrupt(env, PGM_ADDRESSING, ra); return -1; } return 0; } void handle_diag_308(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra) { bool valid; CPUState *cs = env_cpu(env); S390CPU *cpu = S390_CPU(cs); uint64_t addr = env->regs[r1]; uint64_t subcode = env->regs[r3]; IplParameterBlock *iplb; if (env->psw.mask & PSW_MASK_PSTATE) { s390_program_interrupt(env, PGM_PRIVILEGED, ra); return; } if (subcode & ~0x0ffffULL) { s390_program_interrupt(env, PGM_SPECIFICATION, ra); return; } if (subcode >= DIAG308_PV_SET && !s390_has_feat(S390_FEAT_UNPACK)) { s390_program_interrupt(env, PGM_SPECIFICATION, ra); return; } switch (subcode) { case DIAG308_RESET_MOD_CLR: s390_ipl_reset_request(cs, S390_RESET_MODIFIED_CLEAR); break; case DIAG308_RESET_LOAD_NORM: s390_ipl_reset_request(cs, S390_RESET_LOAD_NORMAL); break; case DIAG308_LOAD_CLEAR: /* Well we still lack the clearing bit... */ s390_ipl_reset_request(cs, S390_RESET_REIPL); break; case DIAG308_SET: case DIAG308_PV_SET: if (diag308_parm_check(env, r1, addr, ra, false)) { return; } iplb = g_new0(IplParameterBlock, 1); if (!s390_is_pv()) { cpu_physical_memory_read(addr, iplb, sizeof(iplb->len)); } else { s390_cpu_pv_mem_read(cpu, 0, iplb, sizeof(iplb->len)); } if (!iplb_valid_len(iplb)) { env->regs[r1 + 1] = DIAG_308_RC_INVALID; goto out; } if (!s390_is_pv()) { cpu_physical_memory_read(addr, iplb, be32_to_cpu(iplb->len)); } else { s390_cpu_pv_mem_read(cpu, 0, iplb, be32_to_cpu(iplb->len)); } valid = subcode == DIAG308_PV_SET ? iplb_valid_pv(iplb) : iplb_valid(iplb); if (!valid) { env->regs[r1 + 1] = DIAG_308_RC_INVALID; goto out; } s390_ipl_update_diag308(iplb); env->regs[r1 + 1] = DIAG_308_RC_OK; out: g_free(iplb); return; case DIAG308_STORE: case DIAG308_PV_STORE: if (diag308_parm_check(env, r1, addr, ra, true)) { return; } if (subcode == DIAG308_PV_STORE) { iplb = s390_ipl_get_iplb_pv(); } else { iplb = s390_ipl_get_iplb(); } if (!iplb) { env->regs[r1 + 1] = DIAG_308_RC_NO_CONF; return; } if (!s390_is_pv()) { cpu_physical_memory_write(addr, iplb, be32_to_cpu(iplb->len)); } else { s390_cpu_pv_mem_write(cpu, 0, iplb, be32_to_cpu(iplb->len)); } env->regs[r1 + 1] = DIAG_308_RC_OK; return; case DIAG308_PV_START: iplb = s390_ipl_get_iplb_pv(); if (!iplb) { env->regs[r1 + 1] = DIAG_308_RC_NO_PV_CONF; return; } if (kvm_s390_get_hpage_1m()) { error_report("Protected VMs can currently not be backed with " "huge pages"); env->regs[r1 + 1] = DIAG_308_RC_INVAL_FOR_PV; return; } s390_ipl_reset_request(cs, S390_RESET_PV); break; default: s390_program_interrupt(env, PGM_SPECIFICATION, ra); break; } }
29.655914
83
0.598803
[ "object" ]
1a4969a1223540be4ad7195d7bb0e865c71d04c8
40,484
c
C
drivers/video/ms/ati/disp/overlay.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
drivers/video/ms/ati/disp/overlay.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
drivers/video/ms/ati/disp/overlay.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "precomp.h" // this will be compiled only for NT40 and greater #if TARGET_BUILD > 351 void ModifyOverlayPosition (PDEV* , LPRECTL , LPDWORD ); /* This procedure writes the Overlay pitch*/ __inline void WriteVTOverlayPitch (PDEV* ppdev, DWORD Pitch) { DD_WriteVTReg ( DD_BUF0_PITCH, Pitch ); DD_WriteVTReg ( DD_BUF1_PITCH, Pitch ); } void DeskScanCallback (PDEV* ppdev ) { RECTL rPhysOverlay; DWORD dwBuf0Offset, dwBuf1Offset; DWORD dwVInc = ppdev->OverlayInfo16.dwVInc; DWORD dwHInc = ppdev->OverlayInfo16.dwHInc; static DWORD dwOldVInc = 0, dwOldHInc = 0; static WORD wOldX = 0xFFFF, wOldY = 0xFFFF; static RECTL rOldPhysOverlay = { 0, 0, 0, 0 }; /* * If we have not allocated the overlay then we better not do * anything or we might collide with the video capture stuff */ if ( ! ( ppdev->OverlayInfo16.dwFlags & OVERLAY_ALLOCATED ) ) { return; } dwBuf0Offset = ppdev->OverlayInfo16.dwBuf0Start; dwBuf1Offset = ppdev->OverlayInfo16.dwBuf1Start; rPhysOverlay.top = ppdev->OverlayInfo16.rDst.top; rPhysOverlay.bottom = ppdev->OverlayInfo16.rDst.bottom ; rPhysOverlay.left = ppdev->OverlayInfo16.rDst.left ; rPhysOverlay.right = ppdev->OverlayInfo16.rDst.right ; /* * Turn off keyer if overlay has moved off the screen. */ if ( rPhysOverlay.right < 0 || rPhysOverlay.bottom < 0 || rPhysOverlay.left > ppdev->cxScreen - 1 || rPhysOverlay.top > ppdev->cyScreen - 1 ) { DD_WriteVTReg ( DD_OVERLAY_KEY_CNTL, 0x00000110L ); return; } /* * Adjust Offsets if overlay source rectangle is clipped */ if ( ppdev->OverlayInfo16.dwFlags & UPDATEOVERLAY ) { if ( ppdev->OverlayInfo16.rSrc.left > 0 ) { dwBuf0Offset += ppdev->OverlayInfo16.rSrc.left * 2; dwBuf1Offset += ppdev->OverlayInfo16.rSrc.left * 2; } if ( ppdev->OverlayInfo16.rSrc.top > 0 ) { if ( ppdev->OverlayInfo16.dwFlags & DOUBLE_PITCH ) { dwBuf0Offset += ppdev->OverlayInfo16.rSrc.top * ppdev->OverlayInfo16.lBuf0Pitch * 2; dwBuf1Offset += ppdev->OverlayInfo16.rSrc.top * ppdev->OverlayInfo16.lBuf1Pitch * 2; } else { dwBuf0Offset += ppdev->OverlayInfo16.rSrc.top * ppdev->OverlayInfo16.lBuf0Pitch; dwBuf1Offset += ppdev->OverlayInfo16.rSrc.top * ppdev->OverlayInfo16.lBuf1Pitch; } } } if ( M64_ID_DIRECT(ppdev->pjMmBase, CRTC_GEN_CNTL ) & CRTC_INTERLACE_EN ) ModifyOverlayPosition (ppdev, &rPhysOverlay, &dwVInc ); if ( dwVInc != dwOldVInc || dwHInc != dwOldHInc ) DD_WriteVTReg ( DD_OVERLAY_SCALE_INC, ( dwHInc << 16 ) | dwVInc ); /* * Try not to write new position at a bad time! */ // if ((ppdev->iAsic ==CI_M64_VTA)||(ppdev->iAsic ==CI_M64_GTA)) // { if ( rPhysOverlay.top != rOldPhysOverlay.top || rPhysOverlay.bottom != rOldPhysOverlay.bottom || rPhysOverlay.left != rOldPhysOverlay.left || rPhysOverlay.right != rOldPhysOverlay.right ) //((M64_ID(ppdev->pjMmBase, CRTC_VLINE_CRNT_VLINE)&0x07FF0000L)>>16L) if ( (LONG)((M64_ID_DIRECT(ppdev->pjMmBase, CRTC_VLINE_CRNT_VLINE)&0x07FF0000L)>>16L)>= rOldPhysOverlay.top ) while ( (LONG)((M64_ID_DIRECT(ppdev->pjMmBase, CRTC_VLINE_CRNT_VLINE)&0x07FF0000L)>>16L) <= rOldPhysOverlay.bottom ); // } /* * Hit the registers with the new overlay information. */ DD_WriteVTReg ( DD_BUF0_OFFSET, dwBuf0Offset ); DD_WriteVTReg ( DD_BUF1_OFFSET, dwBuf1Offset ); DD_WriteVTReg ( DD_OVERLAY_Y_X, (DWORD)( ( (DWORD)rPhysOverlay.left << 16L ) | ( (DWORD)rPhysOverlay.top ) | (0x80000000) ) ); DD_WriteVTReg ( DD_OVERLAY_Y_X_END, (DWORD)( ( (DWORD)rPhysOverlay.right << 16L ) | ( (DWORD)rPhysOverlay.bottom ) ) ); if ( ppdev->OverlayInfo16.dwFlags & UPDATEOVERLAY ) { DD_WriteVTReg ( DD_OVERLAY_KEY_CNTL, ppdev->OverlayInfo16.dwOverlayKeyCntl ); } dwOldVInc = dwVInc; dwOldHInc = dwHInc; rOldPhysOverlay.top = max ( rPhysOverlay.top, 0 ); rOldPhysOverlay.bottom = min ( rPhysOverlay.bottom, (LONG)ppdev->cyScreen - 1 ); rOldPhysOverlay.left = rPhysOverlay.left; rOldPhysOverlay.right = rPhysOverlay.right; } void ModifyOverlayPosition (PDEV* ppdev, LPRECTL lprOverlay, LPDWORD lpdwVInc ) { DWORD dwVInc; DWORD dwScaleChange; DWORD dwHeight; DWORD dwTop, dwBottom; lprOverlay->top -= 3; if ( lprOverlay->top < 0 ) { lprOverlay->top += M64_ID(ppdev->pjMmBase, CRTC_V_TOTAL_DISP )& 0x07FFL; } if ( lprOverlay->top != 0 ) { if ( lprOverlay->top % 2 == 0 ) lprOverlay->top++; if ( lprOverlay->top == 1 ) lprOverlay->top = 0; } if ( lprOverlay->bottom%2 == 1 ) lprOverlay->bottom++; lprOverlay->bottom = min ( lprOverlay->bottom, (LONG) ppdev->cyScreen - 2 ); /* * Adjust scaling factor so we don't get the "green line" at the * bottom of the overlay if we are moving the overlay off the top * of the screen */ dwVInc = ppdev->OverlayInfo16.dwVInc; dwBottom = lprOverlay->bottom; dwTop = lprOverlay->top; if ( (LONG)dwTop > ppdev->cyScreen - 1 ) dwTop = 0L; dwHeight = dwBottom - dwTop; if ( dwHeight != 0 ) dwScaleChange = ( ( dwHeight - 1 ) << 12 ) / ( dwHeight ); else dwScaleChange = 0; if ( dwScaleChange != 0 ) dwVInc = ( dwVInc * dwScaleChange ) >> 12; *lpdwVInc = dwVInc; } void TurnOnVTRegisters ( PDEV* ppdev ) { DWORD dwBusCntl; dwBusCntl = M64_ID_DIRECT(ppdev->pjMmBase, BUS_CNTL ); dwBusCntl |= 0x08000000U; M64_OD_DIRECT(ppdev->pjMmBase, BUS_CNTL, dwBusCntl ); } void TurnOffVTRegisters ( PDEV* ppdev ) { DWORD dwBusCntl; dwBusCntl = M64_ID(ppdev->pjMmBase, BUS_CNTL ); dwBusCntl &= ~0x08000000U; M64_CHECK_FIFO_SPACE(ppdev,ppdev-> pjMmBase, 2); M64_OD(ppdev->pjMmBase, BUS_CNTL, dwBusCntl ); } DWORD DdSetColorKey(PDD_SETCOLORKEYDATA lpSetColorKey) { PDEV* ppdev; BYTE* pjIoBase; BYTE* pjMmBase; DD_SURFACE_GLOBAL* lpSurface; DWORD dwKeyLow; DWORD dwKeyHigh; ppdev = (PDEV*) lpSetColorKey->lpDD->dhpdev; pjMmBase = ppdev->pjMmBase; lpSurface = lpSetColorKey->lpDDSurface->lpGbl; // We don't have to do anything for normal blt source colour keys: if (lpSetColorKey->dwFlags & DDCKEY_SRCBLT) { lpSetColorKey->ddRVal = DD_OK; return(DDHAL_DRIVER_HANDLED); } else if (lpSetColorKey->dwFlags & DDCKEY_DESTOVERLAY) { dwKeyLow = lpSetColorKey->ckNew.dwColorSpaceLowValue; /* if (lpSurface->ddpfSurface.dwFlags & DDPF_PALETTEINDEXED8) { dwKeyLow = dwGetPaletteEntry(ppdev, dwKeyLow); } else { ASSERTDD(lpSurface->ddpfSurface.dwFlags & DDPF_RGB, "Expected only RGB cases here"); // We have to transform the colour key from its native format // to 8-8-8: if (lpSurface->ddpfSurface.dwRGBBitCount == 16) { if (IS_RGB15_R(lpSurface->ddpfSurface.dwRBitMask)) dwKeyLow = RGB15to32(dwKeyLow); else dwKeyLow = RGB16to32(dwKeyLow); } else { ASSERTDD((lpSurface->ddpfSurface.dwRGBBitCount == 32), "Expected the primary surface to be either 8, 16, or 32bpp"); } } */ DD_WriteVTReg ( DD_OVERLAY_GRAPHICS_KEY_CLR, dwKeyLow ); ppdev->OverlayInfo16.dwOverlayKeyCntl &= 0xFFFFFF8FL; ppdev->OverlayInfo16.dwOverlayKeyCntl |= 0x00000050L; DD_WriteVTReg ( DD_OVERLAY_KEY_CNTL, ppdev->OverlayInfo16.dwOverlayKeyCntl ); lpSetColorKey->ddRVal = DD_OK; return(DDHAL_DRIVER_HANDLED); } DISPDBG((0, "DdSetColorKey: Invalid command")); return(DDHAL_DRIVER_NOTHANDLED); } /******************************Public*Routine******************************\ * DWORD DdCanCreateSurface * \**************************************************************************/ DWORD DdCanCreateSurface( PDD_CANCREATESURFACEDATA lpCanCreateSurface) { PDEV* ppdev; DWORD dwRet; LPDDSURFACEDESC lpSurfaceDesc; ppdev = (PDEV*) lpCanCreateSurface->lpDD->dhpdev; lpSurfaceDesc = lpCanCreateSurface->lpDDSurfaceDesc; dwRet = DDHAL_DRIVER_NOTHANDLED; if (!lpCanCreateSurface->bIsDifferentPixelFormat) { // It's trivially easy to create plain surfaces that are the same // type as the primary surface: dwRet = DDHAL_DRIVER_HANDLED; } else if (ppdev->iAsic >=CI_M64_VTA) { // When using the Streams processor, we handle only overlays of // different pixel formats -- not any off-screen memory: if (lpSurfaceDesc->ddsCaps.dwCaps & DDSCAPS_OVERLAY) { // We handle two types of YUV overlay surfaces: if (lpSurfaceDesc->ddpfPixelFormat.dwFlags & DDPF_FOURCC) { // Check first for a supported YUV type: if ( (lpSurfaceDesc->ddpfPixelFormat.dwFourCC == FOURCC_UYVY) || (lpSurfaceDesc->ddpfPixelFormat.dwFourCC == FOURCC_YUY2) ) { lpSurfaceDesc->ddpfPixelFormat.dwYUVBitCount = 16; dwRet = DDHAL_DRIVER_HANDLED; } } // We handle 16bpp and 32bpp RGB overlay surfaces: else if ((lpSurfaceDesc->ddpfPixelFormat.dwFlags & DDPF_RGB) && !(lpSurfaceDesc->ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED8)) { if (lpSurfaceDesc->ddpfPixelFormat.dwRGBBitCount == 16) { if (IS_RGB15(&lpSurfaceDesc->ddpfPixelFormat) || IS_RGB16(&lpSurfaceDesc->ddpfPixelFormat)) { dwRet = DDHAL_DRIVER_HANDLED; } } else if (lpSurfaceDesc->ddpfPixelFormat.dwRGBBitCount == 32) { if (IS_RGB32(&lpSurfaceDesc->ddpfPixelFormat)) { dwRet = DDHAL_DRIVER_HANDLED; } } } } } // Print some spew if this was a surface we refused to create: if (dwRet == DDHAL_DRIVER_NOTHANDLED) { if (lpSurfaceDesc->ddpfPixelFormat.dwFlags & DDPF_RGB) { DISPDBG((10, "Failed creation of %libpp RGB surface %lx %lx %lx", lpSurfaceDesc->ddpfPixelFormat.dwRGBBitCount, lpSurfaceDesc->ddpfPixelFormat.dwRBitMask, lpSurfaceDesc->ddpfPixelFormat.dwGBitMask, lpSurfaceDesc->ddpfPixelFormat.dwBBitMask)); } else { DISPDBG((10, "Failed creation of type 0x%lx YUV 0x%lx surface", lpSurfaceDesc->ddpfPixelFormat.dwFlags, lpSurfaceDesc->ddpfPixelFormat.dwFourCC)); } } lpCanCreateSurface->ddRVal = DD_OK; return(dwRet); } /******************************Public*Routine******************************\ * DWORD DdCreateSurface * \**************************************************************************/ DWORD DdCreateSurface( PDD_CREATESURFACEDATA lpCreateSurface) { PDEV* ppdev; DD_SURFACE_LOCAL* lpSurfaceLocal; DD_SURFACE_GLOBAL* lpSurfaceGlobal; LPDDSURFACEDESC lpSurfaceDesc; DWORD dwByteCount; LONG lLinearPitch; DWORD dwHeight; OH* poh; FLATPTR fpVidMem; DISPDBG((10, " Enter Create Surface")); ppdev = (PDEV*) lpCreateSurface->lpDD->dhpdev; // On Windows NT, dwSCnt will always be 1, so there will only ever // be one entry in the 'lplpSList' array: lpSurfaceLocal = lpCreateSurface->lplpSList[0]; lpSurfaceGlobal = lpSurfaceLocal->lpGbl; lpSurfaceDesc = lpCreateSurface->lpDDSurfaceDesc; // We repeat the same checks we did in 'DdCanCreateSurface' because // it's possible that an application doesn't call 'DdCanCreateSurface' // before calling 'DdCreateSurface'. ASSERTDD(lpSurfaceGlobal->ddpfSurface.dwSize == sizeof(DDPIXELFORMAT), "NT is supposed to guarantee that ddpfSurface.dwSize is valid"); // DdCanCreateSurface already validated whether the hardware supports // the surface, so we don't need to do any validation here. We'll // just go ahead and allocate it. // // // Note that on NT, an overlay can be created only if the driver // okay's it here in this routine. Under Win95, the overlay will be // created automatically if it's the same pixel format as the primary // display. if ((lpSurfaceLocal->ddsCaps.dwCaps & DDSCAPS_OVERLAY) || (lpSurfaceGlobal->ddpfSurface.dwFlags & DDPF_FOURCC) || (lpSurfaceGlobal->ddpfSurface.dwYUVBitCount != (DWORD) 8 * ppdev->cjPelSize) || (lpSurfaceGlobal->ddpfSurface.dwRBitMask != ppdev->flRed)) { if (lpSurfaceGlobal->wWidth <= (DWORD) ppdev->cxMemory) { if (lpSurfaceGlobal->ddpfSurface.dwFlags & DDPF_FOURCC) { //dwByteCount = (lpSurfaceGlobal->ddpfSurface.dwFourCC == FOURCC_UYVY)? 2 : 1; dwByteCount =2; // We have to fill in the bit-count for FourCC surfaces: lpSurfaceGlobal->ddpfSurface.dwYUVBitCount = 8 * dwByteCount; DISPDBG((10, "Created YUV: %li x %li", lpSurfaceGlobal->wWidth, lpSurfaceGlobal->wHeight)); } else { dwByteCount = lpSurfaceGlobal->ddpfSurface.dwRGBBitCount >> 3; DISPDBG((10, "Created RGB %libpp: %li x %li Red: %lx", 8 * dwByteCount, lpSurfaceGlobal->wWidth, lpSurfaceGlobal->wHeight, lpSurfaceGlobal->ddpfSurface.dwRBitMask)); // we support 15,16 and 32 bits if (((dwByteCount < 2)||(dwByteCount ==3)) && (lpSurfaceLocal->ddsCaps.dwCaps & DDSCAPS_OVERLAY)) { lpCreateSurface->ddRVal = DDERR_INVALIDPIXELFORMAT; return(DDHAL_DRIVER_HANDLED); } } // We want to allocate a linear surface to store the FourCC // surface, but our driver is using a 2-D heap-manager because // the rest of our surfaces have to be 2-D. So here we have to // convert the linear size to a 2-D size. // lLinearPitch = (lpSurfaceGlobal->wWidth * dwByteCount ) ; // + 7) & ~7; // The stride has to be a qword multiple. dwHeight = ( (lpSurfaceGlobal->wHeight * lLinearPitch + ppdev->lDelta - 1) / ppdev->lDelta) ; /// ppdev->cjPelSize; // in pixels // Free up as much off-screen memory as possible: bMoveAllDfbsFromOffscreenToDibs(ppdev); poh = pohAllocate(ppdev, NULL, ppdev->cxMemory, dwHeight, FLOH_MAKE_PERMANENT); if (poh != NULL) { fpVidMem = (poh->y * ppdev->lDelta) + (poh->x ) * ppdev->cjPelSize; // poh->x must be 0 in this case lpSurfaceGlobal->dwReserved1 = (ULONG_PTR)poh; lpSurfaceGlobal->xHint = poh->x; lpSurfaceGlobal->yHint = poh->y; lpSurfaceGlobal->fpVidMem = fpVidMem; lpSurfaceGlobal->lPitch = lLinearPitch; lpSurfaceDesc->lPitch = lLinearPitch; lpSurfaceDesc->dwFlags |= DDSD_PITCH; // We handled the creation entirely ourselves, so we have to // set the return code and return DDHAL_DRIVER_HANDLED: lpCreateSurface->ddRVal = DD_OK; DISPDBG((10, " Exit Create Surface 1: Created YUV surface at poh X=%d, Y=%d", poh->x, poh->y)); return(DDHAL_DRIVER_HANDLED); } /* // Now fill in enough stuff to have the DirectDraw heap-manager // do the allocation for us: lpSurfaceGlobal->fpVidMem = DDHAL_PLEASEALLOC_BLOCKSIZE; lpSurfaceGlobal->dwBlockSizeX = ppdev->lDelta; // Specified in bytes lpSurfaceGlobal->dwBlockSizeY = dwHeight; lpSurfaceGlobal->lPitch = lLinearPitch; lpSurfaceGlobal->dwReserved1 = DD_RESERVED_DIFFERENTPIXELFORMAT; lpSurfaceDesc->lPitch = lLinearPitch; lpSurfaceDesc->dwFlags |= DDSD_PITCH; */ } else { DISPDBG((10, "Refused to create surface with large width")); } } else { if (lpSurfaceGlobal->wWidth <= (DWORD) ppdev->cxMemory) { if(lpSurfaceGlobal->ddpfSurface.dwRBitMask == ppdev->flRed) { DISPDBG((10, "Surface with the same pixel format as primary")); dwByteCount = lpSurfaceGlobal->ddpfSurface.dwRGBBitCount >> 3; lLinearPitch = ppdev->lDelta ; dwHeight = lpSurfaceGlobal->wHeight ; // Free up as much off-screen memory as possible: bMoveAllDfbsFromOffscreenToDibs(ppdev); DISPDBG((10, "Try to allocate Cx=%d, Cy=%d", ppdev->cxMemory, dwHeight)); if((ULONG)lpSurfaceGlobal->wWidth*dwByteCount < (ULONG)ppdev->lDelta) poh = pohAllocate(ppdev, NULL, ( (lpSurfaceGlobal->wWidth*dwByteCount + 8) / (ppdev->cjPelSize) ) +1, dwHeight, FLOH_MAKE_PERMANENT); else poh = pohAllocate(ppdev, NULL, (lpSurfaceGlobal->wWidth*dwByteCount )/ppdev->cjPelSize , dwHeight, FLOH_MAKE_PERMANENT); if (poh != NULL) { if((ULONG)lpSurfaceGlobal->wWidth*dwByteCount < (ULONG)ppdev->lDelta) fpVidMem =( ( (poh->y * ppdev->lDelta) + ((poh->x ) * ppdev->cjPelSize) + 7 )&~7 ); // poh->x must be 0 in this case else fpVidMem = (poh->y * ppdev->lDelta) + ((poh->x ) * ppdev->cjPelSize) ; // no allocation for flip surfaces beyond 4MB if (( (LONG)lpSurfaceGlobal->wWidth < ppdev->cxScreen) || ( (LONG)lpSurfaceGlobal->wHeight < ppdev->cyScreen) || (fpVidMem < 0x400000)) { lpSurfaceGlobal->dwReserved1=(ULONG_PTR)poh; lpSurfaceGlobal->xHint = poh->x; lpSurfaceGlobal->yHint = poh->y; lpSurfaceGlobal->fpVidMem = fpVidMem; lpSurfaceGlobal->lPitch = ppdev->lDelta; lpSurfaceDesc->lPitch = ppdev->lDelta; lpSurfaceDesc->dwFlags |= DDSD_PITCH; // We handled the creation entirely ourselves, so we have to // set the return code and return DDHAL_DRIVER_HANDLED: DISPDBG((10, " Exit Create Surface 2: Created RGB surface at poh X=%d, Y=%d", poh->x, poh->y)); lpCreateSurface->ddRVal = DD_OK; return(DDHAL_DRIVER_HANDLED); } // dealocate the poh because The allocation is beyond 4MB for a flip surface: cx = cxScreen ; cy = cyScreen // bMoveAllDfbsFromOffscreenToDibs(ppdev); // avoid fragmentation pohFree(ppdev, poh); DISPDBG((10, " The allocation is beyond 4MB, so we deallocate; for a flip surface: cx = cxScreen ; cy = cyScreen")); } DISPDBG((10, " Cannot allocate poh")); } } } DISPDBG((10, " Exit Create Surface NOTOK")); return(DDHAL_DRIVER_NOTHANDLED); } /******************************Public*Routine******************************\ * DWORD DdUpdateOverlay * \**************************************************************************/ DWORD DdUpdateOverlay(PDD_UPDATEOVERLAYDATA lpUpdateOverlay) { PDEV* ppdev; BYTE* pjIoBase; BYTE* pjMmBase; DD_SURFACE_GLOBAL* lpSource; DD_SURFACE_GLOBAL* lpDestination; DWORD dwStride; LONG srcWidth; LONG srcHeight; LONG dstWidth; LONG dstHeight; DWORD dwBitCount; DWORD dwStart; DWORD dwTmp; BOOL bColorKey; DWORD dwKeyLow; DWORD dwKeyHigh; DWORD dwBytesPerPixel; DWORD dwSecCtrl; DWORD dwBlendCtrl; LONG dwVInc; LONG dwHInc; DWORD SrcBufOffset,Temp; BYTE bPLLAddr,bFatPixel; RECTL rSrc,rDst,rOverlay; DWORD myval; DWORD g_dwGamma=0; // Used to set the gamma correction for the overlay. DWORD value; ppdev = (PDEV*) lpUpdateOverlay->lpDD->dhpdev; pjMmBase = ppdev->pjMmBase; // 'Source' is the overlay surface, 'destination' is the surface to // be overlayed: lpSource = lpUpdateOverlay->lpDDSrcSurface->lpGbl; if (lpUpdateOverlay->dwFlags & DDOVER_HIDE) { if (lpSource->fpVidMem == ppdev->fpVisibleOverlay) { ppdev->semph_overlay=0; // = 0 ; resource free //WAIT_FOR_VBLANK(pjIoBase); ppdev->OverlayInfo16.dwFlags |= UPDATEOVERLAY; ppdev->OverlayInfo16.dwFlags &= ~OVERLAY_VISIBLE; ppdev->OverlayInfo16.dwOverlayKeyCntl = 0x00000110L; DeskScanCallback (ppdev ); ppdev->OverlayInfo16.dwFlags &= ~UPDATEOVERLAY; ppdev->fpVisibleOverlay = 0; } lpUpdateOverlay->ddRVal = DD_OK; return(DDHAL_DRIVER_HANDLED); } // Dereference 'lpDDDestSurface' only after checking for the DDOVER_HIDE // case: lpDestination = lpUpdateOverlay->lpDDDestSurface->lpGbl; if (lpSource->fpVidMem != ppdev->fpVisibleOverlay) { if (lpUpdateOverlay->dwFlags & DDOVER_SHOW) { if (ppdev->fpVisibleOverlay != 0) { // Some other overlay is already visible: DISPDBG((10, "DdUpdateOverlay: An overlay is already visible")); lpUpdateOverlay->ddRVal = DDERR_OUTOFCAPS; return(DDHAL_DRIVER_HANDLED); } else { // first we have to verify if the overlay resource is in use if(ppdev->semph_overlay==0) // = 0 ; resource free // = 1 ; in use by DDraw // = 2 ; in use by Palindrome { // We're going to make the overlay visible, so mark it as // such: ppdev->semph_overlay = 1; ppdev->fpVisibleOverlay = lpSource->fpVidMem; } else { // Palindrome is using the overlay : DISPDBG((10, "DdUpdateOverlay: An overlay is already visible (used byPalindrome) ")); lpUpdateOverlay->ddRVal = DDERR_OUTOFCAPS; return(DDHAL_DRIVER_HANDLED); } } } else { // The overlay isn't visible, and we haven't been asked to make // it visible, so this call is trivially easy: lpUpdateOverlay->ddRVal = DD_OK; return(DDHAL_DRIVER_HANDLED); } } dwStride = lpSource->lPitch; srcWidth = lpUpdateOverlay->rSrc.right - lpUpdateOverlay->rSrc.left; srcHeight = lpUpdateOverlay->rSrc.bottom - lpUpdateOverlay->rSrc.top; dstWidth = lpUpdateOverlay->rDest.right - lpUpdateOverlay->rDest.left; dstHeight = lpUpdateOverlay->rDest.bottom - lpUpdateOverlay->rDest.top; if ( dstHeight < srcHeight || lpUpdateOverlay->rSrc.top > 0 ) ppdev->OverlayScalingDown = 1; else ppdev->OverlayScalingDown = 0; /* * Determine scaling factors for the hardware. These factors will * be modified based on either "fat pixel" mode or interlace mode. */ dwHInc = ( srcWidth << 12L ) / ( dstWidth ); /* * Determine if VT/GT is in FAT PIXEL MODE */ /* Get current PLL reg so we can restore. */ value=M64_ID_DIRECT(ppdev->pjMmBase, CLOCK_CNTL ); /* Set PLL reg 5 for reading. This is where the "fat pixel" bit is */ M64_OD_DIRECT(ppdev->pjMmBase, CLOCK_CNTL, (value&0xFFFF00FF)|0x1400); /* Get the "fat pixel" bit from PLL reg */ bFatPixel =(BYTE)( (M64_ID_DIRECT(ppdev->pjMmBase, CLOCK_CNTL )&0x00FF0000)>>16 ) & 0x30; /* Restore original register pointer in PLL reg */ M64_OD_DIRECT( ppdev->pjMmBase, CLOCK_CNTL, value); /* adjust horizontal scaling if necessary */ if ( bFatPixel ) dwHInc *= 2; /* * We can't clip overlays, so we must make sure the co-ord, are within * the bounds of the screen. */ rOverlay.top = max ( 0,lpUpdateOverlay->rDest.top ); rOverlay.left = max ( 0, lpUpdateOverlay->rDest.left ); rOverlay.bottom = min ( (DWORD)ppdev->cyScreen - 1, (DWORD)lpUpdateOverlay->rDest.bottom ); rOverlay.right = min ( (DWORD)ppdev->cxScreen - 1, (DWORD)lpUpdateOverlay->rDest.right ); /* * Modify overlay destination based on wether we are in inerlace mode. * If we are in interlace dwVInc must be multiplied by 2. */ dwVInc = ( srcHeight << 12L ) / ( dstHeight ); if ( M64_ID_DIRECT(ppdev->pjMmBase, CRTC_GEN_CNTL ) & CRTC_INTERLACE_EN ) { ppdev->OverlayScalingDown = 1; /* Always replicate UVs in this case */ dwVInc *= 2; } /* * Overlay destination must be primary, so we will check current * pixel depth of the screen. */ // here we have to turn on the second block of regs switch ( ppdev->cBitsPerPel) //Screen BPP { case 8: DD_WriteVTReg ( DD_OVERLAY_GRAPHICS_KEY_MSK, 0x000000FFL ); break; case 16: DD_WriteVTReg ( DD_OVERLAY_GRAPHICS_KEY_MSK, 0x0000FFFFL ); break; case 24: case 32: DD_WriteVTReg ( DD_OVERLAY_GRAPHICS_KEY_MSK, 0x00FFFFFFL ); break; default: DD_WriteVTReg ( DD_OVERLAY_GRAPHICS_KEY_MSK, 0x0000FFFFL ); break; } /* Scaler */ DD_WriteVTReg ( DD_SCALER_HEIGHT_WIDTH, ( srcWidth << 16L ) | ( srcHeight ) ); // Overlay input data format: if (lpSource->ddpfSurface.dwFlags & DDPF_FOURCC) { dwBitCount = lpSource->ddpfSurface.dwYUVBitCount; switch (lpSource->ddpfSurface.dwFourCC) { case FOURCC_UYVY: /* YVYU in VT Specs */ WriteVTOverlayPitch (ppdev, lpUpdateOverlay->lpDDSrcSurface->lpGbl->lPitch /2); //Check's to see if it's VTB or not. DD_WriteVTReg ( DD_VIDEO_FORMAT, 0x000C000CL ); DD_WriteVTReg ( DD_OVERLAY_VIDEO_KEY_MSK, 0x0000FFFF ); ppdev->OverlayInfo16.dwFlags &= ~DOUBLE_PITCH; break; case FOURCC_YUY2: /* VYUY in VT Specs */ WriteVTOverlayPitch (ppdev, lpUpdateOverlay->lpDDSrcSurface->lpGbl->lPitch /2 ); //Check's to see if it's VTB or not. DD_WriteVTReg ( DD_VIDEO_FORMAT, 0x000B000BL ); DD_WriteVTReg ( DD_OVERLAY_VIDEO_KEY_MSK, 0x0000FFFF ); ppdev->OverlayInfo16.dwFlags &= ~DOUBLE_PITCH; break; default: WriteVTOverlayPitch (ppdev, lpUpdateOverlay->lpDDSrcSurface->lpGbl->lPitch); //Check's to see if it's VTB or not. DD_WriteVTReg ( DD_VIDEO_FORMAT, 0x000B000BL ); DD_WriteVTReg ( DD_OVERLAY_VIDEO_KEY_MSK, 0x0000FFFF ); ppdev->OverlayInfo16.dwFlags &= ~DOUBLE_PITCH; break; } } else { ASSERTDD(lpSource->ddpfSurface.dwFlags & DDPF_RGB, "Expected us to have created only RGB or YUV overlays"); // The overlay surface is in RGB format: dwBitCount = lpSource->ddpfSurface.dwRGBBitCount; switch ( lpSource->ddpfSurface.dwRGBBitCount ) { case 16: /*********** * * Are we 5:5:5 or 5:6:5? * ************/ if ( lpUpdateOverlay->lpDDSrcSurface->lpGbl->ddpfSurface.dwRBitMask & 0x00008000L ) { DD_WriteVTReg ( DD_VIDEO_FORMAT, 0x00040004L ); } else { DD_WriteVTReg ( DD_VIDEO_FORMAT, 0x00030003L ); } WriteVTOverlayPitch (ppdev, lpUpdateOverlay->lpDDSrcSurface->lpGbl->lPitch /2); DD_WriteVTReg ( DD_OVERLAY_VIDEO_KEY_MSK, 0x0000FFFF ); ppdev->OverlayInfo16.dwFlags &= ~DOUBLE_PITCH; break; case 32: WriteVTOverlayPitch (ppdev, lpUpdateOverlay->lpDDSrcSurface->lpGbl->lPitch /4); DD_WriteVTReg ( DD_VIDEO_FORMAT, 0x00060006L ); DD_WriteVTReg ( DD_OVERLAY_VIDEO_KEY_MSK, 0xFFFFFFFF ); ppdev->OverlayInfo16.dwFlags &= ~DOUBLE_PITCH; break; default: WriteVTOverlayPitch (ppdev, lpUpdateOverlay->lpDDSrcSurface->lpGbl->lPitch /2); //Check's to see if it's VTB or not. DD_WriteVTReg ( DD_VIDEO_FORMAT, 0x00030003L ); DD_WriteVTReg ( DD_OVERLAY_VIDEO_KEY_MSK, 0x0000FFFF ); ppdev->OverlayInfo16.dwFlags &= ~DOUBLE_PITCH; break; } } // Calculate start of video memory in QWORD boundary dwBytesPerPixel = dwBitCount >> 3; dwStart = (lpUpdateOverlay->rSrc.top * dwStride) + (lpUpdateOverlay->rSrc.left * dwBytesPerPixel); dwStart = dwStart - (dwStart & 0x7); ppdev->dwOverlayFlipOffset = dwStart; // Save for flip dwStart += (DWORD)lpSource->fpVidMem; // Set overlay filter characteristics: /* * This register write enables the overlay and scaler registers */ //gwRedTemp =0 ; //gamma control if(0) //if ( gwRedTemp ) { DD_WriteVTReg ( DD_OVERLAY_SCALE_CNTL, 0xC0000001L | g_dwGamma ); } else { DD_WriteVTReg ( DD_OVERLAY_SCALE_CNTL, 0xC0000003L | g_dwGamma ); } /* * Get offset of buffer, if we are using a YUV Planar Overlay we * must extract the address from another field (dwReserved1). */ SrcBufOffset = (DWORD)(lpUpdateOverlay->lpDDSrcSurface->lpGbl->fpVidMem); //- (FLATPTR)ppdev->pjScreen; ppdev->OverlayInfo16.dwBuf0Start = SrcBufOffset; ppdev->OverlayInfo16.dwBuf1Start = SrcBufOffset; /* * Set up the colour keying, if any? */ if ( lpUpdateOverlay->dwFlags & DDOVER_KEYSRC || lpUpdateOverlay->dwFlags & DDOVER_KEYSRCOVERRIDE || lpUpdateOverlay->dwFlags & DDOVER_KEYDEST || lpUpdateOverlay->dwFlags & DDOVER_KEYDESTOVERRIDE ) { ppdev->OverlayInfo16.dwOverlayKeyCntl = 0; if ( lpUpdateOverlay->dwFlags & DDOVER_KEYSRC || lpUpdateOverlay->dwFlags & DDOVER_KEYSRCOVERRIDE ) { //Set source colour key if ( lpUpdateOverlay->dwFlags & DDOVER_KEYSRC ) { Temp=lpUpdateOverlay->lpDDDestSurface->ddckCKSrcOverlay.dwColorSpaceLowValue; } else { Temp=lpUpdateOverlay->overlayFX.dckSrcColorkey.dwColorSpaceLowValue; } DD_WriteVTReg ( DD_OVERLAY_VIDEO_KEY_CLR, Temp ); //ppdev->OverlayInfo16.dwOverlayKeyCntl &= 0xFFFFFEE8; if(ppdev->iAsic ==CI_M64_VTA) { ppdev->OverlayInfo16.dwOverlayKeyCntl &= 0xFFFFF0E8; ppdev->OverlayInfo16.dwOverlayKeyCntl |= 0x00000c14; } else { ppdev->OverlayInfo16.dwOverlayKeyCntl &= 0xFFFFFEE8; ppdev->OverlayInfo16.dwOverlayKeyCntl |= 0x00000114; } } if ( lpUpdateOverlay->dwFlags & DDOVER_KEYDEST || lpUpdateOverlay->dwFlags & DDOVER_KEYDESTOVERRIDE ) { //Set destination colour key if ( lpUpdateOverlay->dwFlags & DDOVER_KEYDEST ) { Temp=lpUpdateOverlay->lpDDDestSurface->ddckCKDestOverlay.dwColorSpaceLowValue; } else { Temp=lpUpdateOverlay->overlayFX.dckDestColorkey.dwColorSpaceLowValue; if ( Temp == 0 && ppdev->cBitsPerPel == 32 ) Temp = 0x00FF00FF; } DD_WriteVTReg ( DD_OVERLAY_GRAPHICS_KEY_CLR, Temp ); ppdev->OverlayInfo16.dwOverlayKeyCntl &= 0xFFFFFF8FL; ppdev->OverlayInfo16.dwOverlayKeyCntl |= 0x00000050L; } } else { //No source or destination colour keying DD_WriteVTReg ( DD_OVERLAY_GRAPHICS_KEY_CLR, 0x00000000 ); ppdev->OverlayInfo16.dwOverlayKeyCntl = 0x8000211L; } /* * Now set the stretch factor and overlay position. */ ppdev->OverlayWidth = rOverlay.right - rOverlay.left; ppdev->OverlayHeight = rOverlay.bottom - rOverlay.top; //LastOverlayPos=OverlayRect; ppdev->OverlayInfo16.dwFlags |= OVERLAY_ALLOCATED; ppdev->OverlayInfo16.dwFlags |= UPDATEOVERLAY; ppdev->OverlayInfo16.dwFlags |= OVERLAY_VISIBLE; ppdev->OverlayInfo16.rOverlay = rOverlay; ppdev->OverlayInfo16.dwVInc = dwVInc; ppdev->OverlayInfo16.dwHInc = dwHInc; // new for DeskScanCallback ppdev->OverlayInfo16.rDst = rOverlay; ppdev->OverlayInfo16.rSrc = lpUpdateOverlay->rSrc; DeskScanCallback (ppdev ); ppdev->OverlayInfo16.dwFlags &= ~UPDATEOVERLAY; /* * return to DirectDraw. */ lpUpdateOverlay->ddRVal = DD_OK; return(DDHAL_DRIVER_HANDLED); } /* * structure for passing information to DDHAL SetOverlayPosition */ DWORD DdSetOverlayPosition (PDD_SETOVERLAYPOSITIONDATA lpSetOverlayPosition ) { RECTL rOverlay; PDEV* ppdev; ppdev = (PDEV*) lpSetOverlayPosition->lpDD->dhpdev; rOverlay.left = lpSetOverlayPosition->lXPos; rOverlay.top = lpSetOverlayPosition->lYPos; rOverlay.right = ppdev->OverlayWidth + lpSetOverlayPosition->lXPos; rOverlay.bottom = ppdev->OverlayHeight + lpSetOverlayPosition->lYPos; /* * We can't clip overlays, so we must make sure the co-ord, are within the * boundaries of the screen. */ rOverlay.top = max ( 0, rOverlay.top ); rOverlay.left = max ( 0, rOverlay.left ); rOverlay.bottom = min ( (DWORD)ppdev->cyScreen -1 , (DWORD) rOverlay.bottom ); rOverlay.right = min ( (DWORD)ppdev->cxScreen -1 , (DWORD) rOverlay.right ); /* *Set overlay position */ M64_CHECK_FIFO_SPACE(ppdev,ppdev-> pjMmBase, 1); ppdev->OverlayWidth =rOverlay.right - rOverlay.left; ppdev->OverlayHeight = rOverlay.bottom - rOverlay.top; ppdev->OverlayInfo16.dwFlags |= SETOVERLAYPOSITION; ppdev->OverlayInfo16.rOverlay = rOverlay; ppdev->OverlayInfo16.rDst = rOverlay; DeskScanCallback (ppdev ); ppdev->OverlayInfo16.dwFlags &= ~SETOVERLAYPOSITION; /* * return to DirectDraw */ lpSetOverlayPosition->ddRVal = DD_OK; return DDHAL_DRIVER_HANDLED; } /******************************Public*Routine******************************\ * DWORD DdDestroySurface * * Note that if DirectDraw did the allocation, DDHAL_DRIVER_NOTHANDLED * should be returned. * \**************************************************************************/ DWORD DdDestroySurface( PDD_DESTROYSURFACEDATA lpDestroySurface) { PDEV* ppdev; DD_SURFACE_GLOBAL* lpSurface; LONG lPitch; OH* poh; DISPDBG((10, " Enter Destroy Surface")); ppdev = (PDEV*) lpDestroySurface->lpDD->dhpdev; lpSurface = lpDestroySurface->lpDDSurface->lpGbl; poh= (OH*)( lpSurface->dwReserved1); if( (ULONG)lpSurface->dwReserved1 != (ULONG_PTR) NULL ) { // let's see first if the value in reserved field is indeed an poh and not a cookie // because I don't know if ddraw is using also this value for system memory surfaces if(poh->ohState==OH_PERMANENT) { // bMoveAllDfbsFromOffscreenToDibs(ppdev); // avoid fragmentation pohFree(ppdev, poh); // Since we did the original allocation ourselves, we have to // return DDHAL_DRIVER_HANDLED here: lpDestroySurface->ddRVal = DD_OK; DISPDBG((10, " Exit Destroy Surface OK; deallocate poh X=%d, Y=%d ", poh->x, poh->y)); return(DDHAL_DRIVER_HANDLED); } DISPDBG((10, " Exit Destroy Surface Not OK : The Reserved1 is not a poh")); } DISPDBG((10, " Exit Destroy Surface Not OK : The Reserved1 is NULL")); return(DDHAL_DRIVER_NOTHANDLED); } #endif
36.049866
154
0.542115
[ "transform" ]
1a49f32d9b2ec15370ce9be73b0e57fe8f33091b
843
h
C
bistro/nodes/test/utils.h
jiazerojia/bistro
95c8d9cf9786ff87d845d7732622a46d90de5f58
[ "BSD-3-Clause" ]
1
2021-05-19T23:02:04.000Z
2021-05-19T23:02:04.000Z
bistro/nodes/test/utils.h
jiazerojia/bistro
95c8d9cf9786ff87d845d7732622a46d90de5f58
[ "BSD-3-Clause" ]
null
null
null
bistro/nodes/test/utils.h
jiazerojia/bistro
95c8d9cf9786ff87d845d7732622a46d90de5f58
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include "bistro/bistro/nodes/Nodes.h" namespace facebook { namespace bistro { boost::iterator_range<std::vector<std::shared_ptr<const Node>>::const_iterator> iterate_non_instance_nodes(const Nodes& n) { CHECK(n.size() > 0); return boost::make_iterator_range(n.begin() + 1, n.end()); } std::shared_ptr<const Node> getNodeVerySlow( const Nodes& nodes, const std::string& name) { for (const auto& node : nodes) { if (node->name() == name) { return node; } } return nullptr; } }}
24.794118
79
0.686833
[ "vector" ]
1a53a2a33174c532fb3c4eb3ceb027375eccf20c
13,719
c
C
source/hosttools/nnimage/imageList.c
nexos-dev/nexnix
c190da0c1598b059dbde370d488df35a7b0f1369
[ "Apache-2.0" ]
3
2021-12-11T15:07:10.000Z
2021-12-21T03:27:01.000Z
source/hosttools/nnimage/imageList.c
nexos-dev/nexnix
c190da0c1598b059dbde370d488df35a7b0f1369
[ "Apache-2.0" ]
null
null
null
source/hosttools/nnimage/imageList.c
nexos-dev/nexnix
c190da0c1598b059dbde370d488df35a7b0f1369
[ "Apache-2.0" ]
null
null
null
/* imageList.c - contains functions to build image list Copyright 2022 The NexNix Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @file imageList.c #include "nnimage.h" #include <conf.h> #include <libnex.h> #include <locale.h> #include <stdio.h> #include <string.h> // List of created images static ListHead_t* images = NULL; // The current partition that is being operated on static Partition_t* curPart = NULL; // Current line number for diagnostics static int lineNo = 0; // What we are expecting. 1 = image, 2 = partition static int expecting = 0; #define EXPECTING_IMAGE 1 #define EXPECTING_PARTITION 2 // The current property name static const char* prop = NULL; // If partition was linked to image static bool wasPartLinked = false; // Data type union union val { int64_t numVal; char strVal[BLOCK_BUFSZ * 4]; }; ListHead_t* getImages() { return images; } // Function to destroy an image void imageDestroy (void* data) { free (((Image_t*) data)->file); ListDestroy (((Image_t*) data)->partsList); free (data); } // Destroys a partition void partDestroy (void* data) { free (((Partition_t*) data)->prefix); free (data); } // Predicate for finding an image bool imageFindByPredicate (ListEntry_t* entry, void* data) { // Data is image name char* s = data; if (!strcmp (s, ((Image_t*) ListEntryData (entry))->name)) return true; return false; } // Predicate to find a partition bool partitionFindByPredicate (ListEntry_t* entry, void* data) { char* s = data; if (!strcmp (s, ((Partition_t*) ListEntryData (entry))->name)) return true; return false; } // Creates an image object static bool addImage (const char* name) { // Allocate it Image_t* img = (Image_t*) calloc_s (sizeof (Image_t)); if (!img) return false; img->name = name; img->partsList = ListCreate ("Partition_t", false, 0); ListSetFindBy (img->partsList, partitionFindByPredicate); ListSetDestroy (img->partsList, partDestroy); // Add it to the list ListAddFront (images, img, 0); return true; } // Creates a partition object static bool addPartition (const char* name) { curPart = (Partition_t*) calloc_s (sizeof (Partition_t)); if (!curPart) return false; curPart->name = name; return true; } // Adds a property bool addProperty (const char* newProp, union val* val, bool isStart, int dataType) { if (isStart) { prop = newProp; return true; } if (expecting == EXPECTING_IMAGE) { Image_t* img = ListEntryData (ListFront (images)); // Decide what property this is if (!strcmp (prop, "defaultFile")) { if (dataType != DATATYPE_STRING) { error ("%s:%d: property \"defaultFile\" requires a string value", ConfGetFileName(), lineNo); return false; } img->file = (char*) malloc_s (strlen (val->strVal) + 1); strcpy (img->file, val->strVal); } else if (!strcmp (prop, "sizeMul")) { if (dataType != DATATYPE_IDENTIFIER) { error ("%s:%d: property \"sizeMul\" requires an identifier value", ConfGetFileName(), lineNo); return false; } // Check the size of the multiplier if (!strcmp (val->strVal, "KiB")) img->mul = 1024; else if (!strcmp (val->strVal, "MiB")) img->mul = 1024 * 1024; else if (!strcmp (val->strVal, "GiB")) img->mul = 1024 * 1024 * 1024; else { error ("%s:%d: size multiplier \"%s\" is unsupported", ConfGetFileName(), lineNo, val->strVal); return false; } } else if (!strcmp (prop, "size")) { if (dataType != DATATYPE_NUMBER) { error ("%s:%d: property \"size\" requires a numeric value", ConfGetFileName(), lineNo); return false; } img->sz = val->numVal; } else if (!strcmp (prop, "sectorSize")) { if (dataType != DATATYPE_NUMBER) { error ("%s:%d: property \"sectorSize\" requires a numeric value", ConfGetFileName(), lineNo); return false; } // Check validity of sector size if (!(val->numVal && !(val->numVal % 512))) { error ("%s:%d: sector size must be a multiple of 512", ConfGetFileName(), lineNo); return false; } img->sectSz = val->numVal; } else if (!strcmp (prop, "format")) { if (dataType != DATATYPE_IDENTIFIER) { error ("%s:%d: property \"format\" requires an identifier value", ConfGetFileName(), lineNo); return false; } if (!strcmp (val->strVal, "gpt")) img->format = IMG_FORMAT_GPT; else if (!strcmp (val->strVal, "mbr")) img->format = IMG_FORMAT_MBR; else if (!strcmp (val->strVal, "iso9660")) img->format = IMG_FORMAT_ISO9660; else if (!strcmp (val->strVal, "floppy")) img->format = IMG_FORMAT_FLOPPY; else { error ("%s:%d: image format \"%s\" is unsupported", ConfGetFileName(), lineNo, val->strVal); return false; } } else if (!strcmp (prop, "bootMode")) { if (dataType != DATATYPE_IDENTIFIER) { error ("%s:%d: property \"bootMode\" requires an identifier value", ConfGetFileName(), lineNo); return false; } if (!strcmp (val->strVal, "bios")) img->bootMode = IMG_BOOTMODE_BIOS; else if (!strcmp (val->strVal, "efi")) img->bootMode = IMG_BOOTMODE_EFI; else if (!strcmp (val->strVal, "hybrid")) img->bootMode = IMG_BOOTMODE_HYBRID; } else { error ("%s:%d: property \"%s\" is unsupported", ConfGetFileName(), lineNo, prop); return false; } } else if (expecting == EXPECTING_PARTITION) { if (!strcmp (prop, "start")) { if (dataType != DATATYPE_NUMBER) { error ("%s:%d: property \"start\" requires a numeric value", ConfGetFileName(), lineNo); return false; } curPart->start = val->numVal; } else if (!strcmp (prop, "size")) { if (dataType != DATATYPE_NUMBER) { error ("%s:%d: property \"size\" requires a numeric value", ConfGetFileName(), lineNo); return false; } curPart->sz = val->numVal; } else if (!strcmp (prop, "format")) { if (dataType != DATATYPE_IDENTIFIER) { error ("%s:%d: property \"format\" requires an identifier value", ConfGetFileName(), lineNo); return false; } // Check format specified if (!strcmp (val->strVal, "fat32")) curPart->filesys = IMG_FILESYS_FAT32; else if (!strcmp (val->strVal, "fat16")) curPart->filesys = IMG_FILESYS_FAT16; else if (!strcmp (val->strVal, "fat12")) curPart->filesys = IMG_FILESYS_FAT12; else if (!strcmp (val->strVal, "ext2")) curPart->filesys = IMG_FILESYS_EXT2; else if (!strcmp (val->strVal, "iso9660")) curPart->filesys = IMG_FILESYS_ISO9660; else { error ("%s:%d: filesystem \"%s\" is unsupported", ConfGetFileName(), lineNo, val->strVal); return false; } } else if (!strcmp (prop, "boot")) { if (dataType != DATATYPE_IDENTIFIER) { error ("%s:%d: property \"boot\" requires an identifier value", ConfGetFileName(), lineNo); return false; } // Check property value if (!strcmp (val->strVal, "true")) curPart->isBootPart = true; else if (!strcmp (val->strVal, "false")) curPart->isBootPart = false; else { error ("%s:%d: property \"boot\" requires a boolean value", ConfGetFileName(), lineNo); return false; } } else if (!strcmp (prop, "prefix")) { if (dataType != DATATYPE_STRING) { error ("%s:%d: property \"prefix\" requires a string value", ConfGetFileName(), lineNo); return false; } curPart->prefix = malloc_s (strlen (val->strVal) + 1); strcpy (curPart->prefix, val->strVal); } else if (!strcmp (prop, "image")) { if (dataType != DATATYPE_IDENTIFIER) { error ("%s:%d: property \"image\" requires an identifier value", ConfGetFileName(), lineNo); return false; } // Find the specified image ListEntry_t* imgEntry = ListFindEntryBy (images, val->strVal); if (!imgEntry) { error ("%s:%d: image \"%s\" not found", ConfGetFileName(), lineNo, val->strVal); return false; } // Add partititon to image ListAddBack (((Image_t*) ListEntryData (imgEntry))->partsList, curPart, 0); ((Image_t*) ListEntryData (imgEntry))->partCount++; wasPartLinked = true; } else { error ("%s:%d: property \"%s\" is unsupported", ConfGetFileName(), lineNo, prop); return false; } } return true; } ListHead_t* createImageList (ListHead_t* confBlocks) { // Create list images = ListCreate ("Image_t", false, 0); if (!images) return NULL; ListSetFindBy (images, imageFindByPredicate); ListSetDestroy (images, imageDestroy); // Iterate through the configuration blocks ListEntry_t* confEntry = ListFront (confBlocks); while (confEntry) { ConfBlock_t* block = ListEntryData (confEntry); lineNo = block->lineNo; // Figure out what this block is if (!strcmp (block->blockType, "image")) { // Ensure a block name was given if (block->blockName[0] == 0) { error ("%s:%d: image declaration requires name", ConfGetFileName(), lineNo); return NULL; } // Add the image if (!addImage (block->blockName)) return NULL; expecting = EXPECTING_IMAGE; } else if (!strcmp (block->blockType, "partition")) { // Ensure a block name was given if (block->blockName[0] == 0) { error ("%s:%d: partition declaration requires name", ConfGetFileName(), lineNo); return NULL; } if (!addPartition (block->blockName)) return NULL; expecting = EXPECTING_PARTITION; } else { // Invalid block error ("%s:%d: invalid block type specified", ConfGetFileName(), lineNo); return NULL; } ListEntry_t* propsEntry = ListFront (block->props); while (propsEntry) { ConfProperty_t* curProp = ListEntryData (propsEntry); lineNo = curProp->lineNo; // Start new property addProperty (curProp->name, NULL, true, 0); for (int i = 0; i < curProp->nextVal; ++i) { lineNo = curProp->lineNo; // Declare value union union val val; if (curProp->vals[i].type == DATATYPE_IDENTIFIER) strcpy (val.strVal, curProp->vals[i].id); else if (curProp->vals[i].type == DATATYPE_STRING) { mbstate_t mbState = {0}; c32stombs (val.strVal, curProp->vals[i].str, (size_t) BLOCK_BUFSZ * 4, &mbState); } else val.numVal = curProp->vals[i].numVal; if (!addProperty (NULL, &val, false, curProp->vals[i].type)) return NULL; } propsEntry = ListIterate (propsEntry); } if (expecting == EXPECTING_PARTITION) { // Make sure partition was linked to an image if (!wasPartLinked) { error ("%s:%d: partition \"%s\" not linked to image", ConfGetFileName(), lineNo, curPart->name); return NULL; } curPart = NULL; } confEntry = ListIterate (confEntry); } return images; }
33.217918
112
0.524892
[ "object" ]
1a5fa499ec27ed228c438c96f9d8681d13c7b831
8,746
c
C
HelloCL_C/HelloCL.c
reinhar2/SamplesWorld
e765a2db8569b4cc538d82cb2140e8eb3abc39ec
[ "BSD-2-Clause" ]
null
null
null
HelloCL_C/HelloCL.c
reinhar2/SamplesWorld
e765a2db8569b4cc538d82cb2140e8eb3abc39ec
[ "BSD-2-Clause" ]
null
null
null
HelloCL_C/HelloCL.c
reinhar2/SamplesWorld
e765a2db8569b4cc538d82cb2140e8eb3abc39ec
[ "BSD-2-Clause" ]
null
null
null
// Most devices still use OpenCL 1.2: #define CL_USE_DEPRECATED_OPENCL_1_2_APIS #include <stdio.h> #include <stdlib.h> #ifdef __APPLE__ #include <OpenCL/opencl.h> #else #include <CL/cl.h> #endif #define MAX_SOURCE_SIZE (0x100000) void checkCL(cl_int error) { if (error != CL_SUCCESS) { fprintf(stderr, "OpenCL error: %i\n", error); exit(error); } } void printPlatformInfo(cl_platform_id platformId) { char buffer[1024]; checkCL(clGetPlatformInfo(platformId, CL_PLATFORM_VENDOR, sizeof(buffer), buffer, NULL)); printf("\t%s", buffer); checkCL(clGetPlatformInfo(platformId, CL_PLATFORM_NAME, sizeof(buffer), buffer, NULL)); printf(" : %s\n", buffer); checkCL(clGetPlatformInfo(platformId, CL_PLATFORM_VERSION, sizeof(buffer), buffer, NULL)); printf("\t%s\n", buffer); checkCL(clGetPlatformInfo(platformId, CL_PLATFORM_PROFILE, sizeof(buffer), buffer, NULL)); printf("\t%s\n", buffer); checkCL(clGetPlatformInfo(platformId, CL_PLATFORM_EXTENSIONS, sizeof(buffer), buffer, NULL)); printf("\t%s\n", buffer); } void printDeviceInfo(cl_device_id deviceId) { char buffer[1024]; cl_device_type deviceType; checkCL(clGetDeviceInfo(deviceId, CL_DEVICE_VENDOR, sizeof(buffer), buffer, NULL)); printf("\t%s", buffer); checkCL(clGetDeviceInfo(deviceId, CL_DEVICE_NAME, sizeof(buffer), buffer, NULL)); printf(" : %s\n", buffer); checkCL(clGetDeviceInfo(deviceId, CL_DEVICE_TYPE, sizeof(cl_device_type), &deviceType, NULL)); switch(deviceType) { case CL_DEVICE_TYPE_CPU: printf("\tCPU Device\n"); break; case CL_DEVICE_TYPE_GPU: printf("\tGPU Device\n"); break; case CL_DEVICE_TYPE_ACCELERATOR: printf("\tAccelerator Device\n"); break; case CL_DEVICE_TYPE_DEFAULT: printf("\tDefault Device\n"); break; } checkCL(clGetDeviceInfo(deviceId, CL_DEVICE_VERSION, sizeof(buffer), buffer, NULL)); printf("\t%s\n", buffer); checkCL(clGetDeviceInfo(deviceId, CL_DEVICE_PROFILE, sizeof(buffer), buffer, NULL)); printf("\t%s\n", buffer); } int main(void) { // Create the two input vectors int i; const int LIST_SIZE = 1024; int *hostA = (int*)malloc(sizeof(int)*LIST_SIZE); int *hostB = (int*)malloc(sizeof(int)*LIST_SIZE); int *hostC = (int*)malloc(sizeof(int)*LIST_SIZE); for(i = 0; i < LIST_SIZE; i++) { hostA[i] = i; hostB[i] = LIST_SIZE - i; hostC[i] = 0; } // Load the kernel source code into the array source_str FILE *fp; char *sourceStr; size_t sourceSize; fp = fopen("kernel.cl", "r"); if (!fp) { fprintf(stderr, "Failed to load kernel.\n"); exit(EXIT_FAILURE); } sourceStr = (char*)malloc(MAX_SOURCE_SIZE); sourceSize = fread( sourceStr, 1, MAX_SOURCE_SIZE, fp); fclose( fp ); // Get number of platforms and according information cl_uint numPlatforms; checkCL(clGetPlatformIDs(0, NULL, &numPlatforms)); if (numPlatforms != 0) { printf("Found %i OpenCL Platform(s)\n", numPlatforms); } else { fprintf(stderr, "no OpenCL Platforms available.\n"); exit(EXIT_FAILURE); } cl_platform_id *platforms = (cl_platform_id*)malloc(sizeof(cl_platform_id) * numPlatforms); checkCL(clGetPlatformIDs(numPlatforms, platforms, NULL)); for (int i = 0; i < numPlatforms; ++i) { printf("Platform: %i\n", i); printPlatformInfo(platforms[i]); } printf("Using platform 0 for further program\n"); // Get Devices and according information: cl_uint numDevices; checkCL(clGetDeviceIDs( platforms[0], CL_DEVICE_TYPE_ALL, 0, NULL, &numDevices)); cl_device_id *devices = (cl_device_id*)malloc(sizeof(cl_device_id) * numDevices); printf("Found %i device(s) on platform 0:\n", numDevices); checkCL(clGetDeviceIDs( platforms[0], CL_DEVICE_TYPE_ALL, numDevices, devices, NULL)); for (int i = 0; i < numDevices; ++i) { printf("Device: %i\n", i); printDeviceInfo(devices[i]); } printf("Using platform 0, device 0 for further program\n"); // Create an OpenCL context cl_int error = CL_SUCCESS; cl_platform_id myPlatform = platforms[0]; cl_device_id myDevice = devices[0]; cl_context_properties contextProps[3]; contextProps[0] = (cl_context_properties) CL_CONTEXT_PLATFORM; contextProps[1] = (cl_context_properties) myPlatform; contextProps[2] = (cl_context_properties) 0; // last element must be 0 // cfreate context with first device from first platform, no callback cl_context context = clCreateContext( contextProps, 1, &myDevice, NULL, NULL, &error); checkCL(error); printf("Created OpenCL Context\n"); // Create a command queue // possible properties (3rd agument): // CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE // CL_QUEUE_PROFILING_ENABLE cl_command_queue commandQueue = clCreateCommandQueue(context, myDevice, 0, &error); checkCL(error); printf("Created OpenCL Command Queue\n"); // Create memory buffers on the device for each vector cl_mem deviceA = clCreateBuffer(context, CL_MEM_READ_ONLY, LIST_SIZE * sizeof(int), NULL, &error); checkCL(error); cl_mem deviceB = clCreateBuffer(context, CL_MEM_READ_ONLY, LIST_SIZE * sizeof(int), NULL, &error); checkCL(error); cl_mem deviceC = clCreateBuffer(context, CL_MEM_WRITE_ONLY, LIST_SIZE * sizeof(int), NULL, &error); checkCL(error); // Copy the lists A and B to their respective memory buffers // copy operation is blocking, without offset and doesn't depend on Events checkCL(clEnqueueWriteBuffer(commandQueue, deviceA, CL_TRUE, 0, LIST_SIZE * sizeof(int), hostA, 0, NULL, NULL)); checkCL(clEnqueueWriteBuffer(commandQueue, deviceB, CL_TRUE, 0, LIST_SIZE * sizeof(int), hostB, 0, NULL, NULL)); printf("Memory written to Device\n"); // Create a program from the kernel source cl_program program = clCreateProgramWithSource(context, 1, (const char **)&sourceStr, (const size_t *)&sourceSize, &error); checkCL(error); checkCL(clBuildProgram(program, 1, &myDevice, NULL, NULL, NULL)); cl_build_status buildStatus; char *buildLog; size_t buildLogSize; checkCL(clGetProgramBuildInfo(program, myDevice, CL_PROGRAM_BUILD_STATUS, sizeof(buildStatus), &buildStatus, NULL)); if(buildStatus != CL_BUILD_SUCCESS) { printf("Problem: %i\n", buildStatus); checkCL(clGetProgramBuildInfo(program, myDevice, CL_PROGRAM_BUILD_LOG, 0, NULL, &buildLogSize)); printf("Build Log:\n"); buildLog = (char*)malloc(buildLogSize); checkCL(clGetProgramBuildInfo(program, myDevice, CL_PROGRAM_BUILD_LOG, sizeof(buildLog), &buildLog, NULL)); printf("%s\n", buildLog); exit(EXIT_FAILURE); } printf("Program built!\n"); // Create the OpenCL kernel cl_kernel kernel = clCreateKernel(program, "vector_add", &error); checkCL(error); checkCL(clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&deviceA)); checkCL(clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&deviceB)); checkCL(clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&deviceC)); printf("Kernel is created and arguments are set\n"); // Execute the OpenCL kernel on the list size_t globalItemSize = LIST_SIZE; // Process the entire lists size_t localItemSize = 64; // Device dependent // Enqueue the kernel without events: checkCL(clEnqueueNDRangeKernel(commandQueue, kernel, 1, NULL, &globalItemSize, &localItemSize, 0, NULL, NULL)); printf("kernel started\n"); // Read the memory buffer C on the device to the local variable C checkCL(clEnqueueReadBuffer(commandQueue, deviceC, CL_TRUE, 0, LIST_SIZE * sizeof(int), hostC, 0, NULL, NULL)); printf("Read from Buffer\n"); // Display the result to the screen int correctResult = 1; for(i = 0; i < LIST_SIZE; i++) { if(hostC[i] != 1024) correctResult = 0; } if(correctResult) { printf("Result of Kernel is correct!\n"); } else { printf("Result is wrong!\n"); } // Clean up checkCL(clReleaseKernel(kernel)); checkCL(clReleaseProgram(program)); checkCL(clReleaseMemObject(deviceA)); checkCL(clReleaseMemObject(deviceB)); checkCL(clReleaseMemObject(deviceC)); checkCL(clFlush(commandQueue)); checkCL(clFinish(commandQueue)); checkCL(clReleaseCommandQueue(commandQueue)); checkCL(clReleaseContext(context)); free(hostA); free(hostB); free(hostC); free(sourceStr); free(platforms); free(devices); // free(buildLog); return EXIT_SUCCESS; }
37.536481
127
0.676195
[ "vector" ]
1a6145f1ac947ef0b269f3779f79f69ae3a802fc
3,320
h
C
testsuite/test_utils/test_case.h
ph4r05/CryptoStreams
0c197842f01994bf22f56121d886a1beebd23e89
[ "MIT" ]
8
2018-03-27T17:02:21.000Z
2021-09-09T07:26:00.000Z
testsuite/test_utils/test_case.h
DalavanCloud/CryptoStreams
7ed6eb5898d75389eee7f5afb7595a304f17514c
[ "MIT" ]
47
2018-03-27T17:57:07.000Z
2020-03-06T08:35:52.000Z
testsuite/test_utils/test_case.h
DalavanCloud/CryptoStreams
7ed6eb5898d75389eee7f5afb7595a304f17514c
[ "MIT" ]
3
2019-02-09T23:44:07.000Z
2019-09-24T11:06:02.000Z
// // Created by mhajas on 7/27/17. // #pragma once #include "common_functions.h" #include "gtest/gtest.h" #include <algorithm> #include <eacirc-core/seed.h> #include <fstream> #include <stream.h> #include <string> namespace testsuite { /** seed is not actually used but some functions needs it as argument **/ const static seed seed1 = seed::create("1fe40505e131963c"); /** * this is abstract parent of all test cases, contains all functions and variables * which cipher suites test vectors has in common e.g. plaintext, ciphertext, rounds etc. */ class test_case { protected: /** * Algorithm name, which is used in cipher suites factories so that it is possible to create * instance from it */ const std::string _algorithm; /** Number of round of function for current test vectors **/ const std::size_t _round; /** This counts number of test vectors tested in operator() **/ std::uint64_t _test_vectors_tested = 0; /** File stream with test vectors **/ std::ifstream _test_vectors; /** Plaintext, should be already converted from pure string to bytes representation **/ std::vector<value_type> _plaintext; /** cipher text in form of byte vector **/ std::vector<value_type> _ciphertext; /** * Auxiliary function which generates filepath to testvectors for arguments * @param algorithm * @param round * @param competition * @return filepath */ static std::string get_test_vectors_filename(const std::string &algorithm, const std::size_t round, const std::string &competition) { return "resources/test_resources/" + competition + "/" + algorithm + "/test_vectors_" + std::to_string(round) + ".txt"; } public: test_case(const std::string &algorithm, const std::size_t round, const std::string &competition) : _algorithm(algorithm) , _round(round) , _test_vectors(get_test_vectors_filename(algorithm, round, competition), std::ifstream::in) { if (!_test_vectors.is_open()) { throw std::runtime_error("Not able to open file: \"" + get_test_vectors_filename(algorithm, round, competition) + "\""); } } /** * Generates next output from stream and compare it with expected output * @param s stream */ void test(std::unique_ptr<stream> &s) const { vec_cview actual = s->next(); ASSERT_EQ(make_cview(_ciphertext), actual); } /** * Create new instance of stream for current function * First it creates JSON configuration of stream and * then create new stream using make_stream function * @return Pointer to instance of stream */ virtual std::unique_ptr<stream> prepare_stream() = 0; /** * test case is actually a functor which can done whole testing * It is necessary to have function name and round number and it * will step by step load all test vectors and test each with raw * function and stream */ virtual void operator()() = 0; virtual ~test_case() { _test_vectors.close(); } }; } // namespace testsuite
31.923077
100
0.629217
[ "vector" ]
1a6543b7a3e67285a58aebbd6496ad5debe3cfa2
3,974
h
C
AcrosyncSwift/rsync/rsync_pathutil.h
aaronvegh/AcrosyncSwift
469201f6d8ca407334d515260e47526c6965d008
[ "Unlicense" ]
null
null
null
AcrosyncSwift/rsync/rsync_pathutil.h
aaronvegh/AcrosyncSwift
469201f6d8ca407334d515260e47526c6965d008
[ "Unlicense" ]
null
null
null
AcrosyncSwift/rsync/rsync_pathutil.h
aaronvegh/AcrosyncSwift
469201f6d8ca407334d515260e47526c6965d008
[ "Unlicense" ]
null
null
null
// Copyright (C) 2015 Acrosync LLC // // Unless explicitly acquired and licensed from Licensor under another // license, the contents of this file are subject to the Reciprocal Public // License ("RPL") Version 1.5, or subsequent versions as allowed by the RPL, // and You may not copy or use this file in either source code or executable // form, except in compliance with the terms and conditions of the RPL. // // All software distributed under the RPL is provided strictly on an "AS // IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND // LICENSOR HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT // LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE, QUIET ENJOYMENT, OR NON-INFRINGEMENT. See the RPL for specific // language governing rights and limitations under the RPL. #ifndef INCLUDED_RSYNC_PATHUTIL_H #define INCLUDED_RSYNC_PATHUTIL_H #include <cstdio> #include <stdint.h> #include <string> #include <vector> namespace rsync { class Entry; struct PathUtil { #if defined(WIN32) || defined(__MINGW32__) // Convert a UTF8 path to UTF16, adding the "\\?\" prefix. static std::basic_string<wchar_t> convertToUTF16(const char *path); // Convert a UTF16 path to UTF8, removing the "\\?\" prefix if there is one. static std::string convertToUTF8(const wchar_t *path); #endif // Return the file size static int64_t getSize(const char *fullPath); // Common file/dir operations. static bool exists(const char *fullPath); static bool remove(const char *fullPath, bool enableLogging = true, bool sendToRecyleBin = false); static bool rename(const char *from, const char *to, bool enableLogging = true); static bool isDirectory(const char *fullPath); static bool createDirectory(const char *fullPath, bool hidden = false); static bool readSymlink(const char *fullPath, std::string *target); static bool setModifiedTime(const char *fullPath, int64_t time); static bool createSymlink(const char *fullPath, const char *target, bool isDir); static bool setMode(const char *fullPath, uint32_t mode); // Concatenate two paths. static std::string join(const char *top, const char *path); // Return the directory part of the path static std::string getDirectory(const char *fullPath); // Return the last component. static std::string getBase(const char *fullPath); // If 'directory' is a prefix of 'path' static bool isPrefix(const char *directory, const char *path); // Create all intermediate directories between 'top' and 'top/dir'. static bool createIntermediateDirectories(const char *top, const char *dir); // List the directory joined by 'top' and 'path'; add file entries to 'fileList', and directory entries to // 'directoryList'. If 'includedPatterns' is specified, add only those entries that match the patterns. // Files or directories matching any pattern specified in 'excludePatterns' will not be included. // 'normalization' is used to indicate to convert paths from UTF8-MAC to UTF8. static void listDirectory(const char *top, const char *path, std::vector<Entry*> *fileList, std::vector<Entry*> *directoryList, bool normalization = false); // Create a new entry from the specified path static Entry* createEntry(const char *top, const char *path); // Return information about a file/directory at the specified path static bool getFileInfo(const char *fullPath, bool *isDir, int64_t *size, int64_t *time); // Return current working directory static std::string getCurrentDirectory(); // Remove a directory and all its contents, recursively static void removeDirectoryRecursively(const char *fullPath); // Replace '/' or '\' with the specified delimiter static void standardizePath(std::string *path, char delimiter = '/'); }; } // close namespace rsync #endif // INCLUDED_RSYNC_PATHUTIL_H
40.141414
110
0.727982
[ "vector" ]
1a759e2d9af8c1c5f6dd86fe95da697d6943b35d
1,743
h
C
Engine/Rendering/Vertex.h
LongerZrLong/Vkita
47785b68aff1f08a40113f0046bdf4ab3dbd6f15
[ "MIT" ]
1
2022-02-24T15:48:44.000Z
2022-02-24T15:48:44.000Z
Engine/Rendering/Vertex.h
LongerZrLong/Vkita
47785b68aff1f08a40113f0046bdf4ab3dbd6f15
[ "MIT" ]
null
null
null
Engine/Rendering/Vertex.h
LongerZrLong/Vkita
47785b68aff1f08a40113f0046bdf4ab3dbd6f15
[ "MIT" ]
null
null
null
#pragma once #include "Math/Glm.h" #include "Vulkan/Initializers.h" using namespace VKT; namespace VKT::Rendering { struct Vertex { glm::vec3 a_Position; glm::vec3 a_Normal; glm::vec3 a_Tangent; glm::vec3 a_Bitangent; glm::vec2 a_TexCoord; bool operator==(const Vertex &other) const { return a_Position == other.a_Position && a_Normal == other.a_Normal && a_Tangent == other.a_Tangent && a_Bitangent == other.a_Bitangent && a_TexCoord == other.a_TexCoord; } static std::vector<VkVertexInputBindingDescription> GetBindingDescription() { return { VKT::Vulkan::Initializers::vertexInputBindingDescription(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX) }; } static std::vector<VkVertexInputAttributeDescription> GetAttributeDescriptions() { return { VKT::Vulkan::Initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, a_Position)), VKT::Vulkan::Initializers::vertexInputAttributeDescription(0, 1, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, a_Normal)), VKT::Vulkan::Initializers::vertexInputAttributeDescription(0, 2, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, a_Tangent)), VKT::Vulkan::Initializers::vertexInputAttributeDescription(0, 3, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, a_Bitangent)), VKT::Vulkan::Initializers::vertexInputAttributeDescription(0, 4, VK_FORMAT_R32G32_SFLOAT, offsetof(Vertex, a_TexCoord)), }; } }; }
35.571429
140
0.631096
[ "vector" ]
1a81d6cff307cbc3303531ef6b7391ce22759e7a
3,589
h
C
src/quadrules/TabulatedRules.h
NicoSchlw/tandem
3a08b5a7ae391c1675c5cbfdad77260d4a0115cc
[ "BSD-3-Clause" ]
4
2021-11-03T17:11:00.000Z
2022-02-16T07:51:01.000Z
src/quadrules/TabulatedRules.h
NicoSchlw/tandem
3a08b5a7ae391c1675c5cbfdad77260d4a0115cc
[ "BSD-3-Clause" ]
12
2020-05-18T14:51:13.000Z
2021-12-16T12:56:31.000Z
src/quadrules/TabulatedRules.h
NicoSchlw/tandem
3a08b5a7ae391c1675c5cbfdad77260d4a0115cc
[ "BSD-3-Clause" ]
2
2020-10-23T08:04:42.000Z
2021-11-15T12:23:59.000Z
#ifndef TABULATEDRULES_20200616_H #define TABULATEDRULES_20200616_H #include "quadrules/SimplexQuadratureRule.h" #include <array> #include <cassert> #include <cstddef> #include <limits> #include <map> #include <utility> #include <vector> namespace tndm { namespace detail { template <std::size_t D> using tabulated_rules_t = const std::map<unsigned, std::pair<std::vector<std::array<double, D>>, std::vector<double>>>; extern tabulated_rules_t<3u> JaskowiecSukumar2020; extern tabulated_rules_t<2u> WitherdenVincent2015_Tri; extern tabulated_rules_t<3u> WitherdenVincent2015_Tet; } // namespace detail template <class Derived> class TabulatedRules { public: /** * @brief Returns size of rule with at least minQuadOrder. Returns numeric_limits max if there * is no such rule. */ static std::size_t size(unsigned minQuadOrder) { auto rule = Derived::rules().lower_bound(minQuadOrder); return rule != Derived::rules().end() ? rule->second.first.size() : std::numeric_limits<std::size_t>::max(); } static auto get(unsigned minQuadOrder) { auto rule = Derived::rules().lower_bound(minQuadOrder); if (rule != Derived::rules().end()) { SimplexQuadratureRule<Derived::dim()> result(rule->second.first.size(), rule->first); result.points() = rule->second.first; result.weights() = rule->second.second; Derived::transform(result); assert(result.points().size() == result.weights().size()); #ifndef NDEBUG for (auto& wgt : result.weights()) { assert(wgt > 0.0); } #endif return result; } return SimplexQuadratureRule<Derived::dim()>(); } }; /** * @brief J. Jaśkowiec and N. Sukumar, High-order cubature rules for tetrahedra. Int J Numer Methods * Eng. 2020; 121: 2418-2436. https://doi.org/10.1002/nme.6313 */ class JaskowiecSukumar2020 : public TabulatedRules<JaskowiecSukumar2020> { public: static constexpr std::size_t dim() { return 3u; } static constexpr detail::tabulated_rules_t<3u> const& rules() { return detail::JaskowiecSukumar2020; } static void transform(SimplexQuadratureRule<3u>& result) { // Divide by volume of reference tetrahedron for (auto& wgt : result.weights()) { wgt /= 6.0; } } }; /** * @brief F.D. Witherden and P.E. Vincent, On the identification of symmetric quadrature rules for * finite element methods. Comput Math Appl; 69.10: 1232-1241. * https://doi.org/10.1016/j.camwa.2015.03.017 */ template <std::size_t D> class WitherdenVincent2015 : public TabulatedRules<WitherdenVincent2015<D>> { public: static constexpr std::size_t dim() { return D; } static constexpr detail::tabulated_rules_t<D> const& rules() { if constexpr (D == 2u) { return detail::WitherdenVincent2015_Tri; } else if constexpr (D == 3u) { return detail::WitherdenVincent2015_Tet; } else { static_assert("No rules for requested dimension."); } } // Map from {-1,1}^D reference tet to {0,1}^D reference tet static void transform(SimplexQuadratureRule<D>& result) { for (auto& pt : result.points()) { for (auto& x : pt) { x = 0.5 * x + 0.5; } } // Multiply weights with 2^-D for (auto& wgt : result.weights()) { wgt /= (1 << D); } } }; } // namespace tndm #endif // TABULATEDRULES_20200616_H
32.926606
100
0.629145
[ "vector", "transform" ]
4ddd95ec38e69c66755db5d06766e39fc364e314
4,239
h
C
include/num_collect/util/source_info_view.h
MusicScience37/numerical-collection-cpp
490c24aae735ba25f1060b2941cff39050a41f8f
[ "Apache-2.0" ]
null
null
null
include/num_collect/util/source_info_view.h
MusicScience37/numerical-collection-cpp
490c24aae735ba25f1060b2941cff39050a41f8f
[ "Apache-2.0" ]
null
null
null
include/num_collect/util/source_info_view.h
MusicScience37/numerical-collection-cpp
490c24aae735ba25f1060b2941cff39050a41f8f
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 MusicScience37 (Kenta Kabashima) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! * \file * \brief Definition of source_info_view class. */ #pragma once #include <string_view> #include "num_collect/base/index_type.h" #if defined(NUM_COLLECT_DOCUMENTATION) /*! * \brief Whether the compiler has source_location class in C++ standard * library. (Value is compiler-dependent.) */ #define NUM_COLLECT_HAS_SOURCE_LOCATION 1 #include <source_location> namespace num_collect::impl { /*! * \brief Type of source_location. */ using source_location_type = std::source_location; } // namespace num_collect::impl #elif __has_include(<source_location>) // NOLINTNEXTLINE #define NUM_COLLECT_HAS_SOURCE_LOCATION 1 #include <source_location> namespace num_collect::impl { /*! * \brief Type of source_location. */ using source_location_type = std::source_location; } // namespace num_collect::impl #elif __has_include(<experimental/source_location>) // NOLINTNEXTLINE #define NUM_COLLECT_HAS_SOURCE_LOCATION 1 #include <experimental/source_location> namespace num_collect::util::impl { /*! * \brief Type of source_location. */ using source_location_type = std::experimental::source_location; } // namespace num_collect::util::impl #else // NOLINTNEXTLINE #define NUM_COLLECT_HAS_SOURCE_LOCATION 0 #endif namespace num_collect::util { /*! * \brief Class to hold information of source codes. * * \note This class won't manage memory for strings. * \note This class is a wrapper of `std::source_location`. */ class source_info_view { public: #if defined(NUM_COLLECT_DOCUMENTATION) || NUM_COLLECT_HAS_SOURCE_LOCATION /*! * \brief Constructor * * \param[in] location source_location object. */ explicit constexpr source_info_view( impl::source_location_type location = impl::source_location_type::current()) : source_info_view(location.file_name(), static_cast<index_type>(location.line()), static_cast<index_type>(location.column()), location.function_name()) {} #else /*! * \brief Constructor */ constexpr source_info_view() : source_info_view("unknown", 0, 0, "unknown") {} #endif /*! * \brief Construct. * * \param[in] file_path File path. * \param[in] line Line number. * \param[in] column Column number. * \param[in] function_name Function name. */ constexpr source_info_view(std::string_view file_path, index_type line, index_type column, std::string_view function_name) : file_path_(file_path), line_(line), column_(column), function_name_(function_name) {} /*! * \brief Get the file path. * * \return File path. */ [[nodiscard]] constexpr auto file_path() const -> std::string_view { return file_path_; } /*! * \brief Get the line number. * * \return Line number. */ [[nodiscard]] constexpr auto line() const -> index_type { return line_; } /*! * \brief Get the column number. * * \return Column number. */ [[nodiscard]] constexpr auto column() const -> index_type { return column_; } /*! * \brief Get the function name. * * \return Function name. */ [[nodiscard]] constexpr auto function_name() const -> std::string_view { return function_name_; } private: //! File path. std::string_view file_path_; //! Line number. index_type line_; //! Column number. index_type column_; //! Function name. std::string_view function_name_; }; } // namespace num_collect::util
23.681564
77
0.671385
[ "object" ]
4dfbad94ce908e6e55b5c1b64f8b304ca43be2d2
1,658
h
C
Release/include/cpp/qiniu/qn_rtc_engine.h
OurEra/QNRTC-Windows
a9e6430a5fe77db3376f35e8051b80da28ca0999
[ "Apache-2.0" ]
null
null
null
Release/include/cpp/qiniu/qn_rtc_engine.h
OurEra/QNRTC-Windows
a9e6430a5fe77db3376f35e8051b80da28ca0999
[ "Apache-2.0" ]
null
null
null
Release/include/cpp/qiniu/qn_rtc_engine.h
OurEra/QNRTC-Windows
a9e6430a5fe77db3376f35e8051b80da28ca0999
[ "Apache-2.0" ]
null
null
null
/*! * \file rtc_engine.h * * \author qiniu * * Global configuration interface * */ #pragma once #include <map> #include <string> #include <vector> #include <list> #include "qn_rtc_errorcode.h" #ifdef _WIN32 #ifdef __QINIU_DLL_EXPORT_ #define QINIU_EXPORT_DLL __declspec(dllexport) #else #define QINIU_EXPORT_DLL __declspec(dllimport) #endif #endif // WIN32 #define QNRTC_MAX_DEVICE_LENGHT 128 namespace qiniu { /** * SDK internal log level */ enum QNLogLevel { LOG_DEBUG = 0, LOG_INFO, LOG_WARNING, LOG_ERROR, }; /** * SDK internal global resource configuration interface */ #ifdef _WIN32 class QINIU_EXPORT_DLL QNRTCEngine #else class QNRTCEngine #endif // WIN32 { public: /** * Initialize the SDK internal resources * @return return 0 if success or an error code */ static int Init(); /** * Release the SDK internal resources * @return return 0 if success or an error code */ static int Release(); /** * Sets the parameter information for the log store * @param [in] level_ * what level of logs will be logged * @param [in] dir_name_ * the log will be stored in which directory * @param [in] file_name_ * the log file name of stored * @return return 0 if success or an error code */ static int SetLogParams(QNLogLevel level_, const std::string& dir_name_, const std::string& file_name_); protected: virtual ~QNRTCEngine() {}; }; }
20.469136
73
0.598311
[ "vector" ]
15000c55488b10a8bc0be553322c662e864d8626
2,252
h
C
client/lib/gameLogic/eventQueue.h
Coestaris/Zomboid2.0
5632b3fafdb90afb48fb6bd0ee3bc3625aa5e39b
[ "MIT" ]
4
2019-05-01T01:07:09.000Z
2020-06-21T17:16:59.000Z
client/lib/gameLogic/eventQueue.h
Coestaris/Zomboid2.0
5632b3fafdb90afb48fb6bd0ee3bc3625aa5e39b
[ "MIT" ]
null
null
null
client/lib/gameLogic/eventQueue.h
Coestaris/Zomboid2.0
5632b3fafdb90afb48fb6bd0ee3bc3625aa5e39b
[ "MIT" ]
null
null
null
// // Created by maxim on 1/23/19. // #ifndef ZOMBOID2_EVENTQUEUE_H #define ZOMBOID2_EVENTQUEUE_H #include <malloc.h> #include <assert.h> #include <memory.h> #include "gameObject.h" #define EVT_KeyDown 0 #define EVT_KeyUp 1 #define EVT_CharKeyDown 2 #define EVT_CharKeyUp 3 #define EVT_MouseClick 4 #define EVT_MouseMove 5 #define EVT_MouseEntry 6 #define EVT_Update 7 #define MAX_CL_EVENTS 200 #define MAX_KB_EVENTS 20 #define MAX_MS_EVENTS 5 #define MAXCOLLISTENERS_START 1024 #define MAXEVENTS_START 256 #define MAXLISTENERS_START 1024 #define SIZE_INCREASE 1.2 #define MB_LEFT 0 #define MB_RIGHT 2 #define MB_MIDDLE 1 #define MB_WHEEL_UP 3 #define MB_WHEEL_DOWN 4 #define MS_PRESSED 0 #define MS_RELEASED 1 typedef struct _registeredNode { int eventType; gameObject_t* object; void (* callback)(gameObject_t*, void*); } eventListener_t; typedef struct _collisionEventListener { int collisionWith; gameObject_t* object; void (* callback)(gameObject_t*, gameObject_t*); } collisionEventListener_t; typedef struct _event { int eventType; void* data; } event_t; typedef struct _keyboardEvent { int key; int x; int y; } keyboardEvent_t; typedef struct _mouseEvent { int mouse; int state; int x; int y; } mouseEvent_t; typedef struct _collisionEvent { gameObject_t* object; } collisionEvent_t; collisionEvent_t* createCollisionEvent(gameObject_t* sub); keyboardEvent_t* createKeyboardEvent(int key, int x, int y); mouseEvent_t* createMouseEvent(int mouse, int state, int x, int y); event_t* createEvent(); void freeEvent(event_t* ev); void evqInit(void); int evqGetListenersCount(void); int evqGetColListenersCount(void); collisionEventListener_t** evqGetCollisionListeners(size_t* count); void evqSubscribeCollisionEvent(gameObject_t* object, int collisionWith, void (* callback)(gameObject_t*, gameObject_t*)); void evqSubscribeEvent(gameObject_t* object, int eventType, void (* callback)(gameObject_t*, void*)); void evqUnsubscribeEvent(gameObject_t* object, int eventType); void evqUnsubscribeEvents(gameObject_t* object); void evqPushEvent(int eventType, void* data); event_t* evqNextEvent(void); void evqResetEvents(void); #endif //ZOMBOID2_EVENTQUEUE_H
19.929204
122
0.769538
[ "object" ]
1503c587e9cb7f7e5391add00987574cbb80cd51
1,105
h
C
lib/Display/RectangleRegion.h
markbirss/epaper_templates
9a1277c1e3a60e2c556e6472a59d95e95f9ab4d0
[ "MIT" ]
209
2018-02-17T21:37:25.000Z
2022-03-31T05:46:30.000Z
lib/Display/RectangleRegion.h
markbirss/epaper_templates
9a1277c1e3a60e2c556e6472a59d95e95f9ab4d0
[ "MIT" ]
52
2018-09-07T12:29:36.000Z
2022-02-18T03:27:48.000Z
lib/Display/RectangleRegion.h
markbirss/epaper_templates
9a1277c1e3a60e2c556e6472a59d95e95f9ab4d0
[ "MIT" ]
32
2018-02-13T13:38:31.000Z
2022-01-29T22:58:42.000Z
#include <Adafruit_GFX.h> #include <ArduinoJson.h> #include <GxEPD2_EPD.h> #include <GxEPD2_GFX.h> #include <Region.h> #include <FillStyle.h> #include <memory> #pragma once class RectangleRegion : public Region { public: enum class DimensionType { STATIC, VARIABLE }; struct Dimension { DimensionType type; uint16_t value; uint16_t getValue(const String& variableValue) const; static bool hasVariable(JsonObject spec); static String extractVariable(JsonObject spec); static JsonObject extractFormatterDefinition(JsonObject spec); static Dimension fromSpec(JsonObject spec); }; RectangleRegion(const String& variable, uint16_t x, uint16_t y, Dimension width, Dimension height, uint16_t color, uint16_t background_color, std::shared_ptr<const VariableFormatter> formatter, FillStyle fillStyle, uint16_t index ); ~RectangleRegion(); virtual void render(GxEPD2_GFX* display); private: const FillStyle fillStyle; const Dimension w, h; Rectangle previousBoundingBox; uint16_t background_color; };
23.020833
66
0.725792
[ "render" ]
15091fab557674aed7edad948c84925a036ba4a1
1,939
h
C
includes/SatHelper/dsp/clockrecovery.h
Cpir/libsathelper-master
fc687672993dc966447d31dde52f3e3046f22d55
[ "MIT" ]
38
2017-01-16T00:56:34.000Z
2022-03-04T00:53:05.000Z
includes/SatHelper/dsp/clockrecovery.h
Cpir/libsathelper-master
fc687672993dc966447d31dde52f3e3046f22d55
[ "MIT" ]
4
2017-05-13T19:21:16.000Z
2019-10-27T15:43:00.000Z
includes/SatHelper/dsp/clockrecovery.h
Cpir/libsathelper-master
fc687672993dc966447d31dde52f3e3046f22d55
[ "MIT" ]
12
2017-01-25T19:51:46.000Z
2020-05-06T22:55:52.000Z
/* * clockrecovery.h * * Created on: 22/12/2016 * Author: Lucas Teske * Based on GNU Radio Implementation */ #ifndef SRC_DSP_CLOCKRECOVERY_H_ #define SRC_DSP_CLOCKRECOVERY_H_ #include <complex> #include <SatHelper/dsp/firinterpolator.h> namespace SatHelper { class ClockRecovery { private: float mu, omega, gainOmega, omegaRelativeLimit, omegaMid, omegaLim, gainMu; std::complex<float> lastSample; MMSEFirInterpolator interp; int sampleHistory; int consumed; std::complex<float> p_2T, p_1T, p_0T; std::complex<float> c_2T, c_1T, c_0T; std::vector<std::complex<float>> samples; std::complex<float> slicer(std::complex<float> sample); int InternalWork(std::complex<float> *rInput, std::complex<float> *output, int inputLen, int outputLen); public: ClockRecovery(float omega, float gainOmega, float mu, float gainMu, float omegaRelativeLimit); virtual ~ClockRecovery(); int Work(std::complex<float> *input, std::complex<float> *output, int length); inline float GetMu() const { return mu; } inline float GetOmega() const { return omega; } inline float GetGainMu() const { return gainMu; } inline float GetGainOmega() const { return gainOmega; } inline void SetGainMu(float gain_mu) { this->gainMu = gain_mu; } inline void SetGainOmega(float gain_omega) { this->gainOmega = gain_omega; } inline void SetMu(float mu) { this->mu = mu; } inline void SetOmega(float omega) { this->omega = omega; this->omegaMid = omega; this->omegaLim = this->omegaRelativeLimit * omega; } }; } /* namespace SatHelper */ #endif /* SRC_DSP_CLOCKRECOVERY_H_ */
24.858974
112
0.598762
[ "vector" ]
15129e7ef6183c0d15f9fea7450713037a9dda27
2,448
h
C
CWin/CWin/ui/ui_sibling.h
benbraide/CWin
0441b48a71fef0dbddabf61033d7286669772c1e
[ "MIT" ]
null
null
null
CWin/CWin/ui/ui_sibling.h
benbraide/CWin
0441b48a71fef0dbddabf61033d7286669772c1e
[ "MIT" ]
null
null
null
CWin/CWin/ui/ui_sibling.h
benbraide/CWin
0441b48a71fef0dbddabf61033d7286669772c1e
[ "MIT" ]
null
null
null
#pragma once #include "ui_object.h" namespace cwin::ui{ template <class object_type> class sibling{ public: using m_object_type = object_type; explicit sibling(std::size_t index) : index_(index){} virtual object_type &get(const object &target) const{ auto value = target.get_sibling<object_type>(index_); if (value == nullptr) throw cwin::exception::not_supported(); return *value; } protected: std::size_t index_; }; template <class object_type> class reverse_sibling : public sibling<object_type>{ public: using base_type = sibling<object_type>; using base_type::base_type; virtual object_type &get(const object &target) const override{ auto value = target.reverse_get_sibling<object_type>(base_type::index_); if (value == nullptr) throw cwin::exception::not_supported(); return *value; } }; template <class object_type> class previous_sibling : public sibling<object_type>{ public: using base_type = sibling<object_type>; using base_type::base_type; virtual object_type &get(const object &target) const override{ auto value = target.get_previous_sibling<object_type>(base_type::index_); if (value == nullptr) throw cwin::exception::not_supported(); return *value; } }; template <class object_type> class next_sibling : public sibling<object_type>{ public: using base_type = sibling<object_type>; using base_type::base_type; virtual object_type &get(const object &target) const override{ auto value = target.get_next_sibling<object_type>(base_type::index_); if (value == nullptr) throw cwin::exception::not_supported(); return *value; } }; template <class object_type> class first_sibling : public sibling<object_type>{ public: using base_type = sibling<object_type>; first_sibling() : base_type(0u){} virtual object_type &get(const object &target) const override{ auto value = target.get_first_sibling<object_type>(); if (value == nullptr) throw cwin::exception::not_supported(); return *value; } }; template <class object_type> class last_sibling : public sibling<object_type>{ public: using base_type = sibling<object_type>; last_sibling() : base_type(0u){} virtual object_type &get(const object &target) const override{ auto value = target.get_last_sibling<object_type>(); if (value == nullptr) throw cwin::exception::not_supported(); return *value; } }; }
23.314286
76
0.71732
[ "object" ]
151325a6809d60d5924d3460279d1b394a112aad
531
h
C
include/colorset.h
deadalley/Monopoly-Cheat
0b69a40e8dac069ecdca8055beeb4b07edc0bda3
[ "MIT" ]
null
null
null
include/colorset.h
deadalley/Monopoly-Cheat
0b69a40e8dac069ecdca8055beeb4b07edc0bda3
[ "MIT" ]
null
null
null
include/colorset.h
deadalley/Monopoly-Cheat
0b69a40e8dac069ecdca8055beeb4b07edc0bda3
[ "MIT" ]
null
null
null
#ifndef H_COLORSET #define H_COLORSET #include <string> #include <vector> #include "color.h" #include "titledeed.h" using namespace std; class ColorSet { private: string name; Color color; vector<TitleDeed*> cards; public: ColorSet(Color); Color getColor(); string getName(); TitleDeed* getCard(int); int getSize(); int getMinHouse(); void addCard(TitleDeed*); void removeCard(TitleDeed*); bool hasMortgage(); bool hasImprovement(); bool hasAllCards(); }; #endif
15.171429
32
0.65725
[ "vector" ]
151fa43b675a606f0827ddca66a59fdad174aad0
4,740
h
C
cpp/ntradesys/HFUtils.h
CodeApprenticeRai/newt
0e07a87aa6b8d4b238c1a9fd3fef363133866c57
[ "Apache-2.0" ]
1
2021-06-21T12:23:55.000Z
2021-06-21T12:23:55.000Z
cpp/ntradesys/HFUtils.h
CodeApprenticeRai/newt
0e07a87aa6b8d4b238c1a9fd3fef363133866c57
[ "Apache-2.0" ]
null
null
null
cpp/ntradesys/HFUtils.h
CodeApprenticeRai/newt
0e07a87aa6b8d4b238c1a9fd3fef363133866c57
[ "Apache-2.0" ]
6
2019-10-17T21:16:21.000Z
2020-10-19T08:27:01.000Z
#ifndef __HFUTILS_H__ #define __HFUTILS_H__ #include "Markets.h" #include "DataManager.h" class DataManager; class AlphaSignal; class HFUtils { public: // Is px1 more (less) aggressive than px2? static bool moreAggressive(Mkt::Side side, double px1, double px2); static bool lessAggressive(Mkt::Side side, double px1, double px2); static bool geAggressive(Mkt::Side side, double px1, double px2); static bool leAggressive(Mkt::Side side, double px1, double px2); /* Price increment/decrement aggressiveness functions. */ // Return nprice that is more (less) aggressive that price by increment. // Increments price by increment in specified direction. // Somewhat confusingly named. Should probably be increment/decrement, rather than // makeMore/makeLess. static double makeMoreAggressive(Mkt::Side side, double price, double increment); static double makeLessAggressive(Mkt::Side side, double price, double increment); /* Price rounding (in aggressiveness space) functions. */ // Round price to nearest increment of mpv, in specified direction (less/more aggressive). // Given a price, find the closest even increment of mpv that has LE/GE aggressiveness // than the specified initial price. static double roundLEAggressive(Mkt::Side side, double price, double mpv); static double roundGEAggressive(Mkt::Side side, double price, double mpv); static double roundClosest(double price, double mpv); /* Price truncation (in aggressiveness space) functions. */ // Resest price relative to a specified aggressiveness limit, and *also* // make sure that price is an even increment of mpv. // Given a price px, return the closest even increment of mpv that is // strictly less/more aggressive than limit. static double pushToLessAggressive(Mkt::Side side, double price, double limit, double mpv); static double pushToMoreAggressive(Mkt::Side side, double price, double limit, double mpv); // Given a price px, return the closest even increment of mpv that is // not more aggressive / not less aggressive than limit px. static double pushToLEAggressive(Mkt::Side side, double price, double limit, double mpv); static double pushToGEAggressive(Mkt::Side side, double price, double limit, double mpv); /* TimeStamp comparison functions. */ // is tv1 within epsilon of tv2. static bool tsFuzzyGE(const TimeVal &tv1, const TimeVal &tv2); // is tv1 <= (tv2 + epsilon). static bool tsFuzzyLE(const TimeVal &tv1, const TimeVal &tv2); // is tv1 = tv2, to within epsilon. static bool tsFuzzyEQ(const TimeVal &tv1, const TimeVal &tv2); // tv2 - tv1, in milliseconds. static double milliSecondsBetween(const TimeVal &tv1, const TimeVal &tv2); /* Simplified book query functions. */ // Top-level CBBO price(s), ignoring odd-lots. // best inside price, ignoring odd lots. static bool bestPrice(DataManager *dm, int cid, Mkt::Side side, double &px); static bool bestMid(DataManager *dm, int cid, double &px, AlphaSignal *fvSignal = NULL); static bool bestSize(DataManager *dm, int cid, Mkt::Side side, size_t &sz); static void bestPrices(DataManager *dm, Mkt::Side side, double defaultValue, vector<double> &fv); static void bestMids(DataManager *dm, double defaultValue, vector<double> &fv); static void bestPrices(DataManager *dm, Mkt::Side side, vector<double> &defaultValues, vector<double> &fv); static void bestMids(DataManager *dm, vector<double> &defaultValues, vector<double> &fv, AlphaSignal *fvSignal = NULL); static bool getTradeableMarket(DataManager*dm, int cid, Mkt::Side side, int level, size_t minSize, double *price, size_t *size); // Round from double to closest integer. static int roundDtoI(double x) { return int(x + 0.5); } /* Odd-lot vs round-lot utility functions. */ static bool isOddLot(int size) { return (size>=0 && size<100); } static bool isRoundLot(int size) { return size >= 100; } static bool isNYSEOddLot(int size) { return (size%100) != 0; } static bool isNYSERoundLot(int size) { return (size%100) == 0; } static int roundSizeForNYSE(int numShares) { return numShares / 100 * 100; } /* Utility functions for breaking bigger orders up into smaller bit-sized chunks. */ /// Break order up into specified chunk-size, plus possibly a single odd lot. static void chunkOrderShares( int numShares, int chunkSize, vector<int> &chunks ); static void setupLogger(tael::Logger *dbg, tael::LoggerDestination *dest); /// Global Constants for Exec Engine. /// How long (in milliseconds) to allow book to be locked/crossed before cancelling orders. const static int INVALD_MKT_CANCEL_MS = 500; }; #endif // __HFUTILS_H__
43.486239
121
0.728692
[ "vector" ]
152c69191f325adb51d2e1cc07aaed9189bf2c1a
3,910
h
C
TAO/tao/LF_CH_Event.h
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/LF_CH_Event.h
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/LF_CH_Event.h
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// -*- C++ -*- //============================================================================= /** * @file LF_CH_Event.h * * $Id: LF_CH_Event.h 93792 2011-04-07 11:48:50Z mcorino $ * * @author Balachandran Natarajan <bala@cs.wustl.edu> */ //============================================================================= #ifndef TAO_LF_CH_EVENT_H #define TAO_LF_CH_EVENT_H #include /**/ "ace/pre.h" #include "tao/LF_Event.h" #include "tao/orbconf.h" #include "ace/Hash_Map_Manager_T.h" #include "ace/Null_Mutex.h" #include "ace/Thread_Mutex.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ TAO_BEGIN_VERSIONED_NAMESPACE_DECL class TAO_LF_Multi_Event; /** * @class TAO_LF_CH_Event * * @brief Use the Leader/Follower loop to wait for one specific event * in the invocation path. * * Concrete event types and manipulation class which is used for * connection handling purposes. */ class TAO_Export TAO_LF_CH_Event: public TAO_LF_Event { public: /** * The TAO_LF_Multi_Event class is another specialization of * TAO_LF_Event, used for aggregating many connection handlers into * a single event object. It requires friendship so that it can * check the is_state_final() flag on each of its contained * connection handlers. */ friend class TAO_LF_Multi_Event; /// Constructor TAO_LF_CH_Event (void); /// Destructor virtual ~TAO_LF_CH_Event (void); //@{ /// Return 1 if the condition was satisfied successfully, 0 if it /// has not int successful (void) const; /// Return 1 if an error was detected while waiting for the /// event int error_detected (void) const; protected: /// Check whether we have reached the final state.. virtual int is_state_final (void); //@} private: /// Validate and change the state /* * This concrete class uses the following states declared in the * class TAO_LF_Event to transition states * * LFS_IDLE - The event is created, and is in * initial state. * * LFS_CONNECTION_WAIT - The event is waiting for connection * completion and it can transition to * any of the following states, all the * states are final. * * LFS_SUCCESS - The event, connection establishment, has * completed successfully. * * LFS_TIMEOUT - The event has timed out. * * LFS_CONNECTION_CLOSED - The connection was closed since * an error occured while trying to * establish connection * * Event State Diagram * ------------------- * |----> CLOSED * | ^ * | | * IDLE ---> CONNECTION_WAIT--| | * | | * | | * |----> SUCESS * * Timeouts can occur while waiting for connections. * */ virtual void state_changed_i (int new_state); /// Set the state irrespective of anything. virtual void set_state (int new_state); virtual int bind (TAO_LF_Follower *follower); virtual int unbind (TAO_LF_Follower *follower); private: /// The previous state that the LF_CH_Event was in int prev_state_; void validate_state_change (int new_state); typedef ACE_Hash_Map_Manager_Ex <TAO_LF_Follower *, int, ACE_Hash<void *>, ACE_Equal_To<TAO_LF_Follower *>, TAO_SYNCH_MUTEX> HASH_MAP; HASH_MAP followers_; }; TAO_END_VERSIONED_NAMESPACE_DECL #include /**/ "ace/post.h" #endif /* TAO_LF_CH_EVENT_H */
28.540146
79
0.562404
[ "object" ]
152fe60b76024077cc4477829365034e9778230c
8,787
h
C
C++CLI/Paint+/Paint+/Application.h
sethballantyne/dev-random
2856811a01da805786fa8069d9cdeb5129148990
[ "MIT" ]
null
null
null
C++CLI/Paint+/Paint+/Application.h
sethballantyne/dev-random
2856811a01da805786fa8069d9cdeb5129148990
[ "MIT" ]
null
null
null
C++CLI/Paint+/Paint+/Application.h
sethballantyne/dev-random
2856811a01da805786fa8069d9cdeb5129148990
[ "MIT" ]
null
null
null
// Copyright(c) 2019 Seth Ballantyne <seth.ballantyne@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files(the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #pragma once #include <SDL.h> #include <msclr\marshal.h> #include "Server.h" #include "Client.h" #define CNT_SERVER 0 #define CNT_CLIENT 1 public ref class Application { private: Socket^ m_socket; SDL_Surface *m_screen; Uint32 m_colour; int m_size = 1; unsigned short m_port; System::String^ m_ipAddress; bool m_initialised; System::ComponentModel::BackgroundWorker^ backgroundWorker = gcnew System::ComponentModel::BackgroundWorker(); void OnDoWork(Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) { if(m_socket->ConnectionEstablished) { ReadSocket(); } } void ClearScreen(bool send) { SDL_FillRect(m_screen, nullptr, SDL_MapRGB(m_screen->format, 0, 0, 0)); if(send && m_socket->ConnectionEstablished) { WriteSocket("clear"); } } void Draw(int x, int y, int size, int colour, bool send) { switch(size) { case 1: DrawPixel(x, y, colour); break; default: SDL_Rect dest; dest.x = x; dest.y = y; dest.w = size; dest.h = size; SDL_FillRect(m_screen, &dest, colour); break; } if(send && m_socket->ConnectionEstablished) { WriteSocket("{0},{1},{2},{3}", x, y, size, colour); /*char data[32]; memset(data, NULL, 32); sprintf(data, "%d,%d,%d,%d", x, y, size, colour); if(!m_socket->SendPacket(data)) { if(m_socket->GetType() == Server::typeid) { System::Console::WriteLine("Client disconnected."); } else { System::Console::WriteLine("Server droppped."); } }*/ } } void DrawPixel(int x, int y, int colour) { Uint8 *p = (Uint8 *)m_screen->pixels + y * m_screen->pitch + x * m_screen->format->BytesPerPixel; switch(m_screen->format->BytesPerPixel) { case 1: *p = colour; break; case 2: *(Uint16 *)p = colour; break; case 3: if(SDL_BYTEORDER == SDL_BIG_ENDIAN) { p[0] = (colour >> 16) & 0xFF; p[1] = (colour >> 8) & 0xFF; p[2] = colour & 0xFF; } else { p[0] = colour & 0xFF; p[1] = (colour >> 8) & 0xFF; p[2] = (colour >> 16) & 0xFF; } break; case 4: *(Uint32 *)p = colour; break; } } void ReadSocket() { System::String^ data = m_socket->ReceivePacket(); if(nullptr != data) { if("clear" == data->ToLower()) { ClearScreen(false); } else if(data->Contains(",")) { array<System::String^, 1>^ splitData = data->Split(','); if(4 == splitData->Length) { int x = System::Convert::ToInt32(splitData[0]); int y = System::Convert::ToInt32(splitData[1]); int size = System::Convert::ToInt32(splitData[2]); int colour = System::Convert::ToInt32(splitData[3]); Draw(x, y, size, colour, false); } } else if("bye" == data->ToLower()) { System::Console::WriteLine("Remote connection terminated."); m_socket->Disconnect(); } } } void WriteSocket(System::String^ data, ...array<Object^, 1>^ args) { msclr::interop::marshal_context^ marshalContext = gcnew msclr::interop::marshal_context(); System::String^ formattedStr = System::String::Format(data, args); const char* cdata = marshalContext->marshal_as<const char*>(formattedStr); if(!m_socket->SendPacket(const_cast<char*>(cdata))) { if(m_socket->GetType() == Server::typeid) { System::Console::WriteLine("Client disconnected."); } else { System::Console::WriteLine("Server droppped."); } } delete marshalContext; } void EstablishConnection() { if(m_socket->GetType() == Server::typeid) { System::Console::WriteLine("Listening on port {0}", m_port); if((safe_cast<Server^>(m_socket))->AwaitConnection(m_port)) { System::Console::WriteLine("Connection established with {0}", (safe_cast<Server^>(m_socket))->ClientIPAddress); } } else { System::Console::WriteLine("Attempting to connect to {0}:{1}", m_ipAddress, m_port); if((safe_cast<Client^>(m_socket))->Connect(m_ipAddress, m_port)) { System::Console::WriteLine("Connection established with server."); } } } public: Application() { backgroundWorker->DoWork += gcnew System::ComponentModel::DoWorkEventHandler(this, &Application::OnDoWork); backgroundWorker->WorkerSupportsCancellation = true; } int Initialise(array<System::String^, 1>^ args) { if(args->Length < 2) { System::Console::WriteLine("No arguments supplied."); System::Console::WriteLine("To run as a client: Paint+.exe <ip address> <port>"); System::Console::WriteLine("To run as a server: Paint+.exe <port>"); return -1; } int result = SDL_Init(SDL_INIT_VIDEO); if(result < 0) { throw gcnew System::Exception(System::String::Format("SDL_Init failed: {0}", gcnew System::String(SDL_GetError()))); } m_initialised = true; m_screen = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE | SDL_DOUBLEBUF); if(!m_screen) { throw gcnew System::Exception(System::String::Format("SDL_SetVideoMode failed: {0}", gcnew System::String(SDL_GetError()))); } m_colour = SDL_MapRGB(m_screen->format, 255, 0, 0); result = SDLNet_Init(); if(result < 0) { throw gcnew System::Exception(System::String::Format("SDLNet_Init failed: {0}", gcnew System::String(SDL_GetError()))); } if(args->Length < 3) { m_socket = gcnew Server(); m_port = System::Convert::ToInt32(args[1]); SDL_WM_SetCaption("Paint+ Server", nullptr); } else { m_socket = gcnew Client(); m_ipAddress = args[1]; m_port = System::Convert::ToInt32(args[2]); SDL_WM_SetCaption("Paint+ Client", nullptr); } return 0; } void Run() { bool quit; bool draw; SDL_Event event; while(!quit) { SDL_PollEvent(&event); if(!m_socket->ConnectionEstablished) { EstablishConnection(); } switch(event.type) { case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_1: m_size = 1; break; case SDLK_2: m_size = 2; break; case SDLK_3: m_size = 3; break; case SDLK_4: m_size = 4; break; case SDLK_5: m_size = 5; break; case SDLK_6: m_size = 6; break; case SDLK_7: m_size = 7; break; case SDLK_8: m_size = 8; break; case SDLK_9: m_size = 9; break; case SDLK_r: m_colour = SDL_MapRGB(m_screen->format, 255, 0, 0); break; case SDLK_g: m_colour = SDL_MapRGB(m_screen->format, 0, 255, 0); break; case SDLK_b: m_colour = SDL_MapRGB(m_screen->format, 0, 0, 255); break; case SDLK_ESCAPE: quit = true; break; case SDLK_SPACE: ClearScreen(true); break; default: break; } break; case SDL_MOUSEMOTION: if(draw) { Draw(event.motion.x, event.motion.y, m_size, m_colour, true); } break; case SDL_MOUSEBUTTONDOWN: draw = true; break; case SDL_MOUSEBUTTONUP: draw = false; break; case SDL_QUIT: quit = true; break; } /*if(m_socket->ConnectionEstablished) { ReadSocket(); }*/ if(!backgroundWorker->IsBusy) { backgroundWorker->RunWorkerAsync(); } SDL_Delay(15); SDL_Flip(m_screen); } if(m_socket->ConnectionEstablished) { WriteSocket("bye"); } backgroundWorker->CancelAsync(); } void Shutdown() { if(m_initialised) { if(m_screen) { SDL_FreeSurface(m_screen); } if(m_socket) { m_socket->Disconnect(); } SDLNet_Quit(); SDL_Quit(); } } property bool Initialised { bool get() { return m_initialised; } } };
22.764249
127
0.629339
[ "object" ]
153516cd1e0b67d165a1d6203923d50f87151ccb
11,727
c
C
source/util_api/slap/components/SlapVarConverter/slap_vco_base.c
lgirdk/ccsp-common-library
8d912984e96f960df6dadb4b0e6bc76c76376776
[ "Apache-2.0" ]
4
2018-02-26T05:41:14.000Z
2019-12-20T07:31:39.000Z
source/util_api/slap/components/SlapVarConverter/slap_vco_base.c
rdkcmf/rdkb-CcspCommonLibrary
3eba76685bbf5eb6656f45eb4b57fdb5c269c2a1
[ "Apache-2.0" ]
null
null
null
source/util_api/slap/components/SlapVarConverter/slap_vco_base.c
rdkcmf/rdkb-CcspCommonLibrary
3eba76685bbf5eb6656f45eb4b57fdb5c269c2a1
[ "Apache-2.0" ]
3
2017-07-30T15:35:16.000Z
2020-08-18T20:44:08.000Z
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2015 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /********************************************************************** Copyright [2014] [Cisco Systems, Inc.] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********************************************************************/ /********************************************************************** module: slap_vco_base.c For Service Logic Aggregation Plane Implementation (SLAP), BroadWay Service Delivery System --------------------------------------------------------------- description: This module implements the basic container object functions of the Slap Var Converter Object. * SlapVcoCreate * SlapVcoRemove * SlapVcoEnrollObjects * SlapVcoInitialize --------------------------------------------------------------- environment: platform independent --------------------------------------------------------------- author: Xuechen Yang Bin Zhu --------------------------------------------------------------- revision: 07/13/2003 initial revision. 08/09/2010 Bin added ipv6 support 09/30/2010 Bin added ipv6_list support. **********************************************************************/ #include "slap_vco_global.h" /********************************************************************** caller: owner of the object prototype: ANSC_HANDLE SlapVcoCreate ( ANSC_HANDLE hContainerContext, ANSC_HANDLE hOwnerContext, ANSC_HANDLE hAnscReserved ); description: This function constructs the Slap Var Converter Object and initializes the member variables and functions. argument: ANSC_HANDLE hContainerContext This handle is used by the container object to interact with the outside world. It could be the real container or an target object. ANSC_HANDLE hOwnerContext This handle is passed in by the owner of this object. ANSC_HANDLE hAnscReserved This handle is passed in by the owner of this object. return: newly created container object. **********************************************************************/ ANSC_HANDLE SlapVcoCreate ( ANSC_HANDLE hContainerContext, ANSC_HANDLE hOwnerContext, ANSC_HANDLE hAnscReserved ) { UNREFERENCED_PARAMETER(hAnscReserved); PANSC_LIGHT_COMPONENT_OBJECT pBaseObject = NULL; PSLAP_VAR_CONVERTER_OBJECT pMyObject = NULL; /* * We create object by first allocating memory for holding the variables and member functions. */ pMyObject = (PSLAP_VAR_CONVERTER_OBJECT)AnscAllocateMemory(sizeof(SLAP_VAR_CONVERTER_OBJECT)); if ( !pMyObject ) { return (ANSC_HANDLE)NULL; } else { pBaseObject = (PANSC_LIGHT_COMPONENT_OBJECT)pMyObject; } /* * Initialize the common variables and functions for a container object. */ pBaseObject->hContainerContext = hContainerContext; pBaseObject->hOwnerContext = hOwnerContext; pBaseObject->Oid = SLAP_VAR_CONVERTER_OID; pBaseObject->Create = SlapVcoCreate; pBaseObject->Remove = SlapVcoRemove; pBaseObject->EnrollObjects = SlapVcoEnrollObjects; pBaseObject->Initialize = SlapVcoInitialize; pBaseObject->EnrollObjects((ANSC_HANDLE)pBaseObject); pBaseObject->Initialize ((ANSC_HANDLE)pBaseObject); return (ANSC_HANDLE)pMyObject; } /********************************************************************** caller: owner of this object prototype: ANSC_STATUS SlapVcoRemove ( ANSC_HANDLE hThisObject ); description: This function destroys the object. argument: ANSC_HANDLE hThisObject This handle is actually the pointer of this object itself. return: status of operation. **********************************************************************/ ANSC_STATUS SlapVcoRemove ( ANSC_HANDLE hThisObject ) { PSLAP_VAR_CONVERTER_OBJECT pMyObject = (PSLAP_VAR_CONVERTER_OBJECT)hThisObject; SlapScoStdRemove((ANSC_HANDLE)pMyObject); return ANSC_STATUS_SUCCESS; } /********************************************************************** caller: owner of this object prototype: ANSC_STATUS SlapVcoEnrollObjects ( ANSC_HANDLE hThisObject ); description: This function enrolls all the objects required by this object. argument: ANSC_HANDLE hThisObject This handle is actually the pointer of this object itself. return: status of operation. **********************************************************************/ ANSC_STATUS SlapVcoEnrollObjects ( ANSC_HANDLE hThisObject ) { PSLAP_VAR_CONVERTER_OBJECT pMyObject = (PSLAP_VAR_CONVERTER_OBJECT)hThisObject; SlapScoStdEnrollObjects((ANSC_HANDLE)pMyObject); return ANSC_STATUS_SUCCESS; } /********************************************************************** caller: owner of this object prototype: ANSC_STATUS SlapVcoInitialize ( ANSC_HANDLE hThisObject ); description: This function first calls the initialization member function of the base class object to set the common member fields inherited from the base class. It then initializes the member fields that are specific to this object. argument: ANSC_HANDLE hThisObject This handle is actually the pointer of this object itself. return: status of operation. **********************************************************************/ ANSC_STATUS SlapVcoInitialize ( ANSC_HANDLE hThisObject ) { PSLAP_VAR_CONVERTER_OBJECT pMyObject = (PSLAP_VAR_CONVERTER_OBJECT)hThisObject; /* * Until you have to simulate C++ object-oriented programming style with standard C, you don't * appreciate all the nice little things come with C++ language and all the dirty works that * have been done by the C++ compilers. Member initialization is one of these things. While in * C++ you don't have to initialize all the member fields inherited from the base class since * the compiler will do it for you, such is not the case with C. */ SlapScoStdInitialize((ANSC_HANDLE)pMyObject); /* * Although we have initialized some of the member fields in the "create" member function, we * repeat the work here for completeness. While this simulation approach is pretty stupid from * a C++/Java programmer perspective, it's the best we can get for universal embedded network * programming. Before we develop our own operating system (don't expect that to happen any * time soon), this is the way things gonna be. */ pMyObject->Oid = SLAP_VAR_CONVERTER_OID; pMyObject->Create = SlapVcoCreate; pMyObject->Remove = SlapVcoRemove; pMyObject->EnrollObjects = SlapVcoEnrollObjects; pMyObject->Initialize = SlapVcoInitialize; pMyObject->Reset = SlapVcoReset; pMyObject->ConvertVariable = SlapVcoConvertVariable; pMyObject->BoolToString = SlapVcoBoolToString; pMyObject->IntToString = SlapVcoIntToString; pMyObject->UcharArrayToString = SlapVcoUcharArrayToString; pMyObject->UcharArrayToBase64String = SlapVcoUcharArrayToBase64String; pMyObject->UcharArrayToString2 = SlapVcoUcharArrayToString2; pMyObject->Uint32ToString = SlapVcoUint32ToString; pMyObject->Ip4AddrToString = SlapVcoIp4AddrToString; pMyObject->Ip4AddrToString2 = SlapVcoIp4AddrToString2; pMyObject->Ip4AddrListToString = SlapVcoIp4AddrListToString; pMyObject->Ip6AddrListToString = SlapVcoIp6AddrListToString; pMyObject->Ip6AddrToString = SlapVcoIp6AddrToString; pMyObject->MacAddrToString = SlapVcoMacAddrToString; pMyObject->MacAddrToString2 = SlapVcoMacAddrToString2; pMyObject->MacAddrListToString = SlapVcoMacAddrListToString; pMyObject->OidListToString = SlapVcoOidListToString; pMyObject->CalendarTimeToString = SlapVcoCalendarTimeToString; pMyObject->Uint32ToHexString = SlapVcoUint32ToHexString; pMyObject->StringToBool = SlapVcoStringToBool; pMyObject->StringToInt = SlapVcoStringToInt; pMyObject->StringToUcharArray = SlapVcoStringToUcharArray; pMyObject->Base64StringToUcharArray = SlapVcoBase64StringToUcharArray; pMyObject->StringToUcharArray2 = SlapVcoStringToUcharArray2; pMyObject->StringToUint32 = SlapVcoStringToUint32; pMyObject->StringToIp4Addr = SlapVcoStringToIp4Addr; pMyObject->StringToIp4AddrList = SlapVcoStringToIp4AddrList; pMyObject->StringToIp6AddrList = SlapVcoStringToIp6AddrList; pMyObject->StringToIp6Addr = SlapVcoStringToIp6Addr; pMyObject->StringToMacAddr = SlapVcoStringToMacAddr; pMyObject->StringToMacAddrList = SlapVcoStringToMacAddrList; pMyObject->StringToOidList = SlapVcoStringToOidList; pMyObject->StringToCalendarTime = SlapVcoStringToCalendarTime; pMyObject->HexStringToUint32 = SlapVcoHexStringToUint32; pMyObject->HexStringToDecimal = SlapVcoHexStringToDecimal; pMyObject->Uint32ArrayToMacAddr = SlapVcoUint32ArrayToMacAddr; pMyObject->Uint32ToUcharArray = SlapVcoUint32ToUcharArray; pMyObject->Uint32ToUchar = SlapVcoUint32ToUchar; pMyObject->UcharArrayToUint32 = SlapVcoUcharArrayToUint32; return ANSC_STATUS_SUCCESS; }
34.390029
98
0.595293
[ "object" ]
15362d00d9292f83abe841133e96ba27dca58bed
5,949
h
C
src/qt/qtwebkit/Source/WebKit/efl/ewk/ewk_tiled_backing_store_private.h
viewdy/phantomjs
eddb0db1d253fd0c546060a4555554c8ee08c13c
[ "BSD-3-Clause" ]
1
2015-05-27T13:52:20.000Z
2015-05-27T13:52:20.000Z
src/qt/qtwebkit/Source/WebKit/efl/ewk/ewk_tiled_backing_store_private.h
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtwebkit/Source/WebKit/efl/ewk/ewk_tiled_backing_store_private.h
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
1
2022-02-18T10:41:38.000Z
2022-02-18T10:41:38.000Z
/* Copyright (C) 2009-2010 Samsung Electronics Copyright (C) 2009-2010 ProFUSION embedded systems This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef ewk_tiled_backing_store_private_h #define ewk_tiled_backing_store_private_h #include "EWebKit.h" #include <Evas.h> /* Enable accounting of render time in tile statistics */ // #define TILE_STATS_ACCOUNT_RENDER_TIME /* If define ewk will do more accounting to check for memory leaks * try "kill -USR1 $PID" to get instantaneous debug * try "kill -USR2 $PID" to get instantaneous debug and force flush of cache */ #undef DEBUG_MEM_LEAKS static const int defaultTileWidth = 256; static const int defaultTileHeigth = 256; static const float zoomStepMinimum = 0.01; #define TILE_SIZE_AT_ZOOM(SIZE, ZOOM) ((int)roundf((SIZE) * (ZOOM))) #define TILE_ZOOM_AT_SIZE(SIZE, ORIG_TILE) ((float)(SIZE) / (float)(ORIG_TILE)) #define ROUNDED_ZOOM(SIZE, ZOOM) ((float)(SIZE) / (float)(((int)roundf((SIZE) / (ZOOM))))) typedef struct _Ewk_Tile Ewk_Tile; typedef struct _Ewk_Tile_Stats Ewk_Tile_Stats; typedef struct _Ewk_Tile_Matrix Ewk_Tile_Matrix; struct _Ewk_Tile_Stats { double last_used; /**< time of last use */ #ifdef TILE_STATS_ACCOUNT_RENDER_TIME double render_time; /**< amount of time this tile took to render */ #endif unsigned int area; /**< cache for (w * h) */ unsigned int misses; /**< number of times it became dirty but not * repainted at all since it was not visible. */ bool full_update : 1; /**< tile requires full size update */ }; struct _Ewk_Tile { Eina_Tiler* updates; /**< updated/dirty areas */ Ewk_Tile_Stats stats; /**< tile usage statistics */ unsigned long column, row; /**< tile tile position */ Evas_Coord x, y; /**< tile coordinate position */ /** Never ever change those after tile is created (respect const!) */ const Evas_Coord width, height; /**< tile size (see TILE_SIZE_AT_ZOOM()) */ const Evas_Colorspace cspace; /**< colorspace */ const float zoom; /**< zoom level contents were rendered at */ const size_t bytes; /**< bytes used in pixels. keep * before pixels to guarantee * alignement! */ int visible; /**< visibility counter of this tile */ Evas_Object* image; /**< Evas Image, the tile to be rendered */ }; /* view */ Evas_Object* ewk_tiled_backing_store_add(Evas* e); void ewk_tiled_backing_store_render_cb_set(Evas_Object* o, bool (*cb)(void* data, Ewk_Tile* t, const Eina_Rectangle* area), const void* data); bool ewk_tiled_backing_store_scroll_full_offset_set(Evas_Object* o, Evas_Coord x, Evas_Coord y); bool ewk_tiled_backing_store_scroll_full_offset_add(Evas_Object* o, Evas_Coord dx, Evas_Coord dy); bool ewk_tiled_backing_store_scroll_inner_offset_add(Evas_Object* o, Evas_Coord dx, Evas_Coord dy, Evas_Coord x, Evas_Coord y, Evas_Coord w, Evas_Coord h); bool ewk_tiled_backing_store_zoom_set(Evas_Object* o, float* zoom, Evas_Coord cx, Evas_Coord cy, Evas_Coord* offx, Evas_Coord* offy); bool ewk_tiled_backing_store_zoom_weak_set(Evas_Object* o, float zoom, Evas_Coord cx, Evas_Coord cy); void ewk_tiled_backing_store_fix_offsets(Evas_Object* o, Evas_Coord w, Evas_Coord h); void ewk_tiled_backing_store_zoom_weak_smooth_scale_set(Evas_Object* o, bool smooth_scale); void ewk_tiled_backing_store_alpha_set(Evas_Object* o, bool has_alpha); bool ewk_tiled_backing_store_update(Evas_Object* o, const Eina_Rectangle* update); void ewk_tiled_backing_store_updates_process_pre_set(Evas_Object* o, void* (*cb)(void* data, Evas_Object* o), const void* data); void ewk_tiled_backing_store_updates_process_post_set(Evas_Object* o, void* (*cb)(void* data, void* pre_data, Evas_Object* o), const void* data); void ewk_tiled_backing_store_updates_process(Evas_Object* o); void ewk_tiled_backing_store_updates_clear(Evas_Object* o); void ewk_tiled_backing_store_contents_resize(Evas_Object* o, Evas_Coord width, Evas_Coord height); void ewk_tiled_backing_store_disabled_update_set(Evas_Object* o, bool value); void ewk_tiled_backing_store_flush(Evas_Object* o); void ewk_tiled_backing_store_enable_scale_set(Evas_Object* o, bool value); Ewk_Tile_Unused_Cache* ewk_tiled_backing_store_tile_unused_cache_get(const Evas_Object* o); void ewk_tiled_backing_store_tile_unused_cache_set(Evas_Object* o, Ewk_Tile_Unused_Cache* tuc); bool ewk_tiled_backing_store_pre_render_region(Evas_Object* o, Evas_Coord x, Evas_Coord y, Evas_Coord w, Evas_Coord h, float zoom); bool ewk_tiled_backing_store_pre_render_relative_radius(Evas_Object* o, unsigned int n, float zoom); bool ewk_tiled_backing_store_pre_render_spiral_queue(Evas_Object* o, Eina_Rectangle* view_rect, Eina_Rectangle* render_rect, int max_memory, float zoom); void ewk_tiled_backing_store_pre_render_cancel(Evas_Object* o); bool ewk_tiled_backing_store_disable_render(Evas_Object* o); bool ewk_tiled_backing_store_enable_render(Evas_Object* o); #endif // ewk_tiled_backing_store_h
51.730435
155
0.73962
[ "render" ]
153674a4d790985e96b436e2d949356c5d4b12db
6,238
h
C
include/level.h
stal12/nikman
711c48579fbfdd781f5d289f933068283f99a5ad
[ "MIT" ]
3
2021-11-10T23:17:29.000Z
2022-03-31T10:48:02.000Z
include/level.h
stal12/nikman
711c48579fbfdd781f5d289f933068283f99a5ad
[ "MIT" ]
null
null
null
include/level.h
stal12/nikman
711c48579fbfdd781f5d289f933068283f99a5ad
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2021 Stefano Allegretti, Davide Papazzoni, Nicola Baldini, Lorenzo Governatori e Simone Gemelli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if !defined NIKMAN_LEVEL_H #define NIKMAN_LEVEL_H #include <vector> #include <fstream> #include <iostream> struct LevelDesc { int h; int w; std::vector<std::pair<int, int>> ver_walls; std::vector<std::pair<int, int>> hor_walls; std::pair<int, int> nik_pos; std::pair<int, int> ste_pos; std::vector<std::pair<int, int>> weapons; std::vector<std::pair<int, int>> home; std::vector<std::pair<int, int>> mud; std::vector<std::pair<int, int>> empty; std::vector<std::pair<int, int>> teleports; }; LevelDesc ReadLevelDesc(const char* filename) { #define INVALID_FORMAT { std::cerr << "Error in ReadLevelDesc: invalid format.\n"; return level; } #define EXPECT_CHAR(c) { if (is.get() != (c)) INVALID_FORMAT } LevelDesc level; auto UseLetterLambda = [&](int c, int x, int y)->bool { switch (c) { case 'n': level.nik_pos = std::make_pair(x, y); break; case 's': level.ste_pos = std::make_pair(x, y); break; case 'w': level.weapons.emplace_back(x, y); break; case 'h': level.home.emplace_back(x, y); break; case 'm': level.mud.emplace_back(x, y); break; case 'e': level.empty.emplace_back(x, y); break; case 't': level.teleports.emplace_back(x, y); break; case ' ': break; default: return false; } return true; }; std::ifstream is(filename); if (!is.is_open()) { std::cerr << "Error in ReadLevelDesc: can't open filename.\n"; return level; } is.seekg(0, std::ios_base::end); size_t filesize = is.tellg(); is.seekg(0, std::ios_base::beg); int c; // Read first line int w = 0; while (true) { EXPECT_CHAR('+') c = is.get(); if (c == '-') { for (int i = 0; i < 2; ++i) { EXPECT_CHAR('-') } ++w; } else if (c == '\n') { break; } else INVALID_FORMAT } int h = (filesize / (w * 4 + 2) - 1) / 2; if (w < 1 || h < 1) { INVALID_FORMAT } level.h = h; level.w = w; int y = h - 1; int x = 0; for (y = h - 1; y > 0; --y) { EXPECT_CHAR('|') EXPECT_CHAR(' ') for (x = 0; x < w - 1; ++x) { c = is.get(); if (!UseLetterLambda(c, x, y)) { INVALID_FORMAT } EXPECT_CHAR(' ') c = is.get(); if (c == '|') { level.ver_walls.emplace_back(x + 1, y); } else if (c != ' ') { INVALID_FORMAT } EXPECT_CHAR(' ') } c = is.get(); if (!UseLetterLambda(c, x, y)) { INVALID_FORMAT } EXPECT_CHAR(' ') EXPECT_CHAR('|') EXPECT_CHAR('\n') // Read wall line for (x = 0; x < w; ++x) { EXPECT_CHAR('+') c = is.get(); if (c == ' ') { for (int i = 0; i < 2; ++i) { EXPECT_CHAR(' ') } } else if (c == '-') { for (int i = 0; i < 2; ++i) { EXPECT_CHAR('-') } level.hor_walls.emplace_back(x, y); } else { INVALID_FORMAT } } EXPECT_CHAR('+') EXPECT_CHAR('\n') // End wall line } EXPECT_CHAR('|') EXPECT_CHAR(' ') for (x = 0; x < w - 1; ++x) { c = is.get(); if (!UseLetterLambda(c, x, y)) { INVALID_FORMAT } EXPECT_CHAR(' ') c = is.get(); if (c == '|') { level.ver_walls.emplace_back(x + 1, y); } else if (c != ' ') { INVALID_FORMAT } EXPECT_CHAR(' ') } c = is.get(); if (!UseLetterLambda(c, x, y)) { INVALID_FORMAT } EXPECT_CHAR(' ') EXPECT_CHAR('|') EXPECT_CHAR('\n') // Read end line for (x = 0; x < w; ++x) { EXPECT_CHAR('+') for (int i = 0; i < 3; ++i) { EXPECT_CHAR('-') } } EXPECT_CHAR('+') // EXPECT_CHAR('\n') // Add external walls for (x = 0; x < w; ++x) { level.hor_walls.emplace_back(x, 0); level.hor_walls.emplace_back(x, h); } for (y = 0; y < h; ++y) { level.ver_walls.emplace_back(0, y); level.ver_walls.emplace_back(w, y); } return level; #undef EXPECT_CHAR #undef INVALID_FORMAT } #endif // NIKMAN_LEVEL_H
27.848214
112
0.480763
[ "vector" ]
d1b59784f8dcc6d53fbd8437e6dbc8ea447de4c7
3,051
h
C
include/another-rxcpp/subscriber.h
CODIANZ/another-rxcpp
5fd85037fa7cafbb6ba91a3dc507822e0d68a383
[ "MIT" ]
9
2022-01-06T16:56:49.000Z
2022-03-15T05:23:48.000Z
include/another-rxcpp/subscriber.h
CODIANZ/another-rxcpp
5fd85037fa7cafbb6ba91a3dc507822e0d68a383
[ "MIT" ]
1
2021-12-30T15:20:57.000Z
2022-01-01T12:00:42.000Z
include/another-rxcpp/subscriber.h
CODIANZ/another-rxcpp
5fd85037fa7cafbb6ba91a3dc507822e0d68a383
[ "MIT" ]
null
null
null
#if !defined(__another_rxcpp_h_subscriber__) #define __another_rxcpp_h_subscriber__ #include "observer.h" #include "internal/source/source_base.h" #include "internal/tools/private_access.h" #include <cassert> namespace another_rxcpp { template <typename T> class subscriber { friend class internal::private_access::subscriber; public: using value_type = T; using observer_type = observer<value_type>; private: using source_base = internal::source_base; using source_sp = typename source_base::sp; using observer_sp = typename observer_type::sp; using source_wp = std::weak_ptr<source_base>; using observer_wp = std::weak_ptr<observer_type>; struct member { source_sp source_; observer_wp observer_; std::vector<source_sp> upstreams_; std::recursive_mutex mtx_; }; std::shared_ptr<member> m_; template <typename X> void add_upstream(X upstream) const noexcept { std::lock_guard<std::recursive_mutex> lock(m_->mtx_); m_->upstreams_.push_back(std::dynamic_pointer_cast<source_base>(upstream)); } void unsubscribe_upstreams() const noexcept { std::lock_guard<std::recursive_mutex> lock(m_->mtx_); for(auto it : m_->upstreams_){ auto u = it; if(u){ u->unsubscribe(); } } m_->upstreams_.clear(); } public: subscriber() noexcept : m_(std::make_shared<member>()) {} template <typename SOURCE_SP> subscriber(SOURCE_SP source, observer_sp observer) noexcept : m_(std::make_shared<member>()) { m_->source_ = std::dynamic_pointer_cast<source_base>(source); m_->observer_ = observer; } void on_next(const value_type& value) const noexcept { auto s = m_->source_; auto o = m_->observer_.lock(); if(!is_subscribed()){ unsubscribe(); return; } if(s){ s->on_next_function([&]() { if(o && o->on_next){ o->on_next(value); } }); } } void on_error(std::exception_ptr err) const noexcept { unsubscribe_upstreams(); auto s = m_->source_; auto o = m_->observer_.lock(); if(s){ s->on_error_function([o, err](){ if(o){ assert(o->on_error); if(o->on_error){ o->on_error(err); } } }); } unsubscribe(); } void on_completed() const noexcept { unsubscribe_upstreams(); auto s = m_->source_; auto o = m_->observer_.lock(); if(s){ s->on_completed_function([o](){ if(o && o->on_completed){ o->on_completed(); } }); } unsubscribe(); } bool is_subscribed() const noexcept { std::lock_guard<std::recursive_mutex> lock(m_->mtx_); auto s = m_->source_; return s ? s->is_subscribed() : false; } void unsubscribe() const noexcept { unsubscribe_upstreams(); std::lock_guard<std::recursive_mutex> lock(m_->mtx_); auto s = m_->source_; if(s){ s->unsubscribe(); } } }; } /* namespace another_rxcpp */ #endif /* !defined(__another_rxcpp_h_subscriber__) */
23.835938
79
0.630613
[ "vector" ]
d1cec1177d119d689591a39b079a8eb9952835df
44,955
c
C
src/read.c
leoagomes/europa
1c588c3f90fd98e9c60304c3926a7074d5e9cfbd
[ "MIT" ]
1
2020-07-30T19:33:53.000Z
2020-07-30T19:33:53.000Z
src/read.c
leoagomes/europa
1c588c3f90fd98e9c60304c3926a7074d5e9cfbd
[ "MIT" ]
null
null
null
src/read.c
leoagomes/europa
1c588c3f90fd98e9c60304c3926a7074d5e9cfbd
[ "MIT" ]
null
null
null
/** Generic port `read` procedure implementation. * * @file read.c * @author Leonardo G. */ #include <ctype.h> #include <stdio.h> #include "europa/europa.h" #include "europa/port.h" #include "europa/error.h" #include "europa/number.h" #include "europa/character.h" #include "europa/util.h" #include "europa/symbol.h" #include "europa/pair.h" #include "europa/bytevector.h" #include "europa/vector.h" #include "europa/table.h" #include "utf8.h" /* This is where the first parser exists. Thread carefully! * * This first iteration of the parser reads from ports a character at a time. * The goal is that each port implementation would have a parser of its own in * order to make optimizations. * * This parser is written using only the concept of "port" instead of files or * memory buffers directly. This will result in a performance penalty. Even more * so because it uses the port's "public" API, so port will end up being * compared to NULL a thousand times, but the second I finish this parser, it * will also work for in memory strings so long as string-port implements the * interface correctly. * */ #define AUX_BUFFER_SIZE 1024 #ifndef EOF #define EOF -1 #endif #define CHASH '#' #define CLPAR '(' #define CRPAR ')' #define CLSQB '[' #define CRSQB ']' #define CLCRLB '{' #define CRCRLB '}' #define CDQUOT '"' #define CSQUOT '\'' #define CVLINE '|' #define CSCOLON ';' #define CPLUS '+' #define CMINUS '-' #define CDOT '.' #define CBSLASH '\\' #define CEXCL '!' #define CDOLLAR '$' #define CPERCENT '%' #define CAMP '&' #define CASTERISK '*' #define CFSLASH '/' #define CCOLON ':' #define CLESS '<' #define CGREAT '>' #define CEQUALS '=' #define CQUEST '?' #define CAT '@' #define CHAT '^' #define CUNDERSC '_' #define CTILDE '~' #define CGRAVE '`' #define CCOMMA ',' #define iseof(c) ((c) == EOF) #define isverticalline(c) ((c) == CVLINE) #define islineending(c) ((c) == '\n') #define iswhitespace(c) ((c) == ' ' || (c) == '\t') #define isitspace(c) (iswhitespace(c) || (c) == CSCOLON || (c) == CHASH) #define islpar(c) ((c) == CLPAR || (c) == CLSQB || (c) == CLCRLB) #define isrpar(c) ((c) == CRPAR || (c) == CRSQB || (c) == CRCRLB) #define isdelimiter(c) (iswhitespace(c) || islineending(c) || islpar(c) || \ isrpar(c) || (c) == CDQUOT || (c) == CSCOLON || iseof(c) || (c) == '\0') #define isexactness(c) ((c) == 'e' || (c) == 'E' || (c) == 'i' || (c) == 'I') #define isradix(c) ((c) == 'b' || (c) == 'B' || (c) == 'o' || (c) == 'O' || \ (c) == 'd' || (c) == 'D' || (c) == 'x' || (c) == 'X') #define isbool(c) ((c) == 't' || (c) == 'T' || (c) == 'f' || (c) == 'F') #define issign(c) ((c) == '-' || (c) == '+') #define isdot(c) ((c) == CDOT) #define isbinarydigit(c) ((c) == '0' || c == '1') #define isoctaldigit(c) ((c) >= '0' && (c) <= '7') #define isdecimaldigit(c) ((c) >= '0' && c <= '9') #define ishexdigit(c) (((c) >= '0' && (c) <= '9') || \ ((c) >= 'A' && (c) <= 'F') || \ ((c) >= 'a' && (c) <= 'f')) #define isspecialinitial(c) ((c) == CEXCL || (c) == CDOLLAR || (c) == CPERCENT ||\ (c) == CAMP || (c) == CASTERISK || (c) == CFSLASH || (c) == CCOLON ||\ (c) == CLESS || (c) == CEQUALS || (c) == CGREAT || (c) == CQUEST ||\ (c) == CAT || (c) == CHAT || (c) == CUNDERSC || (c) == CTILDE) #define isletter(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z')) #define isinitial(c) (isspecialinitial(c) || isletter(c)) #define isvline(c) ((c) == CVLINE) #define isexplicitsign(c) ((c) == CPLUS || (c) == CMINUS) #define ispeculiar(c) (isexplicitsign(c) || (c) == CDOT) #define isidentifier(c) (isinitial(c) || isvline(c) || ispeculiar(c)) #define isspecialsubsequent(c) (isexplicitsign(c) || (c) == CDOT || (c) == CAT) #define issubsequent(c) (isinitial(c) || isdecimaldigit(c) ||\ isspecialsubsequent(c)) #define isdotsubsequent(c) (issubsequent(c) || isdot(c)) #define issignsubsequent(c) (isinitial(c) || isexplicitsign(c) || (c) == CAT) #define isabbrevprefix(c) ((c) == CSQUOT || (c) == CGRAVE || (c) == CCOMMA) typedef struct parser parser; struct parser { europa* s; eu_port* port; eu_error* error; int current, peek, line, col; char buf[AUX_BUFFER_SIZE]; eu_table* intern; eu_symbol *quote, *quasiquote, *unquote, *unqspl; }; /* some helper macros */ #define _checkreturn(res, cond) \ if ((res = cond)) \ return res #define errorf(p, fmt, ...) \ snprintf(p->buf, AUX_BUFFER_SIZE, "%d:%d: " fmt, p->line, p->col,\ __VA_ARGS__) #define seterrorf(p, fmt, ...) \ do {\ errorf(p, fmt, __VA_ARGS__);\ p->error = euerror_new(p->s, EU_ERROR_READ, p->buf, NULL);\ } while(0) #define seterror(p, fmt) \ do {\ snprintf(p->buf, AUX_BUFFER_SIZE, "%d:%d: " fmt, p->line, p->col);\ p->error = euerror_new(p->s, EU_ERROR_READ, p->buf, NULL);\ } while(0) #define testmake(p, name) ((p)->name != NULL ? (p)->name : pmake##name(p)) #define pquote(p) testmake(p, quote) #define punquote(p) testmake(p, unquote) #define pquasiquote(p) testmake(p, quasiquote) #define punqspl(p) testmake(p, unqspl) /* some needed prototypes */ int pread_datum(parser* p, eu_value* out); int pskip_itspace(parser* p); /* Because strings and identifiers can be arbitrarily long, the auxilary buffer * (p->buf) may be too small to hold them. Because of that, we take the approach * of using the auxilary buffer until it is full, then copying the data into the * heap, reallocating memory in chunks of a predetermined size whenever this * heap store is filled with string data. * * To make this switch between p->buf and a heap allocated buffer transparent, * we use the following functions. */ int gbuf_init(parser* p, void** buf, void** next, size_t* size) { /* set all variables to the auxilary buffer initially. */ *buf = p->buf; *next = *buf; *size = AUX_BUFFER_SIZE; /* zero-out the buffer to ensure that there will be a final NUL byte. */ memset(p->buf, 0, AUX_BUFFER_SIZE); return EU_RESULT_OK; } /* this is how much the buffer grows every time we need more memory for the * string/symbol. */ #define GBUF_GROWTH_RATE 128 int gbuf_append(parser* p, void** buf, void** next, size_t* size, size_t* remaining, int c) { char *cbuf, *cnext; /* append the character */ *next = utf8catcodepoint(*next, c, *remaining - 1); /* check whether there was space for the character in the buffer */ if (*next == NULL) { /* in case there wasn't, we need to either allocate a new heap buffer * or grow the heap buffer. */ if (*buf == p->buf) { /* we need to allocate a new buffer on the heap a bit larger than * the auxilary buffer. */ cbuf = _eugc_malloc(_eu_gc(p->s), *size + GBUF_GROWTH_RATE); if (cbuf == NULL) return EU_RESULT_BAD_ALLOC; /* copy the contents of the aux buffer into the newly allocated * buffer */ memcpy(cbuf, p->buf, AUX_BUFFER_SIZE); } else { /* the buffer currently lives in the heap, so we just need to grow it */ cbuf = _eugc_realloc(_eu_gc(p->s), *buf, *size + GBUF_GROWTH_RATE); if (cbuf == NULL) return EU_RESULT_BAD_ALLOC; } /* update the remainig space in the buffer and its size */ *size += GBUF_GROWTH_RATE; *remaining += GBUF_GROWTH_RATE; /* update the effective values */ *buf = cbuf; cnext = cbuf + (*size - *remaining); *next = cnext; /* try appending the character again */ *next = utf8catcodepoint(*next, c, *remaining); if (*next == NULL) return EU_RESULT_ERROR; } *remaining -= utf8codepointsize(c); /* put a nul byte just after the last appended byte */ cast(eu_byte*, *next)[0] = '\0'; return EU_RESULT_OK; } int gbuf_append_byte(parser* p, void** buf, void** next, size_t* size, size_t* remaining, eu_byte c) { eu_byte *bbuf, *bnext; bbuf = *buf; bnext = *next; if (remaining == 0) { if (*buf == p->buf) { /* we need to allocate a new buffer on the heap a bit larger than * the auxilary buffer. */ bbuf = _eugc_malloc(_eu_gc(p->s), *size + GBUF_GROWTH_RATE); if (bbuf == NULL) return EU_RESULT_BAD_ALLOC; /* copy the contents of the aux buffer into the newly allocated * buffer */ memcpy(bbuf, p->buf, AUX_BUFFER_SIZE); } else { /* the buffer currently lives in the heap, so we just need to grow it */ bbuf = _eugc_realloc(_eu_gc(p->s), *buf, *size + GBUF_GROWTH_RATE); if (bbuf == NULL) return EU_RESULT_BAD_ALLOC; } /* update the effective values */ *buf = bbuf; bnext = bbuf + *size; *next = bnext; /* update the remainig space in the buffer and its size */ *size += GBUF_GROWTH_RATE; *remaining += GBUF_GROWTH_RATE; } *bnext = c; bnext++; *next = bnext; (*remaining) -= 1; return EU_RESULT_OK; } /* TODO: this code can be improved. * at the moment whenever a value is appended to the buffer it is copied twice * once to a temporary value and then to the buffer. * * if instead of using the function to append a value to the buffer we append it * directly by passing next to the read function, we will save one copy. * to do that, we need to use the append_value function instead as a "check that * next is valid, if not do whatever you need and give me a valid next" helper. * */ int gbuf_append_value(parser* p, void** buf, void** next, size_t* size, size_t* remaining, eu_value* val) { eu_value *vbuf, *vnext; vbuf = *buf; vnext = *next; if (*remaining < sizeof(eu_value)) { if (*buf == p->buf) { /* we need to allocate a new buffer on the heap a bit larger than * the auxilary buffer. */ vbuf = _eugc_malloc(_eu_gc(p->s), *size + GBUF_GROWTH_RATE); if (vbuf == NULL) return EU_RESULT_BAD_ALLOC; /* copy the contents of the aux buffer into the newly allocated * buffer */ memcpy(vbuf, p->buf, AUX_BUFFER_SIZE); } else { /* the buffer currently lives in the heap, so we just need to grow it */ vbuf = _eugc_realloc(_eu_gc(p->s), *buf, *size + GBUF_GROWTH_RATE); if (vbuf == NULL) return EU_RESULT_BAD_ALLOC; } /* update the effective values */ *buf = vbuf; vnext = vbuf + *size; *next = vnext; /* update the remainig space in the buffer and its size */ *size += GBUF_GROWTH_RATE; *remaining += GBUF_GROWTH_RATE; } *vnext = *val; vnext++; *next = vnext; (*remaining) -= sizeof(eu_value); return EU_RESULT_OK; } int gbuf_terminate(parser* p, void** buf) { if (p->buf != *buf) { _eugc_free(_eu_gc(p->s), *buf); } *buf = NULL; return EU_RESULT_OK; } /* initializes a parser structure */ int parser_init(parser* p, europa* s, eu_port* port) { int res; p->s = s; p->port = port; p->current = EOF; p->line = p->col = 0; p->error = NULL; p->quote = NULL; p->unquote = NULL; p->unqspl = NULL; p->quasiquote = NULL; /* create the internalization table */ p->intern = eutable_new(s, 32); /* completely arbitrary number */ if (p->intern == NULL) return EU_RESULT_BAD_ALLOC; _eutable_set_index(p->intern, _eu_global(s)->internalized); return euport_peek_char(s, port, &(p->peek)); } eu_symbol* pmake_symbol(parser* p, void* text) { eu_symbol* sym; eu_value *rval, sval; /* try getting the symbol from the internalized table */ if (eutable_rget_symbol(p->s, p->intern, text, &rval)) return NULL; if (rval) /* got a symbol, return it */ return _euvalue_to_symbol(_eutnode_key(_eutnode_from_valueptr(rval))); /* not in internalized table, create it and add to the table */ sym = eusymbol_new(p->s, text); if (sym == NULL) return NULL; _eu_makesym(&sval, sym); /* make a value out of it */ /* add it to the table */ if (eutable_create_key(p->s, p->intern, &sval, &rval)) return NULL; /* set its value to something that does not need marking for collection */ _eu_makebool(rval, EU_TRUE); return sym; } eu_string* pmake_string(parser* p, void* text) { eu_string* str; eu_value *rval, sval; /* try getting the string from the internalized table */ if (eutable_rget_string(p->s, p->intern, text, &rval)) return NULL; if (rval) /* got a string, return it */ return _euvalue_to_string(_eutnode_key(_eutnode_from_valueptr(rval))); /* not in internalized table, create it and add to the table */ str = eustring_new(p->s, text); if (str == NULL) return NULL; _eu_makestring(&sval, str); /* make a value out of it */ /* add it to the table */ if (eutable_create_key(p->s, p->intern, &sval, &rval)) return NULL; /* set its value to something that does not need marking for collection */ _eu_makebool(rval, EU_TRUE); return str; } /* consumes a character from the parser port */ int pconsume(parser* p) { p->col++; if (islineending(p->current)) { p->line++; p->col = 0; } return euport_read_char(p->s, p->port, &(p->current)); } /* peeks a character from the parser port, placing it into p->peek */ int ppeek(parser* p) { return euport_peek_char(p->s, p->port, &(p->peek)); } /* consumes the current character, making p->current = p->peek and populating * p->peek with the next peek character. * * basically reads a character and peeks the other in a sequence */ int padvance(parser* p) { int res; if ((res = pconsume(p))) return res; return ppeek(p); } /* asserts that the current character (p->current) matches a given character, * returning an error in case it does not match. */ int pmatch(parser* p, int c) { if (p->current != c) { seterrorf(p, "Expected character '%c' but got %x ('%c').", c, p->current, (char)p->current); return EU_RESULT_ERROR; } return EU_RESULT_OK; } /* asserts that the current character (p->current) matches a given character, * ignoring case, returning an error if they do not match. */ int pcasematch(parser* p, int c) { if (tolower(p->current) != tolower(c)) { seterrorf(p, "Expected (case-insensitive) '%c' but got %x ('%c').", c, p->current, (char)p->current); return EU_RESULT_ERROR; } return EU_RESULT_OK; } /* applies the match procedure over all characters in a string, advancing the * port along with the string. */ int pmatchstring(parser* p, void* str) { void* next; int cp; int res; next = utf8codepoint(str, &cp); while (cp && next) { if ((res = pmatch(p, cp))) break; if ((res = padvance(p))) break; next = utf8codepoint(next, &cp); } if (res) { seterrorf(p, "Could not match expected '%s'.", (char*)str); return res; } return EU_RESULT_OK; } /* applies the casematch procedure over all characters in a string, just like * matchstring. */ int pcasematchstring(parser* p, void* str) { void* next; int cp; int res; next = utf8codepoint(str, &cp); while (cp && next) { if ((res = pcasematch(p, cp))) break; if ((res = padvance(p))) break; next = utf8codepoint(next, &cp); } if (res) { seterrorf(p, "Could not match (ignoring case) expected '%s'.", (char*)str); return res; } return EU_RESULT_OK; } /* reads a <boolean> in either #t or #true (or #f and #false) formats, returning * an error if the sequence does not form a valid boolean. */ int pread_boolean(parser* p, eu_value* out) { int res; _checkreturn(res, pmatch(p, CHASH)); _checkreturn(res, padvance(p)); switch (p->current) { case 't': if (!isdelimiter(p->peek)) { /* in case it wasnt exactly '#t' */ _checkreturn(res, pcasematchstring(p, "true")); if (!isdelimiter(p->current)) { /* in case it wasn't exactly '#true' */ seterror(p, "Invalid token provided when 'true' was expected."); return EU_RESULT_INVALID; } /* at this point we either returned an error or consumed all "true" * characters. so we're already with p->current at the character just * after the 'e' */ } else { /* consume the 't' character */ padvance(p); } /* this code will only be reached if the input was either '#t' or * '#true' so we set the value to the true boolean and that's it */ *out = _true; return EU_RESULT_OK; case 'f': if (!isdelimiter(p->peek)) { /* in case it wasnt exactly '#f' */ _checkreturn(res, pcasematchstring(p, "false")); if (!isdelimiter(p->current)) { /* in case it wasn't exactly '#false' */ seterror(p, "Invalid token provided when 'false' was expected."); return EU_RESULT_INVALID; } /* at this point we either returned an error or consumed all "false" * characters. so we're already with p->current at the character just * after the 'e' */ } else { /* consume the 't' character */ padvance(p); } /* this code will only be reached if the input was either '#f' or * '#false' so we set the value to the true boolean and that's it */ *out = _false; return EU_RESULT_OK; break; default: seterror(p, "Parser in invalid state."); return EU_RESULT_ERROR; } } #define UNEXPECTED_DIGIT_IN_RADIX_STR "Unexpected digit %c for radix '%c' in number literal." #define UNEXPECTED_CHAR_IN_NUMBER_STR "Unexpected character %c in number literal." /* reads a <number> * * <number> is defined in a bnf-like language: * <number> := <num 2> | <num 8> | <num 10> | <num 16> * <num R> := <prefix R> <real R> * <prefix R> := <radix R> <exactness> * | <exactness> <radix R> * <real R> := <sign> <ureal R> * <ureal R> := <uinteger R> | <decimal R> * <uinteger R> := <digit R>+ * <decimal R> := <uinteger R> * | . <digit R>+ * | <digit R>+ . <digit R>* * * * available radices are #b #o #d #x for binary (2), octal (8), decimal (10) and * hexadecimal (16) respectively. note that the decimal radix is optional. * digits go according to the bases, so valid binary digits are 0 and 1, valid * octal digits are 0-7, decimal 0-9 and hex 0-9 and A-F (case-insensitive) * * TODO: add support for <suffix> * * WARNING: this implementation currently ignores explicitely exact real numbers, * integer numbers are exact unless #i is explicitely set and real (non-integer) * numbers are numbers are always inexact. */ int pread_number(parser* p, eu_value* out) { int res; int exactness = 'a', radix = 'd', sign = 1, value = 0, divideby = 0, aux; eu_integer ipart = 0; eu_real rpart = 0.0; /* test for explicit exactness/radix */ if (p->current == CHASH) { if (isexactness(p->peek)) { /* exactnes radix */ _checkreturn(res, padvance(p)); exactness = tolower(p->current); /* check for radix */ if (p->peek == CHASH) { _checkreturn(res, padvance(p)); if (!isradix(p->peek)) { seterror(p, "Expected radix for number literal."); return EU_RESULT_ERROR; } _checkreturn(res, padvance(p)); /* consume # */ radix = tolower(p->current); } } else if (isradix(p->peek)) { /* radix exactness */ _checkreturn(res, padvance(p)); radix = tolower(p->current); /* check for exactness */ if (p->peek == CHASH) { _checkreturn(res, padvance(p)); if (!isexactness(p->peek)) { seterror(p, "Expected exactness for number literal."); return EU_RESULT_ERROR; } _checkreturn(res, padvance(p)); /* consume # */ exactness = tolower(p->current); } } else { /* this is not a number token, it does not start with a prefix */ seterrorf(p, "Unexpected character %c parsing a number (<prefix>).", p->peek); return EU_RESULT_ERROR; } /* consume final exactness/radix character */ _checkreturn(res, padvance(p)); } /* read optinal sign */ if (issign(p->current)) { sign = p->current == '+' ? 1 : -1; _checkreturn(res, padvance(p)); } /* convert radix to meaningful value */ switch (radix) { case 'd': radix = 10; break; case 'b': radix = 2; break; case 'o': radix = 8; break; case 'x': radix = 16; break; default: seterrorf(p, "Invalid number radix '%c'.", radix); return EU_RESULT_ERROR; } /* read number */ do { if (p->current == CDOT) { if (divideby != 0) { /* in case a dot appeared already */ seterrorf(p, UNEXPECTED_CHAR_IN_NUMBER_STR, p->current); return EU_RESULT_ERROR; } /* TODO: maybe report when '.' appears in an explicitely exact * number */ _checkreturn(res, padvance(p)); /* consume the dot */ /* place whatever was recognized as integer part so far into the * real part and reset the integer part */ rpart = (eu_real)ipart; ipart = 0; /* set divideby to one so it will behave properly when multiplied * by radix */ divideby = 1; continue; /* restart the loop */ } /* assert digit is valid for current radix */ if ((radix == 2 && !isbinarydigit(p->current)) || (radix == 8 && !isoctaldigit(p->current)) || (radix == 10 && !isdecimaldigit(p->current)) || (radix == 16 && !ishexdigit(p->current))) { seterrorf(p, UNEXPECTED_DIGIT_IN_RADIX_STR, p->current, radix); return EU_RESULT_ERROR; } /* since most of the radices accept numbers in the 0-9 range, we * can pre-calculate the value in a "radix-independent" way */ value = p->current - '0'; /* if the digit was in the A-F range, we need to correct 'value' */ aux = tolower(p->current); if (aux >= 'a' && aux <= 'f') value = (aux - 'a') + 10; /* update integer part */ ipart = (ipart * radix) + value; /* if no '.' appeared, then divideby will be 0 and the following line * will result in divideby being zero still. * if a '.' appeared, then divideby will be the value we need to divide * ipart by and sum to rpart to represent the final real number. */ divideby *= radix; /* advance a character */ _checkreturn(res, padvance(p)); } while (!isdelimiter(p->current)); if (divideby) { /* in case the resulting number is real */ rpart = (eu_real)sign * (rpart + ((eu_real)ipart / (eu_real)divideby)); _eu_makereal(out, rpart); return EU_RESULT_OK; } if (exactness == 'i') { /* in case the number was explicitely inexact int */ _eu_makereal(out, (eu_real)(sign * ipart)); return EU_RESULT_OK; } /* in case the resulting number was an exact integer */ _eu_makeint(out, sign * ipart); return EU_RESULT_OK; } #define _checkchar(buf, out, str, c) \ if (utf8cmp(buf, str) == 0) {\ _eu_makechar(out, c);\ return EU_RESULT_OK;\ } #define CHAR_BUF_SIZE 128 /* reads a character literal * <character>s are either '#\<any character>', '#\<character name>' or * '#\x<unicode hex value>'. * * only R7RS-required character names are currently implemented. */ int pread_character(parser* p, eu_value* out) { int res; int c, v, pos; char buf[CHAR_BUF_SIZE]; void *next; size_t size; _checkreturn(res, pmatch(p, CHASH)); _checkreturn(res, padvance(p)); _checkreturn(res, pmatch(p, CBSLASH)); _checkreturn(res, padvance(p)); if (isdelimiter(p->peek)) { /* the #\<char> case */ _eu_makechar(out, p->current); _checkreturn(res, padvance(p)); return EU_RESULT_OK; } else if (p->current == 'x' || p->current == 'X') { /* the #\x<hexval> case */ _checkreturn(res, padvance(p)); /* consume 'x' */ c = 0; /* read the hex value */ while (!isdelimiter(p->current)) { /* check for invalid digits */ if (!ishexdigit(p->current)) { seterrorf(p, "Invalid character '%c' in unicode hex character literal.", (char)p->current); return EU_RESULT_ERROR; } /* calculate current character value from 0 to 15 */ v = tolower(p->current); if (v <= 'a' && v >= 'f') v = v - 'a' + 10; else v = v - '0'; c = (c << 4) | v; /* advance to the next character */ _checkreturn(res, padvance(p)); } /* conver the character to UTF-8 */ c = unicodetoutf8(c); _eu_makechar(out, c); return EU_RESULT_OK; } else { /* the #\<character name> case */ /* read the character name into the aux buffer */ size = CHAR_BUF_SIZE; next = buf; while (next != NULL && !isdelimiter(p->current)) { next = utf8catcodepoint(next, p->current, size); size -= utf8codepointsize(p->current); _checkreturn(res, padvance(p)); } /* check if the char name was too big */ if (next == NULL) { seterror(p, "Literal character name too big (and probably invalid)."); return EU_RESULT_ERROR; } cast(eu_byte*, next)[0] = '\0'; /* check for names */ _checkchar(buf, out, "alarm", '\n'); _checkchar(buf, out, "backspace", '\n'); _checkchar(buf, out, "delete", '\n'); _checkchar(buf, out, "escape", '\n'); _checkchar(buf, out, "newline", '\n'); _checkchar(buf, out, "return", '\n'); _checkchar(buf, out, "space", '\n'); _checkchar(buf, out, "tab", '\n'); /* in case it didn't match any valid character */ seterrorf(p, "Unknown character literal name '%s'.", buf); return EU_RESULT_ERROR; } } int pread_bytevector(parser* p, eu_value* out) { int res; eu_integer vsize; eu_value temp; void *buf, *next; size_t size, remaining; eu_bvector* vec; /* match the '#u8(' */ _checkreturn(res, pcasematchstring(p, "#u8(")); /* initialize auxilary buffer */ _checkreturn(res, gbuf_init(p, &buf, &next, &size)); remaining = size; /* read bytevector elements */ while (p->current != CRPAR && !iseof(p->current)) { /* skip any intertoken space */ _checkreturn(res, pskip_itspace(p)); /* assert that the next token is a number */ if (!(isdecimaldigit(p->current) || (issign(p->current) && isdecimaldigit(p->peek)) || (isdot(p->current) && isdecimaldigit(p->peek)) || (p->current == CHASH && (isexactness(p->peek) || isradix(p->peek))))) { seterrorf(p, "Expected a number literal but got character sequence " "'%c%c'.", (char)p->current, (char)p->peek); return EU_RESULT_ERROR; } /* read a number */ _checkreturn(res, pread_number(p, &temp)); /* assert the number is a valid byte (exact and in [0,256[) */ if (temp.type & EU_NUMBER_REAL || temp.value.i >= 256 || temp.value.i < 0) { seterror(p, "Bytevector values need to be an integer between 0 and " "255."); return EU_RESULT_ERROR; } /* append the byte to the buffer */ _checkreturn(res, gbuf_append_byte(p, &buf, &next, &size, &remaining, temp.value.i)); } /* turn the buf into a bytevector */ vec = eubvector_new(p->s, size - remaining, cast(eu_byte*, buf)); if (vec == NULL) return EU_RESULT_BAD_ALLOC; /* set the return value */ _eu_makebvector(out, vec); /* terminate the buffer */ _checkreturn(res, gbuf_terminate(p, &buf)); return EU_RESULT_OK; } #define VECTOR_GROWTH_RATE 5 /* * This reads a vector. */ int pread_vector(parser* p, eu_value* out) { int res; eu_value temp; eu_vector* vec; eu_integer count = 0; int size; /* match '#(' */ _checkreturn(res, pmatchstring(p, "#(")); /* initialize the vector's size */ size = 0; /* allocate the vector but only with the size of the GC header */ vec = _eugc_malloc(_eu_gc(p->s), sizeof(eu_object)); if (vec == NULL) { seterror(p, "Could not create read vector header."); return EU_RESULT_BAD_ALLOC; } /* initialize the header */ vec->_color = EUGC_COLOR_WHITE; vec->_previous = vec->_next = _euvector_to_obj(vec); vec->_type = EU_TYPE_VECTOR | EU_TYPEFLAG_COLLECTABLE; while (p->current != CRPAR && !iseof(p->current)) { /* skip intertoken space */ _checkreturn(res, pskip_itspace(p)); /* read a <datum> element */ _checkreturn(res, pread_datum(p, &temp)); /* append it to the vector */ /* check if we need to grow the vector */ if (size - (count + 1) <= 0) { /* because realloc'ing the vector may change its address, we have * to remove it from the root set */ if (vec) { _checkreturn(res, eugc_remove_object(p->s, _euvector_to_obj(vec))); } size += VECTOR_GROWTH_RATE; vec = _eugc_realloc(_eu_gc(p->s), vec, sizeof(eu_vector) + ((size - 1) * sizeof(eu_value))); if (vec == NULL) { seterrorf(p, "Could not grow read vector to size %d.", size); return EU_RESULT_BAD_ALLOC; } /* reading a vector requires creating objects, which may cause a GC * cycle. in order to prevent read objects from being collected, we * add the current vector to the GC's root set. */ _checkreturn(res, eugc_add_object(p->s, _eugc_root_head(_eu_gc(p->s)), _euvector_to_obj(vec))); } /* set the value at the appropriate index */ *_euvector_ref(vec, count) = temp; count++; /* correct vector length */ vec->length = count; } /* give vector ownership to the GC */ _checkreturn(res, eugc_move_off_root(p->s, _euvector_to_obj(vec))); /* set the return to it */ _eu_makevector(out, vec); return EU_RESULT_OK; } /* reads a token that begins with a '#', those can be booleans (#t), numbers * (#e#x1F), characters, vectors (#(a b c)), bytevectors (#u8(a b c)) */ int pread_hash(parser* p, eu_value* out) { int res; /* match the hash character */ _checkreturn(res, pmatch(p, CHASH)); if (isbool(p->peek)) return pread_boolean(p, out); else if (isradix(p->peek) || isexactness(p->peek)) return pread_number(p, out); else if (p->peek == CBSLASH) return pread_character(p, out); else if (p->peek == 'u') return pread_bytevector(p, out); else if (p->peek == CLPAR) return pread_vector(p, out); seterror(p, "Expected a boolean, number, ..., but nothing matched."); return EU_RESULT_ERROR; } /* skips a single-line comment */ int pskip_linecomment(parser* p) { int res; if ((res = pmatch(p, CSCOLON))) return res; do { _checkreturn(res, padvance(p)); } while (p->current != '\n' && p->current != '\r' && p->current != EOF); if (p->current == '\r' && p->peek == '\n') { /* check if line ending is \r\n */ _checkreturn(res, padvance(p)); } /* consume the final line ending character */ _checkreturn(res, padvance(p)); return EU_RESULT_OK; } /* skips a nested comment */ int pskip_nestedcomment(parser* p) { int res; int nestedcount = 0; _checkreturn(res, pmatch(p, CHASH)); /* make sure we're at a # */ while (p->current != EOF) { if (p->current == CHASH && p->peek == CVLINE) { /* we found an opening '#|' */ /* consume the # */ _checkreturn(res, padvance(p)); /* increment the nestedcount */ nestedcount++; } else if (p->current == CVLINE && p->peek == CHASH) { /* we found a closing '|#' */ /* consume the | */ _checkreturn(res, padvance(p)); /* decrement nested count */ nestedcount--; /* check that there aren't more closings than openings */ if (nestedcount < 0) { /* in which case consume the hash */ _checkreturn(res, padvance(p)); /* and break to return the error */ break; } else if (nestedcount == 0) { /* in case we just closed the last comment */ /* consume the # character and break */ _checkreturn(res, padvance(p)); break; } } _checkreturn(res, padvance(p)); } if (nestedcount > 0) { /* more comments were started than ended */ errorf(p, "%d more comments were opened than ended.", nestedcount); return EU_RESULT_ERROR; } else if (nestedcount < 0) { /* more comments were ended than started*/ seterror(p, "More nested comments were closed than opened."); return EU_RESULT_ERROR; } else { /* comments were properly nested */ return EU_RESULT_OK; } } /* skips datum comment */ int pskip_datumcomment(parser* p) { int res; eu_value out; _checkreturn(res, pmatch(p, CHASH)); _checkreturn(res, padvance(p)); _checkreturn(res, pmatch(p, CSCOLON)); _checkreturn(res, padvance(p)); /* skip any intertoken space */ _checkreturn(res, pskip_itspace(p)); /* read a datum that will be ignored */ /* TODO: create a function that skips datum instead of just ignoring it */ _checkreturn(res, pread_datum(p, &out)); return EU_RESULT_OK; } /* skips intertoken space */ int pskip_itspace(parser* p) { int res; while (isitspace(p->current)) { if (iswhitespace(p->current) || p->current == '\r' || p->current == '\n') { /* in case it was a \r\n sequence, also consume the \n */ if (p->current == '\r' && p->peek == '\n') _checkreturn(res, padvance(p)); _checkreturn(res, padvance(p)); } else if (p->current == CSCOLON) { /* single line comment, starting with ';' */ _checkreturn(res, pskip_linecomment(p)); /* skip the comment and continue in the loop */ } else if (p->current == CHASH) { /* might be a comment */ if (p->peek == CVLINE) { /* skip a nested comment */ _checkreturn(res, pskip_nestedcomment(p)); } else if (p->peek == CSCOLON) { /* skip a datum comment */ _checkreturn(res, pskip_datumcomment(p)); } else { /* it does not qualify for intertoken space */ break; } } } /* we already read any intertoken space available, so just return success */ return EU_RESULT_OK; } /* reads the inline (in-string?) escaped hex character value, something akin to * \xABC */ int pread_escaped_hex_char(parser* p, int* out) { int c = 0, v; int res; /* consume the x */ _checkreturn(res, padvance(p)); /* read characters up to a semicolon */ while (p->current != CSCOLON) { /* check for invalid digits */ if (!ishexdigit(p->current)) { seterrorf(p, "Invalid character '%c' in unicode inline hex character.", (char)p->current); return EU_RESULT_ERROR; } /* calculate current character value from 0 to 15 */ v = tolower(p->current); if (v <= 'a' && v >= 'f') v = v - 'a' + 10; else v = v - '0'; c = (c << 4) | v; /* advance to the next character */ _checkreturn(res, padvance(p)); } /* consume the semicolon */ *out = unicodetoutf8(c); return EU_RESULT_OK; } /* skips an (inlined/instring) escaped whitespace-newline-whitespace sequence */ int pskip_escaped_whitespace(parser* p) { int res; /* skip whitespace */ while (iswhitespace(p->current)) { _checkreturn(res, padvance(p)); } /* make sure that there is a line ending */ if (!islineending(p->current)) { seterrorf(p, "Expected a line ending after \\, but got %c.", p->current); return EU_RESULT_ERROR; } /* in case the newline was a \r\n consume the \r */ if (p->current == '\r' && p->peek == '\n') { padvance(p); } _checkreturn(res, padvance(p)); /* skip additional whitespace */ while (iswhitespace(p->current)) { _checkreturn(res, padvance(p)); } return EU_RESULT_OK; } /* reads an inline (in-string) escaped character */ int pread_escaped_char(parser* p, int* out) { int res; int c, v; /* consume the \ */ _checkreturn(res, padvance(p)); c = tolower(p->current); switch (c) { /* special characters */ case 'a': c = '\a'; break; case 'b': c = '\b'; break; case 't': c = '\t'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case '"': c = '"'; break; case '\\': c = '\\'; break; case '|': c = '|'; break; /* inline hex escape */ case 'x': return pread_escaped_hex_char(p, out); /* invalid */ default: seterrorf(p, "Invalid escape character %c.", p->current); return EU_RESULT_OK; } *out = c; return EU_RESULT_OK; } /* reads a string literal from the port */ int pread_string(parser* p, eu_value* out) { int res; int c, v, should_advance; void *buf, *next; size_t size, remaining; eu_string* str; /* make sure the first character is a " */ _checkreturn(res, pmatch(p, CDQUOT)); _checkreturn(res, padvance(p)); /* consume it */ /* initialize buffer pointers */ _checkreturn(res, gbuf_init(p, &buf, &next, &size)); remaining = size; /* read until end */ while (p->current != CDQUOT && p->current != EOF) { /* handle special chars */ if (p->current == CBSLASH) { if (iswhitespace(p->peek) || islineending(p->peek)) { _checkreturn(res, pskip_escaped_whitespace(p)); /* start a new iteration of the loop after the spaces */ continue; } else { _checkreturn(res, pread_escaped_char(p, &c)); } } else { /* any other character */ c = p->current; } /* append the character to the buffer */ _checkreturn(res, gbuf_append(p, &buf, &next, &size, &remaining, c)); /* advance to the next character in the string */ _checkreturn(res, padvance(p)); } /* if the string ended abruptly, we need to return an error */ if (p->current == EOF) { seterror(p, "String literal ended abruptly."); return EU_RESULT_ERROR; } /* consume the closing dquote */ _checkreturn(res, pconsume(p)); /* the string is valid, create the object */ str = pmake_string(p, buf); if (str == NULL) return EU_RESULT_BAD_ALLOC; out->type = EU_TYPE_STRING | EU_TYPEFLAG_COLLECTABLE; out->value.object = _eustring_to_obj(str); /* terminate the aux buffer, releasing memory if applicable */ gbuf_terminate(p, &buf); return EU_RESULT_OK; } /* reads a * <symbol> := <vertical line> <symbol element>* <vertical line> */ int pread_vline_symbol(parser* p, eu_value* out) { int res; void *next, *buf; size_t size, remaining; eu_symbol* sym; int c; _checkreturn(res, pmatch(p, CVLINE)); _checkreturn(res, padvance(p)); _checkreturn(res, gbuf_init(p, &buf, &next, &size)); remaining = size; while (!isvline(p->current) && !iseof(p->current)) { /* handle special chars */ if (p->current == CBSLASH) { _checkreturn(res, pread_escaped_char(p, &c)); } else { /* any other character */ c = p->current; } /* append the character to the auxilary buffer */ _checkreturn(res, gbuf_append(p, &buf, &next, &size, &remaining, c)); /* advance to the next character */ _checkreturn(res, padvance(p)); } /* create the symbol object */ sym = pmake_symbol(p, buf); if (sym == NULL) return EU_RESULT_BAD_ALLOC; /* set the output value */ out->type = EU_TYPE_SYMBOL | EU_TYPEFLAG_COLLECTABLE; out->value.object = _eusymbol_to_obj(sym); return EU_RESULT_OK; } int pread_insub_symbol(parser* p, eu_value* out) { int res; void *next, *buf; size_t size, remaining; eu_symbol* sym; /* initialize the auxilary buffer */ _checkreturn(res, gbuf_init(p, &buf, &next, &size)); remaining = size; do { /* append the current character to the symbol */ _checkreturn(res, gbuf_append(p, &buf, &next, &size, &remaining, p->current)); /* advance a character */ _checkreturn(res, padvance(p)); } while (issubsequent(p->current)); /* create the symbol */ sym = pmake_symbol(p, buf); if (sym == NULL) return EU_RESULT_BAD_ALLOC; out->type = EU_TYPE_SYMBOL | EU_TYPEFLAG_COLLECTABLE; out->value.object = _eusymbol_to_obj(sym); _checkreturn(res, gbuf_terminate(p, &buf)); return EU_RESULT_OK; } /* reads a <symbol> */ int pread_symbol(parser* p, eu_value* out) { if (isvline(p->current)) { /* vertical line symbols */ return pread_vline_symbol(p, out); } else if (isinitial(p->current) || (issign(p->current) && isdelimiter(p->peek)) || (issign(p->current) && issignsubsequent(p->peek)) || (issign(p->current) && isdot(p->peek)) || (isdot(p->current) && isdotsubsequent(p->peek))) { return pread_insub_symbol(p, out); } else { seterrorf(p, "Parser in inconsistent state. Tried to read an identifier" " and got '%c'.", (char)p->current); return EU_RESULT_ERROR; } return EU_RESULT_OK; } /* reads a <list> * <list> := ( <datum>* ) * | ( <datum>+ . <datum> ) */ int pread_list(parser* p, eu_value* out) { int res; int has_datum = 0; int has_dot = 0; eu_pair *first_pair, *pair, *nextpair; eu_value *slot; /* consume left parenthesis */ _checkreturn(res, padvance(p)); /* skip whitespaces and check if the list is empty */ _checkreturn(res, pskip_itspace(p)); if (isrpar(p->current)) { *out = _null; _checkreturn(res, pconsume(p)); /* consume the closing parenthesis */ return EU_RESULT_OK; } /* setup the first pair */ first_pair = pair = eupair_new(p->s, &_null, &_null); if (pair == NULL) return EU_RESULT_BAD_ALLOC; slot = _eupair_head(pair); /* move pair to GC's root set */ _checkreturn(res, eugc_move_to_root(p->s, _eupair_to_obj(pair))); /* place the first pair in out */ out->type = EU_TYPEFLAG_COLLECTABLE | EU_TYPE_PAIR; out->value.object = _eupair_to_obj(pair); while (!isrpar(p->current) && !iseof(p->current)) { /* check for dotted pair */ if (isdot(p->current) && isitspace(p->peek)) { if (!has_datum) { seterror(p, "Invalid dot found in list. There must be at least" " one <datum> before a dot."); return EU_RESULT_ERROR; } if (has_dot) { seterror(p, "Only a single dot is permitted in a dotted list."); return EU_RESULT_ERROR; } /* mark dotted pair */ has_dot = 1; /* setup the slot for the next value */ slot = _eupair_tail(pair); /* consume the dot, skip spaces and restart the loop */ _checkreturn(res, padvance(p)); _checkreturn(res, pskip_itspace(p)); continue; } /* try reading a datum */ _checkreturn(res, pread_datum(p, slot)); has_datum = 1; if (has_dot) { /* only one last datum is allowed after a dot, so we need to * terminate the list here. */ /* we skip whitespaces in order to make sure that if this list is * valid, p->current after the end of the loop is a closing par */ _checkreturn(res, pskip_itspace(p)); break; } /* skip intertoken spaces in order to check if we are at end of list */ _checkreturn(res, pskip_itspace(p)); /* if this is not the end of the list, we need to allocate a new pair * to hold the next element in it head and place it in the current pair's * tail */ if (!isrpar(p->current) && !(isdot(p->current) && isitspace(p->peek))) { /* allocate the next pair */ nextpair = eupair_new(p->s, &_null, &_null); if (nextpair == NULL) return EU_RESULT_BAD_ALLOC; /* place the next pair in the last pair's tail */ _eupair_tail(pair)->type = EU_TYPEFLAG_COLLECTABLE | EU_TYPE_PAIR; _eupair_tail(pair)->value.object = _eupair_to_obj(nextpair); /* set the next slot */ slot = _eupair_head(nextpair); /* update pairs */ pair = nextpair; } } if (!isrpar(p->current)) { /* incomplete or incorrect list */ if (iseof(p->current)) { /* incomplete */ seterror(p, "Unexpected incomplete list. Expected a datum, got EOF."); return EU_RESULT_ERROR; } if (has_dot) { /* erroneous dot */ seterror(p, "Expected end of dotted list, but found something else." " Do you have more than one <datum> after a dot?"); return EU_RESULT_ERROR; } /* inconsistent */ seterrorf(p, "Expected end of list (')'), but got character '%c'.", (char)p->current); return EU_RESULT_ERROR; } /* the closing parenthesis ')' is still in the buffer, so we should remove it */ _eu_checkreturn(padvance(p)); /* move first pair into object list again */ _checkreturn(res, eugc_move_off_root(p->s, _eupair_to_obj(pair))); return EU_RESULT_OK; } int pread_abbreviation(parser* p, eu_value* out) { int res; eu_symbol* sym; eu_pair* pair; eu_value* slot; /* make sure the state is consistent */ if (!isabbrevprefix(p->current)) { seterror(p, "Parser in inconsistent state. Tried reading an invalid " "abbreviation."); return EU_ERROR_NONE; } /* create a new pair for the abbreviation symbol */ pair = eupair_new(p->s, &_null, &_null); if (pair == NULL) return EU_RESULT_BAD_ALLOC; /* place it on the output */ _eu_makepair(out, pair); /* add it to GC root set */ _checkreturn(res, eugc_move_to_root(p->s, _eupair_to_obj(pair))); /* read the abbreviation */ if (p->current == CSQUOT) { sym = pmake_symbol(p, "quote"); } else if (p->current == CCOMMA) { sym = pmake_symbol(p, "unquote"); if (p->peek == CAT) { sym = pmake_symbol(p, "unquote-splicing"); padvance(p); } } else if (p->current == CGRAVE) { sym = pmake_symbol(p, "quasiquote"); } /* consume abbrev prefix character */ _checkreturn(res, padvance(p)); /* place correct symbol in pair's head and a new pair in tail */ _eu_makesym(_eupair_head(pair), sym); _eu_makepair(_eupair_tail(pair), eupair_new(p->s, &_null, &_null)); pair = _euobj_to_pair(_eupair_tail(pair)->value.object); if (pair == NULL) return EU_RESULT_BAD_ALLOC; /* read the next datum into the new pair's head */ _checkreturn(res, pread_datum(p, _eupair_head(pair))); /* remove the pair from the root set, putting it in object list */ _checkreturn(res, eugc_move_off_root(p->s, _eupair_to_obj(p->s))); return EU_RESULT_OK; } /* this reads a <datum> */ int pread_datum(parser* p, eu_value* out) { int res; /* check and skip inter token spaces (aka <atmosphere>) */ if (isitspace(p->current)) { _checkreturn(res, pskip_itspace(p)); } /* check terminals that start with # */ if (p->current == CHASH) { return pread_hash(p, out); } else if (isdecimaldigit(p->current) || (issign(p->current) && isdecimaldigit(p->peek)) || (isdot(p->current) && isdecimaldigit(p->peek))) { return pread_number(p, out); } else if (p->current == CDQUOT) { return pread_string(p, out); } else if (isidentifier(p->current) || (isdot(p->current) && isdotsubsequent(p->peek))) { return pread_symbol(p, out); } else if (islpar(p->current)) { return pread_list(p, out); } else if (isabbrevprefix(p->current)) { return pread_abbreviation(p, out); } return EU_RESULT_OK; } int euport_read(europa* s, eu_port* port, eu_value* out) { parser p; int res; if (!s || !port || !out) return EU_RESULT_NULL_ARGUMENT; parser_init(&p, s, port); _checkreturn(res, padvance(&p)); if ((res = pread_datum(&p, out))) { out->type = EU_TYPE_ERROR | EU_TYPEFLAG_COLLECTABLE; out->value.object = _euerror_to_obj(p.error); s->err = p.error; return res; } return EU_RESULT_OK; }
28.327032
93
0.643888
[ "object", "vector" ]
d1d57b1ef7e37d55fdc81b12ddedb479e6f93bc4
3,409
h
C
include/region-octree.h
rodp63/octree
d8a3210741d53c5899561f96c8508956a448b5a5
[ "MIT" ]
2
2020-09-24T14:58:16.000Z
2020-10-16T15:15:13.000Z
include/region-octree.h
rodp63/octree
d8a3210741d53c5899561f96c8508956a448b5a5
[ "MIT" ]
null
null
null
include/region-octree.h
rodp63/octree
d8a3210741d53c5899561f96c8508956a448b5a5
[ "MIT" ]
1
2020-09-25T05:49:36.000Z
2020-09-25T05:49:36.000Z
#pragma once #include <iostream> #include <fstream> #include <string> #include <vector> #include <stack> using namespace std; enum {WHITE, BLACK, INTERNAL}; template<typename T> struct Point { T x, y, z; Point(T a, T b, T c) : x(a), y(b), z(c) {} }; template<typename T> struct Node { Point<T> minBound, maxBound; int color; Node<T>* child[8]; Node(Point<T> a, Point<T> b, int c) : minBound(a), maxBound(b), color(c) { for(int i = 0; i < 8; ++i) child[i] = nullptr; } }; template<typename T, size_t DEPTH> class Octree { Node<T>* root; bool fit(Point<T> point, Node<T> *node) { bool X = point.x < (node->maxBound).x && point.x >= (node->minBound).x; bool Y = point.y < (node->maxBound).y && point.y >= (node->minBound).y; bool Z = point.z < (node->maxBound).z && point.z >= (node->minBound).z; return (X && Y && Z); } bool find(Point<T> val, stack<Node<T>* > &path, int col, Node<T>* start = nullptr) { Node<T> *current, *next; for(current = start ? start : root; current; current = next){ next = nullptr; for(int i = 0; i < 8; ++i) { if(current->child[i] && fit(val, current->child[i])) next = current->child[i]; } path.push(current); } return path.top()->color == col; } public: Octree(Point<T> lower_bottom_left, Point<T> upper_front_right) { root = new Node<T> (lower_bottom_left, upper_front_right, WHITE); } bool find(Point<T> point) { stack<Node<T>*> tmp; return (fit(point, root) && find(point, tmp, BLACK)); } void insert(Point<T> point, int col = BLACK) { stack<Node<T>*> path; if(fit(point, root) && !find(point, path, col)) { while(path.size() != DEPTH) { Node<T>* pos = path.top(); path.pop(); int cc = pos->color; pos->color = INTERNAL; T _x = pos->minBound.x, _y = pos->minBound.y, _z = pos->minBound.z; T _X = pos->maxBound.x, _Y = pos->maxBound.y, _Z = pos->maxBound.z; T _mx = (_x + _X)/2, _my = (_y + _Y)/2, _mz = (_z + _Z)/2; pos->child[0] = new Node<T>(Point<T>(_x, _y, _z), Point<T>(_mx, _my, _mz), cc); pos->child[1] = new Node<T>(Point<T>(_mx, _y, _z), Point<T>(_X, _my, _mz), cc); pos->child[2] = new Node<T>(Point<T>(_x, _my, _z), Point<T>(_mx, _Y, _mz), cc); pos->child[3] = new Node<T>(Point<T>(_mx, _my, _z), Point<T>(_X, _Y, _mz), cc); pos->child[4] = new Node<T>(Point<T>(_x, _y, _mz), Point<T>(_mx, _my, _Z), cc); pos->child[5] = new Node<T>(Point<T>(_mx, _y, _mz), Point<T>(_X, _my, _Z), cc); pos->child[6] = new Node<T>(Point<T>(_x, _my, _mz), Point<T>(_mx, _Y, _Z), cc); pos->child[7] = new Node<T>(Point<T>(_mx, _my, _mz), Point<T>(_X, _Y, _Z), cc); find(point, path, col, pos); } path.top()->color = col; path.pop(); bool flag = true; while(!path.empty() && flag) { Node<T>* current = path.top(); path.pop(); for(int i = 0; i < 8; ++i) { if(current->child[i]->color != col) flag = false; } if(flag) { current->color = col; for(int i = 0; i < 8; ++i) { delete current->child[i]; current->child[i] = nullptr; } } }} } void erase(Point<T> point) { insert(point, WHITE); } };
26.632813
87
0.523321
[ "vector" ]
d1e943cee80f76ae6a5ed67008d3eb98bc46365f
5,220
h
C
externals/lcm/lcm-1.0.0/lcmgen/lcmgen.h
ericmanzi/double_pendulum_lqr
76bba3091295abb7d412c4a3156258918f280c96
[ "BSD-3-Clause" ]
null
null
null
externals/lcm/lcm-1.0.0/lcmgen/lcmgen.h
ericmanzi/double_pendulum_lqr
76bba3091295abb7d412c4a3156258918f280c96
[ "BSD-3-Clause" ]
null
null
null
externals/lcm/lcm-1.0.0/lcmgen/lcmgen.h
ericmanzi/double_pendulum_lqr
76bba3091295abb7d412c4a3156258918f280c96
[ "BSD-3-Clause" ]
null
null
null
#ifndef _LCM_H #define _LCM_H #include <stdint.h> #include <glib.h> #include "getopt.h" ///////////////////////////////////////////////// #ifndef g_ptr_array_size #define g_ptr_array_size(x) ((x)->len) #endif ///////////////////////////////////////////////// // lcm_typename_t: represents the name of a type, including package // // Originally, the first field in the lcm_typename was named typename - which is a C++ // keyword and caused much grief. Renamed to lctypename. typedef struct lcm_typename lcm_typename_t; struct lcm_typename { char *lctypename; // fully-qualified name, e.g., "edu.mit.dgc.laser_t" char *package; // package name, e.g., "edu.mit.dgc" char *shortname; // e.g., "laser_t" }; ///////////////////////////////////////////////// // lcm_dimension_t: represents the size of a dimension of an // array. The size can be either dynamic (a variable) // or a constant. // typedef enum { LCM_CONST, LCM_VAR } lcm_dimension_mode_t; typedef struct lcm_dimension lcm_dimension_t; struct lcm_dimension { lcm_dimension_mode_t mode; char *size; // a string containing either a member variable name or a constant }; ///////////////////////////////////////////////// // lcm_member_t: represents one member of a struct, including (if its // an array), its dimensions. // typedef struct lcm_member lcm_member_t; struct lcm_member { lcm_typename_t *type; char *membername; // an array of lcm_dimension_t. A scalar is a 1-dimensional array // of length 1. GPtrArray *dimensions; }; ///////////////////////////////////////////////// // lcm_struct_t: a first-class LCM object declaration // typedef struct lcm_struct lcm_struct_t; struct lcm_struct { lcm_typename_t *structname; // name of the data type GPtrArray *members; // lcm_member_t // recursive declaration of structs and enums GPtrArray *structs; // lcm_struct_t GPtrArray *enums; // locally-declared enums DEPRECATED GPtrArray *constants; // lcm_constant_t char *lcmfile; // file/path of function that declared it int64_t hash; }; ///////////////////////////////////////////////// // lcm_constant_: the symbolic name of a constant and its value. // typedef struct lcm_constant lcm_constant_t; struct lcm_constant { char *lctypename; // int8_t / int16_t / int32_t / int64_t / float / double char *membername; union { int8_t i8; int16_t i16; int32_t i32; int64_t i64; float f; double d; } val; char *val_str; // value as a string, as specified in the .lcm file }; ///////////////////////////////////////////////// // DEPRECATED // lcm_enum_value_t: the symbolic name of an enum and its constant // value. // typedef struct lcm_enum_value lcm_enum_value_t; struct lcm_enum_value { char *valuename; int32_t value; }; ///////////////////////////////////////////////// // DEPRECATED // lcm_enum_t: an enumeration, also a first-class LCM object. // typedef struct lcm_enum lcm_enum_t; struct lcm_enum { lcm_typename_t *enumname; // name of the enum GPtrArray *values; // legal values for the enum char *lcmfile; // file/path of function that declared it // hash values for enums are "weak". They only involve the name of the enum, // so that new enumerated values can be added without breaking the hash. int64_t hash; }; ///////////////////////////////////////////////// // lcmgen_t: State used when parsing LCM declarations. The gopt is // essentially a set of key-value pairs that configure // various options. structs and enums are populated // according to the parsed definitions. // typedef struct lcmgen lcmgen_t; struct lcmgen { char *package; // remembers the last-specified package name, which is prepended to other types. getopt_t *gopt; GPtrArray *structs; // lcm_struct_t GPtrArray *enums; // lcm_enum_t (declared at top level) }; ///////////////////////////////////////////////// // Helper functions ///////////////////////////////////////////////// // Returns 1 if the argument is a built-in type (e.g., "int64_t", "float"). int lcm_is_primitive_type(const char *t); // Returns 1 if the argument is a legal constant type (e.g., "int64_t", "float"). int lcm_is_legal_const_type(const char *t); // Returns the member of a struct by name. Returns NULL on error. lcm_member_t *lcm_find_member(lcm_struct_t *lr, const char *name); // Returns the constant of a struct by name. Returns NULL on error. lcm_constant_t *lcm_find_const(lcm_struct_t *lr, const char *name); // Returns 1 if the "lazy" option is enabled AND the file "outfile" is // older than the file "declaringfile" int lcm_needs_generation(lcmgen_t *lcmgen, const char *declaringfile, const char *outfile); // create a new parsing context. lcmgen_t *lcmgen_create(); // for debugging, emit the contents to stdout void lcmgen_dump(lcmgen_t *lcm); // parse the provided file int lcmgen_handle_file(lcmgen_t *lcm, const char *path); // Are all of the dimensions of this array constant? // (scalars return 1) int lcm_is_constant_size_array(lcm_member_t *lm); #endif
29
104
0.630651
[ "object" ]
0606697dad28ce0655fd328d544030565f9ca969
8,120
h
C
chrome/browser/previews/previews_lite_page_redirect_url_loader_interceptor.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/previews/previews_lite_page_redirect_url_loader_interceptor.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/previews/previews_lite_page_redirect_url_loader_interceptor.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_PREVIEWS_PREVIEWS_LITE_PAGE_REDIRECT_URL_LOADER_INTERCEPTOR_H_ #define CHROME_BROWSER_PREVIEWS_PREVIEWS_LITE_PAGE_REDIRECT_URL_LOADER_INTERCEPTOR_H_ #include <stdint.h> #include <memory> #include <set> #include "base/memory/scoped_refptr.h" #include "base/sequence_checker.h" #include "chrome/browser/previews/previews_lite_page_redirect_serving_url_loader.h" #include "chrome/browser/previews/previews_lite_page_redirect_url_loader.h" #include "components/previews/content/previews_user_data.h" #include "content/public/browser/url_loader_request_interceptor.h" #include "net/http/http_request_headers.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "url/gurl.h" namespace content { class BrowserContext; class NavigationHandle; } // namespace content class PreviewsLitePageRedirectDecider; namespace previews { // Reasons that a navigation is blacklisted from a lite page redirect preview. // This enum must remain synchronized with the enum // |PreviewsServerLitePageBlacklistReason| in // tools/metrics/histograms/enums.xml. enum class LitePageRedirectBlacklistReason { // DEPRECATED: kPathSuffixBlacklisted = 0, kNavigationToPreviewsDomain = 1, kNavigationToPrivateDomain = 2, kHostBypassBlacklisted = 3, kMaxValue = kHostBypassBlacklisted, }; // Reasons that a navigation is not eligible for a lite page redirect preview. // This enum must remain synchronized with the enum // |PreviewsServerLitePageIneligibleReason| in // tools/metrics/histograms/enums.xml. enum class LitePageRedirectIneligibleReason { kNonHttpsScheme = 0, // DEPRECATED: kHttpPost = 1, kSubframeNavigation = 2, kServerUnavailable = 3, kInfoBarNotSeen = 4, // DEPRECATED: kNetworkNotSlow = 5, kLoadOriginalReload = 6, kCookiesBlocked = 7, // DEPRECATED: kECTUnknown = 8, kExceededMaxNavigationRestarts = 9, // DEPRECATED: kPreviewsState = 10, kInvalidProxyHeaders = 11, kServiceProbeIncomplete = 12, kServiceProbeFailed = 13, kAPIPageTransition = 14, kForwardBackPageTransition = 15, kMaxValue = kForwardBackPageTransition, }; // The response type from the previews server. This enum must // remain synchronized with the enum |PreviewsServerLitePageServerResponse| in // tools/metrics/histograms/enums.xml. enum class LitePageRedirectServerResponse { // A preview was served (HTTP 200). kOk = 0, // The client was redirected to another page (HTTP 307). kRedirect = 1, // The requested preview was not available (HTTP 307). kPreviewUnavailable = 2, // The previews server is not available (HTTP 503). kServiceUnavailable = 3, // The previews server responded with some other HTTP code. kOther = 4, // There was some network error and we did not get a response from the // previews server. kFailed = 5, // The previews server did not respond after a timeout. kTimeout = 6, // The previews server rejected our authentication (HTTP 403). kAuthFailure = 7, // No response headers were available from the preview server. kNoResponseHeaders = 8, // The connection was closed without getting a response. kOnCompleteBeforeOnResponse = 9, // There was an error connecting to the previews server. kConnectionError = 10, kMaxValue = kConnectionError, }; // Records an entry in the lite page redirect ineligibility histogram. void LogLitePageRedirectIneligibleReason( LitePageRedirectIneligibleReason reason); // If the given URL is a LitePage Preview URL, this returns true but does not // change the |url|. This will set |update_virtual_url_with_url| on // NavigationEntry so that |HandlePreviewsLitePageRedirectURLRewriteReverse| is // called when the navigation finishes. Note: This means the virtual URL will // not be set during the navigation load. This is handled separately in UI on // Android. bool HandlePreviewsLitePageRedirectURLRewrite( GURL* url, content::BrowserContext* browser_context); // Handles translating the given Lite Page URL to the original URL. Returns true // if the given |url| was a preview, otherwise returns false and does not change // |url|. bool HandlePreviewsLitePageRedirectURLRewriteReverse( GURL* url, content::BrowserContext* browser_context); // Returns the URL for a preview given by the url. GURL GetLitePageRedirectURLForURL(const GURL& original_url); // A class that attempts to intercept requests and fetch the Lite Page version // of the request. Its lifetime matches that of the content/ navigation loader // code. class PreviewsLitePageRedirectURLLoaderInterceptor : public content::URLLoaderRequestInterceptor { public: PreviewsLitePageRedirectURLLoaderInterceptor( const scoped_refptr<network::SharedURLLoaderFactory>& network_loader_factory, uint64_t page_id, int frame_tree_node_id); ~PreviewsLitePageRedirectURLLoaderInterceptor() override; // Gets the ServerLitePageInfo struct from an existing attempted lite page // navigation, if there is one. If not, returns a new ServerLitePageInfo // initialized with metadata from navigation_handle() and |this| that is owned // by the PreviewsUserData associated with navigation_handle(). static PreviewsUserData::ServerLitePageInfo* GetOrCreateServerLitePageInfo( content::NavigationHandle* navigation_handle, PreviewsLitePageRedirectDecider* manager); // content::URLLaoderRequestInterceptor: void MaybeCreateLoader( const network::ResourceRequest& tentative_resource_request, content::BrowserContext* browser_context, content::URLLoaderRequestInterceptor::LoaderCallback callback) override; private: // Begins an attempt at fetching the lite page version of the URL. void CreateRedirectLoader( const network::ResourceRequest& tentative_resource_request, content::BrowserContext* browser_context, content::URLLoaderRequestInterceptor::LoaderCallback callback); // Creates a redirect URL loader that immediately serves a redirect to // |original_url|. void CreateOriginalURLLoader( const network::ResourceRequest& tentative_resource_request, const GURL& original_url, content::URLLoaderRequestInterceptor::LoaderCallback callback); // Runs |callback| with |handler| and stores |serving_url_loader|. void HandleRedirectLoader( content::URLLoaderRequestInterceptor::LoaderCallback callback, std::unique_ptr<PreviewsLitePageRedirectServingURLLoader> serving_url_loader, RequestHandler handler); // Checks if the pending navigation is a forward/back nav and should be // disallowed according to experiment parameters. bool IsDisallowedFwdBackNavigation(); // All URLs already seen in this navigation. This prevents redirect loops, // etc. std::set<GURL> urls_processed_; // While attempting to fetch a lite page, this object manages communication // with the lite page server and serving redirects. Once, a decision has been // made regarding serving the preview, this object will be null. std::unique_ptr<PreviewsLitePageRedirectURLLoader> redirect_url_loader_; // Once a decision to serve the lite page has been made (based on server // response), this object will exist until a redirect to the lite page URL has // been handed off to the navigation stack and the next request is being // handled. std::unique_ptr<PreviewsLitePageRedirectServingURLLoader> serving_url_loader_; // Factory to create a network service URLLoader. scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory_; // Used in the chrome-proxy header if a preview is attempted. uint64_t page_id_; // Used to create the network service URLLoader. int frame_tree_node_id_; SEQUENCE_CHECKER(sequence_checker_); DISALLOW_COPY_AND_ASSIGN(PreviewsLitePageRedirectURLLoaderInterceptor); }; } // namespace previews #endif // CHROME_BROWSER_PREVIEWS_PREVIEWS_LITE_PAGE_REDIRECT_URL_LOADER_INTERCEPTOR_H_
37.419355
88
0.780665
[ "object" ]
4d54218938179082e76fea928da3e896cfbdad08
3,083
h
C
Wonderland/Wonderland/Editor/Foundation/UI/Widgets/UIBase.h
RodrigoHolztrattner/Wonderland
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
[ "MIT" ]
3
2018-04-09T13:01:07.000Z
2021-03-18T12:28:48.000Z
Wonderland/Wonderland/Editor/Foundation/UI/Widgets/UIBase.h
RodrigoHolztrattner/Wonderland
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
[ "MIT" ]
null
null
null
Wonderland/Wonderland/Editor/Foundation/UI/Widgets/UIBase.h
RodrigoHolztrattner/Wonderland
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
[ "MIT" ]
1
2021-03-18T12:28:50.000Z
2021-03-18T12:28:50.000Z
//////////////////////////////////////////////////////////////////////////////// // Filename: UIBase.h //////////////////////////////////////////////////////////////////////////////// #pragma once ////////////// // INCLUDES // ////////////// #include "..\..\ECS\ECS_Entity.h" #include "..\ViewController\Modules\CommandModule\CommandType.h" #include "..\Components\Tree\UITreeComponent.h" #include "..\Components\State\UIStateComponent.h" #include "..\Components\Frame\UIFrameComponent.h" #include <string> #include <iostream> /////////////// // NAMESPACE // /////////////// ///////////// // DEFINES // ///////////// //////////// // GLOBAL // //////////// //////////////////////////////////////////////////////////////////////////////// // Class name: UIBase //////////////////////////////////////////////////////////////////////////////// class UIBase : public ECS_Entity { public: template<typename WidgetClass, typename FrameComponent = UIFrameComponent, typename CommandComponent = UICommandComponent> static WidgetClass* CreateWidget(UIBase* _parent) { // Create the widget on the memory WidgetClass* widget = new WidgetClass(); // Create all components UIStateComponent* stateComponent = ECS_System<UIStateComponent>::Create(); UITreeComponent* treeComponent = ECS_System<UITreeComponent>::Create(); UIFrameComponent* frameComponent = ECS_System<FrameComponent>::Create(); CommandComponent* commandComponent = ECS_System<CommandComponent>::Create(); // Set the dependencies treeComponent->RegisterDependency(stateComponent); frameComponent->RegisterDependency(treeComponent); commandComponent->RegisterDependency(treeComponent); commandComponent->RegisterDependency(stateComponent); commandComponent->RegisterDependency(frameComponent); // Add all components widget->AddComponent(treeComponent); widget->AddComponent(stateComponent); widget->AddComponent(frameComponent); widget->AddComponent(commandComponent); // If the parent is valid if (_parent != nullptr) { // Get the parent tree component UITreeComponent* parentTreeComponent = _parent->FindComponent<UITreeComponent>(); // Add this child parentTreeComponent->AddChild(treeComponent); // Set our parent treeComponent->SetParent(parentTreeComponent); } // Create the widget widget->Create(); return widget; } UIBase(); UIBase(const UIBase&); ~UIBase(); // Return the parent UIBase* GetParent(); // Return the root parent UIBase* GetRootParent(); // Test void Update(); ///////////// // VIRTUAL // public: ///// // Process a command (virtual, dont call the parent function back if overloaded) virtual bool ProcessCommand(CommandType* _command); // Render this widget virtual void Render() {}; /////////// // DEBUG // public: /// // Set the debug name void SetDebugName(const char* _debugName) { m_DebugName = _debugName; } // Return the debug name std::string GetDebugName() { return m_DebugName; } /////////////// // VARIABLES // private: ////// // The debug name std::string m_DebugName; };
23.899225
123
0.618878
[ "render" ]
4d5bd6b3cb770b6d49ebbb97f35d10f04b89ce95
805
h
C
header/Vector.h
Wroyk-UniProjects/Robo_Steuerung_BS_A2a
0bf7fcf2c455b3fb9564452bf5c316a3502e5d4b
[ "MIT" ]
null
null
null
header/Vector.h
Wroyk-UniProjects/Robo_Steuerung_BS_A2a
0bf7fcf2c455b3fb9564452bf5c316a3502e5d4b
[ "MIT" ]
null
null
null
header/Vector.h
Wroyk-UniProjects/Robo_Steuerung_BS_A2a
0bf7fcf2c455b3fb9564452bf5c316a3502e5d4b
[ "MIT" ]
null
null
null
/* * Betribssicherheit * Aufgabe 2 Teil a * Robotorsteuerung in C++ * * * File: Vector.h * Author: Rudolf * * Created on 22. Mai 2017, 23:35 */ #ifndef VECTOR_H #define VECTOR_H #include <cstdlib> #include <cstdio> #include <vector> #include <iostream> class Vector { public: Vector(); Vector(double x, double y, double z); Vector(const Vector& orig); virtual ~Vector(); std::vector<Vector> linear(const Vector& end, int steps); void printCoord() const; void setCoord(double x, double y, double z); void setCoord(const Vector& orig); double getX() const; double getY() const; double getZ() const; private: double x,y,z; }; #endif /* VECTOR_H */
18.295455
66
0.567702
[ "vector" ]
4d60a629773fdd568fdc423899e4646426aed8b5
2,066
h
C
ConnectionAction.h
wootpthomas/smagick
55f36dcabfa9e987511f62fd50891c68c53903ba
[ "BSD-3-Clause" ]
null
null
null
ConnectionAction.h
wootpthomas/smagick
55f36dcabfa9e987511f62fd50891c68c53903ba
[ "BSD-3-Clause" ]
null
null
null
ConnectionAction.h
wootpthomas/smagick
55f36dcabfa9e987511f62fd50891c68c53903ba
[ "BSD-3-Clause" ]
null
null
null
#pragma once /*********************** Qt Includes ***********************/ #include <QAction> /*********************** Includes ***********************/ #include "DataTypes.h" /***************** * Memory Leak Detection *****************/ #if defined(WIN32) && defined(_DEBUG) && ( ! defined(CC_MEM_OPTIMIZE)) #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif class ConnectionAction : public QAction { Q_OBJECT public: ConnectionAction(const ConnectionDetails &CD, QObject *in_parent) : QAction(in_parent) { actionDetails = new ConnectionDetails(); this->setObjectName(QString("action_storedConnection") + CD.connectionID); this->setText(CD.username + QString("@") + CD.hostAddress); *actionDetails = CD; connect( this, SIGNAL( triggered() ), this, SLOT( slotTriggered() ) ); } ~ConnectionAction() { if(actionDetails) delete actionDetails; } signals: void triggeredDetails(ConnectionDetails *CD); private slots: void slotTriggered() { ConnectionDetails *tempDetails = new ConnectionDetails(); //this object is deleted by the sshtab *tempDetails = *actionDetails; emit triggeredDetails(tempDetails); } private: ConnectionDetails *actionDetails; }; class GroupAction : public QAction { Q_OBJECT public: GroupAction(const GroupDetails &GD, QObject *in_parent) : QAction(in_parent) { actionDetails = new GroupDetails(); this->setObjectName(QString("action_storedGroup") + QString::number(GD.groupID)); this->setText("Open all in " + GD.groupName); *actionDetails = GD; connect( this, SIGNAL( triggered() ), this, SLOT( slotTriggered() ) ); } ~GroupAction() { if(actionDetails) delete actionDetails; } signals: void triggeredDetails(GroupDetails *GD); private slots: void slotTriggered() { GroupDetails *tempDetails = new GroupDetails(); *tempDetails = *actionDetails; emit triggeredDetails(tempDetails); } private: GroupDetails *actionDetails; };
22.955556
100
0.648112
[ "object" ]
4d640d837620aa09de0e912f6cb5eca536077d35
528
c
C
lib/wizards/irmeli/area2/ruum27.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/irmeli/area2/ruum27.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/irmeli/area2/ruum27.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
inherit "room/room"; object monster; reset(arg) { if(!present("hobbit")) { move_object(clone_object("/wizards/irmeli/area2/king.c"), this_object()); } if(arg) return; add_exit("north","/wizards/irmeli/area2/ruum26.c"); set_not_out(1); short_desc = "Chamber of hobbit king"; long_desc = "A huge chamber where the king of hobbits lives. There is kings bed at the far\n"+ "end of the chamber. There is also a fireplace burning in the middle of\n"+ "chamber. \n"; }
24
96
0.632576
[ "object" ]
4d6a39b6621ad96dc7c634beac945b275fa7463a
3,115
h
C
clusters/Likelihood.h
mlebeur/merlin
71a595a414c30fdfa067a2633d8768ab1c2eb722
[ "BSD-3-Clause" ]
4
2017-01-11T13:24:50.000Z
2022-01-18T21:37:50.000Z
cstatgen/src/umich/clusters/Likelihood.h
changebio/rvnpl
22053ca4e24e5486e1179a5e85aaf316a218391f
[ "MIT" ]
8
2020-03-18T02:39:45.000Z
2020-12-12T08:05:24.000Z
cstatgen/src/umich/clusters/Likelihood.h
changebio/rvnpl
22053ca4e24e5486e1179a5e85aaf316a218391f
[ "MIT" ]
3
2021-01-26T03:22:59.000Z
2021-11-15T14:27:51.000Z
////////////////////////////////////////////////////////////////////// // clusters/Likelihood.h // (c) 2000-2007 Goncalo Abecasis // // This file is distributed as part of the MERLIN source code package // and may not be redistributed in any form, without prior written // permission from the author. Permission is granted for you to // modify this file for your own personal use, but modified versions // must retain this copyright notice and must not be distributed. // // Permission is granted for you to use this file to compile MERLIN. // // All computer programs have bugs. Use this file at your own risk. // // Tuesday December 18, 2007 // #ifndef __LIKELIHOOD_H__ #define __LIKELIHOOD_H__ #include "HaploGraph.h" #include "HaploSet.h" #include "MathVector.h" #define PAIRWISE_COUPLING 1 /* The first two alleles are coupled */ #define PAIRWISE_EQUILIBRIUM 0 /* The markers are in equilibrium */ #define PAIRWISE_REPULSION -1 /* The first two alleles are in repulsion */ class Likelihood { public: // Information about haplotypes int haplos; Vector frequencies; // Information about individual markers int markers; IntArray alleleCounts; Likelihood(); ~Likelihood() { if (index != NULL) delete [] index; } void Initialize(const IntArray & allelicCounts); void Initialize(const IntArray & allelicCounts, const IntArray & haplos, const Vector & freqs); void EditedEM(HaplotypeSets * sets); void RandomEM(HaplotypeSets * sets); void EM(HaplotypeSets * sets); void Print(double minfreq, HaplotypeSets * sets = NULL); void PrintExtras(); void SaveSummary(); void RetrieveHaplotypes(IntArray & haplos, Vector & freqs, double minFreq); double SetLikelihood(HaplotypeSet * set); double GraphLikelihood(HaplotypeGraph * graph); double GraphLikelihood(HaplotypeGraph * graph, int i); double CurrentLikelihood(HaplotypeGraph * graph); // Calculate pairwise LD coefficients for bi-allelic markers bool PairwiseLD(double & dprime, double & deltasq, int & coupling); bool PairwiseLD(double & dprime, double & deltasq) { int coupling; return PairwiseLD(dprime, deltasq, coupling); } double best_llk; Vector best_frequencies; double tol, ztol; // The following variables are used for favoring similar haplotypes void CheckSmoothing(); double pseudoMutation; bool gradual_smoothing; bool two_pass_smoothing; const char * failText; private: IntArray * index; IntArray last; Vector marginals; bool secondPass; double setLikelihood; double missingHaplotypes; Vector new_frequencies; void UpdateIndex(HaplotypeGraph * graph, int i); void ExpandIndex(HaplotypeGraph * graph, int i); void ReverseIndex(HaplotypeGraph * graph, int i, int pos); void CoreEM(HaplotypeSets * sets); void PseudoCoalescent(int start, int stop); }; #endif
30.841584
101
0.660674
[ "vector" ]
4d6dbd724b24c5df467621fa434feac8e5badd02
282
h
C
StarRender/src/Skybox.h
NBurley93/Prometheus3D
b09736bae108d0d0104f5fb6a1560219063008c7
[ "MIT" ]
null
null
null
StarRender/src/Skybox.h
NBurley93/Prometheus3D
b09736bae108d0d0104f5fb6a1560219063008c7
[ "MIT" ]
5
2021-06-07T21:23:09.000Z
2021-06-08T02:25:56.000Z
StarRender/src/Skybox.h
NBurley93/Prometheus3D
b09736bae108d0d0104f5fb6a1560219063008c7
[ "MIT" ]
null
null
null
#pragma once #include <GL/glew.h> #include <string> #include "Camera.h" class Skybox { public: Skybox(); ~Skybox(); void loadCubemap(std::string path); void Init(); void Render(Camera& cam); GLuint getTex() { return mTextureID; } private: GLuint mTextureID, mVAO, mVBO; };
15.666667
39
0.687943
[ "render" ]
4d6dea08741709bd7ffb9a5c85fff3c74af4a4c4
4,079
h
C
src/third_party/mozjs/include/js/Object.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/third_party/mozjs/include/js/Object.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/third_party/mozjs/include/js/Object.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: set ts=8 sts=2 et sw=2 tw=80: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef js_public_Object_h #define js_public_Object_h #include "js/shadow/Object.h" // JS::shadow::Object #include "mozilla/Assertions.h" // MOZ_ASSERT #include <stddef.h> // size_t #include <stdint.h> // uint32_t #include "jstypes.h" // JS_PUBLIC_API #include "js/Class.h" // js::ESClass, JSCLASS_RESERVED_SLOTS, JSCLASS_HAS_PRIVATE #include "js/Realm.h" // JS::GetCompartmentForRealm #include "js/RootingAPI.h" // JS::{,Mutable}Handle #include "js/Value.h" // JS::Value struct JS_PUBLIC_API JSContext; class JS_PUBLIC_API JSObject; namespace JS { class JS_PUBLIC_API Compartment; /** * Determine the ECMAScript "class" -- Date, String, RegExp, and all the other * builtin object types (described in ECMAScript in terms of an objecting having * "an [[ArrayBufferData]] internal slot" or similar language for other kinds of * object -- of the provided object. * * If this function is passed a wrapper that can be unwrapped, the determination * is performed on that object. If the wrapper can't be unwrapped, and it's not * a wrapper that prefers to treat this operation as a failure, this function * will indicate that the object is |js::ESClass::Other|. */ extern JS_PUBLIC_API bool GetBuiltinClass(JSContext* cx, Handle<JSObject*> obj, js::ESClass* cls); /** Get the |JSClass| of an object. */ inline const JSClass* GetClass(const JSObject* obj) { return reinterpret_cast<const shadow::Object*>(obj)->shape->base->clasp; } /** * Get the |JS::Compartment*| of an object. * * Note that the compartment of an object in this realm, that is a * cross-compartment wrapper around an object from another realm, is the * compartment of this realm. */ static MOZ_ALWAYS_INLINE Compartment* GetCompartment(JSObject* obj) { Realm* realm = reinterpret_cast<shadow::Object*>(obj)->shape->base->realm; return GetCompartmentForRealm(realm); } /** * Get the private value stored for an object whose class has a private. * * It is safe to call this function within |obj|'s finalize hook. */ inline void* GetPrivate(JSObject* obj) { MOZ_ASSERT(GetClass(obj)->flags & JSCLASS_HAS_PRIVATE); const auto* nobj = reinterpret_cast<const shadow::Object*>(obj); return nobj->fixedSlots()[nobj->numFixedSlots()].toPrivate(); } /** * Set the private value for |obj|. * * This function may called during the finalization of |obj|. */ extern JS_PUBLIC_API void SetPrivate(JSObject* obj, void* data); /** * Get the value stored in a reserved slot in an object. * * If |obj| is known to be a proxy and you're willing to use friend APIs, * |js::GetProxyReservedSlot| in "js/Proxy.h" is very slightly more efficient. */ inline const Value& GetReservedSlot(JSObject* obj, size_t slot) { MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetClass(obj))); return reinterpret_cast<const shadow::Object*>(obj)->slotRef(slot); } namespace detail { extern JS_PUBLIC_API void SetReservedSlotWithBarrier(JSObject* obj, size_t slot, const Value& value); } // namespace detail /** * Store a value in an object's reserved slot. * * This can be used with both native objects and proxies. However, if |obj| is * known to be a proxy, |js::SetProxyReservedSlot| in "js/Proxy.h" is very * slightly more efficient. */ inline void SetReservedSlot(JSObject* obj, size_t slot, const Value& value) { MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetClass(obj))); auto* sobj = reinterpret_cast<shadow::Object*>(obj); if (sobj->slotRef(slot).isGCThing() || value.isGCThing()) { detail::SetReservedSlotWithBarrier(obj, slot, value); } else { sobj->slotRef(slot) = value; } } } // namespace JS #endif // js_public_Object_h
34.567797
82
0.702623
[ "object", "shape" ]
4d7adce05b145f64e6cfeb4862109a6aacadd0ac
949
h
C
underworld/libUnderworld/StgDomain/libStgDomain/src/StgDomain.h
longgangfan/underworld2
5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4
[ "CC-BY-4.0" ]
116
2015-09-28T10:30:55.000Z
2022-03-22T04:12:38.000Z
underworld/libUnderworld/StgDomain/libStgDomain/src/StgDomain.h
longgangfan/underworld2
5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4
[ "CC-BY-4.0" ]
561
2015-09-29T06:05:50.000Z
2022-03-22T23:37:29.000Z
underworld/libUnderworld/StgDomain/libStgDomain/src/StgDomain.h
longgangfan/underworld2
5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4
[ "CC-BY-4.0" ]
68
2015-12-14T21:57:46.000Z
2021-08-25T04:54:26.000Z
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #ifndef __Domain_h__ #define __Domain_h__ #include "Geometry/Geometry.h" #include "Shape/Shape.h" #include "Mesh/Mesh.h" #include "Utils/Utils.h" #include "Swarm/Swarm.h" #include "Init.h" #include "Finalise.h" #endif /* __Domain_h__ */
39.541667
87
0.363541
[ "mesh", "geometry", "shape" ]
4d812d6651d4ded3e9f30b79b2d3fba7cbcd2678
807
h
C
fcode_object.h
remaxos/fcode
eb5087601b6e8d059137cfc0b35304fe1e1eb24d
[ "MIT" ]
null
null
null
fcode_object.h
remaxos/fcode
eb5087601b6e8d059137cfc0b35304fe1e1eb24d
[ "MIT" ]
1
2019-08-02T20:02:09.000Z
2019-08-02T21:32:08.000Z
fcode_object.h
remaxos/fcode
eb5087601b6e8d059137cfc0b35304fe1e1eb24d
[ "MIT" ]
null
null
null
#include <stdbool.h> #include <gtk/gtk.h> #include "fcode_list.h" #ifndef FCODE_OBJECT_H #define FCODE_OBJECT_H #define MAXNAME 512 typedef enum obj_type { FCODE_ROOT = 0, FCODE_DIR, FCODE_FILE } fcode_objtype; typedef struct object { fcode_objtype type; char name[MAXNAME]; struct object *parent; node *children; /* drawing */ float sx; float sy; float dx; float dy; bool exp; /* horizontal/vertical expansion */ } fcode_object; typedef struct project { fcode_object *objects; /* zoom-in/zoom-out feature */ float scale; /* needed for redrawing inside a click */ GtkWidget *drawing_area; } fcode_project; void print_object(fcode_object *obj); void print_project(fcode_project *proj); #endif /* FCODE_OBJECT_H */
17.170213
49
0.674102
[ "object" ]
4d9bc4da0fb195a0371a07d331b0ba0d574bbff1
5,478
h
C
v3d_main/cellseg/FL_main_brainseg.h
lens-biophotonics/v3d_external
44ff3b60a297a96eaa77ca092e0de9af5c990ed3
[ "MIT" ]
39
2015-05-10T23:23:03.000Z
2022-01-26T01:31:30.000Z
v3d_main/cellseg/FL_main_brainseg.h
lens-biophotonics/v3d_external
44ff3b60a297a96eaa77ca092e0de9af5c990ed3
[ "MIT" ]
13
2016-03-04T05:29:23.000Z
2021-02-07T01:11:10.000Z
v3d_main/cellseg/FL_main_brainseg.h
lens-biophotonics/v3d_external
44ff3b60a297a96eaa77ca092e0de9af5c990ed3
[ "MIT" ]
44
2015-11-11T07:30:59.000Z
2021-12-26T16:41:21.000Z
/* * Copyright (c)2006-2010 Hanchuan Peng (Janelia Farm, Howard Hughes Medical Institute). * All rights reserved. */ /************ ********* LICENSE NOTICE ************ This folder contains all source codes for the V3D project, which is subject to the following conditions if you want to use it. You will ***have to agree*** the following terms, *before* downloading/using/running/editing/changing any portion of codes in this package. 1. This package is free for non-profit research, but needs a special license for any commercial purpose. Please contact Hanchuan Peng for details. 2. You agree to appropriately cite this work in your related studies and publications. Peng, H., Ruan, Z., Long, F., Simpson, J.H., and Myers, E.W. (2010) “V3D enables real-time 3D visualization and quantitative analysis of large-scale biological image data sets,” Nature Biotechnology, Vol. 28, No. 4, pp. 348-353, DOI: 10.1038/nbt.1612. ( http://penglab.janelia.org/papersall/docpdf/2010_NBT_V3D.pdf ) Peng, H, Ruan, Z., Atasoy, D., and Sternson, S. (2010) “Automatic reconstruction of 3D neuron structures using a graph-augmented deformable model,” Bioinformatics, Vol. 26, pp. i38-i46, 2010. ( http://penglab.janelia.org/papersall/docpdf/2010_Bioinfo_GD_ISMB2010.pdf ) 3. This software is provided by the copyright holders (Hanchuan Peng), Howard Hughes Medical Institute, Janelia Farm Research Campus, and contributors "as is" and any express or implied warranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the copyright owner, Howard Hughes Medical Institute, Janelia Farm Research Campus, 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; reasonable royalties; 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. 4. Neither the name of the Howard Hughes Medical Institute, Janelia Farm Research Campus, nor Hanchuan Peng, may be used to endorse or promote products derived from this software without specific prior written permission. *************/ //FL_main_brainseg.h //by Fuhui Long //20081024 #ifndef __FL_MAIN_BRAINSEG_H__ #define __FL_MAIN_BRAINSEG_H__ //typedef unsigned short int CellSegLabelType; class levelset_segParameter // for watershed segmentation { public: char *infilename, *segfilename, *outfilename; // name of input and output files int channelNo; // channel to be segmented int dimension; int regionnum; // number of regions to be segmented int *regions; int maxregionnum; //maximum number of regions in the template int *regionNoModel; // regions that should not apply model, such as optical lobes int regionNoModelNum; // number of regions that should not apply model float lamda; //coefficient of the weighted length term Lg(\phi) float alf; //coefficient of the weighted area term Ag(\phi); float epsilon; // the papramater in the definition of smoothed Dirac function float delt; // time step float mu; //coefficient of the internal (penalizing) energy term P(\phi) float gama ; // int method; levelset_segParameter() //initialize parameters using default values { infilename = NULL; outfilename = NULL; segfilename = NULL; channelNo = 2; dimension = 2; regionnum = 62; maxregionnum = 62; regions = new int [regionnum]; for (int i=0; i<regionnum; i++) regions[i] = i+1; regionNoModel = new int [2]; // should revise regionNoModel[0] = 1; regionNoModel[1] = 34; regionNoModelNum = 2; lamda = 0.5; //coefficient of the weighted length term Lg(\phi) alf =1; //coefficient of the weighted area term Ag(\phi); epsilon = 1.5; // the papramater in the definition of smoothed Dirac function delt = 5; // time step mu = 0.1/delt; //coefficient of the internal (penalizing) energy term P(\phi) gama = 0.001; // method = 1; } levelset_segParameter(const levelset_segParameter & segPara) //initialize parameters using input values { infilename = segPara.infilename; segfilename = segPara.segfilename; outfilename = segPara.outfilename; channelNo = segPara.channelNo; dimension = segPara.dimension; regionnum = segPara.regionnum; maxregionnum = 62; regions = new int [regionnum]; for (int i=0; i<regionnum; i++) regions[i] = segPara.regions[i]; regionNoModel = new int [2]; // should revise regionNoModel[0] = 1; regionNoModel[1] = 34; regionNoModelNum = 2; lamda = segPara.lamda; //coefficient of the weighted length term Lg(\phi) alf = segPara.alf; //coefficient of the weighted area term Ag(\phi); epsilon = segPara.epsilon; // the papramater in the definition of smoothed Dirac function delt = segPara.delt; // time step mu = 0.1/segPara.delt; //coefficient of the internal (penalizing) energy term P(\phi) gama = segPara.gama; // method = segPara.method; } }; bool brainSeg2D(Vol3DSimple <unsigned char> *rawimg3d, Vol3DSimple <unsigned short int> *segimg3d, Vol3DSimple <unsigned short int> *outimg3d, const levelset_segParameter & mypara); #endif
43.47619
941
0.732384
[ "model", "3d" ]
4da14d7c6cf3bab4632bdaaec618e8a42cce68f7
1,766
h
C
src/cellogram/MeshUtils.h
cellogram/cellogram
d378e9b87e56b879b2fb352b08b0fed714481968
[ "MIT" ]
4
2019-09-25T15:04:27.000Z
2021-01-20T08:17:44.000Z
src/cellogram/MeshUtils.h
cellogram/cellogram
d378e9b87e56b879b2fb352b08b0fed714481968
[ "MIT" ]
null
null
null
src/cellogram/MeshUtils.h
cellogram/cellogram
d378e9b87e56b879b2fb352b08b0fed714481968
[ "MIT" ]
2
2019-10-14T01:36:20.000Z
2019-11-11T20:27:57.000Z
#pragma once //////////////////////////////////////////////////////////////////////////////// #include <cellogram/common.h> #include <geogram/mesh/mesh.h> #include <Eigen/Dense> #include <vector> #include <memory> //////////////////////////////////////////////////////////////////////////////// namespace cellogram { /// /// @brief { Converts a surface mesh to a Geogram mesh } /// /// @param[in] V { #V x 3 input mesh vertices } /// @param[in] F { #F x (3|4) input mesh surface (triangles or quads) } /// @param[out] M { Output Geogram mesh } /// void to_geogram_mesh(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, GEO::Mesh &M); /// /// @brief { Converts a tet-mesh to a Geogram mesh } /// /// @param[in] V { #V x 3 input mesh vertices } /// @param[in] F { #F x (3|4) input mesh surface (triangles or quads) } /// @param[in] T { #F x 4 input mesh tetrahedra } /// @param[out] M { Output Geogram mesh } /// void to_geogram_mesh(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, const Eigen::MatrixXi &T, GEO::Mesh &M); /// /// @brief { Extract simplices from a Geogram mesh } /// /// @param[in] M { Input Geogram mesh } /// @param[out] V { #V x 3 output mesh vertices } /// @param[out] F { #F x 3 output mesh faces } /// @param[out] T { #T x 4 output mesh tets } /// void from_geogram_mesh(const GEO::Mesh &M, Eigen::MatrixXd &V, Eigen::MatrixXi &F, Eigen::MatrixXi &T); /// /// @brief { Compute the median edge length of a mesh } /// /// @param[in] V { #V x (2|3) mesh vertices } /// @param[in] F { #F x 3 mesh faces } /// /// @return { Median edge length } /// double median_edge_length(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F); } // namespace cellogram
33.320755
113
0.549264
[ "mesh", "vector" ]
4da8f06365224978ed8f7133704cc6968512261e
1,216
h
C
src/base/rdb_parser/rdb_object_builder.h
nneesshh/kjredis
0d0b2389bede41e7985755f9b2ef310bc2335b99
[ "MIT" ]
1
2019-01-12T03:22:11.000Z
2019-01-12T03:22:11.000Z
src/base/rdb_parser/rdb_object_builder.h
nneesshh/KjCppRedis
0d0b2389bede41e7985755f9b2ef310bc2335b99
[ "MIT" ]
null
null
null
src/base/rdb_parser/rdb_object_builder.h
nneesshh/KjCppRedis
0d0b2389bede41e7985755f9b2ef310bc2335b99
[ "MIT" ]
1
2020-07-07T10:43:21.000Z
2020-07-07T10:43:21.000Z
#pragma once #include "rdb_parser_def.h" /* object-builder error code */ #define OB_OVER 1 #define OB_AGAIN 0 #define OB_ABORT -1 #define OB_ERROR_PREMATURE -2 #define OB_ERROR_INVALID_PATH -3 #define OB_ERROR_INVALID_MAGIC_STRING -4 #define OB_ERROR_INVALID_NB_TYPE -5 #define OB_ERROR_INVALID_STING_ENC -6 #define OB_ERROR_INVALID_NB_STATE -7 #define OB_ERROR_LZF_DECOMPRESS -8 #define OB_LOOP_BEGIN(_rp, _nb, _depth) \ _nb = stack_alloc_object_builder(_rp, _depth); \ do #define OB_LOOP_END(_rp, _rc) \ while (_rc == OB_AGAIN); \ if (_rc == OB_OVER) { \ stack_pop_object_builder(_rp); \ } rdb_object_builder_t * stack_push_object_builder(rdb_parser_t *rp); void stack_pop_object_builder(rdb_parser_t *rp); rdb_object_builder_t * stack_alloc_object_builder(rdb_parser_t *rp, uint8_t depth); rdb_object_builder_t * stack_object_builder_at(rdb_parser_t *rp, uint8_t depth); rdb_object_builder_t * stack_object_builder_top(rdb_parser_t *rp); /* EOF */
35.764706
84
0.629112
[ "object" ]
4db961f316f265f0cad317a71ecaf819f755195b
6,335
h
C
Include/Math/Vector2.h
FrostigaLimpan/FLCL
93e0895573956a5e82ff7b4c636534f192c09044
[ "MIT" ]
1
2016-10-09T14:29:17.000Z
2016-10-09T14:29:17.000Z
Include/Math/Vector2.h
FrostigaLimpan/FLCL
93e0895573956a5e82ff7b4c636534f192c09044
[ "MIT" ]
null
null
null
Include/Math/Vector2.h
FrostigaLimpan/FLCL
93e0895573956a5e82ff7b4c636534f192c09044
[ "MIT" ]
null
null
null
#pragma once #include <Types.h> #include <iostream> #include <typeinfo> namespace FLCL { namespace Math { // Forward declaration, should probably be moved to a common file. template <typename> struct Vec2; // Basetemplate for a vector 2. Contains the datastructure and the common operators that dosent need to be overloaded // by specialization. This template cannot be instanciated outside the vec2 class, since we have a private constructor // on it. // This should be refactored to a common baseclass for all vectors later on. Note about the hadamard // representation in that case since its internal counter is based on the vector size now. template <typename T> struct Basevector2 { // Friend with the Vec2 specialization so its possible to return a correct type from common // operators and to be able to instance through the private constructor. template<typename> friend struct Vec2; private: explicit Basevector2<T>(T xy) : x{ xy }, y{ xy } {}; Basevector2<T>(T inX, T inY) : x{ inX }, y{ inY } {}; Basevector2<T>(const Basevector2<T>& other) = default; public: // Internal datastructure and it's union so the variables can be easily accessed though name union { T values[2]; struct { T x, y; }; struct { T r, g; }; struct { T s, t; }; struct { T width, height; }; }; // Common operator overloads T& operator[](USize index) { return values[index]; }; const T& operator[](USize index) const { return values[index]; }; Bool8 operator==(const Vec2<T> other) const { for (USize iCount = 0; iCount < 2; iCount++) if (values[iCount] != other.values[iCount]) return false; return true; }; Bool8 operator!=(const Vec2<T> other) const { return !operator==(other); }; Vec2<T> operator+(const Vec2<T>& other) const { return Vec2<T>{x + other.x, y + other.y}; }; Vec2<T> operator-(const Vec2<T>& other) const { return Vec2<T>{x - other.x, y - other.y}; }; // Hadamard product representation Vec2<T> operator*(const Vec2<T>& other) const { Vec2<T> result; for (USize iCount = 0; iCount < 2; iCount++) result[iCount] = values[iCount] * other.values[iCount]; return result; } Vec2<T>& operator+=(const Vec2<T>& other) { x += other.x; y += other.y; return *this; }; Vec2<T>& operator-=(const Vec2<T>& other) { x -= other.x; y -= other.y; return *this; }; Vec2<T> operator*(T scalar) const { return Vec2<T>{scalar * x, scalar * y}; }; Vec2<T> operator/(T scalar) const { return Vec2<T>{x / scalar, y / scalar}; }; Vec2<T>& operator*=(T scalar) { x *= scalar; y *= scalar; return *this; }; Vec2<T>& operator/=(T scalar) { x /= scalar; y /= scalar; return *this; }; }; // Template specialization for Float32 type. template <> struct Vec2<Float32> : public Basevector2<Float32> { Vec2() :Basevector2(0.f, 0.f) {} explicit Vec2(Float32 xy) :Basevector2<Float32>(xy) {}; Vec2(Float32 x, Float32 y) :Basevector2(x, y) {}; Vec2(Float32 xy[]) :Basevector2(xy[0], xy[1]) {}; Vec2(const Vec2<Float32>& other) = default; }; // Template specialization for Float64 type. template <> struct Vec2<Float64> : public Basevector2<Float64> { Vec2() :Basevector2(0.f, 0.f) {} explicit Vec2(Float64 xy) :Basevector2<Float64>(xy) {}; Vec2(Float64 x, Float64 y) :Basevector2(x, y) {}; Vec2(Float64 xy[]) :Basevector2(xy[0], xy[1]) {}; Vec2(const Vec2<Float64>& other) = default; }; // Template specialization for Int8 type. template <> struct Vec2<Int8> : public Basevector2<Int8> { Vec2() :Basevector2(0, 0) {} explicit Vec2(Int8 xy) :Basevector2<Int8>(xy) {}; Vec2(Int8 x, Int8 y) :Basevector2(x, y) {}; Vec2(Int8 xy[]) :Basevector2(xy[0], xy[1]) {}; Vec2(const Vec2<Int8>& other) = default; }; // Template specialization for Int16 type. template <> struct Vec2<Int16> : public Basevector2<Int16> { Vec2() :Basevector2(0, 0) {} explicit Vec2(Int16 xy) :Basevector2<Int16>(xy) {}; Vec2(Int16 x, Int16 y) :Basevector2(x, y) {}; Vec2(Int16 xy[]) :Basevector2(xy[0], xy[1]) {}; Vec2(const Vec2<Int16>& other) = default; }; // Template specialization for Int32 type. template <> struct Vec2<Int32> : public Basevector2<Int32> { Vec2() :Basevector2(0, 0) {} explicit Vec2(Int32 xy) :Basevector2<Int32>(xy) {}; Vec2(Int32 x, Int32 y) :Basevector2(x, y) {}; Vec2(Int32 xy[]) :Basevector2(xy[0], xy[1]) {}; Vec2(const Vec2<Int32>& other) = default; }; // Template specialization for Int64 type. template <> struct Vec2<Int64> : public Basevector2<Int64> { Vec2() :Basevector2(0, 0) {} explicit Vec2(Int64 xy) :Basevector2<Int64>(xy) {}; Vec2(Int64 x, Int64 y) :Basevector2(x, y) {}; Vec2(Int64 xy[]) :Basevector2(xy[0], xy[1]) {}; Vec2(const Vec2<Int64>& other) = default; }; /* * Outside functions and operators that is common */ template<typename T> inline T dot(const Vec2<T>& first, const Vec2<T> second) { return first.x * second.x + first.y * second.y; }; template<typename T> inline T cross(const Vec2<T>& first, const Vec2<T> second) { return first.x * second.y - second.x * first.y; }; template<typename T> inline Vec2<T> operator*(T scalar, const Vec2<T>& vector) { return vector * scalar; }; // We might want a specialization that always uses Float32 as a scalar even on // non-Float32 vectors. Not decided on this yet. // TODO: Decide on this /*template<typename T> inline Vec2<T> operator*(Float32 scalar, const Vec2<T>& vector) { return vector * scalar; };*/ template<typename T> inline Vec2<T> norm(const Vec2<T>& a) { return a * (1.0f / length(a)); } template<typename T> inline T lengthSquared(const Vec2<T>& a) { return dot(a, a); }; template<typename T> inline T length(const Vec2<T>& a) { //return std::sqrtf(dot(a, a)); return std::sqrtf(lengthSquared(a)); }; template<typename T> inline std::ostream& operator<<(std::ostream& outStream, const Vec2<T>& vec) { return outStream << "Vec2<" << typeid(T).name() << ">(" << vec[0] << ":" << vec[1] << ")"; }; } //namespace Math } // namespace FLCL
28.155556
120
0.626835
[ "vector" ]
4dbe79b285374a7ff93dfaa9ce94cb8a0912a87f
414
h
C
lib/AerisCore.xcframework/tvos-arm64_x86_64-simulator/AerisCore.framework/Headers/AWFApiObject.h
aerisweather/aerisweather-ios
a1d6dcb02b0f4a26edfa1829f4161f21ddc5e5e0
[ "BSD-3-Clause" ]
null
null
null
lib/AerisCore.xcframework/tvos-arm64_x86_64-simulator/AerisCore.framework/Headers/AWFApiObject.h
aerisweather/aerisweather-ios
a1d6dcb02b0f4a26edfa1829f4161f21ddc5e5e0
[ "BSD-3-Clause" ]
null
null
null
lib/AerisCore.xcframework/tvos-arm64_x86_64-simulator/AerisCore.framework/Headers/AWFApiObject.h
aerisweather/aerisweather-ios
a1d6dcb02b0f4a26edfa1829f4161f21ddc5e5e0
[ "BSD-3-Clause" ]
null
null
null
// // AWFApiObject.h // AerisApiLibrary // // Created by Nicholas Shipes on 3/24/15. // Copyright (c) 2015 AerisWeather, LLC. All rights reserved. // #import <Foundation/Foundation.h> #import <AerisCore/AWFAutoCodingObject.h> @interface AWFApiObject : AWFAutoCodingObject @property (readonly, nonatomic) id identifier; - (void)updateWithObject:(AWFApiObject *)object; - (NSDictionary *)toDictionary; @end
20.7
62
0.743961
[ "object" ]
4dcc111bf1407f733a290b988490bccff86760d2
2,631
h
C
AI/path/pathfinder2d.h
jjuiddong/Common
2518fa05474222f84c474707b4511f190a34f574
[ "MIT" ]
2
2017-11-24T12:34:14.000Z
2021-09-10T02:18:34.000Z
AI/path/pathfinder2d.h
jjuiddong/Common
2518fa05474222f84c474707b4511f190a34f574
[ "MIT" ]
null
null
null
AI/path/pathfinder2d.h
jjuiddong/Common
2518fa05474222f84c474707b4511f190a34f574
[ "MIT" ]
6
2017-11-24T12:34:56.000Z
2022-03-22T10:05:45.000Z
// // 2018-11-02, jjuiddong // 2 Dimensional map path finder // thread safe // // - node character type // - 0 : no move // - 1 : slow node // - 2 : fast node // - 3 : wide road node // // sample data // // 111111111111111111111111 // 122222222222222222222222 // 120111102011110201111021 // 121000012100001210000121 // 121000012100001210000121 // 121000012100001210000121 // 121000012100001210000121 // 121000012100001210000121 // 121000012100001210000121 // 121000012100001210000121 // 121000012100001210000121 // 121000012100001210000121 // 121000012100001210000121 // 121000012100001210000121 // 120111102011110201111021 // 122222222222222222222222 // 111111111111111111111111 // #pragma once namespace ai { class cPathFinder2D { public: struct sVertex { int type; int edgeKey; // m_fastmap unique edge key (= max(from,to)*1000 + min(from,to)) float startLen; float endLen; sVertex() : type(0) {} }; typedef vector<Vector2i> ppath; // position path typedef vector<uint> vpath; // vertex index path typedef vector<cPathFinder::sEdge> epath; // edge path cPathFinder2D(); virtual ~cPathFinder2D(); bool Read(const char *fileName); bool Find(const Vector2i &startPos , const Vector2i &endPos , OUT ppath &out); bool FindEnumeration(const Vector2i &startPos , const Vector2i &endPos , OUT vector<ppath> &outPos , OUT vector<ppath> &outVertexPos , OUT vector<epath> &outEdges); bool GetEdgePath2PosPath(const epath &edgePath, OUT ppath &out); inline int MakeEdgeKey(const int from, const int to) const; inline int MakeUniqueEdgeKey(const int from, const int to) const; inline std::pair<int, int> SeparateEdgeKey(const int edgeKey) const; void Clear(); protected: inline sVertex& GetMap(const int idx); inline sVertex& GetMap(const Vector2i &pos); std::pair<int, int> GetRowsCols(const char *fileName); bool GenerateGraphNode(); bool AddTemporaryVertexAndEdges(const Vector3 &pos); bool RemoveTemporaryVertexAndEdges(const Vector3 &pos); bool CollectEdgeVertices(const int from, const int to, const int uniqueEdgeKey , OUT ppath &out); bool CollectEdgeAddedVertices(const int from, const int to, const int uniqueEdgeKey , const int addedVertexFrom, const int addedVertexTo , OUT ppath &out); inline bool CheckRange(const Vector2i &pos); float Distance_Manhatan(const Vector2i &p0, const Vector2i &p1) const; public: sVertex *m_map; // size = m_rows*m_cols, access = y*m_cols + x cPathFinder *m_fastmap; // fast path search int m_rows; int m_cols; vector<Vector2i> m_waypoints; static sVertex m_dummy; }; }
26.31
85
0.732041
[ "vector" ]
4dd0f33a46f5d297932dec6f41f3b21a4f2c2321
2,987
h
C
apps/libmc/core/neighborhood.h
djpetti/molecube
b7267803f080ed62e158fc5c1cfcff6beb709de7
[ "MIT" ]
2
2018-09-11T21:09:22.000Z
2018-10-05T08:35:58.000Z
apps/libmc/core/neighborhood.h
djpetti/molecube
b7267803f080ed62e158fc5c1cfcff6beb709de7
[ "MIT" ]
24
2018-09-09T22:51:26.000Z
2018-11-29T22:49:57.000Z
apps/libmc/core/neighborhood.h
djpetti/molecube
b7267803f080ed62e158fc5c1cfcff6beb709de7
[ "MIT" ]
1
2018-10-16T20:01:20.000Z
2018-10-16T20:01:20.000Z
#ifndef LIBMC_CORE_NEIGHBORHOOD_H_ #define LIBMC_CORE_NEIGHBORHOOD_H_ #include <stdint.h> namespace libmc { namespace core { // Represents the connection configuration of a cube. struct Connections { // Whether a cube is connected to the top face of this one. bool Top; // Whether a cube is connected to the bottom face of this one. bool Bottom; // Whether a cube is connected to the left face of this one. bool Left; // Whether a cube is connected to the right face of this one. bool Right; }; // Enumerates the faces of a cube. enum class Face { TOP, BOTTOM, LEFT, RIGHT }; // An abstract base class for dealing with connected cubes. class Neighborhood { public: virtual ~Neighborhood() = default; // Gets the current connection configuration of the cube. // Returns: // A Connections object representing the current configuration. const Connections &GetConnections(); // Sends a message to a particular cube. // Args: // face: The face on this cube that the recipient is connected to. // message: The message to send. Assumed to have a NULL terminator. // Returns: // True if the message was sent successfully, false if no cube is connected. bool SendMessage(Face face, const char *message); // Sends a binary message to a particular cube. // Args: // face: The face on this cube that the recipient is connected to. // message: The message to send. // length: The length of the message in bytes. // Returns: // True if the message was sent successfully, false if no cube is connected. bool SendBinaryMessage(Face face, const void *message, uint32_t length); // Waits indefinitely for an event. An event is either the connection // configuration being changed, or a message being received. Will not return // until an event occurs and the appropriate handler is run. void WaitForEvent(); // Checks if an event has occurred. If so, it runs the appropriate handler. It // will return immediately, regardless of whether an event occurs or not. void PollForEvent(); protected: // This method is called when the cube's connection configuration changes. virtual void OnConfigChanged() = 0; // This method is called when a new message is received. // Args: // face: The face that the sending cube is connected to. // message: The message that was received. virtual void OnMessageReceived(Face face, const char *message) = 0; // This method is called when a new binary message is received. // Args: // face: The face that the sending cube is connected to. // message: The message that was received. // length: The length of the message, in bytes. virtual void OnBinaryMessageReceived(Face face, const void *message, uint32_t length) = 0; private: // Indicates which cubes are connected to which faces at this time. Connections connections_; }; } // namespace core } // namespace libmc #endif // LIBMC_CORE_NEIGHBORHOOD_H_
35.559524
80
0.715768
[ "object" ]
4dd148065c59632bf520a07306db54baccb866c0
598
h
C
Assignment2/include/object.h
Young2647/Computer-Graphics
d52aafe16d1128dafaf349ac726c40bb6dab8758
[ "Apache-2.0" ]
null
null
null
Assignment2/include/object.h
Young2647/Computer-Graphics
d52aafe16d1128dafaf349ac726c40bb6dab8758
[ "Apache-2.0" ]
null
null
null
Assignment2/include/object.h
Young2647/Computer-Graphics
d52aafe16d1128dafaf349ac726c40bb6dab8758
[ "Apache-2.0" ]
null
null
null
#ifndef _object_H_ #define _object_H_ #include "defines.h" #include <shader.h> #include <vector> struct Vertex { vec3 position; vec3 normal; vec3 tangent; }; struct DrawMode { GLenum primitive_mode; }; class Object { private: unsigned int VAO; unsigned int VBO; unsigned int EBO; public: std::vector<Vertex> vertices; std::vector<GLuint> indices; DrawMode draw_mode; Object(); ~Object(); void init(); void drawArrays() const; void drawArrays(const Shader& shader) const; void drawElements() const; void drawElements(const Shader& shader) const; }; #endif
15.333333
48
0.702341
[ "object", "vector" ]
0632a05d00d335cba7139f99d54983f87238b32b
15,982
c
C
source/editor.c
hugosrc/cmd-text-editor
8e5da6375fcdf8d51bafacd21e7b4fa20673ef81
[ "MIT" ]
1
2021-08-12T22:32:05.000Z
2021-08-12T22:32:05.000Z
source/editor.c
hugosrc/cmd-text-editor
8e5da6375fcdf8d51bafacd21e7b4fa20673ef81
[ "MIT" ]
null
null
null
source/editor.c
hugosrc/cmd-text-editor
8e5da6375fcdf8d51bafacd21e7b4fa20673ef81
[ "MIT" ]
1
2021-07-21T20:06:26.000Z
2021-07-21T20:06:26.000Z
#include "editor.h" #include "syntax.h" struct editorConfig Editor; void initEditor() { Editor.cx = 0; Editor.cy = 0; Editor.rx = 0; Editor.rowoff = 0; Editor.coloff = 0; Editor.numrows = 0; Editor.row = NULL; Editor.dirty = 0; Editor.filename = NULL; Editor.statusmsg[0] = '\0'; Editor.statusmsg_time = 0; Editor.syntax = NULL; if (getWindowSize(&Editor.screenrows, &Editor.screencols) == -1) die("getWindowSize"); Editor.screenrows -= 2; } void editorOpen(char* filename) { free(Editor.filename); Editor.filename = strdup(filename); editorSelectSyntaxHighlight(); FILE* fp = fopen(filename, "r"); if (!fp) die("fopen"); char* line = NULL; size_t linecap = 0; ssize_t linelen; while ((linelen = getline(&line, &linecap, fp)) != -1) { while (linelen > 0 && (line[linelen - 1] == '\n' || line[linelen - 1] == '\r')) linelen--; editorInsertRow(Editor.numrows, line, linelen); } free(line); fclose(fp); Editor.dirty = 0; } void editorSave() { if (Editor.filename == NULL) { Editor.filename = editorPrompt("Save as: %s (ESC to cancel)", NULL); if (Editor.filename == NULL) { editorSetStatusMessage("Save aborted"); return; } editorSelectSyntaxHighlight(); } int len; char *buf = editorRowsToString(&len); int fd = open(Editor.filename, O_RDWR | O_CREAT, 0644); if (fd != -1) { if (ftruncate(fd, len) != -1) { if (write(fd, buf, len) == len) { close(fd); free(buf); Editor.dirty = 0; editorSetStatusMessage("%d bytes written to disk", len); return; } } close(fd); } free(buf); editorSetStatusMessage("Can't save! I/O error: %s", strerror(errno)); } void editorInsertChar(int c) { if (Editor.cy == Editor.numrows) { editorInsertRow(Editor.numrows, "", 0); } editorRowInsertChar(&Editor.row[Editor.cy], Editor.cx, c); Editor.cx++; } void editorInsertNewLine() { if (Editor.cx == 0) { editorInsertRow(Editor.cy, "", 0); } else { erow *row = &Editor.row[Editor.cy]; editorInsertRow(Editor.cy + 1, &row->chars[Editor.cx], row->size - Editor.cx); row = &Editor.row[Editor.cy]; row->size = Editor.cx; row->chars[row->size] = '\0'; editorUpdateRow(row); } Editor.cy++; Editor.cx = 0; } void editorDelChar() { if (Editor.cy == Editor.numrows) return; if (Editor.cx == 0 && Editor.cy == 0) return; erow* row = &Editor.row[Editor.cy]; if (Editor.cx > 0) { editorRowDelChar(row, Editor.cx - 1); Editor.cx--; } else { Editor.cx = Editor.row[Editor.cy - 1].size; editorRowAppendString(&Editor.row[Editor.cy - 1], row->chars, row->size); editorDelRow(Editor.cy); Editor.cy--; } } void editorFindCallback(char *query, int key) { static int last_match = -1; static int direction = 1; static int saved_hl_line; static char *saved_hl = NULL; if (saved_hl) { memcpy(Editor.row[saved_hl_line].highlight, saved_hl, Editor.row[saved_hl_line].rsize); free(saved_hl); saved_hl = NULL; } if (key == '\r' || key == '\x1b') { last_match = -1; direction = 1; return; } else if (key == ARROW_RIGHT || key == ARROW_DOWN) { direction = 1; } else if (key == ARROW_LEFT || key == ARROW_UP) { direction = -1; } else { last_match = -1; direction = 1; } if (last_match == -1) direction = 1; int current = last_match; for (int i = 0; i < Editor.numrows; i++) { current += direction; if (current == -1) { current = Editor.numrows - 1; } else if (current == Editor.numrows) { current = 0; } erow *row = &Editor.row[current]; char *match = strstr(row->render, query); if (match) { last_match = current; Editor.cy = current; Editor.cx = editorRowRxToCx(row, match - row->render); Editor.rowoff = Editor.numrows; saved_hl_line = current; saved_hl = malloc(row->rsize); memcpy(saved_hl, row->highlight, row->rsize); memset(&row->highlight[match - row->render], HL_MATCH, strlen(query)); break; } } } void editorFind() { int saved_cx = Editor.cx; int saved_cy = Editor.cy; int saved_coloff = Editor.coloff; int saved_rowoff = Editor.rowoff; char *query = editorPrompt("Search: %s (Use ESC/Arrows/Enter)", editorFindCallback); if (query) { free(query); } else { Editor.cx = saved_cx; Editor.cy = saved_cy; Editor.coloff = saved_coloff; Editor.rowoff = saved_rowoff; } } void editorDrawStatusBar(struct abuf* ab) { abAppend(ab, "\x1b[7m", 4); char status[80], rstatus[80]; int len = snprintf(status, sizeof(status), "%.20s - %d lines %s", Editor.filename ? Editor.filename : "[No Name]", Editor.numrows, Editor.dirty ? "(modified)" : ""); int rlen = snprintf( rstatus, sizeof(rstatus), "%s | %d/%d", Editor.syntax ? Editor.syntax->filetype : "no filetype", Editor.cy + 1, Editor.numrows); if (len > Editor.screencols) len = Editor.screencols; abAppend(ab, status, len); while (len < Editor.screencols) { if (Editor.screenrows - len == rlen) { abAppend(ab, rstatus, rlen); break; } else { abAppend(ab, " ", 1); len++; } } abAppend(ab, "\x1b[m", 3); abAppend(ab, "\r\n", 2); } void editorDrawMessageBar(struct abuf* ab) { abAppend(ab, "\x1b[K", 3); int msglen = strlen(Editor.statusmsg); if (msglen > Editor.screencols) msglen = Editor.screencols; if (msglen && time(NULL) - Editor.statusmsg_time < 5) abAppend(ab, Editor.statusmsg, msglen); } void editorSetStatusMessage(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vsnprintf(Editor.statusmsg, sizeof(Editor.statusmsg), fmt, ap); va_end(ap); Editor.statusmsg_time = time(NULL); } void editorRefreshScreen(); char *editorPrompt(char *prompt, void (*callback)(char *, int)) { size_t bufsize = 128; char *buf = malloc(bufsize); size_t buflen = 0; buf[0] = '\0'; while (1) { editorSetStatusMessage(prompt, buf); editorRefreshScreen(); int c = editorReadKey(); if (c == DEL_KEY || c == CTRL_KEY('h') || c == BACKSPACE) { if (buflen != 0) buf[--buflen] = '\0'; } else if (c == '\x1b') { editorSetStatusMessage(""); if (callback) callback(buf, c); free(buf); return NULL; } else if (c == '\r') { if (buflen != 0) { editorSetStatusMessage(""); if (callback) callback(buf, c); return buf; } } else if (!iscntrl(c) && c < 128) { if (buflen == bufsize - 1) { bufsize *= 2; buf = realloc(buf, bufsize); } buf[buflen++] = c; buf[buflen] = '\0'; } if (callback) callback(buf, c); } } void editorMoveCursor(int key) { erow* row = (Editor.cy >= Editor.numrows) ? NULL : &Editor.row[Editor.cy]; switch (key) { case ARROW_LEFT: if (Editor.cx != 0) { Editor.cx--; } else if (Editor.cy > 0) { Editor.cy--; Editor.cx = Editor.row[Editor.cy].size; } break; case ARROW_RIGHT: if (row && Editor.cx < row->size) { Editor.cx++; } else if (row && Editor.cx == row->size) { Editor.cy++; Editor.cx = 0; } break; case ARROW_UP: if (Editor.cy != 0) { Editor.cy--; } break; case ARROW_DOWN: if (Editor.cy < Editor.numrows) { Editor.cy++; } break; } row = (Editor.cy >= Editor.numrows) ? NULL : &Editor.row[Editor.cy]; int rowlen = row ? row->size : 0; if (Editor.cx > rowlen) { Editor.cx = rowlen; } } void editorProcessKeypress() { static int quit_times = EDITOR_QUIT_TIMES; int c = editorReadKey(); switch (c) { case '\r': editorInsertNewLine(); break; case CTRL_KEY('q'): if (Editor.dirty && quit_times > 0) { editorSetStatusMessage( "WARNING!!! File has unsaved changes. " "Press Ctrl-Q %d more times to quit.", quit_times); quit_times--; return; } write(STDOUT_FILENO, "\x1b[2J", 4); write(STDOUT_FILENO, "\x1b[H", 3); exit(0); break; case CTRL_KEY('s'): editorSave(); break; case HOME_KEY: Editor.cx = 0; break; case END_KEY: if (Editor.cy < Editor.numrows) { Editor.cx = Editor.row[Editor.cy].size; } break; case CTRL_KEY('f'): editorFind(); break; case BACKSPACE: case CTRL_KEY('h'): case DEL_KEY: if (c == DEL_KEY) editorMoveCursor(ARROW_RIGHT); editorDelChar(); break; case PAGE_UP: case PAGE_DOWN: { if (c == PAGE_UP) { Editor.cy = Editor.rowoff; } else if (c == PAGE_DOWN) { Editor.cy = Editor.rowoff + Editor.screenrows - 1; if (Editor.cy > Editor.numrows) { Editor.cy = Editor.numrows; } } int times = Editor.screenrows; while(times--) editorMoveCursor(c == PAGE_UP ? ARROW_UP : ARROW_DOWN); } break; case ARROW_LEFT: case ARROW_RIGHT: case ARROW_UP: case ARROW_DOWN: editorMoveCursor(c); break; case CTRL_KEY('l'): case '\x1b': break; default: editorInsertChar(c); break; } quit_times = EDITOR_QUIT_TIMES; } void editorScroll() { Editor.rx = 0; if (Editor.cy < Editor.numrows) { Editor.rx = editorRowCxToRx(&Editor.row[Editor.cy], Editor.cx); } if (Editor.cy < Editor.rowoff) { Editor.rowoff = Editor.cy; } if (Editor.cy >= Editor.rowoff + Editor.screenrows) { Editor.rowoff = Editor.cy - Editor.screenrows + 1; } if (Editor.rx < Editor.coloff) { Editor.coloff = Editor.rx; } if (Editor.rx >= Editor.coloff + Editor.screencols) { Editor.coloff = Editor.rx - Editor.screencols + 1; } } void editorDrawRows(struct abuf* ab) { for (int i = 0; i < Editor.screenrows; i++) { int filerow = i + Editor.rowoff; if (filerow >= Editor.numrows) { if (Editor.numrows == 0 && i == Editor.screenrows / 3) { char welcome[80]; int welcomelen = snprintf(welcome, sizeof(welcome), "%s -- version %s", EDITOR_NAME, EDITOR_VERSION); if (welcomelen > Editor.screencols) welcomelen = Editor.screencols; int padding = (Editor.screencols - Editor.screenrows) / 2; if (padding) { abAppend(ab, "~", 1); padding--; } while (padding--) abAppend(ab, " ", 1); abAppend(ab, welcome, welcomelen); } else { abAppend(ab, "~", 1); } } else { int len = Editor.row[filerow].rsize - Editor.coloff; if (len < 0) len = 0; if (len > Editor.screencols) len = Editor.screencols; char *c = &Editor.row[filerow].render[Editor.coloff]; unsigned char *highlight = &Editor.row[filerow].highlight[Editor.coloff]; int current_color = -1; for (int i = 0; i < len; i++) { if (iscntrl(c[i])) { char sym = (c[i] <= 26) ? '@' + c[i] : '?'; abAppend(ab, "\x1b[7m", 4); abAppend(ab, &sym, 1); abAppend(ab, "\x1b[m", 3); if (current_color != -1) { char buf[16]; int clen = snprintf(buf, sizeof(buf), "\x1b[%dm", current_color); abAppend(ab, buf, clen); } } else if (highlight[i] == HL_NORMAL) { if (current_color != -1) { abAppend(ab, "\x1b[39m", 5); current_color = -1; } abAppend(ab, &c[i], 1); } else { int color = editorSyntaxToColor(highlight[i]); if (color != current_color) { current_color = color; char buf[16]; int clen = snprintf(buf, sizeof(buf), "\x1b[%dm", color); abAppend(ab, buf, clen); } abAppend(ab, &c[i], 1); } } abAppend(ab, "\x1b[39m", 5); } abAppend(ab, "\x1b[K", 3); abAppend(ab, "\r\n", 2); } } void editorRefreshScreen() { editorScroll(); struct abuf ab = ABUF_INIT; abAppend(&ab, "\x1b[?25l", 6); abAppend(&ab, "\x1b[H", 3); editorDrawRows(&ab); editorDrawStatusBar(&ab); editorDrawMessageBar(&ab); char buf[32]; snprintf(buf, sizeof(buf), "\x1b[%d;%dH", (Editor.cy - Editor.rowoff) + 1, (Editor.rx + Editor.coloff) + 1); abAppend(&ab, buf, strlen(buf)); abAppend(&ab, "\x1b[?25h", 6); write(STDOUT_FILENO, ab.b, ab.length); abFree(&ab); } int editorRowCxToRx(erow* row, int cx) { int rx = 0; for (int i = 0; i < cx; i++) { if (row->chars[i] == '\t') { rx += (EDITOR_TAB_STOP - 1) - (rx % EDITOR_TAB_STOP); } rx++; } return rx; } int editorRowRxToCx(erow* row, int rx) { int cur_rx = 0; int cx; for (cx = 0; cx < row->size; cx++) { if (row->chars[cx] == '\t') { cur_rx += (EDITOR_TAB_STOP - 1) - (cur_rx % EDITOR_TAB_STOP); } cur_rx++; if (cur_rx > rx) return cx; } return cx; } void editorUpdateRow(erow* row) { int tabs = 0; for (int i = 0; i < row->size; i++) { if (row->chars[i] == '\t') tabs++; } free(row->render); row->render = malloc(row->size + tabs * (EDITOR_TAB_STOP - 1) + 1); int index = 0; for (int i = 0; i < row->size; i++) { if (row->chars[i] == '\t') { row->render[index++] = ' '; while (index % EDITOR_TAB_STOP != 0) row->render[index++] = ' '; } else { row->render[index++] = row->chars[i]; } } row->render[index] = '\0'; row->rsize = index; editorUpdateSyntax(row); } void editorInsertRow(int at, char* s, size_t len) { if (at < 0 || at > Editor.numrows) return; Editor.row = realloc(Editor.row, sizeof(erow) * (Editor.numrows + 1)); memmove(&Editor.row[at + 1], &Editor.row[at], sizeof(erow) * (Editor.numrows - at)); for (int i = at + 1; i <= Editor.numrows; i++) Editor.row[i].index++; Editor.row[at].index = at; Editor.row[at].size = len; Editor.row[at].chars = malloc(len + 1); memcpy(Editor.row[at].chars, s, len); Editor.row[at].chars[len] = '\0'; Editor.row[at].rsize = 0; Editor.row[at].render = NULL; Editor.row[at].highlight = NULL; Editor.row[at].hl_open_comment = 0; editorUpdateRow(&Editor.row[at]); Editor.numrows++; Editor.dirty++; } void editorFreeRow(erow* row) { free(row->render); free(row->chars); free(row->highlight); } void editorDelRow(int at) { if (at < 0 || at >= Editor.numrows) return; editorFreeRow(&Editor.row[at]); memmove(&Editor.row[at], &Editor.row[at + 1], sizeof(erow) * (Editor.numrows - at - 1)); for (int i = at + 1; i <= Editor.numrows - 1; i++) Editor.row[i].index--; Editor.numrows--; Editor.dirty++; } void editorRowInsertChar(erow* row, int at, int c) { if (at < 0 || at > row->size) at = row->size; row->chars = realloc(row->chars, row->size + 2); memmove(&row->chars[at + 1], &row->chars[at], row->size - at + 1); row->size++; row->chars[at] = c; editorUpdateRow(row); Editor.dirty++; } void editorRowAppendString(erow *row, char *s, size_t len) { row->chars = realloc(row->chars, row->size + len + 1); memcpy(&row->chars[row->size], s, len); row->size += len; row->chars[row->size] = '\0'; editorUpdateRow(row); Editor.dirty++; } void editorRowDelChar(erow* row, int at) { if (at < 0 || at >= row->size) return; memmove(&row->chars[at], &row->chars[at + 1], row->size - at); row->size--; editorUpdateRow(row); Editor.dirty++; } char *editorRowsToString(int *buflen) { int totlen = 0; for (int i = 0; i < Editor.numrows; i++) { totlen += Editor.row[i].size + 1; } *buflen = totlen; char* buf = malloc(totlen); char *p = buf; for (int i = 0; i < Editor.numrows; i++) { memcpy(p, Editor.row[i].chars, Editor.row[i].size); p += Editor.row[i].size; *p = '\n'; p++; } return buf; }
23.502941
110
0.566575
[ "render" ]
06335038462b5f712a7e61814329f39177e08f58
45,803
h
C
released_plugins/v3d_plugins/neurontracing_vn2/app1/gd.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
released_plugins/v3d_plugins/neurontracing_vn2/app1/gd.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
released_plugins/v3d_plugins/neurontracing_vn2/app1/gd.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
/* * Copyright (c)2006-2010 Hanchuan Peng (Janelia Farm, Howard Hughes Medical Institute). * All rights reserved. */ /************ ********* LICENSE NOTICE ************ This folder contains all source codes for the V3D project, which is subject to the following conditions if you want to use it. You will ***have to agree*** the following terms, *before* downloading/using/running/editing/changing any portion of codes in this package. 1. This package is free for non-profit research, but needs a special license for any commercial purpose. Please contact Hanchuan Peng for details. 2. You agree to appropriately cite this work in your related studies and publications. Peng, H., Ruan, Z., Long, F., Simpson, J.H., and Myers, E.W. (2010) “V3D enables real-time 3D visualization and quantitative analysis of large-scale biological image data sets,” Nature Biotechnology, Vol. 28, No. 4, pp. 348-353, DOI: 10.1038/nbt.1612. ( http://penglab.janelia.org/papersall/docpdf/2010_NBT_V3D.pdf ) Peng, H, Ruan, Z., Atasoy, D., and Sternson, S. (2010) “Automatic reconstruction of 3D neuron structures using a graph-augmented deformable model,” Bioinformatics, Vol. 26, pp. i38-i46, 2010. ( http://penglab.janelia.org/papersall/docpdf/2010_Bioinfo_GD_ISMB2010.pdf ) 3. This software is provided by the copyright holders (Hanchuan Peng), Howard Hughes Medical Institute, Janelia Farm Research Campus, and contributors "as is" and any express or implied warranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the copyright owner, Howard Hughes Medical Institute, Janelia Farm Research Campus, 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; reasonable royalties; 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. 4. Neither the name of the Howard Hughes Medical Institute, Janelia Farm Research Campus, nor Hanchuan Peng, may be used to endorse or promote products derived from this software without specific prior written permission. *************/ //by Hanchuan Peng //090516 //090518: add ParaShortestPath struct //100327: add find_shortest_path_graphpointset //101212: add some block operation functions //101219: update the deformable curve part //101221: renamed as gd.h //110115: add rearrange_and_remove_labeled_deletion_nodes_mmUnit() //170606: add a favorite direction to trace #ifndef __NEURON_TRACING_H__ #define __NEURON_TRACING_H__ #include <math.h> #include <iostream> #include <vector> #include <algorithm> //added 100417 for Ubuntu, PHC #include "v_neuronswc.h" #include "bdb_minus.h" #if defined(__LP64__) || defined(__LLP64__) typedef double Weight; typedef V3DLONG Node; #else typedef float Weight; typedef int Node; #endif typedef std::pair<Node, Node> Edge; #include <boost/config.hpp> #include <boost/math/special_functions/fpclassify.hpp> using namespace boost; using namespace std; struct ParaShortestPath { int node_step; //should be >=1 && odd. int outsample_step; int smooth_winsize; int edge_select; //0 -- only use length 1 edge(optimal for small step), 1 -- plus diagonal edge int background_select; //0 -- no background, 1 -- compute background threshold double imgTH; double visible_thresh; bool b_use_favorite_direction; //add by PHC 170606 double favorite_direction[3]; int downsample_method; //0 -- use average, 1 -- use max //added by Zhi 20170925 ParaShortestPath() { node_step = 3; //should be >=1 outsample_step = 2; smooth_winsize = 5; edge_select = 0; //0 -- bgl_shortest_path(), 1 -- phc_shortest_path() background_select = 1; imgTH = 0; //do not tracing image background visible_thresh = 30; b_use_favorite_direction = false; favorite_direction[0] = favorite_direction[1] = favorite_direction[2] = 0; downsample_method = 0; } }; class BDB_Minus_Prior_Parameter { public: double f_prior, f_smooth, f_length; //the coefficients for the prior force, smoothness and length forces, respectively. double Kfactor; //the factor in "mean+Kfactor*sigma" of an image that would be used to find the backbone int nloops; BDB_Minus_Prior_Parameter() { f_prior = 0.2; f_smooth = 0.1; f_length = 0.1; Kfactor = 1.0; nloops = 100; } }; //#define VISIBLE_THRESHOLD 30 //change back to 30 from 10, to be consistent with APP1 code v1.70, which generate good result for Rubin_raw1 test data //replace VISIBLE_THRESHOLD using the new "visible_thresh" field. 2013-02-10 struct VPoint { double *v; V3DLONG n; VPoint() { v = 0; n = 0; } VPoint(V3DLONG m) { if (m <= 0) { v = 0; n = 0; return; } n = m; v = new double[n]; } VPoint(V3DLONG m, double inival) { if (m <= 0) { v = 0; n = 0; return; } n = m; v = new double[n]; for (V3DLONG i = 0; i < n; i++) v[i] = inival; } ~VPoint() { if (v) { delete[]v; v = 0; } n = 0; } bool isValid() { return (n <= 0 || !v) ? false : true; } bool isComparable(VPoint &t) { if (!t.isValid() || !isValid()) return false; return (t.n == n) ? true : false; } bool isComparable(VPoint *t) { if (!t->isValid() || !isValid()) return false; return (t->n == n) ? true : false; } double abs() { double s = 0; for (V3DLONG i = 0; i < n; i++) s += v[i] * v[i]; return sqrt(s); } bool simpleProduct(VPoint &t) { if (isComparable(t) == false) return false; for (V3DLONG i = 0; i < n; i++) v[i] *= t.v[i]; return true; } bool simpleProduct(VPoint *t) { if (isComparable(t) == false) return false; for (V3DLONG i = 0; i < n; i++) v[i] *= t->v[i]; return true; } double innerProduct(VPoint &t) { if (!simpleProduct(t)) return 0; else return sqrt(abs()); } double innerProduct(VPoint *t) { if (!simpleProduct(t)) return 0; else return sqrt(abs()); } }; // return error message, NULL is no error char* find_shortest_path_graphimg(unsigned char ****img4d, V3DLONG sz[4], V3DLONG channelsToUse[], V3DLONG nChannel, //image float zthickness, // z-thickness for weighted edge //const V3DLONG box[6], //bounding box V3DLONG bx0, V3DLONG by0, V3DLONG bz0, V3DLONG bx1, V3DLONG by1, V3DLONG bz1, //bounding box (ROI) float x0, float y0, float z0, // start node int n_end_nodes, // n_end_nodes == (0 for shortest path tree) (1 for shortest path) (n-1 for n pair path) float x1[], float y1[], float z1[], // all end nodes vector< vector<V_NeuronSWC_unit> >& mmUnit, // change from Coord3D for shortest path tree const ParaShortestPath & para); char* find_shortest_path_graphimg(unsigned char ***img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2, //image float zthickness, // z-thickness for weighted edge //const V3DLONG box[6], //bounding box V3DLONG bx0, V3DLONG by0, V3DLONG bz0, V3DLONG bx1, V3DLONG by1, V3DLONG bz1, //bounding box (ROI) float x0, float y0, float z0, // start node int n_end_nodes, // n_end_nodes == (0 for shortest path tree) (1 for shortest path) (n-1 for n pair path) float x1[], float y1[], float z1[], // all end nodes vector< vector<V_NeuronSWC_unit> >& mmUnit, // change from Coord3D for shortest path tree const ParaShortestPath & para); char* find_shortest_path_graphpointset(V3DLONG n_all_nodes, double xa[], double ya[], double za[], double va[], //the coordinates and values of all nodes float zthickness, // z-thickness for weighted edge std::vector<Edge> edge_array0, V3DLONG ind_startnode, // start node's index V3DLONG n_end_nodes0, // n_end_nodes == (0 for shortest path tree) (1 for shortest path) (n-1 for n pair path) V3DLONG ind_end_nodes0[], // all end nodes' indexes vector< vector<V_NeuronSWC_unit> >& mmUnit, // change from Coord3D for shortest path tree const ParaShortestPath & para); void rearrange_and_remove_labeled_deletion_nodes_mmUnit(vector< vector<V_NeuronSWC_unit> >& mmUnit); //remove those nchild < 0 and update indexes // assume root node at tail of vector (result of back tracing) char* merge_back_traced_paths(vector< vector<V_NeuronSWC_unit> >& mmUnit); bool fit_radius_and_position(unsigned char ***img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2, vector <V_NeuronSWC_unit> & mUnit, bool b_move_position, float zthickness = 1.0, bool b_est_in_xyplaneonly = false, double vis_threshold = 30.0); bool fit_radius_and_position(unsigned char ****img4d, V3DLONG sz[4], vector <V_NeuronSWC_unit> & mCoord, bool b_move_position, float zthickness, bool b_est_in_xyplaneonly = false, double vis_threshold = 30.0); double getImageMaxValue(unsigned char ***img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2); double getImageAveValue(unsigned char ***img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2); double getImageStdValue(unsigned char ***img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2); double fitRadiusPercent(unsigned char ***img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2, double imgTH, double bound_r, float x, float y, float z, float zthickness, bool b_est_in_xyplaneonly); void fitPosition(unsigned char ***img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2, double imgTH, double ir, float &x, float &y, float &z, float* D = 0, float zthickness = 1.0); //some block operation functions double getBlockMaxValue(unsigned char ***img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2, V3DLONG x0, V3DLONG y0, V3DLONG z0, int xstep, int ystep, int zstep); double getBlockAveValue(unsigned char ***img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2, V3DLONG x0, V3DLONG y0, V3DLONG z0, int xstep, int ystep, int zstep); template <class T> VPoint *getBlockAveValue(T ****img4d, V3DLONG sz[4], V3DLONG channelsToUse[], V3DLONG nChannel, V3DLONG x0, V3DLONG y0, V3DLONG z0, int xstep, int ystep, int zstep); bool setBlockAveValue(unsigned char ***img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2, V3DLONG x0, V3DLONG y0, V3DLONG z0, int xstep, int ystep, int zstep, unsigned char target_val); double getBlockStdValue(unsigned char ***img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2, V3DLONG x0, V3DLONG y0, V3DLONG z0, int xstep, int ystep, int zstep); // template based functions ///////////////////////////////////////////////////////////////////// static bool less_r(V_NeuronSWC_unit a, V_NeuronSWC_unit b) { return (a.r < b.r); } template <class T> //should be a struct included members of (r), like V_NeuronSWC_unit bool smooth_radius(vector <T> & mCoord, int winsize, bool median_filter) { //std::cout<<" smooth_radius "; if (winsize < 2) return true; std::vector<T> mC = mCoord; // a copy V3DLONG N = mCoord.size(); int halfwin = winsize / 2; for (int i = 1; i < N - 1; i++) // don't move start & end point { std::vector<T> winC; std::vector<double> winW; winC.clear(); winW.clear(); winC.push_back(mC[i]); winW.push_back(1. + halfwin); for (int j = 1; j <= halfwin; j++) { int k1 = i + j; if (k1<0) k1 = 0; if (k1>N - 1) k1 = N - 1; int k2 = i - j; if (k2<0) k2 = 0; if (k2>N - 1) k2 = N - 1; winC.push_back(mC[k1]); winC.push_back(mC[k2]); winW.push_back(1. + halfwin - j); winW.push_back(1. + halfwin - j); } //std::cout<<"winC.size = "<<winC.size()<<"\n"; double r = 0; if (median_filter) { sort(winC.begin(), winC.end(), less_r); r = winC[halfwin].r; } else { double s = r = 0; for (int i = 0; i < winC.size(); i++) { r += winW[i] * winC[i].r; s += winW[i]; } if (s) r /= s; } mCoord[i].r = r; // output } return true; } template <class T> //should be a struct included members of (x,y,z), like Coord3D bool smooth_curve(std::vector<T> & mCoord, int winsize) { //std::cout<<" smooth_curve "; if (winsize < 2) return true; std::vector<T> mC = mCoord; // a copy V3DLONG N = mCoord.size(); int halfwin = winsize / 2; for (int i = 1; i < N - 1; i++) // don't move start & end point { std::vector<T> winC; std::vector<double> winW; winC.clear(); winW.clear(); winC.push_back(mC[i]); winW.push_back(1. + halfwin); for (int j = 1; j <= halfwin; j++) { int k1 = i + j; if (k1<0) k1 = 0; if (k1>N - 1) k1 = N - 1; int k2 = i - j; if (k2<0) k2 = 0; if (k2>N - 1) k2 = N - 1; winC.push_back(mC[k1]); winC.push_back(mC[k2]); winW.push_back(1. + halfwin - j); winW.push_back(1. + halfwin - j); } //std::cout<<"winC.size = "<<winC.size()<<"\n"; double s, x, y, z; s = x = y = z = 0; for (int i = 0; i < winC.size(); i++) { x += winW[i] * winC[i].x; y += winW[i] * winC[i].y; z += winW[i] * winC[i].z; s += winW[i]; } if (s) { x /= s; y /= s; z /= s; } mCoord[i].x = x; // output mCoord[i].y = y; // output mCoord[i].z = z; // output } return true; } template <class T> std::vector<T> downsample_curve(const std::vector<T> & mCoord, int step) { //std::cout<<" downsample_curve "; if (step < 1) return mCoord; std::vector<T> mC; // for out put mC.clear(); V3DLONG N = mCoord.size(); if (N > 0) mC.push_back(mCoord[0]); // output for (int i = 1; i < N - 1; i += step) // don't move start & end point { mC.push_back(mCoord[i]); // output } if (N > 1) mC.push_back(mCoord[N - 1]); // output return mC; } ////////////////////////////////////////////////////////////////////////////////// // make the shift vector be orthogonal with curve -- a repulsion force opposite to attraction force #define DIFF(diff, mCoord, i, xyz, HW) \ { \ diff = 0; \ int kk; \ V3DLONG N = mCoord.size(); \ for (int k=1;k<=HW;k++) \ { \ kk = i+k; if (kk<0) kk=0; if (kk>N-1) kk=N-1; \ diff += mCoord[kk].xyz; \ kk = i-k; if (kk<0) kk=0; if (kk>N-1) kk=N-1; \ diff -= mCoord[kk].xyz; \ } \ } template <class T> void curve_bending_vector(vector<T>& mCoord, V3DLONG i, T& Coord_new) { float D[3]; DIFF(D[0], mCoord, i, x, 5); DIFF(D[1], mCoord, i, y, 5); DIFF(D[2], mCoord, i, z, 5); //printf("[%g,%g,%g] ", D[0],D[1],D[2]); float x = mCoord[i].x; float y = mCoord[i].y; float z = mCoord[i].z; float cx = Coord_new.x; float cy = Coord_new.y; float cz = Coord_new.z; { // make normal vector double len = sqrt(D[0] * D[0] + D[1] * D[1] + D[2] * D[2]); if (len) { D[0] /= len; D[1] /= len; D[2] /= len; // displacement cx = cx - x; cy = cy - y; cz = cz - z; //printf("<%g,%g,%g> ", cx,cy,cz); double proj = cx*D[0] + cy*D[1] + cz*D[2]; cx = cx - proj*D[0]; cy = cy - proj*D[1]; cz = cz - proj*D[2]; //printf("<<%g,%g,%g>> ", cx,cy,cz); x += cx; y += cy; z += cz; } } Coord_new.x = x; Coord_new.y = y; Coord_new.z = z; } inline double get_intensity(unsigned char*** img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2, int ix, int iy, int iz) { if ((ix<0) || (ix>dim0 - 1)) return 0; if ((iy<0) || (iy>dim1 - 1)) return 0; if ((iz<0) || (iz>dim2 - 1)) return 0; return double(img3d[iz][iy][ix]); } #define I(ix, iy, iz) get_intensity(img3d, dim0, dim1, dim2, ix, iy, iz) // 090520: create according to point_bdb_minus_3d_localwinmass() // 090619: move from bdb_minus.h to here // And combined with adaptive radius estimation & orthogonal shift // 090621: add bending_code template <class T> //should be a struct included members of (x,y,z), like V_NeuronSWC_unit bool point_bdb_minus_3d_localwinmass_prior(unsigned char*** img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2, vector <T> & mCoord, const BDB_Minus_Prior_Parameter & bdb_para, bool b_fix_end, const vector <T> & mCoord_prior, int bending_code = 1, float zthickness = 1.0, bool b_est_in_xyplaneonly = false) // 0--no bending, 1--bending M_term, 2--bending mCoord { bool b_use_M_term = 1; //for switch bool b_use_P_term = 1; //for switch bool b_use_G_term = 0; //for switch double f_image = 1; double f_length = bdb_para.f_length; double f_smooth = bdb_para.f_smooth; double f_prior = bdb_para.f_prior; //0.2; double f_gradient = 0;/// gradient is not stable int max_loops = bdb_para.nloops; double TH = 1; //pixel/node, the threshold to judge convergence double AR = 0; for (V3DLONG i = 0; i < mCoord.size() - 1; i++) { double x = mCoord[i].x; double y = mCoord[i].y; double z = mCoord[i].z; double x1 = mCoord[i + 1].x; double y1 = mCoord[i + 1].y; double z1 = mCoord[i + 1].z; AR += sqrt((x - x1)*(x - x1) + (y - y1)*(y - y1) + (z - z1)*(z - z1)); } AR /= mCoord.size() - 1; // average distance between nodes double radius = AR * 2; double imgAve = getImageAveValue(img3d, dim0, dim1, dim2); double imgStd = getImageStdValue(img3d, dim0, dim1, dim2); double imgTH = imgAve + imgStd; V3DLONG M = mCoord.size(); // number of control points / centers of k_means if (M <= 2) return true; //in this case no adjusting is needed. by PHC, 090119. also prevent a memory crash V3DLONG M_prior = mCoord_prior.size(); // number of prior control points V3DLONG i, j; T F_1_term, F_2_term, M_term, P_term, G_term; vector <T> mCoord_new = mCoord; // temporary out vector <T> mCoord_old = mCoord; // a constant copy double lastscore; int wp_start = 0; int wp_end = 0; int wp_radius = 10; if (mCoord[0].timestamp == 99999){ wp_start = wp_radius; cout << "yes" << endl; } else{ cout << "no" << endl; } if (mCoord[M - 1].timestamp == 99999){ wp_end = wp_radius; cout << "yes" << endl; } else{ cout << "no" << endl; } double org_x, org_y, org_z; org_x = mCoord[M - 1].x; org_y = mCoord[M - 1].y; org_z = mCoord[M - 1].z; for (V3DLONG nloop = 0; nloop < max_loops; nloop++) { // for each control point double average_radius = 0; for (j = 0 + wp_start; j < M - wp_end; j++) { //mCoord_new[j].timestamp = 66666; //================================================================== // external force term initialization M_term = mCoord.at(j); P_term = mCoord.at(j); G_term = mCoord.at(j); // 090623 RZC //------------------------------------------------------------------ //image force: M_term if (img3d && (b_use_M_term)) { double xc = mCoord.at(j).x; double yc = mCoord.at(j).y; double zc = mCoord.at(j).z; //090621 RZC: dynamic radius estimation radius = 2*fitRadiusPercent(img3d, dim0, dim1, dim2, imgTH, AR * 2, xc, yc, zc, zthickness, b_est_in_xyplaneonly); //radius = radius / 2; if (radius > 10){ radius = 10; } if (radius < 2){ radius = 2; } //mCoord_new[j].r = radius; //cout << radius << endl; average_radius += radius / M; // cout << radius << endl; V3DLONG x0 = xc - radius; x0 = (x0 < 0) ? 0 : x0; V3DLONG x1 = xc + radius; x1 = (x1 > dim0 - 1) ? (dim0 - 1) : x1; V3DLONG y0 = yc - radius; y0 = (y0 < 0) ? 0 : y0; V3DLONG y1 = yc + radius; y1 = (y1 > dim1 - 1) ? (dim1 - 1) : y1; V3DLONG z0 = zc - radius / zthickness; z0 = (z0 < 0) ? 0 : z0; V3DLONG z1 = zc + radius / zthickness; z1 = (z1 > dim2 - 1) ? (dim2 - 1) : z1; double sum_x = 0, sum_y = 0, sum_z = 0, sum_px = 0, sum_py = 0, sum_pz = 0; V3DLONG ix, iy, iz; //use a sphere region, as this is easiest to compute the unbiased center of mass double dx, dy, dz, r2 = double(radius)*(radius); for (iz = z0; iz <= z1; iz++) { dz = fabs(iz - zc) * zthickness; dz *= dz; for (iy = y0; iy <= y1; iy++) { dy = fabs(iy - yc); dy *= dy; if (dy + dz > r2) continue; dy += dz; for (ix = x0; ix < x1; ix++) { dx = fabs(ix - xc); dx *= dx; if (dx + dy > r2) continue; //register unsigned char tmpval = img3d[iz][iy][ix]; double tmpval = img3d[iz][iy][ix]; tmpval = pow(tmpval / 10.0,2); //if (tmpval>240) { // // //cout << (tmpval*tmpval) << " " << (tmpval ^ 2) << endl; // cout << tmpval << endl; //} //tmpval = tmpval ^ 2; if (tmpval) { sum_x += tmpval; sum_y += tmpval; sum_z += tmpval; sum_px += double(tmpval) * ix; sum_py += double(tmpval) * iy; sum_pz += double(tmpval) * iz; } } } } if (sum_x && sum_y && sum_z) { M_term.x = sum_px / sum_x; M_term.y = sum_py / sum_y; M_term.z = sum_pz / sum_z; } else { M_term.x = xc; M_term.y = yc; M_term.z = zc; } ///////////////////////////////////////////// //std::cout << "wp_debug: " << __LINE__ << " " << bending_code << endl; //090621 RZC if (bending_code == 1) curve_bending_vector(mCoord, j, M_term); ///////////////////////////////////////////// } //---------------------------------------------------------------- // image prior G_term (grident) if (img3d && b_use_G_term) { double xc = mCoord.at(j).x; double yc = mCoord.at(j).y; double zc = mCoord.at(j).z; V3DLONG ix = xc + .5; V3DLONG iy = yc + .5; V3DLONG iz = zc + .5; double gx = 0; for (V3DLONG j = -1; j <= 1; j++) for (int k = -1; k <= 1; k++) { gx += I(ix + 1, iy + j, iz + k); gx -= I(ix - 1, iy + j, iz + k); } double gy = 0; for (V3DLONG j = -1; j <= 1; j++) for (int k = -1; k <= 1; k++) { gy += I(ix + j, iy + 1, iz + k); gy -= I(ix + j, iy - 1, iz + k); } double gz = 0; for (V3DLONG j = -1; j <= 1; j++) for (int k = -1; k <= 1; k++) { gz += I(ix + k, iy + j, iz + 1); gz -= I(ix + k, iy + j, iz - 1); } double Im = I(ix, iy, iz); // factor to connect grayscle with pixel step for G_term double gradient_step = (imgStd) ? 1 / (imgStd*imgStd) : 0; Im = gradient_step*(255 - Im); G_term.x += gx*Im; G_term.y += gy*Im; G_term.z += gz*Im; } //------------------------------------------------------------------ // geometric prior P_term if (mCoord_prior.size() > 0 && (b_use_P_term)) { P_term = mCoord_prior.at(0); double dx, dy, dz; dx = mCoord.at(j).x - mCoord_prior.at(0).x; dy = mCoord.at(j).y - mCoord_prior.at(0).y; dz = mCoord.at(j).z - mCoord_prior.at(0).z; double d0 = sqrt(dx*dx + dy*dy + dz*dz); for (V3DLONG ip = 1; ip < mCoord_prior.size(); ip++) { dx = mCoord.at(j).x - mCoord_prior.at(ip).x; dy = mCoord.at(j).y - mCoord_prior.at(ip).y; dz = mCoord.at(j).z - mCoord_prior.at(ip).z; double d1 = sqrt(dx*dx + dy*dy + dz*dz); if (d1 < d0) { P_term = mCoord_prior.at(ip); d0 = d1; } } } //printf("M_term : [%5.3f, %5.3f, %5.3f], %d\n", M_term.x, M_term.y, M_term.z, j); //printf("P_term : [%5.3f, %5.3f, %5.3f], %d\n", P_term.x, P_term.y, P_term.z, j); //printf("G_term : [%5.3f, %5.3f, %5.3f], %d\n", G_term.x, G_term.y, G_term.z, j); //======================================================================================================================== // b{Ckm1 + Ckp1} + c{Ckm1 + Ckp1 - 0.25 Ckm2 - 0.25 Ckp2} + a{Mk} + d{Pk} + e{Ck + (1 - I[Ck] / Imax) I'[Ck]} // Ck_new = --------------------------------------------------------------------------------------------------------------------- // (2 b + 1.5 c + a + d + e) //======================================================================================================================== //internal force: F_1_term F_2_term for smoothing // new_coord = { f_length*F_1_term + f_smooth*F_2_term + f_image*M_term + // f_prior*P_term + f_gradient*(G_term) } /(2*f_length + 1.5*f_smooth + f_image + f_prior + f_gradient) // boundary nodes have simple format double f; if (j == 0 || j == M - 1) { f = (f_image + f_prior + f_gradient); if (f == 0) f = 1; mCoord_new.at(j).x = (f_image*M_term.x + f_prior*P_term.x + f_gradient*G_term.x) / f; mCoord_new.at(j).y = (f_image*M_term.y + f_prior*P_term.y + f_gradient*G_term.y) / f; mCoord_new.at(j).z = (f_image*M_term.z + f_prior*P_term.z + f_gradient*G_term.z) / f; } else if (j == 1 || j == M - 2) { F_1_term.x = mCoord.at(j - 1).x + mCoord.at(j + 1).x; F_1_term.y = mCoord.at(j - 1).y + mCoord.at(j + 1).y; F_1_term.z = mCoord.at(j - 1).z + mCoord.at(j + 1).z; f = (2 * f_length + f_image + f_prior + f_gradient); if (f == 0) f = 1; mCoord_new.at(j).x = (f_length*F_1_term.x + f_image*M_term.x + f_prior*P_term.x + f_gradient*G_term.x) / f; mCoord_new.at(j).y = (f_length*F_1_term.y + f_image*M_term.y + f_prior*P_term.y + f_gradient*G_term.y) / f; mCoord_new.at(j).z = (f_length*F_1_term.z + f_image*M_term.z + f_prior*P_term.z + f_gradient*G_term.z) / f; } else // not boundary nodes { F_1_term.x = mCoord.at(j - 1).x + mCoord.at(j + 1).x; F_1_term.y = mCoord.at(j - 1).y + mCoord.at(j + 1).y; F_1_term.z = mCoord.at(j - 1).z + mCoord.at(j + 1).z; F_2_term.x = (mCoord.at(j - 1).x + mCoord.at(j + 1).x) - 0.25* (mCoord.at(j + 2).x + mCoord.at(j - 2).x); F_2_term.y = (mCoord.at(j - 1).y + mCoord.at(j + 1).y) - 0.25* (mCoord.at(j + 2).y + mCoord.at(j - 2).y); F_2_term.z = (mCoord.at(j - 1).z + mCoord.at(j + 1).z) - 0.25* (mCoord.at(j + 2).z + mCoord.at(j - 2).z); f = (2 * f_length + 1.5*f_smooth + f_image + f_prior + f_gradient); if (f == 0) f = 1; mCoord_new.at(j).x = (f_length*F_1_term.x + f_smooth*F_2_term.x + f_image*M_term.x + f_prior*P_term.x + f_gradient*G_term.x) / f; mCoord_new.at(j).y = (f_length*F_1_term.y + f_smooth*F_2_term.y + f_image*M_term.y + f_prior*P_term.y + f_gradient*G_term.y) / f; mCoord_new.at(j).z = (f_length*F_1_term.z + f_smooth*F_2_term.z + f_image*M_term.z + f_prior*P_term.z + f_gradient*G_term.z) / f; } //cout<<"image w: "<<f_image*M_term.x<<endl; //cout<<"smooth w: "<<f_smooth*F_2_term.x<<endl; //printf("[%5.3f, %5.3f, %5.3f], %d\n", mCoord_new.at(j).x, mCoord_new.at(j).y, mCoord_new.at(j).z, j); } //cout<<"Radius: "<<average_radius<<endl; /////////////////////////////////////////////////////// //090621 RZC if (bending_code == 2) for (j = 0; j < M; j++) curve_bending_vector(mCoord, j, mCoord_new[j]); ///////////////////////////////////////////////////// // compute curve score double score = 0.0; for (j = 0; j < M; j++) score += fabs(mCoord_new.at(j).x - mCoord.at(j).x) + fabs(mCoord_new.at(j).y - mCoord.at(j).y) + fabs(mCoord_new.at(j).z - mCoord.at(j).z); printf("score[%d]=%g ", nloop, score); // update the coordinates of the control points mCoord = mCoord_new; ///////////////////////////////////////////////////// if (b_fix_end) { //without changing the start and end points mCoord[0].x = mCoord_old[0].x; mCoord[M - 1].x = mCoord_old[M - 1].x; mCoord[0].y = mCoord_old[0].y; mCoord[M - 1].y = mCoord_old[M - 1].y; mCoord[0].z = mCoord_old[0].z; mCoord[M - 1].z = mCoord_old[M - 1].z; } ////////////////////////////////////////////////////// // Can the iteration be terminated ? if (score < TH || boost::math::isnan(score)) break; if (nloop > 0) { if (fabs(lastscore - score) < TH*0.5 / M) // to prevent jumping around break; } lastscore = score; } //mCoord[M - 1].timestamp == 77777; for (j = 0; j < M; j++) mCoord.at(j).z += 1; /*mCoord[M - 1].r = 1; mCoord[0].r = 1;*/ if (mCoord[M - 1].timestamp == 88888 && (org_x != mCoord[M - 1].x || org_y != mCoord[M - 1].y || org_z != mCoord[M - 1].z)){ mCoord[M - 1].timestamp = -mCoord[M - 1].timestamp; } return true; } //a special function to run the bdb- method but using the graph to find the neighbors (instead of assume a linear order) template <class T> //should be a struct included members of (x,y,z), like V_NeuronSWC_unit bool point_bdb_minus_3d_localwinmass_prior_withGraphOrder(unsigned char*** img3d, V3DLONG dim0, V3DLONG dim1, V3DLONG dim2, vector <T> & mCoord, const BDB_Minus_Prior_Parameter & bdb_para, bool b_fix_end, const vector <T> & mCoord_prior, int bending_code = 1, float zthickness = 1.0, bool b_est_in_xyplaneonly = false) // 0--no bending, 1--bending M_term, 2--bending mCoord { V3DLONG tnodes = mCoord.size(); V3DLONG i, j; //first propduce a LUT for easier access std::map<double, V3DLONG> index_map; index_map.clear(); V3DLONG root_id = -1; for (j = 0; j < tnodes; j++) { double ndx = mCoord[j].n; V3DLONG new_ndx = index_map.size(); //map the neuron node's id to row number index_map[ndx] = new_ndx; if (mCoord[j].parent < 0) { if (root_id != -1) printf("==================== detect a non-unique root!\n"); root_id = V3DLONG(mCoord[j].n); printf("==================== nchild of root [%ld, id=%ld] = %ld\n", j, V3DLONG(mCoord[j].n), V3DLONG(mCoord[j].nchild)); } } //also create a children list vector < vector < V3DLONG > > childrenList; childrenList.clear(); for (j = 0; j < tnodes; j++) { vector<V3DLONG> tmp; tmp.clear(); childrenList.push_back(tmp); } for (j = 0; j < tnodes; j++) { if (mCoord[j].parent >= 0) { childrenList[index_map[mCoord[j].parent]].push_back(mCoord[j].n); } } //now turn this children list as a neighbor list vector < vector < V3DLONG > > neighborList = childrenList; for (j = 0; j < tnodes; j++) { if (mCoord[j].parent >= 0) { neighborList[index_map[mCoord[j].n]].push_back(mCoord[j].parent); } } // bool b_use_M_term = 1; //for switch bool b_use_P_term = 1; //for switch bool b_use_G_term = 0; //for switch double f_image = 1; double f_length = bdb_para.f_length; double f_smooth = bdb_para.f_smooth; double f_prior = bdb_para.f_prior; //0.2; double f_gradient = 0;/// gradient is not stable int max_loops = bdb_para.nloops; double TH = 1; //pixel/node, the threshold to judge convergence double AR = 0; for (V3DLONG i = 0; i < mCoord.size() - 1; i++) { double x = mCoord[i].x; double y = mCoord[i].y; double z = mCoord[i].z; V3DLONG pi = mCoord[i].parent; if (pi < 0 || pi == mCoord[i].n) //isolated nodes should not be counted { continue; } V3DLONG pi_rownum = index_map[mCoord[i].parent]; double x1 = mCoord[pi_rownum].x; double y1 = mCoord[pi_rownum].y; double z1 = mCoord[pi_rownum].z; AR += sqrt((x - x1)*(x - x1) + (y - y1)*(y - y1) + (z - z1)*(z - z1)); } AR /= mCoord.size() - 1; // average distance between nodes double radius = AR * 2; double imgAve = getImageAveValue(img3d, dim0, dim1, dim2); double imgStd = getImageStdValue(img3d, dim0, dim1, dim2); double imgTH = imgAve + imgStd; V3DLONG M = mCoord.size(); // number of control points / centers of k_means if (M <= 2) return true; //in this case no adjusting is needed. by PHC, 090119. also prevent a memory crash V3DLONG M_prior = mCoord_prior.size(); // number of prior control points T F_1_term, F_2_term, M_term, P_term, G_term; vector <T> mCoord_new = mCoord; // temporary out vector <T> mCoord_old = mCoord; // a constant copy double lastscore; for (V3DLONG nloop = 0; nloop < max_loops; nloop++) { // for each control point for (j = 0; j < M; j++) { //================================================================== // external force term initialization M_term = mCoord.at(j); P_term = mCoord.at(j); G_term = mCoord.at(j); //------------------------------------------------------------------ //image force: M_term if (img3d && (b_use_M_term)) { double xc = mCoord.at(j).x; double yc = mCoord.at(j).y; double zc = mCoord.at(j).z; //dynamic radius estimation radius = 2 * fitRadiusPercent(img3d, dim0, dim1, dim2, imgTH, AR * 2, xc, yc, zc, zthickness, b_est_in_xyplaneonly); V3DLONG x0 = xc - radius; x0 = (x0 < 0) ? 0 : x0; V3DLONG x1 = xc + radius; x1 = (x1 > dim0 - 1) ? (dim0 - 1) : x1; V3DLONG y0 = yc - radius; y0 = (y0 < 0) ? 0 : y0; V3DLONG y1 = yc + radius; y1 = (y1 > dim1 - 1) ? (dim1 - 1) : y1; V3DLONG z0 = zc - radius; z0 = (z0 < 0) ? 0 : z0; V3DLONG z1 = zc + radius; z1 = (z1 > dim2 - 1) ? (dim2 - 1) : z1; double sum_x = 0, sum_y = 0, sum_z = 0, sum_px = 0, sum_py = 0, sum_pz = 0; V3DLONG ix, iy, iz; //use a sphere region, as this is easiest to compute the unbiased center of mass double dx, dy, dz, r2 = double(radius)*(radius); for (iz = z0; iz <= z1; iz++) { dz = fabs(iz - zc); dz *= dz; for (iy = y0; iy <= y1; iy++) { dy = fabs(iy - yc); dy *= dy; if (dy + dz > r2) continue; dy += dz; for (ix = x0; ix < x1; ix++) { dx = fabs(ix - xc); dx *= dx; if (dx + dy > r2) continue; register unsigned char tmpval = img3d[iz][iy][ix]; if (tmpval) { sum_x += tmpval; sum_y += tmpval; sum_z += tmpval; sum_px += double(tmpval) * ix; sum_py += double(tmpval) * iy; sum_pz += double(tmpval) * iz; } } } } if (sum_x && sum_y && sum_z) { M_term.x = sum_px / sum_x; M_term.y = sum_py / sum_y; M_term.z = sum_pz / sum_z; } else { M_term.x = xc; M_term.y = yc; M_term.z = zc; } } //---------------------------------------------------------------- // image prior G_term (gradient) if (img3d && b_use_G_term) { double xc = mCoord.at(j).x; double yc = mCoord.at(j).y; double zc = mCoord.at(j).z; V3DLONG ix = xc + .5; V3DLONG iy = yc + .5; V3DLONG iz = zc + .5; double gx = 0; for (V3DLONG j = -1; j <= 1; j++) for (int k = -1; k <= 1; k++) { gx += I(ix + 1, iy + j, iz + k); gx -= I(ix - 1, iy + j, iz + k); } double gy = 0; for (V3DLONG j = -1; j <= 1; j++) for (int k = -1; k <= 1; k++) { gy += I(ix + j, iy + 1, iz + k); gy -= I(ix + j, iy - 1, iz + k); } double gz = 0; for (V3DLONG j = -1; j <= 1; j++) for (int k = -1; k <= 1; k++) { gz += I(ix + k, iy + j, iz + 1); gz -= I(ix + k, iy + j, iz - 1); } double Im = I(ix, iy, iz); // factor to connect grayscle with pixel step for G_term double gradient_step = (imgStd) ? 1 / (imgStd*imgStd) : 0; Im = gradient_step*(255 - Im); G_term.x += gx*Im; G_term.y += gy*Im; G_term.z += gz*Im; } //------------------------------------------------------------------ // geometric prior P_term if (mCoord_prior.size() > 0 && (b_use_P_term)) { P_term = mCoord_prior.at(0); double dx, dy, dz; dx = mCoord.at(j).x - mCoord_prior.at(0).x; dy = mCoord.at(j).y - mCoord_prior.at(0).y; dz = mCoord.at(j).z - mCoord_prior.at(0).z; double d0 = sqrt(dx*dx + dy*dy + dz*dz); for (V3DLONG ip = 1; ip < mCoord_prior.size(); ip++) { dx = mCoord.at(j).x - mCoord_prior.at(ip).x; dy = mCoord.at(j).y - mCoord_prior.at(ip).y; dz = mCoord.at(j).z - mCoord_prior.at(ip).z; double d1 = sqrt(dx*dx + dy*dy + dz*dz); if (d1 < d0) { P_term = mCoord_prior.at(ip); d0 = d1; } } } //printf("M_term : [%5.3f, %5.3f, %5.3f], %d\n", M_term.x, M_term.y, M_term.z, j); //printf("P_term : [%5.3f, %5.3f, %5.3f], %d\n", P_term.x, P_term.y, P_term.z, j); //printf("G_term : [%5.3f, %5.3f, %5.3f], %d\n", G_term.x, G_term.y, G_term.z, j); // boundary nodes have simple format double f; if (neighborList[index_map[mCoord[j].n]].size() < 1) //do not adjust isolated node (and this should never happen anyway?) continue; else if (neighborList[index_map[mCoord[j].n]].size() == 1) { f = (f_image + f_prior + f_gradient); if (f == 0) f = 1; mCoord_new.at(j).x = (f_image*M_term.x + f_prior*P_term.x + f_gradient*G_term.x) / f; mCoord_new.at(j).y = (f_image*M_term.y + f_prior*P_term.y + f_gradient*G_term.y) / f; mCoord_new.at(j).z = (f_image*M_term.z + f_prior*P_term.z + f_gradient*G_term.z) / f; } else { V3DLONG cur_row = index_map[mCoord[j].n]; F_1_term.x = 0; F_1_term.y = 0; F_1_term.z = 0; for (V3DLONG n = 0; n < neighborList[cur_row].size(); n++) { V3DLONG cur_neighbor = index_map[neighborList[cur_row][n]]; F_1_term.x += mCoord.at(cur_neighbor).x; F_1_term.y += mCoord.at(cur_neighbor).y; F_1_term.z += mCoord.at(cur_neighbor).z; } f = (neighborList[cur_row].size()*f_length + f_image + f_prior + f_gradient); if (f == 0) f = 1; mCoord_new.at(j).x = (f_length*F_1_term.x + f_image*M_term.x + f_prior*P_term.x + f_gradient*G_term.x) / f; mCoord_new.at(j).y = (f_length*F_1_term.y + f_image*M_term.y + f_prior*P_term.y + f_gradient*G_term.y) / f; mCoord_new.at(j).z = (f_length*F_1_term.z + f_image*M_term.z + f_prior*P_term.z + f_gradient*G_term.z) / f; } //printf("[%5.3f, %5.3f, %5.3f], %d\n", mCoord_new.at(j).x, mCoord_new.at(j).y, mCoord_new.at(j).z, j); } ///////////////////////////////////////////////////// // compute curve score double score = 0.0; for (j = 0; j < M; j++) score += fabs(mCoord_new.at(j).x - mCoord.at(j).x) + fabs(mCoord_new.at(j).y - mCoord.at(j).y) + fabs(mCoord_new.at(j).z - mCoord.at(j).z); printf("score[%d]=%g ", nloop, score); // update the coordinates of the control points mCoord = mCoord_new; ///////////////////////////////////////////////////// if (b_fix_end) { //without changing the start and end points for (j = 0; j < M; j++) if (neighborList[index_map[mCoord[j].n]].size() <= 1) //then terminal node { mCoord[j].x = mCoord_old[j].x; mCoord[j].y = mCoord_old[j].y; mCoord[j].z = mCoord_old[j].z; } } ////////////////////////////////////////////////////// // Can the iteration be terminated ? if (score < TH || boost::math::isnan(score)) break; if (nloop > 0) { if (fabs(lastscore - score) < TH*0.1 / M) // to prevent jumping around break; } lastscore = score; } return true; } template <class T> VPoint *getBlockAveValueVPoint(T ****img4d, V3DLONG sz[4], V3DLONG channelsToUse[], V3DLONG nChannel, V3DLONG x0, V3DLONG y0, V3DLONG z0, int xstep, int ystep, int zstep, int method) { if (!img4d || !sz || sz[0] <= 0 || sz[1] <= 0 || sz[2] <= 0 || sz[3] <= 0 || x0 < 0 || x0 >= sz[0] || y0 < 0 || y0 >= sz[1] || z0 < 0 || z0 >= sz[2] || nChannel <= 0 || !channelsToUse) return 0; V3DLONG i, j, k, c, n; for (c = 0; c < nChannel; c++) { if (channelsToUse[c] < 0 || channelsToUse[c] >= sz[3]) return 0; } double xsteph = fabs(xstep) / 2, ysteph = fabs(ystep) / 2, zsteph = fabs(zstep) / 2; V3DLONG xs = x0 - xsteph, xe = x0 + xsteph, ys = y0 - ysteph, ye = y0 + ysteph, zs = z0 - zsteph, ze = z0 + zsteph; if (xs < 0) xs = 0; if (xe >= sz[0]) xe = sz[0] - 1; if (ys < 0) ys = 0; if (ye >= sz[1]) ye = sz[1] - 1; if (zs < 0) zs = 0; if (ze >= sz[2]) ze = sz[2] - 1; if (method == 0) { VPoint *v = new VPoint(nChannel, 0); n = 0; for (k = zs; k <= ze; k++) for (j = ys; j <= ye; j++) for (i = xs; i <= xe; i++) { for (c = 0; c < nChannel; c++) { v->v[c] += double(img4d[channelsToUse[c]][k][j][i]); n++; } } if (n > 0) for (c = 0; c < nChannel; c++) { //printf("[%5.4f %5.4f]", v->v[c], (double(n))); v->v[c] /= n; if (v->v[c]>255) printf("ha"); } return v; } else { VPoint *v = new VPoint(1, 0); n = 0; for (k = zs; k <= ze; k++) for (j = ys; j <= ye; j++) for (i = xs; i <= xe; i++) { double m = double(img4d[channelsToUse[0]][k][j][i]); for (c = 1; c < nChannel; c++) { if (m < double(img4d[channelsToUse[c]][k][j][i])) m = double(img4d[channelsToUse[c]][k][j][i]); } v->v[0] += m; n++; } if (n > 0) { v->v[0] /= n; if (v->v[0]>255) printf("ha"); } return v; } } template <class T> double getBlockAveValue(T ****img4d, V3DLONG sz[4], V3DLONG channelsToUse[], V3DLONG nChannel, V3DLONG x0, V3DLONG y0, V3DLONG z0, int xstep, int ystep, int zstep, int method) { VPoint * v = getBlockAveValueVPoint(img4d, sz, channelsToUse, nChannel, x0, y0, z0, xstep, ystep, zstep, method); if (!v) return 0; double s = v->abs(); if (v) { delete v; v = 0; } return s; } template <class T> VPoint *getBlockMaxValueVPoint(T ****img4d, V3DLONG sz[4], V3DLONG channelsToUse[], V3DLONG nChannel, V3DLONG x0, V3DLONG y0, V3DLONG z0, int xstep, int ystep, int zstep, int method) { if (!img4d || !sz || sz[0] <= 0 || sz[1] <= 0 || sz[2] <= 0 || sz[3] <= 0 || x0 < 0 || x0 >= sz[0] || y0 < 0 || y0 >= sz[1] || z0 < 0 || z0 >= sz[2] || nChannel <= 0 || !channelsToUse) return 0; V3DLONG i, j, k, c; for (c = 0; c < nChannel; c++) { if (channelsToUse[c] < 0 || channelsToUse[c] >= sz[3]) return 0; } double xsteph = fabs(xstep) / 2, ysteph = fabs(ystep) / 2, zsteph = fabs(zstep) / 2; V3DLONG xs = x0 - xsteph, xe = x0 + xsteph, ys = y0 - ysteph, ye = y0 + ysteph, zs = z0 - zsteph, ze = z0 + zsteph; if (xs < 0) xs = 0; if (xe >= sz[0]) xe = sz[0] - 1; if (ys < 0) ys = 0; if (ye >= sz[1]) ye = sz[1] - 1; if (zs < 0) zs = 0; if (ze >= sz[2]) ze = sz[2] - 1; if (method == 0) { VPoint *v = new VPoint(nChannel, 0); for (k = zs; k <= ze; k++) for (j = ys; j <= ye; j++) for (i = xs; i <= xe; i++) { for (c = 0; c < nChannel; c++) { if (double(img4d[channelsToUse[c]][k][j][i]) >= v->v[c]) v->v[c] = double(img4d[channelsToUse[c]][k][j][i]); } } return v; } else { VPoint *v = new VPoint(1, 0); for (k = zs; k <= ze; k++) for (j = ys; j <= ye; j++) for (i = xs; i <= xe; i++) { double m = double(img4d[channelsToUse[0]][k][j][i]); for (c = 1; c < nChannel; c++) { if (m<double(img4d[channelsToUse[c]][k][j][i])) m = double(img4d[channelsToUse[c]][k][j][i]); } if (m >= v->v[0]) v->v[0] = m; } return v; } } template <class T> double getBlockMaxValue(T ****img4d, V3DLONG sz[4], V3DLONG channelsToUse[], V3DLONG nChannel, V3DLONG x0, V3DLONG y0, V3DLONG z0, int xstep, int ystep, int zstep, int method) { VPoint * v = getBlockMaxValueVPoint(img4d, sz, channelsToUse, nChannel, x0, y0, z0, xstep, ystep, zstep, method); if (!v) return 0; double s = v->abs(); if (v) { delete v; v = 0; } return s; } template <class T> VPoint *getImageAveValueVPoint(T ****img4d, V3DLONG sz[4], V3DLONG channelsToUse[], V3DLONG nChannel, int method) { V3DLONG x0 = sz[0] / 2; V3DLONG y0 = sz[1] / 2; V3DLONG z0 = sz[2] / 2; V3DLONG xstep = sz[0]; V3DLONG ystep = sz[1]; V3DLONG zstep = sz[2]; return getBlockAveValueVPoint(img4d, sz, channelsToUse, nChannel, x0, y0, z0, xstep, ystep, zstep, method); } template <class T> double getImage4DAveValue(T ****img4d, V3DLONG sz[4], V3DLONG channelsToUse[], V3DLONG nChannel, int method) { VPoint * v = getImageAveValueVPoint(img4d, sz, channelsToUse, nChannel, method); if (!v) return 0; double s = v->abs(); if (v) { delete v; v = 0; } return s; } template <class T> VPoint * getBlockStdValueVPoint(T ****img4d, V3DLONG sz[4], V3DLONG channelsToUse[], V3DLONG nChannel, V3DLONG x0, V3DLONG y0, V3DLONG z0, int xstep, int ystep, int zstep) { if (!img4d || !sz || sz[0] <= 0 || sz[1] <= 0 || sz[2] <= 0 || sz[3] <= 0 || x0 < 0 || x0 >= sz[0] || y0 < 0 || y0 >= sz[1] || z0 < 0 || z0 >= sz[2] || nChannel <= 0 || !channelsToUse) { printf("getBlockStdValueVPoint() return 0! Error."); return 0; } V3DLONG i, j, k, c, n; for (c = 0; c < nChannel; c++) { if (channelsToUse[c] < 0 || channelsToUse[c] >= sz[3]) return 0; } int method = 0; VPoint *va = getBlockAveValueVPoint(img4d, sz, channelsToUse, nChannel, x0, y0, z0, xstep, ystep, zstep, method); double xsteph = fabs(xstep) / 2, ysteph = fabs(ystep) / 2, zsteph = fabs(zstep) / 2; V3DLONG xs = x0 - xsteph, xe = x0 + xsteph, ys = y0 - ysteph, ye = y0 + ysteph, zs = z0 - zsteph, ze = z0 + zsteph; if (xs < 0) xs = 0; if (xe >= sz[0]) xe = sz[0] - 1; if (ys < 0) ys = 0; if (ye >= sz[1]) ye = sz[1] - 1; if (zs < 0) zs = 0; if (ze >= sz[2]) ze = sz[2] - 1; VPoint *vs = new VPoint(nChannel, 0); double v = 0; n = 0; for (k = zs; k <= ze; k++) for (j = ys; j <= ye; j++) for (i = xs; i <= xe; i++) { for (c = 0; c < nChannel; c++) { double d = (double(img4d[channelsToUse[c]][k][j][i]) - va->v[c]); vs->v[c] += d*d; } n++; } if (n > 0) { for (c = 0; c < nChannel; c++) { vs->v[c] = sqrt(vs->v[c] / n); printf("[------------------------------------------------------------------------------%5.4f]\n", vs->v[c]); } } if (va) { delete va; va = 0; } return vs; } template <class T> double getBlockStdValue(T ****img4d, V3DLONG sz[4], V3DLONG channelsToUse[], V3DLONG nChannel, V3DLONG x0, V3DLONG y0, V3DLONG z0, int xstep, int ystep, int zstep) { VPoint *v = getBlockStdValueVPoint(img4d, sz, channelsToUse, nChannel, x0, y0, z0, xstep, ystep, zstep); if (!v) return 0; double s = v->abs(); if (v) { delete v; v = 0; } return s; } template <class T> VPoint *getImageStdValueVPoint(T ****img4d, V3DLONG sz[4], V3DLONG channelsToUse[], V3DLONG nChannel) { V3DLONG x0 = sz[0] / 2; V3DLONG y0 = sz[1] / 2; V3DLONG z0 = sz[2] / 2; V3DLONG xstep = sz[0]; V3DLONG ystep = sz[1]; V3DLONG zstep = sz[2]; return getBlockStdValueVPoint(img4d, sz, channelsToUse, nChannel, x0, y0, z0, xstep, ystep, zstep); } template <class T> double getImage4DStdValue(T ****img4d, V3DLONG sz[4], V3DLONG channelsToUse[], V3DLONG nChannel) { VPoint * v = getImageStdValueVPoint(img4d, sz, channelsToUse, nChannel); if (!v) return 0; double s = v->abs(); if (v) { delete v; v = 0; } return s; } #endif
32.880833
952
0.576884
[ "vector", "model", "3d" ]
06349cea7093ac4d7dcc4d51f4bf287676e8669f
11,361
h
C
src/theia/sfm/camera/extended_unified_camera_model.h
Sergej91/TheiaSfM
e603e16888456c3e565a2c197fa9f8643c176175
[ "BSD-3-Clause" ]
null
null
null
src/theia/sfm/camera/extended_unified_camera_model.h
Sergej91/TheiaSfM
e603e16888456c3e565a2c197fa9f8643c176175
[ "BSD-3-Clause" ]
null
null
null
src/theia/sfm/camera/extended_unified_camera_model.h
Sergej91/TheiaSfM
e603e16888456c3e565a2c197fa9f8643c176175
[ "BSD-3-Clause" ]
null
null
null
// Copyright (C) 2016 The Regents of the University of California (Regents). // 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 Regents or University of California 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 HOLDERS 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. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney (cmsweeney@cs.ucsb.edu) // author: Steffen Urban (urbste@googlemail.com), December 2020 #ifndef THEIA_SFM_CAMERA_EXTENDED_UNIFIED_CAMERA_MODEL_H_ #define THEIA_SFM_CAMERA_EXTENDED_UNIFIED_CAMERA_MODEL_H_ #include <Eigen/Core> #include <Eigen/Geometry> #include <cereal/access.hpp> #include <cereal/cereal.hpp> #include <cereal/types/base_class.hpp> #include <cereal/types/polymorphic.hpp> #include <ceres/ceres.h> #include <stdint.h> #include <vector> #include "theia/sfm/camera/camera_intrinsics_model.h" #include "theia/sfm/types.h" namespace theia { // This class implements the extended unified camera model: // https://arxiv.org/pdf/1807.08957.pdf, "The Double Sphere Camera Model", // V.Usenko et al. class ExtendedUnifiedCameraModel : public CameraIntrinsicsModel { public: ExtendedUnifiedCameraModel(); ~ExtendedUnifiedCameraModel() {} static const int kIntrinsicsSize = 7; enum InternalParametersIndex { FOCAL_LENGTH = 0, ASPECT_RATIO = 1, SKEW = 2, PRINCIPAL_POINT_X = 3, PRINCIPAL_POINT_Y = 4, ALPHA = 5, // value range 0, 1 BETA = 6 // value range > 0 }; int NumParameters() const override; // Returns the camera model type of the object. CameraIntrinsicsModelType Type() const override; // Set the intrinsic camera parameters from the priors. void SetFromCameraIntrinsicsPriors(const CameraIntrinsicsPrior &prior) override; // Return a CameraIntrinsicsPrior that can be used to initialize a camera with // the same parameters with the SetFromCameraIntrinsicsPriors method. CameraIntrinsicsPrior CameraIntrinsicsPriorFromIntrinsics() const override; // Returns the indices of the parameters that will be optimized during bundle // adjustment. std::vector<int> GetSubsetFromOptimizeIntrinsicsType( const OptimizeIntrinsicsType &intrinsics_to_optimize) const override; // Returns the calibration matrix in the form specified above. void GetCalibrationMatrix(Eigen::Matrix3d *kmatrix) const override; // Prints the camera intrinsics in a human-readable format. void PrintIntrinsics() const override; // Given a point in the camera coordinate system, apply the camera intrinsics // (e.g., focal length, principal point, distortion) to transform the point // into pixel coordinates. template <typename T> static bool CameraToPixelCoordinates(const T *intrinsic_parameters, const T *point, T *pixel); // Given a pixel in the image coordinates, remove the effects of camera // intrinsics parameters and lens distortion to produce a point in the camera // coordinate system. The point output by this method is effectively a ray in // the direction of the pixel in the camera coordinate system. template <typename T> static bool PixelToCameraCoordinates(const T *intrinsic_parameters, const T *pixel, T *point); // Given an undistorted point, apply lens distortion to the point to get a // distorted point. The type of distortion (i.e. radial, tangential, fisheye, // etc.) will depend on the camera intrinsics model. template <typename T> static bool DistortPoint(const T *intrinsic_parameters, const T *undistorted_point, T *distorted_point); // Given a distorted point, apply lens undistortion to the point to get an // undistorted point. The type of distortion (i.e. radial, tangential, // fisheye, etc.) will depend on the camera intrinsics model. template <typename T> static bool UndistortPoint(const T *intrinsic_parameters, const T *distorted_point, T *undistorted_point); // ----------------------- Getter and Setter methods ---------------------- // void SetAspectRatio(const double aspect_ratio); double AspectRatio() const; void SetSkew(const double skew); double Skew() const; void SetAlphaBetaDistortion(const double alpha, const double beta); double Alpha() const; double Beta() const; private: // Templated method for disk I/O with cereal. This method tells cereal which // data members should be used when reading/writing to/from disk. friend class cereal::access; template <class Archive> void serialize(Archive &ar, const std::uint32_t version) { // NOLINT if (version > 0) { ar(cereal::base_class<CameraIntrinsicsModel>(this)); } else { CHECK_EQ(this->parameters_.size(), NumParameters()); ar(cereal::binary_data(this->parameters_.data(), sizeof(double) * NumParameters())); } } }; template <typename T> bool ExtendedUnifiedCameraModel::CameraToPixelCoordinates( const T *intrinsic_parameters, const T *point, T *pixel) { // Get normalized pixel projection at image plane depth = 1. // Apply radial distortion. T distorted_pixel[2]; bool result = ExtendedUnifiedCameraModel::DistortPoint( intrinsic_parameters, point, distorted_pixel); // Apply calibration parameters to transform normalized units into pixels. const T &focal_length = intrinsic_parameters[ExtendedUnifiedCameraModel::FOCAL_LENGTH]; const T &skew = intrinsic_parameters[ExtendedUnifiedCameraModel::SKEW]; const T &aspect_ratio = intrinsic_parameters[ExtendedUnifiedCameraModel::ASPECT_RATIO]; const T &principal_point_x = intrinsic_parameters[ExtendedUnifiedCameraModel::PRINCIPAL_POINT_X]; const T &principal_point_y = intrinsic_parameters[ExtendedUnifiedCameraModel::PRINCIPAL_POINT_Y]; pixel[0] = focal_length * distorted_pixel[0] + skew * distorted_pixel[1] + principal_point_x; pixel[1] = focal_length * aspect_ratio * distorted_pixel[1] + principal_point_y; return result; } template <typename T> bool ExtendedUnifiedCameraModel::PixelToCameraCoordinates( const T *intrinsic_parameters, const T *pixel, T *point) { const T &focal_length = intrinsic_parameters[ExtendedUnifiedCameraModel::FOCAL_LENGTH]; const T &aspect_ratio = intrinsic_parameters[ExtendedUnifiedCameraModel::ASPECT_RATIO]; const T &focal_length_y = focal_length * aspect_ratio; const T &skew = intrinsic_parameters[ExtendedUnifiedCameraModel::SKEW]; const T &principal_point_x = intrinsic_parameters[ExtendedUnifiedCameraModel::PRINCIPAL_POINT_X]; const T &principal_point_y = intrinsic_parameters[ExtendedUnifiedCameraModel::PRINCIPAL_POINT_Y]; // Normalize the y coordinate first. T distorted_point[2]; distorted_point[1] = (pixel[1] - principal_point_y) / focal_length_y; distorted_point[0] = (pixel[0] - principal_point_x - distorted_point[1] * skew) / focal_length; // Undo the distortion. return ExtendedUnifiedCameraModel::UndistortPoint(intrinsic_parameters, distorted_point, point); } template <typename T> bool ExtendedUnifiedCameraModel::DistortPoint(const T *intrinsic_parameters, const T *undistorted_point, T *distorted_point) { const T &alpha = intrinsic_parameters[ExtendedUnifiedCameraModel::ALPHA]; const T &beta = intrinsic_parameters[ExtendedUnifiedCameraModel::BETA]; const T xx = undistorted_point[0] * undistorted_point[0]; const T yy = undistorted_point[1] * undistorted_point[1]; const T zz = undistorted_point[2] * undistorted_point[2]; const T r2 = xx + yy; const T rho2 = beta * r2 + zz; const T rho = ceres::sqrt(rho2); const T norm = alpha * rho + (T(1) - alpha) * undistorted_point[2]; distorted_point[0] = T(0); distorted_point[1] = T(0); if (norm < T(1e-3)) { return true; } // Check that the point is in the upper hemisphere in case of ellipsoid if (alpha > T(0.5)) { const T zn = undistorted_point[2] / norm; const T C = (alpha - T(1)) / (alpha + alpha - T(1)); if (zn < C) { return true; } } distorted_point[0] = undistorted_point[0] / norm; distorted_point[1] = undistorted_point[1] / norm; return true; } template <typename T> bool ExtendedUnifiedCameraModel::UndistortPoint(const T *intrinsic_parameters, const T *distorted_point, T *undistorted_point) { const T &alpha = intrinsic_parameters[ExtendedUnifiedCameraModel::ALPHA]; const T &beta = intrinsic_parameters[ExtendedUnifiedCameraModel::BETA]; const T r2 = distorted_point[0] * distorted_point[0] + distorted_point[1] * distorted_point[1]; const T gamma = T(1) - alpha; if (alpha > T(0.5)) { if (r2 >= T(1) / ((alpha - gamma) * beta)) { return false; } } const T tmp1 = (T(1) - alpha * alpha * beta * r2); const T tmp_sqrt = ceres::sqrt(T(1) - (alpha - gamma) * beta * r2); const T tmp2 = (alpha * tmp_sqrt + gamma); const T k = tmp1 / tmp2; T norm = ceres::sqrt(r2 + k * k); if (norm < T(1e-12)) { norm = T(1e-12); } undistorted_point[0] = distorted_point[0] / norm; undistorted_point[1] = distorted_point[1] / norm; undistorted_point[2] = k / norm; return true; } } // namespace theia #include <cereal/archives/portable_binary.hpp> CEREAL_CLASS_VERSION(theia::ExtendedUnifiedCameraModel, 1) // Register the polymorphic relationship for serialization. CEREAL_REGISTER_TYPE(theia::ExtendedUnifiedCameraModel) CEREAL_REGISTER_POLYMORPHIC_RELATION(theia::CameraIntrinsicsModel, theia::ExtendedUnifiedCameraModel) #endif // THEIA_SFM_CAMERA_EXTENDED_UNIFIED_CAMERA_MODEL_H_
38.511864
80
0.708212
[ "geometry", "object", "vector", "model", "transform" ]
066d4d94776c239699bd6e3d0e55dc9950f391bd
1,032
h
C
scm_gl_core/src/scm/gl_core/window_management/future_use/output_device_enumerator.h
Nyran/schism
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
[ "BSD-3-Clause" ]
10
2015-09-17T06:01:03.000Z
2019-10-23T07:10:20.000Z
scm_gl_core/src/scm/gl_core/window_management/future_use/output_device_enumerator.h
Nyran/schism
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
[ "BSD-3-Clause" ]
5
2015-01-06T14:11:32.000Z
2016-12-12T10:26:53.000Z
scm_gl_core/src/scm/gl_core/window_management/future_use/output_device_enumerator.h
Nyran/schism
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
[ "BSD-3-Clause" ]
15
2015-01-29T20:56:13.000Z
2020-07-02T19:03:20.000Z
#ifndef OUTPUT_DEVICE_ENUMERATOR_H_INCLUDED #define OUTPUT_DEVICE_ENUMERATOR_H_INCLUDED #include <defines_clr.h> #include <string> #include <vector> #include <ogl/render_context/output_device_descriptor.h> namespace gl { CLR_PUBLIC class output_device_enumerator { public: typedef std::vector<std::string> string_vec_t; output_device_enumerator(); virtual ~output_device_enumerator(); virtual bool enumerate_devices(std::vector<gl::output_device_descriptor>& devices) = 0; virtual bool enumerate_device(gl::output_device_descriptor& desc, unsigned device = 0) = 0; virtual bool enumerate_device(gl::output_device_descriptor& desc, const std::string& name) = 0; const string_vec_t& get_feedback_messages() const { return (_issues); } protected: string_vec_t _issues; private: }; } // namespace gl #endif // OUTPUT_DEVICE_ENUMERATOR_H_INCLUDED
29.485714
122
0.664729
[ "vector" ]
066ea8a44f4ad8356da22ca257a83934e344c01e
10,199
c
C
SingleSource/UnitTests/Vector/AVX512F/m512_op_pd.c
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
70
2019-01-15T03:03:55.000Z
2022-03-28T02:16:13.000Z
SingleSource/UnitTests/Vector/AVX512F/m512_op_pd.c
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
519
2020-09-15T07:40:51.000Z
2022-03-31T20:51:15.000Z
SingleSource/UnitTests/Vector/AVX512F/m512_op_pd.c
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
117
2020-06-24T13:11:04.000Z
2022-03-23T15:44:23.000Z
#include "m512_test_util.h" #include <memory.h> #include <stdio.h> #include <stdlib.h> /* * This test was created to check the correctness * of the following intrinsics support: * _mm512_add_pd() * _mm512_max_pd() * _mm512_min_pd() * _mm512_mask_max_pd() * _mm512_mask_min_pd() * _mm512_mask_mul_pd() * _mm512_mask_abs_pd() * _mm512_add_round_pd() * _mm512_sub_round_pd() */ int show_op = 0; typedef enum { ASSIGN, ABS, ADD, MAX, MIN, MUL, SUB } OPER; static void NOINLINE intop(OPER op, double ivalout[8], double ivalop1[8], double ivalop2[8]) { int i; int handled = 0; memset(ivalout, 0, sizeof(ivalout)); for (i = 0; i < 8; i += 1) { switch (op) { case ASSIGN: handled = 1; ivalout[i] = ivalop1[i]; break; case ABS: handled = 1; ivalout[i] = ivalop1[i] >= 0 ? ivalop1[i] : -ivalop1[i]; break; case ADD: handled = 1; ivalout[i] = ivalop1[i] + ivalop2[i]; break; case MAX: handled = 1; ivalout[i] = (ivalop1[i] > ivalop2[i]) ? ivalop1[i] : ivalop2[i]; break; case MIN: handled = 1; ivalout[i] = (ivalop1[i] < ivalop2[i]) ? ivalop1[i] : ivalop2[i]; break; case MUL: handled = 1; ivalout[i] = ivalop2[i] * ivalop1[i]; break; case SUB: handled = 1; ivalout[i] = ivalop1[i] - ivalop2[i]; break; default: printf("FAIL: bad op\n"); break; } } if (!handled) { printf("FAIL: unsupported op\n"); n_errs++; } } static int NOINLINE check(double val1[], double good[]) { int i; int res = 1; for (i = 0; i < 8; i += 1) { if (val1[i] != good[i]) { res = 0; printf("FAIL: %f != %f\n", val1[i], good[i]); } } return (res); } static int NOINLINE check_mask(double val1[], double good[], int mask) { int i; int res = 1; for (i = 0; i < 8; i += 1) { if ((1 << i) & mask) { if (val1[i] != good[i]) { res = 0; printf("FAIL: %f != %f\n", val1[i], good[i]); } } } return (res); } static void NOINLINE print_vec(char *pfx, double ivec[]) { if (pfx) { printf("%s: ", pfx); } printf("%10.4f %10.4f %10.4f %10.4f ", ivec[7], ivec[6], ivec[5], ivec[4]); printf("%10.4f %10.4f %10.4f %10.4f\n", ivec[3], ivec[2], ivec[1], ivec[0]); } #define DOONE(OP, FUNC) \ { \ int passed = 0; \ intop(OP, good.f64, v1.f64, v2.f64); \ vvv.zmmd = FUNC(v1.zmmd, v2.zmmd); \ passed = check(vvv.f64, good.f64); \ if (!passed) { \ printf("FAIL " #FUNC "\n"); \ n_errs++; \ } \ if (!passed || show_op) { \ print_vec("Opand1", v1.f64); \ print_vec("Opand2", v2.f64); \ print_vec("Scalar", good.f64); \ print_vec("Vector", vvv.f64); \ } \ } #define DOONE_WITH_MASK(OP, FUNC, MMASK) \ { \ int passed = 0; \ intop(OP, good.f64, v1.f64, v2.f64); \ vvv.zmmd = FUNC(vvv.zmmd, MMASK, v1.zmmd, v2.zmmd); \ passed = check_mask(vvv.f64, good.f64, MMASK); \ if (!passed) { \ printf("FAIL " #FUNC "\n"); \ n_errs++; \ } \ if (!passed || show_op) { \ print_vec("Opand1", v1.f64); \ print_vec("Opand2", v2.f64); \ print_vec("Scalar", good.f64); \ print_vec("Vector", vvv.f64); \ } \ } #define DOONE_WITH_MASK_1OP(OP, FUNC, MMASK) \ { \ int passed = 0; \ intop(OP, good.f64, v1.f64, v2.f64); \ vvv.zmmd = FUNC(vvv.zmmd, MMASK, v1.zmmd); \ passed = check_mask(vvv.f64, good.f64, MMASK); \ if (!passed) { \ printf("FAIL " #FUNC "\n"); \ n_errs++; \ } \ if (!passed || show_op) { \ print_vec("Opand1", v1.f64); \ print_vec("Opand2", v2.f64); \ print_vec("Scalar", good.f64); \ print_vec("Vector", vvv.f64); \ } \ } #define DOONE_ROUND(OP, FUNC, ROUND) \ { \ int passed = 0; \ intop(OP, good.f64, v1.f64, v2.f64); \ vvv.zmmd = FUNC(v1.zmmd, v2.zmmd, ROUND); \ passed = check(vvv.f64, good.f64); \ if (!passed) { \ printf("FAIL " #FUNC "\n"); \ n_errs++; \ } \ if (!passed || show_op) { \ print_vec("Opand1", v1.f64); \ print_vec("Opand2", v2.f64); \ print_vec("Scalar", good.f64); \ print_vec("Vector", vvv.f64); \ } \ } #define DOONE_WITH_MASK_ROUND(OP, FUNC, MMASK, ROUND) \ { \ int passed = 0; \ intop(OP, good.f64, v1.f64, v2.f64); \ vvv.zmmd = FUNC(vvv.zmmd, MMASK, v1.zmmd, v2.zmmd, ROUND); \ passed = check_mask(vvv.f64, good.f64, MMASK); \ if (!passed) { \ printf("FAIL " #FUNC "\n"); \ n_errs++; \ } \ if (!passed || show_op) { \ print_vec("Opand1", v1.f64); \ print_vec("Opand2", v2.f64); \ print_vec("Scalar", good.f64); \ print_vec("Vector", vvv.f64); \ } \ } int main() { double init1[] = {1, 2, -3, 4, 5, -6, 7, 8}; double init2[] = {11, 12, 23, 24, 35, 36, 17, 38}; V512 v1; V512 v2; V512 good; V512 vvv; intop(ASSIGN, v1.f64, init1, 0); intop(ASSIGN, v2.f64, init2, 0); // simple intrinsics DOONE(ADD, _mm512_add_pd); DOONE(MAX, _mm512_max_pd); DOONE(MIN, _mm512_min_pd); DOONE(MUL, _mm512_mul_pd); DOONE(SUB, _mm512_sub_pd); DOONE_WITH_MASK(ADD, _mm512_mask_add_pd, 0x07); DOONE_WITH_MASK(MAX, _mm512_mask_max_pd, 0x01); DOONE_WITH_MASK(MIN, _mm512_mask_min_pd, 0x03); DOONE_WITH_MASK(MUL, _mm512_mask_mul_pd, 0xf0); DOONE_WITH_MASK(SUB, _mm512_mask_sub_pd, 0x9f); DOONE_WITH_MASK_1OP(ABS, _mm512_mask_abs_pd, 0xf4); // intrinsics with rounding mode DOONE_ROUND(ADD, _mm512_add_round_pd, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC); DOONE_ROUND(SUB, _mm512_sub_round_pd, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); DOONE_WITH_MASK_ROUND(ADD, _mm512_mask_add_round_pd, 0x07, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); DOONE_WITH_MASK_ROUND(SUB, _mm512_mask_sub_round_pd, 0xf0, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC); if (n_errs != 0) { printf("FAILED\n"); return 1; } printf("PASSED\n"); return 0; }
42.319502
80
0.335033
[ "vector" ]
066ecd76255c20d9bf44564d9699b2a0f24a3be0
3,550
h
C
systems/sensors/image_to_lcm_image_array_t.h
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
systems/sensors/image_to_lcm_image_array_t.h
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
systems/sensors/image_to_lcm_image_array_t.h
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
#pragma once #include <string> #include <vector> #include "drake/common/drake_copyable.h" #include "drake/lcmt_image_array.hpp" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/sensors/image.h" #include "drake/systems/sensors/pixel_types.h" #include "drake/systems/sensors/robotlocomotion_compat.h" namespace drake { namespace systems { namespace sensors { // TODO(jwnimmer-tri) Throughout this filename, classname, and method names, the // the "_t" or "T" suffix is superfluous and should be removed. /// An ImageToLcmImageArrayT takes as input an ImageRgba8U, ImageDepth32F and /// ImageLabel16I. This system outputs an AbstractValue containing a /// `Value<lcmt_image_array>` LCM message that defines an array of images /// (lcmt_image). This message can then be sent to other processes that /// sbscribe it using LcmPublisherSystem. Note that you should NOT assume any /// particular order of those images stored in lcmt_image_array, /// instead check the semantic of those images with /// lcmt_image::pixel_format before using them. /// /// @note The output message's header field `seq` is always zero. class ImageToLcmImageArrayT : public systems::LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ImageToLcmImageArrayT) /// Constructs an empty system with no input ports. /// After construction, use DeclareImageInputPort() to add inputs. explicit ImageToLcmImageArrayT(bool do_compress = false); /// An %ImageToLcmImageArrayT constructor. Declares three input ports -- /// one color image, one depth image, and one label image. /// /// @param color_frame_name The frame name used for color image. /// @param depth_frame_name The frame name used for depth image. /// @param label_frame_name The frame name used for label image. /// @param do_compress When true, zlib compression will be performed. The /// default is false. ImageToLcmImageArrayT(const std::string& color_frame_name, const std::string& depth_frame_name, const std::string& label_frame_name, bool do_compress = false); /// Returns the input port containing a color image. /// Note: Only valid if the color/depth/label constructor is used. const InputPort<double>& color_image_input_port() const; /// Returns the input port containing a depth image. /// Note: Only valid if the color/depth/label constructor is used. const InputPort<double>& depth_image_input_port() const; /// Returns the input port containing a label image. /// Note: Only valid if the color/depth/label constructor is used. const InputPort<double>& label_image_input_port() const; /// Returns the abstract valued output port that contains a /// `Value<lcmt_image_array>`. const OutputPort<double>& image_array_t_msg_output_port() const; template <PixelType kPixelType> const InputPort<double>& DeclareImageInputPort(const std::string& name) { input_port_pixel_type_.push_back(kPixelType); return this->DeclareAbstractInputPort( name, Value<Image<kPixelType>>()); } private: void CalcImageArray(const systems::Context<double>& context, lcmt_image_array* msg) const; int color_image_input_port_index_{-1}; int depth_image_input_port_index_{-1}; int label_image_input_port_index_{-1}; int image_array_t_msg_output_port_index_{-1}; std::vector<PixelType> input_port_pixel_type_{}; const bool do_compress_; }; } // namespace sensors } // namespace systems } // namespace drake
39.444444
80
0.741408
[ "vector" ]
944aecc9bce107f0d246da6ce98d46276bf9e0f9
3,340
h
C
MetaheuristicsCPP/Optimizer.h
Belvenix/metaheuristics-all-laboratories-jb
c8a8a3533b19bfbfad66ae464dc6e5ce5b10570b
[ "MIT" ]
null
null
null
MetaheuristicsCPP/Optimizer.h
Belvenix/metaheuristics-all-laboratories-jb
c8a8a3533b19bfbfad66ae464dc6e5ce5b10570b
[ "MIT" ]
null
null
null
MetaheuristicsCPP/Optimizer.h
Belvenix/metaheuristics-all-laboratories-jb
c8a8a3533b19bfbfad66ae464dc6e5ce5b10570b
[ "MIT" ]
null
null
null
#pragma once #include "OptimizationResult.h" #include "StopCondition.h" #include "TimeUtils.h" #include <ctime> #include <Evaluation.h> #include <random> #include <vector> using namespace StopConditions; using namespace Evaluations; using namespace std; namespace Optimizers { template <typename TElement> class IOptimizer { public: virtual ~IOptimizer() = default; virtual void vInitialize() = 0; virtual bool bRunIteration() = 0; virtual bool bShouldStop() = 0; virtual void vRun() = 0; virtual COptimizationResult<TElement> *pcGetResult() = 0; };//class IOptimizer template <typename TElement> class COptimizer : public IOptimizer<TElement> { public: COptimizer(IEvaluation<TElement> &cEvaluation, IStopCondition &cStopCondition) : c_evaluation(cEvaluation), c_stop_condition(cStopCondition) { pc_result = nullptr; }//COptimizer(IEvaluation<TElement> &cEvaluation, IStopCondition &cStopCondition) COptimizer(const COptimizer<TElement> &cOther) = delete; COptimizer(COptimizer<TElement> &&cOther) = delete; virtual ~COptimizer() { delete pc_result; }//virtual ~COptimizer() virtual void vInitialize() final { delete pc_result; pc_result = nullptr; i_iteration_number = 0; t_start_time = clock(); v_initialize(t_start_time); }//virtual void vInitialize() final virtual bool bRunIteration() final { bool b_best_updated = b_run_iteration(i_iteration_number, t_start_time); i_iteration_number++; return b_best_updated; }//virtual void vRunIteration() final virtual bool bShouldStop() final { double d_best_value = pc_result != nullptr ? pc_result->dGetBestValue() : -DBL_MAX; return c_stop_condition.bStop(d_best_value, i_iteration_number, c_evaluation.iGetFFE(), t_start_time); }//virtual bool bShouldStop() final virtual void vRun() { vInitialize(); while (!bShouldStop()) { bRunIteration(); }//while (!bShouldStop()) }//virtual void vRun() virtual COptimizationResult<TElement> *pcGetResult() { return pc_result; } COptimizer<TElement>& operator=(const COptimizer<TElement> &cOther) = delete; COptimizer<TElement>& operator=(COptimizer<TElement> &&cOther) = delete; protected: virtual void v_initialize(clock_t tStartTime) = 0; virtual bool b_run_iteration(long long iIterationNumber, clock_t tStartTime) = 0; bool b_check_new_best(vector<TElement> &vSolution, double dValue, bool bOnlyImprovements = true) { bool b_best_updated = false; if (pc_result == nullptr || dValue > pc_result->dGetBestValue() || dValue == pc_result->dGetBestValue() && !bOnlyImprovements) { delete pc_result; pc_result = new COptimizationResult<TElement>(dValue, vSolution, i_iteration_number, c_evaluation.iGetFFE(), TimeUtils::dCalculateSeconds(t_start_time)); b_best_updated = true; }//if (pc_result == nullptr || dValue > pc_result->dGetBestValue() || dValue == pc_result->dGetBestValue() && !bOnlyImprovements) return b_best_updated; }//void v_check_new_best(vector<TElement> &vSolution, double dValue) IEvaluation<TElement> &c_evaluation; IStopCondition &c_stop_condition; COptimizationResult<TElement> *pc_result; private: long long i_iteration_number; clock_t t_start_time; };//class COptimizer : public IOptimizer<TElement> }//namespace Optimizers
26.935484
157
0.737425
[ "vector" ]
944bfe6c7ec2b9de70475d9812e18c6dda52a43d
2,789
h
C
external/umesimd/unittest/UMEUnitTestSimd.h
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
external/umesimd/unittest/UMEUnitTestSimd.h
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
external/umesimd/unittest/UMEUnitTestSimd.h
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
// The MIT License (MIT) // // Copyright (c) 2015-2017 CERN // // Author: Przemyslaw Karpinski // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // // This piece of code was developed as part of ICE-DIP project at CERN. // "ICE-DIP is a European Industrial Doctorate project funded by the European Community's // 7th Framework programme Marie Curie Actions under grant PITN-GA-2012-316596". // #ifndef UME_UNIT_TEST_SIMD_H_ #define UME_UNIT_TEST_SIMD_H_ #include "UMEUnitTestCommon.h" #include "../UMESimd.h" // masks #include "UMEUnitTestMasks.h" // swizzle masks #include "UMEUnitTestSwizzleMask.h" // arithmetic vectors #include "UMEUnitTestSimd8b.h" #include "UMEUnitTestSimd16b.h" #include "UMEUnitTestSimd32b.h" #include "UMEUnitTestSimd64b.h" #include "UMEUnitTestSimd128b.h" #include "UMEUnitTestSimd256b.h" #include "UMEUnitTestSimd512b.h" #include "UMEUnitTestSimd1024b.h" int test_UMESimd(bool supressMessages) { char header[] = "UME::SIMD::SIMD vector test"; INIT_TEST(header, supressMessages); int failCount = 0; // This checks if template based generation of vector types works correctly // masks failCount += test_UME_SIMDMasks(supressMessages); // swizzle masks failCount += test_UME_SIMDSwizzleMasks(supressMessages); // arithmetic vectors failCount += test_UME_SIMD8b(supressMessages); failCount += test_UME_SIMD16b(supressMessages); failCount += test_UME_SIMD32b(supressMessages); failCount += test_UME_SIMD64b(supressMessages); failCount += test_UME_SIMD128b(supressMessages); failCount += test_UME_SIMD256b(supressMessages); failCount += test_UME_SIMD512b(supressMessages); failCount += test_UME_SIMD1024b(supressMessages); return failCount; } #endif
34.012195
91
0.757261
[ "vector" ]
945196011515d2464a432f2cd5b0a1977bbce6d9
5,656
h
C
QCloudCOSXML/Classes/CI/model/QCloudVideoRecognitionResult.h
yoferzhang/QCloudCOSXML
b0f2cee5da6be25c6364221642a68d0c0f3d905b
[ "Unlicense", "MIT" ]
null
null
null
QCloudCOSXML/Classes/CI/model/QCloudVideoRecognitionResult.h
yoferzhang/QCloudCOSXML
b0f2cee5da6be25c6364221642a68d0c0f3d905b
[ "Unlicense", "MIT" ]
null
null
null
QCloudCOSXML/Classes/CI/model/QCloudVideoRecognitionResult.h
yoferzhang/QCloudCOSXML
b0f2cee5da6be25c6364221642a68d0c0f3d905b
[ "Unlicense", "MIT" ]
null
null
null
// // QCloudVideoRecognitionResult.h // QCloudCOSXML // // Created by garenwang on 2021/10/26. // #import <Foundation/Foundation.h> @class QCloudVideoRecognitionItemInfo; @class QCloudVideoRecognitionSnapshotItemInfo; @class QCloudVideoRecognitionSnapshot; @class QCloudVideoRecognitionAudioSectionItemInfo; @class QCloudVideoRecognitionAudioSection; NS_ASSUME_NONNULL_BEGIN @interface QCloudVideoRecognitionResult : NSObject /// 错误码,值为0时表示审核成功,非0表示审核失败。 @property (nonatomic,strong)NSString * Code; /// 错误描述 @property (nonatomic,strong)NSString * Message; /// 视频审核任务的 ID。 @property (nonatomic,strong)NSString * JobId; /// 视频审核任务的状态,值为 Submitted(已提交审核)、Snapshoting(视频截帧中)、Success(审核成功)、Failed(审核失败)、Auditing(审核中)其中一个。 @property (nonatomic,strong)NSString * State; /// 视频审核任务的创建时间 @property (nonatomic,strong)NSString * CreationTime; /// 被审核的视频文件的名称。 @property (nonatomic,strong)NSString * Object; /// 本次审核的文件链接,创建任务使用 Url 时返回。 @property (nonatomic,strong)NSString * Url; /// 视频截图的总数量。 @property (nonatomic,strong)NSString * SnapshotCount; /// 该字段用于返回检测结果中所对应的优先级最高的恶意标签,表示模型推荐的审核结果,建议您按照业务所需,对不同违规类型与建议值进行处理。 返回值:Normal:正常,Porn:色情,Ads:广告,Politics:涉政,Terrorism:暴恐。 @property (nonatomic,strong)NSString * Label; /// 该字段表示本次判定的审核结果,您可以根据该结果,进行后续的操作;建议您按照业务所需,对不同的审核结果进行相应处理。 /// 有效值:0(审核正常),1 (判定为违规敏感文件),2(疑似敏感,建议人工复核)。 @property (nonatomic,strong)NSString * Result; /// 审核场景为涉黄的审核结果信息。 @property (nonatomic,strong)QCloudVideoRecognitionItemInfo * PornInfo; /// 审核场景为涉暴恐的审核结果信息。 @property (nonatomic,strong)QCloudVideoRecognitionItemInfo * TerrorismInfo; /// 审核场景为政治敏感的审核结果信息。 @property (nonatomic,strong)QCloudVideoRecognitionItemInfo * PoliticsInfo; /// 审核场景为广告引导的审核结果信息。 @property (nonatomic,strong)QCloudVideoRecognitionItemInfo * AdsInfo; /// 该字段用于返回视频中视频画面截图审核的结果。 /// 注意:每次查看数据的有效期为2小时,2小时后如还需查看,请重新发起查询请求。 @property (nonatomic,strong)NSArray <QCloudVideoRecognitionSnapshot *> * Snapshot; /// 该字段用于返回视频中视频声音审核的结果。 /// 注意:每次查看数据的有效期为2小时,2小时后如还需查看,请重新发起查询请求 @property (nonatomic,strong)QCloudVideoRecognitionAudioSection * AudioSection; @property (nonatomic,strong)NSString * NonExistJobIds; @end @interface QCloudVideoRecognitionItemInfo : NSObject /// 是否命中该审核分类,0表示未命中,1表示命中,2表示疑似。 @property (nonatomic,strong)NSString * HitFlag; @property (nonatomic,strong)NSString * Count; @end @interface QCloudVideoRecognitionSnapshot : NSObject /// 视频截图的访问地址,您可以通过该地址查看该截图内容,地址格式为标准 URL 格式。 @property (nonatomic,strong)NSString * Url; /// 该字段用于返回当前截图的图片 OCR 文本识别的检测结果(仅在审核策略开启文本内容检测时返回),识别上限为5000字节。 @property (nonatomic,strong)NSString * Text; /// 该字段用于返回当前截图位于视频中的时间,单位为毫秒。例如5000(视频开始后5000毫秒)。 @property (nonatomic,strong)NSString * SnapshotTime; @property (nonatomic,strong)NSString * Result; @property (nonatomic,strong)NSString * Label; @property (nonatomic,strong)QCloudVideoRecognitionSnapshotItemInfo * PornInfo; @property (nonatomic,strong)QCloudVideoRecognitionSnapshotItemInfo * TerrorismInfo; @property (nonatomic,strong)QCloudVideoRecognitionSnapshotItemInfo * PoliticsInfo; @property (nonatomic,strong)QCloudVideoRecognitionSnapshotItemInfo * AdsInfo; /// <#Description#> @end @interface QCloudVideoRecognitionSnapshotItemInfo : NSObject /// 是否命中该审核分类,0表示未命中,1表示命中,2表示疑似。 @property (nonatomic,strong)NSString * HitFlag; /// 该字段表示审核结果命中审核信息的置信度,取值范围:0(置信度最低)-100(置信度最高 ),越高代表该内容越有可能属于当前返回审核信息。 /// 例如:色情 99,则表明该内容非常有可能属于色情内容。 @property (nonatomic,strong)NSString * Score; /// 该字段为兼容旧版本的保留字段,表示该截图的结果标签(可能为 SubLabel,可能为人物名字等)。 @property (nonatomic,strong)NSString * Label; /// 该字段表示审核命中的具体子标签,例如:Porn 下的 SexBehavior 子标签。 /// 注意:该字段可能返回空,表示未命中具体的子标签。 @property (nonatomic,strong)NSString * SubLabel; @end @interface QCloudVideoRecognitionAudioSection : NSObject /// 视频声音片段的访问地址,您可以通过该地址获取该声音片段的内容,地址格式为标准 URL 格式。 @property (nonatomic,strong)NSString * Url; /// 该字段用于返回当前声音片段位于视频中的时间,单位为毫秒,例如5000(视频开始后5000毫秒)。 @property (nonatomic,strong)NSString * OffsetTime; /// 当前视频声音片段的时长,单位毫秒。 @property (nonatomic,strong)NSString * Duration; /// 该字段用于返回当前视频声音的 ASR 文本识别的检测结果(仅在审核策略开启文本内容检测时返回),识别上限为5小时。 @property (nonatomic,strong)NSString * Text; /// 该字段用于返回检测结果中所对应的优先级最高的恶意标签,表示模型推荐的审核结果,建议您按照业务所需,对不同违规类型与建议值进行处理。 返回值:Normal:正常,Porn:色情,Ads:广告,Politics:涉政,Terrorism:暴恐。 @property (nonatomic,strong)NSString * Label; /// 该字段表示本次判定的审核结果,您可以根据该结果,进行后续的操作;建议您按照业务所需,对不同的审核结果进行相应处理。 /// 有效值:0(审核正常),1 (判定为违规敏感文件),2(疑似敏感,建议人工复核)。 @property (nonatomic,strong)NSString * Result; /// 审核场景为涉黄的审核结果信息。 @property (nonatomic,strong)QCloudVideoRecognitionAudioSectionItemInfo * PornInfo; /// 审核场景为涉暴恐的审核结果信息。 @property (nonatomic,strong)QCloudVideoRecognitionAudioSectionItemInfo * TerrorismInfo; /// 审核场景为政治敏感的审核结果信息。 @property (nonatomic,strong)QCloudVideoRecognitionAudioSectionItemInfo * PoliticsInfo; /// 审核场景为广告引导的审核结果信息。 @property (nonatomic,strong)QCloudVideoRecognitionAudioSectionItemInfo * AdsInfo; @end @interface QCloudVideoRecognitionAudioSectionItemInfo : NSObject /// 是否命中该审核分类,0表示未命中,1表示命中,2表示疑似。 @property (nonatomic,strong)NSString * HitFlag; /// 该字段表示审核结果命中审核信息的置信度,取值范围:0(置信度最低)-100(置信度最高 ),越高代表该内容越有可能属于当前返回审核信息 /// 例如:色情 99,则表明该内容非常有可能属于色情内容。 @property (nonatomic,strong)NSString * Score; /// 在当前审核场景下命中的关键词。 @property (nonatomic,strong)NSString * Keywords; @end @interface QCloudPostVideoRecognitionResult : NSObject /// 本次视频审核任务的 ID。 @property (nonatomic,strong)NSString * JobId; /// 视频审核任务的状态,值为 Submitted(已提交审核)、Snapshoting(视频截帧中)、Success(审核成功)、Failed(审核失败)、Auditing(审核中)其中一个 @property (nonatomic,strong)NSString * State; @property (nonatomic,strong)NSString * Object; /// 视频审核任务的创建时间 @property (nonatomic,strong)NSString * CreationTime; @end NS_ASSUME_NONNULL_END
29.768421
124
0.796853
[ "object" ]
946e1168d919e49c1a635bdc4866b56ca5a8b59e
1,786
h
C
src/OrbitGl/TextRendererInterface.h
ioperations/orbit
c7935085023cce1abb70ce96dd03339f47a1c826
[ "BSD-2-Clause" ]
716
2017-09-22T11:50:40.000Z
2020-03-14T21:52:22.000Z
src/OrbitGl/TextRendererInterface.h
ioperations/orbit
c7935085023cce1abb70ce96dd03339f47a1c826
[ "BSD-2-Clause" ]
132
2017-09-24T11:48:18.000Z
2020-03-17T17:39:45.000Z
src/OrbitGl/TextRendererInterface.h
ioperations/orbit
c7935085023cce1abb70ce96dd03339f47a1c826
[ "BSD-2-Clause" ]
49
2017-09-23T10:23:59.000Z
2020-03-14T09:27:49.000Z
// Copyright (c) 2022 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ORBIT_GL_TEXT_RENDERER_INTERFACE_H_ #define ORBIT_GL_TEXT_RENDERER_INTERFACE_H_ #include <GteVector.h> #include <stdint.h> #include <vector> #include "CoreMath.h" #include "PrimitiveAssembler.h" namespace orbit_gl { class TextRendererInterface { public: enum class HAlign { Left, Right, Centered }; enum class VAlign { Top, Middle, Bottom }; struct TextFormatting { uint32_t font_size = 14; Color color = Color(255, 255, 255, 255); float max_size = -1.f; HAlign halign = HAlign::Left; VAlign valign = VAlign::Top; }; virtual ~TextRendererInterface() = default; virtual void Init() = 0; virtual void Clear() = 0; virtual void RenderLayer(float layer) = 0; virtual void RenderDebug(PrimitiveAssembler* primitive_assembler) = 0; [[nodiscard]] virtual std::vector<float> GetLayers() const = 0; virtual void AddText(const char* text, float x, float y, float z, TextFormatting formatting) = 0; virtual void AddText(const char* text, float x, float y, float z, TextFormatting formatting, Vec2* out_text_pos, Vec2* out_text_size) = 0; virtual float AddTextTrailingCharsPrioritized(const char* text, float x, float y, float z, TextFormatting formatting, size_t trailing_chars_length) = 0; [[nodiscard]] virtual float GetStringWidth(const char* text, uint32_t font_size) = 0; [[nodiscard]] virtual float GetStringHeight(const char* text, uint32_t font_size) = 0; }; } // namespace orbit_gl #endif // ORBIT_GL_TEXT_RENDERER_INTERFACE_H_
33.074074
99
0.68813
[ "vector" ]
947908bcb144f69253a2a9bb8b2eb822ae70b6f4
103,712
h
C
hyperion/utility.h
mpokorny/legms
8ea5d1899ac5e2658ebe481b706430474685bb2d
[ "Apache-2.0" ]
2
2021-02-03T00:40:55.000Z
2021-02-03T13:30:31.000Z
hyperion/utility.h
mpokorny/legms
8ea5d1899ac5e2658ebe481b706430474685bb2d
[ "Apache-2.0" ]
null
null
null
hyperion/utility.h
mpokorny/legms
8ea5d1899ac5e2658ebe481b706430474685bb2d
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Associated Universities, Inc. Washington DC, USA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef HYPERION_UTILITY_H_ #define HYPERION_UTILITY_H_ #include <hyperion/hyperion.h> #include <experimental/mdspan> #ifdef HYPERION_USE_KOKKOS # include <Kokkos_Core.hpp> # define HYPERION_INLINE_FUNCTION KOKKOS_INLINE_FUNCTION #else # ifdef HYPERION_USE_CUDA # define HYPERION_INLINE_FUNCTION __device__ __host__ inline # else # define HYPERION_INLINE_FUNCTION inline #endif #endif // HYPERION_USE_KOKKOS #ifdef HYPERION_USE_CASACORE # include <casacore/measures/Measures/Stokes.h> #endif #if !HAVE_CXX17 namespace std { // Conforming C++14 implementation (is also a valid C++11 implementation): namespace detail { template<class T> struct invoke_impl { template<class F, class... Args> static auto call(F&& f, Args&&... args) -> decltype(std::forward<F>(f)(std::forward<Args>(args)...)); }; template<class B, class MT> struct invoke_impl<MT B::*> { template<class T, class Td = typename std::decay<T>::type, class = typename std::enable_if<std::is_base_of<B, Td>::value>::type > static auto get(T&& t) -> T&&; template<class T, class Td = typename std::decay<T>::type, class = typename std::enable_if<is_reference<Td>::value>::type > static auto get(T&& t) -> decltype(t.get()); template<class T, class Td = typename std::decay<T>::type, class = typename std::enable_if<!std::is_base_of<B, Td>::value>::type, class = typename std::enable_if<!is_reference<Td>::value>::type > static auto get(T&& t) -> decltype(*std::forward<T>(t)); template<class T, class... Args, class MT1, class = typename std::enable_if<std::is_function<MT1>::value>::type > static auto call(MT1 B::*pmf, T&& t, Args&&... args) -> decltype((invoke_impl::get(std::forward<T>(t)).*pmf)(std::forward<Args>(args)...)); template<class T> static auto call(MT B::*pmd, T&& t) -> decltype(invoke_impl::get(std::forward<T>(t)).*pmd); }; template<class F, class... Args, class Fd = typename std::decay<F>::type> auto INVOKE(F&& f, Args&&... args) -> decltype(invoke_impl<Fd>::call(std::forward<F>(f), std::forward<Args>(args)...)); template <typename AlwaysVoid, typename, typename...> struct invoke_result { }; template <typename F, typename...Args> struct invoke_result<decltype(void(detail::INVOKE(std::declval<F>(), std::declval<Args>()...))), F, Args...> { using type = decltype(detail::INVOKE(std::declval<F>(), std::declval<Args>()...)); }; } // namespace detail // template <class> struct result_of; // template <class F, class... ArgTypes> // struct result_of<F(ArgTypes...)> : detail::invoke_result<void, F, ArgTypes...> {}; template <class F, class... ArgTypes> struct invoke_result : detail::invoke_result<void, F, ArgTypes...> {}; template< class F, class... ArgTypes> using invoke_result_t = typename invoke_result<F, ArgTypes...>::type; } // end namespace std #endif // !HAVE_CXX17 #include <hyperion/IndexTree.h> #include <hyperion/utility_c.h> #include <mappers/default_mapper.h> #include <algorithm> #include <array> #include <atomic> #include <cassert> #include <complex> #include <cstring> #include <limits> #include <memory> #include <numeric> #include CXX_OPTIONAL_HEADER #include <set> #include <type_traits> #include <unordered_map> #include <unordered_set> #include CXX_FILESYSTEM_HEADER #ifdef HYPERION_USE_HDF5 # include <hdf5.h> #endif #ifdef HYPERION_USE_CASACORE # include <casacore/casa/aipstype.h> # include <casacore/casa/Arrays/IPosition.h> # include <casacore/casa/BasicSL/String.h> # include <casacore/casa/Containers/Record.h> # include <casacore/casa/Utilities/DataType.h> # include <casacore/coordinates/Coordinates/CoordinateSystem.h> # include <casacore/coordinates/Coordinates/LinearCoordinate.h> # include <casacore/coordinates/Coordinates/DirectionCoordinate.h> #endif // The following reiterates a constant in Realm -- unfortunately there is no way // to either import or discover its value. Hopefully the impact is minor, as // this value should only be required by serdez functions, and Realm has // implemented a runtime check. #define HYPERION_IB_MAX_SIZE (63 * (((size_t)1) << 20)) namespace hyperion { class Table; class ColumnSpace; class TableField; typedef IndexTree<Legion::coord_t> IndexTreeL; #ifndef HYPERION_USE_KOKKOS template <typename T> using complex = std::complex<T>; template <typename T, size_t N> using array = std::array<T, N>; template <typename S, typename T> using pair = std::pair<S, T>; #else template <typename T> using complex = Kokkos::complex<T>; template <typename T, size_t N> using array = Kokkos::Array<T, N>; template <typename S, typename T> using pair = Kokkos::pair<S, T>; #endif template <int N, typename C> bool operator<(const Legion::Point<N, C>& a, const Legion::Point<N, C>& b) { bool result = true; for (size_t i = 0; result && i < N; ++i) result = a[i] < b[i]; return result; } template <int N, typename C> bool operator<(const Legion::Rect<N, C>& a, const Legion::Rect<N, C>& b) { if (a.lo < b.lo) return true; if (b.lo < a.lo) return false; return a.hi < b.hi; } #ifdef HYPERION_USE_CASACORE typedef casacore::Stokes::StokesTypes stokes_t; typedef std::integral_constant<unsigned, casacore::Stokes::NumberOfTypes> num_stokes_t; #else typedef int stokes_t; typedef std::integral_constant<unsigned, 32> num_stokes_t; #endif #if HAVE_CXX17 template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; #endif // HAVE_CXX17 template <typename T, typename F> CXX_OPTIONAL_NAMESPACE::optional<std::invoke_result_t<F, T>> map(const CXX_OPTIONAL_NAMESPACE::optional<T>& ot, F f) { return ot ? CXX_OPTIONAL_NAMESPACE::optional<std::invoke_result_t<F, T>>(f(ot.value())) : CXX_OPTIONAL_NAMESPACE::optional<std::invoke_result_t<F, T>>(); } template <typename T, typename F> std::invoke_result_t<F, T> flatMap(const CXX_OPTIONAL_NAMESPACE::optional<T>& ot, F f) { return ot ? f(ot.value()) : std::invoke_result_t<F, T>(); } template <typename T, typename F> std::vector<std::invoke_result_t<F, T>> map(const std::vector<T>& ts, F f) { std::vector<std::invoke_result_t<F, T>> result; std::transform( ts.begin(), ts.end(), std::inserter(result, result.end()), [&f](const auto& t) { return f(t); }); return result; } template <typename T> std::vector<int> map_to_int(const std::vector<T>& ts) { return map(ts, [](const auto& t) { return static_cast<int>(t); }); } void toupper(std::string& s); std::string toupper(const std::string& s); bool has_suffix(const std::string& str, const std::string& suffix); std::string add_name_prefix(const std::string& prefix, const std::string& str); template <typename D> struct Axes { static const char* uid; static const std::vector<std::string> names; static const unsigned num_axes; #ifdef HYPERION_USE_HDF5 static const hid_t h5_datatype; #endif }; CXX_OPTIONAL_NAMESPACE::optional<int> column_is_axis( const std::vector<std::string>& axis_names, const std::string& colname, const std::vector<int>& axes); template <size_t N> char * fstrcpy(char(& dest)[N], const std::string& src) { auto n = std::min(N, src.size() + 1); std::strncpy(&dest[0], src.c_str(), n); dest[n - 1] = '\0'; return &dest[0]; } template <size_t N> char * fstrcpy(char(& dest)[N], const char* src) { auto n = std::min(N, std::strlen(src) + 1); std::strncpy(&dest[0], src, n); dest[n - 1] = '\0'; return &dest[0]; } HYPERION_EXPORT unsigned min_divisor( size_t numerator, size_t min_quotient, unsigned max_divisor); // this returns an IndexPartition with a new IndexSpace as a color space, which // the caller must eventually destroy HYPERION_EXPORT Legion::IndexPartition partition_over_default_tunable( Legion::Context ctx, Legion::Runtime* rt, Legion::IndexSpace is, size_t min_block_size, Legion::Mapping::DefaultMapper::DefaultTunables tunable); HYPERION_EXPORT IndexTreeL index_space_as_tree(Legion::Runtime* rt, Legion::IndexSpace is); #ifdef HYPERION_USE_CASACORE HYPERION_EXPORT std::tuple< std::string, ColumnSpace, std::vector< std::tuple<ColumnSpace, std::vector<std::pair<std::string, TableField>>>>> from_ms( Legion::Context ctx, Legion::Runtime* runtime, const CXX_FILESYSTEM_NAMESPACE::path& path, const std::unordered_set<std::string>& column_selections); #endif // HYPERION_USE_CASACORE template < typename OPEN, typename F, typename CLOSE, std::enable_if_t< !std::is_void< std::invoke_result_t<F, std::invoke_result_t<OPEN>&>>::value, int> = 0> std::invoke_result_t<F, std::invoke_result_t<OPEN>&> using_resource(OPEN open, F f, CLOSE close) { auto r = open(); std::invoke_result_t<F, std::invoke_result_t<OPEN>&> result; try { result = f(r); } catch (...) { close(r); throw; } close(r); return result; } template < typename OPEN, typename F, typename CLOSE, std::enable_if_t< std::is_void< std::invoke_result_t<F, std::invoke_result_t<OPEN>&>>::value, int> = 0> void using_resource(OPEN open, F f, CLOSE close) { auto r = open(); try { f(r); } catch (...) { close(r); throw; } close(r); } struct HYPERION_EXPORT string { string() { val[0] = '\0'; } string(const std::string& s) { fstrcpy(val, s); } string(const char* s) { fstrcpy(val, s); } string& operator=(const std::string& s) { fstrcpy(val, s); return *this; } string& operator=(const char* s) { fstrcpy(val, s); return *this; } char val[HYPERION_MAX_STRING_SIZE]; operator std::string() const { return std::string(val); } size_t size() const { return std::strlen(val); }; bool operator==(const string& other) const { return std::strncmp(val, other.val, sizeof(val)) == 0; } bool operator!=(const string& other) const { return std::strncmp(val, other.val, sizeof(val)) != 0; } bool operator<(const string& other) const { return std::strncmp(val, other.val, sizeof(val)) < 0; } }; template <typename D> bool has_unique_values(const std::vector<D>& axes) { std::vector<D> ax = axes; std::sort(ax.begin(), ax.end()); std::unique(ax.begin(), ax.end()); return ax.size() == axes.size(); } template <typename D> std::vector<int> dimensions_map(const std::vector<D>& from, const std::vector<D>& to) { std::vector<int> result(from.size()); for (size_t i = 0; i < from.size(); ++i) { result[i] = -1; for (size_t j = 0; result[i] == -1 && j < to.size(); ++j) if (from[i] == to[j]) result[i] = j; } return result; } typedef ::type_tag_t TypeTag; template <typename T> class vector_serdez { public: typedef std::vector<T> FIELD_TYPE; static const size_t MAX_SERIALIZED_SIZE = HYPERION_IB_MAX_SIZE; static size_t serialized_size(const FIELD_TYPE& val) { return sizeof(size_t) + val.size() * sizeof(T); } static size_t serialize(const FIELD_TYPE& val, void *buffer) { size_t result = serialized_size(val); size_t n = val.size(); std::memcpy(static_cast<size_t *>(buffer), &n, sizeof(n)); if (n > 0) { T* tbuf = reinterpret_cast<T *>(static_cast<size_t *>(buffer) + 1); for (size_t i = 0; i < n; ++i) *tbuf++ = val[i]; } return result; } static size_t deserialize(FIELD_TYPE& val, const void *buffer) { ::new(&val) FIELD_TYPE; size_t n = *static_cast<const size_t *>(buffer); if (n > 0) { val.resize(n); const T* tbuf = reinterpret_cast<const T*>(static_cast<const size_t *>(buffer) + 1); for (size_t i = 0; i < n; ++i) val[i] = *tbuf++; } return serialized_size(val); } static void destroy(FIELD_TYPE&) { } }; template <> class vector_serdez<bool> { public: typedef std::vector<bool> FIELD_TYPE; static const size_t MAX_SERIALIZED_SIZE = HYPERION_IB_MAX_SIZE; static size_t serialized_size(const FIELD_TYPE& val) { return sizeof(size_t) + val.size() * sizeof(bool); } static size_t serialize(const FIELD_TYPE& val, void *buffer) { size_t result = serialized_size(val); size_t n = val.size(); std::memcpy(static_cast<size_t *>(buffer), &n, sizeof(n)); if (n > 0) { bool* bbuf = reinterpret_cast<bool *>(static_cast<size_t *>(buffer) + 1); for (size_t i = 0; i < n; ++i) { bool b = val[i]; std::memcpy(bbuf++, &b, sizeof(bool)); } } return result; } static size_t deserialize(FIELD_TYPE& val, const void *buffer) { ::new(&val) FIELD_TYPE; size_t n = *static_cast<const size_t *>(buffer); if (n > 0) { val.resize(n); const bool* bbuf = reinterpret_cast<const bool *>(static_cast<const size_t *>(buffer) + 1); for (size_t i = 0; i < n; ++i) val[i] = *bbuf++; } return serialized_size(val); } static void destroy(FIELD_TYPE&) { } }; template <typename T> class acc_field_serdez { public: typedef std::vector< std::tuple<T, std::vector<Legion::DomainPoint>>> FIELD_TYPE; static const size_t MAX_SERIALIZED_SIZE = HYPERION_IB_MAX_SIZE; static size_t serialized_size(const FIELD_TYPE& val) { return std::accumulate( val.begin(), val.end(), sizeof(size_t), [](auto& acc, auto& t) { return acc + sizeof(T) + vector_serdez<Legion::DomainPoint>::serialized_size( std::get<1>(t)); }); } static size_t serialize(const FIELD_TYPE& val, void *buffer) { size_t result = serialized_size(val); size_t n = val.size(); std::memcpy(static_cast<size_t *>(buffer), &n, sizeof(n)); buffer = static_cast<void *>(static_cast<size_t*>(buffer) + 1); for (size_t i = 0; i < n; ++i) { #if HAVE_CXX17 auto& [t, rns] = val[i]; #else // !HAVE_CXX17 auto& t = std::get<0>(val[i]); auto& rns = std::get<1>(val[i]); #endif // HAVE_CXX17 T* tbuf = reinterpret_cast<T *>(buffer); std::memcpy(tbuf, &t, sizeof(T)); buffer = static_cast<void *>(tbuf + 1); buffer = static_cast<char*>(buffer) + vector_serdez<Legion::DomainPoint>::serialize(rns, buffer); } return result; } static size_t deserialize(FIELD_TYPE& val, const void *buffer) { ::new(&val) FIELD_TYPE; size_t n = *static_cast<const size_t *>(buffer); buffer = static_cast<const void *>(static_cast<const size_t*>(buffer) + 1); val.reserve(n); for (size_t i = 0; i < n; ++i) { const T* tbuf = reinterpret_cast<const T *>(buffer); buffer = static_cast<const void *>(tbuf + 1); std::vector<Legion::DomainPoint> rns; buffer = static_cast<const char*>(buffer) + vector_serdez<Legion::DomainPoint>::deserialize(rns, buffer); val.emplace_back(*tbuf, rns); } return serialized_size(val); } static void destroy(FIELD_TYPE&) { } }; template <typename S> class string_serdez { // this class only works for fixed size character encodings! public: typedef S FIELD_TYPE; typedef typename S::size_type size_type; typedef typename S::value_type value_type; static const size_t MAX_SERIALIZED_SIZE = 1000; static const size_t MAX_CHARLEN = MAX_SERIALIZED_SIZE - 1; static size_t serialized_size(const S& val) { assert(val.size() < MAX_CHARLEN); return val.size() + 1; } static size_t serialize(const S& val, void *buffer) { assert(val.size() < MAX_CHARLEN); char* buff = static_cast<char*>(buffer); if (val.size() > 0) { std::strcpy(buff, val.c_str()); buff += val.size(); } *buff = '\0'; buff += 1; return buff - static_cast<char*>(buffer); } static size_t deserialize(S& val, const void *buffer) { const char* buff = static_cast<const char*>(buffer); ::new(&val) S; val.assign(buff); buff += val.size() + 1; return buff - static_cast<const char*>(buffer); } static void destroy(S&) { } }; template <> class acc_field_serdez<hyperion::string> { public: typedef std::vector< std::tuple<hyperion::string, std::vector<Legion::DomainPoint>>> FIELD_TYPE; static const size_t MAX_SERIALIZED_SIZE = HYPERION_IB_MAX_SIZE; static size_t serialized_size(const FIELD_TYPE& val) { return std::accumulate( val.begin(), val.end(), sizeof(size_t), [](auto& acc, auto& t) { return acc + sizeof(hyperion::string) + vector_serdez<Legion::DomainPoint>::serialized_size( std::get<1>(t)); }); } static size_t serialize(const FIELD_TYPE& val, void *buffer) { size_t result = serialized_size(val); size_t n = val.size(); std::memcpy(static_cast<size_t *>(buffer), &n, sizeof(n)); buffer = static_cast<void *>(static_cast<size_t*>(buffer) + 1); char* buff = static_cast<char*>(buffer); for (size_t i = 0; i < n; ++i) { #if HAVE_CXX17 auto& [t, rns] = val[i]; #else // !HAVE_CXX17 auto& t = std::get<0>(val[i]); auto& rns = std::get<1>(val[i]); #endif // HAVE_CXX17 std::memcpy(buff, t.val, sizeof(hyperion::string)); buff += sizeof(hyperion::string); buff += vector_serdez<Legion::DomainPoint>::serialize(rns, buff); } return result; } static size_t deserialize(FIELD_TYPE& val, const void *buffer) { ::new(&val) FIELD_TYPE; size_t n = *static_cast<const size_t *>(buffer); buffer = static_cast<const void *>(static_cast<const size_t*>(buffer) + 1); val.reserve(n); const char* buff = static_cast<const char*>(buffer); for (size_t i = 0; i < n; ++i) { hyperion::string str; std::memcpy(str.val, buff, sizeof(hyperion::string)); buff += sizeof(hyperion::string); std::vector<Legion::DomainPoint> rns; buff += vector_serdez<Legion::DomainPoint>::deserialize(rns, buff); val.emplace_back(str, rns); } return serialized_size(val); } static void destroy(FIELD_TYPE&) { } }; class HYPERION_EXPORT index_tree_serdez { public: typedef IndexTreeL FIELD_TYPE; static const size_t MAX_SERIALIZED_SIZE = HYPERION_IB_MAX_SIZE; static size_t serialized_size(const FIELD_TYPE& val); static size_t serialize(const FIELD_TYPE& val, void *buffer); static size_t deserialize(FIELD_TYPE& val, const void *buffer); static void destroy(FIELD_TYPE&); }; #ifdef HYPERION_USE_CASACORE /** * Serialization/deserialization for casacore Records * * Can be used as the basis of serdez functions for other casacore types that * are convertible to and from Records */ class record_serdez { public: typedef casacore::Record FIELD_TYPE; static const size_t MAX_SERIALIZED_SIZE = 1 << 13; static size_t serialized_size(const FIELD_TYPE& val); static size_t serialize(const FIELD_TYPE& val, void *buffer); static size_t deserialize(FIELD_TYPE& val, const void *buffer); static void destroy(FIELD_TYPE& val); }; class HYPERION_EXPORT coordinate_system_serdez { public: typedef casacore::CoordinateSystem FIELD_TYPE; static const size_t MAX_SERIALIZED_SIZE = record_serdez::MAX_SERIALIZED_SIZE; static size_t serialized_size(const FIELD_TYPE& val); static size_t serialize(const FIELD_TYPE& val, void *buffer); static size_t deserialize(FIELD_TYPE& val, const void *buffer); static void destroy(FIELD_TYPE& val); }; class HYPERION_EXPORT linear_coordinate_serdez { public: typedef casacore::LinearCoordinate FIELD_TYPE; static const size_t MAX_SERIALIZED_SIZE = record_serdez::MAX_SERIALIZED_SIZE; static size_t serialized_size(const FIELD_TYPE& val); static size_t serialize(const FIELD_TYPE& val, void *buffer); static size_t deserialize(FIELD_TYPE& val, const void *buffer); static void destroy(FIELD_TYPE& val); }; class HYPERION_EXPORT direction_coordinate_serdez { public: typedef casacore::DirectionCoordinate FIELD_TYPE; static const size_t MAX_SERIALIZED_SIZE = record_serdez::MAX_SERIALIZED_SIZE; static size_t serialized_size(const FIELD_TYPE& val); static size_t serialize(const FIELD_TYPE& val, void *buffer); static size_t deserialize(FIELD_TYPE& val, const void *buffer); static void destroy(FIELD_TYPE& val); }; #endif // HYPERION_USE_CASACORE class bool_or_redop { public: typedef bool LHS; typedef bool RHS; static void combine(LHS& lhs, RHS rhs) { lhs = lhs || rhs; } template <bool EXCL> static void apply(LHS& lhs, RHS rhs) { combine(lhs, rhs); } static constexpr const RHS identity = false; template <bool EXCL> static void fold(RHS& rhs1, RHS rhs2) { combine(rhs1, rhs2); } }; template <typename T> struct acc_field_redop_rhs { std::vector<std::tuple<T, std::vector<Legion::DomainPoint>>> v; size_t legion_buffer_size(void) const { return acc_field_serdez<T>::serialized_size(v); } size_t legion_serialize(void* buffer) const { return acc_field_serdez<T>::serialize(v, buffer); } size_t legion_deserialize(const void* buffer) { return acc_field_serdez<T>::deserialize(v, buffer); } }; template <typename T> class acc_field_redop { public: typedef std::vector<std::tuple<T, std::vector<Legion::DomainPoint>>> LHS; typedef acc_field_redop_rhs<T> RHS; static void combine(LHS& lhs, const RHS& rhs) { if (lhs.size() == 0) { lhs = rhs.v; } else { std::for_each( rhs.v.begin(), rhs.v.end(), [&lhs](auto& t_rns) { #if HAVE_CXX17 auto& [t, rns] = t_rns; #else // !HAVE_CXX17 auto& t = std::get<0>(t_rns); auto& rns = std::get<1>(t_rns); #endif // HAVE_CXX17 if (rns.size() > 0) { auto lb = std::lower_bound( lhs.begin(), lhs.end(), t, [](const auto& a, const auto& b) { return std::get<0>(a) < b; }); if (lb != lhs.end() && std::get<0>(*lb) == t) { auto& lrns = std::get<1>(*lb); auto l = lrns.begin(); auto r = rns.begin(); while (r != rns.end() && l != lrns.end()) { if (*r < *l) { // the following lrns.insert() call may invalidate the "l" // iterator; to compensate, save the iterator's offset, do the // insertion, and then recreate the iterator auto lo = std::distance(l, lrns.begin()); lrns.insert(l, *r); l = lrns.begin() + lo + 1; ++r; } else if (*r == *l) { ++r; } else { ++l; } } std::copy(r, rns.end(), std::back_inserter(lrns)); } else { lhs.insert(lb, t_rns); } } }); } } template <bool EXCL> static void apply(LHS& lhs, const RHS& rhs) { combine(lhs, rhs); } static const RHS identity; template <bool EXCL> static void fold(RHS& rhs1, const RHS& rhs2) { combine(rhs1.v, rhs2); } #ifdef WITH_ACC_FIELD_REDOP_SERDEZ static void init_fn(const Legion::ReductionOp*, void *& state, size_t& sz) { RHS rhs; state = realloc(state, rhs.legion_buffer_size()); sz = rhs.legion_serialize(state); } static void fold_fn( const Legion::ReductionOp* reduction_op, void *& state, size_t& sz, const void* result) { RHS rhs, lhs; rhs.legion_deserialize(result); lhs.legion_deserialize(state); reduction_op->fold(&lhs, &rhs, 1, true); sz = lhs.legion_buffer_size(); state = realloc(state, sz); lhs.legion_serialize(state); } #endif // WITH_ACC_FIELD_REDOP_SERDEZ }; template <typename T> typename acc_field_redop<T>::RHS const acc_field_redop<T>::identity = acc_field_redop_rhs<T>{{}}; struct HYPERION_EXPORT coord_bor_redop { typedef coord_t LHS; typedef coord_t RHS; static const constexpr coord_t identity = 0; template <bool EXCLUSIVE> static void apply(LHS& lhs, RHS rhs); template <bool EXCLUSIVE> static void fold(RHS& rhs1, RHS rhs2); }; template <> inline void coord_bor_redop::apply<true>(LHS& lhs, RHS rhs) { lhs |= rhs; } template <> inline void coord_bor_redop::apply<false>(LHS& lhs, RHS rhs) { __atomic_or_fetch(&lhs, rhs, __ATOMIC_ACQUIRE); } template <> inline void coord_bor_redop::fold<true>(RHS& rhs1, RHS rhs2) { rhs1 |= rhs2; } template <> inline void coord_bor_redop::fold<false>(RHS& rhs1, RHS rhs2) { __atomic_or_fetch(&rhs1, rhs2, __ATOMIC_ACQUIRE); } template <TypeTag T> struct DataType { //typedef X ValueType; }; class HYPERION_EXPORT OpsManager { public: enum { INDEX_TREE_SID = 0, V_DOMAIN_POINT_SID, STD_STRING_SID, ACC_FIELD_STRING_SID, ACC_FIELD_BOOL_SID, ACC_FIELD_CHAR_SID, ACC_FIELD_UCHAR_SID, ACC_FIELD_SHORT_SID, ACC_FIELD_USHORT_SID, ACC_FIELD_INT_SID, ACC_FIELD_UINT_SID, ACC_FIELD_FLOAT_SID, ACC_FIELD_DOUBLE_SID, ACC_FIELD_COMPLEX_SID, ACC_FIELD_DCOMPLEX_SID, ACC_FIELD_RECT2_SID, ACC_FIELD_RECT3_SID, ACC_FIELD_STOKES_SID, ACC_FIELD_STOKES_PAIR_SID, #ifdef HYPERION_USE_CASACORE CC_COORDINATE_SYSTEM_SID, CC_LINEAR_COORDINATE_SID, CC_DIRECTION_COORDINATE_SID, #endif NUM_SIDS }; enum { BOOL_OR_REDOP = 0, COORD_BOR_REDOP, ACC_FIELD_STRING_REDOP, ACC_FIELD_BOOL_REDOP, ACC_FIELD_CHAR_REDOP, ACC_FIELD_UCHAR_REDOP, ACC_FIELD_SHORT_REDOP, ACC_FIELD_USHORT_REDOP, ACC_FIELD_INT_REDOP, ACC_FIELD_UINT_REDOP, ACC_FIELD_FLOAT_REDOP, ACC_FIELD_DOUBLE_REDOP, ACC_FIELD_COMPLEX_REDOP, ACC_FIELD_DCOMPLEX_REDOP, ACC_FIELD_RECT2_REDOP, ACC_FIELD_RECT3_REDOP, ACC_FIELD_STOKES_REDOP, ACC_FIELD_STOKES_PAIR_REDOP, // this must be at the end POINT_ADD_REDOP_BASE }; static void register_ops( Legion::Machine machine, Legion::Runtime* rt, const std::set<Legion::Processor>& local_procs); static Legion::CustomSerdezID serdez_id_base; static inline int POINT_ADD_REDOP(int dim) { return POINT_ADD_REDOP_BASE + dim - 1; } static Legion::CustomSerdezID serdez_id(int sid) { return serdez_id_base + sid; } static Legion::ReductionOpID reduction_id_base; static Legion::ReductionOpID reduction_id(int redop) { return reduction_id_base + redop; } }; template <int DIM> class point_add_redop { public: typedef Legion::Point<DIM> LHS; typedef Legion::Point<DIM> RHS; static const RHS identity; template <bool EXCL> static void apply(LHS& lhs, RHS rhs) { lhs += rhs; } template <bool EXCL> static void fold(RHS& rhs1, RHS rhs2) { rhs1 += rhs2; } }; #ifdef HYPERION_USE_HDF5 class HYPERION_EXPORT H5DatatypeManager { public: // TODO: add support for non-native types in HDF5 files enum { BOOL_H5T = 0, CHAR_H5T, UCHAR_H5T, SHORT_H5T, USHORT_H5T, INT_H5T, UINT_H5T, FLOAT_H5T, DOUBLE_H5T, COMPLEX_H5T, DCOMPLEX_H5T, STRING_H5T, DATATYPE_H5T, FIELD_ID_H5T, RECT2_H5T, RECT3_H5T, STOKES_H5T, STOKES_PAIR_H5T, #ifdef HYPERION_USE_CASACORE MEASURE_CLASS_H5T, #endif N_H5T_DATATYPES }; static void preregister_datatypes(); static const hid_t* datatypes() { return datatypes_; } template <TypeTag DT> static constexpr hid_t datatype(); static herr_t commit_derived( hid_t loc_id, hid_t lcpl_id = H5P_DEFAULT, hid_t tcpl_id = H5P_DEFAULT, hid_t tapl_id = H5P_DEFAULT); static hid_t create( const CXX_FILESYSTEM_NAMESPACE::path& path, unsigned flags, hid_t fcpl_t = H5P_DEFAULT, hid_t fapl_t = H5P_DEFAULT); private: static hid_t datatypes_[N_H5T_DATATYPES]; }; #endif class HYPERION_EXPORT AxesRegistrar { public: struct A { std::string uid; std::vector<std::string> names; #ifdef HYPERION_USE_HDF5 hid_t h5_datatype; #endif }; #ifdef HYPERION_USE_HDF5 static void register_axes( const std::string uid, const std::vector<std::string> names, hid_t hid); template <typename D> static void register_axes() { register_axes(Axes<D>::uid, Axes<D>::names, Axes<D>::h5_datatype); } #else // !HYPERION_USE_HDF5 static void register_axes( const std::string uid, const std::vector<std::string> names); template <typename D> static void register_axes() { register_axes(Axes<D>::uid, Axes<D>::names); } #endif static CXX_OPTIONAL_NAMESPACE::optional<A> axes(const std::string& uid); #ifdef HYPERION_USE_HDF5 static CXX_OPTIONAL_NAMESPACE::optional<std::string> match_axes_datatype(hid_t hid); #endif // HYPERION_USE_HDF5 static bool in_range(const std::string& uid, const std::vector<int> xs); private: static std::unordered_map<std::string, A> axes_; }; HYPERION_EXPORT Legion::FieldID add_field( TypeTag datatype, Legion::FieldAllocator fa, Legion::FieldID field_id = AUTO_GENERATE_ID); template <> struct DataType<HYPERION_TYPE_BOOL> { typedef bool ValueType; constexpr static const char* s = "bool"; constexpr static int id = static_cast<int>(HYPERION_TYPE_BOOL); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_BOOL_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_BOOL_REDOP; #ifdef HYPERION_USE_CASACORE typedef casacore::Bool CasacoreType; constexpr static casacore::DataType CasacoreTypeTag = casacore::DataType::TpBool; constexpr static casacore::DataType CasacoreArrayTypeTag = casacore::DataType::TpArrayBool; static void from_casacore(ValueType& v, const CasacoreType& c) { v = c; } #endif #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::BOOL_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_CHAR> { typedef char ValueType; constexpr static const char* s = "char"; constexpr static int id = static_cast<int>(HYPERION_TYPE_CHAR); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_CHAR_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_CHAR_REDOP; #ifdef HYPERION_USE_CASACORE typedef casacore::Char CasacoreType; constexpr static casacore::DataType CasacoreTypeTag = casacore::DataType::TpChar; constexpr static casacore::DataType CasacoreArrayTypeTag = casacore::DataType::TpArrayChar; static void from_casacore(ValueType& v, const CasacoreType& c) { v = c; } #endif #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::CHAR_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_UCHAR> { typedef unsigned char ValueType; constexpr static const char* s = "uChar"; constexpr static int id = static_cast<int>(HYPERION_TYPE_UCHAR); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_UCHAR_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_UCHAR_REDOP; #ifdef HYPERION_USE_CASACORE typedef casacore::uChar CasacoreType; constexpr static casacore::DataType CasacoreTypeTag = casacore::DataType::TpUChar; constexpr static casacore::DataType CasacoreArrayTypeTag = casacore::DataType::TpArrayUChar; static void from_casacore(ValueType& v, const CasacoreType& c) { v = c; } #endif #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::UCHAR_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_SHORT> { typedef short ValueType; constexpr static const char* s = "short"; constexpr static int id = static_cast<int>(HYPERION_TYPE_SHORT); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_SHORT_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_SHORT_REDOP; #ifdef HYPERION_USE_CASACORE typedef casacore::Short CasacoreType; constexpr static casacore::DataType CasacoreTypeTag = casacore::DataType::TpShort; constexpr static casacore::DataType CasacoreArrayTypeTag = casacore::DataType::TpArrayShort; static void from_casacore(ValueType& v, const CasacoreType& c) { v = c; } #endif #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::SHORT_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_USHORT> { typedef unsigned short ValueType; constexpr static const char* s = "uShort"; constexpr static int id = static_cast<int>(HYPERION_TYPE_USHORT); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_USHORT_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_USHORT_REDOP; #ifdef HYPERION_USE_CASACORE typedef casacore::uShort CasacoreType; constexpr static casacore::DataType CasacoreTypeTag = casacore::DataType::TpUShort; constexpr static casacore::DataType CasacoreArrayTypeTag = casacore::DataType::TpArrayUShort; static void from_casacore(ValueType& v, const CasacoreType& c) { v = c; } #endif #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::USHORT_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_INT> { typedef int ValueType; constexpr static const char* s = "int"; constexpr static int id = static_cast<int>(HYPERION_TYPE_INT); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_INT_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_INT_REDOP; #ifdef HYPERION_USE_CASACORE typedef casacore::Int CasacoreType; constexpr static casacore::DataType CasacoreTypeTag = casacore::DataType::TpInt; constexpr static casacore::DataType CasacoreArrayTypeTag = casacore::DataType::TpArrayInt; static void from_casacore(ValueType& v, const CasacoreType& c) { v = c; } #endif #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::INT_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_UINT> { typedef unsigned int ValueType; constexpr static const char* s = "uInt"; constexpr static int id = static_cast<int>(HYPERION_TYPE_UINT); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_UINT_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_UINT_REDOP; #ifdef HYPERION_USE_CASACORE typedef casacore::uInt CasacoreType; constexpr static casacore::DataType CasacoreTypeTag = casacore::DataType::TpUInt; constexpr static casacore::DataType CasacoreArrayTypeTag = casacore::DataType::TpArrayUInt; static void from_casacore(ValueType& v, const CasacoreType& c) { v = c; } #endif #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::UINT_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_FLOAT> { typedef float ValueType; constexpr static const char* s = "float"; constexpr static int id = static_cast<int>(HYPERION_TYPE_FLOAT); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_FLOAT_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_FLOAT_REDOP; #ifdef HYPERION_USE_CASACORE typedef casacore::Float CasacoreType; constexpr static casacore::DataType CasacoreTypeTag = casacore::DataType::TpFloat; constexpr static casacore::DataType CasacoreArrayTypeTag = casacore::DataType::TpArrayFloat; static void from_casacore(ValueType& v, const CasacoreType& c) { v = c; } #endif #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::FLOAT_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_DOUBLE> { typedef double ValueType; constexpr static const char* s = "double"; constexpr static int id = static_cast<int>(HYPERION_TYPE_DOUBLE); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_DOUBLE_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_DOUBLE_REDOP; #ifdef HYPERION_USE_CASACORE typedef casacore::Double CasacoreType; constexpr static casacore::DataType CasacoreTypeTag = casacore::DataType::TpDouble; constexpr static casacore::DataType CasacoreArrayTypeTag = casacore::DataType::TpArrayDouble; static void from_casacore(ValueType& v, const CasacoreType& c) { v = c; } #endif #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::DOUBLE_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_COMPLEX> { typedef complex<float> ValueType; constexpr static const char* s = "complex"; constexpr static int id = static_cast<int>(HYPERION_TYPE_COMPLEX); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_COMPLEX_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_COMPLEX_REDOP; #ifdef HYPERION_USE_CASACORE typedef casacore::Complex CasacoreType; constexpr static casacore::DataType CasacoreTypeTag = casacore::DataType::TpComplex; constexpr static casacore::DataType CasacoreArrayTypeTag = casacore::DataType::TpArrayComplex; static void from_casacore(ValueType& v, const CasacoreType& c) { v = c; } #endif #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::COMPLEX_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_DCOMPLEX> { typedef complex<double> ValueType; constexpr static const char* s = "dComplex"; constexpr static int id = static_cast<int>(HYPERION_TYPE_DCOMPLEX); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_DCOMPLEX_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_DCOMPLEX_REDOP; #ifdef HYPERION_USE_CASACORE typedef casacore::DComplex CasacoreType; constexpr static casacore::DataType CasacoreTypeTag = casacore::DataType::TpDComplex; constexpr static casacore::DataType CasacoreArrayTypeTag = casacore::DataType::TpArrayDComplex; static void from_casacore(ValueType& v, const CasacoreType& c) { v = c; } #endif #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::DCOMPLEX_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_STRING> { typedef hyperion::string ValueType; constexpr static const char* s = "string"; constexpr static int id = static_cast<int>(HYPERION_TYPE_STRING); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_STRING_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_STRING_REDOP; #ifdef HYPERION_USE_CASACORE typedef casacore::String CasacoreType; constexpr static casacore::DataType CasacoreTypeTag = casacore::DataType::TpString; constexpr static casacore::DataType CasacoreArrayTypeTag = casacore::DataType::TpArrayString; static void from_casacore(ValueType& v, const CasacoreType& c) { fstrcpy(v.val, c); } #endif #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::STRING_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return std::strcmp(a.val, b.val) == 0; } }; template <> struct DataType<HYPERION_TYPE_RECT2> { typedef Legion::Rect<2> ValueType; constexpr static const char* s = "rect2"; constexpr static int id = static_cast<int>(HYPERION_TYPE_RECT2); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_RECT2_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_RECT2_REDOP; #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::RECT2_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_RECT3> { typedef Legion::Rect<3> ValueType; constexpr static const char* s = "rect3"; constexpr static int id = static_cast<int>(HYPERION_TYPE_RECT3); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_RECT3_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_RECT3_REDOP; #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::RECT3_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_STOKES> { typedef stokes_t ValueType; constexpr static const char* s = "stokes"; constexpr static int id = static_cast<int>(HYPERION_TYPE_STOKES); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_STOKES_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_STOKES_REDOP; #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::STOKES_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; template <> struct DataType<HYPERION_TYPE_STOKES_PAIR> { // I'd prefer to use std::pair or std::tuple but they are not copy assignable, // which is an issue in the acc_field_redop implementation above typedef std::array<stokes_t, 2> ValueType; constexpr static const char* s = "stokes_pair"; constexpr static int id = static_cast<int>(HYPERION_TYPE_STOKES_PAIR); constexpr static size_t serdez_size = sizeof(ValueType); constexpr static int af_serdez_id = OpsManager::ACC_FIELD_STOKES_PAIR_SID; constexpr static int af_redop_id = OpsManager::ACC_FIELD_STOKES_PAIR_REDOP; #ifdef HYPERION_USE_HDF5 constexpr static hid_t h5t_id = H5DatatypeManager::STOKES_PAIR_H5T; #endif static bool equiv(const ValueType& a, const ValueType& b) { return a == b; } }; #ifdef HYPERION_USE_HDF5 template <TypeTag DT> constexpr hid_t H5DatatypeManager::datatype() { return datatypes()[DataType<DT>::h5t_id]; } #endif #define HYPERION_FOREACH_CC_DATATYPE(__func__) \ __func__(HYPERION_TYPE_BOOL) \ __func__(HYPERION_TYPE_CHAR) \ __func__(HYPERION_TYPE_UCHAR) \ __func__(HYPERION_TYPE_SHORT) \ __func__(HYPERION_TYPE_USHORT) \ __func__(HYPERION_TYPE_INT) \ __func__(HYPERION_TYPE_UINT) \ __func__(HYPERION_TYPE_FLOAT) \ __func__(HYPERION_TYPE_DOUBLE) \ __func__(HYPERION_TYPE_COMPLEX) \ __func__(HYPERION_TYPE_DCOMPLEX) \ __func__(HYPERION_TYPE_STRING) #ifdef HYPERION_USE_CASACORE #define HYPERION_FOREACH_DATATYPE(__func__)\ HYPERION_FOREACH_CC_DATATYPE(__func__) \ __func__(HYPERION_TYPE_RECT2) \ __func__(HYPERION_TYPE_RECT3) \ __func__(HYPERION_TYPE_STOKES) \ __func__(HYPERION_TYPE_STOKES_PAIR) #else #define HYPERION_FOREACH_DATATYPE(__func__) \ HYPERION_FOREACH_CC_DATATYPE(__func__) \ __func__(HYPERION_TYPE_RECT2) \ __func__(HYPERION_TYPE_RECT3) \ __func__(HYPERION_TYPE_STOKES_PAIR) #endif #define HYPERION_FOREACH_CC_RECORD_DATATYPE(__func__) \ __func__(HYPERION_TYPE_BOOL) \ __func__(HYPERION_TYPE_UCHAR) \ __func__(HYPERION_TYPE_SHORT) \ __func__(HYPERION_TYPE_INT) \ __func__(HYPERION_TYPE_UINT) \ __func__(HYPERION_TYPE_FLOAT) \ __func__(HYPERION_TYPE_DOUBLE) \ __func__(HYPERION_TYPE_COMPLEX) \ __func__(HYPERION_TYPE_DCOMPLEX) \ __func__(HYPERION_TYPE_STRING) template <typename T> struct ValueType { // constexpr static const TypeTag DataType; }; #define VT(dt) \ template <> \ struct ValueType<DataType<dt>::ValueType> { \ constexpr static const TypeTag DataType = dt; \ }; HYPERION_FOREACH_DATATYPE(VT) #undef VT struct HYPERION_EXPORT AxisPartition { string axes_uid; int dim; // stride between start of partition sub-spaces Legion::coord_t stride; // offset of start of first partition Legion::coord_t offset; // extent of partition std::array<Legion::coord_t, 2> extent; // axis limits std::array<Legion::coord_t, 2> limits; bool operator==(const AxisPartition& other) const { // limits values is not compared, as it depends only on value of dim return axes_uid == other.axes_uid && dim == other.dim && stride == other.stride && offset == other.offset && extent == other.extent; } bool operator!=(const AxisPartition& other) const { return !operator==(other); } bool operator<(const AxisPartition& other) const { if (axes_uid != other.axes_uid) return false; if (dim < other.dim) return true; if (dim == other.dim) { if (stride < other.stride) return true; if (stride == other.stride) { if (offset < other.offset) return true; if (offset == other.offset) return extent < other.extent; } } return false; } }; HYPERION_EXPORT Legion::LayoutConstraintRegistrar& add_right_layout_constraint( Legion::LayoutConstraintRegistrar& lc, unsigned rank); HYPERION_EXPORT void register_mapper( Legion::Machine machine, Legion::Runtime* rt, const std::set<Legion::Processor>& local_procs); HYPERION_EXPORT void preregister_all(); HYPERION_EXPORT void add_soa_right_ordering_constraint(Legion::LayoutConstraintRegistrar& reg); HYPERION_EXPORT void add_soa_left_ordering_constraint(Legion::LayoutConstraintRegistrar& reg); HYPERION_EXPORT void add_aos_right_ordering_constraint(Legion::LayoutConstraintRegistrar& reg); HYPERION_EXPORT void add_aos_left_ordering_constraint(Legion::LayoutConstraintRegistrar& reg); HYPERION_EXPORT extern Legion::MapperID table_mapper; HYPERION_EXPORT extern Legion::LayoutConstraintID soa_right_layout; HYPERION_EXPORT extern Legion::LayoutConstraintID soa_left_layout; HYPERION_EXPORT extern Legion::LayoutConstraintID aos_right_layout; HYPERION_EXPORT extern Legion::LayoutConstraintID aos_left_layout; #if LEGION_MAX_DIM == 1 #define HYPERION_FOREACH_N(__func__) \ __func__(1) #define HYPERION_FOREACH_NN(__func__) \ __func__(1,1) #define HYPERION_FOREACH_MN(__func__) \ __func__(1,1) #define HYPERION_FOREACH_LMN(__func__) \ __func__(1,1,1) #define HYPERION_FOREACH_LESS_MAX_N(__func__) #elif LEGION_MAX_DIM == 2 #define HYPERION_FOREACH_N(__func__) \ __func__(1) \ __func__(2) #define HYPERION_FOREACH_NN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(2,1) \ __func__(2,2) #define HYPERION_FOREACH_MN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(2,2) #define HYPERION_FOREACH_LMN(__func__) \ __func__(1,1,1) \ __func__(1,1,2) \ __func__(1,2,2) \ __func__(2,2,2) #define HYPERION_FOREACH_N_LESS_MAX(__func__) \ __func__(1) #elif LEGION_MAX_DIM == 3 #define HYPERION_FOREACH_N(__func__) \ __func__(1) \ __func__(2) \ __func__(3) #define HYPERION_FOREACH_NN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(2,1) \ __func__(2,2) \ __func__(2,3) \ __func__(3,1) \ __func__(3,2) \ __func__(3,3) #define HYPERION_FOREACH_MN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(2,2) \ __func__(2,3) \ __func__(3,3) #define HYPERION_FOREACH_LMN(__func__) \ __func__(1,1,1) \ __func__(1,1,2) \ __func__(1,1,3) \ __func__(1,2,2) \ __func__(2,2,2) \ __func__(1,2,3) \ __func__(2,2,3) \ __func__(1,3,3) \ __func__(2,3,3) \ __func__(3,3,3) #define HYPERION_FOREACH_N_LESS_MAX(__func__) \ __func__(1) \ __func__(2) #elif LEGION_MAX_DIM == 4 #define HYPERION_FOREACH_N(__func__) \ __func__(1) \ __func__(2) \ __func__(3) \ __func__(4) #define HYPERION_FOREACH_NN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(1,4) \ __func__(2,1) \ __func__(2,2) \ __func__(2,3) \ __func__(2,4) \ __func__(3,1) \ __func__(3,2) \ __func__(3,3) \ __func__(3,4) \ __func__(4,1) \ __func__(4,2) \ __func__(4,3) \ __func__(4,4) #define HYPERION_FOREACH_MN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(1,4) \ __func__(2,2) \ __func__(2,3) \ __func__(2,4) \ __func__(3,3) \ __func__(3,4) \ __func__(4,4) #define HYPERION_FOREACH_LMN(__func__) \ __func__(1,1,1) \ __func__(1,1,2) \ __func__(1,1,3) \ __func__(1,1,4) \ __func__(1,2,2) \ __func__(2,2,2) \ __func__(1,2,3) \ __func__(2,2,3) \ __func__(1,2,4) \ __func__(2,2,4) \ __func__(1,3,3) \ __func__(2,3,3) \ __func__(3,3,3) \ __func__(1,3,4) \ __func__(2,3,4) \ __func__(3,3,4) \ __func__(1,4,4) \ __func__(2,4,4) \ __func__(3,4,4) \ __func__(4,4,4) #define HYPERION_FOREACH_N_LESS_MAX(__func__) \ __func__(1) \ __func__(2) \ __func__(3) #elif LEGION_MAX_DIM == 5 #define HYPERION_FOREACH_N(__func__) \ __func__(1) \ __func__(2) \ __func__(3) \ __func__(4) \ __func__(5) #define HYPERION_FOREACH_NN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(1,4) \ __func__(1,5) \ __func__(2,1) \ __func__(2,2) \ __func__(2,3) \ __func__(2,4) \ __func__(2,5) \ __func__(3,1) \ __func__(3,2) \ __func__(3,3) \ __func__(3,4) \ __func__(3,5) \ __func__(4,1) \ __func__(4,2) \ __func__(4,3) \ __func__(4,4) \ __func__(4,5) \ __func__(5,1) \ __func__(5,2) \ __func__(5,3) \ __func__(5,4) \ __func__(5,5) #define HYPERION_FOREACH_MN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(1,4) \ __func__(1,5) \ __func__(2,2) \ __func__(2,3) \ __func__(2,4) \ __func__(2,5) \ __func__(3,3) \ __func__(3,4) \ __func__(3,5) \ __func__(4,4) \ __func__(4,5) \ __func__(5,5) #define HYPERION_FOREACH_LMN(__func__) \ __func__(1,1,1) \ __func__(1,1,2) \ __func__(1,1,3) \ __func__(1,1,4) \ __func__(1,1,5) \ __func__(1,2,2) \ __func__(2,2,2) \ __func__(1,2,3) \ __func__(2,2,3) \ __func__(1,2,4) \ __func__(2,2,4) \ __func__(1,2,5) \ __func__(2,2,5) \ __func__(1,3,3) \ __func__(2,3,3) \ __func__(3,3,3) \ __func__(1,3,4) \ __func__(2,3,4) \ __func__(3,3,4) \ __func__(1,3,5) \ __func__(2,3,5) \ __func__(3,3,5) \ __func__(1,4,4) \ __func__(2,4,4) \ __func__(3,4,4) \ __func__(4,4,4) \ __func__(1,4,5) \ __func__(2,4,5) \ __func__(3,4,5) \ __func__(4,4,5) \ __func__(1,5,5) \ __func__(2,5,5) \ __func__(3,5,5) \ __func__(4,5,5) \ __func__(5,5,5) #define HYPERION_FOREACH_N_LESS_MAX(__func__) \ __func__(1) \ __func__(2) \ __func__(3) \ __func__(4) #elif LEGION_MAX_DIM == 6 #define HYPERION_FOREACH_N(__func__) \ __func__(1) \ __func__(2) \ __func__(3) \ __func__(4) \ __func__(5) \ __func__(6) #define HYPERION_FOREACH_NN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(1,4) \ __func__(1,5) \ __func__(1,6) \ __func__(2,1) \ __func__(2,2) \ __func__(2,3) \ __func__(2,4) \ __func__(2,5) \ __func__(2,6) \ __func__(3,1) \ __func__(3,2) \ __func__(3,3) \ __func__(3,4) \ __func__(3,5) \ __func__(3,6) \ __func__(4,1) \ __func__(4,2) \ __func__(4,3) \ __func__(4,4) \ __func__(4,5) \ __func__(4,6) \ __func__(5,1) \ __func__(5,2) \ __func__(5,3) \ __func__(5,4) \ __func__(5,5) \ __func__(5,6) \ __func__(6,1) \ __func__(6,2) \ __func__(6,3) \ __func__(6,4) \ __func__(6,5) \ __func__(6,6) #define HYPERION_FOREACH_MN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(1,4) \ __func__(1,5) \ __func__(1,6) \ __func__(2,2) \ __func__(2,3) \ __func__(2,4) \ __func__(2,5) \ __func__(2,6) \ __func__(3,3) \ __func__(3,4) \ __func__(3,5) \ __func__(3,6) \ __func__(4,4) \ __func__(4,5) \ __func__(4,6) \ __func__(5,5) \ __func__(5,6) \ __func__(6,6) #define HYPERION_FOREACH_LMN(__func__) \ __func__(1,1,1) \ __func__(1,1,2) \ __func__(1,1,3) \ __func__(1,1,4) \ __func__(1,1,5) \ __func__(1,1,6) \ __func__(1,2,2) \ __func__(2,2,2) \ __func__(1,2,3) \ __func__(2,2,3) \ __func__(1,2,4) \ __func__(2,2,4) \ __func__(1,2,5) \ __func__(2,2,5) \ __func__(1,2,6) \ __func__(2,2,6) \ __func__(1,3,3) \ __func__(2,3,3) \ __func__(3,3,3) \ __func__(1,3,4) \ __func__(2,3,4) \ __func__(3,3,4) \ __func__(1,3,5) \ __func__(2,3,5) \ __func__(3,3,5) \ __func__(1,3,6) \ __func__(2,3,6) \ __func__(3,3,6) \ __func__(1,4,4) \ __func__(2,4,4) \ __func__(3,4,4) \ __func__(4,4,4) \ __func__(1,4,5) \ __func__(2,4,5) \ __func__(3,4,5) \ __func__(4,4,5) \ __func__(4,4,6) \ __func__(1,5,5) \ __func__(2,5,5) \ __func__(3,5,5) \ __func__(4,5,5) \ __func__(5,5,5) \ __func__(5,5,6) \ __func__(1,6,6) \ __func__(2,6,6) \ __func__(3,6,6) \ __func__(4,6,6) \ __func__(5,6,6) \ __func__(6,6,6) #define HYPERION_FOREACH_N_LESS_MAX(__func__) \ __func__(1) \ __func__(2) \ __func__(3) \ __func__(4) \ __func__(5) #elif LEGION_MAX_DIM == 7 #define HYPERION_FOREACH_N(__func__) \ __func__(1) \ __func__(2) \ __func__(3) \ __func__(4) \ __func__(5) \ __func__(6) \ __func__(7) #define HYPERION_FOREACH_NN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(1,4) \ __func__(1,5) \ __func__(1,6) \ __func__(1,7) \ __func__(2,1) \ __func__(2,2) \ __func__(2,3) \ __func__(2,4) \ __func__(2,5) \ __func__(2,6) \ __func__(2,7) \ __func__(3,1) \ __func__(3,2) \ __func__(3,3) \ __func__(3,4) \ __func__(3,5) \ __func__(3,6) \ __func__(3,7) \ __func__(4,1) \ __func__(4,2) \ __func__(4,3) \ __func__(4,4) \ __func__(4,5) \ __func__(4,6) \ __func__(4,7) \ __func__(5,1) \ __func__(5,2) \ __func__(5,3) \ __func__(5,4) \ __func__(5,5) \ __func__(5,6) \ __func__(5,7) \ __func__(6,1) \ __func__(6,2) \ __func__(6,3) \ __func__(6,4) \ __func__(6,5) \ __func__(6,6) \ __func__(6,7) \ __func__(7,1) \ __func__(7,2) \ __func__(7,3) \ __func__(7,4) \ __func__(7,5) \ __func__(7,6) \ __func__(7,7) #define HYPERION_FOREACH_MN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(1,4) \ __func__(1,5) \ __func__(1,6) \ __func__(1,7) \ __func__(2,2) \ __func__(2,3) \ __func__(2,4) \ __func__(2,5) \ __func__(2,6) \ __func__(2,7) \ __func__(3,3) \ __func__(3,4) \ __func__(3,5) \ __func__(3,6) \ __func__(3,7) \ __func__(4,4) \ __func__(4,5) \ __func__(4,6) \ __func__(4,7) \ __func__(5,5) \ __func__(5,6) \ __func__(5,7) \ __func__(6,6) \ __func__(6,7) \ __func__(7,7) #define HYPERION_FOREACH_LMN(__func__) \ __func__(1,1,1) \ __func__(1,1,2) \ __func__(1,1,3) \ __func__(1,1,4) \ __func__(1,1,5) \ __func__(1,1,6) \ __func__(1,1,7) \ __func__(1,2,2) \ __func__(2,2,2) \ __func__(1,2,3) \ __func__(2,2,3) \ __func__(1,2,4) \ __func__(2,2,4) \ __func__(1,2,5) \ __func__(2,2,5) \ __func__(1,2,6) \ __func__(2,2,6) \ __func__(1,2,7) \ __func__(2,2,7) \ __func__(1,3,3) \ __func__(2,3,3) \ __func__(3,3,3) \ __func__(1,3,4) \ __func__(2,3,4) \ __func__(3,3,4) \ __func__(1,3,5) \ __func__(2,3,5) \ __func__(3,3,5) \ __func__(1,3,6) \ __func__(2,3,6) \ __func__(3,3,6) \ __func__(1,3,7) \ __func__(2,3,7) \ __func__(3,3,7) \ __func__(1,4,4) \ __func__(2,4,4) \ __func__(3,4,4) \ __func__(4,4,4) \ __func__(1,4,5) \ __func__(2,4,5) \ __func__(3,4,5) \ __func__(4,4,5) \ __func__(1,4,6) \ __func__(2,4,6) \ __func__(3,4,6) \ __func__(4,4,6) \ __func__(1,4,7) \ __func__(2,4,7) \ __func__(3,4,7) \ __func__(4,4,7) \ __func__(1,5,5) \ __func__(2,5,5) \ __func__(3,5,5) \ __func__(4,5,5) \ __func__(5,5,5) \ __func__(1,5,6) \ __func__(2,5,6) \ __func__(3,5,6) \ __func__(4,5,6) \ __func__(5,5,6) \ __func__(1,5,7) \ __func__(2,5,7) \ __func__(3,5,7) \ __func__(4,5,7) \ __func__(5,5,7) \ __func__(1,6,6) \ __func__(2,6,6) \ __func__(3,6,6) \ __func__(4,6,6) \ __func__(5,6,6) \ __func__(6,6,6) \ __func__(1,6,7) \ __func__(2,6,7) \ __func__(3,6,7) \ __func__(4,6,7) \ __func__(5,6,7) \ __func__(6,6,7) \ __func__(1,7,7) \ __func__(2,7,7) \ __func__(3,7,7) \ __func__(4,7,7) \ __func__(5,7,7) \ __func__(6,7,7) \ __func__(7,7,7) #define HYPERION_FOREACH_N_LESS_MAX(__func__) \ __func__(1) \ __func__(2) \ __func__(3) \ __func__(4) \ __func__(5) \ __func__(6) #elif LEGION_MAX_DIM == 8 #define HYPERION_FOREACH_N(__func__) \ __func__(1) \ __func__(2) \ __func__(3) \ __func__(4) \ __func__(5) \ __func__(6) \ __func__(7) \ __func__(8) #define HYPERION_FOREACH_NN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(1,4) \ __func__(1,5) \ __func__(1,6) \ __func__(1,7) \ __func__(1,8) \ __func__(2,1) \ __func__(2,2) \ __func__(2,3) \ __func__(2,4) \ __func__(2,5) \ __func__(2,6) \ __func__(2,7) \ __func__(2,8) \ __func__(3,1) \ __func__(3,2) \ __func__(3,3) \ __func__(3,4) \ __func__(3,5) \ __func__(3,6) \ __func__(3,7) \ __func__(3,8) \ __func__(4,1) \ __func__(4,2) \ __func__(4,3) \ __func__(4,4) \ __func__(4,5) \ __func__(4,6) \ __func__(4,7) \ __func__(4,8) \ __func__(5,1) \ __func__(5,2) \ __func__(5,3) \ __func__(5,4) \ __func__(5,5) \ __func__(5,6) \ __func__(5,7) \ __func__(5,8) \ __func__(6,1) \ __func__(6,2) \ __func__(6,3) \ __func__(6,4) \ __func__(6,5) \ __func__(6,6) \ __func__(6,7) \ __func__(6,8) \ __func__(7,1) \ __func__(7,2) \ __func__(7,3) \ __func__(7,4) \ __func__(7,5) \ __func__(7,6) \ __func__(7,7) \ __func__(7,8) \ __func__(8,1) \ __func__(8,2) \ __func__(8,3) \ __func__(8,4) \ __func__(8,5) \ __func__(8,6) \ __func__(8,7) \ __func__(8,8) #define HYPERION_FOREACH_MN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(1,4) \ __func__(1,5) \ __func__(1,6) \ __func__(1,7) \ __func__(1,8) \ __func__(2,2) \ __func__(2,3) \ __func__(2,4) \ __func__(2,5) \ __func__(2,6) \ __func__(2,7) \ __func__(2,8) \ __func__(3,3) \ __func__(3,4) \ __func__(3,5) \ __func__(3,6) \ __func__(3,7) \ __func__(3,8) \ __func__(4,4) \ __func__(4,5) \ __func__(4,6) \ __func__(4,7) \ __func__(4,8) \ __func__(5,5) \ __func__(5,6) \ __func__(5,7) \ __func__(5,8) \ __func__(6,6) \ __func__(6,7) \ __func__(6,8) \ __func__(7,7) \ __func__(7,8) \ __func__(8,8) #define HYPERION_FOREACH_LMN(__func__) \ __func__(1,1,1) \ __func__(1,1,2) \ __func__(1,1,3) \ __func__(1,1,4) \ __func__(1,1,5) \ __func__(1,1,6) \ __func__(1,1,7) \ __func__(1,1,8) \ __func__(1,2,2) \ __func__(2,2,2) \ __func__(1,2,3) \ __func__(2,2,3) \ __func__(1,2,4) \ __func__(2,2,4) \ __func__(1,2,5) \ __func__(2,2,5) \ __func__(1,2,6) \ __func__(2,2,6) \ __func__(1,2,7) \ __func__(2,2,7) \ __func__(1,2,8) \ __func__(2,2,8) \ __func__(1,3,3) \ __func__(2,3,3) \ __func__(3,3,3) \ __func__(1,3,4) \ __func__(2,3,4) \ __func__(3,3,4) \ __func__(1,3,5) \ __func__(2,3,5) \ __func__(3,3,5) \ __func__(1,3,6) \ __func__(2,3,6) \ __func__(3,3,6) \ __func__(1,3,7) \ __func__(2,3,7) \ __func__(3,3,7) \ __func__(1,3,8) \ __func__(2,3,8) \ __func__(3,3,8) \ __func__(1,4,4) \ __func__(2,4,4) \ __func__(3,4,4) \ __func__(4,4,4) \ __func__(1,4,5) \ __func__(2,4,5) \ __func__(3,4,5) \ __func__(4,4,5) \ __func__(1,4,6) \ __func__(2,4,6) \ __func__(3,4,6) \ __func__(4,4,6) \ __func__(1,4,7) \ __func__(2,4,7) \ __func__(3,4,7) \ __func__(4,4,7) \ __func__(1,4,8) \ __func__(2,4,8) \ __func__(3,4,8) \ __func__(4,4,8) \ __func__(1,5,5) \ __func__(2,5,5) \ __func__(3,5,5) \ __func__(4,5,5) \ __func__(5,5,5) \ __func__(1,5,6) \ __func__(2,5,6) \ __func__(3,5,6) \ __func__(4,5,6) \ __func__(5,5,6) \ __func__(1,5,7) \ __func__(2,5,7) \ __func__(3,5,7) \ __func__(4,5,7) \ __func__(5,5,7) \ __func__(1,5,8) \ __func__(2,5,8) \ __func__(3,5,8) \ __func__(4,5,8) \ __func__(5,5,8) \ __func__(1,6,6) \ __func__(2,6,6) \ __func__(3,6,6) \ __func__(4,6,6) \ __func__(5,6,6) \ __func__(6,6,6) \ __func__(1,6,7) \ __func__(2,6,7) \ __func__(3,6,7) \ __func__(4,6,7) \ __func__(5,6,7) \ __func__(6,6,7) \ __func__(1,6,8) \ __func__(2,6,8) \ __func__(3,6,8) \ __func__(4,6,8) \ __func__(5,6,8) \ __func__(6,6,8) \ __func__(1,7,7) \ __func__(2,7,7) \ __func__(3,7,7) \ __func__(4,7,7) \ __func__(5,7,7) \ __func__(6,7,7) \ __func__(7,7,7) \ __func__(1,7,8) \ __func__(2,7,8) \ __func__(3,7,8) \ __func__(4,7,8) \ __func__(5,7,8) \ __func__(6,7,8) \ __func__(7,7,8) \ __func__(1,8,8) \ __func__(2,8,8) \ __func__(3,8,8) \ __func__(4,8,8) \ __func__(5,8,8) \ __func__(6,8,8) \ __func__(7,8,8) \ __func__(8,8,8) #define HYPERION_FOREACH_N_LESS_MAX(__func__) \ __func__(1) \ __func__(2) \ __func__(3) \ __func__(4) \ __func__(5) \ __func__(6) \ __func__(7) #elif LEGION_MAX_DIM == 9 #define HYPERION_FOREACH_N(__func__) \ __func__(1) \ __func__(2) \ __func__(3) \ __func__(4) \ __func__(5) \ __func__(6) \ __func__(7) \ __func__(8) \ __func__(9) #define HYPERION_FOREACH_NN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(1,4) \ __func__(1,5) \ __func__(1,6) \ __func__(1,7) \ __func__(1,8) \ __func__(1,9) \ __func__(2,1) \ __func__(2,2) \ __func__(2,3) \ __func__(2,4) \ __func__(2,5) \ __func__(2,6) \ __func__(2,7) \ __func__(2,8) \ __func__(2,9) \ __func__(3,1) \ __func__(3,2) \ __func__(3,3) \ __func__(3,4) \ __func__(3,5) \ __func__(3,6) \ __func__(3,7) \ __func__(3,8) \ __func__(3,9) \ __func__(4,1) \ __func__(4,2) \ __func__(4,3) \ __func__(4,4) \ __func__(4,5) \ __func__(4,6) \ __func__(4,7) \ __func__(4,8) \ __func__(4,9) \ __func__(5,1) \ __func__(5,2) \ __func__(5,3) \ __func__(5,4) \ __func__(5,5) \ __func__(5,6) \ __func__(5,7) \ __func__(5,8) \ __func__(5,9) \ __func__(6,1) \ __func__(6,2) \ __func__(6,3) \ __func__(6,4) \ __func__(6,5) \ __func__(6,6) \ __func__(6,7) \ __func__(6,8) \ __func__(6,9) \ __func__(7,1) \ __func__(7,2) \ __func__(7,3) \ __func__(7,4) \ __func__(7,5) \ __func__(7,6) \ __func__(7,7) \ __func__(7,8) \ __func__(7,9) \ __func__(8,1) \ __func__(8,2) \ __func__(8,3) \ __func__(8,4) \ __func__(8,5) \ __func__(8,6) \ __func__(8,7) \ __func__(8,8) \ __func__(8,9) \ __func__(9,1) \ __func__(9,2) \ __func__(9,3) \ __func__(9,4) \ __func__(9,5) \ __func__(9,6) \ __func__(9,7) \ __func__(9,8) \ __func__(9,9) #define HYPERION_FOREACH_MN(__func__) \ __func__(1,1) \ __func__(1,2) \ __func__(1,3) \ __func__(1,4) \ __func__(1,5) \ __func__(1,6) \ __func__(1,7) \ __func__(1,8) \ __func__(1,9) \ __func__(2,2) \ __func__(2,3) \ __func__(2,4) \ __func__(2,5) \ __func__(2,6) \ __func__(2,7) \ __func__(2,8) \ __func__(2,9) \ __func__(3,3) \ __func__(3,4) \ __func__(3,5) \ __func__(3,6) \ __func__(3,7) \ __func__(3,8) \ __func__(3,9) \ __func__(4,4) \ __func__(4,5) \ __func__(4,6) \ __func__(4,7) \ __func__(4,8) \ __func__(4,9) \ __func__(5,5) \ __func__(5,6) \ __func__(5,7) \ __func__(5,8) \ __func__(5,9) \ __func__(6,6) \ __func__(6,7) \ __func__(6,8) \ __func__(6,9) \ __func__(7,7) \ __func__(7,8) \ __func__(7,9) \ __func__(8,8) \ __func__(8,9) \ __func__(9,9) #define HYPERION_FOREACH_LMN(__func__) \ __func__(1,1,1) \ __func__(1,1,2) \ __func__(1,1,3) \ __func__(1,1,4) \ __func__(1,1,5) \ __func__(1,1,6) \ __func__(1,1,7) \ __func__(1,1,8) \ __func__(1,1,9) \ __func__(1,2,2) \ __func__(2,2,2) \ __func__(1,2,3) \ __func__(2,2,3) \ __func__(1,2,4) \ __func__(2,2,4) \ __func__(1,2,5) \ __func__(2,2,5) \ __func__(1,2,6) \ __func__(2,2,6) \ __func__(1,2,7) \ __func__(2,2,7) \ __func__(1,2,8) \ __func__(2,2,8) \ __func__(1,2,9) \ __func__(2,2,9) \ __func__(1,3,3) \ __func__(2,3,3) \ __func__(3,3,3) \ __func__(1,3,4) \ __func__(2,3,4) \ __func__(3,3,4) \ __func__(1,3,5) \ __func__(2,3,5) \ __func__(3,3,5) \ __func__(1,3,6) \ __func__(2,3,6) \ __func__(3,3,6) \ __func__(1,3,7) \ __func__(2,3,7) \ __func__(3,3,7) \ __func__(1,3,8) \ __func__(2,3,8) \ __func__(3,3,8) \ __func__(1,3,9) \ __func__(2,3,9) \ __func__(3,3,9) \ __func__(1,4,4) \ __func__(2,4,4) \ __func__(3,4,4) \ __func__(4,4,4) \ __func__(1,4,5) \ __func__(2,4,5) \ __func__(3,4,5) \ __func__(4,4,5) \ __func__(1,4,6) \ __func__(2,4,6) \ __func__(3,4,6) \ __func__(4,4,6) \ __func__(1,4,7) \ __func__(2,4,7) \ __func__(3,4,7) \ __func__(4,4,7) \ __func__(1,4,8) \ __func__(2,4,8) \ __func__(3,4,8) \ __func__(4,4,8) \ __func__(1,4,9) \ __func__(2,4,9) \ __func__(3,4,9) \ __func__(4,4,9) \ __func__(1,5,5) \ __func__(2,5,5) \ __func__(3,5,5) \ __func__(4,5,5) \ __func__(5,5,5) \ __func__(1,5,6) \ __func__(2,5,6) \ __func__(3,5,6) \ __func__(4,5,6) \ __func__(5,5,6) \ __func__(1,5,7) \ __func__(2,5,7) \ __func__(3,5,7) \ __func__(4,5,7) \ __func__(5,5,7) \ __func__(1,5,8) \ __func__(2,5,8) \ __func__(3,5,8) \ __func__(4,5,8) \ __func__(5,5,8) \ __func__(1,5,9) \ __func__(2,5,9) \ __func__(3,5,9) \ __func__(4,5,9) \ __func__(5,5,9) \ __func__(1,6,6) \ __func__(2,6,6) \ __func__(3,6,6) \ __func__(4,6,6) \ __func__(5,6,6) \ __func__(6,6,6) \ __func__(1,6,7) \ __func__(2,6,7) \ __func__(3,6,7) \ __func__(4,6,7) \ __func__(5,6,7) \ __func__(6,6,7) \ __func__(1,6,8) \ __func__(2,6,8) \ __func__(3,6,8) \ __func__(4,6,8) \ __func__(5,6,8) \ __func__(6,6,8) \ __func__(1,6,9) \ __func__(2,6,9) \ __func__(3,6,9) \ __func__(4,6,9) \ __func__(5,6,9) \ __func__(6,6,9) \ __func__(1,7,7) \ __func__(2,7,7) \ __func__(3,7,7) \ __func__(4,7,7) \ __func__(5,7,7) \ __func__(6,7,7) \ __func__(7,7,7) \ __func__(1,7,8) \ __func__(2,7,8) \ __func__(3,7,8) \ __func__(4,7,8) \ __func__(5,7,8) \ __func__(6,7,8) \ __func__(7,7,8) \ __func__(1,7,9) \ __func__(2,7,9) \ __func__(3,7,9) \ __func__(4,7,9) \ __func__(5,7,9) \ __func__(6,7,9) \ __func__(7,7,9) \ __func__(1,8,8) \ __func__(2,8,8) \ __func__(3,8,8) \ __func__(4,8,8) \ __func__(5,8,8) \ __func__(6,8,8) \ __func__(7,8,8) \ __func__(8,8,8) \ __func__(1,8,9) \ __func__(2,8,9) \ __func__(3,8,9) \ __func__(4,8,9) \ __func__(5,8,9) \ __func__(6,8,9) \ __func__(7,8,9) \ __func__(8,8,9) \ __func__(1,9,9) \ __func__(2,9,9) \ __func__(3,9,9) \ __func__(4,9,9) \ __func__(5,9,9) \ __func__(6,9,9) \ __func__(7,9,9) \ __func__(8,9,9) \ __func__(9,9,9) #define HYPERION_FOREACH_N_LESS_MAX(__func__) \ __func__(1) \ __func__(2) \ __func__(3) \ __func__(4) \ __func__(5) \ __func__(6) \ __func__(7) \ __func__(8) #else #error "Unsupported LEGION_MAX_DIM" #endif #define DEFINE_POINT_ADD_REDOP(DIM) \ template <> \ class point_add_redop<DIM> { \ public: \ typedef Legion::Point<DIM> LHS; \ typedef Legion::Point<DIM> RHS; \ \ static const RHS identity; \ \ template <bool EXCL> \ static void \ apply(LHS& lhs, RHS rhs); \ \ template <bool EXCL> \ static void \ fold(RHS& rhs1, RHS rhs2); \ }; \ template <> \ inline void \ point_add_redop<DIM>::apply<true>(LHS& lhs, RHS rhs) { \ lhs += rhs; \ } \ template <> \ inline void \ point_add_redop<DIM>::apply<false>(LHS& lhs, RHS rhs) { \ for (int i = 0; i < DIM; ++i) \ __atomic_fetch_add(&lhs[i], rhs[i], __ATOMIC_ACQUIRE); \ } \ template <> \ inline void \ point_add_redop<DIM>::fold<true>(RHS& rhs1, RHS rhs2) { \ rhs1 += rhs2; \ } \ template <> \ inline void \ point_add_redop<DIM>::fold<false>(RHS& rhs1, RHS rhs2) { \ for (int i = 0; i < DIM; ++i) \ __atomic_fetch_add(&rhs1[i], rhs2[i], __ATOMIC_ACQUIRE); \ } HYPERION_FOREACH_N(DEFINE_POINT_ADD_REDOP); #undef DEFINE_POINT_ADD_REDOP } // end namespace hyperion HYPERION_EXPORT std::ostream& operator<<(std::ostream& stream, const hyperion::string& str); #if !defined(HYPERION_USE_KOKKOS) && !defined(HYPERION_USE_CASACORE) namespace std { template <typename F> HYPERION_EXPORT bool operator<(const complex<F>& a, const complex<F>& b) { if (a.real() < b.real()) return true; if (a.real() > b.real()) return false; return a.imag() < b.imag(); } } #endif // HYPERION_USE_KOKKOS && HYPERION_USE_CASACORE #ifndef HYPERION_USE_KOKKOS namespace std { template <typename S, typename T> HYPERION_EXPORT bool operator<(const pair<S, T>& a, const pair<S, T>& b) { if (a.first < b.first) return true; if (a.first > b.first) return false; return a.second < b.second; } } #endif // !HYPERION_USE_KOKKOS #ifdef HYPERION_USE_KOKKOS namespace Kokkos { template <typename F> HYPERION_INLINE_FUNCTION bool operator<(const complex<F>& a, const complex<F>& b) { if (a.real() < b.real()) return true; if (a.real() > b.real()) return false; return a.imag() < b.imag(); } } #endif // HYPERION_USE_KOKKOS #endif // HYPERION_UTILITY_H_ // Local Variables: // mode: c++ // c-basic-offset: 2 // fill-column: 80 // indent-tabs-mode: nil // End:
35.037838
96
0.453487
[ "vector", "transform" ]
947bdca0f236fac4c4c84efadd18027408996db0
5,408
h
C
src/client/plugin/core/cross/param_cache.h
kripken/intensityengine
9ae352b4f526ecb180004ae4968db7f64f140762
[ "MIT" ]
31
2015-01-18T20:27:31.000Z
2021-07-03T03:58:47.000Z
o3d/core/cross/param_cache.h
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
4
2015-07-05T21:09:37.000Z
2019-09-06T14:34:59.000Z
o3d/core/cross/param_cache.h
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
11
2015-02-03T19:24:10.000Z
2019-09-20T10:59:50.000Z
/* * Copyright 2009, Google Inc. * 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 Google Inc. 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 file contains the declaration of ParamCache. #ifndef O3D_CORE_CROSS_PARAM_CACHE_H_ #define O3D_CORE_CROSS_PARAM_CACHE_H_ #include <vector> #include "core/cross/param_object.h" #include "core/cross/stream_bank.h" namespace o3d { class Element; class Renderer; class Material; class DrawElement; class Effect; // A ParamCache holds on to a specific set of Platform specific shader params // to O3D param cached map to make rendering faster. class ParamCache { public: ParamCache() : rebuild_cache_(true) {} virtual ~ParamCache() {} // Clears any internal Param to Shader Parameter cache. void ClearParamCache(); // Checks if the cache of Params to Effect parameters is valid and if it is // not rebuilds the cache. // Returns true if the cache was valid, false if it was rebuilt. bool ValidateAndCacheParams(Effect* effect, DrawElement* draw_element, Element* element, StreamBank* stream_bank, Material* material, ParamObject* override); // Update the cache of params. virtual void UpdateCache(Effect* effect, DrawElement* draw_element, Element* element, Material* material, ParamObject* override) = 0; protected: // Validates platform specific information about the effect. // Returns: // True if effect and cache are valid. virtual bool ValidateEffect(Effect* effect) = 0; private: // If true we need to rebuild the cache of Params to Shader Parameters. bool rebuild_cache_; // A class to track the change of an object and its parameters. template <typename T, typename TPOINTER> class ChangeTracker { public: ChangeTracker() : last_object_(NULL), last_change_count_(0) { } inline bool NeedToUpdate(TPOINTER object) { return object != last_object_ || (object != NULL && object->change_count() != last_change_count_); } inline void Update(TPOINTER object) { last_object_ = T(object); last_change_count_ = object->change_count(); } private: T last_object_; int last_change_count_; }; // These fields track whether this cache matches a certain set of inputs. ChangeTracker<ParamObject::Ref, ParamObject*> draw_element_tracker_; ChangeTracker<ParamObject::Ref, ParamObject*> element_tracker_; ChangeTracker<ParamObject::Ref, ParamObject*> material_tracker_; ChangeTracker<ParamObject::Ref, ParamObject*> effect_tracker_; ChangeTracker<StreamBank::Ref, StreamBank*> stream_bank_tracker_; ChangeTracker<ParamObject*, ParamObject*> override_tracker_; // NOTE: override_tracker_ has to be a pointer, not a Ref because the cache is // stored inside a Transform and ends up referencing itself making it // unfreeable. Is okay that it's a pointer though because a cache is always // used for by a transform for itself so there is no chance that the // override_tracker's pointer will point to something that was freed. DISALLOW_COPY_AND_ASSIGN(ParamCache); }; // A ParamCacheManager manages an array of ParamCaches. class ParamCacheManager { public: explicit ParamCacheManager(Renderer* renderer); ~ParamCacheManager(); // Returns the next ParamCache // Returns: // The next ParamCache ParamCache* GetNextCache(Renderer* renderer); private: typedef std::vector<ParamCache*> ParamCacheArray; ParamCacheArray param_caches_; unsigned top_cache_index_; // If this does not match the current render count we need to reset // the top cache. int last_render_count_; DISALLOW_COPY_AND_ASSIGN(ParamCacheManager); }; } // namespace o3d #endif // O3D_CORE_CROSS_PARAM_CACHE_H_
34.890323
80
0.713572
[ "render", "object", "vector", "transform" ]
94806a6b9bff2dae6e93225c60d7b6a903710bf2
1,173
c
C
d/deku/open/castle/moat5.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/deku/open/castle/moat5.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/deku/open/castle/moat5.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
// moat5.c // Written by Pator@ShadowGate // Tue Apr 11 05:31:25 1995 #include <castle.h> inherit ROOM; void create() { ::create(); set_terrain(SHALLOW_WATER); set_travel(FOOT_PATH); set_light(2); set_short("In the moat"); set_long( @MOAT5 You are now at the side of the castle. The moat is much deeper here and you have troubles to keep your head above the water. You see a closed iron gate. When you study it more closely you see that it hasn't got a lock, but that it is built into the walls. MOAT5 ); set_smell("default","You smell rotten things from behind the gate. pfffuh !"); set_listen("default","You hear water running."); set_exits(([ "south" : CASTLE+"moat4", "north" : CASTLE+"moat6" ] )); set_items(([ "fish" : "You see no fish in the water and not just because it isn't clear anymore !", "water" : "The water is dirty and smelly here.", "gate" : "The gate is build into the wall and looks very solid." ] )); } // There are some fish here ... ready to be butchered by low-level players void reset() { ::reset(); if(!(present("rat"))) new("/d/shadow/mon/rat")->move(this_object()); }
30.868421
255
0.657289
[ "solid" ]
9485f44f5d74fb79b1d5173ef33a2eb8e403afb0
5,340
h
C
cpp/video/atom.h
google/vr180
f55eaa1c6835b911b7a11830ec546636a16d49da
[ "Apache-2.0" ]
37
2018-12-09T17:58:51.000Z
2022-03-06T11:43:24.000Z
cpp/video/atom.h
google/vr180
f55eaa1c6835b911b7a11830ec546636a16d49da
[ "Apache-2.0" ]
3
2019-05-21T06:01:29.000Z
2022-01-11T09:49:29.000Z
cpp/video/atom.h
google/vr180
f55eaa1c6835b911b7a11830ec546636a16d49da
[ "Apache-2.0" ]
12
2019-05-25T02:18:14.000Z
2022-01-11T09:35:03.000Z
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // This file defines an mp4 Atom abstract base class. // Subclasses of this class are instantiated in AtomFactory. // // In order to do anything meaningful with this library, you need to know a // little bit about the MP4 file format. // // Briefly: // 1) An MP4 file consists of a tree of atoms. // 2) Each MP4 atom consists of a header and payload. // * An atom header consists of a size and an atom_type: // size is the number of bytes in this atom including the header. // atom_type is a std::string tag that differentiates one kind of atom from // another. // * Payload is everything in an atom that isn't the header. If an atom // is known, it knows the difference between the atom-specific data, // and its children. Otherwise, it assumes everything is atom specific // data, and it does not have any chidren. // // See ISO/IEC 14496-12 (MPEG-4 Part 12 specification): goto/iso2012spec // #ifndef VR180_CPP_VIDEO_FORMAT_ATOM_H_ #define VR180_CPP_VIDEO_FORMAT_ATOM_H_ #include <cstdint> #include <functional> #include <memory> #include <string> #include <vector> #include "cpp/video/binary_reader.h" #include "cpp/video/binary_writer.h" #include "cpp/video/format_status.h" namespace vr180 { class Atom { public: // The MP4 spec provides a few ways of defining the size of mp4 objects: // atom objects may have 32bit or 64bit sizes, while descriptor size may // various from 8bits and up to 32bits. typedef uint64_t AtomSize; static const int kIndicateSizeIsToEndOfFile; static const int kIndicateSizeIs64; static const int kSizeOf32bitSize; static const int kSizeOf64bitSize; static const int kAtomTypeSize; static const int kUserTypeSize; static const int kMinSizeofAtomHeader; static const uint64_t kMaxSizeofAtomHeader; Atom(const AtomSize header_size, const AtomSize data_size, const std::string& atom_type); virtual ~Atom() {} // Returns the number of children. int NumChildren() const { return static_cast<int>(children_.size()); } // Adds a new child atom at the end of this atom. void AddChild(std::unique_ptr<Atom> child); // Adds a new child atom at the provided index. void AddChildAt(std::unique_ptr<Atom> child, int i); // Deletes the i-th child atom. Returns the deleted child. std::unique_ptr<Atom> DeleteChild(int i); // Returns a pointer to the i-th child atom. Atom* GetChild(int i) const { return children_[i].get(); } // Eg. "st3d", "proj", etc. const std::string& atom_type() const { return atom_type_; } // Size of the atom header in bytes. AtomSize header_size() const { return header_size_; } // Size of the atom payload in bytes, including the null // terminator if present. AtomSize data_size() const { return data_size_; } // Size of the atom in bytes. AtomSize size() const { return header_size() + data_size(); } // Some atoms may have 4 byte optional null terminator at the end. // Currently known atoms are UDTA and VisualSampleEntry. // For details see please: // QuickTime File Format Spec [07-13-2011] on page 132. bool has_null_terminator() const { return has_null_terminator_; } void set_has_null_terminator(bool value); // Interfaces for dealing with atom specific data, i.e. payload data excluding // children. The default implementations assume the atom does not carrie any // custom data, i.e. the atom will just contain its header and other atoms // as children. virtual FormatStatus WriteDataWithoutChildren(BinaryWriter* io) const { return FormatStatus::OkStatus(); } virtual FormatStatus ReadDataWithoutChildren(BinaryReader* input) { return FormatStatus::OkStatus(); } virtual AtomSize GetDataSizeWithoutChildren() const { return 0; } protected: // Updates the atom's size as the sum of its header, payload, and children. void Update(); // Sets a new atom type. void set_atom_type(const std::string& type) { atom_type_ = type; } // Sets new header size in bytes. void set_header_size(const AtomSize size) { header_size_ = size; } // Sets the payload size in bytes. void set_data_size(const AtomSize size) { data_size_ = size; } // Calculates the header size. void ComputeHeaderSize(); private: // Computes the size of the current atom. void UpdateSize(); void set_parent(Atom* parent) { parent_ = parent; } // Tag describing what kind of atom this is. std::string atom_type_; // Number of bytes required to store header. AtomSize header_size_; // Number of bytes required to store the payload. AtomSize data_size_; std::vector<std::unique_ptr<Atom>> children_; Atom* parent_; bool has_null_terminator_; }; } // namespace vr180 #endif // VR180_CPP_VIDEO_FORMAT_ATOM_H_
34.230769
80
0.727341
[ "vector" ]
949c7c4393b9f3ac5dee71b52a0b8c3bc677dab1
2,802
h
C
jata/libraries/RestKit-RestKit-991bd5c/Code/ObjectMapping/RKObjectMappingOperation.h
JordanForeman/Just-Another-Twitter-App--JATA-
50559f541ad6a9d8cfb08e8f91824e664a18fbfe
[ "MIT" ]
null
null
null
jata/libraries/RestKit-RestKit-991bd5c/Code/ObjectMapping/RKObjectMappingOperation.h
JordanForeman/Just-Another-Twitter-App--JATA-
50559f541ad6a9d8cfb08e8f91824e664a18fbfe
[ "MIT" ]
null
null
null
jata/libraries/RestKit-RestKit-991bd5c/Code/ObjectMapping/RKObjectMappingOperation.h
JordanForeman/Just-Another-Twitter-App--JATA-
50559f541ad6a9d8cfb08e8f91824e664a18fbfe
[ "MIT" ]
null
null
null
// // RKObjectMappingOperation.h // RestKit // // Created by Blake Watters on 4/30/11. // Copyright 2011 Two Toasters. All rights reserved. // #import "RKObjectMapping.h" #import "RKObjectAttributeMapping.h" @class RKObjectMappingOperation; @protocol RKObjectMappingOperationDelegate <NSObject> @optional - (void)objectMappingOperation:(RKObjectMappingOperation *)operation didFindMapping:(RKObjectAttributeMapping *)mapping forKeyPath:(NSString *)keyPath; - (void)objectMappingOperation:(RKObjectMappingOperation *)operation didNotFindMappingForKeyPath:(NSString *)keyPath; - (void)objectMappingOperation:(RKObjectMappingOperation *)operation didSetValue:(id)value forKeyPath:(NSString *)keyPath usingMapping:(RKObjectAttributeMapping*)mapping; - (void)objectMappingOperation:(RKObjectMappingOperation *)operation didFailWithError:(NSError*)error; @end /** Performs an object mapping operation by mapping values from a dictinary of elements and setting the mapped values onto a target object. */ @interface RKObjectMappingOperation : NSObject { id _sourceObject; id _destinationObject; RKObjectMapping* _objectMapping; id<RKObjectMappingOperationDelegate> _delegate; NSDictionary* _nestedAttributeSubstitution; NSError* _validationError; } /** A dictionary of mappable elements containing simple values or nested object structures. */ @property (nonatomic, readonly) id sourceObject; /** The target object for this operation. Mappable values in elements will be applied to object using key-value coding. */ @property (nonatomic, readonly) id destinationObject; /** The object mapping defining how values contained in the source object should be transformed to the destination object via key-value coding */ @property (nonatomic, readonly) RKObjectMapping* objectMapping; /** The delegate to inform of interesting events during the mapping operation */ @property (nonatomic, assign) id<RKObjectMappingOperationDelegate> delegate; /** Create a new mapping operation configured to transform the object representation in a source object to a new destination object according to an object mapping definition */ + (RKObjectMappingOperation*)mappingOperationFromObject:(id)sourceObject toObject:(id)destinationObject withMapping:(id<RKObjectMappingDefinition>)mapping; /** Initialize a mapping operation for an object and set of data at a particular key path with an object mapping definition */ - (id)initWithSourceObject:(id)sourceObject destinationObject:(id)destinationObject mapping:(id<RKObjectMappingDefinition>)mapping; /** Process all mappable values from the mappable dictionary and assign them to the target object according to the rules expressed in the object mapping definition */ - (BOOL)performMapping:(NSError**)error; @end
36.868421
170
0.799072
[ "object", "transform" ]
94abdd2b7afc5b662897d0a4d1f29309deaaabc9
9,678
h
C
ConsoleRig/ResourceBox.h
djewsbury/XLE
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
[ "MIT" ]
3
2015-12-04T09:16:53.000Z
2021-05-28T23:22:49.000Z
ConsoleRig/ResourceBox.h
djewsbury/XLE
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
[ "MIT" ]
null
null
null
ConsoleRig/ResourceBox.h
djewsbury/XLE
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
[ "MIT" ]
2
2015-03-03T05:32:39.000Z
2015-12-04T09:16:54.000Z
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #pragma once #include "../Assets/Marker.h" #include "../Assets/AssetTraits.h" #include "../Assets/InitializerPack.h" #include "../OSServices/Log.h" #include "../Utility/MemoryUtils.h" #include "../Utility/PtrUtils.h" #include "../Utility/IteratorUtils.h" #include <vector> #include <utility> #include <memory> namespace ConsoleRig { // // This file implements 2 functions: // // FindCachedBox<Type>(...) // TryActualizeCachedBox<Type>(...) // // Both will check the result of GetDependencyValidation() of the object and rebuild // invalidated objects TryActualizeCachedBox() can only be used with classes that have // a method like: // // static void ConstructToPromise(std::promise<std::shared_ptr<Type>>&& promise); // // implemented. This will invoke a background compile on first access and return nullptr // until the object is aready to go. // FindCachedBox<> can also be used with assets with a ConstructToPromise() method, but // will throw ::Assets::Exceptions::PendingAsset if the asset is not ready // /////////////////////////////////////////////////////////////////////////////////////////////// namespace Internal { struct IBoxTable { virtual ~IBoxTable(); }; IBoxTable* GetOrRegisterBoxTable(uint64_t typeId, std::unique_ptr<IBoxTable> table); template <typename Box> struct BoxTable : public IBoxTable { std::vector<std::pair<uint64_t, std::unique_ptr<Box>>> _internalTable; std::vector<std::pair<uint64_t, ::Assets::PtrToMarkerPtr<Box>>> _internalFuturesTable; }; template <typename Box> std::vector<std::pair<uint64_t, std::unique_ptr<Box>>>& GetBoxTable() { static BoxTable<Box>* table = nullptr; if (!table) table = (BoxTable<Box>*)GetOrRegisterBoxTable(typeid(Box).hash_code(), std::make_unique<Internal::BoxTable<Box>>()); return table->_internalTable; } template <typename Box> std::vector<std::pair<uint64_t, ::Assets::PtrToMarkerPtr<Box>>>& GetBoxFutureTable() { static BoxTable<Box>* table = nullptr; if (!table) table = (BoxTable<Box>*)GetOrRegisterBoxTable(typeid(Box).hash_code(), std::make_unique<Internal::BoxTable<Box>>()); return table->_internalFuturesTable; } } template <typename Box, typename... Params> std::enable_if_t< ::Assets::Internal::HasGetDependencyValidation<Box>::value && !::Assets::Internal::HasConstructToPromiseOverride<std::shared_ptr<Box>, Params...>::value, Box&> FindCachedBox(Params... params) { auto hashValue = ::Assets::Internal::BuildParamHash(params...); auto& boxTable = Internal::GetBoxTable<std::decay_t<Box>>(); auto i = LowerBound(boxTable, hashValue); if (i!=boxTable.end() && i->first==hashValue) { if (i->second->GetDependencyValidation().GetValidationIndex()!=0) { i->second = std::make_unique<Box>(std::forward<Params>(params)...); Log(Verbose) << "Created cached box for type (" << typeid(Box).name() << ") -- rebuilding due to validation failure. HashValue:(0x" << std::hex << hashValue << std::dec << ")" << std::endl; } return *i->second; } auto ptr = std::make_unique<Box>(std::forward<Params>(params)...); Log(Verbose) << "Created cached box for type (" << typeid(Box).name() << ") -- first time. HashValue:(0x" << std::hex << hashValue << std::dec << ")" << std::endl; auto i2 = boxTable.emplace(i, std::make_pair(hashValue, std::move(ptr))); return *i2->second; } template <typename Box, typename... Params> std::enable_if_t< !::Assets::Internal::HasGetDependencyValidation<Box>::value && !::Assets::Internal::HasConstructToPromiseOverride<std::shared_ptr<Box>, Params...>::value, Box&> FindCachedBox(Params... params) { auto hashValue = ::Assets::Internal::BuildParamHash(params...); auto& boxTable = Internal::GetBoxTable<std::decay_t<Box>>(); auto i = LowerBound(boxTable, hashValue); if (i!=boxTable.end() && i->first==hashValue) return *i->second; auto ptr = std::make_unique<Box>(std::forward<Params>(params)...); Log(Verbose) << "Created cached box for type (" << typeid(Box).name() << ") -- first time. HashValue:(0x" << std::hex << hashValue << std::dec << ")" << std::endl; auto i2 = boxTable.emplace(i, std::make_pair(hashValue, std::move(ptr))); return *i2->second; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename Box, typename... Params> std::enable_if_t< ::Assets::Internal::HasGetDependencyValidation<Box>::value && ::Assets::Internal::HasConstructToPromiseOverride<std::shared_ptr<Box>, Params...>::value, Box&> FindCachedBox(Params... params) { auto hashValue = ::Assets::Internal::BuildParamHash(params...); auto& boxTable = Internal::GetBoxFutureTable<std::decay_t<Box>>(); auto i = LowerBound(boxTable, hashValue); if (i!=boxTable.end() && i->first==hashValue) { if (::Assets::IsInvalidated(*i->second)) { i->second = std::make_shared<::Assets::MarkerPtr<Box>>(); Box::ConstructToPromise(i->second->AdoptPromise(), std::forward<Params>(params)...); Log(Verbose) << "Created cached box for type (" << typeid(Box).name() << ") -- rebuilding due to validation failure. HashValue:(0x" << std::hex << hashValue << std::dec << ")" << std::endl; } return *i->second->Actualize(); } auto future = std::make_shared<::Assets::MarkerPtr<Box>>(); Box::ConstructToPromise(future->AdoptPromise(), std::forward<Params>(params)...); Log(Verbose) << "Created cached box for type (" << typeid(Box).name() << ") -- first time. HashValue:(0x" << std::hex << hashValue << std::dec << ")" << std::endl; auto i2 = boxTable.emplace(i, std::make_pair(hashValue, std::move(future))); return *i2->second->Actualize(); } template <typename Box, typename... Params> std::enable_if_t< !::Assets::Internal::HasGetDependencyValidation<Box>::value && ::Assets::Internal::HasConstructToPromiseOverride<std::shared_ptr<Box>, Params...>::value, Box&> FindCachedBox(Params... params) { auto hashValue = ::Assets::Internal::BuildParamHash(params...); auto& boxTable = Internal::GetBoxFutureTable<std::decay_t<Box>>(); auto i = LowerBound(boxTable, hashValue); if (i!=boxTable.end() && i->first==hashValue) { return *i->second->Actualize(); } auto future = std::make_shared<::Assets::MarkerPtr<Box>>(); Box::ConstructToPromise(future->AdoptPromise(), std::forward<Params>(params)...); Log(Verbose) << "Created cached box for type (" << typeid(Box).name() << ") -- first time. HashValue:(0x" << std::hex << hashValue << std::dec << ")" << std::endl; auto i2 = boxTable.emplace(i, std::make_pair(hashValue, std::move(future))); return *i2->second->Actualize(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename Box, typename... Params> std::enable_if_t< ::Assets::Internal::HasGetDependencyValidation<Box>::value && ::Assets::Internal::HasConstructToPromiseOverride<std::shared_ptr<Box>, Params...>::value, Box*> TryActualizeCachedBox(Params... params) { auto hashValue = ::Assets::Internal::BuildParamHash(params...); auto& boxTable = Internal::GetBoxFutureTable<std::decay_t<Box>>(); auto i = LowerBound(boxTable, hashValue); if (i!=boxTable.end() && i->first==hashValue) { if (::Assets::IsInvalidated(*i->second)) { i->second = std::make_shared<::Assets::MarkerPtr<Box>>(); Box::ConstructToPromise(i->second->AdoptPromise(), std::forward<Params>(params)...); Log(Verbose) << "Created cached box for type (" << typeid(Box).name() << ") -- rebuilding due to validation failure. HashValue:(0x" << std::hex << hashValue << std::dec << ")" << std::endl; } auto* res = i->second->TryActualize(); if (!res) return nullptr; return res->get(); } auto future = std::make_shared<::Assets::MarkerPtr<Box>>(); Box::ConstructToPromise(future->AdoptPromise(), std::forward<Params>(params)...); Log(Verbose) << "Created cached box for type (" << typeid(Box).name() << ") -- first time. HashValue:(0x" << std::hex << hashValue << std::dec << ")" << std::endl; auto i2 = boxTable.emplace(i, std::make_pair(hashValue, std::move(future))); auto* res = i2->second->TryActualize(); if (!res) return nullptr; return res->get(); } template <typename Box, typename... Params> std::enable_if_t< !::Assets::Internal::HasGetDependencyValidation<Box>::value && ::Assets::Internal::HasConstructToPromiseOverride<std::shared_ptr<Box>, Params...>::value, Box*> TryActualizeCachedBox(Params... params) { auto hashValue = ::Assets::Internal::BuildParamHash(params...); auto& boxTable = Internal::GetBoxFutureTable<std::decay_t<Box>>(); auto i = LowerBound(boxTable, hashValue); if (i!=boxTable.end() && i->first==hashValue) { auto* res = i->second->TryActualize(); if (!res) return nullptr; return res->get(); } auto future = std::make_shared<::Assets::MarkerPtr<Box>>(); Box::ConstructToPromise(future->AdoptPromise(), std::forward<Params>(params)...); Log(Verbose) << "Created cached box for type (" << typeid(Box).name() << ") -- first time. HashValue:(0x" << std::hex << hashValue << std::dec << ")" << std::endl; auto i2 = boxTable.emplace(i, std::make_pair(hashValue, std::move(future))); auto* res = i2->second->TryActualize(); if (!res) return nullptr; return res->get(); } /////////////////////////////////////////////////////////////////////////////////////////////// }
46.085714
195
0.641455
[ "object", "vector" ]
94acb41189a6c14937843ba2d682696a1fad0d69
6,243
h
C
src/common.h
kdv1/p3
5d5345efd705322e8bcbf3c52ecd3eea3d7072ee
[ "Zlib" ]
1
2020-03-15T10:14:27.000Z
2020-03-15T10:14:27.000Z
src/common.h
kdv1/p3
5d5345efd705322e8bcbf3c52ecd3eea3d7072ee
[ "Zlib" ]
null
null
null
src/common.h
kdv1/p3
5d5345efd705322e8bcbf3c52ecd3eea3d7072ee
[ "Zlib" ]
1
2021-01-11T08:07:15.000Z
2021-01-11T08:07:15.000Z
/* Copyright (C) 2019 Dmitry Korunos This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <stddef.h> #include <stdlib.h> #include <string.h> /* Type of build macro */ #ifdef NDEBUG #define P3_RELEASE #else #define P3_DEBUG #endif #define P3_CHECKED /* Keep string only if P3_CHECKED defined */ #if defined(P3_CHECKED) #define CHECK_LINE(L) L #else #define CHECK_LINE(L) #endif /* Include assert.h depend of P3_CHECKED */ #if defined(P3_CHECKED) && defined(P3_RELEASE) #undef NDEBUG #include <assert.h> #define NDEBUG 1 #else #include <assert.h> #endif /* Alignment related macro */ #if(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 has alignas specifier and alignof operator */ #include <stdalign.h> #elif defined(_MSC_VER) #define alignas(N) __declspec(align(N)) #define __alignas_is_defined #elif defined(__GNUC__) #define alignas(N) __attribute__((aligned(N))) #define __alignas_is_defined #endif #ifdef __alignas_is_defined #define cache_aligned alignas(64) #else #define cache_aligned #endif /* inline specifier */ #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 compiler has inline specifier */ #elif defined(_MSC_VER) || defined(__GNUC__) #define inline __inline #else #error Unknown compiler #endif /* forceinline specifier */ #ifdef P3_RELEASE #if defined(_MSC_VER) #define forceinline __forceinline #elif defined(__GNUC__) #define forceinline __attribute__((always_inline)) inline #else #define forceinline inline #endif #else #define forceinline #endif /* Exact-width integer C types */ #if defined(__GNUC__) || (defined(_MSC_VER) && (_MSC_VER >= 1600)) ||\ (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) /* GCC, VS2010 and later, C99 */ #include <stdint.h> #elif defined(_MSC_VER) && (_MSC_VER < 1600) /* VS2008 and earlier */ typedef __int8 int8_t; typedef __int16 int16_t; typedef __int32 int32_t; typedef __int64 int64_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; #endif /* Boolean */ typedef int8_t BOOL; #define FALSE 0 #define TRUE 1 #define TO_BOOL(V) ((V)!=0) /* Basic NES data type */ typedef uint8_t byte; /* Type for holding offset of byte in PPU tileset, valid range is 0..8191 This type is also used to hold byte offset in nametables and attribute tables */ typedef uint16_t padr_t; /* Type for holding offset of byte in tileset */ typedef uint32_t cadr_t; typedef unsigned int sprite_index_t; #define SCREEN_WIDTH 256 #define SCREEN_HEIGHT 240 #define OBJ_MAX 64 #define OBJ_MAX_PER_SCANLINE 8 #define DEFAULT_SPRITE {0, 255, P3_PALETTE_0, P3_SPRITE_FRONT, FALSE, FALSE} struct mmc_table_state { int table; int *mode; cadr_t *banks; const byte **shift; const padr_t **mask; const byte **group; }; /* Sprite bitmap row on scanline */ struct sprite_unit { byte attribute; byte chr_lo; byte chr_hi; byte priority; byte x; }; struct p3_object { /* tileset.c */ byte *tileset_pointer; int tileset_size; /* mapper.c */ int glob_mmc_mode; cadr_t bank_8x1; /* left table */ int left_table_mode; cadr_t left_table_banks[4]; const byte *left_shift_lut; const padr_t *left_mask_lut; const byte *left_group_lut; /* right table */ int right_table_mode; cadr_t right_table_banks[4]; const byte *right_shift_lut; const padr_t *right_mask_lut; const byte *right_group_lut; /* pointers to tables */ struct mmc_table_state mmc_tables[2]; /* switchable mapping functions */ cadr_t (*main_map_func)(padr_t); cadr_t (*bg_map_func)(padr_t); cadr_t (*obj_map_func)(padr_t); /* mirroring */ int mirroring_type; byte mirroring_lut[4]; byte(*mirroring_function)(byte); /* p3.c */ int bg_pattern_table; int obj_pattern_table; byte page_memory[4096]; P3_SPRITE obj_memory[OBJ_MAX]; BOOL idle; BOOL enabled; BOOL show_bg; BOOL show_obj; BOOL clip_bg; BOOL clip_obj; BOOL fix_obj_y; BOOL callback_enabled; BOOL obj_overflow; sprite_index_t sprite_count; byte tmp_tpg, tmp_tcx, tmp_tcy, tmp_tfx, tmp_tfy; byte tmp_vpg, tmp_vcx, tmp_vcy, tmp_vfx, tmp_vfy; int increment_size; byte obj_mode; padr_t bg_chr_base; padr_t obj_chr_base; /* temp variables */ byte cache_aligned bg_color_index; byte bg_tile_hi, bg_tile_lo; byte bg_tile_attributes; byte bg_show_mask; uint32_t bg_clip_mask; /* temp variables */ byte obj_color_index; byte obj_show_mask; uint32_t obj_clip_mask; /* registers */ byte vpg, vcx, vcy, vfx, vfy; byte tpg, tcx, tcy, tfx, tfy; /* color */ uint16_t tint_value; byte palette_memory[32]; byte grayscale_mask; byte *bg_palette; byte *obj_palette; /* frame */ size_t frame_pos; byte frame_row; uint16_t frame_row_pos; uint16_t frame_buffer[SCREEN_WIDTH * SCREEN_HEIGHT]; /* sprites */ struct sprite_unit sprite_units[OBJ_MAX_PER_SCANLINE]; byte sprite_buffer[SCREEN_WIDTH]; /* render callback state */ P3_CALLBACK callback_proc; int callback_type; byte callback_x; byte callback_y; void *callback_param; /* attribute_table.c */ byte last_attribute_pos; }; /* Access to global state */ #define DEFINE_P3_OBJECT P3_OBJECT *g_p3obj = NULL #define USE_P3_OBJECT extern P3_OBJECT *g_p3obj #define S(N) (g_p3obj->N) void set_last_error(const char *err);
25.275304
97
0.729617
[ "render" ]
94b78cfe70c7e9d1af0e7af6a0cdea874860bb6a
3,988
h
C
soc/xtensa/intel_adsp/common/include/soc.h
olavst-nordic/sdk-zephyr
c3208e7ff49d22d8271f305344382e9306fdde99
[ "Apache-2.0" ]
6,224
2016-06-24T20:04:19.000Z
2022-03-31T20:33:45.000Z
soc/xtensa/intel_adsp/common/include/soc.h
olavst-nordic/sdk-zephyr
c3208e7ff49d22d8271f305344382e9306fdde99
[ "Apache-2.0" ]
32,027
2017-03-24T00:02:32.000Z
2022-03-31T23:45:53.000Z
soc/xtensa/intel_adsp/common/include/soc.h
olavst-nordic/sdk-zephyr
c3208e7ff49d22d8271f305344382e9306fdde99
[ "Apache-2.0" ]
4,374
2016-08-11T07:28:47.000Z
2022-03-31T14:44:59.000Z
/* * Copyright (c) 2019 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __INC_SOC_H #define __INC_SOC_H #include <string.h> #include <errno.h> #include <arch/xtensa/cache.h> /* macros related to interrupt handling */ #define XTENSA_IRQ_NUM_SHIFT 0 #define CAVS_IRQ_NUM_SHIFT 8 #define XTENSA_IRQ_NUM_MASK 0xff #define CAVS_IRQ_NUM_MASK 0xff /* * IRQs are mapped on 2 levels. 3rd and 4th level are left as 0x00. * * 1. Peripheral Register bit offset. * 2. CAVS logic bit offset. */ #define XTENSA_IRQ_NUMBER(_irq) \ ((_irq >> XTENSA_IRQ_NUM_SHIFT) & XTENSA_IRQ_NUM_MASK) #define CAVS_IRQ_NUMBER(_irq) \ (((_irq >> CAVS_IRQ_NUM_SHIFT) & CAVS_IRQ_NUM_MASK) - 1) /* Macro that aggregates the bi-level interrupt into an IRQ number */ #define SOC_AGGREGATE_IRQ(cavs_irq, core_irq) \ ( \ ((core_irq & XTENSA_IRQ_NUM_MASK) << XTENSA_IRQ_NUM_SHIFT) | \ (((cavs_irq + 1) & CAVS_IRQ_NUM_MASK) << CAVS_IRQ_NUM_SHIFT) \ ) #define CAVS_L2_AGG_INT_LEVEL2 DT_IRQN(DT_INST(0, intel_cavs_intc)) #define CAVS_L2_AGG_INT_LEVEL3 DT_IRQN(DT_INST(1, intel_cavs_intc)) #define CAVS_L2_AGG_INT_LEVEL4 DT_IRQN(DT_INST(2, intel_cavs_intc)) #define CAVS_L2_AGG_INT_LEVEL5 DT_IRQN(DT_INST(3, intel_cavs_intc)) #define CAVS_ICTL_INT_CPU_OFFSET(x) (0x40 * x) #define IOAPIC_EDGE 0 #define IOAPIC_HIGH 0 /* I2S */ #define I2S_CAVS_IRQ(i2s_num) \ SOC_AGGREGATE_IRQ(0, (i2s_num), CAVS_L2_AGG_INT_LEVEL5) #define I2S0_CAVS_IRQ I2S_CAVS_IRQ(0) #define I2S1_CAVS_IRQ I2S_CAVS_IRQ(1) #define I2S2_CAVS_IRQ I2S_CAVS_IRQ(2) #define I2S3_CAVS_IRQ I2S_CAVS_IRQ(3) #define SSP_MN_DIV_SIZE (8) #define SSP_MN_DIV_BASE(x) \ (0x00078D00 + ((x) * SSP_MN_DIV_SIZE)) #define PDM_BASE DMIC_BASE /* DSP Wall Clock Timers (0 and 1) */ #define DSP_WCT_IRQ(x) \ SOC_AGGREGATE_IRQ((22 + x), CAVS_L2_AGG_INT_LEVEL2) #define DSP_WCT_CS_TA(x) BIT(x) #define DSP_WCT_CS_TT(x) BIT(4 + x) /* Attribute macros to place code and data into IMR memory */ #define __imr __in_section_unique(imr) #define __imrdata __in_section_unique(imrdata) extern void z_soc_irq_enable(uint32_t irq); extern void z_soc_irq_disable(uint32_t irq); extern int z_soc_irq_is_enabled(unsigned int irq); /* Legacy SOC-level API still used in a few drivers */ #define SOC_DCACHE_FLUSH(addr, size) \ z_xtensa_cache_flush((addr), (size)) #define SOC_DCACHE_INVALIDATE(addr, size) \ z_xtensa_cache_inv((addr), (size)) /** * @brief Return uncached pointer to a RAM address * * The Intel ADSP architecture maps all addressable RAM (of all types) * twice, in two different 512MB segments regions whose L1 cache * settings can be controlled independently. So for any given * pointer, it is possible to convert it to and from a cached version. * * This function takes a pointer to any addressible object (either in * cacheable memory or not) and returns a pointer that can be used to * refer to the same memory while bypassing the L1 data cache. Data * in the L1 cache will not be inspected nor modified by the access. * * @see z_soc_cached_ptr() * * @param p A pointer to a valid C object * @return A pointer to the same object bypassing the L1 dcache */ static inline void *z_soc_uncached_ptr(void *p) { return ((void *)(((size_t)p) & ~0x20000000)); } /** * @brief Return cached pointer to a RAM address * * This function takes a pointer to any addressible object (either in * cacheable memory or not) and returns a pointer that can be used to * refer to the same memory through the L1 data cache. Data read * through the resulting pointer will reflect locally cached values on * the current CPU if they exist, and writes will go first into the * cache and be written back later. * * @see z_soc_uncached_ptr() * * @param p A pointer to a valid C object * @return A pointer to the same object via the L1 dcache */ static inline void *z_soc_cached_ptr(void *p) { return ((void *)(((size_t)p) | 0x20000000)); } #endif /* __INC_SOC_H */
31.15625
70
0.739468
[ "object" ]
94ba4d133d8309fddc15f9b5691594e076e59eaf
2,149
h
C
Source/ModuleRender.h
Memory-Leakers/Pinball
d07228aa92be7988aa2da31f0a86cfd836b8c5a5
[ "MIT" ]
null
null
null
Source/ModuleRender.h
Memory-Leakers/Pinball
d07228aa92be7988aa2da31f0a86cfd836b8c5a5
[ "MIT" ]
null
null
null
Source/ModuleRender.h
Memory-Leakers/Pinball
d07228aa92be7988aa2da31f0a86cfd836b8c5a5
[ "MIT" ]
null
null
null
#pragma once #include "Module.h" #include "Globals.h" #include "Point.h" #include <vector> #include <string> using namespace std; struct RenderObject { SDL_Texture* texture = nullptr; SDL_Rect* section = nullptr; SDL_Rect renderRect; SDL_RendererFlip flip = SDL_FLIP_NONE; float rotation = 0.0f; int layer = 0; float orderInLayer = 0.0f; float speed = 1.0f; float scale = 1.0f; SDL_Point pivot = { 0,0 }; string name = "def"; bool rotationEnabled = true; bool followPhysBody = true; }; struct RenderRect { SDL_Rect rect; SDL_Color color; bool isAbove; }; class ModuleRender : public Module { public: ModuleRender(Application* app, bool start_enabled = true); ~ModuleRender(); bool Init(); UpdateStatus PreUpdate(); UpdateStatus Update(); UpdateStatus PostUpdate(); bool CleanUp(); void AddTextureRenderQueue(RenderObject object); void AddTextureRenderQueue(SDL_Texture* texture, iPoint pos, SDL_Rect* section = nullptr, float scale = 1, int layer = 0, float orderInlayer = 0.0f, float rotation = 0, SDL_RendererFlip flip = SDL_FLIP_NONE, SDL_Rect pivot = { 0,0 }, float speed = 1.0f);// Speed = 1.0f = Fullscreen camera void AddRectRenderQueue(const SDL_Rect& rect, Uint8 r, Uint8 g, Uint8 b, Uint8 a = 255, bool above = false, bool filled = true, bool use_camera = true); void SortRenderObjects(vector<RenderObject>& obj); #pragma region OBSOLETE bool Blit(SDL_Texture* texture, int x, int y, float scale = 1, SDL_Rect* section = NULL, float speed = 1.0f, double angle = 0,SDL_RendererFlip flip=SDL_FLIP_NONE,int pivot_x = INT_MAX, int pivot_y = INT_MAX); bool DrawQuad(const SDL_Rect& rect, Uint8 r, Uint8 g, Uint8 b, Uint8 a = 255, bool filled = true, bool use_camera = true); bool DrawLine(int x1, int y1, int x2, int y2, Uint8 r, Uint8 g, Uint8 b, Uint8 a = 255, bool use_camera = true); bool DrawCircle(int x1, int y1, int redius, Uint8 r, Uint8 g, Uint8 b, Uint8 a = 255, bool use_camera = true); void CameraMove(iPoint pos); #pragma endregion public: SDL_Renderer* renderer; SDL_Rect camera; private: float defaultSpeed = 1; vector<vector<RenderObject>> layers; vector<RenderRect> rects; };
30.7
290
0.728711
[ "object", "vector" ]
94d15be2582894a745e7d8dc8bf1fea325768ea2
23,255
c
C
src/Geometry/ImagesGeom.c
xomachine/gabedit
1f63b6675b8bffdda910012fec00b89630bcb4a2
[ "MIT" ]
null
null
null
src/Geometry/ImagesGeom.c
xomachine/gabedit
1f63b6675b8bffdda910012fec00b89630bcb4a2
[ "MIT" ]
null
null
null
src/Geometry/ImagesGeom.c
xomachine/gabedit
1f63b6675b8bffdda910012fec00b89630bcb4a2
[ "MIT" ]
null
null
null
/* ImagesGeom.c */ /********************************************************************************************************** Copyright (c) 2002-2013 Abdul-Rahman Allouche. All rights reserved Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Gabedit), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************************************************/ #include "../../Config.h" #include "../Common/Global.h" #include "../Geometry/GeomGlobal.h" #include "../Geometry/Fragments.h" #include "../Geometry/DrawGeom.h" #include "../Utils/UtilsInterface.h" #include "../Utils/Utils.h" #ifdef DRAWGEOMGL #include <GL/gl.h> #include <GL/glu.h> /**************************************************************************/ static void snapshot_pixbuf_free (guchar *pixels, gpointer data) { g_free (pixels); } /**************************************************************************/ static GdkPixbuf *get_pixbuf_gl(guchar* colorTrans) { gint stride; GdkPixbuf *pixbuf = NULL; GdkPixbuf *tmp = NULL; GdkPixbuf *tmp2 = NULL; guchar *data; gint height; gint width; GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); width = viewport[2]; height = viewport[3]; stride = width*4; data = g_malloc0 (sizeof (guchar) * stride * height); #ifdef G_OS_WIN32 glReadBuffer(GL_BACK); glReadPixels(0,0,width,height,GL_RGBA,GL_UNSIGNED_BYTE,data); #else glReadBuffer(GL_FRONT); glReadPixels(0,0,width,height,GL_RGBA,GL_UNSIGNED_BYTE,data); #endif tmp = gdk_pixbuf_new_from_data (data, GDK_COLORSPACE_RGB, TRUE, 8, width, height, stride, snapshot_pixbuf_free, NULL); if(tmp) { tmp2 = gdk_pixbuf_flip (tmp, TRUE); g_object_unref (tmp); } if(tmp2) { pixbuf = gdk_pixbuf_rotate_simple (tmp2, GDK_PIXBUF_ROTATE_UPSIDEDOWN); g_object_unref (tmp2); } if(colorTrans) { tmp = gdk_pixbuf_add_alpha(pixbuf, TRUE, colorTrans[0], colorTrans[1], colorTrans[2]); if(tmp!=pixbuf) { g_object_unref (pixbuf); pixbuf = tmp; } } return pixbuf; } /*************************************************************************/ static void gabedit_save_image_gl(GtkWidget* widget, gchar *fileName, gchar* type, guchar* colorTrans) { GError *error = NULL; GdkPixbuf *pixbuf = NULL; pixbuf = get_pixbuf_gl(colorTrans); if(pixbuf) { if(!fileName) { GtkClipboard * clipboard; clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); if(clipboard) { gtk_clipboard_clear(clipboard); gtk_clipboard_set_image(clipboard, pixbuf); } } else { if(type && strstr(type,"j") && strstr(type,"g") ) gdk_pixbuf_save(pixbuf, fileName, type, &error, "quality", "100", NULL); else if(type && strstr(type,"png")) gdk_pixbuf_save(pixbuf, fileName, type, &error, "compression", "5", NULL); else if(type && (strstr(type,"tif") || strstr(type,"tiff"))) gdk_pixbuf_save(pixbuf, fileName, "tiff", &error, "compression", "1", NULL); else gdk_pixbuf_save(pixbuf, fileName, type, &error, NULL); } g_object_unref (pixbuf); } } #endif /**********************************************************************************************************************************/ static void save_geometry_image(GabeditFileChooser *SelecFile, gchar* type, guchar* colorTrans) { gchar *fileName; fileName = gabedit_file_chooser_get_current_file(SelecFile); if ((!fileName) || (strcmp(fileName,"") == 0)) { Message(_("Sorry\n No selected file"),_("Error"),TRUE); return ; } gtk_widget_hide(GTK_WIDGET(SelecFile)); while( gtk_events_pending() ) gtk_main_iteration(); gtk_window_move(GTK_WINDOW(GeomDlg),0,0); rafresh_drawing(); while( gtk_events_pending() ) gtk_main_iteration(); #ifdef DRAWGEOMGL gabedit_save_image_gl(GeomDrawingArea, fileName, type, colorTrans); #else gabedit_save_image(GeomDrawingArea, fileName, type); #endif } /************************************************************************** * Get image in rgb format **************************************************************************/ guchar *get_rgb_image() { if(!GeomDrawingArea) { Message(_("Sorry I can not create image file \nbecause Geometry display windows is closed"),_("Error"),TRUE); return NULL; } #ifdef DRAWGEOMGL { GdkPixbuf* tmp = get_pixbuf_gl(NULL); guchar *data = NULL; if(tmp) data =gdk_pixbuf_get_pixels(tmp); return data; } #endif { gdouble fac=255.0/65535.0; GdkPixmap* pixmap = get_drawing_pixmap(); GdkColormap *colormap = get_drawing_colormap(); guint height = GeomDrawingArea->allocation.height; guint width = GeomDrawingArea->allocation.width; guint32 pixel; GdkImage* image = NULL; GdkVisual *v; guint8 component; guint k=0; gint x; gint y; gint i; guchar* rgbbuf=(guchar *) g_malloc(3*width*height*sizeof(guchar)); if(!pixmap || !colormap) return NULL; if(!rgbbuf) { Message(_("Sorry: couldn't allocate memory\n"),_("Error"),TRUE); return NULL; } /* Debug("End get colormap\n");*/ image = gdk_drawable_get_image(GeomDrawingArea->window,0,0,width,height); /* Debug("End get Image\n");*/ v = gdk_colormap_get_visual(colormap); /* Debug("End get visual\n");*/ switch(v->type) { case GDK_VISUAL_STATIC_GRAY: case GDK_VISUAL_GRAYSCALE: case GDK_VISUAL_STATIC_COLOR: case GDK_VISUAL_PSEUDO_COLOR: for(y=height-1;y>=0;y--) for(x=0;x<(gint)width;x++) { pixel = gdk_image_get_pixel(image, x, y); rgbbuf[k] = (guchar)(colormap->colors[pixel].red*fac); rgbbuf[k+1] =(guchar) (colormap->colors[pixel].green*fac); rgbbuf[k+2] =(guchar) (colormap->colors[pixel].blue*fac); k+=3; } break; case GDK_VISUAL_TRUE_COLOR: /* Debug("True color\n");*/ for(y=height-1;y>=0;y--) for(x=0;x<(gint)width;x++) { pixel = gdk_image_get_pixel(image, x, y); component = 0; for (i = 24; i < 32; i += v->red_prec) component |= ((pixel & v->red_mask) << (32 - v->red_shift - v->red_prec)) >> i; rgbbuf[k] = (guchar)(component); component = 0; for (i = 24; i < 32; i += v->green_prec) component |= ((pixel & v->green_mask) << (32 - v->green_shift - v->green_prec)) >> i; rgbbuf[k+1] = (guchar)(component); component = 0; for (i = 24; i < 32; i += v->blue_prec) component |= ((pixel & v->blue_mask) << (32 - v->blue_shift - v->blue_prec)) >> i; rgbbuf[k+2] = (guchar)(component); k += 3; } break; case GDK_VISUAL_DIRECT_COLOR: for(y=height-1;y>=0;y--) for(x=0;x<(gint)width;x++) { pixel = gdk_image_get_pixel(image, x, y); component = colormap->colors[((pixel & v->red_mask) << (32 - v->red_shift - v->red_prec)) >> 24].red; rgbbuf[k] = (guchar)(component*fac); component = colormap->colors[((pixel & v->green_mask) << (32 - v->green_shift - v->green_prec)) >> 24].green; rgbbuf[k+1] = (guchar)(component*fac); component = colormap->colors[((pixel & v->blue_mask) << (32 - v->blue_shift - v->blue_prec)) >> 24].blue; rgbbuf[k+2] = (guchar)(component*fac); k += 3; } break; default : Message(_("Unknown visual\n"),_("Error"),TRUE); g_free(rgbbuf); return NULL; } return rgbbuf; } return NULL; } /************************************************************************** * Save the Frame Buffer in a jpeg format file **************************************************************************/ void save_geometry_jpeg_file(GabeditFileChooser *SelecFile, gint response_id) { if(response_id != GTK_RESPONSE_OK) return; save_geometry_image(SelecFile, "jpeg",NULL); } /************************************************************************** * Save the Frame Buffer in a ppm format file **************************************************************************/ #ifdef DRAWGEOMGL static gchar* save_ppm(gchar* fileName) { FILE *file; int i; int j; int k; int width; int height; GLubyte *rgbbuf; static gchar message[1024]; int ierr; if ((!fileName) || (strcmp(fileName,"") == 0)) { sprintf(message,_("Sorry\n No selected file")); return message; } file = FOpen(fileName,"wb"); if (!file) { sprintf(message,_("Sorry: can't open %s file\n"), fileName); return message; } height = GeomDrawingArea->allocation.height; width = GeomDrawingArea->allocation.width; glPixelStorei(GL_PACK_ROW_LENGTH,width); glPixelStorei(GL_PACK_ALIGNMENT,1); rgbbuf = (GLubyte *) malloc(3*width*height*sizeof(GLubyte)); if (!rgbbuf) { sprintf(message,_("Sorry: couldn't allocate memory\n")); fclose(file); return message; } #ifdef G_OS_WIN32 glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,rgbbuf); #else glReadBuffer(GL_FRONT); glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,rgbbuf); #endif fprintf(file,"P6\n"); fprintf(file,"#Image rendered with gabedit\n"); fprintf(file,"%d\n%d\n255\n", width,height); for(i=height-1; i>= 0; i--){ for(j=0; j< width; j++){ k = 3*(j + i*width); ierr = fwrite( &rgbbuf[k] ,sizeof(*rgbbuf), 1, file); ierr = fwrite( &rgbbuf[k+1] ,sizeof(*rgbbuf), 1, file); ierr = fwrite( &rgbbuf[k+2] ,sizeof(*rgbbuf), 1, file); } } fclose(file); free(rgbbuf); return NULL; } #else static gchar* save_ppm(gchar* FileName) { FILE *file; int i; int j; int k; int width; int height; guchar *rgbbuf; static gchar message[1024]; file = FOpen(FileName,"wb"); if (!file) { sprintf(message,_("Sorry: can't open %s file\n"), FileName); return message; } rgbbuf = get_rgb_image(); if (!rgbbuf) { sprintf(message,_("Sorry: couldn't allocate memory\n")); fclose(file); return message; } width = GeomDrawingArea->allocation.width; height = GeomDrawingArea->allocation.height; fprintf(file,"P6\n"); fprintf(file,"#Image rendered with gabedit\n"); fprintf(file,"%d\n%d\n255\n", width,height); for(i=height-1; i>= 0; i--){ for(j=0; j< width; j++){ k = 3*(j + i*width); fwrite( &rgbbuf[k] ,sizeof(*rgbbuf), 1, file); fwrite( &rgbbuf[k+1] ,sizeof(*rgbbuf), 1, file); fwrite( &rgbbuf[k+2] ,sizeof(*rgbbuf), 1, file); } } fclose(file); g_free(rgbbuf); return NULL; } #endif /**************************************************************************/ void save_geometry_ppm_file(GabeditFileChooser *SelecFile, gint response_id) { gchar *fileName; gchar* message; if(response_id != GTK_RESPONSE_OK) return; fileName = gabedit_file_chooser_get_current_file(SelecFile); if ((!fileName) || (strcmp(fileName,"") == 0)) { Message(_("Sorry\n No selected file"),_("Error"),TRUE); return ; } gtk_widget_hide(GTK_WIDGET(SelecFile)); gtk_window_move(GTK_WINDOW(GeomDlg),0,0); rafresh_drawing(); while( gtk_events_pending() ) gtk_main_iteration(); message = save_ppm(fileName); if(message != NULL) { Message(message,_("Error"),TRUE); } } /************************************************************************** * Save the Frame Buffer in a bmp format file **************************************************************************/ static void WLSBL(int val,char* arr) { arr[0] = (char) (val&0xff); arr[1] = (char) ((val>>8) &0xff); arr[2] = (char) ((val>>16)&0xff); arr[3] = (char) ((val>>24)&0xff); } /**************************************************************************/ #ifdef DRAWGEOMGL static gchar* save_bmp(gchar* fileName) { FILE *file; int i; int j; int width; int height; GLubyte *rgbbuf; GLubyte rgbtmp[3]; int pad; static gchar message[1024]; int ierr; char bmp_header[]= { 'B','M', 0,0,0,0, 0,0, 0,0, 54,0,0,0, 40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0, 24,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }; if ((!fileName) || (strcmp(fileName,"") == 0)) { sprintf(message,_("Sorry\n No selected file")); return message; } file = FOpen(fileName,"wb"); if (!file) { sprintf(message,_("Sorry: can't open %s file\n"), fileName); return message; } height = GeomDrawingArea->allocation.height; width = GeomDrawingArea->allocation.width; glPixelStorei(GL_PACK_ROW_LENGTH,width); glPixelStorei(GL_PACK_ALIGNMENT,1); rgbbuf = (GLubyte *)malloc(3*width*height*sizeof(GLubyte)); if (!rgbbuf) { sprintf(message,_("Sorry: couldn't allocate memory\n")); fclose(file); return message; } #ifdef G_OS_WIN32 glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,rgbbuf); #else glReadBuffer(GL_FRONT); glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,rgbbuf); #endif /* The number of bytes on a screenline should be wholly devisible by 4 */ pad = (width*3)%4; if (pad) pad = 4 - pad; WLSBL((int) (3*width+pad)*height+54,bmp_header+2); WLSBL((int) width,bmp_header+18); WLSBL((int) height,bmp_header+22); WLSBL((int) 3*width*height,bmp_header+34); ierr = fwrite(bmp_header,1,54,file); for (i=0;i<height;i++) { for (j=0;j<width;j++) { rgbtmp[0] = rgbbuf[(j+width*i)*3+2]; rgbtmp[1] = rgbbuf[(j+width*i)*3+1]; rgbtmp[2] = rgbbuf[(j+width*i)*3+0]; ierr = fwrite(rgbtmp,3,1,file); } rgbtmp[0] = (char) 0; for (j=0;j<pad;j++) ierr = fwrite(rgbtmp,1,1,file); } fclose(file); free(rgbbuf); return NULL; } #else /**************************************************************************/ static gchar* save_bmp(gchar* fileName) { FILE *file; int i; int j; int width; int height; guchar *rgbbuf; guchar rgbtmp[3]; int pad; static gchar message[1024]; char bmp_header[]= { 'B','M', 0,0,0,0, 0,0, 0,0, 54,0,0,0, 40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0, 24,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }; if ((!fileName) || (strcmp(fileName,"") == 0)) { sprintf(message,_("Sorry\n No selected file")); return message; } file = FOpen(fileName,"wb"); if (!file) { sprintf(message,_("Sorry: can't open %s file\n"), fileName); return message; } height = GeomDrawingArea->allocation.height; width = GeomDrawingArea->allocation.width; rgbbuf = get_rgb_image(); if (!rgbbuf) { sprintf(message,_("Sorry: couldn't allocate memory\n")); fclose(file); return message; } pad = (width*3)%4; if (pad) pad = 4 - pad; WLSBL((int) (3*width+pad)*height+54,bmp_header+2); WLSBL((int) width,bmp_header+18); WLSBL((int) height,bmp_header+22); WLSBL((int) 3*width*height,bmp_header+34); fwrite(bmp_header,1,54,file); for (i=0;i<height;i++) { for (j=0;j<width;j++) { rgbtmp[0] = rgbbuf[(j+width*i)*3+2]; rgbtmp[1] = rgbbuf[(j+width*i)*3+1]; rgbtmp[2] = rgbbuf[(j+width*i)*3+0]; fwrite(rgbtmp,3,1,file); } rgbtmp[0] = (char) 0; for (j=0;j<pad;j++) fwrite(rgbtmp,1,1,file); } fclose(file); g_free(rgbbuf); return NULL; } #endif /**************************************************************************/ void save_geometry_bmp_file(GabeditFileChooser *SelecFile, gint response_id) { gchar *fileName; gchar* message; if(response_id != GTK_RESPONSE_OK) return; fileName = gabedit_file_chooser_get_current_file(SelecFile); if ((!fileName) || (strcmp(fileName,"") == 0)) { Message(_("Sorry\n No selected file"),_("Error"),TRUE); return ; } gtk_widget_hide(GTK_WIDGET(SelecFile)); gtk_window_move(GTK_WINDOW(GeomDlg),0,0); rafresh_drawing(); while( gtk_events_pending() ) gtk_main_iteration(); message = save_bmp(fileName); if(message != NULL) { Message(message,_("Error"),TRUE); } } /************************************************************************** * Save the Frame Buffer in a ps format file **************************************************************************/ static void ps_header(FILE* file) { fprintf(file,"%%true {\n"); fprintf(file,"systemdict /colorimage known not {\n"); fprintf(file,"%%\n"); fprintf(file,"/colorImageDict 50 dict def\n"); fprintf(file,"/colorimage {\n"); fprintf(file," colorImageDict begin\n"); fprintf(file," /Ncomp exch def\n"); fprintf(file," {\n"); fprintf(file," (Multi-source not implemented\\n) print flush\n"); fprintf(file," limitcheck\n"); fprintf(file," } {\n"); fprintf(file," /Dsrc exch def\n"); fprintf(file," /Matrix exch def\n"); fprintf(file," /Bcomp exch def\n"); fprintf(file," /Height exch def\n"); fprintf(file," /Width exch def\n"); fprintf(file," /Bycomp Bcomp 7 add 8 idiv def\n"); fprintf(file," Bcomp 8 gt { (Only 8 bit per sample images \\n)\n"); fprintf(file," print flush limitcheck\n"); fprintf(file," } if\n"); fprintf(file," Width Height Bcomp Matrix\n"); fprintf(file," Ncomp 1 eq {\n"); fprintf(file," { Dsrc exec }\n"); fprintf(file," } if\n"); fprintf(file," Ncomp 3 eq {\n"); fprintf(file," /Gstr Bycomp Width mul string def\n"); fprintf(file," { Dsrc exec\n"); fprintf(file," /Cstr exch def\n"); fprintf(file," 0 1 Width 1 sub {\n"); fprintf(file," /I exch def\n"); fprintf(file," /X I 3 mul def\n"); fprintf(file," Gstr I\n"); fprintf(file," Cstr X get 0.3 mul\n"); fprintf(file," Cstr X 1 add get 0.59 mul\n"); fprintf(file," Cstr X 2 add get 0.11 mul\n"); fprintf(file," add add cvi\n"); fprintf(file," put\n"); fprintf(file," } for\n"); fprintf(file," Gstr\n"); fprintf(file," }\n"); fprintf(file," } if\n"); fprintf(file," Ncomp 4 eq {\n"); fprintf(file," /Gstr Bycomp Width mul string def\n"); fprintf(file," { Dsrc exec\n"); fprintf(file," /Cstr exch def\n"); fprintf(file," 0 1 Width 1 sub {\n"); fprintf(file," /I exch def\n"); fprintf(file," /X I 4 mul def\n"); fprintf(file," Gstr I\n"); fprintf(file," 2 Bcomp exp 1 sub\n"); fprintf(file," Cstr X get 0.3 mul\n"); fprintf(file," Cstr X 1 add get 0.59 mul\n"); fprintf(file," Cstr X 2 add get 0.11 mul\n"); fprintf(file," Cstr X 3 add get\n"); fprintf(file," add add add dup 2 index gt {pop dup} if\n"); fprintf(file," sub cvi\n"); fprintf(file," put\n"); fprintf(file," } for\n"); fprintf(file," Gstr\n"); fprintf(file," }\n"); fprintf(file," } if\n"); fprintf(file," image\n"); fprintf(file," } ifelse\n"); fprintf(file," end\n"); fprintf(file,"} bind def\n"); fprintf(file,"} if\n"); } /****************************************************************************************************************/ void save_geometry_ps_file(GabeditFileChooser *SelecFile, gint response_id) { gchar *fileName; FILE *file; int i; int j; int k; int width; int height; #ifdef DRAWGEOMGL GLubyte *rgbbuf; #else guchar *rgbbuf; #endif if(response_id != GTK_RESPONSE_OK) return; fileName = gabedit_file_chooser_get_current_file(SelecFile); if ((!fileName) || (strcmp(fileName,"") == 0)) { Message(_("Sorry\n No selected file"),_("Error"),TRUE); return ; } gtk_widget_hide(GTK_WIDGET(SelecFile)); gtk_window_move(GTK_WINDOW(GeomDlg),0,0); rafresh_drawing(); while( gtk_events_pending() ) gtk_main_iteration(); height = GeomDrawingArea->allocation.height; width = GeomDrawingArea->allocation.width; #ifdef DRAWGEOMGL glPixelStorei(GL_PACK_ROW_LENGTH,width); glPixelStorei(GL_PACK_ALIGNMENT,1); rgbbuf = (GLubyte *) malloc(3*width*height*sizeof(GLubyte)); #else rgbbuf = get_rgb_image(); #endif if (!rgbbuf) { Message(_("Sorry: couldn't allocate memory\n"),_("Error"),TRUE); return; } #ifdef DRAWGEOMGL #ifdef G_OS_WIN32 glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,rgbbuf); #else glReadBuffer(GL_FRONT); glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,rgbbuf); #endif #endif file = FOpen(fileName,"w"); if (!file) { Message(_("Sorry: can't open output file\n"),_("Error"),TRUE); return; } fprintf(file,"%%!PS-Adobe-2.0 EPSF-2.0\n"); fprintf(file,"%%%%BoundingBox: 16 16 %d %d\n",width+16,height+16); fprintf(file,"%%%%Creator: gabedit\n"); fprintf(file,"%%%%Title: gabedit output file\n"); fprintf(file,"%%%%EndComments\n"); ps_header(file); fprintf(file,"/picstr %d string def\n",height*3); fprintf(file,"16 16 translate\n"); fprintf(file,"%d %d scale\n",width,height); fprintf(file,"%d %d 8 [ %d 0 0 %d 0 0] \n",width,height,width,height); fprintf(file,"{ currentfile picstr readhexstring pop }\n"); fprintf(file,"false 3 colorimage\n"); j = k = 0; for (i=0;i<width*height+1;i++){ fprintf(file,"%02x%02x%02x",rgbbuf[j],rgbbuf[j+1],rgbbuf[j+2]); j += 3; k += 6; if (k>70){ fprintf(file,"\n"); k=0; } } fprintf(file,"\nshowpage\n"); fprintf(file,"%%%%Trailer\n"); fclose(file); g_free(rgbbuf); } /**********************************************************************************************************************************/ void save_geometry_png_file(GabeditFileChooser *SelecFile, gint response_id) { if(response_id != GTK_RESPONSE_OK) return; save_geometry_image(SelecFile, "png",NULL); } /**********************************************************************************************************************************/ void save_geometry_tiff_file(GabeditFileChooser *SelecFile, gint response_id) { if(response_id != GTK_RESPONSE_OK) return; save_geometry_image(SelecFile, "tiff",NULL); }
30.006452
132
0.565212
[ "geometry" ]
94dbcabdda562fd84665e54e6ff58963447dd729
4,219
h
C
libs/initializer.h
Hsarham/automatic-ar
b49495572e9ceb24c805449fd398126685384de5
[ "BSD-2-Clause" ]
22
2018-06-16T17:57:11.000Z
2022-03-22T02:05:40.000Z
libs/initializer.h
Hsarham/automatic-ar
b49495572e9ceb24c805449fd398126685384de5
[ "BSD-2-Clause" ]
2
2019-07-10T18:47:15.000Z
2019-08-06T04:38:05.000Z
libs/initializer.h
Hsarham/automatic-ar
b49495572e9ceb24c805449fd398126685384de5
[ "BSD-2-Clause" ]
4
2018-06-08T10:06:01.000Z
2020-08-18T14:14:10.000Z
#ifndef INITIALIZER_H #define INITIALIZER_H #include <opencv2/core.hpp> #include <map> #include <set> #include <aruco/aruco.h> #include "cam_config.h" class Initializer { public: Initializer(double marker_s, std::vector<CamConfig> &cam_c, const std::set<int> &excluded_cs=std::set<int>()); Initializer(std::vector<std::vector<std::vector<aruco::Marker>>> &dts, double marker_s, std::vector<CamConfig> &cam_c, const std::set<int> &excluded_cs=std::set<int>()); static std::vector<std::vector<std::vector<aruco::Marker>>> read_detections_file(std::string path, const std::vector<int> &subseqs=std::vector<int>()); struct Config{ bool init_cams=true; bool init_markers=true; bool init_relative_poses=true; }; std::set<int> get_marker_ids(); std::set<int> get_cam_ids(); int get_root_cam(); int get_root_marker(); std::map<int,cv::Mat> get_transforms_to_root_cam(); std::map<int,cv::Mat> get_transforms_to_root_marker(); void set_transforms_to_root_cam(std::map<int,cv::Mat> &ttrc); void set_transforms_to_root_marker(std::map<int,cv::Mat> &ttrm); void set_detections(std::vector<std::vector<std::vector<aruco::Marker>>> &dts); void obtain_pose_estimations(); void init_object_transforms(); std::map<int,cv::Mat> get_object_transforms(); double get_marker_size(); std::map<int, std::map<int, std::vector<aruco::Marker>>> get_frame_cam_markers(); std::vector<CamConfig> get_cam_configs(); private: Config config; std::vector<std::vector<std::vector<aruco::Marker>>> detections; enum transform_type{camera,marker}; std::map<int, std::map<int, std::vector<std::tuple<cv::Mat,cv::Mat,cv::Mat,double>>>> transformation_sets_cam, transformation_sets_marker; struct Node{ int id; mutable double distance; mutable int parent; bool operator < (const Node &n) const{ return this->id<n.id; } }; int root_cam,root_marker,min_detections = 2; double marker_size,threshold = 2.0; std::set<int> marker_ids,cam_ids,excluded_cams; std::map<int, std::map<int, std::map<int, std::vector<std::pair<cv::Mat,double>>>>> frame_poses_cam,frame_poses_marker; std::map<int, std::map<int, std::vector<aruco::Marker>>> frame_cam_markers; std::vector<CamConfig> cam_configs; std::map<int,cv::Mat> transforms_to_root_cam,transforms_to_root_marker,object_transforms; void fill_transformation_set(const std::map<int, std::map<int, std::vector<std::pair<cv::Mat,double>>>> &pose_estimations, const std::map<int, cv::Mat>& transforms_to_root_cam, const std::map<int, cv::Mat>& transforms_to_root_marker, std::vector<std::tuple<cv::Mat,cv::Mat,cv::Mat,double>> &transformation_set); void fill_transformation_sets(transform_type tt, const std::map<int, std::map<int, std::vector<std::pair<cv::Mat,double>>>> &pose_estimations, std::map<int, std::map<int, std::vector<std::tuple<cv::Mat,cv::Mat,cv::Mat,double>>>> &transformation_sets); int find_best_transformation_min(double marker_size, const std::vector<std::tuple<cv::Mat,cv::Mat,cv::Mat,double>>& solutions, double& min_error); int find_best_transformation(double marker_size, const std::vector<std::tuple<cv::Mat,cv::Mat,cv::Mat,double>>& solutions, double& weight); void find_best_transformations(double marker_size, const std::map<int, std::map<int, std::vector<std::tuple<cv::Mat,cv::Mat,cv::Mat,double>>>> &transformation_sets, std::map<int, std::map<int, std::pair<cv::Mat,double>>> &best_transformations); // double get_reprojection_error(double marker_size, aruco::Marker marker, cv::Mat r, cv::Mat t, cv::Mat cam_mat, cv::Mat dist_coeffs); void make_mst(int starting_node, std::set<int> node_ids, const std::map<int, std::map<int, std::pair<cv::Mat,double>>>& adjacency, std::map<int, std::set<int>> &children); void find_transforms_to_root(int root_node, const std::map<int,std::set<int>> &children, const std::map<int, std::map<int, std::pair<cv::Mat,double>>> &best_transforms, std::map<int, cv::Mat> &transforms_to_root); void init_transforms_cam(); void init_transforms_marker(); void init_transforms(); }; #endif // INITIALIZER_H
55.513158
315
0.708462
[ "vector" ]
03fea1fbc85f403e3d89ad16a5dc04aa3e07abe2
390,182
c
C
src/FLAMCLP.c
limes-datentechnik-gmbh/FLAMCLEP
280ad65c4aebbf8242a5970b040b0fe010cd7414
[ "Zlib" ]
null
null
null
src/FLAMCLP.c
limes-datentechnik-gmbh/FLAMCLEP
280ad65c4aebbf8242a5970b040b0fe010cd7414
[ "Zlib" ]
null
null
null
src/FLAMCLP.c
limes-datentechnik-gmbh/FLAMCLEP
280ad65c4aebbf8242a5970b040b0fe010cd7414
[ "Zlib" ]
null
null
null
/** * @file FLAMCLP.c * @brief LIMES Command Line Parser in ANSI-C * @author limes datentechnik gmbh * @date 06.03.2015 * @copyright (c) 2015 limes datentechnik gmbh * www.flam.de * * LIMES Command Line Executor (CLE) in ANSI-C * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute * it freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must * not claim that you wrote the original software. If you use this * software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must * not be misrepresented as being the original software. * 3. This notice may not be removed or altered from any source * distribution. * * If you need professional services or support for this library please * contact support@flam.de. **********************************************************************/ /* Standard-Includes **************************************************/ #include <time.h> #include <errno.h> #include <ctype.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <locale.h> #if defined(__DEBUG__) && defined(__FL5__) //# define __HEAP_STATISTIC__ # include "CHKMEM.h" #endif #include "CLEPUTL.h" /* Include der Schnittstelle ******************************************/ #include "FLAMCLP.h" /* Definition der Version von FL-CLP ********************************** * * Changelog: * 1.1.1: Adjust version and about * 1.1.2: Change escape sequence for strings and supplements to two times the same character (''/"") * 1.1.3: Support of command line or property file only parameter * 1.1.4: Support of dummy (DMY) flag for parameter which are not visible on command line and property file * 1.1.5: Support the use of different symbol tables for property and command line parsing * 1.1.6: Add pcClpError to provide an error message for an error code * 1.1.7: Add possibility to use getenv to override hard coded default values * 1.1.8: An empty path "" are handled like NULL pointer path * 1.1.9: Allow strings without ' like keyword=...SPACE/SEP and switch between " and ' * 1.1.10: Add new flag to prevent print outs in clear form for passwords or other critical information * 1.1.11: Add overlays and objects to parsed parameter list * 1.1.12: Correct generation of manpages * 1.1.13: Keywords can now be preceded by '-' or '--' * 1.1.14: Don't print manpage twice at end of path anymore * 1.1.15: Support of new flags to define default interpretation of binary strings (CHR/ASC/EBC/HEX) * 1.1.16: Get selections, object and overlays for aliases up and running * 1.1.17: Support line comment (initiated with ';' up to '\n') * 1.1.18: Support object without parenthesis and overlays without dot * 1.1.19: Extent strxcmp() to support keyword compare and stop flag * 1.1.20: Support flag to print all or only defined (set) properties * 1.1.21: Support flag to print aliases at help (if false aliases are now suppressed at help) * 1.1.22: Support property generation up to single parameters * 1.1.23: eliminate uiFlg to manage file properties and command line with the same symbol table * 1.1.24: Add support for parameter files for each object and overlay (read.text=parfilename.txt) * 1.1.25: Invent CLEPUTL.h/c * 1.1.26: Eliminate static variables to get more thread safe * 1.1.27: To save memory and simplify the usage of CLP the pointer to the data structure can be NULL * 1.1.28: Improve error handling (count rows and cols, print error msg and build error structure) and support isPfl-Flag * 1.1.29: Replace static variables for version and about to make it possible to use the lib as DLL * 1.1.30: Rework to make CLEP better usable with DLLs (eliminate global variables, adjust about and version, adjust includes) * 1.1.31: fix memory leaks found with memchecker * 1.1.32: use SELECTION as Type in argument lists if the selection flag on and KEYWORD for constant definitions * 1.1.33: If no SELECTION but keywords possible the help shows a additional statement that you can enter also a value * 1.1.34: Get properties from environment variables and property files working * 1.1.35: Correct error position (source, row, column) if property parsing used * 1.1.36: Use snprintf() instead of sprintf() for static array strings * 1.1.37: Support file name mapping (+/<Cuser>) * 1.1.38: Use GETENV() makro * 1.1.39: Rework all format strings (replace "\'" with "'" for better readability) * 1.1.40: Print synopsis at help if keyword man is used * 1.1.41: Support OID as default for numbers if CLPFLG_DEF defined (if only the keyword used (DECODE)) * 1.1.42: Correct order (scan new token as last step) to fix issue 614 * 1.1.43: fix null pointer references * 1.1.44: Code page specific interpretation of punctuation characters on EBCDIC systems * 1.1.45: Replace unnecessary strlen() * 1.1.46: Change "###SECRET###" in "***SECRET***" to eliminate dia-critical characters * 1.1.47: Make qualifier for commands variable in ClpDocu * 1.1.48: Support dia-critical characters in string lexemes (add new macro isStr()) * 1.1.49: Fix issue 684: correct length in error messages (longer then n) * 1.1.50: Support replacement of &{OWN} and &{PGM} in man pages * 1.1.51: Fix cut & paste error at syntax error print out * 1.1.52: Add symbol table walk and update functions * 1.1.53: Change flag (isSet) to method (siMtd) to better define property printing * 1.1.54: Support links in overlay of overlays * 1.1.55: Fix CLEP lexical error message "Character ('%c') not valid" * 1.1.56: Fix build scan issue: Access to field 'psDep' results in a dereference of a null pointer (loaded from variable 'psArg') * 1.1.57: Support filename type for strings to read passwords from files (f'pwdfile.txt') - string file support * 1.1.58: Print time string for time entry in parsed parameter list * 1.1.59: Support shorted time entries (0t2015, 0t2015/04/01, 0t2015/04/02.23:13) * 1.1.60: Fix wrong hour at time entry if daylight saving time used * 1.1.62: Support optional headline in the first level of docu generation * 1.1.63: Accept decimal number as a float if it is a integer and the expected type is float * 1.1.64: Make acPro and acSrc dynamic to reduce memory consumption of symbol table * 1.1.65: Support also grave (` - 0x60) to enclose strings * 1.1.66: Add new flag bit to separate default from defined properties * 1.1.67: Correct type of variable t to time_t to get correct time on z/OS * 1.1.68: Correct relative time entry (use localtime() instead of gmtime() for mktime()) * 1.1.69: Don't add OID to array of OIDs if overlay of overlay used if OID==0 * 1.1.70: Add info function to print help message for a path * 1.1.71: Add CLPPRO_MTD_DOC for property print out * 1.1.72: Don't print if print file NULL * 1.2.73: Make acLst dynamic (pcLst, introduce srprintc) * 1.2.74: Separate CLPMAX_KYW/SRCSIZ from CLPMAX_LEXSIZ (introduce srprintf, limit key word length to a maximum of 63) * 1.2.75: Rename pcSrc in pcInp and make source qualifier dynamic * 1.2.76: Make lexeme dynamic in length * 1.2.77: Make prefix and path dynamic in length * 1.2.78: Make message dynamic in length * 1.2.79: Add parameter file support for arrays * 1.2.80: Support command string replacements by environment variables (<HOME>) * 1.2.81: Support constant expression (blksiz=64*KiB) * 1.2.82: Read siNow from environment variable * 1.2.83: Support CLPFLG_TIM to mark numbers as time values * 1.2.84: Support expression including symbol keywords which are defined (FROM=NOW-10Day TO=FROM[0]+5DAY) * 1.2.85: Add new CLPFLG_DLM to ensure an additional element as delimiter in arrays (required if CLPFLG_CNT cannot used (overlay with arrays)) * 1.2.86: Support dynamic strings and arrays as new flag CLPFLG_DYN * 1.2.87: Support string mapping functions for build of CLP structure * 1.2.88: Make remaining parameter file names dynamic * 1.2.89: Check if keyword and alias contain only valid letters * 1.2.90: Use realloc_nowarn macro for realloc() to give the possibility to use own defines for it * 1.2.91: Support separation of signed and unsigned numbers over a new flag * 1.2.92: Support type string to determine unsigned flag * 1.2.93: Support literal or static variable assignments for dynamic values in CLP structure * 1.2.94: Reduce memory of symbol table (don't store pcAli use psAli instead) * 1.2.95: Add new link to get the index (byte offset) of the current key word in the CLP string * 1.2.96: Set locale to "C" close to strtod (remove from open and close functions) * 1.2.97: Support NULL pointer for owner, program, command, help and manpage at ClpOpen (path don't start with '.' in such case) * 1.2.98: Use threat safe time functions * 1.2.99: avoid using set locale for strtod * 1.2.100: Support XML path string mapping with '(' and ')' instead of '<' and '>' * 1.2.101: Add xxYEAR2 string literal for year without century (YY) * 1.2.102: Add missing frees if ClpOpen failed * 1.2.103: Add flag hidden (CLPFLG_HID) to support hidden parameter * 1.2.104: Separate version and build number with hyphen instead of dot * 1.2.105: Support parameter list without '***SECRET***' replacement * 1.2.106: Allow help, info, syntax, docu and proterty generation without command as start of the path * 1.2.107: Correct '***SECRET***' replacement * 1.2.108: Don't support disablement of '***SECRET***' replacement in trace messages * 1.2.109: Use new file2str interface * 1.2.110: Support callback function for file to string * 1.2.111: Support escaping of CLP string (&xxx; or &nnnn<...>) * 1.2.112: Fix replacement of environment variables and increase amount from 32 to 256 * 1.2.113: Support critical character escape sequences for strings, file names and key labels * 1.2.114: Fix reallocation with pointer change for lexeme if key word at scanning detected * 1.2.115: Support empty strings behind assignments (comment= ...) * 1.2.116: Don't parse but accept parameter files if isPfl==2 * 1.2.117: Required strings are only terminated with separation characters (space or comma), comment or close bracket on level 0 * 1.2.118: Use main keyword instead of alias in parsed parameter list * 1.2.119: Support parameter files for arguments (keyword=>filename) * 1.2.120: Support arrays of simple values after assignment (keyword=hugo,berta detlef) * 1.2.121: Index for variables in expressions must be enclosed in curly brackets and only a number is useless * 1.2.122: Support additional access control check possibility for each write in CLP structure * 1.2.123: Increase maximal amount of parameter per object from 256 to 512 (CLPMAX_TABCNT) * 1.2.124: Use type of function and not type of pointer to function (usable for pragma's) * 1.2.125: Add vdClpReset function to reset after an application handled error * 1.3.126: Support better docu generation and headings as single line variants (= Hdl1, ==Hdl2, ...) * 1.3.127: Support documentation generation by callback function (for built-in HTMLDOC) * 1.3.128: Use trace macro with fflush and time stamp, add symbols find to parse trace **/ #define CLP_VSN_STR "1.3.128" #define CLP_VSN_MAJOR 1 #define CLP_VSN_MINOR 3 #define CLP_VSN_REVISION 128 /* Definition der Konstanten ******************************************/ #define CLPMAX_TABCNT 512 #define CLPMAX_HDEPTH 128 #define CLPMAX_KYWLEN 63 #define CLPMAX_KYWSIZ 64 #define CLPMAX_BUFCNT 256 #define CLPINI_LEXSIZ 1024 #define CLPINI_LSTSIZ 1024 #define CLPINI_SRCSIZ 1024 #define CLPINI_MSGSIZ 1024 #define CLPINI_PRESIZ 1024 #define CLPINI_PATSIZ 1024 #define CLPINI_VALSIZ 128 #define CLPINI_PTRCNT 128 #define CLPTOK_INI 0 #define CLPTOK_END 1 #define CLPTOK_KYW 2 #define CLPTOK_RBO 3 #define CLPTOK_RBC 4 #define CLPTOK_SBO 5 #define CLPTOK_SBC 6 #define CLPTOK_SGN 7 #define CLPTOK_DOT 8 #define CLPTOK_ADD 9 #define CLPTOK_SUB 10 #define CLPTOK_MUL 11 #define CLPTOK_DIV 12 #define CLPTOK_STR 13 #define CLPTOK_NUM 14 #define CLPTOK_FLT 15 #define CLPTOK_SAB 16 #define CLPTOK_CBO 17 #define CLPTOK_CBC 18 #define isPrnInt(p,v) (CLPISF_PWD(p->psStd->uiFlg)?((I64)0):(v)) #define isPrnFlt(p,v) (CLPISF_PWD(p->psStd->uiFlg)?((F64)0.0):(v)) #define isPrnStr(p,v) ((CLPISF_PWD(p->psStd->uiFlg) && psHdl->isPwd)?("***SECRET***"):(v)) #define isPrnLen(p,v) (CLPISF_PWD(p->psStd->uiFlg)?((int)0):(v)) #define GETALI(sym) (((sym)->psStd->psAli!=NULL)?(sym)->psStd->psAli->psStd->pcKyw:NULL) #define GETKYW(sym) (((sym)->psStd->psAli!=NULL)?(sym)->psStd->psAli->psStd->pcKyw:(sym)->psStd->pcKyw) #ifndef realloc_nowarn # define realloc_nowarn realloc #endif #define TRACE(f,...) if ((f)!=NULL) {\ char acTs[24];\ fprintf((f),"%s ",cstime(0,acTs));\ efprintf((f),__VA_ARGS__);\ fflush((f));\ } static const char* apClpTok[]={ "INI", "END", "KEYWORD", "ROUND-BRACKET-OPEN", "ROUND-BRACKET-CLOSE", "SQUARED-BRACKET-OPEN", "SQUARED-BRACKET-CLOSE", "SIGN", "DOT", "ADD", "SUB", "MUL", "DIV", "STRING", "NUMBER", "FLOAT", "SIGN-ANGEL-BRACKET", "CURLY-BRACKET-OPEN", "CURLY-BRACKET-CLOSE"}; static const char* apClpTyp[]={ "NO-TYP", "SWITCH", "NUMBER", "FLOAT", "STRING", "OBJECT", "OVERLAY"}; #define CLP_ASSIGNMENT "=" static const char* pcClpErr(int siErr) { switch (siErr) { case CLPERR_LEX: return("LEXICAL-ERROR"); case CLPERR_SYN: return("SYNTAX-ERROR"); case CLPERR_SEM: return("SEMANTIC-ERROR"); case CLPERR_TYP: return("TYPE-ERROR"); case CLPERR_TAB: return("TABLE-ERROR"); case CLPERR_SIZ: return("SIZE-ERROR"); case CLPERR_PAR: return("PARAMETER-ERROR"); case CLPERR_MEM: return("MEMORY-ERROR"); case CLPERR_INT: return("INTERNAL-ERROR"); case CLPERR_SYS: return("SYSTEM-ERROR"); case CLPERR_AUT: return("AUTHORIZATION-ERROR"); default : return("UNKNOWN-ERROR"); } } /* Definition der Strukturen ******************************************/ typedef struct Std { const char* pcKyw; struct Sym* psAli; unsigned int uiFlg; int siKwl; int siLev; int siPos; }TsStd; typedef struct Fix { const char* pcDft; const char* pcMan; const char* pcHlp; char* pcPro; int siTyp; int siMin; int siMax; int siSiz; int siOfs; int siOid; struct Sym* psLnk; struct Sym* psCnt; struct Sym* psOid; struct Sym* psInd; struct Sym* psEln; struct Sym* psSln; struct Sym* psTln; char* pcSrc; int siRow; }TsFix; typedef struct Var { void* pvDat; void* pvPtr; int siCnt; int siLen; int siRst; int siInd; }TsVar; typedef struct Sym { struct Sym* psNxt; struct Sym* psBak; struct Sym* psDep; struct Sym* psHih; TsStd* psStd; TsFix* psFix; TsVar* psVar; }TsSym; typedef struct Ptr { void* pvPtr; int siSiz; } TsPtr; typedef struct ParamDescriptor { const char* pcAnchorPrefix; const char* pcCommand; const char* pcPath; const char* pcNum; } TsParamDescription; static const TsParamDescription stDefaultParamDesc = { "", "" ,"", "" }; typedef struct Hdl { const char* pcOwn; const char* pcPgm; const char* pcBld; const char* pcCmd; const char* pcMan; const char* pcHlp; const char* pcInp; const char* pcCur; const char* pcOld; const char* pcDep; const char* pcOpt; const char* pcEnt; const char* pcRow; int siMkl; int isOvl; int isChk; int isPwd; int isCas; int isPfl; int isEnv; int siTok; int isSep; size_t szLex; char* pcLex; size_t szSrc; char* pcSrc; TsSym* psTab; TsSym* psSym; TsSym* psOld; void* pvDat; FILE* pfHlp; FILE* pfErr; FILE* pfSym; FILE* pfScn; FILE* pfPrs; FILE* pfBld; const TsSym* apPat[CLPMAX_HDEPTH]; size_t szMsg; char* pcMsg; size_t szPre; char* pcPre; size_t szPat; char* pcPat; size_t szLst; char* pcLst; int siBuf; size_t pzBuf[CLPMAX_BUFCNT]; char* apBuf[CLPMAX_BUFCNT]; int siRow; int siCol; int siErr; unsigned int uiLev; I64 siNow; I64 siRnd; int siPtr; int szPtr; TsPtr* psPtr; const TsSym* psVal; void* pvGbl; void* pvF2s; TfF2S* pfF2s; void* pvSaf; TfSaf* pfSaf; long siSym; void* pvPrn; TfClpPrintPage* pfPrn; int isMan; int isDep; int isAnc; int isNbr; int isShl; int isIdt; int isPat; int siPs1; int siPs2; int siPr3; } TsHdl; /* Deklaration der internen Funktionen ********************************/ static TsSym* psClpSymIns( void* pvHdl, const int siLev, const int siPos, const TsClpArgument* psArg, TsSym* psHih, TsSym* psCur); static int siClpSymIni( void* pvHdl, const int siLev, const TsClpArgument* psArg, const TsClpArgument* psTab, TsSym* psHih, TsSym** ppFst); static int siClpSymCal( void* pvHdl, int siLev, TsSym* psArg, TsSym* psTab); static int siClpSymFnd( void* pvHdl, const int siLev, const char* pcKyw, const TsSym* psTab, TsSym** ppArg, int* piElm); static void vdClpSymPrn( void* pvHdl, int siLev, TsSym* psSym); static void vdClpSymTrc( void* pvHdl); static void vdClpSymDel( TsSym* psSym); static char* pcClpUnEscape( void* pvHdl, const char* pcInp); static int siClpScnNat( void* pvHdl, FILE* pfErr, FILE* pfTrc, const char** ppCur, size_t* pzLex, char** ppLex, int siTyp, const TsSym* psArg, int* piSep, const TsSym** ppVal); static int siClpScnSrc( void* pvHdl, int siTyp, const TsSym* psArg); static int siClpConNat( void* pvHdl, FILE* pfErr, FILE* pfTrc, const char* pcKyw, size_t* pzLex, char** ppLex, const int siTyp, const TsSym* psArg); static int siClpConSrc( void* pvHdl, const int isChk, const TsSym* psArg); static int siClpPrsMain( void* pvHdl, TsSym* psTab, int* piOid); static int siClpPrsParLst( void* pvHdl, const int siLev, const TsSym* psTab); static int siClpPrsPar( void* pvHdl, const int siLev, const int siPos, const TsSym* psTab, int* piOid); static int siClpPrsNum( void* pvHdl, const int siLev, const int siPos, TsSym* psArg); static int siClpPrsSwt( void* pvHdl, const int siLev, const int siPos, TsSym* psArg); static int siClpPrsSgn( void* pvHdl, const int siLev, const int siPos, TsSym* psArg); static int siClpPrsFil( void* pvHdl, const int siLev, const int siPos, const int isAry, TsSym* psArg); static int siClpAcpFil( void* pvHdl, const int siLev, const int siPos, const int isAry, TsSym* psArg); static int siClpPrsObjWob( void* pvHdl, const int siLev, const int siPos, TsSym* psArg); static int siClpPrsObj( void* pvHdl, const int siLev, const int siPos, TsSym* psArg); static int siClpPrsOvl( void* pvHdl, const int siLev, const int siPos, TsSym* psArg); static int siClpPrsAry( void* pvHdl, const int siLev, const int siPos, TsSym* psArg); static int siClpPrsValLstFlexible( void* pvHdl, const int siLev, const int siTok, TsSym* psArg); static int siClpPrsValLstOnlyArg( void* pvHdl, const int siLev, const int isEnd, const int siTok, TsSym* psArg); static int siClpPrsObjLst( void* pvHdl, const int siLev, TsSym* psArg); static int siClpPrsOvlLst( void* pvHdl, const int siLev, TsSym* psArg); static int siClpPrsVal( void* pvHdl, const int siLev, const int siPos, const int isAry, TsSym* psArg); static int siClpPrsProLst( void* pvHdl, const TsSym* psTab); static int siClpPrsPro( void* pvHdl, const TsSym* psTab); static int siClpPrsKywLst( void* pvHdl, size_t* pzPat, char** ppPat); static int siClpBldPro( void* pvHdl, const char* pcPat, const char* pcPro, const int siRow); static int siClpBldLnk( void* pvHdl, const int siLev, const int siPos, const int siNum, TsSym* psArg, const int isApp); static int siClpBldSwt( void* pvHdl, const int siLev, const int siPos, TsSym* psArg); static int siClpBldNum( void* pvHdl, const int siLev, const int siPos, TsSym* psArg); static int siClpBldLit( void* pvHdl, const int siLev, const int siPos, TsSym* psArg, const char* pcVal); static int siClpIniMainObj( void* pvHdl, TsSym* psTab, TsVar* psSav); static int siClpFinMainObj( void* pvHdl, TsSym* psTab, const TsVar* psSav); static int siClpIniMainOvl( void* pvHdl, TsSym* psTab, TsVar* psSav); static int siClpFinMainOvl( void* pvHdl, TsSym* psTab, const TsVar* psSav, const int siOid); static int siClpIniObj( void* pvHdl, const int siLev, const int siPos, TsSym* psArg, TsSym** ppDep, TsVar* psSav); static int siClpFinObj( void* pvHdl, const int siLev, const int siPos, TsSym* psArg, TsSym* psDep, const TsVar* psSav); static int siClpIniOvl( void* pvHdl, const int siLev, const int siPos, TsSym* psArg, TsSym** ppDep, TsVar* psSav); static int siClpFinOvl( void* pvHdl, const int siLev, const int siPos, TsSym* psArg, TsSym* psDep, const TsVar* psSav, const int siOid); static int siClpSetDefault( void* pvHdl, const int siLev, const int siPos, TsSym* psArg); static void vdClpPrnArg( void* pvHdl, FILE* pfOut, const int siLev, const char* pcKyw, const char* pcAli, const int siKwl, const int siTyp, const char* pcHlp, const char* pcDft, const unsigned int isSel, const unsigned int isCon); static void vdClpPrnArgTab( void* pvHdl, FILE* pfOut, const int siLev, int siTyp, const TsSym* psTab); static void vdClpPrnAli( FILE* pfOut, const char* pcSep, const TsSym* psTab); static void vdClpPrnOpt( FILE* pfOut, const char* pcSep, const int siTyp, const TsSym* psTab); static int siClpPrnSyn( void* pvHdl, FILE* pfOut, const int isPat, const int siLev, const TsSym* psArg); static int siClpPrnCmd( void* pvHdl, FILE* pfOut, const int siCnt, const int siLev, const int siDep, const TsSym* psArg, const TsSym* psTab, const int isSkr, const int isMin); static int siClpPrnHlp( void* pvHdl, FILE* pfOut, const int isAli, const int siLev, const int siDep, const int siTyp, const TsSym* psTab, const int isFlg); static int siClpPrnDoc( void* pvHdl, FILE* pfDoc, const int siLev, const TsParamDescription* psParamDesc, const TsSym* psArg, const TsSym* psTab); static int siClpPrnPro( void* pvHdl, FILE* pfOut, int isMan, const int siMtd, const int siLev, const int siDep, const TsSym* psTab, const char* pcArg); static int siFromNumberLexeme( void* pvHdl, const int siLev, TsSym* psArg, const char* pcVal, I64* piVal); static int siFromFloatLexeme( void* pvHdl, const int siLev, TsSym* psArg, const char* pcVal, double* pfVal); static const char* fpcPre( void* pvHdl, const int siLev); static const char* fpcPat( void* pvHdl, const int siLev); static inline int CLPERR(TsHdl* psHdl,int siErr, char* pcMsg, ...) { const char* p; va_list argv; int i,l,f=FALSE; const char* pcErr=pcClpErr(siErr); char acMsg[1024]; va_start(argv,pcMsg); vsnprintf(acMsg,sizeof(acMsg),pcMsg,argv); va_end(argv); srprintf(&psHdl->pcMsg,&psHdl->szMsg,strlen(pcErr)+strlen(acMsg),"%s: %s",pcErr,acMsg); psHdl->siErr=siErr; if (psHdl->pcRow!=NULL && psHdl->pcOld>=psHdl->pcRow) { psHdl->siCol=(int)((psHdl->pcOld-psHdl->pcRow)+1); } else psHdl->siCol=0; if (psHdl->pfErr!=NULL) { fprintf(psHdl->pfErr,"%s:\n%s %s\n",pcErr,fpcPre(psHdl,0),acMsg); if (psHdl->pcSrc!=NULL && psHdl->pcInp!=NULL && psHdl->pcOld!=NULL && psHdl->pcCur!=NULL && (psHdl->pcCur>psHdl->pcInp || psHdl->pcLst!=NULL || psHdl->siRow)) { if (strcmp(psHdl->pcSrc,CLPSRC_CMD)==0) { fprintf(psHdl->pfErr,"%s Cause: Row=%d Column=%d from command line\n", fpcPre(psHdl,1),psHdl->siRow,psHdl->siCol); } else if (strcmp(psHdl->pcSrc,CLPSRC_PRO)==0) { fprintf(psHdl->pfErr,"%s Cause: Row=%d Column=%d from property list\n", fpcPre(psHdl,1),psHdl->siRow,psHdl->siCol); } else if (strncmp(psHdl->pcSrc,CLPSRC_ENV,strlen(CLPSRC_ENV))==0) { fprintf(psHdl->pfErr,"%s Cause: Row=%d Column=%d from environment variable '%s'\n", fpcPre(psHdl,1),psHdl->siRow,psHdl->siCol,psHdl->pcSrc+strlen(CLPSRC_ENV)); } else if (strncmp(psHdl->pcSrc,CLPSRC_DEF,strlen(CLPSRC_DEF))==0) { fprintf(psHdl->pfErr,"%s Cause: Row=%d Column=%d from default value of argument '%s'\n",fpcPre(psHdl,1),psHdl->siRow,psHdl->siCol,psHdl->pcSrc+strlen(CLPSRC_DEF)); } else if (strncmp(psHdl->pcSrc,CLPSRC_PRF,strlen(CLPSRC_PRF))==0) { fprintf(psHdl->pfErr,"%s Cause: Row=%d Column=%d supplement from property file '%s'\n", fpcPre(psHdl,1),psHdl->siRow,psHdl->siCol,psHdl->pcSrc+strlen(CLPSRC_PRF)); } else if (strncmp(psHdl->pcSrc,CLPSRC_PAF,strlen(CLPSRC_PAF))==0) { fprintf(psHdl->pfErr,"%s Cause: Row=%d Column=%d from parameter file '%s'\n", fpcPre(psHdl,1),psHdl->siRow,psHdl->siCol,psHdl->pcSrc+strlen(CLPSRC_PAF)); } else if (strncmp(psHdl->pcSrc,CLPSRC_SRF,strlen(CLPSRC_SRF))==0) { fprintf(psHdl->pfErr,"%s Cause: Row=%d Column=%d from string file '%s'\n", fpcPre(psHdl,1),psHdl->siRow,psHdl->siCol,psHdl->pcSrc+strlen(CLPSRC_SRF)); } else if (strncmp(psHdl->pcSrc,CLPSRC_CMF,strlen(CLPSRC_CMF))==0) { fprintf(psHdl->pfErr,"%s Cause: Row=%d Column=%d from command file '%s'\n", fpcPre(psHdl,1),psHdl->siRow,psHdl->siCol,psHdl->pcSrc+strlen(CLPSRC_CMF)); } else { fprintf(psHdl->pfErr,"%s Cause: Row=%d Column=%d in file '%s'\n", fpcPre(psHdl,1),psHdl->siRow,psHdl->siCol,psHdl->pcSrc); } if (psHdl->pcRow!=NULL) { fprintf(psHdl->pfErr,"%s \"",fpcPre(psHdl,1)); for (p=psHdl->pcRow;!iscntrl(*p);p++) fprintf(psHdl->pfErr,"%c",*p); fprintf(psHdl->pfErr,"\"\n"); if (psHdl->pcCur==psHdl->pcRow) { fprintf(psHdl->pfErr,"%s %c",fpcPre(psHdl,1),C_CRT); } else { fprintf(psHdl->pfErr,"%s ",fpcPre(psHdl,1)); } for (p=psHdl->pcRow;!iscntrl(*p);p++) { if (p>=psHdl->pcOld && p<psHdl->pcCur) { f=TRUE; fprintf(psHdl->pfErr,"%c",C_CRT); } else { fprintf(psHdl->pfErr," "); } } if (f) { fprintf(psHdl->pfErr," \n"); } else { fprintf(psHdl->pfErr,"%c\n",C_CRT); } } l=(psHdl->pcLst!=NULL)?strlen(psHdl->pcLst):0; if (l>1) { l--; fprintf(psHdl->pfErr,"%s After successful parsing of arguments below:\n",fpcPre(psHdl,0)); fprintf(psHdl->pfErr,"%s ",fpcPre(psHdl ,1)); for (i=0;i<l;i++) { if (psHdl->pcLst[i]=='\n') { fprintf(psHdl->pfErr,"\n%s ",fpcPre(psHdl,1)); } else fprintf(psHdl->pfErr,"%c",psHdl->pcLst[i]); } fprintf(psHdl->pfErr,"\n"); } else fprintf(psHdl->pfErr,"%s Something is wrong with the first argument\n",fpcPre(psHdl,0)); } } return(siErr); } static inline void CLPERRADD(TsHdl* psHdl,int siLev, char* pcMsg, ...) { if (psHdl->pfErr!=NULL) { va_list argv; fprintf(psHdl->pfErr,"%s ",fpcPre(psHdl,siLev)); va_start(argv,pcMsg); vfprintf(psHdl->pfErr,pcMsg,argv); va_end(argv); fprintf(psHdl->pfErr,"\n"); } } static inline I64 ClpRndFnv(const I64 siRnd) { unsigned char* p=(unsigned char*)&siRnd; U64 h=0xcbf29ce48422232LLU; h^=p[0]; h*=0x100000001b3LLU; // cppcheck-suppress objectIndex h^=p[1]; h*=0x100000001b3LLU; // cppcheck-suppress objectIndex h^=p[2]; h*=0x100000001b3LLU; // cppcheck-suppress objectIndex h^=p[3]; h*=0x100000001b3LLU; // cppcheck-suppress objectIndex h^=p[4]; h*=0x100000001b3LLU; // cppcheck-suppress objectIndex h^=p[5]; h*=0x100000001b3LLU; // cppcheck-suppress objectIndex h^=p[6]; h*=0x100000001b3LLU; // cppcheck-suppress objectIndex h^=p[7]; h*=0x100000001b3LLU; return h; } extern void* pvClpAlloc( void* pvHdl, void* pvPtr, int siSiz, int* piInd) { TsHdl* psHdl=(TsHdl*)pvHdl; if (pvPtr==NULL) { if (siSiz>0) { if (psHdl->siPtr>=psHdl->szPtr) { void* pvHlp=realloc_nowarn(psHdl->psPtr,sizeof(TsPtr)*(psHdl->szPtr+CLPINI_PTRCNT)); if (pvHlp==NULL) return(NULL); psHdl->psPtr=pvHlp; psHdl->szPtr+=CLPINI_PTRCNT; } pvPtr=calloc(1,siSiz); if (pvPtr!=NULL) { psHdl->psPtr[psHdl->siPtr].pvPtr=pvPtr; psHdl->psPtr[psHdl->siPtr].siSiz=siSiz; if (piInd!=NULL) *piInd=psHdl->siPtr; psHdl->siPtr++; } } else return(NULL); } else { if (piInd!=NULL && *piInd>=0 && *piInd<psHdl->siPtr && psHdl->psPtr[*piInd].pvPtr==pvPtr) { pvPtr=realloc_nowarn(pvPtr,siSiz); if (pvPtr!=NULL) { if (psHdl->psPtr[*piInd].siSiz<siSiz) { memset(((char*)pvPtr)+psHdl->psPtr[*piInd].siSiz,0,siSiz-psHdl->psPtr[*piInd].siSiz); } psHdl->psPtr[*piInd].pvPtr=pvPtr; psHdl->psPtr[*piInd].siSiz=siSiz; } } else { for (int i=0;i<psHdl->siPtr;i++) { if (psHdl->psPtr[i].pvPtr==pvPtr) { pvPtr=realloc_nowarn(pvPtr,siSiz); if (pvPtr!=NULL) { if (psHdl->psPtr[i].siSiz<siSiz) { memset(((char*)pvPtr)+psHdl->psPtr[i].siSiz,0,siSiz-psHdl->psPtr[i].siSiz); } psHdl->psPtr[i].pvPtr=pvPtr; psHdl->psPtr[i].siSiz=siSiz; if (piInd!=NULL) *piInd=i; } return(pvPtr); } } return(pvClpAlloc(pvHdl,NULL,siSiz,piInd)); } } return(pvPtr); } static void vdClpFree( void* pvHdl) { TsHdl* psHdl=(TsHdl*)pvHdl; if (psHdl->psPtr!=NULL) { for (int i=0;i<psHdl->siPtr;i++) { if (psHdl->psPtr[i].pvPtr!=NULL) { free(psHdl->psPtr[i].pvPtr); psHdl->psPtr[i].pvPtr=NULL; psHdl->psPtr[i].siSiz=0; } } } } /* Implementierung der externen Funktionen ****************************/ extern const char* pcClpVersion(const int l, const int s, char* b) { snprintc(b,s,"%2.2d FLAM-CLP VERSION: %s-%u BUILD: %s %s %s\n",l,CLP_VSN_STR,__BUILDNR__,__BUILD__,__DATE__,__TIME__); return(b); } extern const char* pcClpAbout(const int l, const int s, char* b) { snprintc(b,s, "%2.2d Frankenstein Limes Command Line Parser (FLAM-CLP)\n" " Version: %s-%u Build: %s %s %s\n" " Copyright (C) limes datentechnik (R) gmbh\n" " This library is open source from the FLAM(R) project: http://www.flam.de\n" " for license see: https://github.com/limes-datentechnik-gmbh/flamclep\n" ,l,CLP_VSN_STR,__BUILDNR__,__BUILD__,__DATE__,__TIME__); return(b); } extern char* pcClpError( int siErr) { switch(siErr) { case CLP_OK :return("No error, everything O.K."); case CLPERR_LEX:return("Lexical error (determined by scanner)"); case CLPERR_SYN:return("Syntax error (determined by parser)"); case CLPERR_SEM:return("Semantic error (determined by builder)"); case CLPERR_TYP:return("Type error (internal error with argument types)"); case CLPERR_TAB:return("Table error (internal error with argument tables)"); case CLPERR_SIZ:return("Size error (internal error with argument tables and data structures)"); case CLPERR_PAR:return("Parameter error (internal error with argument tables and data structures)"); case CLPERR_MEM:return("Memory error (internal error with argument tables and data structures)"); case CLPERR_INT:return("Internal error (internal error with argument tables and data structures)"); case CLPERR_SYS:return("System error (internal error with argument tables and data structures)"); default: return("Unknown error (not expected)"); } } static int siOwnFile2String(void* gbl, void* hdl, const char* filename, char** buf, int* bufsize, char* errmsg, const int msgsiz) { (void)gbl; char* pcFil=dcpmapfil(filename); if (pcFil==NULL) return(-1); int siErr=file2str(hdl, pcFil, buf, bufsize, errmsg, msgsiz); free(pcFil); return(siErr); } extern void* pvClpOpen( const int isCas, const int isPfl, const int isEnv, const int siMkl, const char* pcOwn, const char* pcPgm, const char* pcBld, const char* pcCmd, const char* pcMan, const char* pcHlp, const int isOvl, const TsClpArgument* psTab, void* pvDat, FILE* pfHlp, FILE* pfErr, FILE* pfSym, FILE* pfScn, FILE* pfPrs, FILE* pfBld, const char* pcDep, const char* pcOpt, const char* pcEnt, TsClpError* psErr, void* pvGbl, void* pvF2S, TfF2S* pfF2S, void* pvSaf, TfSaf* pfSaf) { TsHdl* psHdl=NULL; const char* pcNow=NULL; I64 siNow=0; int siErr,i; if (psTab!=NULL) { psHdl=(TsHdl*)calloc(1,sizeof(TsHdl)); if (psHdl!=NULL) { psHdl->isCas=isCas; psHdl->isPfl=isPfl; psHdl->isEnv=isEnv; psHdl->siMkl=siMkl; psHdl->pcOwn=(pcOwn!=NULL)?pcOwn:""; psHdl->pcPgm=(pcPgm!=NULL)?pcPgm:""; psHdl->pcBld=(pcBld!=NULL)?pcBld:""; psHdl->pcCmd=(pcCmd!=NULL)?pcCmd:""; psHdl->pcMan=(pcMan!=NULL)?pcMan:""; psHdl->pcHlp=(pcHlp!=NULL)?pcHlp:""; psHdl->isOvl=isOvl; psHdl->pcInp=NULL; psHdl->pcCur=NULL; psHdl->pcOld=NULL; psHdl->psPtr=NULL; psHdl->szLex=CLPINI_LEXSIZ; psHdl->pcLex=(C08*)calloc(1,psHdl->szLex); psHdl->szSrc=CLPINI_SRCSIZ; psHdl->pcSrc=(C08*)calloc(1,psHdl->szSrc); psHdl->szPre=CLPINI_PRESIZ; psHdl->pcPre=(C08*)calloc(1,psHdl->szPre); psHdl->szPat=CLPINI_PATSIZ; psHdl->pcPat=(C08*)calloc(1,psHdl->szPat); psHdl->szLst=CLPINI_LSTSIZ; psHdl->pcLst=(C08*)calloc(1,psHdl->szLst); psHdl->szMsg=CLPINI_MSGSIZ; psHdl->pcMsg=(C08*)calloc(1,psHdl->szMsg); for (i=0;i<CLPMAX_BUFCNT;i++) { psHdl->pzBuf[i]=0; psHdl->apBuf[i]=NULL; } psHdl->pvDat=pvDat; psHdl->psTab=NULL; psHdl->psSym=NULL; psHdl->psOld=NULL; psHdl->isChk=FALSE; if (pfHlp==NULL) psHdl->pfHlp=stderr; else psHdl->pfHlp=pfHlp; psHdl->pfErr=pfErr; psHdl->pfSym=pfSym; psHdl->pfScn=pfScn; psHdl->pfPrs=pfPrs; psHdl->pfBld=pfBld; psHdl->pcDep=pcDep; psHdl->pcOpt=pcOpt; psHdl->pcEnt=pcEnt; psHdl->pvGbl=pvGbl; if (pfF2S!=NULL) { psHdl->pfF2s=pfF2S; psHdl->pvF2s=pvF2S; } else { psHdl->pfF2s=siOwnFile2String; psHdl->pvF2s=NULL; } psHdl->pvSaf=pvSaf; psHdl->pfSaf=pfSaf; #if defined(__DEBUG__) && defined(__HEAP_STATISTIC__) long siBeginCurHeapSize=CUR_HEAP_SIZE(); #endif siErr=siClpSymIni(psHdl,0,NULL,psTab,NULL,&psHdl->psTab); if (siErr<0) { vdClpSymDel(psHdl->psTab); SAFE_FREE(psHdl->pcLex); SAFE_FREE(psHdl->pcSrc); SAFE_FREE(psHdl->pcPre); SAFE_FREE(psHdl->pcPat); SAFE_FREE(psHdl->pcLst); SAFE_FREE(psHdl->pcMsg); free(psHdl); return(NULL); } #if defined(__DEBUG__) && defined(__HEAP_STATISTIC__) long siEndCurHeapSize=CUR_HEAP_SIZE(); printd("---------- CLP-SYMTAB-CUR_HEAP_SIZE(%ld)=>%ld(%ld) Count==%ld(%ld)\n",siBeginCurHeapSize,siEndCurHeapSize,siEndCurHeapSize-siBeginCurHeapSize,psHdl->siSym,(siEndCurHeapSize-siBeginCurHeapSize)/psHdl->siSym); #endif siErr=siClpSymCal(psHdl,0,NULL,psHdl->psTab); if (siErr<0) { vdClpSymDel(psHdl->psTab); SAFE_FREE(psHdl->pcLex); SAFE_FREE(psHdl->pcSrc); SAFE_FREE(psHdl->pcPre); SAFE_FREE(psHdl->pcPat); SAFE_FREE(psHdl->pcLst); SAFE_FREE(psHdl->pcMsg); free(psHdl); return(NULL); } vdClpSymTrc(psHdl); if (psErr!=NULL) { psErr->ppMsg=(const char**)&psHdl->pcMsg; psErr->ppSrc=(const char**)&psHdl->pcSrc; psErr->piRow=&psHdl->siRow; psErr->piCol=&psHdl->siCol; } psHdl->siNow=time(NULL); srand(psHdl->siNow+clock()); psHdl->siRnd=ClpRndFnv(rand()+clock()); pcNow=GETENV("CLP_NOW"); if (pcNow!=NULL && *pcNow) { siErr=siClpScnNat(psHdl,psHdl->pfErr,psHdl->pfScn,&pcNow,&psHdl->szLex,&psHdl->pcLex,CLPTYP_NUMBER,NULL,NULL,NULL); if (siErr==CLPTOK_NUM) { siErr=siFromNumberLexeme(psHdl,0,NULL,psHdl->pcLex,&siNow); if (siErr==0 && siNow>0) { siErr=siClpScnNat(psHdl,psHdl->pfErr,psHdl->pfScn,&pcNow,&psHdl->szLex,&psHdl->pcLex,0,NULL,NULL,NULL); if (siErr==CLPTOK_END) { psHdl->siNow=siNow; } } } } psHdl->siTok=CLPTOK_INI; } else { if (pfErr!=NULL) fprintf(pfErr,"Allocation of CLP structure failed\n"); } } else { if (pfErr!=NULL) fprintf(pfErr,"Parameter psTab is NULL\n"); } return((void*)psHdl); } extern void vdClpReset( void* pvHdl) { TsHdl* psHdl=(TsHdl*)pvHdl; if (psHdl!=NULL) { psHdl->siTok=CLPTOK_INI; } } extern int siClpParsePro( void* pvHdl, const char* pcSrc, const char* pcPro, const int isChk, char** ppLst) { TsHdl* psHdl=(TsHdl*)pvHdl; int siCnt; if (pcPro==NULL) return CLPERR(psHdl,CLPERR_INT,"Property string is NULL"); if (psHdl->pcLst!=NULL) psHdl->pcLst[0]=0x00; if (pcSrc!=NULL && *pcSrc) { srprintf(&psHdl->pcSrc,&psHdl->szSrc,strlen(CLPSRC_PRF)+strlen(pcSrc),"%s%s",CLPSRC_PRF,pcSrc); } else { srprintf(&psHdl->pcSrc,&psHdl->szSrc,strlen(CLPSRC_PRO),"%s",CLPSRC_PRO); } psHdl->pcInp=pcClpUnEscape(pvHdl,pcPro); if (psHdl->pcInp==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Un-escaping of property string failed"); } psHdl->pcCur=psHdl->pcInp; psHdl->pcOld=psHdl->pcInp; psHdl->pcRow=psHdl->pcInp; psHdl->isChk=isChk; psHdl->siRow=1; psHdl->siCol=0; psHdl->pcLex[0]=EOS; if (psHdl->siTok==CLPTOK_INI) { #if defined(__DEBUG__) && defined(__HEAP_STATISTIC__) long siBeginCurHeapSize=CUR_HEAP_SIZE(); #endif TRACE(psHdl->pfPrs,"PROPERTY-PARSER-BEGIN\n"); psHdl->siTok=siClpScnSrc(pvHdl,0,NULL); if (psHdl->siTok<0) return(psHdl->siTok); siCnt=siClpPrsProLst(pvHdl,psHdl->psTab); if (siCnt<0) return(siCnt); #if defined(__DEBUG__) && defined(__HEAP_STATISTIC__) long siEndCurHeapSize=CUR_HEAP_SIZE(); printd("---------- CLP-PRSPRO-CUR_HEAP_SIZE(%ld)=>%ld(%ld)\n",siBeginCurHeapSize,siEndCurHeapSize,siEndCurHeapSize-siBeginCurHeapSize); #endif if (psHdl->siTok==CLPTOK_END) { psHdl->siTok=CLPTOK_INI; psHdl->pcInp=NULL; psHdl->pcCur=NULL; psHdl->pcOld=NULL; psHdl->pcLex[0]=EOS; psHdl->isChk=FALSE; TRACE(psHdl->pfPrs,"PROPERTY-PARSER-END(CNT=%d)\n",siCnt); if (ppLst!=NULL) *ppLst=psHdl->pcLst; return(siCnt); } else { if (ppLst!=NULL) *ppLst=psHdl->pcLst; return CLPERR(psHdl,CLPERR_SYN,"Last token (%s) of property list is not EOS",apClpTok[psHdl->siTok]); } } else { if (ppLst!=NULL) *ppLst=psHdl->pcLst; return CLPERR(psHdl,CLPERR_SYN,"Initial token (%s) in handle is not valid",apClpTok[psHdl->siTok]); } } extern int siClpParseCmd( void* pvHdl, const char* pcSrc, const char* pcCmd, const int isChk, const int isPwd, int* piOid, char** ppLst) { TsHdl* psHdl=(TsHdl*)pvHdl; int siCnt; if (pcCmd==NULL) return CLPERR(psHdl,CLPERR_INT,"Command string is NULL"); if (psHdl->pcLst!=NULL) psHdl->pcLst[0]=0x00; if (pcSrc!=NULL && *pcSrc) { srprintf(&psHdl->pcSrc,&psHdl->szSrc,strlen(CLPSRC_CMF)+strlen(pcSrc),"%s%s",CLPSRC_CMF,pcSrc); } else { srprintf(&psHdl->pcSrc,&psHdl->szSrc,strlen(CLPSRC_CMD),"%s",CLPSRC_CMD); } psHdl->pcInp=pcClpUnEscape(pvHdl,pcCmd); if (psHdl->pcInp==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Un-escaping of command string failed"); } psHdl->pcCur=psHdl->pcInp; psHdl->pcOld=psHdl->pcInp; psHdl->pcRow=psHdl->pcInp; psHdl->isChk=isChk; psHdl->isPwd=isPwd; psHdl->siRow=1; psHdl->siCol=0; psHdl->pcLex[0]=EOS; if (psHdl->siTok==CLPTOK_INI) { #if defined(__DEBUG__) && defined(__HEAP_STATISTIC__) long siBeginCurHeapSize=CUR_HEAP_SIZE(); #endif TRACE(psHdl->pfPrs,"COMMAND-PARSER-BEGIN\n"); psHdl->siTok=siClpScnSrc(pvHdl,0,NULL); if (psHdl->siTok<0) return(psHdl->siTok); siCnt=siClpPrsMain(pvHdl,psHdl->psTab,piOid); if (siCnt<0) return (siCnt); #if defined(__DEBUG__) && defined(__HEAP_STATISTIC__) long siEndCurHeapSize=CUR_HEAP_SIZE(); printd("---------- CLP-PRSCMD-CUR_HEAP_SIZE(%ld)=>%ld(%ld)\n",siBeginCurHeapSize,siEndCurHeapSize,siEndCurHeapSize-siBeginCurHeapSize); #endif if (psHdl->siTok==CLPTOK_END) { psHdl->siTok=CLPTOK_INI; psHdl->pcInp=NULL; psHdl->pcCur=NULL; psHdl->pcOld=NULL; psHdl->pcLex[0]=EOS; psHdl->isChk=FALSE; TRACE(psHdl->pfPrs,"COMMAND-PARSER-END(CNT=%d)\n",siCnt); if (ppLst!=NULL) *ppLst=psHdl->pcLst; return(siCnt); } else { if (ppLst!=NULL) *ppLst=psHdl->pcLst; return CLPERR(psHdl,CLPERR_SYN,"Last token (%s) of parameter list is not EOS",apClpTok[psHdl->siTok]); } } else { if (ppLst!=NULL) *ppLst=psHdl->pcLst; return CLPERR(psHdl,CLPERR_SYN,"Initial token (%s) in handle is not valid",apClpTok[psHdl->siTok]); } } extern int siClpSyntax( void* pvHdl, const int isSkr, const int isMin, const int siDep, const char* pcPat) { TsHdl* psHdl=(TsHdl*)pvHdl; TsSym* psTab=psHdl->psTab; TsSym* psArg=NULL; const char* pcPtr=NULL; const char* pcKyw=NULL; char acKyw[CLPMAX_KYWSIZ]; int siErr,siLev,i; unsigned int l=strlen(psHdl->pcCmd); if (psHdl->pcLst!=NULL) psHdl->pcLst[0]=0x00; psHdl->pcInp=NULL; psHdl->pcCur=NULL; psHdl->pcOld=NULL; psHdl->pcRow=NULL; psHdl->siCol=0; psHdl->siRow=0; psHdl->pcLex[0]=EOS; psHdl->pcMsg[0]=EOS; psHdl->pcPat[0]=EOS; psHdl->pcPre[0]=EOS; srprintf(&psHdl->pcSrc,&psHdl->szSrc,0,":SYNTAX:"); if (pcPat!=NULL && *pcPat) { if (l==0 || strxcmp(psHdl->isCas,psHdl->pcCmd,pcPat,l,0,FALSE)==0) { if (l && strlen(pcPat)>l && pcPat[l]!='.') { return CLPERR(psHdl,CLPERR_SEM,"Path (%s) is not valid",pcPat); } for (siLev=0,pcPtr=l?strchr(pcPat,'.'):pcPat-1;pcPtr!=NULL && siLev<CLPMAX_HDEPTH;pcPtr=strchr(pcPtr+1,'.'),siLev++) { for (pcKyw=pcPtr+1,i=0;i<CLPMAX_KYWLEN && pcKyw[i]!=EOS && pcKyw[i]!='.';i++) acKyw[i]=pcKyw[i]; acKyw[i]=EOS; siErr=siClpSymFnd(pvHdl,siLev,acKyw,psTab,&psArg,NULL); if (siErr<0) return(siErr); psHdl->apPat[siLev]=psArg; psTab=psArg->psDep; } if (psTab!=NULL && !CLPISF_CON(psTab->psStd->uiFlg)) { siErr=siClpPrnCmd(pvHdl,psHdl->pfHlp,0,siLev,siLev+siDep,psArg,psTab,isSkr,isMin); if (siErr<0) return (siErr); } else { return CLPERR(psHdl,CLPERR_SEM,"Path (%s) contains too many or invalid qualifiers",pcPat); } } else { return CLPERR(psHdl,CLPERR_SEM,"Root of path (%s) does not match root of handle (%s)",pcPat,psHdl->pcCmd); } } else { siErr=siClpPrnCmd(pvHdl,psHdl->pfHlp,0,0,siDep,NULL,psHdl->psTab,isSkr,isMin); if (siErr<0) return (siErr); } if (isSkr && psHdl->pfHlp!=NULL) fprintf(psHdl->pfHlp,"\n"); return(CLP_OK); } extern const char* pcClpInfo( void* pvHdl, const char* pcPat) { TsHdl* psHdl=(TsHdl*)pvHdl; TsSym* psTab=psHdl->psTab; TsSym* psArg=NULL; const char* pcPtr=NULL; const char* pcKyw=NULL; char acKyw[CLPMAX_KYWSIZ]; int siErr,siLev,i; unsigned int l=strlen(psHdl->pcCmd); if (psHdl->pcLst!=NULL) psHdl->pcLst[0]=0x00; psHdl->pcInp=NULL; psHdl->pcCur=NULL; psHdl->pcOld=NULL; psHdl->pcRow=NULL; psHdl->siCol=0; psHdl->siRow=0; psHdl->pcLex[0]=EOS; psHdl->pcMsg[0]=EOS; psHdl->pcPat[0]=EOS; psHdl->pcPre[0]=EOS; srprintf(&psHdl->pcSrc,&psHdl->szSrc,0,":INFO:"); if (pcPat!=NULL && *pcPat) { if (l==0 || strxcmp(psHdl->isCas,psHdl->pcCmd,pcPat,l,0,FALSE)==0) { if (strlen(pcPat)<=l || pcPat[l]=='.') { for (siLev=0,pcPtr=l?strchr(pcPat,'.'):pcPat-1;pcPtr!=NULL && siLev<CLPMAX_HDEPTH;pcPtr=strchr(pcPtr+1,'.'),siLev++) { for (pcKyw=pcPtr+1,i=0;i<CLPMAX_KYWLEN && pcKyw[i]!=EOS && pcKyw[i]!='.';i++) acKyw[i]=pcKyw[i]; acKyw[i]=EOS; siErr=siClpSymFnd(pvHdl,siLev,acKyw,psTab,&psArg,NULL); if (siErr<0) return(""); psHdl->apPat[siLev]=psArg; psTab=psArg->psDep; } if (psArg!=NULL) return(psArg->psFix->pcHlp); } } } return(""); } extern int siClpHelp( void* pvHdl, const int siDep, const char* pcPat, const int isAli, const int isMan) { TsHdl* psHdl=(TsHdl*)pvHdl; TsSym* psTab=psHdl->psTab; TsSym* psArg=NULL; const char* pcPtr=NULL; const char* pcKyw=NULL; char acKyw[CLPMAX_KYWSIZ]; int siErr,siLev,i; unsigned int l=strlen(psHdl->pcCmd); if (psHdl->pcLst!=NULL) psHdl->pcLst[0]=0x00; psHdl->pcInp=NULL; psHdl->pcCur=NULL; psHdl->pcOld=NULL; psHdl->pcRow=NULL; psHdl->siCol=0; psHdl->siRow=0; psHdl->pcLex[0]=EOS; psHdl->pcMsg[0]=EOS; psHdl->pcPat[0]=EOS; psHdl->pcPre[0]=EOS; srprintf(&psHdl->pcSrc,&psHdl->szSrc,0,":HELP:"); if (psHdl->pfHlp!=NULL) { if (pcPat!=NULL && *pcPat) { if (l==0 || strxcmp(psHdl->isCas,psHdl->pcCmd,pcPat,l,0,FALSE)==0) { if (l && strlen(pcPat)>l && pcPat[l]!='.') { return CLPERR(psHdl,CLPERR_SEM,"Path (%s) is not valid",pcPat); } for (siLev=0,pcPtr=l?strchr(pcPat,'.'):pcPat-1;pcPtr!=NULL && siLev<CLPMAX_HDEPTH;pcPtr=strchr(pcPtr+1,'.'),siLev++) { for (pcKyw=pcPtr+1,i=0;i<CLPMAX_KYWLEN && pcKyw[i]!=EOS && pcKyw[i]!='.';i++) acKyw[i]=pcKyw[i]; acKyw[i]=EOS; siErr=siClpSymFnd(pvHdl,siLev,acKyw,psTab,&psArg,NULL); if (siErr<0) return(siErr); psHdl->apPat[siLev]=psArg; psTab=psArg->psDep; } if (psTab!=NULL) { if (siDep==0) { if (psArg==NULL) { fprintf(psHdl->pfHlp, "SYNOPSIS\n"); fprintf(psHdl->pfHlp, "--------\n"); efprintf(psHdl->pfHlp, "HELP: %s\n",psHdl->pcHlp); fprintf(psHdl->pfHlp, "PATH: %s.%s\n",psHdl->pcOwn,psHdl->pcPgm); if (psHdl->isOvl) { fprintf(psHdl->pfHlp,"TYPE: OVERLAY\n"); } else { fprintf(psHdl->pfHlp,"TYPE: OBJECT\n"); } fprintf(psHdl->pfHlp, "SYNTAX: > %s ",psHdl->pcPgm); siErr=siClpPrnCmd(pvHdl,psHdl->pfHlp,0,0,1,NULL,psHdl->psTab,FALSE,FALSE); if (siErr<0) return(siErr); fprintf(psHdl->pfHlp,"\n\n"); fprintf(psHdl->pfHlp,"DESCRIPTION\n"); fprintf(psHdl->pfHlp,"-----------\n"); if (psHdl->pcMan!=NULL && *psHdl->pcMan) { fprintm(psHdl->pfHlp,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psHdl->pcMan,1); } else { fprintf(psHdl->pfHlp,"No detailed description available for this command.\n\n"); } } else { fprintf(psHdl->pfHlp, "SYNOPSIS\n"); fprintf(psHdl->pfHlp, "--------\n"); efprintf(psHdl->pfHlp,"HELP: %s\n",psArg->psFix->pcHlp); fprintf(psHdl->pfHlp, "PATH: %s\n",fpcPat(pvHdl,siLev-1)); fprintf(psHdl->pfHlp, "TYPE: %s\n",apClpTyp[psArg->psFix->siTyp]); fprintf(psHdl->pfHlp, "SYNTAX: "); siErr=siClpPrnSyn(pvHdl,psHdl->pfHlp,FALSE,siLev-1,psArg); fprintf(psHdl->pfHlp,"\n\n"); if (siErr<0) return(siErr); fprintf(psHdl->pfHlp, "DESCRIPTION\n"); fprintf(psHdl->pfHlp, "-----------\n"); if (psArg->psFix->pcMan!=NULL && *psArg->psFix->pcMan) { efprintf(psHdl->pfHlp,"%s\n",psArg->psFix->pcMan); } else { fprintf(psHdl->pfHlp,"No detailed description available for this argument.\n\n"); } } } else { if (psArg!=NULL) { if (psArg->psFix->siTyp==CLPTYP_OBJECT || psArg->psFix->siTyp==CLPTYP_OVRLAY) { siErr=siClpPrnHlp(pvHdl,psHdl->pfHlp,isAli,siLev,siLev+siDep,-1,psTab,FALSE); if (siErr<0) return(siErr); } else { if (CLPISF_SEL(psArg->psStd->uiFlg)) { siErr=siClpPrnHlp(pvHdl,psHdl->pfHlp,isAli,siLev,siLev+siDep,psArg->psFix->siTyp,psTab,FALSE); if (siErr<0) return(siErr); } else { siErr=siClpPrnHlp(pvHdl,psHdl->pfHlp,isAli,siLev,siLev+siDep,psArg->psFix->siTyp,psTab,TRUE); if (siErr<0) return(siErr); } } } else { siErr=siClpPrnHlp(pvHdl,psHdl->pfHlp,isAli,siLev,siLev+siDep,-1,psTab,FALSE); if (siErr<0) return(siErr); } } } else { if (isMan) { if (psArg!=NULL) { fprintf(psHdl->pfHlp, "SYNOPSIS\n"); fprintf(psHdl->pfHlp, "--------\n"); efprintf(psHdl->pfHlp,"HELP: %s\n",psArg->psFix->pcHlp); fprintf(psHdl->pfHlp, "PATH: %s\n",fpcPat(pvHdl,siLev-1)); fprintf(psHdl->pfHlp, "TYPE: %s\n",apClpTyp[psArg->psFix->siTyp]); fprintf(psHdl->pfHlp, "SYNTAX: "); siErr=siClpPrnSyn(pvHdl,psHdl->pfHlp,FALSE,siLev-1,psArg); fprintf(psHdl->pfHlp, "\n\n"); if (siErr<0) return(siErr); fprintf(psHdl->pfHlp, "DESCRIPTION\n"); fprintf(psHdl->pfHlp, "-----------\n"); if (psArg->psFix->pcMan!=NULL && *psArg->psFix->pcMan) { fprintm(psHdl->pfHlp,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psArg->psFix->pcMan,1); } else { fprintf(psHdl->pfHlp,"No detailed description available for this argument.\n\n"); } } else { fprintf(psHdl->pfHlp,"No detailed description available for this argument.\n\n"); } } else { fprintf(psHdl->pfHlp,"No further arguments available.\n"); } } } else { return CLPERR(psHdl,CLPERR_SEM,"Root of path (%s) does not match root of handle (%s)",pcPat,psHdl->pcCmd); } } else { if (siDep==0) { fprintf(psHdl->pfHlp, "SYNOPSIS\n"); fprintf(psHdl->pfHlp, "--------\n"); efprintf(psHdl->pfHlp, "HELP: %s\n",psHdl->pcHlp); fprintf(psHdl->pfHlp, "PATH: %s.%s\n",psHdl->pcOwn,psHdl->pcPgm); if (psHdl->isOvl) { fprintf(psHdl->pfHlp,"TYPE: OVERLAY\n"); } else { fprintf(psHdl->pfHlp,"TYPE: OBJECT\n"); } fprintf(psHdl->pfHlp, "SYNTAX: > %s ",psHdl->pcPgm); siErr=siClpPrnCmd(pvHdl,psHdl->pfHlp,0,0,1,NULL,psHdl->psTab,FALSE,FALSE); fprintf(psHdl->pfHlp,"\n\n"); if (siErr<0) return(siErr); fprintf(psHdl->pfHlp,"DESCRIPTION\n"); fprintf(psHdl->pfHlp,"-----------\n"); if (psHdl->pcMan!=NULL && *psHdl->pcMan) { fprintm(psHdl->pfHlp,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psHdl->pcMan,1); } else { fprintf(psHdl->pfHlp,"No detailed description available for this command.\n\n"); } } else { siErr=siClpPrnHlp(pvHdl,psHdl->pfHlp,isAli,0,siDep,-1,psTab,FALSE); if (siErr<0) return(siErr); } } } return(CLP_OK); } static inline void vdPrintHdl(FILE* pfDoc,TsHdl* psHdl, const TsParamDescription* psParamDesc, const char* pcKnd, const char* pcKyw, const char chHdl) { unsigned int l,i,isLev=psHdl->uiLev>1; unsigned int uiLev=psHdl->uiLev; if (chHdl==C_CRT) { uiLev+=1; } else if (chHdl=='+') { uiLev+=2; } if (psHdl->isAnc && psParamDesc != NULL) { efprintf(pfDoc, "[[%s%s%s]]\n", psParamDesc->pcAnchorPrefix, psParamDesc->pcCommand, psParamDesc->pcPath); } if (psHdl->isNbr) { if (isLev) { for (l=0;l<uiLev;l++) fprintf(pfDoc,"="); if (psHdl->isShl) { fprintf(pfDoc, " %s %s\n\n",psParamDesc->pcNum,pcKyw); } else { fprintf(pfDoc, " %s %s '%s'\n\n",psParamDesc->pcNum,pcKnd,pcKyw); } } else { if (psHdl->isShl) { fprintf(pfDoc, "%s %s\n",psParamDesc->pcNum,pcKyw); l=strlen(psParamDesc->pcNum)+strlen(pcKyw)+1; for (i=0;i<l;i++) fprintf(pfDoc,"%c",chHdl); fprintf(pfDoc,"\n\n"); } else { fprintf(pfDoc, "%s %s '%s'\n",psParamDesc->pcNum,pcKnd,pcKyw); l=strlen(psParamDesc->pcNum)+strlen(pcKnd)+strlen(pcKyw)+4; for (i=0;i<l;i++) fprintf(pfDoc,"%c",chHdl); fprintf(pfDoc,"\n\n"); } } } else { if (isLev) { for (l=0;l<uiLev;l++) fprintf(pfDoc,"="); if (psHdl->isShl) { fprintf(pfDoc, " %s\n",pcKyw); } else { fprintf(pfDoc, " %s '%s'\n",pcKnd,pcKyw); } } else { if (psHdl->isShl) { fprintf(pfDoc, "%s\n",pcKyw); l=strlen(pcKyw); for (i=0;i<l;i++) fprintf(pfDoc,"%c",chHdl); fprintf(pfDoc,"\n\n"); } else { fprintf(pfDoc, "%s '%s'\n",pcKnd,pcKyw); l=strlen(pcKnd)+strlen(pcKyw)+3; for (i=0;i<l;i++) fprintf(pfDoc,"%c",chHdl); fprintf(pfDoc,"\n\n"); } } } if (psHdl->isIdt && psParamDesc != NULL) { efprintf(pfDoc, "indexterm:[%s, %s, %s%s]\n\n", pcKnd, pcKyw, psParamDesc->pcCommand, psParamDesc->pcPath); } } extern int siClpDocu( void* pvHdl, FILE* pfDoc, const char* pcPat, const char* pcNum, const char* pcKnd, const int isCmd, const int isDep, const int isMan, const int isAnc, const int isNbr, const int isIdt, const int isPat, const unsigned int uiLev) { TsHdl* psHdl=(TsHdl*)pvHdl; if (psHdl->pcLst!=NULL) psHdl->pcLst[0]=0x00; psHdl->pcInp=NULL; psHdl->pcCur=NULL; psHdl->pcOld=NULL; psHdl->pcRow=NULL; psHdl->siCol=0; psHdl->siRow=0; psHdl->uiLev=uiLev; psHdl->isMan=isMan; psHdl->isDep=isDep; psHdl->isAnc=isAnc; psHdl->isNbr=isNbr; psHdl->isShl=FALSE; psHdl->isIdt=isIdt; psHdl->isPat=isPat; psHdl->pcLex[0]=EOS; psHdl->pcMsg[0]=EOS; psHdl->pcPat[0]=EOS; psHdl->pcPre[0]=EOS; srprintf(&psHdl->pcSrc,&psHdl->szSrc,0,":DOCU:"); if (psHdl->uiLev) { if (psHdl->uiLev<3 || psHdl->uiLev>4) { return CLPERR(psHdl,CLPERR_INT,"Initial level for docu generation (%u) is not valid (<3 or >4)",psHdl->uiLev); } } if (pcNum!=NULL && strlen(pcNum)<100 && pcKnd!=NULL) { if (pfDoc!=NULL) { TsSym* psTab=psHdl->psTab; TsSym* psArg=NULL; const char* pcPtr=NULL; const char* pcKyw=NULL; char acKyw[CLPMAX_KYWSIZ]; int siErr=0,siLev,siPos; unsigned int i,l=strlen(psHdl->pcCmd); char acNum[64]; char acArg[20]; const char* p; if (pcPat!=NULL && *pcPat) { if (l==0 || strxcmp(psHdl->isCas,psHdl->pcCmd,pcPat,l,0,FALSE)==0) { if (l && strlen(pcPat)>l && pcPat[l]!='.') { return CLPERR(psHdl,CLPERR_SEM,"Path (%s) is not valid",pcPat); } if (strlen(pcPat)>l) { strlcpy(acNum,pcNum,sizeof(acNum)); for (siLev=0,pcPtr=l?strchr(pcPat,'.'):pcPat-1;pcPtr!=NULL && siLev<CLPMAX_HDEPTH;pcPtr=strchr(pcPtr+1,'.'),siLev++) { for (pcKyw=pcPtr+1,i=0;i<CLPMAX_KYWLEN && pcKyw[i]!=EOS && pcKyw[i]!='.';i++) acKyw[i]=pcKyw[i]; acKyw[i]=EOS; siErr=siClpSymFnd(pvHdl,siLev,acKyw,psTab,&psArg,&siPos); if (siErr<0) return(siErr); psHdl->apPat[siLev]=psArg; psTab=psArg->psDep; snprintc(acNum,sizeof(acNum),"%d.",siPos+1); } if (psArg!=NULL) { TsParamDescription stParamDesc = stDefaultParamDesc; stParamDesc.pcNum = acNum; psHdl->isAnc=FALSE; psHdl->isIdt=FALSE; if (CLPISF_ARG(psArg->psStd->uiFlg)) { if (isMan) { if (psHdl->pcPgm!=NULL && *psHdl->pcPgm) { for (p=psHdl->pcPgm;*p;p++) fprintf(pfDoc,"%c",tolower(*p)); fprintf(pfDoc,"."); l=strlen(psHdl->pcPgm)+strlen(fpcPat(pvHdl,siLev))+4; } else { l=strlen(fpcPat(pvHdl,siLev))+3; } for (p=fpcPat(pvHdl,siLev);*p;p++) fprintf(pfDoc,"%c",tolower(*p)); fprintf(pfDoc,"(3)\n"); for (i=0;i<l;i++) fprintf(pfDoc,"="); fprintf(pfDoc,"\n"); fprintf(pfDoc, ":doctype: manpage\n\n"); fprintf(pfDoc, "NAME\n"); fprintf(pfDoc, "----\n\n"); if (psHdl->pcPgm!=NULL && *psHdl->pcPgm) { for (p=psHdl->pcPgm;*p;p++) fprintf(pfDoc,"%c",tolower(*p)); fprintf(pfDoc,"."); for (p=fpcPat(pvHdl,siLev);*p;p++) fprintf(pfDoc,"%c",tolower(*p)); } else { vdClpPrnAli(pfDoc,", ",psArg); } efprintf(pfDoc," - `%s`\n\n",psArg->psFix->pcHlp); fprintf(pfDoc, "SYNOPSIS\n"); fprintf(pfDoc, "--------\n\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n"); fprintf(pfDoc, "PATH: %s\n",fpcPat(pvHdl,siLev-1)); fprintf(pfDoc, "TYPE: %s\n",apClpTyp[psArg->psFix->siTyp]); fprintf(pfDoc, "SYNTAX: "); siErr=siClpPrnSyn(pvHdl,pfDoc,FALSE,siLev-1,psArg); fprintf(pfDoc,"\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n\n"); if (siErr<0) return(siErr); fprintf(pfDoc, "DESCRIPTION\n"); fprintf(pfDoc, "-----------\n\n"); if (psArg->psFix->pcMan!=NULL && *psArg->psFix->pcMan) { fprintm(pfDoc,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psArg->psFix->pcMan,2); } else { fprintf(pfDoc,"No detailed description available for this argument.\n\n"); } fprintf(pfDoc, "AUTHOR\n"); fprintf(pfDoc, "------\n\n"); fprintf(pfDoc, "limes datentechnik(r) gmbh (www.flam.de)\n\n"); } else { switch (psArg->psFix->siTyp){ case CLPTYP_OBJECT:strcpy(acArg,"Object");break; case CLPTYP_OVRLAY:strcpy(acArg,"Overlay");break; default :strcpy(acArg,"Parameter");break; } vdPrintHdl(pfDoc,psHdl,&stParamDesc,acArg,psArg->psStd->pcKyw,C_CRT); fprintf(pfDoc, ".Synopsis\n\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n"); efprintf(pfDoc,"HELP: %s\n",psArg->psFix->pcHlp); if(isPat) fprintf(pfDoc, "PATH: %s\n",fpcPat(pvHdl,siLev-1)); fprintf(pfDoc, "TYPE: %s\n",apClpTyp[psArg->psFix->siTyp]); fprintf(pfDoc, "SYNTAX: "); siErr=siClpPrnSyn(pvHdl,pfDoc,FALSE,siLev-1,psArg); fprintf(pfDoc,"\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n\n"); if (siErr<0) return(siErr); fprintf(pfDoc,".Description\n\n"); if (psArg->psFix->pcMan!=NULL && *psArg->psFix->pcMan) { fprintm(pfDoc,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psArg->psFix->pcMan,2); } else { fprintf(pfDoc,"No detailed description available for this argument.\n\n"); } siErr=siClpPrnDoc(pvHdl,pfDoc,siLev,&stParamDesc,psArg,psTab); if (siErr<0) return(siErr); } } else if (CLPISF_CON(psArg->psStd->uiFlg)) { if (isMan) { if (psHdl->pcPgm!=NULL && *psHdl->pcPgm) { for (p=psHdl->pcPgm;*p;p++) fprintf(pfDoc,"%c",tolower(*p)); fprintf(pfDoc,"."); l=strlen(psHdl->pcPgm)+strlen(fpcPat(pvHdl,siLev))+4; } else { l=strlen(fpcPat(pvHdl,siLev))+3; } for(p=fpcPat(pvHdl,siLev);*p;p++) fprintf(pfDoc,"%c",tolower(*p)); fprintf(pfDoc,"(3)\n"); for (i=0;i<l;i++) fprintf(pfDoc,"="); fprintf(pfDoc,"\n"); fprintf(pfDoc, ":doctype: manpage\n\n"); fprintf(pfDoc, "NAME\n"); fprintf(pfDoc, "----\n\n"); if (psHdl->pcPgm!=NULL && *psHdl->pcPgm) { for (p=psHdl->pcPgm;*p;p++) fprintf(pfDoc,"%c",tolower(*p)); fprintf(pfDoc,"."); for (p=fpcPat(pvHdl,siLev);*p;p++) fprintf(pfDoc,"%c",tolower(*p)); } else { for (p=psArg->psStd->pcKyw;*p;p++) fprintf(pfDoc,"%c",tolower(*p)); } efprintf(pfDoc," - `%s`\n\n",psArg->psFix->pcHlp); fprintf(pfDoc, "SYNOPSIS\n"); fprintf(pfDoc, "--------\n\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n"); fprintf(pfDoc, "PATH: %s\n",fpcPat(pvHdl,siLev-1)); fprintf(pfDoc, "TYPE: %s\n",apClpTyp[psArg->psFix->siTyp]); fprintf(pfDoc, "SYNTAX: %s\n",psArg->psStd->pcKyw); fprintf(pfDoc, "-----------------------------------------------------------------------\n\n"); if (siErr<0) return(siErr); fprintf(pfDoc, "DESCRIPTION\n"); fprintf(pfDoc, "-----------\n\n"); if (psArg->psFix->pcMan!=NULL && *psArg->psFix->pcMan) { fprintm(pfDoc,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psArg->psFix->pcMan,2); } else { fprintf(pfDoc,"No detailed description available for this constant.\n\n"); } fprintf(pfDoc, "AUTHOR\n"); fprintf(pfDoc, "------\n\n"); fprintf(pfDoc, "limes datentechnik(r) gmbh (www.flam.de)\n\n"); } else { vdPrintHdl(pfDoc,psHdl,&stParamDesc,"Constant",psArg->psStd->pcKyw,'+'); fprintf(pfDoc, ".Synopsis\n\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n"); efprintf(pfDoc,"HELP: %s\n",psArg->psFix->pcHlp); if(isPat) fprintf(pfDoc, "PATH: %s\n",fpcPat(pvHdl,siLev-1)); fprintf(pfDoc, "TYPE: %s\n",apClpTyp[psArg->psFix->siTyp]); fprintf(pfDoc, "SYNTAX: %s\n",psArg->psStd->pcKyw); fprintf(pfDoc, "-----------------------------------------------------------------------\n\n"); if (siErr<0) return(siErr); fprintf(pfDoc,".Description\n\n"); if (psArg->psFix->pcMan!=NULL && *psArg->psFix->pcMan) { fprintm(pfDoc,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psArg->psFix->pcMan,2); } else { fprintf(pfDoc,"No detailed description available for this constant.\n\n"); } } } else { return CLPERR(psHdl,CLPERR_SEM,"Path (%s) contains too many or invalid qualifiers",pcPat); } } else { return CLPERR(psHdl,CLPERR_SEM,"Path (%s) contains too many or invalid qualifiers",pcPat); } return(CLP_OK); } } else { return CLPERR(psHdl,CLPERR_SEM,"Root of path (%s) does not match root of handle (%s)",pcPat,psHdl->pcCmd); } } if (isMan) { if (psHdl->pcPgm!=NULL && *psHdl->pcPgm) { for (p=psHdl->pcPgm;*p;p++) fprintf(pfDoc,"%c",tolower(*p)); fprintf(pfDoc,"."); l=strlen(psHdl->pcPgm)+strlen(psHdl->pcCmd)+4; } else { l=strlen(psHdl->pcCmd)+3; } for (p=psHdl->pcCmd;*p;p++) fprintf(pfDoc,"%c",tolower(*p)); fprintf(pfDoc, "(1)\n"); for (i=0;i<l;i++) fprintf(pfDoc,"="); fprintf(pfDoc,"\n"); fprintf(pfDoc, ":doctype: manpage\n\n"); fprintf(pfDoc, "NAME\n"); fprintf(pfDoc, "----\n\n"); if (psHdl->pcPgm!=NULL && strlen(psHdl->pcPgm)) { for (p=psHdl->pcPgm;*p;p++) fprintf(pfDoc,"%c",tolower(*p)); fprintf(pfDoc,"."); } for (p=psHdl->pcCmd;*p;p++) fprintf(pfDoc,"%c",tolower(*p)); efprintf(pfDoc, " - `%s`\n\n",psHdl->pcHlp); fprintf(pfDoc, "SYNOPSIS\n"); fprintf(pfDoc, "--------\n\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n"); fprintf(pfDoc, "PATH: %s.%s\n",psHdl->pcOwn,psHdl->pcPgm); if (psHdl->isOvl) { fprintf(pfDoc,"TYPE: OVERLAY\n"); } else { fprintf(pfDoc,"TYPE: OBJECT\n"); } fprintf(pfDoc, "SYNTAX: > %s ",psHdl->pcPgm); siErr=siClpPrnCmd(pvHdl,pfDoc,0,0,1,NULL,psHdl->psTab,FALSE,FALSE); fprintf(pfDoc,"\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n\n"); if (siErr<0) return(siErr); fprintf(pfDoc, "DESCRIPTION\n"); fprintf(pfDoc, "-----------\n\n"); if (psHdl->pcMan!=NULL && *psHdl->pcMan) { fprintm(pfDoc,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psHdl->pcMan,2); } else { fprintf(pfDoc,"No detailed description available for this command.\n\n"); } fprintf(pfDoc,"AUTHOR\n"); fprintf(pfDoc,"------\n\n"); fprintf(pfDoc,"limes datentechnik(r) gmbh (www.flam.de)\n\n"); } else { TsParamDescription stParamDesc = { .pcCommand = psHdl->pcCmd, .pcPath = "", .pcAnchorPrefix = isCmd?"CLEP.COMMAND.":"CLEP.OTHERCLP.", .pcNum = pcNum }; vdPrintHdl(pfDoc,psHdl,&stParamDesc,pcKnd,psHdl->pcCmd,C_TLD); fprintf(pfDoc, ".Synopsis\n\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n"); efprintf(pfDoc, "HELP: %s\n",psHdl->pcHlp); if (isPat) { fprintf(pfDoc,"PATH: %s.%s\n",psHdl->pcOwn,psHdl->pcPgm); } if (psHdl->isOvl) { fprintf(pfDoc,"TYPE: OVERLAY\n"); } else { fprintf(pfDoc,"TYPE: OBJECT\n"); } fprintf(pfDoc, "SYNTAX: > %s ",psHdl->pcPgm); siErr=siClpPrnCmd(pvHdl,pfDoc,0,0,1,NULL,psHdl->psTab,FALSE,FALSE); fprintf(pfDoc,"\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n\n"); if (siErr<0) return(siErr); fprintf(pfDoc, ".Description\n\n"); if (psHdl->pcMan!=NULL && *psHdl->pcMan) { fprintm(pfDoc,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psHdl->pcMan,2); } else { fprintf(pfDoc,"No detailed description available for this command.\n\n"); } siPos=siClpPrnDoc(pvHdl,pfDoc,0,&stParamDesc,NULL,psTab); if (siPos<0) return(siPos); } } } else { return CLPERR(psHdl,CLPERR_INT,"No valid initial number or command string for head lines (%s)",psHdl->pcCmd); } return(CLP_OK); } static int siClpPrintTable( void* pvHdl, const int siLev, const TsParamDescription* psParamDesc, const char* pcPat, const char* pcFil, const TsSym* psTab); static int siClpWriteRemaining( void* pvHdl, FILE* pfDoc, const int siLev, const char* pcPat, const TsSym* psTab) { TsHdl* psHdl=(TsHdl*)pvHdl; int i=0; for (const TsSym* psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt) { if (psHlp->psFix->pcMan==NULL) { if (CLPISF_ARG(psHlp->psStd->uiFlg) && CLPISF_CMD(psHlp->psStd->uiFlg)) { if (psHlp->psFix->siTyp==CLPTYP_OBJECT || psHlp->psFix->siTyp==CLPTYP_OVRLAY) { return CLPERR(psHdl,CLPERR_TAB,"Manual page for %s '%s.%s' missing",apClpTyp[psHlp->psFix->siTyp],pcPat,psHlp->psStd->pcKyw); } if (i==0) fprintf(pfDoc,".Arguments\n\n"); efprintf(pfDoc,"* `%s: ",apClpTyp[psHlp->psFix->siTyp]); siClpPrnSyn(pvHdl,pfDoc,FALSE,siLev,psHlp); efprintf(pfDoc," - %s`\n",psHlp->psFix->pcHlp); for (const TsSym* psSel=psHlp->psDep;psSel!=NULL;psSel=psSel->psNxt) { if (psSel->psFix->siTyp==psHlp->psFix->siTyp) { if (psSel->psFix->pcMan!=NULL) { return CLPERR(psHdl,CLPERR_TAB,"Manual page for SELECTION '%s.%s.%s' useless",pcPat,psHlp->psStd->pcKyw,psSel->psStd->pcKyw); } efprintf(pfDoc,"** `%s - %s`\n",psSel->psStd->pcKyw,psSel->psFix->pcHlp); } } i++; } else if (CLPISF_CON(psHlp->psStd->uiFlg)) { if (i==0) fprintf(pfDoc,".Selections\n\n"); efprintf(pfDoc,"* `%s - %s`\n",psHlp->psStd->pcKyw,psHlp->psFix->pcHlp); i++; } } } if (i) fprintf(pfDoc,"\n"); return(CLP_OK); } static int siClpPrintWritten( void* pvHdl, FILE* pfDoc, const int siLev, const char* pcPat, const char* pcFil, const char* pcMan) { int i; TsHdl* psHdl=(TsHdl*)pvHdl; size_t s=(size_t)ftell(pfDoc); rewind(pfDoc); char* pcPge=malloc(s+1); if (pcPge==NULL) { return CLPERR(psHdl,CLPERR_SYS,"Allocation of memory for temporary file to print page for argument '%s' failed",psHdl->pcCmd); } size_t r=fread(pcPge,1,s,pfDoc); if (r!=s) { free(pcPge); return CLPERR(psHdl,CLPERR_SYS,"Read of temporary file to print page for command '%s' failed",psHdl->pcCmd); } pcPge[r]=0x00; const char* p=strchr(pcPge,'='); if (p==NULL) { free(pcPge); return CLPERR(psHdl,CLPERR_INT,"No headline found in manual page for command '%s' (no sign)",psHdl->pcCmd); } while (*p=='=') p++; if (*p!=' ') { free(pcPge); return CLPERR(psHdl,CLPERR_INT,"No headline found in manual page for command '%s' (no blank after sign)",psHdl->pcCmd); } p++; const char* e=strchr(p,'\n'); if (e==NULL) { free(pcPge); return CLPERR(psHdl,CLPERR_INT,"No end of headline found in manual page for command '%s'",psHdl->pcCmd); } int l=e-p; char acHdl[l+1]; memcpy(acHdl,p,l); acHdl[l]=0x00; l=strlen(pcFil); char acFil[l+16]; unsigned int uiHsh=fnvHash(l,(const unsigned char*)pcFil); for (i=0;i<l;i++) { if (pcFil[i]=='\t') { acFil[i]=psHdl->siPs1; } else if (pcFil[i]=='\v') { acFil[i]=psHdl->siPs2; } else if (isalnum(pcFil[i])) { acFil[i]=tolower(pcFil[i]); } else { acFil[i]=psHdl->siPr3; } } acFil[i]=0x00; snprintc(acFil,sizeof(acFil),"%c%04x",psHdl->siPr3,uiHsh&0xFFFF); int siErr=psHdl->pfPrn(psHdl->pvPrn,psHdl->uiLev+siLev,acHdl,pcPat,acFil,pcMan,pcPge); free(pcPge); if (siErr) { return CLPERR(psHdl,CLPERR_SYS,"Print page over call back function for command '%s' failed with %d",psHdl->pcCmd,siErr); } return(CLP_OK); } extern int siClpPrint( void* pvHdl, const char* pcFil, const char* pcNum, const char* pcKnd, const int isCmd, const int isDep, const int isAnc, const int isNbr, const int isShl, const int isIdt, const int isPat, const unsigned int uiLev, const int siPs1, const int siPs2, const int siPr3, void* pvPrn, TfClpPrintPage* pfPrn) { TsHdl* psHdl=(TsHdl*)pvHdl; if (psHdl->pcLst!=NULL) psHdl->pcLst[0]=0x00; psHdl->pcInp=NULL; psHdl->pcCur=NULL; psHdl->pcOld=NULL; psHdl->pcRow=NULL; psHdl->siCol=0; psHdl->siRow=0; psHdl->uiLev=uiLev; psHdl->isMan=FALSE; psHdl->isDep=TRUE; psHdl->isAnc=isAnc; psHdl->isNbr=isNbr; psHdl->isShl=isShl; psHdl->isIdt=isIdt; psHdl->isPat=isPat; psHdl->siPs1=siPs1; psHdl->siPs2=siPs2; psHdl->siPr3=siPr3; psHdl->pvPrn=pvPrn; psHdl->pfPrn=pfPrn; psHdl->pcLex[0]=EOS; psHdl->pcMsg[0]=EOS; psHdl->pcPat[0]=EOS; psHdl->pcPre[0]=EOS; srprintf(&psHdl->pcSrc,&psHdl->szSrc,0,":DOCU:"); if (psHdl->uiLev) { if (psHdl->uiLev<3 || psHdl->uiLev>4) { return CLPERR(psHdl,CLPERR_INT,"Initial level for docu generation (%u) is not valid (<3 or >4)",psHdl->uiLev); } } if (psHdl->pfPrn==NULL) { return CLPERR(psHdl,CLPERR_INT,"No print callback function provided"); } if (pcNum!=NULL && pcKnd!=NULL) { int siErr; FILE* pfDoc; char acFil[strlen(pcFil)+strlen(psHdl->pcCmd)+2]; snprintf(acFil,sizeof(acFil),"%s\t%s",pcFil,psHdl->pcCmd); pfDoc=fopen_tmp(); if (pfDoc==NULL) { return CLPERR(psHdl,CLPERR_SYS,"Open of temporary file to print main page for command '%s' failed",psHdl->pcCmd); } TsParamDescription stParamDesc = { .pcCommand = psHdl->pcCmd, .pcPath = "", .pcAnchorPrefix = isCmd?"CLEP.COMMAND.":"CLEP.OTHERCLP.", .pcNum = pcNum }; vdPrintHdl(pfDoc,psHdl,&stParamDesc,pcKnd,psHdl->pcCmd,C_TLD); efprintf(pfDoc, ".Synopsis\n\n"); efprintf(pfDoc, "-----------------------------------------------------------------------\n"); efprintf(pfDoc, "HELP: %s\n",psHdl->pcHlp); if(psHdl->isPat) { efprintf(pfDoc,"PATH: %s.%s\n",psHdl->pcOwn,psHdl->pcPgm); } if (psHdl->isOvl) { efprintf(pfDoc,"TYPE: OVERLAY\n"); } else { efprintf(pfDoc,"TYPE: OBJECT\n"); } efprintf(pfDoc, "SYNTAX: > %s ",psHdl->pcPgm); siErr=siClpPrnCmd(pvHdl,pfDoc,0,0,1,NULL,psHdl->psTab,FALSE,FALSE); fprintf(pfDoc, "\n"); efprintf(pfDoc, "-----------------------------------------------------------------------\n\n"); if (siErr<0) { fclose_tmp(pfDoc); return(siErr); } efprintf(pfDoc, ".Description\n\n"); if (psHdl->pcMan!=NULL && *psHdl->pcMan) { fprintm(pfDoc,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psHdl->pcMan,2); } else { return CLPERR(psHdl,CLPERR_TAB,"Manual page for COMMAND/OTHERCLP '%s' missing",psHdl->pcCmd); } siErr=siClpWriteRemaining(pvHdl,pfDoc,0,psHdl->pcCmd,psHdl->psTab); if (siErr) { fclose_tmp(pfDoc); return(siErr); } siErr=siClpPrintWritten(pvHdl,pfDoc,0,psHdl->pcCmd,acFil,psHdl->pcMan); fclose_tmp(pfDoc); if (siErr) { return(siErr); } if (isDep) { siErr=siClpPrintTable(pvHdl,0,&stParamDesc,psHdl->pcCmd,acFil,psHdl->psTab); if (siErr) return(siErr); } } else { return CLPERR(psHdl,CLPERR_INT,"No valid initial number or command string for head lines (%s)",psHdl->pcCmd); } return(CLP_OK); } extern int siClpProperties( void* pvHdl, const int siMtd, const int siDep, const char* pcPat, FILE* pfOut) { TsHdl* psHdl=(TsHdl*)pvHdl; TsSym* psTab=psHdl->psTab; TsSym* psArg=NULL; const char* pcPtr=NULL; const char* pcKyw=NULL; char acKyw[CLPMAX_KYWSIZ]; int siErr,siLev,i; unsigned int l=strlen(psHdl->pcCmd); const char* pcArg=NULL; if (psHdl->pcLst!=NULL) psHdl->pcLst[0]=0x00; psHdl->pcInp=NULL; psHdl->pcCur=NULL; psHdl->pcOld=NULL; psHdl->pcRow=NULL; psHdl->siCol=0; psHdl->siRow=0; psHdl->pcLex[0]=EOS; psHdl->pcMsg[0]=EOS; psHdl->pcPat[0]=EOS; psHdl->pcPre[0]=EOS; srprintf(&psHdl->pcSrc,&psHdl->szSrc,0,":PROPERTIES:"); if (pfOut==NULL) pfOut=psHdl->pfHlp; if (pfOut!=NULL) { if (pcPat!=NULL && *pcPat) { if (l==0 || strxcmp(psHdl->isCas,psHdl->pcCmd,pcPat,l,0,FALSE)==0) { if (l && strlen(pcPat)>l && pcPat[l]!='.') { return CLPERR(psHdl,CLPERR_SEM,"Path (%s) is not valid",pcPat); } for (siLev=0,pcPtr=l?strchr(pcPat,'.'):pcPat-1;pcPtr!=NULL && siLev<CLPMAX_HDEPTH;pcPtr=strchr(pcPtr+1,'.'),siLev++) { for (pcKyw=pcPtr+1,i=0;i<CLPMAX_KYWLEN && pcKyw[i]!=EOS && pcKyw[i]!='.';i++) acKyw[i]=pcKyw[i]; acKyw[i]=EOS; if (pcArg!=NULL) { return CLPERR(psHdl,CLPERR_SEM,"Path (%s) contains too many or invalid qualifiers",pcPat); } siErr=siClpSymFnd(pvHdl,siLev,acKyw,psTab,&psArg,NULL); if (siErr<0) return(siErr); psHdl->apPat[siLev]=psArg; if (psArg->psDep!=NULL) { psTab=psArg->psDep; } else { pcArg=psArg->psStd->pcKyw; } } if (pcArg!=NULL) siLev--; siErr=siClpPrnPro(pvHdl,pfOut,FALSE,siMtd,siLev,siLev+siDep,psTab,pcArg); if (siErr<0) return(siErr); } else { return CLPERR(psHdl,CLPERR_SEM,"Root of path (%s) does not match root of handle (%s)",pcPat,psHdl->pcCmd); } } else { siErr=siClpPrnPro(pvHdl,pfOut,FALSE,siMtd,0,siDep,psTab,NULL); if (siErr<0) return(siErr); } } return(CLP_OK); } extern int siClpSymbolTableWalk( void* pvHdl, const unsigned int uiOpr, TsClpSymWlk* psSym) { TsHdl* psHdl=(TsHdl*)pvHdl; psHdl->psOld=psHdl->psSym; switch (uiOpr) { case CLPSYM_ROOT: psHdl->psSym = psHdl->psTab; break; case CLPSYM_OLD: psHdl->psSym = psHdl->psOld; break; case CLPSYM_NEXT: psHdl->psSym = psHdl->psSym->psNxt; break; case CLPSYM_BACK: psHdl->psSym = psHdl->psSym->psBak; break; case CLPSYM_DEP: psHdl->psSym = psHdl->psSym->psDep; break; case CLPSYM_HIH: psHdl->psSym = psHdl->psSym->psHih; break; case CLPSYM_ALIAS: psHdl->psSym = psHdl->psSym->psStd->psAli; break; case CLPSYM_COUNT: psHdl->psSym = psHdl->psSym->psFix->psCnt; break; case CLPSYM_ELN: psHdl->psSym = psHdl->psSym->psFix->psEln; break; case CLPSYM_LINK: psHdl->psSym = psHdl->psSym->psFix->psLnk; break; case CLPSYM_OID: psHdl->psSym = psHdl->psSym->psFix->psOid; break; case CLPSYM_SLN: psHdl->psSym = psHdl->psSym->psFix->psSln; break; case CLPSYM_TLN: psHdl->psSym = psHdl->psSym->psFix->psTln; break; default: return CLPERR(psHdl,CLPERR_PAR,"Operation (%u) for symbol table walk not supported",uiOpr); } if (psHdl->psSym!=NULL) { TsSym* apTmp[CLPMAX_HDEPTH]; TsSym* psTmp; int i; if (psHdl->pcCmd!=NULL && *psHdl->pcCmd) { srprintf(&psHdl->pcPat,&psHdl->szPat,strlen(psHdl->pcCmd),"%s",psHdl->pcCmd); } else { psHdl->pcPat[0]=EOS; } for (i=0,psTmp=psHdl->psSym->psHih;i<CLPMAX_HDEPTH && psTmp!=NULL;psTmp=psTmp->psHih,i++) apTmp[i]=psTmp; while (i>0) { srprintc(&psHdl->pcPat,&psHdl->szPat,strlen(apTmp[i-1]->psStd->pcKyw),".%s",apTmp[i-1]->psStd->pcKyw); i--; } psSym->pcPat=psHdl->pcPat; psSym->siKwl=psHdl->psSym->psStd->siKwl; psSym->pcKyw=psHdl->psSym->psStd->pcKyw; psSym->pcAli=GETALI(psHdl->psSym); psSym->uiFlg=psHdl->psSym->psStd->uiFlg; psSym->pcDft=psHdl->psSym->psFix->pcDft; psSym->pcMan=psHdl->psSym->psFix->pcMan; psSym->pcHlp=psHdl->psSym->psFix->pcHlp; psSym->siTyp=psHdl->psSym->psFix->siTyp; psSym->siMin=psHdl->psSym->psFix->siMin; psSym->siMax=psHdl->psSym->psFix->siMax; psSym->siSiz=psHdl->psSym->psFix->siSiz; psSym->siOid=psHdl->psSym->psFix->siOid; psSym->uiOpr=0; psSym->uiOpr|=(psHdl->psTab!=NULL)?CLPSYM_ROOT:0; psSym->uiOpr|=(psHdl->psOld!=NULL)?CLPSYM_OLD:0; psSym->uiOpr|=(psHdl->psSym->psNxt!=NULL)?CLPSYM_NEXT:0; psSym->uiOpr|=(psHdl->psSym->psBak!=NULL)?CLPSYM_BACK:0; psSym->uiOpr|=(psHdl->psSym->psDep!=NULL)?CLPSYM_DEP:0; psSym->uiOpr|=(psHdl->psSym->psHih!=NULL)?CLPSYM_HIH:0; psSym->uiOpr|=(psHdl->psSym->psStd->psAli!=NULL)?CLPSYM_ALIAS:0; psSym->uiOpr|=(psHdl->psSym->psFix->psCnt!=NULL)?CLPSYM_COUNT:0; psSym->uiOpr|=(psHdl->psSym->psFix->psEln!=NULL)?CLPSYM_ELN:0; psSym->uiOpr|=(psHdl->psSym->psFix->psLnk!=NULL)?CLPSYM_LINK:0; psSym->uiOpr|=(psHdl->psSym->psFix->psOid!=NULL)?CLPSYM_OID:0; psSym->uiOpr|=(psHdl->psSym->psFix->psSln!=NULL)?CLPSYM_SLN:0; psSym->uiOpr|=(psHdl->psSym->psFix->psTln!=NULL)?CLPSYM_TLN:0; return(psSym->siTyp); } else { psHdl->psSym=psHdl->psOld; memset(psSym,0,sizeof(TsClpSymWlk)); return(0); } } extern int siClpSymbolTableUpdate( void* pvHdl, TsClpSymUpd* psSym) { TsHdl* psHdl=(TsHdl*)pvHdl; C08* pcHlp; if (psSym->pcPro!=NULL) { if (!CLPISF_ARG(psHdl->psSym->psStd->uiFlg)) { return CLPERR(psHdl,CLPERR_SIZ,"Update of property field failed (symbol (%s) is not a argument)",psHdl->psSym->psStd->pcKyw); } pcHlp=realloc_nowarn(psHdl->psSym->psFix->pcPro,strlen(psSym->pcPro)+1); if (pcHlp==NULL) { return CLPERR(psHdl,CLPERR_SIZ,"Update of property field failed (string (%d(%s)) too long)",(int)strlen(psSym->pcPro),psSym->pcPro); } psHdl->psSym->psFix->pcPro=pcHlp; strcpy(psHdl->psSym->psFix->pcPro,psSym->pcPro); psHdl->psSym->psFix->pcDft=psHdl->psSym->psFix->pcPro; psHdl->psSym->psStd->uiFlg|=CLPFLG_PDF; } return(CLP_OK); } extern void vdClpClose( void* pvHdl, const int siMtd) { if (pvHdl!=NULL) { TsHdl* psHdl=(TsHdl*)pvHdl; int i; if (psHdl->pcLex!=NULL) { free(psHdl->pcLex); psHdl->pcLex=NULL; psHdl->szLex=0; } if (psHdl->pcSrc!=NULL) { free(psHdl->pcSrc); psHdl->pcSrc=NULL; psHdl->szSrc=0; } if (psHdl->pcPre!=NULL) { free(psHdl->pcPre); psHdl->pcPre=NULL; psHdl->szPre=0; } if (psHdl->pcPat!=NULL) { free(psHdl->pcPat); psHdl->pcPat=NULL; psHdl->szPat=0; } if (psHdl->pcLst!=NULL) { free(psHdl->pcLst); psHdl->pcLst=NULL; psHdl->szLst=0; } if (psHdl->pcMsg!=NULL) { free(psHdl->pcMsg); psHdl->pcMsg=NULL; psHdl->szMsg=0; } for (i=0;i<CLPMAX_BUFCNT;i++) { if (psHdl->apBuf[i]!=NULL) { free(psHdl->apBuf[i]); psHdl->apBuf[i]=NULL; psHdl->pzBuf[i]=0; } } vdClpSymDel(psHdl->psTab); psHdl->psTab=NULL; switch (siMtd) { case CLPCLS_MTD_KEP: break; case CLPCLS_MTD_EXC: if (psHdl->psPtr!=NULL) { free(psHdl->psPtr); psHdl->psPtr=NULL; psHdl->szPtr=0; psHdl->siPtr=0; } free(pvHdl); break; default: if (psHdl->psPtr!=NULL) { vdClpFree(psHdl); free(psHdl->psPtr); psHdl->psPtr=NULL; psHdl->szPtr=0; psHdl->siPtr=0; } free(pvHdl); break; } } } /* Interne Funktionen *************************************************/ static const char* get_env(char* var,const size_t size,const char* fmtstr, ...) { int i; va_list argv; va_start(argv,fmtstr); vsnprintf(var,size,fmtstr,argv); va_end(argv); for (i=0;var[i];i++) { var[i]=toupper(var[i]); if (var[i]=='.') var[i]='_'; } return(GETENV(var)); } #undef ERROR #define ERROR(s) if (s!=NULL) { \ if (s->psStd!=NULL) { free(s->psStd); s->psStd=NULL; } \ if (s->psFix!=NULL) { \ if (s->psFix->pcPro!=NULL) { free(s->psFix->pcPro); s->psFix->pcPro=NULL; }\ if (s->psFix->pcSrc!=NULL) { free(s->psFix->pcSrc); s->psFix->pcSrc=NULL; }\ free(s->psFix); s->psFix=NULL; \ } \ if (s->psVar!=NULL) { free(s->psVar); s->psVar=NULL; } \ free(s); } return(NULL); static TsSym* psClpSymIns( void* pvHdl, const int siLev, const int siPos, const TsClpArgument* psArg, TsSym* psHih, TsSym* psCur) { TsHdl* psHdl=(TsHdl*)pvHdl; TsSym* psSym; TsSym* psHlp; const char* pcEnv=NULL; const char* pcPat=fpcPat(pvHdl,siLev); char acVar[strlen(psHdl->pcOwn)+strlen(psHdl->pcPgm)+strlen(pcPat)+strlen(psArg->pcKyw)+4]; int k; acVar[0]=0x00; psSym=(TsSym*)calloc(1,sizeof(TsSym)); if (psSym==NULL) { CLPERR(psHdl,CLPERR_MEM,"Allocation of memory for symbol '%s.%s' failed",pcPat,psArg->pcKyw); ERROR(psSym); } psSym->psStd=(TsStd*)calloc(1,sizeof(TsStd)); psSym->psFix=(TsFix*)calloc(1,sizeof(TsFix)); psSym->psVar=(TsVar*)calloc(1,sizeof(TsVar)); if (psSym->psStd==NULL || psSym->psFix==NULL || psSym->psVar==NULL) { CLPERR(psHdl,CLPERR_MEM,"Allocation of memory for symbol element '%s.%s' failed",pcPat,psArg->pcKyw); ERROR(psSym); } if (psArg->pcKyw!=NULL) { if (!isalpha(*psArg->pcKyw)) { CLPERR(psHdl,CLPERR_TAB,"Invalid first letter (%c) in keyword '%s.%s'",*psArg->pcKyw,pcPat,psArg->pcKyw); ERROR(psSym); } for (const char* p=psArg->pcKyw+1; *p; p++) { if (CLPISF_CON(psArg->uiFlg)?!isCon(*p):!isKyw(*p)) { CLPERR(psHdl,CLPERR_TAB,"Invalid letter (%c) in keyword '%s.%s'",*p,pcPat,psArg->pcKyw); ERROR(psSym); } } } if (psArg->pcAli!=NULL) { if (!isalpha(*psArg->pcAli)) { CLPERR(psHdl,CLPERR_TAB,"Invalid first letter (%c) in alias '%s.%s'",*psArg->pcAli,pcPat,psArg->pcKyw); ERROR(psSym); } for (const char* p=psArg->pcAli+1; *p; p++) { if (CLPISF_CON(psArg->uiFlg)?!isCon(*p):!isKyw(*p)) { CLPERR(psHdl,CLPERR_TAB,"Invalid letter (%c) in alias '%s.%s'",*p,pcPat,psArg->pcAli); ERROR(psSym); } } } psSym->psStd->pcKyw=psArg->pcKyw; psSym->psStd->uiFlg=psArg->uiFlg; if (psArg->pcTyp!=NULL) { if (strcmp(psArg->pcTyp,"U08")==0 || strcmp(psArg->pcTyp,"U16")==0 || strcmp(psArg->pcTyp,"U32")==0 || strcmp(psArg->pcTyp,"U64")==0) { psSym->psStd->uiFlg|=CLPFLG_UNS; } } pcEnv=GETENV("CLEP_NO_SECRETS"); if (pcEnv!=NULL) { if (strcmp(pcEnv,"OFF")==0) { psSym->psStd->uiFlg&=~CLPFLG_PWD; } pcEnv=NULL; } psSym->psStd->psAli=NULL; psSym->psStd->siKwl=strlen(psSym->psStd->pcKyw); psSym->psStd->siLev=siLev; psSym->psStd->siPos=siPos; psSym->psFix->pcMan=psArg->pcMan; psSym->psFix->pcHlp=psArg->pcHlp; if (CLPISF_ARG(psArg->uiFlg)) { pcEnv=get_env(acVar,sizeof(acVar),"%s.%s.%s.%s",psHdl->pcOwn,psHdl->pcPgm,pcPat,psArg->pcKyw); if (pcEnv==NULL) { pcEnv=get_env(acVar,sizeof(acVar),"%s.%s.%s",psHdl->pcPgm,pcPat,psArg->pcKyw); if (pcEnv==NULL) { pcEnv=get_env(acVar,sizeof(acVar),"%s.%s",pcPat,psArg->pcKyw); } } } if (pcEnv!=NULL && *pcEnv) { psSym->psFix->pcPro=malloc(strlen(pcEnv)+1); if (psSym->psFix->pcPro==NULL) { CLPERR(psHdl,CLPERR_MEM,"Allocation of memory for symbol element property '%s.%s' failed",pcPat,psArg->pcKyw); ERROR(psSym); } strcpy(psSym->psFix->pcPro,pcEnv); psSym->psFix->pcDft=psSym->psFix->pcPro; psSym->psFix->pcSrc=malloc(strlen(CLPSRC_ENV)+strlen(acVar)+1); if (psSym->psFix->pcSrc==NULL) { CLPERR(psHdl,CLPERR_MEM,"Allocation of memory for symbol element source '%s.%s' failed",pcPat,psArg->pcKyw); ERROR(psSym); } sprintf(psSym->psFix->pcSrc,"%s%s",CLPSRC_ENV,acVar); psSym->psFix->siRow=1; } else { psSym->psFix->pcDft=psArg->pcDft; if (psArg->pcDft!=NULL) { psSym->psFix->pcSrc=malloc(strlen(CLPSRC_DEF)+strlen(pcPat)+strlen(psArg->pcKyw)+2); if (psSym->psFix->pcSrc==NULL) { CLPERR(psHdl,CLPERR_MEM,"Allocation of memory for symbol element source '%s.%s' failed",pcPat,psArg->pcKyw); ERROR(psSym); } sprintf(psSym->psFix->pcSrc,"%s%s.%s",CLPSRC_DEF,pcPat,psArg->pcKyw); psSym->psFix->siRow=1; } } psSym->psFix->siTyp=psArg->siTyp; psSym->psFix->siMin=psArg->siMin; psSym->psFix->siMax=(psArg->siMax==0)?((CLPISF_DYN(psSym->psStd->uiFlg))?2147483647:0):psArg->siMax; psSym->psFix->siSiz=(psArg->siSiz==0)?((CLPISF_DYN(psSym->psStd->uiFlg))?2147483647:0):psArg->siSiz; psSym->psFix->siOfs=psArg->siOfs; psSym->psFix->siOid=psArg->siOid; psSym->psFix->psLnk=NULL; psSym->psFix->psCnt=NULL; psSym->psFix->psOid=NULL; psSym->psFix->psInd=NULL; psSym->psFix->psEln=NULL; psSym->psFix->psSln=NULL; psSym->psFix->psTln=NULL; switch (psSym->psFix->siTyp) { case CLPTYP_SWITCH: psSym->psStd->uiFlg|=CLPFLG_FIX; break; case CLPTYP_NUMBER: psSym->psStd->uiFlg|=CLPFLG_FIX; break; case CLPTYP_FLOATN: psSym->psStd->uiFlg|=CLPFLG_FIX; break; case CLPTYP_OBJECT: psSym->psStd->uiFlg|=CLPFLG_FIX; break; case CLPTYP_OVRLAY: psSym->psStd->uiFlg|=CLPFLG_FIX; break; case CLPTYP_STRING: if (CLPISF_DLM(psSym->psStd->uiFlg) && !CLPISF_FIX(psSym->psStd->uiFlg) && psSym->psFix->siSiz>0) { psSym->psFix->siSiz--; // CLPFLG_DLM support } break; case CLPTYP_XALIAS: break; default: CLPERR(psHdl,CLPERR_TAB,"Type (%d) for argument '%s.%s' not supported",psSym->psFix->siTyp,pcPat); ERROR(psSym); } if (CLPISF_DLM(psSym->psStd->uiFlg) && CLPISF_FIX(psSym->psStd->uiFlg) && psSym->psFix->siMax>0) { psSym->psFix->siMax--; // CLPFLG_DLM support } if (psSym->psFix->siTyp!=CLPTYP_NUMBER && CLPISF_DEF(psSym->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_TAB,"Default flag for type '%s' of argument '%s.%s' not supported",apClpTyp[psSym->psFix->siTyp],pcPat); ERROR(psSym); } if (psSym->psFix->siTyp==CLPTYP_NUMBER && CLPISF_DEF(psSym->psStd->uiFlg) && psSym->psFix->siMax>1) { CLPERR(psHdl,CLPERR_TAB,"Default flag for arrays of type number of argument '%s.%s' not supported",pcPat); ERROR(psSym); } if (psArg->pcAli!=NULL) { if (psSym->psStd->pcKyw==NULL || *psSym->psStd->pcKyw==0) { CLPERR(psHdl,CLPERR_TAB,"Keyword of alias (%s.%s) is not defined",pcPat,psArg->pcAli); ERROR(psSym); } if (strxcmp(psHdl->isCas,psSym->psStd->pcKyw,psArg->pcAli,0,0,FALSE)==0) { CLPERR(psHdl,CLPERR_TAB,"Keyword and alias (%s.%s) are equal",pcPat,psArg->pcAli); ERROR(psSym); } for (k=0,psHlp=psCur;psHlp!=NULL;psHlp=psHlp->psBak) { if (CLPISF_ARG(psHlp->psStd->uiFlg) && strxcmp(psHdl->isCas,psArg->pcAli,psHlp->psStd->pcKyw,0,0,FALSE)==0) { if (k==0) { psSym->psStd->psAli=psHlp; psSym->psStd->uiFlg=psHlp->psStd->uiFlg|CLPFLG_ALI; free(psSym->psFix); psSym->psFix=psHlp->psFix; free(psSym->psVar); psSym->psVar=psHlp->psVar; } else { CLPERR(psHdl,CLPERR_TAB,"Alias '%s' for keyword '%s.%s' is not unique",psArg->pcAli,pcPat,psSym->psStd->pcKyw); ERROR(psSym); } k++; } } if (k==0) { CLPERR(psHdl,CLPERR_TAB,"Alias '%s' for keyword '%s.%s' cannot be resolved",psArg->pcAli,pcPat,psSym->psStd->pcKyw); ERROR(psSym); } } else if (CLPISF_ARG(psSym->psStd->uiFlg)) { if (psSym->psStd->pcKyw==NULL || *psSym->psStd->pcKyw==0) { CLPERR(psHdl,CLPERR_TAB,"Keyword for argument (%s.?) is not defined",pcPat); ERROR(psSym); } if (psSym->psFix->siMax<1 || psSym->psFix->siMax<psSym->psFix->siMin) { CLPERR(psHdl,CLPERR_TAB,"Maximal amount for argument '%s.%s' is too small",pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (psSym->psFix->siSiz<1) { CLPERR(psHdl,CLPERR_TAB,"Size for argument '%s.%s' is smaller than 1",pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (psSym->psFix->pcHlp==NULL || *psSym->psFix->pcHlp==0) { CLPERR(psHdl,CLPERR_TAB,"Help for argument '%s.%s' not defined",pcPat,psSym->psStd->pcKyw); ERROR(psSym); } } else if (CLPISF_LNK(psSym->psStd->uiFlg)) { if (psSym->psStd->pcKyw==NULL || *psSym->psStd->pcKyw==0) { CLPERR(psHdl,CLPERR_TAB,"Keyword of a link (%s.?) is not defined",pcPat); ERROR(psSym); } if (psArg->pcAli!=NULL) { CLPERR(psHdl,CLPERR_TAB,"Alias (%s) for link '%s.%s' defined",psArg->pcAli,pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (psSym->psFix->pcDft!=NULL) { CLPERR(psHdl,CLPERR_TAB,"Default (%s) for link '%s.%s' defined",psSym->psFix->pcDft,pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (psSym->psFix->siTyp!=CLPTYP_NUMBER) { CLPERR(psHdl,CLPERR_TAB,"Type for link '%s.%s' is not a number",pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (psSym->psFix->siMax<1 || psSym->psFix->siMax<psSym->psFix->siMin) { CLPERR(psHdl,CLPERR_TAB,"Maximal amount for link '%s.%s' is too small",pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (psSym->psFix->siSiz<1) { CLPERR(psHdl,CLPERR_TAB,"Size for link '%s.%s' is smaller than 1",pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (CLPISF_SEL(psSym->psStd->uiFlg) || CLPISF_CON(psSym->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_TAB,"Flag SEL or CON set for link '%s.%s'",pcPat,psSym->psStd->pcKyw); ERROR(psSym); } } else if (CLPISF_CON(psSym->psStd->uiFlg)) { if (psSym->psStd->pcKyw==NULL || *psSym->psStd->pcKyw==0) { CLPERR(psHdl,CLPERR_TAB,"Key word for a constant (%s.?) is not defined",pcPat); ERROR(psSym); } if (psArg->pcAli!=NULL) { CLPERR(psHdl,CLPERR_TAB,"Alias (%s) for constant '%s.%s' defined",psArg->pcAli,pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (psSym->psFix->pcDft!=NULL) { CLPERR(psHdl,CLPERR_TAB,"Default (%s) for constant '%s.%s' defined",psSym->psFix->pcDft,pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (psArg->psTab!=NULL) { CLPERR(psHdl,CLPERR_TAB,"Table for constant '%s.%s' defined",pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (CLPISF_SEL(psSym->psStd->uiFlg) || CLPISF_LNK(psSym->psStd->uiFlg) || CLPISF_ALI(psSym->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_TAB,"Flags SEL, LNK or ALI set for constant '%s.%s'",pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (psSym->psFix->pcHlp==NULL || *psSym->psFix->pcHlp==0) { CLPERR(psHdl,CLPERR_TAB,"Help for constant '%s.%s' not defined",pcPat,psSym->psStd->pcKyw); ERROR(psSym); } psSym->psFix->siMin=1; psSym->psFix->siMax=1; psSym->psFix->siOfs=0; psSym->psFix->siOid=0; switch (psSym->psFix->siTyp) { case CLPTYP_NUMBER: psSym->psFix->siSiz=sizeof(psArg->siVal); psSym->psVar->pvDat=(void*)&psArg->siVal; break; case CLPTYP_FLOATN: psSym->psFix->siSiz= sizeof(psArg->flVal); psSym->psVar->pvDat=(void*)&psArg->flVal; break; case CLPTYP_STRING: if (psArg->pcVal==NULL) { CLPERR(psHdl,CLPERR_TAB,"Type '%s' for constant '%s.%s' requires a value (pcVal==NULL)",apClpTyp[psSym->psFix->siTyp],pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (!CLPISF_BIN(psSym->psStd->uiFlg) && psSym->psFix->siSiz==0) { psSym->psFix->siSiz=strlen((char*)psArg->pcVal)+1; } psSym->psVar->pvDat=(void*)psArg->pcVal; break; default: CLPERR(psHdl,CLPERR_TAB,"Type (%s) for argument '%s.%s' not supported for constant definitions",apClpTyp[psSym->psFix->siTyp],pcPat,psSym->psStd->pcKyw); ERROR(psSym); } psSym->psVar->pvPtr=NULL; psSym->psVar->siLen=psSym->psFix->siSiz; psSym->psVar->siCnt=1; psSym->psVar->siRst=0; } else { CLPERR(psHdl,CLPERR_TAB,"Kind (ALI/ARG/LNK/CON) of argument '%s.%s' not determinable",pcPat,psSym->psStd->pcKyw); ERROR(psSym); } if (!CLPISF_CMD(psSym->psStd->uiFlg) && !CLPISF_PRO(psSym->psStd->uiFlg) && !CLPISF_DMY(psSym->psStd->uiFlg) && !CLPISF_HID(psSym->psStd->uiFlg)) { psSym->psStd->uiFlg|=CLPFLG_CMD; psSym->psStd->uiFlg|=CLPFLG_PRO; } if (psCur!=NULL) { psSym->psNxt=psCur->psNxt; psSym->psBak=psCur; if (psCur->psNxt!=NULL) { psCur->psNxt->psBak=psSym; } psCur->psNxt=psSym; } else { psSym->psNxt=NULL; psSym->psBak=NULL; if (psHih!=NULL) psHih->psDep=psSym; } psSym->psDep=NULL; psSym->psHih=psHih; psHdl->siSym++; return(psSym); } #undef ERROR static int siClpSymIni( void* pvHdl, const int siLev, const TsClpArgument* psArg, const TsClpArgument* psTab, TsSym* psHih, TsSym** ppFst) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr; TsSym* psCur=NULL; TsSym* psFst=NULL; int i,j; if (psTab==NULL) { if (psArg==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Argument table not defined%s",""); } else { return CLPERR(psHdl,CLPERR_TAB,"Parameter table of argument '%s:%s' not defined",fpcPat(pvHdl,siLev),psArg->pcKyw); } } for (j=i=0;psTab[i].siTyp;i++) { if (i>=CLPMAX_TABCNT) { if (psArg==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Argument table bigger than maximal supported entry count (%d)",CLPMAX_TABCNT); } else { return CLPERR(psHdl,CLPERR_TAB,"Table for key word (%s:%s) bigger than maximal supported entry count (%d)",fpcPat(pvHdl,siLev),psArg->pcKyw,CLPMAX_TABCNT); } } if (psTab[i].pcKyw==NULL || psTab[i].pcKyw[0]==0x00) { if (psArg==NULL) { return CLPERR(psHdl,CLPERR_TAB,"There is no keyword defined in argument table at index %d",i); } else { return CLPERR(psHdl,CLPERR_TAB,"The table for keyword (%s:%s) has no keyword defined at index %d",fpcPat(pvHdl,siLev),psArg->pcKyw,i); } } else { if (strlen(psTab[i].pcKyw)>CLPMAX_KYWLEN) { if (psArg==NULL) { return CLPERR(psHdl,CLPERR_TAB,"The keyword defined in argument table at index %d is too long (>%d)",i,CLPMAX_KYWLEN); } else { return CLPERR(psHdl,CLPERR_TAB,"The keyword defined in table (%s:%s) at index %d is too long (>%d)",fpcPat(pvHdl,siLev),psArg->pcKyw,i,CLPMAX_KYWLEN); } } } if (!CLPISF_DMY(psTab[i].uiFlg)) { psCur=psClpSymIns(pvHdl,siLev,i,&psTab[i],psHih,psCur); if (psCur==NULL) { return CLPERR(psHdl,CLPERR_SYS,"Insert of symbol (%s.%s) in symbol table failed",fpcPat(pvHdl,siLev),psTab[i].pcKyw); } if (j==0) *ppFst=psCur; switch (psTab[i].siTyp) { case CLPTYP_SWITCH: if (psTab[i].psTab!=NULL) { return CLPERR(psHdl,CLPERR_TAB,"Parameter table of argument '%s.%s' of type switch is defined (NULL for psTab required)",fpcPat(pvHdl,siLev),psTab[i].pcKyw); } if (psTab[i].siMax!=1) { return CLPERR(psHdl,CLPERR_TAB,"Array definition not possible for a switch (%s.%s)",fpcPat(pvHdl,siLev),psTab[i].pcKyw); } break; case CLPTYP_NUMBER: case CLPTYP_FLOATN: case CLPTYP_STRING: if (CLPISF_SEL(psTab[i].uiFlg)) { psHdl->apPat[siLev]=psCur; siErr=siClpSymIni(pvHdl,siLev+1,psTab+i,psTab[i].psTab,psCur,&psFst); if (siErr<0) return(siErr); } else { if (psTab[i].psTab!=NULL) { psHdl->apPat[siLev]=psCur; siErr=siClpSymIni(pvHdl,siLev+1,psTab+i,psTab[i].psTab,psCur,&psFst); if (siErr<0) return(siErr); } } break; case CLPTYP_OBJECT: case CLPTYP_OVRLAY: psHdl->apPat[siLev]=psCur; siErr=siClpSymIni(pvHdl,siLev+1,psTab+i,psTab[i].psTab,psCur,&psFst); if (siErr<0) return(siErr); break; case CLPTYP_XALIAS: break; default: return CLPERR(psHdl,CLPERR_TYP,"Type (%d) of parameter '%s.%s' not supported",psTab[i].siTyp,fpcPat(pvHdl,siLev),psTab[i].pcKyw); } j++; } } return(CLP_OK); } static void vdClpSymLnkCnt( TsSym* psSym, TsSym* psLnk) { TsSym* psSon; for (psSon=psSym->psDep; psSon!=NULL; psSon=psSon->psNxt) { if (psSon->psFix->siTyp==CLPTYP_OVRLAY) { psSon->psFix->psCnt=psLnk; vdClpSymLnkCnt(psSon,psLnk); } } } static void vdClpSymLnkOid( TsSym* psSym, TsSym* psLnk) { TsSym* psSon; for (psSon=psSym->psDep; psSon!=NULL; psSon=psSon->psNxt) { if (psSon->psFix->siTyp==CLPTYP_OVRLAY) { psSon->psFix->psOid=psLnk; vdClpSymLnkOid(psSon,psLnk); } } } static void vdClpSymLnkInd( TsSym* psSym, TsSym* psLnk) { TsSym* psSon; for (psSon=psSym->psDep; psSon!=NULL; psSon=psSon->psNxt) { if (psSon->psFix->siTyp==CLPTYP_OVRLAY) { psSon->psFix->psInd=psLnk; vdClpSymLnkInd(psSon,psLnk); } } } static void vdClpSymLnkEln( TsSym* psSym, TsSym* psLnk) { TsSym* psSon; for (psSon=psSym->psDep; psSon!=NULL; psSon=psSon->psNxt) { if (psSon->psFix->siTyp==CLPTYP_OVRLAY) { psSon->psFix->psEln=psLnk; vdClpSymLnkEln(psSon,psLnk); } } } static void vdClpSymLnkSln( TsSym* psSym, TsSym* psLnk) { TsSym* psSon; for (psSon=psSym->psDep; psSon!=NULL; psSon=psSon->psNxt) { if (psSon->psFix->siTyp==CLPTYP_OVRLAY) { psSon->psFix->psSln=psLnk; vdClpSymLnkSln(psSon,psLnk); } } } static void vdClpSymLnkTln( TsSym* psSym, TsSym* psLnk) { TsSym* psSon; for (psSon=psSym->psDep; psSon!=NULL; psSon=psSon->psNxt) { if (psSon->psFix->siTyp==CLPTYP_OVRLAY) { psSon->psFix->psTln=psLnk; vdClpSymLnkTln(psSon,psLnk); } } } static int siClpSymCal( void* pvHdl, int siLev, TsSym* psArg, TsSym* psTab) { TsHdl* psHdl=(TsHdl*)pvHdl; TsSym* psSym; TsSym* psHlp=NULL; int isPar=FALSE; int isCon=FALSE; int siCon=0; int siErr,siPos,k,h; for (siPos=0,psSym=psTab;psSym!=NULL;psSym=psSym->psNxt,siPos++) { if (psSym->psStd->siLev!=siLev) { if (psArg==NULL) { return CLPERR(psHdl,CLPERR_INT,"Argument table not in sync with symbol table%s",""); } else { return CLPERR(psHdl,CLPERR_INT,"Parameter table of argument '%s.%s' not in sync with symbol table",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } } if (CLPISF_ALI(psSym->psStd->uiFlg)) { isPar=TRUE; } else if (CLPISF_ARG(psSym->psStd->uiFlg)) { isPar=TRUE; } else if (CLPISF_LNK(psSym->psStd->uiFlg)) { isPar=TRUE; for (h=k=0,psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt) { if (CLPISF_ARG(psHlp->psStd->uiFlg) && strxcmp(psHdl->isCas,psSym->psStd->pcKyw,psHlp->psStd->pcKyw,0,0,FALSE)==0) { psSym->psFix->psLnk=psHlp; h++; if (CLPISF_CNT(psSym->psStd->uiFlg)) { psHlp->psFix->psCnt=psSym; k++; if (psHlp->psFix->siTyp==CLPTYP_OVRLAY) { vdClpSymLnkCnt(psHlp,psSym); } } if (CLPISF_OID(psSym->psStd->uiFlg)) { psHlp->psFix->psOid=psSym; k++; if (psHlp->psFix->siTyp==CLPTYP_OVRLAY) { vdClpSymLnkOid(psHlp,psSym); } } if (CLPISF_IND(psSym->psStd->uiFlg)) { psHlp->psFix->psInd=psSym; k++; if (psHlp->psFix->siTyp==CLPTYP_OVRLAY) { vdClpSymLnkInd(psHlp,psSym); } } if (CLPISF_ELN(psSym->psStd->uiFlg)) { psHlp->psFix->psEln=psSym; k++; if (psHlp->psFix->siTyp==CLPTYP_OVRLAY) { vdClpSymLnkEln(psHlp,psSym); } } if (CLPISF_SLN(psSym->psStd->uiFlg)) { psHlp->psFix->psSln=psSym; k++; if (psHlp->psFix->siTyp==CLPTYP_OVRLAY) { vdClpSymLnkSln(psHlp,psSym); } } if (CLPISF_TLN(psSym->psStd->uiFlg)) { psHlp->psFix->psTln=psSym; k++; if (psHlp->psFix->siTyp==CLPTYP_OVRLAY) { vdClpSymLnkTln(psHlp,psSym); } } } } if (psSym->psFix->psLnk==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Link for keyword '%s.%s' cannot be resolved",fpcPat(pvHdl,siLev),psSym->psStd->pcKyw); } if (h>1) { return CLPERR(psHdl,CLPERR_TAB,"Link for keyword '%s.%s' is not unique",fpcPat(pvHdl,siLev),psSym->psStd->pcKyw); } if (k>1) { return CLPERR(psHdl,CLPERR_TAB,"More than one link defined for keyword '%s.%s'",fpcPat(pvHdl,siLev),psSym->psStd->pcKyw); } if (k==0) { return CLPERR(psHdl,CLPERR_TAB,"Link for keyword '%s.%s' was not assigned",fpcPat(pvHdl,siLev),psSym->psStd->pcKyw); } } else if (CLPISF_CON(psSym->psStd->uiFlg)) { isCon=TRUE; siCon++; } else { return CLPERR(psHdl,CLPERR_TAB,"Kind (ALI/ARG/LNK/CON) of argument '%s.%s' not determinable",fpcPat(pvHdl,siLev),psSym->psStd->pcKyw); } psSym->psStd->siKwl=strlen(psSym->psStd->pcKyw); if (psHdl->siMkl>0) { if (psSym->psStd->siKwl>psHdl->siMkl) psSym->psStd->siKwl=psHdl->siMkl; if (!CLPISF_LNK(psSym->psStd->uiFlg)) { for (psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt) { if (psHlp!=psSym && !CLPISF_LNK(psHlp->psStd->uiFlg)) { if (psHdl->isCas) { for (k=0;psSym->psStd->pcKyw[k] && psHlp->psStd->pcKyw[k] && psSym->psStd->pcKyw[k] == psHlp->psStd->pcKyw[k] ;k++); } else { for (k=0;psSym->psStd->pcKyw[k] && psHlp->psStd->pcKyw[k] && toupper(psSym->psStd->pcKyw[k])==toupper(psHlp->psStd->pcKyw[k]);k++); } if (psSym->psStd->pcKyw[k]==0 && psHlp->psStd->pcKyw[k]==0) { return CLPERR(psHdl,CLPERR_TAB,"Key word '%s.%s' is not unique",fpcPat(pvHdl,siLev),psSym->psStd->pcKyw); } if (psSym->psStd->pcKyw[k]==0) { psSym->psStd->siKwl=k; if (psHlp->psStd->siKwl<=k) psHlp->psStd->siKwl=k+1; } else if (psHlp->psStd->pcKyw[k]==0) { psHlp->psStd->siKwl=k; if (psSym->psStd->siKwl<=k) psSym->psStd->siKwl=k+1; } else { if (psSym->psStd->siKwl<=k) psSym->psStd->siKwl=k+1; } } } } } if (psSym->psDep!=NULL) { psHdl->apPat[siLev]=psSym; siErr=siClpSymCal(pvHdl,siLev+1,psSym,psSym->psDep); if (siErr<0) return(siErr); } #ifdef __DEBUG__ char acKyw[strlen(psSym->psStd->pcKyw)+1]; strcpy(acKyw,psSym->psStd->pcKyw); for (int i=strlen(acKyw);i>=psSym->psStd->siKwl;i--) { acKyw[i]=0x00; if (CLPTOK_KYW!=siClpConNat(pvHdl,psHdl->pfErr,NULL,acKyw,NULL,NULL,-1,NULL)) { fprintf(stderr,"%s:%d:1: warning: Constant keyword (%s) re-used in table definitions (%s.%s)\n",__FILE__,__LINE__,acKyw,fpcPat(pvHdl,siLev),psSym->psStd->pcKyw); } } #endif } if (isCon && (isPar || siCon!=siPos)) { if (psArg==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Argument table is not consistent (mix of constants and parameter)%s",""); } else { return CLPERR(psHdl,CLPERR_TAB,"Parameter table of argument '%s.%s' is not consistent (mix of constants and parameter)",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } } if (isCon==FALSE && isPar==FALSE) { if (psArg==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Argument table neither contains constants nor arguments%s",""); } else { return CLPERR(psHdl,CLPERR_TAB,"Parameter table of argument '%s.%s' neither contains constants nor arguments",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } } for (psSym=psTab;psSym!=NULL;psSym=psSym->psNxt) { if (!CLPISF_LNK(psSym->psStd->uiFlg)) { if (psSym->psStd->siKwl<=0) { return CLPERR(psHdl,CLPERR_TAB,"Required keyword length (%d) of argument '%s.%s' is smaller or equal to zero",psSym->psStd->siKwl,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } if (psSym->psStd->siKwl>(int)strlen(psSym->psStd->pcKyw)) { return CLPERR(psHdl,CLPERR_TAB,"Required keyword length (%d) of argument '%s.%s' is greater then keyword length",psSym->psStd->siKwl,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } } if (CLPISF_ALI(psSym->psStd->uiFlg)) { psSym->psDep=psSym->psStd->psAli->psDep; psSym->psHih=psSym->psStd->psAli->psHih; } } return(CLP_OK); } static const TsSym* psClpFndSym( void* pvHdl, const char* pcKyw, const TsSym* psTab) { TsHdl* psHdl=(TsHdl*)pvHdl; const TsSym* psHlp=NULL; int i,j,k; for (i=0,psHlp=psTab;psHlp!=NULL && psHlp->psStd!=NULL;psHlp=psHlp->psNxt,i++) { if (!CLPISF_LNK(psHlp->psStd->uiFlg)) { if (psHdl->isCas) { for (k=j=0;k==0 && pcKyw[j]!=EOS && psHlp->psStd->pcKyw!=NULL;j++) { if (pcKyw[j]!=psHlp->psStd->pcKyw[j]) k++; } } else { for (k=j=0;k==0 && pcKyw[j]!=EOS && psHlp->psStd->pcKyw!=NULL;j++) { if (toupper(pcKyw[j])!=toupper(psHlp->psStd->pcKyw[j])) k++; } } if (k==0 && j>=psHlp->psStd->siKwl) { TRACE(psHdl->pfPrs,"FIND-SYMBOL1(KYW=%s(%s))\n",pcKyw,psHlp->psStd->pcKyw); return(psHlp); } } } return(NULL); } static const TsSym* psClpFndSym2( void* pvHdl, const char* pcKyw, const TsSym* psTab) { TsHdl* psHdl=(TsHdl*)pvHdl; const TsSym* psHlp=NULL; int i,j,k; if (psTab) { for (i=0,psHlp=psTab;psHlp!=NULL && psHlp->psStd!=NULL;psHlp=psHlp->psBak,i++) { if (!CLPISF_LNK(psHlp->psStd->uiFlg)) { if (psHdl->isCas) { for (k=j=0;k==0 && pcKyw[j]!=EOS && psHlp->psStd->pcKyw!=NULL;j++) { if (pcKyw[j]!=psHlp->psStd->pcKyw[j]) k++; } } else { for (k=j=0;k==0 && pcKyw[j]!=EOS && psHlp->psStd->pcKyw!=NULL;j++) { if (toupper(pcKyw[j])!=toupper(psHlp->psStd->pcKyw[j])) k++; } } if (k==0 && j>=psHlp->psStd->siKwl) { TRACE(psHdl->pfPrs,"FIND-SYMBOL2a(KYW=%s(%s))\n",pcKyw,psHlp->psStd->pcKyw); return(psHlp); } } } for (i=0,psHlp=psTab->psNxt;psHlp!=NULL && psHlp->psStd!=NULL;psHlp=psHlp->psNxt,i++) { if (!CLPISF_LNK(psHlp->psStd->uiFlg)) { if (psHdl->isCas) { for (k=j=0;k==0 && pcKyw[j]!=EOS && psHlp->psStd->pcKyw!=NULL;j++) { if (pcKyw[j]!=psHlp->psStd->pcKyw[j]) k++; } } else { for (k=j=0;k==0 && pcKyw[j]!=EOS && psHlp->psStd->pcKyw!=NULL;j++) { if (toupper(pcKyw[j])!=toupper(psHlp->psStd->pcKyw[j])) k++; } } if (k==0 && j>=psHlp->psStd->siKwl) { TRACE(psHdl->pfPrs,"FIND-SYMBOL2b(KYW=%s(%s))\n",pcKyw,psHlp->psStd->pcKyw); return(psHlp); } } } } return(NULL); } static int siClpSymFnd( void* pvHdl, const int siLev, const char* pcKyw, const TsSym* psTab, TsSym** ppArg, int* piElm) { TsHdl* psHdl=(TsHdl*)pvHdl; const TsSym* psHlp=NULL; int i,j,k,e; *ppArg=NULL; if (psTab==NULL) { CLPERR(psHdl,CLPERR_SYN,"Keyword '%s.%s' not valid",fpcPat(pvHdl,siLev),pcKyw); CLPERRADD(psHdl, 1,"Unexpected end of path reached%s",""); return(CLPERR_SYN); } if (psTab->psBak!=NULL) { CLPERR(psHdl,CLPERR_INT,"Entry '%s.%s' not at beginning of a table",fpcPat(pvHdl,siLev),psTab->psStd->pcKyw); CLPERRADD(psHdl, 1,"Try to find keyword '%s' in this table",pcKyw); return(CLPERR_INT); } for (e=i=0,psHlp=psTab;psHlp!=NULL && psHlp->psStd!=NULL;psHlp=psHlp->psNxt,i++) { if (!CLPISF_LNK(psHlp->psStd->uiFlg)) { if (psHdl->isCas) { for (k=j=0;k==0 && pcKyw[j]!=EOS && psHlp->psStd->pcKyw!=NULL;j++) { if (pcKyw[j]!=psHlp->psStd->pcKyw[j]) k++; } } else { for (k=j=0;k==0 && pcKyw[j]!=EOS && psHlp->psStd->pcKyw!=NULL;j++) { if (toupper(pcKyw[j])!=toupper(psHlp->psStd->pcKyw[j])) k++; } } if (k==0 && j>=psHlp->psStd->siKwl) { if (piElm!=NULL) (*piElm)=e; *ppArg=(TsSym*)psHlp; TRACE(psHdl->pfPrs,"%s FIND-SYMBOL3(LEV=%d ELM=%d IND=%d KYW=%s(%s))\n",fpcPre(pvHdl,siLev),siLev,e,i,pcKyw,psHlp->psStd->pcKyw); return(i); } if (piElm!=NULL) { if (CLPISF_ARG(psHlp->psStd->uiFlg) || CLPISF_CON(psHlp->psStd->uiFlg)) { e++; } } } } CLPERR(psHdl,CLPERR_SYN,"Parameter '%s.%s' not valid",fpcPat(pvHdl,siLev),pcKyw); CLPERRADD(psHdl,0,"Please use one of the following parameters:%s",""); vdClpPrnArgTab(pvHdl,psHdl->pfErr,1,-1,psTab); return(CLPERR_SYN); } static void vdClpSymPrn( void* pvHdl, int siLev, TsSym* psSym) { TsHdl* psHdl=(TsHdl*)pvHdl; TsSym* psHlp=psSym; while (psHlp!=NULL) { if (psHdl->pfSym!=NULL) { char acTs[24]; efprintf(psHdl->pfSym,"%s %s %3.3d - %s (KWL=%d TYP=%s MIN=%d MAX=%d SIZ=%d OFS=%d OID=%d FLG=%8.8X (NXT=%p BAK=%p DEP=%p HIH=%p ALI=%p CNT=%p OID=%p IND=%p ELN=%p SLN=%p TLN=%p LNK=%p)) - %s\n", cstime(0,acTs),fpcPre(pvHdl,siLev),psHlp->psStd->siPos+1,psHlp->psStd->pcKyw,psHlp->psStd->siKwl,apClpTyp[psHlp->psFix->siTyp],psHlp->psFix->siMin,psHlp->psFix->siMax,psHlp->psFix->siSiz, psHlp->psFix->siOfs,psHlp->psFix->siOid,psHlp->psStd->uiFlg,psHlp->psNxt,psHlp->psBak,psHlp->psDep,psHlp->psHih,psHlp->psStd->psAli,psHlp->psFix->psCnt,psHlp->psFix->psOid, psHlp->psFix->psInd,psHlp->psFix->psEln,psHlp->psFix->psSln,psHlp->psFix->psTln,psHlp->psFix->psLnk,psHlp->psFix->pcHlp); fflush(psHdl->pfSym); } if (psHlp->psDep!=NULL) { vdClpSymPrn(pvHdl,siLev+1,psHlp->psDep); } psHlp=psHlp->psNxt; } } static void vdClpSymTrc( void* pvHdl) { TsHdl* psHdl=(TsHdl*)pvHdl; if (psHdl->pfSym!=NULL) { char acTs[24]; fprintf(psHdl->pfSym,"%s BEGIN-SYMBOL-TABLE-TRACE\n",cstime(0,acTs)); fflush(psHdl->pfSym); vdClpSymPrn(pvHdl,0,psHdl->psTab); fprintf(psHdl->pfSym,"%s END-SYMBOL-TABLE-TRACE\n",cstime(0,acTs)); fflush(psHdl->pfSym); } } static void vdClpSymDel( TsSym* psSym) { TsSym* psHlp=psSym; TsSym* psOld; while (psHlp!=NULL) { if (!CLPISF_ALI(psHlp->psStd->uiFlg) && psHlp->psDep!=NULL) { vdClpSymDel(psHlp->psDep); } if (!CLPISF_ALI(psHlp->psStd->uiFlg) && psHlp->psVar!=NULL) { memset(psHlp->psVar,0,sizeof(TsVar)); free(psHlp->psVar); psHlp->psVar=NULL; } if (!CLPISF_ALI(psHlp->psStd->uiFlg) && psHlp->psFix!=NULL) { if (psHlp->psFix->pcPro!=NULL) free(psHlp->psFix->pcPro); if (psHlp->psFix->pcSrc!=NULL) free(psHlp->psFix->pcSrc); memset(psHlp->psFix,0,sizeof(TsFix)); free(psHlp->psFix); psHlp->psFix=NULL; } if (psHlp->psStd!=NULL) { memset(psHlp->psStd,0,sizeof(TsStd)); free(psHlp->psStd); psHlp->psStd=NULL; } psOld=psHlp; psHlp=psHlp->psNxt; memset(psOld,0,sizeof(TsSym)); free(psOld); } } /* Scanner ************************************************************/ #define STRCHR '\'' #define SPMCHR '\"' #define ALTCHR C_GRV extern int siClpLexemes( void* pvHdl, FILE* pfOut) { if (pfOut!=NULL) { fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," COMMENT '#' [:print:]* '#' (will be ignored)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," LCOMMENT ';' [:print:]* 'nl' (will be ignored)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," SEPARATOR [:space: | :cntr: | ',']* (abbreviated with SEP)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," OPERATOR '=' | '.' | '(' | ')' | '[' | ']' | (SGN, DOT, RBO, RBC, SBO, SBC)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '=>'| '+' | '-' | '*' | '/' | '{' | '}' (SAB, ADD, SUB, MUL, DIV, CBO,CBC)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," KEYWORD ['-'['-']][:alpha:]+[:alnum: | '_']* (always predefined)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," NUMBER ([+|-] [ :digit:]+) | (decimal (default))\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," num ([+|-]0b[ :digit:]+) | (binary)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," num ([+|-]0o[ :digit:]+) | (octal)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," num ([+|-]0d[ :digit:]+) | (decimal)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," num ([+|-]0x[ :xdigit:]+) | (hexadecimal)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," num ([+|-]0t(yyyy/mm/tt.hh:mm:ss)) | (relativ (+|-) or absolut time)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," FLOAT ([+|-] [ :digit:]+.[:digit:]+e|E[:digit:]+) | (decimal(default))\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," flt ([+|-]0d[ :digit:]+.[:digit:]+e|E[:digit:]+) (decimal)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," STRING ''' [:print:]* ''' | (default (if binary c else s))\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," str [s|S]''' [:print:]* ''' | (null-terminated string)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," str [c|C]''' [:print:]* ''' | (binary string in local character set)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," str [a|A]''' [:print:]* ''' | (binary string in ASCII)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," str [e|E]''' [:print:]* ''' | (binary string in EBCDIC)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," str [x|X]''' [:print:]* ''' | (binary string in hex notation)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," str [f|F]''' [:print:]* ''' | (read string from file (for passwords))\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," Strings can contain two '' to represent one ' \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," Strings can also be enclosed in \" or %c instead of ' \n",ALTCHR); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," Strings can directly start behind a '=' without enclosing ('%c\") \n",ALTCHR); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," In this case the string ends at the next separator or operator\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," and keywords are preferred. To use keywords, separators or \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," operators in strings, enclosing quotes are required. \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," The predefined constant keyword below can be used in a value expressions \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," NOW NUMBER - current time in seconds since 1970 (+0t0000) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," MINUTE NUMBER - minute in seconds (60) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," HOUR NUMBER - hour in seconds (60*60) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," DAY NUMBER - day in seconds (24*60*60) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," YEAR NUMBER - year in seconds (365*24*60*60) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," KiB NUMBER - kilobyte (1024) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," MiB NUMBER - megabyte (1024*1024) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," GiB NUMBER - gigabyte (1024*1024*1024) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," TiB NUMBER - terrabyte (1024*1024*1024*1024) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," RNDn NUMBER - simple random number with n * 8 bit in length (1,2,4,8) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," PI FLOAT - PI (3.14159265359) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," LCSTAMP STRING - current local stamp in format: YYYYMMDD.HHMMSS\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," LCDATE STRING - current local date in format: YYYYMMDD \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," LCYEAR STRING - current local year in format: YYYY \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," LCYEAR2 STRING - current local year in format: YY \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," LCMONTH STRING - current local month in format: MM \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," LCDAY STRING - current local day in format: DD \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," LCTIME STRING - current local time in format: HHMMSS \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," LCHOUR STRING - current local hour in format: HH \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," LCMINUTE STRING - current local minute in format: MM \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," LCSECOND STRING - current local second in format: SS \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," GMSTAMP STRING - current Greenwich mean stamp in format: YYYYMMDD.HHMMSS\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," GMDATE STRING - current Greenwich mean date in format: YYYYMMDD \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," GMYEAR STRING - current Greenwich mean year in format: YYYY \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," GMYEAR2 STRING - current Greenwich mean year in format: YY \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," GMMONTH STRING - current Greenwich mean month in format: MM \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," GMDAY STRING - current Greenwich mean day in format: DD \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," GMTIME STRING - current Greenwich mean time in format: HHMMSS \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," GMHOUR STRING - current Greenwich mean hour in format: HH \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," GMMINUTE STRING - current Greenwich mean minute in format: MM \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," GMSECOND STRING - current Greenwich mean second in format: SS \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," GMSECOND STRING - current Greenwich mean second in format: SS \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," SnRND10 STRING - decimal random number of length n (1 to 8) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," SnRND16 STRING - hexadecimal random number of length n (1 to 8) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," SUPPLEMENT '\"' [:print:]* '\"' | (null-terminated string (properties))\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," Supplements can contain two \"\" to represent one \" \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," Supplements can also be enclosed in ' or %c instead of \" \n",ALTCHR); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," Supplements can also be enclosed in ' or %c instead of \" \n",ALTCHR); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," ENVIRONMENT VARIABLES '<'varnam'>' will replaced by the corresponding value \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," Escape sequences for critical punctuation characters on EBCDIC systems \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '!' = '&EXC;' - Exclamation mark \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '$' = '&DLR;' - Dollar sign \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '#' = '&HSH;' - Hashtag (number sign) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '@' = '&ATS;' - At sign \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '[' = '&SBO;' - Square bracket open \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '\\' = '&BSL;' - Backslash \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," ']' = '&SBC;' - Square bracket close \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '^' = '&CRT;' - Caret (circumflex) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '`' = '&GRV;' - Grave accent \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '{' = '&CBO;' - Curly bracket open \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '|' = '&VBR;' - Vertical bar \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '}' = '&CBC;' - Curly bracket close \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '~' = '&TLD;' - Tilde \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," Define CCSIDs for certain areas in CLP strings on EBCDIC systems (0-reset) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '&' [:digit:]+ '; (...\"&1047;get.file='&0;%%s&1047;'\",f) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," Escape sequences for hexadecimal byte values \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," '&' ['X''x'] :xdigit: :xdigit: ';' (\"&xF5;\") \n"); } return(CLP_OK); } #define isPrintF(p) (((p)!=NULL)?(CLPISF_PWD((p)->psStd->uiFlg)==FALSE):(TRUE)) #define isPrnLex(p,l) (isPrintF(p)?(l):("***SECRET***")) #define isPrintF2(p) (CLPISF_PWD((p)->psStd->uiFlg)==FALSE) #define isPrnLex2(p,l) (isPrintF2(p)?(l):("***SECRET***")) #define isStringChr(c) ((c)==STRCHR || (c)==SPMCHR || (c)==ALTCHR) #define isSeparation(c) (isspace((c)) || iscntrl((c)) || ((c))==',') #define isReqStrOpr1(c) ((c)=='=' || (c)=='+' || (c)==')' || (c)==C_SBC || (c)==C_CBC) // required string cannot start with this characters #define isReqStrOpr2(c) ((c)==';' || (c)==C_HSH) // required string must end at this #define isReqStrOpr3(c) (isReqStrOpr1(c) || (c)=='(' || (c)=='.' || (c)==C_SBO || (c)==C_CBO || isStringChr(c))// required string must end at key word if one of this follows #define LEX_REALLOC \ if (pcLex>=(pcEnd-4)) {\ size_t l=pcLex-(*ppLex);\ size_t h=pcHlp-(*ppLex);\ size_t s=(*pzLex)?(*pzLex)*2:CLPINI_LEXSIZ;\ char* b=(char*)realloc_nowarn(*ppLex,s);\ if (b==NULL) return CLPERR(psHdl,CLPERR_MEM,"Re-allocation to store the lexeme failed");\ (*pzLex)=s;\ if (b!=(*ppLex)) {\ (*ppLex)=b;\ pcLex=(*ppLex)+l;\ pcHlp=(*ppLex)+h;\ pcEnd=(*ppLex)+(*pzLex);\ }\ } static int siClpConNat( void* pvHdl, FILE* pfErr, FILE* pfTrc, const char* pcKyw, size_t* pzLex, char** ppLex, const int siTyp, const TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; (void)pfErr; if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"NOW",0,0,FALSE)==0) { if (pzLex!=NULL && ppLex!=NULL) { srprintf(ppLex,pzLex,24,"d+%"PRIu64"",((U64)psHdl->siNow)); TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); if (psArg!=NULL) psArg->psStd->uiFlg|=CLPFLG_TIM; } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"MINUTE",0,0,FALSE)==0) { if (pzLex!=NULL) { srprintf(ppLex,pzLex,24,"d+%"PRIu64"",((U64)60)); TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"HOUR",0,0,FALSE)==0) { if (pzLex!=NULL) { srprintf(ppLex,pzLex,24,"d+%"PRIu64"",((U64)60)*((U64)60)); TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"DAY",0,0,FALSE)==0) { if (pzLex!=NULL) { srprintf(ppLex,pzLex,24,"d+%"PRIu64"",((U64)24)*((U64)60)*((U64)60)); TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"YEAR",0,0,FALSE)==0) { if (pzLex!=NULL) { srprintf(ppLex,pzLex,24,"d+%"PRIu64"",((U64)365)*((U64)24)*((U64)60)*((U64)60)); TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"KiB",0,0,FALSE)==0) { if (pzLex!=NULL) { srprintf(ppLex,pzLex,24,"d+%"PRIu64"",((U64)1024)); TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"MiB",0,0,FALSE)==0) { if (pzLex!=NULL) { srprintf(ppLex,pzLex,24,"d+%"PRIu64"",((U64)1024)*((U64)1024)); TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"GiB",0,0,FALSE)==0) { if (pzLex!=NULL) { srprintf(ppLex,pzLex,24,"d+%"PRIu64"",((U64)1024)*((U64)1024)*((U64)1024)); TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"TiB",0,0,FALSE)==0) { if (pzLex!=NULL) { srprintf(ppLex,pzLex,24,"d+%"PRIu64"",((U64)1024)*((U64)1024)*((U64)1024)*((U64)1024)); TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"RND8",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); if (psHdl->siRnd>=0) { srprintf(ppLex,pzLex,24,"d+%"PRIi64"",psHdl->siRnd); } else { srprintf(ppLex,pzLex,24,"d%"PRIi64"",psHdl->siRnd); } TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"RND4",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); I32 siRnd=(I32)psHdl->siRnd; if (siRnd>=0) { srprintf(ppLex,pzLex,24,"d+%d",siRnd); } else { srprintf(ppLex,pzLex,24,"d%d",siRnd); } TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"RND2",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); I16 siRnd=(I16)psHdl->siRnd; if (siRnd>=0) { srprintf(ppLex,pzLex,24,"d+%d",(I32)siRnd); } else { srprintf(ppLex,pzLex,24,"d%d",(I32)siRnd); } TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_NUMBER || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"RND1",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); I08 siRnd=(I08)psHdl->siRnd; if (siRnd>=0) { srprintf(ppLex,pzLex,24,"d+%d",(I32)siRnd); } else { srprintf(ppLex,pzLex,24,"d%d",(I32)siRnd); } TRACE(pfTrc,"CONSTANT-TOKEN(NUM)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_NUM); } else if ((siTyp==CLPTYP_FLOATN || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"PI",0,0,FALSE)==0) { if (pzLex!=NULL) { srprintf(ppLex,pzLex,24,"d+%f",3.14159265359); for (char* p=*ppLex;*p;p++) { if (*p==',') *p='.'; } TRACE(pfTrc,"CONSTANT-TOKEN(FLT)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_FLT); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"LCSTAMP",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%Y%m%d.%H%M%S",localtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"LCDATE",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%Y%m%d",localtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"LCYEAR",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%Y",localtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"LCYEAR2",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%y",localtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"LCMONTH",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%m",localtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"LCDAY",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%d",localtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"LCTIME",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%H%M%S",localtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"LCHOUR",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%H",localtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"LCMINUTE",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%M",localtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"LCSECOND",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%S",localtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"GMSTAMP",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%Y%m%d.%H%M%S",gmtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"GMDATE",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%Y%m%d",gmtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"GMYEAR",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%Y",gmtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"GMYEAR2",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%y",gmtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"GMMONTH",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%m",gmtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"GMDAY",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%d",gmtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"GMTIME",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%H%M%S",gmtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"GMHOUR",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%H",gmtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"GMMINUTE",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%M",gmtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"GMSECOND",0,0,FALSE)==0) { if (pzLex!=NULL) { struct tm st; time_t t=psHdl->siNow; strftime(*ppLex,*pzLex,"d'%S",gmtime_r(&t,&st)); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S1RND10",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%01u",((U32)psHdl->siRnd)%10); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S2RND10",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%02u",((U32)psHdl->siRnd)%100); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S3RND10",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%03u",((U32)psHdl->siRnd)%1000); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S4RND10",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%04u",((U32)psHdl->siRnd)%10000); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S5RND10",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%05u",((U32)psHdl->siRnd)%100000); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S6RND10",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%06u",((U32)psHdl->siRnd)%1000000); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S7RND10",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%07u",((U32)psHdl->siRnd)%10000000); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S8RND10",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%08u",((U32)psHdl->siRnd)%100000000); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S1RND16",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%01x",((U32)psHdl->siRnd)&0x0000000F); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S2RND16",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%02x",((U32)psHdl->siRnd)&0x000000FF); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S3RND16",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%03x",((U32)psHdl->siRnd)&0x00000FFF); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S4RND16",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%04x",((U32)psHdl->siRnd)&0x0000FFFF); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S5RND16",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%05x",((U32)psHdl->siRnd)&0x000FFFFF); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S6RND16",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%06x",((U32)psHdl->siRnd)&0x00FFFFFF); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S7RND16",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%07x",((U32)psHdl->siRnd)&0x0FFFFFFF); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else if ((siTyp==CLPTYP_STRING || siTyp==-1) && strxcmp(psHdl->isCas,pcKyw,"S8RND16",0,0,FALSE)==0) { if (pzLex!=NULL) { psHdl->siRnd=ClpRndFnv((psHdl->siRnd+1)^rand()); srprintf(ppLex,pzLex,10,"d'%08x",((U32)psHdl->siRnd)&0xFFFFFFFF); TRACE(pfTrc,"CONSTANT-TOKEN(STR)-LEXEME(%s)\n",*ppLex); } return(CLPTOK_STR); } else { return(CLPTOK_KYW); } } static inline int siClpNxtOpr( const char* pcCur) { while (1) { if (*pcCur==EOS) { /*end*/ return(0x00); } else if (isSeparation(*pcCur)) { /*separation*/ pcCur++; } else if (*pcCur==C_HSH) { /*comment*/ pcCur++; while (*pcCur!=C_HSH && *pcCur!=EOS) { pcCur++; } if (*pcCur!=C_HSH) { return(0x00); } pcCur++; } else if (*pcCur==';') { /*line comment*/ pcCur++; while (*pcCur!='\n' && *pcCur!=EOS) { pcCur++; } } else { return(*pcCur); } } } static inline int isClpKywTyp( void* pvHdl, FILE* pfErr, FILE* pfTrc, const char* pcKyw, const TsSym* psArg) { const TsSym* psVal=NULL; if (psArg->psDep!=NULL) { // selection psVal=psClpFndSym(pvHdl,pcKyw,psArg->psDep); } if (psVal==NULL && !CLPISF_SEL(psArg->psStd->uiFlg)) { psVal=psClpFndSym2(pvHdl,pcKyw,psArg); } if (psVal!=NULL && psVal->psFix->siTyp==psArg->psFix->siTyp) { return(TRUE); } return(CLPTOK_KYW!=siClpConNat(pvHdl,pfErr,pfTrc,pcKyw,NULL,NULL,psArg->psFix->siTyp,psArg)); } static inline int isClpKywVal( void* pvHdl, FILE* pfErr, FILE* pfTrc, const char* pcKyw, const TsSym* psArg, const TsSym** ppVal) { const TsSym* psVal=NULL; if (psArg!=NULL) { if (psArg->psDep!=NULL) { // selection psVal=psClpFndSym(pvHdl,pcKyw,psArg->psDep); } if (psVal==NULL && !CLPISF_SEL(psArg->psStd->uiFlg)) { psVal=psClpFndSym2(pvHdl,pcKyw,psArg); } } if (ppVal!=NULL) *ppVal=psVal; if (psVal!=NULL) return(TRUE); return(CLPTOK_KYW!=siClpConNat(pvHdl,pfErr,pfTrc,pcKyw,NULL,NULL,-1,psArg)); } static inline int isClpKywStr( void* pvHdl, FILE* pfErr, FILE* pfTrc, const char* pcKyw, const TsSym* psArg, const TsSym** ppVal, const char scOpr) { const TsSym* psVal=NULL; if (ppVal!=NULL) *ppVal=NULL; if (psArg!=NULL) { if (psArg->psDep!=NULL) { // selection psVal=psClpFndSym(pvHdl,pcKyw,psArg->psDep); } if (psVal==NULL && !CLPISF_SEL(psArg->psStd->uiFlg)) { psVal=psClpFndSym2(pvHdl,pcKyw,psArg); } } if (psVal!=NULL) { switch (scOpr) { case '(': // required string ends only if type is an object if (psVal->psFix->siTyp==CLPTYP_OBJECT) { if (ppVal!=NULL) *ppVal=psVal; return(TRUE); } break; case '.': // required string ends only if type is an overlay if (psVal->psFix->siTyp==CLPTYP_OVRLAY) { if (ppVal!=NULL) *ppVal=psVal; return(TRUE); } break; default: // at each other operator or separator the required string must end if (ppVal!=NULL) *ppVal=psVal; return(TRUE); } } return(CLPTOK_KYW!=siClpConNat(pvHdl,pfErr,pfTrc,pcKyw,NULL,NULL,CLPTYP_STRING,psArg)); } static inline int isClpKywAry( void* pvHdl, const int siTok, const char* pcKyw, const TsSym* psArg, const TsSym** ppVal) { TsHdl* psHdl=(TsHdl*)pvHdl; const TsSym* psVal=NULL; if (ppVal!=NULL) { if (*ppVal!=NULL) { int siOpr=siClpNxtOpr(psHdl->pcCur); if ((*ppVal)->psFix->siTyp==psArg->psFix->siTyp && siOpr!='=' && siOpr!='(' && siOpr!='.' && siOpr!=C_SBO) { return(TRUE); } else { return(FALSE); } } } if (psArg!=NULL) { if (psArg->psDep!=NULL) { // selection psVal=psClpFndSym(pvHdl,pcKyw,psArg->psDep); } if (psVal==NULL && !CLPISF_SEL(psArg->psStd->uiFlg)) { psVal=psClpFndSym2(pvHdl,pcKyw,psArg); } if (psVal!=NULL) { if (ppVal!=NULL) *ppVal=psVal; int siOpr=siClpNxtOpr(psHdl->pcCur); if (psVal->psFix->siTyp==psArg->psFix->siTyp && siOpr!='=' && siOpr!='(' && siOpr!='.' && siOpr!=C_SBO) { return(TRUE); } else { return(FALSE); } } return(siTok==siClpConNat(pvHdl,psHdl->pfErr,NULL,pcKyw,NULL,NULL,psArg->psFix->siTyp,psArg)); } return(FALSE); } static char* pcClpUnEscape( void* pvHdl, const char* pcInp) { char* pcOut=(char*)pvClpAlloc(pvHdl,NULL,strlen(pcInp)+1,NULL); if (pcOut==NULL) return(pcOut); return(unEscape(pcInp,pcOut)); } static int siClpScnNat( void* pvHdl, FILE* pfErr, FILE* pfTrc, const char** ppCur, size_t* pzLex, char** ppLex, int siTyp, const TsSym* psArg, int* piSep, const TsSym** ppVal) { TsHdl* psHdl=(TsHdl*)pvHdl; char* pcLex=(*ppLex); char* pcHlp=(*ppLex); char* pcEnd=(*ppLex)+(*pzLex); const char* pcCur=(*ppCur); int isEnv=psHdl->isEnv; const char* pcEnv=NULL; const char* pcOld=NULL; char* pcZro=NULL; time_t t; struct tm tm; struct tm stAkt; struct tm *tmAkt; char acHlp[1024]; int siRbc=0; int siSbc=0; int siCbc=0; if (siTyp!=CLPTYP_NUMBER && siTyp!=CLPTYP_FLOATN && siTyp!=CLPTYP_STRING) siTyp=0; if (piSep!=NULL) *piSep=FALSE; if (ppVal!=NULL) *ppVal=NULL; while (1) { if (*(*ppCur)==EOS) { /*end*/ pcLex[0]=EOS; TRACE(pfTrc,"SCANNER-TOKEN(END)-LEXEME(%s)\n",isPrnLex(psArg,pcHlp)); return(CLPTOK_END); } else if (isSeparation(*(*ppCur))) { /*separation*/ if (piSep!=NULL) *piSep=*(*ppCur); if (*(*ppCur)=='\n') { psHdl->siRow++; psHdl->pcRow=(*ppCur)+1; } (*ppCur)++; psHdl->pcOld=(*ppCur); } else if (*(*ppCur)==C_HSH) { /*comment*/ (*ppCur)++; while (*(*ppCur)!=C_HSH && *(*ppCur)!=EOS) { if (*(*ppCur)=='\n') { psHdl->siRow++; psHdl->pcRow=(*ppCur)+1; } (*ppCur)++; } if (*(*ppCur)!=C_HSH) { return CLPERR(psHdl,CLPERR_LEX,"Comment not terminated with '%c'",C_HSH); } (*ppCur)++; psHdl->pcOld=(*ppCur); } else if (*(*ppCur)==';') { /*line comment*/ (*ppCur)++; while (*(*ppCur)!='\n' && *(*ppCur)!=EOS) (*ppCur)++; if (*(*ppCur)=='\n') { (*ppCur)++; psHdl->siRow++; psHdl->pcRow=(*ppCur); } psHdl->pcOld=(*ppCur); } else if (isEnv && *(*ppCur)=='<') { /*environment variable replacement*/ (*ppCur)++; while ((*ppCur)[0]!=EOS && (*ppCur)[0]!='>') { LEX_REALLOC *pcLex=*(*ppCur); pcLex++; (*ppCur)++; } *pcLex=EOS; if (*(*ppCur)!='>') { return CLPERR(psHdl,CLPERR_LEX,"Environment variable not terminated with '>'"); } (*ppCur)++; pcLex=(*ppLex); pcEnv=getenvar(pcLex,0,sizeof(acHlp),acHlp); if (pcEnv!=NULL) { size_t l=pcCur-psHdl->pcInp; if (psHdl->siBuf>=CLPMAX_BUFCNT) { return CLPERR(psHdl,CLPERR_LEX,"Environment variable replacement (%s=%s) not possible (more than %d replacements)",pcLex,pcEnv,CLPMAX_BUFCNT); } srprintf(&psHdl->apBuf[psHdl->siBuf],&psHdl->pzBuf[psHdl->siBuf],l+strlen(pcEnv)+strlen((*ppCur)),"%.*s%s%s",(int)l,psHdl->pcInp,pcEnv,(*ppCur)); TRACE(pfTrc,"SCANNER-ENVARREP\n%s %s\n%s %s\n",fpcPre(psHdl,0),psHdl->pcInp,fpcPre(psHdl,0),psHdl->apBuf[psHdl->siBuf]); (*ppCur)=psHdl->apBuf[psHdl->siBuf]+l; psHdl->pcInp=psHdl->apBuf[psHdl->siBuf]; psHdl->pcOld=psHdl->apBuf[psHdl->siBuf]+(psHdl->pcOld-psHdl->pcInp); psHdl->pcRow=psHdl->apBuf[psHdl->siBuf]+(psHdl->pcRow-psHdl->pcInp); psHdl->siBuf++; isEnv=TRUE; } else { isEnv=FALSE; (*ppCur)=pcCur; } } else if (isStringChr((*ppCur)[0])) {/*simple string*/ char USECHR=(*ppCur)[0]; *pcLex= 'd'; pcLex++; *pcLex='\''; pcLex++; (*ppCur)++; while ((*ppCur)[0]!=EOS && ((*ppCur)[0]!=USECHR || (*ppCur)[1]==USECHR)) { LEX_REALLOC *pcLex=*(*ppCur); pcLex++; if (*(*ppCur)=='\n') { (*ppCur)++; psHdl->siRow++; psHdl->pcRow=(*ppCur); } else if ((*ppCur)[0]==USECHR) { (*ppCur)+=2; } else { (*ppCur)++; } } *pcLex=EOS; if (*(*ppCur)!=USECHR) { return CLPERR(psHdl,CLPERR_LEX,"String literal not terminated with '%c'",USECHR); } (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(STR)-LEXEME(%s)-SIMPLE\n",isPrnLex(psArg,pcHlp)); return(CLPTOK_STR); } else if ((tolower((*ppCur)[0])=='x' || tolower((*ppCur)[0])=='a' || tolower((*ppCur)[0])=='e' || tolower((*ppCur)[0])=='c' || tolower((*ppCur)[0])=='s' || tolower((*ppCur)[0])=='f') && isStringChr((*ppCur)[1])) {/*defined string '...'*/ char USECHR=(*ppCur)[1]; *pcLex=tolower(*(*ppCur)); pcLex++; *pcLex='\''; pcLex++; (*ppCur)+=2; while ((*ppCur)[0]!=EOS && ((*ppCur)[0]!=USECHR || (*ppCur)[1]==USECHR)) { LEX_REALLOC *pcLex=*(*ppCur); pcLex++; if (*(*ppCur)=='\n') { (*ppCur)++; psHdl->siRow++; psHdl->pcRow=(*ppCur); } else if ((*ppCur)[0]==USECHR) { (*ppCur)+=2; } else { (*ppCur)++; } } *pcLex=EOS; if (*(*ppCur)!=USECHR) { return CLPERR(psHdl,CLPERR_LEX,"String literal not terminated with '%c'",USECHR); } (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(STR)-LEXEME(%s)-DEFINED\n",isPrnLex(psArg,pcHlp)); return(CLPTOK_STR); } else if (((*ppCur)[0]=='-' && isalpha((*ppCur)[1])) || ((*ppCur)[0]=='-' && (*ppCur)[1]=='-' && isalpha((*ppCur)[2]))) { /*defined keyword*/ while ((*ppCur)[0]=='-') { (*ppCur)++; } *pcLex=*(*ppCur); (*ppCur)++; pcLex++; while (isCon(*(*ppCur))) { LEX_REALLOC if (!isKyw(*(*ppCur)) && pcOld==NULL) { pcOld=(*ppCur); pcZro=pcLex; } *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } *pcLex=EOS; if(pcCur[0]=='-' && pcCur[1]!='-' && psArg!=NULL && psArg->psFix->siTyp==siTyp && isClpKywTyp(pvHdl,pfErr,pfTrc,pcHlp,psArg)) { (*ppCur)=pcCur+1; pcLex[0]='-'; pcLex[1]=EOS; TRACE(pfTrc,"SCANNER-TOKEN(SUB)-LEXEME(%s)-NOKYW\n",pcHlp); return(CLPTOK_SUB); } else { if (pcOld!=NULL && !isClpKywVal(pvHdl,pfErr,pfTrc,pcHlp,psArg,ppVal)) { *pcZro=0x00; *ppCur=pcOld; } TRACE(pfTrc,"SCANNER-TOKEN(KYW)-LEXEME(%s)-DEFINED\n",pcHlp); return(CLPTOK_KYW); } } else if (siTyp==CLPTYP_STRING && isStr((*ppCur)[0]) && !isReqStrOpr1((*ppCur)[0])) {/*required string*/ if ((*ppCur)[0]=='(') { siRbc++; } else if ((*ppCur)[0]==C_SBO) { siSbc++; } else if ((*ppCur)[0]==C_CBO) { siCbc++; } else if ((*ppCur)[0]==')') { siRbc--; } else if ((*ppCur)[0]==C_SBC) { siSbc--; } else if ((*ppCur)[0]==C_CBC) { siCbc--; } *pcLex='d'; pcLex++; *pcLex='\''; pcLex++; if (psArg!=NULL && isalpha(*(*ppCur))) { *pcLex=*(*ppCur); (*ppCur)++; pcLex++; while (isCon(*(*ppCur))) { LEX_REALLOC *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } *pcLex=EOS; if (isReqStrOpr3(*(*ppCur)) || isSeparation(*(*ppCur))) { if (isClpKywStr(pvHdl,pfErr,pfTrc,(*ppLex)+2,psArg,ppVal,*(*ppCur))) { char* p1=pcHlp; char* p2=(*ppLex)+2; while (*p2) { *p1++=*p2++; } *p1=EOS; TRACE(pfTrc,"SCANNER-TOKEN(KYW)-LEXEME(%s)-REQSTR\n",pcHlp); return(CLPTOK_KYW); } } } while ((*ppCur)[0]!=EOS && isStr((*ppCur)[0]) && !isSeparation((*ppCur)[0]) && !isReqStrOpr2((*ppCur)[0]) && (siRbc>0 || (*ppCur)[0]!=')') && (siSbc>0 || (*ppCur)[0]!=C_SBC) && (siCbc>0 || (*ppCur)[0]!=C_CBC)) { if ((*ppCur)[0]=='(') { siRbc++; } else if ((*ppCur)[0]==C_SBO) { siSbc++; } else if ((*ppCur)[0]==C_CBO) { siCbc++; } else if ((*ppCur)[0]==')') { siRbc--; } else if ((*ppCur)[0]==C_SBC) { siSbc--; } else if ((*ppCur)[0]==C_CBC) { siCbc--; } LEX_REALLOC *pcLex=*(*ppCur); pcLex++; (*ppCur)++; } *pcLex=EOS; TRACE(pfTrc,"SCANNER-TOKEN(STR)-LEXEME(%s)-REQUIRED\n",isPrnLex(psArg,pcHlp)); return(CLPTOK_STR); } else if (isalpha((*ppCur)[0])) { /*simple keyword*/ *pcLex=*(*ppCur); (*ppCur)++; pcLex++; while (isCon(*(*ppCur))) { LEX_REALLOC if (!isKyw(*(*ppCur)) && pcOld==NULL) { pcOld=(*ppCur); pcZro=pcLex; } *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } *pcLex=EOS; if (pcOld!=NULL && !isClpKywVal(pvHdl,pfErr,pfTrc,pcHlp,psArg,ppVal)) { *pcZro=0x00; *ppCur=pcOld; } TRACE(pfTrc,"SCANNER-TOKEN(KYW)-LEXEME(%s)-SIMPLE\n",pcHlp); return(CLPTOK_KYW); } else if ((((*ppCur)[0]=='+' || (*ppCur)[0]=='-') && isdigit((*ppCur)[1])) || isdigit((*ppCur)[0])) { /*number*/ if ((*ppCur)[0]=='+' || (*ppCur)[0]=='-') { pcLex[1]=(*ppCur)[0]; (*ppCur)++; } else pcLex[1]=' '; if (((*ppCur)[0]=='0') && (tolower((*ppCur)[1])=='b' || tolower((*ppCur)[1])=='o' || tolower((*ppCur)[1])=='d' || tolower((*ppCur)[1])=='x' || tolower((*ppCur)[1])=='t') && (isdigit((*ppCur)[2]) || (isxdigit((*ppCur)[2]) && tolower((*ppCur)[1])=='x'))) { pcLex[0]=tolower((*ppCur)[1]); (*ppCur)+=2; } else pcLex[0]='d'; pcLex+=2; if (pcHlp[0]=='x') { while (isxdigit(*(*ppCur))) { LEX_REALLOC *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } } else if (pcHlp[0]=='t') { memset(&tm,0,sizeof(tm)); while (isdigit(*(*ppCur))) { LEX_REALLOC *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } *pcLex=EOS; tm.tm_mon=0; tm.tm_mday=0; tm.tm_hour=0; tm.tm_min=0; tm.tm_sec=0; tm.tm_year=strtol(pcHlp+2,NULL,10); if ((*ppCur)[0]=='/' && isdigit((*ppCur)[1])) { pcLex=pcHlp+2; (*ppCur)++; while (isdigit(*(*ppCur))) { LEX_REALLOC *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } *pcLex=EOS; tm.tm_mon=strtol(pcHlp+2,NULL,10); if ((*ppCur)[0]=='/' && isdigit((*ppCur)[1])) { pcLex=pcHlp+2; (*ppCur)++; while (isdigit(*(*ppCur))) { LEX_REALLOC *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } *pcLex=EOS; tm.tm_mday=strtol(pcHlp+2,NULL,10); if ((*ppCur)[0]=='.' && isdigit((*ppCur)[1])) { pcLex=pcHlp+2; (*ppCur)++; while (isdigit(*(*ppCur))) { LEX_REALLOC *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } *pcLex=EOS; tm.tm_hour=strtol(pcHlp+2,NULL,10); if ((*ppCur)[0]==':' && isdigit((*ppCur)[1])) { pcLex=pcHlp+2; (*ppCur)++; while (isdigit(*(*ppCur))) { LEX_REALLOC *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } *pcLex=EOS; tm.tm_min=strtol(pcHlp+2,NULL,10); if ((*ppCur)[0]==':' && isdigit((*ppCur)[1])) { pcLex=pcHlp+2; (*ppCur)++; while (isdigit(*(*ppCur))) { LEX_REALLOC *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } *pcLex=EOS; tm.tm_sec=strtol(pcHlp+2,NULL,10); } } } } } if (pcHlp[1]=='+') { t=time(NULL); if (t==-1) { return CLPERR(psHdl,CLPERR_SYS,"Determine the current time is not possible%s",""); } tmAkt=localtime_r(&t,&stAkt); tmAkt->tm_year +=tm.tm_year; tmAkt->tm_mon +=tm.tm_mon; tmAkt->tm_mday +=tm.tm_mday; tmAkt->tm_hour +=tm.tm_hour; tmAkt->tm_min +=tm.tm_min; tmAkt->tm_sec +=tm.tm_sec; t=mktime(tmAkt); if (t==-1) { return CLPERR(psHdl,CLPERR_LEX,"The calculated time value (0t%4.4d/%2.2d/%2.2d.%2.2d:%2.2d:%2.2d) cannot be converted to a number", tmAkt->tm_year+1900,tmAkt->tm_mon+1,tmAkt->tm_mday,tmAkt->tm_hour,tmAkt->tm_min,tmAkt->tm_sec); } } else if (pcHlp[1]=='-') { t=time(NULL); if (t==-1) { return CLPERR(psHdl,CLPERR_SYS,"Determine the current time is not possible%s",""); } tmAkt=localtime_r(&t,&stAkt); tmAkt->tm_year -=tm.tm_year; tmAkt->tm_mon -=tm.tm_mon; tmAkt->tm_mday -=tm.tm_mday; tmAkt->tm_hour -=tm.tm_hour; tmAkt->tm_min -=tm.tm_min; tmAkt->tm_sec -=tm.tm_sec; t=mktime(tmAkt); if (t==-1) { return CLPERR(psHdl,CLPERR_LEX,"The calculated time value (0t%4.4d/%2.2d/%2.2d.%2.2d:%2.2d:%2.2d) cannot be converted to a number", tmAkt->tm_year+1900,tmAkt->tm_mon+1,tmAkt->tm_mday,tmAkt->tm_hour,tmAkt->tm_min,tmAkt->tm_sec); } } else { if (tm.tm_year>=1900) tm.tm_year-=1900; if (tm.tm_mon >= 1) tm.tm_mon -=1; if (tm.tm_mday== 0) tm.tm_mday++; t=mktime(&tm); if (t==-1) { return CLPERR(psHdl,CLPERR_LEX,"The given time value (0t%4.4d/%2.2d/%2.2d.%2.2d:%2.2d:%2.2d) cannot be converted to a number", tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec); } if (tm.tm_isdst>0) t-=60*60;//correct daylight saving time } pcHlp[1]='+'; sprintf(pcHlp+2,"%"PRIu64"",(U64)t); TRACE(pfTrc,"SCANNER-TOKEN(NUM)-LEXEME(%s)-TIME\n",isPrnLex(psArg,pcHlp)); if (psArg!=NULL) psArg->psStd->uiFlg|=CLPFLG_TIM; return(CLPTOK_NUM); } else { while (isdigit(*(*ppCur))) { LEX_REALLOC *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } } if (pcHlp[0]=='d' && (*ppCur)[0]=='.' && (isdigit((*ppCur)[1]))) { /*float*/ *pcLex=*(*ppCur); (*ppCur)++; pcLex++; while (isdigit(*(*ppCur))) { LEX_REALLOC *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } if ((tolower((*ppCur)[0])=='e') && (isdigit((*ppCur)[1]) || ((*ppCur)[1]=='+' && isdigit((*ppCur)[2])) || ((*ppCur)[1]=='-' && isdigit((*ppCur)[2])))) { /*float*/ *pcLex=*(*ppCur); (*ppCur)++; pcLex++; if (!isdigit((*ppCur)[0])) { *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } while (isdigit(*(*ppCur))) { LEX_REALLOC *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } *pcLex=EOS; if (pcHlp[1]==' ') pcHlp[1]='+'; TRACE(pfTrc,"SCANNER-TOKEN(FLT)-LEXEME(%s)\n",isPrnLex(psArg,pcHlp)); return(CLPTOK_FLT); } *pcLex=EOS; if (pcHlp[1]==' ') pcHlp[1]='+'; TRACE(pfTrc,"SCANNER-TOKEN(FLT)-LEXEME(%s)\n",isPrnLex(psArg,pcHlp)); return(CLPTOK_FLT); } else if ((tolower((*ppCur)[0])=='e') && (isdigit((*ppCur)[1]) || ((*ppCur)[1]=='+' && isdigit((*ppCur)[2])) || ((*ppCur)[1]=='-' && isdigit((*ppCur)[2])))) { /*float*/ *pcLex=*(*ppCur); (*ppCur)++; pcLex++; if (!isdigit((*ppCur)[0])) { *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } while (isdigit(*(*ppCur))) { LEX_REALLOC *pcLex=*(*ppCur); (*ppCur)++; pcLex++; } *pcLex=EOS; if (pcHlp[1]==' ') pcHlp[1]='+'; TRACE(pfTrc,"SCANNER-TOKEN(FLT)-LEXEME(%s)\n",isPrnLex(psArg,pcHlp)); return(CLPTOK_FLT); } else { *pcLex=EOS; if (pcHlp[1]==' ') pcHlp[1]='+'; TRACE(pfTrc,"SCANNER-TOKEN(NUM)-LEXEME(%s)\n",isPrnLex(psArg,pcHlp)); return((siTyp==CLPTOK_FLT)?CLPTOK_FLT:CLPTOK_NUM); } } else if (*(*ppCur)=='=') { /*sign or sign with agle breckets*/ if ((*ppCur)[1]=='>') { pcLex[0]='='; pcLex[1]='>'; pcLex[2]=EOS; (*ppCur)+=2; TRACE(pfTrc,"SCANNER-TOKEN(SAB)-LEXEME(%s)\n",pcHlp); return(CLPTOK_SAB); } else { pcLex[0]='='; pcLex[1]=EOS; (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(SGN)-LEXEME(%s)\n",pcHlp); return(CLPTOK_SGN); } } else if (*(*ppCur)=='.') { /*dot*/ pcLex[0]='.'; pcLex[1]=EOS; (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(DOT)-LEXEME(%s)\n",pcHlp); return(CLPTOK_DOT); } else if (*(*ppCur)=='+') { /*add*/ pcLex[0]='+'; pcLex[1]=EOS; (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(ADD)-LEXEME(%s)\n",pcHlp); return(CLPTOK_ADD); } else if (*(*ppCur)=='-') { /*sub*/ pcLex[0]='-'; pcLex[1]=EOS; (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(SUB)-LEXEME(%s)\n",pcHlp); return(CLPTOK_SUB); } else if (*(*ppCur)=='*') { /*mul*/ pcLex[0]='*'; pcLex[1]=EOS; (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(MUL)-LEXEME(%s)\n",pcHlp); return(CLPTOK_MUL); } else if (*(*ppCur)=='/') { /*div*/ pcLex[0]='/'; pcLex[1]=EOS; (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(DIV)-LEXEME(%s)\n",pcHlp); return(CLPTOK_DIV); } else if (*(*ppCur)=='(') { /*round bracket open*/ pcLex[0]='('; pcLex[1]=EOS; (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(RBO)-LEXEME(%s)\n",pcHlp); return(CLPTOK_RBO); } else if (*(*ppCur)==')') { /*round bracket close*/ pcLex[0]=')'; pcLex[1]=EOS; (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(RBC)-LEXEME(%s)\n",pcHlp); return(CLPTOK_RBC); } else if (*(*ppCur)==C_SBO) { /*squared bracket open*/ pcLex[0]=C_SBO; pcLex[1]=EOS; (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(SBO)-LEXEME(%s)\n",pcHlp); return(CLPTOK_SBO); } else if (*(*ppCur)==C_SBC) { /*squared bracket close*/ pcLex[0]=C_SBC; pcLex[1]=EOS; (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(SBC)-LEXEME(%s)\n",pcHlp); return(CLPTOK_SBC); } else if (*(*ppCur)==C_CBO) { /*curly bracket open*/ pcLex[0]=C_CBO; pcLex[1]=EOS; (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(CBO)-LEXEME(%s)\n",pcHlp); return(CLPTOK_CBO); } else if (*(*ppCur)==C_CBC) { /*curly bracket close*/ pcLex[0]=C_CBC; pcLex[1]=EOS; (*ppCur)++; TRACE(pfTrc,"SCANNER-TOKEN(CBC)-LEXEME(%s)\n",pcHlp); return(CLPTOK_CBC); } else { /*lexical error*/ pcLex[0]=EOS; (*ppCur)++; return CLPERR(psHdl,CLPERR_LEX,"Character ('%c') not valid",*((*ppCur)-1)); } } } static int siClpConSrc( void* pvHdl, const int isChk, const TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; return(siClpConNat(pvHdl,psHdl->pfErr,psHdl->pfScn,psHdl->pcLex,(isChk)?NULL:&psHdl->szLex,(isChk)?NULL:&psHdl->pcLex,(psArg!=NULL)?psArg->psFix->siTyp:0,psArg)); } static int siClpScnSrc( void* pvHdl, int siTyp, const TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; psHdl->pcOld=psHdl->pcCur; return(siClpScnNat(pvHdl,psHdl->pfErr,psHdl->pfScn,&psHdl->pcCur,&psHdl->szLex,&psHdl->pcLex,siTyp,psArg,&psHdl->isSep,&psHdl->psVal)); } /**********************************************************************/ extern int siClpGrammar( void* pvHdl, FILE* pfOut) { if (pfOut!=NULL) { TsHdl* psHdl=(TsHdl*)pvHdl; fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," Command Line Parser \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," command -> ['('] parameter_list [')'] (main=object) \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | ['.'] parameter (main=overlay)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," parameter_list -> parameter SEP parameter_list \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | EMPTY \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," parameter -> switch | assignment | object | overlay | array \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," switch -> KEYWORD \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," assignment -> KEYWORD '=' value \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD '=' KEYWORD # SELECTION # \n"); if (psHdl->isPfl) { fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD '=>' STRING # parameter file # \n"); } fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," object -> KEYWORD ['('] parameter_list [')'] \n"); if (psHdl->isPfl) { fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD '=' STRING # parameter file # \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD '=>' STRING # parameter file # \n"); } fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," overlay -> KEYWORD ['.'] parameter \n"); if (psHdl->isPfl) { fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD '=' STRING # parameter file # \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD '=>' STRING # parameter file # \n"); } fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," array -> KEYWORD '[' value_list ']' \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD '[' object_list ']' \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD '[' overlay_list ']' \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD '=' value_list # with certain limitations #\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," It is recommended to use only enclosed array lists to know the end\n"); if (psHdl->isPfl) { fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD '[=' STRING ']' # parameter file # \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD '[=>' STRING ']' # parameter file # \n"); } fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," value_list -> value SEP value_list \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | EMPTY \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," object_list -> object SEP object_list \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | EMPTY \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," overlay_list -> overlay SEP overlay_list \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | EMPTY \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," A list of objects requires parenthesis to enclose the arguments \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," value -> term '+' value \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | term '-' value \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | term \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," term -> factor '*' term \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | factor '/' term \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | factor \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," factor -> NUMBER | FLOAT | STRING \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | selection | variable | constant \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | '(' value ')' \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," selection -> KEYWORD # value from a selection table #\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," variable -> KEYWORD # value from a previous assignment #\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD '{' NUMBER '}' # with index for arrays#\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," constant -> KEYWORD # see predefined constants at lexeme #\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," For strings only the operator '+' is implemented as concatenation\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," Strings without an operator in between are also concatenated \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," A number followed by a constant is a multiplication (4KiB=4*1024)\n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," Property File Parser \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," properties -> property_list \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," property_list -> property SEP property_list \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | EMPTY \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," property -> keyword_list '=' SUPPLEMENT \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," keyword_list -> KEYWORD '.' keyword_list \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," | KEYWORD \n"); fprintf(pfOut,"%s",fpcPre(pvHdl,0)); efprintf(pfOut," SUPPLEMENT is a string in double quotation marks (\"property\") \n"); } return(CLP_OK); } static int siClpPrsParLst( void* pvHdl, const int siLev, const TsSym* psTab) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr,siPos=0; while (psHdl->siTok==CLPTOK_KYW) { siErr=siClpPrsPar(pvHdl,siLev,siPos,psTab,NULL); if (siErr<0) return(siErr); siPos++; } return(siPos); } static int siClpPrsPar( void* pvHdl, const int siLev, const int siPos, const TsSym* psTab, int* piOid) { TsHdl* psHdl=(TsHdl*)pvHdl; char acKyw[CLPMAX_KYWSIZ]; TsSym* psArg=NULL; int siErr; if (psHdl->siTok==CLPTOK_KYW) { strlcpy(acKyw,psHdl->pcLex,sizeof(acKyw)); siErr=siClpSymFnd(pvHdl,siLev,acKyw,psTab,&psArg,NULL); if (siErr<0) return(siErr); siErr=siClpBldLnk(pvHdl,siLev,siPos,psHdl->pcOld-psHdl->pcInp,psArg->psFix->psInd,TRUE); if (siErr<0) return(siErr); if (piOid!=NULL) *piOid=psArg->psFix->siOid; psHdl->siTok=siClpScnSrc(pvHdl,0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); if (psHdl->siTok==CLPTOK_SGN) { if (psArg->psFix->siTyp==CLPTYP_OBJECT || psArg->psFix->siTyp==CLPTYP_OVRLAY) { if (psHdl->isPfl) { if (psHdl->isPfl==2) { return(siClpAcpFil(pvHdl,siLev,siPos,FALSE,psArg)); } else { return(siClpPrsFil(pvHdl,siLev,siPos,FALSE,psArg)); } } else { CLPERR(psHdl,CLPERR_SEM,"Parameter files not allowed (%s.?)",fpcPat(pvHdl,siLev)); return(CLPERR_SEM); } } else { return(siClpPrsSgn(pvHdl,siLev,siPos,psArg)); } } else if (psHdl->siTok==CLPTOK_SAB) { if (psHdl->isPfl) { if (psHdl->isPfl==2) { return(siClpAcpFil(pvHdl,siLev,siPos,FALSE,psArg)); } else { return(siClpPrsFil(pvHdl,siLev,siPos,FALSE,psArg)); } } else { CLPERR(psHdl,CLPERR_SEM,"Parameter files not allowed (%s.?)",fpcPat(pvHdl,siLev)); return(CLPERR_SEM); } } else if (psHdl->siTok==CLPTOK_RBO) { return(siClpPrsObj(pvHdl,siLev,siPos,psArg)); } else if (psHdl->siTok==CLPTOK_DOT) { psHdl->siTok=siClpScnSrc(pvHdl,0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); return(siClpPrsOvl(pvHdl,siLev,siPos,psArg)); } else if (psHdl->siTok==CLPTOK_SBO) { return(siClpPrsAry(pvHdl,siLev,siPos,psArg)); } else { if (psArg->psFix->siTyp==CLPTYP_OBJECT) { return(siClpPrsObjWob(pvHdl,siLev,siPos,psArg)); } else if (psArg->psFix->siTyp==CLPTYP_OVRLAY) { return(siClpPrsOvl(pvHdl,siLev,siPos,psArg)); } else if (psArg->psFix->siTyp==CLPTYP_NUMBER && CLPISF_DEF(psArg->psStd->uiFlg)) { return(siClpPrsNum(pvHdl,siLev,siPos,psArg)); } else { return(siClpPrsSwt(pvHdl,siLev,siPos,psArg)); } } } else { CLPERR(psHdl,CLPERR_SYN,"Keyword expected (%s.?)",fpcPat(pvHdl,siLev)); CLPERRADD(psHdl,0,"Please use one of the following arguments:%s",""); vdClpPrnArgTab(pvHdl,psHdl->pfErr,1,-1,psTab); return(CLPERR_SYN); } } static int siClpPrsNum( void* pvHdl, const int siLev, const int siPos, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d NUM(%s) USING OID AS DEFAULT VALUE)\n",fpcPre(pvHdl,siLev),siLev,siPos,psArg->psStd->pcKyw); return(siClpBldNum(pvHdl,siLev,siPos,psArg)); } static int siClpPrsSwt( void* pvHdl, const int siLev, const int siPos, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d SWT(%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,psArg->psStd->pcKyw); return(siClpBldSwt(pvHdl,siLev,siPos,psArg)); } static int siClpPrsSgn( void* pvHdl, const int siLev, const int siPos, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d SGN(%s=val)\n",fpcPre(pvHdl,siLev),siLev,siPos,psArg->psStd->pcKyw); psHdl->siTok=siClpScnSrc(pvHdl,psArg->psFix->siTyp,psArg); if (psHdl->siTok<0) return(psHdl->siTok); if (psArg->psFix->siMax>1) { // ARRAY switch (psArg->psFix->siTyp) { case CLPTYP_NUMBER: return(siClpPrsValLstOnlyArg(pvHdl,siLev,FALSE,CLPTOK_NUM,psArg)); case CLPTYP_FLOATN: return(siClpPrsValLstOnlyArg(pvHdl,siLev,FALSE,CLPTOK_FLT,psArg)); case CLPTYP_STRING: return(siClpPrsValLstOnlyArg(pvHdl,siLev,FALSE,CLPTOK_STR,psArg)); default: return CLPERR(psHdl,CLPERR_SEM,"Type (%d) of parameter '%s.%s' is not supported with arrays",psArg->psFix->siTyp,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } } else { return(siClpPrsVal(pvHdl,siLev,siPos,FALSE,psArg)); } } static int siClpAcpFil( void* pvHdl, const int siLev, const int siPos, const int isAry, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; const char* pcPat=fpcPat(pvHdl,siLev); (void)isAry; TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d PARFIL(%s=val)\n",fpcPre(pvHdl,siLev),siLev,siPos,psArg->psStd->pcKyw); psHdl->siTok=siClpScnSrc(pvHdl,CLPTYP_STRING,psArg); if (psHdl->siTok<0) return(psHdl->siTok); if (psHdl->siTok!=CLPTOK_STR) { return CLPERR(psHdl,CLPERR_SYN,"After object/overlay/array assignment '%s.%s=' parameter file ('filename') expected",pcPat,psArg->psStd->pcKyw); } srprintc(&psHdl->pcLst,&psHdl->szLst,strlen(pcPat)+strlen(GETKYW(psArg))+strlen(isPrnLex2(psArg,psHdl->pcLex)),"%s.%s=%s\n",pcPat,GETKYW(psArg),isPrnLex2(psArg,psHdl->pcLex)); psHdl->siTok=siClpScnSrc(pvHdl,0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); return(CLP_OK); } static int siClpPrsFil( void* pvHdl, const int siLev, const int siPos, const int isAry, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; char acSrc[strlen(psHdl->pcSrc)+1]; char* pcPar=NULL; int siRow,siCnt,siErr,siSiz=0; const char* pcCur; const char* pcInp; const char* pcOld; const char* pcRow; char acMsg[1024]=""; TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d PARFIL(%s=val)\n",fpcPre(pvHdl,siLev),siLev,siPos,psArg->psStd->pcKyw); psHdl->siTok=siClpScnSrc(pvHdl,CLPTYP_STRING,psArg); if (psHdl->siTok<0) return(psHdl->siTok); if (psHdl->siTok!=CLPTOK_STR) { return CLPERR(psHdl,CLPERR_SYN,"After object/overlay/array assignment '%s.%s=' parameter file ('filename') expected",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } char acFil[strlen(psHdl->pcLex)]; strcpy(acFil,psHdl->pcLex+2); siErr=psHdl->pfF2s(psHdl->pvGbl,psHdl->pvF2s,acFil,&pcPar,&siSiz,acMsg,sizeof(acMsg)); if (siErr<0) { siErr=CLPERR(psHdl,CLPERR_SYS,"Parameter file: %s",acMsg); SAFE_FREE(pcPar); return(siErr); } TRACE(psHdl->pfPrs,"PARAMETER-FILE-PARSER-BEGIN(FILE=%s)\n",acFil); strcpy(acSrc,psHdl->pcSrc); srprintf(&psHdl->pcSrc,&psHdl->szSrc,strlen(CLPSRC_PAF)+strlen(acFil),"%s%s",CLPSRC_PAF,acFil); pcInp=psHdl->pcInp; psHdl->pcInp=pcClpUnEscape(pvHdl,pcPar); SAFE_FREE(pcPar); if (psHdl->pcInp==NULL) { siErr=CLPERR(psHdl,CLPERR_MEM,"Un-escaping of parameter file (%s) failed",acFil); return(siErr); } pcCur=psHdl->pcCur; psHdl->pcCur=psHdl->pcInp; pcOld=psHdl->pcOld; psHdl->pcOld=psHdl->pcInp; pcRow=psHdl->pcRow; psHdl->pcRow=psHdl->pcInp; siRow=psHdl->siRow; psHdl->siRow=1; psHdl->siBuf++; psHdl->siTok=siClpScnSrc(pvHdl,psArg->psFix->siTyp,psArg); if (psHdl->siTok<0) return(psHdl->siTok); if (isAry) { switch (psArg->psFix->siTyp) { case CLPTYP_NUMBER: siCnt=siClpPrsValLstFlexible(pvHdl,siLev,CLPTOK_NUM,psArg); break; case CLPTYP_FLOATN: siCnt=siClpPrsValLstFlexible(pvHdl,siLev,CLPTOK_FLT,psArg); break; case CLPTYP_STRING: siCnt=siClpPrsValLstFlexible(pvHdl,siLev,CLPTOK_STR,psArg); break; case CLPTYP_OBJECT: siCnt=siClpPrsObjLst(pvHdl,siLev,psArg); break; case CLPTYP_OVRLAY: siCnt=siClpPrsOvlLst(pvHdl,siLev,psArg); break; default: return CLPERR(psHdl,CLPERR_SEM,"Type (%d) of parameter '%s.%s' is not supported with arrays",psArg->psFix->siTyp,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } if (siCnt<0) return(siCnt); psHdl->siTok=siClpScnSrc(pvHdl,0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); } else { if (psHdl->siTok==CLPTOK_RBO) { siCnt=siClpPrsObj(pvHdl,siLev,siPos,psArg); if (siCnt<0) return(siCnt); } else if (psHdl->siTok==CLPTOK_DOT) { psHdl->siTok=siClpScnSrc(pvHdl,0,psArg); if (psHdl->siTok<0) { return(psHdl->siTok); } siCnt=siClpPrsOvl(pvHdl,siLev,siPos,psArg); if (siCnt<0) return(siCnt); } else { if (psArg->psFix->siTyp==CLPTYP_OBJECT) { siCnt=siClpPrsObjWob(pvHdl,siLev,siPos,psArg); if (siCnt<0) return(siCnt); } else if(psArg->psFix->siTyp==CLPTYP_OVRLAY) { siCnt=siClpPrsOvl(pvHdl,siLev,siPos,psArg); if (siCnt<0) return(siCnt); } else { if (psArg->psFix->siMax>1) { // ARRAY switch (psArg->psFix->siTyp) { case CLPTYP_NUMBER: siCnt=siClpPrsValLstOnlyArg(pvHdl,siLev,TRUE,CLPTOK_NUM,psArg); break; case CLPTYP_FLOATN: siCnt=siClpPrsValLstOnlyArg(pvHdl,siLev,TRUE,CLPTOK_FLT,psArg); break; case CLPTYP_STRING: siCnt=siClpPrsValLstOnlyArg(pvHdl,siLev,TRUE,CLPTOK_STR,psArg); break; default: return CLPERR(psHdl,CLPERR_SEM,"Type (%d) of parameter '%s.%s' is not supported with arrays",psArg->psFix->siTyp,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } } else { siCnt=siClpPrsVal(pvHdl,siLev,siPos,isAry,psArg); if (siCnt<0) return(siCnt); } } } } if (psHdl->siTok==CLPTOK_END) { psHdl->siBuf--; psHdl->pcLex[0]=EOS; strcpy(psHdl->pcSrc,acSrc); psHdl->pcInp=pcInp; psHdl->pcCur=pcCur; psHdl->pcOld=pcOld; psHdl->pcRow=pcRow; psHdl->siRow=siRow; TRACE(psHdl->pfPrs,"PARAMETER-FILE-PARSER-END(FILE=%s CNT=%d)\n",acFil,siCnt); psHdl->siTok=siClpScnSrc(pvHdl,0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); return(siCnt); } else { return(CLPERR(psHdl,CLPERR_SYN,"Last token (%s) of parameter file '%s' is not EOF",apClpTok[psHdl->siTok],acFil)); } } static int siClpPrsObjWob( void* pvHdl, const int siLev, const int siPos, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr,siCnt; TsSym* psDep=NULL; TsVar asSav[CLPMAX_TABCNT]; TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d OBJ(%s(parlst))-OPN)\n",fpcPre(pvHdl,siLev),siLev,siPos,psArg->psStd->pcKyw); siErr=siClpIniObj(pvHdl,siLev,siPos,psArg,&psDep,asSav); if (siErr<0) return(siErr); siCnt=siClpPrsParLst(pvHdl,siLev+1,psDep); if (siCnt<0) return(siCnt); siErr=siClpFinObj(pvHdl,siLev,siPos,psArg,psDep,asSav); if (siErr<0) return(siErr); return(siCnt); } static int siClpPrsObj( void* pvHdl, const int siLev, const int siPos, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; int siCnt; TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d OBJ(%s(parlst))-OPN)\n",fpcPre(pvHdl,siLev),siLev,siPos,psArg->psStd->pcKyw); psHdl->siTok=siClpScnSrc(pvHdl,0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); siCnt=siClpPrsObjWob(pvHdl,siLev,siPos,psArg); if (siCnt<0) return(siCnt); if (psHdl->siTok==CLPTOK_RBC) { psHdl->siTok=siClpScnSrc(pvHdl,0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d CNT=%d OBJ(%s(parlst))-CLS)\n",fpcPre(pvHdl,siLev),siLev,siPos,siCnt,psArg->psStd->pcKyw); } else { return CLPERR(psHdl,CLPERR_SYN,"Character ')' missing to enclose object (%s)",fpcPat(pvHdl,siLev)); } return(CLP_OK); } static int siClpPrsOvl( void* pvHdl, const int siLev, const int siPos, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr,siCnt,siOid=0; TsSym* psDep=NULL; TsVar asSav[CLPMAX_TABCNT]; TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d OVL(%s.par)\n",fpcPre(pvHdl,siLev),siLev,siPos,psArg->psStd->pcKyw); siErr=siClpIniOvl(pvHdl,siLev,siPos,psArg,&psDep,asSav); if (siErr<0) return(siErr); siCnt=siClpPrsPar(pvHdl,siLev+1,siPos,psDep,&siOid); if (siCnt<0) return(siCnt); siErr=siClpFinOvl(pvHdl,siLev,siPos,psArg,psDep,asSav,siOid); if (siErr<0) return(siErr); return(CLP_OK); } static int siClpPrsMain( void* pvHdl, TsSym* psTab, int* piOid) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr,siCnt,siOid; TsVar asSav[CLPMAX_TABCNT]; if (psHdl->isOvl) { TRACE(psHdl->pfPrs,"%s PARSER(OVL(MAIN.par)\n",fpcPre(pvHdl,0)); if (psHdl->siTok==CLPTOK_DOT) { psHdl->siTok=siClpScnSrc(pvHdl,0,NULL); if (psHdl->siTok<0) return(psHdl->siTok); } siErr=siClpIniMainOvl(pvHdl,psTab,asSav); if (siErr<0) return(siErr); siErr=siClpPrsPar(pvHdl,0,0,psTab,&siOid); if (siErr<0) return(siErr); siErr=siClpFinMainOvl(pvHdl,psTab,asSav,siOid); if (siErr<0) return(siErr); if (piOid!=NULL) (*piOid)=siOid; return(1); } else { TRACE(psHdl->pfPrs,"%s PARSER(OBJ(MAIN(parlst)-OPN)\n",fpcPre(pvHdl,0)); siErr=siClpIniMainObj(pvHdl,psTab,asSav); if (siErr<0) return(siErr); if (psHdl->siTok==CLPTOK_RBO) { psHdl->siTok=siClpScnSrc(pvHdl,0,NULL); if (psHdl->siTok<0) return(psHdl->siTok); siCnt=siClpPrsParLst(pvHdl,0,psTab); if (siCnt<0) return(siCnt); if (psHdl->siTok==CLPTOK_RBC) { psHdl->siTok=siClpScnSrc(pvHdl,0,NULL); if (psHdl->siTok<0) return(psHdl->siTok); } else { return CLPERR(psHdl,CLPERR_SYN,"Character ')' missing to enclose object (%s)","***MAIN***"); } } else { siCnt=siClpPrsParLst(pvHdl,0,psTab); if (siCnt<0) return(siCnt); } siErr=siClpFinMainObj(pvHdl,psTab,asSav); if (siErr<0) return(siErr); TRACE(psHdl->pfPrs,"%s PARSER(OBJ(MAIN(parlst))-CLS)\n",fpcPre(pvHdl,0)); return(siCnt); } } static int siClpPrsAry( void* pvHdl, const int siLev, const int siPos, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; int siCnt; TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d ARY(%s%ctyplst%c)-OPN)\n",fpcPre(pvHdl,siLev),siLev,siPos,psArg->psStd->pcKyw,C_SBO,C_SBC); psHdl->siTok=siClpScnSrc(pvHdl,psArg->psFix->siTyp,psArg); if (psHdl->siTok<0) return(psHdl->siTok); if (psHdl->siTok==CLPTOK_SGN || psHdl->siTok==CLPTOK_SAB) { if (psHdl->isPfl) { if (psHdl->isPfl==2) { siCnt=siClpAcpFil(pvHdl,siLev,siPos,TRUE,psArg); } else { siCnt=siClpPrsFil(pvHdl,siLev,siPos,TRUE,psArg); } if (siCnt<0) return(siCnt); } else { CLPERR(psHdl,CLPERR_SEM,"Parameter files not allowed (%s.?)",fpcPat(pvHdl,siLev)); return(CLPERR_SEM); } } else { switch (psArg->psFix->siTyp) { case CLPTYP_NUMBER: siCnt=siClpPrsValLstFlexible(pvHdl,siLev,CLPTOK_NUM,psArg); break; case CLPTYP_FLOATN: siCnt=siClpPrsValLstFlexible(pvHdl,siLev,CLPTOK_FLT,psArg); break; case CLPTYP_STRING: siCnt=siClpPrsValLstFlexible(pvHdl,siLev,CLPTOK_STR,psArg); break; case CLPTYP_OBJECT: siCnt=siClpPrsObjLst(pvHdl,siLev,psArg); break; case CLPTYP_OVRLAY: siCnt=siClpPrsOvlLst(pvHdl,siLev,psArg); break; default: return CLPERR(psHdl,CLPERR_SEM,"Type (%d) of parameter '%s.%s' is not supported with arrays",psArg->psFix->siTyp,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } if (siCnt<0) return(siCnt); } if (psHdl->siTok==CLPTOK_SBC) { psHdl->siTok=siClpScnSrc(pvHdl,0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d CNT=%d ARY(%s%ctyplst%c)-CLS)\n",fpcPre(pvHdl,siLev),siLev,siPos,siCnt,psArg->psStd->pcKyw,C_SBO,C_SBC); return(CLP_OK); } else { return CLPERR(psHdl,CLPERR_SYN,"Character '%c' missing to enclose the array (%s)",C_SBC,fpcPat(pvHdl,siLev)); } } static int siClpPrsValLstFlexible( void* pvHdl, const int siLev, const int siTok, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr,siPos=0; while (psHdl->siTok==siTok || psHdl->siTok==CLPTOK_KYW || psHdl->siTok==CLPTOK_RBO) { siErr=siClpPrsVal(pvHdl,siLev,siPos,TRUE,psArg); if (siErr<0) return(siErr); siPos++; } return(siPos); } static int siClpPrsValLstOnlyArg( void* pvHdl, const int siLev, const int isEnd, const int siTok, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr,siPos=0; while ((isEnd || siPos==0 || psHdl->isSep==',' || psHdl->isSep=='\n') && (psHdl->siTok==siTok || (psHdl->siTok==CLPTOK_KYW && isClpKywAry(pvHdl,siTok,psHdl->pcLex,psArg,&psHdl->psVal)))) { siErr=siClpPrsVal(pvHdl,siLev,siPos,TRUE,psArg); if (siErr<0) return(siErr); siPos++; } return(siPos); } static int siClpPrsObjLst( void* pvHdl, const int siLev, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr,siPos=0; while (psHdl->siTok==CLPTOK_RBO) { siErr=siClpPrsObj(pvHdl,siLev,siPos,psArg); if (siErr<0) return(siErr); siPos++; } return(siPos); } static int siClpPrsOvlLst( void* pvHdl, const int siLev, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr,siPos=0; while (psHdl->siTok==CLPTOK_KYW) { siErr=siClpPrsOvl(pvHdl,siLev,siPos,psArg); if (siErr<0) return(siErr); siPos++; } return(siPos); } /**********************************************************************/ static int siFromNumberLexeme( void* pvHdl, const int siLev, TsSym* psArg, const char* pcVal, I64* piVal) { TsHdl* psHdl=(TsHdl*)pvHdl; char* pcHlp=NULL; errno=0; switch (pcVal[0]) { case 'b':*piVal=strtoll(pcVal+1,&pcHlp, 2); break; case 'o':*piVal=strtoll(pcVal+1,&pcHlp, 8); break; case 'd':*piVal=strtoll(pcVal+1,&pcHlp,10); break; case 'x':*piVal=strtoll(pcVal+1,&pcHlp,16); break; case 't':*piVal=strtoll(pcVal+1,&pcHlp,10); break; default: return CLPERR(psHdl,CLPERR_SEM,"Base (%c) of number literal (%s.%s=%s) not supported",pcVal[0],fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,isPrnStr(psArg,pcVal+1)); } if (errno || (pcHlp!=NULL && *pcHlp)) { if (pcHlp!=NULL && *pcHlp) { return CLPERR(psHdl,CLPERR_SEM,"Number (%s) of '%s.%s' cannot be converted to a valid 64 bit value (rest: %s)",isPrnStr(psArg,pcVal),fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,isPrnStr(psArg,pcHlp)); } else { return CLPERR(psHdl,CLPERR_SEM,"Number (%s) of '%s.%s' cannot be converted to a valid 64 bit value (errno: %d - %s)",isPrnStr(psArg,pcVal),fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,errno,strerror(errno)); } } return(CLP_OK); } static int siFromFloatLexeme( void* pvHdl, const int siLev, TsSym* psArg, const char* pcVal, double* pfVal) { TsHdl* psHdl=(TsHdl*)pvHdl; char* pcHlp=NULL; errno=0; switch (pcVal[0]) { case 'd': *pfVal=strtod(pcVal+1,&pcHlp); if (pcHlp!=NULL && *pcHlp=='.') { char* p=pcHlp; *p=','; *pfVal=strtod(pcVal+1,&pcHlp); *p='.'; } break; default: return CLPERR(psHdl,CLPERR_SEM,"Base (%c) of floating point literal (%s.%s=%s) not supported",pcVal[0],fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,isPrnStr(psArg,pcVal+1)); } if (errno || (pcHlp!=NULL && *pcHlp)) { if (pcHlp!=NULL && *pcHlp) { return CLPERR(psHdl,CLPERR_SEM,"Floating number (%s) of '%s.%s' cannot be converted to a valid 64 bit value (rest: %s)",isPrnStr(psArg,pcVal),fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,pcHlp); } else { return CLPERR(psHdl,CLPERR_SEM,"Floating number (%s) of '%s.%s' cannot be converted to a valid 64 bit value (errno: %d - %s)",isPrnStr(psArg,pcVal),fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,errno,strerror(errno)); } } return(CLP_OK); } static int siClpPrsExp( void* pvHdl, const int siLev, const int siPos, const int isAry, TsSym* psArg, size_t* pzVal, char** ppVal); static int siClpPrsFac( void* pvHdl, const int siLev, const int siPos, const int isAry, TsSym* psArg, size_t* pzVal, char** ppVal) { TsHdl* psHdl=(TsHdl*)pvHdl; const TsSym* psVal=psHdl->psVal; int siErr; I64 siInd; I64 siVal; F64 flVal; void* pvDat; char acLex[strlen(psHdl->pcLex)+1]; strcpy(acLex,psHdl->pcLex); switch(psHdl->siTok) { case CLPTOK_NUM: case CLPTOK_FLT: case CLPTOK_STR: psHdl->siTok=siClpScnSrc(pvHdl,(isAry)?psArg->psFix->siTyp:0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); if (CLPISF_SEL(psArg->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_SEM,"The argument '%s.%s' requires one of the defined keywords as value",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); CLPERRADD(psHdl,0,"Please use one of the following arguments:%s",""); vdClpPrnArgTab(pvHdl,psHdl->pfErr,1,psArg->psFix->siTyp,psArg->psDep); return(CLPERR_SEM); } srprintf(ppVal,pzVal,strlen(acLex),"%s",acLex); TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d NUM/FLT/STR(%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,*ppVal); return(CLP_OK); case CLPTOK_KYW: siInd=0; if (siClpNxtOpr(psHdl->pcCur)==C_CBO) { psHdl->siTok=siClpScnSrc(pvHdl,0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); if (psHdl->siTok==CLPTOK_CBO) { psHdl->siTok=siClpScnSrc(pvHdl,0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); if (psHdl->siTok!=CLPTOK_NUM) { return CLPERR(psHdl,CLPERR_SYN,"Index number expected (%s)",fpcPat(pvHdl,siLev)); } siErr=siFromNumberLexeme(pvHdl,siLev,psArg,psHdl->pcLex,&siInd); if (siErr) return(siErr); psHdl->siTok=siClpScnSrc(pvHdl,0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); if (psHdl->siTok!=CLPTOK_CBC) { return CLPERR(psHdl,CLPERR_SYN,"Character '%c' missing to define the index (%s)",C_CBC,fpcPat(pvHdl,siLev)); } } } psHdl->siTok=siClpScnSrc(pvHdl,(isAry)?psArg->psFix->siTyp:0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); if (psVal==NULL) { // not already find in scanner psVal=psClpFndSym(pvHdl,acLex,psArg->psDep); if (psVal==NULL) { if (CLPISF_SEL(psArg->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_SEM,"The argument '%s.%s' requires one of the defined keywords as value",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); CLPERRADD(psHdl,0,"Please use one of the following arguments:%s",""); vdClpPrnArgTab(pvHdl,psHdl->pfErr,1,psArg->psFix->siTyp,psArg->psDep); return(CLPERR_SEM); } psVal=psClpFndSym2(pvHdl,acLex,psArg); } } if (psVal!=NULL) { if (psArg->psFix->siTyp!=psVal->psFix->siTyp) { return CLPERR(psHdl,CLPERR_SEM,"The type (%s) of the symbol (%s) for argument '%s.%s' don't match the expected type (%s)", apClpTyp[psVal->psFix->siTyp],acLex,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psVal->psVar->pvDat==NULL || psVal->psVar->siCnt==0) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s) and type (%s) of variable value for argument (%s.%s) defined but data pointer not set (variable not yet defined)", psVal->psStd->pcKyw,apClpTyp[psVal->psFix->siTyp],fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } if (siInd<0 || siInd>=psVal->psVar->siCnt) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s) and type (%s) of variable value for argument (%s.%s) defined but data element counter (%d) too small (index (%d) not valid)", psVal->psStd->pcKyw,apClpTyp[psVal->psFix->siTyp],fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,psVal->psVar->siCnt,(int)siInd); } if (CLPISF_DYN(psVal->psStd->uiFlg)) { pvDat=(*((void**)psVal->psVar->pvDat)); } else { pvDat=psVal->psVar->pvDat; } switch (psVal->psFix->siTyp) { case CLPTYP_NUMBER: switch (psVal->psFix->siSiz) { case 1: siVal=((I08*)pvDat)[siInd]; break; case 2: siVal=((I16*)pvDat)[siInd]; break; case 4: siVal=((I32*)pvDat)[siInd]; break; case 8: siVal=((I64*)pvDat)[siInd]; break; default:return CLPERR(psHdl,CLPERR_SIZ,"Size (%d) for the constant value '%s' of '%s.%s' is not 1, 2, 4 or 8)", psVal->psFix->siSiz,psVal->psStd->pcKyw,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } if (siVal>=0) { srprintf(ppVal,pzVal,24,"d+%"PRIi64"",siVal); } else { srprintf(ppVal,pzVal,24,"d%"PRIi64"",siVal); } break; case CLPTYP_FLOATN: switch (psVal->psFix->siSiz) { case 4: flVal=((F32*)pvDat)[siInd]; break; case 8: flVal=((F64*)pvDat)[siInd]; break; default: return CLPERR(psHdl,CLPERR_SIZ,"Size (%d) for the constant value '%s' of '%s.%s' is not 4 or 8)", psVal->psFix->siSiz,psVal->psStd->pcKyw,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } if (flVal>=0.0) { srprintf(ppVal,pzVal,24,"d+%f",flVal); } else { srprintf(ppVal,pzVal,24,"d%f",flVal); } for (char* p=*ppVal;*p;p++) { if (*p==',') *p='.'; } break; case CLPTYP_STRING: if (siInd>0) { char* pcDat=pvDat; char* pcEnd=pcDat+psVal->psVar->siLen; if (CLPISF_FIX(psVal->psStd->uiFlg)) { pcDat+=siInd*psVal->psFix->siSiz; } else { for (int j=0;pcDat<pcEnd && j<siInd;pcDat++) { if (*pcDat==0x00) j++; } } if (pcDat>=pcEnd) { return CLPERR(psHdl,CLPERR_TAB,"Array access with index %d is not possible for this string argument (%s.%s)",(int)siInd,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } pvDat=pcDat; } if (CLPISF_BIN(psVal->psStd->uiFlg)) { char acHlp[(2*psVal->psVar->siLen)+1]; int l=bin2hex((unsigned char*)pvDat,acHlp,psVal->psVar->siLen); acHlp[l]=0x00; srprintf(ppVal,pzVal,strlen(acHlp),"x'%s",acHlp); } else if (CLPISF_HEX(psVal->psStd->uiFlg)) { srprintf(ppVal,pzVal,strlen((char*)pvDat),"x'%s",(char*)pvDat); } else if (CLPISF_ASC(psVal->psStd->uiFlg)) { srprintf(ppVal,pzVal,strlen((char*)pvDat),"a'%s",(char*)pvDat); } else if (CLPISF_EBC(psVal->psStd->uiFlg)) { srprintf(ppVal,pzVal,strlen((char*)pvDat),"e'%s",(char*)pvDat); } else { srprintf(ppVal,pzVal,strlen((char*)pvDat),"d'%s",(char*)pvDat); } break; default: return CLPERR(psHdl,CLPERR_TYP,"Type (%d) of constant '%s.%s' not supported in this case", psArg->psFix->siTyp,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d KYW-CON(%s) TAB)\n",fpcPre(pvHdl,siLev),siLev,siPos,*ppVal); } else { siErr=siClpConNat(pvHdl,psHdl->pfErr,psHdl->pfScn,acLex,pzVal,ppVal,psArg->psFix->siTyp,psArg); if (siErr==CLPTOK_KYW) { return CLPERR(psHdl,CLPERR_SYN,"Keyword (%s) not valid in expression of type %s for argument %s.%s", acLex,apClpTyp[psArg->psFix->siTyp],fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d KYW-CON(%s) FIX)\n",fpcPre(pvHdl,siLev),siLev,siPos,*ppVal); } return(CLP_OK); case CLPTOK_RBO: if (CLPISF_SEL(psArg->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_SEM,"The argument '%s.%s' requires one of the defined keywords as value",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); CLPERRADD(psHdl,0,"Please use one of the following arguments:%s",""); vdClpPrnArgTab(pvHdl,psHdl->pfErr,1,psArg->psFix->siTyp,psArg->psDep); return(CLPERR_SEM); } psHdl->siTok=siClpScnSrc(pvHdl,psArg->psFix->siTyp,psArg); if (psHdl->siTok<0) return(psHdl->siTok); siErr=siClpPrsExp(pvHdl,siLev,siPos,isAry,psArg,pzVal,ppVal); if (siErr) return(siErr); if (psHdl->siTok==CLPTOK_RBC) { psHdl->siTok=siClpScnSrc(pvHdl,(isAry)?psArg->psFix->siTyp:0,psArg); if (psHdl->siTok<0) return(psHdl->siTok); return(CLP_OK); } else { return CLPERR(psHdl,CLPERR_SYN,"Character ')' missing to enclose expression (%s)",fpcPat(pvHdl,siLev)); } default://Empty string behind = and infront of the next not matching token if (CLPISF_SEL(psArg->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_SEM,"The argument '%s.%s' requires one of the defined keywords as value",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); CLPERRADD(psHdl,0,"Please use one of the following arguments:%s",""); vdClpPrnArgTab(pvHdl,psHdl->pfErr,1,psArg->psFix->siTyp,psArg->psDep); return(CLPERR_SEM); } srprintf(ppVal,pzVal,0,"d'"); TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d NUM/FLT/STR(%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,*ppVal); return(CLP_OK); } } static int siClpPrsTrm( void* pvHdl, const int siLev, const int siPos, const int isAry, TsSym* psArg, size_t* pzVal, char** ppVal) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr; I64 siVal1=0; I64 siVal2=0; I64 siVal=0; F64 flVal1=0; F64 flVal2=0; F64 flVal=0; siErr=siClpPrsFac(pvHdl,siLev,siPos,isAry,psArg,pzVal,ppVal); if (siErr) return(siErr); if (psHdl->siTok==CLPTOK_MUL) { if (CLPISF_SEL(psArg->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_SEM,"The argument '%s.%s' requires one of the defined keywords as value",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); CLPERRADD(psHdl,0,"Please use one of the following arguments:%s",""); vdClpPrnArgTab(pvHdl,psHdl->pfErr,1,psArg->psFix->siTyp,psArg->psDep); return(CLPERR_SEM); } psHdl->siTok=siClpScnSrc(pvHdl,psArg->psFix->siTyp,psArg); if (psHdl->siTok<0) return(psHdl->siTok); size_t szVal=strlen(psHdl->pcLex)+CLPINI_VALSIZ; char* pcVal=(char*)calloc(1,szVal); if (pcVal==NULL) return(CLPERR(psHdl,CLPERR_MEM,"Allocation of memory to store expression values failed")); siErr=siClpPrsTrm(pvHdl,siLev,siPos,isAry,psArg,&szVal,&pcVal); if (siErr) { free(pcVal); return(siErr); } switch(psArg->psFix->siTyp) { case CLPTYP_NUMBER: siErr=siFromNumberLexeme(pvHdl,siLev,psArg,*ppVal,&siVal1); if (siErr) { free(pcVal); return(siErr); } siErr=siFromNumberLexeme(pvHdl,siLev,psArg,pcVal,&siVal2); if (siErr) { free(pcVal); return(siErr); } siVal=siVal1*siVal2; if (siVal>=0) { srprintf(ppVal,pzVal,24,"d+%"PRIi64"",siVal); } else { srprintf(ppVal,pzVal,24,"d%"PRIi64"",siVal); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d MUL-NUM(%"PRIi64"*%"PRIi64"=%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,siVal1,siVal2,*ppVal); break; case CLPTYP_FLOATN: siErr=siFromFloatLexeme(pvHdl,siLev,psArg,*ppVal,&flVal1); if (siErr) { free(pcVal); return(siErr); } siErr=siFromFloatLexeme(pvHdl,siLev,psArg,pcVal,&flVal2); if (siErr) { free(pcVal); return(siErr); } flVal=flVal1*flVal2; if (flVal>=0) { srprintf(ppVal,pzVal,24,"d+%f",flVal); } else { srprintf(ppVal,pzVal,24,"d%f",flVal); } for (char* p=*ppVal;*p;p++) { if (*p==',') *p='.'; } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d MUL-FLT(%f*%f=%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,flVal1,flVal2,*ppVal); break; default: free(pcVal); return CLPERR(psHdl,CLPERR_SEM,"Multiplication not supported for type %s",apClpTyp[psArg->psFix->siTyp]); } free(pcVal); } else if (psHdl->siTok==CLPTOK_DIV) { if (CLPISF_SEL(psArg->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_SEM,"The argument '%s.%s' requires one of the defined keywords as value",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); CLPERRADD(psHdl,0,"Please use one of the following arguments:%s",""); vdClpPrnArgTab(pvHdl,psHdl->pfErr,1,psArg->psFix->siTyp,psArg->psDep); return(CLPERR_SEM); } psHdl->siTok=siClpScnSrc(pvHdl,psArg->psFix->siTyp,psArg); if (psHdl->siTok<0) return(psHdl->siTok); size_t szVal=strlen(psHdl->pcLex)+CLPINI_VALSIZ; char* pcVal=(char*)calloc(1,szVal); if (pcVal==NULL) return(CLPERR(psHdl,CLPERR_MEM,"Allocation of memory to store expression values failed")); siErr=siClpPrsTrm(pvHdl,siLev,siPos,isAry,psArg,&szVal,&pcVal); if (siErr) { free(pcVal); return(siErr); } switch(psArg->psFix->siTyp) { case CLPTYP_NUMBER: siErr=siFromNumberLexeme(pvHdl,siLev,psArg,*ppVal,&siVal1); if (siErr) { free(pcVal); return(siErr); } siErr=siFromNumberLexeme(pvHdl,siLev,psArg,pcVal,&siVal2); if (siErr) { free(pcVal); return(siErr); } if (siVal2==0) { free(pcVal); return CLPERR(psHdl,CLPERR_SEM,"Devision by zero",apClpTyp[psArg->psFix->siTyp]); } siVal=siVal1/siVal2; if (siVal>=0) { srprintf(ppVal,pzVal,24,"d+%"PRIi64"",siVal); } else { srprintf(ppVal,pzVal,24,"d%"PRIi64"",siVal); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d DIV-NUM(%"PRIi64"/%"PRIi64"=%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,siVal1,siVal2,*ppVal); break; case CLPTYP_FLOATN: siErr=siFromFloatLexeme(pvHdl,siLev,psArg,*ppVal,&flVal1); if (siErr) { free(pcVal); return(siErr); } siErr=siFromFloatLexeme(pvHdl,siLev,psArg,pcVal,&flVal2); if (siErr) { free(pcVal); return(siErr); } if (flVal2==0) { free(pcVal); return CLPERR(psHdl,CLPERR_SEM,"Devision by zero",apClpTyp[psArg->psFix->siTyp]); } flVal=flVal1/flVal2; if (flVal>=0) { srprintf(ppVal,pzVal,24,"d+%f",flVal); } else { srprintf(ppVal,pzVal,24,"d%f",flVal); } for (char* p=*ppVal;*p;p++) { if (*p==',') *p='.'; } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d DIV-FLT(%f/%f=%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,flVal1,flVal2,*ppVal); break; default: free(pcVal); return CLPERR(psHdl,CLPERR_SEM,"Division not supported for type %s",apClpTyp[psArg->psFix->siTyp]); } free(pcVal); } else if (psHdl->siTok==CLPTOK_KYW && psHdl->isSep==FALSE && CLPTOK_KYW!=siClpConSrc(pvHdl,TRUE,psArg)) { if (CLPISF_SEL(psArg->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_SEM,"The argument '%s.%s' requires one of the defined keywords as value",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); CLPERRADD(psHdl,0,"Please use one of the following arguments:%s",""); vdClpPrnArgTab(pvHdl,psHdl->pfErr,1,psArg->psFix->siTyp,psArg->psDep); return(CLPERR_SEM); } size_t szVal=strlen(psHdl->pcLex)+CLPINI_VALSIZ; char* pcVal=(char*)calloc(1,szVal); if (pcVal==NULL) return(CLPERR(psHdl,CLPERR_MEM,"Allocation of memory to store expression values failed")); siErr=siClpPrsTrm(pvHdl,siLev,siPos,isAry,psArg,&szVal,&pcVal); if (siErr) { free(pcVal); return(siErr); } switch(psArg->psFix->siTyp) { case CLPTYP_NUMBER: siErr=siFromNumberLexeme(pvHdl,siLev,psArg,*ppVal,&siVal1); if (siErr) { free(pcVal); return(siErr); } siErr=siFromNumberLexeme(pvHdl,siLev,psArg,pcVal,&siVal2); if (siErr) { free(pcVal); return(siErr); } siVal=siVal1*siVal2; if (siVal>=0) { srprintf(ppVal,pzVal,24,"d+%"PRIi64"",siVal); } else { srprintf(ppVal,pzVal,24,"d%"PRIi64"",siVal); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d AUTO-MUL-NUM(%"PRIi64"*%"PRIi64"=%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,siVal1,siVal2,*ppVal); break; case CLPTYP_FLOATN: siErr=siFromFloatLexeme(pvHdl,siLev,psArg,*ppVal,&flVal1); if (siErr) { free(pcVal); return(siErr); } siErr=siFromFloatLexeme(pvHdl,siLev,psArg,pcVal,&flVal2); if (siErr) { free(pcVal); return(siErr); } flVal=flVal1*flVal2; if (flVal>=0) { srprintf(ppVal,pzVal,24,"d+%f",flVal); } else { srprintf(ppVal,pzVal,24,"d%f",flVal); } for (char* p=*ppVal;*p;p++) { if (*p==',') *p='.'; } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d AUTO-MUL-FLT(%f*%f=%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,flVal1,flVal2,*ppVal); break; case CLPTYP_STRING: if ((*ppVal)[0]==pcVal[0]) { } else if (((*ppVal)[0]=='d' && pcVal[0]=='s') || ((*ppVal)[0]=='s' && pcVal[0]=='d')){ (*ppVal)[0]='s'; } else if (((*ppVal)[0]=='d' && pcVal[0]=='c') || ((*ppVal)[0]=='c' && pcVal[0]=='d')){ (*ppVal)[0]='c'; } else { siErr=CLPERR(psHdl,CLPERR_SEM,"Cannot concatenate different types (%c <> %c) of strings",(*ppVal)[0],pcVal[0]); free(pcVal); return(siErr); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d ADD-STR(%s+",fpcPre(pvHdl,siLev),siLev,siPos,*ppVal); srprintc(ppVal,pzVal,strlen(pcVal),"%s",pcVal+2); TRACE(psHdl->pfPrs,"%s=%s))\n",pcVal,*ppVal); break; default: free(pcVal); return CLPERR(psHdl,CLPERR_SEM,"Multiplication not supported for type %s",apClpTyp[psArg->psFix->siTyp]); } free(pcVal); } return(CLP_OK); } static int siClpPrsExp( void* pvHdl, const int siLev, const int siPos, const int isAry, TsSym* psArg, size_t* pzVal, char** ppVal) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr; I64 siVal1=0; I64 siVal2=0; I64 siVal=0; F64 flVal1=0; F64 flVal2=0; F64 flVal=0; siErr=siClpPrsTrm(pvHdl,siLev,siPos,isAry,psArg,pzVal,ppVal); if (siErr) return(siErr); if (psHdl->siTok==CLPTOK_ADD) { if (CLPISF_SEL(psArg->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_SEM,"The argument '%s.%s' requires one of the defined keywords as value",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); CLPERRADD(psHdl,0,"Please use one of the following arguments:%s",""); vdClpPrnArgTab(pvHdl,psHdl->pfErr,1,psArg->psFix->siTyp,psArg->psDep); return(CLPERR_SEM); } psHdl->siTok=siClpScnSrc(pvHdl,psArg->psFix->siTyp,psArg); if (psHdl->siTok<0) return(psHdl->siTok); size_t szVal=strlen(psHdl->pcLex)+CLPINI_VALSIZ; char* pcVal=(char*)calloc(1,szVal); if (pcVal==NULL) return(CLPERR(psHdl,CLPERR_MEM,"Allocation of memory to store expression values failed")); siErr=siClpPrsExp(pvHdl,siLev,siPos,isAry,psArg,&szVal,&pcVal); if (siErr) { free(pcVal); return(siErr); } switch(psArg->psFix->siTyp) { case CLPTYP_NUMBER: siErr=siFromNumberLexeme(pvHdl,siLev,psArg,*ppVal,&siVal1); if (siErr) { free(pcVal); return(siErr); } siErr=siFromNumberLexeme(pvHdl,siLev,psArg,pcVal,&siVal2); if (siErr) { free(pcVal); return(siErr); } siVal=siVal1+siVal2; if (siVal>=0) { srprintf(ppVal,pzVal,24,"d+%"PRIi64"",siVal); } else { srprintf(ppVal,pzVal,24,"d%"PRIi64"",siVal); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d ADD-NUM(%"PRIi64"+%"PRIi64"=%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,siVal1,siVal2,*ppVal); break; case CLPTYP_FLOATN: siErr=siFromFloatLexeme(pvHdl,siLev,psArg,*ppVal,&flVal1); if (siErr) { free(pcVal); return(siErr); } siErr=siFromFloatLexeme(pvHdl,siLev,psArg,pcVal,&flVal2); if (siErr) { free(pcVal); return(siErr); } flVal=flVal1+flVal2; if (flVal>=0) { srprintf(ppVal,pzVal,24,"d+%f",flVal); } else { srprintf(ppVal,pzVal,24,"d%f",flVal); } for (char* p=*ppVal;*p;p++) { if (*p==',') *p='.'; } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d ADD-FLT(%f+%f=%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,flVal1,flVal2,*ppVal); break; case CLPTYP_STRING: if (pcVal[1]!=STRCHR) { siErr=CLPERR(psHdl,CLPERR_SEM,"The provided value (%s) is not a string literal",pcVal); free(pcVal); return(siErr); } if ((*ppVal)[0]==pcVal[0]) { } else if (((*ppVal)[0]=='d' && pcVal[0]=='s') || ((*ppVal)[0]=='s' && pcVal[0]=='d')){ (*ppVal)[0]='s'; } else if (((*ppVal)[0]=='d' && pcVal[0]=='c') || ((*ppVal)[0]=='c' && pcVal[0]=='d')){ (*ppVal)[0]='c'; } else { siErr=CLPERR(psHdl,CLPERR_SEM,"Cannot concatenate different types (%c <> %c) of strings",(*ppVal)[0],pcVal[0]); free(pcVal); return(siErr); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d ADD-STR(%s+",fpcPre(pvHdl,siLev),siLev,siPos,*ppVal); srprintc(ppVal,pzVal,strlen(pcVal),"%s",pcVal+2); TRACE(psHdl->pfPrs,"%s=%s))\n",pcVal,*ppVal); break; default: free(pcVal); return CLPERR(psHdl,CLPERR_SEM,"Addition not supported for type %s",apClpTyp[psArg->psFix->siTyp]); } free(pcVal); } else if (psHdl->siTok==CLPTOK_SUB) { if (CLPISF_SEL(psArg->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_SEM,"The argument '%s.%s' requires one of the defined keywords as value",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); CLPERRADD(psHdl,0,"Please use one of the following arguments:%s",""); vdClpPrnArgTab(pvHdl,psHdl->pfErr,1,psArg->psFix->siTyp,psArg->psDep); return(CLPERR_SEM); } psHdl->siTok=siClpScnSrc(pvHdl,psArg->psFix->siTyp,psArg); if (psHdl->siTok<0) return(psHdl->siTok); size_t szVal=strlen(psHdl->pcLex)+CLPINI_VALSIZ; char* pcVal=(char*)calloc(1,szVal); if (pcVal==NULL) return(CLPERR(psHdl,CLPERR_MEM,"Allocation of memory to store expression values failed")); siErr=siClpPrsExp(pvHdl,siLev,siPos,isAry,psArg,&szVal,&pcVal); if (siErr) { free(pcVal); return(siErr); } switch(psArg->psFix->siTyp) { case CLPTYP_NUMBER: siErr=siFromNumberLexeme(pvHdl,siLev,psArg,*ppVal,&siVal1); if (siErr) { free(pcVal); return(siErr); } siErr=siFromNumberLexeme(pvHdl,siLev,psArg,pcVal,&siVal2); if (siErr) { free(pcVal); return(siErr); } siVal=siVal1-siVal2; if (siVal>=0) { srprintf(ppVal,pzVal,24,"d+%"PRIi64"",siVal); } else { srprintf(ppVal,pzVal,24,"d%"PRIi64"",siVal); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d SUB-NUM(%"PRIi64"-%"PRIi64"=%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,siVal1,siVal2,*ppVal); break; case CLPTYP_FLOATN: siErr=siFromFloatLexeme(pvHdl,siLev,psArg,*ppVal,&flVal1); if (siErr) { free(pcVal); return(siErr); } siErr=siFromFloatLexeme(pvHdl,siLev,psArg,pcVal,&flVal2); if (siErr) { free(pcVal); return(siErr); } flVal=flVal1-flVal2; if (flVal>=0) { srprintf(ppVal,pzVal,24,"d+%f",flVal); } else { srprintf(ppVal,pzVal,24,"d%f",flVal); } for (char* p=*ppVal;*p;p++) { if (*p==',') *p='.'; } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d SUB-FLT(%f-%f=%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,flVal1,flVal2,*ppVal); break; default: free(pcVal); return CLPERR(psHdl,CLPERR_SEM,"Subtracation not supported for type %s",apClpTyp[psArg->psFix->siTyp]); } free(pcVal); } else if ((psHdl->siTok==CLPTOK_NUM || psHdl->siTok==CLPTOK_FLT || psHdl->siTok==CLPTOK_STR) && psHdl->isSep==FALSE) { if (CLPISF_SEL(psArg->psStd->uiFlg)) { CLPERR(psHdl,CLPERR_SEM,"The argument '%s.%s' requires one of the defined keywords as value",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); CLPERRADD(psHdl,0,"Please use one of the following arguments:%s",""); vdClpPrnArgTab(pvHdl,psHdl->pfErr,1,psArg->psFix->siTyp,psArg->psDep); return(CLPERR_SEM); } size_t szVal=strlen(psHdl->pcLex)+CLPINI_VALSIZ; char* pcVal=(char*)calloc(1,szVal); if (pcVal==NULL) return(CLPERR(psHdl,CLPERR_MEM,"Allocation of memory to store expression values failed")); siErr=siClpPrsExp(pvHdl,siLev,siPos,isAry,psArg,&szVal,&pcVal); if (siErr) { free(pcVal); return(siErr); } switch(psArg->psFix->siTyp) { case CLPTYP_NUMBER: siErr=siFromNumberLexeme(pvHdl,siLev,psArg,*ppVal,&siVal1); if (siErr) { free(pcVal); return(siErr); } siErr=siFromNumberLexeme(pvHdl,siLev,psArg,pcVal,&siVal2); if (siErr) { free(pcVal); return(siErr); } siVal=siVal1+siVal2; if (siVal>=0) { srprintf(ppVal,pzVal,24,"d+%"PRIi64"",siVal); } else { srprintf(ppVal,pzVal,24,"d%"PRIi64"",siVal); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d AUTO-ADD-NUM(%"PRIi64"+%"PRIi64"=%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,siVal1,siVal2,*ppVal); break; case CLPTYP_FLOATN: siErr=siFromFloatLexeme(pvHdl,siLev,psArg,*ppVal,&flVal1); if (siErr) { free(pcVal); return(siErr); } siErr=siFromFloatLexeme(pvHdl,siLev,psArg,pcVal,&flVal2); if (siErr) { free(pcVal); return(siErr); } flVal=flVal1+flVal2; if (flVal>=0) { srprintf(ppVal,pzVal,24,"d+%f",flVal); } else { srprintf(ppVal,pzVal,24,"d%f",flVal); } for (char* p=*ppVal;*p;p++) { if (*p==',') *p='.'; } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d AUTO-ADD-FLT(%f+%f=%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,flVal1,flVal2,*ppVal); break; case CLPTYP_STRING: if (pcVal[1]!=STRCHR) { siErr=CLPERR(psHdl,CLPERR_SEM,"The provided value (%s) is not a string literal",pcVal); free(pcVal); return(siErr); } if ((*ppVal)[0]==pcVal[0]) { } else if (((*ppVal)[0]=='d' && pcVal[0]=='s') || ((*ppVal)[0]=='s' && pcVal[0]=='d')){ (*ppVal)[0]='s'; } else if (((*ppVal)[0]=='d' && pcVal[0]=='c') || ((*ppVal)[0]=='c' && pcVal[0]=='d')){ (*ppVal)[0]='c'; } else { siErr=CLPERR(psHdl,CLPERR_SEM,"Cannot concatenate different types (%c <> %c) of strings",(*ppVal)[0],pcVal[0]); free(pcVal); return(siErr); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d ADD-STR(%s+",fpcPre(pvHdl,siLev),siLev,siPos,*ppVal); srprintc(ppVal,pzVal,strlen(pcVal),"%s",pcVal+2); TRACE(psHdl->pfPrs,"%s=%s))\n",pcVal,*ppVal); break; default: free(pcVal); return CLPERR(psHdl,CLPERR_SEM,"Addition not supported for type %s",apClpTyp[psArg->psFix->siTyp]); } free(pcVal); } return(CLP_OK); } static int siClpPrsVal( void* pvHdl, const int siLev, const int siPos, const int isAry, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; int siInd; size_t szVal=strlen(psHdl->pcLex)+CLPINI_VALSIZ; char* pcVal=(char*)malloc(szVal); if (pcVal==NULL) return(CLPERR(psHdl,CLPERR_MEM,"Allocation of memory to store expression values failed")); psHdl->apPat[siLev]=psArg; siInd=siClpPrsExp(pvHdl,siLev,siPos,isAry,psArg,&szVal,&pcVal); if (siInd<0) { free(pcVal); return(siInd); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d LIT(%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,isPrnLex(psArg,pcVal)); siInd=siClpBldLit(pvHdl,siLev,siPos,psArg,pcVal); free(pcVal); return(siInd); } /**********************************************************************/ static int siClpPrsProLst( void* pvHdl, const TsSym* psTab) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr,siPos=0; while (psHdl->siTok==CLPTOK_KYW) { siErr=siClpPrsPro(pvHdl,psTab); if (siErr<0) return(siErr); siPos++; } return(siPos); } static int siClpPrsPro( void* pvHdl, const TsSym* psTab) { TsHdl* psHdl=(TsHdl*)pvHdl; size_t szPat=CLPINI_PATSIZ; char* pcPat=(char*)calloc(1,szPat); int siErr,siLev,siRow; if (pcPat==NULL) return(CLPERR(psHdl,CLPERR_MEM,"Allocation of memory to store the path failed")); siLev=siClpPrsKywLst(pvHdl,&szPat,&pcPat); if (siLev<0) { free(pcPat); return(siLev); } if (psHdl->siTok==CLPTOK_SGN) { siRow=psHdl->siRow; psHdl->siTok=siClpScnSrc(pvHdl,CLPTYP_STRING,psTab); if (psHdl->siTok<0) { free(pcPat); return(psHdl->siTok); } if (psHdl->siTok==CLPTOK_STR) { char acSup[strlen(psHdl->pcLex)]; strcpy(acSup,psHdl->pcLex+2); psHdl->siTok=siClpScnSrc(pvHdl,0,psTab); if (psHdl->siTok<0) { free(pcPat); return(psHdl->siTok); } siErr=siClpBldPro(pvHdl,pcPat,acSup,siRow); free(pcPat); return(siErr); } else { siErr=CLPERR(psHdl,CLPERR_SYN,"Property string (\"...\") missing (%s)",pcPat); free(pcPat); return(siErr); } } else { siErr=CLPERR(psHdl,CLPERR_SYN,"Assignment character ('=') missing (%s)",pcPat); free(pcPat); return(siErr); } } static int siClpPrsKywLst( void* pvHdl, size_t* pzPat, char** ppPat) { TsHdl* psHdl=(TsHdl*)pvHdl; int siLev=0; (*ppPat)[0]=EOS; while (psHdl->siTok==CLPTOK_KYW) { srprintc(ppPat,pzPat,strlen(psHdl->pcLex),"%s",psHdl->pcLex); psHdl->siTok=siClpScnSrc(pvHdl,0,NULL); if (psHdl->siTok<0) return(psHdl->siTok); if (psHdl->siTok==CLPTOK_DOT) { srprintc(ppPat,pzPat,0,"."); psHdl->siTok=siClpScnSrc(pvHdl,0,NULL); if (psHdl->siTok<0) return(psHdl->siTok); } siLev++; } return(siLev); } /**********************************************************************/ static int siClpBldPro( void* pvHdl, const char* pcPat, const char* pcPro, const int siRow) { TsHdl* psHdl=(TsHdl*)pvHdl; TsSym* psTab=psHdl->psTab; TsSym* psArg=NULL; const char* pcPtr=NULL; const char* pcKyw=NULL; char acKyw[CLPMAX_KYWSIZ]; int siErr,siLev,i,l=strlen(psHdl->pcOwn)+strlen(psHdl->pcPgm)+strlen(psHdl->pcCmd)+2; char acRot[l+1]; snprintf(acRot,sizeof(acRot),"%s.%s.%s",psHdl->pcOwn,psHdl->pcPgm,psHdl->pcCmd); if (strxcmp(psHdl->isCas,acRot,pcPat,l,0,FALSE)==0) { if (pcPat[l]!='.') { return CLPERR(psHdl,CLPERR_SEM,"Property path (%s) is not valid",pcPat); } for (siLev=0,pcPtr=pcPat+l;pcPtr!=NULL && siLev<CLPMAX_HDEPTH && psTab!=NULL;pcPtr=strchr(pcPtr+1,'.'),siLev++) { for (pcKyw=pcPtr+1,i=0;i<CLPMAX_KYWLEN && pcKyw[i]!=EOS && pcKyw[i]!='.';i++) acKyw[i]=pcKyw[i]; acKyw[i]=EOS; siErr=siClpSymFnd(pvHdl,siLev,acKyw,psTab,&psArg,NULL); if (siErr<0) return(siErr); psHdl->apPat[siLev]=psArg; if (psArg!=NULL) psTab=psArg->psDep; else psTab=NULL; } if (psArg!=NULL) { if (CLPISF_ARG(psArg->psStd->uiFlg) || CLPISF_ALI(psArg->psStd->uiFlg)) { C08* pcHlp=realloc_nowarn(psArg->psFix->pcPro,strlen(pcPro)+1); if (pcHlp==NULL) { return CLPERR(psHdl,CLPERR_SIZ,"Build of property field failed (string (%d(%s)) too long)",(int)strlen(pcPro),pcPro); } psArg->psFix->pcPro=pcHlp; strcpy(psArg->psFix->pcPro,pcPro); psArg->psFix->pcDft=psArg->psFix->pcPro; pcHlp=realloc_nowarn(psArg->psFix->pcSrc,strlen(psHdl->pcSrc)+1); if (pcHlp==NULL) { return CLPERR(psHdl,CLPERR_SIZ,"Build of source field failed (string (%d(%s)) too long)",(int)strlen(psHdl->pcSrc),psHdl->pcSrc); } psArg->psFix->pcSrc=pcHlp; strcpy(psArg->psFix->pcSrc,psHdl->pcSrc); psArg->psFix->siRow=siRow; srprintc(&psHdl->pcLst,&psHdl->szLst,strlen(pcPat)+strlen(isPrnLex2(psArg,pcPro)),"%s=\"%s\"\n",pcPat,isPrnLex2(psArg,pcPro)); TRACE(psHdl->pfBld,"BUILD-PROPERTY %s=\"%s\"\n",pcPat,isPrnStr(psArg,pcPro)); } else { return CLPERR(psHdl,CLPERR_SEM,"Path '%s' for property \"%s\" is not an argument or alias",pcPat,isPrnStr(psArg,pcPro)); } } else { return CLPERR(psHdl,CLPERR_SEM,"Path '%s' not valid",pcPat); } } else { if (psHdl->isChk) { return CLPERR(psHdl,CLPERR_SEM,"Root of path (%s) does not match root of handle (%s.%s.%s)",pcPat,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcCmd); } } return(CLP_OK); } static int siClpBldLnk( void* pvHdl, const int siLev, const int siPos, const int siNum, TsSym* psArg, const int isApp) { TsHdl* psHdl=(TsHdl*)pvHdl; const int siTyp=CLPTYP_NUMBER; I64 siVal=siNum; (void)siPos; if (psArg!=NULL) { if (isApp==FALSE) { psArg->psVar->pvPtr=psArg->psVar->pvDat; psArg->psVar->siCnt=0; psArg->psVar->siLen=0; psArg->psVar->siRst=(CLPISF_DYN(psArg->psStd->uiFlg))?0:psArg->psFix->siSiz; if (CLPISF_FIX(psArg->psStd->uiFlg)) psArg->psVar->siRst*=psArg->psFix->siMax; } if (psArg->psFix->siTyp!=siTyp) { return CLPERR(psHdl,CLPERR_SEM,"The type (%s) of link '%s.%s' don't match the expected type (%s)",apClpTyp[siTyp],fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psVar->siCnt>=psArg->psFix->siMax) { return CLPERR(psHdl,CLPERR_SEM,"Too many (>%d) occurrences of link '%s.%s' with type '%s'",psArg->psFix->siMax,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,apClpTyp[siTyp]); } if (psArg->psVar->pvDat==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of link are defined but data pointer not set",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (CLPISF_DYN(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+((((CLPISF_DLM(psArg->psStd->uiFlg))?2:1)*psArg->psFix->siSiz)),&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for link '%s.%s' failed",psArg->psVar->siLen+psArg->psFix->siSiz,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { if (psArg->psVar->siRst<psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_SIZ,"Rest of space (%d) is not big enough for link '%s.%s' with type '%s'",psArg->psVar->siRst,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,apClpTyp[siTyp]); } if (psArg->psVar->pvPtr==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of link are defined but write pointer not set",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } } switch (psArg->psFix->siSiz) { case 1: if (siVal<(-128) || siVal>255) { return CLPERR(psHdl,CLPERR_SEM,"Internal number (%"PRIi64") for link '%s.%s' need more than 8 Bit",isPrnInt(psArg,siVal),fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } *((I08*)psArg->psVar->pvPtr)=(I08)siVal; TRACE(psHdl->pfBld,"%s BUILD-LINK-I08(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; case 2: if (siVal<(-32768) || siVal>65535) { return CLPERR(psHdl,CLPERR_SEM,"Internal number (%"PRIi64") for link '%s.%s' need more than 16 Bit",isPrnInt(psArg,siVal),fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } *((I16*)psArg->psVar->pvPtr)=(I16)siVal; TRACE(psHdl->pfBld,"%s BUILD-LINK-I16(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; case 4: if (siVal<(-2147483648LL) || siVal>4294967295LL) { return CLPERR(psHdl,CLPERR_SEM,"Internal number (%"PRIi64") for link '%s.%s' need more than 32 Bit",isPrnInt(psArg,siVal),fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } *((I32*)psArg->psVar->pvPtr)=(I32)siVal; TRACE(psHdl->pfBld,"%s BUILD-LINK-I32(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; case 8: *((I64*)psArg->psVar->pvPtr)=(I64)siVal; TRACE(psHdl->pfBld,"%s BUILD-LINK-I64(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; default: return CLPERR(psHdl,CLPERR_SIZ,"Size (%d) for the value (%"PRIi64") of link '%s.%s' is not 1, 2, 4 or 8)",psArg->psFix->siSiz,isPrnInt(psArg,siVal),fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)psArg->psVar->pvPtr)+psArg->psFix->siSiz; psArg->psVar->siLen+=psArg->psFix->siSiz; psArg->psVar->siRst-=CLPISF_DYN(psArg->psStd->uiFlg)?0:psArg->psFix->siSiz; psArg->psVar->siCnt++; return(psArg->psFix->siTyp); } else return(CLP_OK); } static int siClpBldSwt( void* pvHdl, const int siLev, const int siPos, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; const int siTyp=CLPTYP_SWITCH; I64 siVal=psArg->psFix->siOid; const char* pcPat=fpcPat(pvHdl,siLev); int siErr; if (psArg->psFix->siTyp!=siTyp) { return CLPERR(psHdl,CLPERR_SEM,"The type (%s) of switch '%s.%s' don't match the expected type (%s)",apClpTyp[siTyp],pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psVar->siCnt>=psArg->psFix->siMax) { return CLPERR(psHdl,CLPERR_SEM,"Too many (>%d) occurrences of switch '%s.%s' with type '%s'",psArg->psFix->siMax,pcPat,psArg->psStd->pcKyw,apClpTyp[siTyp]); } if (psArg->psVar->pvDat==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of switch defined but data pointer not set",pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psHdl->pfSaf!=NULL) { char acEnt[strlen(pcPat)+strlen(GETKYW(psArg))+2]; snprintf(acEnt,sizeof(acEnt),"%s.%s",pcPat,GETKYW(psArg)); if (psHdl->pfSaf(psHdl->pvGbl,psHdl->pvSaf,acEnt)) { return CLPERR(psHdl,CLPERR_AUT,"Authorization request for entity '%s' failed",acEnt); } } if (CLPISF_DYN(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+((((CLPISF_DLM(psArg->psStd->uiFlg))?2:1)*psArg->psFix->siSiz)),&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for switch '%s.%s' failed",psArg->psVar->siLen+psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { if (psArg->psVar->siRst<psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_SIZ,"Rest of space (%d) is not big enough for switch '%s.%s' with type '%s'",psArg->psVar->siRst,pcPat,psArg->psStd->pcKyw,apClpTyp[siTyp]); } if (psArg->psVar->pvPtr==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of switch are defined but write pointer not set",pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } } switch (psArg->psFix->siSiz) { case 1: if (siVal<(-128) || siVal>65535) { return CLPERR(psHdl,CLPERR_SEM,"Object identifier (%"PRIi64") of '%s.%s' need more than 8 Bit",isPrnInt(psArg,siVal),pcPat,psArg->psStd->pcKyw); } *((I08*)psArg->psVar->pvPtr)=(I08)siVal; TRACE(psHdl->pfBld,"%s BUILD-SWITCH-I08(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; case 2: if (siVal<(-32768) || siVal>65535) { return CLPERR(psHdl,CLPERR_SEM,"Object identifier (%"PRIi64") of '%s.%s' need more than 16 Bit",isPrnInt(psArg,siVal),pcPat,psArg->psStd->pcKyw); } *((I16*)psArg->psVar->pvPtr)=(I16)siVal; TRACE(psHdl->pfBld,"%s BUILD-SWITCH-I16(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; case 4: if (siVal<(-2147483648LL) || siVal>4294967295LL) { return CLPERR(psHdl,CLPERR_SEM,"Object identifier (%"PRIi64") of '%s.%s' need more than 32 Bit",isPrnInt(psArg,siVal),pcPat,psArg->psStd->pcKyw); } *((I32*)psArg->psVar->pvPtr)=(I32)siVal; TRACE(psHdl->pfBld,"%s BUILD-SWITCH-I32(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; case 8: *((I64*)psArg->psVar->pvPtr)=(I64)siVal; TRACE(psHdl->pfBld,"%s BUILD-SWITCH-64(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; default: return CLPERR(psHdl,CLPERR_SIZ,"Size (%d) for the value (%"PRIi64") of '%s.%s' is not 1, 2, 4 or 8)",psArg->psFix->siSiz,isPrnInt(psArg,siVal),pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)psArg->psVar->pvPtr)+psArg->psFix->siSiz; psArg->psVar->siLen+=psArg->psFix->siSiz; psArg->psVar->siRst-=CLPISF_DYN(psArg->psStd->uiFlg)?0:psArg->psFix->siSiz; psArg->psVar->siCnt++; srprintc(&psHdl->pcLst,&psHdl->szLst,strlen(pcPat)+strlen(GETKYW(psArg)),"%s.%s=ON\n",pcPat,GETKYW(psArg)); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psVar->siCnt,psArg->psFix->psCnt,FALSE); if (siErr<0) return(siErr); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psFix->siSiz,psArg->psFix->psEln,TRUE); if (siErr<0) return(siErr); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psVar->siLen,psArg->psFix->psTln,FALSE); if (siErr<0) return(siErr); if(psArg->psFix->siOid){ siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psFix->siOid,psArg->psFix->psOid,TRUE); if (siErr<0) return(siErr); } return(psArg->psFix->siTyp); } static int siClpBldNum( void* pvHdl, const int siLev, const int siPos, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; const int siTyp=CLPTYP_NUMBER; I64 siVal=psArg->psFix->siOid; const char* pcPat=fpcPat(pvHdl,siLev); int siErr; if (psArg->psFix->siTyp!=siTyp) { return CLPERR(psHdl,CLPERR_SEM,"The type (%s) of argument '%s.%s' don't match the expected type (%s)",apClpTyp[siTyp],pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psVar->siCnt>=psArg->psFix->siMax) { return CLPERR(psHdl,CLPERR_SEM,"Too many (>%d) occurrences of argument '%s.%s' with type '%s'",psArg->psFix->siMax,pcPat,psArg->psStd->pcKyw,apClpTyp[siTyp]); } if (psArg->psVar->pvDat==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of argument defined but data pointer not set",pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psHdl->pfSaf!=NULL) { char acEnt[strlen(pcPat)+strlen(GETKYW(psArg))+2]; snprintf(acEnt,sizeof(acEnt),"%s.%s",pcPat,GETKYW(psArg)); if (psHdl->pfSaf(psHdl->pvGbl,psHdl->pvSaf,acEnt)) { return CLPERR(psHdl,CLPERR_AUT,"Authorization request for entity '%s' failed",acEnt); } } if (CLPISF_DYN(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+((((CLPISF_DLM(psArg->psStd->uiFlg))?2:1)*psArg->psFix->siSiz)),&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (1)",psArg->psVar->siLen+psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { if (psArg->psVar->siRst<psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_SIZ,"Rest of space (%d) is not big enough for argument '%s.%s' with type '%s'",psArg->psVar->siRst,pcPat,psArg->psStd->pcKyw,apClpTyp[siTyp]); } if (psArg->psVar->pvPtr==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of argument defined but write pointer not set",pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } } switch (psArg->psFix->siSiz) { case 1: if (siVal<(-128) || siVal>65535) { return CLPERR(psHdl,CLPERR_SEM,"Default value (%"PRIi64") of '%s.%s' need more than 8 Bit",isPrnInt(psArg,siVal),pcPat,psArg->psStd->pcKyw); } *((I08*)psArg->psVar->pvPtr)=(I08)siVal; TRACE(psHdl->pfBld,"%s BUILD-NUMBER-I08(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; case 2: if (siVal<(-32768) || siVal>65535) { return CLPERR(psHdl,CLPERR_SEM,"Default value (%"PRIi64") of '%s.%s' need more than 16 Bit",isPrnInt(psArg,siVal),pcPat,psArg->psStd->pcKyw); } *((I16*)psArg->psVar->pvPtr)=(I16)siVal; TRACE(psHdl->pfBld,"%s BUILD-NUMBER-I16(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; case 4: if (siVal<(-2147483648LL) || siVal>4294967295LL) { return CLPERR(psHdl,CLPERR_SEM,"Default value (%"PRIi64") of '%s.%s' need more than 32 Bit",isPrnInt(psArg,siVal),pcPat,psArg->psStd->pcKyw); } *((I32*)psArg->psVar->pvPtr)=(I32)siVal; TRACE(psHdl->pfBld,"%s BUILD-NUMBER-I32(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; case 8: *((I64*)psArg->psVar->pvPtr)=(I64)siVal; TRACE(psHdl->pfBld,"%s BUILD-NUMBER-64(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; default: return CLPERR(psHdl,CLPERR_SIZ,"Size (%d) for the value (%"PRIi64") of '%s.%s' is not 1, 2, 4 or 8)",psArg->psFix->siSiz,isPrnInt(psArg,siVal),pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)psArg->psVar->pvPtr)+psArg->psFix->siSiz; psArg->psVar->siLen+=psArg->psFix->siSiz; psArg->psVar->siRst-=CLPISF_DYN(psArg->psStd->uiFlg)?0:psArg->psFix->siSiz; psArg->psVar->siCnt++; srprintc(&psHdl->pcLst,&psHdl->szLst,strlen(pcPat)+strlen(GETKYW(psArg))+16,"%s.%s=DEFAULT(%d)\n",pcPat,GETKYW(psArg),(int)siVal); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psVar->siCnt,psArg->psFix->psCnt,FALSE); if (siErr<0) return(siErr); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psFix->siSiz,psArg->psFix->psEln,TRUE); if (siErr<0) return(siErr); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psVar->siLen,psArg->psFix->psTln,FALSE); if (siErr<0) return(siErr); if(psArg->psFix->siOid){ siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psFix->siOid,psArg->psFix->psOid,TRUE); if (siErr<0) return(siErr); } return(psArg->psFix->siTyp); } static int siClpBldLit( void* pvHdl, const int siLev, const int siPos, TsSym* psArg, const char* pcVal) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr; int l0=0; int l1=0; int l2=0; int siSln=0; I64 siVal=0; F64 flVal=0; char* pcHlp=NULL; const char* pcKyw=NULL; const char* pcPat=fpcPat(pvHdl,siLev); TsSym* psCon; C08 acTim[CSTIME_BUFSIZ]; if (psArg->psVar->siCnt>=psArg->psFix->siMax) { return CLPERR(psHdl,CLPERR_SEM,"Too many (>%d) occurrences of argument '%s.%s' with type '%s'",psArg->psFix->siMax,pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psVar->pvDat==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of argument defined but data pointer not set",pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psHdl->pfSaf!=NULL) { char acEnt[strlen(pcPat)+strlen(GETKYW(psArg))+2]; snprintf(acEnt,sizeof(acEnt),"%s.%s",pcPat,GETKYW(psArg)); if (psHdl->pfSaf(psHdl->pvGbl,psHdl->pvSaf,acEnt)) { return CLPERR(psHdl,CLPERR_AUT,"Authorization request for entity '%s' failed",acEnt); } } switch (psArg->psFix->siTyp) { case CLPTYP_SWITCH: case CLPTYP_NUMBER: if (CLPISF_DYN(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+((((CLPISF_DLM(psArg->psStd->uiFlg))?2:1)*psArg->psFix->siSiz)),&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (2)",psArg->psVar->siLen+psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { if (psArg->psVar->siRst<psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_SIZ,"Rest of space (%d) is not big enough for argument '%s.%s' with type '%s'",psArg->psVar->siRst,pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psVar->pvPtr==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of argument are defined but write pointer not set",pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } } siErr=siFromNumberLexeme(pvHdl,siLev,psArg,pcVal,&siVal); if (siErr) return(siErr); if (siVal<0 && CLPISF_UNS(psArg->psStd->uiFlg)) { return CLPERR(psHdl,CLPERR_SEM,"Literal number (%s) of '%s.%s' is negative (%"PRIi64") but marked as unsigned",isPrnStr(psArg,pcVal),pcPat,psArg->psStd->pcKyw,siVal); } switch (psArg->psFix->siSiz) { case 1: if (siVal<(-128) || siVal>255) { return CLPERR(psHdl,CLPERR_SEM,"Literal number (%s) of '%s.%s' need more than 8 Bit",isPrnStr(psArg,pcVal),pcPat,psArg->psStd->pcKyw); } *((I08*)psArg->psVar->pvPtr)=(I08)siVal; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-I08(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; case 2: if (siVal<(-32768) || siVal>65535) { return CLPERR(psHdl,CLPERR_SEM,"Literal number (%s) of '%s.%s' need more than 16 Bit",isPrnStr(psArg,pcVal),pcPat,psArg->psStd->pcKyw); } *((I16*)psArg->psVar->pvPtr)=(I16)siVal; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-I16(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; case 4: if (siVal<(-2147483648LL) || siVal>4294967295LL) { return CLPERR(psHdl,CLPERR_SEM,"Literal number (%s) of '%s.%s' need more than 32 Bit",isPrnStr(psArg,pcVal),pcPat,psArg->psStd->pcKyw); } *((I32*)psArg->psVar->pvPtr)=(I32)siVal; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-I32(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; case 8: *((I64*)psArg->psVar->pvPtr)=(I64)siVal; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-I64(PTR=%p CNT=%d LEN=%d RST=%d)%s=%"PRIi64"\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnInt(psArg,siVal)); break; default: return CLPERR(psHdl,CLPERR_SIZ,"Size (%d) for the value (%s) of '%s.%s' is not 1, 2, 4 or 8)",psArg->psFix->siSiz,isPrnStr(psArg,pcVal),pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)psArg->psVar->pvPtr)+psArg->psFix->siSiz; psArg->psVar->siLen+=psArg->psFix->siSiz; psArg->psVar->siRst-=CLPISF_DYN(psArg->psStd->uiFlg)?0:psArg->psFix->siSiz; siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psVar->siLen,psArg->psFix->psEln,FALSE); if (siErr<0) return(siErr); break; case CLPTYP_FLOATN: if (CLPISF_DYN(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+((((CLPISF_DLM(psArg->psStd->uiFlg))?2:1)*psArg->psFix->siSiz)),&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (3)",psArg->psVar->siLen+psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { if (psArg->psVar->siRst<psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_SIZ,"Rest of space (%d) is not big enough for argument '%s.%s' with type '%s'",psArg->psVar->siRst,pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psVar->pvPtr==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of argument are defined but write pointer not set",pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } } siErr=siFromFloatLexeme(pvHdl,siLev,psArg,pcVal,&flVal); if (siErr) return(siErr); if (flVal<0 && CLPISF_UNS(psArg->psStd->uiFlg)) { return CLPERR(psHdl,CLPERR_SEM,"Literal number (%s) of '%s.%s' is negative (%f) but marked as unsigned",isPrnStr(psArg,pcVal),pcPat,psArg->psStd->pcKyw,flVal); } switch (psArg->psFix->siSiz) { case 4: *((F32*)psArg->psVar->pvPtr)=flVal; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-F32(PTR=%p CNT=%d LEN=%d RST=%d)%s=%f\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnFlt(psArg,flVal)); break; case 8: *((F64*)psArg->psVar->pvPtr)=flVal; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-F64(PTR=%p CNT=%d LEN=%d RST=%d)%s=%f\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnFlt(psArg,flVal)); break; default: return CLPERR(psHdl,CLPERR_SIZ,"Size (%d) for the value (%s) of '%s.%s' is not 4 (float) or 8 (double))",psArg->psFix->siSiz,isPrnStr(psArg,pcVal),pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)psArg->psVar->pvPtr)+psArg->psFix->siSiz; psArg->psVar->siLen+=psArg->psFix->siSiz; psArg->psVar->siRst-=CLPISF_DYN(psArg->psStd->uiFlg)?0:psArg->psFix->siSiz; siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psVar->siLen,psArg->psFix->psEln,FALSE); if (siErr<0) return(siErr); break; case CLPTYP_STRING: if (CLPISF_FIX(psArg->psStd->uiFlg)) { l0=psArg->psFix->siSiz; if (CLPISF_DYN(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+((((CLPISF_DLM(psArg->psStd->uiFlg))?2:1)*psArg->psFix->siSiz)),&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (4)",psArg->psVar->siLen+psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { if (psArg->psVar->siRst<psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_SIZ,"Rest of space (%d) is not big enough for argument '%s.%s' with type '%s'",psArg->psVar->siRst,pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psVar->pvPtr==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of argument are defined but write pointer not set",pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } } } else { l0=psArg->psVar->siRst; if (!CLPISF_DYN(psArg->psStd->uiFlg)) { if (psArg->psVar->pvPtr==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of argument are defined but write pointer not set",pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } } } switch (pcVal[0]) { case 'x': l1=strlen(pcVal+2); if (CLPISF_BIN(psArg->psStd->uiFlg)) { if (l1%2) { return CLPERR(psHdl,CLPERR_LEX,"Length of hexadecimal string (%c(%s)) for '%s.%s' is not a multiple of 2",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw); } if ((l1/2)>l0) { if (CLPISF_DYN(psArg->psStd->uiFlg) && !CLPISF_FIX(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; if (psArg->psVar->siLen+(l1/2)>psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_MEM,"Size limit (%d) reached for argument '%s.%s'",psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+(l1/2)+4,&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (5)",psArg->psVar->siLen+(l1/2)+4,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { return CLPERR(psHdl,CLPERR_LEX,"Hexadecimal string (%c(%s)) of '%s.%s' is longer than %d",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw,2*l0); } } l2=hex2bin(pcVal+2,(U08*)psArg->psVar->pvPtr,l1); if (l2!=l1/2) { return CLPERR(psHdl,CLPERR_SEM,"Hexadecimal string (%c(%s)) of '%s.%s' cannot be converted from hex to bin",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw); } siSln=l2; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-HEX(PTR=%p CNT=%d LEN=%d RST=%d)%s=%s(%d)\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnStr(psArg,pcVal),isPrnLen(psArg,l2)); } else { return CLPERR(psHdl,CLPERR_SEM,"String literal (%c(%s)) for '%s.%s' is binary (only null-terminated character string permitted)",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw); } break; case 'a': l1=strlen(pcVal+2); if (CLPISF_BIN(psArg->psStd->uiFlg)) { if (l1>l0) { if (CLPISF_DYN(psArg->psStd->uiFlg)&& !CLPISF_FIX(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; if (psArg->psVar->siLen+l1>psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_MEM,"Size limit (%d) reached for argument '%s.%s'",psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+l1+4,&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (6)",psArg->psVar->siLen+l1+4,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { return CLPERR(psHdl,CLPERR_LEX,"ASCII string (%c(%s)) of '%s.%s' is longer than %d",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw,l0); } } l2=chr2asc(pcVal+2,(C08*)psArg->psVar->pvPtr,l1); if (l2!=l1) { return CLPERR(psHdl,CLPERR_SEM,"ASCII string (%c(%s)) of '%s.%s' cannot be converted to ASCII",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw); } siSln=l1; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-ASC(PTR=%p CNT=%d LEN=%d RST=%d)%s=%s(%d)\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnStr(psArg,pcVal),isPrnLen(psArg,l2)); } else { return CLPERR(psHdl,CLPERR_SEM,"String literal (%c(%s)) for '%s.%s' is binary (only null-terminated character string permitted)",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw); } break; case 'e': l1=strlen(pcVal+2); if (CLPISF_BIN(psArg->psStd->uiFlg)) { if (l1>l0) { if (CLPISF_DYN(psArg->psStd->uiFlg) && !CLPISF_FIX(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; if (psArg->psVar->siLen+l1>psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_MEM,"Size limit (%d) reached for argument '%s.%s'",psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+l1+4,&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (7)",psArg->psVar->siLen+l1+4,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { return CLPERR(psHdl,CLPERR_LEX,"EBCDIC string (%c(%s)) of '%s.%s' is longer than %d",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw,l0); } } l2=chr2ebc(pcVal+2,(C08*)psArg->psVar->pvPtr,l1); if (l2!=l1) { return CLPERR(psHdl,CLPERR_SEM,"EBCDIC string (%c(%s)) of '%s.%s' cannot be converted to EBCDIC",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw); } siSln=l1; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-EBC(PTR=%p CNT=%d LEN=%d RST=%d)%s=%s(%d)\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnStr(psArg,pcVal),isPrnLen(psArg,l2)); } else { return CLPERR(psHdl,CLPERR_SEM,"String literal (%c(%s)) for '%s.%s' is binary (only null-terminated character string permitted)",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw); } break; case 'c': l1=strlen(pcVal+2); if (CLPISF_BIN(psArg->psStd->uiFlg)) { if (l1>l0) { if (CLPISF_DYN(psArg->psStd->uiFlg)&& !CLPISF_FIX(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; if (psArg->psVar->siLen+l1>psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_MEM,"Size limit (%d) reached for argument '%s.%s'",psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+l1+4,&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (8)",psArg->psVar->siLen+l1+4,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { return CLPERR(psHdl,CLPERR_LEX,"Character string (%c(%s)) of '%s.%s' is longer than %d",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw,l0); } } memcpy(psArg->psVar->pvPtr,pcVal+2,l1); l2=l1; siSln=l1; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-CHR(PTR=%p CNT=%d LEN=%d RST=%d)%s=%s(%d)\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnStr(psArg,pcVal),isPrnLen(psArg,l2)); } else { return CLPERR(psHdl,CLPERR_SEM,"String literal (%c(%s)) for '%s.%s' is binary (only null-terminated character string permitted)",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw); } break; case 's': if (CLPISF_XML(psArg->psStd->uiFlg)) { pcHlp=dmapxml(pcVal+2,CLPISF_UPP(psArg->psStd->uiFlg)?1:CLPISF_LOW(psArg->psStd->uiFlg)?2:0); } else if (CLPISF_FIL(psArg->psStd->uiFlg)) { pcHlp=dmapfil(pcVal+2,CLPISF_UPP(psArg->psStd->uiFlg)?1:CLPISF_LOW(psArg->psStd->uiFlg)?2:0); } else if (CLPISF_LAB(psArg->psStd->uiFlg)) { pcHlp=dmaplab(pcVal+2,CLPISF_UPP(psArg->psStd->uiFlg)?1:CLPISF_LOW(psArg->psStd->uiFlg)?2:0); } else { pcHlp=dmapstr(pcVal+2,CLPISF_UPP(psArg->psStd->uiFlg)?1:CLPISF_LOW(psArg->psStd->uiFlg)?2:0); } if (pcHlp==NULL) { return CLPERR(psHdl,CLPERR_MEM,"String mapping (memory allocation) for argument '%s.%s' failed",pcPat,psArg->psStd->pcKyw); } l1=strlen(pcHlp); if (l1+1>l0) { if (CLPISF_DYN(psArg->psStd->uiFlg) && !CLPISF_FIX(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; if (psArg->psVar->siLen+l1+1>psArg->psFix->siSiz) { free(pcHlp); return CLPERR(psHdl,CLPERR_MEM,"Size limit (%d) reached for argument '%s.%s'",psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+l1+4,&psArg->psVar->siInd); if ((*ppDat)==NULL) { free(pcHlp); return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (9)",psArg->psVar->siLen+l1+4,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { siErr=CLPERR(psHdl,CLPERR_LEX,"Character string (%c(%s)) of '%s.%s' is longer than %d",pcVal[0],isPrnStr(psArg,pcHlp),pcPat,psArg->psStd->pcKyw,l0-1); free(pcHlp); return(siErr); } } memcpy(psArg->psVar->pvPtr,pcHlp,l1); ((char*)psArg->psVar->pvPtr)[l1]=EOS; free(pcHlp); l2=l1+1; siSln=l1; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-STR(PTR=%p CNT=%d LEN=%d RST=%d)%s=%s(%d)\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnStr(psArg,pcVal),isPrnLen(psArg,l2)); break; case 'f': { int siTok; int siRow; int siSiz=0; char* pcDat=NULL; const char* pcCur; const char* pcInp; const char* pcOld; const char* pcRow; char acSrc[strlen(psHdl->pcSrc)+1]; size_t szLex=CLPINI_LEXSIZ; char* pcLex=(char*)calloc(1,szLex); char acMsg[1024]=""; if (pcLex==NULL) { return(CLPERR(psHdl,CLPERR_MEM,"Allocation of memory to store the lexeme or file name failed")); } siErr=psHdl->pfF2s(psHdl->pvGbl,psHdl->pvF2s,pcVal+2,&pcDat,&siSiz,acMsg,sizeof(acMsg)); if (siErr<0) { siErr=CLPERR(psHdl,CLPERR_SYS,"String file: %s",acMsg); SAFE_FREE(pcDat); free(pcLex); return(siErr); } TRACE(psHdl->pfPrs,"STRING-FILE-BEGIN(%s)\n",pcVal+2); strcpy(acSrc,psHdl->pcSrc); srprintf(&psHdl->pcSrc,&psHdl->szSrc,strlen(CLPSRC_SRF)+strlen(pcVal+2),"%s%s",CLPSRC_SRF,pcVal+2); pcInp=psHdl->pcInp; psHdl->pcInp=pcClpUnEscape(pvHdl,pcDat); SAFE_FREE(pcDat); if (psHdl->pcInp==NULL) { siErr=CLPERR(psHdl,CLPERR_MEM,"Un-escaping of string file (%s) failed",pcVal+2); free(pcLex); return(siErr); } pcCur=psHdl->pcCur; psHdl->pcCur=psHdl->pcInp; pcOld=psHdl->pcOld; psHdl->pcOld=psHdl->pcInp; pcRow=psHdl->pcRow; psHdl->pcRow=psHdl->pcInp; siRow=psHdl->siRow; psHdl->siRow=1; psHdl->siBuf++; siTok=siClpScnNat(pvHdl,psHdl->pfErr,psHdl->pfScn,&psHdl->pcCur,&szLex,&pcLex,CLPTYP_STRING,psArg,NULL,NULL); if (siTok<0) { free(pcLex); return(siTok); } if (siTok!=CLPTOK_STR) { siErr=CLPERR(psHdl,CLPERR_SYN,"The token (%s(%s)) is not allowed in a string file (%c(%s)) of '%s.%s'",apClpTok[siTok],pcLex,pcVal[0],pcVal+2,pcPat,psArg->psStd->pcKyw); free(pcLex); return(siErr); } if (pcLex[0]=='f') { siErr=CLPERR(psHdl,CLPERR_SYN,"Define a string file (%c(%s)) in a string file (%c(%s)) is not allowed (%s.%s)",pcLex[0],pcLex+2,pcVal[0],pcVal+2,pcPat,psArg->psStd->pcKyw); free(pcLex); return(siErr); } siErr=siClpBldLit(pvHdl,siLev,siPos,psArg,pcLex); psHdl->siBuf--; strcpy(psHdl->pcSrc,acSrc); psHdl->pcInp=pcInp; psHdl->pcCur=pcCur; psHdl->pcOld=pcOld; psHdl->pcRow=pcRow; psHdl->siRow=siRow; TRACE(psHdl->pfPrs,"STRING-FILE-END(%s)\n",pcVal+2); free(pcLex); return(siErr); } case 'd': if (CLPISF_BIN(psArg->psStd->uiFlg)) { if (CLPISF_HEX(psArg->psStd->uiFlg)) { l1=strlen(pcVal+2); if (l1%2) { return CLPERR(psHdl,CLPERR_LEX,"Length of hexadecimal string (%c(%s)) for '%s.%s' is not a multiple of 2",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw); } if ((l1/2)>l0) { if (CLPISF_DYN(psArg->psStd->uiFlg)&& !CLPISF_FIX(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; if (psArg->psVar->siLen+(l1/2)>psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_MEM,"Size limit (%d) reached for argument '%s.%s'",psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+(l1/2)+4,&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (10)",psArg->psVar->siLen+(l1/2)+4,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { return CLPERR(psHdl,CLPERR_LEX,"Hexadecimal string (%c(%s)) of '%s.%s' is longer than %d",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw,2*l0); } } l2=hex2bin(pcVal+2,(U08*)psArg->psVar->pvPtr,l1); if (l2!=l1/2) { return CLPERR(psHdl,CLPERR_SEM,"Hexadecimal string (%c(%s)) of '%s.%s' cannot be converted from hex to bin",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw); } siSln=l2; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-HEX(PTR=%p CNT=%d LEN=%d RST=%d)%s=%s(%d)\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnStr(psArg,pcVal),isPrnLen(psArg,l2)); } else if (CLPISF_ASC(psArg->psStd->uiFlg)) { l1=strlen(pcVal+2); if (l1>l0) { if (CLPISF_DYN(psArg->psStd->uiFlg)&& !CLPISF_FIX(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; if (psArg->psVar->siLen+l1>psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_MEM,"Size limit (%d) reached for argument '%s.%s'",psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+l1+4,&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (11)",psArg->psVar->siLen+l1+4,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { return CLPERR(psHdl,CLPERR_LEX,"ASCII string (%c(%s)) of '%s.%s' is longer than %d",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw,l0); } } l2=chr2asc(pcVal+2,(C08*)psArg->psVar->pvPtr,l1); if (l2!=l1) { return CLPERR(psHdl,CLPERR_SEM,"ASCII string (%c(%s)) of '%s.%s' cannot be converted to ASCII",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw); } siSln=l1; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-ASC(PTR=%p CNT=%d LEN=%d RST=%d)%s=%s(%d)\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnStr(psArg,pcVal),isPrnLen(psArg,l2)); } else if (CLPISF_EBC(psArg->psStd->uiFlg)) { l1=strlen(pcVal+2); if (l1>l0) { if (CLPISF_DYN(psArg->psStd->uiFlg)&& !CLPISF_FIX(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; if (psArg->psVar->siLen+l1>psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_MEM,"Size limit (%d) reached for argument '%s.%s'",psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+l1+4,&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (12)",psArg->psVar->siLen+l1+4,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { return CLPERR(psHdl,CLPERR_LEX,"EBCDIC string (%c(%s)) of '%s.%s' is longer than %d",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw,l0); } } l2=chr2ebc(pcVal+2,(C08*)psArg->psVar->pvPtr,l1); if (l2!=l1) { return CLPERR(psHdl,CLPERR_SEM,"EBCDIC string (%c(%s)) of '%s.%s' cannot be converted to EBCDIC",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw); } siSln=l1; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-EBC(PTR=%p CNT=%d LEN=%d RST=%d)%s=%s(%d)\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnStr(psArg,pcVal),isPrnLen(psArg,l2)); } else { l1=strlen(pcVal+2); if (l1>l0) { if (CLPISF_DYN(psArg->psStd->uiFlg)&& !CLPISF_FIX(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; if (psArg->psVar->siLen+l1>psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_MEM,"Size limit (%d) reached for argument '%s.%s'",psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+l1+4,&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (13)",psArg->psVar->siLen+l1+4,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { return CLPERR(psHdl,CLPERR_LEX,"Character string (%c(%s)) of '%s.%s' is longer than %d",pcVal[0],isPrnStr(psArg,pcVal+2),pcPat,psArg->psStd->pcKyw,l0); } } memcpy(psArg->psVar->pvPtr,pcVal+2,l1); l2=l1; siSln=l1; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-CHR(PTR=%p CNT=%d LEN=%d RST=%d)%s=%s(%d)\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnStr(psArg,pcVal),isPrnLen(psArg,l2)); } } else { if (CLPISF_XML(psArg->psStd->uiFlg)) { pcHlp=dmapxml(pcVal+2,CLPISF_UPP(psArg->psStd->uiFlg)?1:CLPISF_LOW(psArg->psStd->uiFlg)?2:0); } else if (CLPISF_FIL(psArg->psStd->uiFlg)) { pcHlp=dmapfil(pcVal+2,CLPISF_UPP(psArg->psStd->uiFlg)?1:CLPISF_LOW(psArg->psStd->uiFlg)?2:0); } else if (CLPISF_LAB(psArg->psStd->uiFlg)) { pcHlp=dmaplab(pcVal+2,CLPISF_UPP(psArg->psStd->uiFlg)?1:CLPISF_LOW(psArg->psStd->uiFlg)?2:0); } else { pcHlp=dmapstr(pcVal+2,CLPISF_UPP(psArg->psStd->uiFlg)?1:CLPISF_LOW(psArg->psStd->uiFlg)?2:0); } if (pcHlp==NULL) { return CLPERR(psHdl,CLPERR_MEM,"String mapping (memory allocation) for argument '%s.%s' failed",pcPat,psArg->psStd->pcKyw); } l1=strlen(pcHlp); if (l1+1>l0) { if (CLPISF_DYN(psArg->psStd->uiFlg)&& !CLPISF_FIX(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; if (psArg->psVar->siLen+l1+1>psArg->psFix->siSiz) { free(pcHlp); return CLPERR(psHdl,CLPERR_MEM,"Size limit (%d) reached for argument '%s.%s'",psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+l1+4,&psArg->psVar->siInd); if ((*ppDat)==NULL) { free(pcHlp); return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (14)",psArg->psVar->siLen+l1+4,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { siErr=CLPERR(psHdl,CLPERR_LEX,"Character string (%c(%s)) of '%s.%s' is longer than %d",pcVal[0],isPrnStr(psArg,pcHlp),pcPat,psArg->psStd->pcKyw,l0-1); free(pcHlp); return(siErr); } } memcpy(psArg->psVar->pvPtr,pcHlp,l1); ((char*)psArg->psVar->pvPtr)[l1]=EOS; free(pcHlp); l2=l1+1; siSln=l1; TRACE(psHdl->pfBld,"%s BUILD-LITERAL-STR(PTR=%p CNT=%d LEN=%d RST=%d)%s=%s(%d)\n", fpcPre(pvHdl,siLev),psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst,psArg->psStd->pcKyw,isPrnStr(psArg,pcVal),isPrnLen(psArg,l2)); } break; default: CLPERR(psHdl,CLPERR_LEX,"String prefix (%c) of '%s.%s' is not supported",pcVal[0],pcPat,psArg->psStd->pcKyw); CLPERRADD(psHdl,0,"Please use one of the following values:%s",""); CLPERRADD(psHdl,1,"x - for conversion from hex to bin%s",""); CLPERRADD(psHdl,1,"a - for conversion in ASCII%s",""); CLPERRADD(psHdl,1,"e - for conversion in EBCDIC%s",""); CLPERRADD(psHdl,1,"c - for no conversion (normal character string without null termination)%s",""); CLPERRADD(psHdl,1,"s - normal character string with null termination%s",""); CLPERRADD(psHdl,1,"f - use file content as string%s",""); return(CLPERR_LEX); } if (CLPISF_FIX(psArg->psStd->uiFlg)) { memset(((U08*)psArg->psVar->pvPtr)+l2,0,psArg->psFix->siSiz-l2); psArg->psVar->pvPtr=((char*)psArg->psVar->pvPtr)+psArg->psFix->siSiz; psArg->psVar->siLen+=psArg->psFix->siSiz; psArg->psVar->siRst-=CLPISF_DYN(psArg->psStd->uiFlg)?0:psArg->psFix->siSiz; siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psFix->siSiz,psArg->psFix->psEln,TRUE); if (siErr<0) return(siErr); } else { if (CLPISF_DLM(psArg->psStd->uiFlg)) { ((char*)psArg->psVar->pvPtr)[l2]=0xFF; // end of string list } psArg->psVar->pvPtr=((char*)psArg->psVar->pvPtr)+l2; psArg->psVar->siLen+=l2; psArg->psVar->siRst-=CLPISF_DYN(psArg->psStd->uiFlg)?0:l2; siErr=siClpBldLnk(pvHdl,siLev,siPos,l2,psArg->psFix->psEln,TRUE); if (siErr<0) return(siErr); } siErr=siClpBldLnk(pvHdl,siLev,siPos,siSln,psArg->psFix->psSln,TRUE); if (siErr<0) return(siErr); break; default: return CLPERR(psHdl,CLPERR_TYP,"Type (%d) of parameter '%s.%s' not supported in this case (literal)",psArg->psFix->siTyp,pcPat,psArg->psStd->pcKyw); } psArg->psVar->siCnt++; for (psCon=psArg->psDep;psCon!=NULL;psCon=psCon->psNxt) { if (pcKyw==NULL && psCon->psFix->siTyp==psArg->psFix->siTyp) { switch (psCon->psFix->siTyp) { case CLPTYP_NUMBER: switch (psCon->psFix->siSiz) { case 1: if (siVal==((I08*)psCon->psVar->pvDat)[0]) pcKyw=psCon->psStd->pcKyw; break; case 2: if (siVal==((I16*)psCon->psVar->pvDat)[0]) pcKyw=psCon->psStd->pcKyw; break; case 4: if (siVal==((I32*)psCon->psVar->pvDat)[0]) pcKyw=psCon->psStd->pcKyw; break; case 8: if (siVal==((I64*)psCon->psVar->pvDat)[0]) pcKyw=psCon->psStd->pcKyw; break; } break; case CLPTYP_FLOATN: switch (psCon->psFix->siSiz) { case 4: if (flVal==((F32*)psCon->psVar->pvDat)[0]) pcKyw=psCon->psStd->pcKyw; break; case 8: if (flVal==((F64*)psCon->psVar->pvDat)[0]) pcKyw=psCon->psStd->pcKyw; break; } break; default: if (l2>0 && psCon->psVar->siLen==l2 && memcmp(psCon->psVar->pvDat,((char*)psArg->psVar->pvPtr)-l2,l2)==0) { pcKyw=psCon->psStd->pcKyw; } break; } } } if (pcKyw!=NULL) { if (psArg->psFix->siTyp==CLPTYP_NUMBER && (CLPISF_TIM(psArg->psStd->uiFlg) || pcVal[0]=='t')) { srprintc(&psHdl->pcLst,&psHdl->szLst,strlen(pcPat)+strlen(GETKYW(psArg))+strlen(isPrnStr(psArg,pcVal))+strlen(cstime(siVal,acTim)),"%s.%s=%s(%s(%s))\n",pcPat,GETKYW(psArg),pcKyw,isPrnStr(psArg,pcVal),acTim); } else { srprintc(&psHdl->pcLst,&psHdl->szLst,strlen(pcPat)+strlen(GETKYW(psArg))+strlen(isPrnStr(psArg,pcVal)),"%s.%s=%s(%s)\n",pcPat,GETKYW(psArg),pcKyw,isPrnStr(psArg,pcVal)); } } else { if (psArg->psFix->siTyp==CLPTYP_NUMBER && (CLPISF_TIM(psArg->psStd->uiFlg) || pcVal[0]=='t')) { srprintc(&psHdl->pcLst,&psHdl->szLst,strlen(pcPat)+strlen(GETKYW(psArg))+strlen(isPrnStr(psArg,pcVal))+strlen(cstime(siVal,acTim)),"%s.%s=%s(%s)\n",pcPat,GETKYW(psArg),isPrnStr(psArg,pcVal),acTim); } else { srprintc(&psHdl->pcLst,&psHdl->szLst,strlen(pcPat)+strlen(GETKYW(psArg))+strlen(isPrnStr(psArg,pcVal)),"%s.%s=%s\n",pcPat,GETKYW(psArg),isPrnStr(psArg,pcVal)); } } siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psVar->siCnt,psArg->psFix->psCnt,FALSE); if (siErr<0) return(siErr); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psVar->siLen,psArg->psFix->psTln,FALSE); if (siErr<0) return(siErr); if(psArg->psFix->siOid){ siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psFix->siOid,psArg->psFix->psOid,TRUE); if (siErr<0) return(siErr); } return(psArg->psFix->siTyp); } static int siClpIniMainObj( void* pvHdl, TsSym* psTab, TsVar* psSav) { TsHdl* psHdl=(TsHdl*)pvHdl; const char* pcPat=fpcPat(pvHdl,0); TsSym* psHlp; if (psTab->psBak!=NULL) { return CLPERR(psHdl,CLPERR_INT,"Entry '%s.%s' not at beginning of a table",pcPat,psTab->psStd->pcKyw); } if (psHdl->pfSaf!=NULL) { if (psHdl->pfSaf(psHdl->pvGbl,psHdl->pvSaf,pcPat)) { return CLPERR(psHdl,CLPERR_AUT,"Authorization request for entity '%s' failed",pcPat); } } if (psHdl->pvDat!=NULL) { for (psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt,psSav++) { *psSav=*psHlp->psVar; psHlp->psVar->pvDat=((char*)psHdl->pvDat)+psHlp->psFix->siOfs; psHlp->psVar->pvPtr=psHlp->psVar->pvDat; psHlp->psVar->siCnt=0; psHlp->psVar->siLen=0; psHlp->psVar->siInd=0; psHlp->psVar->siRst=CLPISF_DYN(psHlp->psStd->uiFlg)?0:psHlp->psFix->siSiz; if (CLPISF_FIX(psHlp->psStd->uiFlg)) psHlp->psVar->siRst*=psHlp->psFix->siMax; } } else { return CLPERR(psHdl,CLPERR_PAR,"Pointer to CLP data structure is NULL (%s.%s)",pcPat,psTab->psStd->pcKyw); } TRACE(psHdl->pfBld,"BUILD-BEGIN-MAIN-ARGUMENT-LIST\n"); return(CLP_OK); } static int siClpFinMainObj( void* pvHdl, TsSym* psTab, const TsVar* psSav) { TsHdl* psHdl=(TsHdl*)pvHdl; TsSym* psHlp=NULL; int siErr,i; if (psTab->psBak!=NULL) { return CLPERR(psHdl,CLPERR_INT,"Entry '%s.%s' not at beginning of a table",fpcPat(pvHdl,0),psTab->psStd->pcKyw); } for (i=0,psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt,i++) { siErr=siClpSetDefault(pvHdl,0,i,psHlp); if (siErr<0) { CLPERRADD(psHdl,0,"Set default value for argument '%s.%s' failed",fpcPat(pvHdl,0),psHlp->psStd->pcKyw); return(siErr); } } if (psHdl->isChk) { for (psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt) { if (psHlp->psVar->siCnt<psHlp->psFix->siMin) { if (psHlp->psFix->siMin<=1) { CLPERR(psHdl,CLPERR_SEM,"Parameter '%s.%s' not specified",fpcPat(pvHdl,0),psHlp->psStd->pcKyw); CLPERRADD(psHdl,0,"Please specify parameter:%s",""); vdClpPrnArg(pvHdl,psHdl->pfErr,1,psHlp->psStd->pcKyw,GETALI(psHlp),psHlp->psStd->siKwl,psHlp->psFix->siTyp,psHlp->psFix->pcHlp,psHlp->psFix->pcDft, CLPISF_SEL(psHlp->psStd->uiFlg),CLPISF_CON(psHlp->psStd->uiFlg)); } else { CLPERR(psHdl,CLPERR_SEM,"Amount of occurrences (%d) of parameter '%s.%s' is smaller than required minimum amount (%d)",psHlp->psVar->siCnt,fpcPat(pvHdl,0),psHlp->psStd->pcKyw,psHlp->psFix->siMin); CLPERRADD(psHdl,0,"Please specify parameter additionally %d times:%s",""); vdClpPrnArg(pvHdl,psHdl->pfErr,1,psHlp->psStd->pcKyw,GETALI(psHlp),psHlp->psStd->siKwl,psHlp->psFix->siTyp,psHlp->psFix->pcHlp,psHlp->psFix->pcDft, CLPISF_SEL(psHlp->psStd->uiFlg),CLPISF_CON(psHlp->psStd->uiFlg)); } return(CLPERR_SEM); } } } for (psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt,psSav++) *psHlp->psVar=*psSav; TRACE(psHdl->pfBld,"BUILD-END-MAIN-ARGUMENT-LIST\n"); return(CLP_OK); } static int siClpIniMainOvl( void* pvHdl, TsSym* psTab, TsVar* psSav) { TsHdl* psHdl=(TsHdl*)pvHdl; const char* pcPat=fpcPat(pvHdl,0); TsSym* psHlp; if (psTab->psBak!=NULL) { return CLPERR(psHdl,CLPERR_INT,"Entry '%s.%s' not at beginning of a table",pcPat,psTab->psStd->pcKyw); } if (psHdl->pfSaf!=NULL) { if (psHdl->pfSaf(psHdl->pvGbl,psHdl->pvSaf,pcPat)) { return CLPERR(psHdl,CLPERR_AUT,"Authorization request for entity '%s' failed",pcPat); } } if (psHdl->pvDat!=NULL) { for (psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt,psSav++) { *psSav=*psHlp->psVar; psHlp->psVar->pvDat=((char*)psHdl->pvDat); psHlp->psVar->pvPtr=psHlp->psVar->pvDat; psHlp->psVar->siCnt=0; psHlp->psVar->siLen=0; psHlp->psVar->siInd=0; psHlp->psVar->siRst=CLPISF_DYN(psHlp->psStd->uiFlg)?0:psHlp->psFix->siSiz; if (CLPISF_FIX(psHlp->psStd->uiFlg)) psHlp->psVar->siRst*=psHlp->psFix->siMax; } } else { return CLPERR(psHdl,CLPERR_PAR,"Pointer to CLP data structure is NULL (%s.%s)",pcPat,psTab->psStd->pcKyw); } TRACE(psHdl->pfBld,"BUILD-BEGIN-MAIN-ARGUMENT\n"); return(CLP_OK); } static int siClpFinMainOvl( void* pvHdl, TsSym* psTab, const TsVar* psSav, const int siOid) { TsHdl* psHdl=(TsHdl*)pvHdl; TsSym* psHlp=NULL; int siErr,i; if (psTab->psBak!=NULL) { return CLPERR(psHdl,CLPERR_INT,"Entry '%s.%s' not at beginning of a table",fpcPat(pvHdl,0),psTab->psStd->pcKyw); } for (i=0,psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt,i++) { if (psHlp->psFix->siOid==siOid) { siErr=siClpSetDefault(pvHdl,0,i,psHlp); if (siErr<0) { CLPERRADD(psHdl,0,"Set default value for argument '%s.%s' failed",fpcPat(pvHdl,0),psHlp->psStd->pcKyw); return(siErr); } } } if (psHdl->isChk) { for (psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt) { if (psHlp->psFix->siOid==siOid) { if (psHlp->psVar->siCnt<psHlp->psFix->siMin) { if (psHlp->psFix->siMin<=1) { CLPERR(psHdl,CLPERR_SEM,"Parameter '%s.%s' not specified",fpcPat(pvHdl,0),psHlp->psStd->pcKyw); CLPERRADD(psHdl,0,"Please specify parameter:%s",""); vdClpPrnArg(pvHdl,psHdl->pfErr,1,psHlp->psStd->pcKyw,GETALI(psHlp),psHlp->psStd->siKwl,psHlp->psFix->siTyp,psHlp->psFix->pcHlp,psHlp->psFix->pcDft, CLPISF_SEL(psHlp->psStd->uiFlg),CLPISF_SEL(psHlp->psStd->uiFlg)); } else { CLPERR(psHdl,CLPERR_SEM,"Amount of occurrences (%d) of parameter '%s.%s' is smaller than required minimum amount (%d)",psHlp->psVar->siCnt,fpcPat(pvHdl,0),psHlp->psStd->pcKyw,psHlp->psFix->siMin); CLPERRADD(psHdl,0,"Please specify parameter additionally %d times:%s",""); vdClpPrnArg(pvHdl,psHdl->pfErr,1,psHlp->psStd->pcKyw,GETALI(psHlp),psHlp->psStd->siKwl,psHlp->psFix->siTyp,psHlp->psFix->pcHlp,psHlp->psFix->pcDft, CLPISF_SEL(psHlp->psStd->uiFlg),CLPISF_CON(psHlp->psStd->uiFlg)); } return(CLPERR_SEM); } } } } for (psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt,psSav++) *psHlp->psVar=*psSav; TRACE(psHdl->pfBld,"BUILD-END-MAIN-ARGUMENT\n"); return(CLP_OK); } static int siClpIniObj( void* pvHdl, const int siLev, const int siPos, TsSym* psArg, TsSym** ppDep, TsVar* psSav) { TsHdl* psHdl=(TsHdl*)pvHdl; const int siTyp=CLPTYP_OBJECT; const char* pcPat=fpcPat(pvHdl,siLev); TsSym* psHlp; (void)siPos; if (psArg->psFix->siTyp!=siTyp) { return CLPERR(psHdl,CLPERR_SEM,"The type (%s) of argument '%s.%s' don't match the expected type (%s)",apClpTyp[siTyp],pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psVar->siCnt>=psArg->psFix->siMax) { return CLPERR(psHdl,CLPERR_SEM,"Too many (>%d) occurrences of '%s.%s' with type '%s'",psArg->psFix->siMax,pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psDep==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of argument defined but pointer to parameter table not set",pcPat,psArg->psStd->pcKyw,apClpTyp[siTyp]); } if (psHdl->pfSaf!=NULL) { char acEnt[strlen(pcPat)+strlen(GETKYW(psArg))+2]; snprintf(acEnt,sizeof(acEnt),"%s.%s",pcPat,GETKYW(psArg)); if (psHdl->pfSaf(psHdl->pvGbl,psHdl->pvSaf,acEnt)) { return CLPERR(psHdl,CLPERR_AUT,"Authorization request for entity '%s' failed",acEnt); } } if (CLPISF_DYN(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+((((CLPISF_DLM(psArg->psStd->uiFlg))?2:1)*psArg->psFix->siSiz)),&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (15)",psArg->psVar->siLen+psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { if (psArg->psVar->siRst<psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_SIZ,"Rest of space (%d) is not big enough for argument '%s.%s' with type '%s'",psArg->psVar->siRst,pcPat,psArg->psStd->pcKyw,apClpTyp[siTyp]); } } for (psHlp=psArg->psDep;psHlp!=NULL;psHlp=psHlp->psNxt,psSav++) { *psSav=*psHlp->psVar; psHlp->psVar->pvDat=((char*)psArg->psVar->pvPtr)+psHlp->psFix->siOfs; psHlp->psVar->pvPtr=psHlp->psVar->pvDat; psHlp->psVar->siCnt=0; psHlp->psVar->siLen=0; psHlp->psVar->siInd=0; psHlp->psVar->siRst=CLPISF_DYN(psHlp->psStd->uiFlg)?0:psHlp->psFix->siSiz; if (CLPISF_FIX(psHlp->psStd->uiFlg)) psHlp->psVar->siRst*=psHlp->psFix->siMax; } TRACE(psHdl->pfBld,"%s BUILD-BEGIN-OBJECT-%s(PTR=%p CNT=%d LEN=%d RST=%d)\n", fpcPre(pvHdl,siLev),psArg->psStd->pcKyw,psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst); srprintc(&psHdl->pcLst,&psHdl->szLst,strlen(pcPat)+strlen(GETKYW(psArg)),"%s.%s(\n",pcPat,GETKYW(psArg)); psHdl->apPat[siLev]=psArg; *ppDep=psArg->psDep; return(psArg->psFix->siTyp); } static int siClpFinObj( void* pvHdl, const int siLev, const int siPos, TsSym* psArg, TsSym* psDep, const TsVar* psSav) { TsHdl* psHdl=(TsHdl*)pvHdl; const int siTyp=CLPTYP_OBJECT; TsSym* psHlp; const char* pcPat; int siErr,i; if (psArg->psFix->siTyp!=siTyp) { return CLPERR(psHdl,CLPERR_SEM,"The type (%s) of argument '%s.%s' don't match the expected type (%s)",apClpTyp[siTyp],fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psDep==NULL || psArg->psDep!=psDep) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of argument defined but pointer to parameter table not set",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,apClpTyp[siTyp]); } for (i=0,psHlp=psDep;psHlp!=NULL;psHlp=psHlp->psNxt,i++) { siErr=siClpSetDefault(pvHdl,siLev+1,i,psHlp); if (siErr<0) { CLPERRADD(psHdl,0,"Set default value for argument '%s.%s.%s' failed",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,psHlp->psStd->pcKyw); return(siErr); } } if (psHdl->isChk) { for (psHlp=psDep;psHlp!=NULL;psHlp=psHlp->psNxt) { if (psHlp->psVar->siCnt<psHlp->psFix->siMin) { if (psHlp->psFix->siMin<=1) { CLPERR(psHdl,CLPERR_SEM,"Parameter '%s.%s.%s' not specified",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,psHlp->psStd->pcKyw); CLPERRADD(psHdl,0,"Please specify parameter:%s",""); vdClpPrnArg(pvHdl,psHdl->pfErr,1,psHlp->psStd->pcKyw,GETALI(psHlp),psHlp->psStd->siKwl,psHlp->psFix->siTyp,psHlp->psFix->pcHlp,psHlp->psFix->pcDft, CLPISF_SEL(psHlp->psStd->uiFlg),CLPISF_CON(psHlp->psStd->uiFlg)); } else { CLPERR(psHdl,CLPERR_SEM,"Amount of occurrences (%d) of parameter '%s.%s.%s' is smaller than required minimum amount (%d)",psDep->psVar->siCnt,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,psHlp->psStd->pcKyw,psHlp->psFix->siMin); CLPERRADD(psHdl,0,"Please specify parameter additionally %d times:%s",""); vdClpPrnArg(pvHdl,psHdl->pfErr,1,psHlp->psStd->pcKyw,GETALI(psHlp),psHlp->psStd->siKwl,psHlp->psFix->siTyp,psHlp->psFix->pcHlp,psHlp->psFix->pcDft, CLPISF_SEL(psHlp->psStd->uiFlg),CLPISF_CON(psHlp->psStd->uiFlg)); } return(CLPERR_SEM); } } } for (psHlp=psDep;psHlp!=NULL;psHlp=psHlp->psNxt,psSav++) *psHlp->psVar=*psSav; psArg->psVar->pvPtr=((char*)psArg->psVar->pvPtr)+psArg->psFix->siSiz; psArg->psVar->siLen+=psArg->psFix->siSiz; psArg->psVar->siRst-=CLPISF_DYN(psArg->psStd->uiFlg)?0:psArg->psFix->siSiz; psArg->psVar->siCnt++; TRACE(psHdl->pfBld,"%s BUILD-END-OBJECT-%s(PTR=%p CNT=%d LEN=%d RST=%d)\n", fpcPre(pvHdl,siLev),psArg->psStd->pcKyw,psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst); pcPat=fpcPat(pvHdl,siLev); srprintc(&psHdl->pcLst,&psHdl->szLst,strlen(pcPat)+strlen(GETKYW(psArg)),"%s.%s)\n",pcPat,GETKYW(psArg)); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psVar->siCnt,psArg->psFix->psCnt,FALSE); if (siErr<0) return(siErr); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psFix->siSiz,psArg->psFix->psEln,TRUE); if (siErr<0) return(siErr); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psVar->siLen,psArg->psFix->psTln,FALSE); if (siErr<0) return(siErr); if(psArg->psFix->siOid){ siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psFix->siOid,psArg->psFix->psOid,TRUE); if (siErr<0) return(siErr); } return(psArg->psFix->siTyp); } static int siClpIniOvl( void* pvHdl, const int siLev, const int siPos, TsSym* psArg, TsSym** ppDep, TsVar* psSav) { TsHdl* psHdl=(TsHdl*)pvHdl; const int siTyp=CLPTYP_OVRLAY; const char* pcPat=fpcPat(pvHdl,siLev); TsSym* psHlp; (void)siPos; if (psArg->psFix->siTyp!=siTyp) { return CLPERR(psHdl,CLPERR_SEM,"The type (%s) of argument '%s.%s' don't match the expected type (%s)",apClpTyp[siTyp],pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psVar->siCnt>=psArg->psFix->siMax) { return CLPERR(psHdl,CLPERR_SEM,"Too many (>%d) occurrences of '%s.%s' with type '%s'",psArg->psFix->siMax,pcPat,psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psDep==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of argument defined but pointer to parameter table not set",pcPat,psArg->psStd->pcKyw,apClpTyp[siTyp]); } if (psHdl->pfSaf!=NULL) { char acEnt[strlen(pcPat)+strlen(GETKYW(psArg))+2]; snprintf(acEnt,sizeof(acEnt),"%s.%s",pcPat,GETKYW(psArg)); if (psHdl->pfSaf(psHdl->pvGbl,psHdl->pvSaf,acEnt)) { return CLPERR(psHdl,CLPERR_AUT,"Authorization request for entity '%s' failed",acEnt); } } if (CLPISF_DYN(psArg->psStd->uiFlg)) { void** ppDat=(void**)psArg->psVar->pvDat; (*ppDat)=pvClpAlloc(pvHdl,(*ppDat),psArg->psVar->siLen+((((CLPISF_DLM(psArg->psStd->uiFlg))?2:1)*psArg->psFix->siSiz)),&psArg->psVar->siInd); if ((*ppDat)==NULL) { return CLPERR(psHdl,CLPERR_MEM,"Dynamic memory allocation (%d) for argument '%s.%s' failed (16)",psArg->psVar->siLen+psArg->psFix->siSiz,pcPat,psArg->psStd->pcKyw); } psArg->psVar->pvPtr=((char*)(*ppDat))+psArg->psVar->siLen; } else { if (psArg->psVar->siRst<psArg->psFix->siSiz) { return CLPERR(psHdl,CLPERR_SIZ,"Rest of space (%d) is not big enough for argument '%s.%s' with type '%s'",psArg->psVar->siRst,pcPat,psArg->psStd->pcKyw,apClpTyp[siTyp]); } } for (psHlp=psArg->psDep;psHlp!=NULL;psHlp=psHlp->psNxt,psSav++) { *psSav=*psHlp->psVar; psHlp->psVar->pvDat=(char*)psArg->psVar->pvPtr; psHlp->psVar->pvPtr=psHlp->psVar->pvDat; psHlp->psVar->siCnt=0; psHlp->psVar->siLen=0; psHlp->psVar->siRst=CLPISF_DYN(psHlp->psStd->uiFlg)?0:psHlp->psFix->siSiz; if (CLPISF_FIX(psHlp->psStd->uiFlg)) psHlp->psVar->siRst*=psHlp->psFix->siMax; } TRACE(psHdl->pfBld,"%s BUILD-BEGIN-OVERLAY-%s(PTR=%p CNT=%d LEN=%d RST=%d)\n", fpcPre(pvHdl,siLev),psArg->psStd->pcKyw,psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst); psHdl->apPat[siLev]=psArg; *ppDep=psArg->psDep; return(psArg->psFix->siTyp); } static int siClpFinOvl( void* pvHdl, const int siLev, const int siPos, TsSym* psArg, TsSym* psDep, const TsVar* psSav, const int siOid) { TsHdl* psHdl=(TsHdl*)pvHdl; const int siTyp=CLPTYP_OVRLAY; TsSym* psHlp; int siErr,i; if (psArg->psFix->siTyp!=siTyp) { return CLPERR(psHdl,CLPERR_SEM,"The type (%s) of argument '%s.%s' don't match the expected type (%s)",apClpTyp[siTyp],fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,apClpTyp[psArg->psFix->siTyp]); } if (psArg->psDep==NULL || psArg->psDep!=psDep) { return CLPERR(psHdl,CLPERR_TAB,"Keyword (%s.%s) and type (%s) of argument defined but pointer to parameter table not set",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,apClpTyp[siTyp]); } for (i=0,psHlp=psDep;psHlp!=NULL;psHlp=psHlp->psNxt,i++) { if (psHlp->psFix->siOid==siOid) { siErr=siClpSetDefault(pvHdl,siLev+1,i,psHlp); if (siErr<0) { CLPERRADD(psHdl,0,"Set default value for argument '%s.%s.%s' failed",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,psHlp->psStd->pcKyw); return(siErr); } } } if (psHdl->isChk) { for (psHlp=psDep;psHlp!=NULL;psHlp=psHlp->psNxt) { if (psHlp->psFix->siOid==siOid) { if (psHlp->psVar->siCnt<psHlp->psFix->siMin) { if (psHlp->psFix->siMin<=1) { CLPERR(psHdl,CLPERR_SEM,"Parameter '%s.%s.%s' not specified",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,psHlp->psStd->pcKyw); CLPERRADD(psHdl,0,"Please specify parameter:%s",""); vdClpPrnArg(pvHdl,psHdl->pfErr,1,psHlp->psStd->pcKyw,GETALI(psHlp),psHlp->psStd->siKwl,psHlp->psFix->siTyp,psHlp->psFix->pcHlp,psHlp->psFix->pcDft, CLPISF_SEL(psHlp->psStd->uiFlg),CLPISF_CON(psHlp->psStd->uiFlg)); } else { CLPERR(psHdl,CLPERR_SEM,"Amount of occurrences (%d) of parameter '%s.%s.%s' is smaller than required minimum amount (%d)",psDep->psVar->siCnt,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,psHlp->psStd->pcKyw,psHlp->psFix->siMin); CLPERRADD(psHdl,0,"Please specify parameter additionally %d times:%s",""); vdClpPrnArg(pvHdl,psHdl->pfErr,1,psHlp->psStd->pcKyw,GETALI(psHlp),psHlp->psStd->siKwl,psHlp->psFix->siTyp,psHlp->psFix->pcHlp,psHlp->psFix->pcDft, CLPISF_SEL(psHlp->psStd->uiFlg),CLPISF_CON(psHlp->psStd->uiFlg)); } return(CLPERR_SEM); } } } } for (psHlp=psDep;psHlp!=NULL;psHlp=psHlp->psNxt,psSav++) *psHlp->psVar=*psSav; psArg->psVar->pvPtr=((char*)psArg->psVar->pvPtr)+psArg->psFix->siSiz; psArg->psVar->siLen+=psArg->psFix->siSiz; psArg->psVar->siRst-=CLPISF_DYN(psArg->psStd->uiFlg)?0:psArg->psFix->siSiz; psArg->psVar->siCnt++; TRACE(psHdl->pfBld,"%s BUILD-END-OVERLAY-%s(PTR=%p CNT=%d LEN=%d RST=%d)\n", fpcPre(pvHdl,siLev),psArg->psStd->pcKyw,psArg->psVar->pvPtr,psArg->psVar->siCnt,psArg->psVar->siLen,psArg->psVar->siRst); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psVar->siCnt,psArg->psFix->psCnt,FALSE); if (siErr<0) return(siErr); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psFix->siSiz,psArg->psFix->psEln,TRUE); if (siErr<0) return(siErr); siErr=siClpBldLnk(pvHdl,siLev,siPos,psArg->psVar->siLen,psArg->psFix->psTln,FALSE); if (siErr<0) return(siErr); if(siOid){ siErr=siClpBldLnk(pvHdl,siLev,siPos,siOid,psArg->psFix->psOid,TRUE); if (siErr<0) return(siErr); } return(psArg->psFix->siTyp); } /**********************************************************************/ static int siClpSetDefault( void* pvHdl, const int siLev, const int siPos, TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; TsSym* psDep=NULL; TsSym* psVal=NULL; size_t szVal=CLPINI_VALSIZ; char* pcVal=(char*)calloc(1,szVal); char acSrc[strlen(psHdl->pcSrc)+1]; char acLex[strlen(psHdl->pcLex)+1]; TsVar asSav[CLPMAX_TABCNT]; int siErr,siRow,siTok; const char* pcCur; const char* pcInp; const char* pcOld; const char* pcRow; if (pcVal==NULL) return(CLPERR(psHdl,CLPERR_MEM,"Allocation of memory to store the value expression failed")); if (CLPISF_ARG(psArg->psStd->uiFlg) && psArg->psVar->siCnt==0 && psArg->psFix->pcDft!=NULL && strlen(psArg->psFix->pcDft)) { TRACE(psHdl->pfPrs,"SUPPLEMENT-LIST-PARSER-BEGIN(%s.%s=%s)\n",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,psArg->psFix->pcDft); strcpy(acSrc,psHdl->pcSrc); strcpy(acLex,psHdl->pcLex); srprintf(&psHdl->pcSrc,&psHdl->szSrc,strlen(psArg->psFix->pcSrc),"%s",psArg->psFix->pcSrc); pcInp=psHdl->pcInp; psHdl->pcInp=psArg->psFix->pcDft; pcCur=psHdl->pcCur; psHdl->pcCur=psHdl->pcInp; pcOld=psHdl->pcOld; psHdl->pcOld=psHdl->pcInp; pcRow=psHdl->pcRow; psHdl->pcRow=psHdl->pcInp; siRow=psHdl->siRow; psHdl->siRow=psArg->psFix->siRow; siTok=psHdl->siTok; psHdl->siBuf++; for (psHdl->siTok=siClpScnSrc(pvHdl,psArg->psFix->siTyp,psArg);psHdl->siTok>=0 && psHdl->siTok!=CLPTOK_END; psHdl->siTok=siClpScnSrc(pvHdl,psArg->psFix->siTyp,psArg)) { if (psHdl->siTok==CLPTOK_KYW) { if (psArg->psFix->siTyp==CLPTYP_OBJECT) { if (strxcmp(psHdl->isCas,psHdl->pcLex,"INIT",0,0,FALSE)!=0) { siErr=CLPERR(psHdl,CLPERR_SYN,"Keyword (%s) in default / property definition for object '%s.%s' is not 'INIT'",psHdl->pcLex,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); free(pcVal); return(siErr); } siErr=siClpIniObj(pvHdl,siLev,siPos,psArg,&psDep,asSav); if (siErr<0) { free(pcVal); return(siErr); } siErr=siClpFinObj(pvHdl,siLev,siPos,psArg,psDep,asSav); if (siErr<0) { free(pcVal); return(siErr); } } else if (psArg->psFix->siTyp==CLPTYP_OVRLAY) { siErr=siClpIniOvl(pvHdl,siLev,siPos,psArg,&psDep,asSav); if (siErr<0) { free(pcVal); return(siErr); } siErr=siClpSymFnd(pvHdl,siLev+1,psHdl->pcLex,psDep,&psVal,NULL); if (siErr<0) { free(pcVal); return(siErr); } siErr=siClpFinOvl(pvHdl,siLev,siPos,psArg,psDep,asSav,psVal->psFix->siOid); if (siErr<0) { free(pcVal); return(siErr); } } else if (psArg->psFix->siTyp==CLPTYP_SWITCH) { if (strxcmp(psHdl->isCas,psHdl->pcLex,"ON",0,0,FALSE)!=0 && strxcmp(psHdl->isCas,psHdl->pcLex,"OFF",0,0,FALSE)!=0) { siErr=CLPERR(psHdl,CLPERR_SYN,"Keyword (%s) in default / property definition for switch '%s.%s' is not 'ON' or 'OFF'",psHdl->pcLex,fpcPat(pvHdl,siLev),psArg->psStd->pcKyw); free(pcVal); return(siErr); } if (strxcmp(psHdl->isCas,psHdl->pcLex,"ON",0,0,FALSE)==0) { siErr=siClpBldSwt(pvHdl,siLev,siPos,psArg); if (siErr<0) { free(pcVal); return(siErr); } } } else { siErr=siClpPrsExp(pvHdl,siLev,siPos,FALSE,psArg,&szVal,&pcVal); if (siErr<0) { free(pcVal); return(siErr); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d LIT(%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,isPrnLex(psArg,pcVal)); siErr=siClpBldLit(pvHdl,siLev,siPos,psArg,pcVal); if (siErr<0) { free(pcVal); return(siErr); } } } else { siErr=siClpPrsExp(pvHdl,siLev,siPos,FALSE,psArg,&szVal,&pcVal); if (siErr<0) { free(pcVal); return(siErr); } TRACE(psHdl->pfPrs,"%s PARSER(LEV=%d POS=%d LIT(%s))\n",fpcPre(pvHdl,siLev),siLev,siPos,isPrnLex(psArg,pcVal)); siErr=siClpBldLit(pvHdl,siLev,siPos,psArg,pcVal); if (siErr<0) { free(pcVal); return(siErr); } } } if (psHdl->siTok<0) { free(pcVal); return(psHdl->siTok); } psHdl->siBuf--; psHdl->siTok=siTok; strcpy(psHdl->pcLex,acLex); strcpy(psHdl->pcSrc,acSrc); psHdl->pcInp=pcInp; psHdl->pcCur=pcCur; psHdl->pcOld=pcOld; psHdl->pcRow=pcRow; psHdl->siRow=siRow; TRACE(psHdl->pfPrs,"SUPPLEMENT-LIST-PARSER-END(%s.%s=%s)\n",fpcPat(pvHdl,siLev),psArg->psStd->pcKyw,psArg->psFix->pcDft); } free(pcVal); return(CLP_OK); } /**********************************************************************/ static void vdClpPrnArg( void* pvHdl, FILE* pfOut, const int siLev, const char* pcKyw, const char* pcAli, const int siKwl, const int siTyp, const char* pcHlp, const char* pcDft, const unsigned int isSel, const unsigned int isCon) { TsHdl* psHdl=(TsHdl*)pvHdl; const char* p=fpcPre(pvHdl,siLev); int i,siLen; const char* a="TYPE"; const char* b=(isSel)?"SELECTION":((isCon)?"KEYWORD":apClpTyp[siTyp]); if (pcAli!=NULL && *pcAli) { a="ALIAS"; b=pcAli; } if (pfOut!=NULL) { if (psHdl->isCas) { if (pcDft!=NULL && *pcDft) { fprintf(pfOut,"%s %s (%s: %s) - ",p,pcKyw,a,b); efprintf(pfOut,"%s",pcHlp); fprintf(pfOut," (PROPERTY: %c%s%c)\n",C_SBO,pcDft,C_SBC); } else { fprintf(pfOut,"%s %s (%s: %s) - ",p,pcKyw,a,b); efprintf(pfOut,"%s\n",pcHlp); } fprintf(pfOut,"%s ",p); for (i=0;i<siKwl;i++) fprintf(pfOut,"%c",C_CRT); fprintf(pfOut,"\n"); } else { siLen=strlen(pcKyw); fprintf(pfOut,"%s ",p); for (i=0;i<siKwl;i++) fprintf(pfOut,"%c",toupper(pcKyw[i])); for (/*i=i*/;i<siLen;i++) fprintf(pfOut,"%c",tolower(pcKyw[i])); if (pcDft!=NULL && *pcDft) { fprintf(pfOut," (%s: %s) - ",a,b); efprintf(pfOut,"%s",pcHlp); fprintf(pfOut," (PROPERTY: %c%s%c)\n",C_SBO,pcDft,C_SBC); } else { fprintf(pfOut," (%s: %s) - ",a,b); efprintf(pfOut,"%s\n",pcHlp); } } } } static void vdClpPrnArgTab( void* pvHdl, FILE* pfOut, const int siLev, int siTyp, const TsSym* psTab) { const TsSym* psHlp; if (psTab!=NULL && psTab->psHih!=NULL && psTab->psStd!=NULL) { if (CLPISF_CON(psTab->psStd->uiFlg)) { if (siTyp<0) siTyp=psTab->psHih->psFix->siTyp; if (CLPISF_SEL(psTab->psHih->psStd->uiFlg)==FALSE) { if (pfOut!=NULL) { if (siTyp>=0) { fprintf(pfOut,"%s Enter a value (TYPE: %s) or use one of the keywords below:\n",fpcPre(pvHdl,siLev),apClpTyp[siTyp]); } else { fprintf(pfOut,"%s Enter a value or use one of the keywords below:\n",fpcPre(pvHdl,siLev)); } } } } } for (psHlp=psTab;psHlp!=NULL && psHlp->psStd!=NULL;psHlp=psHlp->psNxt) { if ((psHlp->psFix->siTyp==siTyp || siTyp<0) && !CLPISF_LNK(psHlp->psStd->uiFlg) && !CLPISF_HID(psHlp->psStd->uiFlg)) { vdClpPrnArg(pvHdl,pfOut,siLev,psHlp->psStd->pcKyw,GETALI(psHlp),psHlp->psStd->siKwl,psHlp->psFix->siTyp,psHlp->psFix->pcHlp,psHlp->psFix->pcDft, CLPISF_SEL(psHlp->psStd->uiFlg),CLPISF_CON(psHlp->psStd->uiFlg)); } } } static void vdClpPrnOpt( FILE* pfOut, const char* pcSep, const int siTyp, const TsSym* psTab) { int k=0; const TsSym* psHlp; if (pfOut!=NULL && psTab!=NULL) { for (psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt) { if ((psHlp->psFix->siTyp==siTyp || siTyp<0) && !CLPISF_LNK(psHlp->psStd->uiFlg)) { if (k) fprintf(pfOut,"%s",pcSep); fprintf(pfOut,"%s",psHlp->psStd->pcKyw); k++; } } } } static void vdClpPrnAli( FILE* pfOut, const char* pcSep, const TsSym* psTab) { const TsSym* psHlp; if (pfOut!=NULL && psTab!=NULL) { fprintf(pfOut,"%s",psTab->psStd->pcKyw); for (psHlp=psTab->psNxt;psHlp!=NULL;psHlp=psHlp->psNxt) { if (CLPISF_ALI(psHlp->psStd->uiFlg) && psHlp->psStd->psAli==psTab) { fprintf(pfOut,"%s",pcSep); fprintf(pfOut,"%s",psHlp->psStd->pcKyw); } } } } static int siClpPrnCmd( void* pvHdl, FILE* pfOut, const int siCnt, const int siLev, const int siDep, const TsSym* psArg, const TsSym* psTab, const int isSkr, const int isMin) { TsHdl* psHdl=(TsHdl*)pvHdl; int siErr,k=0; const char* pcHlp=NULL; const TsSym* psHlp; const char* pcSep; if (psTab==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Argument table not defined%s",""); } if (psTab->psBak!=NULL) { return CLPERR(psHdl,CLPERR_INT,"Entry '%s.%s' not at beginning of a table",fpcPat(pvHdl,siLev),psTab->psStd->pcKyw); } if (pfOut!=NULL) { if (siLev<siDep || siDep>9) { if (psArg==NULL) { if (psHdl->isOvl) { pcSep=psHdl->pcOpt; if (siCnt==0) { fprintf(pfOut,"%s.%c",psHdl->pcCmd,C_CBO); if (isSkr) k++; } } else { pcSep=psHdl->pcEnt; if (siCnt==0) { fprintf(pfOut,"%s(",psHdl->pcCmd); if (isSkr) k++; } } if (isSkr) k++; } else { if (psArg->psFix->siTyp==CLPTYP_OVRLAY) { pcSep=psHdl->pcOpt; if (siCnt==0) { fprintf(pfOut,"%s.%c",fpcPat(pvHdl,siLev),C_CBO); if (isSkr) k++; } } else { pcSep=psHdl->pcEnt; if (siCnt==0) { fprintf(pfOut,"%s(",fpcPat(pvHdl,siLev)); if (isSkr) k++; } } } for (psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt) { if (CLPISF_CMD(psHlp->psStd->uiFlg) && !CLPISF_LNK(psHlp->psStd->uiFlg) && !CLPISF_ALI(psHlp->psStd->uiFlg)) { if (isSkr) { if (k) fprintf(pfOut,"\n%s ",fpcPre(pvHdl,siLev)); else fprintf(pfOut,"%s " ,fpcPre(pvHdl,siLev)); if (isMin) { if (psHlp->psFix->siMin) fprintf(pfOut,"%c ",C_EXC); else fprintf(pfOut,"%c ",'?'); } } else { if (k) fprintf(pfOut,"%s",pcSep); if (isMin) { if (psHlp->psFix->siMin) fprintf(pfOut,"%c",C_EXC); else fprintf(pfOut,"%c",'?'); } } k++; switch (psHlp->psFix->siTyp) { case CLPTYP_SWITCH: if (psHlp->psFix->siMax==1) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp); } else { return CLPERR(psHdl,CLPERR_TAB,"Maximum amount of entries (%d) for parameter '%s' not valid",psHlp->psFix->siMax,psHlp->psStd->pcKyw); } break; case CLPTYP_NUMBER: if (psHlp->psFix->siMax==1) { if (CLPISF_SEL(psHlp->psStd->uiFlg)) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp); if (CLPISF_DEF(psHlp->psStd->uiFlg)) { fprintf(pfOut,"%c%s",C_SBO,CLP_ASSIGNMENT); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); fprintf(pfOut,"%c",C_SBC); } else { fprintf(pfOut,CLP_ASSIGNMENT); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); } } else { if (psHlp->psDep!=NULL) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp); if (CLPISF_DEF(psHlp->psStd->uiFlg)) { fprintf(pfOut,"%c%snum%s",C_SBO,CLP_ASSIGNMENT,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); fprintf(pfOut,"%c",C_SBC); } else { fprintf(pfOut,"%snum%s",CLP_ASSIGNMENT,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); } } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp); if (CLPISF_DEF(psHlp->psStd->uiFlg)) { fprintf(pfOut,"%c%snum%c",C_SBO,CLP_ASSIGNMENT,C_SBC); } else { fprintf(pfOut,"%snum",CLP_ASSIGNMENT); } } } } else if (psHlp->psFix->siMax>1) { if (CLPISF_SEL(psHlp->psStd->uiFlg)) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%c",C_SBO); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); fprintf(pfOut,"...%c",C_SBC); } else { if (psHlp->psDep!=NULL) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%cnum%s",C_SBO,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); fprintf(pfOut,"...%c",C_SBC); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%cnum...%c",C_SBO,C_SBC); } } } else { return CLPERR(psHdl,CLPERR_TAB,"Maximum amount of entries (%d) for parameter '%s' not valid",psHlp->psFix->siMax,psHlp->psStd->pcKyw); } break; case CLPTYP_FLOATN: if (psHlp->psFix->siMax==1) { if (CLPISF_SEL(psHlp->psStd->uiFlg)) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,CLP_ASSIGNMENT); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); } else { if (psHlp->psDep!=NULL) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%sflt%s",CLP_ASSIGNMENT,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%sflt",CLP_ASSIGNMENT); } } } else if (psHlp->psFix->siMax>1) { if (CLPISF_SEL(psHlp->psStd->uiFlg)) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%c",C_SBO); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); fprintf(pfOut,"...%c",C_SBC); } else { if (psHlp->psDep!=NULL) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%cflt%s",C_SBO,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); fprintf(pfOut,"...%c",C_SBC); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%cflt...%c",C_SBO,C_SBC); } } } else { return CLPERR(psHdl,CLPERR_TAB,"Maximum amount of entries (%d) for parameter '%s' not valid",psHlp->psFix->siMax,psHlp->psStd->pcKyw); } break; case CLPTYP_STRING: if (CLPISF_BIN(psHlp->psStd->uiFlg)) { if (CLPISF_HEX(psHlp->psStd->uiFlg)) { pcHlp="bin-hex"; } else if (CLPISF_ASC(psHlp->psStd->uiFlg)) { pcHlp="bin-ascii"; } else if (CLPISF_EBC(psHlp->psStd->uiFlg)) { pcHlp="bin-ebcdic"; } else if (CLPISF_CHR(psHlp->psStd->uiFlg)) { pcHlp="bin-char"; } else { pcHlp="bin"; } } else pcHlp="str"; if (psHlp->psFix->siMax==1) { if (CLPISF_SEL(psHlp->psStd->uiFlg)) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,CLP_ASSIGNMENT); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); } else { if (psHlp->psDep!=NULL) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%s'%s'%s",CLP_ASSIGNMENT,pcHlp,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%s'%s'",CLP_ASSIGNMENT,pcHlp); } } } else if (psHlp->psFix->siMax>1) { if (CLPISF_SEL(psHlp->psStd->uiFlg)) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%c",C_SBO); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); fprintf(pfOut,"...%c",C_SBC); } else { if (psHlp->psDep!=NULL) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%c'%s'%s",C_SBO,pcHlp,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psHlp->psFix->siTyp,psHlp->psDep); fprintf(pfOut,"...%c",C_SBC); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%c'%s'...%c",C_SBO,pcHlp,C_SBC); } } } else { return CLPERR(psHdl,CLPERR_TAB,"Maximum amount of entries (%d) for parameter '%s' not valid",psHlp->psFix->siMax,psHlp->psStd->pcKyw); } break; case CLPTYP_OBJECT: if (psHlp->psDep==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Argument table for object '%s' not defined",psHlp->psStd->pcKyw); } if (psHlp->psFix->siMax==1) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp); fprintf(pfOut,"("); if (isSkr && (siLev+1<siDep || siDep>9)) fprintf(pfOut,"\n"); psHdl->apPat[siLev]=psHlp; siErr=siClpPrnCmd(pvHdl,pfOut,siCnt+1,siLev+1,siDep,psHlp,psHlp->psDep,isSkr,isMin); if (siErr<0) return(siErr); fprintf(pfOut,")"); } else if (psHlp->psFix->siMax>1) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp); fprintf(pfOut,"%c(",C_SBO); if (isSkr && (siLev+1<siDep || siDep>9)) fprintf(pfOut,"\n"); psHdl->apPat[siLev]=psHlp; siErr=siClpPrnCmd(pvHdl,pfOut,siCnt+1,siLev+1,siDep,psHlp,psHlp->psDep,isSkr,isMin); if (siErr<0) return(siErr); fprintf(pfOut,")...%c",C_SBC); } else { return CLPERR(psHdl,CLPERR_TAB,"Maximum amount of entries (%d) for parameter '%s' not valid",psHlp->psFix->siMax,psHlp->psStd->pcKyw); } break; case CLPTYP_OVRLAY: if (psHlp->psDep==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Argument table for object '%s' not defined",psHlp->psStd->pcKyw); } if (psHlp->psFix->siMax==1) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,".%c",C_CBO); if (isSkr && (siLev+1<siDep || siDep>9)) fprintf(pfOut,"\n"); psHdl->apPat[siLev]=psHlp; siErr=siClpPrnCmd(pvHdl,pfOut,siCnt+1,siLev+1,siDep,psHlp,psHlp->psDep,isSkr,isMin); if (siErr<0) return(siErr); fprintf(pfOut,"%c",C_CBC); } else if (psHlp->psFix->siMax>1) { vdClpPrnAli(pfOut,psHdl->pcOpt,psHlp);fprintf(pfOut,"%c%c",C_SBO,C_CBO); if (isSkr && (siLev+1<siDep || siDep>9)) fprintf(pfOut,"\n"); psHdl->apPat[siLev]=psHlp; siErr=siClpPrnCmd(pvHdl,pfOut,siCnt+1,siLev+1,siDep,psHlp,psHlp->psDep,isSkr,isMin); if (siErr<0) return(siErr); fprintf(pfOut,"%c...%c",C_CBC,C_SBC); } else { return CLPERR(psHdl,CLPERR_TAB,"Maximum amount of entries (%d) for parameter '%s' not valid",psHlp->psFix->siMax,psHlp->psStd->pcKyw); } break; default: return CLPERR(psHdl,CLPERR_TYP,"Type (%d) of parameter '%s' not supported",psHlp->psFix->siTyp,psHlp->psStd->pcKyw); } } } if (psArg==NULL) { if (psHdl->isOvl) { if (siCnt==0) fprintf(pfOut,"%c",C_CBC); } else { if (siCnt==0) fprintf(pfOut,"%c",')'); } } else { if (psArg->psFix->siTyp==CLPTYP_OVRLAY) { if (siCnt==0) fprintf(pfOut,"%c",C_CBC); } else { if (siCnt==0) fprintf(pfOut,"%c",')'); } } } } return (CLP_OK); } static int siClpPrnHlp( void* pvHdl, FILE* pfOut, const int isAli, const int siLev, const int siDep, const int siTyp, const TsSym* psTab, const int isFlg) { TsHdl* psHdl=(TsHdl*)pvHdl; const TsSym* psHlp; int siErr; if (psTab==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Argument table not defined%s",""); } if (psTab->psBak!=NULL) { return CLPERR(psHdl,CLPERR_INT,"Entry '%s.%s' not at beginning of a table",fpcPat(pvHdl,siLev),psTab->psStd->pcKyw); } if (pfOut!=NULL) { if (siLev<siDep || siDep>9) { if (isFlg) { if (siTyp>=0) { fprintf(pfOut,"%s Enter a value (TYPE: %s) or use one of the keywords below:\n",fpcPre(pvHdl,siLev),apClpTyp[siTyp]); } else { fprintf(pfOut,"%s Enter a value or use one of the keywords below:\n",fpcPre(pvHdl,siLev)); } } for (psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt) { if ((psHlp->psFix->siTyp==siTyp || siTyp<0) && CLPISF_CMD(psHlp->psStd->uiFlg) && !CLPISF_LNK(psHlp->psStd->uiFlg)) { if (!CLPISF_ALI(psHlp->psStd->uiFlg) || (CLPISF_ALI(psHlp->psStd->uiFlg) && isAli)) { vdClpPrnArg(pvHdl,pfOut,siLev,psHlp->psStd->pcKyw,GETALI(psHlp),psHlp->psStd->siKwl,psHlp->psFix->siTyp,psHlp->psFix->pcHlp,psHlp->psFix->pcDft, CLPISF_SEL(psHlp->psStd->uiFlg),CLPISF_CON(psHlp->psStd->uiFlg)); if (psHlp->psFix->siTyp==CLPTYP_NUMBER && CLPISF_DEF(psHlp->psStd->uiFlg)) { fprintf(pfOut,"%s If you type the keyword without an assignment of a value, the default (%d) is used\n",fpcPre(pvHdl,siLev+1),psHlp->psFix->siOid); } if (psHlp->psDep!=NULL) { if (psHlp->psFix->siTyp==CLPTYP_OBJECT || psHlp->psFix->siTyp==CLPTYP_OVRLAY) { psHdl->apPat[siLev]=psHlp; siErr=siClpPrnHlp(pvHdl,pfOut,isAli,siLev+1,siDep,-1,psHlp->psDep,FALSE); if (siErr<0) return(siErr); } else { psHdl->apPat[siLev]=psHlp; if (CLPISF_SEL(psHlp->psStd->uiFlg)) { siErr=siClpPrnHlp(pvHdl,pfOut,isAli,siLev+1,siDep,psHlp->psFix->siTyp,psHlp->psDep,FALSE); if (siErr<0) return(siErr); } else { siErr=siClpPrnHlp(pvHdl,pfOut,isAli,siLev+1,siDep,psHlp->psFix->siTyp,psHlp->psDep,TRUE); if (siErr<0) return(siErr); } } } } } } } } return (CLP_OK); } static int siClpPrnSyn( void* pvHdl, FILE* pfOut, const int isPat, const int siLev, const TsSym* psArg) { TsHdl* psHdl=(TsHdl*)pvHdl; const char* pcHlp=NULL; int siErr; if (psArg==NULL) { return CLPERR(psHdl,CLPERR_TAB,"Argument not defined%s",""); } if (pfOut!=NULL) { if (isPat) { fprintf(pfOut,"%s.",fpcPat(pvHdl,siLev)); } switch (psArg->psFix->siTyp) { case CLPTYP_SWITCH: vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); break; case CLPTYP_NUMBER: if (psArg->psFix->siMax==1) { if (CLPISF_SEL(psArg->psStd->uiFlg)) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,CLP_ASSIGNMENT); vdClpPrnOpt(pfOut,psHdl->pcOpt,psArg->psFix->siTyp,psArg->psDep); } else { if (psArg->psDep!=NULL) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%snum%s",CLP_ASSIGNMENT,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psArg->psFix->siTyp,psArg->psDep); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%snum",CLP_ASSIGNMENT); } } } else { if (CLPISF_SEL(psArg->psStd->uiFlg)) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%c",C_SBO); vdClpPrnOpt(pfOut,psHdl->pcOpt,psArg->psFix->siTyp,psArg->psDep); fprintf(pfOut,"...%c",C_SBC); } else { if (psArg->psDep!=NULL) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%cnum%s",C_SBO,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psArg->psFix->siTyp,psArg->psDep); fprintf(pfOut,"...%c",C_SBC); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%cnum...%c",C_SBO,C_SBC); } } } break; case CLPTYP_FLOATN: if (psArg->psFix->siMax==1) { if (CLPISF_SEL(psArg->psStd->uiFlg)) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,CLP_ASSIGNMENT); vdClpPrnOpt(pfOut,psHdl->pcOpt,psArg->psFix->siTyp,psArg->psDep); } else { if (psArg->psDep!=NULL) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%sflt%s",CLP_ASSIGNMENT,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psArg->psFix->siTyp,psArg->psDep); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%sflt",CLP_ASSIGNMENT); } } } else { if (CLPISF_SEL(psArg->psStd->uiFlg)) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%c",C_SBO); vdClpPrnOpt(pfOut,psHdl->pcOpt,psArg->psFix->siTyp,psArg->psDep); fprintf(pfOut,"...%c",C_SBC); } else { if (psArg->psDep!=NULL) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%cflt%s",C_SBO,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psArg->psFix->siTyp,psArg->psDep); fprintf(pfOut,"...%c",C_SBC); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%cflt...%c",C_SBO,C_SBC); } } } break; case CLPTYP_STRING: if (CLPISF_BIN(psArg->psStd->uiFlg)) { if (CLPISF_HEX(psArg->psStd->uiFlg)) { pcHlp="bin-hex"; } else if (CLPISF_ASC(psArg->psStd->uiFlg)) { pcHlp="bin-ascii"; } else if (CLPISF_EBC(psArg->psStd->uiFlg)) { pcHlp="bin-ebcdic"; } else if (CLPISF_CHR(psArg->psStd->uiFlg)) { pcHlp="bin-char"; } else { pcHlp="bin"; } } else pcHlp="str"; if (psArg->psFix->siMax==1) { if (CLPISF_SEL(psArg->psStd->uiFlg)) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,CLP_ASSIGNMENT); vdClpPrnOpt(pfOut,psHdl->pcOpt,psArg->psFix->siTyp,psArg->psDep); } else { if (psArg->psDep!=NULL) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%s'%s'%s",CLP_ASSIGNMENT,pcHlp,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psArg->psFix->siTyp,psArg->psDep); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%s'%s'",CLP_ASSIGNMENT,pcHlp); } } } else { if (CLPISF_SEL(psArg->psStd->uiFlg)) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%c",C_SBO); vdClpPrnOpt(pfOut,psHdl->pcOpt,psArg->psFix->siTyp,psArg->psDep); fprintf(pfOut,"...%c",C_SBC); } else { if (psArg->psDep!=NULL) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%c'%s'%s",C_SBO,pcHlp,psHdl->pcOpt); vdClpPrnOpt(pfOut,psHdl->pcOpt,psArg->psFix->siTyp,psArg->psDep); fprintf(pfOut,"...%c",C_SBC); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%c'%s'...%c",C_SBO,pcHlp,C_SBC); } } } break; case CLPTYP_OBJECT: if (psArg->psFix->siMax==1) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"("); psHdl->apPat[siLev]=psArg; siErr=siClpPrnCmd(pvHdl,pfOut,1,siLev+1,siLev+2,psArg,psArg->psDep,FALSE,FALSE); fprintf(pfOut,")"); if (siErr<0) return(siErr); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%c(",C_SBO); psHdl->apPat[siLev]=psArg; siErr=siClpPrnCmd(pvHdl,pfOut,1,siLev+1,siLev+2,psArg,psArg->psDep,FALSE,FALSE); fprintf(pfOut,")...%c",C_SBC); if (siErr<0) return(siErr); } break; case CLPTYP_OVRLAY: if (psArg->psFix->siMax==1) { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,".%c",C_CBO); psHdl->apPat[siLev]=psArg; siErr=siClpPrnCmd(pvHdl,pfOut,1,siLev+1,siLev+2,psArg,psArg->psDep,FALSE,FALSE); fprintf(pfOut,"%c",C_CBC); if (siErr<0) return(siErr); } else { vdClpPrnAli(pfOut,psHdl->pcOpt,psArg); fprintf(pfOut,"%c%c",C_SBO,C_CBO); psHdl->apPat[siLev]=psArg; siErr=siClpPrnCmd(pvHdl,pfOut,1,siLev+1,siLev+2,psArg,psArg->psDep,FALSE,FALSE); fprintf(pfOut,"%c...%c",C_CBC,C_SBC); if (siErr<0) return(siErr); } break; } } return(CLP_OK); } static int siClpPrnDoc( void* pvHdl, FILE* pfDoc, const int siLev, const TsParamDescription* psParamDesc, const TsSym* psArg, const TsSym* psTab) { TsHdl* psHdl=(TsHdl*)pvHdl; if (pfDoc!=NULL && psTab!=NULL && psParamDesc!=NULL) { const TsSym* psHlp; const TsSym* psSel; int siErr,isCon; int k,m; char acArg[20]; int siMan=0; int siLst=0; const TsSym* apMan[CLPMAX_TABCNT]; const TsSym* apLst[CLPMAX_TABCNT]; if (psTab->psBak!=NULL) { return CLPERR(psHdl,CLPERR_INT,"Entry '%s.%s' not at beginning of a table",fpcPat(pvHdl,siLev),psTab->psStd->pcKyw); } for (isCon=FALSE,psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt) { if (CLPISF_ARG(psHlp->psStd->uiFlg) && CLPISF_CMD(psHlp->psStd->uiFlg)) { if (psHlp->psFix->siTyp==CLPTYP_OBJECT || psHlp->psFix->siTyp==CLPTYP_OVRLAY || (psHlp->psFix->pcMan!=NULL && *psHlp->psFix->pcMan)) { apMan[siMan]=psHlp; siMan++; } else { for (psSel=psHlp->psDep;psSel!=NULL;psSel=psSel->psNxt) { if (psSel->psFix->pcMan!=NULL && *psSel->psFix->pcMan) { apMan[siMan]=psHlp; siMan++; break; } } if (psSel==NULL) { apLst[siLst]=psHlp; siLst++; } } } else if (CLPISF_CON(psHlp->psStd->uiFlg) && psArg!=NULL && psArg->psFix->siTyp == psHlp->psFix->siTyp) { if (psHlp->psFix->pcMan!=NULL && *psHlp->psFix->pcMan) { apMan[siMan]=psHlp; siMan++; } else { apLst[siLst]=psHlp; siLst++; } isCon=TRUE; } } if (isCon) { if (psArg!=NULL) { if (siLst) { fprintf(pfDoc,".Selections\n\n"); for (m=0;m<siLst;m++) { efprintf(pfDoc,"* `%s - %s`\n",apLst[m]->psStd->pcKyw,apLst[m]->psFix->pcHlp); } fprintf(pfDoc,"\n"); } if (psHdl->isDep && siMan) { for (k=m=0;m<siMan;m++) { TsParamDescription stNewParamDesc = *psParamDesc; char acNewPath[strlen(psParamDesc->pcPath)+strlen(apMan[m]->psStd->pcKyw)+2]; char acNewNum[strlen(psParamDesc->pcNum)+10]; snprintf(acNewPath,sizeof(acNewPath),"%s.%s",psParamDesc->pcPath,apMan[m]->psStd->pcKyw); snprintf(acNewNum,sizeof(acNewNum),"%s%d.",psParamDesc->pcNum,k+1); stNewParamDesc.pcPath = acNewPath; stNewParamDesc.pcNum = acNewNum; vdPrintHdl(pfDoc,psHdl,&stNewParamDesc,"Constant",apMan[m]->psStd->pcKyw,'+'); fprintf(pfDoc, ".Synopsis\n\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n"); efprintf(pfDoc,"HELP: %s\n",apMan[m]->psFix->pcHlp); if (psHdl->isPat) fprintf(pfDoc, "PATH: %s\n",fpcPat(pvHdl,siLev)); fprintf(pfDoc, "TYPE: %s\n",apClpTyp[apMan[m]->psFix->siTyp]); fprintf(pfDoc, "SYNTAX: %s\n",apMan[m]->psStd->pcKyw); fprintf(pfDoc, "-----------------------------------------------------------------------\n\n"); fprintf(pfDoc, ".Description\n\n"); fprintm(pfDoc,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,apMan[m]->psFix->pcMan,2); k++; } } } } else { if (siLst) { fprintf(pfDoc,".Arguments\n\n"); for (m=0;m<siLst;m++) { fprintf(pfDoc,"* %c%s: ",C_GRV,apClpTyp[apLst[m]->psFix->siTyp]); siClpPrnSyn(pvHdl,pfDoc,FALSE,siLev,apLst[m]); efprintf(pfDoc," - %s`\n",apLst[m]->psFix->pcHlp); for (psSel=apLst[m]->psDep;psSel!=NULL;psSel=psSel->psNxt) { efprintf(pfDoc,"** `%s - %s`\n",psSel->psStd->pcKyw,psSel->psFix->pcHlp); } } fprintf(pfDoc,"\n"); } if (psHdl->isDep && siMan) { for (k=m=0;m<siMan;m++) { psHdl->apPat[siLev]=apMan[m]; switch (apMan[m]->psFix->siTyp){ case CLPTYP_OBJECT:strcpy(acArg,"Object");break; case CLPTYP_OVRLAY:strcpy(acArg,"Overlay");break; default :strcpy(acArg,"Parameter");break; } TsParamDescription stParamDesc = *psParamDesc; char acNewPath[strlen(psParamDesc->pcPath)+strlen(apMan[m]->psStd->pcKyw)+2]; char acNewNum[strlen(psParamDesc->pcNum)+10]; snprintf(acNewPath,sizeof(acNewPath),"%s.%s",psParamDesc->pcPath,apMan[m]->psStd->pcKyw); snprintf(acNewNum,sizeof(acNewNum),"%s%d.",psParamDesc->pcNum,k+1); stParamDesc.pcPath = acNewPath; stParamDesc.pcNum = acNewNum; vdPrintHdl(pfDoc,psHdl,&stParamDesc,acArg,apMan[m]->psStd->pcKyw,C_CRT); fprintf(pfDoc, ".Synopsis\n\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n"); efprintf(pfDoc,"HELP: %s\n",apMan[m]->psFix->pcHlp); if (psHdl->isPat) fprintf(pfDoc, "PATH: %s\n",fpcPat(pvHdl,siLev)); fprintf(pfDoc, "TYPE: %s\n",apClpTyp[apMan[m]->psFix->siTyp]); fprintf(pfDoc, "SYNTAX: "); siErr=siClpPrnSyn(pvHdl,pfDoc,FALSE,siLev,apMan[m]); fprintf(pfDoc,"\n"); if (siErr<0) return(siErr); fprintf(pfDoc, "-----------------------------------------------------------------------\n\n"); fprintf(pfDoc, ".Description\n\n"); if (apMan[m]->psFix->pcMan!=NULL && *apMan[m]->psFix->pcMan) { fprintm(pfDoc,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,apMan[m]->psFix->pcMan,2); } else { fprintf(pfDoc,"No detailed description available for this argument.\n\n"); } if (apMan[m]->psDep!=NULL) { siErr=siClpPrnDoc(pvHdl,pfDoc,siLev+1,&stParamDesc,apMan[m],apMan[m]->psDep); if (siErr<0) return(siErr); } k++; } } } } return (CLP_OK); } static int siClpWriteArgument( void* pvHdl, FILE* pfDoc, const int siLev, const TsParamDescription* psParamDesc, const char* pcPat, const TsSym* psArg) { int siErr,i; TsHdl* psHdl=(TsHdl*)pvHdl; if (CLPISF_CON(psArg->psStd->uiFlg)) { vdPrintHdl(pfDoc,psHdl,psParamDesc,"Constant",psArg->psStd->pcKyw,'+'); fprintf(pfDoc, ".Synopsis\n\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n"); efprintf(pfDoc,"HELP: %s\n",psArg->psFix->pcHlp); if (psHdl->isPat) fprintf(pfDoc, "PATH: %s\n",pcPat); fprintf(pfDoc, "TYPE: %s\n",apClpTyp[psArg->psFix->siTyp]); fprintf(pfDoc, "SYNTAX: %s\n",psArg->psStd->pcKyw); fprintf(pfDoc, "-----------------------------------------------------------------------\n\n"); fprintf(pfDoc, ".Description\n\n"); if (psArg->psFix->pcMan!=NULL && *psArg->psFix->pcMan) { fprintm(pfDoc,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psArg->psFix->pcMan,2); } else { return CLPERR(psHdl,CLPERR_TAB,"Manual page for constant '%s.%s' missing",pcPat,psArg->psStd->pcKyw); } i=0; for (const TsSym* psHlp=psArg->psDep;psHlp!=NULL;psHlp=psHlp->psNxt) { if (psArg->psFix->siTyp==psHlp->psFix->siTyp && psHlp->psFix->pcMan==NULL) { if (i==0) fprintf(pfDoc,".Selections\n\n"); efprintf(pfDoc,"* `%s - %s`\n",psHlp->psStd->pcKyw,psHlp->psFix->pcHlp); i++; } } if (i) fprintf(pfDoc,"\n"); } else if (CLPISF_ARG(psArg->psStd->uiFlg)){ char acArg[16]; switch (psArg->psFix->siTyp){ case CLPTYP_OBJECT:strcpy(acArg,"Object");break; case CLPTYP_OVRLAY:strcpy(acArg,"Overlay");break; default :strcpy(acArg,"Parameter");break; } vdPrintHdl(pfDoc,psHdl,psParamDesc,acArg,psArg->psStd->pcKyw,C_CRT); fprintf(pfDoc, ".Synopsis\n\n"); fprintf(pfDoc, "-----------------------------------------------------------------------\n"); efprintf(pfDoc,"HELP: %s\n",psArg->psFix->pcHlp); if (psHdl->isPat) fprintf(pfDoc, "PATH: %s\n",pcPat); fprintf(pfDoc, "TYPE: %s\n",apClpTyp[psArg->psFix->siTyp]); fprintf(pfDoc, "SYNTAX: "); siErr=siClpPrnSyn(pvHdl,pfDoc,FALSE,siLev,psArg); fprintf(pfDoc,"\n"); if (siErr<0) return(siErr); fprintf(pfDoc, "-----------------------------------------------------------------------\n\n"); fprintf(pfDoc, ".Description\n\n"); if (psArg->psFix->pcMan!=NULL && *psArg->psFix->pcMan) { fprintm(pfDoc,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psArg->psFix->pcMan,2); } else { return CLPERR(psHdl,CLPERR_TAB,"Manual page for %s '%s.%s' missing",acArg,pcPat,psArg->psStd->pcKyw); } siErr=siClpWriteRemaining(pvHdl,pfDoc,siLev,pcPat,psArg->psDep); if (siErr) return(siErr); } return (CLP_OK); } static int siClpPrintArgument( void* pvHdl, const int siLev, const TsParamDescription* psParamDesc, const char* pcPat, const char* pcFil, const TsSym* psArg) { int siErr; TsHdl* psHdl=(TsHdl*)pvHdl; FILE* pfTmp; pfTmp=fopen_tmp(); if (pfTmp==NULL) { return CLPERR(psHdl,CLPERR_SYS,"Open of temporary file to print page for argument '%s.%s' failed",pcPat,psArg->psStd->pcKyw); } siErr=siClpWriteArgument(pvHdl,pfTmp,siLev,psParamDesc,pcPat,psArg); if (siErr) { fclose_tmp(pfTmp); return(siErr); } char acPat[strlen(pcPat)+strlen(psArg->psStd->pcKyw)+2]; char acFil[strlen(pcFil)+strlen(psArg->psStd->pcKyw)+2]; snprintf(acPat,sizeof(acPat),"%s.%s",pcPat,psArg->psStd->pcKyw); snprintf(acFil,sizeof(acFil),"%s\v%s",pcFil,psArg->psStd->pcKyw); siErr=siClpPrintWritten(pvHdl,pfTmp,siLev+1,acPat,acFil,psArg->psFix->pcMan); fclose_tmp(pfTmp); if (siErr) { return(siErr); } return(CLP_OK); } static int siClpPrintTable( void* pvHdl, const int siLev, const TsParamDescription* psParamDesc, const char* pcPat, const char* pcFil, const TsSym* psTab) { int siErr,i=1; TsHdl* psHdl=(TsHdl*)pvHdl; const TsSym* psHlp; if (psTab->psBak!=NULL) { return CLPERR(psHdl,CLPERR_INT,"Entry '%s.%s' not at beginning of a table.",pcPat,psTab->psStd->pcKyw); } if (psParamDesc==NULL) { return CLPERR(psHdl,CLPERR_INT,"Parameter psParamDesc must not be NULL."); } for (psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt) { if (CLPISF_CMD(psHlp->psStd->uiFlg) && (CLPISF_ARG(psHlp->psStd->uiFlg) || CLPISF_CON(psHlp->psStd->uiFlg)) && (psHlp->psFix->siTyp==CLPTYP_OBJECT || psHlp->psFix->siTyp==CLPTYP_OVRLAY || (psHlp->psFix->pcMan!=NULL && *psHlp->psFix->pcMan))) { TsParamDescription stParamDesc = *psParamDesc; char acNewNum[strlen(psParamDesc->pcNum)+16]; char acNewPath[strlen(psParamDesc->pcPath)+strlen(psHlp->psStd->pcKyw)+2]; snprintf(acNewPath,sizeof(acNewPath),"%s.%s",psParamDesc->pcPath,psHlp->psStd->pcKyw); snprintf(acNewNum,sizeof(acNewNum),"%s%d.",psParamDesc->pcNum,i); i++; stParamDesc.pcPath=acNewPath; stParamDesc.pcNum=acNewNum; psHdl->apPat[siLev]=psHlp; siErr=siClpPrintArgument(pvHdl,siLev,&stParamDesc,pcPat,pcFil,psHlp); if (siErr) return(siErr); if (psHlp->psDep!=NULL) { char acPat[strlen(pcPat)+strlen(psHlp->psStd->pcKyw)+2]; char acFil[strlen(pcFil)+strlen(psHlp->psStd->pcKyw)+2]; snprintf(acPat,sizeof(acPat),"%s.%s",pcPat,psHlp->psStd->pcKyw); snprintf(acFil,sizeof(acFil),"%s\v%s",pcFil,psHlp->psStd->pcKyw); siErr=siClpPrintTable(pvHdl,siLev+1,&stParamDesc,acPat,acFil,psHlp->psDep); if (siErr) return(siErr); } } } return(CLP_OK); } static int siClpPrnPro( void* pvHdl, FILE* pfOut, int isMan, const int siMtd, const int siLev, const int siDep, const TsSym* psTab, const char* pcArg) { TsHdl* psHdl=(TsHdl*)pvHdl; const TsSym* psHlp; int siErr; if (psTab==NULL) { return CLPERR(psHdl,CLPERR_INT,"Argument table not defined%s",""); } if (psTab->psBak!=NULL) { return CLPERR(psHdl,CLPERR_INT,"Entry '%s.%s' not at beginning of a table",fpcPat(pvHdl,siLev),psTab->psStd->pcKyw); } if (pfOut!=NULL) { if (siLev<siDep || siDep>9) { for (psHlp=psTab;psHlp!=NULL;psHlp=psHlp->psNxt) { if (CLPISF_ARG(psHlp->psStd->uiFlg) && CLPISF_PRO(psHlp->psStd->uiFlg) && (pcArg==NULL || strxcmp(psHdl->isCas,psHlp->psStd->pcKyw,pcArg,0,0,FALSE)==0)) { if (psHlp->psFix->pcDft!=NULL && *psHlp->psFix->pcDft) { if ((isMan || (!CLPISF_CMD(psHlp->psStd->uiFlg))) && psHlp->psFix->pcMan!=NULL && *psHlp->psFix->pcMan) { if (siMtd==CLPPRO_MTD_DOC) { fprintf(pfOut,".DESCRIPTION FOR %s.%s.%s.%s: (TYPE: %s) %s\n\n",psHdl->pcOwn,psHdl->pcPgm,fpcPat(pvHdl,siLev),psHlp->psStd->pcKyw,apClpTyp[psHlp->psFix->siTyp],psHlp->psFix->pcHlp); fprintm(pfOut,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psHlp->psFix->pcMan,0); fprintf(pfOut," \n"); } else { fprintf(pfOut,"\n%c DESCRIPTION for %s.%s.%s.%s:\n",C_HSH,psHdl->pcOwn,psHdl->pcPgm,fpcPat(pvHdl,siLev),psHlp->psStd->pcKyw); fprintm(pfOut,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psHlp->psFix->pcMan,0); fprintf(pfOut," %c\n",C_HSH); } isMan=TRUE; } else { if (isMan) fprintf(pfOut,"\n"); isMan=FALSE; } if (siMtd==CLPPRO_MTD_DOC) { if (!CLPISF_CMD(psHlp->psStd->uiFlg)) { fprintf(pfOut,".HELP FOR %s.%s.%s.%s: (TYPE: %s) %s\n\n",psHdl->pcOwn,psHdl->pcPgm,fpcPat(pvHdl,siLev),psHlp->psStd->pcKyw,apClpTyp[psHlp->psFix->siTyp],psHlp->psFix->pcHlp); } } else { fprintf(pfOut," %s.%s.%s.%s=\"%s\" ",psHdl->pcOwn,psHdl->pcPgm,fpcPat(pvHdl,siLev),psHlp->psStd->pcKyw,psHlp->psFix->pcDft); efprintf(pfOut,"# TYPE: %s HELP: %s #\n",apClpTyp[psHlp->psFix->siTyp],psHlp->psFix->pcHlp); } } else { if (siMtd==CLPPRO_MTD_ALL || siMtd==CLPPRO_MTD_CMT || siMtd==CLPPRO_MTD_DOC) { if ((isMan || (!CLPISF_CMD(psHlp->psStd->uiFlg))) && psHlp->psFix->pcMan!=NULL && *psHlp->psFix->pcMan) { if (siMtd==CLPPRO_MTD_DOC) { fprintf(pfOut,".DESCRIPTION FOR %s.%s.%s.%s: (TYPE: %s) %s\n\n",psHdl->pcOwn,psHdl->pcPgm,fpcPat(pvHdl,siLev),psHlp->psStd->pcKyw,apClpTyp[psHlp->psFix->siTyp],psHlp->psFix->pcHlp); fprintm(pfOut,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psHlp->psFix->pcMan,0); fprintf(pfOut," \n"); } else { fprintf(pfOut,"\n%c DESCRIPTION for %s.%s.%s.%s:\n",C_HSH,psHdl->pcOwn,psHdl->pcPgm,fpcPat(pvHdl,siLev),psHlp->psStd->pcKyw); fprintm(pfOut,psHdl->pcOwn,psHdl->pcPgm,psHdl->pcBld,psHlp->psFix->pcMan,0); fprintf(pfOut," %c\n",C_HSH); } isMan=TRUE; } else { if (isMan) fprintf(pfOut,"\n"); isMan=FALSE; } if (siMtd==CLPPRO_MTD_DOC) { if (!CLPISF_CMD(psHlp->psStd->uiFlg)) { fprintf(pfOut,".HELP FOR %s.%s.%s.%s: (TYPE: %s) %s\n\n",psHdl->pcOwn,psHdl->pcPgm,fpcPat(pvHdl,siLev),psHlp->psStd->pcKyw,apClpTyp[psHlp->psFix->siTyp],psHlp->psFix->pcHlp); } } else { if (siMtd==CLPPRO_MTD_CMT) { fprintf(pfOut, ";%s.%s.%s.%s=\"\" ",psHdl->pcOwn,psHdl->pcPgm,fpcPat(pvHdl,siLev),psHlp->psStd->pcKyw); } else { fprintf(pfOut, " %s.%s.%s.%s=\"\" ",psHdl->pcOwn,psHdl->pcPgm,fpcPat(pvHdl,siLev),psHlp->psStd->pcKyw); } efprintf(pfOut,"# TYPE: %s HELP: %s #\n",apClpTyp[psHlp->psFix->siTyp],psHlp->psFix->pcHlp); } } } if (psHlp->psDep!=NULL) { if (psHlp->psFix->siTyp==CLPTYP_OBJECT || psHlp->psFix->siTyp==CLPTYP_OVRLAY) { psHdl->apPat[siLev]=psHlp; siErr=siClpPrnPro(pvHdl,pfOut,isMan,siMtd,siLev+1,siDep,psHlp->psDep,NULL); if (siErr<0) return(siErr); } } } } } } return (CLP_OK); } /**********************************************************************/ static const char* fpcPre( void* pvHdl, const int siLev) { TsHdl* psHdl=(TsHdl*)pvHdl; int i; psHdl->pcPre[0]=EOS; for (i=0;i<siLev+1;i++) { srprintc(&psHdl->pcPre,&psHdl->szPre,strlen(psHdl->pcDep),"%s",psHdl->pcDep); } return(psHdl->pcPre); } static const char* fpcPat( void* pvHdl, const int siLev) { TsHdl* psHdl=(TsHdl*)pvHdl; int i; if (psHdl->pcCmd!=NULL && *psHdl->pcCmd) { if (siLev) { srprintf(&psHdl->pcPat,&psHdl->szPat,strlen(psHdl->pcCmd),"%s.",psHdl->pcCmd); } else { srprintf(&psHdl->pcPat,&psHdl->szPat,strlen(psHdl->pcCmd),"%s",psHdl->pcCmd); } } else { psHdl->pcPat[0]=EOS; } for (i=0;i<(siLev);i++) { if (i) { srprintc(&psHdl->pcPat,&psHdl->szPat,strlen(psHdl->apPat[i]->psStd->pcKyw),".%s",psHdl->apPat[i]->psStd->pcKyw); } else { srprintc(&psHdl->pcPat,&psHdl->szPat,strlen(psHdl->apPat[i]->psStd->pcKyw),"%s",psHdl->apPat[i]->psStd->pcKyw); } } return(psHdl->pcPat); } /**********************************************************************/
46.235573
241
0.516815
[ "object", "3d" ]
ff04b0720de7bc4bcc96c50b75cb769cc1315298
7,700
h
C
lammps-master/lib/atc/Vector.h
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/lib/atc/Vector.h
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/lib/atc/Vector.h
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
#ifndef VECTOR_H #define VECTOR_H #include "Matrix.h" namespace ATC_matrix { /////////////////////////////////////////////////////////////////////////////// // forward declarations /////////////////////////////////////////////////////// //* Matrix-vector product //template<typename T> //void MultMv(const Matrix<T> &A, const Vector<T> &v, DenseVector<T> &c, // const bool At=0, T a=1, T b=0); /****************************************************************************** * abstract class Vector ******************************************************************************/ template<typename T> class Vector : public Matrix<T> { public: Vector() {} Vector(const Vector<T> &c); // do not implement! virtual ~Vector() {} std::string to_string() const; // pure virtual functions virtual T operator()(INDEX i, INDEX j=0) const=0; virtual T& operator()(INDEX i, INDEX j=0) =0; virtual T operator[](INDEX i) const=0; virtual T& operator[](INDEX i) =0; virtual INDEX nRows() const=0; virtual T* ptr() const=0; virtual void resize(INDEX nRows, INDEX nCols=1, bool copy=0)=0; virtual void reset(INDEX nRows, INDEX nCols=1, bool zero=0)=0; virtual void copy(const T * ptr, INDEX nRows, INDEX nCols=1)=0; void write_restart(FILE *f) const; // will be virtual // output to matlab using Matrix<T>::matlab; void matlab(std::ostream &o, const std::string &s="v") const; using Matrix<T>::operator=; INDEX nCols() const; bool in_range(INDEX i) const; bool same_size(const Vector &m) const; static bool same_size(const Vector &a, const Vector &b); protected: void _set_equal(const Matrix<T> &r); //* don't allow this Vector& operator=(const Vector &r); }; /////////////////////////////////////////////////////////////////////////////// //* performs a matrix-vector multiply with default naive implementation template<typename T> void MultMv(const Matrix<T> &A, const Vector<T> &v, DenseVector<T> &c, const bool At, T a, T b) { const INDEX sA[2] = {A.nRows(), A.nCols()}; // m is sA[At] k is sA[!At] const INDEX M=sA[At], K=sA[!At]; GCK(A, v, v.size()!=K, "MultAb<T>: matrix-vector multiply"); if (c.size() != M) { c.resize(M); // set size of C c.zero(); // do not add result to C } else c *= b; for (INDEX p=0; p<M; p++) for (INDEX r=0; r<K; r++) c[p] += A(p*!At+r*At, p*At+r*!At) * v[r]; } /////////////////////////////////////////////////////////////////////////////// //* Operator for Matrix-vector product template<typename T> DenseVector<T> operator*(const Matrix<T> &A, const Vector<T> &b) { DenseVector<T> c; MultMv(A, b, c, 0, 1.0, 0.0); return c; } /////////////////////////////////////////////////////////////////////////////// //* Operator for Vector-matrix product template<typename T> DenseVector<T> operator*(const Vector<T> &a, const Matrix<T> &B) { DenseVector<T> c; MultMv(B, a, c, 1, 1.0, 0.0); return c; } /////////////////////////////////////////////////////////////////////////////// //* Multiply a vector by a scalar template<typename T> DenseVector<T> operator*(const Vector<T> &v, const T s) { DenseVector<T> r(v); r*=s; return r; } /////////////////////////////////////////////////////////////////////////////// //* Multiply a vector by a scalar - communitive template<typename T> DenseVector<T> operator*(const T s, const Vector<T> &v) { DenseVector<T> r(v); r*=s; return r; } /////////////////////////////////////////////////////////////////////////////// //* inverse scaling operator - must always create memory template<typename T> DenseVector<T> operator/(const Vector<T> &v, const T s) { DenseVector<T> r(v); r*=(1.0/s); // for integer types this may be worthless return r; } /////////////////////////////////////////////////////////////////////////////// //* Operator for Vector-Vector sum template<typename T> DenseVector<T> operator+(const Vector<T> &a, const Vector<T> &b) { DenseVector<T> c(a); c+=b; return c; } /////////////////////////////////////////////////////////////////////////////// //* Operator for Vector-Vector subtraction template<typename T> DenseVector<T> operator-(const Vector<T> &a, const Vector<T> &b) { DenseVector<T> c(a); c-=b; return c; } /////////////////////////////////////////////////////////////////////////////// // Template definitions /////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //* output operator template<typename T> std::string Vector<T>::to_string() const { std::string s; int sz = this->size(); for (INDEX i = 0; i < sz; i++) s += std::string(i?"\t":"") + ATC_Utility::to_string((*this)[i],myPrecision); return s; } /////////////////////////////////////////////////////////////////////////////// //* Writes a matlab script defining the vector to the stream template<typename T> void Vector<T>::matlab(std::ostream &o, const std::string &s) const { o << s <<"=zeros(" << this->size() << ",1);\n"; int sz = this->size(); for (INDEX i = 0; i < sz; i++) o << s << "("<<i+1<<") = " << (*this)[i] << ";\n"; } /////////////////////////////////////////////////////////////////////////////// //* writes the vector data to a file template <typename T> void Vector<T>::write_restart(FILE *f) const { INDEX size = this->size(); fwrite(&size, sizeof(INDEX),1,f); if (size) fwrite(this->ptr(), sizeof(T), this->size(), f); } /////////////////////////////////////////////////////////////////////////////// //* returns the number of columns; always 1 template<typename T> inline INDEX Vector<T>::nCols() const { return 1; } /////////////////////////////////////////////////////////////////////////////// //* returns true if INDEX i is within the range of the vector template<typename T> bool Vector<T>::in_range(INDEX i) const { return i<this->size(); } /////////////////////////////////////////////////////////////////////////////// //* returns true if m has the same number of elements this vector template<typename T> bool Vector<T>::same_size(const Vector &m) const { return this->size() == m.size(); } /////////////////////////////////////////////////////////////////////////////// //* returns true if a and b have the same number of elements template<typename T> inline bool Vector<T>::same_size(const Vector &a, const Vector &b) { return a.same_size(b); } //---------------------------------------------------------------------------- // general matrix assignment (for densely packed matrices) //---------------------------------------------------------------------------- template<typename T> void Vector<T>::_set_equal(const Matrix<T> &r) { this->resize(r.nRows(), r.nCols()); const Matrix<T> *pr = &r; #ifdef OBSOLETE if (const SparseMatrix<T> *ps = dynamic_cast<const SparseMatrix<T>*>(pr))//sparse_cast(pr)) copy_sparse_to_matrix(ps, *this); else if (dynamic_cast<const DiagonalMatrix<T>*>(pr))//diag_cast(pr)) // r is Diagonal? { this->zero(); for (INDEX i=0; i<r.size(); i++) (*this)(i,i) = r[i]; } else memcpy(this->ptr(), r.ptr(), r.size()*sizeof(T)); #else const Vector<T> *pv = dynamic_cast<const Vector<T>*> (pr); if (pv) this->copy(pv->ptr(),pv->nRows()); else { std::cout <<"Error in general vector assignment\n"; exit(1); } #endif } } // end namespace #endif
32.765957
94
0.467532
[ "vector" ]
ff0885c21b9a2bbb259114f2f684374d40811cfa
11,348
c
C
nitan/d/penglai/npc/shuzhongxian.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/d/penglai/npc/shuzhongxian.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/d/penglai/npc/shuzhongxian.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
// // #include <ansi.h> inherit NPC; string ask_nanti1(); string ask_nanti2(); string ask_nanti3(); string ask_nanti4(); string ask_nanti5(); string ask_nanti6(); void create() { set_name(HIW "書中仙" NOR, ({ "shuzhong xian", "shuzhong", "xian" })); set("long", HIW "這位仙人乃大名鼎鼎的書中仙,據説天上地下之事他無所不知,神通廣大。\n" NOR); set("gender", "男性"); set("age", 9999); set("attitude", "friendly"); set("shen_type", 1); set("str", 100); set("int", 100); set("con", 100); set("dex", 100); set("max_qi", 200000); set("max_jing", 50000); set("max_neili", 30000); set("neili", 30000); set("jiali", 200); set("combat_exp", 90000000); set_skill("dodge", 550); set_skill("parry",550); set_skill("unarmed", 550); set_skill("yinyang-shiertian", 550); set_skill("force", 550); set_skill("martial-cognize", 550); set_skill("literate", 550); map_skill("force", "yinyang-shiertian"); map_skill("dodge", "yinyang-shiertian"); map_skill("parry", "yinyang-shiertian"); map_skill("unarmed", "yinyang-shiertian"); set("inquiry", ([ "如何不被仙氣困擾" : "這仙氣的困擾對於你們凡人來説是無可避免的,不過只要你能回答我的幾個難題,\n" "本仙人到是可以教你如何減少仙氣對你的困擾。\n", "難題" : "我這裏總共有六道難題,如果你能按順序逐一解決,我便教你如何減少被仙氣困擾的方法。\n", "解決難題" : "你想好了就在這裏找我吧,按照順序如第一道題你就 ask xian about 難題一 。\n", "如何答覆" : "每道題目都是一首詩的一部分,答案是一樣物品,你找到這個物品交給我就行了。\n", "蓬萊仙島" : "這不是你該來的地方,我看你還是快走吧。\n", "難題一" : (: ask_nanti1 :), "難題二" : (: ask_nanti2 :), "難題三" : (: ask_nanti3 :), "難題四" : (: ask_nanti4 :), "難題五" : (: ask_nanti5 :), "難題六" : (: ask_nanti6 :), ])); set("chat_chance_combat", 120); set("chat_msg_combat", ({ (: exert_function, "powerup" :), (: exert_function, "shield" :), }) ); setup(); carry_object("/kungfu/class/sky/npc/obj/xianpao")->wear(); } string ask_nanti1() { object me; string str; me = this_player(); str = HIC "“悠然見南山。”" NOR; if (me->query("penglai/go_quest/ok")) return "我的六道難題你都解決了,不錯,不錯。"; if (me->query("penglai/go_quest/step") > 1) return "這道難題你已經解答過了。"; tell_object(me, HIG "題目是:" + str + HIG "\n " NOR); me->set("penglai/go_quest/step", 1); me->save(); return "我等你的好消息了。"; } string ask_nanti2() { object me; string str; me = this_player(); str = HIC "“碧草生在幽谷中,沐日浴露姿從容。”\n“天賜神香自悠遠,引來蝴蝶弄清風。”" NOR; if (me->query("penglai/go_quest/ok")) return "我的六道難題你都解決了,不錯,不錯。"; if (me->query("penglai/go_quest/step") > 2) return "這道難題你已經解答過了。"; if (me->query("penglai/go_quest/step") < 2) return "你還是先解答前面的難題吧。"; tell_object(me, HIG "題目是:\n" + str + HIG "\n " NOR); me->set("penglai/go_quest/step", 2); me->save(); return "我等你的好消息了。"; } string ask_nanti3() { object me; string str; me = this_player(); str = HIC "“綵衣天授浮生夢,粉翅風憐浪客詩。”\n“獨步尋花花謝早,相思寄月月難知。”" NOR; if (me->query("penglai/go_quest/ok")) return "我的六道難題你都解決了,不錯,不錯。"; if (me->query("penglai/go_quest/step") > 3) return "這道難題你已經解答過了。"; if (me->query("penglai/go_quest/step") < 3) return "你還是先解答前面的難題吧。"; tell_object(me, HIG "題目是:\n" + str + HIG "\n " NOR); me->set("penglai/go_quest/step", 3); me->save(); return "我等你的好消息了。"; } string ask_nanti4() { object me; string str; me = this_player(); str = HIC "“若非一番寒澈骨。”\n" NOR; if (me->query("penglai/go_quest/ok")) return "我的六道難題你都解決了,不錯,不錯。"; if (me->query("penglai/go_quest/step") > 4) return "這道難題你已經解答過了。"; if (me->query("penglai/go_quest/step") < 4) return "你還是先解答前面的難題吧。"; tell_object(me, HIG "題目是:\n" + str + HIG "\n " NOR); me->set("penglai/go_quest/step", 4); me->save(); return "我等你的好消息了。"; } string ask_nanti5() { object me; string str; me = this_player(); str = HIC "“長晝風雷驚虎豹,半空鱗甲舞蛟龍。”" NOR; if (me->query("penglai/go_quest/ok")) return "我的六道難題你都解決了,不錯,不錯。"; if (me->query("penglai/go_quest/step") > 5) return "這道難題你已經解答過了。"; if (me->query("penglai/go_quest/step") < 5) return "你還是先解答前面的難題吧。"; tell_object(me, HIG "題目是:\n" + str + HIG "\n " NOR); me->set("penglai/go_quest/step", 5); me->save(); return "我等你的好消息了。"; } string ask_nanti6() { object me; string str; me = this_player(); str = HIC "“勸君莫嗟歎,精神可勝兵;”\n“充塞天和地,懷抱浪與星。”" NOR; if (me->query("penglai/go_quest/ok")) return "我的六道難題你都解決了,不錯,不錯。"; if (me->query("penglai/go_quest/step") > 6) return "這道難題你已經解答過了。"; if (me->query("penglai/go_quest/step") < 6) return "你還是先解答前面的難題吧。"; tell_object(me, HIG "題目是:\n" + str + HIG "\n " NOR); me->set("penglai/go_quest/step", 6); me->save(); return "我等你的好消息了。"; } int accept_object(object me, object obj) { if (me->query("penglai/go_quest/ok")) { command("say 閣下智慧超羣,佩服佩服。"); return 0; } switch(me->query("penglai/go_quest/step")) { // 菊花 case 1: if (obj->query("id") == "penglai juhua" && base_name(obj) == "/d/penglai/obj/juhua") { command("nod"); command("say 很好,很好,你可以開始解答下一道難題了。"); destruct(obj); me->set("penglai/go_quest/step", 2); me->save(); return 1; } command("say 本仙人從不亂收別人東西。"); return 0; break; // 蘭草 case 2: if (obj->query("id") == "penglai lancao" && base_name(obj) == "/d/penglai/obj/lancao") { command("nod"); command("say 很好,很好,你可以開始解答下一道難題了。"); destruct(obj); me->set("penglai/go_quest/step", 3); me->save(); return 1; } command("say 本仙人從不亂收別人東西。"); return 0; break; // 蝴蝶標本 case 3: if (obj->query("id") == "hudie biaoben" && base_name(obj) == "/d/penglai/obj/biaoben") { command("nod"); command("say 很好,很好,你可以開始解答下一道難題了。"); destruct(obj); me->set("penglai/go_quest/step", 4); me->save(); return 1; } command("say 本仙人從不亂收別人東西。"); return 0; break; // 梅花 case 4: if (obj->query("id") == "penglai meihua" && base_name(obj) == "/d/penglai/obj/meihua") { command("nod"); command("say 很好,很好,你可以開始解答下一道難題了。"); destruct(obj); me->set("penglai/go_quest/step", 5); me->save(); return 1; } command("say 本仙人從不亂收別人東西。"); return 0; break; // 松葉 case 5: if (obj->query("id") == "penglai songye" && base_name(obj) == "/d/penglai/obj/songye") { command("nod"); command("say 很好,很好,你可以開始解答下一道難題了。"); destruct(obj); me->set("penglai/go_quest/step", 6); me->save(); return 1; } command("say 本仙人從不亂收別人東西。"); return 0; break; // 竹葉 case 6: if (obj->query("id") == "penglai zhuye" && base_name(obj) == "/d/penglai/obj/zhuye") { command("nod"); command("say 很好,很好,閣下智慧超羣,將老仙難題逐一解答。"); destruct(obj); command("say 本仙人便教你如何減少仙氣的困擾,你可記好了 ……"); tell_object(me, HIG "恭喜你,已經學會了如何減少島上仙氣對你的困擾。\n" NOR); me->set("penglai/go_quest/ok", 1); me->save(); return 1; } command("say 本仙人從不亂收別人東西。"); return 0; break; default : command("say 本仙人從不亂收別人東西。"); return 0; break; } return 0; } void unconcious() { die(); }
34.387879
116
0.360857
[ "object" ]