<commit_before>#include "core.h"
#include <vector>

void IgnoreDecl();				// 忽略xml声明
void IgnoreValid();				// 忽略文档验证信息
void IgnoreComment();			// 忽略xml注释

int Look;						// 碗
FILE *File = NULL;				// 锅

struct Attrib_st {
	std::string attrib_name;
	std::string attrib_value;
};

typedef std::vector<Attrib_st> Attribs;
typedef std::vector<Node_st> Nodes;

struct Node_st {
	std::string elem_name;
	std::string elem_value;
	Attribs attribs;
	Nodes childs;
} XML;

Node_st* Parse(const char* file) {
	Init(file);
	GetElement(&XML);
	fclose(File);
	if (!XML.childs.empty()) {
		return &XML.childs[0];
	}
	else {
		return NULL;
	}
}

void Init(const char* file) {
	// 开锅
	File = fopen(file, "rb");
	if (File == NULL) {
		Expected("File open normally");
	}
	// 先捞一碗
	GetChar();
	// 过滤老鼠屎
	SkipWhite();
}

void GetElement(Node_st *parent) {
	std::string elem_name, elem_value;
	do {
		Node_st node;
		Match('<');
		while (Ignored()) {
			Match('<');
		}
		node.elem_name = GetElemName();
		while (Look != '/' && Look != '>') {
			// 解析属性
			GetAttrib(&node);
		}
		if (Look == '/') {
			Match('/');
			Match('>');
		}
		else if (Look == '>') {
			Match('>');
			if (Look != '<') {
				node.elem_value.append(GetElemValue());
			}
			fpos_t pos;
			fgetpos(File, &pos);
			Match('<');
			while (Ignored()) {
				if (Look != '<' && Look != EOF) {
					parent->elem_value.append(GetElemValue());
				}
				fgetpos(File, &pos);
				Match('<');
			}
			if (Look != '/') {
				// 子节点
				fsetpos(File, &pos);
				Look = '<';
				GetElement(&node);
				if (Look != '<') {
					parent->elem_value.append(GetElemValue());
				}
				Match('<');
				while (Ignored()) {
					if (Look != '<' && Look != EOF) {
						parent->elem_value.append(GetElemValue());
					}
					fgetpos(File, &pos);
					Match('<');
				}
			}

			Match('/');
			MatchString(node.elem_name.c_str());
			Match('>');
		}
		else {
			Expected("Closed Brackets needed");
		}
		parent->childs.push_back(node);

		if (Look != '<' && Look != EOF) {
			parent->elem_value.append(GetElemValue());
		}
		if (Look != EOF) {
			fpos_t pos;
			fgetpos(File, &pos);
			Match('<');
			while (Ignored()) {
				if (Look != '<' && Look != EOF) {
					parent->elem_value.append(GetElemValue());
				}
				if (Look != EOF) {
					fgetpos(File, &pos);
					Match('<');
				}
			}
			if (Look == EOF) {
				return;
			}
			if (Look != '/') {
				fsetpos(File, &pos);
				Look = '<';
			}
			else {
				fsetpos(File, &pos);
				Look = '<';
				break;
			}
		}

	} while (Look != EOF);
}

std::string GetElemName() {
	if (!isalpha(Look)) {
		Expected("Name");
	}
	char name[30] = {0};
	char *p = name;
	while (isalnum(Look) || (!isspace(Look) && (Look != '>'))) {
		*p = Look;
		p++;
		GetChar();
	}
	SkipWhite();
	return name;
}

std::string GetElemValue() {
	std::string elem_value;
	while (Look != '<') {
		elem_value.append(1, Look);
		GetChar();
	}
	return elem_value;
}

std::string GetAttribName() {
	if (!isalpha(Look)) {
		Expected("Name");
	}
	char name[30] = {0};
	char *p = name;
	while (isalnum(Look) || (!isspace(Look) && (Look != '='))) {
		*p = Look;
		p++;
		GetChar();
	}
	SkipWhite();
	return name;
}

std::string GetAttribValue() {
	std::string attrib_value;
	if (Look == '\'' || Look == '"') {
		char mode = Look;
		Match(mode);
		while (Look != mode) {
			attrib_value.append(1, Look);
			GetChar();
		}
		Match(mode);
	}
	else {
		Expected("Attribute Value");
	}
	return attrib_value;
}

void GetAttrib(Node_st *node) {
	Attrib_st attrib;
	attrib.attrib_name = GetAttribName();
	Match('=');
	attrib.attrib_value = GetAttribValue();
	node->attribs.push_back(attrib);
}

void GetChar() {
	Look = fgetc(File);
	//printf("%c",Look);
}

void Match(char ch) {
	if (Look == ch) {
		GetChar();
		SkipWhite();
	}
	else {
		char info[] = {"'''''''"};
		info[3] = ch;
		Expected(info);
	}
}

void MatchString(const char* str) {
	for (const char *p = str; *p != 0; p++) {
		Match(*p);
	}
}

void SkipWhite() {
	do {
		switch (Look) {
			case ' ':
			case '\t':
			case '\n':
			case '\r':
				GetChar();
				continue;
			default:
				return;
		}
	} while (true);
}

void Abort(const char* s) {
	printf("\nError: %s.\n", s);

	if (File != NULL) {
		printf("Crash location: %d\n", ftell(File));
	}

	printf("Press ENTER to exit...");
	system("pause");
	exit(-1);
}

void Expected(const char* s) {
	char info[20] = {0};
	size_t nLen = strlen(s);
	strcpy(info, s);
	strcpy(&info[nLen], " Expected");
	Abort(info);
}

void IgnoreComment() {
	while (Look != '>') {
		GetChar();
	}
	Match('>');
}

void IgnoreValid() {
	while (Look != '>') {
		GetChar();
		if (Look == '[') {
			while (Look != ']') {
				GetChar();
			}
		}
	}
	Match('>');
}

void IgnoreDecl() {
	IgnoreComment();
}

bool Ignored() {
	if (Look == '?') {
		IgnoreDecl();
	}
	else if (Look == '!') {
		Match('!');
		if (Look == '-') {
			IgnoreComment();
		}
		else {
			IgnoreValid();
		}
	}
	else {
		return false;
	}
	return true;
}
<commit_msg>MatchString应该完整匹配，包括中间的white-space character<commit_after>#include "core.h"
#include <vector>

void IgnoreDecl();				// 忽略xml声明
void IgnoreValid();				// 忽略文档验证信息
void IgnoreComment();			// 忽略xml注释

int Look;						// 碗
FILE *File = NULL;				// 锅

struct Attrib_st {
	std::string attrib_name;
	std::string attrib_value;
};

typedef std::vector<Attrib_st> Attribs;
typedef std::vector<Node_st> Nodes;

struct Node_st {
	std::string elem_name;
	std::string elem_value;
	Attribs attribs;
	Nodes childs;
} XML;

Node_st* Parse(const char* file) {
	Init(file);
	GetElement(&XML);
	fclose(File);
	if (!XML.childs.empty()) {
		return &XML.childs[0];
	}
	else {
		return NULL;
	}
}

void Init(const char* file) {
	// 开锅
	File = fopen(file, "rb");
	if (File == NULL) {
		Expected("File open normally");
	}
	// 先捞一碗
	GetChar();
	// 过滤老鼠屎
	SkipWhite();
}

void GetElement(Node_st *parent) {
	do {
		Node_st node;
		Match('<');
		while (Ignored()) {
			Match('<');
		}
		node.elem_name = GetElemName();
		while (Look != '/' && Look != '>') {
			// 解析属性
			GetAttrib(&node);
		}
		if (Look == '/') {
			Match('/');
			Match('>');
		}
		else if (Look == '>') {
			Match('>');
			if (Look != '<') {
				node.elem_value.append(GetElemValue());
			}
			fpos_t pos;
			fgetpos(File, &pos);
			Match('<');
			while (Ignored()) {
				if (Look != '<' && Look != EOF) {
					parent->elem_value.append(GetElemValue());
				}
				fgetpos(File, &pos);
				Match('<');
			}
			if (Look != '/') {
				// 子节点
				fsetpos(File, &pos);
				Look = '<';
				GetElement(&node);
				if (Look != '<') {
					parent->elem_value.append(GetElemValue());
				}
				Match('<');
				while (Ignored()) {
					if (Look != '<' && Look != EOF) {
						parent->elem_value.append(GetElemValue());
					}
					fgetpos(File, &pos);
					Match('<');
				}
			}

			Match('/');
			MatchString(node.elem_name.c_str());
			Match('>');
		}
		else {
			Expected("Closed Brackets needed");
		}
		parent->childs.push_back(node);

		if (Look != '<' && Look != EOF) {
			parent->elem_value.append(GetElemValue());
		}
		if (Look != EOF) {
			fpos_t pos;
			fgetpos(File, &pos);
			Match('<');
			while (Ignored()) {
				if (Look != '<' && Look != EOF) {
					parent->elem_value.append(GetElemValue());
				}
				if (Look != EOF) {
					fgetpos(File, &pos);
					Match('<');
				}
			}
			if (Look == EOF) {
				return;
			}
			if (Look != '/') {
				fsetpos(File, &pos);
				Look = '<';
			}
			else {
				fsetpos(File, &pos);
				Look = '<';
				break;
			}
		}

	} while (Look != EOF);
}

std::string GetElemName() {
	if (!isalpha(Look)) {
		Expected("Name");
	}
	char name[30] = {0};
	char *p = name;
	while (isalnum(Look) || (!isspace(Look) && (Look != '>'))) {
		*p = Look;
		p++;
		GetChar();
	}
	SkipWhite();
	return name;
}

std::string GetElemValue() {
	std::string elem_value;
	while (Look != '<') {
		elem_value.append(1, Look);
		GetChar();
	}
	return elem_value;
}

std::string GetAttribName() {
	if (!isalpha(Look)) {
		Expected("Name");
	}
	char name[30] = {0};
	char *p = name;
	while (isalnum(Look) || (!isspace(Look) && (Look != '='))) {
		*p = Look;
		p++;
		GetChar();
	}
	SkipWhite();
	return name;
}

std::string GetAttribValue() {
	std::string attrib_value;
	if (Look == '\'' || Look == '"') {
		char mode = Look;
		Match(mode);
		while (Look != mode) {
			attrib_value.append(1, Look);
			GetChar();
		}
		Match(mode);
	}
	else {
		Expected("Attribute Value");
	}
	return attrib_value;
}

void GetAttrib(Node_st *node) {
	Attrib_st attrib;
	attrib.attrib_name = GetAttribName();
	Match('=');
	attrib.attrib_value = GetAttribValue();
	node->attribs.push_back(attrib);
}

void GetChar() {
	Look = fgetc(File);
	//printf("%c",Look);
}

void Match(char ch) {
	if (Look == ch) {
		GetChar();
		SkipWhite();
	}
	else {
		char info[] = {"'''''''"};
		info[3] = ch;
		Expected(info);
	}
}

void MatchString(const char* str) {
	for (const char *p = str; *p != 0; p++) {
		if (*p == Look) {
			GetChar();
		}
		else {
			Expected(p);
		}
	}
	SkipWhite();
}

void SkipWhite() {
	do {
		switch (Look) {
			case ' ':
			case '\t':
			case '\n':
			case '\r':
				GetChar();
				continue;
			default:
				return;
		}
	} while (true);
}

void Abort(const char* s) {
	printf("\nError: %s.\n", s);

	if (File != NULL) {
		printf("Crash location: %d\n", ftell(File));
	}

	printf("Press ENTER to exit...");
	system("pause");
	exit(-1);
}

void Expected(const char* s) {
	char info[20] = {0};
	size_t nLen = strlen(s);
	strcpy(info, s);
	strcpy(&info[nLen], " Expected");
	Abort(info);
}

void IgnoreComment() {
	while (Look != '>') {
		GetChar();
	}
	Match('>');
}

