int main(void) { init_timer(); init_io(); USART_Init(); sei(); fill_cube(0xFF); _delay_us(1500000); int mode = (PIND & (1<<PD3)); if (mode) { while (1) { random_filler(1); random_filler(0); loadbar(); rain(100); send_voxels_rand_z(200); set_edges(); _delay_us(5000000); } } else { int escape = 0; int counter = 0; while (1) { uint8_t byte; byte = USART_Receive(); if (!escape) { if (byte == 0xAB) { // escape character escape = 1; } else if (counter < 64) { tab[counter/8][counter%8] = byte; counter++; } } else { if (byte == 0xCD) { // start character counter = 0; } else if (byte == 0xAB && counter < 64) { tab[counter/8][counter%8] = byte; counter++; } escape = 0; } } } return 0; }
void fill_random(vec2_d *data, double ctr, double rng) { for(int i = 0; i < (*data).size(); i++) { loadbar(i, (*data).size(), LOADBAR_SIZE); for(int j = 0; j < (*data)[0].size(); j++) { (*data)[i][j] = (double)((std::rand() - RAND_MAX / 2) * rng * 2)/(double)RAND_MAX + ctr; } } }
vec2_d* construct_vec2_d(int x, int y) { vec2_d *res = new vec2_d(x); for(int i = 0; i < x; i++) { loadbar(i, x, LOADBAR_SIZE); for(int j = 0; j < y; j++) { (*res)[i] = vec_d(y); } } return res; }
void dump_data(vec2_d *data, const char* path, const char delim) { std::ofstream data_file; data_file.open(path); if(data_file.is_open()) { for(int i = 0; i < (*data).size(); i++) { loadbar(i, (*data).size(), LOADBAR_SIZE); for(int j = 0; j < (*data)[0].size(); j++) { data_file << (*data)[i][j] << (j == (*data)[i].size() - 1 ? '\n' : delim); } } } data_file.close(); }
void dump_rand_data_i(int n, int d, int ctr, int rng, const char* path, const char delim, int seed) { srand(seed); std::ofstream data_file; data_file.open(path); if(data_file.is_open()) { for(int i = 0; i < n; i++) { loadbar(i, n, LOADBAR_SIZE); for(int j = 0; j < d; j++) { data_file << round((((std::rand() - RAND_MAX / 2.0) * rng * 2.0)/(double)RAND_MAX + ctr)) << (j == d - 1 ? '\n' : delim); } } } }
void dump_rand_data_d(int n, int d, double ctr, double rng, const char* path, const char delim, int seed) { srand(seed); std::ofstream data_file; data_file.open(path); if(data_file.is_open()) { for(int i = 0; i < n; i++) { loadbar(i, n, 50); for(int j = 0; j < d; j++) { data_file << ((double)((std::rand() - RAND_MAX / 2.0) * rng * 2.0)/(double)RAND_MAX + ctr) << (j == d - 1 ? '\n' : delim); } } } data_file.close(); }
void RootMakePlots::Run(int nentries, std::vector<Cut*> cuts){ std::cout << "Processing " << nentries << "points" << std::endl; //initiate iterators over cuts and spaces outside for loop std::vector<Cut*>::iterator cut_it; std::vector<Space*>::iterator space_it; int cut_counter=0; for(int i=0; i<nentries; i++){ // get entry _chain->GetEntry(i); // check for cuts: if a cut function returns true, then go to the next entry bool passed_cuts=true; for (cut_it=cuts.begin();cut_it!=cuts.end();cut_it++){ // NOTE: *cut_it is a pointer, therefore dereference if ((*(*cut_it))(_vars)){ passed_cuts=false; cut_counter++; break; } } if (passed_cuts){ ///Update all _spaces: check whether X^2 is lower than existing X^2 for( space_it=_spaces.begin(); space_it!=_spaces.end() ; space_it++){ (*space_it)->update(_vars,i); } } // print progress bar loadbar(i,nentries-1); } std::cout << "Number of point cut out: " << cut_counter << std::endl; //Write all plots (X^2,entries, *zaxes) to root file if (_outfile->cd(_outdir)!=kTRUE){ _outfile->mkdir(_outdir); _outfile->cd(_outdir); } for( std::vector<Space*>::iterator it=_spaces.begin(); it!=_spaces.end() ; it++){ (*it)->write_plots(); } }
//data loading bool ModelData::LoadIn(QString filepath) { bool loaderReady; bool abort; STLTri* pLoadedTri = NULL; Triangle3D newtri; this->filepath = filepath; if(filepath.isEmpty()) return false; //extract filename from path! filename = QFileInfo(filepath).fileName(); B9ModelLoader mLoader(filepath,loaderReady,NULL); if(loaderReady == false)//error opening model data { //display Loader Error QMessageBox msgBox; msgBox.setText(mLoader.GetError()); msgBox.exec(); return false; } //make a progress bar and connect it to LoadingBar loadbar(0,100); loadbar.useCancelButton(false); loadbar.setDescription("Importing: " + filename); QObject::connect(&mLoader,SIGNAL(PercentCompletedUpdate(qint64,qint64)), &loadbar,SLOT(setProgress(qint64,qint64))); //now we are ready to walk the loader through reading each triangle //and copying it into the this model data. while(mLoader.LoadNextTri(pLoadedTri,abort)) { if(abort) { //display Loader abort error QMessageBox msgBox; msgBox.setText(mLoader.GetError()); msgBox.exec(); return false; } else { //newtri.normal.setX(pLoadedTri->nx); //newtri.normal.setY(pLoadedTri->ny); //newtri.normal.setZ(pLoadedTri->nz); newtri.vertex[0].setX(pLoadedTri->x0); newtri.vertex[0].setY(pLoadedTri->y0); newtri.vertex[0].setZ(pLoadedTri->z0); newtri.vertex[1].setX(pLoadedTri->x1); newtri.vertex[1].setY(pLoadedTri->y1); newtri.vertex[1].setZ(pLoadedTri->z1); newtri.vertex[2].setX(pLoadedTri->x2); newtri.vertex[2].setY(pLoadedTri->y2); newtri.vertex[2].setZ(pLoadedTri->z2); //use right hand rule for importing normals - ignore file normals.. newtri.UpdateNormalFromGeom(); delete pLoadedTri; newtri.UpdateBounds(); triList.push_back(newtri); } } qDebug() << "Loaded triangles: " << triList.size(); //now center it! CenterModel(); //generate a normal display lists. int displaySuccess = FormNormalDisplayLists(); if(displaySuccess) return true; else return false; }
int kernel_run_bch_ber_ch_mode ( int galois_field_degree, int bch_code_length, int error_correction, int decoded_seq_buf_size_frames, double ber, char* out_file_postfix, char* input_file_name, int gui_progress ) { FILE* flog = stdout; log(flog, "Current mode: use of BCH codec only via BER parametrized channel\n"); log(flog, "Simulation kernel settings:\n"); log(flog, "Galois field degree: %d\n", galois_field_degree); log(flog, "BCH code length: %d\n", bch_code_length); log(flog, "Error correction property: %d\n", error_correction); log(flog, "BER (Bit Error Rate): %.2f\n", ber); log(flog, "Output file postfix: %s\n", out_file_postfix); log(flog, "Input file name: %s\n", input_file_name); /************************************************************************/ /* Параметры тестового окружения. */ /************************************************************************/ char* file_path = input_file_name; int* data_in = get_file_data(file_path); int data_size = get_file_size(file_path) * CHAR_BIT; //print_data(data_in, data_size); int* data_out = NULL; /************************************************************************/ /* Параметры БЧХ-кодера */ /************************************************************************/ //int galois_field_degree = 4; //int bch_code_length = 15; //int error_correction = 3; /************************************************************************/ /* Параметры ДСК-канала */ /************************************************************************/ //double ber = 0;//2*1e-5; int random_errors_quantity = 5; int erase_errors_quantity = 2; /************************************************************************/ /* Создание программных компонентов. */ /************************************************************************/ bch_encoder_t bch_encoder = bch_encoder_create(flog, galois_field_degree, bch_code_length, error_correction); bch_decoder_t bch_decoder = bch_decoder_create(ERRORS_CORRECTION_MODE, flog, galois_field_degree, bch_code_length, error_correction); /* Получение длины фрейма данных, который может кодировать БЧХ-кодер. */ int bch_frame_size = bch_encoder_get_frame_size(bch_encoder); int bch_codeword_size = bch_encoder_get_codeword_size(bch_encoder); /************************************************************************/ /* Создание программных компонентов. */ /************************************************************************/ transmitter_t transmitter = transmitter_create(flog, bch_frame_size, data_in, data_size); receiver_t receiver = receiver_create(flog, bch_frame_size, data_size); /************************************************************************/ /* Создание программных компонентов. */ /************************************************************************/ channel_bs_t channel_bs = channel_bs_create(flog, ber); /************************************************************************/ /* Параметры промежуточных буферов */ /************************************************************************/ int bch_frame_fifo_size = decoded_seq_buf_size_frames + 1; int bch_codeword_fifo_size = decoded_seq_buf_size_frames + 1; /************************************************************************/ /* Создание промежуточных буферов. */ /************************************************************************/ frame_fifo_t bch_frame_fifo = frame_fifo_create(bch_frame_fifo_size, bch_frame_size); codeword_fifo_t bch_codeword_fifo = codeword_fifo_create(bch_codeword_fifo_size, bch_codeword_size); /************************************************************************/ /* Запуск программных компонентов. */ /************************************************************************/ log(flog, "Simulation started\n"); transmitter->start(transmitter); receiver->start(receiver); bch_encoder->start(bch_encoder); bch_decoder->start(bch_decoder); channel_bs->start(channel_bs); /************************************************************************/ /* Запуск цикла моделирования. */ /************************************************************************/ int sent_frames = 0; int frames_to_sent = data_size/bch_frame_size; int send_bits_all = data_size+decoded_seq_buf_size_frames*bch_frame_size; L_Loop: /*if (!(sent_bits_cnt % percent_precision) && !gui_progress) printf("\rProgress: %.0f%%", ((float)sent_bits_cnt/ (float)send_bits_all) * 100); else if (!(sent_bits_cnt % percent_precision)) printf("Progress: %.0f%%\n", ((float)sent_bits_cnt/ (float)send_bits_all) * 100);*/ loadbar(sent_frames++, frames_to_sent, 50); /* Генерация фрейма данных передатчиком. */ frame_t bch_frame_in = transmitter->transmit_frame(transmitter); if (bch_frame_in == NULL) goto L_Stop; frame_display(bch_frame_in); /* Запись сгенерированного кодового слова БЧХ-кода в промежуточный буфер. */ bch_frame_fifo = frame_fifo_put(bch_frame_fifo, bch_frame_in); /* Кодирование фрейма данных БЧХ-кодером и получение кодового слова БЧХ-кода. */ codeword_t bch_codeword_in = bch_encoder->encode(bch_encoder, bch_frame_in); codeword_display(bch_codeword_in); /* Передача кодового слова сверточного кода по каналу. */ codeword_t bch_codeword_out = channel_bs->transfer(channel_bs, bch_codeword_in); /* Декодирование кодового слова БЧХ-декодером и получение фрейма данных. */ frame_t bch_frame_out = bch_decoder->decode(bch_decoder, bch_codeword_out, bch_codeword_in); frame_display(bch_frame_out); /* Извлечение из промежуточного буфера фрейма данных. */ bch_frame_in = frame_fifo_get(bch_frame_fifo); /* Прием фрейма данных и анализ его корректности. */ receiver->receive_frame(receiver, bch_frame_out, bch_frame_in); goto L_Loop; /************************************************************************/ /* Останов программных компонентов. */ /************************************************************************/ L_Stop: transmitter->stop(transmitter); receiver->stop(receiver); bch_encoder->stop(bch_encoder); bch_decoder->stop(bch_decoder); channel_bs->stop(channel_bs); log(flog, "Simulation stopped\n"); /************************************************************************/ /* Проверка корректности принятых данных. */ /************************************************************************/ data_out = receiver_get_received_data(receiver); printf("\n"); if (cmp_data(data_in, data_out, data_size)) printf("Comparison test: OK\n"); else printf("Comparison test: FAIL\n"); free(data_in); out_file_postfix = extend_out_file_postfix( out_file_postfix, galois_field_degree, bch_code_length, error_correction, 0, ber); put_file_data(data_out, file_path, out_file_postfix); //print_data(data_in, data_size); //print_data(data_out, data_size); /************************************************************************/ /* Уничтожение программных компонентов. */ /************************************************************************/ transmitter_destroy(transmitter); receiver_destroy(receiver); bch_encoder_destroy(bch_encoder); bch_decoder_destroy(bch_decoder); channel_bs_destroy(channel_bs); frame_fifo_destroy(bch_frame_fifo); codeword_fifo_destroy(bch_codeword_fifo); #ifdef _DEBUG _CrtDumpMemoryLeaks(); #endif return 0; }
int kernel_run_cnv_mode ( int galois_field_degree, int bch_code_length, int error_correction, int decoded_seq_buf_size_frames, double ber, char* out_file_postfix, char* input_file_name, int gui_progress) { FILE* flog = stdout; log(flog, "Current mode: use of CNV codec only via BER parametrized channel\n"); log(flog, "Simulation kernel settings:\n"); log(flog, "Galois field degree: %d\n", galois_field_degree); log(flog, "BCH code length: %d\n", bch_code_length); log(flog, "Error correction property: %d\n", error_correction); log(flog, "Size of decoded buffer (CNV decoder): %d\n", decoded_seq_buf_size_frames); log(flog, "BER (Bit Error Rate): %.2f\n", ber); log(flog, "Output file postfix: %s\n", out_file_postfix); log(flog, "Input file name: %s\n", input_file_name); /************************************************************************/ /* Параметры тестового окружения. */ /************************************************************************/ int* data_in = get_file_data(input_file_name); int data_size = get_file_size(input_file_name) * CHAR_BIT; //print_data(data_in, data_size); int* data_out = NULL; int use_bch_codec = 0; /************************************************************************/ /* Параметры ДСК-канала */ /************************************************************************/ //double ber = 0;//2*1e-5; /************************************************************************/ /* Технологические переменные. */ /************************************************************************/ int skip_q_cnt = 0; int percent_precision = gui_progress ? (int)1e3 : 5; int sent_bits_cnt = 0; /************************************************************************/ /* Создание программных компонентов. */ /************************************************************************/ int frame_size = 10; transmitter_t transmitter = transmitter_create(flog, frame_size, data_in, data_size); receiver_t receiver = receiver_create(flog, frame_size, data_size); /************************************************************************/ /* Параметры сверточного кодера. */ /************************************************************************/ int regs_q = 2; /* ! do not change */ int codeword_length = frame_size * regs_q; //int decoded_seq_buf_size_frames = 2; int decoded_seq_buf_size = frame_size * decoded_seq_buf_size_frames + 1; int skip_q = decoded_seq_buf_size_frames; /************************************************************************/ /* Создание программных компонентов. */ /************************************************************************/ cnv_encoder_t cnv_encoder = cnv_encoder_create(flog, regs_q, codeword_length); cnv_decoder_t cnv_decoder = cnv_decoder_create(flog, regs_q, decoded_seq_buf_size); /************************************************************************/ /* Создание программных компонентов. */ /************************************************************************/ channel_bs_t channel_bs = channel_bs_create(flog, ber); /************************************************************************/ /* Параметры промежуточных буферов */ /************************************************************************/ int frame_fifo_size = decoded_seq_buf_size_frames + 1; /************************************************************************/ /* Создание промежуточных буферов. */ /************************************************************************/ frame_fifo_t frame_fifo = frame_fifo_create(frame_fifo_size, frame_size); /************************************************************************/ /* Запуск программных компонентов. */ /************************************************************************/ log(flog, "Simulation started\n"); transmitter->start(transmitter); receiver->start(receiver); cnv_encoder->start(cnv_encoder); cnv_decoder->start(cnv_decoder); channel_bs->start(channel_bs); /************************************************************************/ /* Запуск цикла моделирования. */ /************************************************************************/ int sent_frames = 0; int frames_to_sent = data_size/frame_size; int send_bits_all = data_size+decoded_seq_buf_size_frames*frame_size; L_Loop: /*if (!(sent_bits_cnt % percent_precision) && !gui_progress) printf("\rProgress: %.0f%%", ((float)sent_bits_cnt/ (float)send_bits_all) * 100); else if (!(sent_bits_cnt % percent_precision)) printf("Progress: %.0f%%\n", ((float)sent_bits_cnt/ (float)send_bits_all) * 100);*/ loadbar(sent_frames++, frames_to_sent, 50); sent_bits_cnt += frame_size; /* Генерация фрейма данных передатчиком. */ frame_t frame_in = transmitter->transmit_frame(transmitter); if (frame_in == NULL) goto L_Dummy_Generation; frame_display(frame_in); /* Запись сгенерированного фрейма данных в промежуточный буфер. */ frame_fifo = frame_fifo_put(frame_fifo, frame_in); /* Кодирование фрейма данных сверточным кодером и получение кодового слова сверточного кода.*/ codeword_t cnv_codeword_in = cnv_encoder->encode(cnv_encoder, frame_in); goto L_Skip_Dummy_Generation; L_Dummy_Generation: cnv_codeword_in = codeword_create(cnv_encoder->codeword_length); L_Skip_Dummy_Generation: codeword_display(cnv_codeword_in); /* Передача кодового слова сверточного кода по каналу. */ codeword_t cnv_codeword_out = channel_bs->transfer(channel_bs, cnv_codeword_in); codeword_display(cnv_codeword_out); /* Декодирование кодового слова сверточного кода и получение фрейма данных. */ frame_t frame_out = cnv_decoder->decode(cnv_decoder, cnv_codeword_out, cnv_codeword_in); frame_display(frame_out); /* Проверка счетчика пропусков. */ if(skip_q_cnt != skip_q) { skip_q_cnt++; goto L_Loop; } /* Извлечение из промежуточного буфера фрейма данных. */ frame_in = frame_fifo_get(frame_fifo); frame_display(frame_in); /* Прием фрейма данных и анализ его корректности. */ receiver->receive_frame(receiver, frame_out, frame_in); /* Проверка наличия фреймов в буфере. */ if(frame_fifo_is_empty(frame_fifo)) goto L_Stop; else goto L_Loop; /************************************************************************/ /* Останов программных компонентов. */ /************************************************************************/ L_Stop: transmitter->stop(transmitter); receiver->stop(receiver); cnv_encoder->stop(cnv_encoder); cnv_decoder->stop(cnv_decoder); channel_bs->stop(channel_bs); log(flog, "Simulation stopped\n"); /************************************************************************/ /* Проверка корректности принятых данных. */ /************************************************************************/ data_out = receiver_get_received_data(receiver); printf("\n"); if (cmp_data(data_in, data_out, data_size)) printf("Comparison test: OK\n"); else printf("Comparison test: FAIL\n"); free(data_in); out_file_postfix = extend_out_file_postfix( out_file_postfix, galois_field_degree, bch_code_length, error_correction, decoded_seq_buf_size, ber); put_file_data(data_out, input_file_name, out_file_postfix); //print_data(data_in, data_size); //print_data(data_out, data_size); /************************************************************************/ /* Уничтожение программных компонентов. */ /************************************************************************/ transmitter_destroy(transmitter); receiver_destroy(receiver); cnv_encoder_destroy(cnv_encoder); cnv_decoder_destroy(cnv_decoder); channel_bs_destroy(channel_bs); frame_fifo_destroy(frame_fifo); #ifdef _DEBUG _CrtDumpMemoryLeaks(); #endif return 0; }
/** * the worker **/ void *preprocess( void *p ) { // get start & end for this thread Thread* thread = (Thread*)p; const long int start = thread->start(); const long int end = thread->end(); const long int nbop = (end-start)/100; // get output file name std::string output_file_name = std::string(c_output_file_name); // attach thread to CPU if (thread->id() != -1){ thread->set(); output_file_name += "-" + typeToString(thread->id()); if (verbose) fprintf(stderr, "create pthread n°%ld, reading from position %ld to %ld\n",thread->id(), start, end-1); } // create output file File output_file(output_file_name,zip); output_file.open("w"); // open input file std::string input_file_name = std::string(c_input_file_name); File input_file(input_file_name); input_file.open(); input_file.jump_to_position(start); char *line = NULL; long int position=input_file.position(); int itr=0; if (verbose) loadbar(thread->id(), itr, 100); while ( position<end ){ // get the line line = input_file.getline(); // lowercase? if (lower) lowercase(line); // replace digits? if (digit) replace_digit(line); // write the preprocessed line output_file.write(line); output_file.write("\n"); // get current position in stream position = input_file.position(); // display progress bar if (verbose){ if ( position-(start+(itr*nbop)) > nbop) loadbar(thread->id(), ++itr, 100); } // release memory free(line); } // display last percent if (verbose) loadbar(thread->id(), 100, 100); // close output file output_file.close(); // close input file input_file.close(); // exit thread if ( thread->id()!= -1 ){ pthread_exit( (void*)thread->id() ); } return 0; }
void ASCHandler::chunking(std::vector<std::string> path) { total_file_num = path.size(); // SysOperation::remove_file("/tmp/asc_handler"); get_seg_size(Chunker::min_chunk_size, Chunker::avg_chunk_size, Chunker::max_chunk_size); Chunker::keep_buf = 1; //classify path_vec.clear(); for(int i = 0; i < path.size(); i++) { std::string m_type = SysOperation::get_type(path[i]); int m_size = SysOperation::get_size(path[i]); if(m_size) { total_origin_size += m_size; max_type_len = Util::max(max_type_len, m_type.size()); origin_size.insert(std::make_pair(m_type, 0)).first->second += m_size; if(path_vec.find(m_type) == path_vec.end()) { std::vector<std::string> vec; path_vec.insert(make_pair(m_type, vec)); seg_exp_size.insert(std::make_pair(m_type, Chunker::avg_chunk_size)); } path_vec[m_type].push_back(path[i]); } } //find exp size int done = 0; for(std::map<std::string, std::vector<std::string> >::iterator it = path_vec.begin(); it != path_vec.end(); ++it) { m_der_rate.insert(make_pair(it->first, 1.0)); bool div_two = false; while((Chunker::avg_chunk_size = seg_exp_size[it->first]) >= 512) { //init std::string path = "/tmp/asc_handler_" + it->first; SysOperation::remove_file(path); type.insert(std::make_pair(it->first, 0)).first->second = 0; //chunk for(int i = 0; i < it->second.size(); i++) { chunk_file(it->second[i]); } //update double der_rate = get_der_rate(it->first); // std::cout << it->first << "\t" << Chunker::avg_chunk_size << "\t" << der_rate << std::endl; if(der_rate > m_der_rate[it->first]) { m_der_rate[it->first] = der_rate; seg_exp_size[it->first] /= 2; div_two = true; } else break; } if(div_two) { seg_exp_size[it->first] *= 2; Chunker::avg_chunk_size = seg_exp_size[it->first]; std::string path = "/tmp/asc_handler_" + it->first; SysOperation::remove_file(path); type[it->first] = 0; //chunk for(int i = 0; i < it->second.size(); i++) { chunk_file(it->second[i]); } } total_seg_num += type[it->first]; done += it->second.size(); // std::cout << done << std::endl; loadbar(done, path.size()); // std::cout << "end" << std::endl; // std::cout << Util::currentTimeinString() << // ", Type: " << it->first << // ", exp size: " << seg_exp_size[it->first] << // ", ASC Der Rate: " << m_der_rate[it->first] << std::endl; } std::cout << std::endl; }
void ASCHandler::db_operation() { loadbar(1,1); std::cout << std::endl; }
// React to keyboard input void keyboard(unsigned char key, int x, int y) { printf("key %d pressed at %d,%d\n",key,x,y); fflush(stdout); switch (key) { // Add a light based on the camera position. case 'L': MyLightPositions.push_back(getCameraPosition()); break; // Update a light based on the camera position. case 'l': MyLightPositions[MyLightPositions.size() - 1] = getCameraPosition(); break; // Pressing r will launch the raytracing. case 'r': { cout << "Raytracing" << endl; // Setup an image with the size of the current image. Image result(ImageSize_X, ImageSize_Y); // Produce the rays for each pixel, by first computing // the rays for the corners of the frustum. Vec3Df origin00, dest00; Vec3Df origin01, dest01; Vec3Df origin10, dest10; Vec3Df origin11, dest11; Vec3Df origin, dest; produceRay(0, 0, &origin00, &dest00); produceRay(0, ImageSize_Y - 1, &origin01, &dest01); produceRay(ImageSize_X - 1, 0, &origin10, &dest10); produceRay(ImageSize_X - 1, ImageSize_Y - 1, &origin11, &dest11); for (unsigned int y = 0; y < ImageSize_Y; ++y) { for (unsigned int x = 0; x < ImageSize_X; ++x) { // Produce the rays for each pixel, by interpolating // the four rays of the frustum corners. float xscale = 1.0f - float(x) / (ImageSize_X - 1); float yscale = 1.0f - float(y) / (ImageSize_Y - 1); origin = yscale*(xscale*origin00 + (1 - xscale)*origin10) + (1 - yscale)*(xscale*origin01 + (1 - xscale)*origin11); dest = yscale*(xscale*dest00 + (1 - xscale)*dest10) + (1 - yscale)*(xscale*dest01 + (1 - xscale)*dest11); // Launch raytracing for the given ray. Vec3Df rgb = performRayTracing(origin, dest); // Store the result in an image result.setPixel(x, y, RGBValue(rgb[0], rgb[1], rgb[2])); } loadbar(y, ImageSize_Y, 50); } loadbar(ImageSize_Y, ImageSize_Y, 50); cout << endl; cout << endl; result.writeImage("result.ppm"); cout << endl; break; } // Pressing s will launch the raytracing with sampling. case 's': { cout << "Raytracing with sampling" << endl; // Setup an image with the size of the current image. Image result(ImageSize_X, ImageSize_Y); // Produce the rays for each pixel, by first computing // the rays for the corners of the frustum. Vec3Df origin00, dest00; Vec3Df origin01, dest01; Vec3Df origin10, dest10; Vec3Df origin11, dest11; Vec3Df origin, dest; produceRay(0, 0, &origin00, &dest00); produceRay(0, ImageSize_Y - 1, &origin01, &dest01); produceRay(ImageSize_X - 1, 0, &origin10, &dest10); produceRay(ImageSize_X - 1, ImageSize_Y - 1, &origin11, &dest11); Vec3Df rgb; unsigned int fromY = 0; unsigned int toY = 100; for (unsigned int y = fromY; y < toY; ++y) { for (unsigned int x = 0; x < ImageSize_X; ++x) { // Produce the rays for each pixel, by interpolating // the four rays of the frustum corners. float xscale; // = 1.0f - float(x) / (ImageSize_X - 1); float yscale; // = 1.0f - float(y) / (ImageSize_Y - 1); for (unsigned int sx = 0; sx < ns; sx++) { for (unsigned int sy = 0; sy < ns; sy++) { xscale = 1.0f - (x + (sx + 0.5f) / ns) / (ImageSize_X - 1); yscale = 1.0f - (y + (sy + 0.5f) / ns) / (ImageSize_Y - 1); origin = yscale*(xscale*origin00 + (1 - xscale)*origin10) + (1 - yscale)*(xscale*origin01 + (1 - xscale)*origin11); dest = yscale*(xscale*dest00 + (1 - xscale)*dest10) + (1 - yscale)*(xscale*dest01 + (1 - xscale)*dest11); // Launch raytracing for the given ray. rgb += performRayTracing(origin, dest); } } rgb /= float(ns*ns); // Store the result in an image result.setPixel(x, y, RGBValue(rgb[0], rgb[1], rgb[2])); } loadbar(y-fromY, toY-fromY, 50); } loadbar(toY - fromY, toY - fromY, 50); cout << endl; cout << endl; result.writeImage("result.ppm"); cout << endl; break; } // ESC pressed case 27: { exit(0); } // Space pressed, trace our debug line. case 32: { cout << "Raytracing single ray" << endl; // Produce the ray for the current mouse position Vec3Df testRayOrigin, testRayDestination; produceRay(x, y, &testRayOrigin, &testRayDestination); yourKeyboardFunc(key, x, y, testRayOrigin, testRayDestination); } } }
/** * the worker **/ void *getvocab( void *p ){ // get start & end for this thread Thread* thread = (Thread*)p; const long int start = thread->start(); const long int end = thread->end(); const long int nbop = (end-start)/100; // get output file name std::string output_file_name = std::string(c_vocab_file_name); // attach thread to CPU if (thread->id() != -1){ thread->set(); output_file_name += "-" + typeToString(thread->id()); if (verbose){ fprintf(stderr,"create pthread n°%ld, reading from position %ld to %ld\n",thread->id(), start, end-1); } } // create vocab vocab hash; // open input file std::string input_file_name = std::string(c_input_file_name); File input_file(input_file_name); input_file.open(); input_file.jump_to_position(start); long long ntokens=0; // read and store tokens char word[MAX_TOKEN]; long int position=input_file.position(); int itr=0; if (verbose) loadbar(thread->id(), itr, 100); while ( position<end ){ // get next word while (input_file.getword(word)){ hash[word]++; ++ntokens; } // get current position in stream position = input_file.position(); if (verbose){ if ( position-(start+(itr*nbop)) > nbop) loadbar(thread->id(), ++itr, 100); } } if (verbose) loadbar(thread->id(), 100, 100); // closing input file input_file.close(); // exit thread if ( thread->id()!= -1 ){ long long *ptr_ntokens = (long long *) thread->object; // increment total number of tokens (*ptr_ntokens) += ntokens; // write hash table hash_print(&hash, output_file_name.c_str()); // existing pthread pthread_exit( (void*)thread->id() ); }else{ if (verbose) fprintf(stderr, "\ndone after reading %lld tokens.\n", ntokens); // write out writevocab(&hash, output_file_name); } return 0; }
int main(int argc, char** argv) try { po::options_description desc("Required options"); desc.add_options() ("help,h", "produce help message") ("force,f", "overwrite existing files") ("mpq", po::value<std::string>(), "the mpq to create") ("files", po::value<std::vector<std::string> >(), "input files"); po::positional_options_description p; p.add("mpq", 1); p.add("files", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (!vm.count("files") || !vm.count("mpq") || vm.count("help")) { std::cout << "usage: <mpq> [<files> ...]" << std::endl << std::endl << desc << std::endl; return 1; } std::vector<std::string> files(vm["files"].as< std::vector<std::string> >()); std::vector<FileEntry> toAdd; fs::path mpqPath(vm["mpq"].as<std::string>()); if(fs::exists(mpqPath)) { if(vm.count("force")) fs::remove(mpqPath); else throw std::runtime_error("mpq does already exist"); } for(std::vector<std::string>::iterator path = files.begin(); path != files.end(); ++path) { if(fs::is_regular_file(*path)) toAdd.push_back(FileEntry(*path, *path)); if(!fs::is_directory(*path)) //no symlinks etc continue; for(fs::recursive_directory_iterator file(*path), end; file != end; ++file) if(fs::is_regular_file(file->path())) toAdd.push_back(FileEntry(file->path(), makeRelative(*path, file->path()))); } for(std::vector<FileEntry>::iterator it = toAdd.begin(); it != toAdd.end(); ++it) std::cout << it->realPath << " >> " << it->mpqPath << std::endl; HANDLE mpq; if(!SFileCreateArchive(mpqPath.string().c_str(), MPQ_CREATE_ARCHIVE_V2, toAdd.size(), &mpq)) throw std::runtime_error("couldn't create mpq"); SFileSetLocale(0); size_t counter(0); for(std::vector<FileEntry>::iterator it = toAdd.begin(); it != toAdd.end(); ++it) { loadbar(++counter, toAdd.size()); if(!SFileAddFileEx(mpq, it->realPath.string().c_str(), it->mpqPath.string().c_str(), MPQ_FILE_COMPRESS, MPQ_COMPRESSION_BZIP2, MPQ_COMPRESSION_BZIP2)) std::cout << "couldn't add file " << it->realPath << std::endl; } std::cout << std::endl; SFileCompactArchive(mpq, NULL, false); SFileFlushArchive(mpq); SFileCloseArchive(mpq); return 0; } catch (const std::exception& e) { std::cerr << "error: " << e.what() << "\n"; }