<commit_before>#include "CryFuse.h"

#include <sys/types.h>
#include <sys/time.h>
#include <dirent.h>
#include <cassert>

#include "cryfs_lib/CryNode.h"
#include "cryfs_lib/CryErrnoException.h"

#define UNUSED(expr) (void)(expr)

using fusepp::path;

namespace cryfs {

CryFuse::CryFuse(CryDevice *device)
  :_device(device) {
}

int CryFuse::getattr(const path &path, struct stat *stbuf) {
  try {
    _device->lstat(path, stbuf);
    return 0;
  } catch(cryfs::CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::fgetattr(const path &path, struct stat *stbuf, fuse_file_info *fileinfo) {
  //printf("fgetattr(%s, _, _)\n", path.c_str());

  // On FreeBSD, trying to do anything with the mountpoint ends up
  // opening it, and then using the FD for an fgetattr.  So in the
  // special case of a path of "/", I need to do a getattr on the
  // underlying root directory instead of doing the fgetattr().
  // TODO Check if necessary
  if (path.native() == "/") {
    return getattr(path, stbuf);
  }

  try {
	_device->fstat(fileinfo->fh, stbuf);
	return 0;
  } catch(cryfs::CryErrnoException &e) {
	  return -e.getErrno();
  }
}

//TODO
int CryFuse::readlink(const path &path, char *buf, size_t size) {
  //printf("readlink(%s, _, %zu)\n", path.c_str(), size);
  auto real_path = _device->RootDir() / path;
  //size-1, because the fuse readlink() function includes the null terminating byte in the buffer size,
  //but the posix version does not and also doesn't append one.
  int real_size = ::readlink(real_path.c_str(), buf, size-1);
  if (real_size < 0) {
    return -errno;
  }
  //Terminate the string
  buf[real_size] = '\0';

  return 0;
}

int CryFuse::mknod(const path &path, mode_t mode, dev_t rdev) {
  UNUSED(rdev);
  UNUSED(mode);
  UNUSED(path);
  printf("Called non-implemented mknod(%s, %d, _)\n", path.c_str(), mode);
  return ENOSYS;
}

int CryFuse::mkdir(const path &path, mode_t mode) {
  //printf("mkdir(%s, %d)\n", path.c_str(), mode);
  try {
    _device->mkdir(path, mode);
    return 0;
  } catch(cryfs::CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::unlink(const path &path) {
  //printf("unlink(%s)\n", path.c_str());
  try {
    _device->unlink(path);
    return 0;
  } catch(cryfs::CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::rmdir(const path &path) {
  try {
    _device->rmdir(path);
    return 0;
  } catch(cryfs::CryErrnoException &e) {
    return -e.getErrno();
  }
}

//TODO
int CryFuse::symlink(const path &from, const path &to) {
  printf("NOT IMPLEMENTED: symlink(%s, %s)\n", from.c_str(), to.c_str());
  //auto real_from = _device->RootDir() / from;
  //auto real_to = _device->RootDir() / to;
  //int retstat = ::symlink(real_from.c_str(), real_to.c_str());
  //return errcode_map(retstat);
  return ENOSYS;
}

int CryFuse::rename(const path &from, const path &to) {
  //printf("rename(%s, %s)\n", from.c_str(), to.c_str());
  try {
    _device->rename(from, to);
    return 0;
  } catch(cryfs::CryErrnoException &e) {
    return -e.getErrno();
  }
}

//TODO
int CryFuse::link(const path &from, const path &to) {
  printf("NOT IMPLEMENTED: link(%s, %s)\n", from.c_str(), to.c_str());
  //auto real_from = _device->RootDir() / from;
  //auto real_to = _device->RootDir() / to;
  //int retstat = ::link(real_from.c_str(), real_to.c_str());
  //return errcode_map(retstat);
  return ENOSYS;
}

//TODO
int CryFuse::chmod(const path &path, mode_t mode) {
  printf("NOT IMPLEMENTED: chmod(%s, %d)\n", path.c_str(), mode);
  //auto real_path = _device->RootDir() / path;
  //int retstat = ::chmod(real_path.c_str(), mode);
  //return errcode_map(retstat);
  return ENOSYS;
}

//TODO
int CryFuse::chown(const path &path, uid_t uid, gid_t gid) {
  printf("NOT IMPLEMENTED: chown(%s, %d, %d)\n", path.c_str(), uid, gid);
  //auto real_path = _device->RootDir() / path;
  //int retstat = ::chown(real_path.c_str(), uid, gid);
  //return errcode_map(retstat);
  return ENOSYS;
}

int CryFuse::truncate(const path &path, off_t size) {
  //printf("truncate(%s, %zu)\n", path.c_str(), size);
  try {
    _device->truncate(path, size);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::ftruncate(const path &path, off_t size, fuse_file_info *fileinfo) {
  //printf("ftruncate(%s, %zu, _)\n", path.c_str(), size);
	UNUSED(path);
  try {
    _device->ftruncate(fileinfo->fh, size);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

//TODO
int CryFuse::utimens(const path &path, const timespec times[2]) {
  //printf("utimens(%s, _)\n", path.c_str());
  try {
    _device->utimens(path, times);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::open(const path &path, fuse_file_info *fileinfo) {
  //printf("open(%s, _)\n", path.c_str());
  try {
	  fileinfo->fh = _device->openFile(path, fileinfo->flags);
	  return 0;
  } catch (CryErrnoException &e) {
	  return -e.getErrno();
  }
}

int CryFuse::release(const path &path, fuse_file_info *fileinfo) {
  //printf("release(%s, _)\n", path.c_str());
  UNUSED(path);
  try {
	  _device->closeFile(fileinfo->fh);
	  return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::read(const path &path, char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
  //printf("read(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
  UNUSED(path);
  try {
    //printf("Reading from file %d\n", fileinfo->fh);
    //fflush(stdout);
    return _device->read(fileinfo->fh, buf, size, offset);
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::write(const path &path, const char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
  //printf("write(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
  UNUSED(path);
  try {
    _device->write(fileinfo->fh, buf, size, offset);
    return size;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

//TODO
int CryFuse::statfs(const path &path, struct statvfs *fsstat) {
  //printf("statfs(%s, _)\n", path.c_str());
  try {
    _device->statfs(path, fsstat);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

//TODO
int CryFuse::flush(const path &path, fuse_file_info *fileinfo) {
  //printf("Called non-implemented flush(%s, _)\n", path.c_str());
  UNUSED(path);
  UNUSED(fileinfo);
  return 0;
}

int CryFuse::fsync(const path &path, int datasync, fuse_file_info *fileinfo) {
  //printf("fsync(%s, %d, _)\n", path.c_str(), datasync);
  UNUSED(path);
  try {
    if (datasync) {
      _device->fdatasync(fileinfo->fh);
    } else {
      _device->fsync(fileinfo->fh);
    }
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::opendir(const path &path, fuse_file_info *fileinfo) {
  //printf("opendir(%s, _)\n", path.c_str());
  try {
    fileinfo->fh = _device->openDir(path);
    return 0;
  } catch(CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::readdir(const path &path, void *buf, fuse_fill_dir_t filler, off_t offset, fuse_file_info *fileinfo) {
  UNUSED(path);
  //printf("readdir(%s, _, _, %zu, _)\n", path.c_str(), offset);
  UNUSED(offset);
  try {
    auto entries = _device->readDir(fileinfo->fh);
    for (const auto &entry : *entries) {
      //TODO Also give file attributes (third param of filler)
      if (filler(buf, entry.c_str(), nullptr, 0) != 0) {
        return -ENOMEM;
      }
    }
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::releasedir(const path &path, fuse_file_info *fileinfo) {
  //printf("releasedir(%s, _)\n", path.c_str());
  UNUSED(path);
  try {
    _device->closeDir(fileinfo->fh);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

//TODO
int CryFuse::fsyncdir(const path &path, int datasync, fuse_file_info *fileinfo) {
  UNUSED(fileinfo);
  UNUSED(datasync);
  UNUSED(path);
  //printf("Called non-implemented fsyncdir(%s, %d, _)\n", path.c_str(), datasync);
  return 0;
}

void CryFuse::init(fuse_conn_info *conn) {
  UNUSED(conn);
  //printf("init()\n");
}

void CryFuse::destroy() {
  //printf("destroy()\n");
}

int CryFuse::access(const path &path, int mask) {
  //printf("access(%s, %d)\n", path.c_str(), mask);
  try {
    _device->access(path, mask);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::create(const path &path, mode_t mode, fuse_file_info *fileinfo) {
  //printf("create(%s, %d, _)\n", path.c_str(), mode);
  try {
    fileinfo->fh = _device->createAndOpenFile(path, mode);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

} /* namespace cryfs */
<commit_msg>Removed todo<commit_after>#include "CryFuse.h"

#include <sys/types.h>
#include <sys/time.h>
#include <dirent.h>
#include <cassert>

#include "cryfs_lib/CryNode.h"
#include "cryfs_lib/CryErrnoException.h"

#define UNUSED(expr) (void)(expr)

using fusepp::path;

namespace cryfs {

CryFuse::CryFuse(CryDevice *device)
  :_device(device) {
}

int CryFuse::getattr(const path &path, struct stat *stbuf) {
  try {
    _device->lstat(path, stbuf);
    return 0;
  } catch(cryfs::CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::fgetattr(const path &path, struct stat *stbuf, fuse_file_info *fileinfo) {
  //printf("fgetattr(%s, _, _)\n", path.c_str());

  // On FreeBSD, trying to do anything with the mountpoint ends up
  // opening it, and then using the FD for an fgetattr.  So in the
  // special case of a path of "/", I need to do a getattr on the
  // underlying root directory instead of doing the fgetattr().
  // TODO Check if necessary
  if (path.native() == "/") {
    return getattr(path, stbuf);
  }

  try {
	_device->fstat(fileinfo->fh, stbuf);
	return 0;
  } catch(cryfs::CryErrnoException &e) {
	  return -e.getErrno();
  }
}

//TODO
int CryFuse::readlink(const path &path, char *buf, size_t size) {
  //printf("readlink(%s, _, %zu)\n", path.c_str(), size);
  auto real_path = _device->RootDir() / path;
  //size-1, because the fuse readlink() function includes the null terminating byte in the buffer size,
  //but the posix version does not and also doesn't append one.
  int real_size = ::readlink(real_path.c_str(), buf, size-1);
  if (real_size < 0) {
    return -errno;
  }
  //Terminate the string
  buf[real_size] = '\0';

  return 0;
}

int CryFuse::mknod(const path &path, mode_t mode, dev_t rdev) {
  UNUSED(rdev);
  UNUSED(mode);
  UNUSED(path);
  printf("Called non-implemented mknod(%s, %d, _)\n", path.c_str(), mode);
  return ENOSYS;
}

int CryFuse::mkdir(const path &path, mode_t mode) {
  //printf("mkdir(%s, %d)\n", path.c_str(), mode);
  try {
    _device->mkdir(path, mode);
    return 0;
  } catch(cryfs::CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::unlink(const path &path) {
  //printf("unlink(%s)\n", path.c_str());
  try {
    _device->unlink(path);
    return 0;
  } catch(cryfs::CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::rmdir(const path &path) {
  try {
    _device->rmdir(path);
    return 0;
  } catch(cryfs::CryErrnoException &e) {
    return -e.getErrno();
  }
}

//TODO
int CryFuse::symlink(const path &from, const path &to) {
  printf("NOT IMPLEMENTED: symlink(%s, %s)\n", from.c_str(), to.c_str());
  //auto real_from = _device->RootDir() / from;
  //auto real_to = _device->RootDir() / to;
  //int retstat = ::symlink(real_from.c_str(), real_to.c_str());
  //return errcode_map(retstat);
  return ENOSYS;
}

int CryFuse::rename(const path &from, const path &to) {
  //printf("rename(%s, %s)\n", from.c_str(), to.c_str());
  try {
    _device->rename(from, to);
    return 0;
  } catch(cryfs::CryErrnoException &e) {
    return -e.getErrno();
  }
}

//TODO
int CryFuse::link(const path &from, const path &to) {
  printf("NOT IMPLEMENTED: link(%s, %s)\n", from.c_str(), to.c_str());
  //auto real_from = _device->RootDir() / from;
  //auto real_to = _device->RootDir() / to;
  //int retstat = ::link(real_from.c_str(), real_to.c_str());
  //return errcode_map(retstat);
  return ENOSYS;
}

//TODO
int CryFuse::chmod(const path &path, mode_t mode) {
  printf("NOT IMPLEMENTED: chmod(%s, %d)\n", path.c_str(), mode);
  //auto real_path = _device->RootDir() / path;
  //int retstat = ::chmod(real_path.c_str(), mode);
  //return errcode_map(retstat);
  return ENOSYS;
}

//TODO
int CryFuse::chown(const path &path, uid_t uid, gid_t gid) {
  printf("NOT IMPLEMENTED: chown(%s, %d, %d)\n", path.c_str(), uid, gid);
  //auto real_path = _device->RootDir() / path;
  //int retstat = ::chown(real_path.c_str(), uid, gid);
  //return errcode_map(retstat);
  return ENOSYS;
}

int CryFuse::truncate(const path &path, off_t size) {
  //printf("truncate(%s, %zu)\n", path.c_str(), size);
  try {
    _device->truncate(path, size);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::ftruncate(const path &path, off_t size, fuse_file_info *fileinfo) {
  //printf("ftruncate(%s, %zu, _)\n", path.c_str(), size);
	UNUSED(path);
  try {
    _device->ftruncate(fileinfo->fh, size);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

//TODO
int CryFuse::utimens(const path &path, const timespec times[2]) {
  //printf("utimens(%s, _)\n", path.c_str());
  try {
    _device->utimens(path, times);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::open(const path &path, fuse_file_info *fileinfo) {
  //printf("open(%s, _)\n", path.c_str());
  try {
	  fileinfo->fh = _device->openFile(path, fileinfo->flags);
	  return 0;
  } catch (CryErrnoException &e) {
	  return -e.getErrno();
  }
}

int CryFuse::release(const path &path, fuse_file_info *fileinfo) {
  //printf("release(%s, _)\n", path.c_str());
  UNUSED(path);
  try {
	  _device->closeFile(fileinfo->fh);
	  return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::read(const path &path, char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
  //printf("read(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
  UNUSED(path);
  try {
    //printf("Reading from file %d\n", fileinfo->fh);
    //fflush(stdout);
    return _device->read(fileinfo->fh, buf, size, offset);
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::write(const path &path, const char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
  //printf("write(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
  UNUSED(path);
  try {
    _device->write(fileinfo->fh, buf, size, offset);
    return size;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

//TODO
int CryFuse::statfs(const path &path, struct statvfs *fsstat) {
  //printf("statfs(%s, _)\n", path.c_str());
  try {
    _device->statfs(path, fsstat);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

//TODO
int CryFuse::flush(const path &path, fuse_file_info *fileinfo) {
  //printf("Called non-implemented flush(%s, _)\n", path.c_str());
  UNUSED(path);
  UNUSED(fileinfo);
  return 0;
}

int CryFuse::fsync(const path &path, int datasync, fuse_file_info *fileinfo) {
  //printf("fsync(%s, %d, _)\n", path.c_str(), datasync);
  UNUSED(path);
  try {
    if (datasync) {
      _device->fdatasync(fileinfo->fh);
    } else {
      _device->fsync(fileinfo->fh);
    }
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::opendir(const path &path, fuse_file_info *fileinfo) {
  //printf("opendir(%s, _)\n", path.c_str());
  try {
    fileinfo->fh = _device->openDir(path);
    return 0;
  } catch(CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::readdir(const path &path, void *buf, fuse_fill_dir_t filler, off_t offset, fuse_file_info *fileinfo) {
  UNUSED(path);
  //printf("readdir(%s, _, _, %zu, _)\n", path.c_str(), offset);
  UNUSED(offset);
  try {
    auto entries = _device->readDir(fileinfo->fh);
    for (const auto &entry : *entries) {
      if (filler(buf, entry.c_str(), nullptr, 0) != 0) {
        return -ENOMEM;
      }
    }
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::releasedir(const path &path, fuse_file_info *fileinfo) {
  //printf("releasedir(%s, _)\n", path.c_str());
  UNUSED(path);
  try {
    _device->closeDir(fileinfo->fh);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

//TODO
int CryFuse::fsyncdir(const path &path, int datasync, fuse_file_info *fileinfo) {
  UNUSED(fileinfo);
  UNUSED(datasync);
  UNUSED(path);
  //printf("Called non-implemented fsyncdir(%s, %d, _)\n", path.c_str(), datasync);
  return 0;
}

void CryFuse::init(fuse_conn_info *conn) {
  UNUSED(conn);
  //printf("init()\n");
}

void CryFuse::destroy() {
  //printf("destroy()\n");
}

int CryFuse::access(const path &path, int mask) {
  //printf("access(%s, %d)\n", path.c_str(), mask);
  try {
    _device->access(path, mask);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

int CryFuse::create(const path &path, mode_t mode, fuse_file_info *fileinfo) {
  //printf("create(%s, %d, _)\n", path.c_str(), mode);
  try {
    fileinfo->fh = _device->createAndOpenFile(path, mode);
    return 0;
  } catch (CryErrnoException &e) {
    return -e.getErrno();
  }
}

} /* namespace cryfs */
<|endoftext|>


<commit_before>//
// EigenJS.cpp
// ~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#include <cstdlib>
#include <ctime>

#include "Complex.hpp"
#include "Matrix.hpp"
#include "CMatrix.hpp"

#include "Vector.hpp"
#include "CVector.hpp"

namespace EigenJS {

void Init(v8::Handle<v8::Object> exports) {
  std::srand(static_cast<unsigned int>(std::time(0)));
  std::rand();

  Complex<>::Init(exports);
  Matrix<>::Init(exports);
  CMatrix<>::Init(exports);

  Vector<>::Init(exports);
  CVector<>::Init(exports);
}

}  // namespace EigenJS

NODE_MODULE(eigen, EigenJS::Init)
<commit_msg>src: using RowVector<commit_after>//
// EigenJS.cpp
// ~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#include <cstdlib>
#include <ctime>

#include "Complex.hpp"
#include "Matrix.hpp"
#include "CMatrix.hpp"

#include "Vector.hpp"
#include "CVector.hpp"

#include "RowVector.hpp"

namespace EigenJS {

void Init(v8::Handle<v8::Object> exports) {
  std::srand(static_cast<unsigned int>(std::time(0)));
  std::rand();

  Complex<>::Init(exports);
  Matrix<>::Init(exports);
  CMatrix<>::Init(exports);

  Vector<>::Init(exports);
  CVector<>::Init(exports);

  RowVector<>::Init(exports);
}

}  // namespace EigenJS

NODE_MODULE(eigen, EigenJS::Init)
<|endoftext|>


<commit_before>/// @file
/// @author  Boris Mikic
/// @version 2.1
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php

#include <hltypes/hmap.h>
#include <hltypes/hstring.h>

#include "Factory.h"
#include "Serializable.h"

namespace liteser
{
	// this approach is used because there is a massive problem with static linking
	hmap<hstr, Serializable* (*)()>* __lsConstructors;

	Factory::Factory()
	{
	}

	Factory::~Factory()
	{
	}

	Serializable* Factory::create(chstr name)
	{
		Serializable* (*constructor)() = __lsConstructors->try_get_by_key(name, NULL);
		if (constructor == NULL)
		{
			throw hl_exception("Detected class not registered as a Serializable: " + name);
		}
		return (*constructor)();
	}

	void Factory::_register(chstr name, Serializable* (*constructor)())
	{
		if (__lsConstructors == NULL)
		{
			__lsConstructors = new hmap<hstr, Serializable* (*)()>();
		}
		__lsConstructors->operator[](name) = constructor;
	}

}
<commit_msg>- small static lib fix<commit_after>/// @file
/// @author  Boris Mikic
/// @version 2.1
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php

#include <hltypes/hmap.h>
#include <hltypes/hstring.h>
#include <hltypes/hlog.h>

#include "Factory.h"
#include "Serializable.h"

namespace liteser
{
	// this approach is used because there is a massive problem with static linking
	static hmap<hstr, Serializable* (*)()>* __lsConstructors = NULL;

	Factory::Factory()
	{
	}

	Factory::~Factory()
	{
	}

	Serializable* Factory::create(chstr name)
	{
		Serializable* (*constructor)() = __lsConstructors->try_get_by_key(name, NULL);
		if (constructor == NULL)
		{
			throw hl_exception("Detected class not registered as a Serializable: " + name);
		}
		return (*constructor)();
	}

	void Factory::_register(chstr name, Serializable* (*constructor)())
	{
		if (__lsConstructors == NULL)
		{
			__lsConstructors = new hmap<hstr, Serializable* (*)()>();
		}
		hlog::debug(liteser::logTag, "Registering class: " + name);
		__lsConstructors->operator[](name) = constructor;
	}

}
<|endoftext|>


<commit_before>// SciTE - Scintilla based Text Editor
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
//
// NAME
// 	LexConf.cxx - lexer for Apache Configuration Files
// AUTHOR
// 	first working version contributed by Ahmad Zawawi <zeus_go64@hotmail.com> on October 28, 2000
// DESCRIPTION
// 	i created this lexer because i needed something pretty when dealing
// when Apache Configuration files...
//

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static void ColouriseConfDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler)
{
	int state = SCE_CONF_DEFAULT;
	char chNext = styler[startPos];
	int lengthDoc = startPos + length;
	// create a buffer large enough to take the largest chunk...
	char *buffer = new char[length];
	int bufferCount = 0;

	// this assumes that we have 2 keyword list in conf.properties
	WordList &directives = *keywordLists[0];
	WordList &params = *keywordLists[1];

	// go through all provided text segment
	// using the hand-written state machine shown below
	styler.StartAt(startPos);
	styler.StartSegment(startPos);
	for (int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			i++;
			continue;
		}
		switch(state) {
			case SCE_CONF_DEFAULT:
				if( ch == '\n' || ch == '\r' || ch == '\t' || ch == ' ') {
					// whitespace is simply ignored here...
					styler.ColourTo(i,SCE_CONF_DEFAULT);
					break;
				} else if( ch == '#' ) {
					// signals the start of a comment...
					state = SCE_CONF_COMMENT;
					styler.ColourTo(i,SCE_CONF_COMMENT);
				} else if( ch == '.' /*|| ch == '/'*/) {
					// signals the start of a file...
					state = SCE_CONF_EXTENSION;
					styler.ColourTo(i,SCE_CONF_EXTENSION);
				} else if( ch == '"') {
					state = SCE_CONF_STRING;
					styler.ColourTo(i,SCE_CONF_STRING);
				} else if( ispunct(ch) ) {
					// signals an operator...
					// no state jump necessary for this
					// simple case...
					styler.ColourTo(i,SCE_CONF_OPERATOR);
				} else if( isalpha(ch) ) {
					// signals the start of an identifier
					bufferCount = 0;
					buffer[bufferCount++] = tolower(ch);
					state = SCE_CONF_IDENTIFIER;
				} else if( isdigit(ch) ) {
					// signals the start of a number
					bufferCount = 0;
					buffer[bufferCount++] = ch;
					//styler.ColourTo(i,SCE_CONF_NUMBER);
					state = SCE_CONF_NUMBER;
				} else {
					// style it the default style..
					styler.ColourTo(i,SCE_CONF_DEFAULT);
				}
				break;

			case SCE_CONF_COMMENT:
				// if we find a newline here,
				// we simply go to default state
				// else continue to work on it...
				if( ch == '\n' || ch == '\r' ) {
					state = SCE_CONF_DEFAULT;
				} else {
					styler.ColourTo(i,SCE_CONF_COMMENT);
				}
				break;

			case SCE_CONF_EXTENSION:
				// if we find a non-alphanumeric char,
				// we simply go to default state
				// else we're still dealing with an extension...
				if( isalnum(ch) || (ch == '_') ||
					(ch == '-') || (ch == '$') ||
					(ch == '/') || (ch == '.') || (ch == '*') )
				{
					styler.ColourTo(i,SCE_CONF_EXTENSION);
				} else {
					state = SCE_CONF_DEFAULT;
					chNext = styler[i--];
				}
				break;

			case SCE_CONF_STRING:
				// if we find the end of a string char, we simply go to default state
				// else we're still dealing with an string...
				if( (ch == '"' && styler.SafeGetCharAt(i-1)!='\\') || (ch == '\n') || (ch == '\r') ) {
					state = SCE_CONF_DEFAULT;
				}
				styler.ColourTo(i,SCE_CONF_STRING);
				break;

			case SCE_CONF_IDENTIFIER:
				// stay  in CONF_IDENTIFIER state until we find a non-alphanumeric
				if( isalnum(ch) || (ch == '_') || (ch == '-') || (ch == '/') || (ch == '$') || (ch == '.') || (ch == '*')) {
					buffer[bufferCount++] = tolower(ch);
				} else {
					state = SCE_CONF_DEFAULT;
					buffer[bufferCount] = '\0';

					// check if the buffer contains a keyword, and highlight it if it is a keyword...
					if(directives.InList(buffer)) {
						styler.ColourTo(i-1,SCE_CONF_DIRECTIVE );
					} else if(params.InList(buffer)) {
						styler.ColourTo(i-1,SCE_CONF_PARAMETER );
					} else if(strchr(buffer,'/') || strchr(buffer,'.')) {
						styler.ColourTo(i-1,SCE_CONF_EXTENSION);
					} else {
						styler.ColourTo(i-1,SCE_CONF_DEFAULT);
					}

					// push back the faulty character
					chNext = styler[i--];

				}
				break;

			case SCE_CONF_NUMBER:
				// stay  in CONF_NUMBER state until we find a non-numeric
				if( isdigit(ch) || ch == '.') {
					buffer[bufferCount++] = ch;
				} else {
					state = SCE_CONF_DEFAULT;
					buffer[bufferCount] = '\0';

					// Colourize here...
					if( strchr(buffer,'.') ) {
						// it is an IP address...
						styler.ColourTo(i-1,SCE_CONF_IP);
					} else {
						// normal number
						styler.ColourTo(i-1,SCE_CONF_NUMBER);
					}

					// push back a character
					chNext = styler[i--];
				}
				break;

		}
	}
}

LexerModule lmConf(SCLEX_CONF, ColouriseConfDoc);
<commit_msg>Added static_cast to hush Borland C++.<commit_after>// SciTE - Scintilla based Text Editor
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
//
// NAME
// 	LexConf.cxx - lexer for Apache Configuration Files
// AUTHOR
// 	first working version contributed by Ahmad Zawawi <zeus_go64@hotmail.com> on October 28, 2000
// DESCRIPTION
// 	i created this lexer because i needed something pretty when dealing
// when Apache Configuration files...
//

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static void ColouriseConfDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler)
{
	int state = SCE_CONF_DEFAULT;
	char chNext = styler[startPos];
	int lengthDoc = startPos + length;
	// create a buffer large enough to take the largest chunk...
	char *buffer = new char[length];
	int bufferCount = 0;

	// this assumes that we have 2 keyword list in conf.properties
	WordList &directives = *keywordLists[0];
	WordList &params = *keywordLists[1];

	// go through all provided text segment
	// using the hand-written state machine shown below
	styler.StartAt(startPos);
	styler.StartSegment(startPos);
	for (int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			i++;
			continue;
		}
		switch(state) {
			case SCE_CONF_DEFAULT:
				if( ch == '\n' || ch == '\r' || ch == '\t' || ch == ' ') {
					// whitespace is simply ignored here...
					styler.ColourTo(i,SCE_CONF_DEFAULT);
					break;
				} else if( ch == '#' ) {
					// signals the start of a comment...
					state = SCE_CONF_COMMENT;
					styler.ColourTo(i,SCE_CONF_COMMENT);
				} else if( ch == '.' /*|| ch == '/'*/) {
					// signals the start of a file...
					state = SCE_CONF_EXTENSION;
					styler.ColourTo(i,SCE_CONF_EXTENSION);
				} else if( ch == '"') {
					state = SCE_CONF_STRING;
					styler.ColourTo(i,SCE_CONF_STRING);
				} else if( ispunct(ch) ) {
					// signals an operator...
					// no state jump necessary for this
					// simple case...
					styler.ColourTo(i,SCE_CONF_OPERATOR);
				} else if( isalpha(ch) ) {
					// signals the start of an identifier
					bufferCount = 0;
					buffer[bufferCount++] = static_cast<char>(tolower(ch));
					state = SCE_CONF_IDENTIFIER;
				} else if( isdigit(ch) ) {
					// signals the start of a number
					bufferCount = 0;
					buffer[bufferCount++] = ch;
					//styler.ColourTo(i,SCE_CONF_NUMBER);
					state = SCE_CONF_NUMBER;
				} else {
					// style it the default style..
					styler.ColourTo(i,SCE_CONF_DEFAULT);
				}
				break;

			case SCE_CONF_COMMENT:
				// if we find a newline here,
				// we simply go to default state
				// else continue to work on it...
				if( ch == '\n' || ch == '\r' ) {
					state = SCE_CONF_DEFAULT;
				} else {
					styler.ColourTo(i,SCE_CONF_COMMENT);
				}
				break;

			case SCE_CONF_EXTENSION:
				// if we find a non-alphanumeric char,
				// we simply go to default state
				// else we're still dealing with an extension...
				if( isalnum(ch) || (ch == '_') ||
					(ch == '-') || (ch == '$') ||
					(ch == '/') || (ch == '.') || (ch == '*') )
				{
					styler.ColourTo(i,SCE_CONF_EXTENSION);
				} else {
					state = SCE_CONF_DEFAULT;
					chNext = styler[i--];
				}
				break;

			case SCE_CONF_STRING:
				// if we find the end of a string char, we simply go to default state
				// else we're still dealing with an string...
				if( (ch == '"' && styler.SafeGetCharAt(i-1)!='\\') || (ch == '\n') || (ch == '\r') ) {
					state = SCE_CONF_DEFAULT;
				}
				styler.ColourTo(i,SCE_CONF_STRING);
				break;

			case SCE_CONF_IDENTIFIER:
				// stay  in CONF_IDENTIFIER state until we find a non-alphanumeric
				if( isalnum(ch) || (ch == '_') || (ch == '-') || (ch == '/') || (ch == '$') || (ch == '.') || (ch == '*')) {
					buffer[bufferCount++] = static_cast<char>(tolower(ch));
				} else {
					state = SCE_CONF_DEFAULT;
					buffer[bufferCount] = '\0';

					// check if the buffer contains a keyword, and highlight it if it is a keyword...
					if(directives.InList(buffer)) {
						styler.ColourTo(i-1,SCE_CONF_DIRECTIVE );
					} else if(params.InList(buffer)) {
						styler.ColourTo(i-1,SCE_CONF_PARAMETER );
					} else if(strchr(buffer,'/') || strchr(buffer,'.')) {
						styler.ColourTo(i-1,SCE_CONF_EXTENSION);
					} else {
						styler.ColourTo(i-1,SCE_CONF_DEFAULT);
					}

					// push back the faulty character
					chNext = styler[i--];

				}
				break;

			case SCE_CONF_NUMBER:
				// stay  in CONF_NUMBER state until we find a non-numeric
				if( isdigit(ch) || ch == '.') {
					buffer[bufferCount++] = ch;
				} else {
					state = SCE_CONF_DEFAULT;
					buffer[bufferCount] = '\0';

					// Colourize here...
					if( strchr(buffer,'.') ) {
						// it is an IP address...
						styler.ColourTo(i-1,SCE_CONF_IP);
					} else {
						// normal number
						styler.ColourTo(i-1,SCE_CONF_NUMBER);
					}

					// push back a character
					chNext = styler[i--];
				}
				break;

		}
	}
}

LexerModule lmConf(SCLEX_CONF, ColouriseConfDoc);
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <stan/model/model_base.hpp>
#include <stan/model/model_base_crtp.hpp>
#include <ostream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

struct mock_model : public stan::model::model_base_crtp<mock_model> {
  mock_model(size_t n) : model_base_crtp(n) {}

  virtual ~mock_model() {}

  std::string model_name() const override { return "mock_model"; }

  std::vector<std::string> model_compile_info() const {
    std::vector<std::string> stanc_info;
    stanc_info.push_back("stanc_version = stanc3");
    return stanc_info;
  }

  void get_param_names(std::vector<std::string>& names) const override {}
  void get_dims(std::vector<std::vector<size_t> >& dimss) const override {}

  void constrained_param_names(std::vector<std::string>& param_names,
                               bool include_tparams,
                               bool include_gqs) const override {}

  void unconstrained_param_names(std::vector<std::string>& param_names,
                                 bool include_tparams,
                                 bool include_gqs) const override {}

  template <bool propto, bool jacobian, typename T>
  T log_prob(Eigen::Matrix<T, -1, 1>& params_r, std::ostream* msgs) const {
    if (std::is_same<T, double>::value) {
      if (!propto && !jacobian)
        return 1;
      else if (!propto && jacobian)
        return 3;
      else if (propto && !jacobian)
        return 5;
      else
        return 7;
    } else {
      if (!propto && !jacobian)
        return 2;
      else if (!propto && jacobian)
        return 4;
      else if (propto && !jacobian)
        return 6;
      else
        return 8;
    }
  }

  void transform_inits(const stan::io::var_context& context,
                       Eigen::VectorXd& params_r,
                       std::ostream* msgs) const override {}

  template <typename RNG>
  void write_array(RNG& base_rng, Eigen::VectorXd& params_r,
                   Eigen::VectorXd& params_constrained_r, bool include_tparams,
                   bool include_gqs, std::ostream* msgs) const {}

  template <bool propto, bool jacobian, typename T>
  T log_prob(std::vector<T>& params_r, std::vector<int>& params_i,
             std::ostream* msgs) const {
    if (std::is_same<T, double>::value) {
      if (!propto && !jacobian)
        return 1;
      else if (!propto && jacobian)
        return 3;
      else if (propto && !jacobian)
        return 5;
      else
        return 7;
    } else {
      if (!propto && !jacobian)
        return 2;
      else if (!propto && jacobian)
        return 4;
      else if (propto && !jacobian)
        return 6;
      else
        return 8;
    }
  }

  void transform_inits(const stan::io::var_context& context,
                       std::vector<int>& params_i,
                       std::vector<double>& params_r,
                       std::ostream* msgs) const override {}

  template <typename RNG>
  void write_array(RNG& base_rng, std::vector<double>& params_r,
                   std::vector<int>& params_i,
                   std::vector<double>& params_r_constrained,
                   bool include_tparams, bool include_gqs,
                   std::ostream* msgs) const {}
};

TEST(model, modelBaseInheritance) {
  // check that base_model and prob_grad inheritance works
  mock_model m(17);
  EXPECT_EQ(17u, m.num_params_r());
  EXPECT_EQ(0u, m.num_params_i());
  EXPECT_THROW(m.param_range_i(0), std::out_of_range);
}

TEST(model, modelTemplateLogProb) {
  mock_model m(17);
  stan::model::model_base& bm = m;
  Eigen::VectorXd params_r(2);
  Eigen::Matrix<stan::math::var, -1, 1> params_r_v(3);
  std::stringstream ss;
  std::ostream* msgs = &ss;

  // test from base class reference
  EXPECT_FLOAT_EQ(1, bm.log_prob(params_r, msgs));
  EXPECT_FLOAT_EQ(2, bm.log_prob(params_r_v, msgs).val());
  EXPECT_FLOAT_EQ(3, bm.log_prob_jacobian(params_r, msgs));
  EXPECT_FLOAT_EQ(4, bm.log_prob_jacobian(params_r_v, msgs).val());
  EXPECT_FLOAT_EQ(5, bm.log_prob_propto(params_r, msgs));
  EXPECT_FLOAT_EQ(6, bm.log_prob_propto(params_r_v, msgs).val());
  EXPECT_FLOAT_EQ(7, bm.log_prob_propto_jacobian(params_r, msgs));
  EXPECT_FLOAT_EQ(8, bm.log_prob_propto_jacobian(params_r_v, msgs).val());

  // test template version from base class reference
  // long form assignment avoids test macro parse error with multi tparams
  double v1 = bm.template log_prob<false, false>(params_r, msgs);
  EXPECT_FLOAT_EQ(1, v1);
  double v2 = bm.template log_prob<false, false>(params_r_v, msgs).val();
  EXPECT_FLOAT_EQ(2, v2);
  double v3 = bm.template log_prob<false, true>(params_r, msgs);
  EXPECT_FLOAT_EQ(3, v3);
  double v4 = bm.template log_prob<false, true>(params_r_v, msgs).val();
  EXPECT_FLOAT_EQ(4, v4);
  double v5 = bm.template log_prob<true, false>(params_r, msgs);
  EXPECT_FLOAT_EQ(5, v5);
  double v6 = bm.template log_prob<true, false>(params_r_v, msgs).val();
  EXPECT_FLOAT_EQ(6, v6);
  double v7 = bm.template log_prob<true, true>(params_r, msgs);
  EXPECT_FLOAT_EQ(7, v7);
  double v8 = bm.template log_prob<true, true>(params_r_v, msgs).val();
  EXPECT_FLOAT_EQ(8, v8);
}
<commit_msg>fix override for model_crtp test<commit_after>#include <gtest/gtest.h>
#include <stan/model/model_base.hpp>
#include <stan/model/model_base_crtp.hpp>
#include <ostream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

struct mock_model : public stan::model::model_base_crtp<mock_model> {
  mock_model(size_t n) : model_base_crtp(n) {}

  virtual ~mock_model() {}

  std::string model_name() const override { return "mock_model"; }

  std::vector<std::string> model_compile_info() const override {
    std::vector<std::string> stanc_info;
    stanc_info.push_back("stanc_version = stanc3");
    return stanc_info;
  }

  void get_param_names(std::vector<std::string>& names) const override {}
  void get_dims(std::vector<std::vector<size_t> >& dimss) const override {}

  void constrained_param_names(std::vector<std::string>& param_names,
                               bool include_tparams,
                               bool include_gqs) const override {}

  void unconstrained_param_names(std::vector<std::string>& param_names,
                                 bool include_tparams,
                                 bool include_gqs) const override {}

  template <bool propto, bool jacobian, typename T>
  T log_prob(Eigen::Matrix<T, -1, 1>& params_r, std::ostream* msgs) const {
    if (std::is_same<T, double>::value) {
      if (!propto && !jacobian)
        return 1;
      else if (!propto && jacobian)
        return 3;
      else if (propto && !jacobian)
        return 5;
      else
        return 7;
    } else {
      if (!propto && !jacobian)
        return 2;
      else if (!propto && jacobian)
        return 4;
      else if (propto && !jacobian)
        return 6;
      else
        return 8;
    }
  }

  void transform_inits(const stan::io::var_context& context,
                       Eigen::VectorXd& params_r,
                       std::ostream* msgs) const override {}

  template <typename RNG>
  void write_array(RNG& base_rng, Eigen::VectorXd& params_r,
                   Eigen::VectorXd& params_constrained_r, bool include_tparams,
                   bool include_gqs, std::ostream* msgs) const {}

  template <bool propto, bool jacobian, typename T>
  T log_prob(std::vector<T>& params_r, std::vector<int>& params_i,
             std::ostream* msgs) const {
    if (std::is_same<T, double>::value) {
      if (!propto && !jacobian)
        return 1;
      else if (!propto && jacobian)
        return 3;
      else if (propto && !jacobian)
        return 5;
      else
        return 7;
    } else {
      if (!propto && !jacobian)
        return 2;
      else if (!propto && jacobian)
        return 4;
      else if (propto && !jacobian)
        return 6;
      else
        return 8;
    }
  }

  void transform_inits(const stan::io::var_context& context,
                       std::vector<int>& params_i,
                       std::vector<double>& params_r,
                       std::ostream* msgs) const override {}

  template <typename RNG>
  void write_array(RNG& base_rng, std::vector<double>& params_r,
                   std::vector<int>& params_i,
                   std::vector<double>& params_r_constrained,
                   bool include_tparams, bool include_gqs,
                   std::ostream* msgs) const {}
};

TEST(model, modelBaseInheritance) {
  // check that base_model and prob_grad inheritance works
  mock_model m(17);
  EXPECT_EQ(17u, m.num_params_r());
  EXPECT_EQ(0u, m.num_params_i());
  EXPECT_THROW(m.param_range_i(0), std::out_of_range);
}

TEST(model, modelTemplateLogProb) {
  mock_model m(17);
  stan::model::model_base& bm = m;
  Eigen::VectorXd params_r(2);
  Eigen::Matrix<stan::math::var, -1, 1> params_r_v(3);
  std::stringstream ss;
  std::ostream* msgs = &ss;

  // test from base class reference
  EXPECT_FLOAT_EQ(1, bm.log_prob(params_r, msgs));
  EXPECT_FLOAT_EQ(2, bm.log_prob(params_r_v, msgs).val());
  EXPECT_FLOAT_EQ(3, bm.log_prob_jacobian(params_r, msgs));
  EXPECT_FLOAT_EQ(4, bm.log_prob_jacobian(params_r_v, msgs).val());
  EXPECT_FLOAT_EQ(5, bm.log_prob_propto(params_r, msgs));
  EXPECT_FLOAT_EQ(6, bm.log_prob_propto(params_r_v, msgs).val());
  EXPECT_FLOAT_EQ(7, bm.log_prob_propto_jacobian(params_r, msgs));
  EXPECT_FLOAT_EQ(8, bm.log_prob_propto_jacobian(params_r_v, msgs).val());

  // test template version from base class reference
  // long form assignment avoids test macro parse error with multi tparams
  double v1 = bm.template log_prob<false, false>(params_r, msgs);
  EXPECT_FLOAT_EQ(1, v1);
  double v2 = bm.template log_prob<false, false>(params_r_v, msgs).val();
  EXPECT_FLOAT_EQ(2, v2);
  double v3 = bm.template log_prob<false, true>(params_r, msgs);
  EXPECT_FLOAT_EQ(3, v3);
  double v4 = bm.template log_prob<false, true>(params_r_v, msgs).val();
  EXPECT_FLOAT_EQ(4, v4);
  double v5 = bm.template log_prob<true, false>(params_r, msgs);
  EXPECT_FLOAT_EQ(5, v5);
  double v6 = bm.template log_prob<true, false>(params_r_v, msgs).val();
  EXPECT_FLOAT_EQ(6, v6);
  double v7 = bm.template log_prob<true, true>(params_r, msgs);
  EXPECT_FLOAT_EQ(7, v7);
  double v8 = bm.template log_prob<true, true>(params_r_v, msgs).val();
  EXPECT_FLOAT_EQ(8, v8);
}
<|endoftext|>


<commit_before>#include "LDLTSolver.h"

#include <sofa/core/ObjectFactory.h>

#include <Eigen/Sparse>
#include <Eigen/SparseCholesky>

#include <Eigen/LU>
#include <Eigen/Cholesky>
#include <Eigen/SVD>

namespace sofa {
namespace component {
namespace linearsolver {

SOFA_DECL_CLASS(LDLTSolver);
int LDLTSolverClass = core::RegisterObject("Direct LDLT solver").add< LDLTSolver >();

typedef AssembledSystem::vec vec;

LDLTSolver::LDLTSolver()
    : damping( initData(&damping, 0.0, "damping", "damping lol") )
    , pimpl()
{

}

LDLTSolver::~LDLTSolver() {

}

void LDLTSolver::factor(const AssembledSystem& sys) {

	pimpl->Hinv.compute( sys.H );

	if( pimpl->Hinv.info() == Eigen::NumericalIssue ) {
		std::cerr << "H is not psd :-/" << std::endl;

		std::cerr << pimpl->H << std::endl;
	}

	pimpl->dt = sys.dt;
	pimpl->m = sys.m;
	pimpl->n = sys.n;

	if( sys.n ) {
		pimpl_type::cmat schur(sys.n, sys.n);
		pimpl_type::cmat PJT = sys.P.transpose() * sys.J.transpose();

		pimpl->HinvPJT.resize(sys.m, sys.n);
		pimpl->HinvPJT = pimpl->Hinv.solve( PJT );

		schur = (sys.C.transpose() + (PJT.transpose() * pimpl->HinvPJT )).selfadjointView<Eigen::Upper>();

		pimpl->schur.compute( schur );

		if( pimpl->schur.info() == Eigen::NumericalIssue ) {
			std::cerr << "schur is not psd :-/" << std::endl;
			std::cerr << schur << std::endl;
		}
	} else {
		// nothing lol
	}

}

void LDLTSolver::solve(AssembledSystem::vec& res,
                         const AssembledSystem& sys,
                         const AssembledSystem::vec& rhs) const {

	assert( res.size() == sys.size() );
	assert( rhs.size() == sys.size() );

	SReal alpha = 1.0 / ( 1.0 + damping.getValue() * pimpl->dt );

	vec tmp = alpha * (sys.P * rhs.head(sys.m));

	// in place solve
	tmp = pimpl->Hinv.solve(tmp);

	res.head( sys.m ) = sys.P * tmp;

	if( sys.n ) {
		vec tmp = rhs.tail( sys.n ) - sys.P * (pimpl->HinvPJT.transpose() * rhs.head( sys.m ));

		// lambdas
		res.tail( sys.n ) = pimpl->schur.solve( tmp );

		// constraint forces
		res.head( sys.m ) += sys.P * (pimpl->HinvPJT * res.tail( sys.n));
	}

}

}
}
}

<commit_msg>r10081/sofa : Compliant: fixed LDLT solver (yay!). Incidentally, CompliantCloth.scn works again.<commit_after>#include "LDLTSolver.h"

#include <sofa/core/ObjectFactory.h>

#include <Eigen/Sparse>
#include <Eigen/SparseCholesky>

#include <Eigen/LU>
#include <Eigen/Cholesky>
#include <Eigen/SVD>

namespace sofa {
namespace component {
namespace linearsolver {

SOFA_DECL_CLASS(LDLTSolver);
int LDLTSolverClass = core::RegisterObject("Direct LDLT solver").add< LDLTSolver >();

typedef AssembledSystem::vec vec;

LDLTSolver::LDLTSolver()
    : damping( initData(&damping, 0.0, "damping", "damping lol") )
    , pimpl()
{

}

LDLTSolver::~LDLTSolver() {

}

void LDLTSolver::factor(const AssembledSystem& sys) {

	pimpl->Hinv.compute( sys.H );

	if( pimpl->Hinv.info() == Eigen::NumericalIssue ) {
		std::cerr << "H is not psd :-/" << std::endl;

		std::cerr << pimpl->H << std::endl;
	}

	pimpl->dt = sys.dt;
	pimpl->m = sys.m;
	pimpl->n = sys.n;

	if( sys.n ) {
		pimpl_type::cmat schur(sys.n, sys.n);
		pimpl_type::cmat PJT = sys.P.transpose() * sys.J.transpose();

		pimpl->HinvPJT.resize(sys.m, sys.n);
		pimpl->HinvPJT = pimpl->Hinv.solve( PJT );

		schur = (sys.C.transpose() + (PJT.transpose() * pimpl->HinvPJT )).selfadjointView<Eigen::Upper>();

		pimpl->schur.compute( schur );

		if( pimpl->schur.info() == Eigen::NumericalIssue ) {
			std::cerr << "schur is not psd :-/" << std::endl;
			std::cerr << schur << std::endl;
		}
	} else {
		// nothing lol
	}

}

void LDLTSolver::solve(AssembledSystem::vec& res,
                         const AssembledSystem& sys,
                         const AssembledSystem::vec& rhs) const {

	assert( res.size() == sys.size() );
	assert( rhs.size() == sys.size() );

	vec Pv = (sys.P * rhs.head(sys.m));

	// in place solve
	Pv = pimpl->Hinv.solve( Pv );

	res.head( sys.m ) = sys.P * Pv;

	if( sys.n ) {
		vec tmp = rhs.tail( sys.n ) - pimpl->HinvPJT.transpose() * rhs.head( sys.m );

		// lambdas
		res.tail( sys.n ) = pimpl->schur.solve( tmp );

		// constraint forces
		res.head( sys.m ) += sys.P * (pimpl->HinvPJT * res.tail( sys.n));
	}

}

}
}
}

<|endoftext|>


<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// RoboSimian on granular terrain
//
// =============================================================================

#include <cmath>
#include <cstdio>
#include <vector>

#include "chrono/core/ChFileutils.h"
#include "chrono/utils/ChUtilsInputOutput.h"

#include "chrono_parallel/physics/ChSystemParallel.h"

#include "chrono_vehicle/terrain/GranularTerrain.h"

#include "chrono_opengl/ChOpenGLWindow.h"

#include "robosimian.h"

using namespace chrono;
using namespace chrono::collision;

// Integration step size
double step_size = 1e-4;

// OpenGL rendering?
bool render = true;

// Time interval between two render frames
double render_step_size = 1.0 / 50;  // FPS = 50

// Drop the robot on terrain
bool drop = true;

// Timed events
double time_create_terrain = 0.5;
double duration_settle_terrain = 1.0;
double time_release = time_create_terrain + duration_settle_terrain;
double duration_settle_robot = 0.5;
double time_offset = time_release + duration_settle_robot;
double duration_sim = 10;
double time_end = time_offset + duration_sim;

// Output directories
const std::string out_dir = GetChronoOutputPath() + "ROBOSIMIAN_PAR";
const std::string pov_dir = out_dir + "/POVRAY";

// POV-Ray output
bool povray_output = false;

// =============================================================================

class RobotDriverCallback : public robosimian::Driver::PhaseChangeCallback {
  public:
    RobotDriverCallback(robosimian::RoboSimian* robot) : m_robot(robot), m_start_x(0), m_start_time(0) {}
    virtual void OnPhaseChange(robosimian::Driver::Phase old_phase, robosimian::Driver::Phase new_phase) override;

    double GetDistance() const { return m_robot->GetChassisPos().x() - m_start_x; }
    double GetDuration() const { return m_robot->GetSystem()->GetChTime() - m_start_time; }
    double GetAvgSpeed() const { return GetDistance() / GetDuration(); }

    double m_start_x;
    double m_start_time;

  private:
    robosimian::RoboSimian* m_robot;
};

void RobotDriverCallback::OnPhaseChange(robosimian::Driver::Phase old_phase, robosimian::Driver::Phase new_phase) {
    if (new_phase == robosimian::Driver::CYCLE && old_phase != robosimian::Driver::CYCLE) {
        m_start_x = m_robot->GetChassisPos().x();
        m_start_time = m_robot->GetSystem()->GetChTime();
    }
}

// =============================================================================

double CreateTerrain(ChSystem& sys, double x, double z) {
    double r_g = 0.0075;
    double rho_g = 2000;
    double coh = 400e3;
    double area = CH_C_PI * r_g * r_g;
    double coh_force = area * coh;
    double coh_g = coh_force * step_size;

    std::cout << "x = " << x << "  z = " << z << std::endl;

    double length = 6;
    double width = 3;
    unsigned int num_layers = 5;
    ChVector<> center(length / 2 + x - 1.5, 0, z - num_layers * 2.1 * r_g);

    vehicle::GranularTerrain terrain(&sys);
    terrain.SetContactFrictionCoefficient(0.7f);
    terrain.SetContactCohesion((float)coh_g);
    terrain.SetCollisionEnvelope(0.1 * r_g / 5);

    terrain.EnableVisualization(true);
    terrain.Initialize(center, length, width, num_layers, r_g, rho_g);

    std::cout << "Generated " << terrain.GetNumParticles() << " particles";

    return (length + x - 2 * 1.5);
}

// =============================================================================

int main(int argc, char* argv[]) {
    // -------------
    // Create system
    // -------------

    ////ChSystemParallelSMC my_sys;
    ChSystemParallelNSC my_sys;
    my_sys.Set_G_acc(ChVector<double>(0, 0, -9.8));
    ////my_sys.Set_G_acc(ChVector<double>(0, 0, 0));

    int threads = 2;
    int max_threads = CHOMPfunctions::GetNumProcs();
    if (threads > max_threads)
        threads = max_threads;
    my_sys.SetParallelThreadNumber(threads);
    CHOMPfunctions::SetNumThreads(threads);

    my_sys.GetSettings()->solver.tolerance = 1e-3;
    my_sys.GetSettings()->solver.solver_mode = SolverMode::SLIDING;
    my_sys.GetSettings()->solver.max_iteration_normal = 0;
    my_sys.GetSettings()->solver.max_iteration_sliding = 100;
    my_sys.GetSettings()->solver.max_iteration_spinning = 0;
    my_sys.GetSettings()->solver.max_iteration_bilateral = 100;
    my_sys.GetSettings()->solver.compute_N = false;
    my_sys.GetSettings()->solver.alpha = 0;
    my_sys.GetSettings()->solver.cache_step_length = true;
    my_sys.GetSettings()->solver.use_full_inertia_tensor = false;
    my_sys.GetSettings()->solver.contact_recovery_speed = 1000;
    my_sys.GetSettings()->solver.bilateral_clamp_speed = 1e8;
    my_sys.GetSettings()->min_threads = threads;

    my_sys.GetSettings()->collision.collision_envelope = 0.01;
    my_sys.GetSettings()->collision.narrowphase_algorithm = NarrowPhaseType::NARROWPHASE_HYBRID_MPR;

    my_sys.ChangeSolverType(SolverType::BB);

    // -----------------------
    // Create RoboSimian robot
    // -----------------------

    robosimian::RoboSimian robot(&my_sys, true, true);

    // Ensure wheels are actuated in ANGLE mode (required for Chrono::Parallel)
    robot.SetMotorActuationMode(robosimian::ActuationMode::ANGLE);

    ////robot.Initialize(ChCoordsys<>(ChVector<>(0, 0, 0), QUNIT));
    robot.Initialize(ChCoordsys<>(ChVector<>(0, 0, 0), Q_from_AngX(CH_C_PI)));

    robot.SetVisualizationTypeChassis(robosimian::VisualizationType::MESH);
    robot.SetVisualizationTypeSled(robosimian::VisualizationType::MESH);
    robot.SetVisualizationTypeLimbs(robosimian::VisualizationType::MESH);

    // -----------------------------------
    // Create a driver and attach to robot
    // -----------------------------------

    ////auto driver = std::make_shared<robosimian::Driver>(
    ////    "",                                                           // start input file
    ////    GetChronoDataFile("robosimian/actuation/walking_cycle.txt"),  // cycle input file
    ////    "",                                                           // stop input file
    ////    true);
    ////auto driver = std::make_shared<robosimian::Driver>(
    ////    GetChronoDataFile("robosimian/actuation/sculling_start.txt"),  // start input file
    ////    GetChronoDataFile("robosimian/actuation/sculling_cycle.txt"),  // cycle input file
    ////    GetChronoDataFile("robosimian/actuation/sculling_stop.txt"),   // stop input file
    ////    true);
    ////auto driver = std::make_shared<robosimian::Driver>(
    ////    GetChronoDataFile("robosimian/actuation/inchworming_start.txt"),  // start input file
    ////    GetChronoDataFile("robosimian/actuation/inchworming_cycle.txt"),  // cycle input file
    ////    GetChronoDataFile("robosimian/actuation/inchworming_stop.txt"),   // stop input file
    ////    true);
    auto driver = std::make_shared<robosimian::Driver>(
        GetChronoDataFile("robosimian/actuation/driving_start.txt"),  // start input file
        GetChronoDataFile("robosimian/actuation/driving_cycle.txt"),  // cycle input file
        GetChronoDataFile("robosimian/actuation/driving_stop.txt"),   // stop input file
        true);

    RobotDriverCallback cbk(&robot);
    driver->RegisterPhaseChangeCallback(&cbk);

    driver->SetOffset(time_offset);
    robot.SetDriver(driver);

    // -----------------
    // Initialize OpenGL
    // -----------------

    if (render) {
        opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
        gl_window.Initialize(1280, 720, "RoboSimian", &my_sys);
        gl_window.SetCamera(ChVector<>(2, -2, 0), ChVector<>(0, 0, 0), ChVector<>(0, 0, 1), 0.05f);
        gl_window.SetRenderMode(opengl::WIREFRAME);
    }

    // -----------------------------
    // Initialize output directories
    // -----------------------------

    if (ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
        std::cout << "Error creating directory " << out_dir << std::endl;
        return 1;
    }
    if (povray_output) {
        if (ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
            std::cout << "Error creating directory " << pov_dir << std::endl;
            return 1;
        }
    }

    // ---------------------------------
    // Run simulation for specified time
    // ---------------------------------

    int render_steps = (int)std::ceil(render_step_size / step_size);
    int sim_frame = 0;
    int render_frame = 0;

    bool terrain_created = false;
    bool robot_released = false;
    double x_max = 0;

    while (true) {
        double time = my_sys.GetChTime();
        double x = robot.GetChassisPos().x();

        if (time >= time_end) {
            std::cout << "Reached final time: " << time << std::endl;
            break;
        }

        if (drop) {
            if (!terrain_created && time > time_create_terrain) {
                // Robot position and bottom point
                double z = robot.GetWheelPos(robosimian::FR).z() - 0.15;
                // Create terrain
                std::cout << "Time: " << time << "  CREATE TERRAIN" << std::endl;
                x_max = CreateTerrain(my_sys, x, z);
                terrain_created = true;
            }
            if (!robot_released && time > time_release) {
                std::cout << "Time: " << time << "  RELEASE ROBOT" << std::endl;
                robot.GetChassis()->GetBody()->SetBodyFixed(false);
                robot_released = true;
            }

            if (robot_released && x > x_max) {
                std::cout << "Time: " << time << " Reached maximum distance" << std::endl;
                break;
            }
        }

        // Output POV-Ray data
        if (povray_output && sim_frame % render_steps == 0) {
            char filename[100];
            sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
            utils::WriteShapesPovray(&my_sys, filename);
            render_frame++;
        }

        ////double time = my_sys.GetChTime();
        ////double A = CH_C_PI / 6;
        ////double freq = 2;
        ////double val = 0.5 * A * (1 - std::cos(CH_C_2PI * freq * time));
        ////robot.Activate(robosimian::FR, "joint2", time, val);
        ////robot.Activate(robosimian::RL, "joint5", time, val);
        ////robot.Activate(robosimian::FL, "joint8", time, -0.4 * time);

        robot.DoStepDynamics(step_size);

        ////if (my_sys.GetNcontacts() > 0) {
        ////    robot.ReportContacts();
        ////}

        if (render) {
            opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
            if (gl_window.Active()) {
                gl_window.Render();
            } else {
                break;
            }
        }

        sim_frame++;
    }

    return 0;
}
<commit_msg>Properly set number of bins and collision envelope for RoboSimian parallel test<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// RoboSimian on granular terrain
//
// =============================================================================

#include <cmath>
#include <cstdio>
#include <vector>

#include "chrono/core/ChFileutils.h"
#include "chrono/utils/ChUtilsInputOutput.h"

#include "chrono_parallel/physics/ChSystemParallel.h"

#include "chrono_vehicle/terrain/GranularTerrain.h"

#include "chrono_opengl/ChOpenGLWindow.h"

#include "robosimian.h"

using namespace chrono;
using namespace chrono::collision;

// Integration step size
double step_size = 1e-4;

// OpenGL rendering?
bool render = true;

// Time interval between two render frames
double render_step_size = 1.0 / 50;  // FPS = 50

// Drop the robot on terrain
bool drop = true;

// Timed events
double time_create_terrain = 0.5;
double duration_settle_terrain = 1.0;
double time_release = time_create_terrain + duration_settle_terrain;
double duration_settle_robot = 0.5;
double time_offset = time_release + duration_settle_robot;
double duration_sim = 10;
double time_end = time_offset + duration_sim;

// Output directories
const std::string out_dir = GetChronoOutputPath() + "ROBOSIMIAN_PAR";
const std::string pov_dir = out_dir + "/POVRAY";

// POV-Ray output
bool povray_output = false;

// =============================================================================

class RobotDriverCallback : public robosimian::Driver::PhaseChangeCallback {
  public:
    RobotDriverCallback(robosimian::RoboSimian* robot) : m_robot(robot), m_start_x(0), m_start_time(0) {}
    virtual void OnPhaseChange(robosimian::Driver::Phase old_phase, robosimian::Driver::Phase new_phase) override;

    double GetDistance() const { return m_robot->GetChassisPos().x() - m_start_x; }
    double GetDuration() const { return m_robot->GetSystem()->GetChTime() - m_start_time; }
    double GetAvgSpeed() const { return GetDistance() / GetDuration(); }

    double m_start_x;
    double m_start_time;

  private:
    robosimian::RoboSimian* m_robot;
};

void RobotDriverCallback::OnPhaseChange(robosimian::Driver::Phase old_phase, robosimian::Driver::Phase new_phase) {
    if (new_phase == robosimian::Driver::CYCLE && old_phase != robosimian::Driver::CYCLE) {
        m_start_x = m_robot->GetChassisPos().x();
        m_start_time = m_robot->GetSystem()->GetChTime();
    }
}

// =============================================================================

double CreateTerrain(ChSystemParallel& sys, double x, double z) {
    double r_g = 0.0075;
    double rho_g = 2000;
    double coh = 400e3;
    double area = CH_C_PI * r_g * r_g;
    double coh_force = area * coh;
    double coh_g = coh_force * step_size;

    std::cout << "x = " << x << "  z = " << z << std::endl;

    double length = 6;
    double width = 3;
    unsigned int num_layers = 5;
    ChVector<> center(length / 2 + x - 1.5, 0, z - num_layers * 2.1 * r_g);

    vehicle::GranularTerrain terrain(&sys);
    terrain.SetContactFrictionCoefficient(0.7f);
    terrain.SetContactCohesion((float)coh_g);
    terrain.SetCollisionEnvelope(0.1 * r_g / 5);

    terrain.EnableVisualization(true);
    terrain.Initialize(center, length, width, num_layers, r_g, rho_g);

    std::cout << "Generated " << terrain.GetNumParticles() << " particles" << std::endl;

    // Estimate number of bins for collision detection
    int factor = 2;
    int binsX = (int)std::ceil((0.5 * length) / r_g) / factor;
    int binsY = (int)std::ceil((0.5 * width) / r_g) / factor;
    int binsZ = 1;
    sys.GetSettings()->collision.bins_per_axis = vec3(binsX, binsY, binsZ);
    std::cout << " broad-phase bins: " << binsX << " x " << binsY << " x " << binsZ << std::endl;

    // Set collision envelope
    sys.GetSettings()->collision.collision_envelope = 0.1 * r_g / 5;

    return (length + x - 2 * 1.5);
}

// =============================================================================

int main(int argc, char* argv[]) {
    // -------------
    // Create system
    // -------------

    ////ChSystemParallelSMC my_sys;
    ChSystemParallelNSC my_sys;
    my_sys.Set_G_acc(ChVector<double>(0, 0, -9.8));
    ////my_sys.Set_G_acc(ChVector<double>(0, 0, 0));

    int threads = 2;
    int max_threads = CHOMPfunctions::GetNumProcs();
    if (threads > max_threads)
        threads = max_threads;
    my_sys.SetParallelThreadNumber(threads);
    CHOMPfunctions::SetNumThreads(threads);

    my_sys.GetSettings()->solver.tolerance = 1e-3;
    my_sys.GetSettings()->solver.solver_mode = SolverMode::SLIDING;
    my_sys.GetSettings()->solver.max_iteration_normal = 0;
    my_sys.GetSettings()->solver.max_iteration_sliding = 100;
    my_sys.GetSettings()->solver.max_iteration_spinning = 0;
    my_sys.GetSettings()->solver.max_iteration_bilateral = 100;
    my_sys.GetSettings()->solver.compute_N = false;
    my_sys.GetSettings()->solver.alpha = 0;
    my_sys.GetSettings()->solver.cache_step_length = true;
    my_sys.GetSettings()->solver.use_full_inertia_tensor = false;
    my_sys.GetSettings()->solver.contact_recovery_speed = 1000;
    my_sys.GetSettings()->solver.bilateral_clamp_speed = 1e8;
    my_sys.GetSettings()->min_threads = threads;

    my_sys.GetSettings()->collision.collision_envelope = 0.01;
    my_sys.GetSettings()->collision.narrowphase_algorithm = NarrowPhaseType::NARROWPHASE_HYBRID_MPR;

    my_sys.ChangeSolverType(SolverType::BB);

    // -----------------------
    // Create RoboSimian robot
    // -----------------------

    robosimian::RoboSimian robot(&my_sys, true, true);

    // Ensure wheels are actuated in ANGLE mode (required for Chrono::Parallel)
    robot.SetMotorActuationMode(robosimian::ActuationMode::ANGLE);

    ////robot.Initialize(ChCoordsys<>(ChVector<>(0, 0, 0), QUNIT));
    robot.Initialize(ChCoordsys<>(ChVector<>(0, 0, 0), Q_from_AngX(CH_C_PI)));

    robot.SetVisualizationTypeChassis(robosimian::VisualizationType::MESH);
    robot.SetVisualizationTypeSled(robosimian::VisualizationType::MESH);
    robot.SetVisualizationTypeLimbs(robosimian::VisualizationType::MESH);

    // -----------------------------------
    // Create a driver and attach to robot
    // -----------------------------------

    ////auto driver = std::make_shared<robosimian::Driver>(
    ////    "",                                                           // start input file
    ////    GetChronoDataFile("robosimian/actuation/walking_cycle.txt"),  // cycle input file
    ////    "",                                                           // stop input file
    ////    true);
    ////auto driver = std::make_shared<robosimian::Driver>(
    ////    GetChronoDataFile("robosimian/actuation/sculling_start.txt"),  // start input file
    ////    GetChronoDataFile("robosimian/actuation/sculling_cycle.txt"),  // cycle input file
    ////    GetChronoDataFile("robosimian/actuation/sculling_stop.txt"),   // stop input file
    ////    true);
    ////auto driver = std::make_shared<robosimian::Driver>(
    ////    GetChronoDataFile("robosimian/actuation/inchworming_start.txt"),  // start input file
    ////    GetChronoDataFile("robosimian/actuation/inchworming_cycle.txt"),  // cycle input file
    ////    GetChronoDataFile("robosimian/actuation/inchworming_stop.txt"),   // stop input file
    ////    true);
    auto driver = std::make_shared<robosimian::Driver>(
        GetChronoDataFile("robosimian/actuation/driving_start.txt"),  // start input file
        GetChronoDataFile("robosimian/actuation/driving_cycle.txt"),  // cycle input file
        GetChronoDataFile("robosimian/actuation/driving_stop.txt"),   // stop input file
        true);

    RobotDriverCallback cbk(&robot);
    driver->RegisterPhaseChangeCallback(&cbk);

    driver->SetOffset(time_offset);
    robot.SetDriver(driver);

    // -----------------
    // Initialize OpenGL
    // -----------------

    if (render) {
        opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
        gl_window.Initialize(1280, 720, "RoboSimian", &my_sys);
        gl_window.SetCamera(ChVector<>(2, -2, 0), ChVector<>(0, 0, 0), ChVector<>(0, 0, 1), 0.05f);
        gl_window.SetRenderMode(opengl::WIREFRAME);
    }

    // -----------------------------
    // Initialize output directories
    // -----------------------------

    if (ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
        std::cout << "Error creating directory " << out_dir << std::endl;
        return 1;
    }
    if (povray_output) {
        if (ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
            std::cout << "Error creating directory " << pov_dir << std::endl;
            return 1;
        }
    }

    // ---------------------------------
    // Run simulation for specified time
    // ---------------------------------

    int render_steps = (int)std::ceil(render_step_size / step_size);
    int sim_frame = 0;
    int render_frame = 0;

    bool terrain_created = false;
    bool robot_released = false;
    double x_max = 0;

    while (true) {
        double time = my_sys.GetChTime();
        double x = robot.GetChassisPos().x();

        if (time >= time_end) {
            std::cout << "Reached final time: " << time << std::endl;
            break;
        }

        if (drop) {
            if (!terrain_created && time > time_create_terrain) {
                // Robot position and bottom point
                double z = robot.GetWheelPos(robosimian::FR).z() - 0.15;
                // Create terrain
                std::cout << "Time: " << time << "  CREATE TERRAIN" << std::endl;
                x_max = CreateTerrain(my_sys, x, z);
                terrain_created = true;
            }
            if (!robot_released && time > time_release) {
                std::cout << "Time: " << time << "  RELEASE ROBOT" << std::endl;
                robot.GetChassis()->GetBody()->SetBodyFixed(false);
                robot_released = true;
            }

            if (robot_released && x > x_max) {
                std::cout << "Time: " << time << " Reached maximum distance" << std::endl;
                break;
            }
        }

        // Output POV-Ray data
        if (povray_output && sim_frame % render_steps == 0) {
            char filename[100];
            sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
            utils::WriteShapesPovray(&my_sys, filename);
            render_frame++;
        }

        ////double time = my_sys.GetChTime();
        ////double A = CH_C_PI / 6;
        ////double freq = 2;
        ////double val = 0.5 * A * (1 - std::cos(CH_C_2PI * freq * time));
        ////robot.Activate(robosimian::FR, "joint2", time, val);
        ////robot.Activate(robosimian::RL, "joint5", time, val);
        ////robot.Activate(robosimian::FL, "joint8", time, -0.4 * time);

        robot.DoStepDynamics(step_size);

        ////if (my_sys.GetNcontacts() > 0) {
        ////    robot.ReportContacts();
        ////}

        if (render) {
            opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
            if (gl_window.Active()) {
                gl_window.Render();
            } else {
                break;
            }
        }

        sim_frame++;
    }

    return 0;
}
<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexLisp.cxx
 ** Lexer for Lisp.
 ** Written by Alexey Yutkin.
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static inline bool isLispoperator(char ch) {
	if (isascii(ch) && isalnum(ch))
		return false;
	if (ch == '\'' || ch == '(' || ch == ')' )
		return true;
	return false;
}

static inline bool isLispwordstart(char ch) {
	return isascii(ch) && ch != ';'  && !isspacechar(ch) && !isLispoperator(ch) &&
		ch != '\n' && ch != '\r' &&  ch != '\"';
}

static void classifyWordLisp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
	PLATFORM_ASSERT(end >= start);
	char s[100];
	unsigned int i;
	bool digit_flag = true;
	for (i = 0; (i < end - start + 1) && (i < 99); i++) {
		s[i] = styler[start + i];
		s[i + 1] = '\0';
		if (!isdigit(s[i]) && (s[i] != '.')) digit_flag = false;
	}
	char chAttr = SCE_LISP_IDENTIFIER;

	if(digit_flag) chAttr = SCE_LISP_NUMBER;
	else {
		if (keywords.InList(s)) {
			chAttr = SCE_LISP_KEYWORD;
		}
	}
	styler.ColourTo(end, chAttr);
	return;
}

static void ColouriseLispDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
                            Accessor &styler) {

	WordList &keywords = *keywordlists[0];

	styler.StartAt(startPos);

	int state = initStyle;
	char chNext = styler[startPos];
	unsigned int lengthDoc = startPos + length;
	styler.StartSegment(startPos);
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			i += 1;
			continue;
		}

		if (state == SCE_LISP_DEFAULT) {
			if (isLispwordstart(ch)) {
				styler.ColourTo(i - 1, state);
				state = SCE_LISP_IDENTIFIER;
			}
			else if (ch == ';') {
				styler.ColourTo(i - 1, state);
				state = SCE_LISP_COMMENT;
			}
			else if (isLispoperator(ch) || ch=='\'') {
				styler.ColourTo(i - 1, state);
				styler.ColourTo(i, SCE_LISP_OPERATOR);
			}
			else if (ch == '\"') {
				styler.ColourTo(i - 1, state);
				state = SCE_LISP_STRING;
			}
		} else if (state == SCE_LISP_IDENTIFIER) {
			if (!isLispwordstart(ch)) {
				classifyWordLisp(styler.GetStartSegment(), i - 1, keywords, styler);
				state = SCE_LISP_DEFAULT;
			} /*else*/
			if (isLispoperator(ch) || ch=='\'') {
				styler.ColourTo(i - 1, state);
				styler.ColourTo(i, SCE_LISP_OPERATOR);
			}

		} else {
			if (state == SCE_LISP_COMMENT) {
				if (atEOL) {
					styler.ColourTo(i - 1, state);
					state = SCE_LISP_DEFAULT;
				}
			} else if (state == SCE_LISP_STRING) {
				if (ch == '\\') {
					if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
						i++;
						chNext = styler.SafeGetCharAt(i + 1);
					}
				} else if (ch == '\"') {
					styler.ColourTo(i, state);
					state = SCE_LISP_DEFAULT;
				}
			}
		}

	}
	styler.ColourTo(lengthDoc - 1, state);
}

static void FoldLispDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
                            Accessor &styler) {
	unsigned int lengthDoc = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;
	char chNext = styler[startPos];
	int styleNext = styler.StyleAt(startPos);
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styleNext;
		styleNext = styler.StyleAt(i + 1);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
		if (style == SCE_LISP_OPERATOR) {
			if (ch == '(') {
				levelCurrent++;
			} else if (ch == ')') {
				levelCurrent--;
			}
		}
		if (atEOL) {
			int lev = levelPrev;
			if (visibleChars == 0)
				lev |= SC_FOLDLEVELWHITEFLAG;
			if ((levelCurrent > levelPrev) && (visibleChars > 0))
				lev |= SC_FOLDLEVELHEADERFLAG;
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelPrev = levelCurrent;
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;
	}
	// Fill in the real level of the next line, keeping the current flags as they will be filled in later
	int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
	styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}

static const char * const lispWordListDesc[] = {
	"Keywords",
	0
};

LexerModule lmLISP(SCLEX_LISP, ColouriseLispDoc, "lisp", FoldLispDoc, lispWordListDesc);
<commit_msg>Patch from Michael Goffioul to Lisp adds SYMBOL, SPECIAL, and MULTI_COMMENT states and a second keyword set.<commit_after>// Scintilla source code edit control
/** @file LexLisp.cxx
 ** Lexer for Lisp.
 ** Written by Alexey Yutkin.
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "StyleContext.h"

#define SCE_LISP_CHARACTER 29
#define SCE_LISP_MACRO 30
#define SCE_LISP_MACRO_DISPATCH 31

static inline bool isLispoperator(char ch) {
	if (isascii(ch) && isalnum(ch))
		return false;
	if (ch == '\'' || ch == '`' || ch == '(' || ch == ')' )
		return true;
	return false;
}

static inline bool isLispwordstart(char ch) {
	return isascii(ch) && ch != ';'  && !isspacechar(ch) && !isLispoperator(ch) &&
		ch != '\n' && ch != '\r' &&  ch != '\"';
}

static void classifyWordLisp(unsigned int start, unsigned int end, WordList &keywords, WordList &keywords_kw, Accessor &styler) {
	PLATFORM_ASSERT(end >= start);
	char s[100];
	unsigned int i;
	bool digit_flag = true;
	for (i = 0; (i < end - start + 1) && (i < 99); i++) {
		s[i] = styler[start + i];
		s[i + 1] = '\0';
		if (!isdigit(s[i]) && (s[i] != '.')) digit_flag = false;
	}
	char chAttr = SCE_LISP_IDENTIFIER;

	if(digit_flag) chAttr = SCE_LISP_NUMBER;
	else {
		if (keywords.InList(s)) {
			chAttr = SCE_LISP_KEYWORD;
		} else if (keywords_kw.InList(s)) {
			chAttr = SCE_LISP_KEYWORD_KW;
		} else if ((s[0] == '*' && s[i-1] == '*') ||
			   (s[0] == '+' && s[i-1] == '+')) {
			chAttr = SCE_LISP_SPECIAL;
		}
	}
	styler.ColourTo(end, chAttr);
	return;
}

static void ColouriseLispDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
                            Accessor &styler) {

	WordList &keywords = *keywordlists[0];
	WordList &keywords_kw = *keywordlists[1];

	styler.StartAt(startPos);

	int state = initStyle, radix = -1;
	char chNext = styler[startPos];
	unsigned int lengthDoc = startPos + length;
	styler.StartSegment(startPos);
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			i += 1;
			continue;
		}

		if (state == SCE_LISP_DEFAULT) {
			if (ch == '#') {
				styler.ColourTo(i - 1, state);
				radix = -1;
				state = SCE_LISP_MACRO_DISPATCH;
			} else if (isLispwordstart(ch)) {
				styler.ColourTo(i - 1, state);
				state = SCE_LISP_IDENTIFIER;
			}
			else if (ch == ';') {
				styler.ColourTo(i - 1, state);
				state = SCE_LISP_COMMENT;
			}
			else if (isLispoperator(ch) || ch=='\'') {
				styler.ColourTo(i - 1, state);
				styler.ColourTo(i, SCE_LISP_OPERATOR);
				if (ch=='\'' && isLispwordstart(chNext)) {
					state = SCE_LISP_SYMBOL;
				}
			}
			else if (ch == '\"') {
				styler.ColourTo(i - 1, state);
				state = SCE_LISP_STRING;
			}
		} else if (state == SCE_LISP_IDENTIFIER || state == SCE_LISP_SYMBOL) {
			if (!isLispwordstart(ch)) {
				if (state == SCE_LISP_IDENTIFIER) {
					classifyWordLisp(styler.GetStartSegment(), i - 1, keywords, keywords_kw, styler);
				} else {
					styler.ColourTo(i - 1, state);
				}
				state = SCE_LISP_DEFAULT;
			} /*else*/
			if (isLispoperator(ch) || ch=='\'') {
				styler.ColourTo(i - 1, state);
				styler.ColourTo(i, SCE_LISP_OPERATOR);
				if (ch=='\'' && isLispwordstart(chNext)) {
					state = SCE_LISP_SYMBOL;
				}
			}
		} else if (state == SCE_LISP_MACRO_DISPATCH) {
			if (!isdigit(ch)) {
				if (ch != 'r' && ch != 'R' && (i - styler.GetStartSegment()) > 1) {
					state = SCE_LISP_DEFAULT;
				} else {
					switch (ch) {
						case '|': state = SCE_LISP_MULTI_COMMENT; break;
						case 'o':
						case 'O': radix = 8; state = SCE_LISP_MACRO; break;
						case 'x':
						case 'X': radix = 16; state = SCE_LISP_MACRO; break;
						case 'b':
						case 'B': radix = 2; state = SCE_LISP_MACRO; break;
						case '\\': state = SCE_LISP_CHARACTER; break;
						case ':':
						case '-':
						case '+': state = SCE_LISP_MACRO; break;
						case '\'': if (isLispwordstart(chNext)) {
								   state = SCE_LISP_SPECIAL;
							   } else {
								   styler.ColourTo(i - 1, SCE_LISP_DEFAULT);
								   styler.ColourTo(i, SCE_LISP_OPERATOR);
								   state = SCE_LISP_DEFAULT;
							   }
							   break;
						default: if (isLispoperator(ch)) {
								 styler.ColourTo(i - 1, SCE_LISP_DEFAULT);
								 styler.ColourTo(i, SCE_LISP_OPERATOR);
							 }
							 state = SCE_LISP_DEFAULT;
							 break;
					}
				}
			}
		} else if (state == SCE_LISP_MACRO) {
			if (isLispwordstart(ch) && (radix == -1 || IsADigit(ch, radix))) {
				state = SCE_LISP_SPECIAL;
			} else {
				state = SCE_LISP_DEFAULT;
			}
		} else if (state == SCE_LISP_CHARACTER) {
			if (isLispoperator(ch)) {
				styler.ColourTo(i, SCE_LISP_SPECIAL);
				state = SCE_LISP_DEFAULT;
			} else if (isLispwordstart(ch)) {
				styler.ColourTo(i, SCE_LISP_SPECIAL);
				state = SCE_LISP_SPECIAL;
			} else {
				state = SCE_LISP_DEFAULT;
			}
		} else if (state == SCE_LISP_SPECIAL) {
			if (!isLispwordstart(ch) || (radix != -1 && !IsADigit(ch, radix))) {
				styler.ColourTo(i - 1, state);
				state = SCE_LISP_DEFAULT;
			}
			if (isLispoperator(ch) || ch=='\'') {
				styler.ColourTo(i - 1, state);
				styler.ColourTo(i, SCE_LISP_OPERATOR);
				if (ch=='\'' && isLispwordstart(chNext)) {
					state = SCE_LISP_SYMBOL;
				}
			}
		} else {
			if (state == SCE_LISP_COMMENT) {
				if (atEOL) {
					styler.ColourTo(i - 1, state);
					state = SCE_LISP_DEFAULT;
				}
			} else if (state == SCE_LISP_MULTI_COMMENT) {
				if (ch == '|' && chNext == '#') {
					i++;
					chNext = styler.SafeGetCharAt(i + 1);
					styler.ColourTo(i, state);
					state = SCE_LISP_DEFAULT;
				}
			} else if (state == SCE_LISP_STRING) {
				if (ch == '\\') {
					if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
						i++;
						chNext = styler.SafeGetCharAt(i + 1);
					}
				} else if (ch == '\"') {
					styler.ColourTo(i, state);
					state = SCE_LISP_DEFAULT;
				}
			}
		}

	}
	styler.ColourTo(lengthDoc - 1, state);
}

static void FoldLispDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
                            Accessor &styler) {
	unsigned int lengthDoc = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;
	char chNext = styler[startPos];
	int styleNext = styler.StyleAt(startPos);
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styleNext;
		styleNext = styler.StyleAt(i + 1);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
		if (style == SCE_LISP_OPERATOR) {
			if (ch == '(') {
				levelCurrent++;
			} else if (ch == ')') {
				levelCurrent--;
			}
		}
		if (atEOL) {
			int lev = levelPrev;
			if (visibleChars == 0)
				lev |= SC_FOLDLEVELWHITEFLAG;
			if ((levelCurrent > levelPrev) && (visibleChars > 0))
				lev |= SC_FOLDLEVELHEADERFLAG;
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelPrev = levelCurrent;
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;
	}
	// Fill in the real level of the next line, keeping the current flags as they will be filled in later
	int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
	styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}

static const char * const lispWordListDesc[] = {
	"Functions and special operators",
	"Keywords",
	0
};

LexerModule lmLISP(SCLEX_LISP, ColouriseLispDoc, "lisp", FoldLispDoc, lispWordListDesc);
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Library
  Module:    MergePts.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "MergePts.hh"

// Description:
// Merge points together if they are exactly coincident. Return a list
// that maps unmerged point ids into new point ids. User is responsible
// for freeing list (use delete []).
int *vlMergePoints::MergePoints()
{
  float *bounds;
  int ptId, i, j;
  int numPts;
  int *index;
  int newPtId;
  float *pt, *p;
  int ijk[3];
  int cno;
  vlIdList *ptIds;

  vlDebugMacro(<<"Merging points");

  if ( this->Points == NULL ||
  (numPts=this->Points->GetNumberOfPoints()) < 1 ) return NULL;

  this->SubDivide(); // subdivides if necessary

  bounds = this->Points->GetBounds();

  index = new int[numPts];
  for (i=0; i < numPts; i++) index[i] = -1;

  newPtId = 0; // renumbering points
//
//  Traverse each point, find bucket that point is in, check the list of
//  points in that bucket for merging.  Also need to search all
//  neighboring buckets within the tolerance.  The number and level of
//  neighbors to search depends upon the tolerance and the bucket width.
//
  for ( i=0; i < numPts; i++ ) //loop over all points
    {
    // Only try to merge the point if it hasn't yet been merged.
    if ( index[i] == -1 )
      {
      p = this->Points->GetPoint(i);
      index[i] = newPtId;

      for (j=0; j<3; j++)
        ijk[j] = (int) ((float)((p[j] - bounds[2*j])*0.999 /
                      (bounds[2*j+1] - bounds[2*j])) * this->Divisions[j]);

      cno = ijk[0] + ijk[1]*this->Divisions[0] +
            ijk[2]*this->Divisions[0]*this->Divisions[1];

      if ( (ptIds = this->HashTable[cno]) != NULL )
        {
        for (j=0; j < ptIds->GetNumberOfIds(); j++)
          {
          ptId = ptIds->GetId(j);
          pt = this->Points->GetPoint(ptId);

          if ( index[ptId] == -1 && pt[0] == p[0] && pt[1] == p[1]
          && pt[2] == p[2] )
            {
            index[ptId] = newPtId;
            }
          }
        }
      newPtId++;
      } // if point hasn't been merged
    } // for all points

  return index;
}

// Description:
// Incrementally insert a point into search structure, merging the point
// with pre-inserted point (if precisely coincident). If point is merged
// with pre-inserted point, pre-inserted point id is returned. Otherwise,
// new point id is returned. Before using this method you must make sure
// that newPts have been supplied, the bounds has been set properly, and
// that divs are properly set. (See InitPointInsertion()).
int vlMergePoints::InsertPoint(float x[3])
{
  int i, ijk[3];
  int idx;
  vlIdList *bucket;
//
//  Locate bucket that point is in.
//
  for (i=0; i<3; i++)
    {
    ijk[i] = (int) ((float) ((x[i] - this->Bounds[2*i])*0.999 /
             (this->Bounds[2*i+1] - this->Bounds[2*i])) * this->Divisions[i]);
    }
  idx = ijk[0] + ijk[1]*this->Divisions[0] +
        ijk[2]*this->Divisions[0]*this->Divisions[1];

  bucket = this->HashTable[idx];

  if ( ! bucket )
    {
    bucket = new vlIdList(this->NumberOfPointsInBucket/2);
    this->HashTable[idx] = bucket;
    }
  else // see whether we've got duplicate point
    {
//
// Check the list of points in that bucket.
//
    int ptId;
    float *pt;

    for (i=0; i < bucket->GetNumberOfIds(); i++)
      {
      ptId = bucket->GetId(i);
      pt = this->Points->GetPoint(ptId);
      if ( x[0] == pt[0] && x[1] == pt[1] && x[2] == pt[2] ) return ptId;
      }
    }

  bucket->InsertNextId(this->InsertionPointId);
  this->Points->InsertPoint(this->InsertionPointId,x);

  return this->InsertionPointId++;
}

<commit_msg>ERR: Fixed zero width bug<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    MergePts.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "MergePts.hh"

// Description:
// Merge points together if they are exactly coincident. Return a list
// that maps unmerged point ids into new point ids. User is responsible
// for freeing list (use delete []).
int *vlMergePoints::MergePoints()
{
  int ptId, i, j;
  int numPts;
  int *index;
  int newPtId;
  float *pt, *p;
  int ijk[3];
  int cno;
  vlIdList *ptIds;

  vlDebugMacro(<<"Merging points");

  if ( this->Points == NULL ||
  (numPts=this->Points->GetNumberOfPoints()) < 1 ) return NULL;

  this->SubDivide(); // subdivides if necessary

  index = new int[numPts];
  for (i=0; i < numPts; i++) index[i] = -1;

  newPtId = 0; // renumbering points
//
//  Traverse each point, find bucket that point is in, check the list of
//  points in that bucket for merging.  Also need to search all
//  neighboring buckets within the tolerance.  The number and level of
//  neighbors to search depends upon the tolerance and the bucket width.
//
  for ( i=0; i < numPts; i++ ) //loop over all points
    {
    // Only try to merge the point if it hasn't yet been merged.
    if ( index[i] == -1 )
      {
      p = this->Points->GetPoint(i);
      index[i] = newPtId;

      for (j=0; j<3; j++)
        ijk[j] = (int) ((float)((p[j] - this->Bounds[2*j])*0.999 /
              (this->Bounds[2*j+1] - this->Bounds[2*j])) * this->Divisions[j]);

      cno = ijk[0] + ijk[1]*this->Divisions[0] +
            ijk[2]*this->Divisions[0]*this->Divisions[1];

      if ( (ptIds = this->HashTable[cno]) != NULL )
        {
        for (j=0; j < ptIds->GetNumberOfIds(); j++)
          {
          ptId = ptIds->GetId(j);
          pt = this->Points->GetPoint(ptId);

          if ( index[ptId] == -1 && pt[0] == p[0] && pt[1] == p[1]
          && pt[2] == p[2] )
            {
            index[ptId] = newPtId;
            }
          }
        }
      newPtId++;
      } // if point hasn't been merged
    } // for all points

  return index;
}

// Description:
// Incrementally insert a point into search structure, merging the point
// with pre-inserted point (if precisely coincident). If point is merged
// with pre-inserted point, pre-inserted point id is returned. Otherwise,
// new point id is returned. Before using this method you must make sure
// that newPts have been supplied, the bounds has been set properly, and
// that divs are properly set. (See InitPointInsertion()).
int vlMergePoints::InsertPoint(float x[3])
{
  int i, ijk[3];
  int idx;
  vlIdList *bucket;
//
//  Locate bucket that point is in.
//
  for (i=0; i<3; i++)
    {
    ijk[i] = (int) ((float) ((x[i] - this->Bounds[2*i])*0.999 /
             (this->Bounds[2*i+1] - this->Bounds[2*i])) * this->Divisions[i]);
    }
  idx = ijk[0] + ijk[1]*this->Divisions[0] +
        ijk[2]*this->Divisions[0]*this->Divisions[1];

  bucket = this->HashTable[idx];

  if ( ! bucket )
    {
    bucket = new vlIdList(this->NumberOfPointsInBucket/2);
    this->HashTable[idx] = bucket;
    }
  else // see whether we've got duplicate point
    {
//
// Check the list of points in that bucket.
//
    int ptId;
    float *pt;

    for (i=0; i < bucket->GetNumberOfIds(); i++)
      {
      ptId = bucket->GetId(i);
      pt = this->Points->GetPoint(ptId);
      if ( x[0] == pt[0] && x[1] == pt[1] && x[2] == pt[2] ) return ptId;
      }
    }

  bucket->InsertNextId(this->InsertionPointId);
  this->Points->InsertPoint(this->InsertionPointId,x);

  return this->InsertionPointId++;
}

<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Modified by Cloudius Systems.
 * Copyright 2015 Cloudius Systems.
 */

#pragma once

#include "streaming/messages/stream_message.hh"

namespace streaming {
namespace messages {

class session_failed_message : public stream_message {
#if 0
    public static Serializer<SessionFailedMessage> serializer = new Serializer<SessionFailedMessage>()
    {
        public SessionFailedMessage deserialize(ReadableByteChannel in, int version, StreamSession session) throws IOException
        {
            return new SessionFailedMessage();
        }

        public void serialize(SessionFailedMessage message, DataOutputStreamAndChannel out, int version, StreamSession session) throws IOException {}
    };

    public SessionFailedMessage()
    {
        super(Type.SESSION_FAILED);
    }

    @Override
    public String toString()
    {
        return "Session Failed";
    }
#endif
public:
    void serialize(bytes::iterator& out) const {
    }
    static session_failed_message deserialize(bytes_view& v) {
        return session_failed_message();
    }
    size_t serialized_size() const {
        return 0;
    }
};

} // namespace messages
} // namespace streaming
<commit_msg>streaming: Add message type for session_failed_message<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Modified by Cloudius Systems.
 * Copyright 2015 Cloudius Systems.
 */

#pragma once

#include "streaming/messages/stream_message.hh"

namespace streaming {
namespace messages {

class session_failed_message : public stream_message {
#if 0
    public static Serializer<SessionFailedMessage> serializer = new Serializer<SessionFailedMessage>()
    {
        public SessionFailedMessage deserialize(ReadableByteChannel in, int version, StreamSession session) throws IOException
        {
            return new SessionFailedMessage();
        }

        public void serialize(SessionFailedMessage message, DataOutputStreamAndChannel out, int version, StreamSession session) throws IOException {}
    };
#endif

    session_failed_message() : stream_message(stream_message::Type::SESSION_FAILED) { }

#if 0
    @Override
    public String toString()
    {
        return "Session Failed";
    }
#endif
public:
    void serialize(bytes::iterator& out) const {
    }
    static session_failed_message deserialize(bytes_view& v) {
        return session_failed_message();
    }
    size_t serialized_size() const {
        return 0;
    }
};

} // namespace messages
} // namespace streaming
<|endoftext|>