void IgnoreValid() {
	while (Look != '>') {
		GetChar();
		if (Look == '[') {
			while (Look != ']') {
				GetChar();
			}
		}
	}
	Match('>');
}

void IgnoreDecl() {
	IgnoreComment();
}

bool Ignored() {
	if (Look == '?') {
		IgnoreDecl();
	}
	else if (Look == '!') {
		Match('!');
		if (Look == '-') {
			IgnoreComment();
		}
		else {
			IgnoreValid();
		}
	}
	else {
		return false;
	}
	return true;
}
<|endoftext|>


<commit_before>/*
 * test-uart.cpp
 *
 * Copyright (c) 2017 Lix N. Paulian (lix@paulian.net)
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom
 * the Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Created on: 16 Jun 2017 (LNP)
 */

#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>

#include <cmsis-plus/rtos/os.h>
#include <cmsis-plus/diag/trace.h>
#include <cmsis-plus/posix-io/file-descriptors-manager.h>

#include "uart-drv.h"
#include "io.h"

extern "C"
{
  UART_HandleTypeDef huart6;
}

using namespace os;
using namespace os::rtos;

// Static manager
os::posix::file_descriptors_manager descriptors_manager
  { 8 };

#define TX_BUFFER_SIZE 200
#define RX_BUFFER_SIZE 200

uint8_t tx_buffer[TX_BUFFER_SIZE];
uint8_t rx_buffer[RX_BUFFER_SIZE];

driver::uart uart6
  { "uart6", &huart6, tx_buffer, rx_buffer, sizeof(tx_buffer), sizeof(rx_buffer) };

void
HAL_UART_TxCpltCallback (UART_HandleTypeDef *huart)
{
  if (huart->Instance == huart6.Instance)
    {
      uart6.cb_tx_event (huart);
    }
}

void
HAL_UART_RxHalfCpltCallback (UART_HandleTypeDef *huart)
{
  if (huart->Instance == huart6.Instance)
    {
      uart6.cb_rx_event (huart);
    }
}

void
HAL_UART_ErrorCallback (UART_HandleTypeDef *huart)
{
  if (huart->Instance == huart6.Instance)
    {
      uart6.cb_rx_event (huart);
    }
}

/**
 * @brief  This is a test function that exercises the UART driver.
 */
void
test_uart (void)
{
  int fd, count;
  char text[] =
    { "The quick brown fox jumps over the lazy dog 1234567890\r\n" };

  // configure the MPI interface
  mpi_ctrl mpi
    { };

  mpi.init_pins ();
  mpi.rs485 (false);
  mpi.shutdown (false);
  mpi.half_duplex (false);

  // open the serial device
  if ((fd = open ("/dev/uart6", 0)) < 0)
    {
      trace::printf ("Error at open\n");
    }

  // send text
  for (int i = 0; i < 1000; i++)
    {
      if ((count = write (fd, text, strlen (text))) < 0)
        {
          trace::printf ("Error at write (%d)\n", i);
        }
    }

}
<commit_msg>Completed the test to perform basic operations open, write, read and close)<commit_after>/*
 * test-uart.cpp
 *
 * Copyright (c) 2017 Lix N. Paulian (lix@paulian.net)
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom
 * the Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Created on: 16 Jun 2017 (LNP)
 */

#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>

#include <cmsis-plus/rtos/os.h>
#include <cmsis-plus/diag/trace.h>
#include <cmsis-plus/posix-io/file-descriptors-manager.h>

#include "uart-drv.h"
#include "io.h"

extern "C"
{
  UART_HandleTypeDef huart6;
}

using namespace os;
using namespace os::rtos;

// Static manager
os::posix::file_descriptors_manager descriptors_manager
  { 8 };

#define TX_BUFFER_SIZE 200
#define RX_BUFFER_SIZE 200

#define TEST_ROUNDS 10
#define WRITE_READ_ROUNDS 10

uint8_t tx_buffer[TX_BUFFER_SIZE];
uint8_t rx_buffer[RX_BUFFER_SIZE];

static ssize_t
targeted_read (int filedes, char *buffer, size_t size);

driver::uart uart6
  { "uart6", &huart6, tx_buffer, rx_buffer, sizeof(tx_buffer), sizeof(rx_buffer) };

void
HAL_UART_TxCpltCallback (UART_HandleTypeDef *huart)
{
  if (huart->Instance == huart6.Instance)
    {
      uart6.cb_tx_event ();
    }
}

void
HAL_UART_RxCpltCallback (UART_HandleTypeDef *huart)
{
  if (huart->Instance == huart6.Instance)
    {
      uart6.cb_rx_event (false);
    }
}

void
HAL_UART_RxHalfCpltCallback (UART_HandleTypeDef *huart)
{
  if (huart->Instance == huart6.Instance)
    {
      uart6.cb_rx_event (true);
    }
}

void
HAL_UART_ErrorCallback (UART_HandleTypeDef *huart)
{
  if (huart->Instance == huart6.Instance)
    {
      uart6.cb_rx_event (false);
    }
}

/**
 * @brief  This is a test function that exercises the UART driver.
 */
void
test_uart (void)
{
  int fd, count;
  char text[] =
    { "The quick brown fox jumps over the lazy dog 1234567890\r\n" };
  char text_end[] =
    { "---------\r\n" };
  char buffer[100];

#ifdef M717
  // configure the MPI interface
  mpi_ctrl mpi
    {};

  /* set to RS232 */
  mpi.init_pins ();
  mpi.rs485 (false);
  mpi.shutdown (false);
  mpi.half_duplex (false);
#endif

  for (int i = 0; i < TEST_ROUNDS; i++)
    {
      // open the serial device
      if ((fd = open ("/dev/uart6", 0)) < 0)
        {
          trace::printf ("Error at open\n");
        }
      else
        {
          for (int j = 0; j < WRITE_READ_ROUNDS; j++)
            {
              // send text
              if ((count = write (fd, text, strlen (text))) < 0)
                {
                  trace::printf ("Error at write (%d)\n", j);
                  break;
                }

              // read text
              count = targeted_read (fd, buffer, strlen (text));
              if (count > 0)
                {
                  buffer[count] = '\0';
                  trace::printf ("%s", buffer);
                }
              else
                {
                  trace::printf ("Error reading data\n");
                }
            }

          // send separating dashes
          if ((count = write (fd, text_end, strlen (text_end))) < 0)
            {
              trace::printf ("Error at write end text\n");
              break;
            }

          // read separating dashes
          count = targeted_read (fd, buffer, strlen (text_end));
          if (count > 0)
            {
              buffer[count] = '\0';
              trace::printf ("%s", buffer);
            }
          else
            {
              trace::printf ("Error reading separator\n");
            }

          // close the serial device
          if ((close (fd)) < 0)
            {
              trace::printf ("Error at close\n");
              break;
            }
        }
    }
}

/**
 * @brief This function waits to read a known amount of bytes before returning
 * @param fd: file descriptor
 * @param buffer: buffer to return data into.
 * @param size: the targeted amount of characters to wait for
 * @return The number of characters read or an error if negative.
 */
static ssize_t
targeted_read (int fd, char *buffer, size_t size)
{
  int count, total = 0;

  do
    {
      if ((count = read (fd, buffer + total, size - total)) < 0)
        {
          break;
        }
      total += count;
    }
  while (total < (int) size);

  return total;
}
<|endoftext|>


<commit_before>#include "fcam/Demosaic.h"
#include "fcam/Demosaic_ARM.h"

#include "benchmark.h"
#include "curved.h"
#include "halide_image.h"
#include "halide_image_io.h"
#include "halide_malloc_trace.h"

#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cassert>

using namespace Halide::Tools;

int main(int argc, char **argv) {
    if (argc < 7) {
        printf("Usage: ./process raw.png color_temp gamma contrast timing_iterations output.png\n"
               "e.g. ./process raw.png 3200 2 50 5 output.png");
        return 0;
    }

#ifdef HL_MEMINFO
    halide_enable_malloc_trace();
#endif

    fprintf(stderr, "input: %s\n", argv[1]);
    Image<uint16_t> input = load_image(argv[1]);
    fprintf(stderr, "       %d %d\n", input.width(), input.height());
    Image<uint8_t> output(((input.width() - 32)/32)*32, ((input.height() - 24)/32)*32, 3);

#ifdef HL_MEMINFO
    info(input, "input");
    stats(input, "input");
    // dump(input, "input");
#endif

    // These color matrices are for the sensor in the Nokia N900 and are
    // taken from the FCam source.
    float _matrix_3200[][4] = {{ 1.6697f, -0.2693f, -0.4004f, -42.4346f},
                                {-0.3576f,  1.0615f,  1.5949f, -37.1158f},
                                {-0.2175f, -1.8751f,  6.9640f, -26.6970f}};

    float _matrix_7000[][4] = {{ 2.2997f, -0.4478f,  0.1706f, -39.0923f},
                                {-0.3826f,  1.5906f, -0.2080f, -25.4311f},
                                {-0.0888f, -0.7344f,  2.2832f, -20.0826f}};
    Image<float> matrix_3200(4, 3), matrix_7000(4, 3);
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            matrix_3200(j, i) = _matrix_3200[i][j];
            matrix_7000(j, i) = _matrix_7000[i][j];
        }
    }

    float color_temp = atof(argv[2]);
    float gamma = atof(argv[3]);
    float contrast = atof(argv[4]);
    int timing_iterations = atoi(argv[5]);
    int blackLevel = 25;
    int whiteLevel = 1023;

    double best;

    best = benchmark(timing_iterations, 1, [&]() {
        curved(color_temp, gamma, contrast, blackLevel, whiteLevel,
               input, matrix_3200, matrix_7000,
               output);
    });
    fprintf(stderr, "Halide:\t%gus\n", best * 1e6);
    fprintf(stderr, "output: %s\n", argv[6]);
    save_image(output, argv[6]);
    fprintf(stderr, "        %d %d\n", output.width(), output.height());

    Image<uint8_t> output_c(output.width(), output.height(), output.channels());
    best = benchmark(timing_iterations, 1, [&]() {
        FCam::demosaic(input, output_c, color_temp, contrast, true, blackLevel, whiteLevel, gamma);
    });
    fprintf(stderr, "C++:\t%gus\n", best * 1e6);
    fprintf(stderr, "output_c: fcam_c.png\n");
    save_image(output_c, "fcam_c.png");
    fprintf(stderr, "        %d %d\n", output_c.width(), output_c.height());

    Image<uint8_t> output_asm(output.width(), output.height(), output.channels());
    best = benchmark(timing_iterations, 1, [&]() {
        FCam::demosaic_ARM(input, output_asm, color_temp, contrast, true, blackLevel, whiteLevel, gamma);
    });
    fprintf(stderr, "ASM:\t%gus\n", best * 1e6);
    fprintf(stderr, "output_asm: fcam_arm.png\n");
    save_image(output_asm, "fcam_arm.png");
    fprintf(stderr, "        %d %d\n", output_asm.width(), output_asm.height());

    // Timings on N900 as of SIGGRAPH 2012 camera ready are (best of 10)
    // Halide: 722ms, FCam: 741ms

    return 0;
}
<commit_msg>Fix camera pipe<commit_after>#include "fcam/Demosaic.h"
#include "fcam/Demosaic_ARM.h"

#include "benchmark.h"
#include "curved.h"
#include "halide_image.h"
#include "halide_image_io.h"
#include "halide_malloc_trace.h"

#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cassert>

using namespace Halide::Tools;

