示例#1
0
文件: Vec2i.cpp 项目: eoma/totem-edk
float Vec2i::distancef(const Vec2i &rhs) const
{
	return sqrtf(powf(((float)x_-(float)rhs.x()), 2.0f) + pow(((float)y_-(float)rhs.y()), 2.0f));
}
示例#2
0
/*
    offsetIndex:    [0] skeleton
                    [1] spline
                    [2] offset spline
*/
ofVec2f BGGraphics::calculateInternalTexOffset(float t, bool isSourceSpline, bool isSourceSegment, int offsetIndex) {

    const float triangleHeight = .5 * tanf(M_PI / 3.0);

    const float baseSize = sqrtf(3.0);
    const float halfBaseSize = .5 * baseSize;
    const ofVec2f source(0, 1);
    const ofVec2f sink1(-halfBaseSize, -.5);
    const ofVec2f sink2(halfBaseSize, -.5);
    const ofVec2f center = (source + sink1 + sink2) / 3.0;
    const float bezierOffset = 0.5 * baseSize;
    const float maxInternalOffset = (.25 * source - .5 * center + .25 * sink1).length();
    const float centerStretchFactor = (maxInternalOffset + bezierOffset) / bezierOffset;


    ofVec2f focusPt = isSourceSpline ? ofVec2f(baseSize, 1) : ofVec2f(0, -2);
    float fromFocusAngle = M_PI * (isSourceSpline ? (1.0 + t / 3.0) : ((1.0 + t) / 3.0));
    ofVec2f toPtVector(cosf(fromFocusAngle), sinf(fromFocusAngle));

    float offset = (offsetIndex == 2) ? (.5 * baseSize) : baseSize;
    ofVec2f xy = focusPt + offset * toPtVector;

    if(offsetIndex == 0) {
        //project point on base spline
        ofVec2f projBase = isSourceSegment ? ofVec2f(0,1) : ofVec2f(halfBaseSize, -.5);
        xy = dot(xy, projBase) * projBase;
    }

    //in case we are dealing with the center point:
    if(offsetIndex == -1)
        xy = ofVec2f(0,0);
    
    const ofVec2f cornerTL = source + (sink1 - sink2);
    const ofVec2f cornerTR = source + (sink2 - sink1);
    const ofVec2f cornerB = sink1 + (sink2 - source);

    ofVec2f vecSource = (center - source).normalize();
    ofVec2f vecSink1 = (sink1 - center).normalize();
    ofVec2f vecSink2 = (sink2 - center).normalize();
 
    float traversalDistance = 2. * (center - source).length();
 
    float projSource = dot(xy - source, vecSource);
    float projSink1 = dot(xy - sink1, vecSink1);
    float projSink2 = dot(xy - sink2, vecSink2);
 
    float orSource = cross(xy - source, vecSource);
    float orSink1 = cross(xy - sink1, vecSink1);
    float orSink2 = cross(xy - sink2, vecSink2);
 
    float val1 = projSource / traversalDistance;
    float val2 = 1.0 + projSink1 / traversalDistance;
    float val3 = 1.0 + projSink2 / traversalDistance;

    float offsetX = 0;
    if(ABS(projSource) < .0001)
        offsetX = val1;
    else if(ABS(projSink1) < .0001)
        offsetX = val2;
    else if(ABS(projSink2) < .0001)
        offsetX = val3;
    else {
        float power = 2.0;
        float weight1 = powf(1.0 / ABS(projSource), power);
        float weight2 = powf(1.0 / ABS(projSink1), power);
        float weight3 = powf(1.0 / ABS(projSink2), power);
        float sumWeight = weight1 + weight2 + weight3;
    
        offsetX = (weight1 / sumWeight) * val1
                    + (weight2 / sumWeight) * val2
                    + (weight3 / sumWeight) * val3;
    }
 
 
  ofVec2f to = xy - focusPt;
  float toDist = to.length();
  to /= toDist;
 
  float dist = MAX(0.0, toDist - bezierOffset);
 
  float maxAng = M_PI / 6.;
 
  float angle = acos(dot(to, (center - focusPt).normalize()));
  float maxOffset = baseSize / cos(M_PI / 6.0 - angle) - bezierOffset;
 
  float circDistFrac = dist / (baseSize - bezierOffset);
  float projDistFrac = dist / maxOffset;
 
 
  float angleFrac = 1. - angle / maxAng;
 
 
  float offFactor = pow(projDistFrac, 2.0 + abs(angleFrac) * projDistFrac);
  float offsetY = (1. - offFactor) * circDistFrac + offFactor * projDistFrac;
  offsetY = 1. - offsetY;

  if(isnan(offsetX) || isnan(offsetY))
      cout << "OFFSET VALUE is NaN" << endl;

  return ofVec2f(offsetX - .5, offsetY);
}
示例#3
0
// autotest helper function
//  _n      :   sequence length
//  _dt     :   fractional sample offset
//  _dphi   :   carrier frequency offset
void detector_cccf_runtest(unsigned int _n,
                           float        _dt,
                           float        _dphi)
{
    // TODO: validate input

    unsigned int i;

    // fixed values
    float noise_floor = -80.0f;     // noise floor [dB]
    float SNRdB       =  30.0f;     // signal-to-noise ratio [dB]
    unsigned int m    =  11;        // resampling filter semi-length
    float threshold   =  0.3f;      // detection threshold

    // derived values
    unsigned int num_samples = _n + 2*m + 1;
    float nstd = powf(10.0f, noise_floor/20.0f);
    float gamma = powf(10.0f, (SNRdB + noise_floor)/20.0f);
    float delay = (float)(_n + m) + _dt;    // expected delay

    // arrays
    float complex s[_n];            // synchronization pattern (samples)
    float complex x[num_samples];   // resampled signal with noise and offsets

    // generate synchronization pattern (two samples per symbol)
    unsigned int n2 = (_n - (_n%2)) / 2;    // n2 = floor(n/2)
    unsigned int mm = liquid_nextpow2(n2);  // mm = ceil( log2(n2) )
    msequence ms = msequence_create_default(mm);
    float complex v = 0.0f;
    for (i=0; i<_n; i++) {
        if ( (i%2)==0 )
            v = msequence_advance(ms) ? 1.0f : -1.0f;
        s[i] = v;
    }
    msequence_destroy(ms);

    // create fractional sample interpolator
    firfilt_crcf finterp = firfilt_crcf_create_kaiser(2*m+1, 0.45f, 40.0f, _dt);

    // generate sequence
    for (i=0; i<num_samples; i++) {
        // add fractional sample timing offset
        if (i < _n) firfilt_crcf_push(finterp, s[i]);
        else        firfilt_crcf_push(finterp, 0.0f);

        // compute output
        firfilt_crcf_execute(finterp, &x[i]);

        // add channel gain
        x[i] *= gamma;

        // add carrier offset
        x[i] *= cexpf(_Complex_I*_dphi*i);

        // add noise
        x[i] += nstd * ( randnf() + _Complex_I*randnf() ) * M_SQRT1_2;
    }
    
    // destroy fractional sample interpolator
    firfilt_crcf_destroy(finterp);

    // create detector
    detector_cccf sync = detector_cccf_create(s, _n, threshold, 2*_dphi);
    
    // push signal through detector
    float tau_hat   = 0.0f;     // fractional sample offset estimate
    float dphi_hat  = 0.0f;     // carrier offset estimate
    float gamma_hat = 1.0f;     // signal level estimate (linear)
    float delay_hat = 0.0f;     // total delay offset estimate
    int signal_detected = 0;    // signal detected flag
    for (i=0; i<num_samples; i++) {
        
        // correlate
        int detected = detector_cccf_correlate(sync, x[i], &tau_hat, &dphi_hat, &gamma_hat);

        if (detected) {
            signal_detected = 1;
            delay_hat = (float)i + (float)tau_hat;
            if (liquid_autotest_verbose) {
                printf("****** preamble found, tau_hat=%8.6f, dphi_hat=%8.6f, gamma_hat=%8.6f\n",
                        tau_hat, dphi_hat, gamma_hat);
            }
        }
    }
    
    // destroy objects
    detector_cccf_destroy(sync);

    // 
    // run tests
    //
    
    // convert to dB
    gamma     = 20*log10f(gamma);
    gamma_hat = 20*log10f(gamma_hat);

    if (liquid_autotest_verbose) {
        printf("detector autotest [%3u]: signal detected? %s\n", _n, signal_detected ? "yes" : "no");
        printf("    dphi    :   estimate = %12.6f (expected %12.6f)\n", dphi_hat,  _dphi);
        printf("    delay   :   estimate = %12.6f (expected %12.6f)\n", delay_hat, delay);
        printf("    gamma   :   estimate = %12.6f (expected %12.6f)\n", gamma_hat, gamma);
    }

    // ensure signal was detected
    CONTEND_EXPRESSION( signal_detected );

    // check carrier offset estimate
    CONTEND_DELTA( dphi_hat, _dphi, 0.01f );
    
    // check delay estimate
    CONTEND_DELTA( delay_hat, delay, 0.2f );
    
    // check signal level estimate
    CONTEND_DELTA( gamma_hat, gamma, 2.0f );
}
void CCEaseIn::update(float time)
{
    m_pOther->update(powf(time, m_fRate));
}
void CCEaseExponentialIn::update(float time)
{
    m_pOther->update(time == 0 ? 0 : powf(2, 10 * (time/1 - 1)) - 1 * 0.001f);
}
示例#6
0
		void Corpse::Update(float dt) {
			SPADES_MARK_FUNCTION();
			float damp = 1.f;
            float damp2 = 1.f;
			if(dt > 0.f){
				damp = powf(.9f, dt);
				damp2 = powf(.371f, dt);
            }
			//dt *= 0.1f;
			
			for(int i = 0; i <NodeCount; i++){
				Node& node = nodes[i];
				Vector3 oldPos = node.lastPos;
				node.pos += node.vel * dt;
				
				SPAssert(!isnan(node.pos.x));
				SPAssert(!isnan(node.pos.y));
				SPAssert(!isnan(node.pos.z));
				
				if(node.pos.z > 63.f){
					node.vel.z -= dt * 6.f; // buoyancy
					node.vel *= damp;
				}else{
                    node.vel.z += dt * 32.f; // gravity
                    node.vel.z *= damp2;
                }
				
				//node.vel *= damp;
				
				if(!map->ClipBox(oldPos.x, oldPos.y, oldPos.z)){
					
					if(map->ClipBox(node.pos.x,
									oldPos.y,
									oldPos.z)){
						node.vel.x = -node.vel.x * .2f;
						if(fabsf(node.vel.x) < .3f)
							node.vel.x = 0.f;
						node.pos.x = oldPos.x;
						
						node.vel.y *= .5f;
						node.vel.z *= .5f;
					}
					
					if(map->ClipBox(node.pos.x,
									node.pos.y,
									oldPos.z)){
						node.vel.y = -node.vel.y * .2f;
						if(fabsf(node.vel.y) < .3f)
							node.vel.y = 0.f;
						node.pos.y = oldPos.y;
						
						node.vel.x *= .5f;
						node.vel.z *= .5f;
					}
					
					if(map->ClipBox(node.pos.x,
									node.pos.y,
									node.pos.z)){
						node.vel.z = -node.vel.z * .2f;
						if(fabsf(node.vel.z) < .3f)
							node.vel.z = 0.f;
						node.pos.z = oldPos.z;
						
						node.vel.x *= .5f;
						node.vel.y *= .5f;
					}
					
					if(map->ClipBox(node.pos.x, node.pos.y, node.pos.z)){
						// TODO: getting out block
						//node.pos = oldPos;
						//node.vel *= .5f;
					}
				}
				
				/*
				if(map->ClipBox(node.pos.x,
								node.pos.y,
								node.pos.z)){
					if(!map->ClipBox(node.pos.x,
									node.pos.y,
									oldPos.z)){
						node.vel.z = -node.vel.z * .2f;
						if(fabsf(node.vel.z) < .3f)
							node.vel.z = 0.f;
						node.pos.z = oldPos.z;
					}
					if(!map->ClipBox(node.pos.x,
									 oldPos.y,
									 node.pos.z)){
						node.vel.y = -node.vel.y * .2f;
						if(fabsf(node.vel.y) < .3f)
							node.vel.y = 0.f;
						node.pos.y = oldPos.y;
					}
					if(!map->ClipBox(oldPos.x,
									 node.pos.y,
									 node.pos.z)){
						node.vel.x = -node.vel.x * .2f;
						if(fabsf(node.vel.x) < .3f)
							node.vel.x = 0.f;
						node.pos.x = oldPos.x;
					}
					node.vel *= .8f;
					//node.pos = oldPos;
					
					if(node.vel.GetLength() < .02f){
						node.vel *= 0.f;
					}
				}*/
				
				node.lastPos = node.pos;
				node.lastForce = node.vel;
			}
			ApplyConstraint(dt);
			
			for(int i = 0; i <NodeCount; i++){
				nodes[i].lastForce = nodes[i].vel - nodes[i].lastForce;
			}
			
		}
