void DGLMainWindow::createActions() { // create "QActions" - bindings between mainwindow clickable widgets, // and // local slots quitAct = new QAction(tr("&Quit"), this); quitAct->setShortcuts(QKeySequence::Quit); quitAct->setStatusTip(tr("Quit the application")); CONNASSERT(quitAct, SIGNAL(triggered()), this, SLOT(close())); quitAct->setShortcut(QKeySequence(Qt::ALT + Qt::Key_F4)); aboutAct = new QAction(tr("&About"), this); aboutAct->setStatusTip(tr("Show the application's About box")); CONNASSERT(aboutAct, SIGNAL(triggered()), this, SLOT(about())); aboutAct->setShortcut(QKeySequence(Qt::Key_F1)); newProjectAct = new QAction(tr("&New Project..."), this); newProjectAct->setStatusTip(tr("Created new debugging project")); CONNASSERT(newProjectAct, SIGNAL(triggered()), this, SLOT(newProject())); newProjectAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_N)); openProjectAct = new QAction(tr("&Open Project..."), this); openProjectAct->setStatusTip(tr("Opens a debugging project")); CONNASSERT(openProjectAct, SIGNAL(triggered()), this, SLOT(openProject())); //TODO: implement openProjectAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_O)); saveProjectAct = new QAction(tr("&Save Project"), this); saveProjectAct->setStatusTip(tr("Save a debugging project")); CONNASSERT(saveProjectAct, SIGNAL(triggered()), this, SLOT(saveProject())); //TODO: implement saveProjectAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S)); saveAsProjectAct = new QAction(tr("&Save Project As ..."), this); saveAsProjectAct->setStatusTip(tr("Save a debugging project as as a file ...")); CONNASSERT(saveAsProjectAct, SIGNAL(triggered()), this, SLOT(saveProjectAs())); //TODO: implement saveAsProjectAct->setShortcut(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_S)); projectProperiesAct = new QAction(tr("&Project properties..."), this); projectProperiesAct->setStatusTip(tr("Change properties of current project")); CONNASSERT(projectProperiesAct, SIGNAL(triggered()), this, SLOT(projectProperties())); closeProjectAct = new QAction(tr("&Close project"), this); closeProjectAct->setStatusTip(tr("Created new debugging project")); CONNASSERT(closeProjectAct, SIGNAL(triggered()), this, SLOT(closeProject())); debugStartAct = new QAction(tr("&Start debugging"), this); debugStartAct->setStatusTip(tr("Stop debugging.")); CONNASSERT(debugStartAct, SIGNAL(triggered()), this, SLOT(debugStart())); CONNASSERT(&m_controller, SIGNAL(setDisconnected(bool)), debugStartAct, SLOT(setVisible(bool))); debugStartAct->setShortcut(QKeySequence(Qt::Key_F5)); debugStopAct = new QAction(tr("Sto&p debugging"), this); debugStopAct->setStatusTip(tr("Stop debugging.")); CONNASSERT(debugStopAct, SIGNAL(triggered()), this, SLOT(debugStop())); CONNASSERT(&m_controller, SIGNAL(setConnected(bool)), debugStopAct, SLOT(setEnabled(bool))); debugStopAct->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_F5)); debugStopAct->setEnabled(false); debugTerminateAct = new QAction(tr("Terminate"), this); debugTerminateAct->setStatusTip(tr("Terminate debugged process.")); CONNASSERT(debugTerminateAct, SIGNAL(triggered()), this, SLOT(debugTerminate())); CONNASSERT(&m_controller, SIGNAL(setConnected(bool)), debugTerminateAct, SLOT(setEnabled(bool))); debugTerminateAct->setEnabled(false); debugContinueAct = new QAction(tr("&Continue"), this); debugContinueAct->setStatusTip(tr("Continue program execution")); CONNASSERT(debugContinueAct, SIGNAL(triggered()), &m_controller, SLOT(debugContinue())); CONNASSERT(&m_controller, SIGNAL(setConnected(bool)), debugContinueAct, SLOT(setVisible(bool))); CONNASSERT(&m_controller, SIGNAL(setBreaked(bool)), debugContinueAct, SLOT(setEnabled(bool))); debugContinueAct->setShortcut(QKeySequence(Qt::Key_F5)); debugContinueAct->setVisible(false); debugInterruptAct = new QAction(tr("&Break on next call"), this); debugInterruptAct->setStatusTip( tr("Break program execution on GL call")); CONNASSERT(debugInterruptAct, SIGNAL(triggered()), &m_controller, SLOT(debugInterrupt())); CONNASSERT(&m_controller, SIGNAL(setConnected(bool)), debugInterruptAct, SLOT(setEnabled(bool))); CONNASSERT(&m_controller, SIGNAL(setRunning(bool)), debugInterruptAct, SLOT(setEnabled(bool))); debugInterruptAct->setShortcut(QKeySequence(Qt::Key_F6)); debugInterruptAct->setEnabled(false); debugStepAct = new QAction(tr("&Step"), this); debugStepAct->setStatusTip(tr("Step one GL call")); CONNASSERT(debugStepAct, SIGNAL(triggered()), &m_controller, SLOT(debugStep())); CONNASSERT(&m_controller, SIGNAL(setConnected(bool)), debugStepAct, SLOT(setEnabled(bool))); CONNASSERT(&m_controller, SIGNAL(setBreaked(bool)), debugStepAct, SLOT(setEnabled(bool))); debugStepAct->setShortcut(QKeySequence(Qt::Key_F11)); debugStepAct->setEnabled(false); debugStepDrawCallAct = new QAction(tr("&Draw step"), this); debugStepDrawCallAct->setStatusTip(tr("Step one GL drawing call")); CONNASSERT(debugStepDrawCallAct, SIGNAL(triggered()), &m_controller, SLOT(debugStepDrawCall())); CONNASSERT(&m_controller, SIGNAL(setConnected(bool)), debugStepDrawCallAct, SLOT(setEnabled(bool))); CONNASSERT(&m_controller, SIGNAL(setBreaked(bool)), debugStepDrawCallAct, SLOT(setEnabled(bool))); debugStepDrawCallAct->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_F11)); debugStepDrawCallAct->setEnabled(false); debugStepFrameAct = new QAction(tr("&Frame step"), this); debugStepFrameAct->setStatusTip(tr("Step one GL frame")); CONNASSERT(debugStepFrameAct, SIGNAL(triggered()), &m_controller, SLOT(debugStepFrame())); CONNASSERT(&m_controller, SIGNAL(setConnected(bool)), debugStepFrameAct, SLOT(setEnabled(bool))); CONNASSERT(&m_controller, SIGNAL(setBreaked(bool)), debugStepFrameAct, SLOT(setEnabled(bool))); debugStepFrameAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_F11)); debugStepFrameAct->setEnabled(false); addDeleteBreakPointsAct = new QAction(tr("&Breakpoints..."), this); addDeleteBreakPointsAct->setStatusTip(tr("Add or remove breakpoints")); CONNASSERT(addDeleteBreakPointsAct, SIGNAL(triggered()), this, SLOT(addDeleteBreakPoints())); addDeleteBreakPointsAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_B)); setBreakOnGLErrorAct = new QAction(tr("Break on GL error"), this); setBreakOnGLErrorAct->setStatusTip( tr("Break execution on GL error (glGetError() != GL_NO_ERROR)")); // this action has a state - it is checbox-like checkable DGLConfiguration& currentConfig = m_controller.getConfig(); setBreakOnGLErrorAct->setCheckable(true); setBreakOnGLErrorAct->setChecked(currentConfig.m_BreakOnGLError); CONNASSERT(setBreakOnGLErrorAct, SIGNAL(toggled(bool)), this, SLOT(setBreakOnWhatever(bool))); setBreakOnDebugOutputAct = new QAction(tr("Break on debug output"), this); setBreakOnDebugOutputAct->setStatusTip( tr("Break execution on debug output message")); // this action has a state - it is checbox-like checkable setBreakOnDebugOutputAct->setCheckable(true); setBreakOnDebugOutputAct->setChecked( currentConfig.m_BreakOnGLError); CONNASSERT(setBreakOnDebugOutputAct, SIGNAL(toggled(bool)), this, SLOT(setBreakOnWhatever(bool))); setBreakOnCompilerErrAct = new QAction(tr("Break on compiler/linker error"), this); setBreakOnCompilerErrAct->setStatusTip( tr("Break execution on debug GLSL compiler or linker error")); // this action has a state - it is checbox-like checkable setBreakOnCompilerErrAct->setCheckable(true); setBreakOnCompilerErrAct->setChecked( currentConfig.m_BreakOnCompilerError); CONNASSERT(setBreakOnCompilerErrAct, SIGNAL(toggled(bool)), this, SLOT(setBreakOnWhatever(bool))); // Only one color scheme can be choosed - put all related actions to // action // group setColorSchemeActGroup = new QActionGroup(this); // iterate through all color schemes. for each one create one action for (uint i = 0; i < DGLNUM_COLOR_SCHEMES; i++) { setColorSchemeActs[i] = new QAction(tr(dglColorSchemes[i].name), this); setColorSchemeActs[i]->setCheckable(true); setColorSchemeActs[i]->setActionGroup(setColorSchemeActGroup); setColorSchemeActs[i]->setStatusTip(tr("Set this color scheme")); // connect all color scheme actions to one mapper, so we can connect // it // later to only one signal m_SetColorSchemeSignalMapper.setMapping(setColorSchemeActs[i], i); CONNASSERT(setColorSchemeActs[i], SIGNAL(triggered()), &m_SetColorSchemeSignalMapper, SLOT(map())); } // mapper maps connected actions to one emitted signal by int parameter. // Connect this signal to "this" CONNASSERT(&m_SetColorSchemeSignalMapper, SIGNAL(mapped(int)), this, SLOT(setColorScheme(int))); configurationAct = new QAction(tr("Configuration..."), this); configurationAct->setStatusTip(tr("Configuration options")); CONNASSERT(configurationAct, SIGNAL(triggered()), this, SLOT(configure())); prepareAndroidAct = new QAction(tr("Prepare Android device..."), this); prepareAndroidAct->setStatusTip(tr("Installs " DGL_PRODUCT " on Android device")); CONNASSERT(prepareAndroidAct, SIGNAL(triggered()), this, SLOT(androidPrepare())); }
/** constructor read attributes for this GeoImage through dictionary*/ GeoImage::GeoImage(ArgDict & dict) { init(); configure(dict); }
void process_event_message(const events::event_message& message) { auto process_start_time = chrono::tsc_clock::now(); auto& metric_ptr = metrics_map[message.destination_name]; bool empty_metric = false; switch (metric_ptr.which()) { case metrics::metric_index::COUNTER: if (boost::get<metrics::counter*>(metric_ptr) == 0) { empty_metric = true; } break; case metrics::metric_index::GAUGE: if (boost::get<metrics::gauge*>(metric_ptr) == 0) { empty_metric = true; } break; case metrics::metric_index::TIMER: if (boost::get<metrics::timer*>(metric_ptr) == 0) { empty_metric = true; } break; case metrics::metric_index::ATTRIBUTE: if (boost::get<metrics::attribute*>(metric_ptr) == 0) { empty_metric = true; } break; } if (empty_metric) { rapidjson::Value* pattern_cfg = config::select_pattern(message.destination_name); switch (message.destination_type) { case events::event_destination_type::COUNTER: { auto counter_opts = config::metrics::counter_opts; if (pattern_cfg) { counter_opts.configure(*pattern_cfg); } metric_ptr = new metrics::counter(counter_opts); break; } case events::event_destination_type::GAUGE: { auto gauge_opts = config::metrics::gauge_opts; if (pattern_cfg) { gauge_opts.configure(*pattern_cfg); } metric_ptr = new metrics::gauge(gauge_opts); break; } case events::event_destination_type::TIMER: { auto timer_opts = config::metrics::timer_opts; if (pattern_cfg) { timer_opts.configure(*pattern_cfg); } metric_ptr = new metrics::timer(timer_opts); break; } case events::event_destination_type::ATTRIBUTE: { metric_ptr = new metrics::attribute(); break; } } } process_event_message(metric_ptr, message); auto process_end_time = chrono::tsc_clock::now(); stats::process_time.set( chrono::duration::convert_to(metrics::timer::value_unit, process_end_time - process_start_time).count(), process_end_time ); stats::size.set(size(), process_end_time); }
BOOL player_impl::open(const char *movie, int media_type, int render_type) { // 如果未关闭原来的媒体, 则先关闭. if (m_avplay || m_source) close(); // 未创建窗口, 无法播放, 返回失败. if (!IsWindow(m_hwnd)) return FALSE; char filename[MAX_PATH]; int len = strlen(movie) + 1; strcpy(filename, movie); uint64_t file_lentgh = 0; if (media_type == MEDIA_TYPE_FILE || media_type == MEDIA_TYPE_BT) { file_lentgh = file_size(movie); if (file_lentgh < 0) { ::logger("get file size failed!\n"); return FALSE; } } do { // 创建avplay. m_avplay = alloc_avplay_context(); if (!m_avplay) { ::logger("allocate avplay context failed!\n"); break; } // 为avplay创建demux. demux_context *demux = alloc_demux_context(); configure(m_avplay, demux, MEDIA_DEMUX); // 目前只有除youku之外, 都使用generic_demux. if (media_type != MEDIA_TYPE_YK) { demux->init_demux = generic_init_demux; demux->read_packet = generic_read_packet; demux->seek_packet = generic_packet_seek; demux->read_pause = generic_read_pause; demux->read_play = generic_read_play; demux->stream_index = generic_stream_index; demux->query_avcodec_id = generic_query_avcodec_id; demux->destory = generic_destory; } else { // TODO: 实现youku相关的demux. break; } // 初始化avplay. if (initialize(m_avplay, filename, media_type, demux) != 0) { ::logger("initialize avplay failed!\n"); break; } // TODO: 如果是bt类型, 则在此得到视频文件列表, 并添加到m_media_list. // if (media_type == MEDIA_TYPE_BT) // { // bt_source_info *bt_info = &m_avplay->m_source_ctx->info.bt; // for (int i = 0; i < bt_info->info_size; i++) // { // std::string name = std::string(bt_info->info[i].file_name); // m_media_list.insert(std::make_pair(filename, name)); // } // } // 分配音频和视频的渲染器. m_audio = alloc_audio_render(); if (!m_audio) { ::logger("allocate audio render failed!\n"); break; } m_video = alloc_video_render(m_hwnd); if (!m_video) { ::logger("allocate video render failed!\n"); break; } // 初始化音频和视频渲染器. init_audio(m_audio); init_video(m_video, render_type); // 配置音频视频渲染器. configure(m_avplay, m_video, VIDEO_RENDER); configure(m_avplay, m_audio, AUDIO_RENDER); // 得到视频宽高. if (m_avplay->m_video_ctx) { m_video_width = m_avplay->m_video_ctx->width; m_video_height = m_avplay->m_video_ctx->height; } // 打开视频实时码率和帧率计算. enable_calc_frame_rate(m_avplay); enable_calc_bit_rate(m_avplay); return TRUE; } while (0); if (m_avplay) free_avplay_context(m_avplay); m_avplay = NULL; if (m_source) free_media_source(m_source); if (m_audio) free_audio_render(m_audio); if (m_video) free_video_render(m_video); ::logger("open avplay failed!\n"); return FALSE; }
int main(int argc, char* argv[]) { signal(SIGSEGV, as_sig_handle_segv); signal(SIGTERM, as_sig_handle_term); fprintf(stdout, "\nAerospike act - device IO test\n"); fprintf(stdout, "Copyright 2011 by Aerospike. All rights reserved.\n\n"); if (! configure(argc, argv)) { exit(-1); } set_schedulers(); srand(time(NULL)); // rand_seed(g_rand_64_buffer); salter salters[g_num_write_buffers ? g_num_write_buffers : 1]; g_salters = salters; if (! create_salters()) { exit(-1); } device devices[g_num_devices]; g_devices = devices; g_p_large_block_read_histogram = histogram_create(); g_p_large_block_write_histogram = histogram_create(); g_p_raw_read_histogram = histogram_create(); g_p_read_histogram = histogram_create(); g_run_start_ms = cf_getms(); uint64_t run_stop_ms = g_run_start_ms + g_run_ms; g_running = 1; int n; for (n = 0; n < g_num_devices; n++) { device* p_device = &g_devices[n]; p_device->name = g_device_names[n]; p_device->p_fd_queue = cf_queue_create(sizeof(int), true); discover_num_blocks(p_device); create_large_block_read_buffer(p_device); p_device->p_raw_read_histogram = histogram_create(); sprintf(p_device->histogram_tag, "%-18s", p_device->name); if (pthread_create(&p_device->large_block_read_thread, NULL, run_large_block_reads, (void*)p_device)) { fprintf(stdout, "Error: create large block read thread %d\n", n); exit(-1); } if (pthread_create(&p_device->large_block_write_thread, NULL, run_large_block_writes, (void*)p_device)) { fprintf(stdout, "Error: create write thread %d\n", n); exit(-1); } } aio_context_t aio_context = 0; if(io_setup(MAXEVENTS, &aio_context) != 0) { fprintf(stdout, "Error: AIO context not set up \n"); exit(-1); } create_async_info_queue(); /* read events generating thread */ pthread_t read_generator; if (pthread_create(&read_generator, NULL, &generate_async_reads, (void*)&aio_context)) { fprintf(stdout, "Error: create read generator thread\n"); exit(-1); } /* Create the worker threads */ pthread_t workers[g_worker_threads]; int j; for (j = 0; j < g_worker_threads; j++) { if (pthread_create(&workers[j], NULL, &worker_func , (void *)(&aio_context))) { fprintf(stdout, "Error: creating worker thread %d failed\n", j); exit(-1); } } fprintf(stdout, "\n"); uint64_t now_ms; uint64_t time_count = 0; int nanosleep_ret = -1; struct timespec initial,remaining; while ((now_ms = cf_getms()) < run_stop_ms && g_running) { time_count++; int sleep_ms = (int) ((time_count * g_report_interval_ms) - (now_ms - g_run_start_ms)); if (sleep_ms > 0) { initial.tv_sec = sleep_ms / 1000; initial.tv_nsec = (sleep_ms % 1000) * 1000000; retry: memset(&remaining, 0, sizeof(remaining)); nanosleep_ret = nanosleep(&initial, &remaining); if(nanosleep_ret == -1 && errno == EINTR) { /* Interrupted by a signal */ initial.tv_sec = remaining.tv_sec; initial.tv_nsec = remaining.tv_nsec; goto retry; } } fprintf(stdout, "After %" PRIu64 " sec:\n", (time_count * g_report_interval_ms) / 1000); fprintf(stdout, "read-reqs queued: %" PRIu64 "\n", cf_atomic_int_get(g_read_reqs_queued)); histogram_dump(g_p_large_block_read_histogram, "LARGE BLOCK READS "); histogram_dump(g_p_large_block_write_histogram, "LARGE BLOCK WRITES"); histogram_dump(g_p_raw_read_histogram, "RAW READS "); int d; for (d = 0; d < g_num_devices; d++) { histogram_dump(g_devices[d].p_raw_read_histogram, g_devices[d].histogram_tag); } histogram_dump(g_p_read_histogram, "READS "); fprintf(stdout, "\n"); fflush(stdout); } fprintf(stdout, "\nTEST COMPLETED \n"); g_running = 0; int i; //TODO aio_destroy? /* Freeing resources used by async */ void* ret_value; for (i = 0; i < g_worker_threads; i++) { pthread_join(workers[i], &ret_value); } destroy_async_info_queue(); int d; for (d = 0; d < g_num_devices; d++) { device* p_device = &g_devices[d]; pthread_join(p_device->large_block_read_thread, &ret_value); pthread_join(p_device->large_block_write_thread, &ret_value); fd_close_all(p_device); cf_queue_destroy(p_device->p_fd_queue); free(p_device->p_large_block_read_buffer); free(p_device->p_raw_read_histogram); } free(g_p_large_block_read_histogram); free(g_p_large_block_write_histogram); free(g_p_raw_read_histogram); free(g_p_read_histogram); destroy_salters(); return (0); }
int16 XSERDPort::open(uint16 config) { // Don't open NULL name devices if (device_name == NULL) return openErr; // Init variables io_killed = false; quitting = false; // Open port, according to the syntax of the path if (device_name[0] == '|') { // Open a process via ptys if (!open_pty()) goto open_error; } else if (!strcmp(device_name, "midi")) { // MIDI: not yet implemented return openErr; } else { // Device special file fd = ::open(device_name, O_RDWR); if (fd < 0) goto open_error; #if defined(__linux__) // Parallel port? struct stat st; if (fstat(fd, &st) == 0) if (S_ISCHR(st.st_mode)) protocol = ((MAJOR(st.st_rdev) == LP_MAJOR) ? parallel : serial); #elif defined(__FreeBSD__) || defined(__NetBSD__) // Parallel port? struct stat st; if (fstat(fd, &st) == 0) if (S_ISCHR(st.st_mode)) protocol = (((st.st_rdev >> 16) == 16) ? parallel : serial); #endif } // Configure port for raw mode if (protocol == serial || protocol == pty) { if (tcgetattr(fd, &mode) < 0) goto open_error; cfmakeraw(&mode); mode.c_cflag |= HUPCL; mode.c_cc[VMIN] = 1; mode.c_cc[VTIME] = 0; tcsetattr(fd, TCSAFLUSH, &mode); } configure(config); // Start input/output threads input_thread_cancel = false; output_thread_cancel = false; if (sem_init(&input_signal, 0, 0) < 0) goto open_error; if (sem_init(&output_signal, 0, 0) < 0) goto open_error; input_thread_active = (pthread_create(&input_thread, &thread_attr, input_func, this) == 0); output_thread_active = (pthread_create(&output_thread, &thread_attr, output_func, this) == 0); if (!input_thread_active || !output_thread_active) goto open_error; return noErr; open_error: if (input_thread_active) { input_thread_cancel = true; #ifdef HAVE_PTHREAD_CANCEL pthread_cancel(input_thread); #endif pthread_join(input_thread, NULL); sem_destroy(&input_signal); input_thread_active = false; } if (output_thread_active) { output_thread_cancel = true; #ifdef HAVE_PTHREAD_CANCEL pthread_cancel(output_thread); #endif pthread_join(output_thread, NULL); sem_destroy(&output_signal); output_thread_active = false; } if (fd > 0) { ::close(fd); fd = -1; } return openErr; }
int main(int argc, char *argv[]) { assert(sizeof(localbuf) >= getpagesize()); close(STDIN_FILENO); setlocale(LC_ALL, "C"); if (!configure(argc, argv)) return EXIT_FAILURE; if (unlikely(!read_proc_swaps()) || unlikely(!activate_old_swaps()) || unlikely(!check_memory_status())) return EXIT_FAILURE; if (erase) return retire_all() ? EXIT_SUCCESS : EXIT_FAILURE; install_sigs(); if (unlikely(!startpidfile())) return EXIT_FAILURE; /* Do a first iteration here so we can report any startup errors, and if we're * going to run as a daemon, we can do so in a steady state. */ handle_requirements(); /* If we're going to fork(), this is the last chance to read /proc/swaps in a * nonempty state before we do so. Make one last attempt to check its format. */ if (!proc_swaps_parsed()) { if (!read_proc_swaps()) return EXIT_FAILURE; #ifndef NO_CONFIG if (!quiet && !proc_swaps_parsed()) fputs("[/proc/swaps is empty, so cannot check its format]\n", stderr); #endif } if (godaemon) { #ifndef NO_CONFIG if (verbose) logm(LOG_DEBUG, "daemonizing..."); #endif const pid_t pid = daemonize(); if (unlikely(pid < 0)) { rmpidfile(); return EXIT_FAILURE; } if (pid > 0) { /* New process, so new pid. Parent process rewrites pidfile. We do this * from the parent, not the child process so that we're sure that the * pidfile is in a stable state when the parent exits. */ lseek(pidfd, 0, SEEK_SET); #ifndef NO_CONFIG if (verbose) logm(LOG_DEBUG, "got process id %d", pid); #endif return writepid(pid) ? EXIT_SUCCESS : EXIT_FAILURE; } } finishpidfile(); if (godaemon) { close(STDERR_FILENO); close(STDOUT_FILENO); // From here on std output is pointless in daemon mode. Use syslog instead. log_start(argv[0]); } // Central loop for (++runclock; !stop; ++runclock) { if (unlikely(print_status)) print_status = false, dump_stats(); else if (unlikely(adjust_swap)) adjust_swap = false, request_diet(); else handle_requirements(); sleep(1); } int result = EXIT_SUCCESS; #ifndef NO_CONFIG /* If we're worried about attackers getting unguarded access to the disk, we * need to retire and erase all swap files to keep them secret. */ if (paranoid && !retire_all()) result = EXIT_FAILURE; #endif rmpidfile(); log_close(); return result; }
/* * This version of Berkeley's rwhod has been modified to use IP multicast * datagrams, under control of a new command-line option: * * rwhod -m causes rwhod to use IP multicast (instead of * broadcast or unicast) on all interfaces that have * the IFF_MULTICAST flag set in their "ifnet" structs * (excluding the loopback interface). The multicast * reports are sent with a time-to-live of 1, to prevent * forwarding beyond the directly-connected subnet(s). * * rwhod -m <ttl> causes rwhod to send IP multicast datagrams with a * time-to-live of <ttl>, via a SINGLE interface rather * than all interfaces. <ttl> must be between 0 and * MAX_MULTICAST_SCOPE, defined below. Note that "-m 1" * is different than "-m", in that "-m 1" specifies * transmission on one interface only. * * When "-m" is used without a <ttl> argument, the program accepts multicast * rwhod reports from all multicast-capable interfaces. If a <ttl> argument * is given, it accepts multicast reports from only one interface, the one * on which reports are sent (which may be controlled via the host's routing * table). Regardless of the "-m" option, the program accepts broadcast or * unicast reports from all interfaces. Thus, this program will hear the * reports of old, non-multicasting rwhods, but, if multicasting is used, * those old rwhods won't hear the reports generated by this program. * * -- Steve Deering, Stanford University, February 1989 */ int main(int argc, char *argv[]) { int on; char *cp; struct sockaddr_in soin; uid_t unpriv_uid; gid_t unpriv_gid; on = 1; if (getuid()) errx(1, "not super user"); run_as(&unpriv_uid, &unpriv_gid); argv++; argc--; while (argc > 0 && *argv[0] == '-') { if (strcmp(*argv, "-m") == 0) { if (argc > 1 && isdigit(*(argv + 1)[0])) { argv++; argc--; multicast_mode = SCOPED_MULTICAST; multicast_scope = atoi(*argv); if (multicast_scope > MAX_MULTICAST_SCOPE) { errx(1, "ttl must not exceed %u", MAX_MULTICAST_SCOPE); } } else { multicast_mode = PER_INTERFACE_MULTICAST; } } else if (strcmp(*argv, "-i") == 0) { insecure_mode = 1; } else if (strcmp(*argv, "-l") == 0) { quiet_mode = 1; } else if (strcmp(*argv, "-p") == 0) { iff_flag = 0; } else { usage(); } argv++; argc--; } if (argc > 0) usage(); #ifndef DEBUG daemon(1, 0); #endif (void) signal(SIGHUP, getboottime); openlog("rwhod", LOG_PID | LOG_NDELAY, LOG_DAEMON); sp = getservbyname("who", "udp"); if (sp == NULL) { syslog(LOG_ERR, "who/udp: unknown service"); exit(1); } if (chdir(_PATH_RWHODIR) < 0) { syslog(LOG_ERR, "%s: %m", _PATH_RWHODIR); exit(1); } /* * Establish host name as returned by system. */ if (gethostname(myname, sizeof(myname) - 1) < 0) { syslog(LOG_ERR, "gethostname: %m"); exit(1); } if ((cp = strchr(myname, '.')) != NULL) *cp = '\0'; strlcpy(mywd.wd_hostname, myname, sizeof(mywd.wd_hostname)); getboottime(0); if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { syslog(LOG_ERR, "socket: %m"); exit(1); } if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0) { syslog(LOG_ERR, "setsockopt SO_BROADCAST: %m"); exit(1); } memset(&soin, 0, sizeof(soin)); soin.sin_len = sizeof(soin); soin.sin_family = AF_INET; soin.sin_port = sp->s_port; if (bind(s, (struct sockaddr *)&soin, sizeof(soin)) < 0) { syslog(LOG_ERR, "bind: %m"); exit(1); } if (setgid(unpriv_gid) != 0) { syslog(LOG_ERR, "setgid: %m"); exit(1); } if (setgroups(1, &unpriv_gid) != 0) { /* XXX BOGUS groups[0] = egid */ syslog(LOG_ERR, "setgroups: %m"); exit(1); } if (setuid(unpriv_uid) != 0) { syslog(LOG_ERR, "setuid: %m"); exit(1); } if (!configure(s)) exit(1); if (!quiet_mode) { pid_child_receiver = pdfork(&fdp, 0); if (pid_child_receiver == 0) { receiver_process(); } else if (pid_child_receiver > 0) { sender_process(); } else if (pid_child_receiver == -1) { if (errno == ENOSYS) { syslog(LOG_ERR, "The pdfork(2) system call is not available - kernel too old."); } else { syslog(LOG_ERR, "pdfork: %m"); } exit(1); } } else { receiver_process(); } }
SphericalCamera(Stream *stream, InstanceManager *manager) : Sensor(stream, manager) { configure(); }
void configure_callback(home_command_manager::home_command_managerConfig &config, uint32_t level) { configure(); }
/** \brief Function associated with the widget. */ int entryFunc ( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * const objv[] ) { #ifdef DEBUG_ENTRY g_print ( "entryFunc\n" ); #endif static const char *cmds[] = { "delete", "configure", "cget", "onChanged", "class", "get", "clear", "set", "setPosition", NULL }; enum cmdIdx { DeleteIdx, ConfigureIdx, CgetIdx, OnChangedIdx, ClassIdx, GetIdx, ClearIdx, SetIdx, SetPositionIdx }; EntryParams *para = ( EntryParams * ) data; //GtkWidget *widget = GTK_WIDGET ( para->entry ); int idx; if ( objc < 2 ) { Tcl_WrongNumArgs ( interp, 1, objv, "command" ); return TCL_ERROR; } if ( Tcl_GetIndexFromObj ( interp, objv[1], cmds, "command", TCL_EXACT, &idx ) != TCL_OK ) return TCL_ERROR; switch ( idx ) { case SetPositionIdx: { if ( 1 ) { gtk_entry_set_position ( GTK_WIDGET ( para->entry ) , Tcl_GetString ( objv[2] ) ); } else { gtk_editable_set_position ( GTK_EDITABLE ( GTK_WIDGET ( para->entry ) ) , Tcl_GetString ( objv[2] ) ); } } break; case SetIdx: { /* simply set the text to nothing */ gtk_entry_set_text ( para->entry, Tcl_GetString ( objv[2] ) ); } break; case GetIdx: { /* equivalent to widget cget -value */ Tcl_Obj *obj = NULL; obj = Tcl_NewStringObj ( gtk_entry_get_text ( para->entry ), -1 ); if ( obj != NULL ) { Tcl_SetObjResult ( interp, obj ); return TCL_OK; } } break; case ClearIdx: { /* simply set the text to nothing */ gtk_entry_set_text ( para->entry, "" ); } break; case ClassIdx: { Tcl_SetObjResult ( interp, Tcl_NewStringObj ( "entry", -1 ) ); } break; case DeleteIdx: { return gnoclDelete ( interp, GTK_WIDGET ( para->entry ), objc, objv ); } case ConfigureIdx: { #ifdef DEBUG_ENTRY g_print ( "entryFunc ConfigureIdx\n" ); #endif int ret = TCL_ERROR; if ( gnoclParseAndSetOptions ( interp, objc - 1, objv + 1, entryOptions, G_OBJECT ( para->entry ) ) == TCL_OK ) { ret = configure ( interp, para, entryOptions ); } gnoclClearOptions ( entryOptions ); return ret; } break; case CgetIdx: { int idx; switch ( gnoclCget ( interp, objc, objv, G_OBJECT ( para->entry ), entryOptions, &idx ) ) { case GNOCL_CGET_ERROR: return TCL_ERROR; case GNOCL_CGET_HANDLED: return TCL_OK; case GNOCL_CGET_NOTHANDLED: return cget ( interp, para, entryOptions, idx ); } } case OnChangedIdx: { const char *txt = gtk_entry_get_text ( para->entry ); if ( objc != 2 ) { Tcl_WrongNumArgs ( interp, 2, objv, NULL ); return TCL_ERROR; } return doCommand ( para, txt, 0 ); } } return TCL_OK; }
int fimg2d4x_bitblt(struct fimg2d_control *ctrl) { int ret = 0; enum addr_space addr_type; struct fimg2d_context *ctx; struct fimg2d_bltcmd *cmd; unsigned long *pgd; fimg2d_debug("%s : enter blitter\n", __func__); while (1) { cmd = fimg2d_get_command(ctrl); if (!cmd) break; ctx = cmd->ctx; ctx->state = CTX_READY; #ifdef CONFIG_PM_RUNTIME if (fimg2d4x_get_clk_cnt(ctrl->clock) == false) fimg2d_err("2D clock is not set\n"); #endif addr_type = cmd->image[IDST].addr.type; atomic_set(&ctrl->busy, 1); perf_start(cmd, PERF_SFR); ret = ctrl->configure(ctrl, cmd); perf_end(cmd, PERF_SFR); if (IS_ERR_VALUE(ret)) { fimg2d_err("failed to configure\n"); ctx->state = CTX_ERROR; goto fail_n_del; } ctx->vma_lock = vma_lock_mapping(ctx->mm, prefbuf, MAX_IMAGES - 1); if (fimg2d_check_pgd(ctx->mm, cmd)) { ret = -EFAULT; goto fail_n_unmap; } if (addr_type == ADDR_USER || addr_type == ADDR_USER_CONTIG) { if (!ctx->mm || !ctx->mm->pgd) { atomic_set(&ctrl->busy, 0); fimg2d_err("ctx->mm:0x%p or ctx->mm->pgd:0x%p\n", ctx->mm, (ctx->mm) ? ctx->mm->pgd : NULL); ret = -EPERM; goto fail_n_unmap; } pgd = (unsigned long *)ctx->mm->pgd; #ifdef FIMG2D_IOVMM_PAGETABLE if (iovmm_activate(ctrl->dev)) { fimg2d_err("failed to iovmm activate\n"); ret = -EPERM; goto fail_n_unmap; } #else if (exynos_sysmmu_enable(ctrl->dev, (unsigned long)virt_to_phys(pgd))) { fimg2d_err("failed to sysmme enable\n"); ret = -EPERM; goto fail_n_unmap; } #endif fimg2d_debug("%s : sysmmu enable: pgd %p ctx %p seq_no(%u)\n", __func__, pgd, ctx, cmd->blt.seq_no); //exynos_sysmmu_set_pbuf(ctrl->dev, nbufs, prefbuf); fimg2d_debug("%s : set smmu prefbuf\n", __func__); } fimg2d4x_pre_bitblt(ctrl, cmd); perf_start(cmd, PERF_BLIT); /* start blit */ fimg2d_debug("%s : start blit\n", __func__); ctrl->run(ctrl); ret = fimg2d4x_blit_wait(ctrl, cmd); perf_end(cmd, PERF_BLIT); #ifdef FIMG2D_IOVMM_PAGETABLE if (addr_type == ADDR_USER || addr_type == ADDR_USER_CONTIG) iovmm_deactivate(ctrl->dev); #else if (addr_type == ADDR_USER || addr_type == ADDR_USER_CONTIG) exynos_sysmmu_disable(ctrl->dev); #endif fail_n_unmap: perf_start(cmd, PERF_UNMAP); if (addr_type == ADDR_USER || addr_type == ADDR_USER_CONTIG) { fimg2d4x_cleanup_pgtable(ctrl, cmd, ISRC, true); fimg2d4x_cleanup_pgtable(ctrl, cmd, IMSK, false); fimg2d4x_cleanup_pgtable(ctrl, cmd, IDST, true); fimg2d_debug("sysmmu disable\n"); } perf_end(cmd, PERF_UNMAP); fail_n_del: vma_unlock_mapping(ctx->vma_lock); fimg2d_del_command(ctrl, cmd); } fimg2d_debug("%s : exit blitter\n", __func__); return ret; }
/** Sets up the application - returns false if the user chooses to abandon configuration. */ bool AApplication::setup(void) { mRoot = new Root(); setupResources("media/common/"); bool carryOn = configure(); if (!carryOn) return false; chooseSceneManager(); // Set default mipmap level (NB some APIs ignore this) TextureManager::getSingleton().setDefaultNumMipmaps(5); ResourceGroupManager::getSingleton().initialiseResourceGroup("Bootstrap"); ResourceGroupManager::getSingleton().initialiseResourceGroup(GUI_RESOURCE_GROUP); ResourceGroupManager::getSingleton().initialiseResourceGroup("General"); ScriptsCamera = mSceneMgr->createCamera("ScriptsCamera"); ScriptsCamera->setNearClipDistance(5); ScriptsCamera->setFarClipDistance(0); CombatCamera = mSceneMgr->createCamera("CombatCamera"); CombatCamera->setNearClipDistance(5); CombatCamera->setFarClipDistance(0); Ogre::SceneNode *node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); node->attachObject(ScriptsCamera); createCamera(); createViewports(); Core *Instance = Core::GetInstance(); Instance->SetSceneManager(mSceneMgr); Instance->SetApplication(this); InitGui(); if (0!=Instance->Init()) return false; //CurrentListener = GUISystem::GetInstance(); //mRoot->addFrameListener(CurrentListener); /*MaterialPtr fade = Ogre::MaterialManager::getSingleton().create("FadeMaterial", "General"); fade->getTechnique(0)->getPass(0)->setSceneBlending(SBT_TRANSPARENT_ALPHA);*/ createFrameListener(); AACommandsFrameListener *commands_listener = AACommandsFrameListener::GetInstance(); commands_listener->Init(mWindow); commands_listener->SetCurrentHandler(Instance); mRoot->addFrameListener(commands_listener); EditorFrameListener *editor_listener = EditorFrameListener::GetInstance(); editor_listener->Init(mWindow); CombatFrameListener::GetInstance()->Init(mWindow); ComixFrameListener::GetInstance()->Init(mWindow); //SetCurrentGameState(AApplication::GS_STUDIOINTRO); SetCurrentGameState(AApplication::GS_COMIX); ComixFrameHandler *handler = new ComixFrameHandler(); TiXmlElement *xml = ObjectsLibrary::GetParsed("logo_intro.xml"); handler->Parse(xml); delete xml; ComixFrameListener *listener = ComixFrameListener::GetInstance(); listener->SetCurrentHandler(handler); CommonDeclarations::PlayIntroMusic(true); //handler->Show(0); //handler->SetActive(0, true); //handler->Show(1); //handler->SetActive(1, true); //SetCurrentGameState(AApplication::GS_GUI); //GUISystem::GetInstance()->GetIntroMenu()->Show(); //GUISystem::GetInstance()->Show(); return true; }
int main(int argc, char **argv) { krb5_error_code ret; krb5_context context; krb5_kdc_configuration *config; int optidx = 0; setprogname(argv[0]); ret = krb5_init_context(&context); if (ret == KRB5_CONFIG_BADFORMAT) errx (1, "krb5_init_context failed to parse configuration file"); else if (ret) errx (1, "krb5_init_context failed: %d", ret); ret = krb5_kt_register(context, &hdb_get_kt_ops); if (ret) errx (1, "krb5_kt_register(HDB) failed: %d", ret); config = configure(context, argc, argv, &optidx); #ifdef HAVE_SIGACTION { struct sigaction sa; sa.sa_flags = 0; sa.sa_handler = sigterm; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); #ifdef SIGXCPU sigaction(SIGXCPU, &sa, NULL); #endif sa.sa_handler = SIG_IGN; #ifdef SIGPIPE sigaction(SIGPIPE, &sa, NULL); #endif } #else signal(SIGINT, sigterm); signal(SIGTERM, sigterm); #ifdef SIGXCPU signal(SIGXCPU, sigterm); #endif #ifdef SIGPIPE signal(SIGPIPE, SIG_IGN); #endif #endif #ifdef __APPLE__ bonjour_announce(context, config); #endif pidfile(NULL); switch_environment(); loop(context, config); krb5_free_context(context); return 0; }
// virtual LLIOPipe::EStatus LLURLRequest::process_impl( const LLChannelDescriptors& channels, buffer_ptr_t& buffer, bool& eos, LLSD& context, LLPumpIO* pump) { PUMP_DEBUG; LLMemType m1(LLMemType::MTYPE_IO_URL_REQUEST); //llinfos << "LLURLRequest::process_impl()" << llendl; if(!buffer) return STATUS_ERROR; switch(mState) { case STATE_INITIALIZED: { PUMP_DEBUG; // We only need to wait for input if we are uploading // something. if(((HTTP_PUT == mAction) || (HTTP_POST == mAction)) && !eos) { // we're waiting to get all of the information return STATUS_BREAK; } // *FIX: bit of a hack, but it should work. The configure and // callback method expect this information to be ready. mDetail->mResponseBuffer = buffer.get(); mDetail->mChannels = channels; if(!configure()) { return STATUS_ERROR; } mState = STATE_WAITING_FOR_RESPONSE; // *FIX: Maybe we should just go to the next state now... return STATUS_BREAK; } case STATE_WAITING_FOR_RESPONSE: case STATE_PROCESSING_RESPONSE: { PUMP_DEBUG; LLIOPipe::EStatus status = STATUS_BREAK; mDetail->mCurlRequest->perform(); while(1) { CURLcode result; bool newmsg = mDetail->mCurlRequest->getResult(&result); if(!newmsg) { // we're still waiting or prcessing, check how many // bytes we have accumulated. const S32 MIN_ACCUMULATION = 100000; if(pump && (mDetail->mByteAccumulator > MIN_ACCUMULATION)) { // This is a pretty sloppy calculation, but this // tries to make the gross assumption that if data // is coming in at 56kb/s, then this transfer will // probably succeed. So, if we're accumlated // 100,000 bytes (MIN_ACCUMULATION) then let's // give this client another 2s to complete. const F32 TIMEOUT_ADJUSTMENT = 2.0f; mDetail->mByteAccumulator = 0; pump->adjustTimeoutSeconds(TIMEOUT_ADJUSTMENT); } // keep processing break; } mState = STATE_HAVE_RESPONSE; switch(result) { case CURLE_OK: case CURLE_WRITE_ERROR: // NB: The error indication means that we stopped the // writing due the body limit being reached if(mCompletionCallback && pump) { LLURLRequestComplete* complete = NULL; complete = (LLURLRequestComplete*) mCompletionCallback.get(); complete->responseStatus( result == CURLE_OK ? STATUS_OK : STATUS_STOP); LLPumpIO::links_t chain; LLPumpIO::LLLinkInfo link; link.mPipe = mCompletionCallback; link.mChannels = LLBufferArray::makeChannelConsumer( channels); chain.push_back(link); pump->respond(chain, buffer, context); mCompletionCallback = NULL; } break; case CURLE_FAILED_INIT: case CURLE_COULDNT_CONNECT: status = STATUS_NO_CONNECTION; break; default: llwarns << "URLRequest Error: " << result << ", " << LLCurl::strerror(result) << ", " << (mDetail->mURL.empty() ? "<EMPTY URL>" : mDetail->mURL) << llendl; status = STATUS_ERROR; break; } } return status; } case STATE_HAVE_RESPONSE: PUMP_DEBUG; // we already stuffed everything into channel in in the curl // callback, so we are done. eos = true; return STATUS_DONE; default: PUMP_DEBUG; return STATUS_ERROR; } }
void RayShape2DSW::set_data(const Variant& p_data) { length=p_data; configure(Rect2(0,0,0.001,length)); }
ABC(Stream *stream, InstanceManager *manager) : BSDF(stream, manager) { configure(); }
void CircleShape2DSW::set_data(const Variant& p_data) { ERR_FAIL_COND(!p_data.is_num()); radius=p_data; configure(Rect2(-radius,-radius,radius*2,radius*2)); }
int16 XSERDPort::control(uint32 pb, uint32 dce, uint16 code) { switch (code) { case 1: // KillIO io_killed = true; if (protocol == serial) tcflush(fd, TCIOFLUSH); while (read_pending || write_pending) usleep(10000); io_killed = false; return noErr; case kSERDConfiguration: if (configure(ReadMacInt16(pb + csParam))) return noErr; else return paramErr; case kSERDInputBuffer: return noErr; // Not supported under Unix case kSERDSerHShake: set_handshake(pb + csParam, false); return noErr; case kSERDSetBreak: if (protocol == serial) tcsendbreak(fd, 0); return noErr; case kSERDClearBreak: return noErr; case kSERDBaudRate: { if (protocol != serial) return noErr; uint16 rate = ReadMacInt16(pb + csParam); speed_t baud_rate; if (rate <= 50) { rate = 50; baud_rate = B50; } else if (rate <= 75) { rate = 75; baud_rate = B75; } else if (rate <= 110) { rate = 110; baud_rate = B110; } else if (rate <= 134) { rate = 134; baud_rate = B134; } else if (rate <= 150) { rate = 150; baud_rate = B150; } else if (rate <= 200) { rate = 200; baud_rate = B200; } else if (rate <= 300) { rate = 300; baud_rate = B300; } else if (rate <= 600) { rate = 600; baud_rate = B600; } else if (rate <= 1200) { rate = 1200; baud_rate = B1200; } else if (rate <= 1800) { rate = 1800; baud_rate = B1800; } else if (rate <= 2400) { rate = 2400; baud_rate = B2400; } else if (rate <= 4800) { rate = 4800; baud_rate = B4800; } else if (rate <= 9600) { rate = 9600; baud_rate = B9600; } else if (rate <= 19200) { rate = 19200; baud_rate = B19200; } else if (rate <= 38400) { rate = 38400; baud_rate = B38400; } else if (rate <= 57600) { rate = 57600; baud_rate = B57600; } else { // Just for safety in case someone wants a rate between 57600 and 65535 rate = 57600; baud_rate = B57600; } WriteMacInt16(pb + csParam, rate); cfsetispeed(&mode, baud_rate); cfsetospeed(&mode, baud_rate); tcsetattr(fd, TCSANOW, &mode); return noErr; } case kSERDHandshake: case kSERDHandshakeRS232: set_handshake(pb + csParam, true); return noErr; case kSERDMiscOptions: if (protocol != serial) return noErr; if (ReadMacInt8(pb + csParam) & kOptionPreserveDTR) mode.c_cflag &= ~HUPCL; else mode.c_cflag |= HUPCL; tcsetattr(fd, TCSANOW, &mode); return noErr; case kSERDAssertDTR: { if (protocol != serial) return noErr; unsigned int status = TIOCM_DTR; ioctl(fd, TIOCMBIS, &status); return noErr; } case kSERDNegateDTR: { if (protocol != serial) return noErr; unsigned int status = TIOCM_DTR; ioctl(fd, TIOCMBIC, &status); return noErr; } case kSERDSetPEChar: case kSERDSetPEAltChar: return noErr; // Not supported under Unix case kSERDResetChannel: if (protocol == serial) tcflush(fd, TCIOFLUSH); return noErr; case kSERDAssertRTS: { if (protocol != serial) return noErr; unsigned int status = TIOCM_RTS; ioctl(fd, TIOCMBIS, &status); return noErr; } case kSERDNegateRTS: { if (protocol != serial) return noErr; unsigned int status = TIOCM_RTS; ioctl(fd, TIOCMBIC, &status); return noErr; } case kSERD115KBaud: if (protocol != serial) return noErr; cfsetispeed(&mode, B115200); cfsetospeed(&mode, B115200); tcsetattr(fd, TCSANOW, &mode); return noErr; case kSERD230KBaud: case kSERDSetHighSpeed: if (protocol != serial) return noErr; cfsetispeed(&mode, B230400); cfsetospeed(&mode, B230400); tcsetattr(fd, TCSANOW, &mode); return noErr; default: printf("WARNING: SerialControl(): unimplemented control code %d\n", code); return controlErr; } }
void ConcavePolygonShape2DSW::set_data(const Variant& p_data) { ERR_FAIL_COND(p_data.get_type()!=Variant::VECTOR2_ARRAY && p_data.get_type()!=Variant::REAL_ARRAY); Rect2 aabb; if (p_data.get_type()==Variant::VECTOR2_ARRAY) { DVector<Vector2> p2arr = p_data; int len = p2arr.size(); ERR_FAIL_COND(len%2); segments.clear(); points.clear(); bvh.clear(); bvh_depth=1; if (len==0) { configure(aabb); return; } DVector<Vector2>::Read arr = p2arr.read(); Map<Point2,int> pointmap; for(int i=0;i<len;i+=2) { Point2 p1 =arr[i]; Point2 p2 =arr[i+1]; int idx_p1,idx_p2; if (pointmap.has(p1)) { idx_p1=pointmap[p1]; } else { idx_p1=pointmap.size(); pointmap[p1]=idx_p1; } if (pointmap.has(p2)) { idx_p2=pointmap[p2]; } else { idx_p2=pointmap.size(); pointmap[p2]=idx_p2; } Segment s; s.points[0]=idx_p1; s.points[1]=idx_p2; segments.push_back(s); } points.resize(pointmap.size()); aabb.pos=pointmap.front()->key(); for(Map<Point2,int>::Element *E=pointmap.front();E;E=E->next()) { aabb.expand_to(E->key()); points[E->get()]=E->key(); } Vector<BVH> main_vbh; main_vbh.resize(segments.size()); for(int i=0;i<main_vbh.size();i++) { main_vbh[i].aabb.pos=points[segments[i].points[0]]; main_vbh[i].aabb.expand_to(points[segments[i].points[1]]); main_vbh[i].left=-1; main_vbh[i].right=i; } _generate_bvh(&main_vbh[0],main_vbh.size(),1); } else { //dictionary with arrays } configure(aabb); }
bool QAhiScreen::connect(const QString &displaySpec) { Q_UNUSED(displaySpec); AhiSts_t status; status = AhiInit(0); if (status != AhiStsOk) { qCritical("QAhiScreen::connect(): AhiInit failed: %x", status); return false; } AhiDev_t device; AhiDevInfo_t info; status = AhiDevEnum(&device, &info, 0); if (status != AhiStsOk) { qCritical("QAhiScreen::connect(): AhiDevEnum failed: %x", status); return false; } #ifdef QAHISCREEN_DEBUG { int displayNo = 0; AhiDevInfo_t dispInfo = info; qDebug("AHI supported devices:"); do { qDebug(" %2i: %s, sw version: %s (rev %u)\n" " chip: 0x%x (rev %u), mem: %i (%i/%i), bus: 0x%x", displayNo, dispInfo.name, dispInfo.swVersion, uint(dispInfo.swRevision), uint(dispInfo.chipId), uint(dispInfo.revisionId), uint(dispInfo.totalMemory), uint(dispInfo.internalMemSize), uint(dispInfo.externalMemSize), uint(dispInfo.cpuBusInterfaceMode)); status = AhiDevEnum(&device, &info, ++displayNo); } while (status == AhiStsOk); } #endif status = AhiDevOpen(&d_ptr->context, device, "qscreenahi", AHIFLAG_USERLEVEL); if (status != AhiStsOk) { qCritical("QAhiScreen::connect(): AhiDevOpen failed: %x", status); return false; } AhiDispMode_t mode; status = AhiDispModeEnum(d_ptr->context, &mode, 0); if (status != AhiStsOk) { qCritical("QAhiScreen::connect(): AhiDispModeEnum failed: %x", status); return false; } #ifdef QAHISCREEN_DEBUG { int modeNo = 0; AhiDispMode_t modeInfo = mode; qDebug("AHI supported modes:"); do { qDebug(" %2i: %ux%u, fmt: %i, %u Hz, rot: %i, mirror: %i", modeNo, uint(modeInfo.size.cx), uint(modeInfo.size.cy), modeInfo.pixFmt, uint(modeInfo.frequency), modeInfo.rotation, modeInfo.mirror); status = AhiDispModeEnum(d_ptr->context, &modeInfo, ++modeNo); } while (status == AhiStsOk); } #endif if (QApplication::type() == QApplication::GuiServer) { if (!d_ptr->setMode(mode)) return false; } else { status = AhiDispSurfGet(d_ptr->context, &d_ptr->surface); if (status != AhiStsOk) { qCritical("QAhiScreen::connect(): AhiDispSurfGet failed: %x", status); return false; } status = AhiDispModeGet(d_ptr->context, &mode); if (status != AhiStsOk) { qCritical("QAhiScreen::context(): AhiDispModeGet failed: %x", status); return false; } } return configure(); }
void Simulation::configure(const config::Configuration& config) { // Resize world { auto size = config.get<SizeVector>("world-size"); if (size.getWidth() == Zero || size.getHeight() == Zero) throw config::Exception("Width or height is zero!"); setWorldSize(size); } // Time step setTimeStep(config.get<units::Time>("dt")); if (config.has("length-coefficient")) { m_converter.setLengthCoefficient(config.get<RealType>("length-coefficient")); } // Set gravity setGravity(config.get("gravity", getGravity())); // Number of iterations setIterations(config.get("iterations", getIterations())); // Background color setBackgroundColor(config.get("background", getBackgroundColor())); #if CONFIG_RENDER_TEXT_ENABLE setFontColor(config.get("text-color", getBackgroundColor().inverted())); #endif #if CONFIG_RENDER_TEXT_ENABLE setFontSize(config.get("text-size", getFontSize())); #endif #if CONFIG_RENDER_TEXT_ENABLE setSimulationTimeRender(config.get("show-simulation-time", isSimulationTimeRender())); #endif #ifdef CECE_ENABLE_RENDER setVisualized(config.get("visualized", isVisualized())); #endif // Parse plugins for (auto&& pluginConfig : config.getConfigurations("plugin")) { // Returns valid pointer or throws an exception requirePlugin(pluginConfig.get("name"))->configure(*this, pluginConfig); } // Parse parameters for (auto&& parameterConfig : config.getConfigurations("parameter")) { setParameter(parameterConfig.get("name"), units::parse(parameterConfig.get("value"))); } // Register user types for (auto&& typeConfig : config.getConfigurations("type")) { addObjectType({ typeConfig.get("name"), typeConfig.get("base"), typeConfig.toMemory() }); } // Parse init for (auto&& initConfig : config.getConfigurations("init")) { const String typeName = initConfig.has("language") ? initConfig.get("language") : initConfig.get("type"); auto initializer = getPluginContext().createInitializer(typeName); if (initializer) { // Configure initializer initializer->loadConfig(*this, initConfig); // Register initializer addInitializer(std::move(initializer)); } } // Parse modules for (auto&& moduleConfig : config.getConfigurations("module")) { // Get name auto name = moduleConfig.get("name"); if (hasModule(name)) continue; const String typeName = moduleConfig.has("language") ? moduleConfig.get("language") : moduleConfig.has("type") ? moduleConfig.get("type") : name ; auto module = getPluginContext().createModule(typeName, *this); if (module) { module->loadConfig(*this, moduleConfig); addModule(std::move(name), std::move(module)); } } // Parse programs for (auto&& programConfig : config.getConfigurations("program")) { const String typeName = programConfig.has("language") ? programConfig.get("language") : programConfig.get("type"); auto program = getPluginContext().createProgram(typeName); if (program) { // Configure program program->loadConfig(*this, programConfig); // Register program addProgram(programConfig.get("name"), std::move(program)); } } // Parse objects for (auto&& objectConfig : config.getConfigurations("object")) { // Create object auto object = buildObject( objectConfig.get("class"), objectConfig.get("type", object::Object::Type::Dynamic) ); if (object) object->configure(objectConfig, *this); } if (config.has("data-out-objects-filename")) { m_dataOutObjects = makeUnique<OutFileStream>(config.get("data-out-objects-filename")); *m_dataOutObjects << "iteration;totalTime;id;typeName;posX;posY;velX;velY\n"; } }
LanczosSincFilter(Stream *stream, InstanceManager *manager) : ReconstructionFilter(stream, manager) { configure(); }
void configure( const T& taps, const size_t decimation_factor ) { configure(taps.data(), taps.size(), decimation_factor); }
/***f* socket/staticFuncs/socketFunc * AUTHOR * PGB * SOURCE */ static int socketFunc ( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * const objv[] ) { const char *cmds[] = { "delete", "configure", "getID", "getPlugID", NULL }; enum cmdIdx { DeleteIdx, ConfigureIdx, GetIDIdx, GetPlugIDIdx }; int idx; GtkSocket *socket = GTK_SOCKET ( data ); if ( objc < 2 ) { Tcl_WrongNumArgs ( interp, 1, objv, "command" ); return TCL_ERROR; } if ( Tcl_GetIndexFromObj ( interp, objv[1], cmds, "command", TCL_EXACT, &idx ) != TCL_OK ) return TCL_ERROR; switch ( idx ) { case DeleteIdx: return gnoclDelete ( interp, GTK_WIDGET ( socket ), objc, objv ); case ConfigureIdx: { int ret = TCL_ERROR; if ( gnoclParseAndSetOptions ( interp, objc - 1, objv + 1, socketOptions, G_OBJECT ( socket ) ) == TCL_OK ) { ret = configure ( interp, socket, socketOptions ); } gnoclClearOptions ( socketOptions ); return ret; } break; case GetIDIdx: { long xid; Tcl_Obj *val; if ( objc != 2 ) { Tcl_WrongNumArgs ( interp, 2, objv, NULL ); return TCL_ERROR; } #ifdef WIN32 xid = gtk_socket_get_id(socket); #else xid = GDK_WINDOW_XWINDOW ( GTK_WIDGET ( socket )->window ); #endif val = Tcl_NewLongObj ( xid ); Tcl_SetObjResult ( interp, val ); } break; case GetPlugIDIdx: { long xid = 0; Tcl_Obj *val; if ( objc != 2 ) { Tcl_WrongNumArgs ( interp, 2, objv, NULL ); return TCL_ERROR; } if ( socket->plug_window ) #ifdef WIN32 xid = gdk_win32_drawable_get_handle( socket->plug_window ); #else xid = GDK_WINDOW_XWINDOW ( socket->plug_window ); #endif val = Tcl_NewLongObj ( xid ); Tcl_SetObjResult ( interp, val ); } break; } return TCL_OK; }
MitchellNetravaliFilter(Stream *stream, InstanceManager *manager) : ReconstructionFilter(stream, manager) { m_B = stream->readFloat(); m_C = stream->readFloat(); configure(); }
DiffuseTransmitter(Stream *stream, InstanceManager *manager) : BSDF(stream, manager) { m_transmittance = static_cast<Texture *>(manager->getInstance(stream)); m_usesRayDifferentials = m_transmittance->usesRayDifferentials(); configure(); }
void Configurable::configure(const std::string &key, const char *value) { configure(key, std::string(value)); }
BOOL player_impl::open(const char *movie, int media_type, int render_type) { // 如果未关闭原来的媒体, 则先关闭. if (m_avplay || m_source) close(); // 未创建窗口, 无法播放, 返回失败. if (!IsWindow(m_hwnd)) return FALSE; char filename[MAX_PATH]; int len = strlen(movie) + 1; strcpy(filename, movie); uint64_t file_lentgh = 0; if (media_type == MEDIA_TYPE_FILE || media_type == MEDIA_TYPE_BT) { file_lentgh = file_size(movie); if (file_lentgh < 0) { ::logger("get file size failed!\n"); return FALSE; } } do { // 创建avplay. m_avplay = alloc_avplay_context(); if (!m_avplay) { ::logger("allocate avplay context failed!\n"); break; } // 根据打开的文件类型, 创建不同媒体源. if (media_type == MEDIA_TYPE_FILE) { len = strlen(filename); m_source = alloc_media_source(MEDIA_TYPE_FILE, filename, len + 1, file_lentgh); if (!m_source) { ::logger("allocate media source failed, type is file.\n"); break; } // 插入到媒体列表. m_media_list.insert(std::make_pair(filename, filename)); // 初始化文件媒体源. init_file_source(m_source); } if (media_type == MEDIA_TYPE_BT) { // 先读取bt种子数据, 然后作为附加数据保存到媒体源. FILE *fp = fopen(filename, "r+b"); if (!fp) { ::logger("open torrent file \'%s\' failed!\n", filename); break; } char *torrent_data = (char*)malloc(file_lentgh); int readbytes = fread(torrent_data, 1, file_lentgh, fp); if (readbytes != file_lentgh) { ::logger("read torrent file \'%s\' failed!\n", filename); break; } m_source = alloc_media_source(MEDIA_TYPE_BT, torrent_data, file_lentgh, 0); if (!m_source) { ::logger("allocate media source failed, type is torrent.\n"); break; } free(torrent_data); // 初始化torrent媒体源. init_torrent_source(m_source); } if (media_type == MEDIA_TYPE_YK) { m_source = alloc_media_source(MEDIA_TYPE_YK, filename, 0, 0); if (!m_source) { ::logger("allocate media source failed, type is yk.\n"); break; } // 初始化yk媒体源. init_yk_source(m_source); } if (media_type == MEDIA_TYPE_HTTP) { len = strlen(filename) + 1; m_source = alloc_media_source(MEDIA_TYPE_HTTP, filename, len, 0); if (!m_source) { ::logger("allocate media source failed, type is youku.\n"); break; } // 插入到媒体列表. m_media_list.insert(std::make_pair(filename, filename)); } if (media_type == MEDIA_TYPE_RTSP) { len = strlen(filename) + 1; m_source = alloc_media_source(MEDIA_TYPE_RTSP, filename, len, 0); if (!m_source) { ::logger("allocate media source failed, type is rtsp.\n"); break; } // 插入到媒体列表. m_media_list.insert(std::make_pair(filename, filename)); } // 初始化avplay. if (initialize(m_avplay, m_source) != 0) { ::logger("initialize avplay failed!\n"); break; } // 如果是bt类型, 则在此得到视频文件列表, 并添加到m_media_list. if (media_type == MEDIA_TYPE_BT) { bt_source_info *bt_info = &m_avplay->m_source_ctx->info.bt; for (int i = 0; i < bt_info->info_size; i++) { std::string name = std::string(bt_info->info[i].file_name); m_media_list.insert(std::make_pair(filename, name)); } } // 分配音频和视频的渲染器. m_audio = alloc_audio_render(); if (!m_audio) { ::logger("allocate audio render failed!\n"); break; } m_video = alloc_video_render(m_hwnd); if (!m_video) { ::logger("allocate video render failed!\n"); break; } // 初始化音频和视频渲染器. init_audio(m_audio); init_video(m_video, render_type); // 配置音频视频渲染器. configure(m_avplay, m_video, VIDEO_RENDER); configure(m_avplay, m_audio, AUDIO_RENDER); // 得到视频宽高. if (m_avplay->m_video_ctx) { m_video_width = m_avplay->m_video_ctx->width; m_video_height = m_avplay->m_video_ctx->height; } // 打开视频实时码率和帧率计算. enable_calc_frame_rate(m_avplay); enable_calc_bit_rate(m_avplay); return TRUE; } while (0); if (m_avplay) free_avplay_context(m_avplay); m_avplay = NULL; if (m_source) free_media_source(m_source); if (m_audio) free_audio_render(m_audio); if (m_video) free_video_render(m_video); ::logger("open avplay failed!\n"); return FALSE; }
/* ============================================================================= Begin Starts the sensor and I2C Process ------------------------------------------------------------------------------ 1. Turn on error reporting, off by default 2. Start Wire (i.e. turn on I2C) 3. Enable 400kHz I2C, 100kHz by default 4. Set configuration for sensor Parameters ------------------------------------------------------------------------------ - configuration: set the configuration for the sensor - default or 0 = equivelent to writing 0x00 to 0x00, i.e. full reset of sensor, if you write nothing for configuration or 0, the sensor will init- iate normally - 1 = high speed setting, set the aquisition count to 1/3 the default (works great for stronger singles) can be a little noisier - fasti2c: if true i2c frequency is 400kHz, default is 100kHz - showErrorReporting: if true reads with errors will print the value of 0x40, used primarily for debugging purposes by PulsedLight - LidarI2cAddress (optional): Default: 0x62, the default LIDAR-Lite address. If you change the address, fill it in here. ============================================================================= */ void Lidar::begin(int configuration, bool showErrorReporting){ errorReporting = showErrorReporting; Lidar::handle = i2c_open(1); // Start I2C configure(configuration); }