<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;

#include "common/config.h"

#include "mon/MonMap.h"
#include "mon/Monitor.h"
#include "mon/MonitorStore.h"
#include "mon/MonClient.h"

#include "msg/SimpleMessenger.h"

#include "include/CompatSet.h"

#include "common/ceph_argparse.h"
#include "common/pick_address.h"
#include "common/Timer.h"
#include "common/errno.h"

#include "global/global_init.h"

extern CompatSet get_ceph_mon_feature_compat_set();

void usage()
{
  cerr << "usage: ceph-mon -i monid [--mon-data=pathtodata] [flags]" << std::endl;
  cerr << "  --debug_mon n\n";
  cerr << "        debug monitor level (e.g. 10)\n";
  cerr << "  --mkfs\n";
  cerr << "        build fresh monitor fs\n";
  generic_server_usage();
}

int main(int argc, const char **argv)
{
  int err;

  bool mkfs = false;
  std::string osdmapfn, inject_monmap;

  vector<const char*> args;
  argv_to_vec(argc, argv, args);
  env_to_vec(args);

  global_init(args, CEPH_ENTITY_TYPE_MON, CODE_ENVIRONMENT_DAEMON, 0);

  uuid_d fsid;
  std::string val;
  for (std::vector<const char*>::iterator i = args.begin(); i != args.end(); ) {
    if (ceph_argparse_double_dash(args, i)) {
      break;
    } else if (ceph_argparse_flag(args, i, "-h", "--help", (char*)NULL)) {
      usage();
      exit(0);
    } else if (ceph_argparse_flag(args, i, "--mkfs", (char*)NULL)) {
      mkfs = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--osdmap", (char*)NULL)) {
      osdmapfn = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--inject_monmap", (char*)NULL)) {
      inject_monmap = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--fsid", (char*)NULL)) {
      if (!fsid.parse(val.c_str())) {
	cerr << "unable to parse fsid '" << val << "'" << std::endl;
	exit(1);
      }
    } else {
      ++i;
    }
  }
  if (!args.empty()) {
    cerr << "too many arguments: " << args << std::endl;
    usage();
  }

  if (g_conf->mon_data.empty()) {
    cerr << "must specify '--mon-data=foo' data path" << std::endl;
    usage();
  }

  // -- mkfs --
  if (mkfs) {
    // resolve public_network -> public_addr
    pick_addresses(g_ceph_context);

    common_init_finish(g_ceph_context);

    bufferlist monmapbl, osdmapbl;
    std::string error;
    MonMap monmap;

    // load or generate monmap
    if (g_conf->monmap.length()) {
      int err = monmapbl.read_file(g_conf->monmap.c_str(), &error);
      if (err < 0) {
	cerr << argv[0] << ": error reading " << g_conf->monmap << ": " << error << std::endl;
	exit(1);
      }
      try {
	monmap.decode(monmapbl);
      }
      catch (const buffer::error& e) {
	cerr << argv[0] << ": error decoding monmap " << g_conf->monmap << ": " << e.what() << std::endl;
	exit(1);
      }
    } else {
      int err = MonClient::build_initial_monmap(g_ceph_context, monmap);
      if (err < 0) {
	cerr << argv[0] << ": error generating initial monmap: " << cpp_strerror(err) << std::endl;
	usage();
	exit(1);
      }

      // am i part of the initial quorum?
      if (monmap.contains(g_conf->name.get_id())) {
	// hmm, make sure the ip listed exists on the current host?
	// maybe later.
      } else if (!g_conf->public_addr.is_blank_ip()) {
	entity_addr_t a = g_conf->public_addr;
	if (a.get_port() == 0)
	  a.set_port(CEPH_MON_PORT);
	if (monmap.contains(a)) {
	  string name;
	  monmap.get_addr_name(a, name);
	  monmap.rename(name, g_conf->name.get_id());
	  cout << argv[0] << ": renaming mon." << name << " " << a
	       << " to mon." << g_conf->name.get_id() << std::endl;
	}
      } else {
	// is a local address listed without a name?  if so, name myself.
	list<entity_addr_t> ls;
	monmap.list_addrs(ls);
	entity_addr_t local;

	if (have_local_addr(g_ceph_context, ls, &local)) {
	  string name;
	  monmap.get_addr_name(local, name);

	  if (name.find("noname-") == 0) {
	    cout << argv[0] << ": mon." << name << " " << local
		 << " is local, renaming to mon." << g_conf->name.get_id() << std::endl;
	    monmap.rename(name, g_conf->name.get_id());
	  } else {
	    cout << argv[0] << ": mon." << name << " " << local
		 << " is local, but not 'noname-' + something; not assuming it's me" << std::endl;
	  }
	}
      }
    }

    if (!fsid.is_zero()) {
      cout << argv[0] << ": setting fsid to " << fsid << std::endl;
      monmap.fsid = fsid;
    }

    if (monmap.fsid.is_zero()) {
      cerr << argv[0] << ": generated monmap has no fsid; use '--fsid <uuid>'" << std::endl;
      exit(10);
    }

    //monmap.print(cout);

    // osdmap
    if (osdmapfn.length()) {
      err = osdmapbl.read_file(osdmapfn.c_str(), &error);
      if (err < 0) {
	cerr << argv[0] << ": error reading " << osdmapfn << ": "
	     << error << std::endl;
	exit(1);
      }
    }

    // go
    MonitorStore store(g_conf->mon_data);
    Monitor mon(g_ceph_context, g_conf->name.get_id(), &store, 0, &monmap);
    mon.mkfs(osdmapbl);
    cout << argv[0] << ": created monfs at " << g_conf->mon_data
	 << " for " << g_conf->name << std::endl;
    return 0;
  }

  CompatSet mon_features = get_ceph_mon_feature_compat_set();
  CompatSet ondisk_features;

  MonitorStore store(g_conf->mon_data);
  err = store.mount();
  if (err < 0) {
    cerr << "problem opening monitor store in " << g_conf->mon_data << ": " << cpp_strerror(err) << std::endl;
    exit(1);
  }

  bufferlist magicbl;
  err = store.get_bl_ss(magicbl, "magic", 0);
  if (err < 0) {
    cerr << "unable to read magic from mon data.. did you run mkcephfs?" << std::endl;
    exit(1);
  }
  string magic(magicbl.c_str(), magicbl.length()-1);  // ignore trailing \n
  if (strcmp(magic.c_str(), CEPH_MON_ONDISK_MAGIC)) {
    cerr << "mon fs magic '" << magic << "' != current '" << CEPH_MON_ONDISK_MAGIC << "'" << std::endl;
    exit(1);
  }

  bufferlist features;
  store.get_bl_ss(features, COMPAT_SET_LOC, 0);
  if (features.length() == 0) {
    cerr << "WARNING: mon fs missing feature list.\n"
	 << "Assuming it is old-style and introducing one." << std::endl;
    //we only want the baseline ~v.18 features assumed to be on disk.
    //If new features are introduced this code needs to disappear or
    //be made smarter.
    ondisk_features = get_ceph_mon_feature_compat_set();
  } else {
    bufferlist::iterator it = features.begin();
    ondisk_features.decode(it);
  }

  if (!mon_features.writeable(ondisk_features)) {
    cerr << "monitor executable cannot read disk! Missing features: "
	 << std::endl;
    CompatSet diff = mon_features.unsupported(ondisk_features);
    //NEEDS_COMPATSET_ITER
    exit(1);
  }

  // inject new monmap?
  if (!inject_monmap.empty()) {
    bufferlist bl;
    std::string error;
    int r = bl.read_file(inject_monmap.c_str(), &error);
    if (r) {
      cerr << "unable to read monmap from " << inject_monmap << ": "
	   << error << std::endl;
      exit(1);
    }

    // get next version
    version_t v = store.get_int("monmap", "last_committed");
    cout << "last committed monmap epoch is " << v << ", injected map will be " << (v+1) << std::endl;
    v++;

    // set the version
    MonMap tmp;
    tmp.decode(bl);
    if (tmp.get_epoch() != v) {
      cout << "changing monmap epoch from " << tmp.get_epoch() << " to " << v << std::endl;
      tmp.set_epoch(v);
    }
    bufferlist mapbl;
    tmp.encode(mapbl);
    bufferlist final;
    ::encode(v, final);
    ::encode(mapbl, final);

    // save it
    store.put_bl_sn(mapbl, "monmap", v);
    store.put_bl_ss(final, "monmap", "latest");
    store.put_int(v, "monmap", "last_committed");

    cout << "done." << std::endl;
    exit(0);
  }

  // monmap?
  MonMap monmap;
  {
    bufferlist mapbl;
    bufferlist latest;
    store.get_bl_ss(latest, "monmap", "latest");
    if (latest.length() > 0) {
      bufferlist::iterator p = latest.begin();
      version_t v;
      ::decode(v, p);
      ::decode(mapbl, p);
    } else {
      store.get_bl_ss(mapbl, "mkfs", "monmap");
      if (mapbl.length() == 0) {
	cerr << "mon fs missing 'monmap/latest' and 'mkfs/monmap'" << std::endl;
	exit(1);
      }
    }
    try {
      monmap.decode(mapbl);
    }
    catch (const buffer::error& e) {
      cerr << "can't decode monmap: " << e.what() << std::endl;
    }
  }

  // this is what i will bind to
  entity_addr_t ipaddr;

  if (monmap.contains(g_conf->name.get_id())) {
    ipaddr = monmap.get_addr(g_conf->name.get_id());

    // print helpful warning if the conf file doesn't match
    entity_addr_t conf_addr;
    std::vector <std::string> my_sections;
    g_conf->get_my_sections(my_sections);
    std::string mon_addr_str;
    if (g_conf->get_val_from_conf_file(my_sections, "mon addr",
				       mon_addr_str, true) == 0) {
      if (conf_addr.parse(mon_addr_str.c_str()) && (ipaddr != conf_addr)) {
	cerr << "WARNING: 'mon addr' config option " << conf_addr
	     << " does not match monmap file" << std::endl
	     << "         continuing with monmap configuration" << std::endl;
      }
    }
  } else {
    dout(0) << g_conf->name << " does not exist in monmap, will attempt to join an existing cluster" << dendl;

    pick_addresses(g_ceph_context);
    if (g_conf->public_addr.is_blank_ip()) {
      derr << "no public_addr or public_network specified, and " << g_conf->name
	   << " not present in monmap" << dendl;
      exit(1);
    }
    ipaddr = g_conf->public_addr;
  }

  // bind
  SimpleMessenger *messenger = new SimpleMessenger(g_ceph_context);
  int rank = monmap.get_rank(g_conf->name.get_id());

  global_print_banner();

  cout << "starting " << g_conf->name << " rank " << rank
       << " at " << ipaddr
       << " mon_data " << g_conf->mon_data
       << " fsid " << monmap.get_fsid()
       << std::endl;

  err = messenger->bind(ipaddr, 0);
  if (err < 0)
    return 1;

  // start monitor
  messenger->register_entity(entity_name_t::MON(rank));
  messenger->set_default_send_priority(CEPH_MSG_PRIO_HIGH);
  Monitor *mon = new Monitor(g_ceph_context, g_conf->name.get_id(), &store, messenger, &monmap);

  global_init_daemonize(g_ceph_context, 0);
  common_init_finish(g_ceph_context);
  global_init_chdir(g_ceph_context);
  messenger->start();

  uint64_t supported =
    CEPH_FEATURE_UID |
    CEPH_FEATURE_NOSRCADDR |
    CEPH_FEATURE_MONCLOCKCHECK |
    CEPH_FEATURE_PGID64;
  messenger->set_default_policy(SimpleMessenger::Policy::stateless_server(supported, 0));
  messenger->set_policy(entity_name_t::TYPE_MON,
			SimpleMessenger::Policy::lossless_peer(supported,
							       CEPH_FEATURE_UID |
							       CEPH_FEATURE_PGID64));
  messenger->set_policy(entity_name_t::TYPE_OSD,
			SimpleMessenger::Policy::stateless_server(supported,
								  CEPH_FEATURE_PGID64));
  mon->init();
  messenger->wait();

  store.umount();
  delete mon;
  messenger->destroy();

  // cd on exit, so that gmon.out (if any) goes into a separate directory for each node.
  char s[20];
  snprintf(s, sizeof(s), "gmon/%d", getpid());
  if ((mkdir(s, 0755) == 0) && (chdir(s) == 0)) {
    dout(0) << "ceph-mon: gmon.out should be in " << s << dendl;
  }

  return 0;
}

<commit_msg>mon: pull addr from ceph.conf, mon_host as needed when joining mon cluster<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;

#include "common/config.h"

#include "mon/MonMap.h"
#include "mon/Monitor.h"
#include "mon/MonitorStore.h"
#include "mon/MonClient.h"

#include "msg/SimpleMessenger.h"

#include "include/CompatSet.h"

#include "common/ceph_argparse.h"
#include "common/pick_address.h"
#include "common/Timer.h"
#include "common/errno.h"

#include "global/global_init.h"

extern CompatSet get_ceph_mon_feature_compat_set();

