<commit_before>#include "iotsa.h"

#if defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
// Tiny http server which forwards to https
class TinyForwardServer {
public:
  ESP8266WebServer server;
  TinyForwardServer()
  : server(80)
  {
    server.onNotFound(std::bind(&TinyForwardServer::notFound, this));
    server.begin();
  }
  void notFound() {
    String newLoc = "https://";
    if (iotsaConfig.wifiPrivateNetworkMode) {
      newLoc += "192.168.4.1";
    } else {
      newLoc += iotsaConfig.hostName;
      newLoc += ".local";
    }
    newLoc += server.uri();
    IFDEBUG IotsaSerial.print("HTTP 301 to ");
    IFDEBUG IotsaSerial.println(newLoc);
    server.sendHeader("Location", newLoc);
    server.uri();
    server.send(301, "", "");
  }
};

static TinyForwardServer *singletonTFS;

#endif // defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)

IotsaWebServerMixin::IotsaWebServerMixin(IotsaApplication* _app)
:
#ifdef IOTSA_WITH_HTTP_OR_HTTPS
    server(new IotsaWebServer(IOTSA_WEBSERVER_PORT)),
#endif
  app(_app)
{
}

#ifdef IOTSA_WITH_HTTP_OR_HTTPS
void
IotsaWebServerMixin::webServerSetup() {
  if (!iotsaConfig.wifiEnabled) return;

#if defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
  if (singletonTFS == NULL)
    singletonTFS = new TinyForwardServer();
#endif // defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)

#ifdef IOTSA_WITH_HTTP_OR_HTTPS
  server->onNotFound(std::bind(&IotsaWebServerMixin::webServerNotFoundHandler, this));
#endif
#ifdef IOTSA_WITH_WEB
  server->on("/", std::bind(&IotsaWebServerMixin::webServerRootHandler, this));
#endif

#ifdef IOTSA_WITH_HTTPS
  IFDEBUG IotsaSerial.print("Using https key len=");
  IFDEBUG IotsaSerial.print(iotsaConfig.httpsKeyLength);
  IFDEBUG IotsaSerial.print(", cert len=");
  IFDEBUG IotsaSerial.println(iotsaConfig.httpsCertificateLength);
  server->getServer().setServerKeyAndCert_P(
    iotsaConfig.httpsKey,
    iotsaConfig.httpsKeyLength,
    iotsaConfig.httpsCertificate,
    iotsaConfig.httpsCertificateLength
  );
#endif
  server->begin();
#ifdef IOTSA_WITH_HTTPS
  IFDEBUG IotsaSerial.println("HTTPS server started");
#else
  IFDEBUG IotsaSerial.println("HTTP server started");
#endif
}

void
IotsaWebServerMixin::webServerLoop() {
  if (!iotsaConfig.wifiEnabled) return;
  server->handleClient();
#if defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
  singletonTFS->server.handleClient();
#endif
}

void
IotsaWebServerMixin::webServerNotFoundHandler() {
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server->uri();
  message += "\nMethod: ";
  message += (server->method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server->args();
  message += "\n";
  for (uint8_t i=0; i<server->args(); i++){
    message += " " + server->argName(i) + ": " + server->arg(i) + "\n";
  }
  server->send(404, "text/plain", message);
}
#endif // IOTSA_WITH_HTTP_OR_HTTPS

#ifdef IOTSA_WITH_WEB
void
IotsaWebServerMixin::webServerRootHandler() {
  String message = "<title>" + app->title + "</title>
" + app->title + "
";
  IotsaBaseMod *m;
  for (m=app->firstModule; m; m=m->nextModule) {
    message += m->info();
  }
  for (m=app->firstEarlyModule; m; m=m->nextModule) {
    message += m->info();
  }
  message += "";
  server->send(200, "text/html", message);
}
#endif // IOTSA_WITH_WEB<commit_msg>Fixed bug when building without any webserver<commit_after>#include "iotsa.h"

#if defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
// Tiny http server which forwards to https
class TinyForwardServer {
public:
  ESP8266WebServer server;
  TinyForwardServer()
  : server(80)
  {
    server.onNotFound(std::bind(&TinyForwardServer::notFound, this));
    server.begin();
  }
  void notFound() {
    String newLoc = "https://";
    if (iotsaConfig.wifiPrivateNetworkMode) {
      newLoc += "192.168.4.1";
    } else {
      newLoc += iotsaConfig.hostName;
      newLoc += ".local";
    }
    newLoc += server.uri();
    IFDEBUG IotsaSerial.print("HTTP 301 to ");
    IFDEBUG IotsaSerial.println(newLoc);
    server.sendHeader("Location", newLoc);
    server.uri();
    server.send(301, "", "");
  }
};

static TinyForwardServer *singletonTFS;

#endif // defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)

IotsaWebServerMixin::IotsaWebServerMixin(IotsaApplication* _app)
#ifdef IOTSA_WITH_HTTP_OR_HTTPS
:
  server(new IotsaWebServer(IOTSA_WEBSERVER_PORT)),
  app(_app)
#endif
{
}

#ifdef IOTSA_WITH_HTTP_OR_HTTPS
void
IotsaWebServerMixin::webServerSetup() {
  if (!iotsaConfig.wifiEnabled) return;

#if defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
  if (singletonTFS == NULL)
    singletonTFS = new TinyForwardServer();
#endif // defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)

#ifdef IOTSA_WITH_HTTP_OR_HTTPS
  server->onNotFound(std::bind(&IotsaWebServerMixin::webServerNotFoundHandler, this));
#endif
#ifdef IOTSA_WITH_WEB
  server->on("/", std::bind(&IotsaWebServerMixin::webServerRootHandler, this));
#endif

#ifdef IOTSA_WITH_HTTPS
  IFDEBUG IotsaSerial.print("Using https key len=");
  IFDEBUG IotsaSerial.print(iotsaConfig.httpsKeyLength);
  IFDEBUG IotsaSerial.print(", cert len=");
  IFDEBUG IotsaSerial.println(iotsaConfig.httpsCertificateLength);
  server->getServer().setServerKeyAndCert_P(
    iotsaConfig.httpsKey,
    iotsaConfig.httpsKeyLength,
    iotsaConfig.httpsCertificate,
    iotsaConfig.httpsCertificateLength
  );
#endif
  server->begin();
#ifdef IOTSA_WITH_HTTPS
  IFDEBUG IotsaSerial.println("HTTPS server started");
#else
  IFDEBUG IotsaSerial.println("HTTP server started");
#endif
}

void
IotsaWebServerMixin::webServerLoop() {
  if (!iotsaConfig.wifiEnabled) return;
  server->handleClient();
#if defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
  singletonTFS->server.handleClient();
#endif
}

void
IotsaWebServerMixin::webServerNotFoundHandler() {
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server->uri();
  message += "\nMethod: ";
  message += (server->method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server->args();
  message += "\n";
  for (uint8_t i=0; i<server->args(); i++){
    message += " " + server->argName(i) + ": " + server->arg(i) + "\n";
  }
  server->send(404, "text/plain", message);
}
#endif // IOTSA_WITH_HTTP_OR_HTTPS

#ifdef IOTSA_WITH_WEB
void
IotsaWebServerMixin::webServerRootHandler() {
  String message = "<title>" + app->title + "</title>
" + app->title + "
";
  IotsaBaseMod *m;
  for (m=app->firstModule; m; m=m->nextModule) {
    message += m->info();
  }
  for (m=app->firstEarlyModule; m; m=m->nextModule) {
    message += m->info();
  }
  message += "";
  server->send(200, "text/html", message);
}
#endif // IOTSA_WITH_WEB<|endoftext|>


<commit_before>#pragma once
#include "GeneNode.hpp"

/*
* This simple class encapsulates all of an Individual's genetic information,
* including the gene pools it uses, with the goal of easing the sharing of
* this information between classes.
*/

class Genome {
	private:

	protected:
	int * gene;
	int genomeLength;
	GeneNode ** genePools;

	public:
	Genome(int * newGene, int newGenomeLength, GeneNode ** newGeneNodes);

	~Genome();

	int * getGenome();
	int getGenomeLength();
	GeneNode ** getGeneNodes();
	int getDifference(Genome * otherGenome);
};
<commit_msg>[Genome]: Tweaked Genome to use vectors<commit_after>#pragma once
#include "Locus.hpp"
#include <vector>

class Genome {
	private:

	protected:
	std::vector<int> genes;
	std::vector<Locus*> loci;

	public:
	Genome(std::vector<Locus*> loci);
	Genome(std::vector<int> genes, std::vector<Locus*> loci);

	~Genome();

	std::vector<int> getGenome();
	int getGenomeLength();
	std::vector<Locus*> getLoci();
	int getDifference(Genome * otherGenome);
};
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebM 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 "third_party/googletest/src/include/gtest/gtest.h"

#include "./vp9_rtcd.h"
#include "./vpx_config.h"
#include "./vpx_dsp_rtcd.h"
#include "test/acm_random.h"
#include "test/bench.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "vp9/common/vp9_blockd.h"
#include "vpx_mem/vpx_mem.h"

typedef void (*SubtractFunc)(int rows, int cols, int16_t *diff_ptr,
                             ptrdiff_t diff_stride, const uint8_t *src_ptr,
                             ptrdiff_t src_stride, const uint8_t *pred_ptr,
                             ptrdiff_t pred_stride);

namespace vp9 {

class VP9SubtractBlockTest : public AbstractBench,
                             public ::testing::TestWithParam<SubtractFunc> {
 public:
  virtual void TearDown() { libvpx_test::ClearSystemState(); }

 protected:
  int block_width_;
  int block_height_;
  int16_t *diff_;
  uint8_t *pred_;
  uint8_t *src_;

  virtual void Run() {
    GetParam()(block_height_, block_width_, diff_, block_width_, src_,
               block_width_, pred_, block_width_);
  }

  void SetupBlocks(BLOCK_SIZE bsize) {
    block_width_ = 4 * num_4x4_blocks_wide_lookup[bsize];
    block_height_ = 4 * num_4x4_blocks_high_lookup[bsize];
    diff_ = reinterpret_cast<int16_t *>(
        vpx_memalign(16, sizeof(*diff_) * block_width_ * block_height_ * 2));
    pred_ = reinterpret_cast<uint8_t *>(
        vpx_memalign(16, block_width_ * block_height_ * 2));
    src_ = reinterpret_cast<uint8_t *>(
        vpx_memalign(16, block_width_ * block_height_ * 2));
  }
};

using libvpx_test::ACMRandom;

TEST_P(VP9SubtractBlockTest, DISABLED_Speed) {
  ACMRandom rnd(ACMRandom::DeterministicSeed());

  for (BLOCK_SIZE bsize = BLOCK_4X4; bsize < BLOCK_SIZES;
       bsize = static_cast<BLOCK_SIZE>(static_cast<int>(bsize) + 1)) {
    SetupBlocks(bsize);

    RunNTimes(100000000 / (block_height_ * block_width_));
    char block_size[16];
    snprintf(block_size, sizeof(block_size), "%dx%d", block_height_,
             block_width_);
    char title[100];
    snprintf(title, sizeof(title), "%8s ", block_size);
    PrintMedian(title);

    vpx_free(diff_);
    vpx_free(pred_);
    vpx_free(src_);
  }
}

TEST_P(VP9SubtractBlockTest, SimpleSubtract) {
  ACMRandom rnd(ACMRandom::DeterministicSeed());

  // FIXME(rbultje) split in its own file
  for (BLOCK_SIZE bsize = BLOCK_4X4; bsize < BLOCK_SIZES;
       bsize = static_cast<BLOCK_SIZE>(static_cast<int>(bsize) + 1)) {
    SetupBlocks(bsize);

    for (int n = 0; n < 100; n++) {
      for (int r = 0; r < block_height_; ++r) {
        for (int c = 0; c < block_width_ * 2; ++c) {
          src_[r * block_width_ * 2 + c] = rnd.Rand8();
          pred_[r * block_width_ * 2 + c] = rnd.Rand8();
        }
      }

      GetParam()(block_height_, block_width_, diff_, block_width_, src_,
                 block_width_, pred_, block_width_);

      for (int r = 0; r < block_height_; ++r) {
        for (int c = 0; c < block_width_; ++c) {
          EXPECT_EQ(diff_[r * block_width_ + c],
                    (src_[r * block_width_ + c] - pred_[r * block_width_ + c]))
              << "r = " << r << ", c = " << c << ", bs = " << bsize;
        }
      }

      GetParam()(block_height_, block_width_, diff_, block_width_ * 2, src_,
                 block_width_ * 2, pred_, block_width_ * 2);

      for (int r = 0; r < block_height_; ++r) {
        for (int c = 0; c < block_width_; ++c) {
          EXPECT_EQ(diff_[r * block_width_ * 2 + c],
                    (src_[r * block_width_ * 2 + c] -
                     pred_[r * block_width_ * 2 + c]))
              << "r = " << r << ", c = " << c << ", bs = " << bsize;
        }
      }
    }
    vpx_free(diff_);
    vpx_free(pred_);
    vpx_free(src_);
  }
}

INSTANTIATE_TEST_CASE_P(C, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_c));

#if HAVE_SSE2
INSTANTIATE_TEST_CASE_P(SSE2, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_sse2));
#endif
#if HAVE_NEON
INSTANTIATE_TEST_CASE_P(NEON, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_neon));
#endif
#if HAVE_MSA
INSTANTIATE_TEST_CASE_P(MSA, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_msa));
#endif

