Exemple #1
0
WorldmapStory::WorldmapStory(const ReaderMapping& reader) :
  title(),
  music(),
  pages()
{
  reader.read_string("title", title);
  title = _(title);
  reader.read_string("music", music);
  ReaderCollection all_pages;
  reader.read_collection("pages", all_pages);

  // Temporary objects
  ResDescriptor desc;
  std::string text;
  std::string page_name;

  // Read each page into the pages vector
  std::vector<ReaderObject> childs = all_pages.get_objects();
  for(auto i = childs.begin(); i != childs.end(); ++i)
  {
    page_name = i->get_name();
    ReaderMapping mapping = i->get_mapping();
    mapping.read_desc("surface", desc);
    mapping.read_string("text", text);
    // Translate the text and break it up.
    text = StringFormat::break_line(_(text), 570, Fonts::chalk_normal);
    pages.push_back(StoryPage(desc, text, page_name));
  }
  std::reverse(pages.begin(), pages.end());

  if (pages.empty())
    raise_exception(std::runtime_error, "WorldmapStory: Worldmap does not include a valid story");
}
void setup()
{
	char logfile[80];
	sprintf(logfile, LOG_FILE, devnum);
	get_mapping();
	goRealTime();
	fp_log = fopen(logfile, "w");
	if (fp_log == 0){
		perror(logfile);
		exit(1);
	}

	xllc_def.len = samples_buffer*VI_LEN;
	if (xllc_def.len > 16*64){
		xllc_def.len = 16*64;
		samples_buffer = xllc_def.len/VI_LEN;
		fprintf(stderr, "WARNING: samples_buffer clipped to %d\n", samples_buffer);
	}

	if (ioctl(fd, AFHBA_START_AI_LLC, &xllc_def)){
		perror("ioctl AFHBA_START_AI_LLC");
		exit(1);
	}
	printf("AI buf pa: 0x%08x\n", xllc_def.pa);
	xllc_def.pa += HB_LEN;
	if (has_do32){
		xllc_def.len += 64;
	}
	if (ioctl(fd, AFHBA_START_AO_LLC, &xllc_def)){
		perror("ioctl AFHBA_START_AO_LLC");
		exit(1);
	}
	printf("AO buf pa: 0x%08x\n", xllc_def.pa);
	ao_buffer = (short*)((void*)host_buffer+HB_LEN);
}
Exemple #3
0
void
World::load_(const std::string& directory)
{
  m_basedir = directory;
  m_worldmap_filename = m_basedir + "/worldmap.stwm";

  std::string filename = m_basedir + "/info";
  register_translation_directory(filename);
  auto doc = ReaderDocument::parse(filename);
  auto root = doc.get_root();

  if(root.get_name() != "supertux-world" &&
     root.get_name() != "supertux-level-subset")
  {
    throw std::runtime_error("File is not a world or levelsubset file");
  }

  m_hide_from_contribs = false;
  m_is_levelset = true;

  auto info = root.get_mapping();

  info.get("title", m_title);
  info.get("description", m_description);
  info.get("levelset", m_is_levelset);
  info.get("hide-from-contribs", m_hide_from_contribs);
}
Exemple #4
0
int main(void)
{
    std::vector<Complex> v;
    // Citeste date de test.
    v = read_data(".date.in");
    std::cout << "Vectorul initial" << std::endl;
    write_vector(v);

    // Verifica sortarea.
    std::vector<Complex> sorted = get_sorted(v);
    std::cout << "Vectorul sortat" << std::endl;
    write_vector(sorted);

    // Verifica maparea.
    std::cout << "Maparea" << std::endl;
    std::map<Complex, int> mapping = get_mapping(v);

    for (unsigned int i = 0; i < sorted.size(); i++)
    {
        std::cout << sorted[i] << " e pe pozitia "
                  << mapping[sorted[i]] << std::endl;
    }

    return 0;
}
Exemple #5
0
std::string
GameManager::get_level_name(const std::string& filename) const
{
  try
  {
    register_translation_directory(filename);
    auto doc = ReaderDocument::from_file(filename);
    auto root = doc.get_root();

    if(root.get_name() != "supertux-level") {
      return "";
    } else {
      auto mapping = root.get_mapping();
      std::string name;
      mapping.get("name", name);
      return name;
    }
  }
  catch(const std::exception& e)
  {
    log_warning << "Problem getting name of '" << filename << "': "
                << e.what() << std::endl;
    return "";
  }
}
void setup()
{
	char logfile[80];
	sprintf(logfile, LOG_FILE, devnum);
	local_buffer = calloc(NSHORTS*nsamples, sizeof(short));
	pollcats = calloc(nsamples, sizeof(int));
	get_mapping();
	fp_log = fopen(logfile, "w");
	if (fp_log == 0){
		perror(logfile);
		exit(1);
	}

	xllc_def.len = samples_buffer*VI_LEN;
	if (xllc_def.len > 16*64){
		xllc_def.len = 16*64;
		samples_buffer = xllc_def.len/VI_LEN;
		fprintf(stderr, "WARNING: samples_buffer clipped to %d\n", samples_buffer);
	}

	if (ioctl(fd, AFHBA_START_AI_LLC, &xllc_def)){
		perror("ioctl AFHBA_START_AI_LLC");
		exit(1);
	}
}
Exemple #7
0
std::string to_string(ATTRIBUTE_KIND kind){
  kind2str const &mapping = get_mapping();
  kind2str::left_const_iterator it = mapping.left.find(kind);

  if(mapping.left.end() == it)
    throw unrecognized_attribute_kind(kind);
  return it->second;
}
Exemple #8
0
static void free_stack_and_tls(uintptr_t stack) {
  unsigned pagesz = get_page_size();

  unsigned flags;
  for (unsigned i = 0; i < THREAD_STACK_SZ; i += pagesz) {
    free_page(get_mapping(stack+i, &flags));
    unmap(stack+i, 1);
  }
}
Exemple #9
0
void
LevelParser::load(const std::string& filepath)
{
  try {
    m_level.m_filename = filepath;
    register_translation_directory(filepath);
    auto doc = ReaderDocument::from_file(filepath);
    auto root = doc.get_root();

    if(root.get_name() != "supertux-level")
      throw std::runtime_error("file is not a supertux-level file.");

    auto level = root.get_mapping();

    int version = 1;
    level.get("version", version);
    if(version == 1) {
      log_info << "[" <<  filepath << "] level uses old format: version 1" << std::endl;
      load_old_format(level);
    } else if (version == 2) {
      level.get("tileset", m_level.m_tileset);

      level.get("name", m_level.m_name);
      level.get("author", m_level.m_author);
      level.get("contact", m_level.m_contact);
      level.get("license", m_level.m_license);
      level.get("target-time", m_level.m_target_time);

      auto iter = level.get_iter();
      while(iter.next()) {
        if (iter.get_key() == "sector") {
          auto sector = SectorParser::from_reader(m_level, iter.as_mapping());
          m_level.add_sector(std::move(sector));
        }
      }

      if (m_level.m_license.empty()) {
        log_warning << "[" <<  filepath << "] The level author \"" << m_level.m_author
                    << "\" did not specify a license for this level \""
                    << m_level.m_name << "\". You might not be allowed to share it."
                    << std::endl;
      }
    } else {
      log_warning << "[" <<  filepath << "] level format version " << version << " is not supported" << std::endl;
    }
  } catch(std::exception& e) {
    std::stringstream msg;
    msg << "Problem when reading level '" << filepath << "': " << e.what();
    throw std::runtime_error(msg.str());
  }

  m_level.m_stats.init(m_level);
}
Exemple #10
0
static void dbg_mappings(const char *cmd, core_debug_state_t *states, int core) {
  uintptr_t v = 0, old_v = 0, start = 0;
  unsigned int flags = 0, old_flags = 0;

  /* If the user specified an address, print the mapping for that address
     instead of all addresses. */
  if (strchr(cmd, ' ')) {
    unsigned long addr = strtoul(strchr(cmd, ' ')+1, NULL, 0);

    uint64_t p = get_mapping(addr, &flags);
    if (p == ~0ULL) {
      kprintf("%08x - not mapped\n", addr);
    } else {
      /* FIXME: Support 64-bit types in printf! */
      kprintf("%08x -> %08x ", addr, (uint32_t)p);
      kprint_bitmask("cuxw", flags);
      kprintf("\n");
    }
    return;
  }

  (void)get_mapping(0, &old_flags);

  while (v <= UINTPTR_MAX - get_page_size()) {
    v = iterate_mappings(v);

    (void)get_mapping(v, &flags);
    if (old_flags != flags || v != old_v + 0x1000) {
      kprintf("%08x..%08x ", start, old_v+0x1000);
      kprint_bitmask("cuxw", old_flags);
      kprintf("\n");

      old_flags = flags;
      start = v;
    }
    old_v = v;
  }

}
Exemple #11
0
void free_chunk(kheader_t *chunk) {
	chunk->prev->next = 0;
	if (chunk->prev == 0)
		kheap_first = 0;
	// While the heap max can contract by a page and still be greater than the chunk address...
	while ((kheap_max - 0x1000) >= (uint32_t) chunk) {
		kheap_max -= 0x1000;
		uint32_t page;
		get_mapping(kheap_max, &page);
		pmm_free_page(page);
		unmap(kheap_max);
	}
}
Exemple #12
0
	void insert(const cm_data &d) {
		case_mapping *p;
#if 0
		/* Check for priority intervals */
		if ((d.first <= 'T' && d.last >= 'T') ||
				(d.first <= 0x0410 && d.last >= 0x0410))
		{
			/* Interval contains ASCII or Cyrillic letters */
			m_prio.push_back(new cm_data(d));
		}
#endif
		if (avl_get_by_key(m_tree, (void*)&d, (void**)&p) != 0) {
			p = get_mapping(d.first, d.last, d.cm);
			avl_insert(m_tree, p);
		}
	}