void usage()
{
  cerr << "usage: ceph-mon -i monid [--mon-data=pathtodata] [flags]" << std::endl;
  cerr << "  --debug_mon n\n";
  cerr << "        debug monitor level (e.g. 10)\n";
  cerr << "  --mkfs\n";
  cerr << "        build fresh monitor fs\n";
  generic_server_usage();
}

int main(int argc, const char **argv)
{
  int err;

  bool mkfs = false;
  std::string osdmapfn, inject_monmap;

  vector<const char*> args;
  argv_to_vec(argc, argv, args);
  env_to_vec(args);

  global_init(args, CEPH_ENTITY_TYPE_MON, CODE_ENVIRONMENT_DAEMON, 0);

  uuid_d fsid;
  std::string val;
  for (std::vector<const char*>::iterator i = args.begin(); i != args.end(); ) {
    if (ceph_argparse_double_dash(args, i)) {
      break;
    } else if (ceph_argparse_flag(args, i, "-h", "--help", (char*)NULL)) {
      usage();
      exit(0);
    } else if (ceph_argparse_flag(args, i, "--mkfs", (char*)NULL)) {
      mkfs = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--osdmap", (char*)NULL)) {
      osdmapfn = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--inject_monmap", (char*)NULL)) {
      inject_monmap = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--fsid", (char*)NULL)) {
      if (!fsid.parse(val.c_str())) {
	cerr << "unable to parse fsid '" << val << "'" << std::endl;
	exit(1);
      }
    } else {
      ++i;
    }
  }
  if (!args.empty()) {
    cerr << "too many arguments: " << args << std::endl;
    usage();
  }

  if (g_conf->mon_data.empty()) {
    cerr << "must specify '--mon-data=foo' data path" << std::endl;
    usage();
  }

  // -- mkfs --
  if (mkfs) {
    // resolve public_network -> public_addr
    pick_addresses(g_ceph_context);

    common_init_finish(g_ceph_context);

    bufferlist monmapbl, osdmapbl;
    std::string error;
    MonMap monmap;

    // load or generate monmap
    if (g_conf->monmap.length()) {
      int err = monmapbl.read_file(g_conf->monmap.c_str(), &error);
      if (err < 0) {
	cerr << argv[0] << ": error reading " << g_conf->monmap << ": " << error << std::endl;
	exit(1);
      }
      try {
	monmap.decode(monmapbl);
      }
      catch (const buffer::error& e) {
	cerr << argv[0] << ": error decoding monmap " << g_conf->monmap << ": " << e.what() << std::endl;
	exit(1);
      }
    } else {
      int err = MonClient::build_initial_monmap(g_ceph_context, monmap);
      if (err < 0) {
	cerr << argv[0] << ": error generating initial monmap: " << cpp_strerror(err) << std::endl;
	usage();
	exit(1);
      }

      // am i part of the initial quorum?
      if (monmap.contains(g_conf->name.get_id())) {
	// hmm, make sure the ip listed exists on the current host?
	// maybe later.
      } else if (!g_conf->public_addr.is_blank_ip()) {
	entity_addr_t a = g_conf->public_addr;
	if (a.get_port() == 0)
	  a.set_port(CEPH_MON_PORT);
	if (monmap.contains(a)) {
	  string name;
	  monmap.get_addr_name(a, name);
	  monmap.rename(name, g_conf->name.get_id());
	  cout << argv[0] << ": renaming mon." << name << " " << a
	       << " to mon." << g_conf->name.get_id() << std::endl;
	}
      } else {
	// is a local address listed without a name?  if so, name myself.
	list<entity_addr_t> ls;
	monmap.list_addrs(ls);
	entity_addr_t local;

	if (have_local_addr(g_ceph_context, ls, &local)) {
	  string name;
	  monmap.get_addr_name(local, name);

	  if (name.find("noname-") == 0) {
	    cout << argv[0] << ": mon." << name << " " << local
		 << " is local, renaming to mon." << g_conf->name.get_id() << std::endl;
	    monmap.rename(name, g_conf->name.get_id());
	  } else {
	    cout << argv[0] << ": mon." << name << " " << local
		 << " is local, but not 'noname-' + something; not assuming it's me" << std::endl;
	  }
	}
      }
    }

    if (!fsid.is_zero()) {
      cout << argv[0] << ": setting fsid to " << fsid << std::endl;
      monmap.fsid = fsid;
    }

    if (monmap.fsid.is_zero()) {
      cerr << argv[0] << ": generated monmap has no fsid; use '--fsid <uuid>'" << std::endl;
      exit(10);
    }

    //monmap.print(cout);

    // osdmap
    if (osdmapfn.length()) {
      err = osdmapbl.read_file(osdmapfn.c_str(), &error);
      if (err < 0) {
	cerr << argv[0] << ": error reading " << osdmapfn << ": "
	     << error << std::endl;
	exit(1);
      }
    }

    // go
    MonitorStore store(g_conf->mon_data);
    Monitor mon(g_ceph_context, g_conf->name.get_id(), &store, 0, &monmap);
    mon.mkfs(osdmapbl);
    cout << argv[0] << ": created monfs at " << g_conf->mon_data
	 << " for " << g_conf->name << std::endl;
    return 0;
  }

  CompatSet mon_features = get_ceph_mon_feature_compat_set();
  CompatSet ondisk_features;

  MonitorStore store(g_conf->mon_data);
  err = store.mount();
  if (err < 0) {
    cerr << "problem opening monitor store in " << g_conf->mon_data << ": " << cpp_strerror(err) << std::endl;
    exit(1);
  }

  bufferlist magicbl;
  err = store.get_bl_ss(magicbl, "magic", 0);
  if (err < 0) {
    cerr << "unable to read magic from mon data.. did you run mkcephfs?" << std::endl;
    exit(1);
  }
  string magic(magicbl.c_str(), magicbl.length()-1);  // ignore trailing \n
  if (strcmp(magic.c_str(), CEPH_MON_ONDISK_MAGIC)) {
    cerr << "mon fs magic '" << magic << "' != current '" << CEPH_MON_ONDISK_MAGIC << "'" << std::endl;
    exit(1);
  }

  bufferlist features;
  store.get_bl_ss(features, COMPAT_SET_LOC, 0);
  if (features.length() == 0) {
    cerr << "WARNING: mon fs missing feature list.\n"
	 << "Assuming it is old-style and introducing one." << std::endl;
    //we only want the baseline ~v.18 features assumed to be on disk.
    //If new features are introduced this code needs to disappear or
    //be made smarter.
    ondisk_features = get_ceph_mon_feature_compat_set();
  } else {
    bufferlist::iterator it = features.begin();
    ondisk_features.decode(it);
  }

  if (!mon_features.writeable(ondisk_features)) {
    cerr << "monitor executable cannot read disk! Missing features: "
	 << std::endl;
    CompatSet diff = mon_features.unsupported(ondisk_features);
    //NEEDS_COMPATSET_ITER
    exit(1);
  }

  // inject new monmap?
  if (!inject_monmap.empty()) {
    bufferlist bl;
    std::string error;
    int r = bl.read_file(inject_monmap.c_str(), &error);
    if (r) {
      cerr << "unable to read monmap from " << inject_monmap << ": "
	   << error << std::endl;
      exit(1);
    }

    // get next version
    version_t v = store.get_int("monmap", "last_committed");
    cout << "last committed monmap epoch is " << v << ", injected map will be " << (v+1) << std::endl;
    v++;

    // set the version
    MonMap tmp;
    tmp.decode(bl);
    if (tmp.get_epoch() != v) {
      cout << "changing monmap epoch from " << tmp.get_epoch() << " to " << v << std::endl;
      tmp.set_epoch(v);
    }
    bufferlist mapbl;
    tmp.encode(mapbl);
    bufferlist final;
    ::encode(v, final);
    ::encode(mapbl, final);

    // save it
    store.put_bl_sn(mapbl, "monmap", v);
    store.put_bl_ss(final, "monmap", "latest");
    store.put_int(v, "monmap", "last_committed");

    cout << "done." << std::endl;
    exit(0);
  }

  // monmap?
  MonMap monmap;
  {
    bufferlist mapbl;
    bufferlist latest;
    store.get_bl_ss(latest, "monmap", "latest");
    if (latest.length() > 0) {
      bufferlist::iterator p = latest.begin();
      version_t v;
      ::decode(v, p);
      ::decode(mapbl, p);
    } else {
      store.get_bl_ss(mapbl, "mkfs", "monmap");
      if (mapbl.length() == 0) {
	cerr << "mon fs missing 'monmap/latest' and 'mkfs/monmap'" << std::endl;
	exit(1);
      }
    }
    try {
      monmap.decode(mapbl);
    }
    catch (const buffer::error& e) {
      cerr << "can't decode monmap: " << e.what() << std::endl;
    }
  }

  // this is what i will bind to
  entity_addr_t ipaddr;

  if (monmap.contains(g_conf->name.get_id())) {
    ipaddr = monmap.get_addr(g_conf->name.get_id());

    // print helpful warning if the conf file doesn't match
    entity_addr_t conf_addr;
    std::vector <std::string> my_sections;
    g_conf->get_my_sections(my_sections);
    std::string mon_addr_str;
    if (g_conf->get_val_from_conf_file(my_sections, "mon addr",
				       mon_addr_str, true) == 0) {
      if (conf_addr.parse(mon_addr_str.c_str()) && (ipaddr != conf_addr)) {
	cerr << "WARNING: 'mon addr' config option " << conf_addr
	     << " does not match monmap file" << std::endl
	     << "         continuing with monmap configuration" << std::endl;
      }
    }
  } else {
    dout(0) << g_conf->name << " does not exist in monmap, will attempt to join an existing cluster" << dendl;

    pick_addresses(g_ceph_context);
    if (!g_conf->public_addr.is_blank_ip()) {
      ipaddr = g_conf->public_addr;
    } else {
      MonMap tmpmap;
      int err = MonClient::build_initial_monmap(g_ceph_context, tmpmap);
      if (err < 0) {
	cerr << argv[0] << ": error generating initial monmap: " << cpp_strerror(err) << std::endl;
	usage();
	exit(1);
      }
      if (tmpmap.contains(g_conf->name.get_id())) {
	ipaddr = tmpmap.get_addr(g_conf->name.get_id());
      } else {
	derr << "no public_addr or public_network specified, and " << g_conf->name
	     << " not present in monmap or ceph.conf" << dendl;
	exit(1);
      }
    }
  }

  // bind
  SimpleMessenger *messenger = new SimpleMessenger(g_ceph_context);
  int rank = monmap.get_rank(g_conf->name.get_id());

  global_print_banner();

  cout << "starting " << g_conf->name << " rank " << rank
       << " at " << ipaddr
       << " mon_data " << g_conf->mon_data
       << " fsid " << monmap.get_fsid()
       << std::endl;

  err = messenger->bind(ipaddr, 0);
  if (err < 0)
    return 1;

  // start monitor
  messenger->register_entity(entity_name_t::MON(rank));
  messenger->set_default_send_priority(CEPH_MSG_PRIO_HIGH);
  Monitor *mon = new Monitor(g_ceph_context, g_conf->name.get_id(), &store, messenger, &monmap);

  global_init_daemonize(g_ceph_context, 0);
  common_init_finish(g_ceph_context);
  global_init_chdir(g_ceph_context);
  messenger->start();

  uint64_t supported =
    CEPH_FEATURE_UID |
    CEPH_FEATURE_NOSRCADDR |
    CEPH_FEATURE_MONCLOCKCHECK |
    CEPH_FEATURE_PGID64;
  messenger->set_default_policy(SimpleMessenger::Policy::stateless_server(supported, 0));
  messenger->set_policy(entity_name_t::TYPE_MON,
			SimpleMessenger::Policy::lossless_peer(supported,
							       CEPH_FEATURE_UID |
							       CEPH_FEATURE_PGID64));
  messenger->set_policy(entity_name_t::TYPE_OSD,
			SimpleMessenger::Policy::stateless_server(supported,
								  CEPH_FEATURE_PGID64));
  mon->init();
  messenger->wait();

  store.umount();
  delete mon;
  messenger->destroy();

  // cd on exit, so that gmon.out (if any) goes into a separate directory for each node.
  char s[20];
  snprintf(s, sizeof(s), "gmon/%d", getpid());
  if ((mkdir(s, 0755) == 0) && (chdir(s) == 0)) {
    dout(0) << "ceph-mon: gmon.out should be in " << s << dendl;
  }

  return 0;
}

<|endoftext|>


<commit_before>#include "WPILib.h"
#include "XboxController.h"
#include "Subsystems/Shooter.h"
#include "Subsystems/BallCollector.h"

class Robot: public IterativeRobot {
private:
	std::unique_ptr<XboxController> controller;
	std::unique_ptr<RobotDrive> robot_drive;
	std::unique_ptr<Shooter> shooter;
	std::unique_ptr<BallCollector> ball_collector;

	void RobotInit() {
		// Initialize Subsystems
		controller = std::unique_ptr<XboxController>(new XboxController(0));
		robot_drive = std::unique_ptr<RobotDrive> (new RobotDrive(1,2,3,4));
		shooter = std::unique_ptr<Shooter> (new Shooter());
		ball_collector = std::unique_ptr<BallCollector> (new BallCollector());
	}

	void DisabledInit() {
	}