#if HAVE_MMI
INSTANTIATE_TEST_CASE_P(MMI, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_mmi));
#endif

}  // namespace vp9
<commit_msg>Cast bsize as int to print a meaninful debug info<commit_after>/*
 *  Copyright (c) 2012 The WebM 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 "third_party/googletest/src/include/gtest/gtest.h"

#include "./vp9_rtcd.h"
#include "./vpx_config.h"
#include "./vpx_dsp_rtcd.h"
#include "test/acm_random.h"
#include "test/bench.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "vp9/common/vp9_blockd.h"
#include "vpx_mem/vpx_mem.h"

typedef void (*SubtractFunc)(int rows, int cols, int16_t *diff_ptr,
                             ptrdiff_t diff_stride, const uint8_t *src_ptr,
                             ptrdiff_t src_stride, const uint8_t *pred_ptr,
                             ptrdiff_t pred_stride);

namespace vp9 {

class VP9SubtractBlockTest : public AbstractBench,
                             public ::testing::TestWithParam<SubtractFunc> {
 public:
  virtual void TearDown() { libvpx_test::ClearSystemState(); }

 protected:
  int block_width_;
  int block_height_;
  int16_t *diff_;
  uint8_t *pred_;
  uint8_t *src_;

  virtual void Run() {
    GetParam()(block_height_, block_width_, diff_, block_width_, src_,
               block_width_, pred_, block_width_);
  }

  void SetupBlocks(BLOCK_SIZE bsize) {
    block_width_ = 4 * num_4x4_blocks_wide_lookup[bsize];
    block_height_ = 4 * num_4x4_blocks_high_lookup[bsize];
    diff_ = reinterpret_cast<int16_t *>(
        vpx_memalign(16, sizeof(*diff_) * block_width_ * block_height_ * 2));
    pred_ = reinterpret_cast<uint8_t *>(
        vpx_memalign(16, block_width_ * block_height_ * 2));
    src_ = reinterpret_cast<uint8_t *>(
        vpx_memalign(16, block_width_ * block_height_ * 2));
  }
};

using libvpx_test::ACMRandom;

TEST_P(VP9SubtractBlockTest, DISABLED_Speed) {
  ACMRandom rnd(ACMRandom::DeterministicSeed());

  for (BLOCK_SIZE bsize = BLOCK_4X4; bsize < BLOCK_SIZES;
       bsize = static_cast<BLOCK_SIZE>(static_cast<int>(bsize) + 1)) {
    SetupBlocks(bsize);

    RunNTimes(100000000 / (block_height_ * block_width_));
    char block_size[16];
    snprintf(block_size, sizeof(block_size), "%dx%d", block_height_,
             block_width_);
    char title[100];
    snprintf(title, sizeof(title), "%8s ", block_size);
    PrintMedian(title);

    vpx_free(diff_);
    vpx_free(pred_);
    vpx_free(src_);
  }
}

TEST_P(VP9SubtractBlockTest, SimpleSubtract) {
  ACMRandom rnd(ACMRandom::DeterministicSeed());

  // FIXME(rbultje) split in its own file
  for (BLOCK_SIZE bsize = BLOCK_4X4; bsize < BLOCK_SIZES;
       bsize = static_cast<BLOCK_SIZE>(static_cast<int>(bsize) + 1)) {
    SetupBlocks(bsize);

    for (int n = 0; n < 100; n++) {
      for (int r = 0; r < block_height_; ++r) {
        for (int c = 0; c < block_width_ * 2; ++c) {
          src_[r * block_width_ * 2 + c] = rnd.Rand8();
          pred_[r * block_width_ * 2 + c] = rnd.Rand8();
        }
      }

      GetParam()(block_height_, block_width_, diff_, block_width_, src_,
                 block_width_, pred_, block_width_);

      for (int r = 0; r < block_height_; ++r) {
        for (int c = 0; c < block_width_; ++c) {
          EXPECT_EQ(diff_[r * block_width_ + c],
                    (src_[r * block_width_ + c] - pred_[r * block_width_ + c]))
              << "r = " << r << ", c = " << c << ", bs = " << (int)bsize;
        }
      }

      GetParam()(block_height_, block_width_, diff_, block_width_ * 2, src_,
                 block_width_ * 2, pred_, block_width_ * 2);

      for (int r = 0; r < block_height_; ++r) {
        for (int c = 0; c < block_width_; ++c) {
          EXPECT_EQ(diff_[r * block_width_ * 2 + c],
                    (src_[r * block_width_ * 2 + c] -
                     pred_[r * block_width_ * 2 + c]))
              << "r = " << r << ", c = " << c << ", bs = " << (int)bsize;
        }
      }
    }
    vpx_free(diff_);
    vpx_free(pred_);
    vpx_free(src_);
  }
}

INSTANTIATE_TEST_CASE_P(C, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_c));

#if HAVE_SSE2
INSTANTIATE_TEST_CASE_P(SSE2, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_sse2));
#endif
#if HAVE_NEON
INSTANTIATE_TEST_CASE_P(NEON, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_neon));
#endif
#if HAVE_MSA
INSTANTIATE_TEST_CASE_P(MSA, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_msa));
#endif

#if HAVE_MMI
INSTANTIATE_TEST_CASE_P(MMI, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_mmi));
#endif

}  // namespace vp9
<|endoftext|>


<commit_before>#include "MISC.H"
#include "CONTROL.H"
#include "CAMERA.H"
#include "GPU.H"
#include "LOAD_LEV.H"
#include "SPECIFIC.H"
#include "TEXT_S.H"

#include <EMULATOR.H>
#include <LIBETC.H>
#include "GAMEFLOW.H"

#if PSXPC_VERSION || PSXPC_TEST
#include <stdint.h>
#endif

#if PSX_VERSION && !PSXPC_TEST
typedef unsigned int uintptr_t;
#endif

void S_MemSet(char* p, int value, int length)
{
	int size;

	if (length != 0)
	{
		if (length > 3)
		{
			value |= value << 8;
			value |= value << 16;

			if (((uintptr_t)p) & 3)
			{
				size = 4 - (((uintptr_t)p) & 3);
				length -= 4 - (((uintptr_t)p) & 3);

				//loc_5E918
				while (size--)
					*p++ = value;
			}
			//loc_5E928
			size = length >> 2;
			if ((length >> 2))
			{
				length &= 3;

				//loc_5E934
				while (size--)
				{
					((int*)p)[0] = value;
					p += 4;
				}
			}
		}
		//loc_5E94C
		while (length-- != 0)
			*p++ = value;
	}
}

void S_LongMemCpy(unsigned long* pDest, unsigned long* pSrc, unsigned long size) //5E964(<), ? (F)
{
	int i;

	if (size > 0)
	{
		for (i = size / sizeof(unsigned long); i > 0; i--, pDest += 4, pSrc += 4)
		{
			//loc_5E974
			pDest[0] = pSrc[0];
			pDest[1] = pSrc[1];
			pDest[2] = pSrc[2];
			pDest[3] = pSrc[3];
		}

		//loc_5E9AC
		for (i = size & 3; i > 0; i--)
		{
			*pDest++ = *pSrc++;
		}
	}
}

void DrawF4(unsigned short x, unsigned short y, unsigned short w, unsigned short h, int unk, int unk2) //5EDF8
{
	UNIMPLEMENTED();
}

void DrawTPage(unsigned char a0, unsigned char a1) //5EE78(<), 5FB58(<)
{
	UNIMPLEMENTED();
}

void DrawLineH(long a0, long a1, long a2, long a3, long a4, long a5) //5EECC(<)
{
	UNIMPLEMENTED();
}

void DrawLineV(long a0, long a1, long a2, long a3, long a4, long a5) //5EF84(<),
{
	UNIMPLEMENTED();
}

void LOAD_VSyncHandler() //5F074(<), 5FD54(<) (F)
{
	int a0, a1, a2;

	if (!LtLoadingBarEnabled)
	{
		return;
	}

	//loc_5F08C
	GPU_BeginScene();

	a0 = 440; //x?
	a1 = 200; //y?
	a2 = 64; //cd width or height?

	if (_first_time_ever)
	{
		a0 += 24;
		a1 += 8;
		a2 = 48;
	}

	//loc_5F0B4
	draw_rotate_sprite(a0, a1, a2);
	db.current_buffer ^= 1;
	GnLastFrameCount = 0;
	DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[0]);
	return;
}

void LOAD_DrawEnable(unsigned char isEnabled) //5F2C8, 5FFA8
{
	LtLoadingBarEnabled = isEnabled;
}

void GPU_BeginScene() //5F0F0(<), 5FDD0(<)
{
	db.ot = db.order_table[db.current_buffer];
	db.polyptr = (char*)db.poly_buffer[db.current_buffer];
	db.curpolybuf = (char*)db.poly_buffer[db.current_buffer];
	db.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer] + 26000);
	db.pickup_ot = db.pickup_order_table[db.current_buffer];
	ClearOTagR(db.order_table[db.current_buffer], db.nOTSize);

	Emulator_BeginScene();
}

void draw_rotate_sprite(long a0, long a1, long a2) //5F134, 5FE14 (F)
{
	long t0;
	short* r_cossinptr;
	long t6;
	long t5;
	long t1;
	long t4;

	DelRotAng = (DelRotAng - 52) & 0xFFF;
	r_cossinptr = &rcossin_tbl[DelRotAng * 2];

	t6 = ((-a2 / 2) * r_cossinptr[0]) / 4096;
	t5 = ((-a2 / 2) * r_cossinptr[1]) / 4096;

	*(long*)&db.polyptr[4] = 0x2C808080;
	*(long*)&db.polyptr[12] = 0;
	*(long*)&db.polyptr[20] = 0x1303F00;

	t0 = t6 - t5;
	a2 = -t6;
	t4 = a2 - t5;
	a2 += t5;
	t1 = t6 + t5;

	*(short*)&db.polyptr[8] = t0 + (t0 / 2) + a0;
	*(short*)&db.polyptr[10] = t5 + t6 + a1;

	*(short*)&db.polyptr[16] = t4 + (t4 / 2) + a0;
	*(short*)&db.polyptr[18] = -t5 + t6 + a1;

	*(short*)&db.polyptr[24] = t1 + (t1 / 2) + a0;
	*(short*)&db.polyptr[26] = (t5 - t6) + a1;

	*(short*)&db.polyptr[28] = 0x3F; //width/height of loading cd?
	*(short*)&db.polyptr[36] = 0x3F3F;

	*(short*)&db.polyptr[32] = a2 + (a2 / 2) + a0;
	*(short*)&db.polyptr[34] = a1 + (-t5 - t6);

	*(long*)&db.polyptr[0] = db.ot[0] | 0x09000000;
	db.ot[0] = (unsigned long)&db.polyptr[0];

	db.polyptr += 0x28; //sizeof(POLY_F3); * 2?

	*(long*)&db.polyptr[4] = 0x2C808080;
	*(long*)&db.polyptr[8] = 0x780100;
	*(long*)&db.polyptr[12] = 0x6800;
	*(long*)&db.polyptr[16] = 0x7801FF;

	*(long*)&db.polyptr[20] = 0x13468FF;
	*(long*)&db.polyptr[24] = 0xEF0100;
	*(short*)&db.polyptr[28] = 0xDF00;
	*(long*)&db.polyptr[32] = 0xEF01FF;

	*(short*)&db.polyptr[36] = 0xDFFF;

	*(long*)&db.polyptr[0] = db.ot[0] | 0x9000000;
	db.ot[0] = (unsigned long)db.polyptr;
	//sizeof(POLY_G3);
	db.polyptr += 0x28;
	return;
}

/*   PSX VRAM   (H)
 *  ----------- 1024px
 *  | TL | TR |  |
 *  -----------  v
 *  | BL | BR |
 *  -----------
 *(W)1024px-->
 *
 */