int main(int argc, char** argv)
{
  for(int i = 1; i < argc; ++i)
  {
    Pathname filename(argv[i], Pathname::SYSTEM_PATH);
    if (filename.has_extension(".pingus"))
    {
      PingusLevel plf(filename);

      emit_msgid(plf.get_levelname());
      emit_msgid(plf.get_description());
    }
    else if (filename.has_extension(".worldmap"))
    {
      // worldmaps don't contain translatable strings at the moment
    }
    else if (filename.has_extension(".story"))
    {
      ReaderObject reader_object = FileReader::parse(filename);
      ReaderMapping reader = reader_object.get_mapping();

      std::string tmp;
      if (reader.read_string("title", tmp))
      {
        emit_msgid(tmp);
      }

      ReaderCollection all_pages = reader.read_collection("pages");
      const auto& childs = all_pages.get_objects();
      for(auto it = childs.begin(); it != childs.end(); ++it)
      {
        ReaderMapping r = it->get_mapping();
        if (r.read_string("text", tmp))
        {
          emit_msgid(tmp);
        }
      }
    }
    else
    {
      raise_exception(std::runtime_error, "unknown file type: " << filename);
    }
  }

  return 0;
}
Exemple #14
0
void free_chunk(header_t *chunk)
{
	if (chunk->prev == 0) {
	      heap_first = 0;
	} else {
		chunk->prev->next = 0;
	}

	// 空闲的内存超过 1 页的话就释放掉
	while ((heap_max - 0x1000) >= (uint32_t)chunk) {
		heap_max -= 0x1000;
		uint32_t page;
		get_mapping(heap_max, &page);
		pmm_free_page(page);
		unmap(heap_max);
	}
}
Exemple #15
0
void free_chunk(header_t * chunk)
{
	if(chunk->prev == 0){
		heap_first = 0;
	} else {
		chunk->prev->next = 0;
	}

	//空闲的内存超过1页的话就释放掉
	while((heap_max - PAGE_SIZE) >= (uint32_t) chunk){
		heap_max -= PAGE_SIZE;
		uint32_t page;
		get_mapping(pgd_kern , heap_max , &page);
		unmap(pgd_kern , heap_max);
		pmm_free_page(page);
	}
}
Exemple #16
0
static void free_chunk(heap_header_t *chunk)
{
	if (chunk->prev == 0) {
		heap_frist = 0;
	} else {
		chunk->prev->next = 0;
	}

	while ((heap_max - PAGE_SIZE) >= (uint32_t)chunk) {
		uint32_t page;

		heap_max -= PAGE_SIZE;
		get_mapping(pgd_k, heap_max, &page);
		unmap(pgd_k, heap_max);
		free_page(page);
	}
}
Exemple #17
0
void free_chunk(header_t *chunk){
  //no allocated chunk all free
  //only move pointer saying this location is used, no pointed are all free could be filled with
  //something but already free, so no use and see as empty and free
  if(chunk->prev == 0)
    heap_first = 0;
  else
    chunk->prev->next = 0;

  //if all free ram over 4K page, then unmap to let system run efficient
  while((heap_max - PAGE_SIZE) >= (uint32_t) chunk){
      heap_max -= PAGE_SIZE;
      uint32_t page;
      get_mapping(pgd_kern, heap_max, &page);
      unmap(pgd_kern, heap_max);
      pmm_free_page(page);
  }

}
Exemple #18
0
void free_chunk(heap_t *chunk) 
{
	if (chunk->prev == 0) {
		heap_first = 0;
	}else {
		//指向自己的指针指向0
		chunk->prev->next = 0;
	} 
	//heap_max 一直是指向申请内存的最上面,当释放掉上面的内存,内存大于4096字节,把这个内存释放掉,就是解除
	//映射,把页表的恢复成可用的选项
	while ((heap_max - PAGE_SIZE) >= (uint32)chunk) {
		heap_max -= PAGE_SIZE;
		uint32 page;
		//通过线性地址找到物理地址,然后赋值给page
		get_mapping(pgd_kernel, heap_max, &page);
		unmap(pgd_kernel, heap_max);
		//里面存在物理内存管理的数组
		pmm_free_page(page);
	}
}
void
WorldMapParser::load_level_information(LevelTile& level)
{
  /** get special_tile's title */
  level.m_title = _("<no title>");
  level.m_target_time = 0.0f;

  try {
    std::string filename = m_worldmap.m_levels_path + level.get_level_filename();

    if (m_worldmap.m_levels_path == "./")
      filename = level.get_level_filename();

    if (!PHYSFS_exists(filename.c_str()))
    {
      log_warning << "Level file '" << filename << "' does not exist. Skipping." << std::endl;
      return;
    }
    if (physfsutil::is_directory(filename))
    {
      log_warning << "Level file '" << filename << "' is a directory. Skipping." << std::endl;
      return;
    }

    register_translation_directory(filename);
    auto doc = ReaderDocument::from_file(filename);
    auto root = doc.get_root();
    if (root.get_name() != "supertux-level") {
      return;
    } else {
      auto level_mapping = root.get_mapping();
      level_mapping.get("name", level.m_title);
      level_mapping.get("target-time", level.m_target_time);
    }
  } catch(std::exception& e) {
    log_warning << "Problem when reading level information: " << e.what() << std::endl;
    return;
  }
}
Exemple #20
0
bool cow_handle_page_fault(uintptr_t cr2, uintptr_t error_code) {
  unsigned flags;

  uint32_t p = (uint32_t)get_mapping(cr2, &flags);

  if ((error_code & (X86_PRESENT|X86_WRITE)) &&
      p != ~0UL && (flags & PAGE_COW) ) {
    /* Page was marked copy-on-write. */
    uint32_t p2 = (uint32_t)alloc_page(PAGE_REQ_UNDER4GB);

    /* We have to copy the page. In order to avoid a costly and 
       non-reentrant map/unmap pair to temporarily have them
       both mapped into memory, copy first into a buffer on
       the stack (this means the stack must be >4KB). */
    uint8_t buffer[4096];

    uint32_t v = cr2 & 0xFFFFF000;
    memcpy(buffer, (uint8_t*)v, 0x1000);
    
    if (unmap(v, 1) == -1)
      panic("unmap() failed during copy-on-write!");

    unsigned f = ((flags & X86_USER) ? PAGE_USER : 0) |
      ((flags & X86_EXECUTE) ? PAGE_EXECUTE : 0) |
      PAGE_WRITE;
    if (map(v, p2, 1, f) == -1)
      panic("map() failed during copy-on-write!");

    memcpy((uint8_t*)v, buffer, 0x1000);

    /* Mark the old page as having one less reference. */
    cow_refcnt_dec(p);

    return true;
  }
  return false;
}
Exemple #21
0
std::unique_ptr<Addon>
Addon::parse(const std::string& fname)
{
  try
  {
    register_translation_directory(fname);
    auto doc = ReaderDocument::parse(fname);
    auto root = doc.get_root();
    if(root.get_name() != "supertux-addoninfo")
    {
      throw std::runtime_error("file is not a supertux-addoninfo file.");
    }
    else
    {
      return parse(root.get_mapping());
    }
  }
  catch(const std::exception& err)
  {
    std::stringstream msg;
    msg << "Problem when reading addoninfo '" << fname << "': " << err.what();
    throw std::runtime_error(msg.str());
  }
}
int main(int argc, char *argv[]) {
    char cmdline[256];
    char *prefix;
    size_t prefix_len;
    int (*compfn)(const void *a, const void *b);

    pm_kernel_t *ker;
    pm_process_t *proc;

    pid_t *pids;
    size_t num_procs;

    pm_map_t **maps;
    size_t num_maps;
    pm_memusage_t map_usage;

    struct library_info *li, **lis;
    struct mapping_info *mi, **mis;
    struct process_info *pi;

    size_t i, j;
    int error;
    int perm;
    bool all;
    uint64_t required_flags;
    uint64_t flags_mask;

    bool has_swap = false;

    signal(SIGPIPE, SIG_IGN);
    compfn = &sort_by_pss;
    order = -1;
    prefix = NULL;
    prefix_len = 0;
    opterr = 0;
    perm = 0;
    all = false;
    required_flags = 0;
    flags_mask = 0;

    while (1) {
        int c;
        const struct option longopts[] = {
            {"all", 0, 0, 'a'},
            {"cached", 0, 0, 'c'},
            {"nocached", 0, 0, 'C'},
            {"ksm", 0, 0, 'k'},
            {"help", 0, 0, 'h'},
            {"pss", 0, 0, 'p'},
            {"uss", 0, 0, 'u'},
            {"vss", 0, 0, 'v'},
            {"rss", 0, 0, 'r'},
            {"swap", 0, 0, 's'},
            {"reverse", 0, 0, 'R'},
            {"path", required_argument, 0, 'P'},
            {"perm", required_argument, 0, 'm'},
            {0, 0, 0, 0}
        };
        c = getopt_long(argc, argv, "acChkm:pP:uvrsR", longopts, NULL);
        if (c < 0) {
            break;
        }
        /* Alphabetical cases */
        switch (c) {
        case 'a':
            all = true;
            break;
        case 'c':
            required_flags = 0;
            flags_mask = PM_PAGE_SWAPBACKED;
            break;
        case 'C':
            required_flags = PM_PAGE_SWAPBACKED;
            flags_mask = PM_PAGE_SWAPBACKED;
            break;
        case 'k':
            required_flags = PM_PAGE_KSM;
            flags_mask = PM_PAGE_KSM;
            break;
        case 'h':
            usage(argv[0]);
            exit(EXIT_SUCCESS);
        case 'm':
            perm = parse_perm(optarg);
            break;
        case 'p':
            compfn = &sort_by_pss;
            break;
        case 'P':
            prefix = optarg;
            prefix_len = strlen(prefix);
            break;
        case 'u':
            compfn = &sort_by_uss;
            break;
        case 'v':
            compfn = &sort_by_vss;
            break;
        case 'r':
            compfn = &sort_by_rss;
            break;
        case 's':
            compfn = &sort_by_swap;
            break;
        case 'R':
            order *= -1;
            break;
        case '?':
            fprintf(stderr, "Invalid argument \"%s\".\n", argv[optind - 1]);
            usage(argv[0]);
            exit(EXIT_FAILURE);
        default:
            abort();
        }
    }

    argc -= optind;
    argv += optind;

    libraries = malloc(INIT_LIBRARIES * sizeof(struct library_info *));
    libraries_count = 0; libraries_size = INIT_LIBRARIES;

    error = pm_kernel_create(&ker);
    if (error) {
        fprintf(stderr, "Error initializing kernel interface -- "
                        "does this kernel have pagemap?\n");
        exit(EXIT_FAILURE);
    }

    error = pm_kernel_pids(ker, &pids, &num_procs);
    if (error) {
        fprintf(stderr, "Error listing processes.\n");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < num_procs; i++) {
        error = pm_process_create(ker, pids[i], &proc);
        if (error) {
            fprintf(stderr, "warning: could not create process interface for %d\n", pids[i]);
            continue;
        }

        pi = get_process(pids[i]);

        error = pm_process_maps(proc, &maps, &num_maps);
        if (error) {
            fprintf(stderr, "Error listing maps for process %d.\n", proc->pid);
            exit(EXIT_FAILURE);
        }

        for (j = 0; j < num_maps; j++) {
            if (prefix && (strncmp(pm_map_name(maps[j]), prefix, prefix_len)))
                continue;

            if (perm && (pm_map_flags(maps[j]) & PM_MAP_PERMISSIONS) != perm)
                continue;

            li = get_library(pm_map_name(maps[j]), all);
            if (!li)
                continue;

            mi = get_mapping(li, pi);

            error = pm_map_usage_flags(maps[j], &map_usage, flags_mask,
                                       required_flags);
            if (error) {
                fprintf(stderr, "Error getting map memory usage of "
                                "map %s in process %d.\n",
                        pm_map_name(maps[j]), proc->pid);
                exit(EXIT_FAILURE);
            }

            if (map_usage.swap) {
                has_swap = true;
            }

            pm_memusage_add(&mi->usage, &map_usage);
            pm_memusage_add(&li->total_usage, &map_usage);
        }
    }

    printf(" %6s   %6s   %6s   %6s   %6s  ", "RSStot", "VSS", "RSS", "PSS", "USS");

    if (has_swap) {
        printf(" %6s  ", "Swap");
    }

    printf("Name/PID\n");
    fflush(stdout);

    qsort(libraries, libraries_count, sizeof(libraries[0]), &licmp);

    for (i = 0; i < libraries_count; i++) {
        li = libraries[i];

        printf("%6zdK   %6s   %6s   %6s   %6s  ", li->total_usage.pss / 1024, "", "", "", "");
        if (has_swap) {
            printf(" %6s  ", "");
        }
        printf("%s\n", li->name);
        fflush(stdout);

        qsort(li->mappings, li->mappings_count, sizeof(li->mappings[0]), compfn);

        for (j = 0; j < li->mappings_count; j++) {
            mi = li->mappings[j];
            pi = mi->proc;
            printf(   " %6s  %6zdK  %6zdK  %6zdK  %6zdK  ", "",
                mi->usage.vss / 1024,
                mi->usage.rss / 1024,
                mi->usage.pss / 1024,
                mi->usage.uss / 1024);
            if (has_swap) {
                printf("%6zdK  ", mi->usage.swap / 1024);
            }
            printf("  %s [%d]\n",
                pi->cmdline,
                pi->pid);
        }
        printf("\n");
        fflush(stdout);
    }

    return 0;
}
int main(int argc, char *argv[]) {
    char cmdline[256];
    char *prefix;
    size_t prefix_len;
    int (*compfn)(const void *a, const void *b);
    /// M: get swap usage @{
    int show_swap;
    /// @}

    pm_kernel_t *ker;
    pm_process_t *proc;

    pid_t *pids;
    size_t num_procs;

    pm_map_t **maps;
    size_t num_maps;
    pm_memusage_t map_usage;

    struct library_info *li, **lis;
    struct mapping_info *mi, **mis;
    struct process_info *pi;

    int i, j, error;

    signal(SIGPIPE, SIG_IGN);
    compfn = &sort_by_pss;
    order = -1;
    prefix = NULL;
    prefix_len = 0;
    /// M: get swap usage @{
    show_swap = 0;
    /// @}

    for (i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "-P")) {
            if (i + 1 >= argc) {
                fprintf(stderr, "Option -P requires an argument.\n");
                usage(argv[0]);
                exit(EXIT_FAILURE);
            }
            prefix = argv[++i];
            prefix_len = strlen(prefix);
            continue;
        }
        if (!strcmp(argv[i], "-v")) { compfn = &sort_by_vss; continue; }
        if (!strcmp(argv[i], "-r")) { compfn = &sort_by_rss; continue; }
        if (!strcmp(argv[i], "-p")) { compfn = &sort_by_pss; continue; }
        if (!strcmp(argv[i], "-u")) { compfn = &sort_by_uss; continue; }
        if (!strcmp(argv[i], "-R")) { order *= -1; continue; }
        /// M: get swap usage @{
        if (!strcmp(argv[i], "-s")) { show_swap = 1; continue; }
        /// @}
        if (!strcmp(argv[i], "-h")) { usage(argv[0]); exit(0); }
        fprintf(stderr, "Invalid argument \"%s\".\n", argv[i]);
        usage(argv[0]);
        exit(EXIT_FAILURE);
    }

    libraries = malloc(INIT_LIBRARIES * sizeof(struct library_info *));
    libraries_count = 0; libraries_size = INIT_LIBRARIES;

    error = pm_kernel_create(&ker);
    if (error) {
        fprintf(stderr, "Error initializing kernel interface -- "
                        "does this kernel have pagemap?\n");
        exit(EXIT_FAILURE);
    }

    error = pm_kernel_pids(ker, &pids, &num_procs);
    if (error) {
        fprintf(stderr, "Error listing processes.\n");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < num_procs; i++) {
        error = pm_process_create(ker, pids[i], &proc);
        if (error) {
            fprintf(stderr, "warning: could not create process interface for %d\n", pids[i]);
            continue;
        }
        
        pi = get_process(pids[i]);

        error = pm_process_maps(proc, &maps, &num_maps);
        if (error) {
            fprintf(stderr, "Error listing maps for process %d.\n", proc->pid);
            exit(EXIT_FAILURE);
        }

        for (j = 0; j < num_maps; j++) {
            if (prefix && (strncmp(pm_map_name(maps[j]), prefix, prefix_len)))
                continue;

            li = get_library(pm_map_name(maps[j]));
            if (!li)
                continue;

            mi = get_mapping(li, pi);
            
            error = pm_map_usage(maps[j], &map_usage);
            if (error) {
                fprintf(stderr, "Error getting map memory usage of "
                                "map %s in process %d.\n",
                        pm_map_name(maps[j]), proc->pid);
                exit(EXIT_FAILURE);
            }
            pm_memusage_add(&mi->usage, &map_usage);
            pm_memusage_add(&li->total_usage, &map_usage);
        }
    }

    /// M: get swap usage @{
    if (show_swap) {
        printf(          " %6s   %6s   %6s   %6s   %6s   %6s   %6s  %s\n", "RSStot", "VSS", "RSS", "PSS", "USS", "SWAP", "PSWAP", "Name/PID");
    } else {
        printf(          " %6s   %6s   %6s   %6s   %6s  %s\n", "RSStot", "VSS", "RSS", "PSS", "USS", "Name/PID");
    }
    /// @}
    fflush(stdout);

    qsort(libraries, libraries_count, sizeof(libraries[0]), &licmp);

    for (i = 0; i < libraries_count; i++) {
        li = libraries[i];

        printf("%6dK   %6s   %6s   %6s   %6s  %s\n", li->total_usage.pss / 1024, "", "", "", "", li->name);
        fflush(stdout);

        qsort(li->mappings, li->mappings_count, sizeof(li->mappings[0]), compfn);

        for (j = 0; j < li->mappings_count; j++) {
            mi = li->mappings[j];
            pi = mi->proc;
            /// M: get swap usage @{
            if (show_swap) {
                printf(   " %6s  %6dK  %6dK  %6dK  %6dK  %6dK  %6dK    %s [%d]\n", "",
                    mi->usage.vss / 1024,
                    mi->usage.rss / 1024,
                    mi->usage.pss / 1024,
                    mi->usage.uss / 1024,
                    mi->usage.swap / 1024,
                    mi->usage.pswap / 1024,
                    pi->cmdline,
                    pi->pid);
            } else {
                printf(   " %6s  %6dK  %6dK  %6dK  %6dK    %s [%d]\n", "",
                    mi->usage.vss / 1024,
                    mi->usage.rss / 1024,
                    mi->usage.pss / 1024,
                    mi->usage.uss / 1024,
                    pi->cmdline,
                    pi->pid);
            }
            /// @}
        }
        printf("\n");
        fflush(stdout);
    }

    return 0;
}
Exemple #24
0
void go_plot_contours(
    char *device, char *title, char *xvar, char *yvar, char *topline,
    double **data, double xmin, double xmax, double ymin, double ymax,
    double dx, double dy, long nx, long ny,
    double *contour_level, long n_contours, long contour_label_interval,
    long contour_label_offset, long layout[2], long ix, long iy,
    char *shapes, int *pen, long flags, long pause_interval,
    SHAPE_DATA *shape, long nshapes, unsigned long long tsetFlags, double xlableScale, double ylabelScale)
{
    double map[4], average, spread;
    double pmin, pmax, qmin, qmax;
    double wpmin, wpmax=0, wqmin, wqmax=0;
    long title_at_top=0;
    char newLabel[50];
    time_t timeValue;

    if (!(flags&DEVICE_DEFINED)) 
      change_term(device, strlen(device));
    if ((ix == 0) && (iy == 0))
      graphics_on();
    if (layout[0] && layout[1]) {
      wpmin = (1.0*ix+0)/layout[0];
      wpmax = (1.0*ix+1)/layout[0];
      wqmin = (layout[1]*1.0 - 1 - iy)/layout[1];
      wqmax = (layout[1]*1.0 - 0 - iy)/layout[1];
      set_wspace(wpmin, wpmax, wqmin, wqmax);
      pmin = (wpmax - wpmin) * .15 + wpmin;
      pmax = wpmax - (wpmax - wpmin) * .1;
      qmin = (wqmax - wqmin) * .17 + wqmin;
      qmax = wqmax - (wqmax - wqmin) * .08;
      set_pspace(pmin, pmax, qmin, qmax);
    }

    if (contour_label_interval<0) {
      get_pspace(&pmin, &pmax, &qmin, &qmax);
      set_pspace(pmin, 0.9 * wpmax, qmin, 0.85 * wqmax);
    }
    if (flags&TITLE_AT_TOP) {
      /* adjust pspace to make room at top for the title */
      get_pspace(&pmin, &pmax, &qmin, &qmax);
      spread = qmax-qmin;
      qmax -= 0.04*spread;
      qmin -= 0.04*spread;
      /*    qmax -= 0.04;
            qmin -= 0.04;*/
      set_pspace(pmin, pmax, qmin, qmax);
      title_at_top = 1;
    }
    set_clipping(1, 1, 1);


    if (flags&EQUAL_ASPECT1) 
        set_aspect(1.0L);
    else if (flags&EQUAL_ASPECT_1)
        set_aspect(-1.0L);

    set_linetype(pen[0]);
    get_mapping(map, map+1, map+2, map+3);
    if (map[0]==map[1]) {
        average  = (xmax+xmin)/2;
        spread   = (xmax-xmin)/2;
        map[0]   = average - spread*1.05;
        map[1]   = average + spread*1.05;
        }
    if (map[2]==map[3]) {
        average  = (ymax+ymin)/2;
        spread   = (ymax-ymin)/2;
        map[2]   = average - spread*1.05;
        map[3]   = average + spread*1.05;
        }
    set_mapping(map[0], map[1], map[2], map[3]);
    get_pspace(&pmin, &pmax, &qmin, &qmax);
    get_wspace(&wpmin, &wpmax, &wqmin, &wqmax);

    if (!(flags&NO_BORDER)) {
      border();
      if (!(flags&NO_SCALES)) {
        if (tsetFlags&TICKSET_XTIME) {
          timeValue = map[0];
          if (timeValue!=DBL_MAX)
            sprintf(newLabel, "Time starting %s", ctime(&timeValue));
          else
            sprintf(newLabel, "Undefined time values!");
          delete_chars(newLabel, "\n");
          makeTimeScales(0, 0.02, 0, map[2], map[2], newLabel, 
                         0, 0.67*(qmin-wqmin)*(map[3]-map[2])/(qmax-qmin), 
                         0, 1, 1);
        } else {
          make_scales_with_label(0, 0, 1, 0.0, 0.02, 0.0, 
                                 0.0, 1.0, 0, 0, 
                                 0, 0, 0, 0, xvar, 0, 0, xlableScale);
        }
	if (!(flags&NO_YSCALES)) {
          if (tsetFlags&TICKSET_YTIME) {
            timeValue = map[2];
            if (timeValue!=DBL_MAX)
              sprintf(newLabel, "Time starting %s", ctime(&timeValue));
            else
              sprintf(newLabel, "Undefined time values!");
            delete_chars(newLabel, "\n");
            makeTimeScales(1, 0.0125, 0, map[0], map[0], newLabel, 
                           0, (pmin-wpmin)*(map[1]-map[0])/(pmax-pmin), 
                           0, 1, 1);
          } else {
            make_scales_with_label(1, 0, 1, 0.0, 0.0125, 0.0, 
                                   0.0, 1.0, 0, 0, 
                                   0, 0, 0, 0, yvar, 0, 0, ylabelScale);
          }
	}
      }
    }
    if (!(flags&NO_LABELS)) {
      plotTitle(title, 1, title_at_top, 1.0, 0.0, 0, 0);
      if (contour_label_interval>=0)
	plotTitle(topline, 0, 0, 1.0, 0.0, 0, 0);
    }
    set_linetype(pen[1]);
    draw_contours(data, xmin, xmax, ymin, ymax, nx, ny, contour_level, n_contours);
    if (contour_label_interval!=0) {
        set_linetype(pen[2]);
        label_contours(data, nx, ny, contour_level, n_contours,
            contour_label_interval, contour_label_offset,
            xmin, (double)dx, ymin, (double)dy);
        }
    set_linetype(pen[0]);

    if (nshapes)
      PlotShapesData(shape, nshapes, xmin, xmax, ymin, ymax);

    if (flags&DATE_STAMP)
        time_date_stamp();

    }