	void DisabledPeriodic() {
		Scheduler::GetInstance()->Run();
	}

	void AutonomousInit() {

	}

	void AutonomousPeriodic() {

	}

	void TeleopInit() {

	}

	void TeleopPeriodic() {
		std::unique_ptr<Vector> left_stick_vector = std::unique_ptr<Vector>(controller->GetLeftVector());
		std::unique_ptr<Vector> right_stick_vector = std::unique_ptr<Vector>(controller->GetRightVector());

		robot_drive->TankDrive(left_stick_vector->magnitude, right_stick_vector->magnitude, false);

		if (controller->GetTrigger(controller->RightTrigger,controller->RightTriggerOffset) >= 0.5){
			shooter->run_shooter();
		}else{
			shooter->stop_shooter();
		}

		if (controller->GetTrigger(controller->LeftTrigger,controller->LeftTriggerOffset) >= 0.5){
			ball_collector->Start();
		}else{
			ball_collector->Stop();
		}
	}

	void TestPeriodic() {

	}
};

START_ROBOT_CLASS(Robot)

<commit_msg>Organized code<commit_after>#include "WPILib.h"
#include "XboxController.h"
#include "Subsystems/Shooter.h"
#include "Subsystems/BallCollector.h"

class Robot: public IterativeRobot {
private:
	// Robot
	std::unique_ptr<RobotDrive> robot_drive;

	// Input devices
	std::unique_ptr<XboxController> controller;

	// Subsystems
	std::unique_ptr<Shooter> shooter;
	std::unique_ptr<BallCollector> ball_collector;

	void RobotInit() {
		// Robot
		robot_drive = std::unique_ptr<RobotDrive> (new RobotDrive(1,2,3,4));

		// Input devices
		controller = std::unique_ptr<XboxController>(new XboxController(0));

		// Subsystems
		shooter = std::unique_ptr<Shooter> (new Shooter());
		ball_collector = std::unique_ptr<BallCollector> (new BallCollector());
	}

	void DisabledInit() {
	}

	void DisabledPeriodic() {
		Scheduler::GetInstance()->Run();
	}

	void AutonomousInit() {

	}

	void AutonomousPeriodic() {

	}

	void TeleopInit() {

	}

	void TeleopPeriodic() {
		// Chases drive
		std::unique_ptr<Vector> left_stick_vector = std::unique_ptr<Vector>(controller->GetLeftVector());
		std::unique_ptr<Vector> right_stick_vector = std::unique_ptr<Vector>(controller->GetRightVector());

		robot_drive->TankDrive(left_stick_vector->magnitude, right_stick_vector->magnitude, false);

		// Shooter control
		if (controller->GetTrigger(controller->RightTrigger,controller->RightTriggerOffset) >= 0.5){
			shooter->run_shooter();
		}else{
			shooter->stop_shooter();
		}

		// Ball Collector control
		if (controller->GetTrigger(controller->LeftTrigger,controller->LeftTriggerOffset) >= 0.5){
			ball_collector->Start();
		}else{
			ball_collector->Stop();
		}
	}

	void TestPeriodic() {

	}
};

START_ROBOT_CLASS(Robot)

<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS sw20402_SRC680 (1.90.132); FILE MERGED 2006/08/28 14:42:17 od 1.90.132.1: #i68958# method <_InsertCnt(..)> 	 - assure that information flags of text frame stay invalid after 	   calling method for accessibility events.<commit_after><|endoftext|>


<commit_before>#include <string>
#include <vector>
#include <iostream>
#include <thread>
#include <ctime>
#include <fstream>
#include <cstring>

#include "snapshot_class.hpp"
#include "common.hpp"
#include "date_class.hpp"
#include "global_defines.hpp"
#include "snapshot_file_loaders.hpp"
#include "filesystem.hpp"
#include "time_class.hpp"

namespace
{
    struct take_snapshot_proc_data;

    void construct_tsproc_data(take_snapshot_proc_data&, const std::string&);
    void collect_snapshot(take_snapshot_proc_data*);
    void show_process_output(take_snapshot_proc_data*);
    void display_current_status(take_snapshot_proc_data&);

    /* Unifies and limits the scope of the data that is used between
     * the functions of collect_snapshot and show_process_output. */
    struct take_snapshot_proc_data
    {
        std::string root, save_file, current_path;
        bool finished : 1, canceled : 1, paused : 1;
        unsigned long long sid, count;
        std::ofstream out;
    };

    void collect_snapshot(take_snapshot_proc_data *pd)
    {
        using fsys::tree_riterator_class;

        for(tree_riterator_class it(pd->root); (!it.at_end() && !pd->canceled); ++it)
        {
            (pd->out)<< it.value()<< mem_delim::value;
            pd->current_path = it.value();
            pd->count++;
            while(pd->paused) std::this_thread::sleep_for(std::chrono::milliseconds(33));
        }
        (pd->out)<< struct_delim::value;
        pd->finished = true;
    }

    void show_process_output(take_snapshot_proc_data *pd)
    {
        common::cl();
        while(!pd->finished && !pd->canceled)
        {
            display_current_status(*pd);
            std::this_thread::sleep_for(std::chrono::milliseconds(33));
            if(common::kbhit())
            {
                pd->paused = true;
                pd->canceled = common::inp::is_sure("Cancel taking this snapshot??");
                pd->paused = false;
                if(!pd->canceled) common::cl();
            }
        }
        if(!pd->canceled)
        {
            using std::cout;
            using std::endl;

            common::cls();
            for(unsigned int x = 0; x < v_center::value; x++) cout<< endl;
            common::center("Paths Captured: " + std::to_string(pd->count));
            common::wait();
            common::cls();
        }
    }

    void display_current_status(take_snapshot_proc_data& pd)
    {
        using std::cout;
        using std::endl;

        common::cls();
        cout<< "Press any key to cancel";
        for(unsigned int x = 0; x < 8; x++) cout<< endl;
        cout<< "root: \""<< pd.root<< "\""<< endl;
        cout<< "Paths saved: "<< pd.count<< endl;
        cout<< "Currently processing: \""<< pd.current_path<< "\""<< endl;
    }

    /** Initializes all the data for the snapshot collection.  It opens a file
     * and saves the header to a "new" snapshot, and it should be used before
     * executing a new snapshot. */
    void construct_tsproc_data(take_snapshot_proc_data& pd, const std::string& rt)
    {
        snapshot::snapshot_data head;

        if(!fsys::is_folder(snapshot::snapshot_folder()))
        {
            if(!fsys::create_folder(snapshot::snapshot_folder()).value) return;
        }
        pd.root = rt;
        pd.sid = snapshot::new_snapshot_id();
        pd.save_file = (snapshot::snapshot_folder() + fsys::pref_slash() +
                        std::to_string(pd.sid) + fsyssnap_SNAPSHOT_FILE_EXTENSION);
        pd.canceled = false;
        pd.finished = false;
        pd.paused = false;
        pd.count = 0;
        pd.current_path = "";

        head.timestamp = tdata::current_time();
        head.root = pd.root;
        head.id = pd.sid;
        pd.out.open(pd.save_file.c_str(), std::ios::binary);
        snapshot::out_header(pd.out, head);
    }

}

/* stream operators: */
namespace snapshot
{
    std::ostream& operator<<(std::ostream& out, const snapshot_data& snap)
    {
        if(out.good())
        {
            out_header(out, snap);
            for(std::vector<std::string>::const_iterator it = snap.paths.begin();
                    it != snap.paths.end(); ++it)
            {
                out<< *it<< mem_delim::value;
            }
            out<< struct_delim::value;
        }
        return out;
    }

    /** Sets failbit only if it fails to retrieve the snapshot. */
    std::istream& operator>>(std::istream& in, snapshot_data& snap)
    {
        using common::safe_getline;

        std::string temps;

        snap = snapshot_data();

        //peek: this will establish that the stream is good.
        in.peek();

        if(in.good())
        {
            in_header(in, snap);
            while(in.good() && (in.peek() != struct_delim::value) && (in.peek() != EOF))
            {
                if(safe_getline(in, temps, mem_delim::value)) snap.paths.push_back(temps);
            }
            if(in.peek() == struct_delim::value)
            {
                in.get();

                /* Clear error state if we've reached the end of the file.
                 * the read was a success, so the stream satte should reflect that.*/
                if(in.peek() == EOF) in.clear();
            }
        }
        return in;
    }

    const snapshot_data& snapshot_data::operator=(const snapshot_data& snap)
    {
        if(this != &snap)
        {
            this->timestamp = snap.timestamp;
            this->root = snap.root;
            this->id = snap.id;

            this->paths.clear();
            this->paths.shrink_to_fit();
            this->paths = snap.paths;
        }
        return *this;
    }

    bool snapshot_data::operator==(const snapshot_data& snap) const
    {
        return (
                (this->id == snap.id) &&
                (this->timestamp == snap.timestamp) &&
                (this->root == snap.root) &&
                (this->paths == snap.paths));
    }

    bool snapshot_data::operator!=(const snapshot_data& snap) const
    {
        return !(this->operator==(snap));
    }

    /** Compares two snapshot's times.  provided for sorting algorithms. */
    bool snapshot_data::operator<(const snapshot_data& s) const
    {
        return (this->timestamp < s.timestamp);
    }

}

/* take_snapshot member functions: */
namespace snapshot
{
    unsigned long long take_snapshot(const std::string& s)
    {
        take_snapshot_proc_data *pd(new take_snapshot_proc_data);
        unsigned long long id(0);

        construct_tsproc_data(*pd, s);

        std::thread collect(collect_snapshot, pd), output(show_process_output, pd);

        collect.join();
        output.join();
        if(pd->out.is_open()) pd->out.close();
        if(pd->canceled)
        {
            if(fsys::is_file(pd->save_file).value &&
                            !fsys::is_symlink(pd->save_file).value)
            {
                if(fsys::can_delete(pd->save_file))
                {
                    fsys::fdelete(pd->save_file);
                    pd->sid = 0;
                }
            }
        }
        id = pd->sid;
        delete pd;
        return id;
    }

    std::ostream& out_header(std::ostream& out, const snapshot_data& snap)
    {
        char *ch(new char[sizeof(unsigned long long)]);

        if(out.good())
        {
            out<< snap.timestamp;
            memcpy(ch, &snap.id, sizeof(unsigned long long));
            for(unsigned int x = 0; x < sizeof(unsigned long long); x++) out<< ch[x];
            out<< snap.root<< mem_delim::value;
        }
        delete[] ch;
        return out;
    }

    std::istream& in_header(std::istream& in, snapshot_data& snap)
    {
        using common::safe_getline;

        char *ch(new char[sizeof(unsigned long long)]);

        in.peek();
        if(in.good())
        {
            in>> snap.timestamp;
            for(unsigned int x = 0; ((x < sizeof(unsigned long long)) && in.good()); x++)
            {
                if(in.peek() != EOF) ch[x] = in.get();
            }
            memcpy(&snap.id, ch, sizeof(unsigned long long));
            safe_getline(in, snap.root, mem_delim::value);
        }
        in.peek();
        return in;
    }

}

<commit_msg>made changes to figure out the problem;<commit_after>#include <string>
#include <vector>
#include <iostream>
#include <thread>
#include <ctime>
#include <fstream>
#include <cstring>

#include "snapshot_class.hpp"
#include "common.hpp"
#include "date_class.hpp"
#include "global_defines.hpp"
#include "snapshot_file_loaders.hpp"
#include "filesystem.hpp"
#include "time_class.hpp"

namespace
{
    struct take_snapshot_proc_data;

    void construct_tsproc_data(take_snapshot_proc_data&, const std::string&);
    void collect_snapshot(take_snapshot_proc_data*);
    void show_process_output(take_snapshot_proc_data*);
    void display_current_status(take_snapshot_proc_data*);

    /* Unifies and limits the scope of the data that is used between
     * the functions of collect_snapshot and show_process_output. */
    struct take_snapshot_proc_data
    {
        std::string root, save_file, current_path;
        bool finished : 1, canceled : 1, paused : 1;
        unsigned long long sid, count;
        std::ofstream out;
    };

    void collect_snapshot(take_snapshot_proc_data *pd)
    {
        using fsys::tree_riterator_class;

        for(tree_riterator_class it(pd->root); (!it.at_end() && !pd->canceled); ++it)
        {
            (pd->out)<< it.value()<< mem_delim::value;
            pd->current_path = it.value();
            pd->count++;
            while(pd->paused) std::this_thread::sleep_for(std::chrono::milliseconds(33));
        }
        (pd->out)<< struct_delim::value;
        pd->finished = true;
    }

    void show_process_output(take_snapshot_proc_data *pd)
    {
        common::cl();
        while(!pd->finished && !pd->canceled)
        {
            display_current_status(pd);
            std::this_thread::sleep_for(std::chrono::milliseconds(33));
            if(common::kbhit())
            {
                pd->paused = true;
                pd->canceled = common::inp::is_sure("Cancel taking this snapshot??");
                pd->paused = false;
                if(!pd->canceled) common::cl();
            }
        }
        if(!pd->canceled)
        {
            using std::cout;
            using std::endl;

            for(unsigned int x = 0; x < v_center::value; x++) cout<< endl;
            common::center("Paths Captured: " + std::to_string(pd->count));
            common::wait();
        }
    }

