void SimpleFluid::testVelocityField(){ //Setup a quad to draw too GL::VertexArray vao; vao.elementBuffer(quadElems); GL::VertexBuffer vbo(quad, GL::USAGE::STATIC_DRAW); //Setup program GL::Program prog("../res/shader.v.glsl", "../res/shader.f.glsl"); //Setup the attributes vao.setAttribPointer(vbo, prog.getAttribute("position"), 3, GL_FLOAT, GL_FALSE); vao.setAttribPointer(vbo, prog.getAttribute("texIn"), 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(glm::vec3) * 4)); glm::mat4 view = glm::lookAt<float>(glm::vec3(0, 0, 1), glm::vec3(0, 0, -1), glm::vec3(0, 1, 0)); //I suppose later I should pass in the window w/h for setting this properly glm::mat4 proj = glm::perspective(60.0f, static_cast<float>(window.box().w) / static_cast<float>(window.box().h), 0.1f, 100.0f); glm::mat4 model = glm::scale(0.35f, 0.35f, 1.0f); glm::mat4 mvp = proj * view * model; prog.uniformMat4x4("mvp", mvp); //Make textures to work with GL::Texture fieldA("../res/simplefluid/fluid32.png", true, SOIL_FLAG_INVERT_Y); GL::Texture fieldB("../res/simplefluid/fluid32.png", true, SOIL_FLAG_INVERT_Y); GL::Texture velocity("../res/simplefluid/right_velocity_32.png", true, SOIL_FLAG_INVERT_Y); //Output is the advection output texture, which will flip each run GL::Texture output = fieldB; //Setup our OpenCL data #ifdef CL_VERSION_1_2 cl::ImageGL imgA = tiny.imageFromTexture(CL::MEM::READ_WRITE, fieldA); cl::ImageGL imgB = tiny.imageFromTexture(CL::MEM::READ_WRITE, fieldB); cl::ImageGL imgVel = tiny.imageFromTexture(CL::MEM::READ_ONLY, velocity); #else cl::Image2DGL imgA = tiny.imageFromTexture(CL::MEM::READ_WRITE, fieldA); cl::Image2DGL imgB = tiny.imageFromTexture(CL::MEM::READ_WRITE, fieldB); cl::Image2DGL imgVel = tiny.imageFromTexture(CL::MEM::READ_ONLY, velocity); #endif std::vector<cl::Memory> glObjs; glObjs.push_back(imgA); glObjs.push_back(imgB); glObjs.push_back(imgVel); cl::Program advectProgram = tiny.loadProgram("../res/simplefluid/advectImageField.cl"); cl::Kernel advect = tiny.loadKernel(advectProgram, "advectImageField"); //We'll pick an arbitray time step for now advect.setArg(0, 1.f / 30.f); advect.setArg(1, imgVel); advect.setArg(2, imgA); advect.setArg(3, imgB); int workSize = tiny.preferredWorkSize(advect); cl::NDRange local(workSize, workSize); cl::NDRange global(dim, dim); //We use the run number to decide which field image should be input and which should be output //on even runs A is in, B is out and odd runs we flip int run = 0; Input::Init(); while (!Input::Quit()){ Input::PollEvents(); if (Input::KeyDown(SDL_SCANCODE_ESCAPE)) Input::Quit(true); //Advect the field if (run % 2 == 0 || run == 0){ advect.setArg(2, imgA); advect.setArg(3, imgB); output = fieldB; } else { advect.setArg(2, imgB); advect.setArg(3, imgA); output = fieldA; } glFinish(); tiny.mQueue.enqueueAcquireGLObjects(&glObjs); tiny.runKernel(advect, local, global); tiny.mQueue.enqueueReleaseGLObjects(&glObjs); tiny.mQueue.finish(); ++run; //RENDERING window.clear(); prog.use(); glBindVertexArray(vao); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, output); glDrawElements(GL_TRIANGLES, vao.numElements(), GL_UNSIGNED_SHORT, NULL); window.present(); } }
void approx1(Param out, const Param in, const Param pos, const float offGrid) { try { static std::once_flag compileFlags[DeviceManager::MAX_DEVICES]; static std::map<int, Program*> approxProgs; static std::map<int, Kernel*> approxKernels; int device = getActiveDeviceId(); std::call_once( compileFlags[device], [device] () { ToNum<Ty> toNum; std::ostringstream options; options << " -D Ty=" << dtype_traits<Ty>::getName() << " -D Tp=" << dtype_traits<Tp>::getName() << " -D ZERO=" << toNum(scalar<Ty>(0)); if((af_dtype) dtype_traits<Ty>::af_type == c32 || (af_dtype) dtype_traits<Ty>::af_type == c64) { options << " -D CPLX=1"; } else { options << " -D CPLX=0"; } if (std::is_same<Ty, double>::value || std::is_same<Ty, cdouble>::value) { options << " -D USE_DOUBLE"; } switch(method) { case AF_INTERP_NEAREST: options << " -D INTERP=NEAREST"; break; case AF_INTERP_LINEAR: options << " -D INTERP=LINEAR"; break; default: break; } Program prog; buildProgram(prog, approx1_cl, approx1_cl_len, options.str()); approxProgs[device] = new Program(prog); approxKernels[device] = new Kernel(*approxProgs[device], "approx1_kernel"); }); auto approx1Op = make_kernel<Buffer, const KParam, const Buffer, const KParam, const Buffer, const KParam, const float, const int> (*approxKernels[device]); NDRange local(THREADS, 1, 1); int blocksPerMat = divup(out.info.dims[0], local[0]); NDRange global(blocksPerMat * local[0] * out.info.dims[1], out.info.dims[2] * out.info.dims[3] * local[0], 1); approx1Op(EnqueueArgs(getQueue(), global, local), *out.data, out.info, *in.data, in.info, *pos.data, pos.info, offGrid, blocksPerMat); CL_DEBUG_FINISH(getQueue()); } catch (cl::Error err) { CL_TO_AF_ERROR(err); throw; } }
int CInstaller::install(const QSet<KUrl> &urls) { QSet<KUrl>::ConstIterator it(urls.begin()), end(urls.end()); bool sysInstall(false); CJobRunner *jobRunner=new CJobRunner(itsParent); CJobRunner::startDbusService(); if(!Misc::root()) { switch(KMessageBox::questionYesNoCancel(itsParent, i18n("Do you wish to install the font(s) for personal use " "(only available to you), or " "system-wide (available to all users)?"), i18n("Where to Install"), KGuiItem(i18n(KFI_KIO_FONTS_USER)), KGuiItem(i18n(KFI_KIO_FONTS_SYS)))) { case KMessageBox::No: sysInstall=true; break; case KMessageBox::Cancel: return -1; default: break; } } QSet<KUrl> instUrls; for(; it!=end; ++it) { KUrl local(KIO::NetAccess::mostLocalUrl(*it, NULL)); bool package(false); if(local.isLocalFile()) { QString localFile(local.toLocalFile()); if(Misc::isPackage(localFile)) { instUrls+=FontsPackage::extract(localFile, &itsTempDir); package=true; } } if(!package) { KUrl::List associatedUrls; CJobRunner::getAssociatedUrls(*it, associatedUrls, false, itsParent); instUrls.insert(*it); KUrl::List::Iterator aIt(associatedUrls.begin()), aEnd(associatedUrls.end()); for(; aIt!=aEnd; ++aIt) instUrls.insert(*aIt); } } if(instUrls.count()) { CJobRunner::ItemList list; QSet<KUrl>::ConstIterator it(instUrls.begin()), end(instUrls.end()); for(; it!=end; ++it) list.append(*it); return jobRunner->exec(CJobRunner::CMD_INSTALL, list, Misc::root() || sysInstall); } else return -1; }
iridium_method(File, read) { object self = local(self); FILE * f = get_file(context, self); char * buffer = read_file(context, f, local(filename)); return IR_STRING(buffer); }
DimFloat Frame::localPosition(float x, float y) { DimFloat local(x, y); this->integratePosition(this->masterlayer(), local); return local; }
int main(){ sky sky1; double Mu = M; //Mass in MeV complex <double> M_I(0,1); // Create momentum space grid std::vector<double> kmesh; std::vector<double> kweights; double const kmax = 5.0; int const kpts = 300; kmesh.resize( kpts ); kweights.resize( kpts ); GausLeg( 0., kmax, kmesh, kweights ); ////////Input Parameters of the potential (fit parameters) ///// std::string parameters_filename="Input.inp"; NuclearParameters Nu = read_nucleus_parameters( "Input/nca40.inp" ); double Ef=Nu.Ef; int lmax=6; double z0=20.0; double zp0; double A0=40.0; double tz=-0.5; int type=1; int mvolume = 4; int AsyVolume = 1; double A = 40.0; double mu = (A)/((A-1.)); if (tz>0) { zp0=1;} else {zp0=0;} double ph_gap = Nu.ph_gap; cout<<"ph_gap = "<<Nu.ph_gap<<endl; double rStart = .05; double rmax = 20.; int ham_pts = 300; double rdelt = rmax / ham_pts; vector<double> dr; dr.assign(ham_pts,rdelt); // Construct Parameters Object Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, zp0 ); // Construct Potential Object pot pottt = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p ); pot * pott = &pottt; boundRspace initiate(rmax , ham_pts , Ef, ph_gap , lmax , Nu.Z , zp0 , Nu.A , pott); double Elower = -11.61818; double Eupper = -9.4; double jj = .5; int ll = 0; int Ifine = 1; initiate.searchNonLoc( Elower, Eupper, jj, ll, Ifine); initiate.exteriorWaveFunct(ll); initiate.normalizeWF(); double tol=.01; double estart=Ef; ///// Making rmesh/// std::vector<double> rmesh_p= initiate.make_rmesh_point(); std::vector<double> rmesh= initiate.make_rmesh(); double rdelt_p = rdelt / 1.025641026; double Emax = 2*Ef; double Emin=-200.0 + Emax; //Generating the propagator double J; //Starting loop over L and J to construct the density matrix //want to start at L=3 to see what QPE I find lmax=6; for(int L=0;L<lmax+1;L++){ for(int s=0;s<2;s++){ J=L-0.5+s; if(J<0){ J=0.5; s=1; } string presky = "waves/neutron/data/ecut120/"; string jlab = sky1.jlab(J); string llab = sky1.llab(L); cout<<endl; cout<<"L = "<<L<<" J = "<<J<<endl; cout<<endl; int N = 0; double QPE = initiate.find_level(rmesh, Ef, N, L, J, tol); //cout<<" QPE = "<<QPE<<endl; //dom_nonlocal_r dom(Ef, N, L, J, rmesh, dr); matrix_t ham; ham.clear(); //change this back to QPE when needed ham = initiate.re_hamiltonian(rmesh, QPE, L, J); matrix_t nonlocal; nonlocal.clear(); nonlocal = initiate.nonlocal_ham(rmesh,QPE,L,J); /* string hamname = "waves/ham" + llab + jlab + ".txt"; ofstream fham(hamname.c_str()); double hmax=0.0; for(int i=0;i<kmesh.size();i++){ for(int j=0;j<kmesh.size();j++){ fham << ham(i,j) << " "; if(ham(i,j) > hmax){ hmax = ham(i,j); } } fham<<endl; } fham.close(); */ vector <eigen_t> hameig = initiate.real_eigvecs(ham); string ename = "waves/hameig" + llab + jlab + ".txt"; ofstream efile(ename.c_str()); cvector_t local(rmesh.size()); double enorm = 0; double fac = -1.0 / ( pott->kconstant * mu ); for(int i=0;i<rmesh.size();i++){ enorm += pow(hameig[0].second[i], 2) * rdelt; local[i] = pott->localPart(rmesh[i]); /* - 2 * fac / pow( rdelt, 2 ) - fac * L * ( L + 1 ) / pow( rmesh[i], 2 ); */ ham(i,i) -= real(local[i]); } /* ofstream hamfile("waves/ham.txt"); for(int i=0;i<rmesh.size();i++){ hamfile << ham(i,i) << endl; } hamfile.close(); */ //cout << "enorm = " << enorm << endl; //cout << "initial ham eig = " << hameig[0].first << endl; /* double kh; double kh2; double kh3; for(int i=0;i<kmesh.size();i++){ if(i%30 == 0){ cout<<"i = "<<i<<endl; } for(int j=0;j<kmesh.size();j++){ kh=0; kh2=0; kh3=0; for(int ii=0;ii<rmesh.size();ii++){ //kh += bess_mtx(i,ii) * bess_mtx(j,ii) * (2.0/M_PI) * real(local[ii]) * pow(rmesh[ii], 2) * rdelt; kh += bess_mtx(i,ii) * bess_mtx(j,ii) * (2.0/M_PI) * real(local[ii]) * rmesh[ii] * rdelt; //kh3 += bess_mtx(i,ii) * bess_mtx(j,ii) * (2.0/M_PI) * real(local[ii]) * pow(rmesh[ii], 2) * rdelt; kh3 += bess_mtx(i,ii) * bess_mtx(j,ii) * (2.0/M_PI) * real(local[ii]) * rmesh[ii] * rdelt; for(int jj=0;jj<rmesh.size();jj++){ //Assuming hamiltonian as not factors of rmesh in it kh += bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * nonlocal(ii,jj)*rmesh[ii]*rmesh[jj]*pow(rdelt,2); //kh += bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * nonlocal(ii,jj)*pow(rmesh[ii]*rmesh[jj]*rdelt,2); kh2 += bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * ham(ii,jj) * rmesh[ii] * rmesh[jj] * pow(rdelt,2); //kh2 += bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * ham(ii,jj) * pow(rmesh[ii] * rmesh[jj] *rdelt,2); kh3 += bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * ham(ii,jj) * rmesh[ii] * rmesh[jj] * pow(rdelt,2); //kh3 += bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * ham(ii,jj) * pow(rmesh[ii] * rmesh[jj] *rdelt,2); if(ii==jj){ //kh3 -= bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * real(local[ii]) * pow(rmesh[ii],2) * rdelt; kh3 -= bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * real(local[ii]) * rmesh[jj] * rdelt; } } } k_ham(i,j) = kh; k_ham2(i,j) = kh2; k_ham3(i,j) = kh3; } //adding kinetic part here k_ham(i,i) += pow(kmesh[i],2) / (2*mu); } vector <eigen_t> khameig = initiate.real_eigvecs(k_ham); vector <eigen_t> khameig2 = initiate.real_eigvecs(k_ham2); vector <eigen_t> khameig3 = initiate.real_eigvecs(k_ham3); cout << "k-space ham eig[0] = " << khameig[0].first << endl; cout << "k-space ham eig[N] = " << khameig[rmesh.size()-1].first << endl; cout << "k-space ham2 eig[0] = " << khameig2[0].first << endl; cout << "k-space ham2 eig[N] = " << khameig2[rmesh.size()-1].first << endl; cout << "k-space ham3 eig[0] = " << khameig3[0].first << endl; cout << "k-space ham3 eig[N] = " << khameig3[rmesh.size()-1].first << endl; */ int Nmax=14; if(L>1){ Nmax=13; } if(L>3){ Nmax=12; } matrix_t skyham(Nmax, Nmax); skyham.clear(); for(int N=0;N<Nmax;N++){ Nlab = sky1.Nlab(N); //opening skyrme file which gives u(r) vector<double> sky0 = sky1.read(N,L,J,presky,rmesh.size()); vector <double> expo; expo.assign(rmesh.size(),0); vector <double> wave = hameig[N].second; for(int M=0;M<Nmax;M++){ string Mlab; ostringstream convert; convert << M; Mlab = convert.str(); //opening skyrme file which gives u(r) vector<double> skyrme = sky1.read(M,L,J,presky,rmesh.size()); double proj=0; for(int i=0;i<rmesh.size();i++){ proj += wave[i]/sqrt(enorm) * skyrme[i] * rdelt; } for(int i=0;i<rmesh.size();i++){ expo[i] += proj * skyrme[i]; } //gonna do in terms of rdelt_p //ham definitely has r*r'*dr in it for(int i=0;i<rmesh.size();i++){ for(int j=0;j<rmesh.size();j++){ //skyham(N,M) += ham(i,j) * sky0[i] * skyrme[j] * pow(rmesh_p[i]/rmesh[i] * rmesh_p[j]/rmesh[j] * rdelt_p,2) / rdelt; skyham(N,M) += ham(i,j) * sky0[i] * skyrme[j] * rdelt; } //delta functions in local part get rid of one integral //assuming even the diagonal also has r*r'*dr included //skyham(N,M) += real(local[i]) * sky0[i] * skyrme[i] / pow(rmesh[i],4) / rdelt * pow(rmesh_p[i],2) * rdelt_p; skyham(N,M) += real(local[i]) * sky0[i] * skyrme[i] / pow(rmesh[i],2); } } //end loop over m string exponame = "waves/expo" + llab + jlab + Nlab + ".txt"; ofstream expofile(exponame.c_str()); double expnorm=0; for(int i=0;i<rmesh.size();i++){ expnorm += pow(expo[i],2) * rdelt; } //cout << "expnorm = "<<expnorm<<endl; double factor; if(expo[10]<0){ factor=-1.0; }else{ factor=1.0; } for(int i=0;i<rmesh.size();i++){ expofile << rmesh[i] << " " << expo[i]/rmesh[i]/sqrt(expnorm)*factor << endl; } //acting on the expanded wavefuncion with h(r,r') /*double act=0; for(int i=0;i<rmesh.size();i++){ act += ham(0,i) * expo[i]; } cout<<"act = "<<act/expo[0]<<endl; */ } //end loop over n vector <eigen_t> eig = initiate.real_eigvecs(skyham); for(int M=0;M<Nmax;M++){ cout<<"M = "<<M<<endl; string Mlab; ostringstream convert; convert << M; Mlab = convert.str(); cout<<"hameig = "<<hameig[M].first<<endl; string fname = "waves/eigvec" + llab + jlab + Mlab + ".txt"; ofstream feig(fname.c_str()); eigen_t dom_wf = initiate.find_boundstate(rmesh, Ef, M, L, J, tol); cout<<"bound energy = "<<dom_wf.first<<endl; string domname = "waves/dom" + llab + jlab + Mlab + ".txt"; ofstream domfile(domname.c_str()); double hnorm=0; for(int i=0;i<rmesh.size();i++){ hnorm += pow(hameig[M].second[i],2) * rdelt; } for(int i=0;i<rmesh.size();i++){ //domfile << rmesh[i] << " " << dom_wf.second[i]<< endl; domfile << rmesh[i] << " " << hameig[M].second[i]/rmesh[i]/sqrt(hnorm) << endl; } //the eigenvector is already normalized for(int i=0;i<Nmax;i++){ feig << eig[M].second[i] << endl; } cout << "eigval = " << eig[M].first << endl; vector<double> qpf; qpf.assign(rmesh.size(),0); for(int j=0;j<Nmax;j++){ vector<double> skyrme = sky1.read(N,L,J,presky,rmesh.size()); for(int i=0;i<rmesh.size();i++){ qpf[i] += eig[M].second[j] * skyrme[i]; } } string qpname = "waves/qp" + llab + jlab + Mlab + ".txt"; ofstream qpfile(qpname.c_str()); string oname = "waves/overlap" + llab +jlab + Mlab + ".txt"; ofstream ofile(oname.c_str()); double norm=0; double overlap=0; for(int i=0;i<rmesh.size();i++){ norm += pow(qpf[i],2) * rdelt; } double fac; if(qpf[10] < 0){ fac = -1.0; }else{ fac = 1.0; } for(int i=0;i<rmesh.size();i++){ qpfile << rmesh[i] <<" "<< qpf[i] / sqrt(norm) / rmesh[i] * fac << endl; overlap += qpf[i] / sqrt(norm) * dom_wf.second[i] * rmesh[i] * rdelt; } cout << "overlap = " << overlap << endl; } } //end loop over J } //end loop over L }
void TileRenderer::renderTile(const TilePos& tile_pos, const TilePos& tile_offset, RGBAImage& tile) { // some vars, set correct image size int block_size = state.images->getBlockImageSize(); int tile_size = state.images->getTileSize(); tile.setSize(tile_size, tile_size); // get the maximum count of water blocks // blitted about each over, until they are nearly opaque int max_water = state.images->getMaxWaterNeededOpaque(); // all visible blocks which are rendered in this tile std::set<RenderBlock> blocks; // call start method of the rendermodes for (size_t i = 0; i < rendermodes.size(); i++) rendermodes[i]->start(); // iterate over the highest blocks in the tile // we use as tile position tile_pos+tile_offset because the offset means that // we treat the tile position as tile_pos, but it's actually tile_pos+tile_offset for (TileTopBlockIterator it(tile_pos + tile_offset, block_size, tile_size); !it.end(); it.next()) { // water render behavior n1: // are we already in a row of water? bool in_water = false; // water render behavior n2: // water counter, how many water blocks are at the moment in this row? int water = 0; // the render block objects in our current block row std::set<RenderBlock> row_nodes; // then iterate over the blocks, which are on the tile at the same position, // beginning from the highest block for (BlockRowIterator block(it.current); !block.end(); block.next()) { // get current chunk position mc::ChunkPos current_chunk(block.current); // check if current chunk is not null // and if the chunk wasn't replaced in the cache (i.e. position changed) if (state.chunk == nullptr || state.chunk->getPos() != current_chunk) // get chunk if not //if (!state.world->hasChunkSection(current_chunk, block.current.y)) // continue; state.chunk = state.world->getChunk(current_chunk); if (state.chunk == nullptr) { // here is nothing (= air), // so reset state if we are in water in_water = false; continue; } // get local block position mc::LocalBlockPos local(block.current); // now get block id uint16_t id = state.chunk->getBlockID(local); // air is completely transparent so continue if (id == 0) { in_water = false; continue; } // now get the block data uint16_t data = state.chunk->getBlockData(local); // check if a rendermode hides this block bool visible = true; for (size_t i = 0; i < rendermodes.size(); i++) { if (rendermodes[i]->isHidden(block.current, id, data)) { visible = false; break; } } if (!visible) continue; bool is_water = (id == 8 || id == 9) && data == 0; if (is_water && !water_preblit) { // water render behavior n1: // render only the top sides of the water blocks // and darken the ground with the lighting data // used for lighting rendermode // if we are already in water, skip checking this water block if (is_water && in_water) continue; in_water = is_water; } else if (water_preblit) { // water render behavior n2: // render the top side of every water block // have also preblit water blocks to skip redundant alphablitting // no lighting is needed because the 'opaque-water-effect' // is created by blitting the top sides of the water blocks // one above the other if (!is_water) { // if not water, reset the counter water = 0; } else { water++; // when we have enough water in a row // we can stop searching more blocks // and replace the already added render blocks with a preblit water block if (water > max_water) { std::set<RenderBlock>::const_iterator it = row_nodes.begin(); // iterate through the render blocks in this row while (it != row_nodes.end()) { std::set<RenderBlock>::const_iterator current = it++; // check if we have reached the top most water block if (it == row_nodes.end() || (it->id != 8 && it->id != 9)) { RenderBlock top = *current; row_nodes.erase(current); // check for neighbors mc::Block south, west; south = state.getBlock(top.pos + mc::DIR_SOUTH); west = state.getBlock(top.pos + mc::DIR_WEST); bool neighbor_south = (south.id == 8 || south.id == 9); if (neighbor_south) data |= DATA_SOUTH; bool neighbor_west = (west.id == 8 || west.id == 9); if (neighbor_west) data |= DATA_WEST; // get image and replace the old render block with this top.image = state.images->getOpaqueWater(neighbor_south, neighbor_west); // don't forget the rendermodes for (size_t i = 0; i < rendermodes.size(); i++) rendermodes[i]->draw(top.image, top.pos, id, data); row_nodes.insert(top); break; } else { // water render block row_nodes.erase(current); } } break; } } } // check for special data (neighbor related) // get block image, check for transparency, create render block... data = checkNeighbors(block.current, id, data); //if (is_water && (data & DATA_WEST) && (data & DATA_SOUTH)) // continue; RGBAImage image; bool transparent = state.images->isBlockTransparent(id, data); // check for biome data if (Biome::isBiomeBlock(id, data)) image = state.images->getBiomeDependBlock(id, data, getBiomeOfBlock(block.current, state.chunk)); else image = state.images->getBlock(id, data); RenderBlock node; node.x = it.draw_x; node.y = it.draw_y; node.pos = block.current; node.image = image; node.id = id; node.data = data; // let the rendermodes do their magic with the block image for (size_t i = 0; i < rendermodes.size(); i++) rendermodes[i]->draw(node.image, node.pos, id, data); // insert into current row row_nodes.insert(node); // if this block is not transparent, then break if (!transparent) break; } // iterate through the created render blocks for (std::set<RenderBlock>::const_iterator it = row_nodes.begin(); it != row_nodes.end(); ++it) { std::set<RenderBlock>::const_iterator next = it; next++; // insert render block to if (next == row_nodes.end()) { blocks.insert(*it); } else { // skip unnecessary leaves if (it->id == 18 && next->id == 18 && (next->data & 3) == (it->data & 3)) continue; blocks.insert(*it); } } } // now blit all blocks for (std::set<RenderBlock>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) { tile.alphablit(it->image, it->x, it->y); } // call the end method of the rendermodes for (size_t i = 0; i < rendermodes.size(); i++) rendermodes[i]->end(); }
// Physics loop bool Physics::update() { updateFall(); updateMinecart(); updateEntity(); if (!enabled) { return true; } // Check if needs to be updated if (simList.empty()) { return true; } std::vector<vec> toAdd; std::vector<vec> toRem; std::set<vec> changed; clock_t starttime = clock(); LOG(INFO, "Physics", "Simulating " + dtos(simList.size()) + " items!"); uint32_t listSize = simList.size(); for (uint32_t simIt = 0; simIt < listSize; simIt++) { vec pos = simList[simIt].blocks[0].pos; // Blocks uint8_t block, meta; map->getBlock(pos, &block, &meta); simList[simIt].blocks[0].id = block; simList[simIt].blocks[0].meta = meta; bool used = false; for (int i = 0; i < 5; i++) { vec local(pos); bool falling = false; switch (i) { case 0: local += vec(0, -1, 0); // First tries to go down falling = true; break; case 1: local += vec(1, 0, 0); // Might be bad to have the 4 cardinal dir' // so predictable break; case 2: local += vec(-1, 0, 0); break; case 3: local += vec(0, 0, 1); break; case 4: local += vec(0, 0, -1); break; case 5: // local += vec(0,1,0); // Going UP break; } uint8_t newblock, newmeta; map->getBlock(pos, &block, &meta); map->getBlock(local, &newblock, &newmeta); if (!isLiquidBlock(block)) { toRem.push_back(pos); break; } if ((isWaterBlock(newblock) && isWaterBlock(block)) || (isLavaBlock(newblock) && isLavaBlock(block)) || (isLiquidBlock(block) && mayFallThrough(newblock))) { if (falling && !isLiquidBlock(newblock)) { map->setBlock(local, block, meta); changed.insert(local); map->setBlock(pos, BLOCK_AIR, 0); changed.insert(pos); toRem.push_back(pos); toAdd.push_back(local); used = true; continue; } if (falling && isLiquidBlock(newblock)) { int top = 8 - meta; int bot = 8 - newmeta; int volume = top + bot; if (volume > 8) { top = volume - 8; bot = 8; } else { top = 0; bot = volume; } int a_meta = 8 - top; int a_newmeta = 8 - bot; toAdd.push_back(local); if (a_meta == meta && a_newmeta == newmeta) { toRem.push_back(pos); toRem.push_back(local); continue; } if ((isWaterBlock(block) && a_meta < 8) || (isLavaBlock(block) && a_meta < 4)) { map->setBlock(pos, block, a_meta); changed.insert(pos); } else { map->setBlock(pos, BLOCK_AIR, 0); changed.insert(pos); } map->setBlock(local, block, a_newmeta); used = true; toAdd.push_back(local); toAdd.push_back(pos); changed.insert(pos); continue; } if (!isLiquidBlock(newblock)) { if (!falling) { if ((isWaterBlock(block) && meta == 7) || (isLavaBlock(block) && meta >= 3)) { toRem.push_back(pos); break; } } // We are spreading onto dry area. newmeta = 7; map->setBlock(local, block, newmeta); changed.insert(local); meta++; if (meta < 8) { map->setBlock(pos, block, meta); changed.insert(pos); } else { map->setBlock(pos, BLOCK_AIR, 0); changed.insert(pos); toRem.push_back(pos); } toAdd.push_back(local); used = true; continue; } if (meta < newmeta - 1 || (meta == newmeta && falling)) { newmeta --; map->setBlock(local, block, newmeta); changed.insert(local); meta ++; if (meta < 8) { map->setBlock(pos, block, meta); changed.insert(pos); } else { map->setBlock(pos, BLOCK_AIR, 0); changed.insert(pos); toRem.push_back(pos); } toAdd.push_back(local); used = true; continue; } } } if (!used) { toRem.push_back(pos); } } for (int i = int(toRem.size()) - 1; i >= 0; i--) { removeSimulation(toRem[i]); } for (size_t i = 0; i < toAdd.size(); i++) { addSimulation(toAdd[i]); } map->sendMultiBlocks(changed); //clock_t endtime = clock() - starttime; // LOG(INFO, "Physics", "Exit simulation, took " + dtos(endtime * 1000 / CLOCKS_PER_SEC) + " ms, " + dtos(simList.size()) + " items left"); return true; }
//Main Program int main() { try { std::cout<<CL_DEVICE_MAX_MEM_ALLOC_SIZE<<std::endl; //const unsigned int size_t k=4; //number of clusters to find size_t n=256*1000000; //1024; //number of data points (MUST BE MULTIPLE OF 256) size_t d=2; //dimensionality of each data point i.e. data[n][d] or n vectors of length d float *data=new float[n*d]; float *centroid=new float[k*d]; //float *dist2=new float[n*k]; //distance squared from each centroid int *clusterI=new int[n]; //index of closest cluster centroid for each point (i.e. which cluster does point belong to?) //make some random data //std::srand((unsigned int)std::time(0)); std::srand(123456); //pick a fixed seed for consistency for (int i=0; i<n*d; i++) { data[i]=(float)std::rand()/(float)RAND_MAX; //std::cout<<"data="<<data[i]<<std::endl; } //pick initial cluster points - use first k points in the data for now - need to check Witten for what the best practice is for (int i=0; i<k*d; i++) { centroid[i]=data[i]; //this is really obtuse - both arrays laid out the same way, so only have to copy k vectors of length d //std::cout<<"centroid="<<centroid[i]<<std::endl; } //OpenCL part //query for platforms cl::vector<cl::Platform> platforms; cl::Platform::get(&platforms); //get a list of devices on this platform cl::vector<cl::Device> devices; platforms[0].getDevices(CL_DEVICE_TYPE_GPU,&devices); //create a context for the devices cl::Context context(devices); //create a command queue for the first device cl::CommandQueue queue = cl::CommandQueue(context,devices[0],CL_QUEUE_PROFILING_ENABLE); //PROFILING ENABLED //create memory buffers cl::Buffer bufferD=cl::Buffer(context,CL_MEM_READ_ONLY,n*d*sizeof(float)); //data buffer cl::Buffer bufferC=cl::Buffer(context,CL_MEM_READ_ONLY,k*d*sizeof(float)); //centroid buffer //cl::Buffer bufferDS=cl::Buffer(context,CL_MEM_WRITE_ONLY,n*k*sizeof(float)); //distance squared from centroids cl::Buffer bufferClusterI=cl::Buffer(context,CL_MEM_WRITE_ONLY,n*sizeof(int)); //index of closest cluster centroid //copy the input data to the input buffers using the command queue for the first device queue.enqueueWriteBuffer(bufferD,CL_TRUE,0,n*d*sizeof(float),data); queue.enqueueWriteBuffer(bufferC,CL_TRUE,0,d*k*sizeof(float),centroid); //read the program source std::ifstream sourceFile("kmeans_kernel.cl"); std::string sourceCode(std::istreambuf_iterator<char>(sourceFile),(std::istreambuf_iterator<char>())); cl::Program::Sources source(1,std::make_pair(sourceCode.c_str(),sourceCode.length()+1)); //make program from source code cl::Program program=cl::Program(context,source); //build the program for the devices program.build(devices); //make kernel //cl::Kernel vecadd_kernel(program,"kmeans"); cl::Kernel vecadd_kernel(program,"kmeans2"); //set the kernel arguments vecadd_kernel.setArg(0,bufferD); vecadd_kernel.setArg(1,bufferC); //vecadd_kernel.setArg(2,bufferDS); //kmeans vecadd_kernel.setArg(2,bufferClusterI); //kmeans2 vecadd_kernel.setArg(3,n); vecadd_kernel.setArg(4,d); vecadd_kernel.setArg(5,k); //execute the kernel cl::NDRange global(n); cl::NDRange local(256); cl::Event timing_event; //perf //cl_int err_code; //perf queue.enqueueNDRangeKernel(vecadd_kernel,cl::NullRange,global,local,NULL,&timing_event); queue.finish(); cl_ulong gpu_starttime; cl_ulong gpu_endtime; gpu_starttime = timing_event.getProfilingInfo<CL_PROFILING_COMMAND_START>(); gpu_endtime = timing_event.getProfilingInfo<CL_PROFILING_COMMAND_END>(); double gpu_ms = 1e-6 * (gpu_endtime-gpu_starttime); //not sure where the 1e-6 came from, but AMD used 1e-9 for seconds std::cout<<"GPU kmeans time="<<gpu_ms<<" milliseconds"<<std::endl; //copy the output data back to the host //queue.enqueueReadBuffer(bufferDS,CL_TRUE,0,n*k*sizeof(float),dist2); //kmeans queue.enqueueReadBuffer(bufferClusterI,CL_TRUE,0,n*sizeof(int),clusterI); //kmeans2 //check the output - kmeans //for (int i=0; i<n; i++) { //loop through all data lines // std::cout<<"dist2 i="<<i<<" : "; // for (int c=0; c<k; c++) { //loop through all centroids and compare this line to each // float sum=0; // for (int j=0; j<d; j++) { //loop through all values on each data line (dimensionality of data points) // sum+=pow(data[i*d+j]-centroid[c*d+j],2); // } // float gpu_value = dist2[i*k+c]; // float error = gpu_value-sum; //error between this data point and centroid c location // std::cout<<error<<" "; // } // std::cout<<std::endl; //} //Do a CPU version of kmeans to check the GPU data against int *cpu_clusterI=new int[n]; LARGE_INTEGER frequency,counter1,counter2; QueryPerformanceFrequency(&frequency); //returns counts per second QueryPerformanceCounter(&counter1); kmeans_cpu(data,centroid,cpu_clusterI,n,d,k); QueryPerformanceCounter(&counter2); float t_ms=((float)(counter2.LowPart-counter1.LowPart))/(float)(frequency.LowPart)*1000; //milliseconds std::cout<<"CPU kmeans time="<<t_ms<<" milliseconds"<<std::endl; //check output - kmeans2 bool result=true; for (int i=0; i<n; i++) { //loop through all data lines int gpu_index = clusterI[i]; //cluster index as calculated by the gpu int cpu_index = cpu_clusterI[i]; //cluster index as calculated by the cpu //std::cout<<"output i="<<i<<" : "<<gpu_index<<" "<<cpu_index<<std::endl; if (gpu_index!=cpu_index) { std::cout<<"Failed: "<<"output i="<<i<<" : "<<gpu_index<<" "<<cpu_index<<std::endl; result=false; break; } } if (result) std::cout<<"Success"<<std::endl; //and don't forget to clean up here delete [] data; delete [] centroid; //delete [] dist2; delete [] clusterI; delete [] cpu_clusterI; } catch (cl::Error error) { std::cout<<error.what()<<"("<<error.err()<<")"<<std::endl; } return 0; }
std::string TrimCopy (const std::string & str) { std::string local(str); Trim(local); return local; }
/** * \brief Parses application command line and calls \ref Cfg::ConfigurationManager * to parse configuration files. * * Results are directly written to \ref Engine class. * * \retval true - Everything goes OK * \retval false - Error */ bool parseOptions (int argc, char** argv, OMW::Engine& engine, Files::ConfigurationManager& cfgMgr) { // Create a local alias for brevity namespace bpo = boost::program_options; typedef std::vector<std::string> StringsVector; bpo::options_description desc("Syntax: openmw <options>\nAllowed options"); desc.add_options() ("help", "print help message") ("version", "print version information and quit") ("data", bpo::value<Files::PathContainer>()->default_value(Files::PathContainer(), "data") ->multitoken()->composing(), "set data directories (later directories have higher priority)") ("data-local", bpo::value<std::string>()->default_value(""), "set local data directory (highest priority)") ("fallback-archive", bpo::value<StringsVector>()->default_value(StringsVector(), "fallback-archive") ->multitoken(), "set fallback BSA archives (later archives have higher priority)") ("resources", bpo::value<std::string>()->default_value("resources"), "set resources directory") ("start", bpo::value<std::string>()->default_value(""), "set initial cell") ("content", bpo::value<StringsVector>()->default_value(StringsVector(), "") ->multitoken(), "content file(s): esm/esp, or omwgame/omwaddon") ("no-sound", bpo::value<bool>()->implicit_value(true) ->default_value(false), "disable all sounds") ("script-verbose", bpo::value<bool>()->implicit_value(true) ->default_value(false), "verbose script output") ("script-all", bpo::value<bool>()->implicit_value(true) ->default_value(false), "compile all scripts (excluding dialogue scripts) at startup") ("script-all-dialogue", bpo::value<bool>()->implicit_value(true) ->default_value(false), "compile all dialogue scripts at startup") ("script-console", bpo::value<bool>()->implicit_value(true) ->default_value(false), "enable console-only script functionality") ("script-run", bpo::value<std::string>()->default_value(""), "select a file containing a list of console commands that is executed on startup") ("script-warn", bpo::value<int>()->implicit_value (1) ->default_value (1), "handling of warnings when compiling scripts\n" "\t0 - ignore warning\n" "\t1 - show warning but consider script as correctly compiled anyway\n" "\t2 - treat warnings as errors") ("script-blacklist", bpo::value<StringsVector>()->default_value(StringsVector(), "") ->multitoken(), "ignore the specified script (if the use of the blacklist is enabled)") ("script-blacklist-use", bpo::value<bool>()->implicit_value(true) ->default_value(true), "enable script blacklisting") ("load-savegame", bpo::value<std::string>()->default_value(""), "load a save game file on game startup (specify an absolute filename or a filename relative to the current working directory)") ("skip-menu", bpo::value<bool>()->implicit_value(true) ->default_value(false), "skip main menu on game startup") ("new-game", bpo::value<bool>()->implicit_value(true) ->default_value(false), "run new game sequence (ignored if skip-menu=0)") ("fs-strict", bpo::value<bool>()->implicit_value(true) ->default_value(false), "strict file system handling (no case folding)") ( "encoding", bpo::value<std::string>()-> default_value("win1252"), "Character encoding used in OpenMW game messages:\n" "\n\twin1250 - Central and Eastern European such as Polish, Czech, Slovak, Hungarian, Slovene, Bosnian, Croatian, Serbian (Latin script), Romanian and Albanian languages\n" "\n\twin1251 - Cyrillic alphabet such as Russian, Bulgarian, Serbian Cyrillic and other languages\n" "\n\twin1252 - Western European (Latin) alphabet, used by default") ("fallback", bpo::value<FallbackMap>()->default_value(FallbackMap(), "") ->multitoken()->composing(), "fallback values") ("no-grab", "Don't grab mouse cursor") ("export-fonts", bpo::value<bool>()->implicit_value(true) ->default_value(false), "Export Morrowind .fnt fonts to PNG image and XML file in current directory") ("activate-dist", bpo::value <int> ()->default_value (-1), "activation distance override"); bpo::parsed_options valid_opts = bpo::command_line_parser(argc, argv) .options(desc).allow_unregistered().run(); bpo::variables_map variables; // Runtime options override settings from all configs bpo::store(valid_opts, variables); bpo::notify(variables); if (variables.count ("help")) { std::cout << desc << std::endl; return false; } std::cout << "OpenMW version " << OPENMW_VERSION; std::string rev = OPENMW_VERSION_COMMITHASH; std::string tag = OPENMW_VERSION_TAGHASH; if (!rev.empty() && !tag.empty()) { rev = rev.substr(0, 10); std::cout << " (revision " << rev << ")"; } std::cout << std::endl; if (variables.count ("version")) return false; cfgMgr.readConfiguration(variables, desc); engine.setGrabMouse(!variables.count("no-grab")); // Font encoding settings std::string encoding(variables["encoding"].as<std::string>()); std::cout << ToUTF8::encodingUsingMessage(encoding) << std::endl; engine.setEncoding(ToUTF8::calculateEncoding(encoding)); // directory settings engine.enableFSStrict(variables["fs-strict"].as<bool>()); Files::PathContainer dataDirs(variables["data"].as<Files::PathContainer>()); std::string local(variables["data-local"].as<std::string>()); if (!local.empty()) { dataDirs.push_back(Files::PathContainer::value_type(local)); } cfgMgr.processPaths(dataDirs); engine.setDataDirs(dataDirs); // fallback archives StringsVector archives = variables["fallback-archive"].as<StringsVector>(); for (StringsVector::const_iterator it = archives.begin(); it != archives.end(); ++it) { engine.addArchive(*it); } engine.setResourceDir(variables["resources"].as<std::string>()); StringsVector content = variables["content"].as<StringsVector>(); if (content.empty()) { std::cout << "No content file given (esm/esp, nor omwgame/omwaddon). Aborting..." << std::endl; return false; } StringsVector::const_iterator it(content.begin()); StringsVector::const_iterator end(content.end()); for (; it != end; ++it) { engine.addContentFile(*it); } // startup-settings engine.setCell(variables["start"].as<std::string>()); engine.setSkipMenu (variables["skip-menu"].as<bool>(), variables["new-game"].as<bool>()); if (!variables["skip-menu"].as<bool>() && variables["new-game"].as<bool>()) std::cerr << "new-game used without skip-menu -> ignoring it" << std::endl; // scripts engine.setCompileAll(variables["script-all"].as<bool>()); engine.setCompileAllDialogue(variables["script-all-dialogue"].as<bool>()); engine.setScriptsVerbosity(variables["script-verbose"].as<bool>()); engine.setScriptConsoleMode (variables["script-console"].as<bool>()); engine.setStartupScript (variables["script-run"].as<std::string>()); engine.setWarningsMode (variables["script-warn"].as<int>()); engine.setScriptBlacklist (variables["script-blacklist"].as<StringsVector>()); engine.setScriptBlacklistUse (variables["script-blacklist-use"].as<bool>()); engine.setSaveGameFile (variables["load-savegame"].as<std::string>()); // other settings engine.setSoundUsage(!variables["no-sound"].as<bool>()); engine.setFallbackValues(variables["fallback"].as<FallbackMap>().mMap); engine.setActivationDistanceOverride (variables["activate-dist"].as<int>()); engine.enableFontExport(variables["export-fonts"].as<bool>()); return true; }
std::string ToLowerCopy (const std::string & str) { std::string local(str); ToLower(local); return local; }
void MouseTest( GLFWwindow* window, GameObjectBird *pBird, ScreenLine* pLine1, ScreenLine* pLine2, std::list<GameObject *> gameObjectList ) { // Quick and dirty test, if these work the rest do. // --> try move the mouse inside the window, click right, click left if (!pBird) return; if (pBird->bState==SLING) { pBird->pBody->SetActive(false); b2Vec2 newPos( PixelToMeter((float)slingX), PixelToMeter((float)slingY) ); pBird->pBody->SetTransform( newPos, 0.0f ); } double xpos; double ypos; static float lastXPos; static float lastYPos; // get mouse position glfwGetCursorPos( window, &xpos, &ypos); Camera *pCam = Camera::Instance(); pCam; // correct for origin double t = ypos / 600.0; ypos = 600.0 + t * (-600.0); MouseState mState = NONE; PositionState pState = UNKNOWN; GameObject* b = pBird; Matrix viewMatrix = pCam->getViewMatrix(); Matrix projMatrix = pCam->getProjMatrix(); Matrix worldMatrix = b->pGameSprite->returnWorld(); Vect vout = Vect(0.0f,0.0f,0.0f) * worldMatrix * viewMatrix * projMatrix; float zoom = vout[w]; vout[x] = vout[x]/vout[w]; vout[y] = vout[y]/vout[w]; float X = (vout[x]+1.0f)*(pCam->viewport_width/2.0f); float Y= (vout[y]+1.0f)*(pCam->viewport_height/2.0f); Vect birdPos(pBird->pos.x, pBird->pos.y,0.0f); Vect mousePos((float ) xpos,(float ) ypos, 0.0f); Vect local( X, Y, 0.0f); Vect Dist = mousePos - local; if ( Dist.mag() < (10.0f / zoom) ) { pState = INSIDE; } else { pState = OUTSIDE; } //printf("%f - %f", Dist[x],Dist[y] ); //printf(" | %f - %f", X, Y ); //xpos = xpos + Dist[x]*zoom; //ypos = ypos + Dist[y]*zoom; //printf("%f - %f ",xpos, ypos); mState = NONE; if( glfwGetMouseButton (window, GLFW_MOUSE_BUTTON_RIGHT ) == GLFW_PRESS) { mState = RIGHT; } if( glfwGetMouseButton (window, GLFW_MOUSE_BUTTON_LEFT ) == GLFW_PRESS) { mState = LEFT; } if (mState == LEFT && pBird->bState == NORMAL1) { pBird->bState = NORMAL2; pBird->onMouseAction(); } // Enter MOVING state if( mState == LEFT && pState == INSIDE) { ; pBird->bState = MOVING; pBird->pBody->SetActive(false); } // small sublty here, once moving, left dictates mode if ( pBird->bState == MOVING) { if( mState == LEFT )//this drags the bird around { /*b2Vec2 newPos( PixelToMeter((float)xpos), PixelToMeter((float)ypos) ); pBird->pBody->SetTransform( newPos, 0.0f ); pLine1->posB=B; pLine2->posB=B;*/ b2Vec2 slingPos(PixelToMeter((float)slingX), PixelToMeter((float)slingY)); b2Vec2 newPos(PixelToMeter((float)pBird->pos.x+Dist[x]*zoom), PixelToMeter((float)pBird->pos.y+Dist[y]*zoom)); b2Vec2 check(PixelToMeter((float)pBird->pos.x+Dist[x]*zoom-slingX), PixelToMeter((float)pBird->pos.y+Dist[y]*zoom - slingY)); if (check.Length() > 2) { check.Normalize(); newPos = slingPos + 2*check; } else { newPos.Set( PixelToMeter((float)pBird->pos.x+Dist[x]*zoom), PixelToMeter((float)pBird->pos.y+Dist[y]*zoom) ); } //printf("%f - %f ",newPos.x, newPos.y); pBird->pBody->SetTransform( newPos, 0.0f ); Vect2D B(MeterToPixel((float)newPos.x), MeterToPixel((float)newPos.y)); pLine1->posB=B; pLine2->posB=B; } else//this fires bird from the slingshot { b2Vec2 slingshot(PixelToMeter(slingX-pBird->pos.x), PixelToMeter(slingY-pBird->pos.y)); pBird->bState = NORMAL1; pBird->pBody->SetActive(true); float32 mag = slingshot.Length(); if (mag>2) mag=2; slingshot.Normalize(); if (pBird->pBody->GetMass()<10) mag*=20; else mag*=200; b2Vec2 vel; vel = mag * slingshot; pBird->pBody->ApplyLinearImpulse( vel, pBird->pBody->GetWorldCenter(), true ); pBird->pBody->SetActive(true); Vect2D B(slingX, slingY) ; pLine1->posB=B; pLine2->posB=B; pBird->launch(); AzulCore::clearTrails(); std::list< GameObject *>::iterator it=gameObjectList.begin(); while( it!=gameObjectList.end() ) { GameObject *pGameObj = *it++; pGameObj->damageActive=true; } } } if (pBird->bState==SLING) { pBird->pBody->SetActive(false); b2Vec2 newPos( PixelToMeter((float)slingX), PixelToMeter((float)slingY) ); pBird->pBody->SetTransform( newPos, 0.0f ); } if (pBird->bState==SLING||pBird->bState==MOVING) { AzulCore::setTargetAndSpeed((slingX), (slingY), -0.2f,0.01f); } else { AzulCore::setTargetAndSpeed(pBird->pos.x, pBird->pos.y, 0.1f,10.0f); } }
/** * \brief Parses application command line and calls \ref Cfg::ConfigurationManager * to parse configuration files. * * Results are directly written to \ref Engine class. * * \retval true - Everything goes OK * \retval false - Error */ bool parseOptions (int argc, char** argv, OMW::Engine& engine, Files::ConfigurationManager& cfgMgr) { // Create a local alias for brevity namespace bpo = boost::program_options; typedef std::vector<std::string> StringsVector; bpo::options_description desc("Syntax: openmw <options>\nAllowed options"); desc.add_options() ("help", "print help message") ("version", "print version information and quit") ("data", bpo::value<Files::PathContainer>()->default_value(Files::PathContainer(), "data") ->multitoken(), "set data directories (later directories have higher priority)") ("data-local", bpo::value<std::string>()->default_value(""), "set local data directory (highest priority)") ("fallback-archive", bpo::value<StringsVector>()->default_value(StringsVector(), "fallback-archive") ->multitoken(), "set fallback BSA archives (later archives have higher priority)") ("resources", bpo::value<std::string>()->default_value("resources"), "set resources directory") ("start", bpo::value<std::string>()->default_value("Beshara"), "set initial cell") ("master", bpo::value<StringsVector>()->default_value(StringsVector(), "") ->multitoken(), "master file(s)") ("plugin", bpo::value<StringsVector>()->default_value(StringsVector(), "") ->multitoken(), "plugin file(s)") ("anim-verbose", bpo::value<bool>()->implicit_value(true) ->default_value(false), "output animation indices files") ("debug", bpo::value<bool>()->implicit_value(true) ->default_value(false), "debug mode") ("nosound", bpo::value<bool>()->implicit_value(true) ->default_value(false), "disable all sounds") ("script-verbose", bpo::value<bool>()->implicit_value(true) ->default_value(false), "verbose script output") ("script-all", bpo::value<bool>()->implicit_value(true) ->default_value(false), "compile all scripts (excluding dialogue scripts) at startup") ("script-console", bpo::value<bool>()->implicit_value(true) ->default_value(false), "enable console-only script functionality") ("script-run", bpo::value<std::string>()->default_value(""), "select a file containing a list of console commands that is executed on startup") ("new-game", bpo::value<bool>()->implicit_value(true) ->default_value(false), "activate char gen/new game mechanics") ("fs-strict", bpo::value<bool>()->implicit_value(true) ->default_value(false), "strict file system handling (no case folding)") ( "encoding", bpo::value<std::string>()-> default_value("win1252"), "Character encoding used in OpenMW game messages:\n" "\n\twin1250 - Central and Eastern European such as Polish, Czech, Slovak, Hungarian, Slovene, Bosnian, Croatian, Serbian (Latin script), Romanian and Albanian languages\n" "\n\twin1251 - Cyrillic alphabet such as Russian, Bulgarian, Serbian Cyrillic and other languages\n" "\n\twin1252 - Western European (Latin) alphabet, used by default") ("fallback", bpo::value<FallbackMap>()->default_value(FallbackMap(), "") ->multitoken()->composing(), "fallback values") ("activate-dist", bpo::value <int> ()->default_value (-1), "activation distance override"); ; bpo::parsed_options valid_opts = bpo::command_line_parser(argc, argv) .options(desc).allow_unregistered().run(); bpo::variables_map variables; // Runtime options override settings from all configs bpo::store(valid_opts, variables); bpo::notify(variables); cfgMgr.readConfiguration(variables, desc); bool run = true; if (variables.count ("help")) { std::cout << desc << std::endl; run = false; } if (variables.count ("version")) { std::cout << "OpenMW version " << OPENMW_VERSION << std::endl; run = false; } if (!run) return false; // Font encoding settings std::string encoding(variables["encoding"].as<std::string>()); std::cout << ToUTF8::encodingUsingMessage(encoding) << std::endl; engine.setEncoding(ToUTF8::calculateEncoding(encoding)); // directory settings engine.enableFSStrict(variables["fs-strict"].as<bool>()); Files::PathContainer dataDirs(variables["data"].as<Files::PathContainer>()); std::string local(variables["data-local"].as<std::string>()); if (!local.empty()) { dataDirs.push_back(Files::PathContainer::value_type(local)); } cfgMgr.processPaths(dataDirs); engine.setDataDirs(dataDirs); // fallback archives StringsVector archives = variables["fallback-archive"].as<StringsVector>(); for (StringsVector::const_iterator it = archives.begin(); it != archives.end(); it++) { engine.addArchive(*it); } engine.setResourceDir(variables["resources"].as<std::string>()); // master and plugin StringsVector master = variables["master"].as<StringsVector>(); if (master.empty()) { std::cout << "No master file given. Assuming Morrowind.esm" << std::endl; master.push_back("Morrowind"); } StringsVector plugin = variables["plugin"].as<StringsVector>(); // Removed check for 255 files, which would be the hard-coded limit in Morrowind. // I'll keep the following variable in, maybe we can use it for something different. // Say, a feedback like "loading file x/cnt". // Commenting this out for now to silence compiler warning. //int cnt = master.size() + plugin.size(); // Prepare loading master/plugin files (i.e. send filenames to engine) for (std::vector<std::string>::size_type i = 0; i < master.size(); i++) { engine.addMaster(master[i]); } for (std::vector<std::string>::size_type i = 0; i < plugin.size(); i++) { engine.addPlugin(plugin[i]); } // startup-settings engine.setCell(variables["start"].as<std::string>()); engine.setNewGame(variables["new-game"].as<bool>()); // other settings engine.setDebugMode(variables["debug"].as<bool>()); engine.setSoundUsage(!variables["nosound"].as<bool>()); engine.setScriptsVerbosity(variables["script-verbose"].as<bool>()); engine.setCompileAll(variables["script-all"].as<bool>()); engine.setAnimationVerbose(variables["anim-verbose"].as<bool>()); engine.setFallbackValues(variables["fallback"].as<FallbackMap>().mMap); engine.setScriptConsoleMode (variables["script-console"].as<bool>()); engine.setStartupScript (variables["script-run"].as<std::string>()); engine.setActivationDistanceOverride (variables["activate-dist"].as<int>()); return true; }
void AstLevel(char plr, char prog, char crew, char ast) { int i, k, man, over = 0, temp, val; char Compat[5], cnt; i = man = Guy(plr, prog, crew, ast); cnt = 0; for (k = 0; k < 5; k++) { Compat[k] = 0; } switch (Data->P[plr].Pool[i].Compat) { case 1: if (Data->P[plr].Pool[i].CL == 2) { Compat[cnt++] = 9; } Compat[cnt++] = 10; Compat[cnt++] = 1; Compat[cnt++] = 2; if (Data->P[plr].Pool[i].CR == 2) { Compat[cnt++] = 3; } break; case 2: if (Data->P[plr].Pool[i].CL == 2) { Compat[cnt++] = 10; } Compat[cnt++] = 1; Compat[cnt++] = 2; Compat[cnt++] = 3; if (Data->P[plr].Pool[i].CR == 2) { Compat[cnt++] = 4; } break; case 3: case 4: case 5: case 6: case 7: case 8: if (Data->P[plr].Pool[i].CL == 2) { Compat[cnt++] = Data->P[plr].Pool[i].Compat - 2; } Compat[cnt++] = Data->P[plr].Pool[i].Compat - 1; Compat[cnt++] = Data->P[plr].Pool[i].Compat; Compat[cnt++] = Data->P[plr].Pool[i].Compat + 1; if (Data->P[plr].Pool[i].CR == 2) { Compat[cnt++] = Data->P[plr].Pool[i].Compat + 2; } break; case 9: if (Data->P[plr].Pool[i].CL == 2) { Compat[cnt++] = 7; } Compat[cnt++] = 8; Compat[cnt++] = 9; Compat[cnt++] = 10; if (Data->P[plr].Pool[i].CR == 2) { Compat[cnt++] = 1; } break; case 10: if (Data->P[plr].Pool[i].CL == 2) { Compat[cnt++] = 8; } Compat[cnt++] = 9; Compat[cnt++] = 10; Compat[cnt++] = 1; if (Data->P[plr].Pool[i].CR == 2) { Compat[cnt++] = 2; } break; } display::LegacySurface local(143, 74); local.copyFrom(display::graphics.legacyScreen(), 94, 38, 236, 111); ShBox(94, 38, 236, 95); InBox(98, 41, 232, 61); fill_rectangle(99, 42, 231, 60, 7 + plr * 3); display::graphics.setForegroundColor(12); draw_string(115, 48, "COMPATIBILITY"); over = 0; val = 0; for (i = 0; i < Data->P[plr].CrewCount[prog][crew]; i++) { if (man != Guy(plr, prog, crew, i)) { temp = 0; for (k = 0; k < cnt; k++) { if (Compat[k] == Data->P[plr].Pool[Guy(plr, prog, crew, i)].Compat) { temp++; } } if ((plr == 1 && Data->Def.Ast2 == 0) || (plr == 0 && Data->Def.Ast1 == 0)) { InBox(111, 66 + 9 * val, 119, 72 + 9 * val); if (temp == 0) { fill_rectangle(112, 67 + 9 * val, 118, 71 + 9 * val, 9); over++; } else { fill_rectangle(112, 67 + 9 * val, 118, 71 + 9 * val, 16); } display::graphics.setForegroundColor(1); draw_string(122, 71 + 9 * val, Data->P[plr].Pool[Guy(plr, prog, crew, i)].Name); } else if (temp == 0) { over++; } val++; } } switch (prog) { case 1: i = 16; break; case 2: i = (over == 1) ? 9 : 16; break; case 3: i = (over == 1) ? 11 : ((over == 2) ? 9 : 16) ; break; case 4: i = (over == 1) ? 11 : ((over == 2) ? 9 : 16) ; break; case 5: i = (over == 1) ? 11 : ((over >= 2) ? 9 : 16) ; break; default: i = 16; break; } // Level 2 Only if ((plr == 1 && Data->Def.Ast2 == 1) || (plr == 0 && Data->Def.Ast1 == 1)) { InBox(111, 66, 119, 72); fill_rectangle(112, 67, 118, 71, i); display::graphics.setForegroundColor(1); draw_string(122, 71, "CREW RELATIONSHIP"); } if ((plr == 1 && Data->Def.Ast2 == 2) || (plr == 0 && Data->Def.Ast1 == 2)) { display::graphics.setForegroundColor(1); draw_string(111, 71, "NO INFO AT THIS LEVEL"); } //fill_rectangle(113,53,119,57,i); // shouldn't be mood display::graphics.setForegroundColor(11); draw_string(115, 57, Data->P[plr].Pool[man].Name); // don't do this for level three draw_string(0, 0, " M: "); draw_number(0, 0, Data->P[plr].Pool[man].Mood); key = 0; if (mousebuttons) { WaitForMouseUp(); } else while (key == 0) { GetMouse(); } local.copyTo(display::graphics.legacyScreen(), 94, 38); }
redraw() { /* erase warning line if necessary */ if ((warntimer <= udcounter) && (warncount > 0)) { W_ClearArea(warnw, 5, 5, W_Textwidth * warncount, W_Textheight, backColor); warncount = 0; } if (W_FastClear) { W_ClearWindow(w); clearcount=0; clearlcount=0; } else { /* TSH 2/10/93 */ while (clearcount) { clearcount--; W_CacheClearArea(w, clearzone[0][clearcount], clearzone[1][clearcount], clearzone[2][clearcount], clearzone[3][clearcount]); } while (clearlcount) { clearlcount--; W_CacheLine(w, clearline[0][clearlcount], clearline[1][clearlcount], clearline[2][clearlcount], clearline[3][clearlcount], backColor); } W_FlushClearAreaCache(w); W_FlushLineCaches(w); while (mclearlcount){ mclearlcount--; W_CacheLine(mapw, mclearline[0][mclearlcount], mclearline[1][mclearlcount], mclearline[2][mclearlcount], mclearline[3][mclearlcount], backColor); } while (mclearpcount){ mclearpcount--; W_CachePoint(mapw, mclearpoint[0][mclearpcount], mclearpoint[1][mclearpcount], backColor); } W_FlushLineCaches(mapw); W_FlushPointCaches(mapw); } local(); /* redraw local window */ if (mapmode) map(); if (W_IsMapped(statwin)){ updateStats(); } /* need a status line but we'll make do with the bottom of the local display for now */ if(runclock) run_clock(1); /* isae */ if(record) show_record(1); if(playback) show_playback(1); if(playback && extracting) show_extracting(extracting); /* 7/27/93 BM */ /* W_Flush(); */ }
clsparseStatus extract_diagonal(cldenseVectorPrivate* pDiag, const clsparseCsrMatrixPrivate* pA, clsparseControl control) { if (!clsparseInitialized) { return clsparseNotInitialized; } //check opencl elements if (control == nullptr) { return clsparseInvalidControlObject; } assert (pA->num_rows > 0); assert (pA->num_cols > 0); assert (pA->num_nonzeros > 0); assert (pDiag->num_values == std::min(pA->num_rows, pA->num_cols)); cl_ulong wg_size = 256; cl_ulong size = pA->num_rows; cl_ulong nnz_per_row = pA->nnz_per_row(); cl_ulong wave_size = control->wavefront_size; cl_ulong subwave_size = wave_size; // adjust subwave_size according to nnz_per_row; // each wavefron will be assigned to the row of the csr matrix if(wave_size > 32) { //this apply only for devices with wavefront > 32 like AMD(64) if (nnz_per_row < 64) { subwave_size = 32; } } if (nnz_per_row < 32) { subwave_size = 16; } if (nnz_per_row < 16) { subwave_size = 8; } if (nnz_per_row < 8) { subwave_size = 4; } if (nnz_per_row < 4) { subwave_size = 2; } std::string params = std::string() + " -DSIZE_TYPE=" + OclTypeTraits<cl_ulong>::type + " -DINDEX_TYPE=" + OclTypeTraits<cl_int>::type + " -DVALUE_TYPE=" + OclTypeTraits<T>::type + " -DWG_SIZE=" + std::to_string(wg_size) + " -DWAVE_SIZE=" + std::to_string(wave_size) + " -DSUBWAVE_SIZE=" + std::to_string(subwave_size); if (inverse) params.append(" -DOP_DIAG_INVERSE"); if(typeid(T) == typeid(cl_double)) { params.append(" -DDOUBLE"); if (!control->dpfp_support) { #ifndef NDEBUG std::cerr << "Failure attempting to run double precision kernel on device without DPFP support." << std::endl; #endif return clsparseInvalidDevice; } } cl::Kernel kernel = KernelCache::get(control->queue, "matrix_utils", "extract_diagonal", params); KernelWrap kWrapper(kernel); kWrapper << size << pDiag->values << pA->rowOffsets << pA->colIndices << pA->values; cl_uint predicted = subwave_size * size; cl_uint global_work_size = wg_size * ((predicted + wg_size - 1 ) / wg_size); cl::NDRange local(wg_size); //cl::NDRange global(predicted > local[0] ? predicted : local[0]); cl::NDRange global(global_work_size > local[0] ? global_work_size : local[0]); cl_int status = kWrapper.run(control, global, local); if (status != CL_SUCCESS) { return clsparseInvalidKernelExecution; } return clsparseSuccess; }
void csrmm_nt(Param out, const Param &values, const Param &rowIdx, const Param &colIdx, const Param &rhs, const T alpha, const T beta) { bool use_alpha = (alpha != scalar<T>(1.0)); bool use_beta = (beta != scalar<T>(0.0)); // Using greedy indexing is causing performance issues on many platforms // FIXME: Figure out why bool use_greedy = false; std::string ref_name = std::string("csrmm_nt_") + std::string(dtype_traits<T>::getName()) + std::string("_") + std::to_string(use_alpha) + std::string("_") + std::to_string(use_beta) + std::string("_") + std::to_string(use_greedy); int device = getActiveDeviceId(); kc_entry_t entry = kernelCache(device, ref_name); if (entry.prog == 0 && entry.ker == 0) { std::ostringstream options; options << " -D T=" << dtype_traits<T>::getName(); options << " -D USE_ALPHA=" << use_alpha; options << " -D USE_BETA=" << use_beta; options << " -D USE_GREEDY=" << use_greedy; options << " -D THREADS_PER_GROUP=" << THREADS_PER_GROUP; if (std::is_same<T, double>::value || std::is_same<T, cdouble>::value) { options << " -D USE_DOUBLE"; } if (std::is_same<T, cfloat>::value || std::is_same<T, cdouble>::value) { options << " -D IS_CPLX=1"; } else { options << " -D IS_CPLX=0"; } const char *ker_strs[] = {csrmm_cl}; const int ker_lens[] = {csrmm_cl_len}; Program prog; buildProgram(prog, 1, ker_strs, ker_lens, options.str()); entry.prog = new Program(prog); entry.ker = new Kernel[2]; entry.ker[0] = Kernel(*entry.prog, "csrmm_nt"); // FIXME: Change this after adding another kernel entry.ker[1] = Kernel(*entry.prog, "csrmm_nt"); addKernelToCache(device, ref_name, entry); } auto csrmm_nt_kernel = entry.ker[0]; auto csrmm_nt_func = KernelFunctor<Buffer, Buffer, Buffer, Buffer, int, int, Buffer, KParam, T, T, Buffer>(csrmm_nt_kernel); NDRange local(THREADS_PER_GROUP, 1); int M = rowIdx.info.dims[0] - 1; int N = rhs.info.dims[0]; int groups_x = divup(N, local[0]); int groups_y = divup(M, REPEAT); groups_y = std::min(groups_y, MAX_CSRMM_GROUPS); NDRange global(local[0] * groups_x, local[1] * groups_y); std::vector<int> count(groups_x); cl::Buffer *counter = bufferAlloc(count.size() * sizeof(int)); getQueue().enqueueWriteBuffer( *counter, CL_TRUE, 0, count.size() * sizeof(int), (void *)count.data()); csrmm_nt_func(EnqueueArgs(getQueue(), global, local), *out.data, *values.data, *rowIdx.data, *colIdx.data, M, N, *rhs.data, rhs.info, alpha, beta, *counter); bufferFree(counter); }
/* The main control loop for the Future Missions feature. */ void Future(char plr) { /** \todo the whole Future()-function is 500 >lines and unreadable */ TRACE1("->Future(plr)"); int MisNum = 0, DuraType = 0, MaxDur = 6; int setting = -1, prev_setting = -1; display::LegacySurface local(166, 9); display::LegacySurface local2(177, 197); vh = new display::LegacySurface(240, 90); unsigned int year = Data->Year; unsigned int season = Data->Season; TRACE3("--- Setting year=Year (%d), season=Season (%d)", year, season); SetParameters(); MarsFlag = MarsInRange(year, season); JupiterFlag = JupiterInRange(year, season); SaturnFlag = SaturnInRange(year, season); while ((MisNum = FutureCheck(plr, 0)) != 5) { F1 = F2 = F3 = F4 = F5 = 0; for (int i = 0; i < 5; i++) { lock[i] = false; status[i] = 0; } keyHelpText = "k011"; helpText = "i011"; Pad = MisNum; DuraType = 0; MisType = 0; ClrFut(plr, MisNum); JointFlag = JointMissionOK(plr, MisNum); // initialize joint flag if (JointFlag == false) { F4 = 2; lock[4] = true; status[4] = 0; } DrawFuture(plr, MisType, MisNum); while (1) { key = 0; GetMouse(); prev_setting = setting; setting = -1; // SEG determines the number of control points used in creating // the B-splines for drawing the mission flight path. // The more control points, the smoother the path should // appear. if (key == '-' && SEG > 1) { SEG--; } else if (key == '+' && SEG < 500) { SEG++; } else if (key >= 65 && key < Bub_Count + 65) { setting = key - 65; } // If the mouse is over one of the Mission Step bubbles, // display the step information. for (int i = 0; i < Bub_Count; i++) { if (x >= StepBub[i].x_cor && x <= StepBub[i].x_cor + 7 && y >= StepBub[i].y_cor && y <= StepBub[i].y_cor + 7) { setting = i; break; } } if (setting >= 0) { if (prev_setting < 0) { local.copyFrom(display::graphics.legacyScreen(), 18, 186, 183, 194); } if (prev_setting != setting) { ShBox(18, 186, 183, 194); display::graphics.setForegroundColor(1); MisStep(21, 192, Mev[setting].loc); } } else if (setting < 0 && prev_setting >= 0) { local.copyTo(display::graphics.legacyScreen(), 18, 186); } if (Mis.Dur <= V[MisType].E && ((x >= 244 && y >= 5 && x <= 313 && y <= 17 && mousebuttons > 0) || key == K_ENTER)) { InBox(244, 5, 313, 17); WaitForMouseUp(); if (key > 0) { delay(300); } key = 0; OutBox(244, 5, 313, 17); // Copy the screen contents to a buffer. If the mission // requires a capsule to be assigned, a pop-up will be // created listing the options. Once the pop-up is // dismissed the screen may be redrawn from the buffer. local2.copyFrom(display::graphics.legacyScreen(), 74, 3, 250, 199); int NewType = V[MisType].X; Data->P[plr].Future[MisNum].Duration = DuraType; int Ok = HardCrewAssign(plr, MisNum, MisType, NewType); local2.copyTo(display::graphics.legacyScreen(), 74, 3); if (Ok == 1) { Data->P[plr].Future[MisNum].Duration = DuraType; break; // return to launchpad loop } else { ClrFut(plr, MisNum); continue; } } else if ((x >= 43 && y >= 74 && x <= 53 && y <= 82 && mousebuttons > 0) || key == '!') { // Duration restriction lock lock[0] = (! lock[0]); if (lock[0] == true) { InBox(43, 74, 53, 82); PlaceRX(1); F5 = (status[0] == 0) ? -1 : status[0]; } else { OutBox(43, 74, 53, 82); ClearRX(1); F5 = status[0] = 0; } WaitForMouseUp(); } else if (lock[0] != true && ((x >= 5 && y >= 49 && x <= 53 && y <= 72 && mousebuttons > 0) || key == '1')) { // Duration toggle InBox(5, 49, 53, 72); if (DuraType == MaxDur) { DuraType = 0; } else { DuraType++; } Data->P[plr].Future[MisNum].Duration = DuraType; if (DuraType == 0) { Toggle(5, 0); } else if (DuraType == 1) { Toggle(5, 1); } if (DuraType != 0) { draw_Pie(DuraType); } status[0] = DuraType; WaitForMouseUp(); display::graphics.setForegroundColor(34); OutBox(5, 49, 53, 72); } else if ((x >= 5 && y >= 74 && x <= 41 && y <= 82 && mousebuttons > 0) || (key == K_ESCAPE)) { // Reset mission selection InBox(5, 74, 41, 82); WaitForMouseUp(); MisType = 0; DuraType = F1 = F2 = F3 = F4 = F5 = 0; for (int i = 0; i < 5; i++) { lock[i] = false; status[i] = 0; } if (JointFlag == false) { F4 = 2; lock[4] = true; InBox(191, 74, 201, 82); TogBox(166, 49, 1); } else { OutBox(191, 74, 201, 82); } OutBox(5, 49, 53, 72); OutBox(43, 74, 53, 82); OutBox(80, 74, 90, 82); OutBox(117, 74, 127, 82); OutBox(154, 74, 164, 82); ClrFut(plr, MisNum); Missions(plr, 8, 37, MisType, 1); GetMinus(plr); OutBox(5, 74, 41, 82); } else if ((x >= 80 && y >= 74 && x <= 90 && y <= 82 && mousebuttons > 0) || key == '@') { // Docking restriction lock lock[1] = (! lock[1]); if (lock[1] == true) { InBox(80, 74, 90, 82); PlaceRX(2); } else { OutBox(80, 74, 90, 82); ClearRX(2); } if ((status[1] == 0) && (lock[1] == true)) { F1 = 2; } else if ((status[1] == 1) && (lock[1] == true)) { F1 = 1; } else { F1 = 0; } WaitForMouseUp(); } else if (lock[1] == false && (((x >= 55 && y >= 49 && x <= 90 && y <= 82) && mousebuttons > 0) || key == '2')) { // Docking toggle TogBox(55, 49, 1); if (status[1] == 0) { Toggle(1, 1); } else { Toggle(1, 0); } status[1] = abs(status[1] - 1); WaitForMouseUp(); TogBox(55, 49, 0); } else if ((x >= 117 && y >= 74 && x <= 127 && y <= 82 && mousebuttons > 0) || key == '#') { // EVA Restriction button lock[2] = (! lock[2]); if (lock[2] == true) { InBox(117, 74, 127, 82); PlaceRX(3); } else { OutBox(117, 74, 127, 82); ClearRX(3); } if ((status[2] == 0) && (lock[2] == true)) { F2 = 2; } else if ((status[2] == 1) && (lock[2] == true)) { F2 = 1; } else { F2 = 0; } WaitForMouseUp(); } else if (lock[2] == false && ((x >= 92 && y >= 49 && x <= 127 && y <= 82 && mousebuttons > 0) || key == '3')) { // EVA toggle TogBox(92, 49, 1); if (status[2] == 0) { Toggle(2, 1); } else { Toggle(2, 0); } status[2] = abs(status[2] - 1); WaitForMouseUp(); TogBox(92, 49, 0); } else if ((x >= 154 && y >= 74 && x <= 164 && y <= 82 && mousebuttons > 0) || key == '$') { // Lunar Module Restriction button lock[3] = (! lock[3]); if (lock[3] == true) { InBox(154, 74, 164, 82); PlaceRX(4); } else { OutBox(154, 74, 164, 82); ClearRX(4); } if ((status[3] == 0) && (lock[3] == true)) { F3 = 2; } else if ((status[3] == 1) && (lock[3] == true)) { F3 = 1; } else { F3 = 0; } WaitForMouseUp(); } else if (lock[3] == false && ((x >= 129 && y >= 49 && x <= 164 && y <= 82 && mousebuttons > 0) || key == '4')) { // LEM toggle TogBox(129, 49, 1); if (status[3] == 0) { Toggle(3, 1); } else { Toggle(3, 0); } status[3] = abs(status[3] - 1); WaitForMouseUp(); TogBox(129, 49, 0); } else if (JointFlag == true && ((x > 191 && y >= 74 && x <= 201 && y <= 82 && mousebuttons > 0) || key == '%')) { // Joint Mission Restriction button lock[4] = (! lock[4]); if (lock[4] == true) { InBox(191, 74, 201, 82); PlaceRX(5); } else { OutBox(191, 74, 201, 82); ClearRX(5); } if ((status[4] == 0) && (lock[4] == true)) { F4 = 2; } else if ((status[4] == 1) && (lock[4] == true)) { F4 = 1; } else { F4 = 0; } WaitForMouseUp(); } else if (lock[4] == false && JointFlag == true && ((x >= 166 && y >= 49 && x <= 201 && y <= 82 && mousebuttons > 0) || key == '5')) { // Joint Mission TogBox(166, 49, 1); status[4] = abs(status[4] - 1); if (status[4] == 0) { Toggle(4, 1); } else { Toggle(4, 0); } WaitForMouseUp(); TogBox(166, 49, 0); } else if ((x >= 5 && y >= 84 && x <= 16 && y <= 130 && mousebuttons > 0) || (key == UP_ARROW)) { // Scroll up among Mission Types InBox(5, 84, 16, 130); for (int i = 0; i < 50; i++) { key = 0; GetMouse(); delay(10); if (mousebuttons == 0) { MisType = UpSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; i = 51; } } // Keep scrolling while mouse/key is held down. while (mousebuttons == 1 || key == UP_ARROW) { MisType = UpSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; Missions(plr, 8, 37, MisType, 3); delay(100); key = 0; GetMouse(); } Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; OutBox(5, 84, 16, 130); } else if ((x >= 5 && y >= 132 && x < 16 && y <= 146 && mousebuttons > 0) || (key == K_SPACE)) { // Turn on Mission Steps display InBox(5, 132, 16, 146); WaitForMouseUp(); delay(50); MisType = Data->P[plr].Future[MisNum].MissionCode; assert(0 <= MisType); if (MisType != 0) { Missions(plr, 8, 37, MisType, 1); } else { Missions(plr, 8, 37, MisType, 3); } OutBox(5, 132, 16, 146); } else if ((x >= 5 && y >= 148 && x <= 16 && y <= 194 && mousebuttons > 0) || (key == DN_ARROW)) { // Scroll down among Mission Types InBox(5, 148, 16, 194); for (int i = 0; i < 50; i++) { key = 0; GetMouse(); delay(10); if (mousebuttons == 0) { MisType = DownSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; i = 51; } } // Keep scrolling while mouse/key is held down. while (mousebuttons == 1 || key == DN_ARROW) { MisType = DownSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; Missions(plr, 8, 37, MisType, 3); delay(100); key = 0; GetMouse(); } Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; OutBox(5, 148, 16, 194); } } // Input while loop } // Launch pad selection loop delete vh; vh = NULL; TRACE1("<-Future()"); }
int main(int argc, char** argv) { if (argc != 2) { std::cout << "Usage: ./pi_vocl num\n" << "\twhere num = 1, 4 or 8\n"; return EXIT_FAILURE; } int vector_size = atoi(argv[1]); // Define some vector size specific constants unsigned int ITERS, WGS; if (vector_size == 1) { ITERS = 262144; WGS = 8; } else if (vector_size == 4) { ITERS = 262144 / 4; WGS = 32; } else if (vector_size == 8) { ITERS = 262144 / 8; WGS = 64; } else { std::cerr << "Invalid vector size\n"; return EXIT_FAILURE; } // Set some default values: // Default number of steps (updated later to device preferable) unsigned int in_nsteps = INSTEPS; // Default number of iterations unsigned int niters = ITERS; unsigned int work_group_size = WGS; try { // Create context, queue and build program cl::Context context(DEVICE); cl::CommandQueue queue(context); cl::Program program(context, util::loadProgram("../pi_vocl.cl"), true); cl::Kernel kernel; // Now that we know the size of the work_groups, we can set the number of work // groups, the actual number of steps, and the step size unsigned int nwork_groups = in_nsteps/(work_group_size*niters); // Get the max work group size for the kernel pi on our device unsigned int max_size; std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>(); if (vector_size == 1) { kernel = cl::Kernel(program, "pi"); max_size = kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(devices[0]); } else if (vector_size == 4) { kernel = cl::Kernel(program, "pi_vec4"); max_size = kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(devices[0]); } else if (vector_size == 8) { kernel = cl::Kernel(program, "pi_vec8"); max_size = kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(devices[0]); } if (max_size > work_group_size) { work_group_size = max_size; nwork_groups = in_nsteps/(nwork_groups*niters); } if (nwork_groups < 1) { nwork_groups = devices[0].getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>(); work_group_size = in_nsteps/(nwork_groups*niters); } unsigned int nsteps = work_group_size * niters * nwork_groups; float step_size = 1.0f / (float) nsteps; // Vector to hold partial sum std::vector<float> h_psum(nwork_groups); std::cout << nwork_groups << " work groups of size " << work_group_size << ".\n" << nsteps << " Integration steps\n"; cl::Buffer d_partial_sums(context, CL_MEM_WRITE_ONLY, sizeof(float) * nwork_groups); // Start the timer util::Timer timer; // Execute the kernel over the entire range of our 1d input data et // using the maximum number of work group items for this device cl::NDRange global(nwork_groups * work_group_size); cl::NDRange local(work_group_size); kernel.setArg(0, niters); kernel.setArg(1, step_size); cl::LocalSpaceArg localmem = cl::Local(sizeof(float) * work_group_size); kernel.setArg(2, localmem); kernel.setArg(3, d_partial_sums); queue.enqueueNDRangeKernel(kernel, cl::NullRange, global, local); cl::copy(queue, d_partial_sums, h_psum.begin(), h_psum.end()); // Complete the sum and compute the final integral value float pi_res = 0.0; for (std::vector<float>::iterator x = h_psum.begin(); x != h_psum.end(); x++) pi_res += *x; pi_res *= step_size; // Stop the timer double rtime = static_cast<double>(timer.getTimeMilliseconds()) / 1000.; std::cout << "The calculation ran in " << rtime << " seconds\n" << " pi = " << pi_res << " for " << nsteps << " steps\n"; return EXIT_SUCCESS; } catch (cl::Error err) { std::cout << "Exception\n"; std::cerr << "ERROR: " << err.what() << "(" << err_code(err.err()) << ")" << std::endl; return EXIT_FAILURE; } }
Foam::fileName Foam::IOobject::filePath() const { if (instance().isAbsolute()) { fileName objectPath = instance()/name(); if (isFile(objectPath)) { return objectPath; } else { return fileName::null; } } else { fileName path = this->path(); fileName objectPath = path/name(); if (isFile(objectPath)) { return objectPath; } else { if ( time().processorCase() && ( instance() == time().system() || instance() == time().constant() ) ) { fileName parentObjectPath = rootPath()/time().globalCaseName() /instance()/db_.dbDir()/local()/name(); if (isFile(parentObjectPath)) { return parentObjectPath; } } if (!isDir(path)) { word newInstancePath = time().findInstancePath ( instant(instance()) ); if (newInstancePath.size()) { fileName fName ( rootPath()/caseName() /newInstancePath/db_.dbDir()/local()/name() ); if (isFile(fName)) { return fName; } } } } return fileName::null; } }
clsparseStatus csrmv_vector(const clsparseScalarPrivate* pAlpha, const clsparseCsrMatrixPrivate* pMatx, const cldenseVectorPrivate* pX, const clsparseScalarPrivate* pBeta, cldenseVectorPrivate* pY, clsparseControl control) { cl_uint nnz_per_row = pMatx->nnz_per_row(); //average nnz per row cl_uint wave_size = control->wavefront_size; cl_uint group_size = 256; // 256 gives best performance! cl_uint subwave_size = wave_size; // adjust subwave_size according to nnz_per_row; // each wavefron will be assigned to the row of the csr matrix if(wave_size > 32) { //this apply only for devices with wavefront > 32 like AMD(64) if (nnz_per_row < 64) { subwave_size = 32; } } if (nnz_per_row < 32) { subwave_size = 16; } if (nnz_per_row < 16) { subwave_size = 8; } if (nnz_per_row < 8) { subwave_size = 4; } if (nnz_per_row < 4) { subwave_size = 2; } const std::string params = std::string() + "-DINDEX_TYPE=" + OclTypeTraits<cl_int>::type + " -DVALUE_TYPE=" + OclTypeTraits<T>::type + " -DSIZE_TYPE=" + OclTypeTraits<cl_ulong>::type + " -DWG_SIZE=" + std::to_string(group_size) + " -DWAVE_SIZE=" + std::to_string(wave_size) + " -DSUBWAVE_SIZE=" + std::to_string(subwave_size); cl::Kernel kernel = KernelCache::get(control->queue, "csrmv_general", "csrmv_general", params); KernelWrap kWrapper(kernel); kWrapper << pMatx->num_rows << pAlpha->value << pAlpha->offset() << pMatx->rowOffsets << pMatx->colIndices << pMatx->values << pX->values << pX->offset() << pBeta->value << pBeta->offset() << pY->values << pY->offset(); // subwave takes care of each row in matrix; // predicted number of subwaves to be executed; cl_uint predicted = subwave_size * pMatx->num_rows; // if NVIDIA is used it does not allow to run the group size // which is not a multiplication of group_size. Don't know if that // have an impact on performance cl_uint global_work_size = group_size* ((predicted + group_size - 1 ) / group_size); cl::NDRange local(group_size); //cl::NDRange global(predicted > local[0] ? predicted : local[0]); cl::NDRange global(global_work_size > local[0] ? global_work_size : local[0]); cl_int status = kWrapper.run(control, global, local); if (status != CL_SUCCESS) { return clsparseInvalidKernelExecution; } return clsparseSuccess; }
ofVec3f BasicScreenObject::localToGlobal(float _x, float _y, float _z){ ofVec3f local(_x, _y, _z); return localToGlobal(local); }
//execute context l_thread::type_return l_thread::execute(l_call_context& context) { //lock context context.lock(); //save context register3(R_CONTEXT) = l_variable( &context ); //pc... unsigned int pc = 0; l_function& function = m_vm->function(context.get_fun_id()); l_list_command& commands = function.m_commands; //macro #define raise(str)\ {\ push_error(str, pc, (unsigned int)commands[pc].m_line);\ return T_RETURN_ERROR;\ } #define vconst(c) function.m_costants[c] #define top_size (m_top+1) //for all commands for (pc = 0; pc < commands.size(); ++pc) { //current command l_command& cmp = commands[pc]; //opcodes switch (cmp.m_op_code) { case L_JMP: pc = cmp.m_arg - 1; break; case L_RETURN: //push return if(cmp.m_arg) { //get value register3(2) = pop(); //return... return T_RETURN_VALUE; } else { //came back return T_RETURN_VOID; } //.. break; case L_IF: if(top().is_true()) { pc = cmp.m_arg - 1; } pop(); break; case L_IF0: if(top().is_false()) { pc = cmp.m_arg - 1; } pop(); break; case L_IF_OR_POP: if(top().is_true()) { pc = cmp.m_arg - 1; } else { pop(); } break; case L_IF0_OR_POP: if(top().is_false()) { pc = cmp.m_arg - 1; } else { pop(); } break; case L_PUSH: push( stack(cmp.m_arg) ); break; case L_PUSH_NULL: push( l_variable() ); break; case L_PUSH_TRUE: push( l_variable(true) ); break; case L_PUSH_FALSE: push( l_variable(false) ); break; case L_PUSHK: push( vconst(cmp.m_arg) ); break; case L_CLOSER: { //get value l_variable& call_fun = vconst(cmp.m_arg); //... if(call_fun.is_function()) { //new context register3(0) = l_closer::gc_new(get_gc()); //init context register3(0).to<l_closer>()->init(call_fun.m_value.m_fid, this, l_variable(&context)); //push context push(register3(0)); } } break; //////////////////////////////////////////////////////////// case L_ADD: if(!stack(1).add(stack(0),stack(1))) raise("not valid operation"); pop(); break; case L_MUL: if(!stack(1).mul(stack(0),stack(1))) raise("not valid operation"); pop(); break; case L_SUB: if(!stack(1).sub(stack(0),stack(1))) raise("not valid operation"); pop(); break; case L_DIV: if(!stack(1).div(stack(0),stack(1))) raise("not valid operation"); pop(); break; case L_MOD: if(!stack(1).mod(stack(0),stack(1))) raise("not valid operation"); pop(); break; case L_UNM: if(!stack(0).unm(stack(0))) raise("not valid operation"); break; //////////////////////////////////////////////////////////// case L_EQ: if(!stack(1).equal(stack(0),stack(1))) raise("not valid operation"); pop(); break; case L_NEQ: if(!stack(1).not_equal(stack(0),stack(1))) raise("not valid operation"); pop(); break; case L_RT: if(!stack(1).rt(stack(0),stack(1))) raise("not valid operation"); pop(); break; case L_RE: if(!stack(1).re(stack(0),stack(1))) raise("not valid operation"); pop(); break; case L_LT: if(!stack(1).lt(stack(0),stack(1))) raise("not valid operation"); pop(); break; case L_LE: if(!stack(1).le(stack(0),stack(1))) raise("not valid operation"); pop(); break; //////////////////////////////////////////////////////////// case L_NOT: if(!stack(0).not_value(stack(0))) raise("not valid operation"); break; case L_OR: if(!stack(1).or_value(stack(0),stack(1))) raise("not valid operation"); pop(); break; case L_AND: if(!stack(1).and_value(stack(0),stack(1))) raise("not valid operation"); pop(); break; //////////////////////////////////////////////////////////// case L_GET_GLOBAL: push( global(context,cmp.m_arg) ); break; case L_SET_GLOBAL: global(context,cmp.m_arg) = pop(); break; //////////////////////////////////////////////////////////// case L_GET_LOCAL: push( strick_local(context,cmp.m_arg) ); break; case L_SET_LOCAL: strick_local(context,cmp.m_arg) = pop(); break; //////////////////////////////////////////////////////////// case L_SET_UP_VALUE: local(context,cmp.m_arg) = pop(); break; case L_GET_UP_VALUE: push( local(context,cmp.m_arg) ); break; //////////////////////////////////////////////////////////// case L_GET_THIS: push(context.this_field()); break; case L_SET_THIS: context.this_field() = pop(); break; case L_SET_THIS_NPOP: context.this_field() = stack(cmp.m_arg); break; //////////////////////////////////////////////////////////// case L_NEW_ARRAY: { register3(0) = l_array::gc_new(get_gc()); //init ? if( cmp.m_arg > 0 ) { //types l_array* vector = register3(0).array(); //put stack into vector for(int i = cmp.m_arg-1; i >= 0; --i) { vector->operator[](i) = pop(); } } //push array (n.b. gc run...) push( register3(0) ); } break; //alloc tablet case L_NEW_TABLE: { register3(0) = l_table::gc_new(get_gc()); //init ? if( cmp.m_arg > 0 ) { //types l_table* table = register3(0).table(); //assert assert(!(cmp.m_arg % 2)); //put stack into vector for(int i = (cmp.m_arg)-1; i >= 0; i-=2) { //push key and value table->operator[](stack(1)) = stack(0); //pop value pop(); //pop key pop(); } } //push table (n.b. gc run...) push( register3(0) ); } break; case L_GET_AT_VAL: { l_variable& r_b = stack(1); const l_variable& r_c = stack(0); //try if ( r_b.is_object() ) { //is a vector if(r_b.is_array()) { //types l_array* vector = r_b.array(); //to size int size_t index = 0; //cast if( r_c.is_int() ) index= (size_t)r_c.m_value.m_i; else if( r_c.is_float() )index= (size_t)r_c.m_value.m_f; else raise( "value isn't a valid key" ); //save last get_this() = stack(1); //get stack(1) = vector->operator[](index) ; } else if(r_b.is_table()) { //types l_table* table = r_b.table(); //is a string? if(!r_c.is_string()) raise( "value isn't a valid key" ); //save last get_this() = stack(1); //get and pop value stack(1) = table->operator[](r_c); } else { raise( "value isn't a vector/table, field not available" ); } } else { raise( "value isn't a vector/table/object, field not avaliable" ); } //pop index pop(); } break; case L_SET_AT_VAL: { //get table/array l_variable& r_a = stack(2); //get index const l_variable& r_b = stack(1); //try if ( r_a.is_object() ) { //is a vector if(r_a.is_array()) { //types l_array* vector = r_a.array(); //to size int size_t index = 0; //cast if( r_b.is_int() ) index= (size_t)r_b.m_value.m_i; else if( r_b.is_float() ) index= (size_t)r_b.m_value.m_f; else raise( "value isn't a valid key" ); //get and pop value vector->operator[](index) = pop(); } else if(r_a.is_table()) { //types l_table* table = r_a.table(); //is a string? if(!r_b.is_string()) raise( "value isn't a valid key" ); //get and pop value table->operator[](r_b) = pop(); } else { raise( "value isn't a vector/table, field not available" ); } } else { //pop value pop(); } //pop index pop(); //pop array/tablet pop(); } break; //for in case L_IT: { //get index l_variable& r_a = top(); //.. //try if ( r_a.is_object() ) { //get object l_obj* this_obj = (l_obj*)r_a.m_value.m_pobj; //is a vector if(r_a.is_array()) { //types l_array* vector = r_a.array(); //pop value pop(); //push it push( vector->get_it() ); } else if (r_a.is_table()) { //types l_table* table = r_a.table(); //pop value pop(); //push it push( table->get_it() ); } else if (r_a.to<l_xrange>()) { //types l_xrange* xrange = static_cast< l_xrange* > ( this_obj ); //pop value pop(); //push it push( xrange->get_it() ); } else { raise( "this value not have a iterator" ); } } else { //pop value pop(); //.. raise( "value isn't a table/array/object, iterator not supported" ); } } break; //for of case L_FOR_IN: case L_FOR_OF: { //get index l_variable& r_it = top(); //try if ( r_it.is_iterator() ) { //types l_iterator* l_it = r_it.iterator(); //is array it if(l_it) { //else assert assert(l_it); //push it if(l_it->valid()) { if(cmp.m_op_code == L_FOR_OF) { //get next push( l_it->get() ); } else //L_FOR_IN { //get next push( l_it->get_id() ); } //next l_it->self_next(); } else { //pop iterator pop(); //and jump pc = cmp.m_arg - 1; } } else { raise( "value isn't a valid iterator" ); } } else { //pop it pop(); //and jump pc = cmp.m_arg - 1; //... raise( "value isn't an iterator" ); } } break; case L_THIS_CALL: case L_CALL: { //get index register3(0) = pop(); //get args if( register3(0).is_cfunction() ) { //return size int n_return = register3(0).m_value.m_pcfun(this,cmp.m_arg); //assert (1 return) assert(n_return <= 1); //error if(n_return<0) { raise( "native call exception" ); } else if(n_return>1) { raise( "native call can't return more than a value" ); } //pop args for(int i=0; i < cmp.m_arg; ++i) { pop(); } //if return if(n_return) push(get_return()); } else if( register3(0).is_closer() ) { //get context l_closer* closer = register3(0).to<l_closer>(); //else assert if(!closer){ assert(0); }; //new function l_function& call_fun = m_vm->function(closer->get_fun_id()); //save last context l_variable last_ctx = register3(R_CONTEXT); //new context register3(1) = l_call_context::gc_new(get_gc()); l_call_context* new_ctx = register3(1).to<l_call_context>(); //this? if(cmp.m_op_code == L_THIS_CALL) { new_ctx->this_field() = get_this(); } //init new_ctx->init(*closer); //lock context new_ctx->lock(); //n args unsigned int n_fun_args = call_fun.m_args_size; //alloc array args..? if (call_fun.m_have_args_list) { //alloc array register3(3) = l_array::gc_new(get_gc()); } //put arguments for(unsigned int arg = 0; arg != cmp.m_arg; ++arg) { if (arg < n_fun_args) { new_ctx->variable( call_fun.constant(arg) ) = pop(); } else if (call_fun.m_have_args_list) { register3(3).array()->push(pop()); } else { pop(); } } //add var list if (call_fun.m_have_args_list) { //push array new_ctx->variable( call_fun.constant(n_fun_args) ) = register3(3); //to null register3(3) = l_variable(); } //save stack long stack_top_bf_call = m_top; //execute call type_return n_return = execute(*new_ctx); //error? if(n_return==T_RETURN_ERROR) { raise( "call exception" ); } //unlock context new_ctx->unlock(); //reset last context register3(R_CONTEXT) = last_ctx; //restore stack m_top = stack_top_bf_call; //return? if(n_return == T_RETURN_VALUE) { push(register3(2)); } } else { raise( "value isn't an function" ); } //dealloc if(cmp.m_op_code == L_THIS_CALL) { get_this() = l_variable(); } } break; default: break; } } return T_RETURN_VOID; }
main() { char buff[100]; int cn, r, k, t, dt, lp, x, rx, ry; int oldx, oldy, newx, newy; int offx, offy; Point jstring(); char *getstring(); Point p; int nonstop = NONSTOP; local(); request(MOUSE); /* random number seed is derived from position of dmd layer */ srand(mouse.xy.x); request(KBD); for ( ;; ) { lp = dt = 0; if ( nonstop == 0 ) { /* ask for lp parameter */ jmoveto(Pt(0,0)); p = jstring("loops="); lp = getnum(p); jmoveto(Pt(0,0)); jstring("loops="); } if ( lp < 0 ) exit(); if ( lp == 0 ) lp = rand() % 31 + 1; if ( nonstop == 0 ) { /* ask for dt parameter */ jmoveto(Pt(0,0)); p = jstring("delta="); dt = getnum(p); jmoveto(Pt(0,0)); jstring("delta="); } if ( dt <= 0 ) dt = rand() % 358 + 1; /* clear screen */ jrectf(Jrect,F_CLR); t=0; oldx = offx = XMAX / 2; oldy = offy = YMAX / 2; cn = 1; /* draw rose */ do { t=(t+dt)%360; x=(lp*t)%360; r = Isin(x); rx=muldiv(r,XMAX-1,1024); ry=muldiv(r,YMAX-1,1024); newx = offx + muldiv(rx,Icos(t),1024) / 2; newy = offy + muldiv(ry,Isin(t),1024) / 2; jsegment(Pt(oldx,oldy),Pt(newx,newy),F_STORE); oldx=newx; oldy=newy; /* give up the CPU every 10 times around */ if ( cn++ > 10 ) { cn = 0; sleep(4); } } while ( t != 0 && (k=kbdchar()) != 'q' ) ; if ( nonstop == 1 ) { /* in nonstop mode, any key aborts */ if ( k != -1 ) exit(); /* sleep 2 seconds between random patterns */ sleep(120); } } }
bool CGUIDialogContextMenu::OnContextButton(const std::string &type, const CFileItemPtr& item, CONTEXT_BUTTON button) { // buttons that are available on both sources and autosourced items if (!item) return false; switch (button) { case CONTEXT_BUTTON_EJECT_DRIVE: return g_mediaManager.Eject(item->GetPath()); #ifdef HAS_DVD_DRIVE case CONTEXT_BUTTON_EJECT_DISC: g_mediaManager.ToggleTray(g_mediaManager.TranslateDevicePath(item->GetPath())[0]); #endif return true; default: break; } // the rest of the operations require a valid share CMediaSource *share = GetShare(type, item.get()); if (!share) return false; switch (button) { case CONTEXT_BUTTON_EDIT_SOURCE: if (CProfilesManager::GetInstance().IsMasterProfile()) { if (!g_passwordManager.IsMasterLockUnlocked(true)) return false; } else if (!g_passwordManager.IsProfileLockUnlocked()) return false; return CGUIDialogMediaSource::ShowAndEditMediaSource(type, *share); case CONTEXT_BUTTON_REMOVE_SOURCE: { if (CProfilesManager::GetInstance().IsMasterProfile()) { if (!g_passwordManager.IsMasterLockUnlocked(true)) return false; } else { if (!CProfilesManager::GetInstance().GetCurrentProfile().canWriteSources() && !g_passwordManager.IsMasterLockUnlocked(false)) return false; if (CProfilesManager::GetInstance().GetCurrentProfile().canWriteSources() && !g_passwordManager.IsProfileLockUnlocked()) return false; } // prompt user if they want to really delete the source if (!CGUIDialogYesNo::ShowAndGetInput(CVariant{751}, CVariant{750})) return false; // check default before we delete, as deletion will kill the share object std::string defaultSource(GetDefaultShareNameByType(type)); if (!defaultSource.empty()) { if (share->strName == defaultSource) ClearDefault(type); } CMediaSourceSettings::GetInstance().DeleteSource(type, share->strName, share->strPath); return true; } case CONTEXT_BUTTON_SET_DEFAULT: if (CProfilesManager::GetInstance().GetCurrentProfile().canWriteSources() && !g_passwordManager.IsProfileLockUnlocked()) return false; else if (!g_passwordManager.IsMasterLockUnlocked(true)) return false; // make share default SetDefault(type, share->strName); return true; case CONTEXT_BUTTON_CLEAR_DEFAULT: if (CProfilesManager::GetInstance().GetCurrentProfile().canWriteSources() && !g_passwordManager.IsProfileLockUnlocked()) return false; else if (!g_passwordManager.IsMasterLockUnlocked(true)) return false; // remove share default ClearDefault(type); return true; case CONTEXT_BUTTON_SET_THUMB: { if (CProfilesManager::GetInstance().GetCurrentProfile().canWriteSources() && !g_passwordManager.IsProfileLockUnlocked()) return false; else if (!g_passwordManager.IsMasterLockUnlocked(true)) return false; // setup our thumb list CFileItemList items; // add the current thumb, if available if (!share->m_strThumbnailImage.empty()) { CFileItemPtr current(new CFileItem("thumb://Current", false)); current->SetArt("thumb", share->m_strThumbnailImage); current->SetLabel(g_localizeStrings.Get(20016)); items.Add(current); } else if (item->HasArt("thumb")) { // already have a thumb that the share doesn't know about - must be a local one, so we mayaswell reuse it. CFileItemPtr current(new CFileItem("thumb://Current", false)); current->SetArt("thumb", item->GetArt("thumb")); current->SetLabel(g_localizeStrings.Get(20016)); items.Add(current); } // see if there's a local thumb for this item std::string folderThumb = item->GetFolderThumb(); if (XFILE::CFile::Exists(folderThumb)) { CFileItemPtr local(new CFileItem("thumb://Local", false)); local->SetArt("thumb", folderThumb); local->SetLabel(g_localizeStrings.Get(20017)); items.Add(local); } // and add a "no thumb" entry as well CFileItemPtr nothumb(new CFileItem("thumb://None", false)); nothumb->SetIconImage(item->GetIconImage()); nothumb->SetLabel(g_localizeStrings.Get(20018)); items.Add(nothumb); std::string strThumb; VECSOURCES shares; g_mediaManager.GetLocalDrives(shares); if (!CGUIDialogFileBrowser::ShowAndGetImage(items, shares, g_localizeStrings.Get(1030), strThumb)) return false; if (strThumb == "thumb://Current") return true; if (strThumb == "thumb://Local") strThumb = folderThumb; if (strThumb == "thumb://None") strThumb = ""; if (!share->m_ignore) { CMediaSourceSettings::GetInstance().UpdateSource(type,share->strName,"thumbnail",strThumb); CMediaSourceSettings::GetInstance().Save(); } else if (!strThumb.empty()) { // this is some sort of an auto-share, so store in the texture database CTextureDatabase db; if (db.Open()) db.SetTextureForPath(item->GetPath(), "thumb", strThumb); } CGUIMessage msg(GUI_MSG_NOTIFY_ALL,0,0,GUI_MSG_UPDATE_SOURCES); g_windowManager.SendThreadMessage(msg); return true; } case CONTEXT_BUTTON_ADD_LOCK: { // prompt user for mastercode when changing lock settings) only for default user if (!g_passwordManager.IsMasterLockUnlocked(true)) return false; std::string strNewPassword = ""; if (!CGUIDialogLockSettings::ShowAndGetLock(share->m_iLockMode,strNewPassword)) return false; // password entry and re-entry succeeded, write out the lock data share->m_iHasLock = 2; CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "lockcode", strNewPassword); strNewPassword = StringUtils::Format("%i", share->m_iLockMode); CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "lockmode", strNewPassword); CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "badpwdcount", "0"); CMediaSourceSettings::GetInstance().Save(); CGUIMessage msg(GUI_MSG_NOTIFY_ALL,0,0,GUI_MSG_UPDATE_SOURCES); g_windowManager.SendThreadMessage(msg); return true; } case CONTEXT_BUTTON_RESET_LOCK: { // prompt user for profile lock when changing lock settings if (!g_passwordManager.IsMasterLockUnlocked(true)) return false; CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "badpwdcount", "0"); CMediaSourceSettings::GetInstance().Save(); CGUIMessage msg(GUI_MSG_NOTIFY_ALL,0,0,GUI_MSG_UPDATE_SOURCES); g_windowManager.SendThreadMessage(msg); return true; } case CONTEXT_BUTTON_REMOVE_LOCK: { if (!g_passwordManager.IsMasterLockUnlocked(true)) return false; if (!CGUIDialogYesNo::ShowAndGetInput(CVariant{12335}, CVariant{750})) return false; share->m_iHasLock = 0; CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "lockmode", "0"); CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "lockcode", "0"); CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "badpwdcount", "0"); CMediaSourceSettings::GetInstance().Save(); CGUIMessage msg(GUI_MSG_NOTIFY_ALL,0,0,GUI_MSG_UPDATE_SOURCES); g_windowManager.SendThreadMessage(msg); return true; } case CONTEXT_BUTTON_REACTIVATE_LOCK: { bool maxRetryExceeded = false; if (CServiceBroker::GetSettings().GetInt(CSettings::SETTING_MASTERLOCK_MAXRETRIES) != 0) maxRetryExceeded = (share->m_iBadPwdCount >= CServiceBroker::GetSettings().GetInt(CSettings::SETTING_MASTERLOCK_MAXRETRIES)); if (!maxRetryExceeded) { // don't prompt user for mastercode when reactivating a lock g_passwordManager.LockSource(type, share->strName, true); return true; } return false; } case CONTEXT_BUTTON_CHANGE_LOCK: { if (!g_passwordManager.IsMasterLockUnlocked(true)) return false; std::string strNewPW; std::string strNewLockMode; if (CGUIDialogLockSettings::ShowAndGetLock(share->m_iLockMode,strNewPW)) strNewLockMode = StringUtils::Format("%i",share->m_iLockMode); else return false; // password ReSet and re-entry succeeded, write out the lock data CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "lockcode", strNewPW); CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "lockmode", strNewLockMode); CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "badpwdcount", "0"); CMediaSourceSettings::GetInstance().Save(); CGUIMessage msg(GUI_MSG_NOTIFY_ALL,0,0,GUI_MSG_UPDATE_SOURCES); g_windowManager.SendThreadMessage(msg); return true; } default: break; } return false; }
int main(int argc, char *argv[]) { if(argc <= 3) { std::cout << "Wrong arguments, please provide config file, raw input file and number of packets." << std::endl; std::cout << argv[0] << " config.xml input.raw <npackets>" << std::endl; return 1; } const std::string configFilename(realpath(argv[1], NULL)); const std::string inputFilename(realpath(argv[2], NULL)); const unsigned long numevents = std::atol(argv[3]); // load events buffer PacketLib::PacketBufferV events(configFilename, inputFilename); events.load(); PacketLib::PacketStream ps(configFilename.c_str()); CTAConfig::CTAMDArray array_conf; std::cout << "Preloading.." << std::endl; array_conf.loadConfig("AARPROD2", "PROD2_telconfig.fits.gz", "Aar.conf", "conf/"); std::cout << "Load complete!" << std::endl; std::chrono::time_point<std::chrono::system_clock> start, end; unsigned long event_count = 0, event_size = 0; std::vector<cl::Platform> platforms; cl::Platform::get(&platforms); for(unsigned int i=0; i<platforms.size(); i++) { cl::Platform platform = platforms[i]; std::cout << "----------------------------" << std::endl; std::cout << "Platform " << i << " info:" << std::endl; std::string info; platform.getInfo(CL_PLATFORM_NAME, &info); std::cout << info << std::endl; platform.getInfo(CL_PLATFORM_VERSION, &info); std::cout << info << std::endl; platform.getInfo(CL_PLATFORM_VENDOR, &info); std::cout << info << std::endl; } std::vector<cl::Device> devices; platforms[0].getDevices(CL_DEVICE_TYPE_ALL, &devices); std::cout << "Using platform 0." << std::endl; for(unsigned int i=0; i<devices.size(); i++) { cl::Device device = devices[i]; std::cout << "----------------------------" << std::endl; std::cout << "Device " << i << " info:" << std::endl; std::string info; device.getInfo(CL_DEVICE_NAME, &info); std::cout << info << std::endl; device.getInfo(CL_DEVICE_VENDOR, &info); std::cout << info << std::endl; device.getInfo(CL_DEVICE_VERSION, &info); std::cout << info << std::endl; device.getInfo(CL_DRIVER_VERSION, &info); std::cout << info << std::endl; } std::cout << "Using device 0." << std::endl; cl::Context context(devices); cl::CommandQueue queue(context, devices[0], 0, NULL); std::string source = loadProgram("extract_wave.cl"); cl::Program::Sources sources(1, std::make_pair(source.c_str(), source.length())); cl::Program program(context, sources); program.build(devices); cl::Kernel koWaveextract(program, "waveextract"); ::size_t workgroupSize = koWaveextract.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(devices[0]); start = std::chrono::system_clock::now(); while(event_count++ < numevents) { PacketLib::ByteStreamPtr event = events.getNext(); event_size += event->size(); /// swap if the stream has a different endianity #ifdef ARCH_BIGENDIAN if(!event->isBigendian()) event->swapWord(); #else if(event->isBigendian()) event->swapWord(); #endif /// decoding packetlib packet PacketLib::Packet *packet = ps.getPacket(event); /// get telescope id PacketLib::DataFieldHeader* dfh = packet->getPacketDataFieldHeader(); const unsigned int telescopeID = dfh->getFieldValue_16ui("TelescopeID"); /// get the waveforms PacketLib::byte* buff = packet->getData()->getStream(); PacketLib::dword buffSize = packet->getData()->size(); /// get npixels and nsamples from ctaconfig using the telescopeID CTAConfig::CTAMDTelescopeType* teltype = array_conf.getTelescope(telescopeID)->getTelescopeType(); int telTypeSim = teltype->getID(); const unsigned int npixels = teltype->getCameraType()->getNpixels(); const unsigned int nsamples = teltype->getCameraType()->getPixel(0)->getPixelType()->getNSamples(); #ifdef DEBUG std::cout << workgroupSize << std::endl; std::cout << npixels << std::endl; #endif // compute waveform extraction cl::Buffer waveCLBuffer(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, buffSize, buff, NULL); std::vector<unsigned short> maxres(npixels); std::vector<unsigned short> timeres(npixels); cl::Buffer maxresCLBuffer(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, npixels*sizeof(unsigned short), maxres.data(), NULL); cl::Buffer timeresCLBuffer(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, npixels*sizeof(unsigned short), timeres.data(), NULL); koWaveextract.setArg(0, waveCLBuffer); koWaveextract.setArg(1, npixels); koWaveextract.setArg(2, nsamples); koWaveextract.setArg(3, 6); koWaveextract.setArg(4, maxresCLBuffer); koWaveextract.setArg(5, timeresCLBuffer); queue.enqueueMapBuffer(waveCLBuffer, CL_FALSE, CL_MAP_WRITE, 0, buffSize); queue.enqueueMapBuffer(maxresCLBuffer, CL_FALSE, CL_MAP_READ, 0, npixels); queue.enqueueMapBuffer(timeresCLBuffer, CL_FALSE, CL_MAP_READ, 0, npixels); cl::NDRange global(npixels); cl::NDRange local(1); queue.enqueueNDRangeKernel(koWaveextract, cl::NullRange, global, local); queue.finish(); #ifdef DEBUG std::cout << "npixels = " << npixels << std::endl; std::cout << "nsamples = " << nsamples << std::endl; for(int pixel = 0; pixel<npixels; pixel++) { PacketLib::word* s = (PacketLib::word*) buff + pixel * nsamples; std::cout << "pixel " << pixel << " samples "; for(int k=0; k<nsamples; k++) { std::cout << s[k] << " "; } std::cout << std::endl; std::cout << "result " << " " << maxres[pixel] << " " << timeres[pixel] << " " << std::endl; } #endif } end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed = end-start; double throughput = event_count / elapsed.count(); double mbytes = (event_size / 1000000) / elapsed.count(); std::cout << event_count << " events sent in " << elapsed.count() << " s" << std::endl; std::cout << "mean event size: " << event_size / event_count << " B" << std::endl; std::cout << "throughput: " << throughput << " event/s = " << mbytes << " MB/s" << std::endl; return 0; }
int main(int argc, const char* argv[]) { {{ // set primitive value CSeq_id obj; CObjectInfo info(ObjectInfo(obj)); CObjectInfo local(info.SetChoiceVariant(info.FindVariantIndex("local"))); local.SetChoiceVariant(local.FindVariantIndex("id")).SetPrimitiveValueInt(234); cout << MSerial_AsnText << obj; }} {{ CSeq_loc obj; CObjectInfo info(ObjectInfo(obj)); // set choice variant info.SetChoiceVariant(info.FindVariantIndex("null")); cout << MSerial_AsnText << obj; // change choice variant CObjectInfo seqid(info.SetChoiceVariant(info.FindVariantIndex("empty"))); CObjectInfo local(seqid.SetChoiceVariant(seqid.FindVariantIndex("local"))); local.SetChoiceVariant(local.FindVariantIndex("id")).SetPrimitiveValueInt(987); cout << MSerial_AsnText << obj; // there is no way to reset choice variant // this does not work: //info.SetChoiceVariant(0); }} {{ CSeq_id_set obj; CObjectInfo info(ObjectInfo(obj)); // 'implicit' class has one member with no name CObjectInfo mem(info.SetClassMember(1)); // add container element CObjectInfo elem(mem.AddNewPointedElement()); CObjectInfo local(elem.SetChoiceVariant(elem.FindVariantIndex("local"))); local.SetChoiceVariant(local.FindVariantIndex("id")).SetPrimitiveValueInt(345); // add container element elem = mem.AddNewPointedElement(); local = elem.SetChoiceVariant(elem.FindVariantIndex("local")); local.SetChoiceVariant(local.FindVariantIndex("str")).SetPrimitiveValueString("345string"); // add container element elem = mem.AddNewPointedElement(); CObjectInfo prf = elem.SetChoiceVariant(elem.FindVariantIndex("prf")); prf.SetClassMember(prf.FindMemberIndex("name")).SetPrimitiveValueString("prfname"); prf.SetClassMember(prf.FindMemberIndex("release")).SetPrimitiveValueString("prfrelease"); prf.SetClassMember(prf.FindMemberIndex("version")).SetPrimitiveValueInt(567); cout << MSerial_AsnText << obj; // unset class member // only optional members can be unset if (prf.FindClassMember("version").IsSet()) { prf.FindClassMember("version").Reset(); } cout << MSerial_AsnText << obj; }} return 0; }
void liveAdvectTexture(){ Window::init(); Window window("Realtime Texture Advection"); //Set an fps cap const float FPS = 60.0f; //Setup a quad to draw too GL::VertexArray vao; vao.elementBuffer(quadElems); GL::VertexBuffer vbo(quad, GL::USAGE::STATIC_DRAW); //Setup program GL::Program prog("../res/shader.v.glsl", "../res/shader.f.glsl"); //Setup the attributes vao.setAttribPointer(vbo, prog.getAttribute("position"), 3, GL_FLOAT, GL_FALSE); vao.setAttribPointer(vbo, prog.getAttribute("texIn"), 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(glm::vec3) * 4)); glm::mat4 view = glm::lookAt<float>(glm::vec3(0, 0, 1), glm::vec3(0, 0, -1), glm::vec3(0, 1, 0)); glm::mat4 proj = glm::perspective(60.0f, (float)(window.box().w) / (float)(window.box().h), 0.1f, 100.0f); glm::mat4 model = glm::scale(0.55f, 0.55f, 1.0f); glm::mat4 mvp = proj * view * model; prog.uniformMat4x4("mvp", mvp); /* * I don't think OpenCL or OpenGL provide a simple method for copying images/textures so * instead we'll flip the in/out image each step and draw the out image by setting active = out */ //Make textures to work with GL::Texture texA("../res/map.png", true, SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB); GL::Texture texB("../res/blank.png", true, SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB); //Active is the actual texture we will draw GL::Texture active = texB; //Setup our OpenCL context + program and kernel CL::TinyCL tiny(CL::DEVICE::GPU, true); cl::Program program = tiny.loadProgram("../res/simpleAdvect.cl"); cl::Kernel kernel = tiny.loadKernel(program, "simpleAdvect"); //Setup our OpenCL data #ifdef CL_VERSION_1_2 cl::ImageGL imgA = tiny.imageFromTexture(CL::MEM::READ_WRITE, texA); cl::ImageGL imgB = tiny.imageFromTexture(CL::MEM::READ_WRITE, texB); #else cl::Image2DGL imgA = tiny.imageFromTexture(CL::MEM::READ_WRITE, texA); cl::Image2DGL imgB = tiny.imageFromTexture(CL::MEM::READ_WRITE, texB); #endif const float speed = 0.2f; float velocity[2] = { 0.0f, 0.0f }; cl::Buffer velBuf = tiny.buffer(CL::MEM::READ_ONLY, 2 * sizeof(float), velocity); //Setup our GL objects vector std::vector<cl::Memory> glObjs; glObjs.push_back(imgA); glObjs.push_back(imgB); //The time step will be constant and velocity won't change each step, so set'em now float dt = 1.0f / FPS; kernel.setArg(0, sizeof(float), &dt); kernel.setArg(1, velBuf); //Query the preferred work group size int workSize = tiny.preferredWorkSize(kernel); //fixed for now int imgSize = 256; cl::NDRange local(workSize, workSize); cl::NDRange global(imgSize, imgSize); //Track the run number so we know which texture to set as in/out and which to draw int run = 0; //Our event structure SDL_Event e; //Limit framerate with a timer Timer delta; //For tracking if we want to quit bool quit = false, paused = false; while (!quit){ delta.Start(); //Event Polling while (SDL_PollEvent(&e)){ //If user closes he window if (e.type == SDL_QUIT) quit = true; //If user presses any key if (e.type == SDL_KEYDOWN){ switch (e.key.keysym.sym){ //So we can change velocity case SDLK_w: velocity[1] = speed; tiny.writeData(velBuf, 2 * sizeof(float), velocity); break; case SDLK_s: velocity[1] = -speed; tiny.writeData(velBuf, 2 * sizeof(float), velocity); break; case SDLK_a: velocity[0] = -speed; tiny.writeData(velBuf, 2 * sizeof(float), velocity); break; case SDLK_d: velocity[0] = speed; tiny.writeData(velBuf, 2 * sizeof(float), velocity); break; case SDLK_r: velocity[0] = 0.0f; velocity[1] = 0.0f; tiny.writeData(velBuf, 2 * sizeof(float), velocity); break; //Toggle pause case SDLK_SPACE: paused = !paused; break; //For quitting, escape key case SDLK_ESCAPE: quit = true; break; default: break; } } } //Run the kernel, setting the in/out textures properly. On even runs the output will be //in texB, on odd runs output will be in texA if (!paused){ try { //On even runs and the first run texB/imgB is our output, on odd runs it's flipped //Is this really the best way to do this? Maybe there is some faster way to copy the image over //instead of updating this each time if (run % 2 == 0 || run == 0){ kernel.setArg(2, imgA); kernel.setArg(3, imgB); active = texB; } else { kernel.setArg(2, imgB); kernel.setArg(3, imgA); active = texA; } glFinish(); tiny.mQueue.enqueueAcquireGLObjects(&glObjs); tiny.runKernel(kernel, local, global); tiny.mQueue.enqueueReleaseGLObjects(&glObjs); tiny.mQueue.finish(); ++run; } catch (const cl::Error &e){ std::cout << "Error: " << e.what() << " code: " << e.err() << std::endl; } } //RENDERING window.clear(); prog.use(); glBindVertexArray(vao); glActiveTexture(GL_TEXTURE0); //Shouldn't we be drawing active here? glBindTexture(GL_TEXTURE_2D, texA); glDrawElements(GL_TRIANGLES, vao.numElements(), GL_UNSIGNED_SHORT, NULL); window.present(); //Cap fps if (delta.Ticks() < 1000 / FPS) SDL_Delay(1000 / FPS - delta.Ticks()); } window.close(); Window::quit(); }
/* * lookup variable (according to (set&LOCAL)), set its attributes * (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL, LCASEV, * UCASEV_AL), and optionally set its value if an assignment. */ struct tbl * typeset(const char *var, uint32_t set, uint32_t clr, int field, int base) { struct tbl *vp; struct tbl *vpbase, *t; char *tvar; const char *val; size_t len; bool vappend = false; /* check for valid variable name, search for value */ val = skip_varname(var, false); if (*val == '[') { if (set_refflag != SRF_NOP) errorf("%s: %s", var, "reference variable can't be an array"); len = array_ref_len(val); if (len == 0) return (NULL); /* * IMPORT is only used when the shell starts up and is * setting up its environment. Allow only simple array * references at this time since parameter/command * substitution is performed on the [expression] which * would be a major security hole. */ if (set & IMPORT) { size_t i; for (i = 1; i < len - 1; i++) if (!ksh_isdigit(val[i])) return (NULL); } val += len; } if (val[0] == '=' || (val[0] == '+' && val[1] == '=')) { strndupx(tvar, var, val - var, ATEMP); if (*val++ == '+') { ++val; vappend = true; } } else if ((val[0] != '\0') || (set & IMPORT)) { /* * must have a = when setting a variable by importing * the original environment, otherwise be empty; we * also end up here when a variable name was invalid * or none given */ return (NULL); } else { /* just varname with no value part nor equals sign */ strdupx(tvar, var, ATEMP); val = NULL; /* handle foo[*] => foo (whole array) mapping for R39b */ len = strlen(tvar); if (len > 3 && tvar[len - 3] == '[' && tvar[len - 2] == '*' && tvar[len - 1] == ']') tvar[len - 3] = '\0'; } if (set_refflag == SRF_ENABLE) { const char *qval; /* bail out on 'nameref foo+=bar' */ if (vappend) errorfz(); /* find value if variable already exists */ if ((qval = val) == NULL) { varsearch(e->loc, &vp, tvar, hash(tvar)); if (vp != NULL) qval = str_val(vp); } /* silently ignore 'nameref foo=foo' */ if (qval != NULL && !strcmp(qval, tvar)) { afree(tvar, ATEMP); return (&vtemp); } } /* prevent typeset from creating a local PATH/ENV/SHELL */ if (Flag(FRESTRICTED) && (strcmp(tvar, "PATH") == 0 || strcmp(tvar, "ENV") == 0 || strcmp(tvar, "SHELL") == 0)) errorf("%s: %s", tvar, "restricted"); vp = (set&LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) : global(tvar); if (set_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC) vp->flag &= ~ASSOC; else if (set_refflag == SRF_ENABLE) { if (vp->flag & ARRAY) { struct tbl *a, *tmp; /* free up entire array */ for (a = vp->u.array; a; ) { tmp = a; a = a->u.array; if (tmp->flag & ALLOC) afree(tmp->val.s, tmp->areap); afree(tmp, tmp->areap); } vp->u.array = NULL; vp->flag &= ~ARRAY; } vp->flag |= ASSOC; } set &= ~(LOCAL|LOCAL_COPY); vpbase = (vp->flag & ARRAY) ? global(arrayname(var)) : vp; /* * only allow export flag to be set; AT&T ksh allows any * attribute to be changed which means it can be truncated or * modified (-L/-R/-Z/-i) */ if ((vpbase->flag&RDONLY) && (val || clr || (set & ~EXPORT))) /* XXX check calls - is error here ok by POSIX? */ errorfx(2, "read-only: %s", tvar); afree(tvar, ATEMP); /* most calls are with set/clr == 0 */ if (set | clr) { bool ok = true; /* * XXX if x[0] isn't set, there will be problems: need * to have one copy of attributes for arrays... */ for (t = vpbase; t; t = t->u.array) { bool fake_assign; char *s = NULL; char *free_me = NULL; fake_assign = (t->flag & ISSET) && (!val || t != vp) && ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) || ((t->flag & INTEGER) && (clr & INTEGER)) || (!(t->flag & INTEGER) && (set & INTEGER))); if (fake_assign) { if (t->flag & INTEGER) { s = str_val(t); free_me = NULL; } else { s = t->val.s + t->type; free_me = (t->flag & ALLOC) ? t->val.s : NULL; } t->flag &= ~ALLOC; } if (!(t->flag & INTEGER) && (set & INTEGER)) { t->type = 0; t->flag &= ~ALLOC; } t->flag = (t->flag | set) & ~clr; /* * Don't change base if assignment is to be * done, in case assignment fails. */ if ((set & INTEGER) && base > 0 && (!val || t != vp)) t->type = base; if (set & (LJUST|RJUST|ZEROFIL)) t->u2.field = field; if (fake_assign) { if (!setstr(t, s, KSH_RETURN_ERROR)) { /* * Somewhat arbitrary action * here: zap contents of * variable, but keep the flag * settings. */ ok = false; if (t->flag & INTEGER) t->flag &= ~ISSET; else { if (t->flag & ALLOC) afree(t->val.s, t->areap); t->flag &= ~(ISSET|ALLOC); t->type = 0; } } if (free_me) afree(free_me, t->areap); } } if (!ok) errorfz(); } if (val != NULL) { char *tval; if (vappend) { tval = shf_smprintf("%s%s", str_val(vp), val); val = tval; } else tval = NULL; if (vp->flag&INTEGER) { /* do not zero base before assignment */ setstr(vp, val, KSH_UNWIND_ERROR | 0x4); /* done after assignment to override default */ if (base > 0) vp->type = base; } else /* setstr can't fail (readonly check already done) */ setstr(vp, val, KSH_RETURN_ERROR | 0x4); if (tval != NULL) afree(tval, ATEMP); } /* only x[0] is ever exported, so use vpbase */ if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) && vpbase->type == 0) exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null); return (vp); }