<commit_before>/*
 *  Copyright (c) 2012 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.
 */

#include "spatial_resampler.h"

namespace webrtc {

VPMSimpleSpatialResampler::VPMSimpleSpatialResampler()
:
_resamplingMode(kFastRescaling),
_targetWidth(0),
_targetHeight(0),
_scaler()
{
}

VPMSimpleSpatialResampler::~VPMSimpleSpatialResampler()
{
  //
}

WebRtc_Word32
VPMSimpleSpatialResampler::SetTargetFrameSize(WebRtc_Word32 width,
                                              WebRtc_Word32 height)
{
  if (_resamplingMode == kNoRescaling)  {
    return VPM_OK;
  }

  if (width < 1 || height < 1)  {
    return VPM_PARAMETER_ERROR;
  }

  _targetWidth = width;
  _targetHeight = height;

  return VPM_OK;
}

void
VPMSimpleSpatialResampler::SetInputFrameResampleMode(VideoFrameResampling
                                                     resamplingMode)
{
  _resamplingMode = resamplingMode;
}

void
VPMSimpleSpatialResampler::Reset()
{
  _resamplingMode = kFastRescaling;
  _targetWidth = 0;
  _targetHeight = 0;
}

WebRtc_Word32
VPMSimpleSpatialResampler::ResampleFrame(const VideoFrame& inFrame,
                                         VideoFrame& outFrame)
{
  if (_resamplingMode == kNoRescaling)
     return outFrame.CopyFrame(inFrame);
  // Check if re-sampling is needed
  if ((inFrame.Width() == (WebRtc_UWord32)_targetWidth) &&
    (inFrame.Height() == (WebRtc_UWord32)_targetHeight))  {
    return outFrame.CopyFrame(inFrame);
  }

  // Setting scaler
  // TODO(mikhal/marpan): Should we allow for setting the filter mode in
  // _scale.Set() with |_resamplingMode|?
  int retVal = 0;
  retVal = _scaler.Set(inFrame.Width(), inFrame.Height(),
                       _targetWidth, _targetHeight, kI420, kI420, kScaleBox);
  if (retVal < 0)
    return retVal;

  // Disabling cut/pad for now - only scaling.
  int target_half_width = (_targetWidth + 1) >> 1;
  int target_half_height = (_targetHeight + 1) >> 1;
  int requiredSize = static_cast<int>(_targetWidth * _targetHeight + 2 *
      (target_half_width * target_half_height));
  outFrame.VerifyAndAllocate(requiredSize);
  outFrame.SetTimeStamp(inFrame.TimeStamp());
  outFrame.SetRenderTime(inFrame.RenderTimeMs());
  outFrame.SetWidth(_targetWidth);
  outFrame.SetHeight(_targetHeight);

  retVal = _scaler.Scale(inFrame.Buffer(), outFrame.Buffer(), requiredSize);
  outFrame.SetLength(requiredSize);
  if (retVal == 0)
    return VPM_OK;
  else
    return VPM_SCALE_ERROR;
}

WebRtc_Word32
VPMSimpleSpatialResampler::TargetHeight()
{
  return _targetHeight;
}

WebRtc_Word32
VPMSimpleSpatialResampler::TargetWidth()
{
  return _targetWidth;
}

bool
VPMSimpleSpatialResampler::ApplyResample(WebRtc_Word32 width,
                                         WebRtc_Word32 height)
{
  if ((width == _targetWidth && height == _targetHeight) ||
       _resamplingMode == kNoRescaling)
    return false;
  else
    return true;
}

} //namespace
<commit_msg>vpm: Updating module to use CalcBufferSize<commit_after>/*
 *  Copyright (c) 2012 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.
 */

#include "spatial_resampler.h"

namespace webrtc {

VPMSimpleSpatialResampler::VPMSimpleSpatialResampler()
:
_resamplingMode(kFastRescaling),
_targetWidth(0),
_targetHeight(0),
_scaler()
{
}

VPMSimpleSpatialResampler::~VPMSimpleSpatialResampler()
{
  //
}

WebRtc_Word32
VPMSimpleSpatialResampler::SetTargetFrameSize(WebRtc_Word32 width,
                                              WebRtc_Word32 height)
{
  if (_resamplingMode == kNoRescaling)  {
    return VPM_OK;
  }

  if (width < 1 || height < 1)  {
    return VPM_PARAMETER_ERROR;
  }

  _targetWidth = width;
  _targetHeight = height;

  return VPM_OK;
}

void
VPMSimpleSpatialResampler::SetInputFrameResampleMode(VideoFrameResampling
                                                     resamplingMode)
{
  _resamplingMode = resamplingMode;
}

void
VPMSimpleSpatialResampler::Reset()
{
  _resamplingMode = kFastRescaling;
  _targetWidth = 0;
  _targetHeight = 0;
}

WebRtc_Word32
VPMSimpleSpatialResampler::ResampleFrame(const VideoFrame& inFrame,
                                         VideoFrame& outFrame)
{
  if (_resamplingMode == kNoRescaling)
     return outFrame.CopyFrame(inFrame);
  // Check if re-sampling is needed
  if ((inFrame.Width() == (WebRtc_UWord32)_targetWidth) &&
    (inFrame.Height() == (WebRtc_UWord32)_targetHeight))  {
    return outFrame.CopyFrame(inFrame);
  }

  // Setting scaler
  // TODO(mikhal/marpan): Should we allow for setting the filter mode in
  // _scale.Set() with |_resamplingMode|?
  int retVal = 0;
  retVal = _scaler.Set(inFrame.Width(), inFrame.Height(),
                       _targetWidth, _targetHeight, kI420, kI420, kScaleBox);
  if (retVal < 0)
    return retVal;

  // Disabling cut/pad for now - only scaling.
  int requiredSize = CalcBufferSize(kI420, _targetWidth, _targetHeight);
  outFrame.VerifyAndAllocate(requiredSize);
  outFrame.SetTimeStamp(inFrame.TimeStamp());
  outFrame.SetRenderTime(inFrame.RenderTimeMs());
  outFrame.SetWidth(_targetWidth);
  outFrame.SetHeight(_targetHeight);

  retVal = _scaler.Scale(inFrame.Buffer(), outFrame.Buffer(), requiredSize);
  outFrame.SetLength(requiredSize);
  if (retVal == 0)
    return VPM_OK;
  else
    return VPM_SCALE_ERROR;
}

WebRtc_Word32
VPMSimpleSpatialResampler::TargetHeight()
{
  return _targetHeight;
}

WebRtc_Word32
VPMSimpleSpatialResampler::TargetWidth()
{
  return _targetWidth;
}

bool
VPMSimpleSpatialResampler::ApplyResample(WebRtc_Word32 width,
                                         WebRtc_Word32 height)
{
  if ((width == _targetWidth && height == _targetHeight) ||
       _resamplingMode == kNoRescaling)
    return false;
  else
    return true;
}

} //namespace
<|endoftext|>


<commit_before>// Copyright Steinwurf ApS 2015.
// All Rights Reserved

#pragma once

#include "decoder_config_descriptor.hpp"
#include "decoder_specific_info_descriptor.hpp"
#include "descriptor.hpp"
#include "elemetary_stream_descriptor.hpp"
#include "empty_descriptor.hpp"
#include "sl_config_descriptor.hpp"<commit_msg>added missing newline<commit_after>// Copyright Steinwurf ApS 2015.
// All Rights Reserved

#pragma once

#include "decoder_config_descriptor.hpp"
#include "decoder_specific_info_descriptor.hpp"
#include "descriptor.hpp"
#include "elemetary_stream_descriptor.hpp"
#include "empty_descriptor.hpp"
#include "sl_config_descriptor.hpp"
<|endoftext|>


<commit_before>// Standard includes
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <inttypes.h>
#include <fstream>
#include <sys/time.h>
#include <limits.h>

// Serial includes
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#
#ifdef __linux
#include <sys/ioctl.h>
#endif

//#include "serialwifly.h" 	// this is from Louis' wifly code, which will be a library
#include "serial_lib/wifly_serial.h" // include the new class for handling a wifly
#include "common.h"
#include "wifly_thread.h"
// #include "test.h" 			// for bearing calculation
#include "commander.h"
#include "bearing_lib/bearing.h"		// this should be all the functions required for bearing calculations

using std::string;
using std::vector;
using namespace std;

/* this is to help with some of the rotation logic */
bool in_rotation = false;

/* keep track of the previous hunt state, as hunt state is sent periodically, not just on updates */
uint8_t prev_hunt_state = 10;

/* whether or not we are currently rotating */
bool rotating = false;

/* whether or not we are currently moving */
bool moving = false;

/* microsecond timestamp of the previous loop iteration */
unsigned long prev_loop_timestamp = 0;

void update_state(uint8_t &new_state) {

	switch (new_state) {
	case TRACKING_HUNT_STATE_ROTATE:
		rotating = true;
		break;
	case TRACKING_HUNT_STATE_MOVE:
		moving = true;
		break;
	case TRACKING_HUNT_STATE_OFF:
		// finished = true;
		break;
	case TRACKING_HUNT_STATE_START:
		// starting = true;
		break;
	}
}

int get_max_rssi(vector<double> rssi_values) {

	double max_rssi = INT_MIN;

	int len = rssi_values.size();
	for (int i = 0; i < len; i++) {
		if (rssi_values[i] > max_rssi && rssi_values[i] < 0) {
			max_rssi = rssi_values[i];
		}
	}

	// return the negative because need it to be a positive value for later
	return (int) -max_rssi;
}

