void progress_bar_set (struct progress_bar *bar, uint64_t position, uint64_t total) { size_t i, cols; int pulse_mode; double ratio; const char *s_open, *s_dot, *s_dash, *s_close; if (bar->machine_readable || bar->have_terminfo == 0) { dumb: printf ("%" PRIu64 "/%" PRIu64 "\n", position, total); } else { cols = tgetnum ((char *) "co"); if (cols < 32) goto dumb; /* Update an existing progress bar just printed? */ if (bar->count > 0) tputs (UP, 2, putchar); bar->count++; /* Find out if we're in "pulse mode". */ pulse_mode = position == 0 && total == 1; ratio = (double) position / total; if (ratio < 0) ratio = 0; else if (ratio > 1) ratio = 1; if (pulse_mode) { printf ("%s --- ", spinner (bar, bar->count)); } else if (ratio < 1) { int percent = 100.0 * ratio; printf ("%s%3d%% ", spinner (bar, bar->count), percent); } else { fputs (" 100% ", stdout); } if (bar->utf8_mode) { s_open = "\u27e6"; s_dot = "\u2593"; s_dash = "\u2550"; s_close = "\u27e7"; } else { s_open = "["; s_dot = "#"; s_dash = "-"; s_close = "]"; } fputs (s_open, stdout); if (!pulse_mode) { size_t dots = ratio * (double) (cols - COLS_OVERHEAD); for (i = 0; i < dots; ++i) fputs (s_dot, stdout); for (i = dots; i < cols - COLS_OVERHEAD; ++i) fputs (s_dash, stdout); } else { /* "Pulse mode": the progress bar just pulses. */ for (i = 0; i < cols - COLS_OVERHEAD; ++i) { int cc = (bar->count * 3 - i) % (cols - COLS_OVERHEAD); if (cc >= 0 && cc <= 3) fputs (s_dot, stdout); else fputs (s_dash, stdout); } } fputs (s_close, stdout); fputc (' ', stdout); /* Time estimate. */ double estimate = estimate_remaining_time (bar, ratio); if (estimate >= 100.0 * 60.0 * 60.0 /* >= 100 hours */) { /* Display hours<h> */ estimate /= 60. * 60.; int hh = floor (estimate); printf (">%dh", hh); } else if (estimate >= 100.0 * 60.0 /* >= 100 minutes */) { /* Display hours<h>minutes */ estimate /= 60. * 60.; int hh = floor (estimate); double ignore; int mm = floor (modf (estimate, &ignore) * 60.); printf ("%02dh%02d", hh, mm); } else if (estimate >= 0.0) { /* Display minutes:seconds */ estimate /= 60.; int mm = floor (estimate); double ignore; int ss = floor (modf (estimate, &ignore) * 60.); printf ("%02d:%02d", mm, ss); } else /* < 0 means estimate was not meaningful */ fputs ("--:--", stdout); fputc ('\n', stdout); } fflush (stdout); }
real_t Triangle::intersect(ray_t myRay){ //variable names taken from shirley text //corresponding to equation 4.2 real_t a = vertices[0].position.x - vertices[1].position.x; real_t b = vertices[0].position.y - vertices[1].position.y; real_t c = vertices[0].position.z - vertices[1].position.z; real_t d = vertices[0].position.x - vertices[2].position.x; real_t e = vertices[0].position.y - vertices[2].position.y; real_t f = vertices[0].position.z - vertices[2].position.z; real_t g = myRay.direction.x; real_t h = myRay.direction.y; real_t i = myRay.direction.z; real_t j = vertices[0].position.x - myRay.eye.x; real_t k = vertices[0].position.y - myRay.eye.y; real_t l = vertices[0].position.z - myRay.eye.z; real_t akMinusjb = a * k - j * b; real_t jcMinusal = j * c - a * l; real_t blMinuskc = b * l - k * c; real_t eiMinushf = e * i - h * f; real_t gfMinusdi = g * f - d * i; real_t dhMinuseg = d * h - e * g; real_t M = a * eiMinushf + b * gfMinusdi + c * dhMinuseg; real_t t = -1.0 * (f * akMinusjb + e * jcMinusal + d * blMinuskc)/M; if( (t < SLOP_FACTOR) || (t > 100) ) return -1; real_t gamma = (i * akMinusjb + h * jcMinusal + g * blMinuskc)/M; if( (gamma < 0) || (gamma > 1) ) return -1; real_t beta = (j * eiMinushf + k * gfMinusdi + l * dhMinuseg)/M; if( (beta < 0) || (beta > 1 - gamma) ) return -1; Vector2 coords = (beta * vertices[1].tex_coord) + (gamma * vertices[2].tex_coord) + ((1-beta-gamma) * vertices[0].tex_coord); double scratch; coords.x = modf(coords.x, &scratch); coords.y = modf(coords.y, &scratch); int width; int height; int x; int y; vertices[1].material->get_texture_size(&width, &height); x = coords.x * width; y = coords.y * height; Color3 betaPixel = vertices[1].material->get_texture_pixel(x,y); vertices[2].material->get_texture_size(&width, &height); x = coords.x * width; y = coords.y * height; Color3 gammaPixel = vertices[2].material->get_texture_pixel(x, y); vertices[0].material->get_texture_size(&width, &height); x = coords.x * width; y = coords.y * height; Color3 betaGammaPixel = vertices[0].material->get_texture_pixel(x, y); texture = beta * betaPixel + gamma * gammaPixel + (1-beta-gamma) * betaGammaPixel; diffuse = (beta * vertices[1].material->diffuse) + (gamma * vertices[2].material->diffuse) + ((1-beta-gamma) * vertices[0].material->diffuse); ambient = (beta * vertices[1].material->ambient) + (gamma * vertices[2].material->ambient) + ((1-beta-gamma) * vertices[0].material->ambient); specular = (beta * vertices[1].material->specular) + (gamma * vertices[2].material->specular) + ((1-beta-gamma) * vertices[0].material->specular); normal = (beta * vertices[1].normal) + (gamma * vertices[2].normal) + ((1-beta-gamma) * vertices[0].normal); normal = normalize(normal); intersection = myRay.eye + (t * myRay.direction); return t; }
/** * grpc_rb_time_timeval creates a time_eval from a ruby time object. * * This func is copied from ruby source, MRI/source/time.c, which is published * under the same license as the ruby.h, on which the entire extensions is * based. */ gpr_timespec grpc_rb_time_timeval(VALUE time, int interval) { gpr_timespec t; gpr_timespec *time_const; const char *tstr = interval ? "time interval" : "time"; const char *want = " want <secs from epoch>|<Time>|<GRPC::TimeConst.*>"; switch (TYPE(time)) { case T_DATA: if (CLASS_OF(time) == grpc_rb_cTimeVal) { Data_Get_Struct(time, gpr_timespec, time_const); t = *time_const; } else if (CLASS_OF(time) == rb_cTime) { t.tv_sec = NUM2INT(rb_funcall(time, id_tv_sec, 0)); t.tv_nsec = NUM2INT(rb_funcall(time, id_tv_nsec, 0)); } else { rb_raise(rb_eTypeError, "bad input: (%s)->c_timeval, got <%s>,%s", tstr, rb_obj_classname(time), want); } break; case T_FIXNUM: t.tv_sec = FIX2LONG(time); if (interval && t.tv_sec < 0) rb_raise(rb_eArgError, "%s must be positive", tstr); t.tv_nsec = 0; break; case T_FLOAT: if (interval && RFLOAT_VALUE(time) < 0.0) rb_raise(rb_eArgError, "%s must be positive", tstr); else { double f, d; d = modf(RFLOAT_VALUE(time), &f); if (d < 0) { d += 1; f -= 1; } t.tv_sec = (time_t)f; if (f != t.tv_sec) { rb_raise(rb_eRangeError, "%f out of Time range", RFLOAT_VALUE(time)); } t.tv_nsec = (time_t)(d * 1e9 + 0.5); } break; case T_BIGNUM: t.tv_sec = NUM2LONG(time); if (interval && t.tv_sec < 0) rb_raise(rb_eArgError, "%s must be positive", tstr); t.tv_nsec = 0; break; default: rb_raise(rb_eTypeError, "bad input: (%s)->c_timeval, got <%s>,%s", tstr, rb_obj_classname(time), want); break; } return t; }
static bool IsIntegral(double d) { double integral_part; return modf(d, &integral_part) == 0.0; }
pixel *Graphics::resample_img(pixel *src, int sw, int sh, int rw, int rh) { #ifdef HIGH_QUALITY_RESAMPLE unsigned char * source = (unsigned char*)src; int sourceWidth = sw, sourceHeight = sh; int resultWidth = rw, resultHeight = rh; int sourcePitch = sourceWidth*PIXELSIZE, resultPitch = resultWidth*PIXELSIZE; // Filter scale - values < 1.0 cause aliasing, but create sharper looking mips. const float filter_scale = 0.75f; const char* pFilter = "lanczos12"; Resampler * resamplers[PIXELCHANNELS]; float * samples[PIXELCHANNELS]; //Resampler for each colour channel if (sourceWidth <= 0 || sourceHeight <= 0 || resultWidth <= 0 || resultHeight <= 0) return NULL; resamplers[0] = new Resampler(sourceWidth, sourceHeight, resultWidth, resultHeight, Resampler::BOUNDARY_CLAMP, 0.0f, 1.0f, pFilter, NULL, NULL, filter_scale, filter_scale); samples[0] = new float[sourceWidth]; for (int i = 1; i < PIXELCHANNELS; i++) { resamplers[i] = new Resampler(sourceWidth, sourceHeight, resultWidth, resultHeight, Resampler::BOUNDARY_CLAMP, 0.0f, 1.0f, pFilter, resamplers[0]->get_clist_x(), resamplers[0]->get_clist_y(), filter_scale, filter_scale); samples[i] = new float[sourceWidth]; } unsigned char * resultImage = new unsigned char[resultHeight * resultPitch]; std::fill(resultImage, resultImage + (resultHeight*resultPitch), 0); //Resample time int resultY = 0; for (int sourceY = 0; sourceY < sourceHeight; sourceY++) { unsigned char * sourcePixel = &source[sourceY * sourcePitch]; //Move pixel components into channel samples for (int c = 0; c < PIXELCHANNELS; c++) { for (int x = 0; x < sourceWidth; x++) { samples[c][x] = sourcePixel[(x*PIXELSIZE)+c] * (1.0f/255.0f); } } //Put channel sample data into resampler for (int c = 0; c < PIXELCHANNELS; c++) { if (!resamplers[c]->put_line(&samples[c][0])) { printf("Out of memory!\n"); return NULL; } } //Perform resample and Copy components from resampler result samples to image buffer for ( ; ; ) { int comp_index; for (comp_index = 0; comp_index < PIXELCHANNELS; comp_index++) { const float* resultSamples = resamplers[comp_index]->get_line(); if (!resultSamples) break; unsigned char * resultPixel = &resultImage[(resultY * resultPitch) + comp_index]; for (int x = 0; x < resultWidth; x++) { int c = (int)(255.0f * resultSamples[x] + .5f); if (c < 0) c = 0; else if (c > 255) c = 255; *resultPixel = (unsigned char)c; resultPixel += PIXELSIZE; } } if (comp_index < PIXELCHANNELS) break; resultY++; } } //Clean up for(int i = 0; i < PIXELCHANNELS; i++) { delete resamplers[i]; delete[] samples[i]; } return (pixel*)resultImage; #else #ifdef DEBUG std::cout << "Resampling " << sw << "x" << sh << " to " << rw << "x" << rh << std::endl; #endif bool stairstep = false; if(rw < sw || rh < sh) { float fx = (float)(((float)sw)/((float)rw)); float fy = (float)(((float)sh)/((float)rh)); int fxint, fyint; double fxintp_t, fyintp_t; float fxf = modf(fx, &fxintp_t), fyf = modf(fy, &fyintp_t); fxint = fxintp_t; fyint = fyintp_t; if(((fxint & (fxint-1)) == 0 && fxf < 0.1f) || ((fyint & (fyint-1)) == 0 && fyf < 0.1f)) stairstep = true; #ifdef DEBUG if(stairstep) std::cout << "Downsampling by " << fx << "x" << fy << " using stairstepping" << std::endl; else std::cout << "Downsampling by " << fx << "x" << fy << " without stairstepping" << std::endl; #endif } int y, x, fxceil, fyceil; //int i,j,x,y,w,h,r,g,b,c; pixel *q = NULL; if(rw == sw && rh == sh){ //Don't resample q = new pixel[rw*rh]; std::copy(src, src+(rw*rh), q); } else if(!stairstep) { float fx, fy, fyc, fxc; double intp; pixel tr, tl, br, bl; q = new pixel[rw*rh]; //Bilinear interpolation for upscaling for (y=0; y<rh; y++) for (x=0; x<rw; x++) { fx = ((float)x)*((float)sw)/((float)rw); fy = ((float)y)*((float)sh)/((float)rh); fxc = modf(fx, &intp); fyc = modf(fy, &intp); fxceil = (int)ceil(fx); fyceil = (int)ceil(fy); if (fxceil>=sw) fxceil = sw-1; if (fyceil>=sh) fyceil = sh-1; tr = src[sw*(int)floor(fy)+fxceil]; tl = src[sw*(int)floor(fy)+(int)floor(fx)]; br = src[sw*fyceil+fxceil]; bl = src[sw*fyceil+(int)floor(fx)]; q[rw*y+x] = PIXRGB( (int)(((((float)PIXR(tl))*(1.0f-fxc))+(((float)PIXR(tr))*(fxc)))*(1.0f-fyc) + ((((float)PIXR(bl))*(1.0f-fxc))+(((float)PIXR(br))*(fxc)))*(fyc)), (int)(((((float)PIXG(tl))*(1.0f-fxc))+(((float)PIXG(tr))*(fxc)))*(1.0f-fyc) + ((((float)PIXG(bl))*(1.0f-fxc))+(((float)PIXG(br))*(fxc)))*(fyc)), (int)(((((float)PIXB(tl))*(1.0f-fxc))+(((float)PIXB(tr))*(fxc)))*(1.0f-fyc) + ((((float)PIXB(bl))*(1.0f-fxc))+(((float)PIXB(br))*(fxc)))*(fyc)) ); } } else { //Stairstepping float fx, fy, fyc, fxc; double intp; pixel tr, tl, br, bl; int rrw = rw, rrh = rh; pixel * oq; oq = new pixel[sw*sh]; std::copy(src, src+(sw*sh), oq); rw = sw; rh = sh; while(rrw != rw && rrh != rh){ if(rw > rrw) rw *= 0.7; if(rh > rrh) rh *= 0.7; if(rw <= rrw) rw = rrw; if(rh <= rrh) rh = rrh; q = new pixel[rw*rh]; //Bilinear interpolation for (y=0; y<rh; y++) for (x=0; x<rw; x++) { fx = ((float)x)*((float)sw)/((float)rw); fy = ((float)y)*((float)sh)/((float)rh); fxc = modf(fx, &intp); fyc = modf(fy, &intp); fxceil = (int)ceil(fx); fyceil = (int)ceil(fy); if (fxceil>=sw) fxceil = sw-1; if (fyceil>=sh) fyceil = sh-1; tr = oq[sw*(int)floor(fy)+fxceil]; tl = oq[sw*(int)floor(fy)+(int)floor(fx)]; br = oq[sw*fyceil+fxceil]; bl = oq[sw*fyceil+(int)floor(fx)]; q[rw*y+x] = PIXRGB( (int)(((((float)PIXR(tl))*(1.0f-fxc))+(((float)PIXR(tr))*(fxc)))*(1.0f-fyc) + ((((float)PIXR(bl))*(1.0f-fxc))+(((float)PIXR(br))*(fxc)))*(fyc)), (int)(((((float)PIXG(tl))*(1.0f-fxc))+(((float)PIXG(tr))*(fxc)))*(1.0f-fyc) + ((((float)PIXG(bl))*(1.0f-fxc))+(((float)PIXG(br))*(fxc)))*(fyc)), (int)(((((float)PIXB(tl))*(1.0f-fxc))+(((float)PIXB(tr))*(fxc)))*(1.0f-fyc) + ((((float)PIXB(bl))*(1.0f-fxc))+(((float)PIXB(br))*(fxc)))*(fyc)) ); } delete[] oq; oq = q; sw = rw; sh = rh; } } return q; #endif }
sas_frame_t sas_file_spectral_get_frame (sas_file_spectral_t sp, sas_frame_t dest, int n) { int length; int harmonics; double fundamental; double amplitudes[MAX_NUMBER_OF_PARTIALS]; double frequencies[MAX_NUMBER_OF_PARTIALS]; int coefficients[MAX_NUMBER_OF_PARTIALS]; length = sp->t_max - sp->t_min; assert (n < length); /* Find out fundamental and number of harmonics. */ { int t; sas_file_partial_t p; double f_min, f_max; double fp, ip; int i; t = sp->t_min + n; f_min = SAS_MAX_AUDIBLE_FREQUENCY; f_max = 0; for (i = 0; i < sp->used; i++) { p = sp->tracks[i]; if ((p->start <= t) && (t < (p->start + p->length))) { if (p->frequency[t - p->start] < f_min) f_min = p->frequency[t - p->start]; if (p->frequency[t - p->start] > f_max) f_max = p->frequency[t - p->start]; } } assert (f_min > 0); fp = modf (f_max / f_min, &ip); if (fp >= 0.5) { ip += 1; fp -= 1; } harmonics = (int) ip; fundamental = f_min; } /* Adjust number of harmonics. */ if (harmonics > MAX_NUMBER_OF_PARTIALS) { fprintf (stderr, "sas_file_spectral_get_frame: %s: too much harmonics in frame %d\n", sp->filename, n); harmonics = MAX_NUMBER_OF_PARTIALS; /* return NULL; */ } /* Compute amplitudes. */ { int t; sas_file_partial_t p; REAL frequency, coefficient; int i; frequency = 0; coefficient = 0; t = sp->t_min + n; /* Zero arrays. */ for (i = 0; i < harmonics; i++) { amplitudes[i] = 0.0; frequencies[i] = 0.0; coefficients[i] = 0; } /* Scan partials. */ for (i = 0; i < sp->used; i++) { p = sp->tracks[i]; if ((p->start <= t) && (t < (p->start + p->length))) { double fp, ip; int h; fp = modf (p->frequency[t - p->start] / fundamental, &ip); if (fp >= 0.5) { ip += 1; fp -= 1; } h = (int) ip - 1; assert (h < harmonics); /* On harmonic conflict, keep the highest amplitude partial. */ if (amplitudes[h] < p->amplitude[t - p->start]) { amplitudes[h] = p->amplitude[t - p->start]; frequency -= frequencies[h]; coefficient -= coefficients[h]; frequencies[h] = p->frequency[t - p->start]; coefficients[h] = ip; frequency += frequencies[h]; coefficient += coefficients[h]; } } } frequency /= coefficient; fundamental = frequency; } /* We may have a new fundamental; should we recompute the amplitudes of harmonics?. */ /* Fill frame. */ { sas_envelope_t C; double A; int i; /* SM idea: use the following formula to determine properly perceived amplitude. Not implemented. A = (1/sqrt(2)) * sqrt(sum(a_i^2)) */ /* A */ A = 0.0; for (i = 0; i < harmonics; i++) A += amplitudes[i]; if (A > 1.0) A = 1.0; sas_frame_set_amplitude (dest, A); /* F */ sas_frame_set_frequency (dest, fundamental); /* C */ C = sas_envelope_make (fundamental, harmonics, amplitudes); sas_envelope_adjust_for_color (C); sas_frame_set_color (dest, C); /* W */ /* Keep identity mapping. */ } return dest; }
/* * rspamd_dispatcher.create(base,fd, read_cb, write_cb, err_cb[, timeout]) */ static int lua_io_dispatcher_create (lua_State *L) { struct rspamd_io_dispatcher_s *io_dispatcher, **pdispatcher; gint fd; struct lua_dispatcher_cbdata *cbdata; struct timeval tv = {0, 0}; double tv_num, tmp; if (lua_gettop (L) >= 5 && lua_isfunction (L, 3) && lua_isfunction (L, 5)) { cbdata = g_slice_alloc0 (sizeof (struct lua_dispatcher_cbdata)); cbdata->base = lua_check_event_base (L); if (cbdata->base == NULL) { /* Create new event base */ msg_warn ("create new event base as it is not specified"); cbdata->base = event_init (); } cbdata->L = L; fd = lua_tointeger (L, 2); lua_pushvalue (L, 3); cbdata->cbref_read = luaL_ref (L, LUA_REGISTRYINDEX); if (lua_isfunction (L, 4)) { /* Push write callback as well */ lua_pushvalue (L, 4); cbdata->cbref_write = luaL_ref (L, LUA_REGISTRYINDEX); } /* Error callback */ lua_pushvalue (L, 5); cbdata->cbref_err = luaL_ref (L, LUA_REGISTRYINDEX); if (lua_gettop (L) > 5) { tv_num = lua_tonumber (L, 6); tv.tv_sec = trunc (tv_num); tv.tv_usec = modf (tv_num, &tmp) * 1000.; io_dispatcher = rspamd_create_dispatcher (cbdata->base, fd, BUFFER_LINE, lua_io_read_cb, lua_io_write_cb, lua_io_err_cb, &tv, cbdata); } else { io_dispatcher = rspamd_create_dispatcher (cbdata->base, fd, BUFFER_LINE, lua_io_read_cb, lua_io_write_cb, lua_io_err_cb, NULL, cbdata); } cbdata->d = io_dispatcher; /* Push result */ pdispatcher = lua_newuserdata (L, sizeof (struct rspamd_io_dispatcher_s *)); rspamd_lua_setclass (L, "rspamd{io_dispatcher}", -1); *pdispatcher = io_dispatcher; } else { msg_err ("invalid number of arguments to io_dispatcher.create: %d", lua_gettop (L)); lua_pushnil (L); } return 1; }
// hud_calculate_lock_position() will determine where on the screen to draw the lock // indicator, and will determine when a lock has occurred. If the lock indicator is not // on the screen yet, hud_calculate_lock_start_pos() is called to pick a starting location void hud_calculate_lock_position(float frametime) { ship_weapon *swp; weapon_info *wip; static float pixels_moved_while_locking; static float pixels_moved_while_degrading; static int Need_new_start_pos = 0; static double accumulated_x_pixels, accumulated_y_pixels; double int_portion; static float last_dist_to_target; static int catching_up; static int maintain_lock_count = 0; static float catch_up_distance = 0.0f; double hypotenuse, delta_x, delta_y; swp = &Player_ship->weapons; wip = &Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]]; if (Player->target_in_lock_cone) { if (!Players[Player_num].lock_indicator_visible) { hud_calculate_lock_start_pos(); last_dist_to_target = 0.0f; Players[Player_num].lock_indicator_x = Players[Player_num].lock_indicator_start_x; Players[Player_num].lock_indicator_y = Players[Player_num].lock_indicator_start_y; Players[Player_num].lock_indicator_visible = 1; Players[Player_num].lock_time_to_target = i2fl(wip->min_lock_time); catching_up = 0; } Need_new_start_pos = 1; if (Player_ai->current_target_is_locked) { Players[Player_num].lock_indicator_x = Player->current_target_sx; Players[Player_num].lock_indicator_y = Player->current_target_sy; return; } delta_x = Players[Player_num].lock_indicator_x - Player->current_target_sx; delta_y = Players[Player_num].lock_indicator_y - Player->current_target_sy; if (!delta_y && !delta_x) { hypotenuse = 0; } else { hypotenuse = _hypot(delta_y, delta_x); } Players[Player_num].lock_dist_to_target = (float)hypotenuse; if (last_dist_to_target == 0) { last_dist_to_target = Players[Player_num].lock_dist_to_target; } //nprintf(("Alan","dist to target: %.2f\n",Players[Player_num].lock_dist_to_target)); //nprintf(("Alan","last to target: %.2f\n\n",last_dist_to_target)); if (catching_up) { //nprintf(("Alan","IN CATCH UP MODE catch_up_dist is %.2f\n",catch_up_distance)); if ( Players[Player_num].lock_dist_to_target < catch_up_distance ) catching_up = 0; } else { //nprintf(("Alan","IN NORMAL MODE\n")); if ( (Players[Player_num].lock_dist_to_target - last_dist_to_target) > 2.0f ) { catching_up = 1; catch_up_distance = last_dist_to_target + wip->catchup_pixel_penalty; } } last_dist_to_target = Players[Player_num].lock_dist_to_target; if (!catching_up) { Players[Player_num].lock_time_to_target -= frametime; if (Players[Player_num].lock_time_to_target < 0.0f) Players[Player_num].lock_time_to_target = 0.0f; } float lock_pixels_per_sec; if (Players[Player_num].lock_time_to_target > 0) { lock_pixels_per_sec = Players[Player_num].lock_dist_to_target / Players[Player_num].lock_time_to_target; } else { lock_pixels_per_sec = i2fl(wip->lock_pixels_per_sec); } if (lock_pixels_per_sec > wip->lock_pixels_per_sec) { lock_pixels_per_sec = i2fl(wip->lock_pixels_per_sec); } if (catching_up) { pixels_moved_while_locking = wip->catchup_pixels_per_sec * frametime; } else { pixels_moved_while_locking = lock_pixels_per_sec * frametime; } if ((delta_x != 0) && (hypotenuse != 0)) { accumulated_x_pixels += pixels_moved_while_locking * delta_x/hypotenuse; } if ((delta_y != 0) && (hypotenuse != 0)) { accumulated_y_pixels += pixels_moved_while_locking * delta_y/hypotenuse; } if (fl_abs((float)accumulated_x_pixels) > 1.0f) { modf(accumulated_x_pixels, &int_portion); Players[Player_num].lock_indicator_x -= (int)int_portion; if ( fl_abs((float)Players[Player_num].lock_indicator_x - (float)Player->current_target_sx) < fl_abs((float)int_portion) ) Players[Player_num].lock_indicator_x = Player->current_target_sx; accumulated_x_pixels -= int_portion; } if (fl_abs((float)accumulated_y_pixels) > 1.0f) { modf(accumulated_y_pixels, &int_portion); Players[Player_num].lock_indicator_y -= (int)int_portion; if ( fl_abs((float)Players[Player_num].lock_indicator_y - (float)Player->current_target_sy) < fl_abs((float)int_portion) ) Players[Player_num].lock_indicator_y = Player->current_target_sy; accumulated_y_pixels -= int_portion; } if ( Missile_track_loop == -1 ) { if (wip->hud_tracking_snd >= 0) { Missile_track_loop = snd_play_looping( &Snds[wip->hud_tracking_snd], 0.0f , -1, -1); } else { Missile_track_loop = snd_play_looping( &Snds[ship_get_sound(Player_obj, SND_MISSILE_TRACKING)], 0.0f , -1, -1); } } if (!Players[Player_num].lock_time_to_target) { if ( (Players[Player_num].lock_indicator_x == Player->current_target_sx) && (Players[Player_num].lock_indicator_y == Player->current_target_sy) ) { if (maintain_lock_count++ > 1) { Player_ai->current_target_is_locked = 1; } } else { maintain_lock_count = 0; } } } else { if ( Missile_track_loop > -1 ) { snd_stop(Missile_track_loop); Missile_track_loop = -1; } Player_ai->current_target_is_locked = 0; if (!Players[Player_num].lock_indicator_visible) { return; } catching_up = 0; last_dist_to_target = 0.0f; if (Need_new_start_pos) { hud_calculate_lock_start_pos(); Need_new_start_pos = 0; accumulated_x_pixels = 0.0f; accumulated_y_pixels = 0.0f; } delta_x = Players[Player_num].lock_indicator_x - Players[Player_num].lock_indicator_start_x; delta_y = Players[Player_num].lock_indicator_y - Players[Player_num].lock_indicator_start_y; if (!delta_y && !delta_x) { hypotenuse = 0; } else { hypotenuse = _hypot(delta_y, delta_x); } Players[Player_num].lock_time_to_target += frametime; if (Players[Player_num].lock_time_to_target > wip->min_lock_time) Players[Player_num].lock_time_to_target = i2fl(wip->min_lock_time); pixels_moved_while_degrading = 2.0f * wip->lock_pixels_per_sec * frametime; if ((delta_x != 0) && (hypotenuse != 0)) accumulated_x_pixels += pixels_moved_while_degrading * delta_x/hypotenuse; if ((delta_y != 0) && (hypotenuse != 0)) accumulated_y_pixels += pixels_moved_while_degrading * delta_y/hypotenuse; if (fl_abs((float)accumulated_x_pixels) > 1.0f) { modf(accumulated_x_pixels, &int_portion); Players[Player_num].lock_indicator_x -= (int)int_portion; if ( fl_abs((float)Players[Player_num].lock_indicator_x - (float)Players[Player_num].lock_indicator_start_x) < fl_abs((float)int_portion) ) Players[Player_num].lock_indicator_x = Players[Player_num].lock_indicator_start_x; accumulated_x_pixels -= int_portion; } if (fl_abs((float)accumulated_y_pixels) > 1.0f) { modf(accumulated_y_pixels, &int_portion); Players[Player_num].lock_indicator_y -= (int)int_portion; if ( fl_abs((float)Players[Player_num].lock_indicator_y - (float)Players[Player_num].lock_indicator_start_y) < fl_abs((float)int_portion) ) Players[Player_num].lock_indicator_y = Players[Player_num].lock_indicator_start_y; accumulated_y_pixels -= int_portion; } if ( (Players[Player_num].lock_indicator_x == Players[Player_num].lock_indicator_start_x) && (Players[Player_num].lock_indicator_y == Players[Player_num].lock_indicator_start_y) ) { Players[Player_num].lock_indicator_visible = 0; } } }
void Fl_Roller::draw() { if (damage()&(FL_DAMAGE_ALL|FL_DAMAGE_HIGHLIGHT)) draw_box(); int X=0; int Y=0; int W=w(); int H=h(); box()->inset(X,Y,W,H); if (W<=0 || H<=0) return; double s = step(); if (!s) s = (maximum()-minimum())/100; int offset = int(value()/s); const double ARC = 1.5; // 1/2 the number of radians visible const double delta = .2; // radians per knurl if (type()==HORIZONTAL) { // draw shaded ends of wheel: int h1 = W/4+1; // distance from end that shading starts fl_color(button_color()); fl_rectf(X+h1,Y,W-2*h1,H); for (int i=0; h1; i++) { fl_color((Fl_Color)(FL_GRAY-i-1)); int h2 = FL_GRAY-i-1 > FL_DARK3 ? 2*h1/3+1 : 0; fl_rectf(X+h2,Y,h1-h2,H); fl_rectf(X+W-h1,Y,h1-h2,H); h1 = h2; } if (active_r()) { // draw ridges: double junk; for (double y = -ARC+modf(offset*sin(ARC)/(W/2)/delta,&junk)*delta;; y += delta) { int y1 = int((sin(y)/sin(ARC)+1)*W/2); if (y1 <= 0) continue; else if (y1 >= W-1) break; fl_color(FL_DARK3); fl_line(X+y1,Y+1,X+y1,Y+H-1); if (y < 0) y1--; else y1++; fl_color(FL_LIGHT1);fl_line(X+y1,Y+1,X+y1,Y+H-1); } // draw edges: h1 = W/8+1; // distance from end the color inverts fl_color(FL_DARK2); fl_line(X+h1,Y+H-1,X+W-h1,Y+H-1); fl_color(FL_DARK3); fl_line(X,Y+H,X,Y); fl_line(X,Y,X+h1,Y); fl_line(X+W-h1,Y,X+W,Y); fl_color(FL_LIGHT2); fl_line(X+h1,Y,X+W-h1,Y); fl_line(X+W,Y,X+W,Y+H); fl_line(X+W,Y+H,X+W-h1,Y+H); fl_line(X+h1,Y+H,X,Y+H); } } // vertical one else { offset = (1-offset); // draw shaded ends of wheel: int h1 = H/4+1; // distance from end that shading starts fl_color(button_color()); fl_rectf(X,Y+h1,W,H-2*h1); for (int i=0; h1; i++) { fl_color((Fl_Color)(FL_GRAY-i-1)); int h2 = FL_GRAY-i-1 > FL_DARK3 ? 2*h1/3+1 : 0; fl_rectf(X,Y+h2,W,h1-h2); fl_rectf(X,Y+H-h1,W,h1-h2); h1 = h2; } if (active_r()) { // draw ridges: double junk; for (double y = -ARC+modf(offset*sin(ARC)/(H/2)/delta,&junk)*delta; ; y += delta) { int y1 = int((sin(y)/sin(ARC)+1)*H/2); if (y1 <= 0) continue; else if (y1 >= H-1) break; fl_color(FL_DARK3); fl_line(X+1,Y+y1,X+W-1,Y+y1); if (y < 0) y1--; else y1++; fl_color(FL_LIGHT1);fl_line(X+1,Y+y1,X+W-1,Y+y1); } // draw edges: h1 = H/8+1; // distance from end the color inverts fl_color(FL_DARK2); fl_line(X+W-1,Y+h1,X+W-1,Y+H-h1); fl_color(FL_DARK3); fl_line(X+W,Y,X,Y); fl_line(X,Y,X,Y+h1); fl_line(X,Y+H-h1,X,Y+H); fl_color(FL_LIGHT2); fl_line(X,Y+h1,X,Y+H-h1); fl_line(X,Y+H,X+W,Y+H); fl_line(X+W,Y+H,X+W,Y+H-h1); fl_line(X+W,Y+h1,X+W,Y); } } if (focused()) { focus_box()->draw(0,0,w(),h(), FL_BLACK, FL_INVISIBLE); } }
CC_FILE_ERROR LASFilter::saveToFile(ccHObject* entity, const char* filename) { if (!entity || !filename) return CC_FERR_BAD_ARGUMENT; ccHObject::Container clouds; if (entity->isKindOf(CC_POINT_CLOUD)) clouds.push_back(entity); else entity->filterChildren(clouds, true, CC_POINT_CLOUD); if (clouds.empty()) { ccConsole::Error("No point cloud in input selection!"); return CC_FERR_BAD_ENTITY_TYPE; } else if (clouds.size()>1) { ccConsole::Error("Can't save more than one cloud per LAS file!"); return CC_FERR_BAD_ENTITY_TYPE; } //the cloud to save ccGenericPointCloud* theCloud = static_cast<ccGenericPointCloud*>(clouds[0]); unsigned numberOfPoints = theCloud->size(); if (numberOfPoints==0) { ccConsole::Error("Cloud is empty!"); return CC_FERR_BAD_ENTITY_TYPE; } //colors bool hasColor = theCloud->hasColors(); //classification (as a scalar field) CCLib::ScalarField* classifSF = 0; if (theCloud->isA(CC_POINT_CLOUD)) { ccPointCloud* pc = static_cast<ccPointCloud*>(theCloud); int sfIdx = pc->getScalarFieldIndexByName(CC_LAS_CLASSIFICATION_FIELD_NAME); if (sfIdx>=0) { classifSF = pc->getScalarField(sfIdx); if (/*classifSF->getMax()>(ScalarType)liblas::Classification::class_table_size ||*/ classifSF->getMin()<0) { ccConsole::Warning("[LASFilter] Found a 'classification' scalar field, but its values outbounds LAS specifications (0-255)..."); classifSF = 0; } else { //we check that it's only integer values! unsigned i,count=classifSF->currentSize(); classifSF->placeIteratorAtBegining(); double integerPart = 0.0; for (i=0;i<count;++i) { if (modf(classifSF->getCurrentValue(),&integerPart) != 0.0) { ccConsole::Warning("[LASFilter] Found a 'classification' scalar field, but its values are not pure integers..."); classifSF = 0; break; } } } } } //open binary file for writing std::ofstream ofs; ofs.open(filename, std::ios::out | std::ios::binary); if (ofs.fail()) return CC_FERR_WRITING; const double* shift = theCloud->getOriginalShift(); liblas::Writer* writer = 0; try { liblas::Header header; //LAZ support based on extension! if (QFileInfo(filename).suffix().toUpper() == "LAZ") { header.SetCompressed(true); } //header.SetDataFormatId(liblas::ePointFormat3); ccBBox bBox = theCloud->getBB(); if (bBox.isValid()) { header.SetMin(-shift[0]+(double)bBox.minCorner().x,-shift[1]+(double)bBox.minCorner().y,-shift[2]+(double)bBox.minCorner().z); header.SetMax(-shift[0]+(double)bBox.maxCorner().x,-shift[1]+(double)bBox.maxCorner().y,-shift[2]+(double)bBox.maxCorner().z); CCVector3 diag = bBox.getDiagVec(); //Set offset & scale, as points will be stored as boost::int32_t values (between 0 and 4294967296) //int_value = (double_value-offset)/scale header.SetOffset(-shift[0]+(double)bBox.minCorner().x,-shift[1]+(double)bBox.minCorner().y,-shift[2]+(double)bBox.minCorner().z); header.SetScale(1.0e-9*std::max<double>(diag.x,ZERO_TOLERANCE), //result must fit in 32bits?! 1.0e-9*std::max<double>(diag.y,ZERO_TOLERANCE), 1.0e-9*std::max<double>(diag.z,ZERO_TOLERANCE)); } header.SetPointRecordsCount(numberOfPoints); //header.SetDataFormatId(Header::ePointFormat1); writer = new liblas::Writer(ofs, header); } catch (...) { return CC_FERR_WRITING; } //progress dialog ccProgressDialog pdlg(true); //cancel available CCLib::NormalizedProgress nprogress(&pdlg,numberOfPoints); pdlg.setMethodTitle("Save LAS file"); char buffer[256]; sprintf(buffer,"Points: %i",numberOfPoints); pdlg.setInfo(buffer); pdlg.start(); //liblas::Point point(boost::shared_ptr<liblas::Header>(new liblas::Header(writer->GetHeader()))); liblas::Point point(&writer->GetHeader()); for (unsigned i=0; i<numberOfPoints; i++) { const CCVector3* P = theCloud->getPoint(i); { double x=-shift[0]+(double)P->x; double y=-shift[1]+(double)P->y; double z=-shift[2]+(double)P->z; point.SetCoordinates(x, y, z); } if (hasColor) { const colorType* rgb = theCloud->getPointColor(i); point.SetColor(liblas::Color(rgb[0]<<8,rgb[1]<<8,rgb[2]<<8)); //DGM: LAS colors are stored on 16 bits! } if (classifSF) { liblas::Classification classif; classif.SetClass((boost::uint32_t)classifSF->getValue(i)); point.SetClassification(classif); } writer->WritePoint(point); if (!nprogress.oneStep()) break; } delete writer; //ofs.close(); return CC_FERR_NO_ERROR; }
static double sinus(double x, int cos_flag) { /* Algorithm and coefficients from: "Software manual for the elementary functions" by W.J. Cody and W. Waite, Prentice-Hall, 1980 */ static double r[] = { -0.16666666666666665052e+0, 0.83333333333331650314e-2, -0.19841269841201840457e-3, 0.27557319210152756119e-5, -0.25052106798274584544e-7, 0.16058936490371589114e-9, -0.76429178068910467734e-12, 0.27204790957888846175e-14 }; double y; int neg = 1; if (__IsNan(x)) { errno = EDOM; return x; } if (x < 0) { x = -x; neg = -1; } if (cos_flag) { neg = 1; y = M_PI_2 + x; } else y = x; /* ??? avoid loss of significance, if y is too large, error ??? */ y = y * M_1_PI + 0.5; if (y >= DBL_MAX/M_PI) return 0.0; /* Use extended precision to calculate reduced argument. Here we used 12 bits of the mantissa for a1. Also split x in integer part x1 and fraction part x2. */ #define A1 3.1416015625 #define A2 -8.908910206761537356617e-6 { double x1, x2; modf(y, &y); if (modf(0.5*y, &x1)) neg = -neg; if (cos_flag) y -= 0.5; x2 = modf(x, &x1); x = x1 - y * A1; x += x2; x -= y * A2; #undef A1 #undef A2 } if (x < 0) { neg = -neg; x = -x; } /* ??? avoid underflow ??? */ y = x * x; x += x * y * POLYNOM7(y, r); return neg==-1 ? -x : x; }
static char* cvt(double arg, size_t ndigits, int *decpt, int *sign, int eflag) { register int r2; double fi, fj; register char *p, *p1; static char buf[NDIG]; #ifdef IEEE /* XXX */ if (__isspecial(arg, buf)) return(buf); #endif if (ndigits>=NDIG-1) ndigits = NDIG-2; r2 = 0; *sign = 0; p = &buf[0]; if (arg<0) { *sign = 1; arg = -arg; } arg = modf(arg, &fi); p1 = &buf[NDIG]; /* * Do integer part */ if (fi != 0) { p1 = &buf[NDIG]; while (fi != 0) { fj = modf(fi/10, &fi); *--p1 = (int)((fj+.03)*10) + '0'; r2++; } while (p1 < &buf[NDIG]) *p++ = *p1++; } else if (arg > 0) { while ((fj = arg*10) < 1) { arg = fj; r2--; } } p1 = &buf[ndigits]; if (eflag==0) p1 += r2; *decpt = r2; if (p1 < &buf[0]) { buf[0] = '\0'; return(buf); } while (p<=p1 && p<&buf[NDIG]) { arg *= 10; arg = modf(arg, &fj); *p++ = (int)fj + '0'; } if (p1 >= &buf[NDIG]) { buf[NDIG-1] = '\0'; return(buf); } p = p1; *p1 += 5; while (*p1 > '9') { *p1 = '0'; if (p1>buf) ++*--p1; else { *p1 = '1'; (*decpt)++; if (eflag==0) { if (p>buf) *p = '0'; p++; } } } *p = '\0'; return(buf); }
double wrapper_get_frac(wrapper_t *wrap) { double i; return modf(wrap->fu.f, &i); }
return newDinar; } std::ostream& operator << (std::ostream &out, const Dinar &x) { double currencyValue = x.getWholeVal() + x.getFractVal(); out << to_string(currencyValue); return out; } std::istream& operator >> (std::istream &in, Dinar &x) { double fract, whole, val; in >> val; // Extract whole and fractional parts fract = modf(val, &whole); fract *= 100; fract = round(fract); Dinar newDinar; x.setWholeVal(static_cast<unsigned>(whole)+x.getWholeVal()); x.setFractVal(fract + x.getFractVal()); x.updateCurrencyVal(); return in; }
void SpectrumPanel::drawPanelContents() { glDisable(GL_TEXTURE_2D); glEnable(GL_BLEND); glEnable(GL_LINE_SMOOTH); glHint( GL_LINE_SMOOTH_HINT, GL_NICEST ); glLoadMatrixf(transform * (CubicVR::mat4::translate(-1.0f, -0.75f, 0.0f) * CubicVR::mat4::scale(2.0f, 1.5f, 1.0f))); if (points.size()) { glBlendFunc(GL_SRC_ALPHA, GL_ONE); double range = ceilValue-floorValue; double ranges[3][4] = { { 90.0, 5000.0, 10.0, 100.0 }, { 20.0, 150.0, 10.0, 10.0 }, { -20.0, 30.0, 10.0, 1.0 } }; for (int i = 0; i < 3; i++) { double p = 0; double rangeMin = ranges[i][0]; double rangeMax = ranges[i][1]; double rangeTrans = ranges[i][2]; double rangeStep = ranges[i][3]; if (range >= rangeMin && range <= rangeMax) { double a = 1.0; if (range <= rangeMin+rangeTrans) { a *= (range-rangeMin)/rangeTrans; } if (range >= rangeMax-rangeTrans) { a *= (rangeTrans-(range-(rangeMax-rangeTrans)))/rangeTrans; } glColor4f(0.12f, 0.12f, 0.12f, a); glBegin(GL_LINES); for (double l = floorValue; l<=ceilValue+rangeStep; l+=rangeStep) { p += rangeStep/range; glVertex2f(0,p); glVertex2f(1,p); } glEnd(); } } glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor3f(ThemeMgr::mgr.currentTheme->fftLine.r, ThemeMgr::mgr.currentTheme->fftLine.g, ThemeMgr::mgr.currentTheme->fftLine.b); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, &points[0]); glDrawArrays(GL_LINE_STRIP, 0, points.size() / 2); if (peak_points.size()) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(0, 1.0, 0, 0.5); glVertexPointer(2, GL_FLOAT, 0, &peak_points[0]); glDrawArrays(GL_LINE_STRIP, 0, peak_points.size() / 2); } glDisableClientState(GL_VERTEX_ARRAY); } GLint vp[4]; glGetIntegerv( GL_VIEWPORT, vp); float viewHeight = (float) vp[3]; float viewWidth = (float) vp[2]; glLoadMatrixf(transform); long long leftFreq = (double) freq - ((double) bandwidth / 2.0); long long rightFreq = leftFreq + (double) bandwidth; long long hzStep = 1000000; long double mhzStep = (100000.0 / (long double) (rightFreq - leftFreq)) * 2.0; double mhzVisualStep = 0.1; std::stringstream label; label.precision(1); double fontScale = GLFont::getScaleFactor(); if (mhzStep * 0.5 * viewWidth < 40 * fontScale) { mhzStep = (250000.0 / (long double) (rightFreq - leftFreq)) * 2.0; mhzVisualStep = 0.25; if (mhzStep * 0.5 * viewWidth < 40 * fontScale) { mhzStep = (500000.0 / (long double) (rightFreq - leftFreq)) * 2.0; mhzVisualStep = 0.5; } if (mhzStep * 0.5 * viewWidth < 40 * fontScale) { mhzStep = (1000000.0 / (long double) (rightFreq - leftFreq)) * 2.0; mhzVisualStep = 1.0; } if (mhzStep * 0.5 * viewWidth < 40 * fontScale) { mhzStep = (2500000.0 / (long double) (rightFreq - leftFreq)) * 2.0; mhzVisualStep = 2.5; } if (mhzStep * 0.5 * viewWidth < 40 * fontScale) { mhzStep = (5000000.0 / (long double) (rightFreq - leftFreq)) * 2.0; mhzVisualStep = 5.0; } if (mhzStep * 0.5 * viewWidth < 40 * fontScale) { mhzStep = (10000000.0 / (long double) (rightFreq - leftFreq)) * 2.0; mhzVisualStep = 10.0; } if (mhzStep * 0.5 * viewWidth < 40 * fontScale) { mhzStep = (50000000.0 / (long double) (rightFreq - leftFreq)) * 2.0; mhzVisualStep = 50.0; } } else if (mhzStep * 0.5 * viewWidth > 350 * fontScale) { mhzStep = (10000.0 / (long double) (rightFreq - leftFreq)) * 2.0; mhzVisualStep = 0.01; label.precision(2); } long long firstMhz = (leftFreq / hzStep) * hzStep; long double mhzStart = ((long double) (firstMhz - leftFreq) / (long double) (rightFreq - leftFreq)) * 2.0; long double currentMhz = trunc(floor(firstMhz / (long double)1000000.0)); double hPos = 1.0 - (16.0 / viewHeight) * GLFont::getScaleFactor(); double lMhzPos = 1.0 - (5.0 / viewHeight); int fontSize = 12; if (viewHeight > 135) { fontSize = 16; hPos = 1.0 - (18.0 / viewHeight) * GLFont::getScaleFactor(); } GLFont::Drawer refDrawingFont = GLFont::getFont(fontSize, GLFont::getScaleFactor()); for (double m = -1.0 + mhzStart, mMax = 1.0 + ((mhzStart>0)?mhzStart:-mhzStart); m <= mMax; m += mhzStep) { if (m < -1.0) { currentMhz += mhzVisualStep; continue; } if (m > 1.0) { break; } label << std::fixed << currentMhz; double fractpart, intpart; fractpart = modf(currentMhz, &intpart); if (fractpart < 0.001) { glLineWidth(4.0); glColor3f(ThemeMgr::mgr.currentTheme->freqLine.r, ThemeMgr::mgr.currentTheme->freqLine.g, ThemeMgr::mgr.currentTheme->freqLine.b); } else { glLineWidth(1.0); glColor3f(ThemeMgr::mgr.currentTheme->freqLine.r * 0.65, ThemeMgr::mgr.currentTheme->freqLine.g * 0.65, ThemeMgr::mgr.currentTheme->freqLine.b * 0.65); } glDisable(GL_TEXTURE_2D); glBegin(GL_LINES); glVertex2f(m, lMhzPos); glVertex2f(m, 1); glEnd(); glColor4f(ThemeMgr::mgr.currentTheme->text.r, ThemeMgr::mgr.currentTheme->text.g, ThemeMgr::mgr.currentTheme->text.b,1.0); refDrawingFont.drawString(label.str(), m, hPos, GLFont::GLFONT_ALIGN_CENTER, GLFont::GLFONT_ALIGN_CENTER, 0, 0, true); label.str(std::string()); currentMhz += mhzVisualStep; } glLineWidth(1.0); if (showDb) { float dbPanelWidth = (1.0 / viewWidth)*88.0 * GLFont::getScaleFactor(); float dbPanelHeight = (1.0/viewHeight)*14.0 * GLFont::getScaleFactor(); std::stringstream ssLabel(""); if (getCeilValue() != getFloorValue() && fftSize) { ssLabel << std::fixed << std::setprecision(1) << (20.0 * log10(2.0*(getCeilValue())/(double)fftSize)) << "dB"; } dbPanelCeil.setText(ssLabel.str(), GLFont::GLFONT_ALIGN_RIGHT); dbPanelCeil.setSize(dbPanelWidth, dbPanelHeight); dbPanelCeil.setPosition(-1.0 + dbPanelWidth, 1.0 - dbPanelHeight); ssLabel.str(""); if (getCeilValue() != getFloorValue() && fftSize) { ssLabel << (20.0 * log10(2.0*(getFloorValue())/(double)fftSize)) << "dB"; } dbPanelFloor.setText(ssLabel.str(), GLFont::GLFONT_ALIGN_RIGHT); dbPanelFloor.setSize(dbPanelWidth, dbPanelHeight); dbPanelFloor.setPosition(-1.0 + dbPanelWidth, - 1.0 + dbPanelHeight); } }
/* * u >= 0 only */ Vec3D Spline::getPoint(float u) { double part; double frac = modf(u, &part); int v = ((int) part ) % (getNumKeyFrames() - 1); return catmull_rom(getKeyPoint(v-1), getKeyPoint(v), getKeyPoint(v+1), getKeyPoint(v+2), frac); }
void PushbroomStereo::RunStereoPushbroomStereo( Mat leftImage, Mat rightImage, Mat laplacian_left, Mat laplacian_right, cv::vector<Point3f> *pointVector3d, cv::vector<Point3i> *pointVector2d, cv::vector<uchar> *pointColors, int row_start, int row_end, PushbroomStereoState state ) { // we will do this by looping through every block in the left image // (defined by blockSize) and checking for a matching value on // the right image cv::vector<Point3f> localHitPoints; int blockSize = state.blockSize; int disparity = state.disparity; int sadThreshold = state.sadThreshold; int startJ = 0; int stopJ = leftImage.cols - (disparity + blockSize); if (disparity < 0) { startJ = -disparity; stopJ = leftImage.cols - blockSize; } //printf("row_start: %d, row_end: %d, startJ: %d, stopJ: %d, rows: %d, cols: %d\n", row_start, row_end, startJ, stopJ, leftImage.rows, leftImage.cols); int hitCounter = 0; if (state.random_results < 0) { int *sadArray = new int[ leftImage.rows * leftImage.step ]; int iStep, jStep; #ifdef USE_GPU StopWatchInterface *timer; sdkCreateTimer( &timer ); sdkResetTimer( &timer ); sdkStartTimer( &timer ); //GetSADBlock(row_start, row_end, blockSize, startJ, stopJ, sadArray, leftImage, rightImage, laplacian_left, laplacian_right, state); m_sadCalculator.runGetSAD( row_start, row_end, startJ, stopJ, sadArray, leftImage.data, rightImage.data, laplacian_left.data, laplacian_right.data, leftImage.step, state.blockSize, state.disparity, state.sobelLimit ); sdkStopTimer( &timer ); //printf("RunStereo bottleneck timer: %.2f ms \n", sdkGetTimerValue( &timer) ); sdkDeleteTimer( &timer ); #endif int gridY = (row_end - row_start)/blockSize; int gridX = (stopJ - startJ)/blockSize; for (int y=0; y< gridY; y++) { for (int x=0; x< gridX; x++) { // check to see if the SAD is below the threshold, // indicating a hit int i = row_start + y * blockSize; int j = startJ + x * blockSize; #ifdef USE_GPU int sad = sadArray[ y * gridX + x]; #else int sad= GetSAD(leftImage, rightImage, laplacian_left, laplacian_right, j, i, state); #endif if (sad < sadThreshold && sad >= 0) { // got a hit // now check for horizontal invariance // (ie check for parts of the image that look the same as this // which would indicate that this might be a false-positive) if (!state.check_horizontal_invariance || CheckHorizontalInvariance(leftImage, rightImage, laplacian_left, laplacian_right, j, i, state) == false) { // add it to the vector of matches // don't forget to offset it by the blockSize, // so we match the center of the block instead // of the top left corner localHitPoints.push_back(Point3f(j+blockSize/2.0, i+blockSize/2.0, -disparity)); //localHitPoints.push_back(Point3f(state.debugJ, state.debugI, -disparity)); uchar pxL = leftImage.at<uchar>(i,j); pointColors->push_back(pxL); // TODO: this is the corner of the box, not the center hitCounter ++; if (state.show_display) { pointVector2d->push_back(Point3i(j, i, sad)); } } // check horizontal invariance } } } } else { double intpart; float fractpart = modf(state.random_results , &intpart); hitCounter = int(intpart); // determine if this is a time we'll use that last point std::random_device rd; std::default_random_engine generator(rd()); // rd() provides a random seed std::uniform_real_distribution<float> distribution(0, 1); if (fractpart > distribution(generator)) { hitCounter ++; } for (int i = 0; i < hitCounter; i++) { int randx = rand() % (stopJ - startJ) + startJ; int randy = rand() % (row_end - row_start) + row_start; localHitPoints.push_back(Point3f(randx, randy, -disparity)); } } // now we have an array of hits -- transform them to 3d points if (hitCounter > 0) { perspectiveTransform(localHitPoints, *pointVector3d, state.Q); } }
int main(int argc, char *argv[]) /* dftfold: Does complex plane vector addition of a DFT freq */ /* Written by Scott Ransom on 31 Aug 00 based on Ransom and */ /* Eikenberry paper I (to be completed sometime...). */ { FILE *infile; char infilenm[200], outfilenm[200]; int dataperread; unsigned long N; double T, rr = 0.0, norm = 1.0; dftvector dftvec; infodata idata; Cmdline *cmd; /* Call usage() if we have no command line arguments */ if (argc == 1) { Program = argv[0]; usage(); exit(1); } /* Parse the command line using the excellent program Clig */ cmd = parseCmdline(argc, argv); #ifdef DEBUG showOptionValues(); #endif printf("\n\n"); printf(" DFT Vector Folding Routine\n"); printf(" by Scott M. Ransom\n"); printf(" 31 August, 2000\n\n"); /* Open the datafile and read the info file */ sprintf(infilenm, "%s.dat", cmd->argv[0]); infile = chkfopen(infilenm, "rb"); readinf(&idata, cmd->argv[0]); /* The number of points in datafile */ N = chkfilelen(infile, sizeof(float)); dataperread = N / cmd->numvect; /* N = cmd->numvect * dataperread; */ T = N * idata.dt; /* Calculate the Fourier frequency */ if (!cmd->rrP) { if (cmd->ffP) rr = cmd->ff; else if (cmd->ppP) rr = T / cmd->pp; else { printf("\n You must specify a frequency to fold! Exiting.\n\n"); } } else rr = cmd->rr; /* Calculate the amplitude normalization if required */ if (cmd->normP) norm = 1.0 / sqrt(cmd->norm); else if (cmd->fftnormP) { FILE *fftfile; int kern_half_width, fftdatalen, startbin; double rrfrac, rrint; char fftfilenm[200]; fcomplex *fftdata; sprintf(fftfilenm, "%s.fft", cmd->argv[0]); fftfile = chkfopen(fftfilenm, "rb"); kern_half_width = r_resp_halfwidth(HIGHACC); fftdatalen = 2 * kern_half_width + 10; rrfrac = modf(rr, &rrint); startbin = (int) rrint - fftdatalen / 2; fftdata = read_fcomplex_file(fftfile, startbin, fftdatalen); norm = 1.0 / sqrt(get_localpower3d(fftdata, fftdatalen, rrfrac + fftdatalen / 2, 0.0, 0.0)); vect_free(fftdata); fclose(fftfile); } /* Initialize the dftvector */ init_dftvector(&dftvec, dataperread, cmd->numvect, idata.dt, rr, norm, T); /* Show our folding values */ printf("\nFolding data from '%s':\n", infilenm); printf(" Folding Fourier Freq = %.5f\n", rr); printf(" Folding Freq (Hz) = %-.11f\n", rr / T); printf(" Folding Period (s) = %-.14f\n", T / rr); printf(" Points per sub-vector = %d\n", dftvec.n); printf(" Number of sub-vectors = %d\n", dftvec.numvect); printf(" Normalization constant = %g\n", norm * norm); /* Perform the actual vector addition */ { int ii, jj; float *data; double real, imag, sumreal = 0.0, sumimag = 0.0; double theta, aa, bb, cc, ss, dtmp; double powargr, powargi, phsargr, phsargi, phstmp; data = gen_fvect(dftvec.n); theta = -TWOPI * rr / (double) N; dtmp = sin(0.5 * theta); aa = -2.0 * dtmp * dtmp; bb = sin(theta); cc = 1.0; ss = 0.0; for (ii = 0; ii < dftvec.numvect; ii++) { chkfread(data, sizeof(float), dftvec.n, infile); real = 0.0; imag = 0.0; for (jj = 0; jj < dftvec.n; jj++) { real += data[jj] * cc; imag += data[jj] * ss; cc = aa * (dtmp = cc) - bb * ss + cc; ss = aa * ss + bb * dtmp + ss; } dftvec.vector[ii].r = norm * real; dftvec.vector[ii].i = norm * imag; sumreal += dftvec.vector[ii].r; sumimag += dftvec.vector[ii].i; } vect_free(data); printf("\nDone:\n"); printf(" Vector sum = %.3f + %.3fi\n", sumreal, sumimag); printf(" Total phase (deg) = %.2f\n", PHASE(sumreal, sumimag)); printf(" Total power = %.2f\n", POWER(sumreal, sumimag)); printf("\n"); } fclose(infile); /* Write the output structure */ sprintf(outfilenm, "%s_%.3f.dftvec", cmd->argv[0], rr); write_dftvector(&dftvec, outfilenm); /* Free our vector and return */ free_dftvector(&dftvec); return (0); }
int ReadFiles(struct CommandLineArgsTag CLA) { char line[256]; INT4 i; FILE *fpS,*fpR,*fpA,*fpSeg; REAL8 Cmag,Cphase,Rmag,Rphase,Amag,Aphase,freq,x,y; static COMPLEX16FrequencySeries R0; static COMPLEX16FrequencySeries C0; static COMPLEX16FrequencySeries A0; /* Allocate space for response and sensing functions; just enough to read first 1200Hz */ LALZCreateVector( &status, &R0.data, MAXLINERS); LALZCreateVector( &status, &C0.data, MAXLINERS); LALZCreateVector( &status, &A0.data, MAXLINERS); /* Fill in R0, C0 data */ R0.f0=0.0; R0.deltaF=1.0/64.0; /*ACHTUNG: HARDWIRED !!*/ C0.f0=0.0; C0.deltaF=1.0/64.0; /*ACHTUNG: HARDWIRED !!*/ A0.f0=0.0; A0.deltaF=1.0/64.0; /*ACHTUNG: HARDWIRED !!*/ /* This is kinda messy... Unfortunately there's no good way of doing this */ /* ------ Open and read Sensing file ------ */ i=0; fpS=fopen(CLA.CFile,"r"); if (fpS==NULL) { fprintf(stderr,"That's weird... %s doesn't exist!\n",CLA.CFile); return 1; } while(fgets(line,sizeof(line),fpS)) { if(*line == '#') continue; if(*line == '%') continue; if (i > MAXLINERS-1) { /* done reading file */ break; } sscanf(line,"%le %le %le",&freq,&Cmag,&Cphase); C0.data->data[i].re=Cmag*cos(Cphase); C0.data->data[i].im=Cmag*sin(Cphase); i++; } fclose(fpS); /* -- close Sensing file -- */ /* ------ Open and read Response file ------ */ i=0; fpR=fopen(CLA.RFile,"r"); if (fpR==NULL) { fprintf(stderr,"That's weird... %s doesn't exist!\n",CLA.RFile); return 1; } while(fgets(line,sizeof(line),fpR)) { if(*line == '#') continue; if(*line == '%') continue; if (i > MAXLINERS-1) { /* done reading file */ break; } sscanf(line,"%le %le %le",&freq,&Rmag,&Rphase); R0.data->data[i].re=Rmag*cos(Rphase); R0.data->data[i].im=Rmag*sin(Rphase); i++; } fclose(fpR); /* -- close Sensing file -- */ /* ------ Open and read Response file ------ */ i=0; fpA=fopen(CLA.AFile,"r"); if (fpA==NULL) { fprintf(stderr,"That's weird... %s doesn't exist!\n",CLA.AFile); return 1; } while(fgets(line,sizeof(line),fpA)) { if(*line == '#') continue; if(*line == '%') continue; if (i > MAXLINERS-1) { /* done reading file */ break; } sscanf(line,"%le %le %le",&freq,&Amag,&Aphase); A0.data->data[i].re=Amag*cos(Aphase); A0.data->data[i].im=Amag*sin(Aphase); i++; } fclose(fpA); /* -- close Sensing file -- */ /* ------ Open and read Segment file ------ */ i=0; fpSeg=fopen(CLA.SegmentsFile,"r"); if (fpSeg==NULL) { fprintf(stderr,"That's weird... %s doesn't exist!\n",CLA.SegmentsFile); return 1; } while(fgets(line,sizeof(line),fpSeg)) { if(*line == '#') continue; if(*line == '%') continue; if (i > MAXLINESEGS-1) { fprintf(stderr,"Too many lines in file %s! Exiting... \n", CLA.SegmentsFile); return 1; } sscanf(line,"%d %d %f",&SL[i].nseg,&SL[i].tgps,&SL[i].seglength); i++; } numsegs=i; fclose(fpSeg); /* -- close Sensing file -- */ /* compute C0 and R0 at correct frequency */ /* use linear interpolation */ x = modf( CLA.f / R0.deltaF, &y ); i = floor( y ); Rf0.re = ( 1 - x ) * R0.data->data[i].re; Rf0.re += x * R0.data->data[i].re; Rf0.im = ( 1 - x ) * R0.data->data[i].im; Rf0.im += x * R0.data->data[i].im; x = modf( CLA.f / C0.deltaF, &y ); i = floor( y ); Cf0.re = ( 1 - x ) * C0.data->data[i].re; Cf0.re += x * C0.data->data[i].re; Cf0.im = ( 1 - x ) * C0.data->data[i].im; Cf0.im += x * C0.data->data[i].im; x = modf( CLA.f / A0.deltaF, &y ); i = floor( y ); Af0.re = ( 1 - x ) * A0.data->data[i].re; Af0.re += x * A0.data->data[i].re; Af0.im = ( 1 - x ) * A0.data->data[i].im; Af0.im += x * A0.data->data[i].im; /* create Frame cache */ framecache = XLALCacheImport(CLA.FrCacheFile); LALFrCacheOpen(&status,&framestream,framecache); XLALDestroyCache(&framecache); LALZDestroyVector(&status,&R0.data); LALZDestroyVector(&status,&C0.data); LALZDestroyVector(&status,&A0.data); return 0; }
static void TestMath() { double eps = 0.000001; double res = fabs(21.091); TEST((21.091 - res) < eps); res = fabs(-1.91); TEST((res - 1.91) < eps); res = atan(0.0); TEST(fabs(res) < eps); // 90 degrees res = tan(KPi/2); TEST(res > 1000000000.0); res = atan(res); TEST(fabs(res - KPi/2) < eps); // 45 degrees res = tan(KPi/4); TEST(fabs(res - 1.0) < eps); res = atan(res); TEST(fabs(res - KPi/4) < eps); // 135 degrees res = tan((3 * KPi) / 4); TEST(fabs(res + 1.0) < eps); res = atan(res); TEST(fabs((KPi + res) - (3 * KPi) / 4) < eps); // 0 degrees res = cos(0.0); TEST(fabs(res - 1) < eps); // 90 degrees res = cos(KPi/2); TEST(res < eps); // 180 degrees res = cos(KPi); TEST(fabs(res + 1.0) < eps); // 0 degrees res = sin(0.0); TEST(res < eps); // 90 degrees res = sin(KPi/2); TEST(fabs(res - 1) < eps); // 180 degrees res = sin(KPi); TEST(res < eps); res = tanh(1.0); TEST(fabs(res - 0.761594) < eps); int exponent; res = frexp(0.51E+2, &exponent); TEST((0.51E+2 - res * pow(2.0, exponent)) < eps); double integer; res = modf(34.567, &integer); TEST(fabs(res - 0.567) < eps); TEST(fabs(integer - 34.0) < eps); res = modf(-35.567, &integer); TEST(fabs(res + 0.567) < eps); TEST(fabs(integer + 35.0) < eps); res = ceil(245.8903); TEST(fabs(res - 246.0) < eps); res = ceil(-11.91); TEST(fabs(res + 11.0) < eps); res = floor(245.8903); TEST(fabs(res - 245.0) < eps); res = floor(-11.91); TEST(fabs(res + 12.0) < eps); res = copysign(4.789, -9.001); TEST((res + 4.789) < eps); res = copysign(-4.789, 9.001); TEST((res - 4.789) < eps); }
static char *cvt(double arg, int ndigits, int *decpt, int *sign, char *buf, int eflag) { int r2; double fi, fj; char *p, *p1; if (ndigits < 0) ndigits = 0; if (ndigits >= CVTBUFSIZE - 1) ndigits = CVTBUFSIZE - 2; r2 = 0; *sign = 0; p = &buf[0]; if (arg < 0) { *sign = 1; arg = -arg; } arg = modf(arg, &fi); p1 = &buf[CVTBUFSIZE]; if (fi != 0) { p1 = &buf[CVTBUFSIZE]; while (fi != 0) { fj = modf(fi / 10, &fi); *--p1 = (int)((fj + .03) * 10) + '0'; r2++; /** \bug Some large doubles seem to generate errors on MosyncLib here. do a check for now. */ if(r2>=CVTBUFSIZE) break; } while (p1 < &buf[CVTBUFSIZE]) *p++ = *p1++; } else if (arg > 0) { while ((fj = arg * 10) < 1) { arg = fj; r2--; } } p1 = &buf[ndigits]; if (eflag == 0) p1 += r2; *decpt = r2; if (p1 < &buf[0]) { buf[0] = '\0'; return buf; } while (p <= p1 && p < &buf[CVTBUFSIZE]) { arg *= 10; arg = modf(arg, &fj); *p++ = (int) fj + '0'; } if (p1 >= &buf[CVTBUFSIZE]) { buf[CVTBUFSIZE - 1] = '\0'; return buf; } p = p1; *p1 += 5; while (*p1 > '9') { *p1 = '0'; if (p1 > buf) ++*--p1; else { *p1 = '1'; (*decpt)++; if (eflag == 0) { if (p > buf) *p = '0'; p++; } } } *p = '\0'; return buf; }
void PolarFreqDomainFilter::Initialize(void) { int i; int samp_num, bin_num; char line_buf[100]; char *item; double tmp_nsexp, frac_part, int_part; double min_data_freq, max_data_freq; double left_freq, right_freq; double bin_freq, left_val, right_val, slope, base; std::complex<float> *time_resp; //PointDataFile input_file; std::complex<float> exponent; std::complex<float> pseudo_complex; ofstream *resp_file; tmp_nsexp = log10(double(Fft_Size))/log10(2.0); frac_part = modf(tmp_nsexp, &int_part); double delta_f = 1.0/(Fft_Size*Dt_For_Fft); //------------------------------------------------------------ // initialize derived parameters Ns_Exp = int_part; Full_Buffer = new std::complex<float>[Fft_Size]; for(i=0; i<Fft_Size; i++) { Full_Buffer[i] = std::complex<float>(0.0,0.0); } time_resp = new std::complex<float>[Fft_Size]; for(i=0; i<Fft_Size; i++) { time_resp[i] = std::complex<float>(0.0,0.0); } FftDitNipo( time_resp, Fft_Size); Mag_Resp = new float[Fft_Size]; Phase_Resp = new float[Fft_Size]; //----------------------------------------------------- // Read in the raw response data Magnitude_Data_File = new ifstream(Magnitude_Data_Fname, ios::in); *Magnitude_Data_File >> Num_Mag_Samps; Magnitude_Data_File->getline(line_buf,100); Raw_Magnitude_Resp = new float[Num_Mag_Samps]; Freqs_For_Magnitude = new float[Num_Mag_Samps]; for(samp_num=0;samp_num<Num_Mag_Samps; samp_num++) { Magnitude_Data_File->getline(line_buf,100); item = strtok(line_buf,",\n\t"); Freqs_For_Magnitude[samp_num] = atof(item); item = strtok(NULL,",\n\t"); Raw_Magnitude_Resp[samp_num] = atof(item); } Magnitude_Data_File->close(); resp_file = new ofstream("mag_resp.txt\0", ios::out); min_data_freq = Mag_Freq_Scaling_Factor * Freqs_For_Magnitude[0]; max_data_freq = Mag_Freq_Scaling_Factor * Freqs_For_Magnitude[Num_Mag_Samps-1]; samp_num=-1; right_freq = Mag_Freq_Scaling_Factor * Freqs_For_Magnitude[0]; right_val = pow(10.0,(Raw_Magnitude_Resp[0]/20.0)); left_freq = -delta_f*Fft_Size/2; slope = right_val/(right_freq-left_freq); base = -left_freq*slope; for(bin_num=-Fft_Size/2;bin_num<0;bin_num++) { bin_freq = bin_num * delta_f; if(bin_freq < min_data_freq) // // put straight-line skirt on negative frequency portion // not covered by input data { Mag_Resp[Fft_Size+bin_num] = bin_freq * slope + base; } else // // do negative-frequency portion that is covered by input data { if(bin_freq >= right_freq) { samp_num++; left_freq = right_freq; right_freq = Mag_Freq_Scaling_Factor * Freqs_For_Magnitude[samp_num+1]; left_val = pow(10.0, Raw_Magnitude_Resp[samp_num]/20.0); right_val = pow(10.0, Raw_Magnitude_Resp[samp_num+1]/20.0); slope = (right_val - left_val)/(right_freq - left_freq); base = left_val - left_freq*slope; } Mag_Resp[Fft_Size+bin_num] = bin_freq * slope + base; } *resp_file << bin_num << ", " << Mag_Resp[Fft_Size+bin_num] << endl; } // // do the positive frequency portion which is covered by input data bin_freq = 0; bin_num = 0; while(bin_freq<max_data_freq && bin_num<Fft_Size/2) { bin_freq = bin_num * delta_f; if(bin_freq >= right_freq) { samp_num++; left_freq = right_freq; right_freq = Mag_Freq_Scaling_Factor * Freqs_For_Magnitude[samp_num+1]; left_val = pow(10.0, Raw_Magnitude_Resp[samp_num]/20.0); right_val = pow(10.0, Raw_Magnitude_Resp[samp_num+1]/20.0); slope = (right_val - left_val)/(right_freq - left_freq); base = left_val - left_freq*slope; } Mag_Resp[bin_num] = bin_freq * slope + base; *resp_file << bin_num << ", " << Mag_Resp[bin_num] << endl; bin_num++; } // // put straight-line skirt on positive frequency portion not coverd by input data left_freq = Mag_Freq_Scaling_Factor * Freqs_For_Magnitude[Num_Mag_Samps-1]; left_val = pow(10.0,(Raw_Magnitude_Resp[Num_Mag_Samps-1]/20.0)); right_freq = delta_f*(Fft_Size-2)/2; slope = -left_val/(right_freq-left_freq); base = left_val-left_freq*slope; while(bin_num<Fft_Size/2) { bin_freq = bin_num * delta_f; Mag_Resp[bin_num] = bin_freq * slope + base; *resp_file << bin_num << ", " << Mag_Resp[bin_num] << endl; bin_num++; } resp_file->close(); Phase_Data_File = new ifstream(Phase_Data_Fname, ios::in); *Phase_Data_File >> Num_Phase_Samps; Phase_Data_File->getline(line_buf,100); Raw_Phase_Resp = new float[Num_Phase_Samps]; Freqs_For_Phase = new float[Num_Phase_Samps]; for(samp_num=0;samp_num<Num_Phase_Samps; samp_num++) { Phase_Data_File->getline(line_buf,100); item = strtok(line_buf,",\n\t"); Freqs_For_Phase[samp_num] = atof(item); item = strtok(NULL,",\n\t"); Raw_Phase_Resp[samp_num] = atof(item); } Phase_Data_File->close(); resp_file = new ofstream("Phase_resp.txt\0", ios::out); min_data_freq = Mag_Freq_Scaling_Factor * Freqs_For_Phase[0]; max_data_freq = Mag_Freq_Scaling_Factor * Freqs_For_Phase[Num_Phase_Samps-1]; samp_num=-1; right_freq = Phase_Freq_Scaling_Factor * Freqs_For_Phase[0]; right_val = Raw_Phase_Resp[0]; left_freq = -delta_f*Fft_Size/2; slope = right_val/(right_freq-left_freq); base = -left_freq*slope; for(bin_num=-Fft_Size/2;bin_num<0;bin_num++) { bin_freq = bin_num * delta_f; if(bin_freq < min_data_freq) // // put straight-line skirt on negative frequency portion // not covered by input data { //Phase_Resp[Fft_Size+bin_num] = bin_freq * slope + base; Phase_Resp[Fft_Size+bin_num] = Raw_Phase_Resp[0]; } else // // do negative-frequency portion that is covered by input data { if(bin_freq >= right_freq) { samp_num++; left_freq = right_freq; right_freq = Phase_Freq_Scaling_Factor * Freqs_For_Phase[samp_num+1]; left_val = Raw_Phase_Resp[samp_num]; right_val = Raw_Phase_Resp[samp_num+1]; slope = (right_val - left_val)/(right_freq - left_freq); base = left_val - left_freq*slope; } Phase_Resp[Fft_Size+bin_num] = bin_freq * slope + base; } *resp_file << bin_num << ", " << Phase_Resp[Fft_Size+bin_num] << endl; } // // do the positive frequency portion which is covered by input data bin_freq = 0; bin_num = 0; while(bin_freq<max_data_freq && bin_num<Fft_Size/2) { bin_freq = bin_num * delta_f; if(bin_freq >= right_freq) { samp_num++; left_freq = right_freq; right_freq = Phase_Freq_Scaling_Factor * Freqs_For_Phase[samp_num+1]; left_val = Raw_Phase_Resp[samp_num]; right_val = Raw_Phase_Resp[samp_num+1]; slope = (right_val - left_val)/(right_freq - left_freq); base = left_val - left_freq*slope; } Phase_Resp[bin_num] = bin_freq * slope + base; *resp_file << bin_num << ", " << Phase_Resp[bin_num] << endl; bin_num++; } // // put straight-line skirt on positive frequency portion not coverd by input data left_freq = Phase_Freq_Scaling_Factor * Freqs_For_Phase[Num_Phase_Samps-1]; left_val = Raw_Phase_Resp[Num_Phase_Samps-1]; right_freq = delta_f*(Fft_Size-2)/2; slope = -left_val/(right_freq-left_freq); base = left_val-left_freq*slope; while(bin_num<Fft_Size/2) { bin_freq = bin_num * delta_f; //Phase_Resp[bin_num] = bin_freq * slope + base; Phase_Resp[bin_num] = Raw_Phase_Resp[Num_Phase_Samps-1]; *resp_file << bin_num << ", " << Phase_Resp[bin_num] << endl; bin_num++; } resp_file->close(); //----------------------------------------------------- }
int32_t processGPGGA (int8_t count, int8_t *f[], struct gps_device_t * session) { double d, m; double lat; double lon; int8_t *p; session->nmea.type = TYPE_GPGGA; session->nmea.nmea_u.gpgga.time.hour = DD(f[0]); session->nmea.nmea_u.gpgga.time.min = DD(&f[0][2]); session->nmea.nmea_u.gpgga.time.sec = DD(&f[0][4]); /*double d, m; double lat;*/ lat = atof(f[1]); m = 100.0 * modf(lat / 100.0, &d); lat = d + m / 60.0; if (f[2][0] == 'S') lat = -lat; session->nmea.nmea_u.gpgga.lat = lat; //double lon; lon = atof(f[3]); m = 100.0 * modf(lon / 100.0, &d); lon = d + m / 60.0; if (f[4][0] == 'S') lon = -lon; session->nmea.nmea_u.gpgga.lon = lon; switch(f[5][0]){ case '0': session->nmea.nmea_u.gpgga.gps_quality = FIX_NOT_AVAIL; break; case '1': session->nmea.nmea_u.gpgga.gps_quality = FIX; break; case '2': session->nmea.nmea_u.gpgga.gps_quality = DIFF_FIX; break; default: session->nmea.nmea_u.gpgga.gps_quality = FIX_UNDEF; /* unknow */ break; } session->nmea.nmea_u.gpgga.nsv = atoi(f[6]); session->nmea.nmea_u.gpgga.hdp = atof(f[7]); session->nmea.nmea_u.gpgga.antenna = atof(f[8]); session->nmea.nmea_u.gpgga.geoidal = atof(f[10]); session->nmea.nmea_u.gpgga.age = atof(f[12]); //int8_t *p; p = f[13]; while(*p != '*') p++; *p = '\0'; session->nmea.nmea_u.gpgga.stationID = atof(f[13]); return true; }
__attribute__((weak)) long double modfl(long double x, long double* y) { return modf((double)x, (double *)y); }
// Returns the fractional part of x inline f32 my_modf(f32 x) { double dummy; return modf(x, &dummy); }
void AFogOfWarWorker::UpdateFowTexture() { Manager->LastFrameTextureData = TArray<FColor>(Manager->TextureData); uint32 halfTextureSize = Manager->TextureSize / 2; int signedSize = (int)Manager->TextureSize; //For convenience.... TSet<FVector2D> texelsToBlur; int sightTexels = Manager->SightRange * Manager->SamplesPerMeter; float dividend = 100.0f / Manager->SamplesPerMeter; Manager->CurrentlyInSight.Reset(); for (auto Itr(Manager->FowActors.CreateIterator()); Itr; Itr++) { if (StopTaskCounter.GetValue() != 0) { return; } //Find actor position if (!*Itr) continue; FVector position = (*Itr)->GetActorLocation(); //We divide by 100.0 because 1 texel equals 1 meter of visibility-data. int posX = (int)(position.X / dividend) + halfTextureSize; int posY = (int)(position.Y / dividend) + halfTextureSize; float integerX, integerY; FVector2D fractions = FVector2D(modf(position.X / 50.0f, &integerX), modf(position.Y / 50.0f, &integerY)); FVector2D textureSpacePos = FVector2D(posX, posY); int size = (int)Manager->TextureSize; FCollisionQueryParams queryParams(FName(TEXT("FOW trace")), false, (*Itr)); int halfKernelSize = (Manager->blurKernelSize - 1) / 2; //Store the positions we want to blur for (int y = posY - sightTexels - halfKernelSize; y <= posY + sightTexels + halfKernelSize; y++) { for (int x = posX - sightTexels - halfKernelSize; x <= posX + sightTexels + halfKernelSize; x++) { if (x > 0 && x < size && y > 0 && y < size) { texelsToBlur.Add(FIntPoint(x, y)); } } } //Unveil the positions our actors are currently looking at for (int y = posY - sightTexels; y <= posY + sightTexels; y++) { for (int x = posX - sightTexels; x <= posX + sightTexels; x++) { //Kernel for radial sight if (x > 0 && x < size && y > 0 && y < size) { FVector2D currentTextureSpacePos = FVector2D(x, y); int length = (int)(textureSpacePos - currentTextureSpacePos).Size(); if (length <= sightTexels) { FVector currentWorldSpacePos = FVector( ((x - (int)halfTextureSize)) * dividend, ((y - (int)halfTextureSize)) * dividend, position.Z); //CONSIDER: This is NOT the most efficient way to do conditional unfogging. With long view distances and/or a lot of actors affecting the FOW-data //it would be preferrable to not trace against all the boundary points and internal texels/positions of the circle, but create and cache "rasterizations" of //viewing circles (using Bresenham's midpoint circle algorithm) for the needed sightranges, shift the circles to the actor's location //and just trace against the boundaries. //We would then use Manager->GetWorld()->LineTraceSingle() and find the first collision texel. Having found the nearest collision //for every ray we would unveil all the points between the collision and origo using Bresenham's Line-drawing algorithm. //However, the tracing doesn't seem like it takes much time at all (~0.02ms with four actors tracing circles of 18 texels each), //it's the blurring that chews CPU.. if (!Manager->GetWorld()->LineTraceTestByObjectType(position, currentWorldSpacePos, ECC_WorldStatic, queryParams)) //if (!Manager->GetWorld()->LineTraceTestByChannel(position, currentWorldSpacePos, ECC_WorldStatic, queryParams)) { //Unveil the positions we are currently seeing Manager->UnfoggedData[x + y * Manager->TextureSize] = true; //Store the positions we are currently seeing. Manager->CurrentlyInSight.Add(FVector2D(x, y)); } } } } } } if (Manager->GetIsBlurEnabled()) { //Horizontal blur pass int offset = floorf(Manager->blurKernelSize / 2.0f); for (auto Itr(texelsToBlur.CreateIterator()); Itr; ++Itr) { int x = (Itr)->IntPoint().X; int y = (Itr)->IntPoint().Y; float sum = 0; for (int i = 0; i < Manager->blurKernelSize; i++) { int shiftedIndex = i - offset; if (x + shiftedIndex >= 0 && x + shiftedIndex <= signedSize - 1) { if (Manager->UnfoggedData[x + shiftedIndex + (y * signedSize)]) { //If we are currently looking at a position, unveil it completely if (Manager->CurrentlyInSight.Contains(FVector2D(x + shiftedIndex, y))) { sum += (Manager->blurKernel[i] * 255); } //If this is a previously discovered position that we're not currently looking at, put it into a "shroud of darkness". else { sum += (Manager->blurKernel[i] * 100); } } } } Manager->HorizontalBlurData[x + y * signedSize] = (uint8)sum; } //Vertical blur pass for (auto Itr(texelsToBlur.CreateIterator()); Itr; ++Itr) { int x = (Itr)->IntPoint().X; int y = (Itr)->IntPoint().Y; float sum = 0; for (int i = 0; i < Manager->blurKernelSize; i++) { int shiftedIndex = i - offset; if (y + shiftedIndex >= 0 && y + shiftedIndex <= signedSize - 1) { sum += (Manager->blurKernel[i] * Manager->HorizontalBlurData[x + (y + shiftedIndex) * signedSize]); } } Manager->TextureData[x + y * signedSize] = FColor((uint8)FMath::Max(sum, 100.0f), (uint8)FMath::Max(sum, 100.0f), (uint8)FMath::Max(sum, 100.0f), 255); } } else { for (int y = 0; y < signedSize; y++) { for (int x = 0; x < signedSize; x++) { if (Manager->UnfoggedData[x + (y * signedSize)]) { if (Manager->CurrentlyInSight.Contains(FVector2D(x, y))) { Manager->TextureData[x + y * signedSize] = FColor((uint8)255, (uint8)255, (uint8)255, 255); } else { Manager->TextureData[x + y * signedSize] = FColor((uint8)100, (uint8)100, (uint8)100, 255); } } } } } Manager->bHasFOWTextureUpdate = true; }
bool EffectToneGen::MakeTone(float *buffer, sampleCount len) { double throwaway = 0; //passed to modf but never used sampleCount i; double f = 0.0; double a,b; int k; double frequencyQuantum; double BlendedFrequency; double BlendedAmplitude; double BlendedLogFrequency = 0.0f; // calculate delta, and reposition from where we left double amplitudeQuantum = (amplitude[1]-amplitude[0]) / numSamples; BlendedAmplitude = amplitude[0] + amplitudeQuantum * mSample; // precalculations: double pre2PI = 2 * M_PI; double pre4divPI = 4. / M_PI; // initial setup should calculate deltas if( mbLogInterpolation ) { // this for log interpolation logFrequency[0] = log10( frequency[0] ); logFrequency[1] = log10( frequency[1] ); // calculate delta, and reposition from where we left frequencyQuantum = (logFrequency[1]-logFrequency[0]) / numSamples; BlendedLogFrequency = logFrequency[0] + frequencyQuantum * mSample; BlendedFrequency = pow( 10.0, (double)BlendedLogFrequency ); } else { // this for regular case, linear interpolation frequencyQuantum = (frequency[1]-frequency[0]) / numSamples; BlendedFrequency = frequency[0] + frequencyQuantum * mSample; } // synth loop for (i = 0; i < len; i++) { switch (waveform) { case 0: //sine f = (float) sin(pre2PI * mPositionInCycles/mCurRate); break; case 1: //square f = (modf(mPositionInCycles/mCurRate, &throwaway) < 0.5) ? 1.0f :-1.0f; break; case 2: //sawtooth f = (2 * modf(mPositionInCycles/mCurRate+0.5f, &throwaway)) -1.0f; break; case 3: //square, no alias. Good down to 110Hz @ 44100Hz sampling. //do fundamental (k=1) outside loop b = (1. + cos((pre2PI * BlendedFrequency)/mCurRate))/pre4divPI; //scaling f = (float) pre4divPI * sin(pre2PI * mPositionInCycles/mCurRate); for(k=3; (k<200) && (k * BlendedFrequency < mCurRate/2.); k+=2) { //Hanning Window in freq domain a = 1. + cos((pre2PI * k * BlendedFrequency)/mCurRate); //calc harmonic, apply window, scale to amplitude of fundamental f += (float) a * sin(pre2PI * mPositionInCycles/mCurRate * k)/(b*k); } } // insert value in buffer buffer[i] = BlendedAmplitude * f; // update freq,amplitude mPositionInCycles += BlendedFrequency; BlendedAmplitude += amplitudeQuantum; if (mbLogInterpolation) { BlendedLogFrequency += frequencyQuantum; BlendedFrequency = pow( 10.0, (double)BlendedLogFrequency); } else { BlendedFrequency += frequencyQuantum; } } // update external placeholder mSample += len; return true; }
/* this takes only non-negative (except -0) numbers that are not NaN or inf */ static char *double2str( char *end, double x, int width, int prec, enum format_flags flags ) { char *begin = end; double frac, whole; frac = modf(x, &whole); if (prec > 0) { /* round fractional part */ int i; for (i = 0; i < prec; i++) { frac *= 10.0; } frac = floor(frac + 0.5); for (i = 0; i < prec; i++) { int digit = fmod(frac, 10.0); *--begin = '0' + digit; frac /= 10.0; } *--begin = '.'; whole += frac; } else { /* round to integers */ whole = floor(x + 0.5); } do { int digit = fmod(whole, 10.0); *--begin = '0' + digit; whole /= 10.0; } while (whole >= 1.0); if (flags & FLAG_ZEROPAD) { while (width >= 0 && width > end - begin + 1) { *--begin = '0'; } if (flags & FLAG_NEGATIVE) { *--begin = '-'; } else if (flags & FLAG_EXPLICITSIGN) { *--begin = '+'; } else if (flags & FLAG_PADSIGN) { *--begin = ' '; } else { *--begin = '0'; } } else { if (flags & FLAG_NEGATIVE) { *--begin = '-'; } else if (flags & FLAG_EXPLICITSIGN) { *--begin = '+'; } else if (flags & FLAG_PADSIGN) { *--begin = ' '; } while (width >= 0 && width > end - begin) { *--begin = ' '; } } return begin; }
color_t getColor(double fraction, double intensity) { /* fraction is a part of the rainbow (0.0 - 1.0) = (Red-Yellow-Green-Cyan-Blue-Magenta-Red) intensity (0.0 - 1.0) 0 = black, 1 = full color, 2 = white */ double red, green, blue; int r,g,b; double dtemp; fraction = fabs(modf(fraction, &dtemp)); if (intensity > 2.0) intensity = 2.0; if (intensity < 0.0) intensity = 0.0; dtemp = 1.0/6.0; if (fraction < 1.0/6.0) { red = 1.0; green = fraction / dtemp; blue = 0.0; } else { if (fraction < 1.0/3.0) { red = 1.0 - ((fraction - dtemp) / dtemp); green = 1.0; blue = 0.0; } else { if (fraction < 0.5) { red = 0.0; green = 1.0; blue = (fraction - (dtemp*2.0)) / dtemp; } else { if (fraction < 2.0/3.0) { red = 0.0; green = 1.0 - ((fraction - (dtemp*3.0)) / dtemp); blue = 1.0; } else { if (fraction < 5.0/6.0) { red = (fraction - (dtemp*4.0)) / dtemp; green = 0.0; blue = 1.0; } else { red = 1.0; green = 0.0; blue = 1.0 - ((fraction - (dtemp*5.0)) / dtemp); } } } } } if (intensity > 1) { intensity = intensity - 1.0; red = red + ((1.0 - red) * intensity); green = green + ((1.0 - green) * intensity); blue = blue + ((1.0 - blue) * intensity); } else { red = red * intensity; green = green * intensity; blue = blue * intensity; } r = (int)(red * 255.0); g = (int)(green * 255.0); b = (int)(blue * 255.0); return RGBtocolor_t(r,g,b); }