示例#7
0
/*
 * Effect output
 */
void
Valve::out (float * smpsl, float * smpsr)
{
    int i;

    float l, r, lout, rout, fx;


    if (Pstereo != 0) {
        //Stereo
        for (i = 0; i < param->PERIOD; i++) {
            efxoutl[i] = smpsl[i] * inputvol;
            efxoutr[i] = smpsr[i] * inputvol;
        };
    } else {
        for (i = 0; i < param->PERIOD; i++) {
            efxoutl[i] =
                (smpsl[i]  +  smpsr[i] ) * inputvol;
        };
    };

    harm->harm_out(efxoutl,efxoutr);


    if (Pprefiltering != 0)
        applyfilters (efxoutl, efxoutr);

    if(Ped) {
        for (i =0; i<param->PERIOD; i++) {
            efxoutl[i]=Wshape(efxoutl[i]);
            if (Pstereo != 0) efxoutr[i]=Wshape(efxoutr[i]);
        }
    }

    for (i =0; i<param->PERIOD; i++) { //soft limiting to 3.0 (max)
        fx = efxoutl[i];
        if (fx>1.0f) fx = 3.0f - 2.0f/sqrtf(fx);
        efxoutl[i] = fx;
        fx = efxoutr[i];
        if (fx>1.0f) fx = 3.0f - 2.0f/sqrtf(fx);
        efxoutr[i] = fx;
    }

    if (q == 0.0f) {
        for (i =0; i<param->PERIOD; i++) {
            if (efxoutl[i] == q) fx = fdist;
            else fx =efxoutl[i] / (1.0f - powf(2.0f,-dist * efxoutl[i] ));
            otml = atk * otml + fx - itml;
            itml = fx;
            efxoutl[i]= otml;
        }
    } else {
        for (i = 0; i < param->PERIOD; i++) {
            if (efxoutl[i] == q) fx = fdist + qcoef;
            else fx =(efxoutl[i] - q) / (1.0f - powf(2.0f,-dist * (efxoutl[i] - q))) + qcoef;
            otml = atk * otml + fx - itml;
            itml = fx;
            efxoutl[i]= otml;

        }
    }


    if (Pstereo != 0) {

        if (q == 0.0f) {
            for (i =0; i<param->PERIOD; i++) {
                if (efxoutr[i] == q) fx = fdist;
                else fx = efxoutr[i] / (1.0f - powf(2.0f,-dist * efxoutr[i] ));
                otmr = atk * otmr + fx - itmr;
                itmr = fx;
                efxoutr[i]= otmr;

            }
        } else {
            for (i = 0; i < param->PERIOD; i++) {
                if (efxoutr[i] == q) fx = fdist + qcoef;
                else fx = (efxoutr[i] - q) / (1.0f - powf(2.0f,-dist * (efxoutr[i] - q))) + qcoef;
                otmr = atk * otmr + fx - itmr;
                itmr = fx;
                efxoutr[i]= otmr;

            }
        }

    }



    if (Pprefiltering == 0)
        applyfilters (efxoutl, efxoutr);

    if (Pstereo == 0) memcpy (efxoutr , efxoutl, param->PERIOD * sizeof(float));


    float level = dB2rap (60.0f * (float)Plevel / 127.0f - 40.0f);

    for (i = 0; i < param->PERIOD; i++) {
        lout = efxoutl[i];
        rout = efxoutr[i];


        l = lout * (1.0f - lrcross) + rout * lrcross;
        r = rout * (1.0f - lrcross) + lout * lrcross;

        lout = l;
        rout = r;

        efxoutl[i] = lout * 2.0f * level * panning;
        efxoutr[i] = rout * 2.0f * level * (1.0f -panning);

    };



};
示例#8
0
void CRMLandScape::Sprinkle(CCMPatch *patch, CCGHeightDetails *hd, int level)
{
	int				i, count, px, py;
	float			density;
	vec3_t			origin, scale, angles, bounds[2];
	refEntity_t		refEnt;
	CRandomModel	*rm;
	CArea			area;
//	int				areaTypes[] = { AT_BSP, AT_OBJECTIVE };
	TCGMiscEnt		*data = (TCGMiscEnt *)cl.mSharedMemory;
	TCGTrace		*td = (TCGTrace *)cl.mSharedMemory;

//	memset(&refEnt, 0, sizeof(refEntity_t));

	px = patch->GetHeightMapX() / common->GetTerxels();
	py = patch->GetHeightMapY() / common->GetTerxels();
	// Get a number -5.3f to 5.3f
	density = (mDensityMap[px + (common->GetBlockWidth() * py)] - 128) / 24.0f;
	// ..and multiply that into the count
	count = Round(common->GetPatchScalarSize() * hd->GetAverageFrequency() * powf(2.0f, density) * 0.001);

	for(i = 0; i < count; i++)
	{
		if(!common->irand(0, 10))
		{
			vec3_t temp;
			float  average;

			rm = hd->GetRandomModel(common);

			refEnt.hModel = re.RegisterModel(rm->GetModelName());
			refEnt.frame = 0;
			re.ModelBoundsRef(&refEnt, bounds[0], bounds[1]);

			// Calculate the scale using some magic to help ensure that the
			// scales are never too different from eachother.  Otherwise you
			// could get an entity that is really small on one axis but huge 
			// on another.
			temp[0] = common->flrand(rm->GetMinScale(), rm->GetMaxScale());
			temp[1] = common->flrand(rm->GetMinScale(), rm->GetMaxScale());
			temp[2] = common->flrand(rm->GetMinScale(), rm->GetMaxScale());

			// Average of the three random numbers and divide that by two
			average = ( ( temp[0] + temp[1] + temp[2] ) / 3) / 2;

			// Add in half of the other two numbers and then subtract half the average to prevent.
			// any number from going beyond the range. If all three numbers were the same then
			// they would remain unchanged after this calculation.
			scale[0] = temp[0] + (temp[1]+temp[2]) / 2 - average;
			scale[1] = temp[1] + (temp[0]+temp[2]) / 2 - average;
			scale[2] = temp[2] + (temp[0]+temp[1]) / 2 - average;

			angles[0] = 0.0f;
			angles[1] = common->flrand(-M_PI, M_PI);
			angles[2] = 0.0f;

			VectorCopy(patch->GetMins(), origin);
			origin[0] += common->flrand(0.0f, common->GetPatchWidth());
			origin[1] += common->flrand(0.0f, common->GetPatchHeight());
			// Get above world height
			float slope = common->GetWorldHeight(origin, bounds, true);

			if (slope > 1.33)
			{	// spot has too steep of a slope
				continue;
			}
			if(origin[2] < common->GetWaterHeight())
			{
				continue;
			}
			// very that we aren't dropped too low
			if (origin[2] < common->CalcWorldHeight(level))
			{
				continue;
			}

			// Hack-ariffic, don't allow them to drop below the big player clip brush.
			if (origin[2] < 1280 )
			{
				continue;
			}
			// FIXME: shouldn't be using a hard-coded 1280 number, only allow to spawn if inside player clip brush? 
	//		if( !(CONTENTS_PLAYERCLIP & VM_Call( cgvm, CG_POINT_CONTENTS )) )
	//		{
	//			continue;
	//		}
			// Simple radius check for buildings
/*			area.Init(origin, VectorLength(bounds[0]));
			if(common->AreaCollision(&area, areaTypes, sizeof(areaTypes) / sizeof(int)))
			{
				continue;
			}*/
			// Make sure there is no architecture around - doesn't work for ents though =(

			memset(td, sizeof(*td), 0);
			VectorCopy(origin, td->mStart);
			VectorCopy(bounds[0], td->mMins);
			VectorCopy(bounds[1], td->mMaxs);
			VectorCopy(origin, td->mEnd);
			td->mSkipNumber = -1;
			td->mMask = MASK_PLAYERSOLID;

			VM_Call( cgvm, CG_TRACE );
			if(td->mResult.surfaceFlags & SURF_NOMISCENTS)
			{
				continue;
			}
			if(td->mResult.startsolid)
			{
//				continue;
			}
			// Get minimum height of area
			common->GetWorldHeight(origin, bounds, false);
			// Account for relative origin
			origin[2] -= bounds[0][2] * scale[2];
			origin[2] -= common->flrand(2.0, (bounds[1][2] - bounds[0][2]) / 4);
			
			// Spawn the client model
			strcpy(data->mModel, rm->GetModelName());
			VectorCopy(origin, data->mOrigin);
			VectorCopy(angles, data->mAngles);
			VectorCopy(scale, data->mScale);
			VM_Call( cgvm, CG_MISC_ENT);
			mModelCount++;
		}
	}
}
示例#9
0
float decibelsToLinear(float decibels)
{
    return powf(10, 0.05f * decibels);
}
示例#10
0
void BKE_image_buf_fill_checker(unsigned char *rect, float *rect_float, int width, int height)
{
	/* these two passes could be combined into one, but it's more readable and 
	* easy to tweak like this, speed isn't really that much of an issue in this situation... */
 
	int checkerwidth= 32, dark= 1;
	int x, y;

	unsigned char *rect_orig= rect;
	float *rect_float_orig= rect_float;

	
	float h=0.0, hoffs=0.0, hue=0.0, s=0.9, v=0.9, r, g, b;

	/* checkers */
	for(y= 0; y<height; y++) {
		dark= powf(-1.0f, floorf(y / checkerwidth));
		
		for(x= 0; x<width; x++) {
			if (x % checkerwidth == 0) dark= -dark;
			
			if (rect_float) {
				if (dark > 0) {
					rect_float[0]= rect_float[1]= rect_float[2]= 0.25f;
					rect_float[3]= 1.0f;
				} else {
					rect_float[0]= rect_float[1]= rect_float[2]= 0.58f;
					rect_float[3]= 1.0f;
				}
				rect_float+= 4;
			}
			else {
				if (dark > 0) {
					rect[0]= rect[1]= rect[2]= 64;
					rect[3]= 255;
				} else {
					rect[0]= rect[1]= rect[2]= 150;
					rect[3]= 255;
				}
				rect+= 4;
			}
		}
	}

	rect= rect_orig;
	rect_float= rect_float_orig;

	/* 2nd pass, colored + */
	for(y= 0; y<height; y++) {
		hoffs= 0.125f * floorf(y / checkerwidth);
		
		for(x= 0; x<width; x++) {
			h= 0.125f * floorf(x / checkerwidth);
			
			if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 4) &&
				(fabs((y % checkerwidth) - (checkerwidth / 2)) < 4)) {
				
				if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 1) ||
					(fabs((y % checkerwidth) - (checkerwidth / 2)) < 1)) {
					
					hue= fmodf(fabs(h-hoffs), 1.0f);
					hsv_to_rgb(hue, s, v, &r, &g, &b);
					
					if (rect) {
						rect[0]= (char)(r * 255.0f);
						rect[1]= (char)(g * 255.0f);
						rect[2]= (char)(b * 255.0f);
						rect[3]= 255;
					}
					
					if (rect_float) {
						rect_float[0]= r;
						rect_float[1]= g;
						rect_float[2]= b;
						rect_float[3]= 1.0f;
					}
				}
			}

			if (rect_float) rect_float+= 4;
			if (rect) rect+= 4;
		}
	}
}
示例#11
0
struct circle computeArea(struct circle instance){
    instance.area = powf ( (pi * (instance.diameter * .5)), 2 );
    return instance;
}
示例#12
0
文件: Audio.cpp 项目: tschw/hifi
inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* outputRight) {

    NodeList* nodeList = NodeList::getInstance();
    Application* interface = Application::getInstance();
    Avatar* interfaceAvatar = interface->getAvatar();
 
    // Add Procedural effects to input samples
    addProceduralSounds(inputLeft, BUFFER_LENGTH_SAMPLES_PER_CHANNEL);
    
    if (nodeList && inputLeft) {
        
        //  Measure the loudness of the signal from the microphone and store in audio object
        float loudness = 0;
        for (int i = 0; i < BUFFER_LENGTH_SAMPLES_PER_CHANNEL; i++) {
            loudness += abs(inputLeft[i]);
        }
        
        loudness /= BUFFER_LENGTH_SAMPLES_PER_CHANNEL;
        _lastInputLoudness = loudness;
        
        // add input (@microphone) data to the scope
        _scope->addSamples(0, inputLeft, BUFFER_LENGTH_SAMPLES_PER_CHANNEL);

        Node* audioMixer = nodeList->soloNodeOfType(NODE_TYPE_AUDIO_MIXER);
        
        if (audioMixer) {
            glm::vec3 headPosition = interfaceAvatar->getHeadJointPosition();
            glm::quat headOrientation = interfaceAvatar->getHead().getOrientation();
            
            int numBytesPacketHeader = numBytesForPacketHeader((unsigned char*) &PACKET_TYPE_MICROPHONE_AUDIO_NO_ECHO);
            int leadingBytes = numBytesPacketHeader + sizeof(headPosition) + sizeof(headOrientation);
            
            // we need the amount of bytes in the buffer + 1 for type
            // + 12 for 3 floats for position + float for bearing + 1 attenuation byte
            unsigned char dataPacket[BUFFER_LENGTH_BYTES_PER_CHANNEL + leadingBytes];
            
            PACKET_TYPE packetType = (Application::getInstance()->shouldEchoAudio())
                ? PACKET_TYPE_MICROPHONE_AUDIO_WITH_ECHO
                : PACKET_TYPE_MICROPHONE_AUDIO_NO_ECHO;
            
            unsigned char* currentPacketPtr = dataPacket + populateTypeAndVersion(dataPacket, packetType);
            
            // memcpy the three float positions
            memcpy(currentPacketPtr, &headPosition, sizeof(headPosition));
            currentPacketPtr += (sizeof(headPosition));
            
            // memcpy our orientation
            memcpy(currentPacketPtr, &headOrientation, sizeof(headOrientation));
            currentPacketPtr += sizeof(headOrientation);
            
            // copy the audio data to the last BUFFER_LENGTH_BYTES bytes of the data packet
            memcpy(currentPacketPtr, inputLeft, BUFFER_LENGTH_BYTES_PER_CHANNEL);
            nodeList->getNodeSocket()->send(audioMixer->getActiveSocket(),
                                              dataPacket,
                                              BUFFER_LENGTH_BYTES_PER_CHANNEL + leadingBytes);

            interface->getBandwidthMeter()->outputStream(BandwidthMeter::AUDIO)
                    .updateValue(BUFFER_LENGTH_BYTES_PER_CHANNEL + leadingBytes);
        }
        
    }
    
    memset(outputLeft, 0, PACKET_LENGTH_BYTES_PER_CHANNEL);
    memset(outputRight, 0, PACKET_LENGTH_BYTES_PER_CHANNEL);
    
    AudioRingBuffer* ringBuffer = &_ringBuffer;
    
    // if there is anything in the ring buffer, decide what to do:
    
    if (ringBuffer->getEndOfLastWrite()) {
        if (!ringBuffer->isStarted() && ringBuffer->diffLastWriteNextOutput() <
            (PACKET_LENGTH_SAMPLES + _jitterBufferSamples * (ringBuffer->isStereo() ? 2 : 1))) {
            //
            //  If not enough audio has arrived to start playback, keep waiting
            //
#ifdef SHOW_AUDIO_DEBUG
            printLog("%i,%i,%i,%i\n",
                     _packetsReceivedThisPlayback,
                     ringBuffer->diffLastWriteNextOutput(),
                     PACKET_LENGTH_SAMPLES,
                     _jitterBufferSamples);
#endif
        } else if (ringBuffer->isStarted() && ringBuffer->diffLastWriteNextOutput() == 0) {
            //
            //  If we have started and now have run out of audio to send to the audio device, 
            //  this means we've starved and should restart.  
            //  
            ringBuffer->setStarted(false);
            
            _numStarves++;
            _packetsReceivedThisPlayback = 0;
            _wasStarved = 10;          //   Frames for which to render the indication that the system was starved.
#ifdef SHOW_AUDIO_DEBUG
            printLog("Starved, remaining samples = %d\n",
                     ringBuffer->diffLastWriteNextOutput());
#endif

        } else {
            //
            //  We are either already playing back, or we have enough audio to start playing back.
            // 
            if (!ringBuffer->isStarted()) {
                ringBuffer->setStarted(true);
#ifdef SHOW_AUDIO_DEBUG
                printLog("starting playback %0.1f msecs delayed, jitter = %d, pkts recvd: %d \n",
                         (usecTimestampNow() - usecTimestamp(&_firstPacketReceivedTime))/1000.0,
                         _jitterBufferSamples,
                         _packetsReceivedThisPlayback);
#endif
            }

            //
            // play whatever we have in the audio buffer
            //
            // if we haven't fired off the flange effect, check if we should
            // TODO: lastMeasuredHeadYaw is now relative to body - check if this still works.
            
            int lastYawMeasured = fabsf(interfaceAvatar->getHeadYawRate());
            
            if (!_samplesLeftForFlange && lastYawMeasured > MIN_FLANGE_EFFECT_THRESHOLD) {
                // we should flange for one second
                if ((_lastYawMeasuredMaximum = std::max(_lastYawMeasuredMaximum, lastYawMeasured)) != lastYawMeasured) {
                    _lastYawMeasuredMaximum = std::min(_lastYawMeasuredMaximum, MIN_FLANGE_EFFECT_THRESHOLD);
                    
                    _samplesLeftForFlange = SAMPLE_RATE;
                    
                    _flangeIntensity = MIN_FLANGE_INTENSITY +
                        ((_lastYawMeasuredMaximum - MIN_FLANGE_EFFECT_THRESHOLD) /
                         (float)(MAX_FLANGE_EFFECT_THRESHOLD - MIN_FLANGE_EFFECT_THRESHOLD)) *
                        (1 - MIN_FLANGE_INTENSITY);
                    
                    _flangeRate = FLANGE_BASE_RATE * _flangeIntensity;
                    _flangeWeight = MAX_FLANGE_SAMPLE_WEIGHT * _flangeIntensity;
                }
            }
            
            for (int s = 0; s < PACKET_LENGTH_SAMPLES_PER_CHANNEL; s++) {
                
                int leftSample = ringBuffer->getNextOutput()[s];
                int rightSample = ringBuffer->getNextOutput()[s + PACKET_LENGTH_SAMPLES_PER_CHANNEL];
                
                if (_samplesLeftForFlange > 0) {
                    float exponent = (SAMPLE_RATE - _samplesLeftForFlange - (SAMPLE_RATE / _flangeRate)) /
                        (SAMPLE_RATE / _flangeRate);
                    int sampleFlangeDelay = (SAMPLE_RATE / (1000 * _flangeIntensity)) * powf(2, exponent);
                    
                    if (_samplesLeftForFlange != SAMPLE_RATE || s >= (SAMPLE_RATE / 2000)) {
                        // we have a delayed sample to add to this sample
                        
                        int16_t *flangeFrame = ringBuffer->getNextOutput();
                        int flangeIndex = s - sampleFlangeDelay;
                        
                        if (flangeIndex < 0) {
                            // we need to grab the flange sample from earlier in the buffer
                            flangeFrame = ringBuffer->getNextOutput() != ringBuffer->getBuffer()
                            ? ringBuffer->getNextOutput() - PACKET_LENGTH_SAMPLES
                            : ringBuffer->getNextOutput() + RING_BUFFER_LENGTH_SAMPLES - PACKET_LENGTH_SAMPLES;
                            
                            flangeIndex = PACKET_LENGTH_SAMPLES_PER_CHANNEL + (s - sampleFlangeDelay);
                        }
                        
                        int16_t leftFlangeSample = flangeFrame[flangeIndex];
                        int16_t rightFlangeSample = flangeFrame[flangeIndex + PACKET_LENGTH_SAMPLES_PER_CHANNEL];
                        
                        leftSample = (1 - _flangeWeight) * leftSample + (_flangeWeight * leftFlangeSample);
                        rightSample = (1 - _flangeWeight) * rightSample + (_flangeWeight * rightFlangeSample);
                        
                        _samplesLeftForFlange--;
                        
                        if (_samplesLeftForFlange == 0) {
                            _lastYawMeasuredMaximum = 0;
                        }
                    }
                }
#ifndef TEST_AUDIO_LOOPBACK
                outputLeft[s] = leftSample;
                outputRight[s] = rightSample;
#else 
                outputLeft[s] = inputLeft[s];
                outputRight[s] = inputLeft[s];                    
#endif
            }
            ringBuffer->setNextOutput(ringBuffer->getNextOutput() + PACKET_LENGTH_SAMPLES);
            
            if (ringBuffer->getNextOutput() == ringBuffer->getBuffer() + RING_BUFFER_LENGTH_SAMPLES) {
                ringBuffer->setNextOutput(ringBuffer->getBuffer());
            }
        }
    }

    eventuallySendRecvPing(inputLeft, outputLeft, outputRight);


    // add output (@speakers) data just written to the scope
    _scope->addSamples(1, outputLeft, BUFFER_LENGTH_SAMPLES_PER_CHANNEL);
    _scope->addSamples(2, outputRight, BUFFER_LENGTH_SAMPLES_PER_CHANNEL);

    gettimeofday(&_lastCallbackTime, NULL);
}
示例#13
0
文件: Vec2i.cpp 项目: eoma/totem-edk
float Vec2i::length() const
{
	return sqrtf(powf((float)x_, 2.0f) + powf((float)y_, 2.0f));
}
示例#14
0
文件: Vec2i.cpp 项目: eoma/totem-edk
float Vec2i::distancef(int x, int y) const
{
	return sqrtf(powf(((float)x_-(float)x), 2.0f) + pow(((float)y_-(float)y), 2.0f));
}
示例#15
0
void
commit_params (dt_iop_module_t *self, dt_iop_params_t *p1, dt_dev_pixelpipe_t *pipe, dt_dev_pixelpipe_iop_t *piece)
{
  dt_iop_profilegamma_params_t *p = (dt_iop_profilegamma_params_t *)p1;
  dt_iop_profilegamma_data_t *d = (dt_iop_profilegamma_data_t *)piece->data;

  const float linear = p->linear;
  const float gamma  = p->gamma;

  d->linear = p->linear;
  d->gamma  = p->gamma;

  float a, b, c, g;
  if(gamma == 1.0)
  {
#ifdef _OPENMP
    #pragma omp parallel for default(none) shared(d) schedule(static)
#endif
    for(int k=0; k<0x10000; k++) d->table[k] = 1.0*k/0x10000;
  }
  else
  {
    if(linear == 0.0)
    {
#ifdef _OPENMP
      #pragma omp parallel for default(none) shared(d) schedule(static)
#endif
      for(int k=0; k<0x10000; k++)
        d->table[k] = powf(1.00*k/0x10000, gamma);
    }
    else
    {
      if(linear<1.0)
      {
        g = gamma*(1.0-linear)/(1.0-gamma*linear);
        a = 1.0/(1.0+linear*(g-1));
        b = linear*(g-1)*a;
        c = powf(a*linear+b, g)/linear;
      }
      else
      {
        a = b = g = 0.0;
        c = 1.0;
      }
#ifdef _OPENMP
      #pragma omp parallel for default(none) shared(d,a,b,c,g) schedule(static)
#endif
      for(int k=0; k<0x10000; k++)
      {
        float tmp;
        if (k<0x10000*linear) tmp = c*k/0x10000;
        else tmp = powf(a*k/0x10000+b, g);
        d->table[k] = tmp;
      }
    }
  }

  // now the extrapolation stuff:
  const float x[4] = {0.7f, 0.8f, 0.9f, 1.0f};
  const float y[4] = {d->table[CLAMP((int)(x[0]*0x10000ul), 0, 0xffff)],
    d->table[CLAMP((int)(x[1]*0x10000ul), 0, 0xffff)],
    d->table[CLAMP((int)(x[2]*0x10000ul), 0, 0xffff)],
    d->table[CLAMP((int)(x[3]*0x10000ul), 0, 0xffff)]
  };
  dt_iop_estimate_exp(x, y, 4, d->unbounded_coeffs);
}
示例#16
0
float discreteTimeConstantForSampleRate(float timeConstant, float sampleRate)
{
    // hardcoded value is temporary build fix for Windows.
    // FIXME: replace hardcode 2.718282 with M_E until the correct MathExtras.h solution is determined.
    return 1 - powf(1 / 2.718282f, 1 / (sampleRate * timeConstant));
}
示例#17
0
float bsd_pow10f(float x)
    {
    return powf(10.f, x);
    }