    void display_current_status(take_snapshot_proc_data *pd)
    {
        using std::cout;
        using std::endl;

        if(pd != nullptr)
        {
            //cur_pos I believe we're getting race conditions in the multi-threaded snapshot algorithm;
            /* It keeps displaying buffer overflows, so I think it's trying to display a string that's
             * being written to by the other thread. */
            cout<< "Press any key to cancel";
            for(unsigned int x = 0; x < 8; x++) cout<< endl;
            cout<< "root: \""<< pd->root<< "\""<< endl;
            cout<< "Paths saved: "<< pd->count<< endl;
            cout<< "Currently processing: \""<< pd->current_path<< "\""<< endl;
        }
        else ethrow("WTF, why is pd == nullptr?!?!");
    }

    /** Initializes all the data for the snapshot collection.  It opens a file
     * and saves the header to a "new" snapshot, and it should be used before
     * executing a new snapshot. */
    void construct_tsproc_data(take_snapshot_proc_data& pd, const std::string& rt)
    {
        snapshot::snapshot_data head;

        if(!fsys::is_folder(snapshot::snapshot_folder()))
        {
            if(!fsys::create_folder(snapshot::snapshot_folder()).value) return;
        }
        pd.root = rt;
        pd.sid = snapshot::new_snapshot_id();
        pd.save_file = (snapshot::snapshot_folder() + fsys::pref_slash() +
                        std::to_string(pd.sid) + fsyssnap_SNAPSHOT_FILE_EXTENSION);
        pd.canceled = false;
        pd.finished = false;
        pd.paused = false;
        pd.count = 0;
        pd.current_path = "";

        head.timestamp = tdata::current_time();
        head.root = pd.root;
        head.id = pd.sid;
        pd.out.open(pd.save_file.c_str(), std::ios::binary);
        snapshot::out_header(pd.out, head);
    }

}

/* stream operators: */
namespace snapshot
{
    std::ostream& operator<<(std::ostream& out, const snapshot_data& snap)
    {
        if(out.good())
        {
            out_header(out, snap);
            for(std::vector<std::string>::const_iterator it = snap.paths.begin();
                    it != snap.paths.end(); ++it)
            {
                out<< *it<< mem_delim::value;
            }
            out<< struct_delim::value;
        }
        return out;
    }

    /** Sets failbit only if it fails to retrieve the snapshot. */
    std::istream& operator>>(std::istream& in, snapshot_data& snap)
    {
        using common::safe_getline;

        std::string temps;

        snap = snapshot_data();

        //peek: this will establish that the stream is good.
        in.peek();

        if(in.good())
        {
            in_header(in, snap);
            while(in.good() && (in.peek() != struct_delim::value) && (in.peek() != EOF))
            {
                if(safe_getline(in, temps, mem_delim::value)) snap.paths.push_back(temps);
            }
            if(in.peek() == struct_delim::value)
            {
                in.get();

                /* Clear error state if we've reached the end of the file.
                 * the read was a success, so the stream satte should reflect that.*/
                if(in.peek() == EOF) in.clear();
            }
        }
        return in;
    }

    const snapshot_data& snapshot_data::operator=(const snapshot_data& snap)
    {
        if(this != &snap)
        {
            this->timestamp = snap.timestamp;
            this->root = snap.root;
            this->id = snap.id;

            this->paths.clear();
            this->paths.shrink_to_fit();
            this->paths = snap.paths;
        }
        return *this;
    }

    bool snapshot_data::operator==(const snapshot_data& snap) const
    {
        return (
                (this->id == snap.id) &&
                (this->timestamp == snap.timestamp) &&
                (this->root == snap.root) &&
                (this->paths == snap.paths));
    }

    bool snapshot_data::operator!=(const snapshot_data& snap) const
    {
        return !(this->operator==(snap));
    }

    /** Compares two snapshot's times.  provided for sorting algorithms. */
    bool snapshot_data::operator<(const snapshot_data& s) const
    {
        return (this->timestamp < s.timestamp);
    }

}

/* take_snapshot member functions: */
namespace snapshot
{
    unsigned long long take_snapshot(const std::string& s)
    {
        take_snapshot_proc_data *pd(new take_snapshot_proc_data);
        unsigned long long id(0);

        construct_tsproc_data(*pd, s);

        std::thread collect(collect_snapshot, pd), output(show_process_output, pd);

        collect.join();
        output.join();
        if(pd->out.is_open()) pd->out.close();
        if(pd->canceled)
        {
            if(fsys::is_file(pd->save_file).value &&
                            !fsys::is_symlink(pd->save_file).value)
            {
                if(fsys::can_delete(pd->save_file))
                {
                    fsys::fdelete(pd->save_file);
                    pd->sid = 0;
                }
            }
        }
        id = pd->sid;
        delete pd;
        return id;
    }

    std::ostream& out_header(std::ostream& out, const snapshot_data& snap)
    {
        char *ch(new char[sizeof(unsigned long long)]);

        if(out.good())
        {
            out<< snap.timestamp;
            memcpy(ch, &snap.id, sizeof(unsigned long long));
            for(unsigned int x = 0; x < sizeof(unsigned long long); x++) out<< ch[x];
            out<< snap.root<< mem_delim::value;
        }
        delete[] ch;
        return out;
    }

    std::istream& in_header(std::istream& in, snapshot_data& snap)
    {
        using common::safe_getline;

        char *ch(new char[sizeof(unsigned long long)]);

        in.peek();
        if(in.good())
        {
            in>> snap.timestamp;
            for(unsigned int x = 0; ((x < sizeof(unsigned long long)) && in.good()); x++)
            {
                if(in.peek() != EOF) ch[x] = in.get();
            }
            memcpy(&snap.id, ch, sizeof(unsigned long long));
            safe_getline(in, snap.root, mem_delim::value);
        }
        in.peek();
        return in;
    }

}

<|endoftext|>


<commit_before><commit_msg>Fix #96678#: Page style may change tthe layout direction<commit_after><|endoftext|>


<commit_before>#include "Types.hpp"

#include "InlineMethods.hpp"

PyObject * MGLContext_scope(MGLContext * self, PyObject * args) {
	MGLFramebuffer * framebuffer;
	PyObject * enable_flags;
	PyObject * textures;
	PyObject * uniform_buffers;
	PyObject * shader_storage_buffers;

	int args_ok = PyArg_ParseTuple(
		args,
		"O!OOOO",
		&MGLFramebuffer_Type,
		&framebuffer,
		&enable_flags,
		&textures,
		&uniform_buffers,
		&shader_storage_buffers
	);

	if (!args_ok) {
		return 0;
	}

	int flags = MGL_INVALID;
	if (enable_flags != Py_None) {
		flags = PyLong_AsLong(enable_flags);
		if (PyErr_Occurred()) {
			MGLError_Set("invalid enable_flags");
			return 0;
		}
	}

	MGLScope * scope = (MGLScope *)MGLScope_Type.tp_alloc(&MGLScope_Type, 0);

	Py_INCREF(self);
	scope->context = self;

	scope->enable_flags = flags;

	Py_INCREF(framebuffer);
	scope->framebuffer = framebuffer;

	Py_INCREF(self->bound_framebuffer);
	scope->old_framebuffer = self->bound_framebuffer;

	int num_textures = (int)PyTuple_Size(textures);
	int num_uniform_buffers = (int)PyTuple_Size(uniform_buffers);
	int num_shader_storage_buffers = (int)PyTuple_Size(shader_storage_buffers);

	scope->num_textures = num_textures;
	scope->textures = new int[scope->num_textures * 3];
	scope->num_buffers = num_uniform_buffers + num_shader_storage_buffers;
	scope->buffers = new int[scope->num_buffers * 3];

	for (int i = 0; i < num_textures; ++i) {
		PyObject * tup = PyTuple_GET_ITEM(textures, i);
		PyObject * item = PyTuple_GET_ITEM(tup, 0);

		int texture_type;
		int texture_obj;

		if (Py_TYPE(item) == &MGLTexture_Type) {
			MGLTexture * texture = (MGLTexture *)item;
			texture_type = texture->samples ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;
			texture_obj = texture->texture_obj;
		} else if (Py_TYPE(item) == &MGLTexture3D_Type) {
			MGLTexture3D * texture = (MGLTexture3D *)item;
			texture_type = GL_TEXTURE_3D;
			texture_obj = texture->texture_obj;
		} else if (Py_TYPE(item) == &MGLTextureCube_Type) {
			MGLTextureCube * texture = (MGLTextureCube *)item;
			texture_type = GL_TEXTURE_CUBE_MAP;
			texture_obj = texture->texture_obj;
		} else {
			MGLError_Set("invalid texture");
			return 0;
		}

		int binding = PyLong_AsLong(PyTuple_GET_ITEM(tup, 1));
		scope->textures[i * 3 + 0] = GL_TEXTURE0 + binding;
		scope->textures[i * 3 + 1] = texture_type;
		scope->textures[i * 3 + 2] = texture_obj;
	}

	for (int i = 0; i < num_uniform_buffers; ++i) {
		PyObject * tup = PyTuple_GET_ITEM(uniform_buffers, i);
		MGLBuffer * buffer = (MGLBuffer *)PyTuple_GET_ITEM(tup, 0);

		if (Py_TYPE(buffer) == &MGLBuffer_Type) {
			int binding = PyLong_AsLong(PyTuple_GET_ITEM(tup, 1));
			scope->buffers[i * 3 + 0] = GL_UNIFORM_BUFFER;
			scope->buffers[i * 3 + 1] = buffer->buffer_obj;
			scope->buffers[i * 3 + 2] = binding;
		} else {
			MGLError_Set("invalid buffer");
			return 0;
		}
	}

	int base = num_uniform_buffers * 3;

	for (int i = 0; i < num_shader_storage_buffers; ++i) {
		PyObject * tup = PyTuple_GET_ITEM(shader_storage_buffers, i);
		MGLBuffer * buffer = (MGLBuffer *)PyTuple_GET_ITEM(tup, 0);

		if (Py_TYPE(buffer) == &MGLBuffer_Type) {
			int binding = PyLong_AsLong(PyTuple_GET_ITEM(tup, 1));
			scope->buffers[base + i * 3 + 0] = GL_SHADER_STORAGE_BUFFER;
			scope->buffers[base + i * 3 + 1] = buffer->buffer_obj;
			scope->buffers[base + i * 3 + 2] = binding;
		} else {
			MGLError_Set("invalid buffer");
			return 0;
		}
	}

	return (PyObject *)scope;
}

PyObject * MGLScope_tp_new(PyTypeObject * type, PyObject * args, PyObject * kwargs) {
	MGLScope * self = (MGLScope *)type->tp_alloc(type, 0);

	if (self) {
		self->textures = 0;
		self->buffers = 0;
	}

	return (PyObject *)self;
}

void MGLScope_tp_dealloc(MGLScope * self) {
	MGLScope_Type.tp_free((PyObject *)self);
}

extern PyObject * MGLFramebuffer_use(MGLFramebuffer * self);

PyObject * MGLScope_begin(MGLScope * self, PyObject * args) {
	int args_ok = PyArg_ParseTuple(
		args,
		""
	);

	if (!args_ok) {
		return 0;
	}

	const GLMethods & gl = self->context->gl;
	const int & flags = self->enable_flags;

	MGLFramebuffer_use(self->framebuffer);

	for (int i = 0; i < self->num_textures; ++i) {
		gl.ActiveTexture(self->textures[i * 3]);
		gl.BindTexture(self->textures[i * 3 + 1], self->textures[i * 3 + 2]);
	}

	for (int i = 0; i < self->num_buffers; ++i) {
		gl.BindBufferBase(self->buffers[i * 3], self->buffers[i * 3 + 1], self->buffers[i * 3 + 2]);
	}

	if (flags & MGL_BLEND) {
		gl.Enable(GL_BLEND);
	} else {
		gl.Disable(GL_BLEND);
	}

	if (flags & MGL_DEPTH_TEST) {
		gl.Enable(GL_DEPTH_TEST);
	} else {
		gl.Disable(GL_DEPTH_TEST);
	}

	if (flags & MGL_CULL_FACE) {
		gl.Enable(GL_CULL_FACE);
	} else {
		gl.Disable(GL_CULL_FACE);
	}

	if (flags & MGL_RASTERIZER_DISCARD) {
		gl.Enable(GL_RASTERIZER_DISCARD);
	} else {
		gl.Disable(GL_RASTERIZER_DISCARD);
	}

	Py_RETURN_NONE;
}

PyObject * MGLScope_end(MGLScope * self, PyObject * args) {
	int args_ok = PyArg_ParseTuple(
		args,
		""
	);

	if (!args_ok) {
		return 0;
	}

	const GLMethods & gl = self->context->gl;
	const int & flags = self->old_enable_flags;

	MGLFramebuffer_use(self->old_framebuffer);

	if (flags & MGL_BLEND) {
		gl.Enable(GL_BLEND);
	} else {
		gl.Disable(GL_BLEND);
	}

	if (flags & MGL_DEPTH_TEST) {
		gl.Enable(GL_DEPTH_TEST);
	} else {
		gl.Disable(GL_DEPTH_TEST);
	}

	if (flags & MGL_CULL_FACE) {
		gl.Enable(GL_CULL_FACE);
	} else {
		gl.Disable(GL_CULL_FACE);
	}

	if (flags & MGL_RASTERIZER_DISCARD) {
		gl.Enable(GL_RASTERIZER_DISCARD);
	} else {
		gl.Disable(GL_RASTERIZER_DISCARD);
	}

	Py_RETURN_NONE;
}