void GPU_ClearVRAM() //5F2D0(<), 5FFB0(<) (F) (D) (ND)
{
	RECT16 r;

	//Clear TL
	r.x = 0;
	r.y = 0;
	r.w = 512;
	r.h = 256;
	clear_a_rect(&r);

	//Clear BL
	r.y = 256;
	clear_a_rect(&r);

	//Clear BR
	r.x = 512;
	clear_a_rect(&r);

	//Clear TR
	r.y = 0;
	clear_a_rect(&r);

	return;
}

void clear_a_rect(RECT16* r) //5F334(<), 60014(<) (F) (D) (ND)
{
	ClearImage(r, 0, 48, 0);
	return;
}

void GPU_GetScreenPosition(short* x, short* y) //5F34C, ? (*) (F) (D) (ND)
{
	*x = db.disp[0].screen.x;
	*y = db.disp[0].screen.y;
	return;
}

void GPU_SetScreenPosition(short x, short y) //5F360(<), 60040(<)
{
	db.disp[0].screen.x = x;
	db.disp[0].screen.y = y;
	db.disp[1].screen.x = x;
	db.disp[1].screen.y = y;

	return;
}

void GPU_SyncBothScreens() //5F374(<), 60054(<)
{
	DrawSync(0);
	db.current_buffer ^= 1;
	if (db.current_buffer != 0)
	{
		MoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y);
	}
	else
	{
		//loc_5F3A8
		MoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y);
	}

	DrawSync(0);

	return;
}

///@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code.
void GPU_FlipToBuffer(int buffer_index) //5F3C8(<), 600A8(<) (F) (D) (ND)
{
	DrawSync(0);
	VSync(0);

	if (buffer_index & 1)
	{
		PutDispEnv(&db.disp[1]);
	}
	else
	{
		PutDispEnv(&db.disp[0]);
	}

	if (buffer_index & 1)
	{
		PutDrawEnv(&db.draw[1]);
	}
	else
	{
		PutDrawEnv(&db.draw[0]);
	}

	db.current_buffer = buffer_index & 1 ^ 1;

	return;
}

void frig_with_monitor_screen(int a0)
{
	UNIMPLEMENTED();
}

void S_AnimateTextures(long nFrames)
{
	AnimComp += nFrames;

	while (AnimComp > 5)
	{
		uint16_t* ptr = AnimTextureRanges;

		for (uint16_t i = *(ptr++); i > 0; i--, ptr++)
		{
			MMTEXTURE tmp = RoomTextInfo[*(ptr + 1)];

			for (uint16_t j = *ptr++; j > 0; j--, ptr++)
			{
				RoomTextInfo[*ptr] = RoomTextInfo[*(ptr + 1)];
			}

			RoomTextInfo[*ptr] = tmp;
		}

		AnimComp -= 5;
	}

	if (gfUVRotate) // 19d8
	{
		uint16_t* t3 = AnimTextureRanges;
		AnimatingTexturesVOffset = (AnimatingTexturesVOffset - gfUVRotate * (nFrames / 2)) & 0x1f;
		if (nAnimUVRanges > 0)
		{
			short (*t2)[8][3] = AnimatingTexturesV;

			for (int i = 0; i < nAnimUVRanges; i++, t2++)
			{
				unsigned short num = *t3++;
				if (num > 0)
				{
					short* t1 = t2[i][num];

					for (int j = 0; j <= num; j++, t1-=3, t3++)
					{
						int t0 = 32;
						int a2 = AnimatingTexturesVOffset;
						MMTEXTURE* a0tm = &RoomTextInfo[*t3];
						for (int a3 = 0; a3 < 3; a3++, a2 >>= 1, t0 >>= 1)
						{
							auto v0__ = (uint8_t)(t1[a3] >> 8);

							a0tm->t[a3].v0 = v0__ + a2;

							a0tm->t[a3].v1 = v0__ + a2;

							a0tm->t[a3].v2 = v0__ + a2 + t0;

							a0tm->t[a3].v3 = v0__ + a2 + t0;
						}
					}
				}
			}
		}
	}

	frig_with_monitor_screen(0);
}

void PrintGauge(int x, int y, int length)
{
	UNIMPLEMENTED();
}

long GetRandomControl() //5E9F0, 926F8 (F)
{
	rand_1 = (rand_1 * 0x41C64E6D) + 0x3039;
	return (rand_1 >> 16) & 0x7FFF;
}

void SeedRandomControl(long seed) //(F)
{
	rand_1 = seed;
}

long GetRandomDraw() //5EA18, 5F6F8 (F)
{
	rand_2 = (rand_2 * 0x41C64E6D) + 0x3039;
	return (rand_2 >> 16) * 0x7FFF;
}

void SeedRandomDraw(long seed) //(F)
{
	rand_2 = seed;
}

void S_MemCpy(char* pSrc, char* pDest, int size)
{
	if (size > 0)
	{
		while (size-- > 0)
			*pSrc++ = *pDest++;
	}
}
<commit_msg>specify type<commit_after>#include "MISC.H"
#include "CONTROL.H"
#include "CAMERA.H"
#include "GPU.H"
#include "LOAD_LEV.H"
#include "SPECIFIC.H"
#include "TEXT_S.H"

#include <EMULATOR.H>
#include <LIBETC.H>
#include "GAMEFLOW.H"

#if PSXPC_VERSION || PSXPC_TEST
#include <stdint.h>
#endif

#if PSX_VERSION && !PSXPC_TEST
typedef unsigned int uintptr_t;
#endif

void S_MemSet(char* p, int value, int length)
{
	int size;

	if (length != 0)
	{
		if (length > 3)
		{
			value |= value << 8;
			value |= value << 16;

			if (((uintptr_t)p) & 3)
			{
				size = 4 - (((uintptr_t)p) & 3);
				length -= 4 - (((uintptr_t)p) & 3);

				//loc_5E918
				while (size--)
					*p++ = value;
			}
			//loc_5E928
			size = length >> 2;
			if ((length >> 2))
			{
				length &= 3;

				//loc_5E934
				while (size--)
				{
					((int*)p)[0] = value;
					p += 4;
				}
			}
		}
		//loc_5E94C
		while (length-- != 0)
			*p++ = value;
	}
}

void S_LongMemCpy(unsigned long* pDest, unsigned long* pSrc, unsigned long size) //5E964(<), ? (F)
{
	int i;

	if (size > 0)
	{
		for (i = size / sizeof(unsigned long); i > 0; i--, pDest += 4, pSrc += 4)
		{
			//loc_5E974
			pDest[0] = pSrc[0];
			pDest[1] = pSrc[1];
			pDest[2] = pSrc[2];
			pDest[3] = pSrc[3];
		}

		//loc_5E9AC
		for (i = size & 3; i > 0; i--)
		{
			*pDest++ = *pSrc++;
		}
	}
}

void DrawF4(unsigned short x, unsigned short y, unsigned short w, unsigned short h, int unk, int unk2) //5EDF8
{
	UNIMPLEMENTED();
}

void DrawTPage(unsigned char a0, unsigned char a1) //5EE78(<), 5FB58(<)
{
	UNIMPLEMENTED();
}

void DrawLineH(long a0, long a1, long a2, long a3, long a4, long a5) //5EECC(<)
{
	UNIMPLEMENTED();
}

void DrawLineV(long a0, long a1, long a2, long a3, long a4, long a5) //5EF84(<),
{
	UNIMPLEMENTED();
}

void LOAD_VSyncHandler() //5F074(<), 5FD54(<) (F)
{
	int a0, a1, a2;

	if (!LtLoadingBarEnabled)
	{
		return;
	}

	//loc_5F08C
	GPU_BeginScene();

	a0 = 440; //x?
	a1 = 200; //y?
	a2 = 64; //cd width or height?

	if (_first_time_ever)
	{
		a0 += 24;
		a1 += 8;
		a2 = 48;
	}

	//loc_5F0B4
	draw_rotate_sprite(a0, a1, a2);
	db.current_buffer ^= 1;
	GnLastFrameCount = 0;
	DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[0]);
	return;
}

void LOAD_DrawEnable(unsigned char isEnabled) //5F2C8, 5FFA8
{
	LtLoadingBarEnabled = isEnabled;
}

void GPU_BeginScene() //5F0F0(<), 5FDD0(<)
{
	db.ot = db.order_table[db.current_buffer];
	db.polyptr = (char*)db.poly_buffer[db.current_buffer];
	db.curpolybuf = (char*)db.poly_buffer[db.current_buffer];
	db.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer] + 26000);
	db.pickup_ot = db.pickup_order_table[db.current_buffer];
	ClearOTagR(db.order_table[db.current_buffer], db.nOTSize);

	Emulator_BeginScene();
}

void draw_rotate_sprite(long a0, long a1, long a2) //5F134, 5FE14 (F)
{
	long t0;
	short* r_cossinptr;
	long t6;
	long t5;
	long t1;
	long t4;

	DelRotAng = (DelRotAng - 52) & 0xFFF;
	r_cossinptr = &rcossin_tbl[DelRotAng * 2];

	t6 = ((-a2 / 2) * r_cossinptr[0]) / 4096;
	t5 = ((-a2 / 2) * r_cossinptr[1]) / 4096;

	*(long*)&db.polyptr[4] = 0x2C808080;
	*(long*)&db.polyptr[12] = 0;
	*(long*)&db.polyptr[20] = 0x1303F00;

	t0 = t6 - t5;
	a2 = -t6;
	t4 = a2 - t5;
	a2 += t5;
	t1 = t6 + t5;

	*(short*)&db.polyptr[8] = t0 + (t0 / 2) + a0;
	*(short*)&db.polyptr[10] = t5 + t6 + a1;

	*(short*)&db.polyptr[16] = t4 + (t4 / 2) + a0;
	*(short*)&db.polyptr[18] = -t5 + t6 + a1;

	*(short*)&db.polyptr[24] = t1 + (t1 / 2) + a0;
	*(short*)&db.polyptr[26] = (t5 - t6) + a1;

	*(short*)&db.polyptr[28] = 0x3F; //width/height of loading cd?
	*(short*)&db.polyptr[36] = 0x3F3F;

	*(short*)&db.polyptr[32] = a2 + (a2 / 2) + a0;
	*(short*)&db.polyptr[34] = a1 + (-t5 - t6);

	*(long*)&db.polyptr[0] = db.ot[0] | 0x09000000;
	db.ot[0] = (unsigned long)&db.polyptr[0];

	db.polyptr += 0x28; //sizeof(POLY_F3); * 2?

	*(long*)&db.polyptr[4] = 0x2C808080;
	*(long*)&db.polyptr[8] = 0x780100;
	*(long*)&db.polyptr[12] = 0x6800;
	*(long*)&db.polyptr[16] = 0x7801FF;

	*(long*)&db.polyptr[20] = 0x13468FF;
	*(long*)&db.polyptr[24] = 0xEF0100;
	*(short*)&db.polyptr[28] = 0xDF00;
	*(long*)&db.polyptr[32] = 0xEF01FF;

	*(short*)&db.polyptr[36] = 0xDFFF;

	*(long*)&db.polyptr[0] = db.ot[0] | 0x9000000;
	db.ot[0] = (unsigned long)db.polyptr;
	//sizeof(POLY_G3);
	db.polyptr += 0x28;
	return;
}

