Пример #1
0
Vector<double> Vector<T>::reduce(double factor) const {
    Vector<double> vec(dimension());
    std::transform(this->begin(), this->end(), vec.begin(),
                   [&factor](const T &v) { return v / factor; });
    return vec;
}
Пример #2
0
Vector3D Vector3D::operator*(double val) const
{
    Vector3D vec(*this);
    vec *= val;
    return vec;
}
Пример #3
0
float pointdistance(coordinate c1,coordinate c2) {
	coordinate vec(c2.x-c1.x,c2.y-c1.y,c2.z-c1.z);
	return (vec.x*vec.x+vec.y*vec.y+vec.z*vec.z);
}
void LLWLParamManager::propagateParameters(void)
{
	LL_RECORD_BLOCK_TIME(FTM_UPDATE_WLPARAM);
	
	LLVector4 sunDir;
	LLVector4 moonDir;

	// set the sun direction from SunAngle and EastAngle
	F32 sinTheta = sin(mCurParams.getEastAngle());
	F32 cosTheta = cos(mCurParams.getEastAngle());

	F32 sinPhi = sin(mCurParams.getSunAngle());
	F32 cosPhi = cos(mCurParams.getSunAngle());

	sunDir.mV[0] = -sinTheta * cosPhi;
	sunDir.mV[1] = sinPhi;
	sunDir.mV[2] = cosTheta * cosPhi;
	sunDir.mV[3] = 0;

	moonDir = -sunDir;

	// is the normal from the sun or the moon
	if(sunDir.mV[1] >= 0)
	{
		mLightDir = sunDir;
	}
	else if(sunDir.mV[1] < 0 && sunDir.mV[1] > LLSky::NIGHTTIME_ELEVATION_COS)
	{
		// clamp v1 to 0 so sun never points up and causes weirdness on some machines
		LLVector3 vec(sunDir.mV[0], sunDir.mV[1], sunDir.mV[2]);
		vec.mV[1] = 0;
		vec.normVec();
		mLightDir = LLVector4(vec, 0.f);
	}
	else
	{
		mLightDir = moonDir;
	}

	// calculate the clamp lightnorm for sky (to prevent ugly banding in sky
	// when haze goes below the horizon
	mClampedLightDir = sunDir;

	if (mClampedLightDir.mV[1] < -0.1f)
	{
		mClampedLightDir.mV[1] = -0.1f;
	}

	mCurParams.set("lightnorm", mLightDir);

	// bind the variables for all shaders only if we're using WindLight
	LLViewerShaderMgr::shader_iter shaders_iter, end_shaders;
	end_shaders = LLViewerShaderMgr::instance()->endShaders();
	for(shaders_iter = LLViewerShaderMgr::instance()->beginShaders(); shaders_iter != end_shaders; ++shaders_iter) 
	{
		if (shaders_iter->mProgramObject != 0
			&& (gPipeline.canUseWindLightShaders()
				|| shaders_iter->mShaderGroup == LLGLSLShader::SG_WATER))
		{
			shaders_iter->mUniformsDirty = TRUE;
		}
	}

	// get the cfr version of the sun's direction
	LLVector3 cfrSunDir(sunDir.mV[2], sunDir.mV[0], sunDir.mV[1]);

	// set direction and don't allow overriding
	gSky.setSunDirection(cfrSunDir, LLVector3(0,0,0));
	gSky.setOverrideSun(TRUE);
}
Пример #5
0
// <int Order_s, int Order_p, int Order_t>
void Convection ::initLinearOperator2( sparse_matrix_ptrtype& L )
{
    boost::timer ti;
    LOG(INFO) << "[initLinearOperator2] start\n";

    mesh_ptrtype mesh = Xh->mesh();
    element_type U( Xh, "u" );
    element_type Un( Xh, "un" );
    element_type V( Xh, "v" );
    element_0_type u = U. element<0>(); // fonction vitesse
    element_0_type un = Un. element<0>(); // fonction vitesse
    element_0_type v = V. element<0>(); // fonction test vitesse
    element_1_type p = U. element<1>(); // fonction pression
    element_1_type pn = Un. element<1>(); // fonction pression
    element_1_type q = V. element<1>(); // fonction test pression
    element_2_type t = U. element<2>(); // fonction temperature
    element_2_type tn = Un. element<2>(); // fonction temperature
    element_2_type s = V. element<2>(); // fonction test temperature
#if defined( FEELPP_USE_LM )
    element_3_type xi = U. element<3>(); // fonction multipliers
    element_3_type eta = V. element<3>(); // fonction test multipliers
#endif

    double gr= M_current_Grashofs;
    double sqgr( 1/math::sqrt( gr ) );
    double pr = M_current_Prandtl;
    double sqgrpr( 1/( pr*math::sqrt( gr ) ) );
    double gamma( this->vm()["penalbc"]. as<double>() );

    double k=this->vm()["k"]. as<double>();
    double nu=this->vm()["nu"]. as<double>();
    double rho=this->vm()["rho"]. as<double>();
    //double dt=this->vm()["dt"]. as<double>();
    int adim=this->vm()["adim"]. as<int>();
    int weakdir=this->vm()["weakdir"]. as<int>();
    //choix de la valeur des paramètres dimensionnés ou adimensionnés
    double a=0.0,b=0.0,c=0.0;
    double pC=1;

    if ( adim == 0 ) pC = this->vm()["pC"]. as<double>();

    if ( adim==1 )
    {
        a=1;
        b=sqgr;
        c=sqgrpr;
    }

    else
    {
        a=rho;
        b=nu;
        c=k;
    }

    double expansion = 1;

    if ( adim == 0 ) expansion=3.7e-3;

    auto bf = form2( _test=Xh, _trial=Xh, _matrix=L );
    // Temperature
#if CONVECTION_DIM==2
    // buyoancy forces c(theta,v)
    bf +=integrate( _range=elements( mesh ),
                    _expr=-expansion*idt( t )*( trans( vec( constant( 0. ),constant( 1.0 ) ) )*id( v ) ) );
#else
    bf +=integrate( _range=elements( mesh ),
                    _expr=-expansion*idt( t )*( trans( vec( cst(0.), constant( 0. ),constant( 1.0 ) ) )*id( v ) ) );
#endif

    LOG(INFO) << "[initLinearOperator] temperature Force terms done\n";
    // heat conduction/diffusion: e(beta1,theta,chi)+f(theta,chi)
    bf  += integrate( _range=elements( mesh ),
                      _expr=cst( c )*gradt( t )*trans( grad( s ) ) );
    LOG(INFO) << "[initLinearOperator] Temperature Diffusion terms done\n";

    if ( weakdir == 1 )
    {
        // weak Dirichlet on temperature (T=0|left wall)
        bf  += integrate ( markedfaces( mesh, "Tfixed"  ),
                           - gradt( t )*N()*id( s )*cst_ref( sqgrpr ) );
        bf  += integrate ( markedfaces( mesh, "Tfixed"  ),
                           - grad( s )*N()*idt( t )*cst_ref( sqgrpr ) );
        bf  += integrate ( markedfaces( mesh, "Tfixed"  ),
                           gamma*idt( t )*id( s )/hFace() );
    }

    LOG(INFO) << "[initLinearOperator2] done in " << ti.elapsed() << "s\n";
}
Пример #6
0
vec add(vec a, vec b)
{
    return vec(a.x + b.x, a.y + b.y);
}
Пример #7
0
 virtual Vector normal(Point) const {
     return vec(vertices[1] - vertices[0], vertices[2] - vertices[0]).normalized();
 }