PyMethodDef MGLScope_tp_methods[] = {
	{"begin", (PyCFunction)MGLScope_begin, METH_VARARGS, 0},
	{"end", (PyCFunction)MGLScope_end, METH_VARARGS, 0},
	// {"release", (PyCFunction)MGLScope_release, METH_NOARGS, 0},
	{0},
};

PyGetSetDef MGLScope_tp_getseters[] = {
	{0},
};

PyTypeObject MGLScope_Type = {
	PyVarObject_HEAD_INIT(0, 0)
	"mgl.Scope",                                            // tp_name
	sizeof(MGLScope),                                       // tp_basicsize
	0,                                                      // tp_itemsize
	(destructor)MGLScope_tp_dealloc,                        // tp_dealloc
	0,                                                      // tp_print
	0,                                                      // tp_getattr
	0,                                                      // tp_setattr
	0,                                                      // tp_reserved
	0,                                                      // tp_repr
	0,                                                      // tp_as_number
	0,                                                      // tp_as_sequence
	0,                                                      // tp_as_mapping
	0,                                                      // tp_hash
	0,                                                      // tp_call
	0,                                                      // tp_str
	0,                                                      // tp_getattro
	0,                                                      // tp_setattro
	0,                                                      // tp_as_buffer
	Py_TPFLAGS_DEFAULT,                                     // tp_flags
	0,                                                      // tp_doc
	0,                                                      // tp_traverse
	0,                                                      // tp_clear
	0,                                                      // tp_richcompare
	0,                                                      // tp_weaklistoffset
	0,                                                      // tp_iter
	0,                                                      // tp_iternext
	MGLScope_tp_methods,                                    // tp_methods
	0,                                                      // tp_members
	MGLScope_tp_getseters,                                  // tp_getset
	0,                                                      // tp_base
	0,                                                      // tp_dict
	0,                                                      // tp_descr_get
	0,                                                      // tp_descr_set
	0,                                                      // tp_dictoffset
	0,                                                      // tp_init
	0,                                                      // tp_alloc
	MGLScope_tp_new,                                        // tp_new
};

void MGLScope_Invalidate(MGLScope * scope) {
	if (Py_TYPE(scope) == &MGLInvalidObject_Type) {
		return;
	}

	// TODO: decref

	// const GLMethods & gl = scope->context->gl;

	// TODO: release

	Py_DECREF(scope->context);
	Py_TYPE(scope) = &MGLInvalidObject_Type;
	Py_DECREF(scope);
}
<commit_msg>Properly handle flags when enter/exit scope<commit_after>#include "Types.hpp"

#include "InlineMethods.hpp"

PyObject * MGLContext_scope(MGLContext * self, PyObject * args) {
	MGLFramebuffer * framebuffer;
	PyObject * enable_flags;
	PyObject * textures;
	PyObject * uniform_buffers;
	PyObject * shader_storage_buffers;

	int args_ok = PyArg_ParseTuple(
		args,
		"O!OOOO",
		&MGLFramebuffer_Type,
		&framebuffer,
		&enable_flags,
		&textures,
		&uniform_buffers,
		&shader_storage_buffers
	);

	if (!args_ok) {
		return 0;
	}

	int flags = MGL_INVALID;
	if (enable_flags != Py_None) {
		flags = PyLong_AsLong(enable_flags);
		if (PyErr_Occurred()) {
			MGLError_Set("invalid enable_flags");
			return 0;
		}
	}

	MGLScope * scope = (MGLScope *)MGLScope_Type.tp_alloc(&MGLScope_Type, 0);

	Py_INCREF(self);
	scope->context = self;

	scope->enable_flags = flags;

	Py_INCREF(framebuffer);
	scope->framebuffer = framebuffer;

	Py_INCREF(self->bound_framebuffer);
	scope->old_framebuffer = self->bound_framebuffer;

	int num_textures = (int)PyTuple_Size(textures);
	int num_uniform_buffers = (int)PyTuple_Size(uniform_buffers);
	int num_shader_storage_buffers = (int)PyTuple_Size(shader_storage_buffers);

	scope->num_textures = num_textures;
	scope->textures = new int[scope->num_textures * 3];
	scope->num_buffers = num_uniform_buffers + num_shader_storage_buffers;
	scope->buffers = new int[scope->num_buffers * 3];

	for (int i = 0; i < num_textures; ++i) {
		PyObject * tup = PyTuple_GET_ITEM(textures, i);
		PyObject * item = PyTuple_GET_ITEM(tup, 0);

		int texture_type;
		int texture_obj;

		if (Py_TYPE(item) == &MGLTexture_Type) {
			MGLTexture * texture = (MGLTexture *)item;
			texture_type = texture->samples ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;
			texture_obj = texture->texture_obj;
		} else if (Py_TYPE(item) == &MGLTexture3D_Type) {
			MGLTexture3D * texture = (MGLTexture3D *)item;
			texture_type = GL_TEXTURE_3D;
			texture_obj = texture->texture_obj;
		} else if (Py_TYPE(item) == &MGLTextureCube_Type) {
			MGLTextureCube * texture = (MGLTextureCube *)item;
			texture_type = GL_TEXTURE_CUBE_MAP;
			texture_obj = texture->texture_obj;
		} else {
			MGLError_Set("invalid texture");
			return 0;
		}

		int binding = PyLong_AsLong(PyTuple_GET_ITEM(tup, 1));
		scope->textures[i * 3 + 0] = GL_TEXTURE0 + binding;
		scope->textures[i * 3 + 1] = texture_type;
		scope->textures[i * 3 + 2] = texture_obj;
	}

	for (int i = 0; i < num_uniform_buffers; ++i) {
		PyObject * tup = PyTuple_GET_ITEM(uniform_buffers, i);
		MGLBuffer * buffer = (MGLBuffer *)PyTuple_GET_ITEM(tup, 0);

		if (Py_TYPE(buffer) == &MGLBuffer_Type) {
			int binding = PyLong_AsLong(PyTuple_GET_ITEM(tup, 1));
			scope->buffers[i * 3 + 0] = GL_UNIFORM_BUFFER;
			scope->buffers[i * 3 + 1] = buffer->buffer_obj;
			scope->buffers[i * 3 + 2] = binding;
		} else {
			MGLError_Set("invalid buffer");
			return 0;
		}
	}

	int base = num_uniform_buffers * 3;

	for (int i = 0; i < num_shader_storage_buffers; ++i) {
		PyObject * tup = PyTuple_GET_ITEM(shader_storage_buffers, i);
		MGLBuffer * buffer = (MGLBuffer *)PyTuple_GET_ITEM(tup, 0);

		if (Py_TYPE(buffer) == &MGLBuffer_Type) {
			int binding = PyLong_AsLong(PyTuple_GET_ITEM(tup, 1));
			scope->buffers[base + i * 3 + 0] = GL_SHADER_STORAGE_BUFFER;
			scope->buffers[base + i * 3 + 1] = buffer->buffer_obj;
			scope->buffers[base + i * 3 + 2] = binding;
		} else {
			MGLError_Set("invalid buffer");
			return 0;
		}
	}

	return (PyObject *)scope;
}

PyObject * MGLScope_tp_new(PyTypeObject * type, PyObject * args, PyObject * kwargs) {
	MGLScope * self = (MGLScope *)type->tp_alloc(type, 0);

	if (self) {
		self->textures = 0;
		self->buffers = 0;
	}

	return (PyObject *)self;
}

void MGLScope_tp_dealloc(MGLScope * self) {
	MGLScope_Type.tp_free((PyObject *)self);
}

extern PyObject * MGLFramebuffer_use(MGLFramebuffer * self);

PyObject * MGLScope_begin(MGLScope * self, PyObject * args) {
	int args_ok = PyArg_ParseTuple(
		args,
		""
	);

	if (!args_ok) {
		return 0;
	}

	const GLMethods & gl = self->context->gl;
	const int & flags = self->enable_flags;

	self->old_enable_flags = self->context->enable_flags;
	self->context->enable_flags = self->enable_flags;

	MGLFramebuffer_use(self->framebuffer);

	for (int i = 0; i < self->num_textures; ++i) {
		gl.ActiveTexture(self->textures[i * 3]);
		gl.BindTexture(self->textures[i * 3 + 1], self->textures[i * 3 + 2]);
	}

	for (int i = 0; i < self->num_buffers; ++i) {
		gl.BindBufferBase(self->buffers[i * 3], self->buffers[i * 3 + 1], self->buffers[i * 3 + 2]);
	}

	if (flags & MGL_BLEND) {
		gl.Enable(GL_BLEND);
	} else {
		gl.Disable(GL_BLEND);
	}

	if (flags & MGL_DEPTH_TEST) {
		gl.Enable(GL_DEPTH_TEST);
	} else {
		gl.Disable(GL_DEPTH_TEST);
	}

	if (flags & MGL_CULL_FACE) {
		gl.Enable(GL_CULL_FACE);
	} else {
		gl.Disable(GL_CULL_FACE);
	}

	if (flags & MGL_RASTERIZER_DISCARD) {
		gl.Enable(GL_RASTERIZER_DISCARD);
	} else {
		gl.Disable(GL_RASTERIZER_DISCARD);
	}

	Py_RETURN_NONE;
}

PyObject * MGLScope_end(MGLScope * self, PyObject * args) {
	int args_ok = PyArg_ParseTuple(
		args,
		""
	);

	if (!args_ok) {
		return 0;
	}

	const GLMethods & gl = self->context->gl;
	const int & flags = self->old_enable_flags;

	MGLFramebuffer_use(self->old_framebuffer);

	if (flags & MGL_BLEND) {
		gl.Enable(GL_BLEND);
	} else {
		gl.Disable(GL_BLEND);
	}

	if (flags & MGL_DEPTH_TEST) {
		gl.Enable(GL_DEPTH_TEST);
	} else {
		gl.Disable(GL_DEPTH_TEST);
	}

	if (flags & MGL_CULL_FACE) {
		gl.Enable(GL_CULL_FACE);
	} else {
		gl.Disable(GL_CULL_FACE);
	}

	if (flags & MGL_RASTERIZER_DISCARD) {
		gl.Enable(GL_RASTERIZER_DISCARD);
	} else {
		gl.Disable(GL_RASTERIZER_DISCARD);
	}

	Py_RETURN_NONE;
}

PyMethodDef MGLScope_tp_methods[] = {
	{"begin", (PyCFunction)MGLScope_begin, METH_VARARGS, 0},
	{"end", (PyCFunction)MGLScope_end, METH_VARARGS, 0},
	// {"release", (PyCFunction)MGLScope_release, METH_NOARGS, 0},
	{0},
};

PyGetSetDef MGLScope_tp_getseters[] = {
	{0},
};

PyTypeObject MGLScope_Type = {
	PyVarObject_HEAD_INIT(0, 0)
	"mgl.Scope",                                            // tp_name
	sizeof(MGLScope),                                       // tp_basicsize
	0,                                                      // tp_itemsize
	(destructor)MGLScope_tp_dealloc,                        // tp_dealloc
	0,                                                      // tp_print
	0,                                                      // tp_getattr
	0,                                                      // tp_setattr
	0,                                                      // tp_reserved
	0,                                                      // tp_repr
	0,                                                      // tp_as_number
	0,                                                      // tp_as_sequence
	0,                                                      // tp_as_mapping
	0,                                                      // tp_hash
	0,                                                      // tp_call
	0,                                                      // tp_str
	0,                                                      // tp_getattro
	0,                                                      // tp_setattro
	0,                                                      // tp_as_buffer
	Py_TPFLAGS_DEFAULT,                                     // tp_flags
	0,                                                      // tp_doc
	0,                                                      // tp_traverse
	0,                                                      // tp_clear
	0,                                                      // tp_richcompare
	0,                                                      // tp_weaklistoffset
	0,                                                      // tp_iter
	0,                                                      // tp_iternext
	MGLScope_tp_methods,                                    // tp_methods
	0,                                                      // tp_members
	MGLScope_tp_getseters,                                  // tp_getset
	0,                                                      // tp_base
	0,                                                      // tp_dict
	0,                                                      // tp_descr_get
	0,                                                      // tp_descr_set
	0,                                                      // tp_dictoffset
	0,                                                      // tp_init
	0,                                                      // tp_alloc
	MGLScope_tp_new,                                        // tp_new
};

void MGLScope_Invalidate(MGLScope * scope) {
	if (Py_TYPE(scope) == &MGLInvalidObject_Type) {
		return;
	}

	// TODO: decref

	// const GLMethods & gl = scope->context->gl;

	// TODO: release

	Py_DECREF(scope->context);
	Py_TYPE(scope) = &MGLInvalidObject_Type;
	Py_DECREF(scope);
}
<|endoftext|>