Exemple #25
0
int vmeio_ioctl(struct inode *inode, struct file *filp, unsigned int cmd,
		unsigned long arg)
{
	void *arb;		/* Argument buffer area */

	struct vmeio_device *dev;

	int iodr;		/* Io Direction */
	int iosz;		/* Io Size in bytes */
	int cc = 0;		/* erro return code */

	long minor;

	iodr = _IOC_DIR(cmd);
	iosz = _IOC_SIZE(cmd);

	minor = MINOR(inode->i_rdev);
	if (!minor_ok(minor))
		return -EACCES;
	dev = filp->private_data;

	if ((arb = kmalloc(iosz, GFP_KERNEL)) == NULL)
		return -ENOMEM;

	if ((iodr & _IOC_WRITE) && copy_from_user(arb, (void *)arg, iosz)) {
		cc = -EACCES;
		goto out;
	}
	debug_ioctl(_IOC_NR(cmd), iodr, iosz, arb, minor, dev->debug);

	if (!dev) {
		cc = -EACCES;
		goto out;
	}

	switch (cmd) {

	case VMEIO_SET_DEBUG:
		vmeio_set_debug(dev, arb);
		break;

	case VMEIO_GET_DEBUG:
		vmeio_get_debug(dev, arb);
		break;

	case VMEIO_GET_VERSION:
		vmeio_get_version(arb);
		break;

	case VMEIO_SET_TIMEOUT:
		vmeio_set_timeout(dev, arb);
		break;

	case VMEIO_GET_TIMEOUT:
		vmeio_get_timeout(dev, arb);
		break;

	case VMEIO_RAW_READ_DMA:
		cc = raw_dma(dev, arb, VME_DMA_FROM_DEVICE);
		if (cc < 0)
			goto out;
		break;

	case VMEIO_RAW_WRITE_DMA:
		cc = raw_dma(dev, arb, VME_DMA_TO_DEVICE);
		if (cc < 0)
			goto out;
		break;

	case VMEIO_READ_DMA:
	case VMEIO_WRITE_DMA:
		cc = do_raw_dma(arb);
		if (cc < 0)
			goto out;
		break;

	case VMEIO_RAW_READ:
		cc = raw_read(dev, arb);
		if (cc < 0)
			goto out;
		break;

	case VMEIO_RAW_WRITE:
		cc = raw_write(dev, arb);
		if (cc < 0)
			goto out;
		break;

	case VMEIO_GET_MAPPING:
		cc = get_mapping(dev, arb);
		if (cc < 0)
			goto out;
		break;

#ifdef ENCORE_DAL
	case VMEIO_GET_NREGS:
		get_nregs(arb);
		break;
	case VMEIO_GET_REGINFO:
		cc = get_reginfo(arb);
		break;
#else
	case VMEIO_GET_NREGS:
	case VMEIO_GET_REGINFO:
		cc = -ENOENT;
		break;
#endif

	default:
		cc = -ENOENT;
		goto out;
		break;
	}

	if ((iodr & _IOC_READ) && copy_to_user((void *)arg, arb, iosz)) {
			cc = -EACCES;
			goto out;
	}
out:	kfree(arb);
	return cc;
}
Exemple #26
0
TextScroller::TextScroller(const std::string& filename) :
  defaultspeed(DEFAULT_SPEED),
  speed(defaultspeed),
  music(),
  background(),
  lines(),
  scroll(0),
  fading(false)
{
  std::string text;
  std::string background_file;

  try {
    register_translation_directory(filename);
    auto doc = ReaderDocument::parse(filename);
    auto root = doc.get_root();

    if(root.get_name() != "supertux-text") {
      throw std::runtime_error("File isn't a supertux-text file");
    } else {
      auto text_lisp = root.get_mapping();

      int version = 1;
      text_lisp.get("version", version);
      if (version == 1) {
        log_info << "[" << filename << "] Text uses old format: version 1" << std::endl;

        if(!text_lisp.get("text", text)) {
          throw std::runtime_error("File doesn't contain a text field");
        }

        // Split text string lines into a vector
        lines = InfoBoxLine::split(text, static_cast<float>(SCREEN_WIDTH) - 2.0f * LEFT_BORDER);
      } else if (version == 2) {
        ReaderMapping content;
        if (!text_lisp.get("content", content)) {
          throw std::runtime_error("File doesn't contain content");
        } else {
          auto iter = content.get_iter();
          while (iter.next()) {
            if (iter.get_key() == "image") {
              std::string image_file;
              iter.get(image_file);
              lines.emplace_back(new InfoBoxLine('!', image_file));
            } else if (iter.get_key() == "person") {
              bool simple;
              std::string name, info, image_file;

              if (!iter.as_mapping().get("simple", simple)) {
                simple = false;
              }

              if (simple) {
                if (!iter.as_mapping().get("name", name) || !iter.as_mapping().get("info", info)) {
                  throw std::runtime_error("Simple entry requires both name and info specified");
                }

                if (iter.as_mapping().get("image", image_file)) {
                  log_warning << "[" << filename << "] Simple person entry shouldn't specify images" << std::endl;
                }

                lines.emplace_back(new InfoBoxLine(' ', name + " (" + info + ")"));
              } else {
                if (iter.as_mapping().get("name", name)) {
                  lines.emplace_back(new InfoBoxLine('\t', name));
                }

                if (iter.as_mapping().get("image", image_file) && !simple) {
                  lines.emplace_back(new InfoBoxLine('!', image_file));
                }

                if (iter.as_mapping().get("info", info)) {
                  lines.emplace_back(new InfoBoxLine(' ', info));
                }
              }
            } else if (iter.get_key() == "blank") {
              // Empty line
              lines.emplace_back(new InfoBoxLine('\t', ""));
            } else if (iter.get_key() == "text") {
              std::string type, string;

              if (!iter.as_mapping().get("type", type)) {
                type = "normal";
              }

              if (!iter.as_mapping().get("string", string)) {
                throw std::runtime_error("Text entry requires a string");
              }

              if (type == "normal")
                lines.emplace_back(new InfoBoxLine('\t', string));
              else if (type == "normal-left")
                lines.emplace_back(new InfoBoxLine('#', string));
              else if (type == "small")
                lines.emplace_back(new InfoBoxLine(' ', string));
              else if (type == "heading")
                lines.emplace_back(new InfoBoxLine('-', string));
              else if (type == "reference")
                lines.emplace_back(new InfoBoxLine('*', string));
              else {
                log_warning << "[" << filename << "] Unknown text type '" << type << "'" << std::endl;
                lines.emplace_back(new InfoBoxLine('\t', string));
              }
            } else {
              log_warning << "[" << filename << "] Unknown token '" << iter.get_key() << "'" << std::endl;
            }
          }
        }
      } else {
        throw std::runtime_error("File format version is not supported");
      }

      if (!text_lisp.get("background", background_file)) {
        throw std::runtime_error("File doesn't contain a background file");
      }

      text_lisp.get("speed", defaultspeed);
      text_lisp.get("music", music);
    }
  } catch (std::exception& e) {
    std::ostringstream msg;
    msg << "Couldn't load file '" << filename << "': " << e.what() << std::endl;
    throw std::runtime_error(msg.str());
  }

  // load background image
  background = Surface::create("images/background/" + background_file);
}
/* Try to get a file descriptor for the shared meory segment
   containing the database.  */