Пример #8
0
std::ostream& operator<<(std::ostream& os, const Eigen::VectorXd &vec)
{
  os << "[";
  for (int dim = 0; dim < vec.rows(); ++dim)
  {
    os << std::setiosflags(std::ios::left) << std::setw(12) << std::setprecision(5) << vec(dim);
  }
  os << "]\n";

  return os;
}
Пример #9
0
void LoadMesh(const String& inputFileName, bool generateTangents, bool splitSubMeshes, bool exportMorphs)
{
    File meshFileSource(context_);
    meshFileSource.Open(inputFileName);
    if (!meshFile_->Load(meshFileSource))
        ErrorExit("Could not load input file " + inputFileName);
    
    XMLElement root = meshFile_->GetRoot("mesh");
    XMLElement subMeshes = root.GetChild("submeshes");
    XMLElement skeletonLink = root.GetChild("skeletonlink");
    if (root.IsNull())
        ErrorExit("Could not load input file " + inputFileName);
    
    String skeletonName = skeletonLink.GetAttribute("name");
    if (!skeletonName.Empty())
        LoadSkeleton(GetPath(inputFileName) + GetFileName(skeletonName) + ".skeleton.xml");
    
    // Check whether there's benefit of avoiding 32bit indices by splitting each submesh into own buffer
    XMLElement subMesh = subMeshes.GetChild("submesh");
    unsigned totalVertices = 0;
    unsigned maxSubMeshVertices = 0;
    while (subMesh)
    {
        materialNames_.Push(subMesh.GetAttribute("material"));
        XMLElement geometry = subMesh.GetChild("geometry");
        if (geometry)
        {
            unsigned vertices = geometry.GetInt("vertexcount");
            totalVertices += vertices;
            if (maxSubMeshVertices < vertices)
                maxSubMeshVertices = vertices;
        }
        ++numSubMeshes_;
        
        subMesh = subMesh.GetNext("submesh");
    }
    
    XMLElement sharedGeometry = root.GetChild("sharedgeometry");
    if (sharedGeometry)
    {
        unsigned vertices = sharedGeometry.GetInt("vertexcount");
        totalVertices += vertices;
        if (maxSubMeshVertices < vertices)
            maxSubMeshVertices = vertices;
    }
    
    if (!sharedGeometry && (splitSubMeshes || (totalVertices > 65535 && maxSubMeshVertices <= 65535)))
    {
        useOneBuffer_ = false;
        vertexBuffers_.Resize(numSubMeshes_);
        indexBuffers_.Resize(numSubMeshes_);
    }
    else
    {
        vertexBuffers_.Resize(1);
        indexBuffers_.Resize(1);
    }
    
    subMesh = subMeshes.GetChild("submesh");
    unsigned indexStart = 0;
    unsigned vertexStart = 0;
    unsigned subMeshIndex = 0;
    
    PODVector<unsigned> vertexStarts;
    vertexStarts.Resize(numSubMeshes_);
    
    while (subMesh)
    {
        XMLElement geometry = subMesh.GetChild("geometry");
        XMLElement faces = subMesh.GetChild("faces");
        
        // If no submesh vertexbuffer, process the shared geometry, but do it only once
        unsigned vertices = 0;
        if (!geometry)
        {
            vertexStart = 0;
            if (!subMeshIndex)
                geometry = root.GetChild("sharedgeometry");
        }
        
        if (geometry)
            vertices = geometry.GetInt("vertexcount");
        
        ModelSubGeometryLodLevel subGeometryLodLevel;
        ModelVertexBuffer* vBuf;
        ModelIndexBuffer* iBuf;
        
        if (useOneBuffer_)
        {
            vBuf = &vertexBuffers_[0];
            if (vertices)
                vBuf->vertices_.Resize(vertexStart + vertices);
            iBuf = &indexBuffers_[0];
            
            subGeometryLodLevel.vertexBuffer_ = 0;
            subGeometryLodLevel.indexBuffer_ = 0;
        }
        else
        {
            vertexStart = 0;
            indexStart = 0;
            
            vBuf = &vertexBuffers_[subMeshIndex];
            vBuf->vertices_.Resize(vertices);
            iBuf = &indexBuffers_[subMeshIndex];
            
            subGeometryLodLevel.vertexBuffer_ = subMeshIndex;
            subGeometryLodLevel.indexBuffer_ = subMeshIndex;
        }
        
        // Store the start vertex for later use
        vertexStarts[subMeshIndex] = vertexStart;
        
        // Ogre may have multiple buffers in one submesh. These will be merged into one
        XMLElement bufferDef;
        if (geometry)
            bufferDef = geometry.GetChild("vertexbuffer");
        
        while (bufferDef)
        {
            if (bufferDef.HasAttribute("positions"))
                vBuf->elementMask_ |= MASK_POSITION;
            if (bufferDef.HasAttribute("normals"))
                vBuf->elementMask_ |= MASK_NORMAL;
            if (bufferDef.HasAttribute("texture_coords"))
            {
                vBuf->elementMask_ |= MASK_TEXCOORD1;
                if (bufferDef.GetInt("texture_coords") > 1)
                    vBuf->elementMask_ |= MASK_TEXCOORD2;
            }
            
            unsigned vertexNum = vertexStart;
            if (vertices)
            {
                XMLElement vertex = bufferDef.GetChild("vertex");
                while (vertex)
                {
                    XMLElement position = vertex.GetChild("position");
                    if (position)
                    {
                        // Convert from right- to left-handed
                        float x = position.GetFloat("x");
                        float y = position.GetFloat("y");
                        float z = position.GetFloat("z");
                        Vector3 vec(x, y, -z);
                        
                        vBuf->vertices_[vertexNum].position_ = vec;
                        boundingBox_.Merge(vec);
                    }
                    XMLElement normal = vertex.GetChild("normal");
                    if (normal)
                    {
                        // Convert from right- to left-handed
                        float x = normal.GetFloat("x");
                        float y = normal.GetFloat("y");
                        float z = normal.GetFloat("z");
                        Vector3 vec(x, y, -z);
                        
                        vBuf->vertices_[vertexNum].normal_ = vec;
                    }
                    XMLElement uv = vertex.GetChild("texcoord");
                    if (uv)
                    {
                        float x = uv.GetFloat("u");
                        float y = uv.GetFloat("v");
                        Vector2 vec(x, y);
                        
                        vBuf->vertices_[vertexNum].texCoord1_ = vec;
                        
                        if (vBuf->elementMask_ & MASK_TEXCOORD2)
                        {
                            uv = uv.GetNext("texcoord");
                            if (uv)
                            {
                                float x = uv.GetFloat("u");
                                float y = uv.GetFloat("v");
                                Vector2 vec(x, y);
                                
                                vBuf->vertices_[vertexNum].texCoord2_ = vec;
                            }
                        }
                    }
                    
                    vertexNum++;
                    vertex = vertex.GetNext("vertex");
                }
            }
            
            bufferDef = bufferDef.GetNext("vertexbuffer");
        }
        
        unsigned triangles = faces.GetInt("count");
        unsigned indices = triangles * 3;
        
        XMLElement triangle = faces.GetChild("face");
        while (triangle)
        {
            unsigned v1 = triangle.GetInt("v1");
            unsigned v2 = triangle.GetInt("v2");
            unsigned v3 = triangle.GetInt("v3");
            iBuf->indices_.Push(v3 + vertexStart);
            iBuf->indices_.Push(v2 + vertexStart);
            iBuf->indices_.Push(v1 + vertexStart);
            triangle = triangle.GetNext("face");
        }
        
        subGeometryLodLevel.indexStart_ = indexStart;
        subGeometryLodLevel.indexCount_ = indices;
        if (vertexStart + vertices > 65535)
            iBuf->indexSize_ = sizeof(unsigned);
        
        XMLElement boneAssignments = subMesh.GetChild("boneassignments");
        if (bones_.Size())
        {
            if (boneAssignments)
            {
                XMLElement boneAssignment = boneAssignments.GetChild("vertexboneassignment");
                while (boneAssignment)
                {
                    unsigned vertex = boneAssignment.GetInt("vertexindex") + vertexStart;
                    unsigned bone = boneAssignment.GetInt("boneindex");
                    float weight = boneAssignment.GetFloat("weight");
                    
                    BoneWeightAssignment assign;
                    assign.boneIndex_ = bone;
                    assign.weight_ = weight;
                    // Source data might have 0 weights. Disregard these
                    if (assign.weight_ > 0.0f)
                    {
                        subGeometryLodLevel.boneWeights_[vertex].Push(assign);
                        
                        // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
                        if (assign.weight_ > 0.33f)
                        {
                            // Check distance of vertex from bone to get bone max. radius information
                            Vector3 bonePos = bones_[bone].derivedPosition_;
                            Vector3 vertexPos = vBuf->vertices_[vertex].position_;
                            float distance = (bonePos - vertexPos).Length();
                            if (distance > bones_[bone].radius_)
                            {
                                bones_[bone].collisionMask_ |= 1;
                                bones_[bone].radius_ = distance;
                            }
                            // Build the hitbox for the bone
                            bones_[bone].boundingBox_.Merge(bones_[bone].inverseWorldTransform_ * (vertexPos));
                            bones_[bone].collisionMask_ |= 2;
                        }
                    }
                    boneAssignment = boneAssignment.GetNext("vertexboneassignment");
                }
            }
            
            if ((subGeometryLodLevel.boneWeights_.Size()) && bones_.Size())
            {
                vBuf->elementMask_ |= MASK_BLENDWEIGHTS | MASK_BLENDINDICES;
                bool sorted = false;
                
                // If amount of bones is larger than supported by HW skinning, must remap per submesh
                if (bones_.Size() > MAX_SKIN_MATRICES)
                {
                    HashMap<unsigned, unsigned> usedBoneMap;
                    unsigned remapIndex = 0;
                    for (HashMap<unsigned, PODVector<BoneWeightAssignment> >::Iterator i =
                        subGeometryLodLevel.boneWeights_.Begin(); i != subGeometryLodLevel.boneWeights_.End(); ++i)
                    {
                        // Sort the bone assigns by weight
                        Sort(i->second_.Begin(), i->second_.End(), CompareWeights);
                        
                        // Use only the first 4 weights
                        for (unsigned j = 0; j < i->second_.Size() && j < 4; ++j)
                        {
                            unsigned originalIndex = i->second_[j].boneIndex_;
                            if (!usedBoneMap.Contains(originalIndex))
                            {
                                usedBoneMap[originalIndex] = remapIndex;
                                remapIndex++;
                            }
                            i->second_[j].boneIndex_ = usedBoneMap[originalIndex];
                        }
                    }
                    
                    // If still too many bones in one subgeometry, error
                    if (usedBoneMap.Size() > MAX_SKIN_MATRICES)
                        ErrorExit("Too many bones in submesh " + String(subMeshIndex + 1));
                    
                    // Write mapping of vertex buffer bone indices to original bone indices
                    subGeometryLodLevel.boneMapping_.Resize(usedBoneMap.Size());
                    for (HashMap<unsigned, unsigned>::Iterator j = usedBoneMap.Begin(); j != usedBoneMap.End(); ++j)
                        subGeometryLodLevel.boneMapping_[j->second_] = j->first_;
                    
                    sorted = true;
                }
                
                for (HashMap<unsigned, PODVector<BoneWeightAssignment> >::Iterator i = subGeometryLodLevel.boneWeights_.Begin();
                    i != subGeometryLodLevel.boneWeights_.End(); ++i)
                {
                    // Sort the bone assigns by weight, if not sorted yet in bone remapping pass
                    if (!sorted)
                        Sort(i->second_.Begin(), i->second_.End(), CompareWeights);
                    
                    float totalWeight = 0.0f;
                    float normalizationFactor = 0.0f;
                    
                    // Calculate normalization factor in case there are more than 4 blend weights, or they do not add up to 1
                    for (unsigned j = 0; j < i->second_.Size() && j < 4; ++j)
                        totalWeight += i->second_[j].weight_;
                    if (totalWeight > 0.0f)
                        normalizationFactor = 1.0f / totalWeight;
                    
                    for (unsigned j = 0; j < i->second_.Size() && j < 4; ++j)
                    {
                        vBuf->vertices_[i->first_].blendIndices_[j] = i->second_[j].boneIndex_;
                        vBuf->vertices_[i->first_].blendWeights_[j] = i->second_[j].weight_ * normalizationFactor;
                    }
                    
                    // If there are less than 4 blend weights, fill rest with zero
                    for (unsigned j = i->second_.Size(); j < 4; ++j)
                    {
                        vBuf->vertices_[i->first_].blendIndices_[j] = 0;
                        vBuf->vertices_[i->first_].blendWeights_[j] = 0.0f;
                    }
                    
                    vBuf->vertices_[i->first_].hasBlendWeights_ = true;
                }
            }
        }
        else if (boneAssignments)
            PrintLine("No skeleton loaded, skipping skinning information");
        
        // Calculate center for the subgeometry
        Vector3 center = Vector3::ZERO;
        for (unsigned i = 0; i < iBuf->indices_.Size(); i += 3)
        {
            center += vBuf->vertices_[iBuf->indices_[i]].position_;
            center += vBuf->vertices_[iBuf->indices_[i + 1]].position_;
            center += vBuf->vertices_[iBuf->indices_[i + 2]].position_;
        }
        if (iBuf->indices_.Size())
            center /= (float)iBuf->indices_.Size();
        subGeometryCenters_.Push(center);
        
        indexStart += indices;
        vertexStart += vertices;
        
        OptimizeIndices(&subGeometryLodLevel, vBuf, iBuf);
        
        PrintLine("Processed submesh " + String(subMeshIndex + 1) + ": " + String(vertices) + " vertices " + 
            String(triangles) + " triangles");
        Vector<ModelSubGeometryLodLevel> thisSubGeometry;
        thisSubGeometry.Push(subGeometryLodLevel);
        subGeometries_.Push(thisSubGeometry);
        
        subMesh = subMesh.GetNext("submesh");
        subMeshIndex++;
    }
    
    // Process LOD levels, if any
    XMLElement lods = root.GetChild("levelofdetail");
    if (lods)
    {
        try
        {
            // For now, support only generated LODs, where the vertices are the same
            XMLElement lod = lods.GetChild("lodgenerated");
            while (lod)
            {
                float distance = M_EPSILON;
                if (lod.HasAttribute("fromdepthsquared"))
                    distance = sqrtf(lod.GetFloat("fromdepthsquared"));
                if (lod.HasAttribute("value"))
                    distance = lod.GetFloat("value");
                XMLElement lodSubMesh = lod.GetChild("lodfacelist");
                while (lodSubMesh)
                {
                    unsigned subMeshIndex = lodSubMesh.GetInt("submeshindex");
                    unsigned triangles = lodSubMesh.GetInt("numfaces");
                    
                    ModelSubGeometryLodLevel newLodLevel;
                    ModelSubGeometryLodLevel& originalLodLevel = subGeometries_[subMeshIndex][0];
                    
                    // Copy all initial values
                    newLodLevel = originalLodLevel;
                    
                    ModelVertexBuffer* vBuf;
                    ModelIndexBuffer* iBuf;
                    
                    if (useOneBuffer_)
                    {
                        vBuf = &vertexBuffers_[0];
                        iBuf = &indexBuffers_[0];
                    }
                    else
                    {
                        vBuf = &vertexBuffers_[subMeshIndex];
                        iBuf = &indexBuffers_[subMeshIndex];
                    }
                    
                    unsigned indexStart = iBuf->indices_.Size();
                    unsigned indexCount = triangles * 3;
                    unsigned vertexStart = vertexStarts[subMeshIndex];
                    
                    newLodLevel.distance_ = distance;
                    newLodLevel.indexStart_ = indexStart;
                    newLodLevel.indexCount_ = indexCount;
                    
                    // Append indices to the original index buffer
                    XMLElement triangle = lodSubMesh.GetChild("face");
                    while (triangle)
                    {
                        unsigned v1 = triangle.GetInt("v1");
                        unsigned v2 = triangle.GetInt("v2");
                        unsigned v3 = triangle.GetInt("v3");
                        iBuf->indices_.Push(v3 + vertexStart);
                        iBuf->indices_.Push(v2 + vertexStart);
                        iBuf->indices_.Push(v1 + vertexStart);
                        triangle = triangle.GetNext("face");
                    }
                    
                    OptimizeIndices(&newLodLevel, vBuf, iBuf);
                    
                    subGeometries_[subMeshIndex].Push(newLodLevel);
                    PrintLine("Processed LOD level for submesh " + String(subMeshIndex + 1) + ": distance " + String(distance));
                    
                    lodSubMesh = lodSubMesh.GetNext("lodfacelist");
                }
                lod = lod.GetNext("lodgenerated");
            }
        }
        catch (...) {}
    }
    
    // Process poses/morphs
    // First find out all pose definitions
    if (exportMorphs)
    {
        try
        {
            Vector<XMLElement> poses;
            XMLElement posesRoot = root.GetChild("poses");
            if (posesRoot)
            {
                XMLElement pose = posesRoot.GetChild("pose");
                while (pose)
                {
                    poses.Push(pose);
                    pose = pose.GetNext("pose");
                }
            }
            
            // Then process animations using the poses
            XMLElement animsRoot = root.GetChild("animations");
            if (animsRoot)
            {
                XMLElement anim = animsRoot.GetChild("animation");
                while (anim)
                {
                    String name = anim.GetAttribute("name");
                    float length = anim.GetFloat("length");
                    HashSet<unsigned> usedPoses;
                    XMLElement tracks = anim.GetChild("tracks");
                    if (tracks)
                    {
                        XMLElement track = tracks.GetChild("track");
                        while (track)
                        {
                            XMLElement keyframes = track.GetChild("keyframes");
                            if (keyframes)
                            {
                                XMLElement keyframe = keyframes.GetChild("keyframe");
                                while (keyframe)
                                {
                                    float time = keyframe.GetFloat("time");
                                    XMLElement poseref = keyframe.GetChild("poseref");
                                    // Get only the end pose
                                    if (poseref && time == length)
                                        usedPoses.Insert(poseref.GetInt("poseindex"));
                                    
                                    keyframe = keyframe.GetNext("keyframe");
                                }
                            }
                            track = track.GetNext("track");
                        }
                    }
                    
                    if (usedPoses.Size())
                    {
                        ModelMorph newMorph;
                        newMorph.name_ = name;
                        
                        if (useOneBuffer_)
                            newMorph.buffers_.Resize(1);
                        else
                            newMorph.buffers_.Resize(usedPoses.Size());
                        
                        unsigned bufIndex = 0;
                        
                        for (HashSet<unsigned>::Iterator i = usedPoses.Begin(); i != usedPoses.End(); ++i)
                        {
                            XMLElement pose = poses[*i];
                            unsigned targetSubMesh = pose.GetInt("index");
                            XMLElement poseOffset = pose.GetChild("poseoffset");
                        
                            if (useOneBuffer_)
                                newMorph.buffers_[bufIndex].vertexBuffer_ = 0;
                            else
                                newMorph.buffers_[bufIndex].vertexBuffer_ = targetSubMesh;
                            
                            newMorph.buffers_[bufIndex].elementMask_ = MASK_POSITION;
                            
                            ModelVertexBuffer* vBuf = &vertexBuffers_[newMorph.buffers_[bufIndex].vertexBuffer_];
                            
                            while (poseOffset)
                            {
                                // Convert from right- to left-handed
                                unsigned vertexIndex = poseOffset.GetInt("index") + vertexStarts[targetSubMesh];
                                float x = poseOffset.GetFloat("x");
                                float y = poseOffset.GetFloat("y");
                                float z = poseOffset.GetFloat("z");
                                Vector3 vec(x, y, -z);
                                
                                if (vBuf->morphCount_ == 0)
                                {
                                    vBuf->morphStart_ = vertexIndex;
                                    vBuf->morphCount_ = 1;
                                }
                                else
                                {
                                    unsigned first = vBuf->morphStart_;
                                    unsigned last = first + vBuf->morphCount_ - 1;
                                    if (vertexIndex < first)
                                        first = vertexIndex;
                                    if (vertexIndex > last)
                                        last = vertexIndex;
                                    vBuf->morphStart_ = first;
                                    vBuf->morphCount_ = last - first + 1;
                                }
                                
                                ModelVertex newVertex;
                                newVertex.position_ = vec;
                                newMorph.buffers_[bufIndex].vertices_.Push(MakePair(vertexIndex, newVertex));
                                poseOffset = poseOffset.GetNext("poseoffset");
                            }
                            
                            if (!useOneBuffer_)
                                ++bufIndex;
                        }
                        morphs_.Push(newMorph);
                        PrintLine("Processed morph " + name + " with " + String(usedPoses.Size()) + " sub-poses");
                    }
                    
                    anim = anim.GetNext("animation");
                }
            }
        }
        catch (...) {}
    }
    
    // Check any of the buffers for vertices with missing blend weight assignments
    for (unsigned i = 0; i < vertexBuffers_.Size(); ++i)
    {
        if (vertexBuffers_[i].elementMask_ & MASK_BLENDWEIGHTS)
        {
            for (unsigned j = 0; j < vertexBuffers_[i].vertices_.Size(); ++j)
                if (!vertexBuffers_[i].vertices_[j].hasBlendWeights_)
                    ErrorExit("Found a vertex with missing skinning information");
        }
    }
    
    // Tangent generation
    if (generateTangents)
    {
        for (unsigned i = 0; i < subGeometries_.Size(); ++i)
        {
            for (unsigned j = 0; j < subGeometries_[i].Size(); ++j)
            {
                ModelVertexBuffer& vBuf = vertexBuffers_[subGeometries_[i][j].vertexBuffer_];
                ModelIndexBuffer& iBuf = indexBuffers_[subGeometries_[i][j].indexBuffer_];
                unsigned indexStart = subGeometries_[i][j].indexStart_;
                unsigned indexCount = subGeometries_[i][j].indexCount_;
                
                // If already has tangents, do not regenerate
                if (vBuf.elementMask_ & MASK_TANGENT || vBuf.vertices_.Empty() || iBuf.indices_.Empty())
                    continue;
                
                vBuf.elementMask_ |= MASK_TANGENT;
                
                if ((vBuf.elementMask_ & (MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1)) != (MASK_POSITION | MASK_NORMAL |
                    MASK_TEXCOORD1))
                    ErrorExit("To generate tangents, positions normals and texcoords are required");
                
                GenerateTangents(&vBuf.vertices_[0], sizeof(ModelVertex), &iBuf.indices_[0], sizeof(unsigned), indexStart,
                    indexCount, offsetof(ModelVertex, normal_), offsetof(ModelVertex, texCoord1_), offsetof(ModelVertex,
                    tangent_));
                
                PrintLine("Generated tangents");
            }
        }
    }
}
Пример #10
0
void mdltrans(float *x, float *y, float *z)
{
    checkmdl;
    loadingmodel->translate = vec(*x, *y, *z);
} 
Пример #11
0
void mdlextendbb(float *x, float *y, float *z)
{
    checkmdl;
    loadingmodel->bbextend = vec(*x, *y, *z);
}
Пример #12
0
void LLWLParamManager::propagateParameters(void)
{
	LLFastTimer ftm(FTM_UPDATE_WLPARAM);
	
	LLVector4 sunDir;
	LLVector4 moonDir;

	// set the sun direction from SunAngle and EastAngle
	F32 sinTheta = sin(mCurParams.getEastAngle());
	F32 cosTheta = cos(mCurParams.getEastAngle());

	F32 sinPhi = sin(mCurParams.getSunAngle());
	F32 cosPhi = cos(mCurParams.getSunAngle());

	sunDir.mV[0] = -sinTheta * cosPhi;
	sunDir.mV[1] = sinPhi;
	sunDir.mV[2] = cosTheta * cosPhi;
	sunDir.mV[3] = 0;

	moonDir = -sunDir;

	// is the normal from the sun or the moon
	if(sunDir.mV[1] >= 0)
	{
		mLightDir = sunDir;
	}
	else if(sunDir.mV[1] < 0 && sunDir.mV[1] > LLSky::NIGHTTIME_ELEVATION_COS)
	{
		// clamp v1 to 0 so sun never points up and causes weirdness on some machines
		LLVector3 vec(sunDir.mV[0], sunDir.mV[1], sunDir.mV[2]);
		vec.mV[1] = 0;
		vec.normVec();
		mLightDir = LLVector4(vec, 0.f);
	}
	else
	{
		mLightDir = moonDir;
	}

	// calculate the clamp lightnorm for sky (to prevent ugly banding in sky
	// when haze goes below the horizon
	mClampedLightDir = sunDir;

	if (mClampedLightDir.mV[1] < -0.1f)
	{
		mClampedLightDir.mV[1] = -0.1f;
	}

	mCurParams.set("lightnorm", mLightDir);

	// bind the variables for all shaders only if we're using WindLight
	std::vector<LLGLSLShader*>::iterator shaders_iter=mShaderList.begin();
	for(; shaders_iter != mShaderList.end(); ++shaders_iter)
	{
		(*shaders_iter)->mUniformsDirty = TRUE;
	}

	// get the cfr version of the sun's direction
	LLVector3 cfrSunDir(sunDir.mV[2], sunDir.mV[0], sunDir.mV[1]);

	// set direction and don't allow overriding
	gSky.setSunDirection(cfrSunDir, LLVector3(0,0,0));
	gSky.setOverrideSun(TRUE);
}
Пример #13
0
int main()
{
    std::vector<int> vec(10);
    std::array_view<int, 1> b(vec);
    int a = b[{100}];
}
Пример #14
0
Vector<long> Vector<T>::div(long factor) const
{
    Vector<long> vec(dimension());
    std::transform(this->begin(), this->end(), vec.begin(), [&factor](T e) { return std::lround(e / factor); });
    return vec;
}
Пример #15
0
bool ofxCalibImage::makeFromImage(CVD::Image<CVD::byte> &im, ofxDataPackege * _data){
    data = _data;
    mvCorners.clear();
    mvGridCorners.clear();
    
    mim = im;
    mim.make_unique();
    
    // Find potential corners..
    // This works better on a blurred image, so make a blurred copy
    // and run the corner finding on that.
    {
        CVD::Image<CVD::byte> imBlurred = mim;
        imBlurred.make_unique();
        CVD::convolveGaussian(imBlurred, data->BlurSigma);
        CVD::ImageRef irTopLeft(5,5);
        CVD::ImageRef irBotRight = mim.size() - irTopLeft;
        CVD::ImageRef ir = irTopLeft;
        
        ofSetColor(255, 0, 255);
        int nGate = data->MeanGate;
        ofPushStyle();
        ofNoFill();
        do
            if( IsCorner(imBlurred, ir, nGate)){
                mvCorners.push_back(ir);
                ofCircle(ir.x,ir.y, 2);
            }
        while( ir.next(irTopLeft, irBotRight));
        ofPopStyle();
    }
    
    // If there's not enough corners, i.e. camera pointing somewhere random, abort.
    if((int) mvCorners.size() < 20)
        return false;
    
    // Pick a central corner point...
    CVD::ImageRef irCenterOfImage = mim.size()  / 2;
    CVD::ImageRef irBestCenterPos;
    unsigned int nBestDistSquared = 99999999;
    for(unsigned int i=0; i<mvCorners.size(); i++){
        unsigned int nDist = (mvCorners[i] - irCenterOfImage).mag_squared();
        if(nDist < nBestDistSquared){
            nBestDistSquared = nDist;
            irBestCenterPos = mvCorners[i];
        }
    }
    
    // ... and try to fit a corner-patch to that.
    PTAMM::CalibCornerPatch Patch( data->CornerPatchSize);
    PTAMM::CalibCornerPatch::Params Params;
    Params.v2Pos = vec(irBestCenterPos);
    Params.v2Angles = GuessInitialAngles(mim, irBestCenterPos); 
    Params.dGain = 80.0;
    Params.dMean = 120.0;
    
    if(!Patch.IterateOnImageWithDrawing(Params, mim))
        return false;
    
    // The first found corner patch becomes the origin of the detected grid.
    ofxCalibGridCorner cFirst;
    cFirst.Params = Params;
    mvGridCorners.push_back(cFirst);
    cFirst.draw();
    
    // Next, go in two compass directions from the origin patch, and see if 
    // neighbors can be found.
    if(!(expandByAngle(0,0) || expandByAngle(0,2)))
        return false;
    if(!(expandByAngle(0,1) || expandByAngle(0,3)))
        return false;
    
    mvGridCorners[1].mInheritedSteps = mvGridCorners[2].mInheritedSteps = mvGridCorners[0].GetSteps(mvGridCorners);
    
    // The three initial grid elements are enough to find the rest of the grid.
    int nNext;
    int nSanityCounter = 0; // Stop it getting stuck in an infinite loop...
    const int nSanityCounterLimit = 500;
    while((nNext = nextToExpand()) >= 0 && nSanityCounter < nSanityCounterLimit ){
        expandByStep(nNext);
        nSanityCounter++;
    }
    if(nSanityCounter == nSanityCounterLimit)
        return false;
    
    drawImageGrid();
    return true;
}
Пример #16
0
 static vec add(vec a, vec b) {
   return vec(a.x+b.x, a.y+b.y, a.z+b.z, a.r+b.r, a.g+b.g, a.b+b.b);
 }