/*   PSX VRAM   (H)
 *  ----------- 1024px
 *  | TL | TR |  |
 *  -----------  v
 *  | BL | BR |
 *  -----------
 *(W)1024px-->
 *
 */
void GPU_ClearVRAM() //5F2D0(<), 5FFB0(<) (F) (D) (ND)
{
	RECT16 r;

	//Clear TL
	r.x = 0;
	r.y = 0;
	r.w = 512;
	r.h = 256;
	clear_a_rect(&r);

	//Clear BL
	r.y = 256;
	clear_a_rect(&r);

	//Clear BR
	r.x = 512;
	clear_a_rect(&r);

	//Clear TR
	r.y = 0;
	clear_a_rect(&r);

	return;
}

void clear_a_rect(RECT16* r) //5F334(<), 60014(<) (F) (D) (ND)
{
	ClearImage(r, 0, 48, 0);
	return;
}

void GPU_GetScreenPosition(short* x, short* y) //5F34C, ? (*) (F) (D) (ND)
{
	*x = db.disp[0].screen.x;
	*y = db.disp[0].screen.y;
	return;
}

void GPU_SetScreenPosition(short x, short y) //5F360(<), 60040(<)
{
	db.disp[0].screen.x = x;
	db.disp[0].screen.y = y;
	db.disp[1].screen.x = x;
	db.disp[1].screen.y = y;

	return;
}

void GPU_SyncBothScreens() //5F374(<), 60054(<)
{
	DrawSync(0);
	db.current_buffer ^= 1;
	if (db.current_buffer != 0)
	{
		MoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y);
	}
	else
	{
		//loc_5F3A8
		MoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y);
	}

	DrawSync(0);

	return;
}

///@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code.
void GPU_FlipToBuffer(int buffer_index) //5F3C8(<), 600A8(<) (F) (D) (ND)
{
	DrawSync(0);
	VSync(0);

	if (buffer_index & 1)
	{
		PutDispEnv(&db.disp[1]);
	}
	else
	{
		PutDispEnv(&db.disp[0]);
	}

	if (buffer_index & 1)
	{
		PutDrawEnv(&db.draw[1]);
	}
	else
	{
		PutDrawEnv(&db.draw[0]);
	}

	db.current_buffer = buffer_index & 1 ^ 1;

	return;
}

void frig_with_monitor_screen(int a0)
{
	UNIMPLEMENTED();
}

void S_AnimateTextures(long nFrames)
{
	AnimComp += nFrames;

	while (AnimComp > 5)
	{
		uint16_t* ptr = AnimTextureRanges;

		for (uint16_t i = *(ptr++); i > 0; i--, ptr++)
		{
			MMTEXTURE tmp = RoomTextInfo[*(ptr + 1)];

			for (uint16_t j = *ptr++; j > 0; j--, ptr++)
			{
				RoomTextInfo[*ptr] = RoomTextInfo[*(ptr + 1)];
			}

			RoomTextInfo[*ptr] = tmp;
		}

		AnimComp -= 5;
	}

	if (gfUVRotate) // 19d8
	{
		uint16_t* t3 = AnimTextureRanges;
		AnimatingTexturesVOffset = (AnimatingTexturesVOffset - gfUVRotate * (nFrames / 2)) & 0x1f;
		if (nAnimUVRanges > 0)
		{
			short (*t2)[8][3] = AnimatingTexturesV;

			for (int i = 0; i < nAnimUVRanges; i++, t2++)
			{
				unsigned short num = *t3++;
				if (num > 0)
				{
					short* t1 = t2[i][num];

					for (int j = 0; j <= num; j++, t1-=3, t3++)
					{
						int t0 = 32;
						int a2 = AnimatingTexturesVOffset;
						MMTEXTURE* a0tm = &RoomTextInfo[*t3];
						for (int a3 = 0; a3 < 3; a3++, a2 >>= 1, t0 >>= 1)
						{
							uint8_t v0__ = (uint8_t)(t1[a3] >> 8);

							a0tm->t[a3].v0 = v0__ + a2;

							a0tm->t[a3].v1 = v0__ + a2;

							a0tm->t[a3].v2 = v0__ + a2 + t0;

							a0tm->t[a3].v3 = v0__ + a2 + t0;
						}
					}
				}
			}
		}
	}

	frig_with_monitor_screen(0);
}

void PrintGauge(int x, int y, int length)
{
	UNIMPLEMENTED();
}

long GetRandomControl() //5E9F0, 926F8 (F)
{
	rand_1 = (rand_1 * 0x41C64E6D) + 0x3039;
	return (rand_1 >> 16) & 0x7FFF;
}

void SeedRandomControl(long seed) //(F)
{
	rand_1 = seed;
}

long GetRandomDraw() //5EA18, 5F6F8 (F)
{
	rand_2 = (rand_2 * 0x41C64E6D) + 0x3039;
	return (rand_2 >> 16) * 0x7FFF;
}

void SeedRandomDraw(long seed) //(F)
{
	rand_2 = seed;
}

void S_MemCpy(char* pSrc, char* pDest, int size)
{
	if (size > 0)
	{
		while (size-- > 0)
			*pSrc++ = *pDest++;
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "shell/browser/native_browser_view_views.h"

#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/background.h"
#include "ui/views/view.h"

namespace electron {

NativeBrowserViewViews::NativeBrowserViewViews(
    InspectableWebContents* inspectable_web_contents)
    : NativeBrowserView(inspectable_web_contents) {}

NativeBrowserViewViews::~NativeBrowserViewViews() = default;

void NativeBrowserViewViews::SetAutoResizeFlags(uint8_t flags) {
  auto_resize_flags_ = flags;
  ResetAutoResizeProportions();
}

void NativeBrowserViewViews::SetAutoResizeProportions(
    const gfx::Size& window_size) {
  if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) &&
      !auto_horizontal_proportion_set_) {
    auto* iwc_view = GetInspectableWebContentsView();
    if (iwc_view)
      return;
    auto* view = iwc_view->GetView();
    auto view_bounds = view->bounds();
    auto_horizontal_proportion_width_ =
        static_cast<float>(window_size.width()) /
        static_cast<float>(view_bounds.width());
    auto_horizontal_proportion_left_ = static_cast<float>(window_size.width()) /
                                       static_cast<float>(view_bounds.x());
    auto_horizontal_proportion_set_ = true;
  }
  if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) &&
      !auto_vertical_proportion_set_) {
    auto* iwc_view = GetInspectableWebContentsView();
    if (iwc_view)
      return;
    auto* view = iwc_view->GetView();
    auto view_bounds = view->bounds();
    auto_vertical_proportion_height_ =
        static_cast<float>(window_size.height()) /
        static_cast<float>(view_bounds.height());
    auto_vertical_proportion_top_ = static_cast<float>(window_size.height()) /
                                    static_cast<float>(view_bounds.y());
    auto_vertical_proportion_set_ = true;
  }
}

void NativeBrowserViewViews::AutoResize(const gfx::Rect& new_window,
                                        int width_delta,
                                        int height_delta) {
  auto* iwc_view = GetInspectableWebContentsView();
  if (iwc_view)
    return;
  auto* view = iwc_view->GetView();
  const auto flags = GetAutoResizeFlags();
  if (!(flags & kAutoResizeWidth)) {
    width_delta = 0;
  }
  if (!(flags & kAutoResizeHeight)) {
    height_delta = 0;
  }
  if (height_delta || width_delta) {
    auto new_view_size = view->size();
    new_view_size.set_width(new_view_size.width() + width_delta);
    new_view_size.set_height(new_view_size.height() + height_delta);
    view->SetSize(new_view_size);
  }
  auto new_view_bounds = view->bounds();
  if (flags & kAutoResizeHorizontal) {
    new_view_bounds.set_width(new_window.width() /
                              auto_horizontal_proportion_width_);
    new_view_bounds.set_x(new_window.width() /
                          auto_horizontal_proportion_left_);
  }
  if (flags & kAutoResizeVertical) {
    new_view_bounds.set_height(new_window.height() /
                               auto_vertical_proportion_height_);
    new_view_bounds.set_y(new_window.height() / auto_vertical_proportion_top_);
  }
  if ((flags & kAutoResizeHorizontal) || (flags & kAutoResizeVertical)) {
    view->SetBoundsRect(new_view_bounds);
  }
}

void NativeBrowserViewViews::ResetAutoResizeProportions() {
  if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) {
    auto_horizontal_proportion_set_ = false;
  }
  if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) {
    auto_vertical_proportion_set_ = false;
  }
}

void NativeBrowserViewViews::SetBounds(const gfx::Rect& bounds) {
  auto* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return;
  auto* view = iwc_view->GetView();
  view->SetBoundsRect(bounds);
  ResetAutoResizeProportions();
}

gfx::Rect NativeBrowserViewViews::GetBounds() {
  auto* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return gfx::Rect();
  return iwc_view->GetView()->bounds();
}

void NativeBrowserViewViews::SetBackgroundColor(SkColor color) {
  auto* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return;
  auto* view = iwc_view->GetView();
  view->SetBackground(views::CreateSolidBackground(color));
  view->SchedulePaint();
}

// static
NativeBrowserView* NativeBrowserView::Create(
    InspectableWebContents* inspectable_web_contents) {
  return new NativeBrowserViewViews(inspectable_web_contents);
}

}  // namespace electron
<commit_msg>fix: correct null pointer checks in autoresizing browser views (#25951)<commit_after>// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "shell/browser/native_browser_view_views.h"

#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/background.h"
#include "ui/views/view.h"

namespace electron {

NativeBrowserViewViews::NativeBrowserViewViews(
    InspectableWebContents* inspectable_web_contents)
    : NativeBrowserView(inspectable_web_contents) {}

NativeBrowserViewViews::~NativeBrowserViewViews() = default;

void NativeBrowserViewViews::SetAutoResizeFlags(uint8_t flags) {
  auto_resize_flags_ = flags;
  ResetAutoResizeProportions();
}

void NativeBrowserViewViews::SetAutoResizeProportions(
    const gfx::Size& window_size) {
  if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) &&
      !auto_horizontal_proportion_set_) {
    auto* iwc_view = GetInspectableWebContentsView();
    if (!iwc_view)
      return;
    auto* view = iwc_view->GetView();
    auto view_bounds = view->bounds();
    auto_horizontal_proportion_width_ =
        static_cast<float>(window_size.width()) /
        static_cast<float>(view_bounds.width());
    auto_horizontal_proportion_left_ = static_cast<float>(window_size.width()) /
                                       static_cast<float>(view_bounds.x());
    auto_horizontal_proportion_set_ = true;
  }
  if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) &&
      !auto_vertical_proportion_set_) {
    auto* iwc_view = GetInspectableWebContentsView();
    if (!iwc_view)
      return;
    auto* view = iwc_view->GetView();
    auto view_bounds = view->bounds();
    auto_vertical_proportion_height_ =
        static_cast<float>(window_size.height()) /
        static_cast<float>(view_bounds.height());
    auto_vertical_proportion_top_ = static_cast<float>(window_size.height()) /
                                    static_cast<float>(view_bounds.y());
    auto_vertical_proportion_set_ = true;
  }
}

void NativeBrowserViewViews::AutoResize(const gfx::Rect& new_window,
                                        int width_delta,
                                        int height_delta) {
  auto* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return;
  auto* view = iwc_view->GetView();
  const auto flags = GetAutoResizeFlags();
  if (!(flags & kAutoResizeWidth)) {
    width_delta = 0;
  }
  if (!(flags & kAutoResizeHeight)) {
    height_delta = 0;
  }
  if (height_delta || width_delta) {
    auto new_view_size = view->size();
    new_view_size.set_width(new_view_size.width() + width_delta);
    new_view_size.set_height(new_view_size.height() + height_delta);
    view->SetSize(new_view_size);
  }
  auto new_view_bounds = view->bounds();
  if (flags & kAutoResizeHorizontal) {
    new_view_bounds.set_width(new_window.width() /
                              auto_horizontal_proportion_width_);
    new_view_bounds.set_x(new_window.width() /
                          auto_horizontal_proportion_left_);
  }
  if (flags & kAutoResizeVertical) {
    new_view_bounds.set_height(new_window.height() /
                               auto_vertical_proportion_height_);
    new_view_bounds.set_y(new_window.height() / auto_vertical_proportion_top_);
  }
  if ((flags & kAutoResizeHorizontal) || (flags & kAutoResizeVertical)) {
    view->SetBoundsRect(new_view_bounds);
  }
}