void *wifly_thread(void *param) {

	// retrieve the MAVInfo struct that is sent to this function as a parameter
	struct MAVInfo *uavData = (struct MAVInfo *)param;

	// some constants that all need to become parameters
	char *ssid = (char *)"JAMMER01"; // "ADL"; // "JAMMER01";
	char *file_name = (char *) "wifly.csv";
	char *file_name2 = (char *) "wifly2.csv";
	char *bearing_file_name = (char *) "bearing_calc_cc.csv";
	char *bearing_mle_file_name = (char *) "bearing_calc_mle.csv";
	// char *port = (char *) "/dev/ttyUSB0";

	// connect to the first wifly
	WiflySerial* wifly1 = new WiflySerial(verbose, wifly_port1);
	if (wifly1->fd < 0) {
		printf("Error opening wifly connection\n");
		return NULL;
	}

	// connect to the second wifly
	WiflySerial* wifly2 = nullptr;
	if (dual_wifly) {
		wifly2 = new WiflySerial(verbose, wifly_port2);
		if (wifly2->fd < 0) {
			printf("Error opening wifly connection\n");
			return NULL;
		}
	}

	/* Go into command mode */
	wifly1->enter_commandmode();
	if (dual_wifly) {
		wifly2->enter_commandmode();
	}

	/* Open a file to write values to */
	/* Appending values */
	FILE *wifly_file = fopen(file_name, "a");
	if (wifly_file == NULL)
	{
		// TODO: figure out what we do want to return when there is an error
		printf("Error opening wifly output file\n");
		return NULL;
	}

	FILE *wifly_file2 = NULL;
	if (dual_wifly) {
		wifly_file2 = fopen(file_name2, "a");
		if (wifly_file2 == NULL) {
			// TODO: figure out what we do want to return when there is an error
			printf("Error opening wifly2 output file\n");
			return NULL;
		}
	}

	/* Open a file to write bearing calcs to */
	FILE *bearing_file = fopen(bearing_file_name, "a");
	if (bearing_file == NULL)
	{
		// TODO: figure out what we do want to return when there is an error
		printf("Error opening bearing output file\n");
		return NULL;
	}

	FILE *bearing_file_mle = NULL;
	if (dual_wifly) {
		bearing_file_mle = fopen(bearing_mle_file_name, "a");
		if (bearing_file_mle == NULL) {
			printf("Error opening bearing mle output file\n");
			return NULL;
		}
	}

	if (get_commands) {
		bool loaded = load_move_commands();
		if (!loaded) {
			printf("Error loading move commands\n");
			return NULL;
		}
	}

	vector<double> angles;
	vector<double> gains;
	vector<double> omni_gains;
	vector<int> norm_gains;

	struct timeval tv;

	double bearing_cc;
	int max_rssi;

	bool send_next = false;

	// main loop that should be constantly taking measurements
	// until the main program is stopped
	while (RUNNING_FLAG) {

		// only want to execute this at most ever 30 ms
		// basically does a dynamic sleep in the sense that if there is a lot of processing time for doing the bearing
		// calculation, we will only pause as long as required so measurements are really made every 30 ms
		// (unless of course bearing calculations take too long)
		gettimeofday(&tv, NULL);
		unsigned long current_loop_time = 1000000 * tv.tv_sec + tv.tv_usec;
		if (prev_loop_timestamp != 0 && (current_loop_time - prev_loop_timestamp) < 30000) {
			continue;
		}
		prev_loop_timestamp = current_loop_time;

		// handle hunt state changes required (sending of commands)
		if (uavData->tracking_status.hunt_mode_state != prev_hunt_state) {

			printf("State changed from %u to %u\n", prev_hunt_state, uavData->tracking_status.hunt_mode_state);

			if (uavData->tracking_status.hunt_mode_state == TRACKING_HUNT_STATE_WAIT) {
				send_next = true;
				// TODO: maybe want to update the state immediately here...
			} else {
				update_state(uavData->tracking_status.hunt_mode_state);
			}

			// update the prev hunt state to be this new state
			prev_hunt_state = uavData->tracking_status.hunt_mode_state;
			printf("Prev State changed to: %u\n", prev_hunt_state);
		}

		//-----------------------------------------------//
		// make measurement, and get start and end angle (for during the measurement)
		//-----------------------------------------------//

		// TODO: potentially capture all measurements at the same time as
		// making the rssi measurement (i.e. lat, lon, alt)
		// not sure what the variability is from here to later on

		int dir_rssi = INT_MAX;
		int omni_rssi = INT_MAX;

		if (verbose) printf("scanning wifly 1...\n");
		int16_t heading_dir_pre = uavData->vfr_hud.heading;
		dir_rssi = wifly1->scanrssi(ssid);

		printf("dir rssi recevied: %i\n", dir_rssi);

		int16_t heading_dir_post = uavData->vfr_hud.heading;

		int16_t heading_omni_pre = uavData->vfr_hud.heading;
		if (dual_wifly) {
			if (verbose) printf("scanning wifly 2...\n");
			omni_rssi = wifly2->scanrssi(ssid);
		}
		int16_t heading_omni_post = uavData->vfr_hud.heading;

		//-----------------------------------------------//
		// Rotation specific calculations
		//-----------------------------------------------//

		/* check if we are in an official rotation */
		if (rotating) {
			if (!in_rotation) {
				if (verbose) printf("rotation started\n");
				// set our logic to mark we are now running the rotation logic
				in_rotation = true;

				// clear the vectors
				angles.clear();
				gains.clear();
				omni_gains.clear();
				norm_gains.clear();
			}

			if (verbose) printf("rotating\n");

			// add heading and rssi to the correct arrays
			angles.push_back((double) heading_dir_pre);
			gains.push_back(dir_rssi);

			if (dual_wifly) {

				// add omni rssi to the correct array
				omni_gains.push_back(omni_rssi);

				// calculate the normalized gains
				norm_gains.push_back(gains2normgain(dir_rssi, omni_rssi));

				// do constant calculation of bearing
				if (verbose) printf("calculating bearing mle\n");
				double curr_bearing_est = get_bearing_mle(angles, norm_gains);

				// save the calculated mle bearing
				fprintf(bearing_file_mle, "%llu,%i,%i,%f,%f\n", uavData->sys_time_us.time_unix_usec,
					uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, curr_bearing_est);

				// send a mavlink message of the calculated mle bearing
				send_bearing_mle_message(curr_bearing_est, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

			}
		}

		/* catch the end of a rotation in order to do the cc gain measurement */
		if (!rotating && in_rotation) {
			if (verbose) printf("ended rotation\n");
			in_rotation = false;

			if (verbose) printf("calculating cc bearing\n");
			// do bearing calculation at this point
			bearing_cc = get_bearing_cc(angles, gains);
			// double bearing = 32.0; // NOT SURE WHAT THIS IS DOING HERE....

			// get what the max value was for the rssi
			max_rssi = get_max_rssi(gains);

			// save bearing cc to file (with important information)
			fprintf(bearing_file, "%llu,%i,%i,%f,%f\n", uavData->sys_time_us.time_unix_usec,
				uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, bearing_cc);

			// send a mavlink message of the calculated bearing
			send_bearing_cc_message(bearing_cc, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

			// tell pixhawk we are finished with the rotation
			// send_finish_command();
		}

		//-----------------------------------------------//
		// save the measured data information to file
		//-----------------------------------------------//

		/* write the directional atenna information */
		printf("writing dir rssi to file: %i\n", dir_rssi);
		fprintf(wifly_file, "%llu,%u,%i,%i,%i,%i,%f,%i\n",
				uavData->sys_time_us.time_unix_usec, uavData->custom_mode, heading_dir_pre, heading_dir_post,
				uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, dir_rssi);

		/* write the omni measurement as needed */
		if (dual_wifly) {
			fprintf(wifly_file2, "%llu,%u,%i,%i,%i,%i,%f,%i\n",
				uavData->sys_time_us.time_unix_usec, uavData->custom_mode, heading_omni_pre, heading_omni_post,
				uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, omni_rssi);
		}

		// send a mavlink message with the current rssi
		send_rssi_message(dir_rssi, heading_dir_pre, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

		if (send_next) {
			send_next_command(prev_hunt_state, uavData->tracking_status.hunt_mode_state, bearing_cc, max_rssi);
			send_next = false;
		}

	} // end of while running

	/* Be sure to close the output file and connection */
	fclose(wifly_file);
	fclose(bearing_file);
	wifly1->end_serial();

	if (dual_wifly) {
		fclose(wifly_file2);
		fclose(bearing_file_mle);
		wifly2->end_serial();
	}

	return NULL;
}
<commit_msg>more debugging<commit_after>// Standard includes
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <inttypes.h>
#include <fstream>
#include <sys/time.h>
#include <limits.h>

// Serial includes
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#
#ifdef __linux
#include <sys/ioctl.h>
#endif

//#include "serialwifly.h" 	// this is from Louis' wifly code, which will be a library
#include "serial_lib/wifly_serial.h" // include the new class for handling a wifly
#include "common.h"
#include "wifly_thread.h"
// #include "test.h" 			// for bearing calculation
#include "commander.h"
#include "bearing_lib/bearing.h"		// this should be all the functions required for bearing calculations

using std::string;
using std::vector;
using namespace std;

/* this is to help with some of the rotation logic */
bool in_rotation = false;

/* keep track of the previous hunt state, as hunt state is sent periodically, not just on updates */
uint8_t prev_hunt_state = 10;

/* whether or not we are currently rotating */
bool rotating = false;

/* whether or not we are currently moving */
bool moving = false;

/* microsecond timestamp of the previous loop iteration */
unsigned long prev_loop_timestamp = 0;

void update_state(uint8_t &new_state) {

	switch (new_state) {
	case TRACKING_HUNT_STATE_ROTATE:
		rotating = true;
		break;
	case TRACKING_HUNT_STATE_MOVE:
		moving = true;
		break;
	case TRACKING_HUNT_STATE_OFF:
		// finished = true;
		break;
	case TRACKING_HUNT_STATE_START:
		// starting = true;
		break;
	}
}

int get_max_rssi(vector<double> rssi_values) {

	double max_rssi = INT_MIN;

	int len = rssi_values.size();
	for (int i = 0; i < len; i++) {
		if (rssi_values[i] > max_rssi && rssi_values[i] < 0) {
			max_rssi = rssi_values[i];
		}
	}

	// return the negative because need it to be a positive value for later
	return (int) -max_rssi;
}

void *wifly_thread(void *param) {

	// retrieve the MAVInfo struct that is sent to this function as a parameter
	struct MAVInfo *uavData = (struct MAVInfo *)param;

	// some constants that all need to become parameters
	char *ssid = (char *) "JAMMER01"; // "ADL"; // "JAMMER01";
	char *file_name = (char *) "wifly.csv";
	char *file_name2 = (char *) "wifly2.csv";
	char *bearing_file_name = (char *) "bearing_calc_cc.csv";
	char *bearing_mle_file_name = (char *) "bearing_calc_mle.csv";
	// char *port = (char *) "/dev/ttyUSB0";

	// connect to the first wifly
	WiflySerial* wifly1 = new WiflySerial(verbose, wifly_port1);
	if (wifly1->fd < 0) {
		printf("Error opening wifly connection\n");
		return NULL;
	}

	// connect to the second wifly
	WiflySerial* wifly2 = nullptr;
	if (dual_wifly) {
		wifly2 = new WiflySerial(verbose, wifly_port2);
		if (wifly2->fd < 0) {
			printf("Error opening wifly connection\n");
			return NULL;
		}
	}

	/* Go into command mode */
	wifly1->enter_commandmode();
	if (dual_wifly) {
		wifly2->enter_commandmode();
	}

	/* Open a file to write values to */
	/* Appending values */
	FILE *wifly_file = fopen(file_name, "a");
	if (wifly_file == NULL)
	{
		// TODO: figure out what we do want to return when there is an error
		printf("Error opening wifly output file\n");
		return NULL;
	}

	FILE *wifly_file2 = NULL;
	if (dual_wifly) {
		wifly_file2 = fopen(file_name2, "a");
		if (wifly_file2 == NULL) {
			// TODO: figure out what we do want to return when there is an error
			printf("Error opening wifly2 output file\n");
			return NULL;
		}
	}

	/* Open a file to write bearing calcs to */
	FILE *bearing_file = fopen(bearing_file_name, "a");
	if (bearing_file == NULL)
	{
		// TODO: figure out what we do want to return when there is an error
		printf("Error opening bearing output file\n");
		return NULL;
	}

	FILE *bearing_file_mle = NULL;
	if (dual_wifly) {
		bearing_file_mle = fopen(bearing_mle_file_name, "a");
		if (bearing_file_mle == NULL) {
			printf("Error opening bearing mle output file\n");
			return NULL;
		}
	}

	if (get_commands) {
		bool loaded = load_move_commands();
		if (!loaded) {
			printf("Error loading move commands\n");
			return NULL;
		}
	}

	vector<double> angles;
	vector<double> gains;
	vector<double> omni_gains;
	vector<int> norm_gains;

	struct timeval tv;

	double bearing_cc;
	int max_rssi;

	bool send_next = false;

	// main loop that should be constantly taking measurements
	// until the main program is stopped
	while (RUNNING_FLAG) {

		// only want to execute this at most ever 30 ms
		// basically does a dynamic sleep in the sense that if there is a lot of processing time for doing the bearing
		// calculation, we will only pause as long as required so measurements are really made every 30 ms
		// (unless of course bearing calculations take too long)
		gettimeofday(&tv, NULL);
		unsigned long current_loop_time = 1000000 * tv.tv_sec + tv.tv_usec;
		if (prev_loop_timestamp != 0 && (current_loop_time - prev_loop_timestamp) < 30000) {
			continue;
		}
		prev_loop_timestamp = current_loop_time;

		// handle hunt state changes required (sending of commands)
		if (uavData->tracking_status.hunt_mode_state != prev_hunt_state) {

			printf("State changed from %u to %u\n", prev_hunt_state, uavData->tracking_status.hunt_mode_state);

			if (uavData->tracking_status.hunt_mode_state == TRACKING_HUNT_STATE_WAIT) {
				send_next = true;
				// TODO: maybe want to update the state immediately here...
			} else {
				update_state(uavData->tracking_status.hunt_mode_state);
			}

			// update the prev hunt state to be this new state
			prev_hunt_state = uavData->tracking_status.hunt_mode_state;
			printf("Prev State changed to: %u\n", prev_hunt_state);
		}

		//-----------------------------------------------//
		// make measurement, and get start and end angle (for during the measurement)
		//-----------------------------------------------//

		// TODO: potentially capture all measurements at the same time as
		// making the rssi measurement (i.e. lat, lon, alt)
		// not sure what the variability is from here to later on

		int dir_rssi = INT_MAX;
		int omni_rssi = INT_MAX;

		if (verbose) printf("scanning wifly 1...\n");
		int16_t heading_dir_pre = uavData->vfr_hud.heading;
		dir_rssi = wifly1->scanrssi(ssid);

		printf("dir rssi recevied: %i\n", dir_rssi);

		int16_t heading_dir_post = uavData->vfr_hud.heading;

		int16_t heading_omni_pre = uavData->vfr_hud.heading;
		if (dual_wifly) {
			if (verbose) printf("scanning wifly 2...\n");
			omni_rssi = wifly2->scanrssi(ssid);
		}
		int16_t heading_omni_post = uavData->vfr_hud.heading;

		//-----------------------------------------------//
		// Rotation specific calculations
		//-----------------------------------------------//

		/* check if we are in an official rotation */
		if (rotating) {
			if (!in_rotation) {
				if (verbose) printf("rotation started\n");
				// set our logic to mark we are now running the rotation logic
				in_rotation = true;

				// clear the vectors
				angles.clear();
				gains.clear();
				omni_gains.clear();
				norm_gains.clear();
			}

			if (verbose) printf("rotating\n");

			// add heading and rssi to the correct arrays
			angles.push_back((double) heading_dir_pre);
			gains.push_back(dir_rssi);

			if (dual_wifly) {

				// add omni rssi to the correct array
				omni_gains.push_back(omni_rssi);

				// calculate the normalized gains
				norm_gains.push_back(gains2normgain(dir_rssi, omni_rssi));

				// do constant calculation of bearing
				if (verbose) printf("calculating bearing mle\n");
				double curr_bearing_est = get_bearing_mle(angles, norm_gains);

				// save the calculated mle bearing
				fprintf(bearing_file_mle, "%llu,%i,%i,%f,%f\n", uavData->sys_time_us.time_unix_usec,
					uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, curr_bearing_est);

				// send a mavlink message of the calculated mle bearing
				send_bearing_mle_message(curr_bearing_est, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

			}
		}

		/* catch the end of a rotation in order to do the cc gain measurement */
		if (!rotating && in_rotation) {
			if (verbose) printf("ended rotation\n");
			in_rotation = false;

			if (verbose) printf("calculating cc bearing\n");
			// do bearing calculation at this point
			bearing_cc = get_bearing_cc(angles, gains);
			// double bearing = 32.0; // NOT SURE WHAT THIS IS DOING HERE....

			// get what the max value was for the rssi
			max_rssi = get_max_rssi(gains);

			// save bearing cc to file (with important information)
			fprintf(bearing_file, "%llu,%i,%i,%f,%f\n", uavData->sys_time_us.time_unix_usec,
				uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, bearing_cc);

			// send a mavlink message of the calculated bearing
			send_bearing_cc_message(bearing_cc, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

			// tell pixhawk we are finished with the rotation
			// send_finish_command();
		}

		//-----------------------------------------------//
		// save the measured data information to file
		//-----------------------------------------------//

		/* write the directional atenna information */
		printf("writing dir rssi to file: %i\n", dir_rssi);
		fprintf(wifly_file, "%llu,%u,%i,%i,%i,%i,%f,%i\n",
				uavData->sys_time_us.time_unix_usec, uavData->custom_mode, heading_dir_pre, heading_dir_post,
				uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, dir_rssi);

		/* write the omni measurement as needed */
		if (dual_wifly) {
			fprintf(wifly_file2, "%llu,%u,%i,%i,%i,%i,%f,%i\n",
				uavData->sys_time_us.time_unix_usec, uavData->custom_mode, heading_omni_pre, heading_omni_post,
				uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, omni_rssi);
		}

		// send a mavlink message with the current rssi
		send_rssi_message(dir_rssi, heading_dir_pre, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

		if (send_next) {
			send_next_command(prev_hunt_state, uavData->tracking_status.hunt_mode_state, bearing_cc, max_rssi);
			send_next = false;
		}

	} // end of while running

	/* Be sure to close the output file and connection */
	fclose(wifly_file);
	fclose(bearing_file);
	wifly1->end_serial();

	if (dual_wifly) {
		fclose(wifly_file2);
		fclose(bearing_file_mle);
		wifly2->end_serial();
	}

	return NULL;
}
<|endoftext|>


<commit_before>#include <Windows.h>
#include <mutex>
#include <stack>
#include <set>
#include <base/hook/inline.h>
#include <base/hook/fp_call.h>
#include <base/path/self.h>
#include <debugger/debugger.h>
#include <debugger/io/namedpipe.h>

HMODULE luadll = 0;

std::unique_ptr<vscode::io::namedpipe> global_io;
std::unique_ptr<vscode::debugger>      global_dbg;

void initialize_debugger(lua_State* L)
{
	if (GetModuleHandleW(L"debugger.dll")) {
		return;
	}
	if (!LoadLibraryW((base::path::self().remove_filename() / L"debugger.dll").c_str())) {
		return;
	}
	debugger_set_luadll(luadll, ::GetProcAddress);

	const wchar_t* pipename = _wgetenv(L"LUADBG_PORT");
	if (!pipename) {
		return;
	}
	global_io.reset(new vscode::io::namedpipe());
	if (!global_io->open_server(pipename)) {
		return;
	}

	global_io->kill_when_close();
	global_dbg.reset(new vscode::debugger(global_io.get()));
	global_dbg->wait_client();
	global_dbg->attach_lua(L);
	global_dbg->open_redirect(vscode::eRedirect::stdoutput);
	global_dbg->open_redirect(vscode::eRedirect::stderror);
}

void uninitialize_debugger(lua_State* L)
{
	if (!GetModuleHandleW(L"debugger.dll")) {
		return;
	}
	if (global_dbg) {
		global_dbg->detach_lua(L, true);
	}
	Sleep(1000);
}

static HMODULE EnumerateModulesInProcess(HANDLE hProcess, HMODULE hModuleLast, PIMAGE_NT_HEADERS32 pNtHeader)
{
	MEMORY_BASIC_INFORMATION mbi = { 0 };
	for (PBYTE pbLast = (PBYTE)hModuleLast + 0x10000;; pbLast = (PBYTE)mbi.BaseAddress + mbi.RegionSize) {
		if (VirtualQueryEx(hProcess, (PVOID)pbLast, &mbi, sizeof(mbi)) <= 0) {
			break;
		}
		if (((PBYTE)mbi.BaseAddress + mbi.RegionSize) < pbLast) {
			break;
		}
		if ((mbi.State != MEM_COMMIT) ||
			((mbi.Protect & 0xff) == PAGE_NOACCESS) ||
			(mbi.Protect & PAGE_GUARD)) {
			continue;
		}
		__try {
			IMAGE_DOS_HEADER idh;
			if (!ReadProcessMemory(hProcess, pbLast, &idh, sizeof(idh), NULL)) {
				continue;
			}
			if (idh.e_magic != IMAGE_DOS_SIGNATURE || (DWORD)idh.e_lfanew > mbi.RegionSize || (DWORD)idh.e_lfanew < sizeof(idh)) {
				continue;
			}
			if (!ReadProcessMemory(hProcess, pbLast + idh.e_lfanew, pNtHeader, sizeof(*pNtHeader), NULL)) {
				continue;
			}
			if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) {
				continue;
			}
			return (HMODULE)pbLast;
		}
		__except (EXCEPTION_EXECUTE_HANDLER) {
			continue;
		}
	}
	return NULL;
}

namespace lua {
	namespace real {
		uintptr_t lua_newstate = 0;
		uintptr_t luaL_newstate = 0;
		uintptr_t lua_close = 0;
	}
	namespace fake {
		static void* __cdecl lua_newstate(void* f, void* ud)
		{
			lua_State* L = base::c_call<lua_State*>(real::lua_newstate, f, ud);
			if (L) initialize_debugger(L);
			return L;
		}
		static void* __cdecl luaL_newstate()
		{
			lua_State* L = base::c_call<lua_State*>(real::luaL_newstate);
			if (L) initialize_debugger(L);
			return L;
		}
		void __cdecl lua_close(lua_State* L)
		{
			uninitialize_debugger(L);
			return base::c_call<void>(real::lua_close, L);
		}
	}

	bool hook(HMODULE m)
	{
		struct Hook {
			uintptr_t& real;
			uintptr_t fake;
		};
		std::vector<Hook> tasks;

#define HOOK(name) do {\
			real::##name = (uintptr_t)GetProcAddress(m, #name); \
			if (!real::##name) return false; \
			tasks.push_back({real::##name, (uintptr_t)fake::##name}); \
		} while (0)

		HOOK(lua_newstate);
		HOOK(luaL_newstate);
		HOOK(lua_close);

		std::stack<base::hook::hook_t> rollback;
		for (auto& task : tasks) {
			base::hook::hook_t h;
			if (!base::hook::install(&task.real, task.fake, &h)) {
				while (!rollback.empty()) {
					base::hook::uninstall(&rollback.top());
					rollback.pop();
				}
				return false;
			}
			rollback.push(h);
		}
		luadll = m;
		return true;
	}
}

std::mutex lockLoadDll;
std::set<std::wstring> loadedModules;

static bool TryHookLuaDll(HMODULE hModule)
{
	wchar_t moduleName[MAX_PATH];
	GetModuleFileNameW(hModule, moduleName, MAX_PATH);
	if (loadedModules.find(moduleName) != loadedModules.end()) {
		return false;
	}
	loadedModules.insert(moduleName);
	return lua::hook(hModule);
}

static bool FindLuaDll()
{
	std::unique_lock<std::mutex> lock(lockLoadDll);
	HANDLE hProcess = GetCurrentProcess();
	HMODULE hModule = NULL;
	for (;;) {
		IMAGE_NT_HEADERS32 inh;
		if ((hModule = EnumerateModulesInProcess(hProcess, hModule, &inh)) == NULL) {
			break;
		}
		if (TryHookLuaDll(hModule)) {
			return true;
		}
	}
	return false;
}

uintptr_t realLoadLibraryExW = 0;
HMODULE __stdcall fakeLoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags)
{
	HMODULE hModule = base::std_call<HMODULE>(realLoadLibraryExW, lpLibFileName, hFile, dwFlags);
	std::unique_lock<std::mutex> lock(lockLoadDll);
	TryHookLuaDll(hModule);
	return hModule;
}

static void WaitLuaDll()
{
	HMODULE hModuleKernel = GetModuleHandleW(L"kernel32.dll");
	if (hModuleKernel)
	{
		realLoadLibraryExW = (uintptr_t)GetProcAddress(hModuleKernel, "LoadLibraryExW");
		if (realLoadLibraryExW) {
			base::hook::install(&realLoadLibraryExW, (uintptr_t)fakeLoadLibraryExW);
		}
	}
}

BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID /*pReserved*/)
{
	if (reason == DLL_PROCESS_ATTACH)
	{
		::DisableThreadLibraryCalls(module);
		if (!FindLuaDll()) {
			WaitLuaDll();
		}
	}
	return TRUE;
}
<commit_msg>整理代码<commit_after>#include <Windows.h>
#include <mutex>
#include <stack>
#include <set>
#include <base/hook/inline.h>
#include <base/hook/fp_call.h>
#include <base/path/self.h>
#include <debugger/debugger.h>
#include <debugger/io/namedpipe.h>

HMODULE luadll = 0;

struct DebuggerWatcher {
	std::unique_ptr<vscode::io::namedpipe> io;
	std::unique_ptr<vscode::debugger>      dbg;

	DebuggerWatcher() {
		if (!GetModuleHandleW(L"debugger.dll")) {
			if (!LoadLibraryW((base::path::self().remove_filename() / L"debugger.dll").c_str())) {
				return;
			}
		}
		debugger_set_luadll(luadll, ::GetProcAddress);
		const wchar_t* pipename = _wgetenv(L"LUADBG_PORT");
		if (!pipename) {
			return;
		}
		io.reset(new vscode::io::namedpipe());
		if (!io->open_server(pipename)) {
			return;
		}
		io->kill_when_close();
		dbg.reset(new vscode::debugger(io.get()));
		dbg->wait_client();
		dbg->open_redirect(vscode::eRedirect::stdoutput);
		dbg->open_redirect(vscode::eRedirect::stderror);
	}

	static DebuggerWatcher& Get() {
		static DebuggerWatcher s_instance;
		return s_instance;
	}
	void attach(lua_State* L) {
		if (dbg && L) dbg->attach_lua(L);
	}
	void detach(lua_State* L) {
		if (dbg && L) dbg->detach_lua(L, true);
	}
};

static HMODULE EnumerateModulesInProcess(HANDLE hProcess, HMODULE hModuleLast, PIMAGE_NT_HEADERS32 pNtHeader)
{
	MEMORY_BASIC_INFORMATION mbi = { 0 };
	for (PBYTE pbLast = (PBYTE)hModuleLast + 0x10000;; pbLast = (PBYTE)mbi.BaseAddress + mbi.RegionSize) {
		if (VirtualQueryEx(hProcess, (PVOID)pbLast, &mbi, sizeof(mbi)) <= 0) {
			break;
		}
		if (((PBYTE)mbi.BaseAddress + mbi.RegionSize) < pbLast) {
			break;
		}
		if ((mbi.State != MEM_COMMIT) ||
			((mbi.Protect & 0xff) == PAGE_NOACCESS) ||
			(mbi.Protect & PAGE_GUARD)) {
			continue;
		}
		__try {
			IMAGE_DOS_HEADER idh;
			if (!ReadProcessMemory(hProcess, pbLast, &idh, sizeof(idh), NULL)) {
				continue;
			}
			if (idh.e_magic != IMAGE_DOS_SIGNATURE || (DWORD)idh.e_lfanew > mbi.RegionSize || (DWORD)idh.e_lfanew < sizeof(idh)) {
				continue;
			}
			if (!ReadProcessMemory(hProcess, pbLast + idh.e_lfanew, pNtHeader, sizeof(*pNtHeader), NULL)) {
				continue;
			}
			if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) {
				continue;
			}
			return (HMODULE)pbLast;
		}
		__except (EXCEPTION_EXECUTE_HANDLER) {
			continue;
		}
	}
	return NULL;
}

namespace lua {
	namespace real {
		uintptr_t lua_newstate = 0;
		uintptr_t luaL_newstate = 0;
		uintptr_t lua_close = 0;
	}
	namespace fake {
		static void* __cdecl lua_newstate(void* f, void* ud)
		{
			lua_State* L = base::c_call<lua_State*>(real::lua_newstate, f, ud);
			DebuggerWatcher::Get().attach(L);
			return L;
		}
		static void* __cdecl luaL_newstate()
		{
			lua_State* L = base::c_call<lua_State*>(real::luaL_newstate);
			DebuggerWatcher::Get().attach(L);
			return L;
		}
		void __cdecl lua_close(lua_State* L)
		{
			DebuggerWatcher::Get().detach(L);
			Sleep(1000);
			return base::c_call<void>(real::lua_close, L);
		}
	}

	bool hook(HMODULE m)
	{
		struct Hook {
			uintptr_t& real;
			uintptr_t fake;
		};
		std::vector<Hook> tasks;

#define HOOK(name) do {\
			real::##name = (uintptr_t)GetProcAddress(m, #name); \
			if (!real::##name) return false; \
			tasks.push_back({real::##name, (uintptr_t)fake::##name}); \
		} while (0)

		HOOK(lua_newstate);
		HOOK(luaL_newstate);
		HOOK(lua_close);

		std::stack<base::hook::hook_t> rollback;
		for (auto& task : tasks) {
			base::hook::hook_t h;
			if (!base::hook::install(&task.real, task.fake, &h)) {
				while (!rollback.empty()) {
					base::hook::uninstall(&rollback.top());
					rollback.pop();
				}
				return false;
			}
			rollback.push(h);
		}
		luadll = m;
		return true;
	}
}

std::mutex lockLoadDll;
std::set<std::wstring> loadedModules;

static bool TryHookLuaDll(HMODULE hModule)
{
	wchar_t moduleName[MAX_PATH];
	GetModuleFileNameW(hModule, moduleName, MAX_PATH);
	if (loadedModules.find(moduleName) != loadedModules.end()) {
		return false;
	}
	loadedModules.insert(moduleName);
	return lua::hook(hModule);
}

static bool FindLuaDll()
{
	std::unique_lock<std::mutex> lock(lockLoadDll);
	HANDLE hProcess = GetCurrentProcess();
	HMODULE hModule = NULL;
	for (;;) {
		IMAGE_NT_HEADERS32 inh;
		if ((hModule = EnumerateModulesInProcess(hProcess, hModule, &inh)) == NULL) {
			break;
		}
		if (TryHookLuaDll(hModule)) {
			return true;
		}
	}
	return false;
}

uintptr_t realLoadLibraryExW = 0;
HMODULE __stdcall fakeLoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags)
{
	HMODULE hModule = base::std_call<HMODULE>(realLoadLibraryExW, lpLibFileName, hFile, dwFlags);
	std::unique_lock<std::mutex> lock(lockLoadDll);
	TryHookLuaDll(hModule);
	return hModule;
}

static void WaitLuaDll()
{
	HMODULE hModuleKernel = GetModuleHandleW(L"kernel32.dll");
	if (hModuleKernel)
	{
		realLoadLibraryExW = (uintptr_t)GetProcAddress(hModuleKernel, "LoadLibraryExW");
		if (realLoadLibraryExW) {
			base::hook::install(&realLoadLibraryExW, (uintptr_t)fakeLoadLibraryExW);
		}
	}
}

BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID /*pReserved*/)
{
	if (reason == DLL_PROCESS_ATTACH)
	{
		::DisableThreadLibraryCalls(module);
		if (!FindLuaDll()) {
			WaitLuaDll();
		}
	}
	return TRUE;
}
<|endoftext|>


<commit_before>//
//  FileManager.hpp
//  CatchLib
//
//  Created by John Barbero Unenge on 9/17/12.
//  Copyright (c) 2012 John Barbero Unenge. All rights reserved.
//

#include "../Helper/Logger.hpp"
#include "GLRenderer10.hpp"
#include "Vertex.hpp"
#include "../Helper/FileManager.hpp"

// Define the positions and colors of two triangles.
const Vertex Vertecies[] = {
    {{-0.5f, -0.866f},  {1, 1, 0.5f, 1}},
    {{0.5f, -0.866f},   {1, 1, 0.5f, 1}},
    {{0, 1},            {1, 1, 0.5f, 1}},

    {{-0.5f, -0.866f},  {0.5f, 0.5f, 0.5f}},
    {{0.5f, -0.866f},   {0.5f, 0.5f, 0.5f}},
    {{0, -0.4f},        {0.5f, 0.5f, 0.5f}},
};

const Vertex shape[] = {
    {{0,0}, {1,1,1,1}},
    {{1,0}, {1,1,1,1}},
    {{0,1}, {1,1,1,1}},
    {{1,1}, {0,0,0,0}},

};
const Vertex txPos[] = {
    {{0,0}, {0,0,0,0}},
    {{1,0}, {0,0,0,0}},
    {{0,1}, {0,0,0,0}},
    {{1,1}, {0,0,0,0}},

};

IRenderer* CreateRendererWithOpenGL10()
{
    return new GLRenderer10();
}

GLRenderer10::GLRenderer10()
{
    Log(LOG_INFO, "GLRenderer10", "Constructed a GLRenderer!");
#ifdef __APPLE__
    Log(LOG_INFO, "GLRenderer10", "Additional iOS setup!");
    glGenRenderbuffersOES(1, &m_renderbuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, m_renderbuffer);

    // Create the framebuffer object and attach the color buffer.
    glGenFramebuffersOES(1, &m_framebuffer);
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, m_framebuffer);
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, m_renderbuffer);
#endif
}
GLRenderer10::~GLRenderer10()
{
	Log(LOG_INFO, "GLRenderer10", "Destroyed a GLRenderer10!");
}

GLuint texID;

void GLRenderer10::init(int width, int height)
{
	Log(LOG_INFO, "GLRenderer10", generateCString("Init WH: %ix%i", width, height));

    glViewport(0, 0, width, height);

    glMatrixMode(GL_PROJECTION);

    // Initialize the projection matrix.
    const float maxX = 2;
    const float maxY = 3;
    glOrthof(-maxX, +maxX, -maxY, +maxY, -1, 1);

    glMatrixMode(GL_MODELVIEW);
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_VERTEX_ARRAY);

//    CLTexture *texture = FileManager::loadTexture("Sprite");

    GLuint imgW = 10;
    GLuint imgH = 10;

    GLubyte* imgData = (GLubyte *) calloc(imgW * imgH * 4, sizeof(GLubyte));

    for (int i = 0; i < imgW * imgH * 4; i+=4) {
        imgData[i] = 0x00;
        imgData[i+1] = 0x70;
        imgData[i+2] = 0xff;
        imgData[i+3] = 0xff;
    }

    CLTexture *texture = new CLTexture();
    texture->width = imgW;
    texture->height = imgH;
    texture->data = imgData;

    m_texture = this->loadTexture(texture);
}

GLuint GLRenderer10::loadTexture(CLTexture* texture)
{
    GLuint tID;

    glGenTextures(1, &tID);
    glBindTexture(GL_TEXTURE_2D, tID);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->width, texture->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture->data);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    return tID;
}