示例#18
0
文件: boids.c 项目: mik0001/Blender
static int rule_goal_avoid(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
{
	BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid*) rule;
	BoidSettings *boids = bbd->part->boids;
	BoidParticle *bpa = pa->boid;
	EffectedPoint epoint;
	ListBase *effectors = bbd->sim->psys->effectors;
	EffectorCache *cur, *eff = NULL;
	EffectorCache temp_eff;
	EffectorData efd, cur_efd;
	float mul = (rule->type == eBoidRuleType_Avoid ? 1.0 : -1.0);
	float priority = 0.0f, len = 0.0f;
	int ret = 0;

	pd_point_from_particle(bbd->sim, pa, &pa->state, &epoint);

	/* first find out goal/predator with highest priority */
	if(effectors) for(cur = effectors->first; cur; cur=cur->next) {
		Object *eob = cur->ob;
		PartDeflect *pd = cur->pd;

		if(gabr->ob && (rule->type != eBoidRuleType_Goal || gabr->ob != bpa->ground)) {
			if(gabr->ob == eob) {
				/* TODO: effectors with multiple points */
				if(get_effector_data(cur, &efd, &epoint, 0)) {
					if(cur->pd && cur->pd->forcefield == PFIELD_BOID)
						priority = mul * pd->f_strength * effector_falloff(cur, &efd, &epoint, bbd->part->effector_weights);
					else
						priority = 1.0;

					eff = cur;
				}
				break;
			}
		}
		else if(rule->type == eBoidRuleType_Goal && eob == bpa->ground)
			; /* skip current object */
		else if(pd->forcefield == PFIELD_BOID && mul * pd->f_strength > 0.0f && get_effector_data(cur, &cur_efd, &epoint, 0)) {
			float temp = mul * pd->f_strength * effector_falloff(cur, &cur_efd, &epoint, bbd->part->effector_weights);

			if(temp == 0.0f)
				; /* do nothing */
			else if(temp > priority) {
				priority = temp;
				eff = cur;
				efd = cur_efd;
				len = efd.distance;
			}
			/* choose closest object with same priority */
			else if(temp == priority && efd.distance < len) {
				eff = cur;
				efd = cur_efd;
				len = efd.distance;
			}
		}
	}

	/* if the object doesn't have effector data we have to fake it */
	if(eff == NULL && gabr->ob) {
		memset(&temp_eff, 0, sizeof(EffectorCache));
		temp_eff.ob = gabr->ob;
		temp_eff.scene = bbd->sim->scene;
		eff = &temp_eff;
		get_effector_data(eff, &efd, &epoint, 0);
		priority = 1.0f;
	}

	/* then use that effector */
	if(priority > (rule->type==eBoidRuleType_Avoid ? gabr->fear_factor : 0.0f)) { /* with avoid, factor is "fear factor" */
		Object *eob = eff->ob;
		PartDeflect *pd = eff->pd;
		float surface = (pd && pd->shape == PFIELD_SHAPE_SURFACE) ? 1.0f : 0.0f;

		if(gabr->options & BRULE_GOAL_AVOID_PREDICT) {
			/* estimate future location of target */
			get_effector_data(eff, &efd, &epoint, 1);

			mul_v3_fl(efd.vel, efd.distance / (val->max_speed * bbd->timestep));
			add_v3_v3(efd.loc, efd.vel);
			sub_v3_v3v3(efd.vec_to_point, pa->prev_state.co, efd.loc);
			efd.distance = len_v3(efd.vec_to_point);
		}

		if(rule->type == eBoidRuleType_Goal && boids->options & BOID_ALLOW_CLIMB && surface!=0.0f) {
			if(!bbd->goal_ob || bbd->goal_priority < priority) {
				bbd->goal_ob = eob;
				copy_v3_v3(bbd->goal_co, efd.loc);
				copy_v3_v3(bbd->goal_nor, efd.nor);
			}
		}
		else if(rule->type == eBoidRuleType_Avoid && bpa->data.mode == eBoidMode_Climbing &&
			priority > 2.0f * gabr->fear_factor) {
			/* detach from surface and try to fly away from danger */
			negate_v3_v3(efd.vec_to_point, bpa->gravity);
		}

		copy_v3_v3(bbd->wanted_co, efd.vec_to_point);
		mul_v3_fl(bbd->wanted_co, mul);

		bbd->wanted_speed = val->max_speed * priority;

		/* with goals factor is approach velocity factor */
		if(rule->type == eBoidRuleType_Goal && boids->landing_smoothness > 0.0f) {
			float len2 = 2.0f*len_v3(pa->prev_state.vel);

			surface *= pa->size * boids->height;

			if(len2 > 0.0f && efd.distance - surface < len2) {
				len2 = (efd.distance - surface)/len2;
				bbd->wanted_speed *= powf(len2, boids->landing_smoothness);
			}
		}

		ret = 1;
	}

	return ret;
}
示例#19
0
void Functions::pow(Aurora::NWScript::FunctionContext &ctx) {
	ctx.getReturn() = powf(ctx.getParams()[0].getFloat(), ctx.getParams()[1].getFloat());
}
/* Evaluate spline IK for a given bone */
static void splineik_evaluate_bone(tSplineIK_Tree *tree, Scene *scene, Object *ob, bPoseChannel *pchan,
                                   int index, float ctime)
{
	bSplineIKConstraint *ikData = tree->ikData;
	float poseHead[3], poseTail[3], poseMat[4][4];
	float splineVec[3], scaleFac, radius = 1.0f;

	/* firstly, calculate the bone matrix the standard way, since this is needed for roll control */
	BKE_pose_where_is_bone(scene, ob, pchan, ctime, 1);

	copy_v3_v3(poseHead, pchan->pose_head);
	copy_v3_v3(poseTail, pchan->pose_tail);

	/* step 1: determine the positions for the endpoints of the bone */
	{
		float vec[4], dir[3], rad;
		float tailBlendFac = 1.0f;

		/* determine if the bone should still be affected by SplineIK */
		if (tree->points[index + 1] >= 1.0f) {
			/* spline doesn't affect the bone anymore, so done... */
			pchan->flag |= POSE_DONE;
			return;
		}
		else if ((tree->points[index] >= 1.0f) && (tree->points[index + 1] < 1.0f)) {
			/* blending factor depends on the amount of the bone still left on the chain */
			tailBlendFac = (1.0f - tree->points[index + 1]) / (tree->points[index] - tree->points[index + 1]);
		}

		/* tail endpoint */
		if (where_on_path(ikData->tar, tree->points[index], vec, dir, NULL, &rad, NULL)) {
			/* apply curve's object-mode transforms to the position
			 * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
			 */
			if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
				mul_m4_v3(ikData->tar->obmat, vec);

			/* convert the position to pose-space, then store it */
			mul_m4_v3(ob->imat, vec);
			interp_v3_v3v3(poseTail, pchan->pose_tail, vec, tailBlendFac);

			/* set the new radius */
			radius = rad;
		}

		/* head endpoint */
		if (where_on_path(ikData->tar, tree->points[index + 1], vec, dir, NULL, &rad, NULL)) {
			/* apply curve's object-mode transforms to the position
			 * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
			 */
			if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
				mul_m4_v3(ikData->tar->obmat, vec);

			/* store the position, and convert it to pose space */
			mul_m4_v3(ob->imat, vec);
			copy_v3_v3(poseHead, vec);

			/* set the new radius (it should be the average value) */
			radius = (radius + rad) / 2;
		}
	}

	/* step 2: determine the implied transform from these endpoints
	 *     - splineVec: the vector direction that the spline applies on the bone
	 *     - scaleFac: the factor that the bone length is scaled by to get the desired amount
	 */
	sub_v3_v3v3(splineVec, poseTail, poseHead);
	scaleFac = len_v3(splineVec) / pchan->bone->length;

	/* step 3: compute the shortest rotation needed to map from the bone rotation to the current axis
	 *      - this uses the same method as is used for the Damped Track Constraint (see the code there for details)
	 */
	{
		float dmat[3][3], rmat[3][3], tmat[3][3];
		float raxis[3], rangle;

		/* compute the raw rotation matrix from the bone's current matrix by extracting only the
		 * orientation-relevant axes, and normalizing them
		 */
		copy_v3_v3(rmat[0], pchan->pose_mat[0]);
		copy_v3_v3(rmat[1], pchan->pose_mat[1]);
		copy_v3_v3(rmat[2], pchan->pose_mat[2]);
		normalize_m3(rmat);

		/* also, normalize the orientation imposed by the bone, now that we've extracted the scale factor */
		normalize_v3(splineVec);

		/* calculate smallest axis-angle rotation necessary for getting from the
		 * current orientation of the bone, to the spline-imposed direction
		 */
		cross_v3_v3v3(raxis, rmat[1], splineVec);

		rangle = dot_v3v3(rmat[1], splineVec);
		CLAMP(rangle, -1.0f, 1.0f);
		rangle = acosf(rangle);

		/* multiply the magnitude of the angle by the influence of the constraint to
		 * control the influence of the SplineIK effect
		 */
		rangle *= tree->con->enforce;

		/* construct rotation matrix from the axis-angle rotation found above
		 *	- this call takes care to make sure that the axis provided is a unit vector first
		 */
		axis_angle_to_mat3(dmat, raxis, rangle);

		/* combine these rotations so that the y-axis of the bone is now aligned as the spline dictates,
		 * while still maintaining roll control from the existing bone animation
		 */
		mul_m3_m3m3(tmat, dmat, rmat); /* m1, m3, m2 */
		normalize_m3(tmat); /* attempt to reduce shearing, though I doubt this'll really help too much now... */
		copy_m4_m3(poseMat, tmat);
	}

	/* step 4: set the scaling factors for the axes */
	{
		/* only multiply the y-axis by the scaling factor to get nice volume-preservation */
		mul_v3_fl(poseMat[1], scaleFac);

		/* set the scaling factors of the x and z axes from... */
		switch (ikData->xzScaleMode) {
			case CONSTRAINT_SPLINEIK_XZS_ORIGINAL:
			{
				/* original scales get used */
				float scale;

				/* x-axis scale */
				scale = len_v3(pchan->pose_mat[0]);
				mul_v3_fl(poseMat[0], scale);
				/* z-axis scale */
				scale = len_v3(pchan->pose_mat[2]);
				mul_v3_fl(poseMat[2], scale);
				break;
			}
			case CONSTRAINT_SPLINEIK_XZS_INVERSE:
			{
				/* old 'volume preservation' method using the inverse scale */
				float scale;

				/* calculate volume preservation factor which is
				 * basically the inverse of the y-scaling factor
				 */
				if (fabsf(scaleFac) != 0.0f) {
					scale = 1.0f / fabsf(scaleFac);

					/* we need to clamp this within sensible values */
					/* NOTE: these should be fine for now, but should get sanitised in future */
					CLAMP(scale, 0.0001f, 100000.0f);
				}
				else
					scale = 1.0f;

				/* apply the scaling */
				mul_v3_fl(poseMat[0], scale);
				mul_v3_fl(poseMat[2], scale);
				break;
			}
			case CONSTRAINT_SPLINEIK_XZS_VOLUMETRIC:
			{
				/* improved volume preservation based on the Stretch To constraint */
				float final_scale;
				
				/* as the basis for volume preservation, we use the inverse scale factor... */
				if (fabsf(scaleFac) != 0.0f) {
					/* NOTE: The method here is taken wholesale from the Stretch To constraint */
					float bulge = powf(1.0f / fabsf(scaleFac), ikData->bulge);
					
					if (bulge > 1.0f) {
						if (ikData->flag & CONSTRAINT_SPLINEIK_USE_BULGE_MAX) {
							float bulge_max = max_ff(ikData->bulge_max, 1.0f);
							float hard = min_ff(bulge, bulge_max);
							
							float range = bulge_max - 1.0f;
							float scale = (range > 0.0f) ? 1.0f / range : 0.0f;
							float soft = 1.0f + range * atanf((bulge - 1.0f) * scale) / (float)M_PI_2;
							
							bulge = interpf(soft, hard, ikData->bulge_smooth);
						}
					}
					if (bulge < 1.0f) {
						if (ikData->flag & CONSTRAINT_SPLINEIK_USE_BULGE_MIN) {
							float bulge_min = CLAMPIS(ikData->bulge_min, 0.0f, 1.0f);
							float hard = max_ff(bulge, bulge_min);
							
							float range = 1.0f - bulge_min;
							float scale = (range > 0.0f) ? 1.0f / range : 0.0f;
							float soft = 1.0f - range * atanf((1.0f - bulge) * scale) / (float)M_PI_2;
							
							bulge = interpf(soft, hard, ikData->bulge_smooth);
						}
					}
					
					/* compute scale factor for xz axes from this value */
					final_scale = sqrtf(bulge);
				}
				else {
					/* no scaling, so scale factor is simple */
					final_scale = 1.0f;
				}
				
				/* apply the scaling (assuming normalised scale) */
				mul_v3_fl(poseMat[0], final_scale);
				mul_v3_fl(poseMat[2], final_scale);
				break;
			}
		}

		/* finally, multiply the x and z scaling by the radius of the curve too,
		 * to allow automatic scales to get tweaked still
		 */
		if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_CURVERAD) == 0) {
			mul_v3_fl(poseMat[0], radius);
			mul_v3_fl(poseMat[2], radius);
		}
	}

	/* step 5: set the location of the bone in the matrix */
	if (ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) {
		/* when the 'no-root' option is affected, the chain can retain
		 * the shape but be moved elsewhere
		 */
		copy_v3_v3(poseHead, pchan->pose_head);
	}
	else if (tree->con->enforce < 1.0f) {
		/* when the influence is too low
		 *	- blend the positions for the 'root' bone
		 *	- stick to the parent for any other
		 */
		if (pchan->parent) {
			copy_v3_v3(poseHead, pchan->pose_head);
		}
		else {
			/* FIXME: this introduces popping artifacts when we reach 0.0 */
			interp_v3_v3v3(poseHead, pchan->pose_head, poseHead, tree->con->enforce);
		}
	}
	copy_v3_v3(poseMat[3], poseHead);

	/* finally, store the new transform */
	copy_m4_m4(pchan->pose_mat, poseMat);
	copy_v3_v3(pchan->pose_head, poseHead);

	/* recalculate tail, as it's now outdated after the head gets adjusted above! */
	BKE_pose_where_is_bone_tail(pchan);

	/* done! */
	pchan->flag |= POSE_DONE;
}
示例#21
0
void
Valve::processReplacing (float **inputs,
								float **outputs,
								int sampleFrames)
{
    int i;

    float l, r, lout, rout, fx;
	param->PERIOD = sampleFrames;
	param->fPERIOD = param->PERIOD;

    if (Pstereo != 0) {
        //Stereo
        for (i = 0; i < param->PERIOD; i++) {
            outputs[0][i] = inputs[0][i] * inputvol;
            outputs[1][i] = inputs[1][i] * inputvol;
        };
    } else {
        for (i = 0; i < param->PERIOD; i++) {
            outputs[0][i] =
                (inputs[0][i]  +  inputs[1][i] ) * inputvol;
        };
    };

    harm->harm_out(outputs[0],outputs[1]);


    if (Pprefiltering != 0)
        applyfilters (outputs[0], outputs[1]);

    if(Ped) {
        for (i =0; i<param->PERIOD; i++) {
            outputs[0][i]=Wshape(outputs[0][i]);
            if (Pstereo != 0) outputs[1][i]=Wshape(outputs[1][i]);
        }
    }

    for (i =0; i<param->PERIOD; i++) { //soft limiting to 3.0 (max)
        fx = outputs[0][i];
        if (fx>1.0f) fx = 3.0f - 2.0f/sqrtf(fx);
        outputs[0][i] = fx;
        fx = outputs[1][i];
        if (fx>1.0f) fx = 3.0f - 2.0f/sqrtf(fx);
        outputs[1][i] = fx;
    }

    if (q == 0.0f) {
        for (i =0; i<param->PERIOD; i++) {
            if (outputs[0][i] == q) fx = fdist;
            else fx =outputs[0][i] / (1.0f - powf(2.0f,-dist * outputs[0][i] ));
            otml = atk * otml + fx - itml;
            itml = fx;
            outputs[0][i]= otml;
        }
    } else {
        for (i = 0; i < param->PERIOD; i++) {
            if (outputs[0][i] == q) fx = fdist + qcoef;
            else fx =(outputs[0][i] - q) / (1.0f - powf(2.0f,-dist * (outputs[0][i] - q))) + qcoef;
            otml = atk * otml + fx - itml;
            itml = fx;
            outputs[0][i]= otml;

        }
    }


    if (Pstereo != 0) {

        if (q == 0.0f) {
            for (i =0; i<param->PERIOD; i++) {
                if (outputs[1][i] == q) fx = fdist;
                else fx = outputs[1][i] / (1.0f - powf(2.0f,-dist * outputs[1][i] ));
                otmr = atk * otmr + fx - itmr;
                itmr = fx;
                outputs[1][i]= otmr;

            }
        } else {
            for (i = 0; i < param->PERIOD; i++) {
                if (outputs[1][i] == q) fx = fdist + qcoef;
                else fx = (outputs[1][i] - q) / (1.0f - powf(2.0f,-dist * (outputs[1][i] - q))) + qcoef;
                otmr = atk * otmr + fx - itmr;
                itmr = fx;
                outputs[1][i]= otmr;

            }
        }

    }



    if (Pprefiltering == 0)
        applyfilters (outputs[0], outputs[1]);

    if (Pstereo == 0) memcpy (outputs[1] , outputs[0], param->PERIOD * sizeof(float));


    float level = dB2rap (60.0f * (float)Plevel / 127.0f - 40.0f);

    for (i = 0; i < param->PERIOD; i++) {
        lout = outputs[0][i];
        rout = outputs[1][i];


        l = lout * (1.0f - lrcross) + rout * lrcross;
        r = rout * (1.0f - lrcross) + lout * lrcross;

        lout = l;
        rout = r;

        outputs[0][i] = lout * 2.0f * level * panning;
        outputs[1][i] = rout * 2.0f * level * (1.0f -panning);

    };



};
static inline float floatToFrequency(float value) {
    if (value > 0.97f) return MAXFREQ;
    if (value < 0.03f) return MINFREQ;
    value = powf(10.0f, (value + ((0.4f - fabsf(value - 0.4f)) * 0.3f)) * log10f(MAXFREQ - MINFREQ)) + MINFREQ;
    return value < MAXFREQ ? value : MAXFREQ;
}
void CCEaseOut::update(float time)
{
    m_pOther->update(powf(time, 1 / m_fRate));
}
示例#24
0
//this gets called when the object is created; everytime the user types in new args, this will get called
void *curvesmooth_new(t_symbol *s, long argc, t_atom *argv)
{
	int i, j;
    
    long upsmooth;      // in ms
    long downsmooth;    // in ms
    double upcoeff;
    double downcoeff;
    
    // deal with incoming values
    if (argc > 0) {
        upsmooth = atom_getlong(argv);
    } else {
        upsmooth = 0;
    }
	
    if (argc > 1) {
        downsmooth = atom_getlong(argv+1);
    } else {
        downsmooth = 0;
    }
	
    if (argc > 2) {
        upcoeff = atom_getfloat(argv+2);
    } else {
        upcoeff = 0;
    }
	
    if (argc > 3) {
        downcoeff = atom_getfloat(argv+3);
    } else {
        downcoeff = 0;
    }
    
    // post("us: %ld, ds: %ld, uc: %f, dc: %f", upsmooth, downsmooth, upcoeff, downcoeff);
    
    //leave this; creates our object
    t_curvesmooth *x = (t_curvesmooth *)object_alloc(curvesmooth_class);
    
    //zero out the struct, to be careful (takk to jkclayton)
    if (x) { 
        for(i=sizeof(t_pxobject);i<sizeof(t_curvesmooth);i++) {
            ((char *)x)[i]=0;
        }
	
        x->num_inputs = 5;
        x->num_outputs = 1;

        //setup up inputs and outputs, for audio
        
        //inputs
        dsp_setup((t_pxobject *)x, x->num_inputs);
        //if you just need one input for message (not using audio), you can just set num_inputs = 1
        //i don't think this causes a performance hit.
        
        //outputs
        for (i=0;i<x->num_outputs;i++) {
            outlet_new((t_object *)x, "signal");
        }   
        //can use intin, floatout, listout, etc... for setting up non-audio ins and outs.
        //but, the order in which you call these funcs is important.
        //for instance, from gQ~
        /*    
        x->outfloat = floatout((t_object *)x);
        x->outlist = listout((t_object *)x);
        outlet_new((t_object *)x, "signal");
        outlet_new((t_object *)x, "signal");
       */
       //this will create four outputs, *rightmost* created first, so the outlets, from left to right, will look like
       //(signal) (signal) (list) (float)
       //when you instantiate gQ~ in Max/MSP.
        
        //initialize some variables; important to do this!
        for (i=0;i<x->num_inputs;i++){
            x->in[i] = 0.;
            x->in_connected[i] = 0;
        }
        x->power = 1;

        x->in[1] = (double)upsmooth;
        x->in[2] = (double)downsmooth;
        x->in[3] = (double)upcoeff;
        x->in[4] = (double)downcoeff;
        x->c = 0.;
        x->update_D = 1;
        x->current_direction = 1;
        x->D = 0.;
        
        //lookup table alloc and init
        for(i=0;i<TABLE_SIZE;i++) {
            //x->s_table_k_exp[i]= t_getbytes(TABLE_SIZE*sizeof(double));
            x->s_table_k_exp[i]= (double *)sysmem_newptr(TABLE_SIZE*sizeof(double));
            if (!x->s_table_k_exp[i]) {
                error("curvesmooth~: out of memory");
                return NULL;
            }
                
            //x->s_table_k_log[i] = t_getbytes(TABLE_SIZE*sizeof(double));
            x->s_table_k_log[i] = (double *)sysmem_newptr(TABLE_SIZE*sizeof(double));
            if (!x->s_table_k_log[i]) {
                error("curvesmooth~: out of memory");
                return NULL;
            }
        }
        for(i=2;i<TABLE_SIZE;i++) { //k, indices 2 to 1000 (exp) and 1 to 1000 (log, so .001 to 1, though we should never use 1)
            for(j=1;j<TABLE_SIZE;j++) { //d or d/D, 0 to 1
                x->s_table_k_exp[i][j] = (i-1.) / ((powf(i, j*.001) - 1.));
                x->s_table_k_log[i-1][j] = ((i-1.)*.001 - 1.) / ((powf((i-1.)*.001, j*.001) - 1.));
            }
            x->s_table_k_exp[i][0] = 0.;
            x->s_table_k_log[i][0] = 0.;
        }

        //occasionally this line is necessary if you are doing weird asynchronous things with the in/out vectors
        //x->x_obj.z_misc = Z_NO_INPLACE;
    }

    return (x);
}
void CCEaseExponentialOut::update(float time)
{
    m_pOther->update(time == 1 ? 1 : (-powf(2, -10 * time / 1) + 1));
}
示例#26
0
文件: switcher.c 项目: djezuz/vlc
/*****************************************************************************
 * VideoGetBuffer: Build an alternate video buffer
 *****************************************************************************/