static struct mapped_database *
get_mapping (request_type type, const char *key,
	     struct mapped_database **mappedp)
{
  struct mapped_database *result = NO_MAPPING;
#ifdef SCM_RIGHTS
  const size_t keylen = strlen (key) + 1;
  char resdata[keylen];
  int saved_errno = errno;

  int mapfd = -1;

  /* Send the request.  */
  struct iovec iov[2];
  request_header req;

  int sock = open_socket ();
  if (sock < 0)
    goto out;

  req.version = NSCD_VERSION;
  req.type = type;
  req.key_len = keylen;

  iov[0].iov_base = &req;
  iov[0].iov_len = sizeof (req);
  iov[1].iov_base = (void *) key;
  iov[1].iov_len = keylen;

  if (__builtin_expect (TEMP_FAILURE_RETRY (__writev (sock, iov, 2))
			!= iov[0].iov_len + iov[1].iov_len, 0))
    /* We cannot even write the request.  */
    goto out_close2;

  /* Room for the data sent along with the file descriptor.  We expect
     the key name back.  */
  iov[0].iov_base = resdata;
  iov[0].iov_len = keylen;

  union
  {
    struct cmsghdr hdr;
    char bytes[CMSG_SPACE (sizeof (int))];
  } buf;
  struct msghdr msg = { .msg_iov = iov, .msg_iovlen = 1,
			.msg_control = buf.bytes,
			.msg_controllen = sizeof (buf) };
  struct cmsghdr *cmsg = CMSG_FIRSTHDR (&msg);