void GLRenderer10::render()
{
//    glBindTexture(GL_TEXTURE_2D, m_texture);

    glClearColor(10, 0.5f, 0.5f, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBindTexture(GL_TEXTURE_2D, m_texture);

    glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &shape[0].Position[0]);
    glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &txPos[0].Position[0]);

    GLsizei vCount = sizeof(shape) / sizeof(Vertex);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, vCount);

}

void GLRenderer10::update(float dt)
{
    Log(LOG_INFO, "GLRenderer", generateCString("Update with dt: %d", dt));

    glMatrixMode(GL_MODELVIEW);
    glRotatef(500*dt, 0, 0, 1);
}

<commit_msg>Made the renderer work with the code generated texture.<commit_after>//
//  FileManager.hpp
//  CatchLib
//
//  Created by John Barbero Unenge on 9/17/12.
//  Copyright (c) 2012 John Barbero Unenge. All rights reserved.
//

#include "../Helper/Logger.hpp"
#include "GLRenderer10.hpp"
#include "Vertex.hpp"
#include "../Helper/FileManager.hpp"

// Define the positions and colors of two triangles.
const Vertex Vertecies[] = {
    {{-0.5f, -0.866f},  {1, 1, 0.5f, 1}},
    {{0.5f, -0.866f},   {1, 1, 0.5f, 1}},
    {{0, 1},            {1, 1, 0.5f, 1}},

    {{-0.5f, -0.866f},  {0.5f, 0.5f, 0.5f}},
    {{0.5f, -0.866f},   {0.5f, 0.5f, 0.5f}},
    {{0, -0.4f},        {0.5f, 0.5f, 0.5f}},
};