<commit_before>/*
 * TriDirectionalLighting.cpp
 * Copyright (C) 2009-2017 by MegaMol Team
 * Alle Rechte vorbehalten.
 */

#include "stdafx.h"
#include "mmcore/view/light/TriDirectionalLighting.h"
#include "glm/glm.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/ColorParam.h"
#include "mmcore/param/FloatParam.h"
#include "mmcore/param/Vector3fParam.h"

using namespace megamol::core::view::light;

/*
 * megamol::core::view::light::DistantLight::DistantLight
 */
TriDirectionalLighting::TriDirectionalLighting(void)
        : AbstractLight()
        , m_key_direction("KeyDirection", "Direction of the key light")
        , m_fill_direction("FillDirection", "Direction of the fill light")
        , m_back_direction("BackDirection", "Direction of the back light")
        , m_in_view_space("InViewSpace", "Locks the light directions to the camera") {

    // distant light
    this->m_key_direction << new core::param::Vector3fParam(vislib::math::Vector<float, 3>(-0.2f, -0.2f, 1.0f));
    this->m_fill_direction << new core::param::Vector3fParam(vislib::math::Vector<float, 3>(1.0f, 0.0f, 0.0f));
    this->m_back_direction << new core::param::Vector3fParam(vislib::math::Vector<float, 3>(0.0f, 0.0f, -1.0f));
    this->m_in_view_space << new core::param::BoolParam(1);
    this->MakeSlotAvailable(&this->m_key_direction);
    this->MakeSlotAvailable(&this->m_fill_direction);
    this->MakeSlotAvailable(&this->m_back_direction);
    this->MakeSlotAvailable(&this->m_in_view_space);

    this->m_key_direction.Parameter()->SetGUIPresentation(
        core::param::AbstractParamPresentation::Presentation::Rotation3D_Direction);
    this->m_fill_direction.Parameter()->SetGUIPresentation(
        core::param::AbstractParamPresentation::Presentation::Rotation3D_Direction);
    this->m_back_direction.Parameter()->SetGUIPresentation(
        core::param::AbstractParamPresentation::Presentation::Rotation3D_Direction);
}

/*
 * megamol::core::view::light::DistantLight::~DistantLight
 */
TriDirectionalLighting::~TriDirectionalLighting(void) {
    this->Release();
}

/*
 * megamol::core::view::light::DistantLight::readParams
 */
void TriDirectionalLighting::readParams() {
    // Read basic light parameters
    lightContainer.lightType = lightenum::TRIDIRECTIONALLIGHTING;
    lightContainer.lightColor = this->lightColor.Param<core::param::ColorParam>()->Value();
    lightContainer.lightIntensity = this->lightIntensity.Param<core::param::FloatParam>()->Value();

    // Read tri-directional lighting parameters
    lightContainer.tdl_in_view_space = this->m_in_view_space.Param<core::param::BoolParam>()->Value();

    auto& key_dir = this->m_key_direction.Param<core::param::Vector3fParam>()->Value();
    glm::vec3 key_dir_normalized(key_dir.X(), key_dir.Y(), key_dir.Z());
    key_dir_normalized = glm::normalize(key_dir_normalized);
    std::copy(glm::value_ptr(key_dir_normalized), glm::value_ptr(key_dir_normalized) + 3,
        lightContainer.tdl_key_direction.begin());

    auto& fill_dir = this->m_fill_direction.Param<core::param::Vector3fParam>()->Value();
    glm::vec3 fill_dir_normalized(fill_dir.X(), fill_dir.Y(), fill_dir.Z());
    fill_dir_normalized = glm::normalize(fill_dir_normalized);
    std::copy(glm::value_ptr(fill_dir_normalized), glm::value_ptr(fill_dir_normalized) + 3,
        lightContainer.tdl_fill_direction.begin());

    auto& back_dir = this->m_back_direction.Param<core::param::Vector3fParam>()->Value();
    glm::vec3 back_dir_normalized(back_dir.X(), back_dir.Y(), back_dir.Z());
    back_dir_normalized = glm::normalize(back_dir_normalized);
    std::copy(glm::value_ptr(back_dir_normalized), glm::value_ptr(back_dir_normalized) + 3,
        lightContainer.tdl_back_direction.begin());
}

/*
 * megamol::core::view::light::DistantLight::InterfaceIsDirty
 */
bool TriDirectionalLighting::InterfaceIsDirty() {
    if (this->AbstractIsDirty() || this->m_key_direction.IsDirty() || this->m_fill_direction.IsDirty() ||
        this->m_back_direction.IsDirty() || this->m_in_view_space.IsDirty()) {
        this->m_key_direction.ResetDirty();
        this->m_fill_direction.ResetDirty();
        this->m_back_direction.ResetDirty();
        this->m_in_view_space.ResetDirty();
        return true;
    } else {
        return false;
    }
}
<commit_msg>Update TriDirectionalLighting.cpp<commit_after>/*
 * TriDirectionalLighting.cpp
 * Copyright (C) 2009-2017 by MegaMol Team
 * Alle Rechte vorbehalten.
 */

#include "stdafx.h"
#include "mmcore/view/light/TriDirectionalLighting.h"
#include "glm/glm.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/ColorParam.h"
#include "mmcore/param/FloatParam.h"
#include "mmcore/param/Vector3fParam.h"

using namespace megamol::core::view::light;

/*
 * megamol::core::view::light::DistantLight::DistantLight
 */
TriDirectionalLighting::TriDirectionalLighting(void)
        : AbstractLight()
        , m_key_direction("KeyDirection", "Direction of the key light")
        , m_fill_direction("FillDirection", "Direction of the fill light")
        , m_back_direction("BackDirection", "Direction of the back light")
        , m_in_view_space("InViewSpace", "Locks the light directions to the camera") {

    // distant light
    this->m_key_direction << new core::param::Vector3fParam(vislib::math::Vector<float, 3>(-0.2f, -0.2f, 1.0f));
    this->m_fill_direction << new core::param::Vector3fParam(vislib::math::Vector<float, 3>(1.0f, 0.0f, 0.0f));
    this->m_back_direction << new core::param::Vector3fParam(vislib::math::Vector<float, 3>(0.0f, 0.0f, -1.0f));
    this->m_in_view_space << new core::param::BoolParam(1);
    this->MakeSlotAvailable(&this->m_key_direction);
    this->MakeSlotAvailable(&this->m_fill_direction);
    this->MakeSlotAvailable(&this->m_back_direction);
    this->MakeSlotAvailable(&this->m_in_view_space);

    this->m_key_direction.Parameter()->SetGUIPresentation(
        core::param::AbstractParamPresentation::Presentation::Rotation);
    this->m_fill_direction.Parameter()->SetGUIPresentation(
        core::param::AbstractParamPresentation::Presentation::Rotation);
    this->m_back_direction.Parameter()->SetGUIPresentation(
        core::param::AbstractParamPresentation::Presentation::Rotation);
}

/*
 * megamol::core::view::light::DistantLight::~DistantLight
 */
TriDirectionalLighting::~TriDirectionalLighting(void) {
    this->Release();
}

/*
 * megamol::core::view::light::DistantLight::readParams
 */
void TriDirectionalLighting::readParams() {
    // Read basic light parameters
    lightContainer.lightType = lightenum::TRIDIRECTIONALLIGHTING;
    lightContainer.lightColor = this->lightColor.Param<core::param::ColorParam>()->Value();
    lightContainer.lightIntensity = this->lightIntensity.Param<core::param::FloatParam>()->Value();

    // Read tri-directional lighting parameters
    lightContainer.tdl_in_view_space = this->m_in_view_space.Param<core::param::BoolParam>()->Value();

    auto& key_dir = this->m_key_direction.Param<core::param::Vector3fParam>()->Value();
    glm::vec3 key_dir_normalized(key_dir.X(), key_dir.Y(), key_dir.Z());
    key_dir_normalized = glm::normalize(key_dir_normalized);
    std::copy(glm::value_ptr(key_dir_normalized), glm::value_ptr(key_dir_normalized) + 3,
        lightContainer.tdl_key_direction.begin());

    auto& fill_dir = this->m_fill_direction.Param<core::param::Vector3fParam>()->Value();
    glm::vec3 fill_dir_normalized(fill_dir.X(), fill_dir.Y(), fill_dir.Z());
    fill_dir_normalized = glm::normalize(fill_dir_normalized);
    std::copy(glm::value_ptr(fill_dir_normalized), glm::value_ptr(fill_dir_normalized) + 3,
        lightContainer.tdl_fill_direction.begin());

    auto& back_dir = this->m_back_direction.Param<core::param::Vector3fParam>()->Value();
    glm::vec3 back_dir_normalized(back_dir.X(), back_dir.Y(), back_dir.Z());
    back_dir_normalized = glm::normalize(back_dir_normalized);
    std::copy(glm::value_ptr(back_dir_normalized), glm::value_ptr(back_dir_normalized) + 3,
        lightContainer.tdl_back_direction.begin());
}

/*
 * megamol::core::view::light::DistantLight::InterfaceIsDirty
 */
bool TriDirectionalLighting::InterfaceIsDirty() {
    if (this->AbstractIsDirty() || this->m_key_direction.IsDirty() || this->m_fill_direction.IsDirty() ||
        this->m_back_direction.IsDirty() || this->m_in_view_space.IsDirty()) {
        this->m_key_direction.ResetDirty();
        this->m_fill_direction.ResetDirty();
        this->m_back_direction.ResetDirty();
        this->m_in_view_space.ResetDirty();
        return true;
    } else {
        return false;
    }
}
<|endoftext|>


<commit_before>//===--- llvmc.cpp - The LLVM Compiler Driver -------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This tool provides a single point of access to the LLVM compilation tools.
//  It has many options. To discover the options supported please refer to the
//  tools' manual page (docs/CommandGuide/html/llvmc.html) or run the tool with
//  the --help option.
//
//===------------------------------------------------------------------------===

#include "CompilerDriver.h"
#include "Configuration.h"
#include "llvm/Pass.h"
#include "llvm/System/Signals.h"
#include "llvm/Support/CommandLine.h"
#include <iostream>

using namespace llvm;