  cmsg->cmsg_level = SOL_SOCKET;
  cmsg->cmsg_type = SCM_RIGHTS;
  cmsg->cmsg_len = CMSG_LEN (sizeof (int));

  /* This access is well-aligned since BUF is correctly aligned for an
     int and CMSG_DATA preserves this alignment.  */
  *(int *) CMSG_DATA (cmsg) = -1;

  msg.msg_controllen = cmsg->cmsg_len;

  if (wait_on_socket (sock) <= 0)
    goto out_close2;

# ifndef MSG_NOSIGNAL
#  define MSG_NOSIGNAL 0
# endif
  if (__builtin_expect (TEMP_FAILURE_RETRY (__recvmsg (sock, &msg,
						       MSG_NOSIGNAL))
			!= keylen, 0))
    goto out_close2;

  mapfd = *(int *) CMSG_DATA (cmsg);

  if (__builtin_expect (CMSG_FIRSTHDR (&msg)->cmsg_len
			!= CMSG_LEN (sizeof (int)), 0))
    goto out_close;

  struct stat64 st;
  if (__builtin_expect (strcmp (resdata, key) != 0, 0)
      || __builtin_expect (fstat64 (mapfd, &st) != 0, 0)
      || __builtin_expect (st.st_size < sizeof (struct database_pers_head), 0))
    goto out_close;