int main(int argc, char **argv) {
    if (argc < 7) {
        printf("Usage: ./process raw.png color_temp gamma contrast timing_iterations output.png\n"
               "e.g. ./process raw.png 3200 2 50 5 output.png");
        return 0;
    }

#ifdef HL_MEMINFO
    halide_enable_malloc_trace();
#endif

    fprintf(stderr, "input: %s\n", argv[1]);
    Image<uint16_t> input = load_image(argv[1]);
    fprintf(stderr, "       %d %d\n", input.width(), input.height());
    Image<uint8_t> output(((input.width() - 32)/32)*32, ((input.height() - 24)/32)*32, 3);

#ifdef HL_MEMINFO
    info(input, "input");
    stats(input, "input");
    // dump(input, "input");
#endif

    // These color matrices are for the sensor in the Nokia N900 and are
    // taken from the FCam source.
    float _matrix_3200[][4] = {{ 1.6697f, -0.2693f, -0.4004f, -42.4346f},
                                {-0.3576f,  1.0615f,  1.5949f, -37.1158f},
                                {-0.2175f, -1.8751f,  6.9640f, -26.6970f}};

    float _matrix_7000[][4] = {{ 2.2997f, -0.4478f,  0.1706f, -39.0923f},
                                {-0.3826f,  1.5906f, -0.2080f, -25.4311f},
                                {-0.0888f, -0.7344f,  2.2832f, -20.0826f}};
    Image<float> matrix_3200(4, 3), matrix_7000(4, 3);
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            matrix_3200(j, i) = _matrix_3200[i][j];
            matrix_7000(j, i) = _matrix_7000[i][j];
        }
    }

    float color_temp = atof(argv[2]);
    float gamma = atof(argv[3]);
    float contrast = atof(argv[4]);
    int timing_iterations = atoi(argv[5]);
    int blackLevel = 25;
    int whiteLevel = 1023;

    double best;

    best = benchmark(timing_iterations, 1, [&]() {
        curved(color_temp, gamma, contrast, blackLevel, whiteLevel,
               &input, &matrix_3200, &matrix_7000,
               &output);
    });
    fprintf(stderr, "Halide:\t%gus\n", best * 1e6);
    fprintf(stderr, "output: %s\n", argv[6]);
    save_image(output, argv[6]);
    fprintf(stderr, "        %d %d\n", output.width(), output.height());

    Image<uint8_t> output_c(output.width(), output.height(), output.channels());
    best = benchmark(timing_iterations, 1, [&]() {
        FCam::demosaic(input, output_c, color_temp, contrast, true, blackLevel, whiteLevel, gamma);
    });
    fprintf(stderr, "C++:\t%gus\n", best * 1e6);
    fprintf(stderr, "output_c: fcam_c.png\n");
    save_image(output_c, "fcam_c.png");
    fprintf(stderr, "        %d %d\n", output_c.width(), output_c.height());

    Image<uint8_t> output_asm(output.width(), output.height(), output.channels());
    best = benchmark(timing_iterations, 1, [&]() {
        FCam::demosaic_ARM(input, output_asm, color_temp, contrast, true, blackLevel, whiteLevel, gamma);
    });
    fprintf(stderr, "ASM:\t%gus\n", best * 1e6);
    fprintf(stderr, "output_asm: fcam_arm.png\n");
    save_image(output_asm, "fcam_arm.png");
    fprintf(stderr, "        %d %d\n", output_asm.width(), output_asm.height());

    // Timings on N900 as of SIGGRAPH 2012 camera ready are (best of 10)
    // Halide: 722ms, FCam: 741ms

    return 0;
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
// PCL specific includes
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/Image.h>

#include <tf/transform_listener.h>

#include <geometry_msgs/PointStamped.h>
#include <art_msgs/ObjectsCentroids.h>

#include <ar_track_alvar_msgs/AlvarMarkers.h>
#include <ar_track_alvar_msgs/AlvarMarker.h>
#include <geometry_msgs/Pose.h>
#include <tf/tf.h>
#include <exception>
#include <tf/transform_broadcaster.h>

class NoMainMarker: public std::exception {
public:
    virtual const char* what() const throw() {
        return "No main marker!";
    }
};

class ArtCalibration {
public:
    ArtCalibration() {
        table_marker_sub = nh_.subscribe ("/table/ar_pose_marker", 1, &ArtCalibration::table_marker_cb, this);
        pr2_marker_sub = nh_.subscribe ("/pr2/ar_pose_marker", 1, &ArtCalibration::pr2_marker_cb, this);
        ros_init();
    }

    ~ArtCalibration() {

    }

    void ros_init() {
        nh_.param<std::string>("robot_frame", robot_frame_, "odom_combined");
        nh_.param<std::string>("table_frame", table_frame_, "kinect2_link");
        nh_.param<std::string>("world_frame", world_frame_, "table");
    }

private:

    tf::StampedTransform tr_table_, tr_pr2_;
    tf::TransformBroadcaster br_;
    ros::Timer tr_timer_;

    ros::Subscriber table_marker_sub, pr2_marker_sub;
    ros::NodeHandle nh_;

    std::string world_frame_, robot_frame_, table_frame_;

    bool table_calibration_done_ = false, pr2_calibration_done_ = false;

    static const int MAIN_MARKER_SIZE = 10;

    void table_marker_cb(ar_track_alvar_msgs::AlvarMarkersConstPtr markers) {
        geometry_msgs::Pose pose;
        try {
            pose = get_main_marker_pose(*markers);
        }
        catch (NoMainMarker& e) {
            std::cout << e.what() << std::endl;
            return;
        }
        tr_table_ = create_transform_from_pose(pose, table_frame_);
        table_marker_sub.shutdown();
        table_calibration_done_ = true;
        tr_timer_ = nh_.createTimer(ros::Duration(0.1), &ArtCalibration::trCallback, this);
    }

    void pr2_marker_cb(ar_track_alvar_msgs::AlvarMarkersConstPtr markers) {
        geometry_msgs::Pose pose;
        try {
            pose = get_main_marker_pose(*markers);
        }
        catch (NoMainMarker& e) {
            std::cout << e.what() << std::endl;
            return;
        }
        tr_pr2_ = create_transform_from_pose(pose, robot_frame_);
        pr2_marker_sub.shutdown();
        pr2_calibration_done_ = true;
        tr_timer_ = nh_.createTimer(ros::Duration(0.1), &ArtCalibration::trCallback, this);
    }

    tf::StampedTransform create_transform_from_pose(geometry_msgs::Pose pose, std::string output_frame) {
        tf::Transform tr;
        tf::Quaternion q;
        tr.setOrigin(tf::Vector3(pose.position.x, pose.position.y, pose.position.z));
        tf::quaternionMsgToTF(pose.orientation, q);
        q.normalize();
        tr.setRotation(q);
        return tf::StampedTransform(tr.inverse(), ros::Time::now(), world_frame_, output_frame);
    }

    geometry_msgs::Pose get_main_marker_pose(ar_track_alvar_msgs::AlvarMarkers marker) {
        for (int i = 0; i < marker.markers.size(); ++i) {
            if (marker.markers[i].id == MAIN_MARKER_SIZE) {
                return marker.markers[i].pose.pose;
            }
        }
        return geometry_msgs::Pose();
    }

    void trCallback(const ros::TimerEvent& event) {
        if (table_calibration_done_) {
            tr_table_.stamp_ = ros::Time::now();
            br_.sendTransform(tr_table_);
        }
        if (pr2_calibration_done_) {
            tr_pr2_.stamp_ = ros::Time::now();
            br_.sendTransform(tr_pr2_);
        }
    }

};

int main (int argc, char** argv)
{
  // Initialize ROS
  ros::init (argc, argv, "art_calibration");

  ArtCalibration calibration;

  // Spin
  ros::spin();

}
<commit_msg>table->marker<commit_after>#include <ros/ros.h>
// PCL specific includes
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/Image.h>

#include <tf/transform_listener.h>

#include <geometry_msgs/PointStamped.h>
#include <art_msgs/ObjectsCentroids.h>

#include <ar_track_alvar_msgs/AlvarMarkers.h>
#include <ar_track_alvar_msgs/AlvarMarker.h>
#include <geometry_msgs/Pose.h>
#include <tf/tf.h>
#include <exception>
#include <tf/transform_broadcaster.h>

class NoMainMarker: public std::exception {
public:
    virtual const char* what() const throw() {
        return "No main marker!";
    }
};

class ArtCalibration {
public:
    ArtCalibration() {
        table_marker_sub = nh_.subscribe ("/table/ar_pose_marker", 1, &ArtCalibration::table_marker_cb, this);
        pr2_marker_sub = nh_.subscribe ("/pr2/ar_pose_marker", 1, &ArtCalibration::pr2_marker_cb, this);
        ros_init();
    }

    ~ArtCalibration() {

    }

    void ros_init() {
        nh_.param<std::string>("robot_frame", robot_frame_, "odom_combined");
        nh_.param<std::string>("table_frame", table_frame_, "kinect2_link");
        nh_.param<std::string>("world_frame", world_frame_, "marker");
    }

private:

    tf::StampedTransform tr_table_, tr_pr2_;
    tf::TransformBroadcaster br_;
    ros::Timer tr_timer_;

    ros::Subscriber table_marker_sub, pr2_marker_sub;
    ros::NodeHandle nh_;

    std::string world_frame_, robot_frame_, table_frame_;

    bool table_calibration_done_ = false, pr2_calibration_done_ = false;

    static const int MAIN_MARKER_SIZE = 10;

    void table_marker_cb(ar_track_alvar_msgs::AlvarMarkersConstPtr markers) {
        geometry_msgs::Pose pose;
        try {
            pose = get_main_marker_pose(*markers);
        }
        catch (NoMainMarker& e) {
            std::cout << e.what() << std::endl;
            return;
        }
        tr_table_ = create_transform_from_pose(pose, table_frame_);
        table_marker_sub.shutdown();
        table_calibration_done_ = true;
        tr_timer_ = nh_.createTimer(ros::Duration(0.1), &ArtCalibration::trCallback, this);
    }

    void pr2_marker_cb(ar_track_alvar_msgs::AlvarMarkersConstPtr markers) {
        geometry_msgs::Pose pose;
        try {
            pose = get_main_marker_pose(*markers);
        }
        catch (NoMainMarker& e) {
            std::cout << e.what() << std::endl;
            return;
        }
        tr_pr2_ = create_transform_from_pose(pose, robot_frame_);
        pr2_marker_sub.shutdown();
        pr2_calibration_done_ = true;
        tr_timer_ = nh_.createTimer(ros::Duration(0.1), &ArtCalibration::trCallback, this);
    }

    tf::StampedTransform create_transform_from_pose(geometry_msgs::Pose pose, std::string output_frame) {
        tf::Transform tr;
        tf::Quaternion q;
        tr.setOrigin(tf::Vector3(pose.position.x, pose.position.y, pose.position.z));
        tf::quaternionMsgToTF(pose.orientation, q);
        q.normalize();
        tr.setRotation(q);
        return tf::StampedTransform(tr.inverse(), ros::Time::now(), world_frame_, output_frame);
    }

    geometry_msgs::Pose get_main_marker_pose(ar_track_alvar_msgs::AlvarMarkers marker) {
        for (int i = 0; i < marker.markers.size(); ++i) {
            if (marker.markers[i].id == MAIN_MARKER_SIZE) {
                return marker.markers[i].pose.pose;
            }
        }
        return geometry_msgs::Pose();
    }

    void trCallback(const ros::TimerEvent& event) {
        if (table_calibration_done_) {
            tr_table_.stamp_ = ros::Time::now();
            br_.sendTransform(tr_table_);
        }
        if (pr2_calibration_done_) {
            tr_pr2_.stamp_ = ros::Time::now();
            br_.sendTransform(tr_pr2_);
        }
    }

};

int main (int argc, char** argv)
{
  // Initialize ROS
  ros::init (argc, argv, "art_calibration");

  ArtCalibration calibration;

  // Spin
  ros::spin();

}
<|endoftext|>


<commit_before>/* Siconos-sample version 2.0.0, Copyright INRIA 2005-2006.
 * Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 * Siconos is a free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * Siconos is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Siconos; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact: Vincent ACARY vincent.acary@inrialpes.fr
*/
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <fstream>
using namespace std;

const double R = 0.1; // beads radius
const double m = 1; // beads mass
const double g = 9.81; // gravity

extern "C" void gravity(unsigned int sizeOfq, double time, double *fExt, double* param)
{
  for (unsigned int i = 0; i < sizeOfq; i++)
    fExt[i] = 0.0;

  fExt[2] = -m * g;
}