const Vertex shape[] = {
    {{0,0}, {1,1,1,1}},
    {{1,0}, {1,1,1,1}},
    {{0,1}, {1,1,1,1}},
    {{1,1}, {0,0,0,0}},

};
const Vertex txPos[] = {
    {{0,0}, {0,0,0,0}},
    {{1,0}, {0,0,0,0}},
    {{0,1}, {0,0,0,0}},
    {{1,1}, {0,0,0,0}},

};

IRenderer* CreateRendererWithOpenGL10()
{
    return new GLRenderer10();
}

GLRenderer10::GLRenderer10()
{
    Log(LOG_INFO, "GLRenderer10", "Constructed a GLRenderer!");
#ifdef __APPLE__
    Log(LOG_INFO, "GLRenderer10", "Additional iOS setup!");
    glGenRenderbuffersOES(1, &m_renderbuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, m_renderbuffer);

    // Create the framebuffer object and attach the color buffer.
    glGenFramebuffersOES(1, &m_framebuffer);
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, m_framebuffer);
#endif
}
GLRenderer10::~GLRenderer10()
{
	Log(LOG_INFO, "GLRenderer10", "Destroyed a GLRenderer10!");
}

GLuint texID;

void GLRenderer10::init(int width, int height)
{

#ifdef __APPLE__
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, m_renderbuffer);
#endif

	Log(LOG_INFO, "GLRenderer10", generateCString("Init WH: %ix%i", width, height));

    glViewport(0, 0, width, height);

    glMatrixMode(GL_PROJECTION);

    // Initialize the projection matrix.
    const float maxX = 2;
    const float maxY = 3;
    glOrthof(-maxX, +maxX, -maxY, +maxY, -1, 1);

    glMatrixMode(GL_MODELVIEW);
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_VERTEX_ARRAY);