void NativeBrowserViewViews::ResetAutoResizeProportions() {
  if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) {
    auto_horizontal_proportion_set_ = false;
  }
  if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) {
    auto_vertical_proportion_set_ = false;
  }
}

void NativeBrowserViewViews::SetBounds(const gfx::Rect& bounds) {
  auto* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return;
  auto* view = iwc_view->GetView();
  view->SetBoundsRect(bounds);
  ResetAutoResizeProportions();
}

gfx::Rect NativeBrowserViewViews::GetBounds() {
  auto* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return gfx::Rect();
  return iwc_view->GetView()->bounds();
}

void NativeBrowserViewViews::SetBackgroundColor(SkColor color) {
  auto* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return;
  auto* view = iwc_view->GetView();
  view->SetBackground(views::CreateSolidBackground(color));
  view->SchedulePaint();
}

// static
NativeBrowserView* NativeBrowserView::Create(
    InspectableWebContents* inspectable_web_contents) {
  return new NativeBrowserViewViews(inspectable_web_contents);
}

}  // namespace electron
<|endoftext|>


<commit_before>/**
 * This file defines the core graph analysis algorithm.
 */

#ifndef D2_ANALYSIS_HPP
#define D2_ANALYSIS_HPP

#include <d2/detail/all_cycles.hpp>

#include <boost/foreach.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/properties.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>

namespace d2 {
namespace detail {

/**
 * Return whether two unordered containers have a non-empty intersection.
 */
template <typename Unordered1, typename Unordered2>
bool unordered_intersects(Unordered1 const& a, Unordered2 const& b) {
    typedef typename Unordered1::const_iterator Iterator;
    typename Unordered2::const_iterator not_found(boost::end(b));
    Iterator elem(boost::begin(a)), last(boost::end(a));
    for (; elem != last; ++elem)
        if (b.find(*elem) == not_found)
            return false;
    return true;
}

/**
 * Wrap a `BinaryFunction` to implement a visitor for the goodlock algorithm.
 *
 * @internal If we use an adjacency_matrix to store the segmentation graph, we
 *           should compute its transitive closure to reduce the complexity of
 *           the happens-before relation.
 */
template <typename LockGraph, typename SegmentationGraph, typename Function>
class CycleVisitor {
    typedef boost::graph_traits<LockGraph> GraphTraits;
    typedef typename GraphTraits::edge_descriptor LockGraphEdgeDescriptor;

    // Property map to access the edge labels of the lock graph.
    typedef typename boost::property_map<
                LockGraph, boost::edge_bundle_t
            >::const_type EdgeLabelMap;

    SegmentationGraph const& sg_;
    Function f_;

public:
    CycleVisitor(SegmentationGraph const& sg, Function const& f)
        : sg_(sg), f_(f)
    { }

    /**
     * Method called whenever a cycle is found.
     *
     * If the cycle respects certain conditions, calls the wrapped
     * `BinaryFunction` with a sequence of unspecified type containing the
     * edges in the cycle and a constant reference to the lock graph.
     *
     * @note The conditions are those that make a cycle a potential deadlock
     *       in the lock graph.
     */
    template <typename EdgePath>
    void cycle(EdgePath const& edge_path, LockGraph const& graph) const {
        // These are the conditions for a cycle to be a valid
        // potential deadlock:

        // For any given pair of edges (e1, e2)
        EdgeLabelMap labels = get(boost::edge_bundle, graph);
        BOOST_FOREACH(LockGraphEdgeDescriptor e1, edge_path) {
            BOOST_FOREACH(LockGraphEdgeDescriptor e2, edge_path) {
                if (e1 == e2) continue;
                else if (!(

                    // The threads must differ.
                    labels[e1].t != labels[e2].t &&

                    // The guard sets must not overlap.
                    !unordered_intersects(labels[e1].g, labels[e2].g) &&

                    // The segments must not be ordered.
                    !happens_before(labels[e1].s2, labels[e2].s1, sg_)

                )) return;
            }
        }

        f_(edge_path, graph);
    }
};

} // end namespace detail

/**
 * Analyze the lock graph and the segmentation graph to determine whether the
 * program execution represented by them contains a deadlock. `f` is called
 * whenever a potential deadlock is detected.
 *
 * @see `detail::CycleVisitor` for more details.
 */
template <typename LockGraph, typename SegmentationGraph, typename Function>
void analyze(LockGraph const& lg, SegmentationGraph const& sg,
             Function const& f) {
    detail::CycleVisitor<LockGraph, SegmentationGraph, Function> vis(sg, f);
    detail::all_cycles(lg, vis);
}

} // end namespace d2

#endif // !D2_ANALYSIS_HPP
<commit_msg>Strip constness of a functor in the analysis to allow for non-const wrapped functors.<commit_after>/**
 * This file defines the core graph analysis algorithm.
 */

#ifndef D2_ANALYSIS_HPP
#define D2_ANALYSIS_HPP

#include <d2/detail/all_cycles.hpp>

#include <boost/foreach.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/properties.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>

namespace d2 {
namespace detail {

/**
 * Return whether two unordered containers have a non-empty intersection.
 */
template <typename Unordered1, typename Unordered2>
bool unordered_intersects(Unordered1 const& a, Unordered2 const& b) {
    typedef typename Unordered1::const_iterator Iterator;
    typename Unordered2::const_iterator not_found(boost::end(b));
    Iterator elem(boost::begin(a)), last(boost::end(a));
    for (; elem != last; ++elem)
        if (b.find(*elem) == not_found)
            return false;
    return true;
}

/**
 * Wrap a `BinaryFunction` to implement a visitor for the goodlock algorithm.
 *
 * @internal If we use an adjacency_matrix to store the segmentation graph, we
 *           should compute its transitive closure to reduce the complexity of
 *           the happens-before relation.
 */
template <typename LockGraph, typename SegmentationGraph, typename Function>
class CycleVisitor {
    typedef boost::graph_traits<LockGraph> GraphTraits;
    typedef typename GraphTraits::edge_descriptor LockGraphEdgeDescriptor;

    // Property map to access the edge labels of the lock graph.
    typedef typename boost::property_map<
                LockGraph, boost::edge_bundle_t
            >::const_type EdgeLabelMap;

    SegmentationGraph const& sg_;
    Function f_;

public:
    CycleVisitor(SegmentationGraph const& sg, Function const& f)
        : sg_(sg), f_(f)
    { }

    /**
     * Method called whenever a cycle is found.
     *
     * If the cycle respects certain conditions, calls the wrapped
     * `BinaryFunction` with a sequence of unspecified type containing the
     * edges in the cycle and a constant reference to the lock graph.
     *
     * @note The conditions are those that make a cycle a potential deadlock
     *       in the lock graph.
     * @internal This must not be const in order to allow non-const functors
     *           to be called.
     */
    template <typename EdgePath>
    void cycle(EdgePath const& edge_path, LockGraph const& graph) {
        // These are the conditions for a cycle to be a valid
        // potential deadlock:

        // For any given pair of edges (e1, e2)
        EdgeLabelMap labels = get(boost::edge_bundle, graph);
        BOOST_FOREACH(LockGraphEdgeDescriptor e1, edge_path) {
            BOOST_FOREACH(LockGraphEdgeDescriptor e2, edge_path) {
                if (e1 == e2) continue;
                else if (!(

                    // The threads must differ.
                    labels[e1].t != labels[e2].t &&

                    // The guard sets must not overlap.
                    !unordered_intersects(labels[e1].g, labels[e2].g) &&

                    // The segments must not be ordered.
                    !happens_before(labels[e1].s2, labels[e2].s1, sg_)

                )) return;
            }
        }

        f_(edge_path, graph);
    }
};

} // end namespace detail

/**
 * Analyze the lock graph and the segmentation graph to determine whether the
 * program execution represented by them contains a deadlock. `f` is called
 * whenever a potential deadlock is detected.
 *
 * @see `detail::CycleVisitor` for more details.
 */
template <typename LockGraph, typename SegmentationGraph, typename Function>
void analyze(LockGraph const& lg, SegmentationGraph const& sg,
             Function const& f) {
    detail::CycleVisitor<LockGraph, SegmentationGraph, Function> vis(sg, f);
    detail::all_cycles(lg, vis);
}

} // end namespace d2

#endif // !D2_ANALYSIS_HPP
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include "surfaceextraction.h"

#include <inviwo/core/properties/propertysemantics.h>
#include <modules/base/algorithm/volume/marchingtetrahedron.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <numeric>

#define TETRA 1