namespace {
//===------------------------------------------------------------------------===
//===          PHASE OPTIONS
//===------------------------------------------------------------------------===
cl::opt<CompilerDriver::Phases> FinalPhase(cl::Optional,
  cl::desc("Choose final phase of compilation:"),
  cl::init(CompilerDriver::LINKING),
  cl::values(
    clEnumValN(CompilerDriver::PREPROCESSING,"E",
      "Stop compilation after pre-processing phase"),
    clEnumValN(CompilerDriver::TRANSLATION, "t",
      "Stop compilation after translation phase"),
    clEnumValN(CompilerDriver::OPTIMIZATION,"c",
      "Stop compilation after optimization phase"),
    clEnumValN(CompilerDriver::ASSEMBLY,"S",
      "Stop compilation after assembly phase"),
    clEnumValEnd
  )
);

//===------------------------------------------------------------------------===
//===          OPTIMIZATION OPTIONS
//===------------------------------------------------------------------------===
cl::opt<CompilerDriver::OptimizationLevels> OptLevel(cl::ZeroOrMore,
  cl::desc("Choose level of optimization to apply:"),
  cl::init(CompilerDriver::OPT_FAST_COMPILE),
  cl::values(
    clEnumValN(CompilerDriver::OPT_FAST_COMPILE,"O0",
      "An alias for the -O1 option"),
    clEnumValN(CompilerDriver::OPT_FAST_COMPILE,"O1",
      "Optimize for compilation speed, not execution speed"),
    clEnumValN(CompilerDriver::OPT_SIMPLE,"O2",
      "Perform simple translation time optimizations"),
    clEnumValN(CompilerDriver::OPT_AGGRESSIVE,"O3",
      "Perform aggressive translation time optimizations"),
    clEnumValN(CompilerDriver::OPT_LINK_TIME,"O4",
      "Perform link time optimizations"),
    clEnumValN(CompilerDriver::OPT_AGGRESSIVE_LINK_TIME,"O5",
      "Perform aggressive link time optimizations"),
    clEnumValEnd
  )
);

//===------------------------------------------------------------------------===
//===          TOOL OPTIONS
//===------------------------------------------------------------------------===

cl::list<std::string> PreprocessorToolOpts("Tpre", cl::ZeroOrMore,
  cl::desc("Pass specific options to the pre-processor"),
  cl::value_desc("option"));

cl::alias PreprocessorToolOptsAlias("Wp,", cl::ZeroOrMore,
  cl::desc("Alias for -Tpre"), cl::aliasopt(PreprocessorToolOpts));

cl::list<std::string> TranslatorToolOpts("Ttrn", cl::ZeroOrMore,
  cl::desc("Pass specific options to the assembler"),
  cl::value_desc("option"));

cl::list<std::string> AssemblerToolOpts("Tasm", cl::ZeroOrMore,
  cl::desc("Pass specific options to the assembler"),
  cl::value_desc("option"));

cl::alias AssemblerToolOptsAlias("Wa,", cl::ZeroOrMore,
  cl::desc("Alias for -Tasm"), cl::aliasopt(AssemblerToolOpts));

cl::list<std::string> OptimizerToolOpts("Topt", cl::ZeroOrMore,
  cl::desc("Pass specific options to the optimizer"),
  cl::value_desc("option"));

cl::list<std::string> LinkerToolOpts("Tlnk", cl::ZeroOrMore,
  cl::desc("Pass specific options to the linker"),
  cl::value_desc("option"));

cl::alias LinkerToolOptsAlias("Wl,", cl::ZeroOrMore,
  cl::desc("Alias for -Tlnk"), cl::aliasopt(LinkerToolOpts));

cl::list<std::string> fOpts("f", cl::ZeroOrMore, cl::Prefix,
  cl::desc("Pass through -f options to compiler tools"),
  cl::value_desc("option"));

cl::list<std::string> MOpts("M", cl::ZeroOrMore, cl::Prefix,
  cl::desc("Pass through -M options to compiler tools"),
  cl::value_desc("option"));

cl::list<std::string> WOpts("W", cl::ZeroOrMore, cl::Prefix,
  cl::desc("Pass through -W options to compiler tools"),
  cl::value_desc("option"));

cl::list<std::string> BOpt("B", cl::ZeroOrMore, cl::Prefix,
  cl::desc("Specify path to find llvmc sub-tools"),
  cl::value_desc("dir"));

//===------------------------------------------------------------------------===
//===          INPUT OPTIONS
//===------------------------------------------------------------------------===

cl::list<std::string> LibPaths("L", cl::Prefix,
  cl::desc("Specify a library search path"), cl::value_desc("dir"));

cl::list<std::string> Libraries("l", cl::Prefix,
  cl::desc("Specify base name of libraries to link to"), cl::value_desc("lib"));

cl::list<std::string> Includes("I", cl::Prefix,
  cl::desc("Specify location to search for included source"),
  cl::value_desc("dir"));

cl::list<std::string> Defines("D", cl::Prefix,
  cl::desc("Specify a pre-processor symbol to define"),
  cl::value_desc("symbol"));

//===------------------------------------------------------------------------===
//===          OUTPUT OPTIONS
//===------------------------------------------------------------------------===

cl::opt<std::string> OutputFilename("o",
  cl::desc("Override output filename"), cl::value_desc("file"));

cl::opt<std::string> OutputMachine("m", cl::Prefix,
  cl::desc("Specify a target machine"), cl::value_desc("machine"));

cl::opt<bool> Native("native", cl::init(false),
  cl::desc("Generative native code instead of bytecode"));

cl::opt<bool> DebugOutput("g", cl::init(false),
  cl::desc("Generate objects that include debug symbols"));

cl::opt<bool> StripOutput("strip", cl::init(false),
  cl::desc("Strip all symbols from linked output file"));

cl::opt<std::string> PrintFileName("print-fname", cl::Optional,
  cl::value_desc("file"),
  cl::desc("Print the full path for the option's value"));

//===------------------------------------------------------------------------===
//===          INFORMATION OPTIONS
//===------------------------------------------------------------------------===

cl::opt<bool> DryRun("dry-run", cl::Optional, cl::init(false),
  cl::desc("Do everything but perform the compilation actions"));

cl::alias DryRunAlias("y", cl::Optional,
  cl::desc("Alias for -dry-run"), cl::aliasopt(DryRun));

cl::opt<bool> Verbose("verbose", cl::Optional, cl::init(false),
  cl::desc("Print out each action taken"));

cl::alias VerboseAlias("v", cl::Optional,
  cl::desc("Alias for -verbose"), cl::aliasopt(Verbose));

cl::opt<bool> Debug("debug", cl::Optional, cl::init(false),
  cl::Hidden, cl::desc("Print out debugging information"));

cl::alias DebugAlias("d", cl::Optional,
  cl::desc("Alias for -debug"), cl::aliasopt(Debug));

cl::opt<bool> TimeActions("time-actions", cl::Optional, cl::init(false),
  cl::desc("Print execution time for each action taken"));

cl::opt<bool> ShowStats("stats", cl::Optional, cl::init(false),
  cl::desc("Print statistics accumulated during optimization"));

//===------------------------------------------------------------------------===
//===          ADVANCED OPTIONS
//===------------------------------------------------------------------------===

static cl::opt<std::string> ConfigDir("config-dir", cl::Optional,
  cl::desc("Specify configuration directory to override defaults"),
  cl::value_desc("dir"));

static cl::opt<bool> EmitRawCode("emit-raw-code", cl::Hidden, cl::Optional,
  cl::desc("Emit raw, unoptimized code"));

static cl::opt<bool> PipeCommands("pipe", cl::Optional,
  cl::desc("Invoke sub-commands by linking input/output with pipes"));

static cl::opt<bool> KeepTemps("keep-temps", cl::Optional,
  cl::desc("Don't delete temporary files created by llvmc"));

//===------------------------------------------------------------------------===
//===          POSITIONAL OPTIONS
//===------------------------------------------------------------------------===

static cl::list<std::string> Files(cl::Positional, cl::ZeroOrMore,
  cl::desc("[Sources/objects/libraries]"));

static cl::list<std::string> Languages("x", cl::ZeroOrMore,
  cl::desc("Specify the source language for subsequent files"),
  cl::value_desc("language"));

//===------------------------------------------------------------------------===
//===          GetFileType - determine type of a file
//===------------------------------------------------------------------------===
const std::string GetFileType(const std::string& fname, unsigned pos ) {
  static std::vector<std::string>::iterator langIt = Languages.begin();
  static std::string CurrLang = "";

  // If a -x LANG option has been specified ..
  if ( langIt != Languages.end() )
    // If the -x LANG option came before the current file on command line
    if ( Languages.getPosition( langIt - Languages.begin() ) < pos ) {
      // use that language
      CurrLang = *langIt++;
      return CurrLang;
    }

  // If there's a current language in effect
  if (!CurrLang.empty())
    return CurrLang; // use that language

  // otherwise just determine lang from the filename's suffix
  return fname.substr( fname.rfind('.',fname.size()) + 1 );
}

} // end anonymous namespace

void handleTerminatingOptions(CompilerDriver* CD) {
  if (!PrintFileName.empty()) {
    sys::Path path = CD->GetPathForLinkageItem(PrintFileName,false);
    std::string p = path.toString();
    if (p.empty())
      std::cout << "Can't locate '" << PrintFileName << "'.\n";
    else
      std::cout << p << "\n";
    exit(0);
  }
}

/// @brief The main program for llvmc
int main(int argc, char **argv) {
  // Make sure we print stack trace if we get bad signals
  sys::PrintStackTraceOnErrorSignal();

  try {

    // Parse the command line options
    cl::ParseCommandLineOptions(argc, argv,
      " LLVM Compiler Driver (llvmc)\n\n"
      "  This program provides easy invocation of the LLVM tool set\n"
      "  and other compiler tools.\n"
    );

    // Deal with unimplemented options.
    if (PipeCommands)
      throw std::string("Not implemented yet: -pipe");

    if (OutputFilename.empty())
      if (OptLevel == CompilerDriver::LINKING)
        OutputFilename = "a.out";

    // Construct the ConfigDataProvider object
    LLVMC_ConfigDataProvider Provider;
    Provider.setConfigDir(sys::Path(ConfigDir));

    // Construct the CompilerDriver object
    CompilerDriver* CD = CompilerDriver::Get(Provider);

    // If the LLVM_LIB_SEARCH_PATH environment variable is
    // set, append it to the list of places to search for libraries
    char *srchPath = getenv("LLVM_LIB_SEARCH_PATH");
    if (srchPath != NULL && strlen(srchPath) != 0)
      LibPaths.push_back(std::string(srchPath));

    // Set the driver flags based on command line options
    unsigned flags = 0;
    if (Verbose)        flags |= CompilerDriver::VERBOSE_FLAG;
    if (Debug)          flags |= CompilerDriver::DEBUG_FLAG;
    if (DryRun)         flags |= CompilerDriver::DRY_RUN_FLAG;
    if (Native)         flags |= CompilerDriver::EMIT_NATIVE_FLAG;
    if (EmitRawCode)    flags |= CompilerDriver::EMIT_RAW_FLAG;
    if (KeepTemps)      flags |= CompilerDriver::KEEP_TEMPS_FLAG;
    if (ShowStats)      flags |= CompilerDriver::SHOW_STATS_FLAG;
    if (TimeActions)    flags |= CompilerDriver::TIME_ACTIONS_FLAG;
    if (TimePassesIsEnabled) flags |= CompilerDriver::TIME_PASSES_FLAG;
    if (StripOutput)    flags |= CompilerDriver::STRIP_OUTPUT_FLAG;
    CD->setDriverFlags(flags);

    // Specify requred parameters
    CD->setFinalPhase(FinalPhase);
    CD->setOptimization(OptLevel);
    CD->setOutputMachine(OutputMachine);
    CD->setIncludePaths(Includes);
    CD->setSymbolDefines(Defines);
    CD->setLibraryPaths(LibPaths);
    CD->setfPassThrough(fOpts);
    CD->setMPassThrough(MOpts);
    CD->setWPassThrough(WOpts);

    // Provide additional tool arguments
    if (!PreprocessorToolOpts.empty())
        CD->setPhaseArgs(CompilerDriver::PREPROCESSING, PreprocessorToolOpts);
    if (!TranslatorToolOpts.empty())
        CD->setPhaseArgs(CompilerDriver::TRANSLATION, TranslatorToolOpts);
    if (!OptimizerToolOpts.empty())
        CD->setPhaseArgs(CompilerDriver::OPTIMIZATION, OptimizerToolOpts);
    if (!AssemblerToolOpts.empty())
        CD->setPhaseArgs(CompilerDriver::ASSEMBLY,AssemblerToolOpts);
    if (!LinkerToolOpts.empty())
        CD->setPhaseArgs(CompilerDriver::LINKING, LinkerToolOpts);

    // Check for options that cause us to terminate before any significant work
    // is done.
    handleTerminatingOptions(CD);

    // Prepare the list of files to be compiled by the CompilerDriver.
    CompilerDriver::InputList InpList;
    std::vector<std::string>::iterator fileIt = Files.begin();
    std::vector<std::string>::iterator libIt  = Libraries.begin();
    unsigned libPos = 0, filePos = 0;
    while ( 1 ) {
      if ( libIt != Libraries.end() )
        libPos = Libraries.getPosition( libIt - Libraries.begin() );
      else
        libPos = 0;
      if ( fileIt != Files.end() )
        filePos = Files.getPosition( fileIt - Files.begin() );
      else
        filePos = 0;

      if ( filePos != 0 && (libPos == 0 || filePos < libPos) ) {
        // Add a source file
        InpList.push_back( std::make_pair(*fileIt, GetFileType(*fileIt,filePos)));
        ++fileIt;
      }
      else if ( libPos != 0 && (filePos == 0 || libPos < filePos) ) {
        // Add a library
        InpList.push_back( std::make_pair(*libIt++,""));
      }
      else
        break; // we're done with the list
    }

    // Tell the driver to do its thing
    int result = CD->execute(InpList,sys::Path(OutputFilename));
    if (result != 0) {
      throw std::string("Error executing actions. Terminated.");
      return result;
    }

    // All is good, return success
    return 0;
  } catch (const std::string& msg) {
    std::cerr << argv[0] << ": " << msg << "\n";
  } catch (...) {
    std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
  }
  return 1;
}
<commit_msg>* Use consistent spacing for function arguments * Output single-character strings as chars<commit_after>//===--- llvmc.cpp - The LLVM Compiler Driver -------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This tool provides a single point of access to the LLVM compilation tools.
//  It has many options. To discover the options supported please refer to the
//  tools' manual page (docs/CommandGuide/html/llvmc.html) or run the tool with
//  the --help option.
//
//===------------------------------------------------------------------------===

#include "CompilerDriver.h"
#include "Configuration.h"
#include "llvm/Pass.h"
#include "llvm/System/Signals.h"
#include "llvm/Support/CommandLine.h"
#include <iostream>

using namespace llvm;

