void SkeletonBlendedGeometry::calculatePositions(void) { if(getBaseGeometry() == NULL) { //Error SWARNING << "Base Geometry is NULL." << std::endl; return; } if(getPositions() == NULL) { //Error SWARNING << "Positions is NULL." << std::endl; return; } if(getBaseGeometry()->getPositions() == NULL) { //Error SWARNING << "Base Geometry Postions is NULL." << std::endl; return; } Pnt3f CalculatedPoint; Pnt3f BasePoint; //Vec3f CalculatedNormal; //Zero the Position Property zeroGeoProperty(getPositions()); //Update the Positions and Normals UInt32 WeightIndex, JointIndex, VertexIndex; UInt32 NumWeightIndexTuples(getWeightIndexes()->size()/3); for(UInt32 i(0) ; i < NumWeightIndexTuples ; ++i) { VertexIndex = getWeightIndexes()->getValue<UInt32>( 3 * i ); JointIndex = getWeightIndexes()->getValue<UInt32>((3 * i) + 1); WeightIndex = getWeightIndexes()->getValue<UInt32>((3 * i) + 2); //v*BSM*IBM*JM*JW getBaseGeometry()->getPositions()->getValue<Pnt3f>(BasePoint, VertexIndex); _JointPoseTransforms[JointIndex].mult(BasePoint, BasePoint); //Add the displacement to the value at this position getPositions()->getValue<Pnt3f>(CalculatedPoint, VertexIndex); CalculatedPoint += Vec3f(BasePoint) * getWeights()->getValue<Pnt1f>(WeightIndex)[0]; getPositions()->setValue<Pnt3f>(CalculatedPoint, VertexIndex); } for(UInt32 i = 0; i < _mfParents.size(); i++) { _mfParents[i]->invalidateVolume(); } _volumeCache.setValid(); _volumeCache.setEmpty(); _NeedRecalc = false; }
void StreamLines::process() { auto mesh = std::make_shared<BasicMesh>(); mesh->setModelMatrix(sampler_.getData()->getModelMatrix()); mesh->setWorldMatrix(sampler_.getData()->getWorldMatrix()); auto m = streamLineProperties_.getSeedPointTransformationMatrix( sampler_.getData()->getCoordinateTransformer()); ImageSampler tf(tf_.get().getData()); float maxVelocity = 0; StreamLineTracer tracer(sampler_.getData(), streamLineProperties_); std::vector<BasicMesh::Vertex> vertices; for (const auto &seeds : seedPoints_) { for (auto &p : (*seeds)) { vec4 P = m * vec4(p, 1.0f); auto line = tracer.traceFrom(P.xyz()); auto position = line.getPositions().begin(); auto velocity = line.getMetaData("velocity").begin(); auto size = line.getPositions().size(); if (size == 0) continue; auto indexBuffer = mesh->addIndexBuffer(DrawType::Lines, ConnectivityType::StripAdjacency); indexBuffer->add(0); for (size_t i = 0; i < size; i++) { vec3 pos(*position); vec3 v(*velocity); float l = glm::length(vec3(*velocity)); float d = glm::clamp(l / velocityScale_.get(), 0.0f, 1.0f); maxVelocity = std::max(maxVelocity, l); auto c = vec4(tf.sample(dvec2(d, 0.0))); indexBuffer->add(static_cast<std::uint32_t>(vertices.size())); vertices.push_back({pos, glm::normalize(v), pos, c}); position++; velocity++; } indexBuffer->add(static_cast<std::uint32_t>(vertices.size() - 1)); } } mesh->addVertices(vertices); linesStripsMesh_.setData(mesh); maxVelocity_.set(toString(maxVelocity)); }
void PosUpdateScan::executePlanOperation() { auto c_pc = checked_pointer_cast<const PointerCalculator>(input.getTable(0)); auto c_store = checked_pointer_cast<const storage::Store>(c_pc->getActualTable()); // Cast the constness away auto store = std::const_pointer_cast<storage::Store>(c_store); // Get the current maximum size const auto& beforSize = store->size(); // Get the offset for inserts into the delta and the size of the delta that // we need to increase by the positions we are inserting auto writeArea = store->appendToDelta(c_pc->getPositions()->size()); // Get the modification record for the current transaction auto& txmgr = tx::TransactionManager::getInstance(); auto& modRecord = txmgr[_txContext.tid]; // Functor we use for updating the data set_json_value_functor fun(store->getDeltaTable()); storage::type_switch<hyrise_basic_types> ts; size_t counter = 0; for(const auto& p : *(c_pc->getPositions())) { // First delete the old record bool deleteOk = store->markForDeletion(p, _txContext.tid) == hyrise::tx::TX_CODE::TX_OK; if(!deleteOk) { txmgr.rollbackTransaction(_txContext); throw std::runtime_error("Aborted TX because TID of other TX found"); } modRecord.deletePos(store, p); //store->setTid(p, _txContext.tid); // Copy the old row from the main store->copyRowToDelta(store, p, writeArea.first+counter, _txContext.tid); // Update all the necessary values for(const auto& kv : _raw_data) { const auto& fld = store->numberOfColumn(kv.first); fun.set(fld, writeArea.first+counter, kv.second); ts(store->typeOfColumn(fld), fun); } // Insert the new one modRecord.insertPos(store, beforSize+counter); ++counter; } // Update affected rows auto rsp = getResponseTask(); if (rsp != nullptr) rsp->incAffectedRows(counter); addResult(c_store); }
/** * Calculate the forward difference elements for a field line with ordered * positions. Output has length fieldline.size()-1 * TODO: Add backward and higher-order differencing */ const std::vector<float>& Fieldline::getDs() { std::vector<Point3f> VectorPositions = getPositions(); int size = getPositions().size(); //vector<Point3f> elements; for (int i = 0; i < size-1; i++) { elements.push_back(this->positions[i+1]-positions[i]); elementsMagnitudes.push_back(elements[i].magnitude()); } return elementsMagnitudes; }
void Geometry::adjustVolume(Volume & volume) { if(!_volumeCache.isEmpty()) { // use cached volume. volume.setValid(); volume.extendBy(_volumeCache); return; } GeoVectorProperty *pos = getPositions(); if(pos == NULL) return; // Node has no points, no volume _volumeCache.setValid(); PrimitiveIterator it = this->beginPrimitives(); PrimitiveIterator end = this->endPrimitives (); for(; it != end; ++it) { for(UInt32 v = 0; v < it.getLength(); ++v) { _volumeCache.extendBy(it.getPosition(v)); } } volume.extendBy(_volumeCache); }
void SpaceShip::checkCollision(Terrain terrain) { if (getY() < terrain.terrainHeight) { Point *bottomPoints = getPositions(); if (bottomPoints[3].y <= terrain.getHight(bottomPoints[3].x)) { loseGame(); } else if (abs(bottomPoints[0].y - bottomPoints[1].y) < 3) { if (bottomPoints[0].y <= terrain.getHight(bottomPoints[0].x) || bottomPoints[2].y <= terrain.getHight(bottomPoints[2].x)) { if (abs(bottomPoints[1].y - terrain.getHight(bottomPoints[1].x)) < 2) { winGame(); } else { loseGame(); } } } else { if (bottomPoints[0].y <= terrain.getHight(bottomPoints[0].x) || bottomPoints[1].y <= terrain.getHight(bottomPoints[1].x) || bottomPoints[2].y <= terrain.getHight(bottomPoints[2].x)) { loseGame(); } } } }
void Visuel::setColor(int &newColor) { for (auto &a : getPositions()) { a.second->Attributes = newColor; } }
/* Writes in numocc the number of occurrences of the substring pattern[0..length-1] in the text indexed by index. It also allocates occ (which must be freed by the caller) and writes the locations of the numocc occurrences in occ, in arbitrary order. */ int locate_PREV(void *index, uchar *pattern, uint length, uint **occ, uint *numocc){ uint integerPatterns[MAX_INTEGER_PATTERN_SIZE]; uint integerPatternSize; twcsa *wcsa=(twcsa *) index; // fprintf(stderr,"\nTO LOCATE: %s, len=%u",pattern,length); parseTextIntoIntegers(wcsa, pattern, length, integerPatterns, &integerPatternSize); if (!integerPatternSize) {*numocc=0; *occ=NULL; return 0;} //not found getPositions (index, pattern, length, integerPatterns, integerPatternSize, (uint **) occ, (uint *) numocc); {fflush(stderr); fprintf(stderr,"\n showing text on occurrences [numocc=%u]:",*numocc); uint i,n; n = (*numocc >6) ? 6 : *numocc; for (i=0; i< n; i++) { ulong pos = (*occ)[i]; fprintf(stderr,"\n\t [%u: %lu]::>",i, pos); fflush(stderr);fflush(stdout); printTextInOffset(wcsa->ct, pos,40); } } fprintf(stderr,"\n"); //fprintf(stderr,"\n** Pattern: %s appears %d times",pattern, *numocc); return 0; }
double Mapping::calculateDistanceFunction( const unsigned& ifunc, const bool& squared ){ // Calculate the distance double dd = mymap->calcDistanceFromConfiguration( ifunc, getPositions(), getPbc(), getArguments(), squared ); // Transform distance by whatever fframes[ifunc]=transformHD( dd, dfframes[ifunc] ); return fframes[ifunc]; }
// calculator void CoordinationBase::calculate() { double ncoord=0.; Tensor virial; vector<Vector> deriv(getNumberOfAtoms()); // deriv.resize(getPositions().size()); if(nl->getStride()>0 && invalidateList){ nl->update(getPositions()); } unsigned stride=comm.Get_size(); unsigned rank=comm.Get_rank(); if(serial){ stride=1; rank=0; }else{ stride=comm.Get_size(); rank=comm.Get_rank(); } for(unsigned int i=rank;i<nl->size();i+=stride) { // sum over close pairs Vector distance; unsigned i0=nl->getClosePair(i).first; unsigned i1=nl->getClosePair(i).second; if(getAbsoluteIndex(i0)==getAbsoluteIndex(i1)) continue; if(pbc){ distance=pbcDistance(getPosition(i0),getPosition(i1)); } else { distance=delta(getPosition(i0),getPosition(i1)); } double dfunc=0.; ncoord += pairing(distance.modulo2(), dfunc,i0,i1); deriv[i0] = deriv[i0] + (-dfunc)*distance ; deriv[i1] = deriv[i1] + dfunc*distance ; virial=virial+(-dfunc)*Tensor(distance,distance); } if(!serial){ comm.Sum(ncoord); if(!deriv.empty()) comm.Sum(&deriv[0][0],3*deriv.size()); comm.Sum(virial); } for(unsigned i=0;i<deriv.size();++i) setAtomsDerivatives(i,deriv[i]); setValue (ncoord); setBoxDerivatives (virial); }
void AdaptivePath::update() { double weight2 = -1.*mypathv->dx; double weight1 = 1.0 + mypathv->dx; if( weight1>1.0 ) { weight1=1.0; weight2=0.0; } else if( weight2>1.0 ) { weight1=0.0; weight2=1.0; } // Add projections to dispalcement accumulators ReferenceConfiguration* myref = getReferenceConfiguration( mypathv->iclose1 ); myref->extractDisplacementVector( getPositions(), getArguments(), mypathv->cargs, false, displacement ); getReferenceConfiguration( mypathv->iclose2 )->extractDisplacementVector( myref->getReferencePositions(), getArguments(), myref->getReferenceArguments(), false, displacement2 ); displacement.addDirection( -mypathv->dx, displacement2 ); pdisplacements[mypathv->iclose1].addDirection( weight1, displacement ); pdisplacements[mypathv->iclose2].addDirection( weight2, displacement ); // Update weight accumulators wsum[mypathv->iclose1] *= fadefact; wsum[mypathv->iclose2] *= fadefact; wsum[mypathv->iclose1] += weight1; wsum[mypathv->iclose2] += weight2; // This does the update of the path if it is time to if( (getStep()>0) && (getStep()%update_str==0) ) { wsum[fixedn[0]]=wsum[fixedn[1]]=0.; for(unsigned inode=0; inode<getNumberOfReferencePoints(); ++inode) { if( wsum[inode]>0 ) { // First displace the node by the weighted direction getReferenceConfiguration( inode )->displaceReferenceConfiguration( 1./wsum[inode], pdisplacements[inode] ); // Reset the displacement pdisplacements[inode].zeroDirection(); } } // Now ensure all the nodes of the path are equally spaced PathReparameterization myspacings( getPbc(), getArguments(), getAllReferenceConfigurations() ); myspacings.reparameterize( fixedn[0], fixedn[1], tolerance ); } if( (getStep()>0) && (getStep()%wstride==0) ) { pathfile.printf("# PATH AT STEP %d TIME %f \n", getStep(), getTime() ); std::vector<std::unique_ptr<ReferenceConfiguration>>& myconfs=getAllReferenceConfigurations(); std::vector<SetupMolInfo*> moldat=plumed.getActionSet().select<SetupMolInfo*>(); if( moldat.size()>1 ) error("you should only have one MOLINFO action in your input file"); SetupMolInfo* mymoldat=NULL; if( moldat.size()==1 ) mymoldat=moldat[0]; std::vector<std::string> argument_names( getNumberOfArguments() ); for(unsigned i=0; i<getNumberOfArguments(); ++i) argument_names[i] = getPntrToArgument(i)->getName(); PDB mypdb; mypdb.setArgumentNames( argument_names ); for(unsigned i=0; i<myconfs.size(); ++i) { pathfile.printf("REMARK TYPE=%s\n", myconfs[i]->getName().c_str() ); mypdb.setAtomPositions( myconfs[i]->getReferencePositions() ); for(unsigned j=0; j<getNumberOfArguments(); ++j) mypdb.setArgumentValue( getPntrToArgument(j)->getName(), myconfs[i]->getReferenceArgument(j) ); mypdb.print( atoms.getUnits().getLength()/0.1, mymoldat, pathfile, ofmt ); } pathfile.flush(); } }
AActor * AMapCreator::createMap(bool binary, ACameraActor * camera, AStaticMeshActor * floor) { binMap = binary; // Read Character start position getPositions(); // Adjust gridSize and meshSize different depending on if binary or not float ratio = gridSize / meshSide; // Set floor size depending on map and cell to view dimensions height = getMap().Num(); width = getMap()[0].Num(); floor->SetActorScale3D(FVector(height * ratio, width * ratio, 1)); floor->SetActorLocation(FVector((width / 2) * gridSize, (height / 2) * gridSize, -((meshSide / 2) + characterHeight))); // Center camera above the center of floor, at a distance that fits the entire field float FOV = 90; float cameraHeight = width / tan(FOV / 2); camera->SetActorLocation(floor->GetActorLocation() + FVector(0, 0, height * gridSize)); // Get MazeBlock blueprint auto cls = StaticLoadObject(UObject::StaticClass(), nullptr, TEXT("Blueprint'/Game/Blueprints/MazeBlock.MazeBlock'")); UBlueprint * bp = Cast<UBlueprint>(cls); blockBP = (UClass*)bp->GeneratedClass; // Get MazeBlock2 blueprint cls = StaticLoadObject(UObject::StaticClass(), nullptr, TEXT("Blueprint'/Game/Blueprints/MazeBlock2.MazeBlock2'")); bp = Cast<UBlueprint>(cls); blockBP2 = (UClass*)bp->GeneratedClass; // Get Character blueprint cls = StaticLoadObject(UObject::StaticClass(), nullptr, TEXT("Blueprint'/Game/Blueprints/Character.Character'")); bp = Cast<UBlueprint>(cls); TSubclassOf<class UObject> characterBP = (UClass*)bp->GeneratedClass; // Spawn objects FVector location = spawnMap(GWorld->GetWorld()); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, // FString::Printf(TEXT("{%f.2, %f.2, %f.2}"), // location.X, location.Y, location.Z)); return GWorld->GetWorld()->SpawnActor<AActor>(characterBP, location, { 0,0,0 }); }
# include <stdio.h> # include <stdlib.h> # include <time.h> int N; //For N * N ChessBoard int flag; void printArray(int a[]); /* Just to Print the Final Solution */ void getPositions(int a[], int n1, int n2); /* The Recursive Function */ int main_NQueens() { int *a; int ctr = 0; printf("\nTHE N QUEENS PROBLEM "); printf("\nNumber Of Rows(N) For NxN Chessboard."); scanf_s("%d", &N); a = (int *)(malloc(sizeof(int)*N)); printf("\nAll possible Solutions .. \n"); printf("\nIn Each of the solutions the Coordinates of the N-Queens are given (Row,Col) ."); printf("\nNote that the Rows and Colums are numbered between 1 - N :\n"); for (ctr = 0; ctr<N; ctr++) getPositions(a, 0, ctr); getchar(); getchar(); }
void VertexGenerator::Mesh2D::dumpInfo() { LOG_INFO("<-Dumpping Mesh2D information->\n"); LOG_INFO("Vertex Point Count: %d, Vertex Size: %d, TexCoords Size: %d, Byte Stride: %d\n", getVertexCount(), getVertexSize(), getTexCoordsSize(), getByteStride()); for(size_t i = 0; i < getVertexCount(); ++i) { float* position = getPositions() + getStride() * i; LOG_INFO("VertexPosition[%d]: %f, %f\n", i, *position, *(position + 1)); } for(size_t i = 0; i < getVertexCount(); ++i) { float* texCoords = getTexCoords() + getStride() * i; LOG_INFO("TexCoords[%d]: %f, %f\n", i, *texCoords, *(texCoords + 1)); } }
/** * TODO: finish documentation * @return */ Fieldline Fieldline::reverseOrder() { std::vector<float> originalVectorValues = getData(); std::vector<Point3f> originalVectorPositions = getPositions(); Fieldline reversedLine; //reversedLine.reserve() int size = originalVectorValues.size(); for (int i = 0; i < size; i++) { Point3f point = originalVectorPositions[size - i - 1]; float value = originalVectorValues[size - i - 1]; reversedLine.insertPointData(point, value); } return reversedLine; }
void FanucAdapter::gatherDeviceData() { if (!mConnected) connect(); else { getPositions(); getAxisLoad(); getSpindleLoad(); getStatus(); getMessages(); getMacros(); getPMC(); getCounts(); getToolData(); } }
void StorageService::removeDocument(QString symbol, bool cancelStoreResult) { try { Database::getInstance().db.transaction(); model->removeDocument(symbol); if(cancelStoreResult) storeResultService->cancelStoreResult(getPositions(symbol)); documentPositionService->removePositions(symbol); relatedDocumentModel->removeLinksToDocument(symbol); Database::getInstance().db.commit(); } catch(SQLException *e) { Database::getInstance().db.rollback(); MessageBox().createWarningBox("Niespodziewany błąd. \nLog: " + e->getLogFilePath()); } }
/** * TODO: finish documentation * @return */ void Fieldline::reverseOrderInPlace() { std::vector<float> originalVectorValues = getData(); std::vector<Point3f> originalVectorPositions = getPositions(); Fieldline reversedLine; int size = originalVectorValues.size(); for (int i = 0; i < size; i++) { Point3f point = originalVectorPositions[size - i - 1]; float value = originalVectorValues[size - i - 1]; //reversedLine.insertPointData(point, value); this->positions[i] = point; this->values[i] = value; } //return reversedLine; }
/* Purpose: animate the enemy missiles and the lines following them Input : a missile struct, an explosion struct, and the clock Returns: nothing, but updates the missiles current position, and updates the explosion if necessary Assume : nothing */ void processEnemyMissiles(struct missile *mis, struct explosion *exp, long clock,int speed){ if ((*mis).shortest == -1) { calculateLine(mis); } if ((*mis).currentX < (*mis).endX || (*mis).currentX > (*mis).endX) { getPositions(mis,speed); } if ((*mis).currentX == (*mis).endX || (*mis).currentY == (*mis).endY && (*mis).endX != 0) { (*mis).destroyed = TRUE; make_explosion(exp,(*mis).endX,(*mis).endY); explosion_sound(); reset_positions(&(*mis)); } }
void getPositions(int a1[], int colno, int val) { int ctr1, ctr2; a1[colno] = val; if (colno == N - 1) { printArray(a1); return; }; for (ctr1 = 0; ctr1<N;) { /* This Loop Finds Suitable Column Numbers , in the NEXT ROW */ for (ctr2 = 0; ctr2 <= colno; ctr2++) if (a1[ctr2] == ctr1 || (colno + 1 - ctr2)*(colno + 1 - ctr2) == (ctr1 - a1[ctr2])*(ctr1 - a1[ctr2])) goto miss1; getPositions(a1, colno + 1, ctr1); miss1: ctr1++; } }
void AdaptivePath::update() { double weight2 = -1.*mypathv->dx; double weight1 = 1.0 + mypathv->dx; if( weight1>1.0 ) { weight1=1.0; weight2=0.0; } else if( weight2>1.0 ) { weight1=0.0; weight2=1.0; } // Add projections to dispalcement accumulators ReferenceConfiguration* myref = getReferenceConfiguration( mypathv->iclose1 ); myref->extractDisplacementVector( getPositions(), getArguments(), mypathv->cargs, false, displacement ); getReferenceConfiguration( mypathv->iclose2 )->extractDisplacementVector( myref->getReferencePositions(), getArguments(), myref->getReferenceArguments(), false, displacement2 ); displacement.addDirection( -mypathv->dx, displacement2 ); pdisplacements[mypathv->iclose1].addDirection( weight1, displacement ); pdisplacements[mypathv->iclose2].addDirection( weight2, displacement ); // Update weight accumulators wsum[mypathv->iclose1] *= fadefact; wsum[mypathv->iclose2] *= fadefact; wsum[mypathv->iclose1] += weight1; wsum[mypathv->iclose2] += weight2; // This does the update of the path if it is time to if( (getStep()>0) && (getStep()%update_str==0) ) { wsum[fixedn[0]]=wsum[fixedn[1]]=0.; for(unsigned inode=0; inode<getNumberOfReferencePoints(); ++inode) { if( wsum[inode]>0 ) { // First displace the node by the weighted direction getReferenceConfiguration( inode )->displaceReferenceConfiguration( 1./wsum[inode], pdisplacements[inode] ); // Reset the displacement pdisplacements[inode].zeroDirection(); } } // Now ensure all the nodes of the path are equally spaced PathReparameterization myspacings( getPbc(), getArguments(), getAllReferenceConfigurations() ); myspacings.reparameterize( fixedn[0], fixedn[1], tolerance ); } if( (getStep()>0) && (getStep()%wstride==0) ) { pathfile.printf("# PATH AT STEP %d TIME %f \n", getStep(), getTime() ); std::vector<ReferenceConfiguration*>& myconfs=getAllReferenceConfigurations(); for(unsigned i=0; i<myconfs.size(); ++i) myconfs[i]->print( pathfile, ofmt, atoms.getUnits().getLength()/0.1 ); pathfile.flush(); } }
/// given a string specifying an interaction, return the /// corresponding interaction Interaction* createInteraction(const ::std::string& act) { ::std::string prefix; prefix.assign(act,0,3); DBG(10) << VAR(prefix) << ::std::endl; ::std::vector<uint> positions=getPositions(act); Interaction* result=NULL; if(prefix=="min") { result=new MinInteraction(positions); } else if (prefix=="max") { result=new MaxInteraction(positions); } else if (prefix=="mul") { result=new MulInteraction(positions); } else { DBG(10) << "unknown prefix: "<< prefix << ::std::endl; } return result; }
void MergeIndexScan::executePlanOperation() { auto left = std::dynamic_pointer_cast<const PointerCalculator>(input.getTable(0)); auto right = std::dynamic_pointer_cast<const PointerCalculator>(input.getTable(1)); storage::pos_list_t result(std::max(left->getPositions()->size(), right->getPositions()->size())); auto it = std::set_intersection(left->getPositions()->begin(), left->getPositions()->end(), right->getPositions()->begin(), right->getPositions()->end(), result.begin()); auto tmp = PointerCalculator::create(left->getActualTable(), new storage::pos_list_t(result.begin(), it)); addResult(tmp); }
/* Writes in numocc the number of occurrences of the substring pattern[0..length-1] found in the text indexed by index. */ int count (void *index, uchar *pattern, uint length, uint *numocc){ uint integerPatterns[MAX_INTEGER_PATTERN_SIZE]; uint integerPatternSize; twcsa *wcsa=(twcsa *) index; parseTextIntoIntegers(wcsa, pattern, length, integerPatterns, &integerPatternSize); //no words if (!integerPatternSize) {*numocc=0; return 0;} //not found #ifdef FREQ_VECTOR_AVAILABLE //only just one word if (integerPatternSize ==1) {*numocc= wcsa->freqs[integerPatterns[0]]; return 0;} #endif //a phrase; { uint *occs; getPositions (index, pattern, length, integerPatterns, integerPatternSize, &occs, (uint *) numocc); free(occs); } return 0; }
void RigidObject::computeBoundingBox() { _bounding_box.resize(8 * 3); Eigen::Map<const Eigen::MatrixXf> vertices_f(getPositions().data(), 3, getNPositions()); Eigen::MatrixXd vertices; vertices = vertices_f.cast<double>(); // subtract vertices mean Eigen::Vector3d mean_vertices = vertices.rowwise().mean(); vertices = vertices - mean_vertices.replicate(1, getNPositions()); // compute eigenvector covariance matrix Eigen::EigenSolver<Eigen::MatrixXd> eigen_solver(vertices * vertices.transpose()); Eigen::MatrixXd real_eigenvectors = eigen_solver.eigenvectors().real(); // rotate centered vertices with inverse eigenvector matrix vertices = real_eigenvectors.transpose() * vertices; // compute simple bounding box auto mn = vertices.rowwise().minCoeff(); auto mx = vertices.rowwise().maxCoeff(); Eigen::Matrix<double, 3, 8> bounding_box; bounding_box << mn(0), mn(0), mn(0), mn(0), mx(0), mx(0), mx(0), mx(0), mn(1), mn(1), mx(1), mx(1), mn(1), mn(1), mx(1), mx(1), mn(2), mx(2), mn(2), mx(2), mn(2), mx(2), mn(2), mx(2); // rotate and translate bounding box back to original position Eigen::Matrix3d rot_back = real_eigenvectors; Eigen::Translation<double, 3> tra_back(mean_vertices); Eigen::Transform<double, 3, Eigen::Affine> t = tra_back * rot_back; bounding_box = t * bounding_box; // convert to float Eigen::Map<Eigen::MatrixXf> bounding_box_f(_bounding_box.data(), 3, 8); bounding_box_f = bounding_box.cast<float>(); }
// =========================================================================== // method definitions // =========================================================================== void MSVTKExport::write(OutputDevice& of, SUMOTime /* timestep */) { std::vector<double> speed = getSpeed(); std::vector<double> points = getPositions(); of << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"; of << "<VTKFile type=\"PolyData\" version=\"0.1\" order=\"LittleEndian\">\n"; of << "<PolyData>\n"; of << " <Piece NumberOfPoints=\"" << speed.size() << "\" NumberOfVerts=\"1\" NumberOfLines=\"0\" NumberOfStrips=\"0\" NumberOfPolys=\"0\">\n"; of << "<PointData>\n"; of << " <DataArray type=\"Float64\" Name=\"speed\" format=\"ascii\">" << List2String(getSpeed()) << "</DataArray>\n"; of << "</PointData>\n"; of << "<CellData/>\n"; of << "<Points>\n"; of << " <DataArray type=\"Float64\" Name=\"Points\" NumberOfComponents=\"3\" format=\"ascii\">" << List2String(getPositions()) << "</DataArray>\n"; of << "</Points>\n"; of << "<Verts>\n"; of << " <DataArray type=\"Int64\" Name=\"connectivity\" format=\"ascii\">" << getOffset((int) speed.size()) << "</DataArray>\n"; of << " <DataArray type=\"Int64\" Name=\"offsets\" format=\"ascii\">" << speed.size() << "</DataArray>\n"; of << "</Verts>\n"; of << "<Lines>\n"; of << " <DataArray type=\"Int64\" Name=\"connectivity\" format=\"ascii\"/>\n"; of << " <DataArray type=\"Int64\" Name=\"offsets\" format=\"ascii\"/>\n"; of << "</Lines>\n"; of << "<Stripes>\n"; of << " <DataArray type=\"Int64\" Name=\"connectivity\" format=\"ascii\"/>\n"; of << " <DataArray type=\"Int64\" Name=\"offsets\" format=\"ascii\"/>\n"; of << "</Stripes>\n"; of << "<Polys>\n"; of << " <DataArray type=\"Int64\" Name=\"connectivity\" format=\"ascii\"/>\n"; of << " <DataArray type=\"Int64\" Name=\"offsets\" format=\"ascii\"/>\n"; of << "</Polys>\n"; of << "</Piece>\n"; of << "</PolyData>\n"; of << "</VTKFile>"; }
Fieldline Fieldline::interpolate(int option, int Npoints) { // Field line will be interpolated to fixed number given by Npoints /* * If Npoints = 3, then the first and third interpolated points (and corresponding * data) will be set equal to the first and last points of the original field line, * and the second point will correspond to the "half-way" mark along the field line as * determined by the following weighting scheme * option=1: interpolate to fixed arc length * option=2: interpolate to fixed integral * option=3: interpolate to fixed index space */ Fieldline interpolated; int size = this->positions.size(); float n = 1; //initialize index for interpolated fieldline interpolated.insertPointData(positions[0], values[0]); interpolated.nearest.push_back(0); interpolated.tlocal.push_back(0); std::cout<<"interpolation option = "<< option<<"\n"; //First get the length of the field line. Total length should be the default. /* * TODO: Create an optional (public?) length variable. This would allow for * custom maxlength, useful for open fields. * * ts=totalLength/(Npoints-1) * |0 -------------------------|ts---------------------------Length| * |P0----P1----P2--...---a----|tlocal---b------...------------Pend| * |0-----t1----t2--...---ta------------tb------...------------tend| * */ float totalLength = 0; if(option==1) { totalLength = this->length[size-1]; std::cout<<"opt=1; total length = "<< totalLength << "\n"<<std::endl; } else if(option==2) { totalLength = this->integral[size-1]; std::cout<<"opt=2; integral tot: "<< totalLength << "\n"<<std::endl; } else if(option==3) { totalLength = size-1; std::cout<<"opt=3; points in original: "<< totalLength <<"\n" << std::endl; } else { std::cout<<"interpolation option not supported!"; } float ta = 0; // initialize ta,tb float tb = 0; int flinedex = 0; float ts = 0; while(n < Npoints-1) { ts = n/(Npoints-1); // ts in [0, 1.0) if (option == 1) { ta = length[flinedex]/totalLength; tb = length[flinedex+1]/totalLength; } else if (option == 2) { ta = integral[flinedex]/totalLength; tb = integral[flinedex+1]/totalLength; } else if (option == 3) { ta = flinedex; ta = ta/totalLength; tb = flinedex+1; tb = tb/totalLength; } else { std::cout<<"interpolation option not supported"; } if ((ts > ta)&&(ts <= tb)) // interpolating parameter between current and next points of original field line { float dt = tb-ta; // get size of parametric field line step float tloc = (ts-ta)/dt; // get local interpolation step (0,1) // linear interpolation float value = values[flinedex]*(1-tloc)+values[flinedex+1]*(tloc); //interpolate data Point3f point = getPositions()[flinedex]*(1-tloc)+getPositions()[flinedex+1]*tloc; //interpolate positions interpolated.insertPointData(point, value); interpolated.nearest.push_back(flinedex); //save closest point interpolated.tlocal.push_back(tloc); //save tlocal n = n+1.0; // std::cout<<"ta, tb, ts "<<ta<<", "<<tb<<" "<<ts<<" n = "<<n<<"\n"; } else { flinedex++; //interpolant not between current and next points of original field line, increment } } // End loop // Insert end positions, data, index, interpolating parameter interpolated.insertPointData(positions[size-1], values[size-1]); interpolated.nearest.push_back(size-1); interpolated.tlocal.push_back(1.0); return interpolated; }
void SkeletonBlendedGeometry::calculatePositions(void) { if(getBaseGeometry() == NULL) { //Error SWARNING << "SkeletonBlendedGeometry::calculatePositions(): Base Geometry is NULL." << std::endl; return; } if(getPositions() == NULL) { //Error SWARNING << "SkeletonBlendedGeometry::calculatePositions(): Positions is NULL." << std::endl; return; } if(getBaseGeometry()->getPositions() == NULL) { //Error SWARNING << "SkeletonBlendedGeometry::calculatePositions(): Base Geometry Postions is NULL." << std::endl; return; } Pnt3f CalculatedPoint; Pnt3f BasePointInfluenced; Pnt3f BasePoint; Vec3f CalculatedNormal; //Reset all points GeoVectorPropertyUnrecPtr ResetPositions(dynamic_pointer_cast<GeoVectorProperty>(getBaseGeometry()->getPositions()->clone())); setPositions(ResetPositions); UInt32 WeightIndex, JointIndex, VertexIndex; //Update the Positions and Normals for(UInt32 i(0) ; i < getWeights()->size() ; ++i) { VertexIndex = getWeightIndexes()->getValue<UInt32>( 3 * i ); JointIndex = getWeightIndexes()->getValue<UInt32>((3 * i) + 1); WeightIndex = getWeightIndexes()->getValue<UInt32>((3 * i) + 2); //Get the position of this index from the base geometry getBaseGeometry()->getPositions()->getValue<Pnt3f>(BasePoint, VertexIndex); //Get the Influence matrix of this joint //Apply the influence of this joint to the position getBindTransformationDiff(JointIndex).mult(BasePoint, BasePointInfluenced); //Add the displacement to the value at this position getPositions()->getValue<Pnt3f>(CalculatedPoint, VertexIndex); //Scale the influence by the blend amount CalculatedPoint += getWeights()->getValue<Pnt1f>(WeightIndex)[0] * (BasePointInfluenced - BasePoint); getPositions()->setValue<Pnt3f>(CalculatedPoint, VertexIndex); } for(UInt32 i = 0; i < _mfParents.size(); i++) { _mfParents[i]->invalidateVolume(); } _volumeCache.setValid(); _volumeCache.setEmpty(); }
std::vector<sf::Vector2i> Rook::validPositions(const InternalBoard &board) { return getPositions(board_pos.x, board_pos.y, type, board); }
void ImageForeground::draw(DrawActionBase *, Viewport *vp) { if(getActive() == false) return; UInt16 i; for(i = 0; i < getMFPositions()->size(); i++) { if(getImages(i) != NullFC) break; } if(i == getMFPositions()->size()) // all images == NULL? return; glPushAttrib(GL_POLYGON_BIT | GL_DEPTH_BUFFER_BIT | GL_LIGHTING_BIT); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_DEPTH_TEST); glDisable(GL_COLOR_MATERIAL); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, 1, 0, 1, 0, 1); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); float vpWidth = 1.0, vpHeight = 1.0; if(vp) { // for absolute pixel position vpWidth = 1.0/vp->getPixelWidth(); vpHeight = 1.0/vp->getPixelHeight(); } for(i = 0; i < getMFPositions()->size(); i++) { ImagePtr img = getImages(i); if(img == NullFC) continue; Pnt2f p = getPositions(i); if( p[0] >= 1.0 || p[1] >= 1.0 ) glRasterPos2f(p[0]*vpWidth, p[1]*vpHeight); // absolute position else glRasterPos2f(p[0], p[1]); // relative position glDrawPixels(img->getWidth(), img->getHeight(), img->getPixelFormat(), GL_UNSIGNED_BYTE, img->getData()); } glDisable(GL_BLEND); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glPopAttrib(); }