// // Momentum inertia
// const double I = 3./5*R*R;

// extern "C" void Mass(unsigned int sizeOfq, const double *q, double *mass, double* param)
// {
//   mass[0]  = mass[7]  = mass[14] = m;
//   mass[21] = mass[28] = mass[35] = I;
// }

extern "C" void NNL1(unsigned int sizeOfq, const double *q, const double *velocity, double *NNL, double* param)
{
  //NNL[3] = - I1*velocity[4]*velocity[5]*sin(q[3]);
  //NNL[4] =   I1*velocity[3]*velocity[5]*sin(q[3]);
  //NNL[5] =   I1*velocity[3]*velocity[4]*sin(q[3]);
}

extern "C" void NNL2(unsigned int sizeOfq, const double *q, const double *velocity, double *NNL, double* param)
{
  // NNL[3] = - I2*velocity[4]*velocity[5]*sin(q[3]);
  // NNL[4] =   I2*velocity[3]*velocity[5]*sin(q[3]);
  // NNL[5] =   I2*velocity[3]*velocity[4]*sin(q[3]);
}

extern "C" void jacobianQNNL1(unsigned int sizeOfq, const double *q, const double *velocity, double *jacob, double* param)
{
  //jacob[21] = - I1*velocity[4]*velocity[5]*cos(q[3]);
  //jacob[27] =   I1*velocity[3]*velocity[5]*cos(q[3]);
  //jacob[33] =   I1*velocity[3]*velocity[4]*cos(q[3]);
}

extern "C" void jacobianQNNL2(unsigned int sizeOfq, const double *q, const double *velocity, double *jacob, double* param)
{
  //jacob[21] = - I2*velocity[4]*velocity[5]*cos(q[3]);
  //jacob[27] =   I2*velocity[3]*velocity[5]*cos(q[3]);
  //jacob[33] =   I2*velocity[3]*velocity[4]*cos(q[3]);
}

extern "C" void jacobianVNNL1(unsigned int sizeOfq, const double *q, const  double *velocity, double *jacob, double* param)
{
  //jacob[22] = - I1*velocity[5]*sin(q[3]);
  //jacob[27] =   I1*velocity[5]*sin(q[3]);
  //jacob[23] = - I1*velocity[4]*sin(q[3]);
  //jacob[33] =   I1*velocity[4]*sin(q[3]);
  //jacob[29] = jacob[34] =   I1*velocity[3]*sin(q[3]);
}

extern "C" void jacobianVNNL2(unsigned int sizeOfq, const double *q, const  double *velocity, double *jacob, double* param)
{
  //jacob[22] = - I2*velocity[5]*sin(q[3]);
  //jacob[27] =   I2*velocity[5]*sin(q[3]);
  //jacob[23] = - I2*velocity[4]*sin(q[3]);
  //jacob[33] =   I2*velocity[4]*sin(q[3]);
  //jacob[29] = jacob[34] =   I2*velocity[3]*sin(q[3]);
}

extern "C" void h0(unsigned int sizeOfq, const double* q, unsigned int sizeOfY, double* y, double* param)
{
  double d = sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  y[0] =  d - 2 * R;
}

