void convertQuadsToTriangles( IndicesPtrType indices, unsigned int elementCount , const VertexAttributeSetSharedPtr & vasSP, std::vector<unsigned int> & newIndices , unsigned int pri = ~0 ) { // for each quad-face create two triangles Buffer::ConstIterator<Vec3f>::Type vertices = vasSP->getVertices(); newIndices.reserve( 6 * ( elementCount / 4 ) ); // might reserve more than needed, due to pri for ( unsigned int i=3 ; i<elementCount ; i+=4 ) { if ( indices[i-3] == pri ) { i -= 3; } else if ( indices[i-2] == pri ) { i -= 2; } else if ( indices[i-1] == pri ) { i -= 1; } else if ( indices[i] != pri ) { // determine the shorter diagonal if ( lengthSquared( vertices[indices[i-1]] - vertices[indices[i-3]] ) < lengthSquared( vertices[indices[i-0]] - vertices[indices[i-2]] ) ) { // cut diagonal 0-2 => 0,1,2 & 2,3,0 newIndices.push_back( indices[i-3] ); newIndices.push_back( indices[i-2] ); newIndices.push_back( indices[i-1] ); newIndices.push_back( indices[i-1] ); newIndices.push_back( indices[i-0] ); newIndices.push_back( indices[i-3] ); } else { // cut diagonal 1-3 => 1,2,3 & 3,0,1 newIndices.push_back( indices[i-2] ); newIndices.push_back( indices[i-1] ); newIndices.push_back( indices[i-0] ); newIndices.push_back( indices[i-0] ); newIndices.push_back( indices[i-3] ); newIndices.push_back( indices[i-2] ); } } } }
/***** Division algebra structure *********************************************/ Quaternion<T>& invert() { auto lensq = lengthSquared(); if(lensq != 0) { (*this).conjugate() /= lensq; } return *this; }
Quaternion<T>& normalize() { auto lensq = lengthSquared(); if(lensq != 0) { *this /= std::sqrt(lensq); } return *this; }
inline Vector4<T> normalize(const Vector4<T>& v) { #ifdef VORB_MATH_FAST return v * vmath::fastInverseSqrt(lengthSquared(v)); #else return v / vmath::length(v); #endif }
void MapView::getTilesInView() { if (MapSource.id == None) return; QRectF viewRect = mapToScene(0,0,width(),height()).boundingRect(); QList<QPoint> XYTileList = getXYTileInRange(currentZoom, getLongFromMercatorX(viewRect.x()+viewRect.width()), getLongFromMercatorX(viewRect.x()), getLatFromMercatorY(viewRect.y()), getLatFromMercatorY(viewRect.y()+viewRect.height()) ); QPoint p1 = XYTileList.first(); QPoint p2 = XYTileList.last(); QPointF center = QPointF( (p2.x()+p1.x()) / 2. , (p1.y()+p2.y()) / 2. ); //sorts list so that points closest to center are loaded first QMap<qreal, QPoint> map; for(int i=0;i<XYTileList.size();++i) map.insertMulti(lengthSquared((XYTileList.at(i))-center),XYTileList.at(i)); XYTileList = map.values(); QPoint p; while(XYTileList.size()>0) { if (currentRequests.count()<requestLimit) p = XYTileList.takeFirst(); else p = XYTileList.takeLast(); if (!tilePlaced(p,currentZoom)) getTile(p.x(),p.y(),currentZoom); } qDebug("Number of items in scene: "+QString::number(scene()->items().count())); }
float4 Random::getFloat4(float maxRadius) { float4 result; do { result = getFloat4(-float4::ONE, float4::ONE); } while (lengthSquared(result) >= 1.0f); return result * maxRadius; }
const Vec2f Mover::attract( const Mover& m, const float g ) const { auto force = location - m.getLocation(); auto distance = force.lengthSquared(); distance = ( distance < 25.0f ) ? 25.0f : ( ( distance > 625.0f ) ? 625.0 : distance ); force.normalize(); force *= g * mass * m.getMass() / ( distance ); return force; }
// General invert void Quaternion::invert () { // q * conj(q) = |q|^2 // ==> q * conj(q) / |q|^2 = 1 // ==> inv(q) = conj(q) / |q|^2 float invLengthSq = 1 / lengthSquared (); w *= +invLengthSq; x *= -invLengthSq; y *= -invLengthSq; z *= -invLengthSq; }
Quaternion Quaternion::inverse() const { float lenSquared = lengthSquared(); if(lenSquared > EPSILON) { float invLenSquared = 1.0f / lenSquared; Quaternion conj = conjugated(); return conj * invLenSquared; } else return IDENTITY; }
void Quat::invert() { conj(); Real l = lengthSquared(); if (l < (Real) 1E-4) return; Real inv = (Real) 1.0 / l; x *= inv; y *= inv; z *= inv; w *= inv; }
void addSample(nv::Color32 o, nv::Color32 c) { nv::Vector3 vo = nv::Vector3(o.r, o.g, o.b); nv::Vector3 vc = nv::Vector3(c.r, c.g, c.b); // Unpack and normalize. vo = nv::normalize(2.0f * (vo / 255.0f) - 1.0f); vc = nv::normalize(2.0f * (vc / 255.0f) - 1.0f); ade += acosf(nv::clamp(dot(vo, vc), -1.0f, 1.0f)); mse += lengthSquared((vo - vc) * (255 / 2.0f)); samples++; }
void PCM::propagateCavityGradients(const ScalarField& A_shape, ScalarField& A_nCavity, ScalarFieldTilde& A_rhoExplicitTilde, bool electricOnly) const { if(fsp.pcmVariant == PCM_SGA13) { //Propagate gradient w.r.t expanded cavities to nCavity: ((PCM*)this)->A_nc = 0; const ScalarField* A_shapeEx[2] = { &A_shape, &Acavity_shapeVdw }; for(int i=0; i<2; i++) { //First compute derivative w.r.t expanded electron density: ScalarField A_nCavityEx; ShapeFunction::propagateGradient(nCavityEx[i], *(A_shapeEx[i]), A_nCavityEx, fsp.nc, fsp.sigma); ((PCM*)this)->A_nc += (-1./fsp.nc) * integral(A_nCavityEx*nCavityEx[i]); //then propagate to original electron density: ScalarField nCavityExUnused; //unused return value below ShapeFunction::expandDensity(wExpand[i], Rex[i], nCavity, nCavityExUnused, &A_nCavityEx, &A_nCavity); } } else if(fsp.pcmVariant == PCM_CANDLE) { ScalarField A_nCavityEx; ScalarFieldTilde A_phiExt; double A_pCavity=0.; ShapeFunction::propagateGradient(nCavityEx[0], coulomb(Sf[0]*rhoExplicitTilde), I(wExpand[0]*J(A_shape)) + Acavity_shapeVdw, A_nCavityEx, A_phiExt, A_pCavity, fsp.nc, fsp.sigma, fsp.pCavity); A_nCavity += fsp.Ztot * I(Sf[0] * J(A_nCavityEx)); if(!electricOnly) A_rhoExplicitTilde += coulomb(Sf[0]*A_phiExt); ((PCM*)this)->A_nc = (-1./fsp.nc) * integral(A_nCavityEx*nCavityEx[0]); ((PCM*)this)->A_eta_wDiel = integral(A_shape * I(wExpand[1]*J(shapeVdw))); ((PCM*)this)->A_pCavity = A_pCavity; } else if(isPCM_SCCS(fsp.pcmVariant)) { //Electrostatic and volumetric combinations via shape: ShapeFunctionSCCS::propagateGradient(nCavity, A_shape - fsp.cavityPressure, A_nCavity, fsp.rhoMin, fsp.rhoMax, epsBulk); //Add surface contributions: ScalarField shapePlus, shapeMinus; ShapeFunctionSCCS::compute(nCavity+(0.5*fsp.rhoDelta), shapePlus, fsp.rhoMin, fsp.rhoMax, epsBulk); ShapeFunctionSCCS::compute(nCavity-(0.5*fsp.rhoDelta), shapeMinus, fsp.rhoMin, fsp.rhoMax, epsBulk); VectorField Dn = gradient(nCavity); ScalarField DnLength = sqrt(lengthSquared(Dn)); ScalarField A_shapeMinus = (fsp.cavityTension/fsp.rhoDelta) * DnLength; ScalarField A_DnLength = (fsp.cavityTension/fsp.rhoDelta) * (shapeMinus - shapePlus); A_nCavity -= divergence(Dn * (inv(DnLength) * A_DnLength)); ShapeFunctionSCCS::propagateGradient(nCavity+(0.5*fsp.rhoDelta), -A_shapeMinus, A_nCavity, fsp.rhoMin, fsp.rhoMax, epsBulk); ShapeFunctionSCCS::propagateGradient(nCavity-(0.5*fsp.rhoDelta), A_shapeMinus, A_nCavity, fsp.rhoMin, fsp.rhoMax, epsBulk); } else //All gradients are w.r.t the same shape function - propagate them to nCavity (which is defined as a density product for SaLSA) { ShapeFunction::propagateGradient(nCavity, A_shape + Acavity_shape, A_nCavity, fsp.nc, fsp.sigma); ((PCM*)this)->A_nc = (-1./fsp.nc) * integral(A_nCavity*nCavity); } }
void Physics3DTestDemo::onTouchesMoved(const std::vector<Touch*>& touches, cocos2d::Event *event) { if (touches.size() && _camera) { auto touch = touches[0]; auto delta = touch->getDelta(); _angle -= CC_DEGREES_TO_RADIANS(delta.x); _camera->setPosition3D(Vec3(100.0f * sinf(_angle), 50.0f, 100.0f * cosf(_angle))); _camera->lookAt(Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 1.0f, 0.0f)); if (delta.lengthSquared() > 16) { _needShootBox = false; } } }
TintersectionResult Tsphere::getIntersect(const Tray &ray) { auto v = ray.origin () - this->center (); auto a0 = v.lengthSquared () - this->m_sqrRadius; auto DdotV = Tvector::dotProduct (ray.direction (),v); if (DdotV <= 0) { auto discr = DdotV * DdotV - a0; if (discr >= 0) { TintersectionResult result; result.setGeometry (this); result.setDistance (-DdotV - sqrt(discr)); result.setPos (ray.getPoint(result.distance ())); auto normal = result.pos () - this->center (); normal.normalize (); result.setNormal (normal); return result; } } return TintersectionResult::getNotHit (); }
int mandelbrot(double x, double y) { transform(&x, &y); point p; setPoint(&p, x,y); int counter = 0; double result = 0; while(counter < 255) { square(&p); p.x += x; p.y += y; result = lengthSquared(&p); if(result >= 4.0) { return 0; } else { counter++; } } return 1; }
inline T length (const Vector<T, Size>& a) { return ::sqrt(lengthSquared(a)); }
// Physics thread that controls the motion of all the spheres. void physicsThread(int threadNum) { int localFrame = 0; // Define the normals for each of the walls. static const Vector3 bottom(0, 1, 0); static const Vector3 left(1, 0, 0); static const Vector3 right(-1, 0, 0); static const Vector3 front(0, 0, -1); static const Vector3 back(0, 0, 1); // Initialize the starting values for the wall and sphere, spring and damping values. float wallSpringConst = UPPER_WALL_SPRING_CONST; float sphereSpringConst = UPPER_SPHERE_SPRING_CONST; float wallDampFactor = UPPER_WALL_DAMP_FACTOR; float sphereDampFactor = UPPER_SPHERE_DAMP_FACTOR; // The physics thread itself deals with reseting its frame counter. // It will do this once a second. float secondCheck = 0.0f; #if _USE_MT // If the physics function is being called as a thread, then we don't want it // to finish after one pass. int threadRunning = 0; while(programRunning) { // If the simulation needs to be paused but the thread is running, // stop. if(pauseSimulation && threadRunning) { threadRunning = 0; threadStopped(); } // If the simulation needs to be running but the thread is stopped, // start. else if(!pauseSimulation && !threadRunning) { threadRunning = 1; threadStarted(); } // If the thread isn't running at this time we can't go any further and // we'll just wait and check if the thread has started up next time the // thread is executing. if(!threadRunning) { boost::this_thread::yield(); continue; } #endif localFrame++; LARGE_INTEGER time; QueryPerformanceCounter(&time); // Get the time since this thread last executed and convert into // seconds (from milliseconds). float dt = (float)(((double)time.QuadPart - (double)updateTimes[threadNum].QuadPart) / freq); dt *= 0.001; // Adjust the spring and dampening values based on dt. // This helps when going to lower frame rates and the overlap between // the walls and spheres when using high frame rate values will cause // the spheres to gain energy. wallSpringConst = WALL_SPRING_GRAD * dt + WALL_SPRING_CONST; sphereSpringConst = SPHERE_SPRING_GRAD * dt + SPHERE_SPRING_CONST; wallDampFactor = WALL_DAMP_GRAD * dt + WALL_DAMP_CONST; sphereDampFactor = SPHERE_DAMP_GRAD * dt + SPHERE_DAMP_CONST; // As the gradients for the spring and dampening factors are negative, // we want to clamp the lower bounds of the values. Otherwise at low // framerates the values will be negative. if (wallSpringConst < LOWER_WALL_SPRING_CONST) wallSpringConst = LOWER_WALL_SPRING_CONST; if (sphereSpringConst < LOWER_SPHERE_SPRING_CONST) sphereSpringConst = LOWER_SPHERE_SPRING_CONST; if (wallDampFactor < LOWER_WALL_DAMP_FACTOR) wallDampFactor = LOWER_WALL_DAMP_FACTOR; if (sphereDampFactor < LOWER_SPHERE_DAMP_FACTOR) sphereDampFactor = LOWER_SPHERE_DAMP_FACTOR; // If this is the 1st thread, then we will deal with the user controlled // sphere here. int startSphere = threadNum; if(threadNum == 0) { // Skip calcuating the user sphere like a typical sphere. startSphere += numPhysicsThreads; // As the user controlled sphere only has a position and velocity // that is either zero or constant, we can easily calculate its new // position. if(numSpheres > 0) { spherePositions[0] += sphereData[0].m_velocity * dt; } } for(int i = startSphere; i < numSpheres; i += numPhysicsThreads) { // Calculate the radius of the sphere based on array index. float radius = (float)((i % 3) + 1) * 0.5f; float roomSize = ROOM_SIZE - radius; Vector3 forces(0); Vector3 &spherePosition = spherePositions[i]; SphereData &sphere = sphereData[i]; // Calculate the interim velocity. Vector3 halfVelo = sphere.m_velocity + (0.5f * sphere.m_acc * dt); spherePosition += halfVelo * dt; Vector3 tempVelocity = sphere.m_velocity + (sphere.m_acc * dt); float overlap; // As the % operator is fairly slow we can take advantage here // that we always know what the next value in the array is going // to be and manually determine the mod. int indexCounter = 0; for(int j = 0; j < numSpheres; j++) { // And since we don't want the actual mod value but mod + 1 // we don't worry about resetting to 0. indexCounter++; if(indexCounter > 3) indexCounter = 1; // We don't want a sphere to check if it's collided with itself. if(i == j) continue; SphereData &otherSphere = sphereData[j]; Vector3 toCentre = spherePosition - spherePositions[j]; // An unfortunately slow way of checking if the radius of the // other sphere should be the other spheres actual radius or // the user controlled spheres radius. float otherRadius; if(j == 0) { otherRadius = userSphereSize; } else { otherRadius = (float)(indexCounter) * 0.5f; } float combinedRadius = radius + otherRadius; float lengthSqrd = lengthSquared(toCentre); float combinedRadiusSqrd = combinedRadius * combinedRadius; // A check to see if the spheres have overlapped at all. float overlapSqrd = lengthSqrd - combinedRadiusSqrd; if(overlapSqrd < 0) { #if _SSE overlap = sqrt(lengthSqrd) - combinedRadius; // We want to let the vector normalize itself in SSE // because we can take advantage of the rsqrt instruction // which will be quicker than loading in a float value // and multiplying by the reciprocal. Vector3 tangent = normalize(toCentre); #else // Here we can take advantage that we've already calculated // the actual length value so that we have the overlap and // can use that value again to normalize the tangent. float len = sqrt(lengthSqrd); overlap = len - combinedRadius; Vector3 tangent = toCentre / len; #endif calcForce(forces, sphereSpringConst, sphereDampFactor, overlap, tangent, tempVelocity); } } // Calculate the overlap with the walls using the normal of the wall // and the walls distance from the origin. Should work best for SSE // as it should not require any checking of individual elements of // the vector. overlap = dot3(spherePosition, bottom) + roomSize; if(overlap < 0) { calcForce(forces, wallSpringConst, wallDampFactor, overlap, bottom, tempVelocity); } overlap = dot3(spherePosition, left) + roomSize; if(overlap < 0) { calcForce(forces, wallSpringConst, wallDampFactor, overlap, left, tempVelocity); } overlap = dot3(spherePosition, right) + roomSize; if(overlap < 0) { calcForce(forces, wallSpringConst, wallDampFactor, overlap, right, tempVelocity); } overlap = dot3(spherePosition, front) + roomSize; if(overlap < 0) { calcForce(forces, wallSpringConst, wallDampFactor, overlap, front, tempVelocity); } overlap = dot3(spherePosition, back) + roomSize; if(overlap < 0) { calcForce(forces, wallSpringConst, wallDampFactor, overlap, back, tempVelocity); } // Apply the accumulated forces to the acceleration. sphere.m_acc = forces / (radius * 2.0f); sphere.m_acc += GRAVITY; // Calculate the final velocity value from the interim velocity // and final acceleration. sphere.m_velocity = halfVelo + (0.5f * sphere.m_acc * dt); } // Determin if we need to reset out physics frame counter. secondCheck += dt; if(secondCheck > 1.0f) { physicsFrames[threadNum] = 1; secondCheck -= 1.0f; } else { physicsFrames[threadNum]++; } updateTimes[threadNum] = time; // If we're running the physics function as a thread function then we // need to keep it running, so this is the end of the while(programRunning) loop. #if _USE_MT } #endif }
float length(const vec4 &V) { return sqrtf(lengthSquared(V)); }
GLfloat Vector3::length(void) const { return sqrt(lengthSquared()); }
T length() const { return sqrt(lengthSquared()); }
float length(const Vec4& v) { return sqrt(lengthSquared(v)); }
Tout length() const { return static_cast<Tout>(std::sqrt(lengthSquared())); }
Real Quat::length() { return ::Xk::Math::sqrt(lengthSquared()); }
bool Quat::isNormalised(Real epsilon_tolerance) { return ::Xk::Math::nearEqual( lengthSquared(), (Real) 1, epsilon_tolerance); }
ScalarFieldArray tauWeizsacker(const Everything& e) { ScalarFieldArray tauW(e.eVars.n.size()); for(size_t j=0; j<e.eVars.n.size(); j++) tauW[j] = (1./8.)*lengthSquared(gradient(e.eVars.n[j]))*pow(e.eVars.n[j], -1); return tauW; }
double myVector3d::length() { return sqrt(lengthSquared()); }
float Quaternion::length () const { // q * conj(q) = w^2 + x^2 + y^2 + z^2 = |q|^2 return (sqrt (lengthSquared ())); }
double Vector3d::length() const { return sqrt(lengthSquared()); }
float FloatPoint::length() const { return sqrtf(lengthSquared()); }
/*! \brief Returns length of a given vector If comparing the length of two vectors it is mroe efficient to use the squared lengths \see lengthSquared */ static inline float length(const sf::Vector2f& source) { return std::sqrt(lengthSquared(source)); }