Пример #17
0
vec scale(vec v, double k)
{
    return vec(v.x * k, v.y * k);
}
Пример #18
0
vector<pair<int, float> > User::sort() {
  vector<pair<int, float> > vec(*((vector<pair<int, float> >*)this));
  std::sort(vec.begin(), vec.end(), hash_sort_comp());
  return vec;
}
Пример #19
0
vec vec_angle(double angle, double distance)
{
    angle = angle * M_PI * 2.0 / full_circle;
    return vec(cos(angle) * distance, sin(angle) * distance);
}
    //---------------------------------------
    void MaterialExporter::setSetParam ( const cgfxShaderNode* shaderNodeCgfx, const cgfxAttrDef* attribute )
    {
        COLLADASW::StreamWriter* streamWriter = mDocumentExporter->getStreamWriter();
        String attributeName = attribute->fName.asChar();

        cgfxAttrDef::cgfxAttrType attributeType = attribute->fType;
        switch ( attributeType )
        {
        case cgfxAttrDef::kAttrTypeBool:
            {
                COLLADASW::SetParamBool setParam ( streamWriter );
                setParam.openParam ( attributeName );
                setParam.appendValues ( attribute->fNumericDef && attribute->fNumericDef[0] );
                setParam.closeParam ();
                break;
            }
        case cgfxAttrDef::kAttrTypeInt:
            {
                COLLADASW::SetParamInt setParam ( streamWriter );
                setParam.openParam ( attributeName );
                setParam.appendValues ( (int) attribute->fNumericDef[0] );
                setParam.closeParam();
                break;
            }
        case cgfxAttrDef::kAttrTypeString:
            {
                COLLADASW::SetParamString setParam ( streamWriter );
                setParam.openParam ( attributeName );
                if ( attribute->fStringDef != NULL ) 
                    setParam.appendValues ( String ( attribute->fStringDef.asChar() ) );
                setParam.closeParam();
                break;
            }
        case cgfxAttrDef::kAttrTypeFloat:
            {
                COLLADASW::SetParamFloat setParam ( streamWriter );
                setParam.openParam ( attributeName );
                if ( attribute->fNumericDef!=NULL /*&& attribute->fNumericDef[0]!=0*/ )  
                    setParam.appendValues ( attribute->fNumericDef[0] );
                setParam.closeParam();
                break;
            }
        case cgfxAttrDef::kAttrTypeVector2:
            {
                COLLADASW::SetParamFloat2 setParam ( streamWriter );
                setParam.openParam ( attributeName );
                for ( int i=0; i<attribute->fSize; ++i )
                {
                    if ( attribute->fNumericDef!=NULL /*&& attribute->fNumericDef[i]!=0*/ )  
                    {
                        double val = attribute->fNumericDef[i];
                        setParam.appendValues( val );
                    }
                }
                setParam.closeParam();
                break;
            }
        case cgfxAttrDef::kAttrTypeVector3:
        case cgfxAttrDef::kAttrTypeColor3:
            {
                COLLADASW::SetParamFloat3 setParam ( streamWriter );
                setParam.openParam ( attributeName );
                for ( int i=0; i<attribute->fSize; ++i )
                {
                    if ( attribute->fNumericDef!=NULL /*&& attribute->fNumericDef[i]!=0*/ )  
                    {
                        double val = attribute->fNumericDef[i];
                        setParam.appendValues( val );
                    }
                }
                setParam.closeParam();
                break;
            }
        case cgfxAttrDef::kAttrTypeVector4:
        case cgfxAttrDef::kAttrTypeColor4:
            {
                COLLADASW::SetParamFloat4 setParam ( streamWriter );
                setParam.openParam ( attributeName );
                for ( int i=0; i<attribute->fSize; ++i )
                {
                    if ( attribute->fNumericDef!=NULL /*&& attribute->fNumericDef[i]!=0*/ )  
                    {
                        double val = attribute->fNumericDef[i];
                        setParam.appendValues( val );
                    }
                }
                setParam.closeParam();
                break;
            }
        case cgfxAttrDef::kAttrTypeWorldDir:
        case cgfxAttrDef::kAttrTypeWorldPos:
            {
                // Read the value
                double tmp[4];
                for ( int i=0; i<attribute->fSize; ++i )
                {
                    tmp[i] = attribute->fNumericDef[i];
                }
                if (attribute->fSize == 3) tmp[3] = 1.0;

                // Find the coordinate space, and whether it is a point or a vector
                int base = cgfxAttrDef::kAttrTypeFirstPos;
                if (attribute->fType <= cgfxAttrDef::kAttrTypeLastDir) 
                    base = cgfxAttrDef::kAttrTypeFirstDir;
                int space = attribute->fType - base;

                // Compute the transform matrix
                MMatrix mat;
                switch (space)
                {
                    /* case 0:	object space, handled in view dependent method */
                case 1:	/* world space  - do nothing, identity */ break;
                    /* case 2: eye space, unsupported yet */
                    /* case 3: clip space, unsupported yet */
                    /* case 4: screen space, unsupported yet */
                }

                if ( base == cgfxAttrDef::kAttrTypeFirstPos )
                {
                    MPoint point(tmp[0], tmp[1], tmp[2], tmp[3]);
                    point *= mat;
                    tmp[0] = point.x;
                    tmp[1] = point.y;
                    tmp[2] = point.z;
                    tmp[3] = point.w;
                }
                else
                {
                    MVector vec(tmp[0], tmp[1], tmp[2]);
                    vec *= mat;
                    tmp[0] = vec.x;
                    tmp[1] = vec.y;
                    tmp[2] = vec.z;
                    tmp[3] = 1;
                }

                COLLADASW::SetParamFloat4 setParam ( streamWriter );
                setParam.openParam ( attributeName );
                setParam.appendValues( tmp[0], tmp[1], tmp[2], tmp[3] );
                setParam.closeParam();
                break;
            }
        case cgfxAttrDef::kAttrTypeMatrix:
        case cgfxAttrDef::kAttrTypeWorldMatrix:
        case cgfxAttrDef::kAttrTypeViewMatrix:
        case cgfxAttrDef::kAttrTypeProjectionMatrix:
        case cgfxAttrDef::kAttrTypeWorldViewMatrix:
        case cgfxAttrDef::kAttrTypeWorldViewProjectionMatrix:
            {
                COLLADASW::SetParamFloat4x4 setParam ( streamWriter );
                setParam.openParam ( attributeName );

                MMatrix mayaMatrix;
                double* p = &mayaMatrix.matrix[0][0];
                for ( int k=0; k<attribute->fSize; ++k )
                {
                    p[k] = attribute->fNumericDef[k];
                }

                MMatrix wMatrix, vMatrix, pMatrix, sMatrix;
                MMatrix wvMatrix, wvpMatrix, wvpsMatrix;
                {
                    float tmp[4][4];

                    wMatrix.setToIdentity();

                    glGetFloatv(GL_MODELVIEW_MATRIX, &tmp[0][0]);
                    wvMatrix = MMatrix(tmp);

                    vMatrix = wMatrix.inverse() * wvMatrix;

                    glGetFloatv(GL_PROJECTION_MATRIX, &tmp[0][0]);
                    pMatrix = MMatrix(tmp);

                    wvpMatrix = wvMatrix * pMatrix;

                    float vpt[4];
                    float depth[2];

                    glGetFloatv(GL_VIEWPORT, vpt);
                    glGetFloatv(GL_DEPTH_RANGE, depth);

                    // Construct the NDC -> screen space matrix
                    //
                    float x0, y0, z0, w, h, d;

                    x0 = vpt[0];
                    y0 = vpt[1];
                    z0 = depth[0];
                    w  = vpt[2];
                    h  = vpt[3];
                    d  = depth[1] - z0;

                    // Make a reference to ease the typing
                    //
                    double* s = &sMatrix.matrix[0][0];

                    s[ 0] = w/2;	s[ 1] = 0.0;	s[ 2] = 0.0;	s[ 3] = 0.0;
                    s[ 4] = 0.0;	s[ 5] = h/2;	s[ 6] = 0.0;	s[ 7] = 0.0;
                    s[ 8] = 0.0;	s[ 9] = 0.0;	s[10] = d/2;	s[11] = 0.0;
                    s[12] = x0+w/2;	s[13] = y0+h/2;	s[14] = z0+d/2;	s[15] = 1.0;

                    wvpsMatrix = wvpMatrix * sMatrix;
                }		

                switch ( attribute->fType )
                {
                case cgfxAttrDef::kAttrTypeWorldMatrix:
                    mayaMatrix = wMatrix; break;
                case cgfxAttrDef::kAttrTypeViewMatrix:
                    mayaMatrix = vMatrix; break;
                case cgfxAttrDef::kAttrTypeProjectionMatrix:
                    mayaMatrix = pMatrix; break;
                case cgfxAttrDef::kAttrTypeWorldViewMatrix:
                    mayaMatrix = wvMatrix; break;
                case cgfxAttrDef::kAttrTypeWorldViewProjectionMatrix:
                    mayaMatrix = wvpMatrix; break;
                default:
                    break;
                }

                if (attribute->fInvertMatrix)
                    mayaMatrix = mayaMatrix.inverse();

                if (!attribute->fTransposeMatrix)
                    mayaMatrix = mayaMatrix.transpose();

                double matrix[4][4];
                convertMayaMatrixToTransposedDouble4x4 ( matrix, mayaMatrix, getTolerance () );
                setParam.appendValues( matrix );
                setParam.closeParam();
                break;
            }
        case cgfxAttrDef::kAttrTypeColor1DTexture:
        case cgfxAttrDef::kAttrTypeColor2DTexture:
        case cgfxAttrDef::kAttrTypeColor3DTexture:
        case cgfxAttrDef::kAttrTypeColor2DRectTexture:
        case cgfxAttrDef::kAttrTypeNormalTexture:
        case cgfxAttrDef::kAttrTypeBumpTexture:
        case cgfxAttrDef::kAttrTypeCubeTexture:
        case cgfxAttrDef::kAttrTypeEnvTexture:
        case cgfxAttrDef::kAttrTypeNormalizationTexture:
            {
                CGparameter cgParameter = attribute->fParameterHandle;
                HwShaderExporter hwShaderExporter ( mDocumentExporter );
                hwShaderExporter.setShaderFxFileUri ( getShaderFxFileUri () );

                MObject shaderNode = shaderNodeCgfx->thisMObject();
                hwShaderExporter.exportSampler ( shaderNode, cgParameter, false );


                // -------------------------------
//                 String imageName = attribute->fStringDef.asChar();
// 
//                 MObject oNode = shaderNodeCgfx->thisMObject();
//                 MFnDependencyNode oNodeFn ( oNode );
//                 String oNodeName = oNodeFn.name().asChar(); // cgfxShader1
// 
//                 MPlug plug;
//                 if ( DagHelper::getPlugConnectedTo( oNode, attributeName, plug ) )
//                 {
//                     String plugName = plug.name().asChar(); // file1.outColor
//                     MObject textureNode = plug.node();
// 
//                     //COLLADASW::Surface::SurfaceType surfaceType;
//                     COLLADASW::Sampler::SamplerType samplerType;
//                     COLLADASW::ValueType::ColladaType samplerValueType;
// 
//                     switch ( attributeType )
//                     {
//                     case cgfxAttrDef::kAttrTypeColor1DTexture:
//                         //surfaceType = COLLADASW::Surface::SURFACE_TYPE_1D;
//                         samplerType = COLLADASW::Sampler::SAMPLER_TYPE_1D;
//                         samplerValueType = COLLADASW::ValueType::SAMPLER_1D;
//                         break;
//                     case cgfxAttrDef::kAttrTypeColor2DTexture:
//                     case cgfxAttrDef::kAttrTypeNormalTexture:
//                     case cgfxAttrDef::kAttrTypeBumpTexture:
//                         //surfaceType = COLLADASW::Surface::SURFACE_TYPE_2D;
//                         samplerType = COLLADASW::Sampler::SAMPLER_TYPE_2D;
//                         samplerValueType = COLLADASW::ValueType::SAMPLER_2D;
//                         break;
//                     case cgfxAttrDef::kAttrTypeColor3DTexture:
//                         //surfaceType = COLLADASW::Surface::SURFACE_TYPE_3D;
//                         samplerType = COLLADASW::Sampler::SAMPLER_TYPE_3D;
//                         samplerValueType = COLLADASW::ValueType::SAMPLER_3D;
//                         break;
//                     case cgfxAttrDef::kAttrTypeColor2DRectTexture:
//                         //surfaceType = COLLADASW::Surface::SURFACE_TYPE_RECT;
//                         samplerType = COLLADASW::Sampler::SAMPLER_TYPE_RECT;
//                         samplerValueType = COLLADASW::ValueType::SAMPLER_RECT;
//                         break;
//                     case cgfxAttrDef::kAttrTypeCubeTexture:
//                     case cgfxAttrDef::kAttrTypeEnvTexture:
//                     case cgfxAttrDef::kAttrTypeNormalizationTexture:
//                         //surfaceType = COLLADASW::Surface::SURFACE_TYPE_CUBE;
//                         samplerType = COLLADASW::Sampler::SAMPLER_TYPE_CUBE;
//                         samplerValueType = COLLADASW::ValueType::SAMPLER_CUBE;
//                         break;
//                     default:
//                         //surfaceType = COLLADASW::Surface::SURFACE_TYPE_UNTYPED;
//                         samplerType = COLLADASW::Sampler::SAMPLER_TYPE_UNSPECIFIED;
//                         samplerValueType = COLLADASW::ValueType::VALUE_TYPE_UNSPECIFIED;
//                     }
// 
//                     // Write the params elements
//                     setSetParamTexture ( attribute, textureNode, samplerType, samplerValueType );
//                }
            }
        }
    }