extern "C" void Gcontact(unsigned int sizeOfq, const double* q, unsigned int sizeOfY, double* G, double* param)
{

  G[0] = -(q[6] - q[0]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[1] = -(q[7] - q[1]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[2] = -(q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[6] = (q[6] - q[0]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[7] = (q[7] - q[1]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[8] = (q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
}
extern "C" void G0(unsigned int sizeOfq, const double* q, unsigned int sizeOfY, double* G, double* param)
{

  G[0] = -(q[6] - q[0]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[3] = -(q[7] - q[1]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[6] = -(q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[18] = (q[6] - q[0]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[21] = (q[7] - q[1]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[24] = (q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));

  G[1] = G[5] = -1.;
  G[11] = R * (q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[13] = -R * (q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[16] =  R * (q[7] - q[1]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[17] = -R * (q[6] - q[0]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));

  G[19] = G[23] = 1.;
  G[29] = R * (q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[31] = -R * (q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[34] =  R * (q[7] - q[1]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[35] = -R * (q[6] - q[0]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));

}

<commit_msg>¨3D¨<commit_after>/* Siconos-sample version 2.0.0, Copyright INRIA 2005-2006.
 * Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 * Siconos is a free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * Siconos is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Siconos; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact: Vincent ACARY vincent.acary@inrialpes.fr
*/
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <fstream>
using namespace std;

const double R = 0.1; // beads radius
const double m = 1; // beads mass
const double g = 9.81; // gravity

extern "C" void gravity(double time, unsigned int sizeOfq, double *fExt, unsigned int sizeZ, double* param)
{
  for (unsigned int i = 0; i < sizeOfq; i++)
    fExt[i] = 0.0;

  fExt[2] = -m * g;
}

extern "C" void h0(unsigned int sizeOfq, const double* q, unsigned int sizeOfY, double* y, unsigned int sizeZ, double* param)
{
  double d = sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  y[0] =  d - 2 * R;
}

extern "C" void Gcontact(unsigned int sizeOfq, const double* q, unsigned int sizeOfY, double* G, unsigned int sizeZ, double* param)
{

  G[0] = -(q[6] - q[0]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[1] = -(q[7] - q[1]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[2] = -(q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[6] = (q[6] - q[0]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[7] = (q[7] - q[1]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[8] = (q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
}
extern "C" void G0(unsigned int sizeOfq, const double* q, unsigned int sizeOfY, double* G, unsigned int sizeZ, double* param)
{

  G[0] = -(q[6] - q[0]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[3] = -(q[7] - q[1]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[6] = -(q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[18] = (q[6] - q[0]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[21] = (q[7] - q[1]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[24] = (q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));

  G[1] = G[5] = -1.;
  G[11] = R * (q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[13] = -R * (q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[16] =  R * (q[7] - q[1]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[17] = -R * (q[6] - q[0]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));

  G[19] = G[23] = 1.;
  G[29] = R * (q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[31] = -R * (q[8] - q[2]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[34] =  R * (q[7] - q[1]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));
  G[35] = -R * (q[6] - q[0]) / sqrt((q[6] - q[0]) * (q[6] - q[0]) + (q[7] - q[1]) * (q[7] - q[1]) + (q[8] - q[2]) * (q[8] - q[2]));

}
<|endoftext|>


<commit_before><commit_msg>Update InputManager.cpp<commit_after><|endoftext|>


<commit_before>// Copyright 2013 Sean McKenna
//
//    Licensed 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.
//

// a ray tracer in C++

// libraries, namespace
#include <thread>
#include <fstream>
#include "library/loadXML.cpp"
#include "library/scene.cpp"
using namespace std;

// scene to load (project #) & whether to debug
const char* xml = "scenes/prj2.xml";
bool printXML = false;

// for ray tracing
int w;
int h;
int size;
Color24 white;
Color24 black;
Color24* img;
float* zImg;
void objectIntersection(Node &n, Ray r, int pixel);

// for threading
static const int numThreads = 8;
void rayTracing(int i);

// for camera ray generation
void cameraRayVars();
Point *imageTopLeftV;
Point *dXV;
Point *dYV;
Point firstPixel;
Transformation* c;
Point cameraRay(int pX, int pY);

// ray tracer
int main(){

  // load scene: root node, camera, image
  loadScene(xml, printXML);

  // set up colors & background image color
  white.Set(233, 233, 233);
  black.Set(33, 33, 33);
  render.setBackground(black);

  // set variables for ray tracing
  w = render.getWidth();
  h = render.getHeight();
  size = render.getSize();
  img = render.getRender();
  zImg = render.getZBuffer();

  // set variables for generating camera rays
  cameraRayVars();

  // start ray tracing loop (in parallel with threads)
  thread t[numThreads];
  for(int i = 0; i < numThreads; i++)
    t[i] = thread(rayTracing, i);

  // when finished, join all threads back to main
  for(int i = 0; i < numThreads; i++)
    t[i].join();

  // output ray-traced image & z-buffer (if uncommented)
  render.save("images/image.ppm");
  //render.computeZBuffer();
  //render.saveZBuffer("images/imageZ.ppm");
}

// ray tracing loop (for an individual pixel)
void rayTracing(int i){

  // initial starting pixel
  int pixel = i;

  // thread continuation condition
  while(pixel < size){

    // establish pixel location
    int pX = pixel % w;
    int pY = pixel / w;

    // transform ray into world space
    Point rayDir = cameraRay(pX, pY);
    Ray *ray = new Ray();
    ray->pos = camera.pos;
    ray->dir = c->transformFrom(rayDir);

    // traverse through scene DOM
    // transform rays into model space
    // detect ray intersections & update pixel
    objectIntersection(rootNode, *ray, pixel);

    // re-assign next pixel (naive, but works)
    pixel += numThreads;
  }
}

// create variables for camera ray generation
void cameraRayVars(){
  float fov = camera.fov * M_PI / 180.0;
  float aspectRatio = (float) w / (float) h;
  float imageDistance = 1.0;
  float imageTipY = imageDistance * tan(fov / 2.0);
  float imageTipX = imageTipY * aspectRatio;
  float dX = (2.0 * imageTipX) / (float) w;
  float dY = (2.0 * imageTipY) / (float) h;
  imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance);
  dXV = new Point(dX, 0.0, 0.0);
  dYV = new Point(0.0, -dY, 0.0);
  firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);

  // set up camera transformation (only need to rotate coordinates)
  c = new Transformation();
  Matrix *rotate = new cyMatrix3f();
  rotate->Set(camera.cross, camera.up, -camera.dir);
  c->transform(*rotate);
}

// compute camera rays
Point cameraRay(int pX, int pY){
  Point ray = firstPixel + (*dXV * pX) + (*dYV * pY);
  ray.Normalize();
  return ray;
}

// recursive object intersection through all scene objects
void objectIntersection(Node &n, Ray r, int pixel){

  // loop on child nodes
  int j = 0;
  int numChild = n.getNumChild();
  while(j < numChild){

    // grab child node
    Node *child = n.getChild(j);
    Object *obj = child->getObject();

    // transform rays into model space (or local space)
    Ray r2 = child->toModelSpace(r);

    // compute ray intersections
    HitInfo h = HitInfo(child);
    bool hit = obj->intersectRay(r2, h);

    // update pixel & z-buffer, only if node is closer
    if(hit){
      if(h.z < zImg[pixel]){
        zImg[pixel] = h.z;

        // transform hit information back to world space
        h.node->fromModelSpace(h);

        // get this node's material
        Material *m = h.node->getMaterial();

        // shade the pixel appropriately
        img[pixel] = m->shade(r, h, lights);
      }
    }

    // recursively check this child's children
    objectIntersection(*child, r2, pixel);
    j++;
  }
}
<commit_msg>clean up node grabbing for ray tracer<commit_after>// Copyright 2013 Sean McKenna
//
//    Licensed 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.
//

// a ray tracer in C++

// libraries, namespace
#include <thread>
#include <fstream>
#include "library/loadXML.cpp"
#include "library/scene.cpp"
using namespace std;

// scene to load (project #) & whether to debug
const char* xml = "scenes/prj2.xml";
bool printXML = false;

// for ray tracing
int w;
int h;
int size;
Color24 white;
Color24 black;
Color24* img;
float* zImg;
void objectIntersection(Node &n, Ray r, int pixel);

// for threading
static const int numThreads = 8;
void rayTracing(int i);

// for camera ray generation
void cameraRayVars();
Point *imageTopLeftV;
Point *dXV;
Point *dYV;
Point firstPixel;
Transformation* c;
Point cameraRay(int pX, int pY);

// ray tracer
int main(){

  // load scene: root node, camera, image
  loadScene(xml, printXML);

  // set up colors & background image color
  white.Set(233, 233, 233);
  black.Set(33, 33, 33);
  render.setBackground(black);

  // set variables for ray tracing
  w = render.getWidth();
  h = render.getHeight();
  size = render.getSize();
  img = render.getRender();
  zImg = render.getZBuffer();

  // set variables for generating camera rays
  cameraRayVars();

  // start ray tracing loop (in parallel with threads)
  thread t[numThreads];
  for(int i = 0; i < numThreads; i++)
    t[i] = thread(rayTracing, i);

  // when finished, join all threads back to main
  for(int i = 0; i < numThreads; i++)
    t[i].join();

  // output ray-traced image & z-buffer (if uncommented)
  render.save("images/image.ppm");
  //render.computeZBuffer();
  //render.saveZBuffer("images/imageZ.ppm");
}

// ray tracing loop (for an individual pixel)
void rayTracing(int i){

  // initial starting pixel
  int pixel = i;

  // thread continuation condition
  while(pixel < size){

    // establish pixel location
    int pX = pixel % w;
    int pY = pixel / w;

    // transform ray into world space
    Point rayDir = cameraRay(pX, pY);
    Ray *ray = new Ray();
    ray->pos = camera.pos;
    ray->dir = c->transformFrom(rayDir);

    // traverse through scene DOM
    // transform rays into model space
    // detect ray intersections & update pixel
    objectIntersection(rootNode, *ray, pixel);

    // re-assign next pixel (naive, but works)
    pixel += numThreads;
  }
}

// create variables for camera ray generation
void cameraRayVars(){
  float fov = camera.fov * M_PI / 180.0;
  float aspectRatio = (float) w / (float) h;
  float imageDistance = 1.0;
  float imageTipY = imageDistance * tan(fov / 2.0);
  float imageTipX = imageTipY * aspectRatio;
  float dX = (2.0 * imageTipX) / (float) w;
  float dY = (2.0 * imageTipY) / (float) h;
  imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance);
  dXV = new Point(dX, 0.0, 0.0);
  dYV = new Point(0.0, -dY, 0.0);
  firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);

  // set up camera transformation (only need to rotate coordinates)
  c = new Transformation();
  Matrix *rotate = new cyMatrix3f();
  rotate->Set(camera.cross, camera.up, -camera.dir);
  c->transform(*rotate);
}

// compute camera rays
Point cameraRay(int pX, int pY){
  Point ray = firstPixel + (*dXV * pX) + (*dYV * pY);
  ray.Normalize();
  return ray;
}

// recursive object intersection through all scene objects
void objectIntersection(Node &n, Ray r, int pixel){

  // loop on child nodes
  int j = 0;
  int numChild = n.getNumChild();
  while(j < numChild){

    // grab child node
    Node *child = n.getChild(j);
    Object *obj = child->getObject();

    // transform rays into model space (or local space)
    Ray r2 = child->toModelSpace(r);

    // compute ray intersections
    HitInfo h = HitInfo(child);
    bool hit = obj->intersectRay(r2, h);

    // update pixel & z-buffer, only if node is closer
    if(hit){
      if(h.z < zImg[pixel]){
        zImg[pixel] = h.z;

        // get node
        Node *node = child;

        // transform hit information back to world space
        node->fromModelSpace(h);

        // get this node's material
        Material *m = node->getMaterial();

        // shade the pixel appropriately
        img[pixel] = m->shade(r, h, lights);
      }
    }

    // recursively check this child's children
    objectIntersection(*child, r2, pixel);
    j++;
  }
}
<|endoftext|>


<commit_before>#include <platform.h>

#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <dirent.h>
#include <netinet/in.h>
#include <linux/if.h>
#include <X11/Xlib.h>

#include <EASTL/string.h>

#include <strutils.h>

void GetMACAddresses(unsigned char*& paiAddresses, size_t& iAddresses)
{
	static unsigned char aiAddresses[16][8];

	struct ifreq ifr;
	struct ifreq *IFR;
	struct ifconf ifc;
   	char buf[1024];
  	int s, i;

	iAddresses = 0;

	s = socket(AF_INET, SOCK_DGRAM, 0);
   	if (s == -1)
  		return;

	ifc.ifc_len = sizeof(buf);
   	ifc.ifc_buf = buf;
  	ioctl(s, SIOCGIFCONF, &ifc);

 	IFR = ifc.ifc_req;
	for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++)
	{
		if (iAddresses >= 16)
			break;

   		strcpy(ifr.ifr_name, IFR->ifr_name);
  		if (ioctl(s, SIOCGIFFLAGS, &ifr) != 0)
			continue;

		if (ifr.ifr_flags & IFF_LOOPBACK)
			continue;

  		if (ioctl(s, SIOCGIFHWADDR, &ifr) != 0)
			continue;

		aiAddresses[iAddresses][6] = 0;
		aiAddresses[iAddresses][7] = 0;
  		bcopy( ifr.ifr_hwaddr.sa_data, aiAddresses[iAddresses++], 6);
	}

	close(s);
}

void GetScreenSize(int& iWidth, int& iHeight)
{
	Display* pdsp = NULL;
	Window wid = 0;
	XWindowAttributes xwAttr;

	pdsp = XOpenDisplay( NULL );
	if ( !pdsp )
		return;

	wid = DefaultRootWindow( pdsp );
	if ( 0 > wid )
		return;

	Status ret = XGetWindowAttributes( pdsp, wid, &xwAttr );
	iWidth = xwAttr.width;
	iHeight = xwAttr.height;

	XCloseDisplay( pdsp );
}

size_t GetNumberOfProcessors()
{
	return sysconf(_SC_NPROCESSORS_ONLN);
}

void SleepMS(size_t iMS)
{
	usleep(iMS);
}

void OpenBrowser(const tstring& sURL)
{
	system(convertstring<tchar, char>(tstring("firefox ") + sURL).c_str());
}

void CreateMinidump(void* pInfo, tchar* pszDirectory)
{
}

tstring OpenFileDialog(const tchar* pszFileTypes, const tchar* pszDirectory)
{
}

tstring SaveFileDialog(const tchar* pszFileTypes, const tchar* pszDirectory)
{
}

eastl::string GetClipboard()
{
}

void SetClipboard(const eastl::string& sBuf)
{
}

tstring GetAppDataDirectory(const tstring& sDirectory, const tstring& sFile)
{
	char* pszVar = getenv("HOME");

	tstring sSuffix;
	sSuffix.append(_T(".")).append(sDirectory).append(_T("/")).append(sFile);

	tstring sReturn(convertstring<char, tchar>(pszVar));

	mkdir(convertstring<tchar, char>(tstring(sReturn).append(_T("/")).append(_T(".")).append(sDirectory)).c_str(), 0777);

	sReturn.append(_T("/")).append(sSuffix);
	return sReturn;
}

eastl::vector<tstring> ListDirectory(tstring sDirectory, bool bDirectories)
{
	eastl::vector<tstring> asResult;

	struct dirent *dp;

	DIR *dir = opendir(convertstring<tchar, char>(sDirectory).c_str());
	while ((dp=readdir(dir)) != NULL)
	{
		if (!bDirectories && (dp->d_type == DT_DIR))
			continue;

		tstring sName = convertstring<char, tchar>(dp->d_name);
		if (sName == _T("."))
			continue;

		if (sName == _T(".."))
			continue;

		asResult.push_back(sName);
	}
	closedir(dir);

	return asResult;
}

bool IsFile(tstring sPath)
{
	struct stat stFileInfo;
	bool blnReturn;
	int intStat;

	// Attempt to get the file attributes
	intStat = stat(convertstring<tchar, char>(sPath).c_str(), &stFileInfo);
	if(intStat == 0 && S_ISREG(stFileInfo.st_mode))
		return true;
	else
		return false;
}

bool IsDirectory(tstring sPath)
{
	struct stat stFileInfo;
	bool blnReturn;
	int intStat;

	// Attempt to get the file attributes
	intStat = stat(convertstring<tchar, char>(sPath).c_str(), &stFileInfo);
	if(intStat == 0 && S_ISDIR(stFileInfo.st_mode))
		return true;
	else
		return false;
}

void DebugPrint(tstring sText)
{
	puts(convertstring<tchar, char>(sText).c_str());
}

void Exec(eastl::string sLine)
{
	system(sLine.c_str());
}
<commit_msg>Fixing exec so it runs files in the current directory like it's supposed to.<commit_after>#include <platform.h>

#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <dirent.h>
#include <netinet/in.h>
#include <linux/if.h>
#include <X11/Xlib.h>

#include <EASTL/string.h>

#include <strutils.h>

void GetMACAddresses(unsigned char*& paiAddresses, size_t& iAddresses)
{
	static unsigned char aiAddresses[16][8];

	struct ifreq ifr;
	struct ifreq *IFR;
	struct ifconf ifc;
   	char buf[1024];
  	int s, i;

	iAddresses = 0;

	s = socket(AF_INET, SOCK_DGRAM, 0);
   	if (s == -1)
  		return;

	ifc.ifc_len = sizeof(buf);
   	ifc.ifc_buf = buf;
  	ioctl(s, SIOCGIFCONF, &ifc);

 	IFR = ifc.ifc_req;
	for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++)
	{
		if (iAddresses >= 16)
			break;

   		strcpy(ifr.ifr_name, IFR->ifr_name);
  		if (ioctl(s, SIOCGIFFLAGS, &ifr) != 0)
			continue;

		if (ifr.ifr_flags & IFF_LOOPBACK)
			continue;

  		if (ioctl(s, SIOCGIFHWADDR, &ifr) != 0)
			continue;

		aiAddresses[iAddresses][6] = 0;
		aiAddresses[iAddresses][7] = 0;
  		bcopy( ifr.ifr_hwaddr.sa_data, aiAddresses[iAddresses++], 6);
	}

	close(s);
}

void GetScreenSize(int& iWidth, int& iHeight)
{
	Display* pdsp = NULL;
	Window wid = 0;
	XWindowAttributes xwAttr;

	pdsp = XOpenDisplay( NULL );
	if ( !pdsp )
		return;

	wid = DefaultRootWindow( pdsp );
	if ( 0 > wid )
		return;

	Status ret = XGetWindowAttributes( pdsp, wid, &xwAttr );
	iWidth = xwAttr.width;
	iHeight = xwAttr.height;

	XCloseDisplay( pdsp );
}

size_t GetNumberOfProcessors()
{
	return sysconf(_SC_NPROCESSORS_ONLN);
}

void SleepMS(size_t iMS)
{
	usleep(iMS);
}

void OpenBrowser(const tstring& sURL)
{
	system(convertstring<tchar, char>(tstring("firefox ") + sURL).c_str());
}

void CreateMinidump(void* pInfo, tchar* pszDirectory)
{
}

tstring OpenFileDialog(const tchar* pszFileTypes, const tchar* pszDirectory)
{
}

tstring SaveFileDialog(const tchar* pszFileTypes, const tchar* pszDirectory)
{
}

eastl::string GetClipboard()
{
}

void SetClipboard(const eastl::string& sBuf)
{
}

tstring GetAppDataDirectory(const tstring& sDirectory, const tstring& sFile)
{
	char* pszVar = getenv("HOME");

	tstring sSuffix;
	sSuffix.append(_T(".")).append(sDirectory).append(_T("/")).append(sFile);

	tstring sReturn(convertstring<char, tchar>(pszVar));

	mkdir(convertstring<tchar, char>(tstring(sReturn).append(_T("/")).append(_T(".")).append(sDirectory)).c_str(), 0777);

	sReturn.append(_T("/")).append(sSuffix);
	return sReturn;
}

eastl::vector<tstring> ListDirectory(tstring sDirectory, bool bDirectories)
{
	eastl::vector<tstring> asResult;

	struct dirent *dp;

	DIR *dir = opendir(convertstring<tchar, char>(sDirectory).c_str());
	while ((dp=readdir(dir)) != NULL)
	{
		if (!bDirectories && (dp->d_type == DT_DIR))
			continue;

		tstring sName = convertstring<char, tchar>(dp->d_name);
		if (sName == _T("."))
			continue;

		if (sName == _T(".."))
			continue;

		asResult.push_back(sName);
	}
	closedir(dir);

	return asResult;
}

bool IsFile(tstring sPath)
{
	struct stat stFileInfo;
	bool blnReturn;
	int intStat;

	// Attempt to get the file attributes
	intStat = stat(convertstring<tchar, char>(sPath).c_str(), &stFileInfo);
	if(intStat == 0 && S_ISREG(stFileInfo.st_mode))
		return true;
	else
		return false;
}

bool IsDirectory(tstring sPath)
{
	struct stat stFileInfo;
	bool blnReturn;
	int intStat;

	// Attempt to get the file attributes
	intStat = stat(convertstring<tchar, char>(sPath).c_str(), &stFileInfo);
	if(intStat == 0 && S_ISDIR(stFileInfo.st_mode))
		return true;
	else
		return false;
}

void DebugPrint(tstring sText)
{
	puts(convertstring<tchar, char>(sText).c_str());
}

void Exec(eastl::string sLine)
{
	system((tstring("./") + sLine).c_str());
}
<|endoftext|>


<commit_before>/*
 * exceptions.hpp
 *
 *  Created on: Oct 1, 2009 at 10:47:42 AM
 *      Author: Jean-Charles DELAY
 *      Mail  : jdelay@aldebaran-robotics.com
 */

#ifndef AL_TRANSPORT_EXCEPTIONS_HPP_
#define AL_TRANSPORT_EXCEPTIONS_HPP_

#include <exception>
#include <string>

namespace AL {
  namespace Transport {

    /// <summary>
    /// A basic exception class, base to other ippc:: exceptions.
    /// </summary>
class Exception : public std::exception {
public:
  Exception () {}
  Exception (const std::string & message) { this->message = message; }
  virtual ~Exception () throw () {}

  virtual const char * what () const throw () { return message.c_str(); }

private:
  std::string message;
};

/// <summary>
/// Exception thrown when creating/opening shared memory segments.
/// </summary>
class SharedSegmentInitializationException : public Exception {
public:
  SharedSegmentInitializationException () {}
  SharedSegmentInitializationException (const std::string & message) : Exception(message) {}
  virtual ~SharedSegmentInitializationException () throw () {}
};

/// <summary>
/// Exception thrown when the connection to the server fail.
/// </summary>
class ConnectionException : public Exception {
public:
  ConnectionException () {}
  ConnectionException (const std::string & message) : Exception(message) {}
  virtual ~ConnectionException () throw () {}
};

/// <summary>
/// Exception thrown when the server encountered a problem.
/// </summary>
class ServerException : public Exception {
public:
  ServerException () {}
  ServerException (const std::string & message) : Exception(message) {}
  virtual ~ServerException () throw () {}
};

/// <summary>
///Exception thrown when the server encountered a problem when reading.
/// </summary>
class ReadException : public Exception {
public:
  ReadException () {}
  ReadException (const std::string & message) : Exception(message) {}
  virtual ~ReadException () throw () {}
};

/// <summary>
/// Exception thrown when the client encountered a problem when writing.
/// </summary>
class WriteException : public Exception {
public:
  WriteException () {}
  WriteException (const std::string & message) : Exception(message) {}
  virtual ~WriteException () throw () {}
};

  }
}

#endif  // AL_TRANSPORT_EXCEPTIONS_HPP_
<commit_msg>Added a service not found exception<commit_after>/*
* exceptions.hpp
*
*  Created on: Oct 1, 2009 at 10:47:42 AM
*      Author: Jean-Charles DELAY
*      Mail  : jdelay@aldebaran-robotics.com
*/

#ifndef AL_TRANSPORT_EXCEPTIONS_HPP_
#define AL_TRANSPORT_EXCEPTIONS_HPP_

#include <exception>
#include <string>

namespace AL {
  namespace Transport {

    /// <summary>
    /// A basic exception class, base to other ippc:: exceptions.
    /// </summary>
    class Exception : public std::exception {
    public:
      Exception () {}
      Exception (const std::string & message) { this->message = message; }
      virtual ~Exception () throw () {}

      virtual const char * what () const throw () { return message.c_str(); }

    private:
      std::string message;
    };

    /// <summary>
    /// Exception thrown when creating/opening shared memory segments.
    /// </summary>
    class SharedSegmentInitializationException : public Exception {
    public:
      SharedSegmentInitializationException () {}
      SharedSegmentInitializationException (const std::string & message) : Exception(message) {}
      virtual ~SharedSegmentInitializationException () throw () {}
    };

    /// <summary>
    /// Exception thrown when the connection to the server fail.
    /// </summary>
    class ConnectionException : public Exception {
    public:
      ConnectionException () {}
      ConnectionException (const std::string & message) : Exception(message) {}
      virtual ~ConnectionException () throw () {}
    };

    /// <summary>
    /// Exception thrown when the server encountered a problem.
    /// </summary>
    class ServerException : public Exception {
    public:
      ServerException () {}
      ServerException (const std::string & message) : Exception(message) {}
      virtual ~ServerException () throw () {}
    };

    /// <summary>
    ///Exception thrown when the server encountered a problem when reading.
    /// </summary>
    class ReadException : public Exception {
    public:
      ReadException () {}
      ReadException (const std::string & message) : Exception(message) {}
      virtual ~ReadException () throw () {}
    };

    /// <summary>
    /// Exception thrown when the client encountered a problem when writing.
    /// </summary>
    class WriteException : public Exception {
    public:
      WriteException () {}
      WriteException (const std::string & message) : Exception(message) {}
      virtual ~WriteException () throw () {}
    };

    /// <summary>
    /// Exception thrown when the client can't find a service
    /// </summary>
    class ServiceNotFoundException : public Exception {
    public:
      ServiceNotFoundException () {}
      ServiceNotFoundException (const std::string & message) : Exception(message) {}
      virtual ~ServiceNotFoundException () throw () {}
    };

  }
}

#endif  // AL_TRANSPORT_EXCEPTIONS_HPP_
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "passes/techmap/libparse.h"

#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct statdata_t
{
	#define STAT_INT_MEMBERS X(num_wires) X(num_wire_bits) X(num_pub_wires) X(num_pub_wire_bits) \
			X(num_memories) X(num_memory_bits) X(num_cells) X(num_processes)

	#define STAT_NUMERIC_MEMBERS STAT_INT_MEMBERS X(area)

	#define X(_name) int _name;
	STAT_INT_MEMBERS
	#undef X
	double area;

	std::map<RTLIL::IdString, int, RTLIL::sort_by_id_str> num_cells_by_type;
	std::set<RTLIL::IdString> unknown_cell_area;

	statdata_t operator+(const statdata_t &other) const
	{
		statdata_t sum = other;
	#define X(_name) sum._name += _name;
		STAT_NUMERIC_MEMBERS
	#undef X
		for (auto &it : num_cells_by_type)
			sum.num_cells_by_type[it.first] += it.second;
		return sum;
	}

	statdata_t operator*(int other) const
	{
		statdata_t sum = *this;
	#define X(_name) sum._name *= other;
		STAT_NUMERIC_MEMBERS
	#undef X
		for (auto &it : sum.num_cells_by_type)
			it.second *= other;
		return sum;
	}

	statdata_t()
	{
	#define X(_name) _name = 0;
		STAT_NUMERIC_MEMBERS
	#undef X
	}

	statdata_t(RTLIL::Design *design, RTLIL::Module *mod, bool width_mode, const dict<IdString, double> &cell_area)
	{
	#define X(_name) _name = 0;
		STAT_NUMERIC_MEMBERS
	#undef X

		for (auto &it : mod->wires_)
		{
			if (!design->selected(mod, it.second))
				continue;

			if (it.first[0] == '\\') {
				num_pub_wires++;
				num_pub_wire_bits += it.second->width;
			}

			num_wires++;
			num_wire_bits += it.second->width;
		}

		for (auto &it : mod->memories) {
			if (!design->selected(mod, it.second))
				continue;
			num_memories++;
			num_memory_bits += it.second->width * it.second->size;
		}

		for (auto &it : mod->cells_)
		{
			if (!design->selected(mod, it.second))
				continue;

			RTLIL::IdString cell_type = it.second->type;

			if (width_mode)
			{
				if (cell_type.in("$not", "$pos", "$neg",
						"$logic_not", "$logic_and", "$logic_or",
						"$reduce_and", "$reduce_or", "$reduce_xor", "$reduce_xnor", "$reduce_bool",
						"$lut", "$and", "$or", "$xor", "$xnor",
						"$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx",
						"$lt", "$le", "$eq", "$ne", "$eqx", "$nex", "$ge", "$gt",
						"$add", "$sub", "$mul", "$div", "$mod", "$pow", "$alu")) {
					int width_a = it.second->hasPort("\\A") ? GetSize(it.second->getPort("\\A")) : 0;
					int width_b = it.second->hasPort("\\B") ? GetSize(it.second->getPort("\\B")) : 0;
					int width_y = it.second->hasPort("\\Y") ? GetSize(it.second->getPort("\\Y")) : 0;
					cell_type = stringf("%s_%d", cell_type.c_str(), max<int>({width_a, width_b, width_y}));
				}
				else if (cell_type.in("$mux", "$pmux"))
					cell_type = stringf("%s_%d", cell_type.c_str(), GetSize(it.second->getPort("\\Y")));
				else if (cell_type.in("$sr", "$dff", "$dffsr", "$adff", "$dlatch", "$dlatchsr"))
					cell_type = stringf("%s_%d", cell_type.c_str(), GetSize(it.second->getPort("\\Q")));
			}

			if (!cell_area.empty()) {
				if (cell_area.count(cell_type))
					area += cell_area.at(cell_type);
				else
					unknown_cell_area.insert(cell_type);
			}

			num_cells++;
			num_cells_by_type[cell_type]++;
		}

		for (auto &it : mod->processes) {
			if (!design->selected(mod, it.second))
				continue;
			num_processes++;
		}
	}

	void log_data(RTLIL::IdString mod_name, bool top_mod)
	{
		log("   Number of wires:             %6d\n", num_wires);
		log("   Number of wire bits:         %6d\n", num_wire_bits);
		log("   Number of public wires:      %6d\n", num_pub_wires);
		log("   Number of public wire bits:  %6d\n", num_pub_wire_bits);
		log("   Number of memories:          %6d\n", num_memories);
		log("   Number of memory bits:       %6d\n", num_memory_bits);
		log("   Number of processes:         %6d\n", num_processes);
		log("   Number of cells:             %6d\n", num_cells);
		for (auto &it : num_cells_by_type)
			log("     %-26s %6d\n", RTLIL::id2cstr(it.first), it.second);

		if (!unknown_cell_area.empty()) {
			log("\n");
			for (auto cell_type : unknown_cell_area)
				log("   Area for cell type %s is unknown!\n", cell_type.c_str());
		}

		if (area != 0) {
			log("\n");
			log("   Chip area for %smodule '%s': %f\n", (top_mod) ? "top " : "", mod_name.c_str(), area);
		}
	}
};

statdata_t hierarchy_worker(std::map<RTLIL::IdString, statdata_t> &mod_stat, RTLIL::IdString mod, int level)
{
	statdata_t mod_data = mod_stat.at(mod);
	std::map<RTLIL::IdString, int, RTLIL::sort_by_id_str> num_cells_by_type;
	num_cells_by_type.swap(mod_data.num_cells_by_type);

	for (auto &it : num_cells_by_type)
		if (mod_stat.count(it.first) > 0) {
			log("     %*s%-*s %6d\n", 2*level, "", 26-2*level, RTLIL::id2cstr(it.first), it.second);
			mod_data = mod_data + hierarchy_worker(mod_stat, it.first, level+1) * it.second;
			mod_data.num_cells -= it.second;
		} else {
			mod_data.num_cells_by_type[it.first] += it.second;
		}

	return mod_data;
}

void read_liberty_cellarea(dict<IdString, double> &cell_area, string liberty_file)
{
	std::ifstream f;
	f.open(liberty_file.c_str());
	yosys_input_files.insert(liberty_file);
	if (f.fail())
		log_cmd_error("Can't open liberty file `%s': %s\n", liberty_file.c_str(), strerror(errno));
	LibertyParser libparser(f);
	f.close();

	for (auto cell : libparser.ast->children)
	{
		if (cell->id != "cell" || cell->args.size() != 1)
			continue;

		LibertyAst *ar = cell->find("area");
		if (ar != NULL && !ar->value.empty())
			cell_area["\\" + cell->args[0]] = atof(ar->value.c_str());
	}
}

struct StatPass : public Pass {
	StatPass() : Pass("stat", "print some statistics") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    stat [options] [selection]\n");
		log("\n");
		log("Print some statistics (number of objects) on the selected portion of the\n");
		log("design.\n");
		log("\n");
		log("    -top <module>\n");
		log("        print design hierarchy with this module as top. if the design is fully\n");
		log("        selected and a module has the 'top' attribute set, this module is used\n");
		log("        default value for this option.\n");
		log("\n");
		log("    -liberty <liberty_file>\n");
		log("        use cell area information from the provided liberty file\n");
		log("\n");
		log("    -width\n");
		log("        annotate internal cell types with their word width.\n");
		log("        e.g. $add_8 for an 8 bit wide $add cell.\n");
		log("\n");
	}
	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		log_header(design, "Printing statistics.\n");

		bool width_mode = false;
		RTLIL::Module *top_mod = NULL;
		std::map<RTLIL::IdString, statdata_t> mod_stat;
		dict<IdString, double> cell_area;

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-width") {
				width_mode = true;
				continue;
			}
			if (args[argidx] == "-liberty" && argidx+1 < args.size()) {
				string liberty_file = args[++argidx];
				rewrite_filename(liberty_file);
				read_liberty_cellarea(cell_area, liberty_file);
				continue;
			}
			if (args[argidx] == "-top" && argidx+1 < args.size()) {
				if (design->modules_.count(RTLIL::escape_id(args[argidx+1])) == 0)
					log_cmd_error("Can't find module %s.\n", args[argidx+1].c_str());
				top_mod = design->modules_.at(RTLIL::escape_id(args[++argidx]));
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		for (auto mod : design->selected_modules())
		{
			if (!top_mod && design->full_selection())
				if (mod->get_bool_attribute("\\top"))
					top_mod = mod;

			if (mod->attributes.count("\\abc_box_id"))
				continue;

			statdata_t data(design, mod, width_mode, cell_area);
			mod_stat[mod->name] = data;

			log("\n");
			log("=== %s%s ===\n", RTLIL::id2cstr(mod->name), design->selected_whole_module(mod->name) ? "" : " (partially selected)");
			log("\n");
			data.log_data(mod->name, false);
		}

		if (top_mod != NULL && GetSize(mod_stat) > 1)
		{
			log("\n");
			log("=== design hierarchy ===\n");
			log("\n");

			log("   %-28s %6d\n", RTLIL::id2cstr(top_mod->name), 1);
			statdata_t data = hierarchy_worker(mod_stat, top_mod->name, 0);

			log("\n");
			data.log_data(top_mod->name, true);
		}

		log("\n");
	}
} StatPass;

PRIVATE_NAMESPACE_END
<commit_msg>Remove use of abc_box_id in stat<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "passes/techmap/libparse.h"

#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct statdata_t
{
	#define STAT_INT_MEMBERS X(num_wires) X(num_wire_bits) X(num_pub_wires) X(num_pub_wire_bits) \
			X(num_memories) X(num_memory_bits) X(num_cells) X(num_processes)

	#define STAT_NUMERIC_MEMBERS STAT_INT_MEMBERS X(area)

	#define X(_name) int _name;
	STAT_INT_MEMBERS
	#undef X
	double area;

	std::map<RTLIL::IdString, int, RTLIL::sort_by_id_str> num_cells_by_type;
	std::set<RTLIL::IdString> unknown_cell_area;

	statdata_t operator+(const statdata_t &other) const
	{
		statdata_t sum = other;
	#define X(_name) sum._name += _name;
		STAT_NUMERIC_MEMBERS
	#undef X
		for (auto &it : num_cells_by_type)
			sum.num_cells_by_type[it.first] += it.second;
		return sum;
	}

	statdata_t operator*(int other) const
	{
		statdata_t sum = *this;
	#define X(_name) sum._name *= other;
		STAT_NUMERIC_MEMBERS
	#undef X
		for (auto &it : sum.num_cells_by_type)
			it.second *= other;
		return sum;
	}

	statdata_t()
	{
	#define X(_name) _name = 0;
		STAT_NUMERIC_MEMBERS
	#undef X
	}

	statdata_t(RTLIL::Design *design, RTLIL::Module *mod, bool width_mode, const dict<IdString, double> &cell_area)
	{
	#define X(_name) _name = 0;
		STAT_NUMERIC_MEMBERS
	#undef X

		for (auto &it : mod->wires_)
		{
			if (!design->selected(mod, it.second))
				continue;

			if (it.first[0] == '\\') {
				num_pub_wires++;
				num_pub_wire_bits += it.second->width;
			}

			num_wires++;
			num_wire_bits += it.second->width;
		}

		for (auto &it : mod->memories) {
			if (!design->selected(mod, it.second))
				continue;
			num_memories++;
			num_memory_bits += it.second->width * it.second->size;
		}

		for (auto &it : mod->cells_)
		{
			if (!design->selected(mod, it.second))
				continue;

			RTLIL::IdString cell_type = it.second->type;

			if (width_mode)
			{
				if (cell_type.in("$not", "$pos", "$neg",
						"$logic_not", "$logic_and", "$logic_or",
						"$reduce_and", "$reduce_or", "$reduce_xor", "$reduce_xnor", "$reduce_bool",
						"$lut", "$and", "$or", "$xor", "$xnor",
						"$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx",
						"$lt", "$le", "$eq", "$ne", "$eqx", "$nex", "$ge", "$gt",
						"$add", "$sub", "$mul", "$div", "$mod", "$pow", "$alu")) {
					int width_a = it.second->hasPort("\\A") ? GetSize(it.second->getPort("\\A")) : 0;
					int width_b = it.second->hasPort("\\B") ? GetSize(it.second->getPort("\\B")) : 0;
					int width_y = it.second->hasPort("\\Y") ? GetSize(it.second->getPort("\\Y")) : 0;
					cell_type = stringf("%s_%d", cell_type.c_str(), max<int>({width_a, width_b, width_y}));
				}
				else if (cell_type.in("$mux", "$pmux"))
					cell_type = stringf("%s_%d", cell_type.c_str(), GetSize(it.second->getPort("\\Y")));
				else if (cell_type.in("$sr", "$dff", "$dffsr", "$adff", "$dlatch", "$dlatchsr"))
					cell_type = stringf("%s_%d", cell_type.c_str(), GetSize(it.second->getPort("\\Q")));
			}

			if (!cell_area.empty()) {
				if (cell_area.count(cell_type))
					area += cell_area.at(cell_type);
				else
					unknown_cell_area.insert(cell_type);
			}

			num_cells++;
			num_cells_by_type[cell_type]++;
		}

		for (auto &it : mod->processes) {
			if (!design->selected(mod, it.second))
				continue;
			num_processes++;
		}
	}

	void log_data(RTLIL::IdString mod_name, bool top_mod)
	{
		log("   Number of wires:             %6d\n", num_wires);
		log("   Number of wire bits:         %6d\n", num_wire_bits);
		log("   Number of public wires:      %6d\n", num_pub_wires);
		log("   Number of public wire bits:  %6d\n", num_pub_wire_bits);
		log("   Number of memories:          %6d\n", num_memories);
		log("   Number of memory bits:       %6d\n", num_memory_bits);
		log("   Number of processes:         %6d\n", num_processes);
		log("   Number of cells:             %6d\n", num_cells);
		for (auto &it : num_cells_by_type)
			log("     %-26s %6d\n", RTLIL::id2cstr(it.first), it.second);

		if (!unknown_cell_area.empty()) {
			log("\n");
			for (auto cell_type : unknown_cell_area)
				log("   Area for cell type %s is unknown!\n", cell_type.c_str());
		}

		if (area != 0) {
			log("\n");
			log("   Chip area for %smodule '%s': %f\n", (top_mod) ? "top " : "", mod_name.c_str(), area);
		}
	}
};

statdata_t hierarchy_worker(std::map<RTLIL::IdString, statdata_t> &mod_stat, RTLIL::IdString mod, int level)
{
	statdata_t mod_data = mod_stat.at(mod);
	std::map<RTLIL::IdString, int, RTLIL::sort_by_id_str> num_cells_by_type;
	num_cells_by_type.swap(mod_data.num_cells_by_type);

	for (auto &it : num_cells_by_type)
		if (mod_stat.count(it.first) > 0) {
			log("     %*s%-*s %6d\n", 2*level, "", 26-2*level, RTLIL::id2cstr(it.first), it.second);
			mod_data = mod_data + hierarchy_worker(mod_stat, it.first, level+1) * it.second;
			mod_data.num_cells -= it.second;
		} else {
			mod_data.num_cells_by_type[it.first] += it.second;
		}

	return mod_data;
}

void read_liberty_cellarea(dict<IdString, double> &cell_area, string liberty_file)
{
	std::ifstream f;
	f.open(liberty_file.c_str());
	yosys_input_files.insert(liberty_file);
	if (f.fail())
		log_cmd_error("Can't open liberty file `%s': %s\n", liberty_file.c_str(), strerror(errno));
	LibertyParser libparser(f);
	f.close();

	for (auto cell : libparser.ast->children)
	{
		if (cell->id != "cell" || cell->args.size() != 1)
			continue;

		LibertyAst *ar = cell->find("area");
		if (ar != NULL && !ar->value.empty())
			cell_area["\\" + cell->args[0]] = atof(ar->value.c_str());
	}
}

struct StatPass : public Pass {
	StatPass() : Pass("stat", "print some statistics") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    stat [options] [selection]\n");
		log("\n");
		log("Print some statistics (number of objects) on the selected portion of the\n");
		log("design.\n");
		log("\n");
		log("    -top <module>\n");
		log("        print design hierarchy with this module as top. if the design is fully\n");
		log("        selected and a module has the 'top' attribute set, this module is used\n");
		log("        default value for this option.\n");
		log("\n");
		log("    -liberty <liberty_file>\n");
		log("        use cell area information from the provided liberty file\n");
		log("\n");
		log("    -width\n");
		log("        annotate internal cell types with their word width.\n");
		log("        e.g. $add_8 for an 8 bit wide $add cell.\n");
		log("\n");
	}
	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		log_header(design, "Printing statistics.\n");

		bool width_mode = false;
		RTLIL::Module *top_mod = NULL;
		std::map<RTLIL::IdString, statdata_t> mod_stat;
		dict<IdString, double> cell_area;

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-width") {
				width_mode = true;
				continue;
			}
			if (args[argidx] == "-liberty" && argidx+1 < args.size()) {
				string liberty_file = args[++argidx];
				rewrite_filename(liberty_file);
				read_liberty_cellarea(cell_area, liberty_file);
				continue;
			}
			if (args[argidx] == "-top" && argidx+1 < args.size()) {
				if (design->modules_.count(RTLIL::escape_id(args[argidx+1])) == 0)
					log_cmd_error("Can't find module %s.\n", args[argidx+1].c_str());
				top_mod = design->modules_.at(RTLIL::escape_id(args[++argidx]));
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		for (auto mod : design->selected_modules())
		{
			if (!top_mod && design->full_selection())
				if (mod->get_bool_attribute("\\top"))
					top_mod = mod;

			statdata_t data(design, mod, width_mode, cell_area);
			mod_stat[mod->name] = data;

			log("\n");
			log("=== %s%s ===\n", RTLIL::id2cstr(mod->name), design->selected_whole_module(mod->name) ? "" : " (partially selected)");
			log("\n");
			data.log_data(mod->name, false);
		}

		if (top_mod != NULL && GetSize(mod_stat) > 1)
		{
			log("\n");
			log("=== design hierarchy ===\n");
			log("\n");

			log("   %-28s %6d\n", RTLIL::id2cstr(top_mod->name), 1);
			statdata_t data = hierarchy_worker(mod_stat, top_mod->name, 0);

			log("\n");
			data.log_data(top_mod->name, true);
		}

		log("\n");
	}
} StatPass;

PRIVATE_NAMESPACE_END
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

// TODO(ajm): Make this a comprehensive test.

extern "C" {
#include "webrtc/modules/audio_processing/utility/ring_buffer.h"
}

#include <stdlib.h>
#include <time.h>

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"

namespace webrtc {

struct FreeBufferDeleter {
  inline void operator()(void* ptr) const {
    WebRtc_FreeBuffer(ptr);
  }
};
typedef scoped_ptr<RingBuffer, FreeBufferDeleter> scoped_ring_buffer;

static void AssertElementEq(int expected, int actual) {
  ASSERT_EQ(expected, actual);
}

static int SetIncrementingData(int* data, int num_elements,
                               int starting_value) {
  for (int i = 0; i < num_elements; i++) {
    data[i] = starting_value++;
  }
  return starting_value;
}

static int CheckIncrementingData(int* data, int num_elements,
                                 int starting_value) {
  for (int i = 0; i < num_elements; i++) {
    AssertElementEq(starting_value++, data[i]);
  }
  return starting_value;
}

// We use ASSERTs in this test to avoid obscuring the seed in the case of a
// failure.
static void RandomStressTest(int** data_ptr) {
  const int kNumTests = 100;
  const int kNumOps = 10000;
  const int kMaxBufferSize = 1000;

  unsigned int seed = time(NULL);
  printf("seed=%u\n", seed);
  srand(seed);
  for (int i = 0; i < kNumTests; i++) {
    const int buffer_size = std::max(rand() % kMaxBufferSize, 1);
    scoped_ptr<int[]> write_data(new int[buffer_size]);
    scoped_ptr<int[]> read_data(new int[buffer_size]);
    scoped_ring_buffer buffer(WebRtc_CreateBuffer(buffer_size, sizeof(int)));
    ASSERT_TRUE(buffer.get() != NULL);
    ASSERT_EQ(0, WebRtc_InitBuffer(buffer.get()));
    int buffer_consumed = 0;
    int write_element = 0;
    int read_element = 0;
    for (int j = 0; j < kNumOps; j++) {
      const bool write = rand() % 2 == 0 ? true : false;
      const int num_elements = rand() % buffer_size;
      if (write) {
        const int buffer_available = buffer_size - buffer_consumed;
        ASSERT_EQ(static_cast<size_t>(buffer_available),
                  WebRtc_available_write(buffer.get()));
        const int expected_elements = std::min(num_elements, buffer_available);
        write_element = SetIncrementingData(write_data.get(), expected_elements,
                                     write_element);
        ASSERT_EQ(static_cast<size_t>(expected_elements),
                  WebRtc_WriteBuffer(buffer.get(), write_data.get(),
                                     num_elements));
        buffer_consumed = std::min(buffer_consumed + expected_elements,
                                   buffer_size);
      } else {
        const int expected_elements = std::min(num_elements,
                                               buffer_consumed);
        ASSERT_EQ(static_cast<size_t>(buffer_consumed),
                  WebRtc_available_read(buffer.get()));
        ASSERT_EQ(static_cast<size_t>(expected_elements),
                  WebRtc_ReadBuffer(buffer.get(),
                                    reinterpret_cast<void**>(data_ptr),
                                    read_data.get(),
                                    num_elements));
        int* check_ptr = read_data.get();
        if (data_ptr) {
          check_ptr = *data_ptr;
        }
        read_element = CheckIncrementingData(check_ptr, expected_elements,
                                             read_element);
        buffer_consumed = std::max(buffer_consumed - expected_elements, 0);
      }
    }
  }
}

TEST(RingBufferTest, RandomStressTest) {
  int* data_ptr = NULL;
  RandomStressTest(&data_ptr);
}

TEST(RingBufferTest, RandomStressTestWithNullPtr) {
  RandomStressTest(NULL);
}

TEST(RingBufferTest, PassingNulltoReadBufferForcesMemcpy) {
  const size_t kDataSize = 2;
  int write_data[kDataSize];
  int read_data[kDataSize];
  int* data_ptr;

  scoped_ring_buffer buffer(WebRtc_CreateBuffer(kDataSize, sizeof(int)));
  ASSERT_TRUE(buffer.get() != NULL);
  ASSERT_EQ(0, WebRtc_InitBuffer(buffer.get()));

  SetIncrementingData(write_data, kDataSize, 0);
  EXPECT_EQ(kDataSize, WebRtc_WriteBuffer(buffer.get(), write_data, kDataSize));
  SetIncrementingData(read_data, kDataSize, kDataSize);
  EXPECT_EQ(kDataSize, WebRtc_ReadBuffer(buffer.get(),
      reinterpret_cast<void**>(&data_ptr), read_data, kDataSize));
  // Copying was not necessary, so |read_data| has not been updated.
  CheckIncrementingData(data_ptr, kDataSize, 0);
  CheckIncrementingData(read_data, kDataSize, kDataSize);

  EXPECT_EQ(kDataSize, WebRtc_WriteBuffer(buffer.get(), write_data, kDataSize));
  EXPECT_EQ(kDataSize, WebRtc_ReadBuffer(buffer.get(), NULL, read_data,
                                         kDataSize));
  // Passing NULL forces a memcpy, so |read_data| is now updated.
  CheckIncrementingData(read_data, kDataSize, 0);
}

TEST(RingBufferTest, CreateHandlesErrors) {
  EXPECT_TRUE(WebRtc_CreateBuffer(0, 1) == NULL);
  EXPECT_TRUE(WebRtc_CreateBuffer(1, 0) == NULL);
  RingBuffer* buffer = WebRtc_CreateBuffer(1, 1);
  EXPECT_TRUE(buffer != NULL);
  WebRtc_FreeBuffer(buffer);
}

}  // namespace webrtc
<commit_msg>Reduce runtime of RingBufferTest by a factor of 100.<commit_after>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

// TODO(ajm): Make this a comprehensive test.

extern "C" {
#include "webrtc/modules/audio_processing/utility/ring_buffer.h"
}

#include <stdlib.h>
#include <time.h>

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"

namespace webrtc {

struct FreeBufferDeleter {
  inline void operator()(void* ptr) const {
    WebRtc_FreeBuffer(ptr);
  }
};
typedef scoped_ptr<RingBuffer, FreeBufferDeleter> scoped_ring_buffer;

static void AssertElementEq(int expected, int actual) {
  ASSERT_EQ(expected, actual);
}

static int SetIncrementingData(int* data, int num_elements,
                               int starting_value) {
  for (int i = 0; i < num_elements; i++) {
    data[i] = starting_value++;
  }
  return starting_value;
}

static int CheckIncrementingData(int* data, int num_elements,
                                 int starting_value) {
  for (int i = 0; i < num_elements; i++) {
    AssertElementEq(starting_value++, data[i]);
  }
  return starting_value;
}

// We use ASSERTs in this test to avoid obscuring the seed in the case of a
// failure.
static void RandomStressTest(int** data_ptr) {
  const int kNumTests = 10;
  const int kNumOps = 1000;
  const int kMaxBufferSize = 1000;

  unsigned int seed = time(NULL);
  printf("seed=%u\n", seed);
  srand(seed);
  for (int i = 0; i < kNumTests; i++) {
    const int buffer_size = std::max(rand() % kMaxBufferSize, 1);
    scoped_ptr<int[]> write_data(new int[buffer_size]);
    scoped_ptr<int[]> read_data(new int[buffer_size]);
    scoped_ring_buffer buffer(WebRtc_CreateBuffer(buffer_size, sizeof(int)));
    ASSERT_TRUE(buffer.get() != NULL);
    ASSERT_EQ(0, WebRtc_InitBuffer(buffer.get()));
    int buffer_consumed = 0;
    int write_element = 0;
    int read_element = 0;
    for (int j = 0; j < kNumOps; j++) {
      const bool write = rand() % 2 == 0 ? true : false;
      const int num_elements = rand() % buffer_size;
      if (write) {
        const int buffer_available = buffer_size - buffer_consumed;
        ASSERT_EQ(static_cast<size_t>(buffer_available),
                  WebRtc_available_write(buffer.get()));
        const int expected_elements = std::min(num_elements, buffer_available);
        write_element = SetIncrementingData(write_data.get(), expected_elements,
                                     write_element);
        ASSERT_EQ(static_cast<size_t>(expected_elements),
                  WebRtc_WriteBuffer(buffer.get(), write_data.get(),
                                     num_elements));
        buffer_consumed = std::min(buffer_consumed + expected_elements,
                                   buffer_size);
      } else {
        const int expected_elements = std::min(num_elements,
                                               buffer_consumed);
        ASSERT_EQ(static_cast<size_t>(buffer_consumed),
                  WebRtc_available_read(buffer.get()));
        ASSERT_EQ(static_cast<size_t>(expected_elements),
                  WebRtc_ReadBuffer(buffer.get(),
                                    reinterpret_cast<void**>(data_ptr),
                                    read_data.get(),
                                    num_elements));
        int* check_ptr = read_data.get();
        if (data_ptr) {
          check_ptr = *data_ptr;
        }
        read_element = CheckIncrementingData(check_ptr, expected_elements,
                                             read_element);
        buffer_consumed = std::max(buffer_consumed - expected_elements, 0);
      }
    }
  }
}

TEST(RingBufferTest, RandomStressTest) {
  int* data_ptr = NULL;
  RandomStressTest(&data_ptr);
}

TEST(RingBufferTest, RandomStressTestWithNullPtr) {
  RandomStressTest(NULL);
}

TEST(RingBufferTest, PassingNulltoReadBufferForcesMemcpy) {
  const size_t kDataSize = 2;
  int write_data[kDataSize];
  int read_data[kDataSize];
  int* data_ptr;

  scoped_ring_buffer buffer(WebRtc_CreateBuffer(kDataSize, sizeof(int)));
  ASSERT_TRUE(buffer.get() != NULL);
  ASSERT_EQ(0, WebRtc_InitBuffer(buffer.get()));

  SetIncrementingData(write_data, kDataSize, 0);
  EXPECT_EQ(kDataSize, WebRtc_WriteBuffer(buffer.get(), write_data, kDataSize));
  SetIncrementingData(read_data, kDataSize, kDataSize);
  EXPECT_EQ(kDataSize, WebRtc_ReadBuffer(buffer.get(),
      reinterpret_cast<void**>(&data_ptr), read_data, kDataSize));
  // Copying was not necessary, so |read_data| has not been updated.
  CheckIncrementingData(data_ptr, kDataSize, 0);
  CheckIncrementingData(read_data, kDataSize, kDataSize);

  EXPECT_EQ(kDataSize, WebRtc_WriteBuffer(buffer.get(), write_data, kDataSize));
  EXPECT_EQ(kDataSize, WebRtc_ReadBuffer(buffer.get(), NULL, read_data,
                                         kDataSize));
  // Passing NULL forces a memcpy, so |read_data| is now updated.
  CheckIncrementingData(read_data, kDataSize, 0);
}

TEST(RingBufferTest, CreateHandlesErrors) {
  EXPECT_TRUE(WebRtc_CreateBuffer(0, 1) == NULL);
  EXPECT_TRUE(WebRtc_CreateBuffer(1, 0) == NULL);
  RingBuffer* buffer = WebRtc_CreateBuffer(1, 1);
  EXPECT_TRUE(buffer != NULL);
  WebRtc_FreeBuffer(buffer);
}

}  // namespace webrtc
<|endoftext|>