namespace inviwo {

ProcessorClassIdentifier(SurfaceExtraction, "org.inviwo.SurfaceExtraction");
ProcessorDisplayName(SurfaceExtraction, "Surface Extraction");
ProcessorTags(SurfaceExtraction, Tags::CPU);
ProcessorCategory(SurfaceExtraction, "Geometry Creation");
ProcessorCodeState(SurfaceExtraction, CODE_STATE_EXPERIMENTAL);

// TODO make changing color not rerun extraction but only change the color, (and run only
// extraction when volume change or iso change)

SurfaceExtraction::SurfaceExtraction()
    : Processor()
    , volume_("volume")
    , outport_("mesh")
    , isoValue_("iso", "ISO Value", 0.5f, 0.0f, 1.0f, 0.01f)
    , method_("method", "Method")
    , colors_("meshColors", "Mesh Colors")
    , dirty_(false) {

    addPort(volume_);
    addPort(outport_);

    addProperty(method_);
    addProperty(isoValue_);
    addProperty(colors_);

    getProgressBar().hide();

    method_.addOption("marchingtetrahedra", "Marching Tetrahedra", TETRA);
    volume_.onChange(this, &SurfaceExtraction::updateColors);
    volume_.onChange(this, &SurfaceExtraction::setMinMax);
    method_.setCurrentStateAsDefault();
}

SurfaceExtraction::~SurfaceExtraction() {}

void SurfaceExtraction::process() {
    if (!meshes_) {
        meshes_ = std::make_shared<std::vector<std::shared_ptr<Mesh>>>();
        outport_.setData(meshes_);
    }

    auto data = volume_.getSourceVectorData();
    auto changed = volume_.getChangedOutports();
    result_.resize(data.size());
    meshes_->resize(data.size());

    for (size_t i = 0; i < data.size(); ++i) {
        const VolumeRAM* vol = data[i].second->getRepresentation<VolumeRAM>();

        switch (method_.get()) {
            case TETRA: {
                if (result_[i].result.valid() &&
                    result_[i].result.wait_for(std::chrono::duration<int, std::milli>(0)) ==
                        std::future_status::ready) {
                    (*meshes_)[i] = std::move(result_[i].result.get());
                    result_[i].status = 1.0f;
                    dirty_ = false;
                }

                float iso = isoValue_.get();
                vec4 color = static_cast<FloatVec4Property*>(colors_[i])->get();
                if (!result_[i].result.valid() && (util::contains(changed, data[i].first) ||
                                            result_[i].iso != iso || result_[i].color != color)) {
                    result_[i].iso = iso;
                    result_[i].color = color;
                    result_[i].status = 0.0f;
                    result_[i].result =
                        dispatchPool([this, vol, iso, color, i]() -> std::shared_ptr<Mesh> {
                            auto m = std::shared_ptr<Mesh>(
                                MarchingTetrahedron::apply(vol, iso, color, [this, i](float s) {
                                    this->result_[i].status = s;
                                    float status = 0;
                                    for (const auto& e : this->result_) status += e.status;
                                    status /= result_.size();
                                    dispatchFront([status](ProgressBar& pb) {
                                        pb.updateProgress(status);
                                        if (status < 1.0f) pb.show();
                                        else pb.hide();
                                    }, std::ref(this->getProgressBar()));

                                }));

                            dispatchFront([this]() {
                                dirty_=true;
                                invalidate(INVALID_OUTPUT);
                            });

                            return std::move(m);
                        });
                }
                break;
            }
            default:
                break;
        }
    }
}

void SurfaceExtraction::setMinMax() {
    if (volume_.hasData()) {
        auto minmax = std::make_pair(std::numeric_limits<double>::max(),
                                     std::numeric_limits<double>::lowest());
        minmax = std::accumulate(volume_.begin(), volume_.end(), minmax,
                        [](decltype(minmax) mm, std::shared_ptr<const Volume> v) {
            return std::make_pair(std::min(mm.first, v->dataMap_.dataRange.x),
                                  std::max(mm.second, v->dataMap_.dataRange.y));
        });

        isoValue_.setMinValue(static_cast<const float>(minmax.first));
        isoValue_.setMaxValue(static_cast<const float>(minmax.second));
    }
}

void SurfaceExtraction::updateColors() {
    const static vec4 defaultColor[11] = {vec4(1.0f),
                                          vec4(0x1f, 0x77, 0xb4, 255) / vec4(255, 255, 255, 255),
                                          vec4(0xff, 0x7f, 0x0e, 255) / vec4(255, 255, 255, 255),
                                          vec4(0x2c, 0xa0, 0x2c, 255) / vec4(255, 255, 255, 255),
                                          vec4(0xd6, 0x27, 0x28, 255) / vec4(255, 255, 255, 255),
                                          vec4(0x94, 0x67, 0xbd, 255) / vec4(255, 255, 255, 255),
                                          vec4(0x8c, 0x56, 0x4b, 255) / vec4(255, 255, 255, 255),
                                          vec4(0xe3, 0x77, 0xc2, 255) / vec4(255, 255, 255, 255),
                                          vec4(0x7f, 0x7f, 0x7f, 255) / vec4(255, 255, 255, 255),
                                          vec4(0xbc, 0xbd, 0x22, 255) / vec4(255, 255, 255, 255),
                                          vec4(0x17, 0xbe, 0xcf, 255) / vec4(255, 255, 255, 255)};

    size_t count = 0;
    for (const auto& data : volume_) {
        count++;
        if (colors_.size() < count) {
            const static std::string color = "color";
            const static std::string dispName = "Color for Volume ";
            FloatVec4Property* colorProp = new FloatVec4Property(
                color + toString(count-1), dispName + toString(count), defaultColor[(count-1) % 11]);
            colorProp->setCurrentStateAsDefault();
            colorProp->setSemantics(PropertySemantics::Color);
            colorProp->setSerializationMode(PropertySerializationMode::ALL);
            colors_.addProperty(colorProp);
        }
        colors_[count-1]->setVisible(true);
    }

    for (size_t i = count; i < colors_.size(); i++) {
        colors_[i]->setVisible(false);
    }
}

// This will stop the invalidation of the network unless the dirty flag is set.
void SurfaceExtraction::invalidate(InvalidationLevel invalidationLevel,
                                   Property* modifiedProperty) {

    notifyObserversInvalidationBegin(this);
    PropertyOwner::invalidate(invalidationLevel, modifiedProperty);

    if (dirty_ || volume_.isChanged()) outport_.invalidate(INVALID_OUTPUT);

    notifyObserversInvalidationEnd(this);
}

SurfaceExtraction::task::task(task&& rhs)
    : result(std::move(rhs.result))
    , iso(rhs.iso)
    , color(std::move(rhs.color))
    , status(rhs.status) {
}

SurfaceExtraction::task& SurfaceExtraction::task::operator=(task&& that) {
    if (this != &that) {
        result = std::move(that.result);
        iso = that.iso;
        color = std::move(that.color);
        status = that.status;
    }

    return *this;
}

}  // namespace
<commit_msg>Base: SurfaceExtraction minor update<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include "surfaceextraction.h"

#include <inviwo/core/properties/propertysemantics.h>
#include <modules/base/algorithm/volume/marchingtetrahedron.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/util/stdextensions.h>
#include <numeric>

#define TETRA 1

namespace inviwo {

ProcessorClassIdentifier(SurfaceExtraction, "org.inviwo.SurfaceExtraction");
ProcessorDisplayName(SurfaceExtraction, "Surface Extraction");
ProcessorTags(SurfaceExtraction, Tags::CPU);
ProcessorCategory(SurfaceExtraction, "Geometry Creation");
ProcessorCodeState(SurfaceExtraction, CODE_STATE_EXPERIMENTAL);

// TODO make changing color not rerun extraction but only change the color, (and run only
// extraction when volume change or iso change)

SurfaceExtraction::SurfaceExtraction()
    : Processor()
    , volume_("volume")
    , outport_("mesh")
    , isoValue_("iso", "ISO Value", 0.5f, 0.0f, 1.0f, 0.01f)
    , method_("method", "Method")
    , colors_("meshColors", "Mesh Colors")
    , dirty_(false) {

    addPort(volume_);
    addPort(outport_);

    addProperty(method_);
    addProperty(isoValue_);
    addProperty(colors_);

    getProgressBar().hide();

    method_.addOption("marchingtetrahedra", "Marching Tetrahedra", TETRA);
    volume_.onChange(this, &SurfaceExtraction::updateColors);
    volume_.onChange(this, &SurfaceExtraction::setMinMax);
    method_.setCurrentStateAsDefault();
}

SurfaceExtraction::~SurfaceExtraction() {}

void SurfaceExtraction::process() {
    if (!meshes_) {
        meshes_ = std::make_shared<std::vector<std::shared_ptr<Mesh>>>();
        outport_.setData(meshes_);
    }

    auto data = volume_.getSourceVectorData();
    auto changed = volume_.getChangedOutports();
    result_.resize(data.size());
    meshes_->resize(data.size());

    for (size_t i = 0; i < data.size(); ++i) {
        const VolumeRAM* vol = data[i].second->getRepresentation<VolumeRAM>();

        switch (method_.get()) {
            case TETRA: {
                if (util::is_future_ready(result_[i].result)) {
                    (*meshes_)[i] = std::move(result_[i].result.get());
                    result_[i].status = 1.0f;
                    dirty_ = false;
                }

                float iso = isoValue_.get();
                vec4 color = static_cast<FloatVec4Property*>(colors_[i])->get();
                if (!result_[i].result.valid() && (util::contains(changed, data[i].first) ||
                                            result_[i].iso != iso || result_[i].color != color)) {
                    result_[i].iso = iso;
                    result_[i].color = color;
                    result_[i].status = 0.0f;
                    result_[i].result =
                        dispatchPool([this, vol, iso, color, i]() -> std::shared_ptr<Mesh> {
                            auto m = std::shared_ptr<Mesh>(
                                MarchingTetrahedron::apply(vol, iso, color, [this, i](float s) {
                                    this->result_[i].status = s;
                                    float status = 0;
                                    for (const auto& e : this->result_) status += e.status;
                                    status /= result_.size();
                                    dispatchFront([status](ProgressBar& pb) {
                                        pb.updateProgress(status);
                                        if (status < 1.0f) pb.show();
                                        else pb.hide();
                                    }, std::ref(this->getProgressBar()));
                                }));

                            dispatchFront([this]() {
                                dirty_=true;
                                invalidate(INVALID_OUTPUT);
                            });

                            return std::move(m);
                        });
                }
                break;
            }
            default:
                break;
        }
    }
}

void SurfaceExtraction::setMinMax() {
    if (volume_.hasData()) {
        auto minmax = std::make_pair(std::numeric_limits<double>::max(),
                                     std::numeric_limits<double>::lowest());
        minmax = std::accumulate(volume_.begin(), volume_.end(), minmax,
                        [](decltype(minmax) mm, std::shared_ptr<const Volume> v) {
            return std::make_pair(std::min(mm.first, v->dataMap_.dataRange.x),
                                  std::max(mm.second, v->dataMap_.dataRange.y));
        });

        isoValue_.setMinValue(static_cast<const float>(minmax.first));
        isoValue_.setMaxValue(static_cast<const float>(minmax.second));
    }
}

void SurfaceExtraction::updateColors() {
    const static vec4 defaultColor[11] = {vec4(1.0f),
                                          vec4(0x1f, 0x77, 0xb4, 255) / vec4(255, 255, 255, 255),
                                          vec4(0xff, 0x7f, 0x0e, 255) / vec4(255, 255, 255, 255),
                                          vec4(0x2c, 0xa0, 0x2c, 255) / vec4(255, 255, 255, 255),
                                          vec4(0xd6, 0x27, 0x28, 255) / vec4(255, 255, 255, 255),
                                          vec4(0x94, 0x67, 0xbd, 255) / vec4(255, 255, 255, 255),
                                          vec4(0x8c, 0x56, 0x4b, 255) / vec4(255, 255, 255, 255),
                                          vec4(0xe3, 0x77, 0xc2, 255) / vec4(255, 255, 255, 255),
                                          vec4(0x7f, 0x7f, 0x7f, 255) / vec4(255, 255, 255, 255),
                                          vec4(0xbc, 0xbd, 0x22, 255) / vec4(255, 255, 255, 255),
                                          vec4(0x17, 0xbe, 0xcf, 255) / vec4(255, 255, 255, 255)};

    size_t count = 0;
    for (const auto& data : volume_) {
        count++;
        if (colors_.size() < count) {
            const static std::string color = "color";
            const static std::string dispName = "Color for Volume ";
            FloatVec4Property* colorProp = new FloatVec4Property(
                color + toString(count-1), dispName + toString(count), defaultColor[(count-1) % 11]);
            colorProp->setCurrentStateAsDefault();
            colorProp->setSemantics(PropertySemantics::Color);
            colorProp->setSerializationMode(PropertySerializationMode::ALL);
            colors_.addProperty(colorProp);
        }
        colors_[count-1]->setVisible(true);
    }

    for (size_t i = count; i < colors_.size(); i++) {
        colors_[i]->setVisible(false);
    }
}

// This will stop the invalidation of the network unless the dirty flag is set.
void SurfaceExtraction::invalidate(InvalidationLevel invalidationLevel,
                                   Property* modifiedProperty) {

    notifyObserversInvalidationBegin(this);
    PropertyOwner::invalidate(invalidationLevel, modifiedProperty);

    if (dirty_ || volume_.isChanged()) outport_.invalidate(INVALID_OUTPUT);

    notifyObserversInvalidationEnd(this);
}

SurfaceExtraction::task::task(task&& rhs)
    : result(std::move(rhs.result))
    , iso(rhs.iso)
    , color(std::move(rhs.color))
    , status(rhs.status) {
}

SurfaceExtraction::task& SurfaceExtraction::task::operator=(task&& that) {
    if (this != &that) {
        result = std::move(that.result);
        iso = that.iso;
        color = std::move(that.color);
        status = that.status;
    }

    return *this;
}

}  // namespace
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef ETL_FAST_OP_HPP
#define ETL_FAST_OP_HPP

#include <random>
#include <functional>
#include <ctime>

#include "math.hpp"

namespace etl {

template<typename T>
struct scalar {
    const T value;

    explicit constexpr scalar(T v) : value(v) {}

    constexpr const T operator[](std::size_t) const {
        return value;
    }

    constexpr const T operator()(std::size_t) const {
        return value;
    }

    constexpr const T operator()(std::size_t, std::size_t) const {
        return value;
    }
};

template<typename T>
struct hflip_transformer {
    using sub_type = T;

    const T& sub;

    explicit hflip_transformer(const T& vec) : sub(vec) {}

    typename T::value_type operator[](std::size_t i) const {
        return sub[size(sub) - 1 - i];
    }

    typename T::value_type operator()(std::size_t i) const {
        return sub(size(sub) - 1 - i);
    }

    typename T::value_type operator()(std::size_t i, std::size_t j) const {
        return sub(i, columns(sub) - 1 - j);
    }
};

template<typename T>
struct vflip_transformer {
    using sub_type = T;

    const T& sub;

    explicit vflip_transformer(const T& vec) : sub(vec) {}

    typename T::value_type operator[](std::size_t i) const {
        return sub[i];
    }

    typename T::value_type operator()(std::size_t i) const {
        return sub(i);
    }

    typename T::value_type operator()(std::size_t i, std::size_t j) const {
        return sub(rows(sub) - 1 - i, j);
    }
};

template<typename T>
struct fflip_transformer {
    using sub_type = T;