  struct database_pers_head head;
  if (__builtin_expect (TEMP_FAILURE_RETRY (__pread (mapfd, &head,
						     sizeof (head), 0))
			!= sizeof (head), 0))
    goto out_close;

  if (__builtin_expect (head.version != DB_VERSION, 0)
      || __builtin_expect (head.header_size != sizeof (head), 0)
      /* This really should not happen but who knows, maybe the update
	 thread got stuck.  */
      || __builtin_expect (! head.nscd_certainly_running
			   && head.timestamp + MAPPING_TIMEOUT < time (NULL),
			   0))
    goto out_close;

  size_t size = (sizeof (head) + roundup (head.module * sizeof (ref_t), ALIGN)
		 + head.data_size);

  if (__builtin_expect (st.st_size < size, 0))
    goto out_close;

  /* The file is large enough, map it now.  */
  void *mapping = __mmap (NULL, size, PROT_READ, MAP_SHARED, mapfd, 0);
  if (__builtin_expect (mapping != MAP_FAILED, 1))
    {
      /* Allocate a record for the mapping.  */
      struct mapped_database *newp = malloc (sizeof (*newp));
      if (newp == NULL)
	{
	  /* Ugh, after all we went through the memory allocation failed.  */
	  __munmap (mapping, size);
	  goto out_close;
	}

      newp->head = mapping;
      newp->data = ((char *) mapping + head.header_size
		    + roundup (head.module * sizeof (ref_t), ALIGN));
      newp->mapsize = size;
      /* Set counter to 1 to show it is usable.  */
      newp->counter = 1;

      result = newp;
    }