Пример #21
0
static inline void findnormal(const normalgroup &g, const vec &surface, vec &v)
{
    v = vec(0, 0, 0);
    int total = 0;
    if(surface.x >= lerpthreshold) { int n = (g.flat>>4)&0xF; v.x += n; total += n; }
Пример #22
0
int CLocalFinderApp::Run(void)
{
    CArgs myargs = GetArgs();

    int left            = myargs["from"].AsInteger();
    int right           = myargs["to"].AsInteger();
    bool repeats        = myargs["rep"];


    //
    // read our sequence data
    //
    CFastaReader fastareader(myargs["input"].AsString());
    CRef<CSeq_loc> masked_regions;
    masked_regions = fastareader.SaveMask();
    CRef<CSeq_entry> se = fastareader.ReadOneSeq();
    
    if(masked_regions) {
        CBioseq& bioseq = se->SetSeq();     // assumes that reader gets only one sequence per fasta id (no [] in file)
        CRef<CSeq_annot> seq_annot(new CSeq_annot);
        seq_annot->SetNameDesc("NCBI-FASTA-Lowercase");
        bioseq.SetAnnot().push_back(seq_annot);
        CSeq_annot::C_Data::TFtable* feature_table = &seq_annot->SetData().SetFtable();
        for(CSeq_loc_CI i(*masked_regions); i; ++i) {
            CRef<CSeq_feat> repeat(new CSeq_feat);
            CRef<CSeq_id> id(new CSeq_id);
            id->Assign(i.GetSeq_id());
            CRef<CSeq_loc> loc(new CSeq_loc(*id, i.GetRange().GetFrom(), i.GetRange().GetTo()));
            repeat->SetLocation(*loc);
            repeat->SetData().SetImp().SetKey("repeat_region");
            feature_table->push_back(repeat);
        }
    }

    CRef<CObjectManager> objmgr = CObjectManager::GetInstance();
    CScope scope(*objmgr);
    scope.AddTopLevelSeqEntry(*se);       

    CRef<CSeq_id> cntg(new CSeq_id);
    cntg->Assign(*se->GetSeq().GetFirstId());
    CSeq_loc loc;
    loc.SetWhole(*cntg);
    CSeqVector vec(loc, scope);
    vec.SetIupacCoding();

    CResidueVec seq;
    ITERATE(CSeqVector,i,vec)
        seq.push_back(*i);

    // read the alignment information
    TGeneModelList alignments;
    if(myargs["align"]) {
        CNcbiIstream& alignmentfile = myargs["align"].AsInputFile();
        string our_contig = cntg->GetSeqIdString(true);
        string cur_contig; 
        CAlignModel algn;
        
        while(alignmentfile >> algn >> getcontig(cur_contig)) {
            if (cur_contig==our_contig)
                alignments.push_back(algn);
        }
    }

    // create engine
    CRef<CHMMParameters> hmm_params(new CHMMParameters(myargs["model"].AsInputFile()));
    CGnomonEngine gnomon(hmm_params, seq, TSignedSeqRange(left, right));

    // run!
    gnomon.Run(alignments, repeats, true, true, false, false, 10.0);

    // dump the annotation
    CRef<CSeq_annot> annot = gnomon.GetAnnot(*cntg);
    auto_ptr<CObjectOStream> os(CObjectOStream::Open(eSerial_AsnText, cout));
    *os << *annot;

    return 0;

}
Пример #23
0
void CaveV6::makeTunnel(bool dirswitch) {
	if (dirswitch && !large_cave) {
		main_direction = v3f(
			((float)(ps->next() % 20) - (float)10) / 10,
			((float)(ps->next() % 20) - (float)10) / 30,
			((float)(ps->next() % 20) - (float)10) / 10
		);
		main_direction *= (float)ps->range(0, 10) / 10;
	}

	// Randomize size
	s16 min_d = min_tunnel_diameter;
	s16 max_d = max_tunnel_diameter;
	rs = ps->range(min_d, max_d);

	v3s16 maxlen;
	if (large_cave) {
		maxlen = v3s16(
			rs * part_max_length_rs,
			rs * part_max_length_rs / 2,
			rs * part_max_length_rs
		);
	} else {
		maxlen = v3s16(
			rs * part_max_length_rs,
			ps->range(1, rs * part_max_length_rs),
			rs * part_max_length_rs
		);
	}

	v3f vec(
		(float)(ps->next() % (maxlen.X * 1)) - (float)maxlen.X / 2,
		(float)(ps->next() % (maxlen.Y * 1)) - (float)maxlen.Y / 2,
		(float)(ps->next() % (maxlen.Z * 1)) - (float)maxlen.Z / 2
	);

	// Jump downward sometimes
	if (!large_cave && ps->range(0, 12) == 0) {
		vec = v3f(
			(float)(ps->next() % (maxlen.X * 1)) - (float)maxlen.X / 2,
			(float)(ps->next() % (maxlen.Y * 2)) - (float)maxlen.Y,
			(float)(ps->next() % (maxlen.Z * 1)) - (float)maxlen.Z / 2
		);
	}

	vec += main_direction;

	v3f rp = orp + vec;
	if (rp.X < 0)
		rp.X = 0;
	else if (rp.X >= ar.X)
		rp.X = ar.X - 1;
	
	if (rp.Y < route_y_min)
		rp.Y = route_y_min;
	else if (rp.Y >= route_y_max)
		rp.Y = route_y_max - 1;
	
	if (rp.Z < 0)
		rp.Z = 0;
	else if (rp.Z >= ar.Z)
		rp.Z = ar.Z - 1;
	
	vec = rp - orp;

	float veclen = vec.getLength();
	// As odd as it sounds, veclen is *exactly* 0.0 sometimes, causing a FPE
	if (veclen < 0.05)
		veclen = 1.0;
		
	// Every second section is rough
	bool randomize_xz = (ps2->range(1, 2) == 1);

	// Carve routes
	for (float f = 0; f < 1.0; f += 1.0 / veclen)
		carveRoute(vec, f, randomize_xz);
	
	orp = rp;
}
Пример #24
0
 void clearloc() { loc = vec(-1e16f, -1e16f, -1e16f); }
Real
NSMomentumInviscidFluxWithGradP::computeQpOffDiagJacobian(unsigned int jvar)
{
  // Map jvar into the numbering expected by this->compute_pressure_jacobain_value()
  unsigned var_number = this->map_var_number(jvar);

  // The Jacobian contribution due to differentiating the grad(p)
  // term wrt variable var_number.
  Real dFdp = compute_pressure_jacobian_value(var_number);


  if (jvar == _rho_var_number)
  {
    // Derivative of inviscid flux convective terms wrt density:
    // x-mom: (-u_1^2   , -u_1*u_2  , -u_1*u_3 ) * grad(phi_i) * phi_j
    // y-mom: (-u_2*u_1 , -u_2^2    , -u_2*u_3 ) * grad(phi_i) * phi_j
    // z-mom: (-u_3*u_1 , -u_3*u_2  , -u_3^2   ) * grad(phi_i) * phi_j

    // Start with the velocity vector
    RealVectorValue vec(_u_vel[_qp], _v_vel[_qp], _w_vel[_qp]);

    // Scale velocity vector by -1 * vec(_component)
    vec *= -vec(_component);

    return
      // Convective terms Jacobian
      -(vec * _grad_test[_i][_qp]) * _phi[_j][_qp]

      +

      // Pressure term Jacobian
      dFdp*_test[_i][_qp];
  }


  // Handle off-diagonal derivatives wrt momentums
  else if ((jvar == _rhou_var_number) || (jvar == _rhov_var_number) || (jvar == _rhow_var_number))
  {
    // Start with the velocity vector
    RealVectorValue vel(_u_vel[_qp], _v_vel[_qp], _w_vel[_qp]);

    // Map jvar into jlocal = {0,1,2}, regardless of how Moose has numbered things.
    // Can't do a case statement here since _rhou_var_number, etc. are not constants...
    unsigned jlocal = 0;

    if (jvar == _rhov_var_number)
      jlocal = 1;
    else if (jvar == _rhow_var_number)
      jlocal = 2;

    return
      // Convective terms Jacobian
      -vel(_component) * _grad_test[_i][_qp](jlocal) * _phi[_j][_qp]

      +

      // Pressure term Jacobian
      dFdp*_test[_i][_qp];
  }

  else if (jvar == _rhoe_var_number)
  {
    return
      // Pressure term Jacobian
      dFdp*_test[_i][_qp];
  }

  // We shouldn't get here... jvar should have matched one of the if statements above!
  mooseError("computeQpOffDiagJacobian called with invalid jvar.");

  return 0;
}
Пример #26
0
expression_ptr cpp_from_cloog::process( clast_expr* expr )
{
    switch(expr->type)
    {
    case clast_expr_name:
    {
        string name = reinterpret_cast<clast_name*>(expr)->name;
        if (m_id_func)
        {
            auto expr = m_id_func(name);
            if (expr)
                return expr;
        }
        return make_shared<id_expression>(name);
    }
    case clast_expr_term:
    {
        auto term = reinterpret_cast<clast_term*>(expr);
        expression_ptr val = literal(term->val);
        if (term->var)
        {
            auto var = process(term->var);
            val = make_shared<bin_op_expression>(op::mult, val, var);
        }
        return val;
    }
    case clast_expr_bin:
    {
        auto operation = reinterpret_cast<clast_binary*>(expr);
        auto lhs = process(operation->LHS);
        auto rhs = literal(operation->RHS);

        cpp_gen::op op_type;

        switch(operation->type)
        {
        case clast_bin_fdiv:
            throw std::runtime_error("Floor-of-division not implemented.");
        case clast_bin_cdiv:
            throw std::runtime_error("Ceiling-of-division not implemented.");
        case clast_bin_div:
            op_type = op::div;
        case clast_bin_mod:
            // FIXME: should be modulo, not remainder!
            op_type = op::rem;
        default:
            throw std::runtime_error("Unexpected binary operation type.");
        }

        return make_shared<bin_op_expression>(op_type, lhs, rhs);
    }
    case clast_expr_red:
    {
        auto reduction = reinterpret_cast<clast_reduction*>(expr);
        if (reduction->n < 1)
            return literal((long)0);

        auto lhs = process( reduction->elts[0] );

        for (int i = 1; i < reduction->n; ++i)
        {
            auto rhs = process( reduction->elts[i] );
            switch(reduction->type)
            {
            case clast_red_sum:
                lhs = make_shared<bin_op_expression>(op::add, lhs, rhs);
                break;
            case clast_red_min:
                lhs = make_shared<call_expression>("min", vec({lhs, rhs}));
                break;
            case clast_red_max:
                lhs = make_shared<call_expression>("max", vec({lhs, rhs}));
                break;
            default:
                throw std::runtime_error("Unexpected reduction type.");
            }
        }
        return lhs;
    }
    default:
        throw std::runtime_error("Unexpected expression type.");
    }
}
Пример #27
0
Vector3D Vector3D::operator-(const Vector3D& vec2) const
{
    Vector3D vec(*this);
    vec -= vec2;
    return vec;
}
Пример #28
0
void ofxCalibImage::expandByStep(int n){
    //static gvar3<double> gvdMaxStepDistFraction("CameraCalibrator.ExpandByStepMaxDistFrac", 0.3, SILENT);
    //static gvar3<int> gvnCornerPatchSize("CameraCalibrator.CornerPatchPixelSize", 20, SILENT);
    
    ofxCalibGridCorner &gSrc = mvGridCorners[n];
    
    // First, choose which direction to expand in...
    // Ideally, choose a dirn for which the Step calc is good!
    int nDirn = -10;
    for(int i=0; nDirn == -10 && i<4; i++){
        if(gSrc.aNeighborStates[i].val == N_NOT_TRIED &&
           gSrc.aNeighborStates[(i+2) % 4].val >= 0)
            nDirn = i;
    }
    if(nDirn == -10)
        for(int i=0; nDirn == -10 && i<4; i++){
            if(gSrc.aNeighborStates[i].val == N_NOT_TRIED)
                nDirn = i;
        }
    assert(nDirn != -10);
    
    TooN::Vector<2> v2Step;
    CVD::ImageRef irGridStep = ir_from_dirn(nDirn);
    
    v2Step = gSrc.GetSteps(mvGridCorners).T() * vec(irGridStep);
    
    TooN::Vector<2> v2SearchPos = gSrc.Params.v2Pos + v2Step;
    
    // Before the search: pre-fill the failure result for easy returns.
    gSrc.aNeighborStates[nDirn].val = N_FAILED;
    
    CVD::ImageRef irBest;
    double dBestDist = 99999;
    for(unsigned int i=0; i<mvCorners.size(); i++){
        TooN::Vector<2> v2Diff = vec(mvCorners[i]) - v2SearchPos;
        if( (v2Diff * v2Diff) > (dBestDist * dBestDist) )
            continue;
        dBestDist = sqrt(v2Diff * v2Diff);
        irBest = mvCorners[i];
    }
    
    double dStepDist= sqrt(v2Step * v2Step);
    if(dBestDist > data->MaxStepDistFraction * dStepDist)
        return;
    
    ofxCalibGridCorner gTarget;
    gTarget.Params = gSrc.Params;
    gTarget.Params.v2Pos = vec(irBest);
    gTarget.Params.dGain *= -1;
    gTarget.irGridPos = gSrc.irGridPos + irGridStep;
    gTarget.mInheritedSteps = gSrc.GetSteps(mvGridCorners);
    PTAMM::CalibCornerPatch Patch( data->CornerPatchSize);
    if(!Patch.IterateOnImageWithDrawing(gTarget.Params, mim))
        return;
    
    // Update connection states:
    int nTargetNum = static_cast<int>(mvGridCorners.size());
    for(int dirn = 0; dirn<4; dirn++){
        CVD::ImageRef irSearch = gTarget.irGridPos + ir_from_dirn(dirn);
        for(unsigned int i=0; i<mvGridCorners.size(); i++)
            if(mvGridCorners[i].irGridPos == irSearch){
                gTarget.aNeighborStates[dirn].val = i;
                mvGridCorners[i].aNeighborStates[(dirn + 2) % 4].val = nTargetNum;
            }
    }
    mvGridCorners.push_back(gTarget);
    mvGridCorners.back().draw();
}
Пример #29
0
//////////////////////////////////////////////////////////////
// Used to handle direct messages into the table, or
// returned plot data from queried objects.
//////////////////////////////////////////////////////////////
void Table::input( double v )
{
    vec().push_back( v );
}
Пример #30
0
int MapgenMath::generateTerrain() {

	MapNode n_air(CONTENT_AIR, LIGHT_SUN), n_water_source(c_water_source, LIGHT_SUN);
	MapNode n_stone(c_stone, LIGHT_SUN);
	u32 index = 0;
	v3s16 em = vm->m_area.getExtent();

#if 1

	/* debug
	v3f vec0 = (v3f(node_min.X, node_min.Y, node_min.Z) - center) * scale ;
	errorstream << " X=" << node_min.X << " Y=" << node_min.Y << " Z=" << node_min.Z
	            //<< " N="<< mengersponge(vec0.X, vec0.Y, vec0.Z, distance, iterations)
	            << " N=" << (*func)(vec0.X, vec0.Y, vec0.Z, distance, iterations)
	            << " Sc=" << scale << " gen=" << params["generator"].asString() << " J=" << Json::FastWriter().write(params) << std::endl;
	*/
	for (s16 z = node_min.Z; z <= node_max.Z; z++) {
		for (s16 x = node_min.X; x <= node_max.X; x++, index++) {
			Biome *biome = bmgr->biomes[biomemap[index]];
			u32 i = vm->m_area.index(x, node_min.Y, z);
			for (s16 y = node_min.Y; y <= node_max.Y; y++) {
				v3f vec = (v3f(x, y, z) - center) * scale ;
				double d = (*func)(vec.X, vec.Y, vec.Z, distance, iterations);
				if ((!invert && d > 0) || (invert && d == 0)  ) {
					if (vm->m_data[i].getContent() == CONTENT_IGNORE)
	//					vm->m_data[i] = (y > water_level + biome->filler) ?
		//				                MapNode(biome->c_filler) : n_stone;
						vm->m_data[i] = n_stone;
				} else if (y <= water_level) {
					vm->m_data[i] = n_water_source;
				} else {
					vm->m_data[i] = n_air;
				}
				vm->m_area.add_y(em, i, 1);
			}
		}
	}
#endif


#if 0
// mandelbulber, unfinished but works
	sFractal par;
	par.doubles.N = 10;

	par.doubles.power = 9.0;
	par.doubles.foldingSphericalFixed =  1.0;
	par.doubles.foldingSphericalMin = 0.5;
	//no par.formula = smoothMandelbox; par.doubles.N = 40; invert = 0;//no
	par.mandelbox.doubles.sharpness = 3.0;
	par.mandelbox.doubles.scale = 1;
	par.mandelbox.doubles.sharpness = 2;
	par.mandelbox.doubles.foldingLimit = 1.0;
	par.mandelbox.doubles.foldingValue = 2;

//ok	par.formula = mandelboxVaryScale4D; par.doubles.N = 50; scale = 5; invert = 1; //ok
	par.mandelbox.doubles.vary4D.scaleVary =  0.1;
	par.mandelbox.doubles.vary4D.fold = 1;
	par.mandelbox.doubles.vary4D.rPower = 1;
	par.mandelbox.doubles.vary4D.minR = 0.5;
	par.mandelbox.doubles.vary4D.wadd = 0;
	par.doubles.constantFactor = 1.0;

	par.formula = menger_sponge; par.doubles.N = 15; invert = 0; size = 30000; center = v3f(-size / 2, -size + (-2 * -invert), 2);  scale = (double)1 / size; //ok

	//double tresh = 1.5;
	//par.formula = mandelbulb2; par.doubles.N = 10; scale = (double)1/size; invert=1; center = v3f(5,-size-5,0); //ok
	//par.formula = hypercomplex; par.doubles.N = 20; scale = 0.0001; invert=1; center = v3f(0,-10001,0); //(double)50 / max_r;

	//no par.formula = trig_DE; par.doubles.N = 5;  scale = (double)10; invert=1;

	//no par.formula = trig_optim; scale = (double)10;  par.doubles.N = 4;

	//par.formula = mandelbulb2; scale = (double)1/10000; par.doubles.N = 10; invert = 1; center = v3f(1,-4201,1); //ok
	// no par.formula = tglad;

	//par.formula = xenodreambuie;  par.juliaMode = 1; par.doubles.julia.x = -1; par.doubles.power = 2.0; center=v3f(-size/2,-size/2-5,5); //ok

	par.mandelbox.doubles.vary4D.scaleVary = 0.1;
	par.mandelbox.doubles.vary4D.fold = 1;
	par.mandelbox.doubles.vary4D.minR = 0.5;
	par.mandelbox.doubles.vary4D.rPower = 1;
	par.mandelbox.doubles.vary4D.wadd = 0;
	//no par.formula = mandelboxVaryScale4D;
	par.doubles.cadd = -1.3;
	//par.formula = aexion; // ok but center
	//par.formula = benesi; par.doubles.N = 10; center = v3f(0,0,0); invert = 0; //ok

	// par.formula = bristorbrot; //ok

	v3f vec0(node_min.X, node_min.Y, node_min.Z);
	vec0 = (vec0 - center) * scale ;
	errorstream << " X=" << node_min.X << " Y=" << node_min.Y << " Z=" << node_min.Z
	            << " N=" << Compute<normal>(CVector3(vec0.X, vec0.Y, vec0.Z), par)
	            //<<" F="<< Compute<fake_AO>(CVector3(node_min.X,node_min.Y,node_min.Z), par)
	            //<<" L="<<node_min.getLength()<< " -="<<node_min.getLength() - Compute<normal>(CVector3(node_min.X,node_min.Y,node_min.Z), par)
	            << " Sc=" << scale
	            << std::endl;

	for (s16 z = node_min.Z; z <= node_max.Z; z++)
		for (s16 y = node_min.Y; y <= node_max.Y; y++) {
			u32 i = vm->m_area.index(node_min.X, y, z);
			for (s16 x = node_min.X; x <= node_max.X; x++) {
				v3f vec(x, y, z);
				vec = (vec - center) * scale ;
				//double d = Compute<fake_AO>(CVector3(x,y,z), par);
				double d = Compute<normal>(CVector3(vec.X, vec.Y, vec.Z), par);
				//if (d>0)
				// errorstream << " d=" << d  <<" v="<< vec.getLength()<< " -="<< vec.getLength() - d <<" yad="
				//<< Compute<normal>(CVector3(x,y,z), par)
				//<< std::endl;
				if ((!invert && d > 0) || (invert && d == 0)/*&& vec.getLength() - d > tresh*/ ) {
					if (vm->m_data[i].getContent() == CONTENT_IGNORE)
						vm->m_data[i] = n_stone;
				} else {
					vm->m_data[i] = n_air;
				}
				i++;
			}
		}


#endif
	return 0;
}