    const T& sub;

    explicit fflip_transformer(const T& vec) : sub(vec) {}

    typename T::value_type operator[](std::size_t i) const {
        return sub[i];
    }

    typename T::value_type operator()(std::size_t i) const {
        return sub(i);
    }

    typename T::value_type operator()(std::size_t i, std::size_t j) const {
        return sub(rows(sub) - 1 - i, columns(sub) - 1 - j);
    }
};

template<typename T>
struct transpose_transformer {
    using sub_type = T;

    const T& sub;

    explicit transpose_transformer(const T& vec) : sub(vec) {}

    typename T::value_type operator[](std::size_t i) const {
        return sub[i];
    }

    typename T::value_type operator()(std::size_t i) const {
        return sub(i);
    }

    typename T::value_type operator()(std::size_t i, std::size_t j) const {
        return sub(j, i);
    }
};

template<typename T, std::size_t D>
struct dim_view {
    static_assert(D > 0 || D < 3, "Invalid dimension");

    using sub_type = T;

    const T& sub;
    const std::size_t i;

    dim_view(const T& vec, std::size_t i) : sub(vec), i(i) {}

    typename T::value_type operator[](std::size_t j) const {
        if(D == 1){
            return sub(i, j);
        } else if(D == 2){
            return sub(j, i);
        }
    }

    typename T::value_type operator()(std::size_t j) const {
        if(D == 1){
            return sub(i, j);
        } else if(D == 2){
            return sub(j, i);
        }
    }
};

template<typename T>
struct sub_view {
    using parent_type = T;

    const T& parent;
    const std::size_t i;

    sub_view(const T& parent, std::size_t i) : parent(parent), i(i) {}

    typename T::value_type operator[](std::size_t j) const {
        return parent[i * subsize(parent) + j];
    }

    template<typename... S>
    typename T::value_type operator()(S... args) const {
        return parent(i, static_cast<size_t>(args)...);
    }
};

template<typename T, std::size_t Rows, std::size_t Columns>
struct fast_matrix_view {
    static_assert(Rows > 0 && Columns > 0 , "Invalid dimensions");

    using value_type = typename T::value_type;

    const T& sub;

    explicit fast_matrix_view(const T& sub) : sub(sub) {}

    value_type operator[](std::size_t j) const {
        return sub(j);
    }

    value_type operator()(std::size_t j) const {
        return sub(j);
    }

    value_type operator()(std::size_t i, std::size_t j) const {
        return sub(i * Columns + j);
    }
};

template<typename T>
struct dyn_matrix_view {
    using value_type = typename T::value_type;

    const T& sub;
    std::size_t rows;
    std::size_t columns;

    dyn_matrix_view(const T& sub, std::size_t rows, std::size_t columns) : sub(sub), rows(rows), columns(columns) {}

    value_type operator[](std::size_t j) const {
        return sub(j);
    }

    value_type operator()(std::size_t j) const {
        return sub(j);
    }

    value_type operator()(std::size_t i, std::size_t j) const {
        return sub(i * columns + j);
    }
};

template<typename T>
struct plus_binary_op {
    static constexpr T apply(const T& lhs, const T& rhs){
        return lhs + rhs;
    }
};

template<typename T>
struct minus_binary_op {
    static constexpr T apply(const T& lhs, const T& rhs){
        return lhs - rhs;
    }
};

template<typename T>
struct mul_binary_op {
    static constexpr T apply(const T& lhs, const T& rhs){
        return lhs * rhs;
    }
};

template<typename T>
struct div_binary_op {
    static constexpr T apply(const T& lhs, const T& rhs){
        return lhs / rhs;
    }
};

template<typename T>
struct mod_binary_op {
    static constexpr T apply(const T& lhs, const T& rhs){
        return lhs % rhs;
    }
};

template<typename T>
struct abs_unary_op {
    static constexpr T apply(const T& x){
        return std::abs(x);
    }
};

template<typename T>
struct log_unary_op {
    static constexpr T apply(const T& x){
        return std::log(x);
    }
};

template<typename T>
struct exp_unary_op {
    static constexpr T apply(const T& x){
        return std::exp(x);
    }
};

template<typename T>
struct sign_unary_op {
    static constexpr T apply(const T& x){
        return sign(x);
    }
};

template<typename T>
struct sigmoid_unary_op {
    static constexpr T apply(const T& x){
        return logistic_sigmoid(x);
    }
};

template<typename T>
struct softplus_unary_op {
    static constexpr T apply(const T& x){
        return softplus(x);
    }
};

template<typename T>
struct minus_unary_op {
    static constexpr T apply(const T& x){
        return -x;
    }
};

template<typename T>
struct plus_unary_op {
    static constexpr T apply(const T& x){
        return +x;
    }
};

template<typename T>
struct identity_unary_op {
    static constexpr T apply(const T& x){
        return x;
    }
};

template<typename T>
struct bernoulli_unary_op {
    static T apply(const T& x){
        static std::default_random_engine rand_engine(std::time(nullptr));
        static std::uniform_real_distribution<double> normal_distribution(0.0, 1.0);
        static auto normal_generator = std::bind(normal_distribution, rand_engine);

        return x > normal_generator() ? 1.0 : 0.0;
    }
};

template<typename T>
struct uniform_noise_unary_op {
    static T apply(const T& x){
        static std::default_random_engine rand_engine(std::time(nullptr));
        static std::uniform_real_distribution<double> real_distribution(0.0, 1.0);
        static auto noise = std::bind(real_distribution, rand_engine);

        return x + noise();
    }
};

template<typename T>
struct normal_noise_unary_op {
    static T apply(const T& x){
        static std::default_random_engine rand_engine(std::time(nullptr));
        static std::normal_distribution<double> normal_distribution(0.0, 1.0);
        static auto noise = std::bind(normal_distribution, rand_engine);

        return x + noise();
    }
};

template<typename T>
struct logistic_noise_unary_op {
    static T apply(const T& x){
        static std::default_random_engine rand_engine(std::time(nullptr));

        std::normal_distribution<double> noise_distribution(0.0, logistic_sigmoid(x));
        auto noise = std::bind(noise_distribution, rand_engine);

        return x + noise();
    }
};

template<typename T, typename E>
struct ranged_noise_binary_op {
    static T apply(const T& x, E value){
        static std::default_random_engine rand_engine(std::time(nullptr));
        static std::normal_distribution<double> normal_distribution(0.0, 1.0);
        static auto noise = std::bind(normal_distribution, rand_engine);

        if(x == 0.0 || x == value){
            return x;
        } else {
            return x + noise();
        }
    }
};

template<typename T, typename E>
struct max_binary_op {
    static constexpr T apply(const T& x, E value){
        return std::max(x, value);
    }
};

template<typename T, typename E>
struct min_binary_op {
    static constexpr T apply(const T& x, E value){
        return std::min(x, value);
    }
};

} //end of namespace etl

#endif
<commit_msg>Use Mersenne Twister method<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef ETL_FAST_OP_HPP
#define ETL_FAST_OP_HPP

#include <random>
#include <functional>
#include <ctime>

#include "math.hpp"

namespace etl {

using random_engine = std::mt19937_64;

template<typename T>
struct scalar {
    const T value;

    explicit constexpr scalar(T v) : value(v) {}

    constexpr const T operator[](std::size_t) const {
        return value;
    }

    constexpr const T operator()(std::size_t) const {
        return value;
    }

    constexpr const T operator()(std::size_t, std::size_t) const {
        return value;
    }
};

template<typename T>
struct hflip_transformer {
    using sub_type = T;

    const T& sub;

    explicit hflip_transformer(const T& vec) : sub(vec) {}

    typename T::value_type operator[](std::size_t i) const {
        return sub[size(sub) - 1 - i];
    }

    typename T::value_type operator()(std::size_t i) const {
        return sub(size(sub) - 1 - i);
    }

    typename T::value_type operator()(std::size_t i, std::size_t j) const {
        return sub(i, columns(sub) - 1 - j);
    }
};

template<typename T>
struct vflip_transformer {
    using sub_type = T;

    const T& sub;

    explicit vflip_transformer(const T& vec) : sub(vec) {}

    typename T::value_type operator[](std::size_t i) const {
        return sub[i];
    }

    typename T::value_type operator()(std::size_t i) const {
        return sub(i);
    }

    typename T::value_type operator()(std::size_t i, std::size_t j) const {
        return sub(rows(sub) - 1 - i, j);
    }
};

template<typename T>
struct fflip_transformer {
    using sub_type = T;

    const T& sub;

    explicit fflip_transformer(const T& vec) : sub(vec) {}

    typename T::value_type operator[](std::size_t i) const {
        return sub[i];
    }

    typename T::value_type operator()(std::size_t i) const {
        return sub(i);
    }

    typename T::value_type operator()(std::size_t i, std::size_t j) const {
        return sub(rows(sub) - 1 - i, columns(sub) - 1 - j);
    }
};

template<typename T>
struct transpose_transformer {
    using sub_type = T;

    const T& sub;

    explicit transpose_transformer(const T& vec) : sub(vec) {}

    typename T::value_type operator[](std::size_t i) const {
        return sub[i];
    }

    typename T::value_type operator()(std::size_t i) const {
        return sub(i);
    }

    typename T::value_type operator()(std::size_t i, std::size_t j) const {
        return sub(j, i);
    }
};

template<typename T, std::size_t D>
struct dim_view {
    static_assert(D > 0 || D < 3, "Invalid dimension");

    using sub_type = T;

    const T& sub;
    const std::size_t i;

    dim_view(const T& vec, std::size_t i) : sub(vec), i(i) {}

    typename T::value_type operator[](std::size_t j) const {
        if(D == 1){
            return sub(i, j);
        } else if(D == 2){
            return sub(j, i);
        }
    }

    typename T::value_type operator()(std::size_t j) const {
        if(D == 1){
            return sub(i, j);
        } else if(D == 2){
            return sub(j, i);
        }
    }
};

template<typename T>
struct sub_view {
    using parent_type = T;

    const T& parent;
    const std::size_t i;

    sub_view(const T& parent, std::size_t i) : parent(parent), i(i) {}

    typename T::value_type operator[](std::size_t j) const {
        return parent[i * subsize(parent) + j];
    }

    template<typename... S>
    typename T::value_type operator()(S... args) const {
        return parent(i, static_cast<size_t>(args)...);
    }
};

template<typename T, std::size_t Rows, std::size_t Columns>
struct fast_matrix_view {
    static_assert(Rows > 0 && Columns > 0 , "Invalid dimensions");

    using value_type = typename T::value_type;

    const T& sub;

    explicit fast_matrix_view(const T& sub) : sub(sub) {}

    value_type operator[](std::size_t j) const {
        return sub(j);
    }

    value_type operator()(std::size_t j) const {
        return sub(j);
    }

    value_type operator()(std::size_t i, std::size_t j) const {
        return sub(i * Columns + j);
    }
};

template<typename T>
struct dyn_matrix_view {
    using value_type = typename T::value_type;

    const T& sub;
    std::size_t rows;
    std::size_t columns;

    dyn_matrix_view(const T& sub, std::size_t rows, std::size_t columns) : sub(sub), rows(rows), columns(columns) {}

    value_type operator[](std::size_t j) const {
        return sub(j);
    }

    value_type operator()(std::size_t j) const {
        return sub(j);
    }