namespace {
//===------------------------------------------------------------------------===
//===          PHASE OPTIONS
//===------------------------------------------------------------------------===
cl::opt<CompilerDriver::Phases> FinalPhase(cl::Optional,
  cl::desc("Choose final phase of compilation:"),
  cl::init(CompilerDriver::LINKING),
  cl::values(
    clEnumValN(CompilerDriver::PREPROCESSING,"E",
      "Stop compilation after pre-processing phase"),
    clEnumValN(CompilerDriver::TRANSLATION, "t",
      "Stop compilation after translation phase"),
    clEnumValN(CompilerDriver::OPTIMIZATION,"c",
      "Stop compilation after optimization phase"),
    clEnumValN(CompilerDriver::ASSEMBLY,"S",
      "Stop compilation after assembly phase"),
    clEnumValEnd
  )
);

//===------------------------------------------------------------------------===
//===          OPTIMIZATION OPTIONS
//===------------------------------------------------------------------------===
cl::opt<CompilerDriver::OptimizationLevels> OptLevel(cl::ZeroOrMore,
  cl::desc("Choose level of optimization to apply:"),
  cl::init(CompilerDriver::OPT_FAST_COMPILE),
  cl::values(
    clEnumValN(CompilerDriver::OPT_FAST_COMPILE,"O0",
      "An alias for the -O1 option"),
    clEnumValN(CompilerDriver::OPT_FAST_COMPILE,"O1",
      "Optimize for compilation speed, not execution speed"),
    clEnumValN(CompilerDriver::OPT_SIMPLE,"O2",
      "Perform simple translation time optimizations"),
    clEnumValN(CompilerDriver::OPT_AGGRESSIVE,"O3",
      "Perform aggressive translation time optimizations"),
    clEnumValN(CompilerDriver::OPT_LINK_TIME,"O4",
      "Perform link time optimizations"),
    clEnumValN(CompilerDriver::OPT_AGGRESSIVE_LINK_TIME,"O5",
      "Perform aggressive link time optimizations"),
    clEnumValEnd
  )
);

//===------------------------------------------------------------------------===
//===          TOOL OPTIONS
//===------------------------------------------------------------------------===

cl::list<std::string> PreprocessorToolOpts("Tpre", cl::ZeroOrMore,
  cl::desc("Pass specific options to the pre-processor"),
  cl::value_desc("option"));

cl::alias PreprocessorToolOptsAlias("Wp,", cl::ZeroOrMore,
  cl::desc("Alias for -Tpre"), cl::aliasopt(PreprocessorToolOpts));

cl::list<std::string> TranslatorToolOpts("Ttrn", cl::ZeroOrMore,
  cl::desc("Pass specific options to the assembler"),
  cl::value_desc("option"));

cl::list<std::string> AssemblerToolOpts("Tasm", cl::ZeroOrMore,
  cl::desc("Pass specific options to the assembler"),
  cl::value_desc("option"));

cl::alias AssemblerToolOptsAlias("Wa,", cl::ZeroOrMore,
  cl::desc("Alias for -Tasm"), cl::aliasopt(AssemblerToolOpts));

cl::list<std::string> OptimizerToolOpts("Topt", cl::ZeroOrMore,
  cl::desc("Pass specific options to the optimizer"),
  cl::value_desc("option"));

cl::list<std::string> LinkerToolOpts("Tlnk", cl::ZeroOrMore,
  cl::desc("Pass specific options to the linker"),
  cl::value_desc("option"));

cl::alias LinkerToolOptsAlias("Wl,", cl::ZeroOrMore,
  cl::desc("Alias for -Tlnk"), cl::aliasopt(LinkerToolOpts));

cl::list<std::string> fOpts("f", cl::ZeroOrMore, cl::Prefix,
  cl::desc("Pass through -f options to compiler tools"),
  cl::value_desc("option"));

cl::list<std::string> MOpts("M", cl::ZeroOrMore, cl::Prefix,
  cl::desc("Pass through -M options to compiler tools"),
  cl::value_desc("option"));

cl::list<std::string> WOpts("W", cl::ZeroOrMore, cl::Prefix,
  cl::desc("Pass through -W options to compiler tools"),
  cl::value_desc("option"));

cl::list<std::string> BOpt("B", cl::ZeroOrMore, cl::Prefix,
  cl::desc("Specify path to find llvmc sub-tools"),
  cl::value_desc("dir"));

//===------------------------------------------------------------------------===
//===          INPUT OPTIONS
//===------------------------------------------------------------------------===

cl::list<std::string> LibPaths("L", cl::Prefix,
  cl::desc("Specify a library search path"), cl::value_desc("dir"));

cl::list<std::string> Libraries("l", cl::Prefix,
  cl::desc("Specify base name of libraries to link to"), cl::value_desc("lib"));

cl::list<std::string> Includes("I", cl::Prefix,
  cl::desc("Specify location to search for included source"),
  cl::value_desc("dir"));

cl::list<std::string> Defines("D", cl::Prefix,
  cl::desc("Specify a pre-processor symbol to define"),
  cl::value_desc("symbol"));

//===------------------------------------------------------------------------===
//===          OUTPUT OPTIONS
//===------------------------------------------------------------------------===

cl::opt<std::string> OutputFilename("o",
  cl::desc("Override output filename"), cl::value_desc("file"));

cl::opt<std::string> OutputMachine("m", cl::Prefix,
  cl::desc("Specify a target machine"), cl::value_desc("machine"));

cl::opt<bool> Native("native", cl::init(false),
  cl::desc("Generative native code instead of bytecode"));

cl::opt<bool> DebugOutput("g", cl::init(false),
  cl::desc("Generate objects that include debug symbols"));

cl::opt<bool> StripOutput("strip", cl::init(false),
  cl::desc("Strip all symbols from linked output file"));

cl::opt<std::string> PrintFileName("print-fname", cl::Optional,
  cl::value_desc("file"),
  cl::desc("Print the full path for the option's value"));

//===------------------------------------------------------------------------===
//===          INFORMATION OPTIONS
//===------------------------------------------------------------------------===

cl::opt<bool> DryRun("dry-run", cl::Optional, cl::init(false),
  cl::desc("Do everything but perform the compilation actions"));

cl::alias DryRunAlias("y", cl::Optional,
  cl::desc("Alias for -dry-run"), cl::aliasopt(DryRun));

cl::opt<bool> Verbose("verbose", cl::Optional, cl::init(false),
  cl::desc("Print out each action taken"));

cl::alias VerboseAlias("v", cl::Optional,
  cl::desc("Alias for -verbose"), cl::aliasopt(Verbose));

cl::opt<bool> Debug("debug", cl::Optional, cl::init(false),
  cl::Hidden, cl::desc("Print out debugging information"));

cl::alias DebugAlias("d", cl::Optional,
  cl::desc("Alias for -debug"), cl::aliasopt(Debug));

cl::opt<bool> TimeActions("time-actions", cl::Optional, cl::init(false),
  cl::desc("Print execution time for each action taken"));

cl::opt<bool> ShowStats("stats", cl::Optional, cl::init(false),
  cl::desc("Print statistics accumulated during optimization"));

//===------------------------------------------------------------------------===
//===          ADVANCED OPTIONS
//===------------------------------------------------------------------------===

static cl::opt<std::string> ConfigDir("config-dir", cl::Optional,
  cl::desc("Specify configuration directory to override defaults"),
  cl::value_desc("dir"));

static cl::opt<bool> EmitRawCode("emit-raw-code", cl::Hidden, cl::Optional,
  cl::desc("Emit raw, unoptimized code"));

static cl::opt<bool> PipeCommands("pipe", cl::Optional,
  cl::desc("Invoke sub-commands by linking input/output with pipes"));

static cl::opt<bool> KeepTemps("keep-temps", cl::Optional,
  cl::desc("Don't delete temporary files created by llvmc"));

//===------------------------------------------------------------------------===
//===          POSITIONAL OPTIONS
//===------------------------------------------------------------------------===

static cl::list<std::string> Files(cl::Positional, cl::ZeroOrMore,
  cl::desc("[Sources/objects/libraries]"));

static cl::list<std::string> Languages("x", cl::ZeroOrMore,
  cl::desc("Specify the source language for subsequent files"),
  cl::value_desc("language"));

//===------------------------------------------------------------------------===
//===          GetFileType - determine type of a file
//===------------------------------------------------------------------------===
const std::string GetFileType(const std::string& fname, unsigned pos) {
  static std::vector<std::string>::iterator langIt = Languages.begin();
  static std::string CurrLang = "";

  // If a -x LANG option has been specified ..
  if (langIt != Languages.end())
    // If the -x LANG option came before the current file on command line
    if (Languages.getPosition( langIt - Languages.begin() ) < pos) {
      // use that language
      CurrLang = *langIt++;
      return CurrLang;
    }

  // If there's a current language in effect
  if (!CurrLang.empty())
    return CurrLang; // use that language

  // otherwise just determine lang from the filename's suffix
  return fname.substr(fname.rfind('.', fname.size()) + 1);
}

} // end anonymous namespace

void handleTerminatingOptions(CompilerDriver* CD) {
  if (!PrintFileName.empty()) {
    sys::Path path = CD->GetPathForLinkageItem(PrintFileName, false);
    std::string p = path.toString();
    if (p.empty())
      std::cout << "Can't locate `" << PrintFileName << "'.\n";
    else
      std::cout << p << '\n';
    exit(0);
  }
}

/// @brief The main program for llvmc
int main(int argc, char **argv) {
  // Make sure we print stack trace if we get bad signals
  sys::PrintStackTraceOnErrorSignal();

  try {

    // Parse the command line options
    cl::ParseCommandLineOptions(argc, argv,
      " LLVM Compiler Driver (llvmc)\n\n"
      "  This program provides easy invocation of the LLVM tool set\n"
      "  and other compiler tools.\n"
    );

    // Deal with unimplemented options.
    if (PipeCommands)
      throw std::string("Not implemented yet: -pipe");

    if (OutputFilename.empty())
      if (OptLevel == CompilerDriver::LINKING)
        OutputFilename = "a.out";

    // Construct the ConfigDataProvider object
    LLVMC_ConfigDataProvider Provider;
    Provider.setConfigDir(sys::Path(ConfigDir));

    // Construct the CompilerDriver object
    CompilerDriver* CD = CompilerDriver::Get(Provider);

    // If the LLVM_LIB_SEARCH_PATH environment variable is
    // set, append it to the list of places to search for libraries
    char *srchPath = getenv("LLVM_LIB_SEARCH_PATH");
    if (srchPath != NULL && strlen(srchPath) != 0)
      LibPaths.push_back(std::string(srchPath));

    // Set the driver flags based on command line options
    unsigned flags = 0;
    if (Verbose)        flags |= CompilerDriver::VERBOSE_FLAG;
    if (Debug)          flags |= CompilerDriver::DEBUG_FLAG;
    if (DryRun)         flags |= CompilerDriver::DRY_RUN_FLAG;
    if (Native)         flags |= CompilerDriver::EMIT_NATIVE_FLAG;
    if (EmitRawCode)    flags |= CompilerDriver::EMIT_RAW_FLAG;
    if (KeepTemps)      flags |= CompilerDriver::KEEP_TEMPS_FLAG;
    if (ShowStats)      flags |= CompilerDriver::SHOW_STATS_FLAG;
    if (TimeActions)    flags |= CompilerDriver::TIME_ACTIONS_FLAG;
    if (TimePassesIsEnabled) flags |= CompilerDriver::TIME_PASSES_FLAG;
    if (StripOutput)    flags |= CompilerDriver::STRIP_OUTPUT_FLAG;
    CD->setDriverFlags(flags);

    // Specify required parameters
    CD->setFinalPhase(FinalPhase);
    CD->setOptimization(OptLevel);
    CD->setOutputMachine(OutputMachine);
    CD->setIncludePaths(Includes);
    CD->setSymbolDefines(Defines);
    CD->setLibraryPaths(LibPaths);
    CD->setfPassThrough(fOpts);
    CD->setMPassThrough(MOpts);
    CD->setWPassThrough(WOpts);

    // Provide additional tool arguments
    if (!PreprocessorToolOpts.empty())
        CD->setPhaseArgs(CompilerDriver::PREPROCESSING, PreprocessorToolOpts);
    if (!TranslatorToolOpts.empty())
        CD->setPhaseArgs(CompilerDriver::TRANSLATION, TranslatorToolOpts);
    if (!OptimizerToolOpts.empty())
        CD->setPhaseArgs(CompilerDriver::OPTIMIZATION, OptimizerToolOpts);
    if (!AssemblerToolOpts.empty())
        CD->setPhaseArgs(CompilerDriver::ASSEMBLY,AssemblerToolOpts);
    if (!LinkerToolOpts.empty())
        CD->setPhaseArgs(CompilerDriver::LINKING, LinkerToolOpts);

    // Check for options that cause us to terminate before any significant work
    // is done.
    handleTerminatingOptions(CD);

    // Prepare the list of files to be compiled by the CompilerDriver.
    CompilerDriver::InputList InpList;
    std::vector<std::string>::iterator fileIt = Files.begin();
    std::vector<std::string>::iterator libIt  = Libraries.begin();
    unsigned libPos = 0, filePos = 0;
    while ( 1 ) {
      if (libIt != Libraries.end())
        libPos = Libraries.getPosition( libIt - Libraries.begin() );
      else
        libPos = 0;
      if (fileIt != Files.end())
        filePos = Files.getPosition(fileIt - Files.begin());
      else
        filePos = 0;

      if (filePos != 0 && (libPos == 0 || filePos < libPos)) {
        // Add a source file
        InpList.push_back(std::make_pair(*fileIt,
                                         GetFileType(*fileIt, filePos)));
        ++fileIt;
      } else if ( libPos != 0 && (filePos == 0 || libPos < filePos) ) {
        // Add a library
        InpList.push_back(std::make_pair(*libIt++, ""));
      }
      else
        break; // we're done with the list
    }

    // Tell the driver to do its thing
    int result = CD->execute(InpList, sys::Path(OutputFilename));
    if (result != 0) {
      throw std::string("Error executing actions. Terminated.");
      return result;
    }

    // All is good, return success
    return 0;
  } catch (const std::string& msg) {
    std::cerr << argv[0] << ": " << msg << '\n';
  } catch (...) {
    std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
  }
  return 1;
}
<|endoftext|>