//    CLTexture *texture = FileManager::loadTexture("color");

    GLuint imgW = 4;
    GLuint imgH = 4;

    unsigned char imgData2[] = {
        0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff,
        0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff,
        0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff,
        0x00,0x00,0x00,0xa0, 0x00,0x00,0x00,0xa0, 0x00,0x00,0x00,0xa0, 0x00,0x00,0x00,0xa0,

    };

    CLTexture *texture = new CLTexture();
    texture->setData(imgData2, imgW, imgH);

    m_texture = this->loadTexture(texture);
}

GLuint GLRenderer10::loadTexture(CLTexture* texture)
{
    GLuint tID;

    glGenTextures(1, &tID);
    glBindTexture(GL_TEXTURE_2D, tID);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->getWidth(), texture->getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture->getData());
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    for (int i = 0; i < texture->getWidth() * texture->getHeight() * 4; i+=4) {
        Log(LOG_INFO, "Loaoding tex", generateCString("CLR: %i,%i,%i.%i", (int)texture->getData()[i], (int)texture->getData()[i+1], (int)texture->getData()[i+2], (int)texture->getData()[i+3]));
    }

    return tID;
}

void GLRenderer10::render()
{
//    glBindTexture(GL_TEXTURE_2D, m_texture);

    glClearColor(10, 0.5f, 0.5f, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBindTexture(GL_TEXTURE_2D, m_texture);

    glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &shape[0].Position[0]);
    glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &txPos[0].Position[0]);

    GLsizei vCount = sizeof(shape) / sizeof(Vertex);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, vCount);

}

void GLRenderer10::update(float dt)
{
    Log(LOG_INFO, "GLRenderer", generateCString("Update with dt: %d", dt));

    glMatrixMode(GL_MODELVIEW);
    glRotatef(500*dt, 0, 0, 1);
}

<|endoftext|>


<commit_before><commit_msg>Ensure that overlay does not appear in incognito mode.<commit_after><|endoftext|>


<commit_before>#include "mitkLookupTableSource.h"
#include <ipPic/ipPic.h>
#include <vtkLookupTable.h>

extern "C"
{
#include "uscfunctions/usc.h"
}

mitk::LookupTableSource::~LookupTableSource()
{}

mitk::LookupTableSource::LookupTableSource()
{
	m_Mode = HP;
	m_LookupTable = NULL;

}

/**
 *
 */
mitk::LookupTableSource::OutputTypePointer mitk::LookupTableSource::GetOutput()
{

	std::cout << "mitk::LookupTableSource::GetOutput() ... " << std::endl;

//	if (m_LookupTable !+= NULL) delete m_LookupTable;

	m_LookupTable = new mitk::LookupTable();

	if (m_Mode == HP)
	{
			std::cout << "  creating HP LookupTable ... " << std::endl;

			ipPicDescriptor *HPMap;
			HPMap=usReadMap("a.map", ".", -1000,-1000);

			vtkLookupTable *vtkLookupTable = vtkLookupTable::New();
			ipUInt1_t *data = ((ipUInt1_t *)HPMap->data);

			int LookupTablesize =256;
			float rgba[4];
			vtkLookupTable->SetNumberOfColors(LookupTablesize);
			for (int i=0; i<LookupTablesize; i++)
			{
				rgba[0] = ((ipUInt1_t *) data)[0 + i*3*LookupTablesize] /255.0f;
				rgba[1] = ((ipUInt1_t *) data)[1 + i*3*LookupTablesize] /255.0f ;
				rgba[2] = ((ipUInt1_t *) data)[2 + i*3*LookupTablesize] /255.0f ;
				rgba[3] = 1;
				vtkLookupTable->SetTableValue (i, rgba);
			}

			m_LookupTable->SetVtkLookupTable(vtkLookupTable);

	} else if (m_Mode ==Strain)
	{
			std::cout << "  creating Strain  LookupTable ... " << std::endl;
			vtkLookupTable *vtkLookupTable = vtkLookupTable::New();

			int size=256;

//			xDim = size;
//			yDim = 3;
			float rgba[4];

			float quartal = size  / 8.0f;

			float sizeQuartal1 = 3 * quartal; //quartal-1;

			float sizeQuartal2 = 0.9375 * quartal;
			float sizeZeroStrain = 0.125* quartal;
			float sizeQuartal3 = 0.9375 * quartal;

//			float sizeQuartal2 = 0.875 * quartal;
//			float sizeZeroStrain = 0.25* quartal;
//			float sizeQuartal3 = 0.875 * quartal;

//			float sizeQuartal2 = 0.975 * quartal;
//			float sizeZeroStrain = 0.05* quartal;
//			float sizeQuartal3 = 0.975 * quartal;

			float sizeQuartal4 = 3 * quartal;

//			std::cout << "quartal = " << quartal << std::endl;
//			std::cout << "quartal 1 = " << sizeQuartal1 << std::endl;
//			std::cout << "quartal 2 = " << sizeQuartal2 << std::endl;
//			std::cout << "quartal 3 = " << sizeQuartal3 << std::endl;
//			std::cout << "quartal 4 = " << sizeQuartal4 << std::endl;
//			std::cout << "quartal zero = " << sizeZeroStrain << std::endl;

			int factor = 1;

			// dunkelrot
			for(int i=1; i<=sizeQuartal1; i++)
			{
				int index = i-1;
    	  rgba[0] = factor * (0.5 + i/(2*sizeQuartal1));      // rot
				rgba[1] = factor * 0;                           // gruen
				rgba[2] = factor * 0;                           // blau
				rgba[3] = factor * 1;
				vtkLookupTable->SetTableValue (index, rgba);
			}

			// hellrot bis gelb
			for (int i=1 ; i<=sizeQuartal2 ; i++)
			{
		   	int index = (i-1) + sizeQuartal1;
      	rgba[0] = factor * 1;
      	rgba[1] = factor * (i/sizeQuartal2);
      	rgba[2] = factor * 0;
				rgba[3] = factor * 1;
				vtkLookupTable->SetTableValue (index, rgba);
			}

				//gruen
			for(int i=1 ; i<=sizeZeroStrain ; i++)
			{
      		int index = (i-1) + (sizeQuartal1+sizeQuartal2);
      		rgba[0] = factor * 0; //1 - i/sizeZeroStrain;
      		rgba[1] = factor * 1;
      		rgba[2] = factor * 0; //i/sizeZeroStrain;
					rgba[3] = factor * 1;
					vtkLookupTable->SetTableValue (index, rgba);
			}

			// hellblau
			for (int i=1 ; i<=sizeQuartal3; i++)
			{
      		int index = (i-1) + ( sizeQuartal1 + sizeQuartal2 + sizeZeroStrain );
      		rgba[0]= factor * 0;
      		rgba[1] = factor * (1 - i/sizeQuartal3);
      		rgba[2] = factor * 1;
					rgba[3] = factor * 1;
					vtkLookupTable->SetTableValue (index, rgba);
			}

			// blau
			for(int i=1 ; i<=sizeQuartal4 ; i++)
			{
		      int index = (i-1) + (sizeQuartal1+sizeQuartal2+sizeQuartal3 + sizeZeroStrain);
    		  rgba[0] = factor * 0;
		      rgba[1] = factor * 0;
    		  rgba[2] = factor * (1- i/sizeQuartal4);
					rgba[3] = factor * 1;
					vtkLookupTable->SetTableValue (index, rgba);

			}

			// the value 0 is mapped to black
			// so we see the field-out-of-view as black
			int index=0;
			rgba[0] = 0;
			rgba[1] = 0;
			rgba[2] = 0;
			rgba[3] = factor * 1;
			vtkLookupTable->SetTableValue (index, rgba);
			vtkLookupTable->SetTableValue (index+1, rgba);

//			for (int i=0; i<size; i++)
//			{
//				vtkLookupTable->GetTableValue(i,&rgba[0]);
//				cout << "i=" <<  i << " r=" << rgba[0] << " g=" << rgba[1]<< " b=" << rgba[2] << endl;
//			}

				m_LookupTable->SetVtkLookupTable(vtkLookupTable);

	} else
		m_LookupTable = NULL;

	std::cout << "mitk::LookupTableSource::GetOutput() ... " << std::endl;
	return m_LookupTable;

}