    value_type operator()(std::size_t i, std::size_t j) const {
        return sub(i * columns + j);
    }
};

template<typename T>
struct plus_binary_op {
    static constexpr T apply(const T& lhs, const T& rhs){
        return lhs + rhs;
    }
};

template<typename T>
struct minus_binary_op {
    static constexpr T apply(const T& lhs, const T& rhs){
        return lhs - rhs;
    }
};

template<typename T>
struct mul_binary_op {
    static constexpr T apply(const T& lhs, const T& rhs){
        return lhs * rhs;
    }
};

template<typename T>
struct div_binary_op {
    static constexpr T apply(const T& lhs, const T& rhs){
        return lhs / rhs;
    }
};

template<typename T>
struct mod_binary_op {
    static constexpr T apply(const T& lhs, const T& rhs){
        return lhs % rhs;
    }
};

template<typename T>
struct abs_unary_op {
    static constexpr T apply(const T& x){
        return std::abs(x);
    }
};

template<typename T>
struct log_unary_op {
    static constexpr T apply(const T& x){
        return std::log(x);
    }
};

template<typename T>
struct exp_unary_op {
    static constexpr T apply(const T& x){
        return std::exp(x);
    }
};

template<typename T>
struct sign_unary_op {
    static constexpr T apply(const T& x){
        return sign(x);
    }
};

template<typename T>
struct sigmoid_unary_op {
    static constexpr T apply(const T& x){
        return logistic_sigmoid(x);
    }
};

template<typename T>
struct softplus_unary_op {
    static constexpr T apply(const T& x){
        return softplus(x);
    }
};

template<typename T>
struct minus_unary_op {
    static constexpr T apply(const T& x){
        return -x;
    }
};

template<typename T>
struct plus_unary_op {
    static constexpr T apply(const T& x){
        return +x;
    }
};

template<typename T>
struct identity_unary_op {
    static constexpr T apply(const T& x){
        return x;
    }
};

template<typename T>
struct bernoulli_unary_op {
    static T apply(const T& x){
        static random_engine rand_engine(std::time(nullptr));
        static std::uniform_real_distribution<double> normal_distribution(0.0, 1.0);
        static auto normal_generator = std::bind(normal_distribution, rand_engine);

        return x > normal_generator() ? 1.0 : 0.0;
    }
};

template<typename T>
struct uniform_noise_unary_op {
    static T apply(const T& x){
        static random_engine rand_engine(std::time(nullptr));
        static std::uniform_real_distribution<double> real_distribution(0.0, 1.0);
        static auto noise = std::bind(real_distribution, rand_engine);

        return x + noise();
    }
};

template<typename T>
struct normal_noise_unary_op {
    static T apply(const T& x){
        static random_engine rand_engine(std::time(nullptr));
        static std::normal_distribution<double> normal_distribution(0.0, 1.0);
        static auto noise = std::bind(normal_distribution, rand_engine);

        return x + noise();
    }
};

template<typename T>
struct logistic_noise_unary_op {
    static T apply(const T& x){
        static random_engine rand_engine(std::time(nullptr));

        std::normal_distribution<double> noise_distribution(0.0, logistic_sigmoid(x));
        auto noise = std::bind(noise_distribution, rand_engine);

        return x + noise();
    }
};

template<typename T, typename E>
struct ranged_noise_binary_op {
    static T apply(const T& x, E value){
        static random_engine rand_engine(std::time(nullptr));
        static std::normal_distribution<double> normal_distribution(0.0, 1.0);
        static auto noise = std::bind(normal_distribution, rand_engine);

        if(x == 0.0 || x == value){
            return x;
        } else {
            return x + noise();
        }
    }
};

template<typename T, typename E>
struct max_binary_op {
    static constexpr T apply(const T& x, E value){
        return std::max(x, value);
    }
};

template<typename T, typename E>
struct min_binary_op {
    static constexpr T apply(const T& x, E value){
        return std::min(x, value);
    }
};

} //end of namespace etl

#endif
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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.
 *****************************************************************************/

#include "modules/common/monitor/monitor_buffer.h"

#include <string>
#include "gtest/gtest.h"
#include "modules/common/monitor/monitor.h"

namespace apollo {
namespace common {
namespace monitor {

class MonitorBufferTest : public ::testing::Test {
 protected:
  void SetUp() override { buffer_ = new MonitorBuffer(nullptr); }
  void TearDown() override { delete buffer_; }
  MonitorBuffer *buffer_ = nullptr;
};

TEST_F(MonitorBufferTest, PrintLog) {
  FLAGS_logtostderr = true;
  FLAGS_v = 4;
  {
    testing::internal::CaptureStderr();
    buffer_->PrintLog();
    EXPECT_TRUE(testing::internal::GetCapturedStderr().empty());
  }
  {
    buffer_->INFO("INFO_msg");
    testing::internal::CaptureStderr();
    buffer_->PrintLog();
    EXPECT_NE(std::string::npos,
              testing::internal::GetCapturedStderr().find("INFO_msg"));
  }
  {
    buffer_->ERROR("ERROR_msg");
    testing::internal::CaptureStderr();
    buffer_->PrintLog();
    EXPECT_NE(std::string::npos,
              testing::internal::GetCapturedStderr().find("ERROR_msg"));
  }
  {
    buffer_->WARN("WARN_msg");
    testing::internal::CaptureStderr();
    buffer_->PrintLog();
    EXPECT_NE(std::string::npos,
              testing::internal::GetCapturedStderr().find("WARN_msg"));
  }
  {
    buffer_->FATAL("FATAL_msg");
    EXPECT_DEATH(buffer_->PrintLog(), "");
  }
}

TEST_F(MonitorBufferTest, RegisterMacro) {
  {
    buffer_->INFO("Info");
    EXPECT_EQ(MonitorMessageItem::INFO, buffer_->level_);
    ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
    const auto &item = buffer_->monitor_msg_items_.back();
    EXPECT_EQ(MonitorMessageItem::INFO, item.first);
    EXPECT_EQ("Info", item.second);
  }

  {
    buffer_->ERROR("Error");
    EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
    ASSERT_EQ(2, buffer_->monitor_msg_items_.size());
    const auto &item = buffer_->monitor_msg_items_.back();
    EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
    EXPECT_EQ("Error", item.second);
  }
}

TEST_F(MonitorBufferTest, AddMonitorMsgItem) {
  buffer_->AddMonitorMsgItem(MonitorMessageItem::ERROR, "TestError");
  EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
  ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
  const auto &item = buffer_->monitor_msg_items_.back();
  EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
  EXPECT_EQ("TestError", item.second);
}

TEST_F(MonitorBufferTest, Operator) {
  buffer_->ERROR() << "Hi";
  EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
  ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
  auto &item = buffer_->monitor_msg_items_.back();
  EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
  EXPECT_EQ("Hi", item.second);
  (*buffer_) << " How"
             << " are"
             << " you";
  EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
  ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
  EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
  EXPECT_EQ("Hi How are you", item.second);

  buffer_->INFO() << 3 << "pieces";
  EXPECT_EQ(MonitorMessageItem::INFO, buffer_->level_);
  ASSERT_EQ(2, buffer_->monitor_msg_items_.size());
  item = buffer_->monitor_msg_items_.back();
  EXPECT_EQ(MonitorMessageItem::INFO, item.first);
  EXPECT_EQ("3pieces", item.second);

  const char *fake_input = nullptr;
  EXPECT_TRUE(&(buffer_->INFO() << fake_input) == buffer_);
}

}  // namespace monitor
}  // namespace common
}  // namespace apollo
<commit_msg>security: fix security report problem.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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.
 *****************************************************************************/

#include "modules/common/monitor/monitor_buffer.h"

#include <string>
#include "gtest/gtest.h"
#include "modules/common/monitor/monitor.h"

namespace apollo {
namespace common {
namespace monitor {

class MonitorBufferTest : public ::testing::Test {
 protected:
  void SetUp() override { buffer_ = new MonitorBuffer(nullptr); }
  void TearDown() override { delete buffer_; }
  MonitorBuffer *buffer_ = nullptr;
};

TEST_F(MonitorBufferTest, PrintLog) {
  FLAGS_logtostderr = true;
  FLAGS_v = 4;
  {
    testing::internal::CaptureStderr();
    buffer_->PrintLog();
    EXPECT_TRUE(testing::internal::GetCapturedStderr().empty());
  }
  {
    buffer_->INFO("INFO_msg");
    testing::internal::CaptureStderr();
    buffer_->PrintLog();
    EXPECT_NE(std::string::npos,
              testing::internal::GetCapturedStderr().find("INFO_msg"));
  }
  {
    buffer_->ERROR("ERROR_msg");
    testing::internal::CaptureStderr();
    buffer_->PrintLog();
    EXPECT_NE(std::string::npos,
              testing::internal::GetCapturedStderr().find("ERROR_msg"));
  }
  {
    buffer_->WARN("WARN_msg");
    testing::internal::CaptureStderr();
    buffer_->PrintLog();
    EXPECT_NE(std::string::npos,
              testing::internal::GetCapturedStderr().find("WARN_msg"));
  }
  {
    buffer_->FATAL("FATAL_msg");
    EXPECT_DEATH(buffer_->PrintLog(), "");
  }
}

TEST_F(MonitorBufferTest, RegisterMacro) {
  {
    buffer_->INFO("Info");
    EXPECT_EQ(MonitorMessageItem::INFO, buffer_->level_);
    ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
    const auto &item = buffer_->monitor_msg_items_.back();
    EXPECT_EQ(MonitorMessageItem::INFO, item.first);
    EXPECT_EQ("Info", item.second);
  }

  {
    buffer_->ERROR("Error");
    EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
    ASSERT_EQ(2, buffer_->monitor_msg_items_.size());
    const auto &item = buffer_->monitor_msg_items_.back();
    EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
    EXPECT_EQ("Error", item.second);
  }
}

TEST_F(MonitorBufferTest, AddMonitorMsgItem) {
  buffer_->AddMonitorMsgItem(MonitorMessageItem::ERROR, "TestError");
  EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
  ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
  const auto &item = buffer_->monitor_msg_items_.back();
  EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
  EXPECT_EQ("TestError", item.second);
}

TEST_F(MonitorBufferTest, Operator) {
  buffer_->ERROR() << "Hi";
  EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
  ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
  auto &item = buffer_->monitor_msg_items_.back();
  EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
  EXPECT_EQ("Hi", item.second);
  (*buffer_) << " How"
             << " are"
             << " you";
  EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
  ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
  EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
  EXPECT_EQ("Hi How are you", item.second);

  buffer_->INFO() << 3 << "pieces";
  EXPECT_EQ(MonitorMessageItem::INFO, buffer_->level_);
  ASSERT_EQ(2, buffer_->monitor_msg_items_.size());
  auto item2 = buffer_->monitor_msg_items_.back();
  EXPECT_EQ(MonitorMessageItem::INFO, item2.first);
  EXPECT_EQ("3pieces", item2.second);

  const char *fake_input = nullptr;
  EXPECT_TRUE(&(buffer_->INFO() << fake_input) == buffer_);
}

}  // namespace monitor
}  // namespace common
}  // namespace apollo
<|endoftext|>


<commit_before>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

#ifndef OPENCV_VERSION_HPP
#define OPENCV_VERSION_HPP

#define CV_VERSION_MAJOR    4
#define CV_VERSION_MINOR    4
#define CV_VERSION_REVISION 0
#define CV_VERSION_STATUS   "-pre"

#define CVAUX_STR_EXP(__A)  #__A
#define CVAUX_STR(__A)      CVAUX_STR_EXP(__A)

#define CVAUX_STRW_EXP(__A)  L ## #__A
#define CVAUX_STRW(__A)      CVAUX_STRW_EXP(__A)

#define CV_VERSION          CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION) CV_VERSION_STATUS

/* old  style version constants*/
#define CV_MAJOR_VERSION    CV_VERSION_MAJOR
#define CV_MINOR_VERSION    CV_VERSION_MINOR
#define CV_SUBMINOR_VERSION CV_VERSION_REVISION

#endif // OPENCV_VERSION_HPP
<commit_msg>release: OpenCV 4.4.0<commit_after>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

#ifndef OPENCV_VERSION_HPP
#define OPENCV_VERSION_HPP

#define CV_VERSION_MAJOR    4
#define CV_VERSION_MINOR    4
#define CV_VERSION_REVISION 0
#define CV_VERSION_STATUS   ""

#define CVAUX_STR_EXP(__A)  #__A
#define CVAUX_STR(__A)      CVAUX_STR_EXP(__A)

#define CVAUX_STRW_EXP(__A)  L ## #__A
#define CVAUX_STRW(__A)      CVAUX_STRW_EXP(__A)

#define CV_VERSION          CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION) CV_VERSION_STATUS

/* old  style version constants*/
#define CV_MAJOR_VERSION    CV_VERSION_MAJOR
#define CV_MINOR_VERSION    CV_VERSION_MINOR
#define CV_SUBMINOR_VERSION CV_VERSION_REVISION

#endif // OPENCV_VERSION_HPP
<|endoftext|>