static block_t *VideoGetBuffer( sout_stream_t *p_stream, sout_stream_id_t *id,
                                block_t *p_buffer )
{
    sout_stream_sys_t *p_sys = p_stream->p_sys;
    int i_out;
    block_t *p_out;

    id->p_frame->quality = p_sys->i_qscale * powf(2.0, FF_LAMBDA_SHIFT + 7.0)
                            / 139.0;
    id->p_frame->interlaced_frame = 0;
    id->p_frame->top_field_first = 1;
    id->p_frame->pts = p_buffer->i_dts;

    if ( id->i_nb_pred >= p_sys->i_gop )
    {
        id->p_frame->pict_type = AV_PICTURE_TYPE_I;
#if 0
        id->p_frame->me_threshold = 0;
        id->p_frame->mb_threshold = 0;
#endif
        id->i_nb_pred = 0;
    }
    else
    {
        id->p_frame->pict_type = AV_PICTURE_TYPE_P;
#if 0
        if ( id->p_frame->mb_type != NULL )
        {
            id->p_frame->me_threshold = MAX_THRESHOLD;
            id->p_frame->mb_threshold = MAX_THRESHOLD;
        }
#endif
        id->i_nb_pred++;
    }

    i_out = avcodec_encode_video( id->ff_enc_c, id->p_buffer_out,
                                  id->ff_enc_c->width * id->ff_enc_c->height * 3,
                                  id->p_frame );

    if ( i_out <= 0 )
        return NULL;

#if 0
    if ( id->p_frame->mb_type == NULL
          && id->ff_enc_c->coded_frame->pict_type != AV_PICTURE_TYPE_I )
    {
        int mb_width = (id->ff_enc_c->width + 15) / 16;
        int mb_height = (id->ff_enc_c->height + 15) / 16;
        int h_chroma_shift, v_chroma_shift;
        int i;

        avcodec_get_chroma_sub_sample( id->ff_enc_c->pix_fmt, &h_chroma_shift,
                                       &v_chroma_shift );

        id->p_frame->motion_subsample_log2
            = id->ff_enc_c->coded_frame->motion_subsample_log2;
        id->p_frame->mb_type = malloc( ((mb_width + 1) * (mb_height + 1) + 1)
                                    * sizeof(uint32_t) );
        memcpy( id->p_frame->mb_type, id->ff_enc_c->coded_frame->mb_type,
                    (mb_width + 1) * mb_height * sizeof(id->p_frame->mb_type[0]));

        for ( i = 0; i < 2; i++ )
        {
            int stride = ((16 * mb_width )
                    >> id->ff_enc_c->coded_frame->motion_subsample_log2) + 1;
            int height = ((16 * mb_height)
                    >> id->ff_enc_c->coded_frame->motion_subsample_log2);
            int b8_stride = mb_width * 2 + 1;

            if ( id->ff_enc_c->coded_frame->motion_val[i] )
            {
                id->p_frame->motion_val[i] = malloc( 2 * stride * height
                                                * sizeof(int16_t) );
                memcpy( id->p_frame->motion_val[i],
                            id->ff_enc_c->coded_frame->motion_val[i],
                            2 * stride * height * sizeof(int16_t) );
            }
            if ( id->ff_enc_c->coded_frame->ref_index[i] )
            {
                id->p_frame->ref_index[i] = malloc( b8_stride * 2 * mb_height
                                               * sizeof(int8_t) );
                memcpy( id->p_frame->ref_index[i],
                            id->ff_enc_c->coded_frame->ref_index[i],
                            b8_stride * 2 * mb_height * sizeof(int8_t));
            }
        }
    }
示例#27
0
/*
=================
CL_MouseMove
=================
*/
void CL_MouseMove(usercmd_t *cmd)	
{
	float mx, my;

	if (m_filter->integer)
	{
		mx = (cl.mouseDx[0] + cl.mouseDx[1]) * 0.5f;
		my = (cl.mouseDy[0] + cl.mouseDy[1]) * 0.5f;
	}
	else
	{
		mx = cl.mouseDx[cl.mouseIndex];
		my = cl.mouseDy[cl.mouseIndex];
	}

	cl.mouseIndex ^= 1;
	cl.mouseDx[cl.mouseIndex] = 0;
	cl.mouseDy[cl.mouseIndex] = 0;

	if (mx == 0.0f && my == 0.0f)
		return;

	if (cl_mouseAccel->value != 0.0f)
	{
		if(cl_mouseAccelStyle->integer == 0)
		{
			float accelSensitivity;
			float rate;

			rate = sqrt(mx * mx + my * my) / (float) frame_msec;

			accelSensitivity = cl_sensitivity->value + rate * cl_mouseAccel->value;
			mx *= accelSensitivity;
			my *= accelSensitivity;

			if(cl_showMouseRate->integer)
				Com_Printf("rate: %f, accelSensitivity: %f\n", rate, accelSensitivity);
		}
		else
		{
			float rate[2];
			float power[2];

			// sensitivity remains pretty much unchanged at low speeds
			// cl_mouseAccel is a power value to how the acceleration is shaped
			// cl_mouseAccelOffset is the rate for which the acceleration will have doubled the non accelerated amplification
			// NOTE: decouple the config cvars for independent acceleration setup along X and Y?

			rate[0] = fabs(mx) / (float) frame_msec;
			rate[1] = fabs(my) / (float) frame_msec;
			power[0] = powf(rate[0] / cl_mouseAccelOffset->value, cl_mouseAccel->value);
			power[1] = powf(rate[1] / cl_mouseAccelOffset->value, cl_mouseAccel->value);

			mx = cl_sensitivity->value * (mx + ((mx < 0) ? -power[0] : power[0]) * cl_mouseAccelOffset->value);
			my = cl_sensitivity->value * (my + ((my < 0) ? -power[1] : power[1]) * cl_mouseAccelOffset->value);

			if(cl_showMouseRate->integer)
				Com_Printf("ratex: %f, ratey: %f, powx: %f, powy: %f\n", rate[0], rate[1], power[0], power[1]);
		}
	}
	else
	{
		mx *= cl_sensitivity->value;
		my *= cl_sensitivity->value;
	}

	// ingame FOV
	mx *= cl.cgameSensitivity;
	my *= cl.cgameSensitivity;

	// add mouse X/Y movement to cmd
	if(in_strafe.active)
		cmd->rightmove = ClampChar(cmd->rightmove + m_side->value * mx);
	else
		cl.viewangles[YAW] -= m_yaw->value * mx;

	if ((in_mlooking || cl_freelook->integer) && !in_strafe.active)
		cl.viewangles[PITCH] += m_pitch->value * my;
	else
		cmd->forwardmove = ClampChar(cmd->forwardmove - m_forward->value * my);
}
示例#28
0
void drawTriangleToRaster(OWRaster *raster, 
                          OWTriangle& triangle, 
                          OWMaterial material, 
                          OWScene scene,
                          bool phong,
                          OWVector4* camPosition)
{
    OWColorFloat* fillcolorF = material.color;
    unsigned rasterHeight = raster->getHeight();
    unsigned rasterWidth = raster->getWidth();
    float lambda1;
    float lambda2;
    float lambda3;
    float zDepth;
    lambda1=lambda3=lambda2=0.0f;
    
    float zb1=triangle.zBuffer[0];
    float zb2=triangle.zBuffer[1];
    float zb3=triangle.zBuffer[2];
    
    float xLength = scene.maxX - scene.minX;
    float yLength = scene.maxY - scene.minY;
    
    float x1,x2,x3,y1,y2,y3,z1,z2,z3;
    x1 = triangle.getVec1().getX();
    x2 = triangle.getVec2().getX();
    x3 = triangle.getVec3().getX();
    
    y1 = triangle.getVec1().getY();
    y2 = triangle.getVec2().getY();
    y3 = triangle.getVec3().getY();
    
    z1 = triangle.getVec1().getZ();
    z2 = triangle.getVec2().getZ();
    z3 = triangle.getVec3().getZ();
    
    float maxTX=fminf(scene.maxX,fmaxf(x1, fmaxf(x2, x3)));
    float maxTY=fminf(scene.maxY,fmaxf(y1, fmaxf(y2, y3)));
    float minTX=fmaxf(scene.minX,fminf(x1, fminf(x2, x3)));
    float minTY=fmaxf(scene.minY,fminf(y1, fminf(y2, y3)));

    unsigned maxRX = ceilf(fminf(rasterWidth, (maxTX - scene.minX)/xLength*(float)rasterWidth));
    unsigned minRX = floorf(fmaxf(0.0f,       (minTX - scene.minX)/xLength*(float)rasterWidth));
    unsigned maxRY = ceilf(fminf(rasterWidth, (maxTY - scene.minY)/yLength*(float)rasterHeight));
    unsigned minRY = floorf(fmaxf(0.0f,       (minTY - scene.minY)/yLength*(float)rasterHeight));
    
    if (maxRX > rasterWidth) {
        printf("raster x max bound error.\n");
        //system("pause");
        maxRX = rasterWidth;
    }
    if (maxRY > rasterHeight) {
        printf("raster y max bound error.\n");
        //system("pause");
        maxRY = rasterHeight;
    }
    
    for (unsigned y=minRY; y<maxRY; y++) {
        for (unsigned x=minRX; x<maxRX; x++) {
            float fx=((float)x/(float)rasterWidth) * xLength+scene.minX;
            float fy=((float)y/(float)rasterHeight)* yLength+scene.minY;
            calculateTriBarycentricCoordinates(triangle, fx, fy, &lambda1, &lambda2, &lambda3);
            zDepth = zb1*lambda1 + zb2*lambda2 + zb3*lambda3;
            if(
               lambda1 >= 0.0f && lambda2 >= 0.0f && lambda3 >= 0.0f 
               //&& (lambda1 <= 0.02f || lambda2 <= 0.02f || lambda3 <= 0.02f)
               && raster->z_buffer[x + y * rasterWidth] > zDepth
               //lambda1 <= 1.0f && lambda2 <= 1.0f && lambda3 <= 1.0f
               )
            {
                raster->z_buffer[x + y * rasterWidth] = zDepth;
                OWColorChannelFloat red,green,blue;
                red = fillcolorF[0].r * lambda1 + fillcolorF[1].r * lambda2 + fillcolorF[2].r * lambda3;
                green = fillcolorF[0].g * lambda1 + fillcolorF[1].g * lambda2 + fillcolorF[2].g * lambda3;
                blue = fillcolorF[0].b * lambda1 + fillcolorF[1].b * lambda2 + fillcolorF[2].b * lambda3;
                if (phong == true) {
/***Phong Mode*************************************************************************************/
                    for (list<OWLight>::iterator iterLight = scene.lightList.begin(); iterLight != scene.lightList.end(); iterLight++) {
                        OWVector4* currVector = new OWVector4;
                        OWVector4* n = new OWVector4;
                        
                        currVector->setX(triangle.worldCoorVec[0].getX() * lambda1 + triangle.worldCoorVec[1].getX() * lambda2 + triangle.worldCoorVec[2].getX() * lambda3);
                        currVector->setY(triangle.worldCoorVec[0].getY() * lambda1 + triangle.worldCoorVec[1].getY() * lambda2 + triangle.worldCoorVec[2].getY() * lambda3);
                        currVector->setZ(triangle.worldCoorVec[0].getZ() * lambda1 + triangle.worldCoorVec[1].getZ() * lambda2 + triangle.worldCoorVec[2].getZ() * lambda3);
                        
                        for (int i=0; i<3; i++) {
                            triangle.norVec[i].normalise();
                        }
                        n->setX(triangle.norVec[0].getX() * lambda1 + triangle.norVec[1].getX() * lambda2 + triangle.norVec[2].getX() * lambda3);
                        n->setY(triangle.norVec[0].getY() * lambda1 + triangle.norVec[1].getY() * lambda2 + triangle.norVec[2].getY() * lambda3);
                        n->setZ(triangle.norVec[0].getZ() * lambda1 + triangle.norVec[1].getZ() * lambda2 + triangle.norVec[2].getZ() * lambda3);
                        
                        OWVector4* l = vectorSubtract((*iterLight).myPosition, currVector);
                        
                        l->normalise();
                        n->normalise();
                        float l_dot_n = l->dotProduct(*n);
                        float diffContr = fmaxf(0.0f, l_dot_n);
                        
                        n->scale(2*l_dot_n);
                        OWVector4* r = vectorSubtract(n,l);
                        OWVector4* v = vectorSubtract(camPosition, currVector);
                        r->normalise();
                        v->normalise();
                        
                        OWColorFloat Idif;
                        if (diffContr < 0.0f) {
                            diffContr = 0.0f;
                        }
                        Idif.a=1.0f;
                        Idif.r=(*iterLight).myColor.r * red * diffContr;
                        Idif.g=(*iterLight).myColor.g * green * diffContr;
                        Idif.b=(*iterLight).myColor.b * blue * diffContr;
                        
                        OWColorFloat shininessColor = material.shininessColor;
                        OWColorFloat Ispec;
                        float specContri = powf(v->dotProduct(*r), shininessColor.a);
                        //float specContri = v->dotProduct(*r);
                        if (
                            l_dot_n >= 0.0f 
                            && specContri >= 0.0f
                            ) {
                            Ispec.a = 1.0f;
                            Ispec.r = (*iterLight).myColor.r * shininessColor.r * specContri;
                            Ispec.g = (*iterLight).myColor.g * shininessColor.g * specContri;
                            Ispec.b = (*iterLight).myColor.b * shininessColor.b * specContri;
                        }else{
                            Ispec.a = 0.0f;
                            Ispec.r = 0.0f;
                            Ispec.g = 0.0f;
                            Ispec.b = 0.0f;
                        }
                        scene.ambient.a = 0.0f;
                        //OWColorFloat tempColor = Idif;
                        //OWColorFloat tempColor = Ispec;
                        //OWColorFloat tempColor = scene.ambient;
                        //OWColorFloat tempColor = colorAdd(Idif, scene.ambient);
                        //OWColorFloat tempColor = colorAdd(Idif, Ispec);
                        OWColorFloat tempColor = colorAdd(Idif, colorAdd(Ispec, scene.ambient));
                        
                        colorNormalise(tempColor);
                        
                        red = tempColor.r;
                        green = tempColor.g;
                        blue = tempColor.b;
                    }
                    
                }
               
                raster->pixels[x + y * rasterWidth] = drawARGBColorFromFloatColor(red, green, blue);
            }
        }
    }
    //triangle.printMyself();
    
}
示例#29
0
//-----------------------------------------------
// Response curve function for the move axes
//-----------------------------------------------
static float ResponseCurve( int curve, float x, int axis, float sensitivity )
{
	switch ( curve )
	{
	case 1:
		// quadratic
		if ( x < 0 )
			return -(x*x) * sensitivity;
		return x*x * sensitivity;

	case 2:
		// cubic
		return x*x*x*sensitivity;

	case 3:
		{
		// quadratic extreme
		float extreme = 1.0f;
		if ( fabs( x ) >= 0.95f )
		{
			extreme = 1.5f;
		}
		if ( x < 0 )
			return -extreme * x*x*sensitivity;
		return extreme * x*x*sensitivity;
		}
	case 4:
		{
			float flScale = sensitivity < 0.0f ? -1.0f : 1.0f;

			sensitivity = clamp( fabs( sensitivity ), 1.0e-8f, 1000.0f );

			float oneOverSens = 1.0f / sensitivity;
		
			if ( x < 0.0f )
			{
				flScale = -flScale;
			}

			float retval = clamp( powf( fabs( x ), oneOverSens ), 0.0f, 1.0f );
			return retval * flScale;
		}
		break;
	case 5:
		{
			float out = x;

			if( fabs(out) <= 0.6f )
			{
				out *= 0.5f;
			}

			out = out * sensitivity;
			return out;
		}
		break;
	case 6: // Custom for driving a vehicle!
		{
			if( axis == YAW )
			{
				// This code only wants to affect YAW axis (the left and right axis), which 
				// is used for turning in the car. We fall-through and use a linear curve on 
				// the PITCH axis, which is the vehicle's throttle. REALLY, these are the 'forward'
				// and 'side' axes, but we don't have constants for those, so we re-use the same
				// axis convention as the look stick. (sjb)
				float sign = 1;

				if( x  < 0.0 )
					sign = -1;

				x = fabs(x);

				if( x <= joy_vehicle_turn_lowend.GetFloat() )
					x = RemapVal( x, 0.0f, joy_vehicle_turn_lowend.GetFloat(), 0.0f, joy_vehicle_turn_lowmap.GetFloat() );
				else
					x = RemapVal( x, joy_vehicle_turn_lowend.GetFloat(), 1.0f, joy_vehicle_turn_lowmap.GetFloat(), 1.0f );

				return x * sensitivity * sign;
			}
			//else
			//	fall through and just return x*sensitivity below (as if using default curve)
		}
	}

	// linear
	return x*sensitivity;
}
示例#30
0
void score_setup()
{
	int i,u;
    //weight_time_setup();
	if(load_model) {
		fpV=fopen(fnameV,"rb");
		fpU=fopen(fnameU,"rb");
		if(fpV || fpU) {
			lg("Loading %s and %s\n",fnameV,fnameU);
			if(!fpV || !fpU)
				error("Cant open both files");
		}
	}

    int day0[NMOVIES];
    ZERO(day0);
    // It is OK to look on all data for day0 because it is always known
    for(i=0;i<NENTRIES;i++) {
        int m=userent[i]&USER_MOVIEMASK;
        int day=userent[i]>>(USER_LMOVIEMASK+3);
        if(!day0[m] || day0[m]>day) day0[m]=day;
    }
    DEVuHat = (float *) malloc(NENTRIES*sizeof(float));
    sdbU    = (float *) malloc(NENTRIES*sizeof(float));
    sdsU    = (float *) malloc(((unsigned int)NENTRIES)*((unsigned int)NFEATURES)*sizeof(float));
	memset(DEVuHat,0,NENTRIES*sizeof(float));
	memset(sdbU,0,NENTRIES*sizeof(float));
	memset(sdsU,0,((unsigned int)NENTRIES)*((unsigned int)NFEATURES)*sizeof(float));
	ZERO(sdbin);

	int tcount[100000];
	ZERO(tcount);
	ZERO(avgdate);
	ZERO(avgdevu);
	ZERO(ucnt);
	int j;
    for(u=0;u<NUSERS;u++) {
        int base=useridx[u][0];
        int d012=UNALL(u);
        int d0=UNTRAIN(u);
        // compute explanatory variable
        for(j=0;j<d012;j++) {
            int m=userent[base+j]&USER_MOVIEMASK;
            int day=userent[base+j]>>(USER_LMOVIEMASK+3);
			if ( day < minday ) 
				minday = day;
			if ( day > maxday ) 
				maxday = day;
            //usertime[j]=DTIME(day-day0[m]);
			if ( day < 0 )
				;//toosmall++;
			else if ( day < 100000-1 )
			    tcount[day]++;
			else 
				;//toobig++;
			ucnt[u]++;
			avgdate[u] += day;
        }
    }
	printf("minday: %d, maxday: %d\n", minday, maxday);
	fflush(stdout);
    for(u=0;u<NUSERS;u++) {
        // 1) Find the average date of rating for every customer. In this step I include the probe dates also in the calculation of the average.
		avgdate[u] /= ucnt[u];
	    //printf("U: %d, avgdate: %f, ucnt: %d\n", u, avgdate[u], ucnt[u]);
		//fflush(stdout);
	}
    for(u=0;u<NUSERS;u++) {
        int base=useridx[u][0];
        int d012=UNALL(u);
        int d0=UNTRAIN(u);
        int j;
        for(j=0;j<d012;j++) {
            int m=userent[base+j]&USER_MOVIEMASK;
            int day=userent[base+j]>>(USER_LMOVIEMASK+3);
  			//2) For every rating [i] in the data set (including probe) I calculate DEVu[i]:
      		//   DEVu[i] = sign(t[i] - t_mean_for_customer) * powf(abs(t[i] - t_mean_for_customer), 0.4);
			double DEVu = sign(day - avgdate[u]) * powf(abs(day - avgdate[u]), 0.4);
			avgdevu[u] += DEVu;
	        //printf("U: %d, M: %d, day: %d, uavg: %f, DEVu: %f\n", u, m, day, avgdate[u], DEVu);
		    //fflush(stdout);

        }
    }
    for(u=0;u<NUSERS;u++) {
        //3) Find the average DEVu[i] for every customer. His/hers probe DEVu[i] values are also included.
		avgdevu[u] /= ucnt[u];
	    //printf("U: %d, avgdevu: %f, avgdate: %f, ucnt: %d\n", u, avgdevu[u], avgdate[u], ucnt[u]);
		//fflush(stdout);
	}
	ZERO(maxDEVuHat);
    for(u=0;u<NUSERS;u++) {
        int base=useridx[u][0];
        int d012=UNALL(u);
        int d0=UNTRAIN(u);
        int j;
        for(j=0;j<d012;j++) {
            int m=userent[base+j]&USER_MOVIEMASK;
            int day=userent[base+j]>>(USER_LMOVIEMASK+3);

  			//  2) For every rating [i] in the data set (including probe) I calculate DEVu[i]:
      		//     DEVu[i] = sign(t[i] - t_mean_for_customer) * powf(abs(t[i] - t_mean_for_customer), 0.4);
			double DEVu = sign(day - avgdate[u]) * powf(abs(day - avgdate[u]), 0.4);

            //  4) Subtract every customer's average DEVu_avg value from every time deviation:
            //     DEVu_hat[i] = DEVu[i] - DEVu_avg_for_customer;
            double DEVuHat = DEVu - avgdevu[u];

	        //printf("U: %d, M: %d, ndevu: %f, day: %d, uavg: %f, DEVu: %f\n", u, m, DEVuHat, day, avgdate[u], DEVu);
		    //fflush(stdout);

	    	// Get the max absolute value of a user's devu_hat values...maxDevu_hat...
			double tDEVu = fabs(DEVuHat);
			if ( tDEVu > maxDEVuHat[u] )
				maxDEVuHat[u] = tDEVu;
        }
    }
	
	// Compute and store DEVuHats and create single day bin numbering per user
	int daysBinValue[maxday+1];
    for(u=0;u<NUSERS;u++) {
        int base=useridx[u][0];
        int d012=UNALL(u);
        int d0=UNTRAIN(u);
        int j;
		ZERO(daysBinValue);
		int dcount=0;
        for(j=0;j<d012;j++) {
            int m=userent[base+j]&USER_MOVIEMASK;
            int day=userent[base+j]>>(USER_LMOVIEMASK+3);

            DEVuHat[base+j] = devuHat(day,u);

			if ( daysBinValue[day] == 0 ) {
				sdbin[base+j] = base+j;
			    daysBinValue[day] = base+j;
				if ( daysBinValue[day] > NENTRIES ) {
					printf("Days bin v: %d\n", daysBinValue[day]);
					fflush(stdout);
				}
				dcount++;
			} else {
				if ( daysBinValue[day] > NENTRIES ) {
					printf("Days bin v: %d\n", daysBinValue[day]);
					fflush(stdout);
				}
				sdbin[base+j] = daysBinValue[day];
			}
        }
    }

	//for (i=minday; i < maxday; i++ ) {
	    //printf("day: %d, count: %d\n", i, tcount[i]);
		//fflush(stdout);
	//}

}