<commit_msg>vc6 compatibility changes<commit_after>#include "mitkLookupTableSource.h"
#include <ipPic/ipPic.h>
#include <vtkLookupTable.h>

extern "C"
{
#include "uscfunctions/usc.h"
}

mitk::LookupTableSource::~LookupTableSource()
{}

mitk::LookupTableSource::LookupTableSource()
{
	m_Mode = HP;
	m_LookupTable = NULL;

}

/**
 *
 */
mitk::LookupTableSource::OutputTypePointer mitk::LookupTableSource::GetOutput()
{

	std::cout << "mitk::LookupTableSource::GetOutput() ... " << std::endl;

//	if (m_LookupTable !+= NULL) delete m_LookupTable;

	m_LookupTable = new mitk::LookupTable();

	if (m_Mode == HP)
	{
			std::cout << "  creating HP LookupTable ... " << std::endl;

			ipPicDescriptor *HPMap;
			HPMap=usReadMap("a.map", ".", -1000,-1000);

			vtkLookupTable *vtkLookupTable = vtkLookupTable::New();
			ipUInt1_t *data = ((ipUInt1_t *)HPMap->data);

			int LookupTablesize =256;
			float rgba[4];
			vtkLookupTable->SetNumberOfColors(LookupTablesize);
			for (int i=0; i<LookupTablesize; i++)
			{
				rgba[0] = ((ipUInt1_t *) data)[0 + i*3*LookupTablesize] /255.0f;
				rgba[1] = ((ipUInt1_t *) data)[1 + i*3*LookupTablesize] /255.0f ;
				rgba[2] = ((ipUInt1_t *) data)[2 + i*3*LookupTablesize] /255.0f ;
				rgba[3] = 1;
				vtkLookupTable->SetTableValue (i, rgba);
			}

			m_LookupTable->SetVtkLookupTable(vtkLookupTable);

	} else if (m_Mode ==Strain)
	{
			std::cout << "  creating Strain  LookupTable ... " << std::endl;
			vtkLookupTable *vtkLookupTable = vtkLookupTable::New();

			int size=256;

//			xDim = size;
//			yDim = 3;
			float rgba[4];

			float quartal = size  / 8.0f;

			float sizeQuartal1 = 3 * quartal; //quartal-1;

			float sizeQuartal2 = 0.9375 * quartal;
			float sizeZeroStrain = 0.125* quartal;
			float sizeQuartal3 = 0.9375 * quartal;

//			float sizeQuartal2 = 0.875 * quartal;
//			float sizeZeroStrain = 0.25* quartal;
//			float sizeQuartal3 = 0.875 * quartal;

//			float sizeQuartal2 = 0.975 * quartal;
//			float sizeZeroStrain = 0.05* quartal;
//			float sizeQuartal3 = 0.975 * quartal;

			float sizeQuartal4 = 3 * quartal;

//			std::cout << "quartal = " << quartal << std::endl;
//			std::cout << "quartal 1 = " << sizeQuartal1 << std::endl;
//			std::cout << "quartal 2 = " << sizeQuartal2 << std::endl;
//			std::cout << "quartal 3 = " << sizeQuartal3 << std::endl;
//			std::cout << "quartal 4 = " << sizeQuartal4 << std::endl;
//			std::cout << "quartal zero = " << sizeZeroStrain << std::endl;

			int factor = 1;
      int i;

			// dunkelrot
			for(i=1; i<=sizeQuartal1; i++)
			{
				int index = i-1;
    	  rgba[0] = factor * (0.5 + i/(2*sizeQuartal1));      // rot
				rgba[1] = factor * 0;                           // gruen
				rgba[2] = factor * 0;                           // blau
				rgba[3] = factor * 1;
				vtkLookupTable->SetTableValue (index, rgba);
			}

			// hellrot bis gelb
			for (i=1 ; i<=sizeQuartal2 ; i++)
			{
		   	int index = (i-1) + sizeQuartal1;
      	rgba[0] = factor * 1;
      	rgba[1] = factor * (i/sizeQuartal2);
      	rgba[2] = factor * 0;
				rgba[3] = factor * 1;
				vtkLookupTable->SetTableValue (index, rgba);
			}

				//gruen
			for(i=1 ; i<=sizeZeroStrain ; i++)
			{
      		int index = (i-1) + (sizeQuartal1+sizeQuartal2);
      		rgba[0] = factor * 0; //1 - i/sizeZeroStrain;
      		rgba[1] = factor * 1;
      		rgba[2] = factor * 0; //i/sizeZeroStrain;
					rgba[3] = factor * 1;
					vtkLookupTable->SetTableValue (index, rgba);
			}

			// hellblau
			for (i=1 ; i<=sizeQuartal3; i++)
			{
      		int index = (i-1) + ( sizeQuartal1 + sizeQuartal2 + sizeZeroStrain );
      		rgba[0]= factor * 0;
      		rgba[1] = factor * (1 - i/sizeQuartal3);
      		rgba[2] = factor * 1;
					rgba[3] = factor * 1;
					vtkLookupTable->SetTableValue (index, rgba);
			}

			// blau
			for(i=1 ; i<=sizeQuartal4 ; i++)
			{
		      int index = (i-1) + (sizeQuartal1+sizeQuartal2+sizeQuartal3 + sizeZeroStrain);
    		  rgba[0] = factor * 0;
		      rgba[1] = factor * 0;
    		  rgba[2] = factor * (1- i/sizeQuartal4);
					rgba[3] = factor * 1;
					vtkLookupTable->SetTableValue (index, rgba);

			}

			// the value 0 is mapped to black
			// so we see the field-out-of-view as black
			int index=0;
			rgba[0] = 0;
			rgba[1] = 0;
			rgba[2] = 0;
			rgba[3] = factor * 1;
			vtkLookupTable->SetTableValue (index, rgba);
			vtkLookupTable->SetTableValue (index+1, rgba);

//			for (int i=0; i<size; i++)
//			{
//				vtkLookupTable->GetTableValue(i,&rgba[0]);
//				cout << "i=" <<  i << " r=" << rgba[0] << " g=" << rgba[1]<< " b=" << rgba[2] << endl;
//			}

				m_LookupTable->SetVtkLookupTable(vtkLookupTable);

	} else
		m_LookupTable = NULL;

	std::cout << "mitk::LookupTableSource::GetOutput() ... " << std::endl;
	return m_LookupTable;

}

<|endoftext|>


<commit_before>#include "mitkGradientBackground.h"
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkMapper.h>
#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyData.h>
#include <vtkCamera.h>
#include <vtkLookupTable.h>
#include <vtkCellArray.h>
#include <vtkUnsignedIntArray.h>
#include <vtkPoints.h>
#include <vtkPointData.h>
#include <vtkObjectFactory.h>
#include <vtkRendererCollection.h>

mitk::GradientBackground::GradientBackground()
{
  m_RenderWindow = NULL;
  m_Renderer = vtkRenderer::New();
  m_Actor = vtkActor::New();
  m_Mapper = vtkPolyDataMapper::New();
  m_Lut = vtkLookupTable::New();
  m_Plane = vtkPolyData::New();
  m_Layer = 1;

  vtkPoints* points = vtkPoints::New( );
  points->InsertPoint(0,-10,0,0);
  points->InsertPoint(1,-10,1,0);
  points->InsertPoint(2,10,1,0);
  points->InsertPoint(3,10,0,0);

  vtkCellArray* cellArray = vtkCellArray::New();
  cellArray->InsertNextCell(4);
  cellArray->InsertCellPoint(0);
  cellArray->InsertCellPoint(1);
  cellArray->InsertCellPoint(2);
  cellArray->InsertCellPoint(3);

  vtkUnsignedIntArray* data = vtkUnsignedIntArray::New();
  data->InsertTuple1(0,1);
  data->InsertTuple1(1,0);
  data->InsertTuple1(2,0);
  data->InsertTuple1(3,1);

  m_Plane->SetPoints( points );
  m_Plane->SetPolys( cellArray );
  m_Plane->GetPointData()->SetScalars( data );

  m_Lut->SetNumberOfColors( 2 );
  m_Lut->Build();
  m_Lut->SetTableValue( m_Lut->GetIndex(0), 1, 1, 1 );
  m_Lut->SetTableValue( m_Lut->GetIndex(1), 0, 0, 0 );

  m_Mapper->SetInput( m_Plane );
  m_Mapper->SetLookupTable( m_Lut );

  m_Actor->SetMapper( m_Mapper );

  m_Renderer->AddActor( m_Actor );
  m_Renderer->InteractiveOff();
  m_Renderer->GetActiveCamera()->ParallelProjectionOn();
  m_Renderer->ResetCamera();
  m_Renderer->GetActiveCamera()->SetParallelScale(0.5);
  m_Renderer->SetLayer( m_Layer );
}

mitk::GradientBackground::~GradientBackground()
{
  if ( m_RenderWindow != NULL )
    if ( this->IsEnabled() )
      this->Disable();

  if ( m_Plane != NULL )
    m_Plane->Delete();

  if( m_Lut != NULL )
    m_Lut->Delete();

  if ( m_Mapper != NULL )
    m_Mapper->Delete();

  if ( m_Actor!=NULL )
    m_Actor->Delete();

  if ( m_Renderer != NULL )
    m_Renderer->Delete();
}

