void NoiseBandSynthesizer::SynthesizeSample(std::vector<double> *instantParams) { if(firstRun) { phase=0.0; phaseAdd=0.0; lastfreq=(*instantParams)[eCenterFrequency]; lastamp=(*instantParams)[eAmplitude]; lastbw=(*instantParams)[eBandwidth]; targetfreq=lastfreq; instfreq=lastfreq; samplesTillNextTarget =-1; firstRun=false; } float lowFreq,highFreq,centerFreq,maxFreq; float freq,amp,bw; maxFreq = 44100.0/2.0; freq=(*instantParams)[eCenterFrequency]; amp=(*instantParams)[eAmplitude]; bw=mymin(1.0,mymax(0.0,(*instantParams)[eBandwidth])); lowFreq = freq*(1.0-bw); highFreq = mymin(maxFreq,freq*(1.0+bw) ); centerFreq = (lowFreq+highFreq)/2.0; //see if we need a new target if(samplesTillNextTarget <0) { targetfreq = randfloat(highFreq-lowFreq)+lowFreq; //assumes bw <1.0 samplesTillNextTarget = randint(44100.0/mymax(2.0,centerFreq))+1.0; } else { samplesTillNextTarget = mymin(44100.0/mymax(2.0,centerFreq),samplesTillNextTarget); samplesTillNextTarget--; } instfreq = instfreq + (targetfreq-instfreq)/mymax(1.0,samplesTillNextTarget); phaseAdd = instfreq*2.0*3.141592/44100.0; //phaseAdd += phaseAdd* (randfloat(bw*2)-bw); phase += phaseAdd; while(phase>2.0*3.141592) phase-=2.0*3.141592; buffer->SetFrame(currentSample++,amp*sin(phase)*SHORTLIMITF); lastfreq=freq; lastamp=amp; lastbw=bw; }
void get_model_matrix(float result[16]) { mat4f_identity(result); if(FIT_TO_VIEW_AND_ROTATE == 0) { /* Translate the model to where we were asked to put it */ float translate[16]; mat4f_translateVec_new(translate, placeToPutModel); /* Do inches to meters conversion if we are asked to. */ float scale[16]; mat4f_identity(scale); if(INCHES_TO_METERS) { float inchesToMeters=1/39.3701; mat4f_scale_new(scale, inchesToMeters, inchesToMeters, inchesToMeters); } mat4f_mult_mat4f_new(result, translate, scale); return; } /* Change angle for animation. */ int count = glutGet(GLUT_ELAPSED_TIME) % 10000; // get a counter that repeats every 10 seconds /* Animate the model if there is animation information available. */ kuhl_update_model_file_ogl3(modelFilename, 0, count/1000.0); dgr_setget("count", &count, sizeof(int)); /* Calculate the width/height/depth of the bounding box and * determine which one of the three is the largest. Then, scale * the scene by 1/(largest value) to ensure that it fits in our * view frustum. */ float bb_min[3], bb_max[3], bb_center[3]; kuhl_model_bounding_box(modelFilename, bb_min, bb_max, bb_center); #define mymax(a,b) (a>b?a:b) float tmp; tmp = bb_max[0] - bb_min[0]; tmp = mymax(bb_max[1] - bb_min[1], tmp); tmp = mymax(bb_max[2] - bb_min[2], tmp); tmp = 1.f / tmp; #undef mymax float scaleBoundBox[16], moveToOrigin[16], moveToLookPoint[16]; mat4f_translate_new(moveToOrigin, -bb_center[0], -bb_center[1], -bb_center[2]); // move to origin // printf("Scaling by factor %f\n", tmp); mat4f_scale_new(scaleBoundBox, tmp, tmp, tmp); // scale model based on bounding box size mat4f_translateVec_new(moveToLookPoint, placeToPutModel); mat4f_mult_mat4f_new(result, moveToOrigin, result); mat4f_mult_mat4f_new(result, scaleBoundBox, result); mat4f_mult_mat4f_new(result, moveToLookPoint, result); }
void Interpolation::Truncate(double startTime, double duration, std::vector<TreeNode*> *activeNodes, std::vector<ParameterList*> *parameters, int layerNum, int topLayer, int numControlledLayers) { mStartTime = startTime; mDuration = duration; //make sure we fit within all parameter boundries for all associated paramter lists. double startValue = (*parameters)[layerNum]->GetValue(mParam); //- we don't know where it will be at the end of the leaf. //now check to see where the parameter will be at upon the end of the leaf. //we do this by asking each of the active nodes what their value will be at the end of THIS leaf //and multiply them against the start value double topValue = startValue; double bottomValue = startValue; for(int i =0;i<numControlledLayers;i++) { topValue = mymax(topValue, (*parameters)[topLayer+i]->GetValue(mParam)); bottomValue = mymin(bottomValue, (*parameters)[topLayer+i]->GetValue(mParam)); } for(int i=0;i<activeNodes->size();i++) { for(int j=0;j<((*activeNodes)[i])->GetNumInterpolations();j++) { if(((*activeNodes)[i])->GetInterpolation(j)->GetParameter() == mParam) { //we use this node's start time, and the parent node's end time (since we can't push them to overstep their boundries.) topValue = mymax(topValue,topValue*((*activeNodes)[i])->GetInterpolation(j)->MaxValueInTimeRange(mStartTime,((*activeNodes)[i])->GetInterpolation(j)->GetStartTime()+((*activeNodes)[i])->GetInterpolation(j)->GetDuration())); bottomValue = mymin(bottomValue,bottomValue*((*activeNodes)[i])->GetInterpolation(j)->MinValueInTimeRange(mStartTime,((*activeNodes)[i])->GetInterpolation(j)->GetStartTime()+((*activeNodes)[i])->GetInterpolation(j)->GetDuration())); } } } assert(topValue >= bottomValue); while(topValue*mEndCoef> (*parameters)[layerNum]->GetMaxValue(mParam)) mEndCoef= randfloat(mEndCoef-1.0)+1.0; while(bottomValue*mEndCoef<(*parameters)[layerNum]->GetMinValue(mParam)) mEndCoef = randfloat(1.0-mEndCoef)+mEndCoef; if((topValue*mEndCoef>(*parameters)[layerNum]->GetMaxValue(mParam)) || (bottomValue*mEndCoef<(*parameters)[layerNum]->GetMinValue(mParam)) ) mEndCoef=1.0; }
/// checks if a ray intersects the mesh, ray_origin and ray_dir must be in local coordinates /// returns face index that was hit, or -1 if nothing hit int MeshShape::RayIntersect (const Vector3& ray_origin,const Vector3& ray_dir,float* pfHitDist) { if (mpMesh.isNull()) return -1; // check bounding sphere first //printf("#WWW### MeshShape::RayIntersect %f\n",mpMesh->getBoundingSphereRadius()); Vector3 vMid = 0.5*(mvMin + mvMax); float fRad = mymax((mvMin-vMid).length(),(mvMax-vMid).length()); //float fRad = mpMesh->getBoundingSphereRadius(); if (!Ogre::Ray(ray_origin,ray_dir).intersects(Ogre::Sphere(vMid,fRad + 0.1)).first) return -1; //printf("MeshShape::RayIntersect hitbounds : rad=%f\n",fRad); int iFaceHit = -1; float myHitDist; //printf("#WWW### MeshShape::RayIntersect rayhit %d\n",mlIndices.size()); for (int i=0;i<mlIndices.size();i+=3) { if (IntersectRayTriangle(ray_origin,ray_dir, mlVertices[mlIndices[i+0]], mlVertices[mlIndices[i+1]], mlVertices[mlIndices[i+2]],&myHitDist)) { if (iFaceHit == -1 || myHitDist < *pfHitDist) { *pfHitDist = myHitDist; iFaceHit = i/3; } } } //printf("MeshShape::RayIntersect hit=%d dist=%f\n",bHit?1:0,bHit?(*pfHitDist):0); return iFaceHit; }
bool LineSegment::containPointClose(Point pt) { double minx = mymin(start.x, end.x); double maxx = mymax(start.x, end.x); double miny = mymin(start.y, end.y); double maxy = mymax(start.y, end.y); if (containPointOpen(pt) && (pt.x > minx || DOUBLE_EQUAL(pt.x, minx)) && (pt.x < maxx || DOUBLE_EQUAL(pt.x, maxx)) && (pt.y > miny || DOUBLE_EQUAL(pt.y, miny)) && (pt.y < maxy || DOUBLE_EQUAL(pt.y, maxy))) return true; else return false; }
// A utility function to left rotate subtree rooted with x // See the diagram given above. struct Node *leftRotate(struct Node *x) { struct Node *y = x->right; struct Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = mymax(height(x->left), height(x->right))+1; y->height = mymax(height(y->left), height(y->right))+1; // Return new root return y; }
// A utility function to right rotate subtree rooted with y // See the diagram given above. struct Node *rightRotate(struct Node *y) { struct Node *x = y->left; struct Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = mymax(height(y->left), height(y->right))+1; x->height = mymax(height(x->left), height(x->right))+1; // Return new root return x; }
// Проверяет, можно ли считать таблицей нечто с адресом p и шириной элементов N static bool slow_check_for_data_table (int N, byte *p, uint32 &type, BYTE *&table_start, BYTE *&table_end, byte *bufstart, byte *bufend, byte *buf, uint64 &offset, Buffer &ReorderingBuffer) { // Сначала сканируем назад, начиная с p, в поисках начала таблицы int useless; table_start = search_for_table_boundary (-N, p, bufstart, bufend, useless); // Затем сканируем вперёд, начиная с table_start, в поисках конца таблицы table_end = search_for_table_boundary (N, table_start, bufstart, bufend, useless); // +разрешить таблицы с широкими столбцами и небольшим числом строк (sqrt(N)*rows >= X) // +учитывать расстояние до предыдущей таблицы для оптимизации конечного уровня сжатия // улучшать оценку для столбцов с фиксированной разницей между элементами (типа 8,16,24,32...) // считать количество байтов, энтропия которых уменьшилась от вычитания [как минимум на два бита] // Теперь выясняем, достаточно ли хороша эта таблица для того, чтобы её стоило закодировать int rows = (table_end-table_start)/N; int useful = rows - useless; // количество полезных строк таблицы double skipBits = logb(mymax(table_start-bufstart,1)); // сколько бит придётся потратить на кодирование поля skip stat ((slow_checks++, verbose>1 && printf ("Slow check %08x-%08x (%d*%d+%d)\n", int(table_start-buf+offset), int(table_end-buf+offset), N, useful, useless))); if (useful*sqrt((double)N) > 30+4*skipBits) { stat ((table_count++, table_sumlen += N*rows, table_skipBits+=skipBits)); stat (verbose>0 && printf("%08x-%08x %d*%d ", int(table_start-buf+offset), int(table_end-buf+offset), N, rows)); // Определить какие столбцы нужно вычесть, а какие являются иммутабельными. // Вычесть вычитаемое и собрать иммутабельные столбцы в начале таблицы (для удобства работы lz77) bool doDiff[MAX_ELEMENT_SIZE], immutable[MAX_ELEMENT_SIZE]; analyze_table (N, table_start, rows, doDiff, immutable); diff_table (N, table_start, rows, doDiff); reorder_table (N, table_start, rows, immutable, ReorderingBuffer); type = encode_type (N, doDiff, immutable); stat (verbose>0 && printf("\n")); return TRUE; } return FALSE; }
void* producer(void* arg) { Chan* writer; int* buf; int id; id = GETID(arg); printf("Producer %d starting"ENDL,id); writer = Chan_Open(GETCHAN(arg),CHAN_WRITE); buf = (int*)Chan_Token_Buffer_Alloc(writer); do { buf[0] = InterlockedIncrement(&item); usleep(1); usleep(1); printf("Producer: item %4d [ + ] %d"ENDL, buf[0], id); #pragma omp critical { mymax(&pmax,*buf); } Chan_Next(writer,(void**)&buf,sizeof(int)); } while(!stop); Chan_Token_Buffer_Free(buf); Chan_Close(writer); printf("Producer %d exiting"ENDL,id); return NULL; }
int delta_compress (MemSize BlockSize, int ExtendedTables, CALLBACK_FUNC *callback, void *auxdata) { int errcode = FREEARC_OK; byte *buf = (byte*) BigAlloc(BlockSize); // Buffer for one block of input data (typically, 8mb long) if (buf==NULL) return FREEARC_ERRCODE_NOT_ENOUGH_MEMORY; // Error: not enough memory uint64 offset = 0; // Current offset of buf[] contents relative to file (increased after each input block processd) Buffer TSkip, TType, TRows; // Buffers for storing info about each table filtered Buffer ReorderingBuffer; // Buffer used in reorder_table // Each iteration of this cycle reads, process and encodes one block of data for (;;) { // Read input block int Size; READ_LEN_OR_EOF (Size, buf, BlockSize); BYTE *bufend = buf + Size; // End of data in buf[] BYTE *last_table_end = buf; // End of last table found so far BYTE *hash[256], *hash1[256]; iterate_var(i,256) hash[i] = hash1[i] = buf-1; for (byte *ptr=buf+LINE; ptr+MAX_ELEMENT_SIZE*4 < bufend; ) { if (*(int32*)ptr != *(int32*)(ptr+3)) // a little speed optimization, mainly to skip blocks of all zeroes { // Посчитаем количество повторений одинаковых или близких байт на разных дистанциях BYTE count[MAX_ELEMENT_SIZE]; zeroArray(count); BYTE *p = ptr; iterate_var(i,LINE) { int n = p - hash[*p/16]; // detecting repeated data by 4 higher bits hash[*p/16] = p; if (n<=MAX_ELEMENT_SIZE) count[n-1]++; #if 0 // Detecting repeating data by all 8 bits - useful for tables with longer rows int n1 = p - hash1[*p]; hash1[*p] = p; if (n!=n1 && n1<=MAX_ELEMENT_SIZE) count[n1-1]++; #endif p++; } // Теперь отберём те дистанции, на которых было больше 5 повторений - // это кандидаты на размер строки таблицы iterate_var(i, MAX_ELEMENT_SIZE) if (count[i] > 5) { int N = i+1; stat ((fast_checks+=N, verbose>1 && printf ("Fast check %08x (%d*%d)\n", int(ptr-buf+offset), N, count[i]))); BYTE *p = ptr; for (int j=0; j<N; j++, p++) FAST_CHECK_FOR_DATA_TABLE(N,p); } } ptr += LINE; continue; // Сюда мы попадаем после того, как найдена и закодирована таблица. // Пропустим её содержимое found: ptr = mymax (ptr+LINE, last_table_end); }
bool LineSegment::containPointExclusiveEnds(Point pt) { double minx = mymin(start.x, end.x); double maxx = mymax(start.x, end.x); double miny = mymin(start.y, end.y); double maxy = mymax(start.y, end.y); if (containPointOpen(pt) && (pt.x > minx || DOUBLE_EQUAL(pt.x, minx)) && (pt.x < maxx || DOUBLE_EQUAL(pt.x, maxx)) && (pt.y > miny || DOUBLE_EQUAL(pt.y, miny)) && (pt.y < maxy || DOUBLE_EQUAL(pt.y, maxy)) && pt.approxInequal(start) && pt.approxInequal(end)) return true; else return false; }
void VoiceHackSynthesizer::SynthesizeFinalizeSample(std::vector<double> *instantParams) { if(blowing) { voice.quiet(); blowing=false; } buffer->SetFrame(currentSample++,voice.tick() *SHORTLIMITF * mymax(0.0f,(float)(kFinalizeSamplesVoiceHack-finalizeSampleCount++)/kFinalizeSamplesVoiceHack)); }
void dtrqsol(int n, double *x, double *p, double delta, double *sigma) { /* c ********** c c Subroutine dtrqsol c c This subroutine computes the largest (non-negative) solution c of the quadratic trust region equation c c ||x + sigma*p|| = delta. c c The code is only guaranteed to produce a non-negative solution c if ||x|| <= delta, and p != 0. If the trust region equation has c no solution, sigma = 0. c c parameters: c c n is an integer variable. c On entry n is the number of variables. c On exit n is unchanged. c c x is a double precision array of dimension n. c On entry x must contain the vector x. c On exit x is unchanged. c c p is a double precision array of dimension n. c On entry p must contain the vector p. c On exit p is unchanged. c c delta is a double precision variable. c On entry delta specifies the scalar delta. c On exit delta is unchanged. c c sigma is a double precision variable. c On entry sigma need not be specified. c On exit sigma contains the non-negative solution. c c ********** */ int inc = 1; double dsq = delta*delta, ptp, ptx, rad, xtx; ptx = ddot_(&n, p, &inc, x, &inc); ptp = ddot_(&n, p, &inc, p, &inc); xtx = ddot_(&n, x, &inc, x, &inc); /* Guard against abnormal cases. */ rad = ptx*ptx + ptp*(dsq - xtx); rad = sqrt(mymax(rad, 0)); if (ptx > 0) *sigma = (dsq - xtx)/(ptx + rad); else if (rad > 0) *sigma = (rad - ptx)/ptp; else *sigma = 0; }
void reserve(uint n) { if (p+n > bufend) { uint newsize = mymax(p+n-buf, (bufend-buf)*2); byte* newbuf = (byte*) realloc (buf, newsize); bufend = newbuf + newsize; p += newbuf-buf; end += newbuf-buf; buf = newbuf; } }
int findMaxDistance(int v1, int v2, int t) { int v_1 = mymin(v1, v2); int v_2 = mymax(v1, v2); if (t == 2) { assert(v_2 - v_1 <= d); return v_1 + v_2; } else { return v_1 + findMaxDistance(v_1 + d, v_2, t - 1); } }
void NoiseBandSynthesizer::SynthesizeFinalizeSample(std::vector<double> *instantParams) { //TODO: this assumes number of finalize samples is 44100 long thisSample = currentSample; SynthesizeSample(instantParams); buffer->SetFrame(thisSample,buffer->GetFrame(thisSample)* mymax(0.0f,(float)(kFinalizeSamplesNoiseBand-finalizeSampleCount++)/kFinalizeSamplesNoiseBand) ); }
//write a wave file bool StereoBuffer16::WriteWave(const char* fname,unsigned int start, float level) { //check to see if we have anything. if(NULL == m_left || NULL == m_right || 0 == mNumFrames) return false; FILE* fptr; fptr = WriteWaveHeader(fname, mNumFrames-start); if(NULL == fptr) { //couldn't come through. return false; } //writing 1 short at a time might not be that fast- if this is //an issue, we'll have to create a temp buff at the level instead //and do the entire buffer in one fwrite. short valuel,valuer; long *bufl = (long*)m_left->GetBuffer(0); long *bufr = (long*)m_right->GetBuffer(0); for(int i = start; i < mNumFrames;i++) { //have to pretend a short valuel = mymax(mymin(bufl[i],SHORTLIMIT),-SHORTLIMIT) * level; valuer = mymax(mymin(bufr[i],SHORTLIMIT),-SHORTLIMIT) * level; //#ifndef LITTLEENDIAN #ifndef __LITTLE_ENDIAN__ valuel = Swap_16(valuel); valuer = Swap_16(valuer); #endif fwrite(&valuel,2,1,fptr); fwrite(&valuer,2,1,fptr); } fclose(fptr); printf("wrote the file %s\n", fname); return true; }
//destructive mix. Keeps original level. the default ins will mix the entire buffer in. void StereoBuffer16::Mix( Genesynth::AudioBuffer* in, unsigned int start, float level,float targetChannel,int taperlength,unsigned int inFrom,int inLength, bool undo) { if(NULL==in) return; if(1==in->GetNumChannels()) { m_left->Mix(in,start,level*(1.0-targetChannel),0,taperlength,inFrom,inLength,undo); m_right->Mix(in,start,level*targetChannel,0,taperlength,inFrom,inLength,undo); } //otherwise mix over all the channels even into left, right into odd. else { for(int i =0;i<in->GetNumChannels();i++) { if(i%2 == 0) m_left->Mix(in->GetChannelBuffer(i),start,level,0,taperlength,inFrom,inLength,undo); else m_right->Mix(in->GetChannelBuffer(i),start,level,0,taperlength,inFrom,inLength,undo); } } mNumFrames = mymax(mNumFrames,mymax(m_left->GetNumFrames(),m_right->GetNumFrames())); }
// Print current compression statistics static void print_stats (Results &r) { #ifndef FREEARC_NO_TIMING FILESIZE insize = r.progress_insize; bool not_enough_input = (insize - r.last_insize < PROGRESS_CHUNK_SIZE); FILESIZE outsize = r.progress_outsize; bool not_enough_output = (outsize - r.last_outsize < PROGRESS_CHUNK_SIZE); if (r.quiet_progress || insize==0 || outsize==0 || not_enough_input && not_enough_output) return; // Prints stats no more often than once per 64 kb r.last_insize = insize; r.last_outsize = outsize; double curtime = GetSomeTime(); // Update progress indicator every 0.2 seconds if (curtime > r.lasttime+0.2) { double time = curtime - r.start_time; // Time used so far char percents0[100] = "", remains0[100] = "", percents[1000] = "", remains[100] = "", insize_str[100], outsize_str[100]; if (r.filesize) { // If progress by 1% takes more than 1-2 seconds - display xx.x%, otherwise xx% // (we don't want to switch it too frequently, therefore "?1:2") r.show_exact_percent = double(r.filesize)/insize*time > (r.show_exact_percent?1:2)*100; if (r.show_exact_percent) sprintf (percents0, "%.1lf%%", double(int(double(insize)*100/r.filesize*10))/10); else sprintf (percents0, "%d%%", int(double(insize)*100/r.filesize)); sprintf (percents, "%s: ", percents0); int remain = int(double(r.filesize-insize)/insize*time)+1; if (remain>=3600) sprintf (remains0, "%02d:%02d:%02d", remain / 3600, (remain % 3600) / 60, remain % 60); else sprintf (remains0, "%02d:%02d", remain / 60, remain % 60); sprintf (remains, ". Remains %s", remains0); } double origsize = (r.mode==_COMPRESS? insize : outsize); // Size of original (uncompressed) data double compsize = (r.mode==_COMPRESS? outsize : insize); // Size of compressed data double ratio = (compsize/origsize)*100; double speed = (origsize/mb) / mymax(time,0.001); // Speed of processing, in MiB/s if (!r.quiet_result && !strequ (r.outname, "-")) fprintf (stderr, "\r%s%s%s -> %s: %.2lf%%, speed %.3lf mb/sec%s ", r.method_name, percents, show3(insize,insize_str), show3(outsize,outsize_str), ratio, speed, remains); if (!r.quiet_title && r.filesize && curtime > r.lasttime2+0.5) // Update window title every 0.5 seconds { const char *op = (r.mode==_COMPRESS? "Compressing": r.mode==_DECOMPRESS? "Extracting": "Benchmarking"); sprintf (percents, "%s %s | %s %s", percents0, remains0, op, strequ(r.filename,"-")? PROGRAM_NAME : r.filename); EnvSetConsoleTitleA (percents); Taskbar_SetProgressValue (insize, r.filesize); r.lasttime2 = curtime; } r.lasttime = curtime; } #endif }
int Colour::setcol(const double & magnitude) { // colour scale 0--1 mag = mymax(0, mymin( 1, magnitude )); // make sure it's between 0 and 1 // hot colormap //r = mymin( mymax( 8*mag / 3 , 0 ), 1 ); //g = mymin( mymax( 8*mag / 3 - 1, 0 ), 1 ); //b = mymin( mymax( 4*mag - 3, 0 ), 1 ); // rainbow colormap, 0 = black // r = mymin( mymax( -2 * fabs( mag - 1 ) + 1.3 ,0) ,1); // g = mymin( mymax( -2 * fabs( mag - 0.55) + 1.05 ,0) ,1); ////b = mymin( mymax( -5 * fabs( mag - 0.25) + 1.2 ,0) ,1); // b = mymin( mymax( -2 * fabs( mag - 0.25) + 1.2 ,0) ,1); // hls, sort of //r = mymin( mymax( (4* (mag-0.25) ) , 0 ), 1 ); //b = mymin( mymax( (4* (0.75-mag) ) , 0 ), 1 ); //g = mymin( mymax( (4*fabs(mag-0.5)-1) , 0 ), 1 ); //r = mymin( mymax( -2 * abs( mag - 1 ) + 1.3 ,0) ,1); //g = mymin( mymax( -2 * abs( mag - 0.4) + 1.15 ,0) ,1); //b = mymin( mymax( -2 * abs( mag - 0.05) + 1.2 ,0) ,1); //r = mymin( mymax( -1.8* fabs( mag - 1 ) + 1.3 ,0) ,1); //g = mymin( mymax( -2.6 * fabs( mag - 0.58) + 1.05 ,0) ,1); //b = mymin( mymax( -3 * fabs( mag - 0.25) + 1.2 ,0) ,1); r = mymin( mymax( -1.8* fabs( mag - 1 ) + 1.3 ,0) ,1); if (mag < 0.58) g = mymin( mymax( -2.0 * fabs( mag - 0.58) + 1.05 ,0) ,1); else g = mymin( mymax( -2.6 * fabs( mag - 0.58) + 1.05 ,0) ,1); if (mag < 0.25) b = mymin( mymax( -2.5 * fabs( mag - 0.25) + 1.2 ,0) ,1); else b = mymin( mymax( -3 * fabs( mag - 0.25) + 1.2 ,0) ,1); // gamma adjustment --- note this is applied both to the data and the scale bar, so we don't misrepresent anything r = pow( r , 1 / COLOUR_GAMMA); g = pow( g , 1 / COLOUR_GAMMA); b = pow( b , 1 / COLOUR_GAMMA); R = (unsigned char) (r*255); G = (unsigned char) (g*255); B = (unsigned char) (b*255); return 0; }
struct Node* insert(struct Node* node, int key, int seg_id) { /* 1. Perform the normal BST rotation */ if (node == NULL) return(newNode(key, seg_id)); if (key < node->key) node->left = insert(node->left, key, seg_id); else if (key > node->key) node->right = insert(node->right, key, seg_id); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node->height = 1 + mymax(height(node->left), height(node->right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; }
void MeshShape::RayIntersect (const Ogre::Vector3& ray_origin,const Ogre::Vector3& ray_dir,std::vector<std::pair<float,int> > &pHitList) { if (mpMesh.isNull()) return; Vector3 vMid = 0.5*(mvMin + mvMax); float fRad = mymax((mvMin-vMid).length(),(mvMax-vMid).length()); if (!Ogre::Ray(ray_origin,ray_dir).intersects(Ogre::Sphere(vMid,fRad + 0.1)).first) return; float myHitDist; for (int i=0;i<mlIndices.size();i+=3) { if (IntersectRayTriangle(ray_origin,ray_dir, mlVertices[mlIndices[i+0]], mlVertices[mlIndices[i+1]], mlVertices[mlIndices[i+2]],&myHitDist)) { pHitList.push_back(std::make_pair(myHitDist,i/3)); } } }
__kernel void CalculateRowMaxs(__global float* Maxs, __global const float* Image, __private int DATA_H, __private int DATA_D) { int z = get_global_id(0); if (z >= DATA_D) return; float max = -10000.0f; for (int y = 0; y < DATA_H; y++) { max = mymax(max, Image[Calculate2DIndex(y,z,DATA_H)]); } Maxs[z] = max; }
long double Matrix<T>::norm(const long double p) const // compute column vector p-norm. { assert(col == 1); long double result = 0; if(p != INF_NORM) { for(int i = 0; i < row; i++) result += pow(fabs((long double) (matrix[i][0])), p); return pow(result, (double) 1 / p); } for(int i = 0; i < row; i++) result = mymax(result, fabs((long double) matrix[i][0])); return result; }
// LDStats data sent to parent contains real PE // LDStats in parent should contain relative PE void HbmLB::Loadbalancing(int atlevel) { CmiAssert(atlevel >= 1); LevelData *lData = levelData[atlevel]; LDStats *statsData = lData->statsData; CmiAssert(statsData); // at this time, all objects processor location is relative, and // all incoming objects from outside group belongs to the fake root proc. // clear background load if needed if (_lb_args.ignoreBgLoad()) statsData->clearBgLoad(); currentLevel = atlevel; double start_lb_time(CkWallTimer()); double lload = lData->statsList[0]; double rload = lData->statsList[1]; double diff = myabs(lload-rload); double maxl = mymax(lload, rload); double avg = (lload+rload)/2.0; CkPrintf("[%d] lload: %f rload: %f atlevel: %d\n", CkMyPe(), lload, rload, atlevel); if (diff/avg > 0.02) { // we need to perform load balancing int numpes = (int)pow(2.0, atlevel); double delta = myabs(lload-rload) / numpes; int overloaded = lData->children[0]; if (lload < rload) { overloaded = lData->children[1]; } DEBUGF(("[%d] branch %d is overloaded by %f... \n", CkMyPe(), overloaded, delta)); thisProxy[overloaded].ReceiveMigrationDelta(delta, atlevel, atlevel); } else { LoadbalancingDone(atlevel); } }
int main(int argc, char **argv) { int res[N]; int tmp[M]; int i; int j; for (i = 0; i < N; i++) { for (j = 0; j < M; j++) { if ((i - am[j]) >= 0) { tmp[j] = res[i - am[j]] + ac[j]; } else { tmp[j] = 0; } } res[i] = mymax(tmp[0], tmp[1], tmp[2]); printf("f(%d) = %d\n", i, res[i]); } return 0; }
__kernel void CalculateColumnMaxs(__global float* Maxs, __global const float* Volume, __private int DATA_W, __private int DATA_H, __private int DATA_D) { int y = get_global_id(0); int z = get_global_id(1); if (y >= DATA_H || z >= DATA_D) return; float max = -10000.0f; for (int x = 0; x < DATA_W; x++) { max = mymax(max, Volume[Calculate3DIndex(x,y,z,DATA_W,DATA_H)]); } Maxs[Calculate2DIndex(y,z,DATA_H)] = max; }
void* consumer(void* arg) { Chan* reader; int* buf,id; id = GETID(arg); printf("Consumer %d starting\n",id); reader = Chan_Open(GETCHAN(arg),CHAN_READ); buf = (int*)Chan_Token_Buffer_Alloc(reader); while(CHAN_SUCCESS(Chan_Next(reader,(void**)&buf,sizeof(int)))) { //i=InterlockedDecrement(&item); printf("Consumer: item %4d [ - ] %d"ENDL, buf[0], id); #pragma omp critical { mymax(&cmax,buf[0]); } } Chan_Token_Buffer_Free(buf); Chan_Close(reader); printf("Consumer %d exiting"ENDL,id); return NULL; }
double segment::diff_min_unary(std::vector<Beliefs> E, int c1, int c2, int dimH, int dimY) { int i, y, max_idx1, max_idx2; double max_val1, max_val2; dVector val_y(dimY); for( y=0; y<dimY; y++ ) { max_idx1 = max_idx2 = -1; max_val1 = max_val2 = -DBL_MAX; for( i=0; i<dimH; i++ ) { if( E[y].belStates[c1][i] > max_val1 ) { max_idx1 = i; max_val1 = E[y].belStates[c1][i]; } if( E[y].belStates[c2][i] > max_val2 ) { max_idx2 = i; max_val2 = E[y].belStates[c2][i]; } } val_y[y] += mymax(E[y].belStates[c1][max_idx2]-max_val1, E[y].belStates[c2][max_idx1]-max_val2); } return val_y.sum(); }
// функци¤ принадлежности точки области // не используетс¤ static AWPBOOL IsPixelBelongArea(AWPINT NumPoints, awpPoint* P, AWPINT x, AWPINT y){ AWPINT Count, i, j, m, x0; AWPBOOL F; AWPDOUBLE t; Count = 0; for (i = 0; i < NumPoints-1; i++) { j = (i+1); if (P[i].Y == P[j].Y) continue; if (P[i].Y > y && P[j].Y > y) continue; if (P[i].Y < y && P[j].Y < y) continue; m = mymax(P[i].Y,P[j].Y, &F); if (F) x0 = P[i].X; else x0 = P[j].X; if (m == y && x0 > x) Count = 1 - Count; else if (mymin(P[i].Y,P[j].Y)== y) continue; else{ t = ((AWPDOUBLE)y - P[i].Y) / (P[j].Y - P[i].Y); if (t > 0 && t <1 && P[i].X + t*(P[j].X - P[i].X) >= x) Count = 1 - Count; } } return (Count == 0)?FALSE:TRUE; }