 out_close:
  __close (mapfd);
 out_close2:
  __close (sock);
 out:
  __set_errno (saved_errno);
#endif	/* SCM_RIGHTS */

  struct mapped_database *oldval = *mappedp;
  *mappedp = result;

  if (oldval != NULL && atomic_decrement_val (&oldval->counter) == 0)
    __nscd_unmap (oldval);

  return result;
}


struct mapped_database *
__nscd_get_map_ref (request_type type, const char *name,
		    struct locked_map_ptr *mapptr, int *gc_cyclep)
{
  struct mapped_database *cur = mapptr->mapped;
  if (cur == NO_MAPPING)
    return cur;

  int cnt = 0;
  while (atomic_compare_and_exchange_val_acq (&mapptr->lock, 1, 0) != 0)
    {
      // XXX Best number of rounds?
      if (++cnt > 5)
	return NO_MAPPING;

      atomic_delay ();
    }

  cur = mapptr->mapped;

  if (__builtin_expect (cur != NO_MAPPING, 1))
    {
      /* If not mapped or timestamp not updated, request new map.  */
      if (cur == NULL
	  || (cur->head->nscd_certainly_running == 0
	      && cur->head->timestamp + MAPPING_TIMEOUT < time (NULL)))
	cur = get_mapping (type, name, &mapptr->mapped);

      if (__builtin_expect (cur != NO_MAPPING, 1))
	{
	  if (__builtin_expect (((*gc_cyclep = cur->head->gc_cycle) & 1) != 0,
				0))
	    cur = NO_MAPPING;
	  else
	    atomic_increment (&cur->counter);
	}
    }

  mapptr->lock = 0;

  return cur;
}


const struct datahead *
__nscd_cache_search (request_type type, const char *key, size_t keylen,
		     const struct mapped_database *mapped)
{
  unsigned long int hash = __nis_hash (key, keylen) % mapped->head->module;

  ref_t work = mapped->head->array[hash];
  while (work != ENDREF)
    {
      struct hashentry *here = (struct hashentry *) (mapped->data + work);

      if (type == here->type && keylen == here->len
	  && memcmp (key, mapped->data + here->key, keylen) == 0)
	{
	  /* We found the entry.  Increment the appropriate counter.  */
	  const struct datahead *dh
	    = (struct datahead *) (mapped->data + here->packet);

	  /* See whether we must ignore the entry or whether something
	     is wrong because garbage collection is in progress.  */
	  if (dh->usable && ((char *) dh + dh->allocsize
			     <= (char *) mapped->head + mapped->mapsize))
	    return dh;
	}

      work = here->next;
    }

  return NULL;
}
Exemple #28
0
void
Config::load()
{
  auto doc = ReaderDocument::from_file("config");
  auto root = doc.get_root();
  if (root.get_name() != "supertux-config")
  {
    throw std::runtime_error("File is not a supertux-config file");
  }

  auto config_mapping = root.get_mapping();
  config_mapping.get("profile", profile);
  config_mapping.get("show_fps", show_fps);
  config_mapping.get("show_player_pos", show_player_pos);
  config_mapping.get("developer", developer_mode);
  config_mapping.get("confirmation_dialog", confirmation_dialog);
  config_mapping.get("pause_on_focusloss", pause_on_focusloss);

  if (is_christmas()) {
    if (!config_mapping.get("christmas", christmas_mode))
    {
      christmas_mode = true;
    }
  }
  config_mapping.get("transitions_enabled", transitions_enabled);
  config_mapping.get("locale", locale);
  config_mapping.get("random_seed", random_seed);
  config_mapping.get("repository_url", repository_url);

  boost::optional<ReaderMapping> config_video_mapping;
  if (config_mapping.get("video", config_video_mapping))
  {
    config_video_mapping->get("fullscreen", use_fullscreen);
    std::string video_string;
    config_video_mapping->get("video", video_string);
    video = VideoSystem::get_video_system(video_string);
    config_video_mapping->get("vsync", try_vsync);

    config_video_mapping->get("fullscreen_width",  fullscreen_size.width);
    config_video_mapping->get("fullscreen_height", fullscreen_size.height);
    if (fullscreen_size.width < 0 || fullscreen_size.height < 0)
    {
      // Somehow, an invalid size got entered into the config file,
      // let's use the "auto" setting instead.
      fullscreen_size = Size(0, 0);
    }
    config_video_mapping->get("fullscreen_refresh_rate", fullscreen_refresh_rate);

    config_video_mapping->get("window_width",  window_size.width);
    config_video_mapping->get("window_height", window_size.height);

    config_video_mapping->get("window_resizable", window_resizable);

    config_video_mapping->get("aspect_width",  aspect_size.width);
    config_video_mapping->get("aspect_height", aspect_size.height);

    config_video_mapping->get("magnification", magnification);
  }

  boost::optional<ReaderMapping> config_audio_mapping;
  if (config_mapping.get("audio", config_audio_mapping))
  {
    config_audio_mapping->get("sound_enabled", sound_enabled);
    config_audio_mapping->get("music_enabled", music_enabled);
    config_audio_mapping->get("sound_volume", sound_volume);
    config_audio_mapping->get("music_volume", music_volume);
  }

  boost::optional<ReaderMapping> config_control_mapping;
  if (config_mapping.get("control", config_control_mapping))
  {
    boost::optional<ReaderMapping> keymap_mapping;
    if (config_control_mapping->get("keymap", keymap_mapping))
    {
      keyboard_config.read(*keymap_mapping);
    }

    boost::optional<ReaderMapping> joystick_mapping;
    if (config_control_mapping->get("joystick", joystick_mapping))
    {
      joystick_config.read(*joystick_mapping);
    }
  }

  boost::optional<ReaderCollection> config_addons_mapping;
  if (config_mapping.get("addons", config_addons_mapping))
  {
    for (auto const& addon_node : config_addons_mapping->get_objects())
    {
      if (addon_node.get_name() == "addon")
      {
        auto addon = addon_node.get_mapping();

        std::string id;
        bool enabled = false;
        if (addon.get("id", id) &&
            addon.get("enabled", enabled))
        {
          addons.push_back({id, enabled});
        }
      }
      else
      {
        log_warning << "Unknown token in config file: " << addon_node.get_name() << std::endl;
      }
    }
  }
}
/**
 * Construct a ureg for the given source register.  Will emit
 * constants, apply swizzling and negation as needed.
 */