/**
 * Sets the renderwindow, in which the gradient background
 * will be shown. Make sure, you have called this function
 * before calling Enable()
 */
void mitk::GradientBackground::SetVtkRenderWindow( vtkRenderWindow* renderWindow )
{
  m_RenderWindow = renderWindow;
}

/**
 * Returns the vtkRenderWindow, which is used
 * for displaying the gradient background
 */
vtkRenderWindow* mitk::GradientBackground::GetVtkRenderWindow()
{
  return m_RenderWindow;
}

/**
 * Returns the renderer responsible for
 * rendering the color gradient into the
 * vtkRenderWindow
 */
vtkRenderer* mitk::GradientBackground::GetVtkRenderer()
{
  return m_Renderer;
}

/**
 * Returns the actor associated with the color gradient
 */
vtkActor* mitk::GradientBackground::GetActor()
{
  return m_Actor;
}

/**
 * Returns the mapper associated with the color
 * gradient.
 */
vtkPolyDataMapper* mitk::GradientBackground::GetMapper()
{
  return m_Mapper;
}

/**
 * Sets the gradient colors. The gradient
 * will smoothly fade from color1 to color2
 */
void mitk::GradientBackground::SetGradientColors( vtkFloatingPointType r1, vtkFloatingPointType g1, vtkFloatingPointType b1, vtkFloatingPointType r2, vtkFloatingPointType g2, vtkFloatingPointType b2 )
{
  m_Lut->SetTableValue( m_Lut->GetIndex(0), r1, g1, b1 );
  m_Lut->SetTableValue( m_Lut->GetIndex(1), r2, g2, b2 );
}

void mitk::GradientBackground::SetUpperColor(vtkFloatingPointType r, vtkFloatingPointType g, vtkFloatingPointType b )
{
  m_Lut->SetTableValue( m_Lut->GetIndex(0), r, g, b );
}

void mitk::GradientBackground::SetLowerColor(vtkFloatingPointType r, vtkFloatingPointType g, vtkFloatingPointType b )
{
  m_Lut->SetTableValue( m_Lut->GetIndex(1), r, g, b );
}

/**
 * The layer, which will be used for rendering into
 * the renderwindow may be set using this function.
 * The default layer is one.
 */
void mitk::GradientBackground::SetLayer( int layer )
{
  m_Layer = layer;
  m_Renderer->SetLayer( m_Layer );
}

/**
 * Returns the layer, in which the color gradient
 * will be drawn
 */
int mitk::GradientBackground::GetLayer()
{
  return m_Layer;
}

/**
 * Enables drawing of the color gradient background.
 * If you want to disable it, call the Disable() function.
 */
void mitk::GradientBackground::Enable()
{
  if ( m_RenderWindow == NULL )
    return;
  if ( m_Renderer == NULL )
    return;

  m_RenderWindow->SetNumberOfLayers( 2 );
  m_RenderWindow->AddRenderer( m_Renderer );
}

/**
 * Disables drawing of the color gradient background.
 * If you want to enable it, call the Enable() function.
 */
void mitk::GradientBackground::Disable()
{
  if ( this->IsEnabled() )
    m_RenderWindow->RemoveRenderer( m_Renderer );
}

/**
 * Checks, if the gradient background is currently
 * enabled (visible)
 */
bool mitk::GradientBackground::IsEnabled()
{
    if ( m_RenderWindow == NULL )
        return false;
    else
        return ( m_RenderWindow->GetRenderers()->IsItemPresent( m_Renderer ) != 0 );
}

void mitk::GradientBackground::SetRequestedRegionToLargestPossibleRegion()
{
    //nothing to do
}

bool mitk::GradientBackground::RequestedRegionIsOutsideOfTheBufferedRegion()
{
    return false;
}

bool mitk::GradientBackground::VerifyRequestedRegion()
{
    return true;
}

void mitk::GradientBackground::SetRequestedRegion(itk::DataObject*)
{
    //nothing to do
}

<commit_msg>FIX: layer ordering has changed from vtk 4.4 to vtk 5.0.<commit_after>#include "mitkGradientBackground.h"
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkMapper.h>
#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyData.h>
#include <vtkCamera.h>
#include <vtkLookupTable.h>
#include <vtkCellArray.h>
#include <vtkUnsignedIntArray.h>
#include <vtkPoints.h>
#include <vtkPointData.h>
#include <vtkObjectFactory.h>
#include <vtkRendererCollection.h>

mitk::GradientBackground::GradientBackground()
{
  m_RenderWindow = NULL;
  m_Renderer = vtkRenderer::New();
  m_Actor = vtkActor::New();
  m_Mapper = vtkPolyDataMapper::New();
  m_Lut = vtkLookupTable::New();
  m_Plane = vtkPolyData::New();
  m_Layer = 1;

  vtkPoints* points = vtkPoints::New( );
  points->InsertPoint(0,-10,0,0);
  points->InsertPoint(1,-10,1,0);
  points->InsertPoint(2,10,1,0);
  points->InsertPoint(3,10,0,0);

  vtkCellArray* cellArray = vtkCellArray::New();
  cellArray->InsertNextCell(4);
  cellArray->InsertCellPoint(0);
  cellArray->InsertCellPoint(1);
  cellArray->InsertCellPoint(2);
  cellArray->InsertCellPoint(3);

  vtkUnsignedIntArray* data = vtkUnsignedIntArray::New();
  data->InsertTuple1(0,1);
  data->InsertTuple1(1,0);
  data->InsertTuple1(2,0);
  data->InsertTuple1(3,1);

  m_Plane->SetPoints( points );
  m_Plane->SetPolys( cellArray );
  m_Plane->GetPointData()->SetScalars( data );

  m_Lut->SetNumberOfColors( 2 );
  m_Lut->Build();
  m_Lut->SetTableValue( m_Lut->GetIndex(0), 1, 1, 1 );
  m_Lut->SetTableValue( m_Lut->GetIndex(1), 0, 0, 0 );

  m_Mapper->SetInput( m_Plane );
  m_Mapper->SetLookupTable( m_Lut );

  m_Actor->SetMapper( m_Mapper );

  m_Renderer->AddActor( m_Actor );
  m_Renderer->InteractiveOff();
  m_Renderer->GetActiveCamera()->ParallelProjectionOn();
  m_Renderer->ResetCamera();
  m_Renderer->GetActiveCamera()->SetParallelScale(0.5);
  m_Renderer->SetLayer( m_Layer );
}

mitk::GradientBackground::~GradientBackground()
{
  if ( m_RenderWindow != NULL )
    if ( this->IsEnabled() )
      this->Disable();

  if ( m_Plane != NULL )
    m_Plane->Delete();

  if( m_Lut != NULL )
    m_Lut->Delete();

  if ( m_Mapper != NULL )
    m_Mapper->Delete();

  if ( m_Actor!=NULL )
    m_Actor->Delete();

  if ( m_Renderer != NULL )
    m_Renderer->Delete();
}

/**
 * Sets the renderwindow, in which the gradient background
 * will be shown. Make sure, you have called this function
 * before calling Enable()
 */
void mitk::GradientBackground::SetVtkRenderWindow( vtkRenderWindow* renderWindow )
{
  m_RenderWindow = renderWindow;
}

/**
 * Returns the vtkRenderWindow, which is used
 * for displaying the gradient background
 */
vtkRenderWindow* mitk::GradientBackground::GetVtkRenderWindow()
{
  return m_RenderWindow;
}

/**
 * Returns the renderer responsible for
 * rendering the color gradient into the
 * vtkRenderWindow
 */
vtkRenderer* mitk::GradientBackground::GetVtkRenderer()
{
  return m_Renderer;
}

/**
 * Returns the actor associated with the color gradient
 */
vtkActor* mitk::GradientBackground::GetActor()
{
  return m_Actor;
}

/**
 * Returns the mapper associated with the color
 * gradient.
 */
vtkPolyDataMapper* mitk::GradientBackground::GetMapper()
{
  return m_Mapper;
}

/**
 * Sets the gradient colors. The gradient
 * will smoothly fade from color1 to color2
 */
void mitk::GradientBackground::SetGradientColors( vtkFloatingPointType r1, vtkFloatingPointType g1, vtkFloatingPointType b1, vtkFloatingPointType r2, vtkFloatingPointType g2, vtkFloatingPointType b2 )
{
  m_Lut->SetTableValue( m_Lut->GetIndex(0), r1, g1, b1 );
  m_Lut->SetTableValue( m_Lut->GetIndex(1), r2, g2, b2 );
}

void mitk::GradientBackground::SetUpperColor(vtkFloatingPointType r, vtkFloatingPointType g, vtkFloatingPointType b )
{
  m_Lut->SetTableValue( m_Lut->GetIndex(0), r, g, b );
}

void mitk::GradientBackground::SetLowerColor(vtkFloatingPointType r, vtkFloatingPointType g, vtkFloatingPointType b )
{
  m_Lut->SetTableValue( m_Lut->GetIndex(1), r, g, b );
}

/**
 * The layer, which will be used for rendering into
 * the renderwindow may be set using this function.
 * The default layer is one.
 */
void mitk::GradientBackground::SetLayer( int layer )
{
  m_Layer = layer;
  m_Renderer->SetLayer( m_Layer );
}

/**
 * Returns the layer, in which the color gradient
 * will be drawn
 */
int mitk::GradientBackground::GetLayer()
{
  return m_Layer;
}

/**
 * Enables drawing of the color gradient background.
 * If you want to disable it, call the Disable() function.
 */
void mitk::GradientBackground::Enable()
{
  if ( m_RenderWindow == NULL )
    return;
  if ( m_Renderer == NULL )
    return;

  //
  // layer ordering has changed from vtk 4.4 to vtk 5.0
  //
  #if ( VTK_MAJOR_VERSION >= 5 )
    int foregroundLayer = 1;
    int backgroundLayer = 0;
  #else
    int foregroundLayer = 0;
    int backgroundLayer = 1;
  #endif

  //
  // traverse the set of renderers and set their
  // layer to foreground / background
  //
  m_RenderWindow->SetNumberOfLayers( 2 );
  m_Renderer->SetLayer( backgroundLayer );
  m_RenderWindow->AddRenderer( m_Renderer );
  for( int i = 0 ; i < m_RenderWindow->GetNumberOfLayers() ; ++i )
  {
      vtkRenderer* currentRenderer =  dynamic_cast<vtkRenderer*>( m_RenderWindow->GetRenderers()->GetItemAsObject(i) );
      if ( currentRenderer != NULL )
      {
          if (currentRenderer == m_Renderer)
              currentRenderer->SetLayer( backgroundLayer );
          else
              currentRenderer->SetLayer( foregroundLayer );
      }
  }
}

/**
 * Disables drawing of the color gradient background.
 * If you want to enable it, call the Enable() function.
 */
void mitk::GradientBackground::Disable()
{
  if ( this->IsEnabled() )
    m_RenderWindow->RemoveRenderer( m_Renderer );
}

/**
 * Checks, if the gradient background is currently
 * enabled (visible)
 */
bool mitk::GradientBackground::IsEnabled()
{
    if ( m_RenderWindow == NULL )
        return false;
    else
        return ( m_RenderWindow->GetRenderers()->IsItemPresent( m_Renderer ) != 0 );
}

void mitk::GradientBackground::SetRequestedRegionToLargestPossibleRegion()
{
    //nothing to do
}

bool mitk::GradientBackground::RequestedRegionIsOutsideOfTheBufferedRegion()
{
    return false;
}

bool mitk::GradientBackground::VerifyRequestedRegion()
{
    return true;
}

void mitk::GradientBackground::SetRequestedRegion(itk::DataObject*)
{
    //nothing to do
}

<|endoftext|>


<commit_before>/*
 * AttentionSCM.cc
 *
 * Guile Scheme bindings for the attentionbank
 * Copyright (C) 2014 Cosmo Harrigan
 * Copyright (c) 2008, 2014, 2015, 2018 Linas Vepstas <linasvepstas@gmail.com>
 */

#ifdef HAVE_GUILE

#include <opencog/atoms/base/Link.h>
#include <opencog/attentionbank/AttentionBank.h>
#include <opencog/guile/SchemePrimitive.h>

namespace opencog {

class AttentionSCM
{
	protected:
		static void* init_in_guile(void*);
		static void init_in_module(void*);
		void init(void);
	public:
		AttentionSCM(void);
		~AttentionSCM();

		Handle update_af(int);
		int af_size(void);
		int set_af_size(int);
		Handle stimulate (const Handle&, double);
};

}

#include <opencog/atomspace/AtomSpace.h>
#include <opencog/guile/SchemePrimitive.h>
#include <opencog/guile/SchemeSmob.h>

using namespace opencog;

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

AttentionSCM::AttentionSCM(void)
{
	static bool is_init = false;
	if (is_init) return;
	is_init = true;
	scm_with_guile(init_in_guile, this);
}

void* AttentionSCM::init_in_guile(void* self)
{
	scm_c_define_module("opencog attention-bank", init_in_module, self);
	scm_c_use_module("opencog attention-bank");
	return NULL;
}

void AttentionSCM::init_in_module(void* data)
{
	AttentionSCM* self = (AttentionSCM*) data;
	self->init();
}

/// This is called while (opencog attention-bank) is the current module.
/// Thus, all the definitions below happen in that module.
void AttentionSCM::init(void)
{
	define_scheme_primitive("cog-update-af", &AttentionSCM::update_af, this, "attention-bank");
	define_scheme_primitive("cog-af-size", &AttentionSCM::af_size, this, "attention-bank");
	define_scheme_primitive("cog-set-af-size!", &AttentionSCM::set_af_size, this, "attention-bank");
	define_scheme_primitive("cog-stimulate", &AttentionSCM::stimulate, this, "attention-bank");
}

AttentionSCM::~AttentionSCM()
{
}

/**
 *   Return AttentionalFocus Size
 **/
int AttentionSCM::af_size(void)
{
    AtomSpace* atomspace = SchemeSmob::ss_get_env_as("cog-af-size");
    return attentionbank(atomspace).get_af_size();
}

/**
 * Set AttentionalFocus Size
 */
int AttentionSCM::set_af_size (int ssize)
{
    AtomSpace* atomspace = SchemeSmob::ss_get_env_as("cog-set-af-size!");

    attentionbank(atomspace).set_af_size(ssize);
    return attentionbank(atomspace).get_af_size();
}

/**
 * Return the list of top n atoms in the AttentionalFocus or
 * return all atoms in the AF if n is unspecified or is larger
 * than the AF size.
 */
Handle AttentionSCM::update_af(int n)
{
	AtomSpace* atomspace = SchemeSmob::ss_get_env_as("cog-af");

	Handle af_anchor = atomspace->add_node(ANCHOR_NODE,
	                                "*-attentional-focus-boundary-*");

	// Get the atoms that were previously in attention focus
	IncomingSet paf(af_anchor->getIncomingSetByType(MEMBER_LINK));
	HandleSet prev_af;
	for (const LinkPtr& lp: paf)
	{
		Handle h(lp->getOutgoingAtom(0));
		if (h != af_anchor)
			prev_af.insert(h);
	}

	HandleSeq attentionalFocus;
	attentionbank(atomspace).get_handle_set_in_attentional_focus(back_inserter(attentionalFocus));
	size_t isz = attentionalFocus.size();

	size_t N = isz;
	if (0 < n) N = n;
	if( N > isz)  N = isz;

	/* Add all the atoms in the current attentional focus that are not
	 * already there. */
	HandleSet curr_af;
	for (size_t i = isz - N; i < isz; i++)
	{
		Handle hi = attentionalFocus[i];
		auto gone = prev_af.find(hi);
		if (prev_af.end() == gone)
		{
			atomspace->add_link(MEMBER_LINK, hi, af_anchor);
		}
		else
		{
			curr_af.insert(hi);
		}
	}

	/* Remove the atoms no longer in attentional focus */
	for (const Handle& h: prev_af)
	{
		auto gone = curr_af.find(h);
		if (curr_af.end() == gone)
		{
			atomspace->extract_atom(h);
		}
	}

	return af_anchor;
}

/**
 *  Stimulate an atom with given stimulus amount.
 */
Handle AttentionSCM::stimulate (const Handle& h, double stimulus)
{
	AtomSpace* atomspace = SchemeSmob::ss_get_env_as("cog-stimulate");
	attentionbank(atomspace).stimulate(h, stimulus);
	return h;
}

extern "C" {
void opencog_attention_init(void);
};

void opencog_attention_init(void)
{
	static AttentionSCM atty;
}
#endif // HAVE_GUILE
<commit_msg>Start moveing the av routines over<commit_after>/*
 * AttentionSCM.cc
 *
 * Guile Scheme bindings for the attentionbank
 * Copyright (C) 2014 Cosmo Harrigan
 * Copyright (c) 2008, 2014, 2015, 2018 Linas Vepstas <linasvepstas@gmail.com>
 */

#ifdef HAVE_GUILE

#include <opencog/atoms/base/Link.h>
#include <opencog/attentionbank/AttentionBank.h>
#include <opencog/guile/SchemePrimitive.h>

namespace opencog {

class AttentionSCM
{
	protected:
		static void* init_in_guile(void*);
		static void init_in_module(void*);
		void init(void);
	public:
		AttentionSCM(void);
		~AttentionSCM();

		AttentionValuePtr get_av(const Handle&);
		Handle update_af(int);
		int af_size(void);
		int set_af_size(int);
		Handle stimulate (const Handle&, double);
};

}

#include <opencog/atomspace/AtomSpace.h>
#include <opencog/guile/SchemePrimitive.h>
#include <opencog/guile/SchemeSmob.h>

using namespace opencog;

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

AttentionSCM::AttentionSCM(void)
{
	static bool is_init = false;
	if (is_init) return;
	is_init = true;
	scm_with_guile(init_in_guile, this);
}

void* AttentionSCM::init_in_guile(void* self)
{
	scm_c_define_module("opencog attention-bank", init_in_module, self);
	scm_c_use_module("opencog attention-bank");
	return NULL;
}

void AttentionSCM::init_in_module(void* data)
{
	AttentionSCM* self = (AttentionSCM*) data;
	self->init();
}

/// This is called while (opencog attention-bank) is the current module.
/// Thus, all the definitions below happen in that module.
void AttentionSCM::init(void)
{
	define_scheme_primitive("cog-av", &AttentionSCM::get_av, this, "attention-bank");

	// Attentional-focus-related stuff
	define_scheme_primitive("cog-update-af", &AttentionSCM::update_af, this, "attention-bank");
	define_scheme_primitive("cog-af-size", &AttentionSCM::af_size, this, "attention-bank");
	define_scheme_primitive("cog-set-af-size!", &AttentionSCM::set_af_size, this, "attention-bank");
	define_scheme_primitive("cog-stimulate", &AttentionSCM::stimulate, this, "attention-bank");
}

AttentionSCM::~AttentionSCM()
{
}

AttentionValuePtr AttentionSCM::get_av(const Handle& h)
{
	return opencog::get_av(h);
}

/**
 *   Return AttentionalFocus Size
 **/
int AttentionSCM::af_size(void)
{
    AtomSpace* atomspace = SchemeSmob::ss_get_env_as("cog-af-size");
    return attentionbank(atomspace).get_af_size();
}

/**
 * Set AttentionalFocus Size
 */
int AttentionSCM::set_af_size (int ssize)
{
    AtomSpace* atomspace = SchemeSmob::ss_get_env_as("cog-set-af-size!");

    attentionbank(atomspace).set_af_size(ssize);
    return attentionbank(atomspace).get_af_size();
}

/**
 * Return the list of top n atoms in the AttentionalFocus or
 * return all atoms in the AF if n is unspecified or is larger
 * than the AF size.
 */
Handle AttentionSCM::update_af(int n)
{
	AtomSpace* atomspace = SchemeSmob::ss_get_env_as("cog-af");

	Handle af_anchor = atomspace->add_node(ANCHOR_NODE,
	                                "*-attentional-focus-boundary-*");

	// Get the atoms that were previously in attention focus
	IncomingSet paf(af_anchor->getIncomingSetByType(MEMBER_LINK));
	HandleSet prev_af;
	for (const LinkPtr& lp: paf)
	{
		Handle h(lp->getOutgoingAtom(0));
		if (h != af_anchor)
			prev_af.insert(h);
	}

	HandleSeq attentionalFocus;
	attentionbank(atomspace).get_handle_set_in_attentional_focus(back_inserter(attentionalFocus));
	size_t isz = attentionalFocus.size();

	size_t N = isz;
	if (0 < n) N = n;
	if( N > isz)  N = isz;

	/* Add all the atoms in the current attentional focus that are not
	 * already there. */
	HandleSet curr_af;
	for (size_t i = isz - N; i < isz; i++)
	{
		Handle hi = attentionalFocus[i];
		auto gone = prev_af.find(hi);
		if (prev_af.end() == gone)
		{
			atomspace->add_link(MEMBER_LINK, hi, af_anchor);
		}
		else
		{
			curr_af.insert(hi);
		}
	}

	/* Remove the atoms no longer in attentional focus */
	for (const Handle& h: prev_af)
	{
		auto gone = curr_af.find(h);
		if (curr_af.end() == gone)
		{
			atomspace->extract_atom(h);
		}
	}

	return af_anchor;
}

/**
 *  Stimulate an atom with given stimulus amount.
 */
Handle AttentionSCM::stimulate (const Handle& h, double stimulus)
{
	AtomSpace* atomspace = SchemeSmob::ss_get_env_as("cog-stimulate");
	attentionbank(atomspace).stimulate(h, stimulus);
	return h;
}

extern "C" {
void opencog_attention_init(void);
};

void opencog_attention_init(void)
{
	static AttentionSCM atty;
}
#endif // HAVE_GUILE
<|endoftext|>


<commit_before><commit_msg>Tweak constants used by sync setup wizard unittest. Reviewed by nick.<commit_after><|endoftext|>