static uint
src_vector(struct i915_fp_compile *p,
           const struct i915_full_src_register *source,
           struct i915_fragment_shader *fs)
{
   uint index = source->Register.Index;
   uint src = 0, sem_name, sem_ind;

   switch (source->Register.File) {
   case TGSI_FILE_TEMPORARY:
      if (source->Register.Index >= I915_MAX_TEMPORARY) {
         i915_program_error(p, "Exceeded max temporary reg");
         return 0;
      }
      src = UREG(REG_TYPE_R, index);
      break;
   case TGSI_FILE_INPUT:
      /* XXX: Packing COL1, FOGC into a single attribute works for
       * texenv programs, but will fail for real fragment programs
       * that use these attributes and expect them to be a full 4
       * components wide.  Could use a texcoord to pass these
       * attributes if necessary, but that won't work in the general
       * case.
       * 
       * We also use a texture coordinate to pass wpos when possible.
       */

      sem_name = p->shader->info.input_semantic_name[index];
      sem_ind = p->shader->info.input_semantic_index[index];

      switch (sem_name) {
      case TGSI_SEMANTIC_POSITION:
         {
            /* for fragcoord */
            int real_tex_unit = get_mapping(fs, I915_SEMANTIC_POS);
            src = i915_emit_decl(p, REG_TYPE_T, T_TEX0 + real_tex_unit, D0_CHANNEL_ALL);
            break;
         }
      case TGSI_SEMANTIC_COLOR:
         if (sem_ind == 0) {
            src = i915_emit_decl(p, REG_TYPE_T, T_DIFFUSE, D0_CHANNEL_ALL);
         }
         else {
            /* secondary color */
            assert(sem_ind == 1);
            src = i915_emit_decl(p, REG_TYPE_T, T_SPECULAR, D0_CHANNEL_XYZ);
            src = swizzle(src, X, Y, Z, ONE);
         }
         break;
      case TGSI_SEMANTIC_FOG:
         src = i915_emit_decl(p, REG_TYPE_T, T_FOG_W, D0_CHANNEL_W);
         src = swizzle(src, W, W, W, W);
         break;
      case TGSI_SEMANTIC_GENERIC:
         {
            int real_tex_unit = get_mapping(fs, sem_ind);
            src = i915_emit_decl(p, REG_TYPE_T, T_TEX0 + real_tex_unit, D0_CHANNEL_ALL);
            break;
         }
      case TGSI_SEMANTIC_FACE:
         {
            /* for back/front faces */
            int real_tex_unit = get_mapping(fs, I915_SEMANTIC_FACE);
            src = i915_emit_decl(p, REG_TYPE_T, T_TEX0 + real_tex_unit, D0_CHANNEL_X);
            break;
         }
      default:
         i915_program_error(p, "Bad source->Index");
         return 0;
      }
      break;

   case TGSI_FILE_IMMEDIATE:
      assert(index < p->num_immediates);
      index = p->immediates_map[index];
      /* fall-through */
   case TGSI_FILE_CONSTANT:
      src = UREG(REG_TYPE_CONST, index);
      break;

   default:
      i915_program_error(p, "Bad source->File");
      return 0;
   }

   src = swizzle(src,
		 source->Register.SwizzleX,
		 source->Register.SwizzleY,
		 source->Register.SwizzleZ,
		 source->Register.SwizzleW);

   /* There's both negate-all-components and per-component negation.
    * Try to handle both here.
    */
   {
      int n = source->Register.Negate;
      src = negate(src, n, n, n, n);
   }

   /* no abs() */
#if 0
   /* XXX assertions disabled to allow arbfplight.c to run */
   /* XXX enable these assertions, or fix things */
   assert(!source->Register.Absolute);
#endif
   if (source->Register.Absolute)
      debug_printf("Unhandled absolute value\n");

   return src;
}
Exemple #30
0
void
Config::load()
{
  auto doc = ReaderDocument::parse("config");
  auto root = doc.get_root();
  if(root.get_name() != "supertux-config")
  {
    throw std::runtime_error("File is not a supertux-config file");
  }

  auto config_lisp = root.get_mapping();
  config_lisp.get("profile", profile);
  config_lisp.get("show_fps", show_fps);
  config_lisp.get("show_player_pos", show_player_pos);
  config_lisp.get("developer", developer_mode);

  if(is_christmas()) {
    if(!config_lisp.get("christmas", christmas_mode))
    {
      christmas_mode = true;
    }
  }
  config_lisp.get("transitions_enabled", transitions_enabled);
  config_lisp.get("locale", locale);
  config_lisp.get("random_seed", random_seed);
  config_lisp.get("repository_url", repository_url);

  ReaderMapping config_video_lisp;
  if(config_lisp.get("video", config_video_lisp))
  {
    config_video_lisp.get("fullscreen", use_fullscreen);
    std::string video_string;
    config_video_lisp.get("video", video_string);
    video = VideoSystem::get_video_system(video_string);
    config_video_lisp.get("vsync", try_vsync);

    config_video_lisp.get("fullscreen_width",  fullscreen_size.width);
    config_video_lisp.get("fullscreen_height", fullscreen_size.height);
    config_video_lisp.get("fullscreen_refresh_rate", fullscreen_refresh_rate);

    config_video_lisp.get("window_width",  window_size.width);
    config_video_lisp.get("window_height", window_size.height);

    config_video_lisp.get("aspect_width",  aspect_size.width);
    config_video_lisp.get("aspect_height", aspect_size.height);

    config_video_lisp.get("magnification", magnification);
  }

  ReaderMapping config_audio_lisp;
  if(config_lisp.get("audio", config_audio_lisp)) {
    config_audio_lisp.get("sound_enabled", sound_enabled);
    config_audio_lisp.get("music_enabled", music_enabled);
  }

  ReaderMapping config_control_lisp;
  if (config_lisp.get("control", config_control_lisp))
  {
    ReaderMapping keymap_lisp;
    if (config_control_lisp.get("keymap", keymap_lisp))
    {
      keyboard_config.read(keymap_lisp);
    }

    ReaderMapping joystick_lisp;
    if (config_control_lisp.get("joystick", joystick_lisp))
    {
      joystick_config.read(joystick_lisp);
    }
  }

  ReaderCollection config_addons_lisp;
  if (config_lisp.get("addons", config_addons_lisp))
  {
    for(auto const& addon_node : config_addons_lisp.get_objects())
    {
      if (addon_node.get_name() == "addon")
      {
        auto addon = addon_node.get_mapping();

        std::string id;
        bool enabled = false;
        if (addon.get("id", id) &&
            addon.get("enabled", enabled))
        {
          addons.push_back({id, enabled});
        }
      }
      else
      {
        log_warning << "Unknown token in config file: " << addon_node.get_name() << std::endl;
      }
    }
  }
}