text
stringlengths 5
1.04M
|
|---|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "content/browser/browser_thread_impl.h"
#include "content/browser/speech/google_one_shot_remote_engine.h"
#include "content/browser/speech/speech_recognizer.h"
#include "content/public/browser/speech_recognition_event_listener.h"
#include "media/audio/mock_audio_manager.h"
#include "media/audio/fake_audio_input_stream.h"
#include "media/audio/fake_audio_output_stream.h"
#include "media/audio/test_audio_input_controller_factory.h"
#include "net/base/net_errors.h"
#include "net/url_request/test_url_fetcher_factory.h"
#include "net/url_request/url_request_status.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::MessageLoopProxy;
using media::AudioInputController;
using media::AudioInputStream;
using media::AudioManager;
using media::AudioOutputStream;
using media::AudioParameters;
using media::TestAudioInputController;
using media::TestAudioInputControllerFactory;
namespace content {
class SpeechRecognizerTest : public SpeechRecognitionEventListener,
public testing::Test {
public:
SpeechRecognizerTest()
: io_thread_(BrowserThread::IO, &message_loop_),
recognition_started_(false),
recognition_ended_(false),
result_received_(false),
audio_started_(false),
audio_ended_(false),
sound_started_(false),
sound_ended_(false),
error_(SPEECH_RECOGNITION_ERROR_NONE),
volume_(-1.0f) {
// SpeechRecognizer takes ownership of sr_engine.
SpeechRecognitionEngine* sr_engine =
new GoogleOneShotRemoteEngine(NULL /* URLRequestContextGetter */);
SpeechRecognitionEngineConfig config;
config.audio_num_bits_per_sample = SpeechRecognizer::kNumBitsPerAudioSample;
config.audio_sample_rate = SpeechRecognizer::kAudioSampleRate;
config.filter_profanities = false;
sr_engine->SetConfig(config);
const int kTestingSessionId = 1;
const bool kOneShotMode = true;
recognizer_ = new SpeechRecognizer(
this, kTestingSessionId, kOneShotMode, sr_engine);
audio_manager_.reset(new media::MockAudioManager(
MessageLoop::current()->message_loop_proxy()));
recognizer_->SetAudioManagerForTests(audio_manager_.get());
int audio_packet_length_bytes =
(SpeechRecognizer::kAudioSampleRate *
GoogleOneShotRemoteEngine::kAudioPacketIntervalMs *
ChannelLayoutToChannelCount(SpeechRecognizer::kChannelLayout) *
SpeechRecognizer::kNumBitsPerAudioSample) / (8 * 1000);
audio_packet_.resize(audio_packet_length_bytes);
}
void CheckEventsConsistency() {
// Note: "!x || y" == "x implies y".
EXPECT_TRUE(!recognition_ended_ || recognition_started_);
EXPECT_TRUE(!audio_ended_ || audio_started_);
EXPECT_TRUE(!sound_ended_ || sound_started_);
EXPECT_TRUE(!audio_started_ || recognition_started_);
EXPECT_TRUE(!sound_started_ || audio_started_);
EXPECT_TRUE(!audio_ended_ || (sound_ended_ || !sound_started_));
EXPECT_TRUE(!recognition_ended_ || (audio_ended_ || !audio_started_));
}
void CheckFinalEventsConsistency() {
// Note: "!(x ^ y)" == "(x && y) || (!x && !x)".
EXPECT_FALSE(recognition_started_ ^ recognition_ended_);
EXPECT_FALSE(audio_started_ ^ audio_ended_);
EXPECT_FALSE(sound_started_ ^ sound_ended_);
}
// Overridden from SpeechRecognitionEventListener:
virtual void OnAudioStart(int session_id) OVERRIDE {
audio_started_ = true;
CheckEventsConsistency();
}
virtual void OnAudioEnd(int session_id) OVERRIDE {
audio_ended_ = true;
CheckEventsConsistency();
}
virtual void OnRecognitionResults(
int session_id, const SpeechRecognitionResults& results) OVERRIDE {
result_received_ = true;
}
virtual void OnRecognitionError(
int session_id, const SpeechRecognitionError& error) OVERRIDE {
EXPECT_TRUE(recognition_started_);
EXPECT_FALSE(recognition_ended_);
error_ = error.code;
}
virtual void OnAudioLevelsChange(int session_id, float volume,
float noise_volume) OVERRIDE {
volume_ = volume;
noise_volume_ = noise_volume;
}
virtual void OnRecognitionEnd(int session_id) OVERRIDE {
recognition_ended_ = true;
CheckEventsConsistency();
}
virtual void OnRecognitionStart(int session_id) OVERRIDE {
recognition_started_ = true;
CheckEventsConsistency();
}
virtual void OnEnvironmentEstimationComplete(int session_id) OVERRIDE {}
virtual void OnSoundStart(int session_id) OVERRIDE {
sound_started_ = true;
CheckEventsConsistency();
}
virtual void OnSoundEnd(int session_id) OVERRIDE {
sound_ended_ = true;
CheckEventsConsistency();
}
// testing::Test methods.
virtual void SetUp() OVERRIDE {
AudioInputController::set_factory_for_testing(
&audio_input_controller_factory_);
}
virtual void TearDown() OVERRIDE {
AudioInputController::set_factory_for_testing(NULL);
}
void FillPacketWithTestWaveform() {
// Fill the input with a simple pattern, a 125Hz sawtooth waveform.
for (size_t i = 0; i < audio_packet_.size(); ++i)
audio_packet_[i] = static_cast<uint8>(i);
}
void FillPacketWithNoise() {
int value = 0;
int factor = 175;
for (size_t i = 0; i < audio_packet_.size(); ++i) {
value += factor;
audio_packet_[i] = value % 100;
}
}
protected:
MessageLoopForIO message_loop_;
BrowserThreadImpl io_thread_;
scoped_refptr<SpeechRecognizer> recognizer_;
scoped_ptr<AudioManager> audio_manager_;
bool recognition_started_;
bool recognition_ended_;
bool result_received_;
bool audio_started_;
bool audio_ended_;
bool sound_started_;
bool sound_ended_;
SpeechRecognitionErrorCode error_;
net::TestURLFetcherFactory url_fetcher_factory_;
TestAudioInputControllerFactory audio_input_controller_factory_;
std::vector<uint8> audio_packet_;
float volume_;
float noise_volume_;
};
TEST_F(SpeechRecognizerTest, StopNoData) {
// Check for callbacks when stopping record before any audio gets recorded.
recognizer_->StartRecognition();
recognizer_->StopAudioCapture();
MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(recognition_started_);
EXPECT_FALSE(audio_started_);
EXPECT_FALSE(result_received_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_NONE, error_);
CheckFinalEventsConsistency();
}
TEST_F(SpeechRecognizerTest, CancelNoData) {
// Check for callbacks when canceling recognition before any audio gets
// recorded.
recognizer_->StartRecognition();
recognizer_->AbortRecognition();
MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(recognition_started_);
EXPECT_FALSE(audio_started_);
EXPECT_FALSE(result_received_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_ABORTED, error_);
CheckFinalEventsConsistency();
}
TEST_F(SpeechRecognizerTest, StopWithData) {
// Start recording, give some data and then stop. This should wait for the
// network callback to arrive before completion.
recognizer_->StartRecognition();
MessageLoop::current()->RunUntilIdle();
TestAudioInputController* controller =
audio_input_controller_factory_.controller();
ASSERT_TRUE(controller);
// Try sending 5 chunks of mock audio data and verify that each of them
// resulted immediately in a packet sent out via the network. This verifies
// that we are streaming out encoded data as chunks without waiting for the
// full recording to complete.
const size_t kNumChunks = 5;
for (size_t i = 0; i < kNumChunks; ++i) {
controller->event_handler()->OnData(controller, &audio_packet_[0],
audio_packet_.size());
MessageLoop::current()->RunUntilIdle();
net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
ASSERT_TRUE(fetcher);
EXPECT_EQ(i + 1, fetcher->upload_chunks().size());
}
recognizer_->StopAudioCapture();
MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(audio_started_);
EXPECT_TRUE(audio_ended_);
EXPECT_FALSE(recognition_ended_);
EXPECT_FALSE(result_received_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_NONE, error_);
// Issue the network callback to complete the process.
net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
ASSERT_TRUE(fetcher);
fetcher->set_url(fetcher->GetOriginalURL());
net::URLRequestStatus status;
status.set_status(net::URLRequestStatus::SUCCESS);
fetcher->set_status(status);
fetcher->set_response_code(200);
fetcher->SetResponseString(
"{\"status\":0,\"hypotheses\":[{\"utterance\":\"123\"}]}");
fetcher->delegate()->OnURLFetchComplete(fetcher);
MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(recognition_ended_);
EXPECT_TRUE(result_received_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_NONE, error_);
CheckFinalEventsConsistency();
}
TEST_F(SpeechRecognizerTest, CancelWithData) {
// Start recording, give some data and then cancel.
recognizer_->StartRecognition();
MessageLoop::current()->RunUntilIdle();
TestAudioInputController* controller =
audio_input_controller_factory_.controller();
ASSERT_TRUE(controller);
controller->event_handler()->OnData(controller, &audio_packet_[0],
audio_packet_.size());
MessageLoop::current()->RunUntilIdle();
recognizer_->AbortRecognition();
MessageLoop::current()->RunUntilIdle();
ASSERT_TRUE(url_fetcher_factory_.GetFetcherByID(0));
EXPECT_TRUE(recognition_started_);
EXPECT_TRUE(audio_started_);
EXPECT_FALSE(result_received_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_ABORTED, error_);
CheckFinalEventsConsistency();
}
TEST_F(SpeechRecognizerTest, ConnectionError) {
// Start recording, give some data and then stop. Issue the network callback
// with a connection error and verify that the recognizer bubbles the error up
recognizer_->StartRecognition();
MessageLoop::current()->RunUntilIdle();
TestAudioInputController* controller =
audio_input_controller_factory_.controller();
ASSERT_TRUE(controller);
controller->event_handler()->OnData(controller, &audio_packet_[0],
audio_packet_.size());
MessageLoop::current()->RunUntilIdle();
net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
ASSERT_TRUE(fetcher);
recognizer_->StopAudioCapture();
MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(audio_started_);
EXPECT_TRUE(audio_ended_);
EXPECT_FALSE(recognition_ended_);
EXPECT_FALSE(result_received_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_NONE, error_);
// Issue the network callback to complete the process.
fetcher->set_url(fetcher->GetOriginalURL());
net::URLRequestStatus status;
status.set_status(net::URLRequestStatus::FAILED);
status.set_error(net::ERR_CONNECTION_REFUSED);
fetcher->set_status(status);
fetcher->set_response_code(0);
fetcher->SetResponseString("");
fetcher->delegate()->OnURLFetchComplete(fetcher);
MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(recognition_ended_);
EXPECT_FALSE(result_received_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_NETWORK, error_);
CheckFinalEventsConsistency();
}
TEST_F(SpeechRecognizerTest, ServerError) {
// Start recording, give some data and then stop. Issue the network callback
// with a 500 error and verify that the recognizer bubbles the error up
recognizer_->StartRecognition();
MessageLoop::current()->RunUntilIdle();
TestAudioInputController* controller =
audio_input_controller_factory_.controller();
ASSERT_TRUE(controller);
controller->event_handler()->OnData(controller, &audio_packet_[0],
audio_packet_.size());
MessageLoop::current()->RunUntilIdle();
net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
ASSERT_TRUE(fetcher);
recognizer_->StopAudioCapture();
MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(audio_started_);
EXPECT_TRUE(audio_ended_);
EXPECT_FALSE(recognition_ended_);
EXPECT_FALSE(result_received_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_NONE, error_);
// Issue the network callback to complete the process.
fetcher->set_url(fetcher->GetOriginalURL());
net::URLRequestStatus status;
status.set_status(net::URLRequestStatus::SUCCESS);
fetcher->set_status(status);
fetcher->set_response_code(500);
fetcher->SetResponseString("Internal Server Error");
fetcher->delegate()->OnURLFetchComplete(fetcher);
MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(recognition_ended_);
EXPECT_FALSE(result_received_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_NETWORK, error_);
CheckFinalEventsConsistency();
}
TEST_F(SpeechRecognizerTest, AudioControllerErrorNoData) {
// Check if things tear down properly if AudioInputController threw an error.
recognizer_->StartRecognition();
MessageLoop::current()->RunUntilIdle();
TestAudioInputController* controller =
audio_input_controller_factory_.controller();
ASSERT_TRUE(controller);
controller->event_handler()->OnError(controller, 0);
MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(recognition_started_);
EXPECT_FALSE(audio_started_);
EXPECT_FALSE(result_received_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_AUDIO, error_);
CheckFinalEventsConsistency();
}
TEST_F(SpeechRecognizerTest, AudioControllerErrorWithData) {
// Check if things tear down properly if AudioInputController threw an error
// after giving some audio data.
recognizer_->StartRecognition();
MessageLoop::current()->RunUntilIdle();
TestAudioInputController* controller =
audio_input_controller_factory_.controller();
ASSERT_TRUE(controller);
controller->event_handler()->OnData(controller, &audio_packet_[0],
audio_packet_.size());
controller->event_handler()->OnError(controller, 0);
MessageLoop::current()->RunUntilIdle();
ASSERT_TRUE(url_fetcher_factory_.GetFetcherByID(0));
EXPECT_TRUE(recognition_started_);
EXPECT_TRUE(audio_started_);
EXPECT_FALSE(result_received_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_AUDIO, error_);
CheckFinalEventsConsistency();
}
TEST_F(SpeechRecognizerTest, NoSpeechCallbackIssued) {
// Start recording and give a lot of packets with audio samples set to zero.
// This should trigger the no-speech detector and issue a callback.
recognizer_->StartRecognition();
MessageLoop::current()->RunUntilIdle();
TestAudioInputController* controller =
audio_input_controller_factory_.controller();
ASSERT_TRUE(controller);
int num_packets = (SpeechRecognizer::kNoSpeechTimeoutMs) /
GoogleOneShotRemoteEngine::kAudioPacketIntervalMs + 1;
// The vector is already filled with zero value samples on create.
for (int i = 0; i < num_packets; ++i) {
controller->event_handler()->OnData(controller, &audio_packet_[0],
audio_packet_.size());
}
MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(recognition_started_);
EXPECT_TRUE(audio_started_);
EXPECT_FALSE(result_received_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_NO_SPEECH, error_);
CheckFinalEventsConsistency();
}
TEST_F(SpeechRecognizerTest, NoSpeechCallbackNotIssued) {
// Start recording and give a lot of packets with audio samples set to zero
// and then some more with reasonably loud audio samples. This should be
// treated as normal speech input and the no-speech detector should not get
// triggered.
recognizer_->StartRecognition();
MessageLoop::current()->RunUntilIdle();
TestAudioInputController* controller =
audio_input_controller_factory_.controller();
ASSERT_TRUE(controller);
controller = audio_input_controller_factory_.controller();
ASSERT_TRUE(controller);
int num_packets = (SpeechRecognizer::kNoSpeechTimeoutMs) /
GoogleOneShotRemoteEngine::kAudioPacketIntervalMs;
// The vector is already filled with zero value samples on create.
for (int i = 0; i < num_packets / 2; ++i) {
controller->event_handler()->OnData(controller, &audio_packet_[0],
audio_packet_.size());
}
FillPacketWithTestWaveform();
for (int i = 0; i < num_packets / 2; ++i) {
controller->event_handler()->OnData(controller, &audio_packet_[0],
audio_packet_.size());
}
MessageLoop::current()->RunUntilIdle();
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_NONE, error_);
EXPECT_TRUE(audio_started_);
EXPECT_FALSE(audio_ended_);
EXPECT_FALSE(recognition_ended_);
recognizer_->AbortRecognition();
MessageLoop::current()->RunUntilIdle();
CheckFinalEventsConsistency();
}
TEST_F(SpeechRecognizerTest, SetInputVolumeCallback) {
// Start recording and give a lot of packets with audio samples set to zero
// and then some more with reasonably loud audio samples. Check that we don't
// get the callback during estimation phase, then get zero for the silence
// samples and proper volume for the loud audio.
recognizer_->StartRecognition();
MessageLoop::current()->RunUntilIdle();
TestAudioInputController* controller =
audio_input_controller_factory_.controller();
ASSERT_TRUE(controller);
controller = audio_input_controller_factory_.controller();
ASSERT_TRUE(controller);
// Feed some samples to begin with for the endpointer to do noise estimation.
int num_packets = SpeechRecognizer::kEndpointerEstimationTimeMs /
GoogleOneShotRemoteEngine::kAudioPacketIntervalMs;
FillPacketWithNoise();
for (int i = 0; i < num_packets; ++i) {
controller->event_handler()->OnData(controller, &audio_packet_[0],
audio_packet_.size());
}
MessageLoop::current()->RunUntilIdle();
EXPECT_EQ(-1.0f, volume_); // No audio volume set yet.
// The vector is already filled with zero value samples on create.
controller->event_handler()->OnData(controller, &audio_packet_[0],
audio_packet_.size());
MessageLoop::current()->RunUntilIdle();
EXPECT_FLOAT_EQ(0.74939233f, volume_);
FillPacketWithTestWaveform();
controller->event_handler()->OnData(controller, &audio_packet_[0],
audio_packet_.size());
MessageLoop::current()->RunUntilIdle();
EXPECT_FLOAT_EQ(0.89926866f, volume_);
EXPECT_FLOAT_EQ(0.75071919f, noise_volume_);
EXPECT_EQ(SPEECH_RECOGNITION_ERROR_NONE, error_);
EXPECT_FALSE(audio_ended_);
EXPECT_FALSE(recognition_ended_);
recognizer_->AbortRecognition();
MessageLoop::current()->RunUntilIdle();
CheckFinalEventsConsistency();
}
} // namespace content
|
/************************************************************************
NxN Matrix class
Copyright (C) 1998 Michael Garland. See "COPYING.txt" for details.
$Id: mixmops.cxx,v 1.7 1998/10/26 21:09:38 garland Exp $
************************************************************************/
#include "stdafx.h"
#pragma hdrstop
#include "MxMatrix.h"
// This section originally from Paul's matrix library.
#define SWAP(a, b, t) {t = a; a = b; b = t;}
#define A(i,j) mxm_ref(_a, i, j, N)
#define B(i,j) mxm_ref(_b, i, j, N)
// Solve nxn system Ax=b.
// Leaves solution x in b, and destroys original A and b vectors.
// Return value is determinant of A.
// If system is singular, returns 0 and leaves trash in b
//
// Uses Gaussian elimination with partial pivoting.
//
static
double internal_solve(double *_a, double *b, const int N)
{
int i, j=0, k;
double max, t, det, sum, pivot;
/*---------- forward elimination ----------*/
det = 1.0;
for (i=0; i<N; i++) { /* eliminate in column i */
max = -1.0;
for (k=i; k<N; k++) /* find pivot for column i */
if (_abs(A(k, i)) > max) {
max = _abs(A(k, i));
j = k;
}
if (max<=0.) return 0.0; /* if no nonzero pivot, PUNT */
if (j!=i) { /* swap rows i and j */
for (k=i; k<N; k++)
SWAP(A(i, k), A(j, k), t);
det = -det;
SWAP(b[i], b[j], t); /* swap elements of column vector */
}
pivot = A(i, i);
det *= pivot;
for (k=i+1; k<N; k++) /* only do elems to right of pivot */
A(i, k) /= pivot;
/* we know that A(i, i) will be set to 1, so don't bother to do it */
b[i] /= pivot;
for (j=i+1; j<N; j++) { /* eliminate in rows below i */
t = A(j, i); /* we're gonna zero this guy */
for (k=i+1; k<N; k++) /* subtract scaled row i from row j */
A(j, k) -= A(i, k)*t; /* (ignore k<=i, we know they're 0) */
b[j] -= b[i]*t;
}
}
/*---------- back substitution ----------*/
for (i=N-1; i>=0; i--) { /* solve for x[i] (put it in b[i]) */
sum = b[i];
for (k=i+1; k<N; k++) /* really A(i, k)*x[k] */
sum -= A(i, k)*b[k];
b[i] = sum;
}
return det;
}
// Returns determinant of a, and b=a inverse.
// If matrix is singular, returns 0 and leaves trash in b.
//
// Uses Gaussian elimination with partial pivoting.
//
static
double internal_invert(double *_a, double *_b, const int N)
{
unsigned int i, j=0, k;
double max, t, det, pivot;
/*---------- forward elimination ----------*/
for (i=0; i<(unsigned int)N; i++) /* put identity matrix in B */
for (j=0; j<(unsigned int)N; j++)
B(i, j) = (double)(i==j);
det = 1.0;
for (i=0; i<(unsigned int)N; i++) { /* eliminate in column i, below diag */
max = -1.;
for (k=i; k<(unsigned int)N; k++) /* find pivot for column i */
if (_abs(A(k, i)) > max) {
max = _abs(A(k, i));
j = k;
}
if (max<=0.) return 0.; /* if no nonzero pivot, PUNT */
if (j!=i) { /* swap rows i and j */
for (k=i; k<(unsigned int)N; k++)
SWAP(A(i, k), A(j, k), t);
for (k=0; k<(unsigned int)N; k++)
SWAP(B(i, k), B(j, k), t);
det = -det;
}
pivot = A(i, i);
det *= pivot;
for (k=i+1; k<(unsigned int)N; k++) /* only do elems to right of pivot */
A(i, k) /= pivot;
for (k=0; k<(unsigned int)N; k++)
B(i, k) /= pivot;
/* we know that A(i, i) will be set to 1, so don't bother to do it */
for (j=i+1; j<(unsigned int)N; j++) { /* eliminate in rows below i */
t = A(j, i); /* we're gonna zero this guy */
for (k=i+1; k<(unsigned int)N; k++) /* subtract scaled row i from row j */
A(j, k) -= A(i, k)*t; /* (ignore k<=i, we know they're 0) */
for (k=0; k<(unsigned int)N; k++)
B(j, k) -= B(i, k)*t;
}
}
/*---------- backward elimination ----------*/
for (i=N-1; i>0; i--) { /* eliminate in column i, above diag */
for (j=0; j<i; j++) { /* eliminate in rows above i */
t = A(j, i); /* we're gonna zero this guy */
for (k=0; k<(unsigned int)N; k++) /* subtract scaled row i from row j */
B(j, k) -= B(i, k)*t;
}
}
return det;
}
#undef A
#undef B
#undef SWAP
float mxm_invert(float *r, const float *a, const int N)
{
mxm_local_block(a2, double, N);
mxm_local_block(r2, double, N);
unsigned int i;
for(i=0; i<(unsigned int)N*N; i++) a2[i] = a[i];
float det = (float)internal_invert(a2, r2, N);
for(i=0; i<(unsigned int)N*N; i++) r[i] = (float)r2[i];
mxm_free_local(a2);
mxm_free_local(r2);
return det;
}
double mxm_invert(double *r, const double *a, const int N)
{
mxm_local_block(a2, double, N);
mxm_set(a2, a, N);
double det = internal_invert(a2, r, N);
mxm_free_local(a2);
return det;
}
double mxm_solve(double *x, const double *A, const double *b, const int N)
{
mxm_local_block(a2, double, N);
mxm_set(a2, A, N);
mxv_set(x, b, N);
double det = internal_solve(a2, x, N);
mxm_free_local(a2);
return det;
}
// Originally based on public domain code by <Ajay_Shah@rand.org>
// which can be found at http://lib.stat.cmu.edu/general/ajay
//
// The factorization is valid as long as the returned nullity == 0
// U contains the upper triangular factor itself.
//
int mxm_cholesky(double *U, const double *A, const int N)
{
double sum;
int nullity = 0;
mxm_set(U, 0.0, N);
for(int i=0; i<N; i++)
{
/* First compute U[i][i] */
sum = mxm_ref(A, i, i, N);
for(int j=0; j<=(i-1); j++)
sum -= mxm_ref(U, j, i, N) * mxm_ref(U, j, i, N);
if( sum > 0 )
{
mxm_ref(U, i, i, N) = _sqrt(sum);
/* Now find elements U[i][k], k > i. */
for(int k=(i+1); k<N; k++)
{
sum = mxm_ref(A, i, k, N);
for(int j=0; j<=(i-1); j++)
sum -= mxm_ref(U, j, i, N)*mxm_ref(U, j, k, N);
mxm_ref(U, i, k, N) = sum / mxm_ref(U, i, i, N);
}
}
else
{
for(int k=i; k<N; k++) mxm_ref(U, i, k, N) = 0.0;
nullity++;
}
}
return nullity;
}
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/installer/util/google_update_settings.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
namespace google_update {
std::string posix_guid;
}
// File name used in the user data dir to indicate consent.
static const char kConsentToSendStats[] = "Consent To Send Stats";
// static
bool GoogleUpdateSettings::GetCollectStatsConsent() {
bool forced_enable = CommandLine::ForCurrentProcess()->
HasSwitch(switches::kEnableCrashReporter);
FilePath consent_file;
PathService::Get(chrome::DIR_USER_DATA, &consent_file);
consent_file = consent_file.Append(kConsentToSendStats);
std::string tmp_guid;
bool consented = file_util::ReadFileToString(consent_file, &tmp_guid);
if (forced_enable || consented)
google_update::posix_guid.assign(tmp_guid);
return forced_enable || consented;
}
// static
bool GoogleUpdateSettings::SetCollectStatsConsent(bool consented) {
FilePath consent_dir;
PathService::Get(chrome::DIR_USER_DATA, &consent_dir);
if (!file_util::DirectoryExists(consent_dir))
return false;
FilePath consent_file = consent_dir.AppendASCII(kConsentToSendStats);
if (consented) {
if ((!file_util::PathExists(consent_file)) ||
(file_util::PathExists(consent_file) &&
!google_update::posix_guid.empty())) {
const char* c_str = google_update::posix_guid.c_str();
int size = google_update::posix_guid.size();
return file_util::WriteFile(consent_file, c_str, size) == size;
}
} else {
google_update::posix_guid.clear();
return file_util::Delete(consent_file, false);
}
return true;
}
bool GoogleUpdateSettings::SetMetricsId(const std::wstring& client_id) {
// Make sure that user has consented to send crashes.
FilePath consent_dir;
PathService::Get(chrome::DIR_USER_DATA, &consent_dir);
if (!file_util::DirectoryExists(consent_dir) ||
!GoogleUpdateSettings::GetCollectStatsConsent())
return false;
// Since user has consented, write the metrics id to the file.
google_update::posix_guid = WideToASCII(client_id);
return GoogleUpdateSettings::SetCollectStatsConsent(true);
}
|
/*
* Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/experiments/rate_control_settings.h"
#include <inttypes.h>
#include <stdio.h>
#include <string>
#include "absl/strings/match.h"
#include "api/transport/field_trial_based_config.h"
#include "rtc_base/logging.h"
#include "rtc_base/numerics/safe_conversions.h"
namespace webrtc {
namespace {
const int kDefaultAcceptedQueueMs = 250;
const int kDefaultMinPushbackTargetBitrateBps = 30000;
const char kVp8TrustedRateControllerFieldTrialName[] =
"WebRTC-LibvpxVp8TrustedRateController";
const char kVp9TrustedRateControllerFieldTrialName[] =
"WebRTC-LibvpxVp9TrustedRateController";
const char kUseBaseHeavyVp8Tl3RateAllocationFieldTrialName[] =
"WebRTC-UseBaseHeavyVP8TL3RateAllocation";
const char* kVideoHysteresisFieldTrialname =
"WebRTC-SimulcastUpswitchHysteresisPercent";
const char* kScreenshareHysteresisFieldTrialname =
"WebRTC-SimulcastScreenshareUpswitchHysteresisPercent";
bool IsEnabled(const WebRtcKeyValueConfig* const key_value_config,
absl::string_view key) {
return absl::StartsWith(key_value_config->Lookup(key), "Enabled");
}
void ParseHysteresisFactor(const WebRtcKeyValueConfig* const key_value_config,
absl::string_view key,
double* output_value) {
std::string group_name = key_value_config->Lookup(key);
int percent = 0;
if (!group_name.empty() && sscanf(group_name.c_str(), "%d", &percent) == 1 &&
percent >= 0) {
*output_value = 1.0 + (percent / 100.0);
}
}
} // namespace
constexpr char CongestionWindowConfig::kKey[];
std::unique_ptr<StructParametersParser> CongestionWindowConfig::Parser() {
return StructParametersParser::Create("QueueSize", &queue_size_ms, //
"MinBitrate", &min_bitrate_bps,
"InitWin", &initial_data_window,
"DropFrame", &drop_frame_only);
}
// static
CongestionWindowConfig CongestionWindowConfig::Parse(absl::string_view config) {
CongestionWindowConfig res;
res.Parser()->Parse(config);
return res;
}
constexpr char VideoRateControlConfig::kKey[];
std::unique_ptr<StructParametersParser> VideoRateControlConfig::Parser() {
// The empty comments ensures that each pair is on a separate line.
return StructParametersParser::Create(
"pacing_factor", &pacing_factor, //
"alr_probing", &alr_probing, //
"vp8_qp_max", &vp8_qp_max, //
"vp8_min_pixels", &vp8_min_pixels, //
"trust_vp8", &trust_vp8, //
"trust_vp9", &trust_vp9, //
"video_hysteresis", &video_hysteresis, //
"screenshare_hysteresis", &screenshare_hysteresis, //
"probe_max_allocation", &probe_max_allocation, //
"bitrate_adjuster", &bitrate_adjuster, //
"adjuster_use_headroom", &adjuster_use_headroom, //
"vp8_s0_boost", &vp8_s0_boost, //
"vp8_base_heavy_tl3_alloc", &vp8_base_heavy_tl3_alloc, //
"vp8_dynamic_rate", &vp8_dynamic_rate, //
"vp9_dynamic_rate", &vp9_dynamic_rate);
}
RateControlSettings::RateControlSettings(
const WebRtcKeyValueConfig* const key_value_config)
: congestion_window_config_(CongestionWindowConfig::Parse(
key_value_config->Lookup(CongestionWindowConfig::kKey))) {
video_config_.trust_vp8 =
IsEnabled(key_value_config, kVp8TrustedRateControllerFieldTrialName);
video_config_.trust_vp9 =
IsEnabled(key_value_config, kVp9TrustedRateControllerFieldTrialName);
video_config_.vp8_base_heavy_tl3_alloc = IsEnabled(
key_value_config, kUseBaseHeavyVp8Tl3RateAllocationFieldTrialName);
ParseHysteresisFactor(key_value_config, kVideoHysteresisFieldTrialname,
&video_config_.video_hysteresis);
ParseHysteresisFactor(key_value_config, kScreenshareHysteresisFieldTrialname,
&video_config_.screenshare_hysteresis);
video_config_.Parser()->Parse(
key_value_config->Lookup(VideoRateControlConfig::kKey));
}
RateControlSettings::~RateControlSettings() = default;
RateControlSettings::RateControlSettings(RateControlSettings&&) = default;
RateControlSettings RateControlSettings::ParseFromFieldTrials() {
FieldTrialBasedConfig field_trial_config;
return RateControlSettings(&field_trial_config);
}
RateControlSettings RateControlSettings::ParseFromKeyValueConfig(
const WebRtcKeyValueConfig* const key_value_config) {
FieldTrialBasedConfig field_trial_config;
return RateControlSettings(key_value_config ? key_value_config
: &field_trial_config);
}
bool RateControlSettings::UseCongestionWindow() const {
return static_cast<bool>(congestion_window_config_.queue_size_ms);
}
int64_t RateControlSettings::GetCongestionWindowAdditionalTimeMs() const {
return congestion_window_config_.queue_size_ms.value_or(
kDefaultAcceptedQueueMs);
}
bool RateControlSettings::UseCongestionWindowPushback() const {
return congestion_window_config_.queue_size_ms &&
congestion_window_config_.min_bitrate_bps;
}
bool RateControlSettings::UseCongestionWindowDropFrameOnly() const {
return congestion_window_config_.drop_frame_only;
}
uint32_t RateControlSettings::CongestionWindowMinPushbackTargetBitrateBps()
const {
return congestion_window_config_.min_bitrate_bps.value_or(
kDefaultMinPushbackTargetBitrateBps);
}
absl::optional<DataSize>
RateControlSettings::CongestionWindowInitialDataWindow() const {
return congestion_window_config_.initial_data_window;
}
absl::optional<double> RateControlSettings::GetPacingFactor() const {
return video_config_.pacing_factor;
}
bool RateControlSettings::UseAlrProbing() const {
return video_config_.alr_probing;
}
absl::optional<int> RateControlSettings::LibvpxVp8QpMax() const {
if (video_config_.vp8_qp_max &&
(*video_config_.vp8_qp_max < 0 || *video_config_.vp8_qp_max > 63)) {
RTC_LOG(LS_WARNING) << "Unsupported vp8_qp_max_ value, ignored.";
return absl::nullopt;
}
return video_config_.vp8_qp_max;
}
absl::optional<int> RateControlSettings::LibvpxVp8MinPixels() const {
if (video_config_.vp8_min_pixels && *video_config_.vp8_min_pixels < 1) {
return absl::nullopt;
}
return video_config_.vp8_min_pixels;
}
bool RateControlSettings::LibvpxVp8TrustedRateController() const {
return video_config_.trust_vp8;
}
bool RateControlSettings::Vp8BoostBaseLayerQuality() const {
return video_config_.vp8_s0_boost;
}
bool RateControlSettings::Vp8DynamicRateSettings() const {
return video_config_.vp8_dynamic_rate;
}
bool RateControlSettings::LibvpxVp9TrustedRateController() const {
return video_config_.trust_vp9;
}
bool RateControlSettings::Vp9DynamicRateSettings() const {
return video_config_.vp9_dynamic_rate;
}
double RateControlSettings::GetSimulcastHysteresisFactor(
VideoCodecMode mode) const {
if (mode == VideoCodecMode::kScreensharing) {
return video_config_.screenshare_hysteresis;
}
return video_config_.video_hysteresis;
}
double RateControlSettings::GetSimulcastHysteresisFactor(
VideoEncoderConfig::ContentType content_type) const {
if (content_type == VideoEncoderConfig::ContentType::kScreen) {
return video_config_.screenshare_hysteresis;
}
return video_config_.video_hysteresis;
}
bool RateControlSettings::Vp8BaseHeavyTl3RateAllocation() const {
return video_config_.vp8_base_heavy_tl3_alloc;
}
bool RateControlSettings::TriggerProbeOnMaxAllocatedBitrateChange() const {
return video_config_.probe_max_allocation;
}
bool RateControlSettings::UseEncoderBitrateAdjuster() const {
return video_config_.bitrate_adjuster;
}
bool RateControlSettings::BitrateAdjusterCanUseNetworkHeadroom() const {
return video_config_.adjuster_use_headroom;
}
} // namespace webrtc
|
#include "Sum.h"
/**
* Constructor.
* @param a The first value to add.
* @param b The second value to add.
*/
Sum::Sum(int a, int b) : value1(a), value2(b)
{
}
/**
* Destructor.
*/
Sum::~Sum()
{}
/**
* Getter for getting the value of the variable value1.
*/
int Sum::getValue1() {
return value1;
}
/**
* Getter for getting the value of the variable value2.
*/
int Sum::getValue2() {
return value2;
}
int Sum::calculate() {
int result = (getValue1() + getValue2());
return result;
}
|
#include "DictionaryBlockInputStreamBase.h"
namespace DB
{
DictionaryBlockInputStreamBase::DictionaryBlockInputStreamBase(size_t rows_count, UInt64 max_block_size)
: rows_count(rows_count), max_block_size(max_block_size)
{
}
Block DictionaryBlockInputStreamBase::readImpl()
{
if (next_row == rows_count)
return Block();
size_t block_size = std::min<size_t>(max_block_size, rows_count - next_row);
Block block = getBlock(next_row, block_size);
next_row += block_size;
return block;
}
Block DictionaryBlockInputStreamBase::getHeader() const
{
return getBlock(0, 0);
}
}
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include "base/macros.h"
#include "chrome/browser/ui/views/reader_mode/reader_mode_icon_view.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/interstitials/security_interstitial_page_test_utils.h"
#include "chrome/browser/ssl/security_state_tab_helper.h"
#include "chrome/browser/ui/page_action/page_action_icon_type.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/toolbar_button_provider.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/dom_distiller/content/browser/distillable_page_utils.h"
#include "components/dom_distiller/content/browser/test_distillability_observer.h"
#include "components/dom_distiller/core/distilled_page_prefs.h"
#include "components/dom_distiller/core/dom_distiller_features.h"
#include "components/dom_distiller/core/dom_distiller_switches.h"
#include "components/dom_distiller/core/pref_names.h"
#include "components/security_interstitials/content/security_interstitial_page.h"
#include "components/security_interstitials/content/security_interstitial_tab_helper.h"
#include "components/security_interstitials/core/controller_client.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/test_navigation_observer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/test/button_test_api.h"
namespace {
const char* kSimpleArticlePath = "/dom_distiller/simple_article.html";
const char* kNonArticlePath = "/dom_distiller/non_og_article.html";
const char* kArticleTitle = "Test Page Title";
class ReaderModeIconViewBrowserTest : public InProcessBrowserTest {
public:
ReaderModeIconViewBrowserTest(const ReaderModeIconViewBrowserTest&) = delete;
ReaderModeIconViewBrowserTest& operator=(
const ReaderModeIconViewBrowserTest&) = delete;
protected:
ReaderModeIconViewBrowserTest() {
feature_list_.InitAndEnableFeature(dom_distiller::kReaderMode);
https_server_secure_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_secure_->ServeFilesFromSourceDirectory(GetChromeTestDataDir());
}
void SetUpOnMainThread() override {
ASSERT_TRUE(https_server_secure()->Start());
reader_mode_icon_ =
BrowserView::GetBrowserViewForBrowser(browser())
->toolbar_button_provider()
->GetPageActionIconView(PageActionIconType::kReaderMode);
ASSERT_NE(nullptr, reader_mode_icon_);
}
net::EmbeddedTestServer* https_server_secure() {
return https_server_secure_.get();
}
PageActionIconView* reader_mode_icon_;
std::unique_ptr<net::EmbeddedTestServer> https_server_secure_;
private:
base::test::ScopedFeatureList feature_list_;
};
// TODO(gilmanmh): Add tests for the following cases:
// * Icon is visible on the distilled page.
// * Icon is not visible on about://blank, both initially and after navigating
// to a distillable page.
IN_PROC_BROWSER_TEST_F(ReaderModeIconViewBrowserTest,
IconVisibilityAdaptsToPageContents) {
dom_distiller::TestDistillabilityObserver observer(
browser()->tab_strip_model()->GetActiveWebContents());
dom_distiller::DistillabilityResult expected_result;
expected_result.is_distillable = false;
expected_result.is_last = false;
expected_result.is_mobile_friendly = false;
// The icon should not be visible by default, before navigation to any page
// has occurred.
const bool is_visible_before_navigation = reader_mode_icon_->GetVisible();
EXPECT_FALSE(is_visible_before_navigation);
// The icon should be hidden on pages that aren't distillable
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_secure()->GetURL(kNonArticlePath)));
observer.WaitForResult(expected_result);
const bool is_visible_on_non_distillable_page =
reader_mode_icon_->GetVisible();
EXPECT_FALSE(is_visible_on_non_distillable_page);
EXPECT_FALSE(observer.IsDistillabilityDriverTimerRunning());
// The icon should appear after navigating to a distillable article.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_secure()->GetURL(kSimpleArticlePath)));
expected_result.is_distillable = true;
observer.WaitForResult(expected_result);
const bool is_visible_on_article = reader_mode_icon_->GetVisible();
EXPECT_TRUE(is_visible_on_article);
EXPECT_TRUE(observer.IsDistillabilityDriverTimerRunning());
// Navigating back to a non-distillable page hides the icon again.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_secure()->GetURL(kNonArticlePath)));
expected_result.is_distillable = false;
observer.WaitForResult(expected_result);
const bool is_visible_after_navigation_back_to_non_distillable_page =
reader_mode_icon_->GetVisible();
EXPECT_FALSE(is_visible_after_navigation_back_to_non_distillable_page);
}
class ReaderModeIconViewPrerenderBrowserTest
: public ReaderModeIconViewBrowserTest {
public:
ReaderModeIconViewPrerenderBrowserTest()
: prerender_helper_(base::BindRepeating(
&ReaderModeIconViewPrerenderBrowserTest::web_contents,
base::Unretained(this))) {}
~ReaderModeIconViewPrerenderBrowserTest() override = default;
protected:
content::WebContents* web_contents() {
return browser()->tab_strip_model()->GetActiveWebContents();
}
content::test::PrerenderTestHelper prerender_helper_;
};
IN_PROC_BROWSER_TEST_F(ReaderModeIconViewPrerenderBrowserTest,
IconVisibilityNotAffectedByPrerendering) {
dom_distiller::TestDistillabilityObserver observer(
browser()->tab_strip_model()->GetActiveWebContents());
dom_distiller::DistillabilityResult expected_result;
expected_result.is_distillable = false;
expected_result.is_last = false;
expected_result.is_mobile_friendly = false;
// The icon should not be visible by default, before navigation to any page
// has occurred.
const bool is_visible_before_navigation = reader_mode_icon_->GetVisible();
EXPECT_FALSE(is_visible_before_navigation);
// The icon should be hidden on pages that aren't distillable.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_secure()->GetURL(kNonArticlePath)));
observer.WaitForResult(expected_result);
const bool is_visible_on_non_distillable_page =
reader_mode_icon_->GetVisible();
EXPECT_FALSE(is_visible_on_non_distillable_page);
// The icon should not yet appear after prerendering a distillable article.
prerender_helper_.AddPrerender(
https_server_secure()->GetURL(kSimpleArticlePath));
EXPECT_FALSE(observer.IsDistillabilityDriverTimerRunning());
// Make the prerendering page primary (i.e. the user clicked on a link to
// the prerendered URL). The icon should become visible at this point.
prerender_helper_.NavigatePrimaryPage(
https_server_secure()->GetURL(kSimpleArticlePath));
expected_result.is_distillable = true;
observer.WaitForResult(expected_result);
const bool is_visible_on_article = reader_mode_icon_->GetVisible();
EXPECT_TRUE(is_visible_on_article);
EXPECT_TRUE(observer.IsDistillabilityDriverTimerRunning());
}
class ReaderModeIconViewBrowserTestWithSettings
: public ReaderModeIconViewBrowserTest {
public:
ReaderModeIconViewBrowserTestWithSettings(
const ReaderModeIconViewBrowserTestWithSettings&) = delete;
ReaderModeIconViewBrowserTestWithSettings& operator=(
const ReaderModeIconViewBrowserTestWithSettings&) = delete;
protected:
ReaderModeIconViewBrowserTestWithSettings() {
feature_list_.InitAndEnableFeatureWithParameters(
dom_distiller::kReaderMode,
{{switches::kReaderModeDiscoverabilityParamName,
switches::kReaderModeOfferInSettings}});
}
void SetOfferReaderModeSetting(bool value) {
browser()->profile()->GetPrefs()->SetBoolean(
dom_distiller::prefs::kOfferReaderMode, value);
}
private:
base::test::ScopedFeatureList feature_list_;
};
// Flaky on Linux Win ChromeOS: crbug.com/1054641
IN_PROC_BROWSER_TEST_F(
ReaderModeIconViewBrowserTestWithSettings,
DISABLED_IconVisibilityDependsOnSettingIfExperimentEnabled) {
SetOfferReaderModeSetting(false);
dom_distiller::TestDistillabilityObserver observer(
browser()->tab_strip_model()->GetActiveWebContents());
dom_distiller::DistillabilityResult expected_result;
expected_result.is_distillable = true;
expected_result.is_last = false;
expected_result.is_mobile_friendly = false;
// The icon should not appear after navigating to a distillable article,
// because the setting to offer reader mode is disabled.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_secure()->GetURL(kSimpleArticlePath)));
observer.WaitForResult(expected_result);
bool is_visible_on_article = reader_mode_icon_->GetVisible();
EXPECT_FALSE(is_visible_on_article);
// It continues to not show up when navigating to a non-distillable page.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_secure()->GetURL(kNonArticlePath)));
expected_result.is_distillable = false;
observer.WaitForResult(expected_result);
bool is_visible_after_navigation_back_to_non_distillable_page =
reader_mode_icon_->GetVisible();
EXPECT_FALSE(is_visible_after_navigation_back_to_non_distillable_page);
// If we turn on the setting, the icon should start to show up on a
// distillable page.
SetOfferReaderModeSetting(true);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_secure()->GetURL(kSimpleArticlePath)));
expected_result.is_distillable = true;
observer.WaitForResult(expected_result);
is_visible_on_article = reader_mode_icon_->GetVisible();
EXPECT_TRUE(is_visible_on_article);
// But it still turns off when navigating to a non-distillable page.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_secure()->GetURL(kNonArticlePath)));
expected_result.is_distillable = false;
observer.WaitForResult(expected_result);
is_visible_after_navigation_back_to_non_distillable_page =
reader_mode_icon_->GetVisible();
EXPECT_FALSE(is_visible_after_navigation_back_to_non_distillable_page);
}
IN_PROC_BROWSER_TEST_F(ReaderModeIconViewBrowserTest,
NonSecurePagesNotDistillable) {
auto https_server_expired = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_expired->SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
https_server_expired->ServeFilesFromSourceDirectory(GetChromeTestDataDir());
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
SecurityStateTabHelper* helper =
SecurityStateTabHelper::FromWebContents(web_contents);
dom_distiller::TestDistillabilityObserver observer(web_contents);
dom_distiller::DistillabilityResult expected_result;
expected_result.is_distillable = true;
expected_result.is_last = false;
expected_result.is_mobile_friendly = false;
// Check test setup by ensuring the icon is shown with the secure test
// server.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_secure()->GetURL(kSimpleArticlePath)));
EXPECT_EQ(security_state::SECURE, helper->GetSecurityLevel());
observer.WaitForResult(expected_result);
EXPECT_TRUE(reader_mode_icon_->GetVisible());
// The icon should not be shown with a http test server.
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL(kSimpleArticlePath)));
EXPECT_NE(security_state::SECURE, helper->GetSecurityLevel());
expected_result.is_distillable = false;
observer.WaitForResult(expected_result);
EXPECT_FALSE(reader_mode_icon_->GetVisible());
// Set security state to DANGEROUS for the test by using an expired
// certificate.
ASSERT_TRUE(https_server_expired->Start());
content::TitleWatcher title_watcher(web_contents,
base::ASCIIToUTF16(kArticleTitle));
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired->GetURL(kSimpleArticlePath)));
// Proceed through the intersitial warning page.
web_contents = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(web_contents, 1);
security_interstitials::SecurityInterstitialTabHelper* interstitial_helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
web_contents);
interstitial_helper
->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->CommandReceived(
base::NumberToString(security_interstitials::CMD_PROCEED));
nav_observer.Wait();
// Check we are on the right page.
ASSERT_EQ(base::ASCIIToUTF16(kArticleTitle), title_watcher.WaitAndGetTitle());
// Check security state is DANGEROUS per https_server_expired_.
EXPECT_EQ(security_state::DANGEROUS, helper->GetSecurityLevel());
// The page should not be distillable.
observer.WaitForResult(expected_result);
EXPECT_FALSE(reader_mode_icon_->GetVisible());
}
} // namespace
|
// Copyright (c) 2011-2019 The Bitcoin Core Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/perbug-config.h>
#endif
#include <qt/sendcoinsdialog.h>
#include <qt/forms/ui_sendcoinsdialog.h>
#include <qt/addresstablemodel.h>
#include <qt/perbugunits.h>
#include <qt/clientmodel.h>
#include <qt/coincontroldialog.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/sendcoinsentry.h>
#include <chainparams.h>
#include <interfaces/node.h>
#include <key_io.h>
#include <policy/fees.h>
#include <txmempool.h>
#include <ui_interface.h>
#include <wallet/coincontrol.h>
#include <wallet/fees.h>
#include <wallet/wallet.h>
#include <QFontMetrics>
#include <QScrollBar>
#include <QSettings>
#include <QTextDocument>
static const std::array<int, 9> confTargets = { {2, 4, 6, 12, 24, 48, 144, 504, 1008} };
int getConfTargetForIndex(int index) {
if (index+1 > static_cast<int>(confTargets.size())) {
return confTargets.back();
}
if (index < 0) {
return confTargets[0];
}
return confTargets[index];
}
int getIndexForConfTarget(int target) {
for (unsigned int i = 0; i < confTargets.size(); i++) {
if (confTargets[i] >= target) {
return i;
}
}
return confTargets.size() - 1;
}
SendCoinsDialog::SendCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
clientModel(nullptr),
model(nullptr),
m_coin_control(new CCoinControl),
fNewRecipientAllowed(true),
fFeeMinimized(true),
platformStyle(_platformStyle)
{
ui->setupUi(this);
if (!_platformStyle->getImagesOnButtons()) {
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
} else {
ui->addButton->setIcon(_platformStyle->SingleColorIcon(":/icons/add"));
ui->clearButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
ui->sendButton->setIcon(_platformStyle->SingleColorIcon(":/icons/send"));
}
GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this);
addEntry();
connect(ui->addButton, &QPushButton::clicked, this, &SendCoinsDialog::addEntry);
connect(ui->clearButton, &QPushButton::clicked, this, &SendCoinsDialog::clear);
// Coin Control
connect(ui->pushButtonCoinControl, &QPushButton::clicked, this, &SendCoinsDialog::coinControlButtonClicked);
connect(ui->checkBoxCoinControlChange, &QCheckBox::stateChanged, this, &SendCoinsDialog::coinControlChangeChecked);
connect(ui->lineEditCoinControlChange, &QValidatedLineEdit::textEdited, this, &SendCoinsDialog::coinControlChangeEdited);
// Coin Control: clipboard actions
QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this);
QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, &QAction::triggered, this, &SendCoinsDialog::coinControlClipboardQuantity);
connect(clipboardAmountAction, &QAction::triggered, this, &SendCoinsDialog::coinControlClipboardAmount);
connect(clipboardFeeAction, &QAction::triggered, this, &SendCoinsDialog::coinControlClipboardFee);
connect(clipboardAfterFeeAction, &QAction::triggered, this, &SendCoinsDialog::coinControlClipboardAfterFee);
connect(clipboardBytesAction, &QAction::triggered, this, &SendCoinsDialog::coinControlClipboardBytes);
connect(clipboardLowOutputAction, &QAction::triggered, this, &SendCoinsDialog::coinControlClipboardLowOutput);
connect(clipboardChangeAction, &QAction::triggered, this, &SendCoinsDialog::coinControlClipboardChange);
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// init transaction fee section
QSettings settings;
if (!settings.contains("fFeeSectionMinimized"))
settings.setValue("fFeeSectionMinimized", true);
if (!settings.contains("nFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility
settings.setValue("nFeeRadio", 1); // custom
if (!settings.contains("nFeeRadio"))
settings.setValue("nFeeRadio", 0); // recommended
if (!settings.contains("nSmartFeeSliderPosition"))
settings.setValue("nSmartFeeSliderPosition", 0);
if (!settings.contains("nTransactionFee"))
settings.setValue("nTransactionFee", (qint64)DEFAULT_PAY_TX_FEE);
ui->groupFee->setId(ui->radioSmartFee, 0);
ui->groupFee->setId(ui->radioCustomFee, 1);
ui->groupFee->button((int)std::max(0, std::min(1, settings.value("nFeeRadio").toInt())))->setChecked(true);
ui->customFee->SetAllowEmpty(false);
ui->customFee->setValue(settings.value("nTransactionFee").toLongLong());
minimizeFeeSection(settings.value("fFeeSectionMinimized").toBool());
}
void SendCoinsDialog::setClientModel(ClientModel *_clientModel)
{
this->clientModel = _clientModel;
if (_clientModel) {
connect(_clientModel, &ClientModel::numBlocksChanged, this, &SendCoinsDialog::updateSmartFeeLabel);
}
}
void SendCoinsDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel())
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(_model);
}
}
interfaces::WalletBalances balances = _model->wallet().getBalances();
setBalance(balances);
connect(_model, &WalletModel::balanceChanged, this, &SendCoinsDialog::setBalance);
connect(_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &SendCoinsDialog::updateDisplayUnit);
updateDisplayUnit();
// Coin Control
connect(_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &SendCoinsDialog::coinControlUpdateLabels);
connect(_model->getOptionsModel(), &OptionsModel::coinControlFeaturesChanged, this, &SendCoinsDialog::coinControlFeatureChanged);
ui->frameCoinControl->setVisible(_model->getOptionsModel()->getCoinControlFeatures());
coinControlUpdateLabels();
// fee section
for (const int n : confTargets) {
ui->confTargetSelector->addItem(tr("%1 (%2 blocks)").arg(GUIUtil::formatNiceTimeOffset(n*Params().GetConsensus().nPowTargetSpacing)).arg(n));
}
connect(ui->confTargetSelector, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SendCoinsDialog::updateSmartFeeLabel);
connect(ui->confTargetSelector, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SendCoinsDialog::coinControlUpdateLabels);
connect(ui->groupFee, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked), this, &SendCoinsDialog::updateFeeSectionControls);
connect(ui->groupFee, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked), this, &SendCoinsDialog::coinControlUpdateLabels);
connect(ui->customFee, &BitcoinAmountField::valueChanged, this, &SendCoinsDialog::coinControlUpdateLabels);
connect(ui->optInRBF, &QCheckBox::stateChanged, this, &SendCoinsDialog::updateSmartFeeLabel);
connect(ui->optInRBF, &QCheckBox::stateChanged, this, &SendCoinsDialog::coinControlUpdateLabels);
CAmount requiredFee = model->wallet().getRequiredFee(1000);
ui->customFee->SetMinValue(requiredFee);
if (ui->customFee->value() < requiredFee) {
ui->customFee->setValue(requiredFee);
}
ui->customFee->setSingleStep(requiredFee);
updateFeeSectionControls();
updateSmartFeeLabel();
// set default rbf checkbox state
ui->optInRBF->setCheckState(Qt::Checked);
if (model->wallet().privateKeysDisabled()) {
ui->sendButton->setText(tr("Cr&eate Unsigned"));
ui->sendButton->setToolTip(tr("Creates a Partially Signed Bitcoin Transaction (PSBT) for use with e.g. an offline %1 wallet, or a PSBT-compatible hardware wallet.").arg(PACKAGE_NAME));
}
// set the smartfee-sliders default value (wallets default conf.target or last stored value)
QSettings settings;
if (settings.value("nSmartFeeSliderPosition").toInt() != 0) {
// migrate nSmartFeeSliderPosition to nConfTarget
// nConfTarget is available since 0.15 (replaced nSmartFeeSliderPosition)
int nConfirmTarget = 25 - settings.value("nSmartFeeSliderPosition").toInt(); // 25 == old slider range
settings.setValue("nConfTarget", nConfirmTarget);
settings.remove("nSmartFeeSliderPosition");
}
if (settings.value("nConfTarget").toInt() == 0)
ui->confTargetSelector->setCurrentIndex(getIndexForConfTarget(model->wallet().getConfirmTarget()));
else
ui->confTargetSelector->setCurrentIndex(getIndexForConfTarget(settings.value("nConfTarget").toInt()));
}
}
SendCoinsDialog::~SendCoinsDialog()
{
QSettings settings;
settings.setValue("fFeeSectionMinimized", fFeeMinimized);
settings.setValue("nFeeRadio", ui->groupFee->checkedId());
settings.setValue("nConfTarget", getConfTargetForIndex(ui->confTargetSelector->currentIndex()));
settings.setValue("nTransactionFee", (qint64)ui->customFee->value());
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
if(!model || !model->getOptionsModel())
return;
QList<SendCoinsRecipient> recipients;
bool valid = true;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate(model->node()))
{
recipients.append(entry->getValue());
}
else if (valid)
{
ui->scrollArea->ensureWidgetVisible(entry);
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
fNewRecipientAllowed = false;
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
// prepare transaction for getting txFee earlier
WalletModelTransaction currentTransaction(recipients);
WalletModel::SendCoinsReturn prepareStatus;
updateCoinControlState(*m_coin_control);
prepareStatus = model->prepareTransaction(currentTransaction, *m_coin_control);
// process prepareStatus and on error generate message shown to user
processSendCoinsReturn(prepareStatus,
BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()));
if(prepareStatus.status != WalletModel::OK) {
fNewRecipientAllowed = true;
return;
}
CAmount txFee = currentTransaction.getTransactionFee();
// Format confirmation message
QStringList formatted;
for (const SendCoinsRecipient &rcp : currentTransaction.getRecipients())
{
// generate amount string with wallet name in case of multiwallet
QString amount = BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
if (model->isMultiwallet()) {
amount.append(tr(" from wallet '%1'").arg(GUIUtil::HtmlEscape(model->getWalletName())));
}
// generate address string
QString address = rcp.address;
QString recipientElement;
{
if(rcp.label.length() > 0) // label with address
{
recipientElement.append(tr("%1 to '%2'").arg(amount, GUIUtil::HtmlEscape(rcp.label)));
recipientElement.append(QString(" (%1)").arg(address));
}
else // just address
{
recipientElement.append(tr("%1 to %2").arg(amount, address));
}
}
formatted.append(recipientElement);
}
QString questionString;
if (model->wallet().privateKeysDisabled()) {
questionString.append(tr("Do you want to draft this transaction?"));
} else {
questionString.append(tr("Are you sure you want to send?"));
}
questionString.append("<br /><span style='font-size:10pt;'>");
if (model->wallet().privateKeysDisabled()) {
questionString.append(tr("Please, review your transaction proposal. This will produce a Partially Signed Bitcoin Transaction (PSBT) which you can copy and then sign with e.g. an offline %1 wallet, or a PSBT-compatible hardware wallet.").arg(PACKAGE_NAME));
} else {
questionString.append(tr("Please, review your transaction."));
}
questionString.append("</span>%1");
if(txFee > 0)
{
// append fee string if a fee is required
questionString.append("<hr /><b>");
questionString.append(tr("Transaction fee"));
questionString.append("</b>");
// append transaction size
questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB): ");
// append transaction fee value
questionString.append("<span style='color:#aa0000; font-weight:bold;'>");
questionString.append(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), txFee));
questionString.append("</span><br />");
// append RBF message according to transaction's signalling
questionString.append("<span style='font-size:10pt; font-weight:normal;'>");
if (ui->optInRBF->isChecked()) {
questionString.append(tr("You can increase the fee later (signals Replace-By-Fee, BIP-125)."));
} else {
questionString.append(tr("Not signalling Replace-By-Fee, BIP-125."));
}
questionString.append("</span>");
}
// add total amount in all subdivision units
questionString.append("<hr />");
CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee;
QStringList alternativeUnits;
for (const BitcoinUnits::Unit u : BitcoinUnits::availableUnits())
{
if(u != model->getOptionsModel()->getDisplayUnit())
alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount));
}
questionString.append(QString("<b>%1</b>: <b>%2</b>").arg(tr("Total Amount"))
.arg(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), totalAmount)));
questionString.append(QString("<br /><span style='font-size:10pt; font-weight:normal;'>(=%1)</span>")
.arg(alternativeUnits.join(" " + tr("or") + " ")));
QString informative_text;
QString detailed_text;
if (formatted.size() > 1) {
questionString = questionString.arg("");
informative_text = tr("To review recipient list click \"Show Details...\"");
detailed_text = formatted.join("\n\n");
} else {
questionString = questionString.arg("<br /><br />" + formatted.at(0));
}
const QString confirmation = model->wallet().privateKeysDisabled() ? tr("Confirm transaction proposal") : tr("Confirm send coins");
const QString confirmButtonText = model->wallet().privateKeysDisabled() ? tr("Copy PSBT to clipboard") : tr("Send");
SendConfirmationDialog confirmationDialog(confirmation, questionString, informative_text, detailed_text, SEND_CONFIRM_DELAY, confirmButtonText, this);
confirmationDialog.exec();
QMessageBox::StandardButton retval = static_cast<QMessageBox::StandardButton>(confirmationDialog.result());
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
bool send_failure = false;
if (model->wallet().privateKeysDisabled()) {
CMutableTransaction mtx = CMutableTransaction{*(currentTransaction.getWtx())};
PartiallySignedTransaction psbtx(mtx);
bool complete = false;
const TransactionError err = model->wallet().fillPSBT(SIGHASH_ALL, false /* sign */, true /* bip32derivs */, psbtx, complete);
assert(!complete);
assert(err == TransactionError::OK);
// Serialize the PSBT
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << psbtx;
GUIUtil::setClipboard(EncodeBase64(ssTx.str()).c_str());
Q_EMIT message(tr("PSBT copied"), "Copied to clipboard", CClientUIInterface::MSG_INFORMATION);
} else {
// now send the prepared transaction
WalletModel::SendCoinsReturn sendStatus = model->sendCoins(currentTransaction);
// process sendStatus and on error generate message shown to user
processSendCoinsReturn(sendStatus);
if (sendStatus.status == WalletModel::OK) {
Q_EMIT coinsSent(currentTransaction.getWtx()->GetHash());
} else {
send_failure = true;
}
}
if (!send_failure) {
accept();
m_coin_control->UnSelectAll();
coinControlUpdateLabels();
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Clear coin control settings
m_coin_control->UnSelectAll();
ui->checkBoxCoinControlChange->setChecked(false);
ui->lineEditCoinControlChange->clear();
coinControlUpdateLabels();
// Remove entries until only one left
while(ui->entries->count())
{
ui->entries->takeAt(0)->widget()->deleteLater();
}
addEntry();
updateTabsAndLabels();
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(platformStyle, this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, &SendCoinsEntry::removeEntry, this, &SendCoinsDialog::removeEntry);
connect(entry, &SendCoinsEntry::useAvailableBalance, this, &SendCoinsDialog::useAvailableBalance);
connect(entry, &SendCoinsEntry::payAmountChanged, this, &SendCoinsDialog::coinControlUpdateLabels);
connect(entry, &SendCoinsEntry::subtractFeeFromAmountChanged, this, &SendCoinsDialog::coinControlUpdateLabels);
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
qApp->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
updateTabsAndLabels();
return entry;
}
void SendCoinsDialog::updateTabsAndLabels()
{
setupTabChain(nullptr);
coinControlUpdateLabels();
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
entry->hide();
// If the last entry is about to be removed add an empty one
if (ui->entries->count() == 1)
addEntry();
entry->deleteLater();
updateTabsAndLabels();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->sendButton);
QWidget::setTabOrder(ui->sendButton, ui->clearButton);
QWidget::setTabOrder(ui->clearButton, ui->addButton);
return ui->addButton;
}
void SendCoinsDialog::setAddress(const QString &address)
{
SendCoinsEntry *entry = nullptr;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setAddress(address);
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = nullptr;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
updateTabsAndLabels();
}
bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient &rv)
{
// Just paste the entry, all pre-checks
// are done in paymentserver.cpp.
pasteEntry(rv);
return true;
}
void SendCoinsDialog::setBalance(const interfaces::WalletBalances& balances)
{
if(model && model->getOptionsModel())
{
CAmount balance = balances.balance;
if (model->wallet().privateKeysDisabled()) {
balance = balances.watch_only_balance;
ui->labelBalanceName->setText(tr("Watch-only balance:"));
}
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balance));
}
}
void SendCoinsDialog::updateDisplayUnit()
{
setBalance(model->wallet().getBalances());
ui->customFee->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
updateSmartFeeLabel();
}
void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn &sendCoinsReturn, const QString &msgArg)
{
QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams;
// Default to a warning message, override if error message is needed
msgParams.second = CClientUIInterface::MSG_WARNING;
// This comment is specific to SendCoinsDialog usage of WalletModel::SendCoinsReturn.
// All status values are used only in WalletModel::prepareTransaction()
switch(sendCoinsReturn.status)
{
case WalletModel::InvalidAddress:
msgParams.first = tr("The recipient address is not valid. Please recheck.");
break;
case WalletModel::InvalidAmount:
msgParams.first = tr("The amount to pay must be larger than 0.");
break;
case WalletModel::AmountExceedsBalance:
msgParams.first = tr("The amount exceeds your balance.");
break;
case WalletModel::AmountWithFeeExceedsBalance:
msgParams.first = tr("The total exceeds your balance when the %1 transaction fee is included.").arg(msgArg);
break;
case WalletModel::DuplicateAddress:
msgParams.first = tr("Duplicate address found: addresses should only be used once each.");
break;
case WalletModel::TransactionCreationFailed:
msgParams.first = tr("Transaction creation failed!");
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
case WalletModel::AbsurdFee:
msgParams.first = tr("A fee higher than %1 is considered an absurdly high fee.").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->wallet().getDefaultMaxTxFee()));
break;
case WalletModel::PaymentRequestExpired:
msgParams.first = tr("Payment request expired.");
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
// included to prevent a compiler warning.
case WalletModel::OK:
default:
return;
}
Q_EMIT message(tr("Send Coins"), msgParams.first, msgParams.second);
}
void SendCoinsDialog::minimizeFeeSection(bool fMinimize)
{
ui->labelFeeMinimized->setVisible(fMinimize);
ui->buttonChooseFee ->setVisible(fMinimize);
ui->buttonMinimizeFee->setVisible(!fMinimize);
ui->frameFeeSelection->setVisible(!fMinimize);
ui->horizontalLayoutSmartFee->setContentsMargins(0, (fMinimize ? 0 : 6), 0, 0);
fFeeMinimized = fMinimize;
}
void SendCoinsDialog::on_buttonChooseFee_clicked()
{
minimizeFeeSection(false);
}
void SendCoinsDialog::on_buttonMinimizeFee_clicked()
{
updateFeeMinimizedLabel();
minimizeFeeSection(true);
}
void SendCoinsDialog::useAvailableBalance(SendCoinsEntry* entry)
{
// Include watch-only for wallets without private key
m_coin_control->fAllowWatchOnly = model->wallet().privateKeysDisabled();
// Calculate available amount to send.
CAmount amount = model->wallet().getAvailableBalance(*m_coin_control);
for (int i = 0; i < ui->entries->count(); ++i) {
SendCoinsEntry* e = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if (e && !e->isHidden() && e != entry) {
amount -= e->getValue().amount;
}
}
if (amount > 0) {
entry->checkSubtractFeeFromAmount();
entry->setAmount(amount);
} else {
entry->setAmount(0);
}
}
void SendCoinsDialog::updateFeeSectionControls()
{
ui->confTargetSelector ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee2 ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee3 ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelFeeEstimation ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelCustomFeeWarning ->setEnabled(ui->radioCustomFee->isChecked());
ui->labelCustomPerKilobyte ->setEnabled(ui->radioCustomFee->isChecked());
ui->customFee ->setEnabled(ui->radioCustomFee->isChecked());
}
void SendCoinsDialog::updateFeeMinimizedLabel()
{
if(!model || !model->getOptionsModel())
return;
if (ui->radioSmartFee->isChecked())
ui->labelFeeMinimized->setText(ui->labelSmartFee->text());
else {
ui->labelFeeMinimized->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ui->customFee->value()) + "/kB");
}
}
void SendCoinsDialog::updateCoinControlState(CCoinControl& ctrl)
{
if (ui->radioCustomFee->isChecked()) {
ctrl.m_feerate = CFeeRate(ui->customFee->value());
} else {
ctrl.m_feerate.reset();
}
// Avoid using global defaults when sending money from the GUI
// Either custom fee will be used or if not selected, the confirmation target from dropdown box
ctrl.m_confirm_target = getConfTargetForIndex(ui->confTargetSelector->currentIndex());
ctrl.m_signal_bip125_rbf = ui->optInRBF->isChecked();
// Include watch-only for wallets without private key
ctrl.fAllowWatchOnly = model->wallet().privateKeysDisabled();
}
void SendCoinsDialog::updateSmartFeeLabel()
{
if(!model || !model->getOptionsModel())
return;
updateCoinControlState(*m_coin_control);
m_coin_control->m_feerate.reset(); // Explicitly use only fee estimation rate for smart fee labels
int returned_target;
FeeReason reason;
CFeeRate feeRate = CFeeRate(model->wallet().getMinimumFee(1000, *m_coin_control, &returned_target, &reason));
ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB");
if (reason == FeeReason::FALLBACK) {
ui->labelSmartFee2->show(); // (Smart fee not initialized yet. This usually takes a few blocks...)
ui->labelFeeEstimation->setText("");
ui->fallbackFeeWarningLabel->setVisible(true);
int lightness = ui->fallbackFeeWarningLabel->palette().color(QPalette::WindowText).lightness();
QColor warning_colour(255 - (lightness / 5), 176 - (lightness / 3), 48 - (lightness / 14));
ui->fallbackFeeWarningLabel->setStyleSheet("QLabel { color: " + warning_colour.name() + "; }");
ui->fallbackFeeWarningLabel->setIndent(GUIUtil::TextWidth(QFontMetrics(ui->fallbackFeeWarningLabel->font()), "x"));
}
else
{
ui->labelSmartFee2->hide();
ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", returned_target));
ui->fallbackFeeWarningLabel->setVisible(false);
}
updateFeeMinimizedLabel();
}
// Coin Control: copy label "Quantity" to clipboard
void SendCoinsDialog::coinControlClipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// Coin Control: copy label "Amount" to clipboard
void SendCoinsDialog::coinControlClipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// Coin Control: copy label "Fee" to clipboard
void SendCoinsDialog::coinControlClipboardFee()
{
GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// Coin Control: copy label "After fee" to clipboard
void SendCoinsDialog::coinControlClipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// Coin Control: copy label "Bytes" to clipboard
void SendCoinsDialog::coinControlClipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace(ASYMP_UTF8, ""));
}
// Coin Control: copy label "Dust" to clipboard
void SendCoinsDialog::coinControlClipboardLowOutput()
{
GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text());
}
// Coin Control: copy label "Change" to clipboard
void SendCoinsDialog::coinControlClipboardChange()
{
GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// Coin Control: settings menu - coin control enabled/disabled by user
void SendCoinsDialog::coinControlFeatureChanged(bool checked)
{
ui->frameCoinControl->setVisible(checked);
if (!checked && model) // coin control features disabled
m_coin_control->SetNull();
coinControlUpdateLabels();
}
// Coin Control: button inputs -> show actual coin control dialog
void SendCoinsDialog::coinControlButtonClicked()
{
CoinControlDialog dlg(*m_coin_control, model, platformStyle);
dlg.exec();
coinControlUpdateLabels();
}
// Coin Control: checkbox custom change address
void SendCoinsDialog::coinControlChangeChecked(int state)
{
if (state == Qt::Unchecked)
{
m_coin_control->destChange = CNoDestination();
ui->labelCoinControlChangeLabel->clear();
}
else
// use this to re-validate an already entered address
coinControlChangeEdited(ui->lineEditCoinControlChange->text());
ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked));
}
// Coin Control: custom change address changed
void SendCoinsDialog::coinControlChangeEdited(const QString& text)
{
if (model && model->getAddressTableModel())
{
// Default to no change address until verified
m_coin_control->destChange = CNoDestination();
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}");
const CTxDestination dest = DecodeDestination(text.toStdString());
if (text.isEmpty()) // Nothing entered
{
ui->labelCoinControlChangeLabel->setText("");
}
else if (!IsValidDestination(dest)) // Invalid address
{
ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid Perbug address"));
}
else // Valid address
{
if (!model->wallet().isSpendable(dest)) {
ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address"));
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm custom change address"), tr("The address you selected for change is not part of this wallet. Any or all funds in your wallet may be sent to this address. Are you sure?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if(btnRetVal == QMessageBox::Yes)
m_coin_control->destChange = dest;
else
{
ui->lineEditCoinControlChange->setText("");
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}");
ui->labelCoinControlChangeLabel->setText("");
}
}
else // Known change address
{
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}");
// Query label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(text);
if (!associatedLabel.isEmpty())
ui->labelCoinControlChangeLabel->setText(associatedLabel);
else
ui->labelCoinControlChangeLabel->setText(tr("(no label)"));
m_coin_control->destChange = dest;
}
}
}
}
// Coin Control: update labels
void SendCoinsDialog::coinControlUpdateLabels()
{
if (!model || !model->getOptionsModel())
return;
updateCoinControlState(*m_coin_control);
// set pay amounts
CoinControlDialog::payAmounts.clear();
CoinControlDialog::fSubtractFeeFromAmount = false;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry && !entry->isHidden())
{
SendCoinsRecipient rcp = entry->getValue();
CoinControlDialog::payAmounts.append(rcp.amount);
if (rcp.fSubtractFeeFromAmount)
CoinControlDialog::fSubtractFeeFromAmount = true;
}
}
if (m_coin_control->HasSelected())
{
// actual coin control calculation
CoinControlDialog::updateLabels(*m_coin_control, model, this);
// show coin control stats
ui->labelCoinControlAutomaticallySelected->hide();
ui->widgetCoinControl->show();
}
else
{
// hide coin control stats
ui->labelCoinControlAutomaticallySelected->show();
ui->widgetCoinControl->hide();
ui->labelCoinControlInsuffFunds->hide();
}
}
SendConfirmationDialog::SendConfirmationDialog(const QString& title, const QString& text, const QString& informative_text, const QString& detailed_text, int _secDelay, const QString& _confirmButtonText, QWidget* parent)
: QMessageBox(parent), secDelay(_secDelay), confirmButtonText(_confirmButtonText)
{
setIcon(QMessageBox::Question);
setWindowTitle(title); // On macOS, the window title is ignored (as required by the macOS Guidelines).
setText(text);
setInformativeText(informative_text);
setDetailedText(detailed_text);
setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
setDefaultButton(QMessageBox::Cancel);
yesButton = button(QMessageBox::Yes);
updateYesButton();
connect(&countDownTimer, &QTimer::timeout, this, &SendConfirmationDialog::countDown);
}
int SendConfirmationDialog::exec()
{
updateYesButton();
countDownTimer.start(1000);
return QMessageBox::exec();
}
void SendConfirmationDialog::countDown()
{
secDelay--;
updateYesButton();
if(secDelay <= 0)
{
countDownTimer.stop();
}
}
void SendConfirmationDialog::updateYesButton()
{
if(secDelay > 0)
{
yesButton->setEnabled(false);
yesButton->setText(confirmButtonText + " (" + QString::number(secDelay) + ")");
}
else
{
yesButton->setEnabled(true);
yesButton->setText(confirmButtonText);
}
}
|
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "unified_image.h"
#include "core/execution_environment/execution_environment.h"
#include "core/gmm_helper/gmm.h"
#include "core/gmm_helper/resource_info.h"
#include "core/helpers/get_info.h"
#include "core/helpers/hw_helper.h"
#include "core/memory_manager/graphics_allocation.h"
#include "runtime/context/context.h"
#include "runtime/mem_obj/image.h"
#include "runtime/memory_manager/memory_manager.h"
namespace NEO {
Image *UnifiedImage::createSharedUnifiedImage(Context *context, cl_mem_flags flags, UnifiedSharingMemoryDescription description,
const cl_image_format *imageFormat, const cl_image_desc *imageDesc, cl_int *errcodeRet) {
ErrorCodeHelper errorCode(errcodeRet, CL_SUCCESS);
UnifiedSharingFunctions *sharingFunctions = context->getSharing<UnifiedSharingFunctions>();
auto *clSurfaceFormat = Image::getSurfaceFormatFromTable(flags, imageFormat);
ImageInfo imgInfo = {};
imgInfo.imgDesc = Image::convertDescriptor(*imageDesc);
imgInfo.surfaceFormat = &clSurfaceFormat->surfaceFormat;
GraphicsAllocation *graphicsAllocation = createGraphicsAllocation(context, description, GraphicsAllocation::AllocationType::SHARED_IMAGE);
if (!graphicsAllocation) {
errorCode.set(CL_INVALID_MEM_OBJECT);
return nullptr;
}
graphicsAllocation->getDefaultGmm()->updateOffsetsInImgInfo(imgInfo, 0u);
auto &memoryManager = *context->getMemoryManager();
if (graphicsAllocation->getDefaultGmm()->unifiedAuxTranslationCapable()) {
const auto &hwInfo = *memoryManager.peekExecutionEnvironment().getHardwareInfo();
const auto &hwHelper = HwHelper::get(hwInfo.platform.eRenderCoreFamily);
graphicsAllocation->getDefaultGmm()->isRenderCompressed = hwHelper.isPageTableManagerSupported(hwInfo) ? memoryManager.mapAuxGpuVA(graphicsAllocation) : true;
}
const uint32_t baseMipmapIndex = 0u;
const uint32_t sharedMipmapsCount = imageDesc->num_mip_levels;
auto sharingHandler = new UnifiedImage(sharingFunctions, description.type);
return Image::createSharedImage(context, sharingHandler, McsSurfaceInfo{}, graphicsAllocation, nullptr,
flags, clSurfaceFormat, imgInfo, __GMM_NO_CUBE_MAP, baseMipmapIndex, sharedMipmapsCount);
}
} // namespace NEO
|
#include <stdlib.h>
#include "LATfield2.hpp"
using namespace LATfield2;
int main(int argc, char **argv)
{
int n,m;
int io_groupe_size,io_size;
string str_filename;
int npts = 64;
int numparts = 64;
Real latresolution =0.1;
for (int i=1 ; i < argc ; i++ ){
if ( argv[i][0] != '-' )
continue;
switch(argv[i][1]) {
case 'n':
n = atoi(argv[++i]); //size of the dim 1 of the processor grid
break;
case 'm':
m = atoi(argv[++i]); //size of the dim 2 of the processor grid
break;
case 'i':
io_size = atoi(argv[++i]);
break;
case 'g':
io_groupe_size = atoi(argv[++i]);
break;
case 'o':
str_filename = argv[++i];
break;
case 's':
npts = atoi(argv[++i]);
break;
case 'p':
numparts = atoi(argv[++i]);
break;
case 'r':
latresolution = atof(argv[++i]);
break;
}
}
#ifndef EXTERNAL_IO
parallel.initialize(n,m);
#else
parallel.initialize(n,m,io_size,io_groupe_size);
if(parallel.isIO()) ioserver.start();
else
{
#endif
int dim=3;
int halo=1;
int khalo=1;
Lattice lat_part(dim,npts,0);
Lattice lat(dim,npts,halo);
Field<Real> phi(lat,1);
Field<Real> B(lat,3);
Field<Real> Tij(lat,3,3,LATfield2::symmetric);
Real boxSize[3];
for(int i=0;i<3;i++)boxSize[i] = latresolution * lat_part.size(i);
double timerRef;
double timerWrite,timerLoad,timerWriteServer;
double timerProjScalar,timerProjVector,timerProjTensor;
double timerCommScalar,timerCommVector,timerCommTensor;
double timerMove,timerVel;
Site x(lat);
for(x.first();x.test();x.next())
{
phi(x)=0.;
for(int i=0;i<3;i++)B(x,i)=0.;
}
//cout<<"start part init done"<<endl;
part_simple_info particles_global_info;
part_simple_dataType particles_dataType;
particles_global_info.mass=0.1;
particles_global_info.relativistic=false;
set_parts_typename(&particles_global_info,"part_simple");
Particles<part_simple,part_simple_info,part_simple_dataType> parts;
parts.initialize(particles_global_info,particles_dataType,&lat_part,boxSize);
//cout<<"init done"<<endl;
part_simple part;
long index =0;
/*
for(int i=0;i<numparts;i++)
for(int j=0;j<numparts;j++)
for(int k=0;k<numparts;k++){
part.ID=index;
part.pos[0]= (Real)i * (Real)boxSize[0] / (Real)numparts;
part.pos[1]= (Real)j * (Real)boxSize[1] / (Real)numparts;
part.pos[2]= (Real)k * (Real)boxSize[2] / (Real)numparts;
part.vel[0]=1.0;
part.vel[1]=1.0;
part.vel[2]=1.0;
//part.mass=0.22;
parts.addParticle_global(part);
index++;
}
*/
int ratio = numparts/npts;
//ratio;
Site xp(lat_part);
for(xp.first();xp.test();xp.next())
{
for(int i=0;i<ratio;i++)
for(int j=0;j<ratio;j++)
for(int k=0;k<ratio;k++){
part.ID=index;
part.pos[0]= (Real)xp.coord(0) * (Real)boxSize[0] / (Real)npts;
part.pos[1]= (Real)xp.coord(1) * (Real)boxSize[1] / (Real)npts;
part.pos[2]= (Real)xp.coord(2) * (Real)boxSize[2] / (Real)npts;
part.vel[0]=1.0;
part.vel[1]=1.0;
part.vel[2]=1.0;
//part.mass=0.22;
parts.addParticle_global(part);
index++;
}
}
cout<<"implementation done"<<endl;
#ifdef EXTERNAL_IO
while( !ioserver.openOstream());
parts.saveHDF5_server_open("data/bench_part_server");
#endif
timerRef = MPI_Wtime();
parts.saveHDF5("bench_part",1);
timerWrite = MPI_Wtime() - timerRef;
timerRef = MPI_Wtime();
parts.loadHDF5("bench_part",1);
timerLoad = MPI_Wtime() - timerRef;
#ifdef EXTERNAL_IO
timerRef = MPI_Wtime();
parts.saveHDF5_server_write();
timerWriteServer = MPI_Wtime() - timerRef;
ioserver.closeOstream();
#endif
/*
// cout<<"write done"<<endl;
projection_init(&phi);
projection_init(&B);
projection_init(&Tij);
//cout<<"init proj done"<<endl;
timerRef = MPI_Wtime();
scalarProjectionCIC_project(&parts,&phi);
timerProjScalar = MPI_Wtime() - timerRef;
//cout<<"scalar proj done"<<endl;
timerRef = MPI_Wtime();
scalarProjectionCIC_comm(&phi);
timerCommScalar = MPI_Wtime() - timerRef;
//cout<<"scalar comm done"<<endl;
timerRef = MPI_Wtime();
vectorProjectionCICNGP_project(&parts,&B);
timerProjVector = MPI_Wtime() - timerRef;
//cout<<"vector proj done"<<endl;
timerRef = MPI_Wtime();
vectorProjectionCICNGP_comm(&B);
timerCommVector = MPI_Wtime() - timerRef;
//cout<<"vector comm done"<<endl;
timerRef = MPI_Wtime();
symtensorProjectionCICNGP_project(&parts,&Tij);
timerProjTensor = MPI_Wtime() - timerRef;
//cout<<"tensor proj done"<<endl;
timerRef = MPI_Wtime();
symtensorProjectionCICNGP_comm(&Tij);
timerCommTensor = MPI_Wtime() - timerRef;
//cout<<"tensor comm done"<<endl;
timerRef = MPI_Wtime();
parts.updateVel(&updateVel_simple,1.0);
timerVel = MPI_Wtime() - timerRef;
//cout<<"update vel done"<<endl;
timerRef = MPI_Wtime();
parts.moveParticles(&move_particles_simple,1.0/ (1.0* (double)npts));
timerMove = MPI_Wtime() - timerRef;
//cout<<"move done"<<endl;
ofstream textfile;
if(parallel.isRoot())
{
textfile.open(str_filename.c_str(),ios::out | ios::app);
textfile<< n<<","<<m<< ","<< io_size<< ","<<io_groupe_size<< ","<< npts << ","<< numparts << ",";
textfile<< timerWrite << ","<< timerLoad << ","<< timerWriteServer << ","<< timerProjScalar << ","<< timerCommScalar << ",";
textfile<< timerProjVector << ","<< timerCommVector << ","<< timerProjTensor << ","<< timerCommTensor << ","<< timerVel << ","<< timerMove <<endl;
textfile.close();
}
*/
#ifdef EXTERNAL_IO
ioserver.stop();
}
#endif
}
|
/**************************************************************/
/* */
/* Copyright Mentor Graphics Corporation 2006 - 2015 */
/* All Rights Reserved */
/* */
/* THIS WORK CONTAINS TRADE SECRET AND PROPRIETARY */
/* INFORMATION WHICH IS THE PROPERTY OF MENTOR */
/* GRAPHICS CORPORATION OR ITS LICENSORS AND IS */
/* SUBJECT TO LICENSE TERMS. */
/* */
/**************************************************************/
//*<
//* Generated By Model Builder, Mentor Graphics Computer Systems, Inc.
//*
//* This file is write protected.
//* DO NOT MODIFY THIS FILE.
//*
//* This file is generated according to the parameters in the
//* Model Builder form.
//* This class contains the infrastructure to define the behavior of the component.
//* The WaveSampleGenerator_pv will be derived from this class.
//*
//* Model Builder version: 4.2.1
//* Generated on: Aug. 15, 2016 06:02:58 PM, (user: kenm)
//*>
#include "WaveSampleGenerator_model.h"
#ifdef MODEL_BUILDER_VERSION_NUMBER
#if 4201 != MODEL_BUILDER_VERSION_NUMBER
#error "This model was generated using Model Builder version: 4.2.1. Please regenerate model."
#endif
#else
#error "Please regenerate model."
#endif
using namespace sc_core;
using namespace sc_dt;
using namespace std;
WaveSampleGenerator_pv_base::WaveSampleGenerator_pv_base(sc_module_name& module_name) :
WaveSampleGenerator_pv_base_mb_compatibility(module_name),
WaveSampleGenerator_pv_base_parameters(this),
VISTA_MB_PV_INIT_MEMBER(Slave),
VISTA_MB_PV_INIT_MEMBER(Waveform) {
// Slave - not a vector port
unsigned u = 0;
payload_on_stack = 0;
payload_for_token = 0;
reset_registers();
// reset value for output signals
// reset value for input signals
// Slave bw binding
VISTA_MB_PV_BIND_FW_PROCESS_TO_TARGET(Slave);
// Slave bw callbacks
VISTA_MB_PV_REGISTER_SELF_FW_PROCESS_CALLBACKS(Slave);
}
void WaveSampleGenerator_pv_base::reset_registers() {
// reset all registers
unsigned u = 0;
}
void WaveSampleGenerator_pv_base::reset_model() {
reset_registers();
// reset value for output signals
// reset value for input signals
}
WaveSampleGenerator_pv_base_parameters::WaveSampleGenerator_pv_base_parameters(sc_object* object) :
m_object(object),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, clock, sc_core::sc_time(10, sc_core::SC_NS)),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, generic_clock, clock),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, nominal_voltage, 1),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, mb_debug, false),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, call_to_default_if, false),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, verbose_parameters, true),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, dmi_enabled, true),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, warning_level, "WARNING"),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, Slave_pipeline_length, 2),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, Max, USHRT_MAX),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, Min, 0),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, Period, sc_core::sc_time(1.0, sc_core::SC_MS)),
SD_INITIALIZE_PARAMETER_EXTERNALLY(object, Type, "sine")
{
if(verbose_parameters) print_parameters();
}
void WaveSampleGenerator_pv_base_parameters::print_parameters()
{
const char* name;
if (!strcmp(m_object->basename(), "PV"))
name = m_object->get_parent()->name();
else
name = m_object->name();
std::cout.setf(ios::hex, ios::basefield);
std::cout.setf(ios::showbase);
std::cout << name << "::parameters:\n";
std::cout << "\tclock = " << clock << "\n";
std::cout << "\tgeneric_clock = " << generic_clock << "\n";
std::cout << "\tnominal_voltage = " << nominal_voltage << "\n";
std::cout << "\tmb_debug = " << mb_debug << "\n";
std::cout << "\tcall_to_default_if = " << call_to_default_if << "\n";
std::cout << "\tverbose_parameters = " << verbose_parameters << "\n";
std::cout << "\tdmi_enabled = " << dmi_enabled << "\n";
std::cout << "\twarning_level = " << warning_level << "\n";
std::cout << "\tSlave_pipeline_length = " << Slave_pipeline_length << "\n";
std::cout << "\tMax = " << Max << "\n";
std::cout << "\tMin = " << Min << "\n";
std::cout << "\tPeriod = " << Period << "\n";
std::cout << "\tType = " << Type << "\n";
std::cout.unsetf(ios::showbase);
std::cout.setf(ios::dec, ios::basefield);
std::cout << std::endl;
}
/**************************************************************/
/* */
/* Copyright Mentor Graphics Corporation 2006 - 2015 */
/* All Rights Reserved */
/* */
/* THIS WORK CONTAINS TRADE SECRET AND PROPRIETARY */
/* INFORMATION WHICH IS THE PROPERTY OF MENTOR */
/* GRAPHICS CORPORATION OR ITS LICENSORS AND IS */
/* SUBJECT TO LICENSE TERMS. */
/* */
/**************************************************************/
//*<
//* Generated By Model Builder, Mentor Graphics Computer Systems, Inc.
//*
//* This file is write protected.
//* DO NOT MODIFY THIS FILE.
//*
//* This file is generated according to the parameters in the
//* Model Builder form.
//*
//* Any change in parameters, policies, ports, protocols, etc. will change this file
//* upon generation of the timing model (using generate_timing_model command).
//* The WaveSampleGenerator_t will be derived from this class.
//*
//* Model Builder version: 4.2.1
//* Generated on: Aug. 15, 2016 06:02:58 PM, (user: kenm)
//*>
#include "WaveSampleGenerator_model.h"
#include <math.h>
#include <stdlib.h>
using namespace esl::tlm_sim;
using namespace esl::sc_sim;
using namespace std;
using namespace sc_dt;
using namespace sc_core;
void WaveSampleGenerator_t_base::start_transaction_generic_READ
(esl::include::TRequest* request,
unsigned port_index,
sc_dt::uint64 startTime,
sc_dt::uint64 endTime,
sc_dt::uint64* parameters,
bool hasBeenError) {
long burstSize = request->getSize();
parameters[0] = request->getAddress();
parameters[1] = request->getFirstDataBlock();
parameters[4] = request->getBlockSize();
this->accept_generic_READ
(port_index,
startTime,
burstSize,
parameters[0],
parameters[1],
parameters[2],
parameters[3],
parameters[4],
parameters[5]);
}
void WaveSampleGenerator_t_base::end_transaction_generic_READ
(esl::include::TRequest* request,
unsigned port_index,
sc_dt::uint64 startTime,
sc_dt::uint64 endTime,
sc_dt::uint64* parameters,
bool hasBeenError) {
long burstSize = request->getSize();
parameters[0] = request->getAddress();
parameters[1] = request->getFirstDataBlock();
parameters[4] = request->getBlockSize();
this->end_generic_READ
(port_index,
endTime,
burstSize,
parameters[0],
parameters[1],
parameters[2],
parameters[3],
parameters[4],
parameters[5]);
}
void WaveSampleGenerator_t_base::start_transaction_generic_WRITE
(esl::include::TRequest* request,
unsigned port_index,
sc_dt::uint64 startTime,
sc_dt::uint64 endTime,
sc_dt::uint64* parameters,
bool hasBeenError) {
long burstSize = request->getSize();
parameters[0] = request->getAddress();
parameters[1] = request->getFirstDataBlock();
parameters[4] = request->getBlockSize();
this->accept_generic_WRITE
(port_index,
startTime,
burstSize,
parameters[0],
parameters[1],
parameters[2],
parameters[3],
parameters[4],
parameters[5]);
}
void WaveSampleGenerator_t_base::end_transaction_generic_WRITE
(esl::include::TRequest* request,
unsigned port_index,
sc_dt::uint64 startTime,
sc_dt::uint64 endTime,
sc_dt::uint64* parameters,
bool hasBeenError) {
long burstSize = request->getSize();
parameters[0] = request->getAddress();
parameters[1] = request->getFirstDataBlock();
parameters[4] = request->getBlockSize();
this->end_generic_WRITE
(port_index,
endTime,
burstSize,
parameters[0],
parameters[1],
parameters[2],
parameters[3],
parameters[4],
parameters[5]);
}
WaveSampleGenerator_t_base::TransactionCallbackFunctionPointer WaveSampleGenerator_t_base::getTransactionCallback(unsigned callbackIndex) {
static TransactionCallbackFunctionPointer funcArray[] = {
static_cast<TransactionCallbackFunctionPointer>(&WaveSampleGenerator_t_base::start_transaction_generic_READ),
static_cast<TransactionCallbackFunctionPointer>(&WaveSampleGenerator_t_base::start_transaction_generic_WRITE),
static_cast<TransactionCallbackFunctionPointer>(&WaveSampleGenerator_t_base::end_transaction_generic_READ),
static_cast<TransactionCallbackFunctionPointer>(&WaveSampleGenerator_t_base::end_transaction_generic_WRITE),
0
};
if(callbackIndex >= sizeof(funcArray) / sizeof(*funcArray) - 1)
return 0;
return funcArray[callbackIndex];
}
config::real80 WaveSampleGenerator_t_base::get_state_power() {
config::real80 power_value = 0;
return power_value;
}
WaveSampleGenerator_t_base::WaveSampleGenerator_t_base(sc_module_name& module_name, long simulation) :
papoulis::SystemCBaseModel(module_name),
SD_INITIALIZE_PARAMETER(clock, sc_core::sc_time(10, sc_core::SC_NS)),
SD_INITIALIZE_PARAMETER(generic_clock, clock),
SD_INITIALIZE_PARAMETER(nominal_voltage, 1),
SD_INITIALIZE_PARAMETER(mb_debug, false),
SD_INITIALIZE_PARAMETER(call_to_default_if, false),
SD_INITIALIZE_PARAMETER(verbose_parameters, true),
SD_INITIALIZE_PARAMETER(dmi_enabled, true),
SD_INITIALIZE_PARAMETER(warning_level, "WARNING"),
SD_INITIALIZE_PARAMETER(Slave_pipeline_length, 2),
SD_INITIALIZE_PARAMETER(Max, USHRT_MAX),
SD_INITIALIZE_PARAMETER(Min, 0),
SD_INITIALIZE_PARAMETER(Period, sc_core::sc_time(1.0, sc_core::SC_MS)),
SD_INITIALIZE_PARAMETER(Type, "sine"),
m_simulation(simulation),
Waveform("Waveform", this)
{
bool separate_read_channel = false;
bool separate_write_channel = false;
char* buffer = 0;
unsigned port_index = 0;
fix_clock_parameter(generic_clock, "generic_clock");
separate_read_channel = false;
separate_write_channel = false;
buffer = new char[15];
sprintf(buffer, "Slave");
port_index = Slave;
port_descriptions[port_index].port_name = buffer;
port_descriptions[port_index].port_kind = PortDescription::READ_WRITE_CHANNEL_PORT;
if (separate_write_channel && separate_read_channel)
port_descriptions[port_index].port_kind = PortDescription::SEPARATE_READ_WRIE_CHANNEL_PORT;
port_descriptions[port_index].is_read_write_address_channel = 0;
port_descriptions[port_index].is_read_write_address_channel = 1;
port_descriptions[port_index].is_master_port = 0;
port_descriptions[port_index].is_signal_port = 0;
port_descriptions[port_index].port_width = ((16 + 7) >> 3);
port_descriptions[port_index].port_width_in_bits = 16;
port_descriptions[port_index].protocol_name = "generic";
port_descriptions[port_index].ipxactBusDef.vendor = "Mentor.com";
port_descriptions[port_index].ipxactBusDef.library = "Lib_ipxact";
port_descriptions[port_index].ipxactBusDef.name = "generic";
port_descriptions[port_index].ipxactBusDef.version = "1.0";
port_descriptions[port_index].ipxactAbstrDef.vendor = "Mentor.com";
port_descriptions[port_index].ipxactAbstrDef.library = "Lib_ipxact";
port_descriptions[port_index].ipxactAbstrDef.name = "generic_tlm20";
port_descriptions[port_index].ipxactAbstrDef.version = "1.0";
port_descriptions[port_index].port_must_bind = 1;
port_descriptions[port_index].params_count = 6 + 10;
port_descriptions[port_index].clock = generic_clock;
port_descriptions[port_index].add_read_phase(tlm::tlm_phase(tlm::BEGIN_REQ), !0, 1);
port_descriptions[port_index].add_read_phase(tlm::tlm_phase(tlm::BEGIN_RESP), !1, 1);
port_descriptions[Slave].default_read_transaction_name = "READ";
port_descriptions[Slave].default_write_transaction_name = "WRITE";
fix_internal_clock_parameter(clock, "clock");
set_ports(mb::sysc::sc_time_to_ps(clock), port_count, port_descriptions);
bool isCpu = false;
esl::tlm_sim::UserRunningModel* userRunningModel = Papoulis_CreateUserRunningModel(name(),
0,
this,
simulation,
false,
isCpu);
setUserRunningModel(userRunningModel, isCpu);
set_nominal_voltage(nominal_voltage);
registerParameter("clock", "sc_core::sc_time", sdGetParameterAsConstString("clock"));
registerParameter("generic_clock", "sc_core::sc_time", sdGetParameterAsConstString("generic_clock"));
registerParameter("nominal_voltage", "double", sdGetParameterAsConstString("nominal_voltage"));
registerParameter("mb_debug", "bool", sdGetParameterAsConstString("mb_debug"));
registerParameter("call_to_default_if", "bool", sdGetParameterAsConstString("call_to_default_if"));
registerParameter("verbose_parameters", "bool", sdGetParameterAsConstString("verbose_parameters"));
registerParameter("dmi_enabled", "bool", sdGetParameterAsConstString("dmi_enabled"));
registerParameter("warning_level", "const char*", sdGetParameterAsConstString("warning_level"));
registerParameter("Slave_pipeline_length", "unsigned int", sdGetParameterAsConstString("Slave_pipeline_length"));
registerParameter("Max", "unsigned int", sdGetParameterAsConstString("Max"));
registerParameter("Min", "unsigned int", sdGetParameterAsConstString("Min"));
registerParameter("Period", "sc_core::sc_time", sdGetParameterAsConstString("Period"));
registerParameter("Type", "const char*", sdGetParameterAsConstString("Type"));
set_sync_all(0);
set_sync_all(0);
delay_policy* delay_policy_handle = 0;
for (unsigned u = 0; u < 1; u++) {
unsigned port_index = Slave + u;
std::string str = std::string(port_descriptions[port_index].port_name);
delay_policy_handle = new delay_policy(userRunningModel,
str.c_str(),
0,
0,
mb::tlm20::SYNC_BEGIN);
delay_policy_handle->set_power(0);
m_delay_vector.push_back(delay_policy_handle);
}
constant_global_power_policy* p = new constant_global_power_policy(userRunningModel);
set_nominal_clock(1000000/100); /* in ps */
update_coefficients();
set_global_power_policy(p);
}
void WaveSampleGenerator_t_base::update_sync_all() {
set_sync_all(0);
set_sync_all(0);
}
void WaveSampleGenerator_t_base::update_pipeline_parameters(esl::sc_sim::pipeline_policy* handle) {
if (m_pipeline_vector.size() == 0)
return;
}
void WaveSampleGenerator_t_base::update_sequential_parameters(esl::sc_sim::sequential_policy* handle) {
if (m_sequential_vector.size() == 0)
return;
}
void WaveSampleGenerator_t_base::update_delay_parameters(esl::sc_sim::delay_policy* handle) {
if (m_delay_vector.size() == 0)
return;
if (handle == m_delay_vector[0]) {
handle->set_inner_delay(0);
handle->set_start_delay(0);
handle->setSyncMode(mb::tlm20::SYNC_BEGIN);
handle->set_power(0);
return;
}
}
void WaveSampleGenerator_t_base::update_bus_parameters(esl::sc_sim::uniform_bus_policy* handle) {
if (m_bus_vector.size() == 0)
return;
}
void WaveSampleGenerator_t_base::update_power_parameters(esl::sc_sim::power_policy* handle) {
if (m_power_vector.size() == 0)
return;
}
void WaveSampleGenerator_t_base::update_state_power_parameters(esl::sc_sim::state_power_policy* handle) {
if (m_state_power_vector.size() == 0)
return;
}
void WaveSampleGenerator_t_base::update_global_power_parameters(esl::sc_sim::constant_global_power_policy* handle) {
return;
}
bool WaveSampleGenerator_t_base::triggerRegistersGotHit(unsigned portIndex, tlm::tlm_generic_payload& trans) {
mb::utl::Segment<uint64_t> transactionRange(trans.get_address(), trans.get_address() + trans.get_data_length());
return false;
}
bool WaveSampleGenerator_t_base::portHasRegisters(unsigned portIndex) {
switch (portIndex) {
}
return false;
}
/**************************************************************/
/* */
/* Copyright Mentor Graphics Corporation 2006 - 2015 */
/* All Rights Reserved */
/* */
/* THIS WORK CONTAINS TRADE SECRET AND PROPRIETARY */
/* INFORMATION WHICH IS THE PROPERTY OF MENTOR */
/* GRAPHICS CORPORATION OR ITS LICENSORS AND IS */
/* SUBJECT TO LICENSE TERMS. */
/* */
/**************************************************************/
//*<
//* Generated By Model Builder, Mentor Graphics Computer Systems, Inc.
//*
//* This file is write protected.
//* DO NOT MODIFY THIS FILE.
//*
//* This file contains the PVT class for WaveSampleGenerator.
//* It connects between the PV and T models.
//* Your top-level design should instantiate this model.
//*
//* In order to synchronize the activty between the PV and the T models, every
//* PV transaction is monitored and queued in the T sync ports.
//* Whenever a synchronization point is reached, the T models are executed and
//* the corresponding T transactions are launched.
//* A synchronization point is reached whenever there is a wait statement on a testbench thread.
//*
//* Model Builder version: 4.2.1
//* Generated on: Aug. 15, 2016 06:02:58 PM, (user: kenm)
//*>
#include "WaveSampleGenerator_model.h"
using namespace std;
using namespace sc_core;
using namespace sc_dt;
#include "WaveSampleGenerator_pv.h"
// Constructor
WaveSampleGenerator_pvt::WaveSampleGenerator_pvt(sc_module_name module_name)
: esl::sc_sim::PVTBaseModel(module_name, 0),
WaveSampleGenerator_pvt_param_defaults(this->name()),
Slave("Slave"),
Slave_entry("unvisible_Slave_entry"),
m_Slave_nb_connector(*this)
{
// Slave - not a vector port
m_WaveSampleGenerator_t = WaveSampleGenerator_t_base::create_t("T", 1);
m_WaveSampleGenerator_pv = new WaveSampleGenerator_pv("PV");
bind();
}
WaveSampleGenerator_pvt::WaveSampleGenerator_pvt(sc_module_name module_name, sc_core::sc_time clock_init, sc_core::sc_time generic_clock_init, double nominal_voltage_init, bool mb_debug_init, bool call_to_default_if_init, bool verbose_parameters_init, bool dmi_enabled_init, const char* warning_level_init, unsigned int Slave_pipeline_length_init, unsigned int Max_init, unsigned int Min_init, sc_core::sc_time Period_init, const char* Type_init)
: esl::sc_sim::PVTBaseModel(module_name, 0),
WaveSampleGenerator_pvt_param_defaults(this->name(), clock_init, generic_clock_init, nominal_voltage_init, mb_debug_init, call_to_default_if_init, verbose_parameters_init, dmi_enabled_init, warning_level_init, Slave_pipeline_length_init, Max_init, Min_init, Period_init, Type_init),
Slave("Slave"),
Slave_entry("unvisible_Slave_entry"),
m_Slave_nb_connector(*this)
{
// Slave - not a vector port
m_WaveSampleGenerator_t = WaveSampleGenerator_t_base::create_t("T", 1);
m_WaveSampleGenerator_pv = new WaveSampleGenerator_pv("PV");
bind();
}
WaveSampleGenerator_pvt::WaveSampleGenerator_pvt(sc_module_name module_name, std::vector<std::pair<char*, unsigned int> > &change_parameters)
: esl::sc_sim::PVTBaseModel(module_name, 0),
WaveSampleGenerator_pvt_param_defaults(this->name(), change_parameters),
Slave("Slave"),
Slave_entry("unvisible_Slave_entry"),
m_Slave_nb_connector(*this)
{
// Slave - not a vector port
m_WaveSampleGenerator_t = WaveSampleGenerator_t_base::create_t("T", 1);
m_WaveSampleGenerator_pv = new WaveSampleGenerator_pv("PV");
bind();
}
WaveSampleGenerator_pvt::~WaveSampleGenerator_pvt() {
remove_pending_scenes();
delete m_WaveSampleGenerator_t; delete m_WaveSampleGenerator_pv;
}
void WaveSampleGenerator_pvt::bind()
{
/* connect pv to entry ports */
Slave_entry.bind(getPV()->Slave);
/* set callbacks on external and entry ports */
Slave.b_transport_cb.set(&Slave_entry, &Slave_entry_type::b_transport);
Slave.transport_dbg_cb.set(&Slave_entry, &Slave_entry_type::transport_dbg);
Slave.get_direct_mem_ptr_cb.set(&Slave_entry, &Slave_entry_type::get_direct_mem_ptr);
/* connect t non blocking callbacks */
Slave.nb_transport_fw_cb.set(this, &self_type::receive_nb_transport_Slave);
getT()->set_port_cb(0, &m_Slave_nb_connector);
Slave_entry.invalidate_direct_mem_ptr_cb.set(&Slave, &Slave_type::invalidate_direct_mem_ptr);
/* check mb_event policies */
m_WaveSampleGenerator_t->check_mb_events();
}
|
// generated from rosidl_generator_cpp/resource/msg__struct.hpp.em
// generated code does not contain a copyright notice
#ifndef TEST_MSGS__MSG__STATIC_ARRAY_PRIMITIVES__STRUCT_HPP_
#define TEST_MSGS__MSG__STATIC_ARRAY_PRIMITIVES__STRUCT_HPP_
// Protect against ERROR being predefined on Windows, in case somebody defines a
// constant by that name.
#if defined(_WIN32) && defined(ERROR)
#undef ERROR
#endif
#include <rosidl_generator_cpp/bounded_vector.hpp>
#include <rosidl_generator_cpp/message_initialization.hpp>
#include <algorithm>
#include <array>
#include <memory>
#include <string>
#include <vector>
// include message dependencies
#ifndef _WIN32
# define DEPRECATED_test_msgs_msg_StaticArrayPrimitives __attribute__((deprecated))
#else
# define DEPRECATED_test_msgs_msg_StaticArrayPrimitives __declspec(deprecated)
#endif
namespace test_msgs
{
namespace msg
{
// message struct
template<class ContainerAllocator>
struct StaticArrayPrimitives_
{
using Type = StaticArrayPrimitives_<ContainerAllocator>;
explicit StaticArrayPrimitives_(rosidl_generator_cpp::MessageInitialization _init = rosidl_generator_cpp::MessageInitialization::ALL)
{
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->bool_values.begin(), this->bool_values.end(), false);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->byte_values.begin(), this->byte_values.end(), 0);
std::fill(this->char_values.begin(), this->char_values.end(), 0);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->float32_values.begin(), this->float32_values.end(), 0.0f);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->float64_values.begin(), this->float64_values.end(), 0.0);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->int8_values.begin(), this->int8_values.end(), 0);
std::fill(this->uint8_values.begin(), this->uint8_values.end(), 0);
std::fill(this->int16_values.begin(), this->int16_values.end(), 0);
std::fill(this->uint16_values.begin(), this->uint16_values.end(), 0);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->int32_values.begin(), this->int32_values.end(), 0l);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->uint32_values.begin(), this->uint32_values.end(), 0ul);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->int64_values.begin(), this->int64_values.end(), 0ll);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->uint64_values.begin(), this->uint64_values.end(), 0ull);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->string_values.begin(), this->string_values.end(), "");
}
}
explicit StaticArrayPrimitives_(const ContainerAllocator & _alloc, rosidl_generator_cpp::MessageInitialization _init = rosidl_generator_cpp::MessageInitialization::ALL)
: bool_values(_alloc),
byte_values(_alloc),
char_values(_alloc),
float32_values(_alloc),
float64_values(_alloc),
int8_values(_alloc),
uint8_values(_alloc),
int16_values(_alloc),
uint16_values(_alloc),
int32_values(_alloc),
uint32_values(_alloc),
int64_values(_alloc),
uint64_values(_alloc),
string_values(_alloc)
{
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->bool_values.begin(), this->bool_values.end(), false);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->byte_values.begin(), this->byte_values.end(), 0);
std::fill(this->char_values.begin(), this->char_values.end(), 0);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->float32_values.begin(), this->float32_values.end(), 0.0f);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->float64_values.begin(), this->float64_values.end(), 0.0);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->int8_values.begin(), this->int8_values.end(), 0);
std::fill(this->uint8_values.begin(), this->uint8_values.end(), 0);
std::fill(this->int16_values.begin(), this->int16_values.end(), 0);
std::fill(this->uint16_values.begin(), this->uint16_values.end(), 0);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->int32_values.begin(), this->int32_values.end(), 0l);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->uint32_values.begin(), this->uint32_values.end(), 0ul);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->int64_values.begin(), this->int64_values.end(), 0ll);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->uint64_values.begin(), this->uint64_values.end(), 0ull);
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
std::fill(this->string_values.begin(), this->string_values.end(), "");
}
}
// field types and members
using _bool_values_type =
std::array<bool, 3>;
_bool_values_type bool_values;
using _byte_values_type =
std::array<uint8_t, 3>;
_byte_values_type byte_values;
using _char_values_type =
std::array<char, 3>;
_char_values_type char_values;
using _float32_values_type =
std::array<float, 3>;
_float32_values_type float32_values;
using _float64_values_type =
std::array<double, 3>;
_float64_values_type float64_values;
using _int8_values_type =
std::array<int8_t, 3>;
_int8_values_type int8_values;
using _uint8_values_type =
std::array<uint8_t, 3>;
_uint8_values_type uint8_values;
using _int16_values_type =
std::array<int16_t, 3>;
_int16_values_type int16_values;
using _uint16_values_type =
std::array<uint16_t, 3>;
_uint16_values_type uint16_values;
using _int32_values_type =
std::array<int32_t, 3>;
_int32_values_type int32_values;
using _uint32_values_type =
std::array<uint32_t, 3>;
_uint32_values_type uint32_values;
using _int64_values_type =
std::array<int64_t, 3>;
_int64_values_type int64_values;
using _uint64_values_type =
std::array<uint64_t, 3>;
_uint64_values_type uint64_values;
using _string_values_type =
std::array<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>, 3>;
_string_values_type string_values;
// setters for named parameter idiom
Type * set__bool_values(
const std::array<bool, 3> & _arg)
{
this->bool_values = _arg;
return this;
}
Type * set__byte_values(
const std::array<uint8_t, 3> & _arg)
{
this->byte_values = _arg;
return this;
}
Type * set__char_values(
const std::array<char, 3> & _arg)
{
this->char_values = _arg;
return this;
}
Type * set__float32_values(
const std::array<float, 3> & _arg)
{
this->float32_values = _arg;
return this;
}
Type * set__float64_values(
const std::array<double, 3> & _arg)
{
this->float64_values = _arg;
return this;
}
Type * set__int8_values(
const std::array<int8_t, 3> & _arg)
{
this->int8_values = _arg;
return this;
}
Type * set__uint8_values(
const std::array<uint8_t, 3> & _arg)
{
this->uint8_values = _arg;
return this;
}
Type * set__int16_values(
const std::array<int16_t, 3> & _arg)
{
this->int16_values = _arg;
return this;
}
Type * set__uint16_values(
const std::array<uint16_t, 3> & _arg)
{
this->uint16_values = _arg;
return this;
}
Type * set__int32_values(
const std::array<int32_t, 3> & _arg)
{
this->int32_values = _arg;
return this;
}
Type * set__uint32_values(
const std::array<uint32_t, 3> & _arg)
{
this->uint32_values = _arg;
return this;
}
Type * set__int64_values(
const std::array<int64_t, 3> & _arg)
{
this->int64_values = _arg;
return this;
}
Type * set__uint64_values(
const std::array<uint64_t, 3> & _arg)
{
this->uint64_values = _arg;
return this;
}
Type * set__string_values(
const std::array<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>, 3> & _arg)
{
this->string_values = _arg;
return this;
}
// constant declarations
// pointer types
using RawPtr =
test_msgs::msg::StaticArrayPrimitives_<ContainerAllocator> *;
using ConstRawPtr =
const test_msgs::msg::StaticArrayPrimitives_<ContainerAllocator> *;
using SharedPtr =
std::shared_ptr<test_msgs::msg::StaticArrayPrimitives_<ContainerAllocator>>;
using ConstSharedPtr =
std::shared_ptr<test_msgs::msg::StaticArrayPrimitives_<ContainerAllocator> const>;
template<typename Deleter = std::default_delete<
test_msgs::msg::StaticArrayPrimitives_<ContainerAllocator>>>
using UniquePtrWithDeleter =
std::unique_ptr<test_msgs::msg::StaticArrayPrimitives_<ContainerAllocator>, Deleter>;
using UniquePtr = UniquePtrWithDeleter<>;
template<typename Deleter = std::default_delete<
test_msgs::msg::StaticArrayPrimitives_<ContainerAllocator>>>
using ConstUniquePtrWithDeleter =
std::unique_ptr<test_msgs::msg::StaticArrayPrimitives_<ContainerAllocator> const, Deleter>;
using ConstUniquePtr = ConstUniquePtrWithDeleter<>;
using WeakPtr =
std::weak_ptr<test_msgs::msg::StaticArrayPrimitives_<ContainerAllocator>>;
using ConstWeakPtr =
std::weak_ptr<test_msgs::msg::StaticArrayPrimitives_<ContainerAllocator> const>;
// pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead
// NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly
typedef DEPRECATED_test_msgs_msg_StaticArrayPrimitives
std::shared_ptr<test_msgs::msg::StaticArrayPrimitives_<ContainerAllocator>>
Ptr;
typedef DEPRECATED_test_msgs_msg_StaticArrayPrimitives
std::shared_ptr<test_msgs::msg::StaticArrayPrimitives_<ContainerAllocator> const>
ConstPtr;
// comparison operators
bool operator==(const StaticArrayPrimitives_ & other) const
{
if (this->bool_values != other.bool_values) {
return false;
}
if (this->byte_values != other.byte_values) {
return false;
}
if (this->char_values != other.char_values) {
return false;
}
if (this->float32_values != other.float32_values) {
return false;
}
if (this->float64_values != other.float64_values) {
return false;
}
if (this->int8_values != other.int8_values) {
return false;
}
if (this->uint8_values != other.uint8_values) {
return false;
}
if (this->int16_values != other.int16_values) {
return false;
}
if (this->uint16_values != other.uint16_values) {
return false;
}
if (this->int32_values != other.int32_values) {
return false;
}
if (this->uint32_values != other.uint32_values) {
return false;
}
if (this->int64_values != other.int64_values) {
return false;
}
if (this->uint64_values != other.uint64_values) {
return false;
}
if (this->string_values != other.string_values) {
return false;
}
return true;
}
bool operator!=(const StaticArrayPrimitives_ & other) const
{
return !this->operator==(other);
}
}; // struct StaticArrayPrimitives_
// alias to use template instance with default allocator
using StaticArrayPrimitives =
test_msgs::msg::StaticArrayPrimitives_<std::allocator<void>>;
// constant definitions
} // namespace msg
} // namespace test_msgs
#endif // TEST_MSGS__MSG__STATIC_ARRAY_PRIMITIVES__STRUCT_HPP_
|
// Copyright (c) 2012-2018 The Pyeongtaekcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <streams.h>
#include <support/allocators/zeroafterfree.h>
#include <test/test_pyeongtaekcoin.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(streams_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(streams_vector_writer)
{
unsigned char a(1);
unsigned char b(2);
unsigned char bytes[] = { 3, 4, 5, 6 };
std::vector<unsigned char> vch;
// Each test runs twice. Serializing a second time at the same starting
// point should yield the same results, even if the first test grew the
// vector.
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 0, a, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{1, 2}}));
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 0, a, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{1, 2}}));
vch.clear();
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 2, a, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 1, 2}}));
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 2, a, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 1, 2}}));
vch.clear();
vch.resize(5, 0);
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 2, a, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 1, 2, 0}}));
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 2, a, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 1, 2, 0}}));
vch.clear();
vch.resize(4, 0);
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 3, a, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 0, 1, 2}}));
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 3, a, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 0, 1, 2}}));
vch.clear();
vch.resize(4, 0);
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 4, a, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 0, 0, 1, 2}}));
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 4, a, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 0, 0, 1, 2}}));
vch.clear();
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 0, bytes);
BOOST_CHECK((vch == std::vector<unsigned char>{{3, 4, 5, 6}}));
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 0, bytes);
BOOST_CHECK((vch == std::vector<unsigned char>{{3, 4, 5, 6}}));
vch.clear();
vch.resize(4, 8);
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 2, a, bytes, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{8, 8, 1, 3, 4, 5, 6, 2}}));
CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 2, a, bytes, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{8, 8, 1, 3, 4, 5, 6, 2}}));
vch.clear();
}
BOOST_AUTO_TEST_CASE(streams_vector_reader)
{
std::vector<unsigned char> vch = {1, 255, 3, 4, 5, 6};
VectorReader reader(SER_NETWORK, INIT_PROTO_VERSION, vch, 0);
BOOST_CHECK_EQUAL(reader.size(), 6);
BOOST_CHECK(!reader.empty());
// Read a single byte as an unsigned char.
unsigned char a;
reader >> a;
BOOST_CHECK_EQUAL(a, 1);
BOOST_CHECK_EQUAL(reader.size(), 5);
BOOST_CHECK(!reader.empty());
// Read a single byte as a signed char.
signed char b;
reader >> b;
BOOST_CHECK_EQUAL(b, -1);
BOOST_CHECK_EQUAL(reader.size(), 4);
BOOST_CHECK(!reader.empty());
// Read a 4 bytes as an unsigned int.
unsigned int c;
reader >> c;
BOOST_CHECK_EQUAL(c, 100992003); // 3,4,5,6 in little-endian base-256
BOOST_CHECK_EQUAL(reader.size(), 0);
BOOST_CHECK(reader.empty());
// Reading after end of byte vector throws an error.
signed int d;
BOOST_CHECK_THROW(reader >> d, std::ios_base::failure);
// Read a 4 bytes as a signed int from the beginning of the buffer.
VectorReader new_reader(SER_NETWORK, INIT_PROTO_VERSION, vch, 0);
new_reader >> d;
BOOST_CHECK_EQUAL(d, 67370753); // 1,255,3,4 in little-endian base-256
BOOST_CHECK_EQUAL(new_reader.size(), 2);
BOOST_CHECK(!new_reader.empty());
// Reading after end of byte vector throws an error even if the reader is
// not totally empty.
BOOST_CHECK_THROW(new_reader >> d, std::ios_base::failure);
}
BOOST_AUTO_TEST_CASE(bitstream_reader_writer)
{
CDataStream data(SER_NETWORK, INIT_PROTO_VERSION);
BitStreamWriter<CDataStream> bit_writer(data);
bit_writer.Write(0, 1);
bit_writer.Write(2, 2);
bit_writer.Write(6, 3);
bit_writer.Write(11, 4);
bit_writer.Write(1, 5);
bit_writer.Write(32, 6);
bit_writer.Write(7, 7);
bit_writer.Write(30497, 16);
bit_writer.Flush();
CDataStream data_copy(data);
uint32_t serialized_int1;
data >> serialized_int1;
BOOST_CHECK_EQUAL(serialized_int1, (uint32_t)0x7700C35A); // NOTE: Serialized as LE
uint16_t serialized_int2;
data >> serialized_int2;
BOOST_CHECK_EQUAL(serialized_int2, (uint16_t)0x1072); // NOTE: Serialized as LE
BitStreamReader<CDataStream> bit_reader(data_copy);
BOOST_CHECK_EQUAL(bit_reader.Read(1), 0);
BOOST_CHECK_EQUAL(bit_reader.Read(2), 2);
BOOST_CHECK_EQUAL(bit_reader.Read(3), 6);
BOOST_CHECK_EQUAL(bit_reader.Read(4), 11);
BOOST_CHECK_EQUAL(bit_reader.Read(5), 1);
BOOST_CHECK_EQUAL(bit_reader.Read(6), 32);
BOOST_CHECK_EQUAL(bit_reader.Read(7), 7);
BOOST_CHECK_EQUAL(bit_reader.Read(16), 30497);
BOOST_CHECK_THROW(bit_reader.Read(8), std::ios_base::failure);
}
BOOST_AUTO_TEST_CASE(streams_serializedata_xor)
{
std::vector<char> in;
std::vector<char> expected_xor;
std::vector<unsigned char> key;
CDataStream ds(in, 0, 0);
// Degenerate case
key.push_back('\x00');
key.push_back('\x00');
ds.Xor(key);
BOOST_CHECK_EQUAL(
std::string(expected_xor.begin(), expected_xor.end()),
std::string(ds.begin(), ds.end()));
in.push_back('\x0f');
in.push_back('\xf0');
expected_xor.push_back('\xf0');
expected_xor.push_back('\x0f');
// Single character key
ds.clear();
ds.insert(ds.begin(), in.begin(), in.end());
key.clear();
key.push_back('\xff');
ds.Xor(key);
BOOST_CHECK_EQUAL(
std::string(expected_xor.begin(), expected_xor.end()),
std::string(ds.begin(), ds.end()));
// Multi character key
in.clear();
expected_xor.clear();
in.push_back('\xf0');
in.push_back('\x0f');
expected_xor.push_back('\x0f');
expected_xor.push_back('\x00');
ds.clear();
ds.insert(ds.begin(), in.begin(), in.end());
key.clear();
key.push_back('\xff');
key.push_back('\x0f');
ds.Xor(key);
BOOST_CHECK_EQUAL(
std::string(expected_xor.begin(), expected_xor.end()),
std::string(ds.begin(), ds.end()));
}
BOOST_AUTO_TEST_SUITE_END()
|
/* R E N D E R _ S V C . C P P
* BRL-CAD
*
* Copyright (c) 2012-2016 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
#include "render_svc.h"
using namespace OSL;
#ifdef OSL_NAMESPACE
namespace OSL_NAMESPACE {
#endif
namespace OSL {
bool
SimpleRenderer::get_matrix (Matrix44 &result, TransformationPtr xform,
float time)
{
// SimpleRenderer doesn't understand motion blur and transformations
// are just simple 4x4 matrices.
result = *(OSL::Matrix44 *)xform;
return true;
}
bool
SimpleRenderer::get_matrix (Matrix44 &result, ustring from, float time)
{
TransformMap::const_iterator found = m_named_xforms.find (from);
if (found != m_named_xforms.end()) {
result = *(found->second);
return true;
} else {
return false;
}
}
bool
SimpleRenderer::get_matrix (Matrix44 &result, TransformationPtr xform)
{
// SimpleRenderer doesn't understand motion blur and transformations
// are just simple 4x4 matrices.
result = *(OSL::Matrix44 *)xform;
return true;
}
bool
SimpleRenderer::get_matrix (Matrix44 &result, ustring from)
{
// SimpleRenderer doesn't understand motion blur, so we never fail
// on account of time-varying transformations.
TransformMap::const_iterator found = m_named_xforms.find (from);
if (found != m_named_xforms.end()) {
result = *(found->second);
return true;
} else {
return false;
}
}
void
SimpleRenderer::name_transform (const char *name, const OSL::Matrix44 &xform)
{
shared_ptr<Transformation> M (new OSL::Matrix44 (xform));
m_named_xforms[ustring(name)] = M;
}
bool
SimpleRenderer::get_array_attribute (void *renderstate, bool derivatives, ustring object,
TypeDesc type, ustring name,
int index, void *val)
{
return false;
}
bool
SimpleRenderer::get_attribute (void *renderstate, bool derivatives, ustring object,
TypeDesc type, ustring name, void *val)
{
return false;
}
bool
SimpleRenderer::get_userdata (bool derivatives, ustring name, TypeDesc type, void *renderstate, void *val)
{
return false;
}
bool
SimpleRenderer::has_userdata (ustring name, TypeDesc type, void *renderstate)
{
return false;
}
void *
SimpleRenderer::get_pointcloud_attr_query (ustring *attr_names,
TypeDesc *attr_types, int nattrs)
{
return NULL;
}
int
SimpleRenderer::pointcloud (ustring filename, const OSL::Vec3 ¢er, float radius,
int max_points, void *_attr_query, void **attr_outdata)
{
return 0;
}
int
SimpleRenderer::pointcloud_search (ustring filename, const OSL::Vec3 ¢er,
float radius, int max_points, size_t *out_indices,
float *out_distances, int derivs_offset)
{
return 0;
}
int
SimpleRenderer::pointcloud_get (ustring filename, size_t *indices, int count,
ustring attr_name, TypeDesc attr_type,
void *out_data)
{
return 0;
}
}; // namespace OSL
#ifdef OSL_NAMESPACE
}; // end namespace OSL_NAMESPACE
#endif
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
|
/**
* Tencent is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 "CommandLoad.h"
#include "RegistryProxy.h"
std::mutex CommandLoad::_mutex;
set<int> CommandLoad::_allPorts;
//////////////////////////////////////////////////////////////
//
ServerCommand::ExeStatus CommandLoad::canExecute(string& sResult)
{
TC_ThreadRecLock::Lock lock(*_serverObjectPtr);
NODE_LOG("KeepAliveThread")->debug() << "CommandLoad::canExecute " << _desc.application << "." << _desc.serverName << "|" << _desc.setId << "| beging loaded------|" << endl;
ServerObject::InternalServerState eState = _serverObjectPtr->getInternalState();
if (_desc.application == "" || _desc.serverName == "")
{
NODE_LOG("KeepAliveThread")->debug() << "CommandLoad::canExecute app or server name is empty"<< endl;
return DIS_EXECUTABLE;
}
if (_serverObjectPtr->toStringState(eState).find("ing") != string::npos && eState != ServerObject::Activating)
{
NODE_LOG("KeepAliveThread")->debug() << "CommandLoad::canExecute cannot loading the config, the server state is "<<_serverObjectPtr->toStringState(eState)<< endl;
return DIS_EXECUTABLE;
}
//设当前状态为正在loading
// _statExChange = new StatExChange(_serverObjectPtr, ServerObject::Loading, eState);
return EXECUTABLE;
}
//////////////////////////////////////////////////////////////
//
int CommandLoad::execute(string& sResult)
{
//初始化服务目录信息
_serverDir = TC_Common::trim(_desc.basePath);
_exePath = TC_Common::trim(_desc.exePath);
_serverType = TC_Common::lower(TC_Common::trim(_desc.serverType));
//若serverDir不合法采用默认路径
if (_serverDir.empty() || TC_File::isAbsolute(_serverDir) == false)
{
_serverDir = TC_File::simplifyDirectory(_nodeInfo.dataDir + FILE_SEP + _desc.application + "." + _desc.serverName);
}
//获取服务框架配置文件
_confPath = _serverDir + FILE_SEP + "conf" + FILE_SEP;
_confFile = _confPath + _desc.application + "." + _desc.serverName + ".config.conf";
//若exePath不合法采用默认路径
//注意java服务启动方式特殊 可执行文件为java 须特殊处理
if (_exePath.empty())
{
_exePath = _serverDir + FILE_SEP + "bin" + FILE_SEP;
if (_serverType == "tars_java")
{
try
{
TC_Config conf;
conf.parseString(_desc.profile);
_exeFile = conf.get("/tars/application/server<java>", "java");
}
catch(exception &ex)
{
NODE_LOG("KeepAliveThread")->error() << "parse template error:" << ex.what() << endl;
_exeFile = "java";
}
}
else if (_serverType == "tars_node")
{
try
{
TC_Config conf;
conf.parseFile(_desc.profile);
_exeFile = conf.get("/tars/application/server<nodejs>", "node");
}
catch(exception &ex)
{
NODE_LOG("KeepAliveThread")->error() << "parse template error:" << ex.what() << endl;
_exeFile = "node";
}
}
else if(_serverType == "tars_php")
{
try
{
TC_Config conf;
conf.parseFile(_desc.profile);
_exeFile = conf.get("/tars/application/server<php>", "php");
}
catch(exception &ex)
{
NODE_LOG("KeepAliveThread")->error() << "parse template error:" << ex.what() << endl;
_exeFile = "php";
}
}
else
{
_exeFile = _exePath + _desc.serverName;
}
}
else if (TC_File::isAbsolute(_exePath) == false)
{
//此时_desc.exePath为手工指定,手工指定时_desc.exePath为文件 所以路径要扣除可执行文件名
//而且可执行文件名可以不等于_strServerName 用来用同一可执行文件,不同配置启动多个服务
_exeFile = _serverDir + FILE_SEP + "bin" + FILE_SEP + _exePath;
_exePath = TC_File::extractFilePath(_exeFile);
}
else
{
//此时_desc.exePath为手工指定,手工指定时_desc.exePath为文件 所以路径要扣除可执行文件名
//而且可执行文件名可以不等于_strServerName 用来用同一可执行文件,不同配置启动多个服务
_exeFile = _desc.exePath;
_exePath = _serverType == "tars_java" ? _serverDir + FILE_SEP + "bin" + FILE_SEP : TC_File::extractFilePath(_desc.exePath);
}
_exeFile = TC_File::simplifyDirectory(_exeFile);
_exePath = TC_File::simplifyDirectory(_exePath) + FILE_SEP;
//启动脚本处理
_startScript = TC_Common::trim(_desc.startScript);
if (!_startScript.empty() && TC_File::isAbsolute(_startScript) == false)
{
_startScript = _exePath + _startScript;
}
//停止脚本处理
_stopScript = TC_Common::trim(_desc.stopScript);
if (!_stopScript.empty() && TC_File::isAbsolute(_stopScript) == false)
{
_stopScript = _exePath + _stopScript;
}
//监控脚本处理
_monitorScript = TC_Common::trim(_desc.monitorScript);
if (!_monitorScript.empty() && TC_File::isAbsolute(_monitorScript) == false)
{
_monitorScript = _exePath + _monitorScript;
}
_startScript = TC_File::simplifyDirectory(_startScript);
_stopScript = TC_File::simplifyDirectory(_stopScript);
_monitorScript = TC_File::simplifyDirectory(_monitorScript);
//创建配置lib文件目录
_libPath = _nodeInfo.dataDir + FILE_SEP + "lib" + FILE_SEP;
NODE_LOG("KeepAliveThread")->debug() << "CommandLoad::execute"<< _serverType << ","
<< "exe_path=" << _exePath << ","
<< "exe_file=" << _exeFile << ","
<< "start_script=" << _startScript << ","
<< "stop_script=" << _stopScript << ","
<< "monitor_script="<< _monitorScript<< ","
<< "config_file=" << _confFile << endl;
//创建目录
if (!TC_File::makeDirRecursive(_exePath))
{
NODE_LOG("KeepAliveThread")->error() << "CommandLoad::execute cannot create dir: "<<(_exePath + " erro:" + strerror(errno))<<endl;
return -1;
}
if (!TC_File::makeDirRecursive(_libPath))
{
NODE_LOG("KeepAliveThread")->error() << "CommandLoad::execute cannot create dir: "<<(_libPath + " erro:" + strerror(errno))<<endl;
return -1;
}
if (!TC_File::makeDirRecursive(_confPath))
{
NODE_LOG("KeepAliveThread")->error() << "CommandLoad::execute cannot create dir: "<<(_confPath + " erro:" + strerror(errno))<<endl;
return -1;
}
if (updateConfigFile(sResult) != 0)
{
NODE_LOG("KeepAliveThread")->error() << "CommandLoad::execute update config error"<<endl;
return -1;
}
if(_succ)
{
getRemoteConf();
}
return 0;
}
int CommandLoad::updateConfigFile(string& sResult)
{
try
{
//node根据server desc生成配置。
TC_Config tConf;
TC_Endpoint tEp;
map<string, string> m;
m["node"] = ServerConfig::Application + "." + ServerConfig::ServerName + ".ServerObj@" + g_app.getAdapterEndpoint("ServerAdapter").toString();
tConf.insertDomainParam("/tars/application/server", m, true);
m.clear();
map<string, AdapterDescriptor>::const_reverse_iterator itAdapters;
for (itAdapters = _desc.adapters.rbegin(); itAdapters != _desc.adapters.rend(); itAdapters++)
{
NODE_LOG("KeepAliveThread")->debug() << "CommandLoad::updateConfigFile get adapter " << itAdapters->first << endl;
if (itAdapters->first == "")
{
continue;
}
tEp.parse(itAdapters->second.endpoint);
{
std::lock_guard<std::mutex> lock(_mutex);
_allPorts.insert(tEp.getPort());
}
m["endpoint"] = tEp.toString();
m["allow"] = itAdapters->second.allowIp;
m["queuecap"] = TC_Common::tostr(itAdapters->second.queuecap);
m["queuetimeout"] = TC_Common::tostr(itAdapters->second.queuetimeout);
m["maxconns"] = TC_Common::tostr(itAdapters->second.maxConnections);
m["threads"] = TC_Common::tostr(itAdapters->second.threadNum);
m["servant"] = TC_Common::tostr(itAdapters->second.servant);
m["protocol"] = itAdapters->second.protocol == "" ? "tars" : itAdapters->second.protocol;
// m["handlegroup"] = itAdapters->second.handlegroup == "" ? itAdapters->first : itAdapters->second.handlegroup;
tConf.insertDomainParam("/tars/application/server/" + itAdapters->first, m, true);
}
//获取本地socket
uint16_t p = tEp.getPort();
TC_Endpoint tLocalEndpoint;
try
{
//原始配置文件中有admin端口了, 直接使用
TC_Config conf;
conf.parseFile(_confFile);
TC_Endpoint ep;
ep.parse(conf.get("/tars/application/server<local>"));
p = ep.getPort();
}
catch(const std::exception& e)
{
//随机分配不冲突的端口
for (;;)
{
p = 30000 + rand() % 15000;
TC_Socket s;
s.createSocket(SOCK_STREAM, AF_INET);
int ret = s.connectNoThrow("127.0.0.1", p);
if(ret != 0 && _allPorts.find(p) == _allPorts.end())
{
//端口无法连接且之前没用过, 则使用之
break;
}
}
}
{
std::lock_guard<std::mutex> lock(_mutex);
_allPorts.insert(tEp.getPort());
}
// uint16_t p = tEp.getPort();
// if (p == 0)
// {
// try
// {
// //原始配置文件中有admin端口了, 直接使用
// TC_Config conf;
// conf.parseFile(_confFile);
// TC_Endpoint ep;
// ep.parse(conf.get("/tars/application/server<local>"));
// p = ep.getPort();
// }
// catch (exception& ex)
// {
// //随机分配一个端口
// TC_Socket t;
// t.createSocket();
// t.bind("127.0.0.1", 0);
// string d;
// t.getSockName(d, p);
// t.close();
// }
// }
tLocalEndpoint.setPort(p);
tLocalEndpoint.setHost("127.0.0.1");
tLocalEndpoint.setType(TC_Endpoint::TCP);
tLocalEndpoint.setTimeout(10000);
// NODE_LOG("KeepAliveThread")->debug() << tConf.tostr() << endl;
//需要宏替换部分配置
TC_Config tConfMacro;
map<string, string> mMacro;
mMacro.clear();
mMacro["locator"] = Application::getCommunicator()->getProperty("locator");
//>>修改成从主控获取locator地址
vector<tars::EndpointF> activeEp;
vector<tars::EndpointF> inactiveEp;
int iRet = 0;
if(_succ)
{
QueryFPrx queryProxy = AdminProxy::getInstance()->getQueryProxy();
try
{
iRet = queryProxy->findObjectById4All(AdminProxy::getInstance()->getQueryProxyName(), activeEp, inactiveEp);
NODE_LOG("KeepAliveThread")->debug() << "CommandLoad::updateConfigFile " << _serverObjectPtr->getServerId() << "|iRet|" << iRet << "|" << activeEp.size() << "|" << inactiveEp.size() << endl;
}
catch (exception& e)
{
//获取主控地址异常时,仍使用node中的locator
NODE_LOG("KeepAliveThread")->error() << "CommandLoad::updateConfigFile:get registry locator exception:" << e.what() << "|" << _serverObjectPtr->getServerId() << endl;
iRet = -1;
}
catch (...)
{
NODE_LOG("KeepAliveThread")->error() << "CommandLoad::updateConfigFile:get registry locator unknown exception|" << _serverObjectPtr->getServerId() << endl;
iRet = -1;
}
}
if (iRet == 0 && activeEp.size() > 0)
{
string sLocator = AdminProxy::getInstance()->getQueryProxyName() + "@";
for (size_t i = 0; i < activeEp.size(); ++i)
{
string sSingleAddr = "tcp -h " + activeEp[i].host + " -p " + TC_Common::tostr(activeEp[i].port);
sLocator += sSingleAddr + ":";
}
sLocator = sLocator.substr(0, sLocator.length() - 1);
mMacro["locator"] = sLocator;
NODE_LOG("KeepAliveThread")->debug() << "CommandLoad::updateConfigFile:" << _serverObjectPtr->getServerId() << "|locator|" << sLocator << endl;
}
mMacro["modulename"] = _desc.application + "." + _desc.serverName;
mMacro["app"] = _desc.application;
mMacro["server"] = _desc.serverName;
mMacro["serverid"] = _serverObjectPtr->getServerId();
mMacro["localip"] = g_app.getAdapterEndpoint("ServerAdapter").getHost();
mMacro["exe"] = TC_File::simplifyDirectory(_exeFile);
mMacro["basepath"] = TC_File::simplifyDirectory(_exePath) + FILE_SEP;
mMacro["datapath"] = TC_File::simplifyDirectory(_serverDir) + FILE_SEP + "data" + FILE_SEP;
mMacro["logpath"] = ServerConfig::LogPath;
mMacro["local"] = tLocalEndpoint.toString();
mMacro["mainclass"] = "com.qq." + TC_Common::lower(_desc.application) + "." + TC_Common::lower(_desc.serverName) + "." + _desc.serverName;
mMacro["config-center-port"] = TC_Common::tostr(_desc.configCenterPort);
mMacro["setdivision"] = _desc.setId;
mMacro["enableset"] = "n";
if (!mMacro["setdivision"].empty())
{
mMacro["enableset"] = "y";
}
else
{
mMacro["setdivision"] = "NULL";
}
mMacro["asyncthread"] = TC_Common::tostr(_desc.asyncThreadNum);
//创建目录
TC_File::makeDirRecursive(mMacro["basepath"]);
TC_File::makeDirRecursive(mMacro["datapath"]);
TC_File::makeDirRecursive(_logPath + FILE_SEP + _desc.application + FILE_SEP + _desc.serverName + FILE_SEP);
//合并两类配置
_serverObjectPtr->setMacro(mMacro);
string strProfile = _serverObjectPtr->decodeMacro(_desc.profile);
tConfMacro.parseString(strProfile);
tConf.joinConfig(tConfMacro, true);
string sStream = TC_Common::replace(tConf.tostr(), "\\s", " ");
string sConfigFileBak = _confFile + ".bak";
if (TC_File::isFileExist(_confFile) && TC_File::load2str(_confFile) != sStream)
{
TC_File::copyFile(_confFile, sConfigFileBak);
}
NODE_LOG("KeepAliveThread")->debug() << "save to: " << _confFile << endl;
ofstream configfile(_confFile.c_str());
if (!configfile.good())
{
NODE_LOG("KeepAliveThread")->error() << "CommandLoad::updateConfigFile cannot create configuration file: " << _confFile << endl;
return -1;
}
configfile << sStream;
configfile.close();
_logPath = tConf.get("/tars/application/server<logpath>", "");
_serverObjectPtr->setJvmParams(tConf.get("/tars/application/server<jvmparams>", ""));
_serverObjectPtr->setMainClass(tConf.get("/tars/application/server<mainclass>", ""));
_serverObjectPtr->setClassPath(tConf.get("/tars/application/server<classpath>", ""));
_serverObjectPtr->setEnv(tConf.get("/tars/application/server<env>", ""));
_serverObjectPtr->setHeartTimeout(TC_Common::strto<int>(tConf.get("/tars/application/server<hearttimeout>", "")));
_serverObjectPtr->setActivatingTimeout(TC_Common::strto<int>(tConf.get("/tars/application/server<activating-timeout>", "")));
_serverObjectPtr->setRedirectPath(tConf.get("/tars/application/<redirectpath>", ""));
_serverObjectPtr->setBackupFileNames(tConf.get("/tars/application/server<backupfiles>", "classes/autoconf"));
bool bEn = (TC_Common::lower(tConf.get("/tars/application/server<enableworking>", "y")) == "y") ? true : false;
_serverObjectPtr->setEnSynState(bEn);
_serverObjectPtr->setExeFile(_exeFile);
_serverObjectPtr->setConfigFile(_confFile);
_serverObjectPtr->setExePath(_exePath);
_serverObjectPtr->setLogPath(_logPath);
_serverObjectPtr->setLibPath(_libPath);
_serverObjectPtr->setServerDir(_serverDir);
_serverObjectPtr->setNodeInfo(_nodeInfo);
//取合并后配置
TC_Endpoint localEp;
localEp.parse(tConf.get("/tars/application/server<local>"));
_serverObjectPtr->setLocalEndpoint(localEp);
_serverObjectPtr->setServerType(_serverType);
_serverObjectPtr->setScript(_startScript, _stopScript, _monitorScript);
_serverObjectPtr->setLoaded(true);
return 0;
}
catch (exception& e)
{
sResult = e.what();
NODE_LOG("KeepAliveThread")->error() << "CommandLoad::updateConfigFile "<<e.what()<<endl;
}
catch (...)
{
NODE_LOG("KeepAliveThread")->error() << "CommandLoad::updateConfigFile catch unkown erro"<<endl;
}
return -1;
}
//服务配置文件文件下载
void CommandLoad::getRemoteConf()
{
if(_serverObjectPtr->getServerId() == "tars.tarsconfig")
{
return ;
}
string sResult;
try
{
ConfigPrx pPtr = Application::getCommunicator()->stringToProxy<ConfigPrx>(ServerConfig::Config);
vector<string> vf;
int ret;
if (_desc.setId.empty())
{
ret = pPtr->ListConfig(_desc.application, _desc.serverName, vf, ServerConfig::Context);
}
else
{
struct ConfigInfo confInfo;
confInfo.appname = _desc.application;
confInfo.servername = _desc.serverName;
confInfo.setdivision = _desc.setId;
ret = pPtr->ListConfigByInfo(confInfo, vf, ServerConfig::Context);
}
if (ret != 0)
{
NODE_LOG("KeepAliveThread")->error() << "CommandLoad::getRemoteConf [fail] get remote file list"<< endl;
g_app.reportServer(_serverObjectPtr->getServerId(), "", _serverObjectPtr->getNodeInfo().nodeName, sResult);
// g_app.reportServer( sResult);
}
for (unsigned i = 0; i < vf.size(); i++)
{
//脚本拉取 需要宏替换
if (_serverObjectPtr->isScriptFile(vf[i]) == true)
{
_serverObjectPtr->getRemoteScript(vf[i]);
continue;
}
//非tars服务配置文件需要node拉取 tars服务配置服务启动时自己拉取
if (_serverObjectPtr->isTarsServer() != true)
{
RemoteConfig remoteConfig;
remoteConfig.setConfigInfo(Application::getCommunicator(),ServerConfig::Config,_desc.application, _desc.serverName, _exePath,_desc.setId);
remoteConfig.addConfig(vf[i], sResult);
g_app.reportServer(_serverObjectPtr->getServerId(), "", _serverObjectPtr->getNodeInfo().nodeName, sResult);
// g_app.reportServer(_serverObjectPtr->getServerId(), sResult);
}
}
}
catch (exception& e)
{
NODE_LOG("KeepAliveThread")->error() << "CommandLoad::getRemoteConf error:" << e.what() << endl;
}
}
|
#ifndef QUITEXCEPTION_HPP
#define QUITEXCEPTION_HPP
class QuitException {
};
#endif
|
#include "Derivative.hh"
void Derivative::calcDerivative(FunctionArgs fargs) {
auto& args = fargs.args;
auto& arg = args[0].x;
auto& ret = fargs.rets[0].x;
auto x0 = m_x->value();
auto reldelta_corrected = m_reldelta*m_x->step();
double f1 = 4.0/(3.0*reldelta_corrected);
double f2 = 1.0/(6.0*reldelta_corrected);
std::array<double, 4> points;
points[0] = m_x->relativeValue(+m_reldelta/2);
points[1] = m_x->relativeValue(-m_reldelta/2);
points[2] = m_x->relativeValue(+m_reldelta);
points[3] = m_x->relativeValue(-m_reldelta);
m_x->set(points[0]); args.touch(); ret = f1*arg;
m_x->set(points[1]); args.touch(); ret -= f1*arg;
m_x->set(points[2]); args.touch(); ret -= f2*arg;
m_x->set(points[3]); args.touch(); ret += f2*arg;
m_x->set(x0); args.touch();
fargs.rets.untaint();
fargs.rets.freeze();
}
|
//
// main.cpp
// arrays-lists
//
// Created by Eric on 7/8/19.
// Copyright © 2019 Eric. All rights reserved.
//
#include <stdio.h>
#include <iostream>
using namespace std;
int main(){
cout << "Array of integers" << endl;
cout << "=================" << endl;
int values[3];
values[0] = 88;
values[1] = 123;
values[2] = 7;
cout << values[0] << endl;
cout << values[1] << endl;
cout << values[2] << endl;
cout << endl << "Array of doubles" << endl;
cout << "================" << endl;
double numbers[4] = {4.5, 2.3, 7.2, 8.1};
for (int i = 0; i < 4; i++)
{
cout << numbers[i] << endl;
}
return 0;
}
|
#include <game/move.h>
#include <base58.h>
#include <consensus/validation.h>
#include <game/db.h>
#include <game/map.h>
#include <game/state.h>
#include <key_io.h>
#include <names/common.h>
#include <names/main.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <script/names.h>
#include <script/standard.h>
#include <util.h>
#include <utilstrencodings.h>
#include <validation.h>
#include <boost/foreach.hpp>
#include <boost/xpressive/xpressive_dynamic.hpp>
/* Maximum number of waypoints per character. */
static const int MAX_WAYPOINTS = 100;
/* Number of colours in the game. */
static const int NUM_TEAM_COLORS = 4;
/* ************************************************************************** */
/* Move. */
bool Move::IsValid(const GameState &state) const
{
PlayerStateMap::const_iterator mi = state.players.find (player);
CAmount oldLocked;
if (mi == state.players.end ())
{
if (!IsSpawn ())
return false;
oldLocked = 0;
}
else
{
if (IsSpawn ())
return false;
oldLocked = mi->second.lockedCoins;
}
assert (oldLocked >= 0 && newLocked >= 0);
const CAmount gameFee = newLocked - oldLocked;
const CAmount required = MinimumGameFee (*state.param, state.nHeight + 1);
assert (required >= 0);
if (gameFee < required)
return error ("%s: too little game fee attached, got %lld, required %lld",
__func__, gameFee, required);
return true;
}
bool ParseWaypoints(UniValue& obj, std::vector<Coord>& result, bool& bWaypoints)
{
bWaypoints = false;
result.clear();
UniValue v;
if (!obj.extractField("wp", v))
return true;
if (!v.isArray())
return false;
if (v.size() % 2)
return false;
int n = v.size() / 2;
if (n > MAX_WAYPOINTS)
return false;
result.resize(n);
for (int i = 0; i < n; i++)
{
int x = v[2 * i].get_int();
int y = v[2 * i + 1].get_int();
if (!IsInsideMap(x, y))
return false;
// Waypoints are reversed for easier deletion of current waypoint from the end of the vector
result[n - 1 - i] = Coord(x, y);
if (i && result[n - 1 - i] == result[n - i])
return false; // Forbid duplicates
}
bWaypoints = true;
return true;
}
bool ParseDestruct(UniValue& obj, bool& result)
{
result = false;
UniValue v;
if (!obj.extractField("destruct", v))
return true;
result = v.get_bool();
return true;
}
static bool
IsValidReceiveAddress (const std::string& str)
{
/* TODO: Allow P2SH addresses at some point in the future. For now,
we have to disable support to stay consensus-compatible with
the existing client. */
const CTxDestination dest = DecodeDestination (str);
return IsKeyDestination (dest);
}
bool Move::Parse(const PlayerID &p, const std::string &json)
{
try
{
if (!IsValidPlayerName(p))
return false;
UniValue obj;
if (!obj.read(json, false) || !obj.isObject())
return false;
UniValue v;
if (obj.extractField ("msg", v))
message = v.get_str();
if (obj.extractField("address", v))
{
const std::string &addr = v.get_str();
if (!addr.empty() && !IsValidReceiveAddress(addr))
return false;
address = addr;
}
if (obj.extractField("addressLock", v))
{
const std::string &addr = v.get_str();
if (!addr.empty() && !IsValidReceiveAddress(addr))
return false;
addressLock = addr;
}
if (obj.extractField("color", v))
{
color = v.get_int();
if (color >= NUM_TEAM_COLORS)
return false;
if (!obj.empty()) // Extra fields are not allowed in JSON string
return false;
player = p;
return true;
}
const std::vector<std::string> keys = obj.getKeys ();
std::set<int> character_indices;
for (const auto& key : keys)
{
const int i = atoi(key.c_str());
if (i < 0 || strprintf("%d", i) != key)
return false; // Number formatting must be strict
if (character_indices.count(i))
return false; // Cannot contain duplicate character indices
character_indices.insert(i);
v = obj[key];
if (!v.isObject ())
return false;
bool bWaypoints = false;
std::vector<Coord> wp;
if (!ParseWaypoints(v, wp, bWaypoints))
return false;
bool bDestruct;
if (!ParseDestruct(v, bDestruct))
return false;
if (bDestruct)
destruct.insert(i);
if (bWaypoints)
waypoints.insert(std::make_pair(i, wp));
if (!v.empty()) // Extra fields are not allowed in JSON string
return false;
}
player = p;
return true;
} catch (const std::runtime_error& exc)
{
/* This happens when some JSON value has a wrong type. */
return false;
}
}
void Move::ApplyCommon(GameState &state) const
{
std::map<PlayerID, PlayerState>::iterator mi = state.players.find(player);
if (mi == state.players.end())
{
if (message)
{
PlayerState &pl = state.dead_players_chat[player];
pl.message = *message;
pl.message_block = state.nHeight;
}
return;
}
PlayerState &pl = mi->second;
if (message)
{
pl.message = *message;
pl.message_block = state.nHeight;
}
if (address)
pl.address = *address;
if (addressLock)
pl.addressLock = *addressLock;
}
std::string Move::AddressOperationPermission(const GameState &state) const
{
if (!address && !addressLock)
return std::string(); // No address operation requested - allow
PlayerStateMap::const_iterator mi = state.players.find(player);
if (mi == state.players.end())
return std::string(); // Spawn move - allow any address operation
return mi->second.addressLock;
}
void
Move::ApplySpawn (GameState &state, RandomGenerator &rnd) const
{
assert (state.players.count (player) == 0);
PlayerState pl;
assert (pl.next_character_index == 0);
pl.color = color;
/* This is a fresh player and name. Set its value to the height's
name coin amount and put the remainder in the game fee. This prevents
people from "overpaying" on purpose in order to get beefed-up players.
This rule, however, is only active after the life-steal fork. Before
that, overpaying did, indeed, allow to set the hunter value
arbitrarily high. */
if (state.ForkInEffect (FORK_LIFESTEAL))
{
const CAmount coinAmount = GetNameCoinAmount (*state.param, state.nHeight);
assert (pl.lockedCoins == 0 && pl.value == -1);
assert (newLocked >= coinAmount);
pl.value = coinAmount;
pl.lockedCoins = newLocked;
state.gameFund += newLocked - coinAmount;
}
else
{
pl.value = newLocked;
pl.lockedCoins = newLocked;
}
const unsigned limit = state.GetNumInitialCharacters ();
for (unsigned i = 0; i < limit; i++)
pl.SpawnCharacter (state, rnd);
state.players.insert (std::make_pair (player, pl));
}
void Move::ApplyWaypoints(GameState &state) const
{
std::map<PlayerID, PlayerState>::iterator pl;
pl = state.players.find (player);
if (pl == state.players.end ())
return;
for (const auto& p : waypoints)
{
std::map<int, CharacterState>::iterator mi;
mi = pl->second.characters.find(p.first);
if (mi == pl->second.characters.end())
continue;
CharacterState &ch = mi->second;
const std::vector<Coord> &wp = p.second;
if (ch.waypoints.empty() || wp.empty() || ch.waypoints.back() != wp.back())
ch.from = ch.coord;
ch.waypoints = wp;
}
}
CAmount
Move::MinimumGameFee (const Consensus::Params& param, unsigned nHeight) const
{
if (IsSpawn ())
{
const CAmount coinAmount = GetNameCoinAmount (param, nHeight);
// fee for new hunter is 1 HUC
if (param.rules->ForkInEffect (FORK_TIMESAVE, nHeight))
return coinAmount + COIN;
if (param.rules->ForkInEffect (FORK_LIFESTEAL, nHeight))
return coinAmount + 5 * COIN;
return coinAmount;
}
// destruct fee is 1 HUC
if (param.rules->ForkInEffect (FORK_TIMESAVE, nHeight))
return COIN * destruct.size ();
if (param.rules->ForkInEffect (FORK_LIFESTEAL, nHeight))
return 20 * COIN * destruct.size ();
return 0;
}
bool
Move::IsValidPlayerName (const std::string& player)
{
if (player.size() > MAX_NAME_LENGTH)
return false;
// Check player name validity
// Can contain letters, digits, underscore, hyphen and whitespace
// Cannot contain double whitespaces or start/end with whitespace
using namespace boost::xpressive;
static sregex regex = sregex::compile("^([a-zA-Z0-9_-]+ )*[a-zA-Z0-9_-]+$");
smatch match;
return regex_search(player, match, regex);
}
/* ************************************************************************** */
/* StepData. */
StepData::StepData (const GameState& s)
: state(s), dup(), nTreasureAmount(-1), newHash(), vMoves()
{
const CAmount nSubsidy = GetBlockSubsidy (state.nHeight + 1, *state.param);
// Miner subsidy is 10%, thus game treasure is 9 times the subsidy
nTreasureAmount = nSubsidy * 9;
}
bool
StepData::addTransaction (const CTransaction& tx, const CCoinsView* pview,
CValidationState& res)
{
if (!tx.IsNamecoin ())
return true;
/* Keep the moves to add to the step data here first. This is necessary
to prevent a situation where some moves are added already but the
function fails later with an error. */
std::vector<Move> newMoves;
for (const auto& txo : tx.vout)
{
const CNameScript nameOp(txo.scriptPubKey);
if (!nameOp.isNameOp () || !nameOp.isAnyUpdate ())
continue;
const std::string strName = ValtypeToString (nameOp.getOpName ());
const std::string strValue = ValtypeToString (nameOp.getOpValue ());
if (dup.count (strName))
return res.Invalid (error ("%s: duplicate name '%s' in block",
__func__, strName.c_str ()));
dup.insert (strName);
Move m;
m.newLocked = txo.nValue;
if (!m.Parse (strName, strValue))
return res.Invalid (error ("%s: cannot parse move %s",
__func__, strValue.c_str ()));
if (!m.IsValid (state))
return res.Invalid (error ("%s: invalid move for player %s",
__func__, strName.c_str ()));
if (m.IsSpawn ())
{
if (nameOp.getNameOp () != OP_NAME_FIRSTUPDATE)
return res.Invalid (error ("%s: spawn is not firstupdate",
__func__));
}
else if (nameOp.getNameOp () != OP_NAME_UPDATE)
return res.Invalid (error ("%s: firstupdate is not spawn"));
const std::string addressLock = m.AddressOperationPermission (state);
if (pview && !addressLock.empty ())
{
/* If one of inputs has address equal to addressLock, then that input
has been signed by the address owner and thus authorizes the
address change operation. */
bool found = false;
for (const auto& txi : tx.vin)
{
const COutPoint prevout = txi.prevout;
Coin coin;
if (!pview->GetCoin (prevout, coin))
continue;
CTxDestination dest;
if (ExtractDestination (coin.out.scriptPubKey, dest)
&& EncodeDestination (dest) == addressLock)
{
found = true;
break;
}
}
if (!found)
return res.Invalid (error ("%s: address operation denied",
__func__));
}
newMoves.push_back (m);
}
vMoves.insert (vMoves.end (), newMoves.begin (), newMoves.end ());
return true;
}
/* ************************************************************************** */
bool
PerformStep (const CBlock& block, const GameState& stateIn,
const CCoinsView* pview, CValidationState& valid,
StepResult& res, GameState& stateOut)
{
StepData step(stateIn);
for (const auto& tx : block.vtx)
if (!step.addTransaction (*tx, pview, valid))
return error ("%s: tx %s not accepted",
__func__, tx->GetHash ().GetHex ().c_str());
step.newHash = block.GetHash ();
if (!PerformStep (stateIn, step, stateOut, res))
return error ("%s: game engine failed to perform step", __func__);
return true;
}
|
#pragma once
#include "../../interfaces/core_serialization_new/ISerializerNew.hpp"
#include "../../lib/core_generic_plugin/interfaces/i_component_context.hpp"
#include <memory>
namespace wgt
{
/**
*The implementation of the ISerializer class. Allows de/serialization of objects using either IDataStreams or
ISerializationDocuments.
*Currently does not support serialization of pointers (including char*).
*Support for pointers will be implemented with the pointer handler, once changes to ObjectHandles are completed.
*/
class SerializationHandlerManager;
class SerializerNew : public Implements<ISerializerNew>
{
friend class SerializationNode;
friend class ISerializationHandler;
public:
typedef std::unique_ptr<SerializationNode> NodePtr;
public:
SerializerNew() = delete;
SerializerNew(SerializationHandlerManager* handlerManager);
std::unique_ptr<SerializationDocument> getDocument(SerializationFormat format) override;
// Variant Serialization
bool serializeToDocument(const Variant& v, SerializationDocument* doc) override;
bool serializeToStream(const Variant& v, IDataStream* stream, SerializationFormat format) override;
bool deserializeFromDocument(Variant& v, SerializationDocument* doc) override;
bool deserializeFromStream(Variant& v, IDataStream* stream, SerializationFormat format) override;
protected:
// Handler serialization - these are the functions that will be called recursively.
bool serializeObject(const Variant& v, const NodePtr& node, bool setType = true);
bool deserializeObject(Variant& v, const NodePtr& node, const char* typeName = nullptr);
private:
SerializationHandlerManager* const handlerManager_;
};
} // end namespace wgt
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: cartographer/mapping/proto/pose_graph_options.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "cartographer/mapping/proto/pose_graph_options.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace cartographer {
namespace mapping {
namespace proto {
class PoseGraphOptionsDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<PoseGraphOptions>
_instance;
} _PoseGraphOptions_default_instance_;
namespace protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_5foptions_2eproto {
namespace {
::google::protobuf::Metadata file_level_metadata[1];
} // namespace
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField
const TableStruct::entries[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField
const TableStruct::aux[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
::google::protobuf::internal::AuxillaryParseTableField(),
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const
TableStruct::schema[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
};
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraphOptions, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraphOptions, optimize_every_n_nodes_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraphOptions, constraint_builder_options_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraphOptions, matcher_translation_weight_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraphOptions, matcher_rotation_weight_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraphOptions, optimization_problem_options_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraphOptions, max_num_final_iterations_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraphOptions, global_sampling_ratio_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraphOptions, log_residual_histograms_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraphOptions, global_constraint_search_after_n_seconds_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(PoseGraphOptions)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&_PoseGraphOptions_default_instance_),
};
namespace {
void protobuf_AssignDescriptors() {
AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
"cartographer/mapping/proto/pose_graph_options.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
} // namespace
void TableStruct::InitDefaultsImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::internal::InitProtobufDefaults();
::cartographer::mapping::constraints::proto::protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2fconstraint_5fbuilder_5foptions_2eproto::InitDefaults();
::cartographer::mapping::optimization::proto::protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2foptimization_5fproblem_5foptions_2eproto::InitDefaults();
_PoseGraphOptions_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_PoseGraphOptions_default_instance_);_PoseGraphOptions_default_instance_._instance.get_mutable()->constraint_builder_options_ = const_cast< ::cartographer::mapping::constraints::proto::ConstraintBuilderOptions*>(
::cartographer::mapping::constraints::proto::ConstraintBuilderOptions::internal_default_instance());
_PoseGraphOptions_default_instance_._instance.get_mutable()->optimization_problem_options_ = const_cast< ::cartographer::mapping::optimization::proto::OptimizationProblemOptions*>(
::cartographer::mapping::optimization::proto::OptimizationProblemOptions::internal_default_instance());
}
void InitDefaults() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl);
}
namespace {
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n3cartographer/mapping/proto/pose_graph_"
"options.proto\022\032cartographer.mapping.prot"
"o\032Fcartographer/mapping/proto/pose_graph"
"/constraint_builder_options.proto\032Hcarto"
"grapher/mapping/proto/pose_graph/optimiz"
"ation_problem_options.proto\"\334\003\n\020PoseGrap"
"hOptions\022\036\n\026optimize_every_n_nodes\030\001 \001(\005"
"\022d\n\032constraint_builder_options\030\003 \001(\0132@.c"
"artographer.mapping.constraints.proto.Co"
"nstraintBuilderOptions\022\"\n\032matcher_transl"
"ation_weight\030\007 \001(\001\022\037\n\027matcher_rotation_w"
"eight\030\010 \001(\001\022i\n\034optimization_problem_opti"
"ons\030\004 \001(\0132C.cartographer.mapping.optimiz"
"ation.proto.OptimizationProblemOptions\022 "
"\n\030max_num_final_iterations\030\006 \001(\005\022\035\n\025glob"
"al_sampling_ratio\030\005 \001(\001\022\037\n\027log_residual_"
"histograms\030\t \001(\010\0220\n(global_constraint_se"
"arch_after_n_seconds\030\n \001(\001b\006proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 714);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"cartographer/mapping/proto/pose_graph_options.proto", &protobuf_RegisterTypes);
::cartographer::mapping::constraints::proto::protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2fconstraint_5fbuilder_5foptions_2eproto::AddDescriptors();
::cartographer::mapping::optimization::proto::protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2foptimization_5fproblem_5foptions_2eproto::AddDescriptors();
}
} // anonymous namespace
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_5foptions_2eproto
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int PoseGraphOptions::kOptimizeEveryNNodesFieldNumber;
const int PoseGraphOptions::kConstraintBuilderOptionsFieldNumber;
const int PoseGraphOptions::kMatcherTranslationWeightFieldNumber;
const int PoseGraphOptions::kMatcherRotationWeightFieldNumber;
const int PoseGraphOptions::kOptimizationProblemOptionsFieldNumber;
const int PoseGraphOptions::kMaxNumFinalIterationsFieldNumber;
const int PoseGraphOptions::kGlobalSamplingRatioFieldNumber;
const int PoseGraphOptions::kLogResidualHistogramsFieldNumber;
const int PoseGraphOptions::kGlobalConstraintSearchAfterNSecondsFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
PoseGraphOptions::PoseGraphOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_5foptions_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:cartographer.mapping.proto.PoseGraphOptions)
}
PoseGraphOptions::PoseGraphOptions(const PoseGraphOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_constraint_builder_options()) {
constraint_builder_options_ = new ::cartographer::mapping::constraints::proto::ConstraintBuilderOptions(*from.constraint_builder_options_);
} else {
constraint_builder_options_ = NULL;
}
if (from.has_optimization_problem_options()) {
optimization_problem_options_ = new ::cartographer::mapping::optimization::proto::OptimizationProblemOptions(*from.optimization_problem_options_);
} else {
optimization_problem_options_ = NULL;
}
::memcpy(&optimize_every_n_nodes_, &from.optimize_every_n_nodes_,
static_cast<size_t>(reinterpret_cast<char*>(&log_residual_histograms_) -
reinterpret_cast<char*>(&optimize_every_n_nodes_)) + sizeof(log_residual_histograms_));
// @@protoc_insertion_point(copy_constructor:cartographer.mapping.proto.PoseGraphOptions)
}
void PoseGraphOptions::SharedCtor() {
::memset(&constraint_builder_options_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&log_residual_histograms_) -
reinterpret_cast<char*>(&constraint_builder_options_)) + sizeof(log_residual_histograms_));
_cached_size_ = 0;
}
PoseGraphOptions::~PoseGraphOptions() {
// @@protoc_insertion_point(destructor:cartographer.mapping.proto.PoseGraphOptions)
SharedDtor();
}
void PoseGraphOptions::SharedDtor() {
if (this != internal_default_instance()) delete constraint_builder_options_;
if (this != internal_default_instance()) delete optimization_problem_options_;
}
void PoseGraphOptions::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* PoseGraphOptions::descriptor() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_5foptions_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_5foptions_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const PoseGraphOptions& PoseGraphOptions::default_instance() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_5foptions_2eproto::InitDefaults();
return *internal_default_instance();
}
PoseGraphOptions* PoseGraphOptions::New(::google::protobuf::Arena* arena) const {
PoseGraphOptions* n = new PoseGraphOptions;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void PoseGraphOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:cartographer.mapping.proto.PoseGraphOptions)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == NULL && constraint_builder_options_ != NULL) {
delete constraint_builder_options_;
}
constraint_builder_options_ = NULL;
if (GetArenaNoVirtual() == NULL && optimization_problem_options_ != NULL) {
delete optimization_problem_options_;
}
optimization_problem_options_ = NULL;
::memset(&optimize_every_n_nodes_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&log_residual_histograms_) -
reinterpret_cast<char*>(&optimize_every_n_nodes_)) + sizeof(log_residual_histograms_));
_internal_metadata_.Clear();
}
bool PoseGraphOptions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:cartographer.mapping.proto.PoseGraphOptions)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int32 optimize_every_n_nodes = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &optimize_every_n_nodes_)));
} else {
goto handle_unusual;
}
break;
}
// .cartographer.mapping.constraints.proto.ConstraintBuilderOptions constraint_builder_options = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_constraint_builder_options()));
} else {
goto handle_unusual;
}
break;
}
// .cartographer.mapping.optimization.proto.OptimizationProblemOptions optimization_problem_options = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_optimization_problem_options()));
} else {
goto handle_unusual;
}
break;
}
// double global_sampling_ratio = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(41u /* 41 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &global_sampling_ratio_)));
} else {
goto handle_unusual;
}
break;
}
// int32 max_num_final_iterations = 6;
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &max_num_final_iterations_)));
} else {
goto handle_unusual;
}
break;
}
// double matcher_translation_weight = 7;
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(57u /* 57 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &matcher_translation_weight_)));
} else {
goto handle_unusual;
}
break;
}
// double matcher_rotation_weight = 8;
case 8: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(65u /* 65 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &matcher_rotation_weight_)));
} else {
goto handle_unusual;
}
break;
}
// bool log_residual_histograms = 9;
case 9: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(72u /* 72 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &log_residual_histograms_)));
} else {
goto handle_unusual;
}
break;
}
// double global_constraint_search_after_n_seconds = 10;
case 10: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(81u /* 81 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &global_constraint_search_after_n_seconds_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:cartographer.mapping.proto.PoseGraphOptions)
return true;
failure:
// @@protoc_insertion_point(parse_failure:cartographer.mapping.proto.PoseGraphOptions)
return false;
#undef DO_
}
void PoseGraphOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:cartographer.mapping.proto.PoseGraphOptions)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// int32 optimize_every_n_nodes = 1;
if (this->optimize_every_n_nodes() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->optimize_every_n_nodes(), output);
}
// .cartographer.mapping.constraints.proto.ConstraintBuilderOptions constraint_builder_options = 3;
if (this->has_constraint_builder_options()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *this->constraint_builder_options_, output);
}
// .cartographer.mapping.optimization.proto.OptimizationProblemOptions optimization_problem_options = 4;
if (this->has_optimization_problem_options()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, *this->optimization_problem_options_, output);
}
// double global_sampling_ratio = 5;
if (this->global_sampling_ratio() != 0) {
::google::protobuf::internal::WireFormatLite::WriteDouble(5, this->global_sampling_ratio(), output);
}
// int32 max_num_final_iterations = 6;
if (this->max_num_final_iterations() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(6, this->max_num_final_iterations(), output);
}
// double matcher_translation_weight = 7;
if (this->matcher_translation_weight() != 0) {
::google::protobuf::internal::WireFormatLite::WriteDouble(7, this->matcher_translation_weight(), output);
}
// double matcher_rotation_weight = 8;
if (this->matcher_rotation_weight() != 0) {
::google::protobuf::internal::WireFormatLite::WriteDouble(8, this->matcher_rotation_weight(), output);
}
// bool log_residual_histograms = 9;
if (this->log_residual_histograms() != 0) {
::google::protobuf::internal::WireFormatLite::WriteBool(9, this->log_residual_histograms(), output);
}
// double global_constraint_search_after_n_seconds = 10;
if (this->global_constraint_search_after_n_seconds() != 0) {
::google::protobuf::internal::WireFormatLite::WriteDouble(10, this->global_constraint_search_after_n_seconds(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:cartographer.mapping.proto.PoseGraphOptions)
}
::google::protobuf::uint8* PoseGraphOptions::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:cartographer.mapping.proto.PoseGraphOptions)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// int32 optimize_every_n_nodes = 1;
if (this->optimize_every_n_nodes() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->optimize_every_n_nodes(), target);
}
// .cartographer.mapping.constraints.proto.ConstraintBuilderOptions constraint_builder_options = 3;
if (this->has_constraint_builder_options()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
3, *this->constraint_builder_options_, deterministic, target);
}
// .cartographer.mapping.optimization.proto.OptimizationProblemOptions optimization_problem_options = 4;
if (this->has_optimization_problem_options()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
4, *this->optimization_problem_options_, deterministic, target);
}
// double global_sampling_ratio = 5;
if (this->global_sampling_ratio() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(5, this->global_sampling_ratio(), target);
}
// int32 max_num_final_iterations = 6;
if (this->max_num_final_iterations() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(6, this->max_num_final_iterations(), target);
}
// double matcher_translation_weight = 7;
if (this->matcher_translation_weight() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(7, this->matcher_translation_weight(), target);
}
// double matcher_rotation_weight = 8;
if (this->matcher_rotation_weight() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(8, this->matcher_rotation_weight(), target);
}
// bool log_residual_histograms = 9;
if (this->log_residual_histograms() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(9, this->log_residual_histograms(), target);
}
// double global_constraint_search_after_n_seconds = 10;
if (this->global_constraint_search_after_n_seconds() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(10, this->global_constraint_search_after_n_seconds(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:cartographer.mapping.proto.PoseGraphOptions)
return target;
}
size_t PoseGraphOptions::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cartographer.mapping.proto.PoseGraphOptions)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// .cartographer.mapping.constraints.proto.ConstraintBuilderOptions constraint_builder_options = 3;
if (this->has_constraint_builder_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->constraint_builder_options_);
}
// .cartographer.mapping.optimization.proto.OptimizationProblemOptions optimization_problem_options = 4;
if (this->has_optimization_problem_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->optimization_problem_options_);
}
// int32 optimize_every_n_nodes = 1;
if (this->optimize_every_n_nodes() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->optimize_every_n_nodes());
}
// int32 max_num_final_iterations = 6;
if (this->max_num_final_iterations() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->max_num_final_iterations());
}
// double global_sampling_ratio = 5;
if (this->global_sampling_ratio() != 0) {
total_size += 1 + 8;
}
// double matcher_translation_weight = 7;
if (this->matcher_translation_weight() != 0) {
total_size += 1 + 8;
}
// double matcher_rotation_weight = 8;
if (this->matcher_rotation_weight() != 0) {
total_size += 1 + 8;
}
// double global_constraint_search_after_n_seconds = 10;
if (this->global_constraint_search_after_n_seconds() != 0) {
total_size += 1 + 8;
}
// bool log_residual_histograms = 9;
if (this->log_residual_histograms() != 0) {
total_size += 1 + 1;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void PoseGraphOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cartographer.mapping.proto.PoseGraphOptions)
GOOGLE_DCHECK_NE(&from, this);
const PoseGraphOptions* source =
::google::protobuf::internal::DynamicCastToGenerated<const PoseGraphOptions>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cartographer.mapping.proto.PoseGraphOptions)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cartographer.mapping.proto.PoseGraphOptions)
MergeFrom(*source);
}
}
void PoseGraphOptions::MergeFrom(const PoseGraphOptions& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cartographer.mapping.proto.PoseGraphOptions)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_constraint_builder_options()) {
mutable_constraint_builder_options()->::cartographer::mapping::constraints::proto::ConstraintBuilderOptions::MergeFrom(from.constraint_builder_options());
}
if (from.has_optimization_problem_options()) {
mutable_optimization_problem_options()->::cartographer::mapping::optimization::proto::OptimizationProblemOptions::MergeFrom(from.optimization_problem_options());
}
if (from.optimize_every_n_nodes() != 0) {
set_optimize_every_n_nodes(from.optimize_every_n_nodes());
}
if (from.max_num_final_iterations() != 0) {
set_max_num_final_iterations(from.max_num_final_iterations());
}
if (from.global_sampling_ratio() != 0) {
set_global_sampling_ratio(from.global_sampling_ratio());
}
if (from.matcher_translation_weight() != 0) {
set_matcher_translation_weight(from.matcher_translation_weight());
}
if (from.matcher_rotation_weight() != 0) {
set_matcher_rotation_weight(from.matcher_rotation_weight());
}
if (from.global_constraint_search_after_n_seconds() != 0) {
set_global_constraint_search_after_n_seconds(from.global_constraint_search_after_n_seconds());
}
if (from.log_residual_histograms() != 0) {
set_log_residual_histograms(from.log_residual_histograms());
}
}
void PoseGraphOptions::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cartographer.mapping.proto.PoseGraphOptions)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void PoseGraphOptions::CopyFrom(const PoseGraphOptions& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cartographer.mapping.proto.PoseGraphOptions)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool PoseGraphOptions::IsInitialized() const {
return true;
}
void PoseGraphOptions::Swap(PoseGraphOptions* other) {
if (other == this) return;
InternalSwap(other);
}
void PoseGraphOptions::InternalSwap(PoseGraphOptions* other) {
using std::swap;
swap(constraint_builder_options_, other->constraint_builder_options_);
swap(optimization_problem_options_, other->optimization_problem_options_);
swap(optimize_every_n_nodes_, other->optimize_every_n_nodes_);
swap(max_num_final_iterations_, other->max_num_final_iterations_);
swap(global_sampling_ratio_, other->global_sampling_ratio_);
swap(matcher_translation_weight_, other->matcher_translation_weight_);
swap(matcher_rotation_weight_, other->matcher_rotation_weight_);
swap(global_constraint_search_after_n_seconds_, other->global_constraint_search_after_n_seconds_);
swap(log_residual_histograms_, other->log_residual_histograms_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata PoseGraphOptions::GetMetadata() const {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_5foptions_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_5foptions_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// PoseGraphOptions
// int32 optimize_every_n_nodes = 1;
void PoseGraphOptions::clear_optimize_every_n_nodes() {
optimize_every_n_nodes_ = 0;
}
::google::protobuf::int32 PoseGraphOptions::optimize_every_n_nodes() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraphOptions.optimize_every_n_nodes)
return optimize_every_n_nodes_;
}
void PoseGraphOptions::set_optimize_every_n_nodes(::google::protobuf::int32 value) {
optimize_every_n_nodes_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.PoseGraphOptions.optimize_every_n_nodes)
}
// .cartographer.mapping.constraints.proto.ConstraintBuilderOptions constraint_builder_options = 3;
bool PoseGraphOptions::has_constraint_builder_options() const {
return this != internal_default_instance() && constraint_builder_options_ != NULL;
}
void PoseGraphOptions::clear_constraint_builder_options() {
if (GetArenaNoVirtual() == NULL && constraint_builder_options_ != NULL) delete constraint_builder_options_;
constraint_builder_options_ = NULL;
}
const ::cartographer::mapping::constraints::proto::ConstraintBuilderOptions& PoseGraphOptions::constraint_builder_options() const {
const ::cartographer::mapping::constraints::proto::ConstraintBuilderOptions* p = constraint_builder_options_;
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraphOptions.constraint_builder_options)
return p != NULL ? *p : *reinterpret_cast<const ::cartographer::mapping::constraints::proto::ConstraintBuilderOptions*>(
&::cartographer::mapping::constraints::proto::_ConstraintBuilderOptions_default_instance_);
}
::cartographer::mapping::constraints::proto::ConstraintBuilderOptions* PoseGraphOptions::mutable_constraint_builder_options() {
if (constraint_builder_options_ == NULL) {
constraint_builder_options_ = new ::cartographer::mapping::constraints::proto::ConstraintBuilderOptions;
}
// @@protoc_insertion_point(field_mutable:cartographer.mapping.proto.PoseGraphOptions.constraint_builder_options)
return constraint_builder_options_;
}
::cartographer::mapping::constraints::proto::ConstraintBuilderOptions* PoseGraphOptions::release_constraint_builder_options() {
// @@protoc_insertion_point(field_release:cartographer.mapping.proto.PoseGraphOptions.constraint_builder_options)
::cartographer::mapping::constraints::proto::ConstraintBuilderOptions* temp = constraint_builder_options_;
constraint_builder_options_ = NULL;
return temp;
}
void PoseGraphOptions::set_allocated_constraint_builder_options(::cartographer::mapping::constraints::proto::ConstraintBuilderOptions* constraint_builder_options) {
delete constraint_builder_options_;
constraint_builder_options_ = constraint_builder_options;
if (constraint_builder_options) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:cartographer.mapping.proto.PoseGraphOptions.constraint_builder_options)
}
// double matcher_translation_weight = 7;
void PoseGraphOptions::clear_matcher_translation_weight() {
matcher_translation_weight_ = 0;
}
double PoseGraphOptions::matcher_translation_weight() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraphOptions.matcher_translation_weight)
return matcher_translation_weight_;
}
void PoseGraphOptions::set_matcher_translation_weight(double value) {
matcher_translation_weight_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.PoseGraphOptions.matcher_translation_weight)
}
// double matcher_rotation_weight = 8;
void PoseGraphOptions::clear_matcher_rotation_weight() {
matcher_rotation_weight_ = 0;
}
double PoseGraphOptions::matcher_rotation_weight() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraphOptions.matcher_rotation_weight)
return matcher_rotation_weight_;
}
void PoseGraphOptions::set_matcher_rotation_weight(double value) {
matcher_rotation_weight_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.PoseGraphOptions.matcher_rotation_weight)
}
// .cartographer.mapping.optimization.proto.OptimizationProblemOptions optimization_problem_options = 4;
bool PoseGraphOptions::has_optimization_problem_options() const {
return this != internal_default_instance() && optimization_problem_options_ != NULL;
}
void PoseGraphOptions::clear_optimization_problem_options() {
if (GetArenaNoVirtual() == NULL && optimization_problem_options_ != NULL) delete optimization_problem_options_;
optimization_problem_options_ = NULL;
}
const ::cartographer::mapping::optimization::proto::OptimizationProblemOptions& PoseGraphOptions::optimization_problem_options() const {
const ::cartographer::mapping::optimization::proto::OptimizationProblemOptions* p = optimization_problem_options_;
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraphOptions.optimization_problem_options)
return p != NULL ? *p : *reinterpret_cast<const ::cartographer::mapping::optimization::proto::OptimizationProblemOptions*>(
&::cartographer::mapping::optimization::proto::_OptimizationProblemOptions_default_instance_);
}
::cartographer::mapping::optimization::proto::OptimizationProblemOptions* PoseGraphOptions::mutable_optimization_problem_options() {
if (optimization_problem_options_ == NULL) {
optimization_problem_options_ = new ::cartographer::mapping::optimization::proto::OptimizationProblemOptions;
}
// @@protoc_insertion_point(field_mutable:cartographer.mapping.proto.PoseGraphOptions.optimization_problem_options)
return optimization_problem_options_;
}
::cartographer::mapping::optimization::proto::OptimizationProblemOptions* PoseGraphOptions::release_optimization_problem_options() {
// @@protoc_insertion_point(field_release:cartographer.mapping.proto.PoseGraphOptions.optimization_problem_options)
::cartographer::mapping::optimization::proto::OptimizationProblemOptions* temp = optimization_problem_options_;
optimization_problem_options_ = NULL;
return temp;
}
void PoseGraphOptions::set_allocated_optimization_problem_options(::cartographer::mapping::optimization::proto::OptimizationProblemOptions* optimization_problem_options) {
delete optimization_problem_options_;
optimization_problem_options_ = optimization_problem_options;
if (optimization_problem_options) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:cartographer.mapping.proto.PoseGraphOptions.optimization_problem_options)
}
// int32 max_num_final_iterations = 6;
void PoseGraphOptions::clear_max_num_final_iterations() {
max_num_final_iterations_ = 0;
}
::google::protobuf::int32 PoseGraphOptions::max_num_final_iterations() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraphOptions.max_num_final_iterations)
return max_num_final_iterations_;
}
void PoseGraphOptions::set_max_num_final_iterations(::google::protobuf::int32 value) {
max_num_final_iterations_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.PoseGraphOptions.max_num_final_iterations)
}
// double global_sampling_ratio = 5;
void PoseGraphOptions::clear_global_sampling_ratio() {
global_sampling_ratio_ = 0;
}
double PoseGraphOptions::global_sampling_ratio() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraphOptions.global_sampling_ratio)
return global_sampling_ratio_;
}
void PoseGraphOptions::set_global_sampling_ratio(double value) {
global_sampling_ratio_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.PoseGraphOptions.global_sampling_ratio)
}
// bool log_residual_histograms = 9;
void PoseGraphOptions::clear_log_residual_histograms() {
log_residual_histograms_ = false;
}
bool PoseGraphOptions::log_residual_histograms() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraphOptions.log_residual_histograms)
return log_residual_histograms_;
}
void PoseGraphOptions::set_log_residual_histograms(bool value) {
log_residual_histograms_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.PoseGraphOptions.log_residual_histograms)
}
// double global_constraint_search_after_n_seconds = 10;
void PoseGraphOptions::clear_global_constraint_search_after_n_seconds() {
global_constraint_search_after_n_seconds_ = 0;
}
double PoseGraphOptions::global_constraint_search_after_n_seconds() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraphOptions.global_constraint_search_after_n_seconds)
return global_constraint_search_after_n_seconds_;
}
void PoseGraphOptions::set_global_constraint_search_after_n_seconds(double value) {
global_constraint_search_after_n_seconds_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.PoseGraphOptions.global_constraint_search_after_n_seconds)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace proto
} // namespace mapping
} // namespace cartographer
// @@protoc_insertion_point(global_scope)
|
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Copyright (c) 2018-2018 The SHIELD Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <merkleblock.h>
#include <uint256.h>
#include <test/test_shield.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(merkleblock_tests, BasicTestingSetup)
/**
* Create a CMerkleBlock using a list of txids which will be found in the
* given block.
*/
BOOST_AUTO_TEST_CASE(merkleblock_construct_from_txids_found)
{
CBlock block = getBlock13b8a();
std::set<uint256> txids;
// Last txn in block.
uint256 txhash1 = uint256S("0x74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20");
// Second txn in block.
uint256 txhash2 = uint256S("0xf9fc751cb7dc372406a9f8d738d5e6f8f63bab71986a39cf36ee70ee17036d07");
txids.insert(txhash1);
txids.insert(txhash2);
CMerkleBlock merkleBlock(block, txids);
BOOST_CHECK_EQUAL(merkleBlock.header.GetHash().GetHex(), block.GetHash().GetHex());
// vMatchedTxn is only used when bloom filter is specified.
BOOST_CHECK_EQUAL(merkleBlock.vMatchedTxn.size(), 0U);
std::vector<uint256> vMatched;
std::vector<unsigned int> vIndex;
BOOST_CHECK_EQUAL(merkleBlock.txn.ExtractMatches(vMatched, vIndex).GetHex(), block.hashMerkleRoot.GetHex());
BOOST_CHECK_EQUAL(vMatched.size(), 2U);
// Ordered by occurrence in depth-first tree traversal.
BOOST_CHECK_EQUAL(vMatched[0].ToString(), txhash2.ToString());
BOOST_CHECK_EQUAL(vIndex[0], 1U);
BOOST_CHECK_EQUAL(vMatched[1].ToString(), txhash1.ToString());
BOOST_CHECK_EQUAL(vIndex[1], 8U);
}
/**
* Create a CMerkleBlock using a list of txids which will not be found in the
* given block.
*/
BOOST_AUTO_TEST_CASE(merkleblock_construct_from_txids_not_found)
{
CBlock block = getBlock13b8a();
std::set<uint256> txids2;
txids2.insert(uint256S("0xc0ffee00003bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20"));
CMerkleBlock merkleBlock(block, txids2);
BOOST_CHECK_EQUAL(merkleBlock.header.GetHash().GetHex(), block.GetHash().GetHex());
BOOST_CHECK_EQUAL(merkleBlock.vMatchedTxn.size(), 0U);
std::vector<uint256> vMatched;
std::vector<unsigned int> vIndex;
BOOST_CHECK_EQUAL(merkleBlock.txn.ExtractMatches(vMatched, vIndex).GetHex(), block.hashMerkleRoot.GetHex());
BOOST_CHECK_EQUAL(vMatched.size(), 0U);
BOOST_CHECK_EQUAL(vIndex.size(), 0U);
}
BOOST_AUTO_TEST_SUITE_END()
|
#include <pamix_ui.hpp>
#include <pamix.hpp>
void pamix_ui::reset() {
m_Entries = nullptr;
m_VolumeBarLineNums.clear();
m_EntrySizes.clear();
m_NumDrawnEntries = 0;
m_NumSkippedEntries = 0;
m_SelectedEntry = m_SelectedChannel = 0;
}
void pamix_ui::drawVolumeBar(int y, int x, int width, double fill, double maxFill) const {
int segments = width - 2;
if (segments <= 0)
return;
if (fill < 0)
fill = 0;
else if (fill > maxFill)
fill = maxFill;
auto filled = (unsigned) (fill / maxFill * (double) segments);
if (filled > segments)
filled = (unsigned) segments;
mvaddstr(y, x++, "[");
mvaddstr(y, x + segments, "]");
auto indexColorA = (int) (segments * ((double) 1 / 3));
auto indexColorB = (int) (segments * ((double) 2 / 3));
FEAT_UNICODE_STRING meter;
meter.append(filled, SYM_VOLBAR);
meter.append((unsigned) segments - filled, SYM_SPACE);
attron(COLOR_PAIR(1));
FEAT_UNICODE_MVADDNSTR(y, x, meter.c_str(), indexColorA);
attroff(COLOR_PAIR(1));
attron(COLOR_PAIR(2));
FEAT_UNICODE_MVADDNSTR(y, x + indexColorA, meter.c_str() + indexColorA, indexColorB - indexColorA);
attroff(COLOR_PAIR(2));
attron(COLOR_PAIR(3));
FEAT_UNICODE_MVADDNSTR(y, x + indexColorB, meter.c_str() + indexColorB, segments - indexColorB);
attroff(COLOR_PAIR(3));
}
void string_maxlen_abs(std::string &str, unsigned max) {
if (str.length() > max) {
str = str.substr(0, max - 2);
str.append("..");
}
}
void string_maxlen_pct(std::string &str, double maxPct) {
string_maxlen_abs(str, (unsigned) (COLS * maxPct));
}
void pamix_ui::redrawAll() {
std::lock_guard<std::mutex> lockGuard(m_DrawMutex);
if (!m_paInterface->isConnected()) {
clear();
mvprintw(1, 1, "No connection to pulseaudio yet");
refresh();
return;
}
clear();
drawHeader();
unsigned lineNumber = 2;
unsigned entryIndex = 0;
auto entryIter = m_Entries->begin();
for (auto end = m_Entries->end(); entryIter != end; entryIter++, entryIndex++)
m_EntrySizes[entryIndex] = entryIter->second->m_Lock ? (char) 1 : entryIter->second->m_PAVolume.channels;
entryIndex = m_NumSkippedEntries;
entryIter = std::next(m_Entries->begin(), entryIndex);
for (auto end = m_Entries->end(); entryIter != end; entryIter++, entryIndex++) {
Entry *entry = entryIter->second.get();
std::string applicationName = entryIter->second ? entry->m_Name : "";
pa_volume_t averageVolume = pa_cvolume_avg(&entry->m_PAVolume);
char numChannels = entry->m_Lock ? (char) 1 : entry->m_PAVolume.channels;
bool isSelectedEntry = entryIndex == m_SelectedEntry;
if (lineNumber + numChannels + 2 > (unsigned) LINES)
break;
lineNumber = drawEntryControlMeters(entry, entryIndex, lineNumber);
double volumePeak = entry->m_Peak;
m_VolumeBarLineNums[entryIter->first] = lineNumber;
if (entry->m_Meter)
drawVolumeBar(lineNumber++, 1, COLS - 2, volumePeak, 1.0);
string_maxlen_pct(applicationName, 0.4);
if (isSelectedEntry)
attron(A_STANDOUT);
mvprintw(lineNumber++, 1, "%s", applicationName.c_str());
attroff(A_STANDOUT);
bool isMuted = entry->m_Mute || averageVolume == PA_VOLUME_MUTED;
printw(" %s %s", isMuted ? SYM_MUTE : "", entry->m_Lock ? SYM_LOCK : "");
int curX = 0, curY = 0;
getyx(stdscr, curY, curX);
unsigned remainingChars = (unsigned) COLS - curX - 3;
std::string displayName = getEntryDisplayName(entry);
if (remainingChars < displayName.length()) {
string_maxlen_abs(displayName, remainingChars);
remainingChars = 0;
} else {
remainingChars -= displayName.length();
}
mvprintw(curY, curX + remainingChars + 1, "%s", displayName.c_str());
lineNumber++;
}
m_NumDrawnEntries = entryIndex - m_NumSkippedEntries;
refresh();
}
unsigned int pamix_ui::drawEntryControlMeters(const Entry *entry, unsigned entryIndex, unsigned int lineNumber) const {
pa_volume_t averageVolume = pa_cvolume_avg(&entry->m_PAVolume);
double dB = pa_sw_volume_to_dB(averageVolume);
double vol = averageVolume / (double) PA_VOLUME_NORM;
char numChannels = entry->m_Lock ? (char) 1 : entry->m_PAVolume.channels;
bool isSelectedEntry = entryIndex == m_SelectedEntry;
if (entry->m_Meter) {
if (entry->m_Lock) {
drawVolumeBar(lineNumber, 32, COLS - 33, vol, MAX_VOL);
std::string descriptionTemplate = "%.2fdB (%.2f)";
if (isSelectedEntry)
descriptionTemplate.insert(0, SYM_ARROW);
mvprintw(lineNumber++, 1, descriptionTemplate.c_str(), dB, vol);
} else {
for (char channel = 0; channel < numChannels; channel++) {
std::string descriptionTemplate = "%.*s %.2fdB (%.2f)";
uint32_t volume = entry->m_PAVolume.values[channel];
bool isSelectedChannel = isSelectedEntry && channel == m_SelectedChannel;
double channel_dB = pa_sw_volume_to_dB(volume);
double channel_pct = volume / (double) PA_VOLUME_NORM;
pa_channel_position_t channelPosition = entry->m_PAChannelMap.map[channel];
std::string channelPrettyName = pa_channel_position_to_pretty_string(channelPosition);
drawVolumeBar(lineNumber, 32, COLS - 33, channel_pct, MAX_VOL);
if (isSelectedChannel)
descriptionTemplate.insert(0, SYM_ARROW);
unsigned indent = isSelectedChannel ? 13 : 15;
mvprintw(lineNumber++, 1, descriptionTemplate.c_str(), indent, channelPrettyName.c_str(), channel_dB,
channel_pct);
}
}
}
return lineNumber;
}
void pamix_ui::redrawVolumeBars() {
std::lock_guard<std::mutex> lockGuard(m_DrawMutex);
auto it = std::next(m_Entries->begin(), m_NumSkippedEntries);
uint32_t index = 0;
for (auto end = m_Entries->end(); it != end; it++, index++) {
if (index >= m_NumSkippedEntries + m_NumDrawnEntries)
break;
uint32_t y = m_VolumeBarLineNums[it->first];
if (it->second->m_Meter)
drawVolumeBar(y, 1, COLS - 2, it->second->m_Peak, 1.0);
}
refresh();
}
void pamix_ui::drawHeader() const {
mvprintw(0, 1, "%d/%d", m_Entries->empty() ? 0 : m_SelectedEntry + 1, (unsigned)m_Entries->size());
mvprintw(0, 10, "%s", entryTypeNames[m_EntriesType]);
}
std::string pamix_ui::getEntryDisplayName(Entry *entry) {
switch (m_EntriesType) {
case ENTRY_SINK:
case ENTRY_SOURCE: {
auto deviceEntry = ((DeviceEntry *) entry);
if (deviceEntry != nullptr) {
const DeviceEntry::DeviceProfile *deviceProfile = deviceEntry->getPortProfile();
if (deviceProfile != nullptr)
return deviceProfile->description.empty() ? deviceProfile->name : deviceProfile->description;
else
return deviceEntry->m_Name;
}
return "";
}
case ENTRY_SINKINPUT: {
auto sinkInput = (SinkInputEntry *) entry;
return m_paInterface->getSinks()[sinkInput->m_Device]->m_Name;
}
case ENTRY_SOURCEOUTPUT: {
auto sourceOutput = (SourceOutputEntry *) entry;
return m_paInterface->getSources()[sourceOutput->m_Device]->m_Name;
}
case ENTRY_CARDS: {
return ((CardEntry *) entry)->m_Profiles[((CardEntry *) entry)->m_Profile].description;
}
default:
return "UNKNOWN ENTRY TYPE";
}
}
pamix_ui::pamix_ui(PAInterface *paInterface) : m_paInterface(paInterface) {
reset();
}
void pamix_ui::selectEntries(entry_type type) {
switch (type) {
case ENTRY_SINK:
m_Entries = &m_paInterface->getSinks();
break;
case ENTRY_SOURCE:
m_Entries = &m_paInterface->getSources();
break;
case ENTRY_SINKINPUT:
m_Entries = &m_paInterface->getSinkInputs();
break;
case ENTRY_SOURCEOUTPUT:
m_Entries = &m_paInterface->getSourceOutputs();
break;
case ENTRY_CARDS:
m_Entries = &m_paInterface->getCards();
break;
default:
return;
}
m_EntriesType = type;
if (m_SelectedEntry > 0 && m_SelectedEntry >= m_Entries->size())
m_SelectedEntry = (unsigned) m_Entries->size() - 1;
auto currentEntry = getSelectedEntryIterator();
if (currentEntry != m_Entries->end() && m_SelectedChannel > 0 &&
m_SelectedChannel >= currentEntry->second->m_PAVolume.channels)
m_SelectedChannel = (unsigned) currentEntry->second->m_PAVolume.channels - 1;
}
int pamix_ui::getKeyInput() {
std::lock_guard<std::mutex> guard(m_DrawMutex);
return getch();
}
pamix_entry_iter_t pamix_ui::getSelectedEntryIterator() {
if (m_SelectedEntry < m_Entries->size())
return std::next(m_Entries->begin(), m_SelectedEntry);
else
return m_Entries->end();
}
void pamix_ui::adjustDisplayedEntries() {
if (m_Entries->empty())
return;
if (m_SelectedEntry >= m_NumSkippedEntries && m_SelectedEntry < m_NumSkippedEntries + m_NumDrawnEntries)
return;
if (m_SelectedEntry < m_NumSkippedEntries) {
// scroll up until selected is at top
m_NumSkippedEntries = m_SelectedEntry;
} else {
// scroll down until selected is at bottom
uint32_t linesToFree = 0;
uint32_t idx = m_NumSkippedEntries + m_NumDrawnEntries;
for (; idx <= m_SelectedEntry; idx++)
linesToFree += m_EntrySizes[idx] + 2;
uint32_t linesFreed = 0;
idx = m_NumSkippedEntries;
while (linesFreed < linesToFree)
linesFreed += m_EntrySizes[idx++] + 2;
m_NumSkippedEntries = idx;
}
}
void pamix_ui::selectNext(bool includeChannels) {
moveSelection(1, includeChannels);
}
void pamix_ui::selectPrevious(bool includeChannels) {
moveSelection(-1, includeChannels);
}
void pamix_ui::moveSelection(int delta, bool includeChannels) {
if (m_SelectedEntry < m_Entries->size()) {
auto it = getSelectedEntryIterator();
int step = delta > 0 ? 1 : -1;
for (int i = 0, numSteps = delta < 0 ? -delta : delta; i < numSteps; i++) {
auto entryThresh = static_cast<int>(delta < 0 ? 0 : m_Entries->size() - 1);
if (includeChannels && m_EntriesType != ENTRY_CARDS) {
bool isLocked = it->second->m_Lock;
int channelThresh = it->second->m_PAVolume.channels - 1;
if (delta < 0)
channelThresh = 0;
if (!isLocked && m_SelectedChannel != channelThresh) {
m_SelectedChannel += step;
continue;
}
}
if ((step == -1 && it == m_Entries->begin()) || (step == 1 && it == m_Entries->end()))
break;
if (m_SelectedEntry != entryThresh) {
it = std::next(it, step);
m_SelectedEntry += step;
m_SelectedChannel = static_cast<unsigned int>(delta < 0 ? it->second->m_PAVolume.channels - (char) 1 : 0);
}
}
}
adjustDisplayedEntries();
}
|
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <ripple/nodestore/impl/DatabaseNodeImp.h>
#include <ripple/nodestore/impl/ManagerImp.h>
#include <boost/algorithm/string/predicate.hpp>
namespace ripple {
namespace NodeStore {
ManagerImp&
ManagerImp::instance()
{
static ManagerImp _;
return _;
}
void
ManagerImp::missing_backend()
{
Throw<std::runtime_error>(
"Your rippled.cfg is missing a [node_db] entry, "
"please see the rippled-example.cfg file!");
}
std::unique_ptr<Backend>
ManagerImp::make_Backend(
Section const& parameters,
std::size_t burstSize,
Scheduler& scheduler,
beast::Journal journal)
{
std::string const type{get<std::string>(parameters, "type")};
if (type.empty())
missing_backend();
auto factory{find(type)};
if (!factory)
missing_backend();
return factory->createInstance(
NodeObject::keyBytes, parameters, burstSize, scheduler, journal);
}
std::unique_ptr<Database>
ManagerImp::make_Database(
std::string const& name,
std::size_t burstSize,
Scheduler& scheduler,
int readThreads,
Stoppable& parent,
Section const& config,
beast::Journal journal)
{
auto backend{make_Backend(config, burstSize, scheduler, journal)};
backend->open();
return std::make_unique<DatabaseNodeImp>(
name,
scheduler,
readThreads,
parent,
std::move(backend),
config,
journal);
}
void
ManagerImp::insert(Factory& factory)
{
std::lock_guard _(mutex_);
list_.push_back(&factory);
}
void
ManagerImp::erase(Factory& factory)
{
std::lock_guard _(mutex_);
auto const iter =
std::find_if(list_.begin(), list_.end(), [&factory](Factory* other) {
return other == &factory;
});
assert(iter != list_.end());
list_.erase(iter);
}
Factory*
ManagerImp::find(std::string const& name)
{
std::lock_guard _(mutex_);
auto const iter =
std::find_if(list_.begin(), list_.end(), [&name](Factory* other) {
return boost::iequals(name, other->getName());
});
if (iter == list_.end())
return nullptr;
return *iter;
}
//------------------------------------------------------------------------------
Manager&
Manager::instance()
{
return ManagerImp::instance();
}
//------------------------------------------------------------------------------
std::unique_ptr<Backend>
make_Backend(
Section const& config,
std::size_t burstSize,
Scheduler& scheduler,
beast::Journal journal)
{
return Manager::instance().make_Backend(
config, burstSize, scheduler, journal);
}
} // namespace NodeStore
} // namespace ripple
|
/*
* Copyright 2012 Rolando Martins, CRACS & INESC-TEC, DCC/FCUP
*
* 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.
*
*/
/*
* File: ServiceDiscoveryProvider.cpp
* Author: rmartins
*
* Created on August 2, 2010, 5:39 PM
*/
#include "stheno/core/SthenoCore.h"
#include "ServiceDiscoveryProvider.h"
#include <stheno/core/p2p/Overlay.h>
#include <stheno/core/p2p/discovery/Discovery.h>
#include <stheno/core/p2p/discovery/service_provider/ServiceQuery.h>
#include <stheno/core/p2p/discovery/service_provider/ServiceQueryReply.h>
#include <stheno/core/SthenoCoreInterface.h>
const UInt ServiceDiscoveryProvider::SERVICE_PROVIDER_TYPE = 0x9912AA;
ServiceDiscoveryProvider::ServiceDiscoveryProvider(Discovery* discovery) : m_discovery(discovery) {
m_providedEvents.push_back(ServiceQuery::SERVICE_QUERY);
}
ServiceDiscoveryProvider::~ServiceDiscoveryProvider() {
}
void ServiceDiscoveryProvider::close() {
}
DiscoveryQueryReply* ServiceDiscoveryProvider::executeQuery(DiscoveryQuery* query,
DiscoveryQoS* qos) throw (DiscoveryException&) {
if (query->getType() != ServiceQuery::SERVICE_QUERY) {
String msg("Unable to execute sync query");
throw DiscoveryException(msg);
}
ServiceQuery* serviceQ = static_cast<ServiceQuery*> (query);
try{
//list<UUIDPtr>* info = m_discovery->getOverlay()->getRuntime()->getInstancesOfService(serviceQ->getSID());
list<ServiceInstanceInfoPtr>* info = m_discovery->getOverlay()->getRuntime()->getInstancesOfService(serviceQ->getSID());
if(info == 0){
return 0;
}
ServiceQueryReply* queryReply = new ServiceQueryReply(*info);
return queryReply;
}catch(ServiceException& ex){
String msg("Unable to execute sync query");
throw DiscoveryException(msg);
}
return 0;
}
AsyncDiscoveryQueryReply* ServiceDiscoveryProvider::executeAsyncQuery(DiscoveryQuery* query,
DiscoveryQoS* qos, ACE_Time_Value* timeout) throw (DiscoveryException&) {
/*if (query->getType() != ROUTING_QUERY) {
throw DiscoveryException();
}
PeerQuery* peerQ = static_cast<PeerQuery*> (query);
try {
PeerInfoPtr* info = getPeerMap().getPeerInfo(peerQ->getUUID());
PeerQueryReply* peerQR = new PeerQueryReply(*info);
AsyncDiscoveryQueryReply* asyncQR = new AsyncDiscoveryQueryReply(timeout);
asyncQR->setFuture(peerQR);
return asyncQR;
} catch (PeerException& pEx) {
//must use remote peers
return remoteAsyncQuery(query, qos, timeout);
//throw DiscoveryException();
}*/
return 0;
}
list<UInt>& ServiceDiscoveryProvider::getProvidedEvents() {
return m_providedEvents;
}
|
// Copyright (c) 2017-2020 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "denomination_functions.h"
// -------------------------------------------------------------------------------------------------------
// Number of coins used for either change or a spend given a map of coins used
// -------------------------------------------------------------------------------------------------------
int getNumberOfCoinsUsed(
const std::map<libzerocoin::CoinDenomination, CAmount>& mapChange)
{
int nChangeCount = 0;
for (const auto& denom : libzerocoin::zerocoinDenomList) {
nChangeCount += mapChange.at(denom);
}
return nChangeCount;
}
// -------------------------------------------------------------------------------------------------------
// Find the max CoinDenomination amongst held coins
// -------------------------------------------------------------------------------------------------------
libzerocoin::CoinDenomination getMaxDenomHeld(
const std::map<libzerocoin::CoinDenomination, CAmount>& mapCoinsHeld)
{
libzerocoin::CoinDenomination maxDenom = libzerocoin::ZQ_ERROR;
for (auto& coin : reverse_iterate(libzerocoin::zerocoinDenomList)) {
if (mapCoinsHeld.at(coin)) {
maxDenom = coin;
break;
}
}
return maxDenom;
}
// -------------------------------------------------------------------------------------------------------
// Get Exact Amount with CoinsHeld
// -------------------------------------------------------------------------------------------------------
std::map<libzerocoin::CoinDenomination, CAmount> getSpendCoins(const CAmount nValueTarget,
const std::map<libzerocoin::CoinDenomination, CAmount> mapOfDenomsHeld)
{
std::map<libzerocoin::CoinDenomination, CAmount> mapUsed;
CAmount nRemainingValue = nValueTarget;
// Initialize
for (const auto& denom : libzerocoin::zerocoinDenomList)
mapUsed.insert(std::pair<libzerocoin::CoinDenomination, CAmount>(denom, 0));
// Start with the Highest Denomination coin and grab coins as long as the remaining amount is greater than the
// current denomination value and we have the denom
for (auto& coin : reverse_iterate(libzerocoin::zerocoinDenomList)) {
CAmount nValue = ZerocoinDenominationToAmount(coin);
do {
if ((nRemainingValue >= nValue) && (mapUsed.at(coin) < mapOfDenomsHeld.at(coin))) {
mapUsed.at(coin)++;
nRemainingValue -= nValue;
}
} while ((nRemainingValue >= nValue) && (mapUsed.at(coin) < mapOfDenomsHeld.at(coin)));
}
return mapUsed;
}
// -------------------------------------------------------------------------------------------------------
// Get change (no limits)
// -------------------------------------------------------------------------------------------------------
std::map<libzerocoin::CoinDenomination, CAmount> getChange(const CAmount nValueTarget)
{
std::map<libzerocoin::CoinDenomination, CAmount> mapChange;
CAmount nRemainingValue = nValueTarget;
// Initialize
for (const auto& denom : libzerocoin::zerocoinDenomList)
mapChange.insert(std::pair<libzerocoin::CoinDenomination, CAmount>(denom, 0));
// Start with the Highest Denomination coin and grab coins as long as the remaining amount is greater than the
// current denomination value
for (auto& coin : reverse_iterate(libzerocoin::zerocoinDenomList)) {
CAmount nValue = ZerocoinDenominationToAmount(coin);
do {
if (nRemainingValue >= nValue) {
mapChange.at(coin)++;
nRemainingValue -= nValue;
}
} while (nRemainingValue >= nValue);
}
return mapChange;
}
// -------------------------------------------------------------------------------------------------------
// Attempt to use coins held to exactly reach nValueTarget, return mapOfDenomsUsed with the coin set used
// Return false if exact match is not possible
// -------------------------------------------------------------------------------------------------------
bool getIdealSpends(
const CAmount nValueTarget,
const std::list<CMintMeta>& listMints,
const std::map<libzerocoin::CoinDenomination, CAmount> mapOfDenomsHeld,
std::map<libzerocoin::CoinDenomination, CAmount>& mapOfDenomsUsed)
{
CAmount nRemainingValue = nValueTarget;
// Initialize
for (const auto& denom : libzerocoin::zerocoinDenomList)
mapOfDenomsUsed.insert(std::pair<libzerocoin::CoinDenomination, CAmount>(denom, 0));
// Start with the Highest Denomination coin and grab coins as long as the remaining amount is greater than the
// current denomination value
for (auto& coin : reverse_iterate(libzerocoin::zerocoinDenomList)) {
for (const CMintMeta& mint : listMints) {
if (mint.isUsed) continue;
if (nRemainingValue >= ZerocoinDenominationToAmount(coin) && coin == mint.denom) {
mapOfDenomsUsed.at(coin)++;
nRemainingValue -= ZerocoinDenominationToAmount(mint.denom);
}
if (nRemainingValue < ZerocoinDenominationToAmount(coin)) break;
}
}
return (nRemainingValue == 0);
}
// -------------------------------------------------------------------------------------------------------
// Return a list of Mint coins based on mapOfDenomsUsed and the overall value in nCoinsSpentValue
// -------------------------------------------------------------------------------------------------------
std::vector<CMintMeta> getSpends(
const std::list<CMintMeta>& listMints,
std::map<libzerocoin::CoinDenomination, CAmount>& mapOfDenomsUsed,
CAmount& nCoinsSpentValue)
{
std::vector<CMintMeta> vSelectedMints;
nCoinsSpentValue = 0;
for (auto& coin : reverse_iterate(libzerocoin::zerocoinDenomList)) {
do {
for (const CMintMeta& mint : listMints) {
if (mint.isUsed) continue;
if (coin == mint.denom && mapOfDenomsUsed.at(coin)) {
vSelectedMints.push_back(mint);
nCoinsSpentValue += ZerocoinDenominationToAmount(coin);
mapOfDenomsUsed.at(coin)--;
}
}
} while (mapOfDenomsUsed.at(coin));
}
return vSelectedMints;
}
// -------------------------------------------------------------------------------------------------------
// Just for printing/debuggin
// -------------------------------------------------------------------------------------------------------
void listSpends(const std::vector<CZerocoinMint>& vSelectedMints)
{
std::map<libzerocoin::CoinDenomination, int64_t> mapZerocoinSupply;
for (auto& denom : libzerocoin::zerocoinDenomList)
mapZerocoinSupply.insert(std::make_pair(denom, 0));
for (const CZerocoinMint& mint : vSelectedMints) {
libzerocoin::CoinDenomination denom = mint.GetDenomination();
mapZerocoinSupply.at(denom)++;
}
CAmount nTotal = 0;
for (auto& denom : libzerocoin::zerocoinDenomList) {
LogPrint(BCLog::LEGACYZC, "%s %d coins for denomination %d used\n", __func__, mapZerocoinSupply.at(denom), denom);
nTotal += libzerocoin::ZerocoinDenominationToAmount(denom);
}
LogPrint(BCLog::LEGACYZC, "Total value of coins %d\n", nTotal);
}
// -------------------------------------------------------------------------------------------------------
// Find the CoinDenomination with the most number for a given amount
// -------------------------------------------------------------------------------------------------------
libzerocoin::CoinDenomination getDenomWithMostCoins(
const std::map<libzerocoin::CoinDenomination, CAmount>& mapOfDenomsUsed)
{
libzerocoin::CoinDenomination maxCoins = libzerocoin::ZQ_ERROR;
CAmount nMaxNumber = 0;
for (const auto& denom : libzerocoin::zerocoinDenomList) {
CAmount amount = mapOfDenomsUsed.at(denom);
if (amount > nMaxNumber) {
nMaxNumber = amount;
maxCoins = denom;
}
}
return maxCoins;
}
// -------------------------------------------------------------------------------------------------------
// Get the next denomination above the current one. Return ZQ_ERROR if already at the highest
// -------------------------------------------------------------------------------------------------------
libzerocoin::CoinDenomination getNextHighestDenom(const libzerocoin::CoinDenomination& this_denom)
{
libzerocoin::CoinDenomination nextValue = libzerocoin::ZQ_ERROR;
for (const auto& denom : libzerocoin::zerocoinDenomList) {
if (ZerocoinDenominationToAmount(denom) > ZerocoinDenominationToAmount(this_denom)) {
nextValue = denom;
break;
}
}
return nextValue;
}
// -------------------------------------------------------------------------------------------------------
// Get the next denomination below the current one that is also amongst those held.
// Return ZQ_ERROR if none found
// -------------------------------------------------------------------------------------------------------
libzerocoin::CoinDenomination getNextLowerDenomHeld(const libzerocoin::CoinDenomination& this_denom,
const std::map<libzerocoin::CoinDenomination, CAmount>& mapCoinsHeld)
{
libzerocoin::CoinDenomination nextValue = libzerocoin::ZQ_ERROR;
for (auto& denom : reverse_iterate(libzerocoin::zerocoinDenomList)) {
if ((denom < this_denom) && (mapCoinsHeld.at(denom) != 0)) {
nextValue = denom;
break;
}
}
return nextValue;
}
int minimizeChange(
int nMaxNumberOfSpends,
int nChangeCount,
const libzerocoin::CoinDenomination nextToMaxDenom,
const CAmount nValueTarget,
const std::map<libzerocoin::CoinDenomination, CAmount>& mapOfDenomsHeld,
std::map<libzerocoin::CoinDenomination, CAmount>& mapOfDenomsUsed)
{
// Now find out if possible without using 1 coin such that we have more spends but less change
// First get set of coins close to value but still less than value (since not exact)
CAmount nRemainingValue = nValueTarget;
CAmount AmountUsed = 0;
int nCoinCount = 0;
// Re-clear this
std::map<libzerocoin::CoinDenomination, CAmount> savedMapOfDenomsUsed = mapOfDenomsUsed;
for (const auto& denom : libzerocoin::zerocoinDenomList)
mapOfDenomsUsed.at(denom) = 0;
// Find the amount this is less than total but uses up higher denoms first,
// starting at the denom that is not greater than the overall total
for (const auto& denom : reverse_iterate(libzerocoin::zerocoinDenomList)) {
if (denom <= nextToMaxDenom) {
CAmount nValue = ZerocoinDenominationToAmount(denom);
do {
if ((nRemainingValue > nValue) && (mapOfDenomsUsed.at(denom) < mapOfDenomsHeld.at(denom))) {
mapOfDenomsUsed.at(denom)++;
nRemainingValue -= nValue;
AmountUsed += nValue;
nCoinCount++;
}
} while ((nRemainingValue > nValue) && (mapOfDenomsUsed.at(denom) < mapOfDenomsHeld.at(denom)));
}
}
// Now work way back up from the bottom filling in with the denom that we have that is just
// bigger than the remaining amount
// Shouldn't need more than one coin here?
for (const auto& denom : libzerocoin::zerocoinDenomList) {
CAmount nValue = ZerocoinDenominationToAmount(denom);
if ((nValue > nRemainingValue) && (mapOfDenomsUsed.at(denom) < mapOfDenomsHeld.at(denom))) {
mapOfDenomsUsed.at(denom)++;
nRemainingValue -= nValue;
AmountUsed += nValue;
nCoinCount++;
}
if (nRemainingValue < 0) break;
}
// This can still result in a case where you've used an extra spend than needed.
// e.g Spend of 26, while having 1*5 + 4*10
// First stage may be 2*10+5 (i.e < 26)
// Second stage can be 3*10+5 (no more fives, so add a 10)
// So 5 is no longer needed and will become change also
CAmount nAltChangeAmount = AmountUsed - nValueTarget;
std::map<libzerocoin::CoinDenomination, CAmount> mapAltChange = getChange(nAltChangeAmount);
// Check if there is overlap between change and spend denominations
// And if so, remove those that overlap
for (const auto& denom : libzerocoin::zerocoinDenomList) {
do {
if (mapAltChange.at(denom) && mapOfDenomsUsed.at(denom)) {
mapOfDenomsUsed.at(denom)--;
mapAltChange.at(denom)--;
nCoinCount--;
CAmount nValue = ZerocoinDenominationToAmount(denom);
AmountUsed -= nValue;
}
} while (mapAltChange.at(denom) && mapOfDenomsUsed.at(denom));
}
// Still possible to have wrong mix. So meet exact amount found above - with least number of coins
mapOfDenomsUsed = getSpendCoins(AmountUsed, mapOfDenomsHeld);
nCoinCount = getNumberOfCoinsUsed(mapOfDenomsUsed);
// Re-calculate change
nAltChangeAmount = AmountUsed - nValueTarget;
mapAltChange = getChange(nAltChangeAmount);
int AltChangeCount = getNumberOfCoinsUsed(mapAltChange);
// Alternative method yields less mints and is less than MaxNumberOfSpends if true
if ((AltChangeCount < nChangeCount) && (nCoinCount <= nMaxNumberOfSpends)) {
return AltChangeCount;
} else {
// if we don't meet above go back to what we started with
mapOfDenomsUsed = savedMapOfDenomsUsed;
return nChangeCount;
}
}
// -------------------------------------------------------------------------------------------------------
// Couldn't meet amount exactly, will need to generate change
// returning with a 0 means either too many spends or no change
// Latter should never happen since we should only get here if exact is not possible
// -------------------------------------------------------------------------------------------------------
int calculateChange(
int nMaxNumberOfSpends,
const CAmount nValueTarget,
const std::map<libzerocoin::CoinDenomination, CAmount>& mapOfDenomsHeld,
std::map<libzerocoin::CoinDenomination, CAmount>& mapOfDenomsUsed)
{
libzerocoin::CoinDenomination minDenomOverTarget = libzerocoin::ZQ_ERROR;
// Initialize
mapOfDenomsUsed.clear();
for (const auto& denom : libzerocoin::zerocoinDenomList)
mapOfDenomsUsed.insert(std::pair<libzerocoin::CoinDenomination, CAmount>(denom, 0));
for (const auto& denom : libzerocoin::zerocoinDenomList) {
if (nValueTarget < ZerocoinDenominationToAmount(denom) && mapOfDenomsHeld.at(denom)) {
minDenomOverTarget = denom;
break;
}
}
// OK so if != ZQ_ERROR we have a solution using 1 coin
if (minDenomOverTarget != libzerocoin::ZQ_ERROR) {
mapOfDenomsUsed.at(minDenomOverTarget) = 1;
// Now find out # of coins in change
CAmount nChangeAmount = ZerocoinDenominationToAmount(minDenomOverTarget) - nValueTarget;
std::map<libzerocoin::CoinDenomination, CAmount> mapChange = getChange(nChangeAmount);
int nChangeCount = getNumberOfCoinsUsed(mapChange);
// always try to minimize change
libzerocoin::CoinDenomination nextToMaxDenom = getNextLowerDenomHeld(minDenomOverTarget, mapOfDenomsHeld);
int newChangeCount = minimizeChange(nMaxNumberOfSpends, nChangeCount,
nextToMaxDenom, nValueTarget,
mapOfDenomsHeld, mapOfDenomsUsed);
// Alternative method yields less mints and is less than MaxNumberOfSpends if true
if (newChangeCount < nChangeCount) return newChangeCount;
// Reclear
for (const auto& denom : libzerocoin::zerocoinDenomList)
mapOfDenomsUsed.at(denom) = 0;
// Then reset as before previous clearing
mapOfDenomsUsed.at(minDenomOverTarget) = 1;
return nChangeCount;
} else {
// Try to meet a different way
for (const auto& denom : libzerocoin::zerocoinDenomList)
mapOfDenomsUsed.at(denom) = 0;
CAmount nRemainingValue = nValueTarget;
int nCoinCount = 0;
CAmount AmountUsed = 0;
for (const auto& denom : reverse_iterate(libzerocoin::zerocoinDenomList)) {
CAmount nValue = ZerocoinDenominationToAmount(denom);
do {
if (mapOfDenomsHeld.at(denom) && nRemainingValue > 0) {
mapOfDenomsUsed.at(denom)++;
AmountUsed += nValue;
nRemainingValue -= nValue;
nCoinCount++;
}
} while ((nRemainingValue > 0) && (mapOfDenomsUsed.at(denom) < mapOfDenomsHeld.at(denom)));
if (nRemainingValue < 0) break;
}
CAmount nChangeAmount = AmountUsed - nValueTarget;
std::map<libzerocoin::CoinDenomination, CAmount> mapChange = getChange(nChangeAmount);
int nMaxChangeCount = getNumberOfCoinsUsed(mapChange);
// Instead get max Denom held
libzerocoin::CoinDenomination maxDenomHeld = getMaxDenomHeld(mapOfDenomsHeld);
// Assign for size (only)
std::map<libzerocoin::CoinDenomination, CAmount> mapOfMinDenomsUsed = mapOfDenomsUsed;
int nChangeCount = minimizeChange(nMaxNumberOfSpends, nMaxChangeCount,
maxDenomHeld, nValueTarget,
mapOfDenomsHeld, mapOfMinDenomsUsed);
mapOfDenomsUsed = mapOfMinDenomsUsed;
return nChangeCount;
}
}
// -------------------------------------------------------------------------------------------------------
// Given a Target Spend Amount, attempt to meet it with a set of coins where less than nMaxNumberOfSpends
// 'spends' are required
// -------------------------------------------------------------------------------------------------------
std::vector<CMintMeta> SelectMintsFromList(const CAmount nValueTarget, CAmount& nSelectedValue, int nMaxNumberOfSpends,
int& nCoinsReturned, const std::list<CMintMeta>& listMints,
const std::map<libzerocoin::CoinDenomination, CAmount> mapOfDenomsHeld, int& nNeededSpends)
{
std::vector<CMintMeta> vSelectedMints;
std::map<libzerocoin::CoinDenomination, CAmount> mapOfDenomsUsed;
nNeededSpends = 0;
bool fCanMeetExactly = getIdealSpends(nValueTarget, listMints, mapOfDenomsHeld, mapOfDenomsUsed);
if (fCanMeetExactly) {
nCoinsReturned = 0;
nSelectedValue = nValueTarget;
vSelectedMints = getSpends(listMints, mapOfDenomsUsed, nSelectedValue);
// If true, we are good and done!
if (vSelectedMints.size() <= (size_t)nMaxNumberOfSpends) {
return vSelectedMints;
}
else {
nNeededSpends = vSelectedMints.size();
}
}
// Since either too many spends needed or can not spend the exact amount,
// calculate the change needed and the map of coins used
nCoinsReturned = calculateChange(nMaxNumberOfSpends, nValueTarget, mapOfDenomsHeld, mapOfDenomsUsed);
if (nCoinsReturned == 0) {
LogPrint(BCLog::LEGACYZC, "%s: Problem getting change (TBD) or Too many spends %d\n", __func__, nValueTarget);
vSelectedMints.clear();
} else {
vSelectedMints = getSpends(listMints, mapOfDenomsUsed, nSelectedValue);
LogPrint(BCLog::LEGACYZC, "%s: %d coins in change for %d\n", __func__, nCoinsReturned, nValueTarget);
}
return vSelectedMints;
}
|
//0
tic_key_escape,
tic_key_escape,
tic_key_f1,
tic_key_f1,
tic_key_f2,
tic_key_f2,
tic_key_f3,
tic_key_f3,
tic_key_f4,
tic_key_f4,
tic_key_f5,
tic_key_f5,
tic_key_f6,
tic_key_f6,
tic_key_f7,
tic_key_f7,
tic_key_f8,
tic_key_f8,
tic_key_f9,
tic_key_f9,
tic_key_f10,
tic_key_f10,
//1
tic_key_escape,
tic_key_escape,
tic_key_f1,
tic_key_f1,
tic_key_f2,
tic_key_f2,
tic_key_f3,
tic_key_f3,
tic_key_f4,
tic_key_f4,
tic_key_f5,
tic_key_f5,
tic_key_f6,
tic_key_f6,
tic_key_f7,
tic_key_f7,
tic_key_f8,
tic_key_f8,
tic_key_f9,
tic_key_f9,
tic_key_f10,
tic_key_f10,
//2
tic_key_tab,
tic_key_tab,
tic_key_grave,
tic_key_grave,
tic_key_leftbracket,
tic_key_leftbracket,
tic_key_rightbracket,
tic_key_rightbracket,
tic_key_semicolon,
tic_key_semicolon,
tic_key_apostrophe,
tic_key_apostrophe,
tic_key_minus,
tic_key_minus,
tic_key_equals,
tic_key_equals,
tic_key_slash,
tic_key_slash,
tic_key_f11,
tic_key_f11,
tic_key_f12,
tic_key_f12,
//3
tic_key_tab,
tic_key_tab,
tic_key_grave,
tic_key_grave,
tic_key_leftbracket,
tic_key_leftbracket,
tic_key_rightbracket,
tic_key_rightbracket,
tic_key_semicolon,
tic_key_semicolon,
tic_key_apostrophe,
tic_key_apostrophe,
tic_key_minus,
tic_key_minus,
tic_key_equals,
tic_key_equals,
tic_key_slash,
tic_key_slash,
tic_key_f11,
tic_key_f11,
tic_key_f12,
tic_key_f12,
//4
tic_key_1,
tic_key_1,
tic_key_2,
tic_key_2,
tic_key_3,
tic_key_3,
tic_key_4,
tic_key_4,
tic_key_5,
tic_key_5,
tic_key_6,
tic_key_6,
tic_key_7,
tic_key_7,
tic_key_8,
tic_key_8,
tic_key_9,
tic_key_9,
tic_key_0,
tic_key_0,
tic_key_backspace,
tic_key_backspace,
//5
tic_key_1,
tic_key_1,
tic_key_2,
tic_key_2,
tic_key_3,
tic_key_3,
tic_key_4,
tic_key_4,
tic_key_5,
tic_key_5,
tic_key_6,
tic_key_6,
tic_key_7,
tic_key_7,
tic_key_8,
tic_key_8,
tic_key_9,
tic_key_9,
tic_key_0,
tic_key_0,
tic_key_backspace,
tic_key_backspace,
//6
tic_key_q,
tic_key_q,
tic_key_w,
tic_key_w,
tic_key_e,
tic_key_e,
tic_key_r,
tic_key_r,
tic_key_t,
tic_key_t,
tic_key_y,
tic_key_y,
tic_key_u,
tic_key_u,
tic_key_i,
tic_key_i,
tic_key_o,
tic_key_o,
tic_key_p,
tic_key_p,
tic_key_backslash,
tic_key_backslash,
//7
tic_key_q,
tic_key_q,
tic_key_w,
tic_key_w,
tic_key_e,
tic_key_e,
tic_key_r,
tic_key_r,
tic_key_t,
tic_key_t,
tic_key_y,
tic_key_y,
tic_key_u,
tic_key_u,
tic_key_i,
tic_key_i,
tic_key_o,
tic_key_o,
tic_key_p,
tic_key_p,
tic_key_backslash,
tic_key_backslash,
//8
tic_key_unknown,
tic_key_a,
tic_key_a,
tic_key_s,
tic_key_s,
tic_key_d,
tic_key_d,
tic_key_f,
tic_key_f,
tic_key_g,
tic_key_g,
tic_key_h,
tic_key_h,
tic_key_j,
tic_key_j,
tic_key_k,
tic_key_k,
tic_key_l,
tic_key_l,
tic_key_return,
tic_key_return,
tic_key_return,
//9
tic_key_unknown,
tic_key_a,
tic_key_a,
tic_key_s,
tic_key_s,
tic_key_d,
tic_key_d,
tic_key_f,
tic_key_f,
tic_key_g,
tic_key_g,
tic_key_h,
tic_key_h,
tic_key_j,
tic_key_j,
tic_key_k,
tic_key_k,
tic_key_l,
tic_key_l,
tic_key_return,
tic_key_return,
tic_key_return,
//10
tic_key_shift,
tic_key_shift,
tic_key_z,
tic_key_z,
tic_key_x,
tic_key_x,
tic_key_c,
tic_key_c,
tic_key_v,
tic_key_v,
tic_key_b,
tic_key_b,
tic_key_n,
tic_key_n,
tic_key_m,
tic_key_m,
tic_key_comma,
tic_key_comma,
tic_key_period,
tic_key_period,
tic_key_return,
tic_key_return,
//11
tic_key_shift,
tic_key_shift,
tic_key_z,
tic_key_z,
tic_key_x,
tic_key_x,
tic_key_c,
tic_key_c,
tic_key_v,
tic_key_v,
tic_key_b,
tic_key_b,
tic_key_n,
tic_key_n,
tic_key_m,
tic_key_m,
tic_key_comma,
tic_key_comma,
tic_key_period,
tic_key_period,
tic_key_return,
tic_key_return,
//12
tic_key_ctrl,
tic_key_ctrl,
tic_key_ctrl,
tic_key_alt,
tic_key_alt,
tic_key_space,
tic_key_space,
tic_key_space,
tic_key_space,
tic_key_space,
tic_key_space,
tic_key_space,
tic_key_insert,
tic_key_insert,
tic_key_delete,
tic_key_delete,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
//13
tic_key_ctrl,
tic_key_ctrl,
tic_key_ctrl,
tic_key_alt,
tic_key_alt,
tic_key_space,
tic_key_space,
tic_key_space,
tic_key_space,
tic_key_space,
tic_key_space,
tic_key_space,
tic_key_insert,
tic_key_insert,
tic_key_delete,
tic_key_delete,
tic_key_unknown,
tic_key_unknown,
tic_key_up,
tic_key_up,
tic_key_unknown,
tic_key_unknown,
//14
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_up,
tic_key_up,
tic_key_unknown,
tic_key_unknown,
//15
tic_key_unknown,
tic_key_board,
tic_key_board,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_left,
tic_key_left,
tic_key_down,
tic_key_down,
tic_key_right,
tic_key_right,
//16
tic_key_unknown,
tic_key_board,
tic_key_board,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_unknown,
tic_key_left,
tic_key_left,
tic_key_down,
tic_key_down,
tic_key_right,
tic_key_right,
|
/////////////////////////////////////////////////////////////////////////////
// Name: src/gtk/toolbar.cpp
// Purpose: GTK toolbar
// Author: Robert Roebling
// Modified: 13.12.99 by VZ to derive from wxToolBarBase
// Copyright: (c) Robert Roebling
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#if wxUSE_TOOLBAR_NATIVE
#include "wx/toolbar.h"
#include <gtk/gtk.h>
#include "wx/gtk/private.h"
#include "wx/gtk/private/gtk2-compat.h"
// ----------------------------------------------------------------------------
// globals
// ----------------------------------------------------------------------------
// data
extern bool g_blockEventsOnDrag;
// ----------------------------------------------------------------------------
// wxToolBarTool
// ----------------------------------------------------------------------------
class wxToolBarTool : public wxToolBarToolBase
{
public:
wxToolBarTool(wxToolBar *tbar,
int id,
const wxString& label,
const wxBitmap& bitmap1,
const wxBitmap& bitmap2,
wxItemKind kind,
wxObject *clientData,
const wxString& shortHelpString,
const wxString& longHelpString)
: wxToolBarToolBase(tbar, id, label, bitmap1, bitmap2, kind,
clientData, shortHelpString, longHelpString)
{
m_item = NULL;
}
wxToolBarTool(wxToolBar *tbar, wxControl *control, const wxString& label)
: wxToolBarToolBase(tbar, control, label)
{
m_item = NULL;
}
void SetImage();
void CreateDropDown();
void ShowDropdown(GtkToggleButton* button);
GtkToolItem* m_item;
};
// ----------------------------------------------------------------------------
// wxWin macros
// ----------------------------------------------------------------------------
wxIMPLEMENT_DYNAMIC_CLASS(wxToolBar, wxControl);
// ============================================================================
// implementation
// ============================================================================
//-----------------------------------------------------------------------------
// "clicked" from m_item
//-----------------------------------------------------------------------------
extern "C" {
static void item_clicked(GtkToolButton*, wxToolBarTool* tool)
{
if (g_blockEventsOnDrag) return;
tool->GetToolBar()->OnLeftClick(tool->GetId(), false);
}
}
//-----------------------------------------------------------------------------
// "toggled" from m_item
//-----------------------------------------------------------------------------
extern "C" {
static void item_toggled(GtkToggleToolButton* button, wxToolBarTool* tool)
{
if (g_blockEventsOnDrag) return;
const bool active = gtk_toggle_tool_button_get_active(button) != 0;
tool->Toggle(active);
if (!active && tool->GetKind() == wxITEM_RADIO)
return;
if (!tool->GetToolBar()->OnLeftClick(tool->GetId(), active))
{
// revert back
tool->Toggle();
}
}
}
//-----------------------------------------------------------------------------
// "button_press_event" from m_item child
//-----------------------------------------------------------------------------
extern "C" {
static gboolean
button_press_event(GtkWidget*, GdkEventButton* event, wxToolBarTool* tool)
{
if (event->button != 3)
return FALSE;
if (g_blockEventsOnDrag) return TRUE;
tool->GetToolBar()->OnRightClick(
tool->GetId(), int(event->x), int(event->y));
return TRUE;
}
}
//-----------------------------------------------------------------------------
// "child_detached" from m_widget
//-----------------------------------------------------------------------------
extern "C" {
static void child_detached(GtkWidget*, GtkToolbar* toolbar, void*)
{
// disable showing overflow arrow when toolbar is detached,
// otherwise toolbar collapses to just an arrow
gtk_toolbar_set_show_arrow(toolbar, false);
}
}
//-----------------------------------------------------------------------------
// "child_attached" from m_widget
//-----------------------------------------------------------------------------
extern "C" {
static void child_attached(GtkWidget*, GtkToolbar* toolbar, void*)
{
gtk_toolbar_set_show_arrow(toolbar, true);
}
}
//-----------------------------------------------------------------------------
// "enter_notify_event" / "leave_notify_event" from m_item
//-----------------------------------------------------------------------------
extern "C" {
static gboolean
enter_notify_event(GtkWidget*, GdkEventCrossing* event, wxToolBarTool* tool)
{
if (g_blockEventsOnDrag) return TRUE;
int id = -1;
if (event->type == GDK_ENTER_NOTIFY)
id = tool->GetId();
tool->GetToolBar()->OnMouseEnter(id);
return FALSE;
}
}
//-----------------------------------------------------------------------------
// "expose_event" from GtkImage inside m_item
//-----------------------------------------------------------------------------
extern "C" {
static gboolean
#ifdef __WXGTK3__
image_draw(GtkWidget* widget, cairo_t* cr, wxToolBarTool* tool)
#else
image_expose_event(GtkWidget* widget, GdkEventExpose*, wxToolBarTool* tool)
#endif
{
const wxBitmap& bitmap = tool->GetDisabledBitmap();
if (tool->IsEnabled() || !bitmap.IsOk())
return false;
// draw disabled bitmap ourselves, GtkImage has no way to specify it
GtkAllocation alloc;
gtk_widget_get_allocation(widget, &alloc);
int x = (alloc.width - bitmap.GetWidth()) / 2;
int y = (alloc.height - bitmap.GetHeight()) / 2;
#ifdef __WXGTK3__
bitmap.Draw(cr, x, y);
#else
x += alloc.x;
y += alloc.y;
gdk_draw_pixbuf(
gtk_widget_get_window(widget), gtk_widget_get_style(widget)->black_gc, bitmap.GetPixbuf(),
0, 0, x, y,
-1, -1, GDK_RGB_DITHER_NORMAL, 0, 0);
#endif
return true;
}
}
//-----------------------------------------------------------------------------
// "toggled" from dropdown menu button
//-----------------------------------------------------------------------------
extern "C" {
static void arrow_toggled(GtkToggleButton* button, wxToolBarTool* tool)
{
if (gtk_toggle_button_get_active(button))
{
tool->ShowDropdown(button);
gtk_toggle_button_set_active(button, false);
}
}
}
//-----------------------------------------------------------------------------
// "button_press_event" from dropdown menu button
//-----------------------------------------------------------------------------
extern "C" {
static gboolean
arrow_button_press_event(GtkToggleButton* button, GdkEventButton* event, wxToolBarTool* tool)
{
if (event->button == 1)
{
g_signal_handlers_block_by_func(button, (void*)arrow_toggled, tool);
gtk_toggle_button_set_active(button, true);
tool->ShowDropdown(button);
gtk_toggle_button_set_active(button, false);
g_signal_handlers_unblock_by_func(button, (void*)arrow_toggled, tool);
return true;
}
return false;
}
}
void wxToolBar::AddChildGTK(wxWindowGTK* child)
{
GtkWidget* align = gtk_alignment_new(0.5, 0.5, 0, 0);
gtk_widget_show(align);
gtk_container_add(GTK_CONTAINER(align), child->m_widget);
GtkToolItem* item = gtk_tool_item_new();
gtk_container_add(GTK_CONTAINER(item), align);
// position will be corrected in DoInsertTool if necessary
gtk_toolbar_insert(GTK_TOOLBAR(gtk_bin_get_child(GTK_BIN(m_widget))), item, -1);
}
// ----------------------------------------------------------------------------
// wxToolBarTool
// ----------------------------------------------------------------------------
void wxToolBarTool::SetImage()
{
const wxBitmap& bitmap = GetNormalBitmap();
wxCHECK_RET(bitmap.IsOk(), "invalid bitmap for wxToolBar icon");
GtkWidget* image = gtk_tool_button_get_icon_widget(GTK_TOOL_BUTTON(m_item));
// always use pixbuf, because pixmap mask does not
// work with disabled images in some themes
gtk_image_set_from_pixbuf(GTK_IMAGE(image), bitmap.GetPixbuf());
}
// helper to create a dropdown menu item
void wxToolBarTool::CreateDropDown()
{
gtk_tool_item_set_homogeneous(m_item, false);
GtkOrientation orient = GTK_ORIENTATION_HORIZONTAL;
GtkArrowType arrowType = GTK_ARROW_DOWN;
if (GetToolBar()->HasFlag(wxTB_LEFT | wxTB_RIGHT))
{
orient = GTK_ORIENTATION_VERTICAL;
arrowType = GTK_ARROW_RIGHT;
}
GtkWidget* box = gtk_box_new(orient, 0);
GtkWidget* arrow = gtk_arrow_new(arrowType, GTK_SHADOW_NONE);
GtkWidget* tool_button = gtk_bin_get_child(GTK_BIN(m_item));
g_object_ref(tool_button);
gtk_container_remove(GTK_CONTAINER(m_item), tool_button);
gtk_container_add(GTK_CONTAINER(box), tool_button);
g_object_unref(tool_button);
GtkWidget* arrow_button = gtk_toggle_button_new();
gtk_button_set_relief(GTK_BUTTON(arrow_button),
gtk_tool_item_get_relief_style(GTK_TOOL_ITEM(m_item)));
gtk_container_add(GTK_CONTAINER(arrow_button), arrow);
gtk_container_add(GTK_CONTAINER(box), arrow_button);
gtk_widget_show_all(box);
gtk_container_add(GTK_CONTAINER(m_item), box);
g_signal_connect(arrow_button, "toggled", G_CALLBACK(arrow_toggled), this);
g_signal_connect(arrow_button, "button_press_event",
G_CALLBACK(arrow_button_press_event), this);
}
void wxToolBarTool::ShowDropdown(GtkToggleButton* button)
{
wxToolBarBase* toolbar = GetToolBar();
wxCommandEvent event(wxEVT_TOOL_DROPDOWN, GetId());
if (!toolbar->HandleWindowEvent(event))
{
wxMenu* menu = GetDropdownMenu();
if (menu)
{
GtkAllocation alloc;
gtk_widget_get_allocation(GTK_WIDGET(button), &alloc);
int x = alloc.x;
int y = alloc.y;
if (toolbar->HasFlag(wxTB_LEFT | wxTB_RIGHT))
x += alloc.width;
else
y += alloc.height;
toolbar->PopupMenu(menu, x, y);
}
}
}
wxToolBarToolBase *wxToolBar::CreateTool(int id,
const wxString& text,
const wxBitmap& bitmap1,
const wxBitmap& bitmap2,
wxItemKind kind,
wxObject *clientData,
const wxString& shortHelpString,
const wxString& longHelpString)
{
return new wxToolBarTool(this, id, text, bitmap1, bitmap2, kind,
clientData, shortHelpString, longHelpString);
}
wxToolBarToolBase *
wxToolBar::CreateTool(wxControl *control, const wxString& label)
{
return new wxToolBarTool(this, control, label);
}
//-----------------------------------------------------------------------------
// wxToolBar construction
//-----------------------------------------------------------------------------
void wxToolBar::Init()
{
m_toolbar = NULL;
m_tooltips = NULL;
}
wxToolBar::~wxToolBar()
{
#ifndef __WXGTK3__
if (m_tooltips) // always NULL if GTK >= 2.12
{
gtk_object_destroy(GTK_OBJECT(m_tooltips));
g_object_unref(m_tooltips);
}
#endif
}
bool wxToolBar::Create( wxWindow *parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name )
{
if ( !PreCreation( parent, pos, size ) ||
!CreateBase( parent, id, pos, size, style, wxDefaultValidator, name ))
{
wxFAIL_MSG( wxT("wxToolBar creation failed") );
return false;
}
FixupStyle();
m_toolbar = GTK_TOOLBAR( gtk_toolbar_new() );
#ifndef __WXGTK3__
if (gtk_check_version(2, 12, 0))
{
m_tooltips = gtk_tooltips_new();
g_object_ref(m_tooltips);
gtk_object_sink(GTK_OBJECT(m_tooltips));
}
#endif
GtkSetStyle();
if (style & wxTB_DOCKABLE)
{
m_widget = gtk_handle_box_new();
g_signal_connect(m_widget, "child_detached",
G_CALLBACK(child_detached), NULL);
g_signal_connect(m_widget, "child_attached",
G_CALLBACK(child_attached), NULL);
if (style & wxTB_FLAT)
gtk_handle_box_set_shadow_type( GTK_HANDLE_BOX(m_widget), GTK_SHADOW_NONE );
}
else
{
m_widget = gtk_event_box_new();
ConnectWidget( m_widget );
}
g_object_ref(m_widget);
gtk_container_add(GTK_CONTAINER(m_widget), GTK_WIDGET(m_toolbar));
gtk_widget_show(GTK_WIDGET(m_toolbar));
m_parent->DoAddChild( this );
PostCreation(size);
return true;
}
GdkWindow *wxToolBar::GTKGetWindow(wxArrayGdkWindows& WXUNUSED(windows)) const
{
return gtk_widget_get_window(GTK_WIDGET(m_toolbar));
}
void wxToolBar::GtkSetStyle()
{
GtkOrientation orient = GTK_ORIENTATION_HORIZONTAL;
if (HasFlag(wxTB_LEFT | wxTB_RIGHT))
orient = GTK_ORIENTATION_VERTICAL;
GtkToolbarStyle style = GTK_TOOLBAR_ICONS;
if (HasFlag(wxTB_NOICONS))
style = GTK_TOOLBAR_TEXT;
else if (HasFlag(wxTB_TEXT))
{
style = GTK_TOOLBAR_BOTH;
if (HasFlag(wxTB_HORZ_LAYOUT))
style = GTK_TOOLBAR_BOTH_HORIZ;
}
#ifdef __WXGTK3__
gtk_orientable_set_orientation(GTK_ORIENTABLE(m_toolbar), orient);
#else
gtk_toolbar_set_orientation(m_toolbar, orient);
#endif
gtk_toolbar_set_style(m_toolbar, style);
}
void wxToolBar::SetWindowStyleFlag( long style )
{
wxToolBarBase::SetWindowStyleFlag(style);
if ( m_toolbar )
GtkSetStyle();
}
bool wxToolBar::Realize()
{
if ( !wxToolBarBase::Realize() )
return false;
// bring the initial state of all the toolbar items in line with the
// internal state if the latter was changed by calling wxToolBarTool::
// Enable(): this works under MSW, where the toolbar items are only created
// in Realize() which uses the internal state to determine the initial
// button state, so make it work under GTK too
for ( wxToolBarToolsList::const_iterator i = m_tools.begin();
i != m_tools.end();
++i )
{
// by default the toolbar items are enabled and not toggled, so we only
// have to do something if their internal state doesn't correspond to
// this
if ( !(*i)->IsEnabled() )
DoEnableTool(*i, false);
if ( (*i)->IsToggled() )
DoToggleTool(*i, true);
}
return true;
}
bool wxToolBar::DoInsertTool(size_t pos, wxToolBarToolBase *toolBase)
{
wxToolBarTool* tool = static_cast<wxToolBarTool*>(toolBase);
GSList* radioGroup;
GtkWidget* bin_child;
switch ( tool->GetStyle() )
{
case wxTOOL_STYLE_BUTTON:
switch (tool->GetKind())
{
case wxITEM_CHECK:
tool->m_item = gtk_toggle_tool_button_new();
g_signal_connect(tool->m_item, "toggled",
G_CALLBACK(item_toggled), tool);
break;
case wxITEM_RADIO:
radioGroup = GetRadioGroup(pos);
if (!radioGroup)
{
// this is the first button in the radio button group,
// it will be toggled automatically by GTK so bring the
// internal flag in sync
tool->Toggle(true);
}
tool->m_item = gtk_radio_tool_button_new(radioGroup);
g_signal_connect(tool->m_item, "toggled",
G_CALLBACK(item_toggled), tool);
break;
default:
wxFAIL_MSG("unknown toolbar child type");
// fall through
case wxITEM_DROPDOWN:
case wxITEM_NORMAL:
tool->m_item = gtk_tool_button_new(NULL, "");
g_signal_connect(tool->m_item, "clicked",
G_CALLBACK(item_clicked), tool);
break;
}
if (!HasFlag(wxTB_NOICONS))
{
GtkWidget* image = gtk_image_new();
gtk_tool_button_set_icon_widget(
GTK_TOOL_BUTTON(tool->m_item), image);
tool->SetImage();
gtk_widget_show(image);
#ifdef __WXGTK3__
g_signal_connect(image, "draw",
G_CALLBACK(image_draw), tool);
#else
g_signal_connect(image, "expose_event",
G_CALLBACK(image_expose_event), tool);
#endif
}
if (!tool->GetLabel().empty())
{
wxString const
label = wxControl::RemoveMnemonics(tool->GetLabel());
gtk_tool_button_set_label(
GTK_TOOL_BUTTON(tool->m_item), wxGTK_CONV(label));
// needed for labels in horizontal toolbar with wxTB_HORZ_LAYOUT
gtk_tool_item_set_is_important(tool->m_item, true);
}
if (!HasFlag(wxTB_NO_TOOLTIPS) && !tool->GetShortHelp().empty())
{
#if GTK_CHECK_VERSION(2, 12, 0)
if (GTK_CHECK_VERSION(3,0,0) || gtk_check_version(2,12,0) == NULL)
{
gtk_tool_item_set_tooltip_text(tool->m_item,
wxGTK_CONV(tool->GetShortHelp()));
}
else
#endif
{
#ifndef __WXGTK3__
gtk_tool_item_set_tooltip(tool->m_item,
m_tooltips, wxGTK_CONV(tool->GetShortHelp()), "");
#endif
}
}
bin_child = gtk_bin_get_child(GTK_BIN(tool->m_item));
g_signal_connect(bin_child, "button_press_event",
G_CALLBACK(button_press_event), tool);
g_signal_connect(bin_child, "enter_notify_event",
G_CALLBACK(enter_notify_event), tool);
g_signal_connect(bin_child, "leave_notify_event",
G_CALLBACK(enter_notify_event), tool);
if (tool->GetKind() == wxITEM_DROPDOWN)
tool->CreateDropDown();
gtk_toolbar_insert(m_toolbar, tool->m_item, int(pos));
break;
case wxTOOL_STYLE_SEPARATOR:
tool->m_item = gtk_separator_tool_item_new();
if ( tool->IsStretchable() )
{
gtk_separator_tool_item_set_draw
(
GTK_SEPARATOR_TOOL_ITEM(tool->m_item),
FALSE
);
gtk_tool_item_set_expand(tool->m_item, TRUE);
}
gtk_toolbar_insert(m_toolbar, tool->m_item, int(pos));
break;
case wxTOOL_STYLE_CONTROL:
wxWindow* control = tool->GetControl();
if (gtk_widget_get_parent(control->m_widget) == NULL)
AddChildGTK(control);
tool->m_item = GTK_TOOL_ITEM(gtk_widget_get_parent(gtk_widget_get_parent(control->m_widget)));
if (gtk_toolbar_get_item_index(m_toolbar, tool->m_item) != int(pos))
{
g_object_ref(tool->m_item);
gtk_container_remove(
GTK_CONTAINER(m_toolbar), GTK_WIDGET(tool->m_item));
gtk_toolbar_insert(m_toolbar, tool->m_item, int(pos));
g_object_unref(tool->m_item);
}
break;
}
gtk_widget_show(GTK_WIDGET(tool->m_item));
InvalidateBestSize();
return true;
}
bool wxToolBar::DoDeleteTool(size_t /* pos */, wxToolBarToolBase* toolBase)
{
wxToolBarTool* tool = static_cast<wxToolBarTool*>(toolBase);
if (tool->GetStyle() == wxTOOL_STYLE_CONTROL)
{
// don't destroy the control here as we can be called from
// RemoveTool() and then we need to keep the control alive;
// while if we're called from DeleteTool() the control will
// be destroyed when wxToolBarToolBase itself is deleted
GtkWidget* widget = tool->GetControl()->m_widget;
gtk_container_remove(GTK_CONTAINER(gtk_widget_get_parent(widget)), widget);
}
gtk_widget_destroy(GTK_WIDGET(tool->m_item));
tool->m_item = NULL;
InvalidateBestSize();
return true;
}
GSList* wxToolBar::GetRadioGroup(size_t pos)
{
GSList* radioGroup = NULL;
GtkToolItem* item = NULL;
if (pos > 0)
{
item = gtk_toolbar_get_nth_item(m_toolbar, int(pos) - 1);
if (!GTK_IS_RADIO_TOOL_BUTTON(item))
item = NULL;
}
if (item == NULL && pos < m_tools.size())
{
item = gtk_toolbar_get_nth_item(m_toolbar, int(pos));
if (!GTK_IS_RADIO_TOOL_BUTTON(item))
item = NULL;
}
if (item)
radioGroup = gtk_radio_tool_button_get_group((GtkRadioToolButton*)item);
return radioGroup;
}
// ----------------------------------------------------------------------------
// wxToolBar tools state
// ----------------------------------------------------------------------------
void wxToolBar::DoEnableTool(wxToolBarToolBase *toolBase, bool enable)
{
wxToolBarTool* tool = static_cast<wxToolBarTool*>(toolBase);
if (tool->m_item)
gtk_widget_set_sensitive(GTK_WIDGET(tool->m_item), enable);
}
void wxToolBar::DoToggleTool( wxToolBarToolBase *toolBase, bool toggle )
{
wxToolBarTool* tool = static_cast<wxToolBarTool*>(toolBase);
if (tool->m_item)
{
g_signal_handlers_block_by_func(tool->m_item, (void*)item_toggled, tool);
gtk_toggle_tool_button_set_active(
GTK_TOGGLE_TOOL_BUTTON(tool->m_item), toggle);
g_signal_handlers_unblock_by_func(tool->m_item, (void*)item_toggled, tool);
}
}
void wxToolBar::DoSetToggle(wxToolBarToolBase * WXUNUSED(tool),
bool WXUNUSED(toggle))
{
// VZ: absolutely no idea about how to do it
wxFAIL_MSG( wxT("not implemented") );
}
// ----------------------------------------------------------------------------
// wxToolBar geometry
// ----------------------------------------------------------------------------
wxSize wxToolBar::DoGetBestSize() const
{
// Unfortunately, if overflow arrow is enabled GtkToolbar only reports size
// of arrow. To get the real size, the arrow is temporarily disabled here.
// This is gross, since it will cause a queue_resize, and could potentially
// lead to an infinite loop. But there seems to be no alternative, short of
// disabling the arrow entirely.
gtk_toolbar_set_show_arrow(m_toolbar, false);
const wxSize size = wxToolBarBase::DoGetBestSize();
gtk_toolbar_set_show_arrow(m_toolbar, true);
return size;
}
wxToolBarToolBase *wxToolBar::FindToolForPosition(wxCoord WXUNUSED(x),
wxCoord WXUNUSED(y)) const
{
// TODO: implement this using gtk_toolbar_get_drop_index()
wxFAIL_MSG( wxT("wxToolBar::FindToolForPosition() not implemented") );
return NULL;
}
void wxToolBar::SetToolShortHelp( int id, const wxString& helpString )
{
wxToolBarTool* tool = static_cast<wxToolBarTool*>(FindById(id));
if ( tool )
{
(void)tool->SetShortHelp(helpString);
if (tool->m_item)
{
#if GTK_CHECK_VERSION(2, 12, 0)
if (GTK_CHECK_VERSION(3,0,0) || gtk_check_version(2,12,0) == NULL)
{
gtk_tool_item_set_tooltip_text(tool->m_item,
wxGTK_CONV(helpString));
}
else
#endif
{
#ifndef __WXGTK3__
gtk_tool_item_set_tooltip(tool->m_item,
m_tooltips, wxGTK_CONV(helpString), "");
#endif
}
}
}
}
void wxToolBar::SetToolNormalBitmap( int id, const wxBitmap& bitmap )
{
wxToolBarTool* tool = static_cast<wxToolBarTool*>(FindById(id));
if ( tool )
{
wxCHECK_RET( tool->IsButton(), wxT("Can only set bitmap on button tools."));
tool->SetNormalBitmap(bitmap);
tool->SetImage();
}
}
void wxToolBar::SetToolDisabledBitmap( int id, const wxBitmap& bitmap )
{
wxToolBarTool* tool = static_cast<wxToolBarTool*>(FindById(id));
if ( tool )
{
wxCHECK_RET( tool->IsButton(), wxT("Can only set bitmap on button tools."));
tool->SetDisabledBitmap(bitmap);
}
}
// ----------------------------------------------------------------------------
// static
wxVisualAttributes
wxToolBar::GetClassDefaultAttributes(wxWindowVariant WXUNUSED(variant))
{
return GetDefaultAttributesFromGTKWidget(gtk_toolbar_new());
}
#endif // wxUSE_TOOLBAR_NATIVE
|
#ifndef _RIVE_CUBIC_MIRRORED_VERTEX_BASE_HPP_
#define _RIVE_CUBIC_MIRRORED_VERTEX_BASE_HPP_
#include "rive/core/field_types/core_double_type.hpp"
#include "rive/shapes/cubic_vertex.hpp"
namespace rive
{
class CubicMirroredVertexBase : public CubicVertex
{
protected:
typedef CubicVertex Super;
public:
static const uint16_t typeKey = 35;
/// Helper to quickly determine if a core object extends another without
/// RTTI at runtime.
bool isTypeOf(uint16_t typeKey) const override
{
switch (typeKey)
{
case CubicMirroredVertexBase::typeKey:
case CubicVertexBase::typeKey:
case PathVertexBase::typeKey:
case ContainerComponentBase::typeKey:
case ComponentBase::typeKey:
return true;
default:
return false;
}
}
uint16_t coreType() const override { return typeKey; }
static const uint16_t rotationPropertyKey = 82;
static const uint16_t distancePropertyKey = 83;
private:
float m_Rotation = 0.0f;
float m_Distance = 0.0f;
public:
inline float rotation() const { return m_Rotation; }
void rotation(float value)
{
if (m_Rotation == value)
{
return;
}
m_Rotation = value;
rotationChanged();
}
inline float distance() const { return m_Distance; }
void distance(float value)
{
if (m_Distance == value)
{
return;
}
m_Distance = value;
distanceChanged();
}
Core* clone() const override;
void copy(const CubicMirroredVertexBase& object)
{
m_Rotation = object.m_Rotation;
m_Distance = object.m_Distance;
CubicVertex::copy(object);
}
bool deserialize(uint16_t propertyKey, BinaryReader& reader) override
{
switch (propertyKey)
{
case rotationPropertyKey:
m_Rotation = CoreDoubleType::deserialize(reader);
return true;
case distancePropertyKey:
m_Distance = CoreDoubleType::deserialize(reader);
return true;
}
return CubicVertex::deserialize(propertyKey, reader);
}
protected:
virtual void rotationChanged() {}
virtual void distanceChanged() {}
};
} // namespace rive
#endif
|
#include <iomanip>
#include <prjxray/bit_ops.h>
#include <prjxray/xilinx/spartan6/frame_address.h>
namespace prjxray {
namespace xilinx {
namespace spartan6 {
// According to UG380 pg. 101 the Frame Address Register (FAR)
// consists of two 16-bit registers (FAR MAJOR and FAR MINOR).
// We construct the 32-bit frame address from these two.
FrameAddress::FrameAddress(spartan6::BlockType block_type,
uint8_t row,
uint8_t column,
uint16_t minor) {
address_ = bit_field_set(0, 31, 28, block_type);
address_ =
bit_field_set(address_, 27, 24, row); // high register, bit 8-11
address_ =
bit_field_set(address_, 23, 16, column); // high register, bits 0-7
address_ =
bit_field_set(address_, 9, 0, minor); // low register, bit 0-9
}
bool FrameAddress::is_bottom_half_rows() const {
return false;
}
spartan6::BlockType FrameAddress::block_type() const {
return static_cast<typename spartan6::BlockType>(
bit_field_get(address_, 31, 28));
}
uint8_t FrameAddress::row() const {
return bit_field_get(address_, 27, 24);
}
uint8_t FrameAddress::column() const {
return bit_field_get(address_, 23, 16);
}
uint16_t FrameAddress::minor() const {
return bit_field_get(address_, 9, 0);
}
std::ostream& operator<<(std::ostream& o, const FrameAddress& addr) {
o << "[" << std::hex << std::showbase << std::setw(10)
<< static_cast<uint32_t>(addr) << "] "
<< " Row=" << std::setw(2) << std::dec
<< static_cast<unsigned int>(addr.row()) << "Column =" << std::setw(2)
<< std::dec << addr.column() << " Minor=" << std::setw(2) << std::dec
<< static_cast<unsigned int>(addr.minor())
<< " Type=" << addr.block_type();
return o;
}
} // namespace spartan6
} // namespace xilinx
} // namespace prjxray
namespace YAML {
namespace spartan6 = prjxray::xilinx::spartan6;
Node convert<spartan6::FrameAddress>::encode(
const spartan6::FrameAddress& rhs) {
Node node;
node.SetTag("xilinx/spartan6/frame_address");
node["block_type"] = rhs.block_type();
node["row"] = static_cast<unsigned int>(rhs.row());
node["column"] = static_cast<unsigned int>(rhs.column());
node["minor"] = static_cast<unsigned int>(rhs.minor());
return node;
}
bool convert<spartan6::FrameAddress>::decode(const Node& node,
spartan6::FrameAddress& lhs) {
if (!(node.Tag() == "xilinx/spartan6/frame_address" ||
node.Tag() == "xilinx/spartan6/configuration_frame_address") ||
!node["block_type"] || !node["row"] || !node["column"] ||
!node["minor"])
return false;
lhs = spartan6::FrameAddress(
node["block_type"].as<spartan6::BlockType>(),
node["row"].as<unsigned int>(), node["column"].as<unsigned int>(),
node["minor"].as<unsigned int>());
return true;
}
} // namespace YAML
|
/* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
// First include (the generated) my_config.h, to get correct platform defines.
#include "my_config.h"
#include <gtest/gtest.h>
#include <gmock/gmock.h>
// Ignore test on windows, as we are mocking away a unix function, see below.
#ifndef _WIN32
namespace mysys_my_write_unittest {
using ::testing::_;
using ::testing::InSequence;
using ::testing::Return;
using ::testing::SetErrnoAndReturn;
class MockWrite
{
public:
virtual ~MockWrite() {}
MOCK_METHOD3(mockwrite, ssize_t(int, const void *, size_t));
};
MockWrite *mockfs= NULL;
// We need to mock away write(2), do it with a macro:
#define write(fd, buf, count) mockfs->mockwrite(fd, buf, count)
/*
Include the source file, which will give us
mysys_my_write_unittest::my_write() for testing.
*/
#include "../../mysys/my_write.c"
#undef write
class MysysMyWriteTest : public ::testing::Test
{
virtual void SetUp()
{
mockfs= new MockWrite;
}
virtual void TearDown()
{
delete mockfs;
mockfs= NULL;
}
};
// Test of normal case: write OK
TEST_F(MysysMyWriteTest, MyWriteOK)
{
uchar buf[4096];
InSequence s;
EXPECT_CALL(*mockfs, mockwrite(_, _, 4096))
.Times(1)
.WillOnce(Return(4096));
const size_t result= my_write(42, buf, 4096, 0);
EXPECT_EQ(4096U, result);
}
// Test of normal case: write OK with MY_NABP
TEST_F(MysysMyWriteTest, MyWriteOKNABP)
{
uchar buf[4096];
InSequence s;
EXPECT_CALL(*mockfs, mockwrite(_, _, 4096))
.Times(1)
.WillOnce(Return(4096));
const size_t result= my_write(42, buf, 4096, MYF(MY_NABP));
EXPECT_EQ(0U, result);
}
// Test of disk full: write not OK
TEST_F(MysysMyWriteTest, MyWriteFail)
{
uchar buf[4096];
InSequence s;
EXPECT_CALL(*mockfs, mockwrite(_, _, 4096))
.Times(1)
.WillOnce(SetErrnoAndReturn(ENOSPC, -1));
const size_t result= my_write(42, buf, 4096, 0);
EXPECT_EQ(MY_FILE_ERROR, result);
}
// Test of disk full: write not OK, with MY_NABP
TEST_F(MysysMyWriteTest, MyWriteFailNABP)
{
uchar buf[4096];
InSequence s;
EXPECT_CALL(*mockfs, mockwrite(_, _, 4096))
.Times(1)
.WillOnce(SetErrnoAndReturn(ENOSPC, -1));
const size_t result= my_write(42, buf, 4096, MYF(MY_NABP));
EXPECT_EQ(MY_FILE_ERROR, result);
}
// Test of disk full after partial write.
TEST_F(MysysMyWriteTest, MyWrite8192)
{
uchar buf[8192];
InSequence s;
// Expect call to write 8192 bytes, return 4096.
EXPECT_CALL(*mockfs, mockwrite(_, _, 8192))
.Times(1)
.WillOnce(Return(4096));
// Expect second call to write remaining 4096 bytes, return disk full.
EXPECT_CALL(*mockfs, mockwrite(_, _, 4096))
.Times(1)
.WillOnce(SetErrnoAndReturn(ENOSPC, -1));
const size_t result= my_write(42, buf, 8192, 0);
EXPECT_EQ(4096U, result);
}
// Test of disk full after partial write.
TEST_F(MysysMyWriteTest, MyWrite8192NABP)
{
uchar buf[8192];
InSequence s;
// Expect call to write 8192 bytes, return 4096.
EXPECT_CALL(*mockfs, mockwrite(_, _, 8192))
.Times(1)
.WillOnce(Return(4096));
// Expect second call to write remaining 4096 bytes, return disk full.
EXPECT_CALL(*mockfs, mockwrite(_, _, 4096))
.Times(1)
.WillOnce(SetErrnoAndReturn(ENOSPC, -1));
const size_t result= my_write(42, buf, 8192, MYF(MY_NABP));
EXPECT_EQ(MY_FILE_ERROR, result);
}
// Test of partial write, followed by interrupt, followed by successful write.
TEST_F(MysysMyWriteTest, MyWrite8192Interrupt)
{
uchar buf[8192];
InSequence s;
// Expect call to write 8192 bytes, return 4096.
EXPECT_CALL(*mockfs, mockwrite(_, _, 8192))
.Times(1)
.WillOnce(Return(4096));
// Expect second call to write remaining 4096 bytes, return interrupt.
EXPECT_CALL(*mockfs, mockwrite(_, _, 4096))
.Times(1)
.WillOnce(SetErrnoAndReturn(EINTR, -1));
// Expect third call to write remaining 4096 bytes, return 4096.
EXPECT_CALL(*mockfs, mockwrite(_, _, 4096))
.Times(1)
.WillOnce(Return(4096));
const size_t result= my_write(42, buf, 8192, 0);
EXPECT_EQ(8192U, result);
}
// Test of partial write, followed by interrupt, followed by successful write.
TEST_F(MysysMyWriteTest, MyWrite8192InterruptNABP)
{
uchar buf[8192];
InSequence s;
// Expect call to write 8192 bytes, return 4096.
EXPECT_CALL(*mockfs, mockwrite(_, _, 8192))
.Times(1)
.WillOnce(Return(4096));
// Expect second call to write remaining 4096 bytes, return interrupt.
EXPECT_CALL(*mockfs, mockwrite(_, _, 4096))
.Times(1)
.WillOnce(SetErrnoAndReturn(EINTR, -1));
// Expect third call to write remaining 4096 bytes, return 4096.
EXPECT_CALL(*mockfs, mockwrite(_, _, 4096))
.Times(1)
.WillOnce(Return(4096));
const size_t result= my_write(42, buf, 8192, MYF(MY_NABP));
EXPECT_EQ(0U, result);
}
// Test of partial write, followed successful write.
TEST_F(MysysMyWriteTest, MyWrite400)
{
uchar buf[400];
InSequence s;
EXPECT_CALL(*mockfs, mockwrite(_, _, 400))
.Times(1)
.WillOnce(Return(200));
EXPECT_CALL(*mockfs, mockwrite(_, _, 200))
.Times(1)
.WillOnce(Return(200));
const size_t result= my_write(42, buf, 400, 0);
EXPECT_EQ(400U, result);
}
// Test of partial write, followed successful write.
TEST_F(MysysMyWriteTest, MyWrite400NABP)
{
uchar buf[400];
InSequence s;
EXPECT_CALL(*mockfs, mockwrite(_, _, 400))
.Times(1)
.WillOnce(Return(200));
EXPECT_CALL(*mockfs, mockwrite(_, _, 200))
.Times(1)
.WillOnce(Return(200));
const size_t result= my_write(42, buf, 400, MYF(MY_NABP));
EXPECT_EQ(0U, result);
}
// Test of partial write, followed by failure, followed successful write.
TEST_F(MysysMyWriteTest, MyWrite300)
{
uchar buf[300];
InSequence s;
EXPECT_CALL(*mockfs, mockwrite(_, _, 300))
.Times(1)
.WillOnce(Return(100));
EXPECT_CALL(*mockfs, mockwrite(_, _, 200))
.Times(1)
.WillOnce(SetErrnoAndReturn(EAGAIN, 0));
EXPECT_CALL(*mockfs, mockwrite(_, _, 200))
.Times(1)
.WillOnce(Return(200));
const size_t result= my_write(42, buf, 300, 0);
EXPECT_EQ(300U, result);
}
}
#endif
|
/*
* ----------------- BEGIN LICENSE BLOCK ---------------------------------
*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
* ----------------- END LICENSE BLOCK -----------------------------------
*/
/**
* Generated file
* @file
*
* Generator Version : 11.0.0-1997
*/
#pragma once
#include <iostream>
#include <sstream>
#include <vector>
#include "ad/physics/Distance2D.hpp"
/*!
* @brief namespace ad
*/
namespace ad {
/*!
* @brief namespace physics
*/
namespace physics {
/*!
* \brief DataType Distance2DList
*
* List of Distance2D
*/
typedef std::vector<::ad::physics::Distance2D> Distance2DList;
} // namespace physics
} // namespace ad
/*!
* \brief protect the definition of functions from duplicates by typedef usage within other data types
*/
#ifndef GEN_GUARD_VECTOR_AD_PHYSICS_DISTANCE2D
#define GEN_GUARD_VECTOR_AD_PHYSICS_DISTANCE2D
namespace std {
/**
* \brief standard ostream operator
*
* \param[in] os The output stream to write to
* \param[in] _value Distance2DList value
*
* \returns The stream object.
*
*/
inline std::ostream &operator<<(std::ostream &os, vector<::ad::physics::Distance2D> const &_value)
{
os << "[";
for (auto it = _value.begin(); it != _value.end(); it++)
{
if (it != _value.begin())
{
os << ",";
}
os << *it;
}
os << "]";
return os;
}
} // namespace std
namespace std {
/*!
* \brief overload of the std::to_string for Distance2DList
*/
inline std::string to_string(::ad::physics::Distance2DList const &value)
{
stringstream sstream;
sstream << value;
return sstream.str();
}
} // namespace std
#endif // GEN_GUARD_VECTOR_AD_PHYSICS_DISTANCE2D
|
/*++
Copyright (C) 2015 Microsoft Corporation
Copyright (C) 2015 netfabb GmbH (Original Author)
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 HOLDER 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.
Abstract:
NMR_ImportStream_COM.cpp defines the CImportStream_COM Class.
This is an abstract base stream class for importing from COM IStreams.
--*/
#include "Common/Platform/NMR_ImportStream_COM.h"
#include "Common/NMR_Exception.h"
#include "Common/NMR_Exception_Windows.h"
#include <cmath>
#include <vector>
namespace NMR {
CImportStream_COM::CImportStream_COM()
{
// empty on purpose
}
CImportStream_COM::CImportStream_COM(_In_ CComPtr <IStream> pStream) : CImportStream()
{
if (pStream == nullptr)
throw CNMRException(NMR_ERROR_INVALIDPARAM);
m_pStream = pStream;
}
CImportStream_COM::CImportStream_COM(_In_ LPCWSTR pwszFileName)
{
if (!pwszFileName)
throw CNMRException(NMR_ERROR_INVALIDPARAM);
HRESULT hResult = SHCreateStreamOnFileEx(pwszFileName, STGM_READ | STGM_SHARE_DENY_WRITE, 0, false, NULL, &m_pStream);
if (hResult != S_OK)
throw CNMRException_Windows(NMR_ERROR_COULDNOTOPENFILE, hResult);
}
nfBool CImportStream_COM::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed)
{
LARGE_INTEGER filepos;
HRESULT hResult;
filepos.QuadPart = position;
hResult = m_pStream->Seek(filepos, STREAM_SEEK_SET, NULL);
if ((hResult != S_OK) && bHasToSucceed)
throw CNMRException_Windows(NMR_ERROR_COULDNOTSEEKSTREAM, hResult);
return (hResult == S_OK);
}
nfBool CImportStream_COM::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed)
{
LARGE_INTEGER offset;
HRESULT hResult;
offset.QuadPart = bytes;
hResult = m_pStream->Seek(offset, STREAM_SEEK_CUR, NULL);
if ((hResult != S_OK) && bHasToSucceed)
throw CNMRException_Windows(NMR_ERROR_COULDNOTSEEKSTREAM, hResult);
return (hResult == S_OK);
}
nfBool CImportStream_COM::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed)
{
LARGE_INTEGER offset;
HRESULT hResult;
ULARGE_INTEGER newfilepos;
offset.QuadPart = bytes;
hResult = m_pStream->Seek(offset, STREAM_SEEK_END, &newfilepos);
if ((hResult != S_OK) && bHasToSucceed)
throw CNMRException_Windows(NMR_ERROR_COULDNOTSEEKSTREAM, hResult);
return (hResult == S_OK);
}
nfUint64 CImportStream_COM::readBuffer(_In_ nfByte * pBuffer, _In_ nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll)
{
HRESULT hResult;
ULONG cbBytesToRead;
ULONG cbReadBytes;
nfUint64 cbTotalReadBytes = 0;
nfUint64 cbBytesLeft = cbTotalBytesToRead;
if (cbBytesLeft == 0)
return cbBytesLeft;
if (!pBuffer)
throw CNMRException(NMR_ERROR_INVALIDPARAM);
nfByte * pData = (nfByte *)pBuffer;
while (cbBytesLeft > 0) {
if (cbBytesLeft > NMR_IMPORTSTREAM_READBUFFERSIZE)
cbBytesToRead = NMR_IMPORTSTREAM_READBUFFERSIZE;
else
cbBytesToRead = (ULONG)cbBytesLeft;
cbBytesLeft -= cbBytesToRead;
hResult = m_pStream->Read(pData, cbBytesToRead, &cbReadBytes);
if (hResult != S_OK)
throw CNMRException_Windows(NMR_ERROR_COULDNOTREADSTREAM, hResult);
cbTotalReadBytes += cbReadBytes;
if (cbReadBytes != cbBytesToRead)
break;
pData += cbReadBytes;
}
if ((cbTotalReadBytes != cbTotalBytesToRead) && bNeedsToReadAll)
throw CNMRException_Windows(NMR_ERROR_COULDNOTREADFULLDATA, hResult);
return cbTotalReadBytes;
}
CComPtr <IStream> CImportStream_COM::getCOMStream()
{
return m_pStream;
}
nfUint64 CImportStream_COM::retrieveSize()
{
nfUint64 nOrigPosition = getPosition();
LARGE_INTEGER offset;
HRESULT hResult;
ULARGE_INTEGER newfilepos;
offset.QuadPart = 0;
hResult = m_pStream->Seek(offset, STREAM_SEEK_END, &newfilepos);
if (hResult != S_OK)
throw CNMRException_Windows(NMR_ERROR_COULDNOTSEEKSTREAM, hResult);
seekPosition(nOrigPosition, true);
return newfilepos.QuadPart;
}
nfUint64 CImportStream_COM::getPosition()
{
LARGE_INTEGER offset;
HRESULT hResult;
ULARGE_INTEGER newfilepos;
offset.QuadPart = 0;
hResult = m_pStream->Seek(offset, STREAM_SEEK_CUR, &newfilepos);
if (hResult != S_OK)
throw CNMRException_Windows(NMR_ERROR_COULDNOTSEEKSTREAM, hResult);
return newfilepos.QuadPart;
}
void CImportStream_COM::writeToFile(_In_ const nfWChar * pwszFileName)
{
if (!pwszFileName)
throw CNMRException(NMR_ERROR_INVALIDPARAM);
CComPtr<IStream> pFileStream;
HRESULT hResult = SHCreateStreamOnFileEx(pwszFileName, STGM_CREATE | STGM_WRITE, 0, false, NULL, &pFileStream);
if (hResult != S_OK)
throw CNMRException_Windows(NMR_ERROR_COULDNOTCREATEFILE, hResult);
nfUint64 cbStreamSize = retrieveSize();
std::vector<nfByte> pBuffer;
pBuffer.resize(NMR_IMPORTSTREAM_COPYBUFFERSIZE);
nfUint64 cbBytesLeft = cbStreamSize;
while (cbBytesLeft > 0) {
nfUint64 cbLength = cbBytesLeft;
if (cbLength > NMR_IMPORTSTREAM_COPYBUFFERSIZE)
cbLength = NMR_IMPORTSTREAM_COPYBUFFERSIZE;
ULONG cbWrittenBytes = 0;
readBuffer(pBuffer.data(), cbLength, true);
HRESULT hResult = pFileStream->Write(pBuffer.data(), (nfUint32)cbLength, &cbWrittenBytes);
if (hResult != S_OK)
throw CNMRException_Windows(NMR_ERROR_COULDNOTWRITESTREAM, hResult);
if (cbWrittenBytes != cbLength)
throw CNMRException(NMR_ERROR_COULDNOTWRITEFULLDATA);
cbBytesLeft -= cbLength;
}
}
PImportStream CImportStream_COM::copyToMemory()
{
CComPtr<IStream> pMemoryStream = nullptr;
HRESULT hResult = CreateStreamOnHGlobal(nullptr, true, &pMemoryStream);
if (hResult != S_OK)
throw CNMRException_Windows(NMR_ERROR_COULDNOTCREATESTREAM, hResult);
nfUint64 cbStreamSize = retrieveSize();
std::vector<nfByte> pBuffer;
pBuffer.resize(NMR_IMPORTSTREAM_COPYBUFFERSIZE);
nfUint64 cbBytesLeft = cbStreamSize;
while (cbBytesLeft > 0) {
nfUint64 cbLength = cbBytesLeft;
if (cbLength > NMR_IMPORTSTREAM_COPYBUFFERSIZE)
cbLength = NMR_IMPORTSTREAM_COPYBUFFERSIZE;
ULONG cbWrittenBytes = 0;
readBuffer(pBuffer.data(), cbLength, true);
HRESULT hResult = pMemoryStream->Write(pBuffer.data(), (nfUint32)cbLength, &cbWrittenBytes);
if (hResult != S_OK)
throw CNMRException_Windows(NMR_ERROR_COULDNOTWRITESTREAM, hResult);
if (cbWrittenBytes != cbLength)
throw CNMRException(NMR_ERROR_COULDNOTWRITEFULLDATA);
cbBytesLeft -= cbLength;
}
LARGE_INTEGER filepos;
filepos.QuadPart = 0;
hResult = pMemoryStream->Seek(filepos, STREAM_SEEK_SET, NULL);
if (hResult != S_OK)
throw CNMRException_Windows(NMR_ERROR_COULDNOTSEEKSTREAM, hResult);
return std::make_shared<CImportStream_COM>(pMemoryStream);
}
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/rand_util.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/infobars/confirm_infobar_delegate.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/translate/translate_infobar_delegate.h"
#include "chrome/browser/translate/translate_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/render_messages.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/autofill/browser/autofill_common_test.h"
#include "components/autofill/browser/autofill_external_delegate.h"
#include "components/autofill/browser/autofill_manager.h"
#include "components/autofill/browser/autofill_manager_test_delegate.h"
#include "components/autofill/browser/autofill_profile.h"
#include "components/autofill/browser/credit_card.h"
#include "components/autofill/browser/personal_data_manager.h"
#include "components/autofill/browser/personal_data_manager_observer.h"
#include "components/autofill/browser/validation.h"
#include "components/autofill/content/browser/autofill_driver_impl.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/test_utils.h"
#include "net/url_request/test_url_fetcher_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/keycodes/keyboard_codes.h"
using content::RenderViewHost;
using content::RenderViewHostTester;
using content::WebContents;
using testing::Invoke;
namespace autofill {
static const char* kDataURIPrefix = "data:text/html;charset=utf-8,";
static const char* kTestFormString =
"<form action=\"http://www.example.com/\" method=\"POST\">"
"<label for=\"firstname\">First name:</label>"
" <input type=\"text\" id=\"firstname\""
" onFocus=\"domAutomationController.send(true)\"><br>"
"<label for=\"lastname\">Last name:</label>"
" <input type=\"text\" id=\"lastname\"><br>"
"<label for=\"address1\">Address line 1:</label>"
" <input type=\"text\" id=\"address1\"><br>"
"<label for=\"address2\">Address line 2:</label>"
" <input type=\"text\" id=\"address2\"><br>"
"<label for=\"city\">City:</label>"
" <input type=\"text\" id=\"city\"><br>"
"<label for=\"state\">State:</label>"
" <select id=\"state\">"
" <option value=\"\" selected=\"yes\">--</option>"
" <option value=\"CA\">California</option>"
" <option value=\"TX\">Texas</option>"
" </select><br>"
"<label for=\"zip\">ZIP code:</label>"
" <input type=\"text\" id=\"zip\"><br>"
"<label for=\"country\">Country:</label>"
" <select id=\"country\">"
" <option value=\"\" selected=\"yes\">--</option>"
" <option value=\"CA\">Canada</option>"
" <option value=\"US\">United States</option>"
" </select><br>"
"<label for=\"phone\">Phone number:</label>"
" <input type=\"text\" id=\"phone\"><br>"
"</form>";
class AutofillManagerTestDelegateImpl
: public autofill::AutofillManagerTestDelegate {
public:
AutofillManagerTestDelegateImpl() {}
virtual void DidPreviewFormData() OVERRIDE {
loop_runner_->Quit();
}
virtual void DidFillFormData() OVERRIDE {
loop_runner_->Quit();
}
virtual void DidShowSuggestions() OVERRIDE {
loop_runner_->Quit();
}
void Reset() {
loop_runner_ = new content::MessageLoopRunner();
}
void Wait() {
loop_runner_->Run();
}
private:
scoped_refptr<content::MessageLoopRunner> loop_runner_;
DISALLOW_COPY_AND_ASSIGN(AutofillManagerTestDelegateImpl);
};
class WindowedPersonalDataManagerObserver
: public PersonalDataManagerObserver,
public content::NotificationObserver {
public:
explicit WindowedPersonalDataManagerObserver(Browser* browser)
: alerted_(false),
has_run_message_loop_(false),
browser_(browser),
infobar_service_(NULL) {
PersonalDataManagerFactory::GetForProfile(browser_->profile())->
AddObserver(this);
registrar_.Add(this, chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
content::NotificationService::AllSources());
}
virtual ~WindowedPersonalDataManagerObserver() {
if (infobar_service_ && infobar_service_->infobar_count() > 0)
infobar_service_->RemoveInfoBar(infobar_service_->infobar_at(0));
}
void Wait() {
if (!alerted_) {
has_run_message_loop_ = true;
content::RunMessageLoop();
}
PersonalDataManagerFactory::GetForProfile(browser_->profile())->
RemoveObserver(this);
}
// PersonalDataManagerObserver:
virtual void OnPersonalDataChanged() OVERRIDE {
if (has_run_message_loop_) {
base::MessageLoopForUI::current()->Quit();
has_run_message_loop_ = false;
}
alerted_ = true;
}
virtual void OnInsufficientFormData() OVERRIDE {
OnPersonalDataChanged();
}
// content::NotificationObserver:
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) OVERRIDE {
// Accept in the infobar.
infobar_service_ = InfoBarService::FromWebContents(
browser_->tab_strip_model()->GetActiveWebContents());
InfoBarDelegate* infobar = infobar_service_->infobar_at(0);
ConfirmInfoBarDelegate* confirm_infobar =
infobar->AsConfirmInfoBarDelegate();
confirm_infobar->Accept();
}
private:
bool alerted_;
bool has_run_message_loop_;
Browser* browser_;
content::NotificationRegistrar registrar_;
InfoBarService* infobar_service_;
};
class TestAutofillExternalDelegate : public AutofillExternalDelegate {
public:
TestAutofillExternalDelegate(content::WebContents* web_contents,
AutofillManager* autofill_manager)
: AutofillExternalDelegate(web_contents, autofill_manager),
keyboard_listener_(NULL) {
}
virtual ~TestAutofillExternalDelegate() {}
virtual void OnPopupShown(content::KeyboardListener* listener) OVERRIDE {
AutofillExternalDelegate::OnPopupShown(listener);
keyboard_listener_ = listener;
}
virtual void OnPopupHidden(content::KeyboardListener* listener) OVERRIDE {
keyboard_listener_ = NULL;
AutofillExternalDelegate::OnPopupHidden(listener);
}
content::KeyboardListener* keyboard_listener() {
return keyboard_listener_;
}
private:
// The popup that is currently registered as a keyboard listener, or NULL if
// there is none.
content::KeyboardListener* keyboard_listener_;
DISALLOW_COPY_AND_ASSIGN(TestAutofillExternalDelegate);
};
class AutofillTest : public InProcessBrowserTest {
protected:
AutofillTest() {}
virtual void SetUpOnMainThread() OVERRIDE {
// Don't want Keychain coming up on Mac.
test::DisableSystemServices(browser()->profile());
// When testing the native UI, hook up a test external delegate, which
// allows us to forward keyboard events to the popup directly.
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
AutofillManager* autofill_manager =
AutofillDriverImpl::FromWebContents(web_contents)->autofill_manager();
if (autofill_manager->IsNativeUiEnabled()) {
external_delegate_.reset(
new TestAutofillExternalDelegate(web_contents, autofill_manager));
autofill_manager->SetExternalDelegate(external_delegate_.get());
}
autofill_manager->SetTestDelegate(&test_delegate_);
}
virtual void CleanUpOnMainThread() OVERRIDE {
// Make sure to close any showing popups prior to tearing down the UI.
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
AutofillManager* autofill_manager =
AutofillDriverImpl::FromWebContents(web_contents)->autofill_manager();
autofill_manager->delegate()->HideAutofillPopup();
}
PersonalDataManager* personal_data_manager() {
return PersonalDataManagerFactory::GetForProfile(browser()->profile());
}
void CreateTestProfile() {
AutofillProfile profile;
test::SetProfileInfo(
&profile, "Milton", "C.", "Waddams",
"red.swingline@initech.com", "Initech", "4120 Freidrich Lane",
"Basement", "Austin", "Texas", "78744", "US", "5125551234");
WindowedPersonalDataManagerObserver observer(browser());
personal_data_manager()->AddProfile(profile);
// AddProfile is asynchronous. Wait for it to finish before continuing the
// tests.
observer.Wait();
}
void SetProfiles(std::vector<AutofillProfile>* profiles) {
WindowedPersonalDataManagerObserver observer(browser());
personal_data_manager()->SetProfiles(profiles);
observer.Wait();
}
void SetProfile(const AutofillProfile& profile) {
std::vector<AutofillProfile> profiles;
profiles.push_back(profile);
SetProfiles(&profiles);
}
void SetCards(std::vector<CreditCard>* cards) {
WindowedPersonalDataManagerObserver observer(browser());
personal_data_manager()->SetCreditCards(cards);
observer.Wait();
}
void SetCard(const CreditCard& card) {
std::vector<CreditCard> cards;
cards.push_back(card);
SetCards(&cards);
}
typedef std::map<std::string, std::string> FormMap;
// Navigate to the form, input values into the fields, and submit the form.
// The function returns after the PersonalDataManager is updated.
void FillFormAndSubmit(const std::string& filename, const FormMap& data) {
GURL url = test_server()->GetURL("files/autofill/" + filename);
ui_test_utils::NavigateToURL(browser(), url);
std::string js;
for (FormMap::const_iterator i = data.begin(); i != data.end(); ++i) {
js += "document.getElementById('" + i->first + "').value = '" +
i->second + "';";
}
js += "document.getElementById('testform').submit();";
WindowedPersonalDataManagerObserver observer(browser());
ASSERT_TRUE(content::ExecuteScript(render_view_host(), js));
observer.Wait();
}
void SubmitCreditCard(const char* name,
const char* number,
const char* exp_month,
const char* exp_year) {
FormMap data;
data["CREDIT_CARD_NAME"] = name;
data["CREDIT_CARD_NUMBER"] = number;
data["CREDIT_CARD_EXP_MONTH"] = exp_month;
data["CREDIT_CARD_EXP_4_DIGIT_YEAR"] = exp_year;
FillFormAndSubmit("autofill_creditcard_form.html", data);
}
// Populates a webpage form using autofill data and keypress events.
// This function focuses the specified input field in the form, and then
// sends keypress events to the tab to cause the form to be populated.
void PopulateForm(const std::string& field_id) {
std::string js("document.getElementById('" + field_id + "').focus();");
ASSERT_TRUE(content::ExecuteScript(render_view_host(), js));
SendKeyToPageAndWait(ui::VKEY_DOWN);
SendKeyToPopupAndWait(ui::VKEY_DOWN);
SendKeyToPopupAndWait(ui::VKEY_RETURN);
}
// Aggregate profiles from forms into Autofill preferences. Returns the number
// of parsed profiles.
int AggregateProfilesIntoAutofillPrefs(const std::string& filename) {
CHECK(test_server()->Start());
std::string data;
base::FilePath data_file =
ui_test_utils::GetTestFilePath(base::FilePath().AppendASCII("autofill"),
base::FilePath().AppendASCII(filename));
CHECK(file_util::ReadFileToString(data_file, &data));
std::vector<std::string> lines;
base::SplitString(data, '\n', &lines);
for (size_t i = 0; i < lines.size(); ++i) {
if (StartsWithASCII(lines[i], "#", false))
continue;
std::vector<std::string> fields;
base::SplitString(lines[i], '|', &fields);
if (fields.empty())
continue; // Blank line.
CHECK_EQ(12u, fields.size());
FormMap data;
data["NAME_FIRST"] = fields[0];
data["NAME_MIDDLE"] = fields[1];
data["NAME_LAST"] = fields[2];
data["EMAIL_ADDRESS"] = fields[3];
data["COMPANY_NAME"] = fields[4];
data["ADDRESS_HOME_LINE1"] = fields[5];
data["ADDRESS_HOME_LINE2"] = fields[6];
data["ADDRESS_HOME_CITY"] = fields[7];
data["ADDRESS_HOME_STATE"] = fields[8];
data["ADDRESS_HOME_ZIP"] = fields[9];
data["ADDRESS_HOME_COUNTRY"] = fields[10];
data["PHONE_HOME_WHOLE_NUMBER"] = fields[11];
FillFormAndSubmit("duplicate_profiles_test.html", data);
}
return lines.size();
}
void ExpectFieldValue(const std::string& field_name,
const std::string& expected_value) {
std::string value;
ASSERT_TRUE(content::ExecuteScriptAndExtractString(
browser()->tab_strip_model()->GetActiveWebContents(),
"window.domAutomationController.send("
" document.getElementById('" + field_name + "').value);",
&value));
EXPECT_EQ(expected_value, value);
}
RenderViewHost* render_view_host() {
return browser()->tab_strip_model()->GetActiveWebContents()->
GetRenderViewHost();
}
void SimulateURLFetch(bool success) {
net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
ASSERT_TRUE(fetcher);
net::URLRequestStatus status;
status.set_status(success ? net::URLRequestStatus::SUCCESS :
net::URLRequestStatus::FAILED);
std::string script = " var google = {};"
"google.translate = (function() {"
" return {"
" TranslateService: function() {"
" return {"
" isAvailable : function() {"
" return true;"
" },"
" restore : function() {"
" return;"
" },"
" getDetectedLanguage : function() {"
" return \"ja\";"
" },"
" translatePage : function(originalLang, targetLang,"
" onTranslateProgress) {"
" document.getElementsByTagName(\"body\")[0].innerHTML = '" +
std::string(kTestFormString) +
" ';"
" onTranslateProgress(100, true, false);"
" }"
" };"
" }"
" };"
"})();";
fetcher->set_url(fetcher->GetOriginalURL());
fetcher->set_status(status);
fetcher->set_response_code(success ? 200 : 500);
fetcher->SetResponseString(script);
fetcher->delegate()->OnURLFetchComplete(fetcher);
}
void FocusFirstNameField() {
LOG(WARNING) << "Clicking on the tab.";
content::SimulateMouseClick(
browser()->tab_strip_model()->GetActiveWebContents(),
0,
WebKit::WebMouseEvent::ButtonLeft);
LOG(WARNING) << "Focusing the first name field.";
bool result = false;
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
render_view_host(),
"if (document.readyState === 'complete')"
" document.getElementById('firstname').focus();"
"else"
" domAutomationController.send(false);",
&result));
ASSERT_TRUE(result);
}
void ExpectFilledTestForm() {
ExpectFieldValue("firstname", "Milton");
ExpectFieldValue("lastname", "Waddams");
ExpectFieldValue("address1", "4120 Freidrich Lane");
ExpectFieldValue("address2", "Basement");
ExpectFieldValue("city", "Austin");
ExpectFieldValue("state", "TX");
ExpectFieldValue("zip", "78744");
ExpectFieldValue("country", "US");
ExpectFieldValue("phone", "5125551234");
}
void SendKeyToPageAndWait(ui::KeyboardCode key) {
test_delegate_.Reset();
content::SimulateKeyPress(
browser()->tab_strip_model()->GetActiveWebContents(),
key, false, false, false, false);
test_delegate_.Wait();
}
void SendKeyToPopupAndWait(ui::KeyboardCode key) {
// TODO(isherman): Remove this condition once the WebKit popup UI code is
// removed.
if (!external_delegate_) {
// When testing the WebKit-based UI, route all keys to the page.
SendKeyToPageAndWait(key);
return;
}
// When testing the native UI, route popup-targeted key presses via the
// external delegate.
content::NativeWebKeyboardEvent event;
event.windowsKeyCode = key;
test_delegate_.Reset();
external_delegate_->keyboard_listener()->HandleKeyPressEvent(event);
test_delegate_.Wait();
}
void TryBasicFormFill() {
FocusFirstNameField();
// Start filling the first name field with "M" and wait for the popup to be
// shown.
LOG(WARNING) << "Typing 'M' to bring up the Autofill popup.";
SendKeyToPageAndWait(ui::VKEY_M);
// Press the down arrow to select the suggestion and preview the autofilled
// form.
LOG(WARNING) << "Simulating down arrow press to initiate Autofill preview.";
SendKeyToPopupAndWait(ui::VKEY_DOWN);
// The previewed values should not be accessible to JavaScript.
ExpectFieldValue("firstname", "M");
ExpectFieldValue("lastname", std::string());
ExpectFieldValue("address1", std::string());
ExpectFieldValue("address2", std::string());
ExpectFieldValue("city", std::string());
ExpectFieldValue("state", std::string());
ExpectFieldValue("zip", std::string());
ExpectFieldValue("country", std::string());
ExpectFieldValue("phone", std::string());
// TODO(isherman): It would be nice to test that the previewed values are
// displayed: http://crbug.com/57220
// Press Enter to accept the autofill suggestions.
LOG(WARNING) << "Simulating Return press to fill the form.";
SendKeyToPopupAndWait(ui::VKEY_RETURN);
// The form should be filled.
ExpectFilledTestForm();
}
TestAutofillExternalDelegate* external_delegate() {
return external_delegate_.get();
}
AutofillManagerTestDelegateImpl test_delegate_;
private:
net::TestURLFetcherFactory url_fetcher_factory_;
scoped_ptr<TestAutofillExternalDelegate> external_delegate_;
};
// http://crbug.com/150084
#if defined(OS_MACOSX)
#define MAYBE_BasicFormFill BasicFormFill
#else
#define MAYBE_BasicFormFill DISABLED_BasicFormFill
#endif
// Test that basic form fill is working.
IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_BasicFormFill) {
CreateTestProfile();
// Load the test page.
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
GURL(std::string(kDataURIPrefix) + kTestFormString)));
// Invoke Autofill.
TryBasicFormFill();
}
// http://crbug.com/150084
#if defined(OS_MACOSX)
#define MAYBE_AutofillViaDownArrow AutofillViaDownArrow
#else
#define MAYBE_AutofillViaDownArrow DISABLED_AutofillViaDownArrow
#endif
// Test that form filling can be initiated by pressing the down arrow.
IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_AutofillViaDownArrow) {
CreateTestProfile();
// Load the test page.
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
GURL(std::string(kDataURIPrefix) + kTestFormString)));
// Focus a fillable field.
FocusFirstNameField();
// Press the down arrow to initiate Autofill and wait for the popup to be
// shown.
SendKeyToPageAndWait(ui::VKEY_DOWN);
// Press the down arrow to select the suggestion and preview the autofilled
// form.
SendKeyToPopupAndWait(ui::VKEY_DOWN);
// Press Enter to accept the autofill suggestions.
SendKeyToPopupAndWait(ui::VKEY_RETURN);
// The form should be filled.
ExpectFilledTestForm();
}
// http://crbug.com/150084
#if defined(OS_MACOSX)
#define MAYBE_OnChangeAfterAutofill OnChangeAfterAutofill
#else
#define MAYBE_OnChangeAfterAutofill DISABLED_OnChangeAfterAutofill
#endif
// Test that a JavaScript onchange event is fired after auto-filling a form.
IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_OnChangeAfterAutofill) {
CreateTestProfile();
const char* kOnChangeScript =
"<script>"
"focused_fired = false;"
"unfocused_fired = false;"
"changed_select_fired = false;"
"unchanged_select_fired = false;"
"document.getElementById('firstname').onchange = function() {"
" focused_fired = true;"
"};"
"document.getElementById('lastname').onchange = function() {"
" unfocused_fired = true;"
"};"
"document.getElementById('state').onchange = function() {"
" changed_select_fired = true;"
"};"
"document.getElementById('country').onchange = function() {"
" unchanged_select_fired = true;"
"};"
"document.getElementById('country').value = 'US';"
"</script>";
// Load the test page.
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
GURL(std::string(kDataURIPrefix) + kTestFormString + kOnChangeScript)));
// Invoke Autofill.
FocusFirstNameField();
// Start filling the first name field with "M" and wait for the popup to be
// shown.
SendKeyToPageAndWait(ui::VKEY_M);
// Press the down arrow to select the suggestion and preview the autofilled
// form.
SendKeyToPopupAndWait(ui::VKEY_DOWN);
// Press Enter to accept the autofill suggestions.
SendKeyToPopupAndWait(ui::VKEY_RETURN);
// The form should be filled.
ExpectFilledTestForm();
// The change event should have already fired for unfocused fields, both of
// <input> and of <select> type. However, it should not yet have fired for the
// focused field.
bool focused_fired = false;
bool unfocused_fired = false;
bool changed_select_fired = false;
bool unchanged_select_fired = false;
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
render_view_host(),
"domAutomationController.send(focused_fired);",
&focused_fired));
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
render_view_host(),
"domAutomationController.send(unfocused_fired);",
&unfocused_fired));
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
render_view_host(),
"domAutomationController.send(changed_select_fired);",
&changed_select_fired));
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
render_view_host(),
"domAutomationController.send(unchanged_select_fired);",
&unchanged_select_fired));
EXPECT_FALSE(focused_fired);
EXPECT_TRUE(unfocused_fired);
EXPECT_TRUE(changed_select_fired);
EXPECT_FALSE(unchanged_select_fired);
// Unfocus the first name field. Its change event should fire.
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
render_view_host(),
"document.getElementById('firstname').blur();"
"domAutomationController.send(focused_fired);", &focused_fired));
EXPECT_TRUE(focused_fired);
}
// Test that we can autofill forms distinguished only by their |id| attribute.
// DISABLED: http://crbug.com/150084
IN_PROC_BROWSER_TEST_F(AutofillTest, DISABLED_AutofillFormsDistinguishedById) {
CreateTestProfile();
// Load the test page.
const std::string kURL =
std::string(kDataURIPrefix) + kTestFormString +
"<script>"
"var mainForm = document.forms[0];"
"mainForm.id = 'mainForm';"
"var newForm = document.createElement('form');"
"newForm.action = mainForm.action;"
"newForm.method = mainForm.method;"
"newForm.id = 'newForm';"
"mainForm.parentNode.insertBefore(newForm, mainForm);"
"</script>";
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(), GURL(kURL)));
// Invoke Autofill.
TryBasicFormFill();
}
// Test that we properly autofill forms with repeated fields.
// In the wild, the repeated fields are typically either email fields
// (duplicated for "confirmation"); or variants that are hot-swapped via
// JavaScript, with only one actually visible at any given time.
// DISABLED: http://crbug.com/150084
IN_PROC_BROWSER_TEST_F(AutofillTest, DISABLED_AutofillFormWithRepeatedField) {
CreateTestProfile();
// Load the test page.
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
GURL(std::string(kDataURIPrefix) +
"<form action=\"http://www.example.com/\" method=\"POST\">"
"<label for=\"firstname\">First name:</label>"
" <input type=\"text\" id=\"firstname\""
" onFocus=\"domAutomationController.send(true)\"><br>"
"<label for=\"lastname\">Last name:</label>"
" <input type=\"text\" id=\"lastname\"><br>"
"<label for=\"address1\">Address line 1:</label>"
" <input type=\"text\" id=\"address1\"><br>"
"<label for=\"address2\">Address line 2:</label>"
" <input type=\"text\" id=\"address2\"><br>"
"<label for=\"city\">City:</label>"
" <input type=\"text\" id=\"city\"><br>"
"<label for=\"state\">State:</label>"
" <select id=\"state\">"
" <option value=\"\" selected=\"yes\">--</option>"
" <option value=\"CA\">California</option>"
" <option value=\"TX\">Texas</option>"
" </select><br>"
"<label for=\"state_freeform\" style=\"display:none\">State:</label>"
" <input type=\"text\" id=\"state_freeform\""
" style=\"display:none\"><br>"
"<label for=\"zip\">ZIP code:</label>"
" <input type=\"text\" id=\"zip\"><br>"
"<label for=\"country\">Country:</label>"
" <select id=\"country\">"
" <option value=\"\" selected=\"yes\">--</option>"
" <option value=\"CA\">Canada</option>"
" <option value=\"US\">United States</option>"
" </select><br>"
"<label for=\"phone\">Phone number:</label>"
" <input type=\"text\" id=\"phone\"><br>"
"</form>")));
// Invoke Autofill.
TryBasicFormFill();
ExpectFieldValue("state_freeform", std::string());
}
// http://crbug.com/150084
#if defined(OS_MACOSX)
#define MAYBE_AutofillFormWithNonAutofillableField \
AutofillFormWithNonAutofillableField
#else
#define MAYBE_AutofillFormWithNonAutofillableField \
DISABLED_AutofillFormWithNonAutofillableField
#endif
// Test that we properly autofill forms with non-autofillable fields.
IN_PROC_BROWSER_TEST_F(AutofillTest,
MAYBE_AutofillFormWithNonAutofillableField) {
CreateTestProfile();
// Load the test page.
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
GURL(std::string(kDataURIPrefix) +
"<form action=\"http://www.example.com/\" method=\"POST\">"
"<label for=\"firstname\">First name:</label>"
" <input type=\"text\" id=\"firstname\""
" onFocus=\"domAutomationController.send(true)\"><br>"
"<label for=\"middlename\">Middle name:</label>"
" <input type=\"text\" id=\"middlename\" autocomplete=\"off\" /><br>"
"<label for=\"lastname\">Last name:</label>"
" <input type=\"text\" id=\"lastname\"><br>"
"<label for=\"address1\">Address line 1:</label>"
" <input type=\"text\" id=\"address1\"><br>"
"<label for=\"address2\">Address line 2:</label>"
" <input type=\"text\" id=\"address2\"><br>"
"<label for=\"city\">City:</label>"
" <input type=\"text\" id=\"city\"><br>"
"<label for=\"state\">State:</label>"
" <select id=\"state\">"
" <option value=\"\" selected=\"yes\">--</option>"
" <option value=\"CA\">California</option>"
" <option value=\"TX\">Texas</option>"
" </select><br>"
"<label for=\"zip\">ZIP code:</label>"
" <input type=\"text\" id=\"zip\"><br>"
"<label for=\"country\">Country:</label>"
" <select id=\"country\">"
" <option value=\"\" selected=\"yes\">--</option>"
" <option value=\"CA\">Canada</option>"
" <option value=\"US\">United States</option>"
" </select><br>"
"<label for=\"phone\">Phone number:</label>"
" <input type=\"text\" id=\"phone\"><br>"
"</form>")));
// Invoke Autofill.
TryBasicFormFill();
}
// Test that we can Autofill dynamically generated forms.
// DISABLED: http://crbug.com/150084
IN_PROC_BROWSER_TEST_F(AutofillTest, DISABLED_DynamicFormFill) {
CreateTestProfile();
// Load the test page.
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
GURL(std::string(kDataURIPrefix) +
"<form id=\"form\" action=\"http://www.example.com/\""
" method=\"POST\"></form>"
"<script>"
"function AddElement(name, label) {"
" var form = document.getElementById('form');"
""
" var label_text = document.createTextNode(label);"
" var label_element = document.createElement('label');"
" label_element.setAttribute('for', name);"
" label_element.appendChild(label_text);"
" form.appendChild(label_element);"
""
" if (name === 'state' || name === 'country') {"
" var select_element = document.createElement('select');"
" select_element.setAttribute('id', name);"
" select_element.setAttribute('name', name);"
""
" /* Add an empty selected option. */"
" var default_option = new Option('--', '', true);"
" select_element.appendChild(default_option);"
""
" /* Add the other options. */"
" if (name == 'state') {"
" var option1 = new Option('California', 'CA');"
" select_element.appendChild(option1);"
" var option2 = new Option('Texas', 'TX');"
" select_element.appendChild(option2);"
" } else {"
" var option1 = new Option('Canada', 'CA');"
" select_element.appendChild(option1);"
" var option2 = new Option('United States', 'US');"
" select_element.appendChild(option2);"
" }"
""
" form.appendChild(select_element);"
" } else {"
" var input_element = document.createElement('input');"
" input_element.setAttribute('id', name);"
" input_element.setAttribute('name', name);"
""
" /* Add the onFocus listener to the 'firstname' field. */"
" if (name === 'firstname') {"
" input_element.setAttribute("
" 'onFocus', 'domAutomationController.send(true)');"
" }"
""
" form.appendChild(input_element);"
" }"
""
" form.appendChild(document.createElement('br'));"
"};"
""
"function BuildForm() {"
" var elements = ["
" ['firstname', 'First name:'],"
" ['lastname', 'Last name:'],"
" ['address1', 'Address line 1:'],"
" ['address2', 'Address line 2:'],"
" ['city', 'City:'],"
" ['state', 'State:'],"
" ['zip', 'ZIP code:'],"
" ['country', 'Country:'],"
" ['phone', 'Phone number:'],"
" ];"
""
" for (var i = 0; i < elements.length; i++) {"
" var name = elements[i][0];"
" var label = elements[i][1];"
" AddElement(name, label);"
" }"
"};"
"</script>")));
// Dynamically construct the form.
ASSERT_TRUE(content::ExecuteScript(render_view_host(), "BuildForm();"));
// Invoke Autofill.
TryBasicFormFill();
}
// Test that form filling works after reloading the current page.
// This test brought to you by http://crbug.com/69204
#if defined(OS_MACOSX)
// Now flaky on everything but mac.
// http://crbug.com/150084
#define MAYBE_AutofillAfterReload AutofillAfterReload
#else
#define MAYBE_AutofillAfterReload DISABLED_AutofillAfterReload
#endif
IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_AutofillAfterReload) {
LOG(WARNING) << "Creating test profile.";
CreateTestProfile();
// Load the test page.
LOG(WARNING) << "Bringing browser window to front.";
LOG(WARNING) << "Navigating to URL.";
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
GURL(std::string(kDataURIPrefix) + kTestFormString)));
// Reload the page.
LOG(WARNING) << "Reloading the page.";
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
tab->GetController().Reload(false);
content::WaitForLoadStop(tab);
// Invoke Autofill.
LOG(WARNING) << "Trying to fill the form.";
TryBasicFormFill();
}
// DISABLED: http://crbug.com/150084
IN_PROC_BROWSER_TEST_F(AutofillTest, DISABLED_AutofillAfterTranslate) {
CreateTestProfile();
GURL url(std::string(kDataURIPrefix) +
"<form action=\"http://www.example.com/\" method=\"POST\">"
"<label for=\"fn\">なまえ</label>"
" <input type=\"text\" id=\"fn\""
" onFocus=\"domAutomationController.send(true)\""
"><br>"
"<label for=\"ln\">みょうじ</label>"
" <input type=\"text\" id=\"ln\"><br>"
"<label for=\"a1\">Address line 1:</label>"
" <input type=\"text\" id=\"a1\"><br>"
"<label for=\"a2\">Address line 2:</label>"
" <input type=\"text\" id=\"a2\"><br>"
"<label for=\"ci\">City:</label>"
" <input type=\"text\" id=\"ci\"><br>"
"<label for=\"st\">State:</label>"
" <select id=\"st\">"
" <option value=\"\" selected=\"yes\">--</option>"
" <option value=\"CA\">California</option>"
" <option value=\"TX\">Texas</option>"
" </select><br>"
"<label for=\"z\">ZIP code:</label>"
" <input type=\"text\" id=\"z\"><br>"
"<label for=\"co\">Country:</label>"
" <select id=\"co\">"
" <option value=\"\" selected=\"yes\">--</option>"
" <option value=\"CA\">Canada</option>"
" <option value=\"US\">United States</option>"
" </select><br>"
"<label for=\"ph\">Phone number:</label>"
" <input type=\"text\" id=\"ph\"><br>"
"</form>");
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(), url));
// Get translation bar.
LanguageDetectionDetails details;
details.adopted_language = "ja";
RenderViewHostTester::TestOnMessageReceived(
render_view_host(),
ChromeViewHostMsg_TranslateLanguageDetermined(0, details, true));
TranslateInfoBarDelegate* infobar = InfoBarService::FromWebContents(
browser()->tab_strip_model()->GetActiveWebContents())->infobar_at(0)->
AsTranslateInfoBarDelegate();
ASSERT_TRUE(infobar != NULL);
EXPECT_EQ(TranslateInfoBarDelegate::BEFORE_TRANSLATE,
infobar->infobar_type());
// Simulate translation button press.
infobar->Translate();
// Simulate the translate script being retrieved.
// Pass fake google.translate lib as the translate script.
SimulateURLFetch(true);
content::WindowedNotificationObserver translation_observer(
chrome::NOTIFICATION_PAGE_TRANSLATED,
content::NotificationService::AllSources());
// Simulate translation to kick onTranslateElementLoad.
// But right now, the call stucks here.
// Once click the text field, it starts again.
ASSERT_TRUE(content::ExecuteScript(
render_view_host(), "cr.googleTranslate.onTranslateElementLoad();"));
// Simulate the render notifying the translation has been done.
translation_observer.Wait();
TryBasicFormFill();
}
// Test filling profiles with unicode strings and crazy characters.
// TODO(isherman): rewrite as unit test under PersonalDataManagerTest.
IN_PROC_BROWSER_TEST_F(AutofillTest, FillProfileCrazyCharacters) {
std::vector<AutofillProfile> profiles;
AutofillProfile profile1;
profile1.SetRawInfo(NAME_FIRST,
WideToUTF16(L"\u0623\u0648\u0628\u0627\u0645\u0627 "
L"\u064a\u0639\u062a\u0630\u0631 "
L"\u0647\u0627\u062a\u0641\u064a\u0627 "
L"\u0644\u0645\u0648\u0638\u0641\u0629 "
L"\u0633\u0648\u062f\u0627\u0621 "
L"\u0627\u0633\u062a\u0642\u0627\u0644\u062a "
L"\u0628\u0633\u0628\u0628 "
L"\u062a\u0635\u0631\u064a\u062d\u0627\u062a "
L"\u0645\u062c\u062a\u0632\u0623\u0629"));
profile1.SetRawInfo(NAME_MIDDLE, WideToUTF16(L"BANK\xcBERF\xc4LLE"));
profile1.SetRawInfo(EMAIL_ADDRESS,
WideToUTF16(L"\uacbd\uc81c \ub274\uc2a4 "
L"\ub354\ubcf4\uae30@google.com"));
profile1.SetRawInfo(ADDRESS_HOME_LINE1,
WideToUTF16(L"\uad6d\uc815\uc6d0\xb7\uac80\ucc30, "
L"\ub178\ubb34\ud604\uc815\ubd80 "
L"\ub300\ubd81\uc811\ucd09 \ub2f4\ub2f9 "
L"\uc778\uc0ac\ub4e4 \uc870\uc0ac"));
profile1.SetRawInfo(ADDRESS_HOME_CITY,
WideToUTF16(L"\u653f\u5e9c\u4e0d\u6392\u9664\u7acb\u6cd5"
L"\u898f\u7ba1\u5c0e\u904a"));
profile1.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"YOHO_54676"));
profile1.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, WideToUTF16(L"861088828000"));
profile1.SetInfo(ADDRESS_HOME_COUNTRY, WideToUTF16(L"India"), "en-US");
profiles.push_back(profile1);
AutofillProfile profile2;
profile2.SetRawInfo(NAME_FIRST,
WideToUTF16(L"\u4e0a\u6d77\u5e02\u91d1\u5c71\u533a "
L"\u677e\u9690\u9547\u4ead\u67ab\u516c"
L"\u8def1915\u53f7"));
profile2.SetRawInfo(NAME_LAST, WideToUTF16(L"aguantó"));
profile2.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"HOME 94043"));
profiles.push_back(profile2);
AutofillProfile profile3;
profile3.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"sue@example.com"));
profile3.SetRawInfo(COMPANY_NAME, WideToUTF16(L"Company X"));
profiles.push_back(profile3);
AutofillProfile profile4;
profile4.SetRawInfo(NAME_FIRST, WideToUTF16(L"Joe 3254"));
profile4.SetRawInfo(NAME_LAST, WideToUTF16(L"\u8bb0\u8d262\u5e74\u591a"));
profile4.SetRawInfo(ADDRESS_HOME_ZIP,
WideToUTF16(L"\uff08\u90ae\u7f16\uff1a201504\uff09"));
profile4.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"télévision@example.com"));
profile4.SetRawInfo(COMPANY_NAME,
WideToUTF16(L"\u0907\u0932\u0947\u0915\u093f\u091f\u094d"
L"\u0930\u0928\u093f\u0915\u094d\u0938, "
L"\u0905\u092a\u094b\u0932\u094b "
L"\u091f\u093e\u092f\u0930\u094d\u0938 "
L"\u0906\u0926\u093f"));
profiles.push_back(profile4);
AutofillProfile profile5;
profile5.SetRawInfo(NAME_FIRST, WideToUTF16(L"Larry"));
profile5.SetRawInfo(NAME_LAST,
WideToUTF16(L"\u0938\u094d\u091f\u093e\u0902\u092a "
L"\u0921\u094d\u092f\u0942\u091f\u0940"));
profile5.SetRawInfo(ADDRESS_HOME_ZIP,
WideToUTF16(L"111111111111110000GOOGLE"));
profile5.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"page@000000.com"));
profile5.SetRawInfo(COMPANY_NAME, WideToUTF16(L"Google"));
profiles.push_back(profile5);
AutofillProfile profile6;
profile6.SetRawInfo(NAME_FIRST,
WideToUTF16(L"\u4e0a\u6d77\u5e02\u91d1\u5c71\u533a "
L"\u677e\u9690\u9547\u4ead\u67ab\u516c"
L"\u8def1915\u53f7"));
profile6.SetRawInfo(NAME_LAST,
WideToUTF16(L"\u0646\u062c\u0627\u0645\u064a\u0646\u0627 "
L"\u062f\u0639\u0645\u0647\u0627 "
L"\u0644\u0644\u0631\u0626\u064a\u0633 "
L"\u0627\u0644\u0633\u0648\u062f\u0627\u0646"
L"\u064a \u0639\u0645\u0631 "
L"\u0627\u0644\u0628\u0634\u064a\u0631"));
profile6.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"HOME 94043"));
profiles.push_back(profile6);
AutofillProfile profile7;
profile7.SetRawInfo(NAME_FIRST, WideToUTF16(L"&$%$$$ TESTO *&*&^&^& MOKO"));
profile7.SetRawInfo(NAME_MIDDLE, WideToUTF16(L"WOHOOOO$$$$$$$$****"));
profile7.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"yuvu@example.com"));
profile7.SetRawInfo(ADDRESS_HOME_LINE1,
WideToUTF16(L"34544, anderson ST.(120230)"));
profile7.SetRawInfo(ADDRESS_HOME_CITY, WideToUTF16(L"Sunnyvale"));
profile7.SetRawInfo(ADDRESS_HOME_STATE, WideToUTF16(L"CA"));
profile7.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"94086"));
profile7.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, WideToUTF16(L"15466784565"));
profile7.SetInfo(ADDRESS_HOME_COUNTRY, WideToUTF16(L"United States"),
"en-US");
profiles.push_back(profile7);
SetProfiles(&profiles);
ASSERT_EQ(profiles.size(), personal_data_manager()->GetProfiles().size());
for (size_t i = 0; i < profiles.size(); ++i)
ASSERT_EQ(profiles[i], *personal_data_manager()->GetProfiles()[i]);
std::vector<CreditCard> cards;
CreditCard card1;
card1.SetRawInfo(CREDIT_CARD_NAME,
WideToUTF16(L"\u751f\u6d3b\u5f88\u6709\u89c4\u5f8b "
L"\u4ee5\u73a9\u4e3a\u4e3b"));
card1.SetRawInfo(CREDIT_CARD_NUMBER, WideToUTF16(L"6011111111111117"));
card1.SetRawInfo(CREDIT_CARD_EXP_MONTH, WideToUTF16(L"12"));
card1.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, WideToUTF16(L"2011"));
cards.push_back(card1);
CreditCard card2;
card2.SetRawInfo(CREDIT_CARD_NAME, WideToUTF16(L"John Williams"));
card2.SetRawInfo(CREDIT_CARD_NUMBER, WideToUTF16(L"WokoAwesome12345"));
card2.SetRawInfo(CREDIT_CARD_EXP_MONTH, WideToUTF16(L"10"));
card2.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, WideToUTF16(L"2015"));
cards.push_back(card2);
CreditCard card3;
card3.SetRawInfo(CREDIT_CARD_NAME,
WideToUTF16(L"\u0623\u062d\u0645\u062f\u064a "
L"\u0646\u062c\u0627\u062f "
L"\u0644\u0645\u062d\u0627\u0648\u0644\u0647 "
L"\u0627\u063a\u062a\u064a\u0627\u0644 "
L"\u0641\u064a \u0645\u062f\u064a\u0646\u0629 "
L"\u0647\u0645\u062f\u0627\u0646 "));
card3.SetRawInfo(CREDIT_CARD_NUMBER,
WideToUTF16(L"\u092a\u0941\u0928\u0930\u094d\u091c\u0940"
L"\u0935\u093f\u0924 \u0939\u094b\u0917\u093e "
L"\u0928\u093e\u0932\u0902\u0926\u093e"));
card3.SetRawInfo(CREDIT_CARD_EXP_MONTH, WideToUTF16(L"10"));
card3.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, WideToUTF16(L"2015"));
cards.push_back(card3);
CreditCard card4;
card4.SetRawInfo(CREDIT_CARD_NAME,
WideToUTF16(L"\u039d\u03ad\u03b5\u03c2 "
L"\u03c3\u03c5\u03b3\u03c7\u03c9\u03bd\u03b5"
L"\u03cd\u03c3\u03b5\u03b9\u03c2 "
L"\u03ba\u03b1\u03b9 "
L"\u03ba\u03b1\u03c4\u03b1\u03c1\u03b3\u03ae"
L"\u03c3\u03b5\u03b9\u03c2"));
card4.SetRawInfo(CREDIT_CARD_NUMBER, WideToUTF16(L"00000000000000000000000"));
card4.SetRawInfo(CREDIT_CARD_EXP_MONTH, WideToUTF16(L"01"));
card4.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, WideToUTF16(L"2016"));
cards.push_back(card4);
SetCards(&cards);
ASSERT_EQ(cards.size(), personal_data_manager()->GetCreditCards().size());
for (size_t i = 0; i < cards.size(); ++i)
ASSERT_EQ(cards[i], *personal_data_manager()->GetCreditCards()[i]);
}
// Test filling in invalid values for profiles are saved as-is. Phone
// information entered into the prefs UI is not validated or rejected except for
// duplicates.
// TODO(isherman): rewrite as WebUI test?
IN_PROC_BROWSER_TEST_F(AutofillTest, Invalid) {
// First try profiles with invalid ZIP input.
AutofillProfile without_invalid;
without_invalid.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Will"));
without_invalid.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Sunnyvale"));
without_invalid.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
without_invalid.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("my_zip"));
without_invalid.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("United States"),
"en-US");
AutofillProfile with_invalid = without_invalid;
with_invalid.SetRawInfo(PHONE_HOME_WHOLE_NUMBER,
ASCIIToUTF16("Invalid_Phone_Number"));
SetProfile(with_invalid);
ASSERT_EQ(1u, personal_data_manager()->GetProfiles().size());
AutofillProfile profile = *personal_data_manager()->GetProfiles()[0];
ASSERT_NE(without_invalid.GetRawInfo(PHONE_HOME_WHOLE_NUMBER),
profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER));
}
// Test invalid credit card numbers typed in prefs should be saved as-is.
// TODO(isherman): rewrite as WebUI test?
IN_PROC_BROWSER_TEST_F(AutofillTest, PrefsStringSavedAsIs) {
CreditCard card;
card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("Not_0123-5Checked"));
SetCard(card);
ASSERT_EQ(1u, personal_data_manager()->GetCreditCards().size());
ASSERT_EQ(card, *personal_data_manager()->GetCreditCards()[0]);
}
// Test credit card info with an invalid number is not aggregated.
// When filling out a form with an invalid credit card number (one that does not
// pass the Luhn test) the credit card info should not be saved into Autofill
// preferences.
IN_PROC_BROWSER_TEST_F(AutofillTest, InvalidCreditCardNumberIsNotAggregated) {
ASSERT_TRUE(test_server()->Start());
std::string card("4408 0412 3456 7890");
ASSERT_FALSE(autofill::IsValidCreditCardNumber(ASCIIToUTF16(card)));
SubmitCreditCard("Bob Smith", card.c_str(), "12", "2014");
ASSERT_EQ(0u,
InfoBarService::FromWebContents(
browser()->tab_strip_model()->GetActiveWebContents())->
infobar_count());
}
// Test whitespaces and separator chars are stripped for valid CC numbers.
// The credit card numbers used in this test pass the Luhn test. For reference:
// http://www.merriampark.com/anatomycc.htm
IN_PROC_BROWSER_TEST_F(AutofillTest,
WhitespacesAndSeparatorCharsStrippedForValidCCNums) {
ASSERT_TRUE(test_server()->Start());
SubmitCreditCard("Bob Smith", "4408 0412 3456 7893", "12", "2014");
SubmitCreditCard("Jane Doe", "4417-1234-5678-9113", "10", "2013");
ASSERT_EQ(2u, personal_data_manager()->GetCreditCards().size());
string16 cc1 = personal_data_manager()->GetCreditCards()[0]->GetRawInfo(
CREDIT_CARD_NUMBER);
ASSERT_TRUE(autofill::IsValidCreditCardNumber(cc1));
string16 cc2 = personal_data_manager()->GetCreditCards()[1]->GetRawInfo(
CREDIT_CARD_NUMBER);
ASSERT_TRUE(autofill::IsValidCreditCardNumber(cc2));
}
// Test that Autofill aggregates a minimum valid profile.
// The minimum required address fields must be specified: First Name, Last Name,
// Address Line 1, City, Zip Code, and State.
IN_PROC_BROWSER_TEST_F(AutofillTest, AggregatesMinValidProfile) {
ASSERT_TRUE(test_server()->Start());
FormMap data;
data["NAME_FIRST"] = "Bob";
data["NAME_LAST"] = "Smith";
data["ADDRESS_HOME_LINE1"] = "1234 H St.";
data["ADDRESS_HOME_CITY"] = "Mountain View";
data["ADDRESS_HOME_STATE"] = "CA";
data["ADDRESS_HOME_ZIP"] = "94043";
FillFormAndSubmit("duplicate_profiles_test.html", data);
ASSERT_EQ(1u, personal_data_manager()->GetProfiles().size());
}
// Test Autofill does not aggregate profiles with no address info.
// The minimum required address fields must be specified: First Name, Last Name,
// Address Line 1, City, Zip Code, and State.
IN_PROC_BROWSER_TEST_F(AutofillTest, ProfilesNotAggregatedWithNoAddress) {
ASSERT_TRUE(test_server()->Start());
FormMap data;
data["NAME_FIRST"] = "Bob";
data["NAME_LAST"] = "Smith";
data["EMAIL_ADDRESS"] = "bsmith@example.com";
data["COMPANY_NAME"] = "Mountain View";
data["ADDRESS_HOME_CITY"] = "Mountain View";
data["PHONE_HOME_WHOLE_NUMBER"] = "650-555-4567";
FillFormAndSubmit("duplicate_profiles_test.html", data);
ASSERT_TRUE(personal_data_manager()->GetProfiles().empty());
}
// Test Autofill does not aggregate profiles with an invalid email.
IN_PROC_BROWSER_TEST_F(AutofillTest, ProfilesNotAggregatedWithInvalidEmail) {
ASSERT_TRUE(test_server()->Start());
FormMap data;
data["NAME_FIRST"] = "Bob";
data["NAME_LAST"] = "Smith";
data["EMAIL_ADDRESS"] = "garbage";
data["ADDRESS_HOME_LINE1"] = "1234 H St.";
data["ADDRESS_HOME_CITY"] = "San Jose";
data["ADDRESS_HOME_STATE"] = "CA";
data["ADDRESS_HOME_ZIP"] = "95110";
data["COMPANY_NAME"] = "Company X";
data["PHONE_HOME_WHOLE_NUMBER"] = "408-871-4567";
FillFormAndSubmit("duplicate_profiles_test.html", data);
ASSERT_TRUE(personal_data_manager()->GetProfiles().empty());
}
// http://crbug.com/150084
#if defined(OS_MACOSX)
#define MAYBE_ComparePhoneNumbers ComparePhoneNumbers
#else
#define MAYBE_ComparePhoneNumbers DISABLED_ComparePhoneNumbers
#endif
// Test phone fields parse correctly from a given profile.
// The high level key presses execute the following: Select the first text
// field, invoke the autofill popup list, select the first profile within the
// list, and commit to the profile to populate the form.
IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_ComparePhoneNumbers) {
ASSERT_TRUE(test_server()->Start());
AutofillProfile profile;
profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bob"));
profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
profile.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("1234 H St."));
profile.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("San Jose"));
profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
profile.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("95110"));
profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("1-408-555-4567"));
SetProfile(profile);
GURL url = test_server()->GetURL("files/autofill/form_phones.html");
ui_test_utils::NavigateToURL(browser(), url);
PopulateForm("NAME_FIRST");
ExpectFieldValue("NAME_FIRST", "Bob");
ExpectFieldValue("NAME_LAST", "Smith");
ExpectFieldValue("ADDRESS_HOME_LINE1", "1234 H St.");
ExpectFieldValue("ADDRESS_HOME_CITY", "San Jose");
ExpectFieldValue("ADDRESS_HOME_STATE", "CA");
ExpectFieldValue("ADDRESS_HOME_ZIP", "95110");
ExpectFieldValue("PHONE_HOME_WHOLE_NUMBER", "14085554567");
ExpectFieldValue("PHONE_HOME_CITY_CODE-1", "408");
ExpectFieldValue("PHONE_HOME_CITY_CODE-2", "408");
ExpectFieldValue("PHONE_HOME_NUMBER", "5554567");
ExpectFieldValue("PHONE_HOME_NUMBER_3-1", "555");
ExpectFieldValue("PHONE_HOME_NUMBER_3-2", "555");
ExpectFieldValue("PHONE_HOME_NUMBER_4-1", "4567");
ExpectFieldValue("PHONE_HOME_NUMBER_4-2", "4567");
ExpectFieldValue("PHONE_HOME_EXT-1", std::string());
ExpectFieldValue("PHONE_HOME_EXT-2", std::string());
ExpectFieldValue("PHONE_HOME_COUNTRY_CODE-1", "1");
}
// Test profile is saved if phone number is valid in selected country.
// The data file contains two profiles with valid phone numbers and two
// profiles with invalid phone numbers from their respective country.
// DISABLED: http://crbug.com/150084
IN_PROC_BROWSER_TEST_F(AutofillTest,
DISABLED_ProfileSavedWithValidCountryPhone) {
ASSERT_TRUE(test_server()->Start());
std::vector<FormMap> profiles;
FormMap data1;
data1["NAME_FIRST"] = "Bob";
data1["NAME_LAST"] = "Smith";
data1["ADDRESS_HOME_LINE1"] = "123 Cherry Ave";
data1["ADDRESS_HOME_CITY"] = "Mountain View";
data1["ADDRESS_HOME_STATE"] = "CA";
data1["ADDRESS_HOME_ZIP"] = "94043";
data1["ADDRESS_HOME_COUNTRY"] = "United States";
data1["PHONE_HOME_WHOLE_NUMBER"] = "408-871-4567";
profiles.push_back(data1);
FormMap data2;
data2["NAME_FIRST"] = "John";
data2["NAME_LAST"] = "Doe";
data2["ADDRESS_HOME_LINE1"] = "987 H St";
data2["ADDRESS_HOME_CITY"] = "San Jose";
data2["ADDRESS_HOME_STATE"] = "CA";
data2["ADDRESS_HOME_ZIP"] = "95510";
data2["ADDRESS_HOME_COUNTRY"] = "United States";
data2["PHONE_HOME_WHOLE_NUMBER"] = "408-123-456";
profiles.push_back(data2);
FormMap data3;
data3["NAME_FIRST"] = "Jane";
data3["NAME_LAST"] = "Doe";
data3["ADDRESS_HOME_LINE1"] = "1523 Garcia St";
data3["ADDRESS_HOME_CITY"] = "Mountain View";
data3["ADDRESS_HOME_STATE"] = "CA";
data3["ADDRESS_HOME_ZIP"] = "94043";
data3["ADDRESS_HOME_COUNTRY"] = "Germany";
data3["PHONE_HOME_WHOLE_NUMBER"] = "+49 40-80-81-79-000";
profiles.push_back(data3);
FormMap data4;
data4["NAME_FIRST"] = "Bonnie";
data4["NAME_LAST"] = "Smith";
data4["ADDRESS_HOME_LINE1"] = "6723 Roadway Rd";
data4["ADDRESS_HOME_CITY"] = "San Jose";
data4["ADDRESS_HOME_STATE"] = "CA";
data4["ADDRESS_HOME_ZIP"] = "95510";
data4["ADDRESS_HOME_COUNTRY"] = "Germany";
data4["PHONE_HOME_WHOLE_NUMBER"] = "+21 08450 777 777";
profiles.push_back(data4);
for (size_t i = 0; i < profiles.size(); ++i)
FillFormAndSubmit("autofill_test_form.html", profiles[i]);
ASSERT_EQ(2u, personal_data_manager()->GetProfiles().size());
ASSERT_EQ(ASCIIToUTF16("(408) 871-4567"),
personal_data_manager()->GetProfiles()[0]->GetRawInfo(
PHONE_HOME_WHOLE_NUMBER));
ASSERT_EQ(ASCIIToUTF16("+49 40/808179000"),
personal_data_manager()->GetProfiles()[1]->GetRawInfo(
PHONE_HOME_WHOLE_NUMBER));
}
// Test Autofill appends country codes to aggregated phone numbers.
// The country code is added for the following case:
// The phone number contains the correct national number size and
// is a valid format.
IN_PROC_BROWSER_TEST_F(AutofillTest, AppendCountryCodeForAggregatedPhones) {
ASSERT_TRUE(test_server()->Start());
FormMap data;
data["NAME_FIRST"] = "Bob";
data["NAME_LAST"] = "Smith";
data["ADDRESS_HOME_LINE1"] = "1234 H St.";
data["ADDRESS_HOME_CITY"] = "San Jose";
data["ADDRESS_HOME_STATE"] = "CA";
data["ADDRESS_HOME_ZIP"] = "95110";
data["ADDRESS_HOME_COUNTRY"] = "Germany";
data["PHONE_HOME_WHOLE_NUMBER"] = "(08) 450 777-777";
FillFormAndSubmit("autofill_test_form.html", data);
ASSERT_EQ(1u, personal_data_manager()->GetProfiles().size());
string16 phone = personal_data_manager()->GetProfiles()[0]->GetRawInfo(
PHONE_HOME_WHOLE_NUMBER);
ASSERT_TRUE(StartsWith(phone, ASCIIToUTF16("+49"), true));
}
// Test CC info not offered to be saved when autocomplete=off for CC field.
// If the credit card number field has autocomplete turned off, then the credit
// card infobar should not offer to save the credit card info. The credit card
// number must be a valid Luhn number.
IN_PROC_BROWSER_TEST_F(AutofillTest, CCInfoNotStoredWhenAutocompleteOff) {
ASSERT_TRUE(test_server()->Start());
FormMap data;
data["CREDIT_CARD_NAME"] = "Bob Smith";
data["CREDIT_CARD_NUMBER"] = "4408041234567893";
data["CREDIT_CARD_EXP_MONTH"] = "12";
data["CREDIT_CARD_EXP_4_DIGIT_YEAR"] = "2014";
FillFormAndSubmit("cc_autocomplete_off_test.html", data);
ASSERT_EQ(0u,
InfoBarService::FromWebContents(
browser()->tab_strip_model()->GetActiveWebContents())->
infobar_count());
}
// http://crbug.com/150084
#if defined(OS_MACOSX)
#define MAYBE_NoAutofillForReadOnlyFields NoAutofillForReadOnlyFields
#else
#define MAYBE_NoAutofillForReadOnlyFields DISABLED_NoAutofillForReadOnlyFields
#endif
// Test that Autofill does not fill in read-only fields.
IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_NoAutofillForReadOnlyFields) {
ASSERT_TRUE(test_server()->Start());
std::string addr_line1("1234 H St.");
AutofillProfile profile;
profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bob"));
profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16("bsmith@gmail.com"));
profile.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16(addr_line1));
profile.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("San Jose"));
profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
profile.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("95110"));
profile.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Company X"));
profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("408-871-4567"));
SetProfile(profile);
GURL url = test_server()->GetURL("files/autofill/read_only_field_test.html");
ui_test_utils::NavigateToURL(browser(), url);
PopulateForm("firstname");
ExpectFieldValue("email", std::string());
ExpectFieldValue("address", addr_line1);
}
// http://crbug.com/150084
#if defined(OS_MACOSX)
#define MAYBE_FormFillableOnReset FormFillableOnReset
#else
#define MAYBE_FormFillableOnReset DISABLED_FormFillableOnReset
#endif
// Test form is fillable from a profile after form was reset.
// Steps:
// 1. Fill form using a saved profile.
// 2. Reset the form.
// 3. Fill form using a saved profile.
IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_FormFillableOnReset) {
ASSERT_TRUE(test_server()->Start());
CreateTestProfile();
GURL url = test_server()->GetURL("files/autofill/autofill_test_form.html");
ui_test_utils::NavigateToURL(browser(), url);
PopulateForm("NAME_FIRST");
ASSERT_TRUE(content::ExecuteScript(
browser()->tab_strip_model()->GetActiveWebContents(),
"document.getElementById('testform').reset()"));
PopulateForm("NAME_FIRST");
ExpectFieldValue("NAME_FIRST", "Milton");
ExpectFieldValue("NAME_LAST", "Waddams");
ExpectFieldValue("EMAIL_ADDRESS", "red.swingline@initech.com");
ExpectFieldValue("ADDRESS_HOME_LINE1", "4120 Freidrich Lane");
ExpectFieldValue("ADDRESS_HOME_CITY", "Austin");
ExpectFieldValue("ADDRESS_HOME_STATE", "Texas");
ExpectFieldValue("ADDRESS_HOME_ZIP", "78744");
ExpectFieldValue("ADDRESS_HOME_COUNTRY", "United States");
ExpectFieldValue("PHONE_HOME_WHOLE_NUMBER", "5125551234");
}
// http://crbug.com/150084
#if defined(OS_MACOSX)
#define MAYBE_DistinguishMiddleInitialWithinName \
DistinguishMiddleInitialWithinName
#else
#define MAYBE_DistinguishMiddleInitialWithinName \
DISABLED_DistinguishMiddleInitialWithinName
#endif
// Test Autofill distinguishes a middle initial in a name.
IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_DistinguishMiddleInitialWithinName) {
ASSERT_TRUE(test_server()->Start());
CreateTestProfile();
GURL url = test_server()->GetURL(
"files/autofill/autofill_middleinit_form.html");
ui_test_utils::NavigateToURL(browser(), url);
PopulateForm("NAME_FIRST");
ExpectFieldValue("NAME_MIDDLE", "C");
}
// http://crbug.com/150084
#if defined(OS_MACOSX)
#define MAYBE_MultipleEmailFilledByOneUserGesture \
MultipleEmailFilledByOneUserGesture
#else
#define MAYBE_MultipleEmailFilledByOneUserGesture \
DISABLED_MultipleEmailFilledByOneUserGesture
#endif
// Test forms with multiple email addresses are filled properly.
// Entire form should be filled with one user gesture.
IN_PROC_BROWSER_TEST_F(AutofillTest,
MAYBE_MultipleEmailFilledByOneUserGesture) {
ASSERT_TRUE(test_server()->Start());
std::string email("bsmith@gmail.com");
AutofillProfile profile;
profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bob"));
profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16(email));
profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("4088714567"));
SetProfile(profile);
GURL url = test_server()->GetURL(
"files/autofill/autofill_confirmemail_form.html");
ui_test_utils::NavigateToURL(browser(), url);
PopulateForm("NAME_FIRST");
ExpectFieldValue("EMAIL_CONFIRM", email);
// TODO(isherman): verify entire form.
}
// Test profile not aggregated if email found in non-email field.
IN_PROC_BROWSER_TEST_F(AutofillTest, ProfileWithEmailInOtherFieldNotSaved) {
ASSERT_TRUE(test_server()->Start());
FormMap data;
data["NAME_FIRST"] = "Bob";
data["NAME_LAST"] = "Smith";
data["ADDRESS_HOME_LINE1"] = "bsmith@gmail.com";
data["ADDRESS_HOME_CITY"] = "San Jose";
data["ADDRESS_HOME_STATE"] = "CA";
data["ADDRESS_HOME_ZIP"] = "95110";
data["COMPANY_NAME"] = "Company X";
data["PHONE_HOME_WHOLE_NUMBER"] = "408-871-4567";
FillFormAndSubmit("duplicate_profiles_test.html", data);
ASSERT_EQ(0u, personal_data_manager()->GetProfiles().size());
}
// http://crbug.com/150084
#if defined(OS_MACOSX)
#define MAYBE_FormFillLatencyAfterSubmit FormFillLatencyAfterSubmit
#else
#define MAYBE_FormFillLatencyAfterSubmit DISABLED_FormFillLatencyAfterSubmit
#endif
// Test latency time on form submit with lots of stored Autofill profiles.
// This test verifies when a profile is selected from the Autofill dictionary
// that consists of thousands of profiles, the form does not hang after being
// submitted.
IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_FormFillLatencyAfterSubmit) {
ASSERT_TRUE(test_server()->Start());
std::vector<std::string> cities;
cities.push_back("San Jose");
cities.push_back("San Francisco");
cities.push_back("Sacramento");
cities.push_back("Los Angeles");
std::vector<std::string> streets;
streets.push_back("St");
streets.push_back("Ave");
streets.push_back("Ln");
streets.push_back("Ct");
const int kNumProfiles = 1500;
base::Time start_time = base::Time::Now();
std::vector<AutofillProfile> profiles;
for (int i = 0; i < kNumProfiles; i++) {
AutofillProfile profile;
string16 name(base::IntToString16(i));
string16 email(name + ASCIIToUTF16("@example.com"));
string16 street = ASCIIToUTF16(
base::IntToString(base::RandInt(0, 10000)) + " " +
streets[base::RandInt(0, streets.size() - 1)]);
string16 city = ASCIIToUTF16(cities[base::RandInt(0, cities.size() - 1)]);
string16 zip(base::IntToString16(base::RandInt(0, 10000)));
profile.SetRawInfo(NAME_FIRST, name);
profile.SetRawInfo(EMAIL_ADDRESS, email);
profile.SetRawInfo(ADDRESS_HOME_LINE1, street);
profile.SetRawInfo(ADDRESS_HOME_CITY, city);
profile.SetRawInfo(ADDRESS_HOME_STATE, WideToUTF16(L"CA"));
profile.SetRawInfo(ADDRESS_HOME_ZIP, zip);
profile.SetRawInfo(ADDRESS_HOME_COUNTRY, WideToUTF16(L"US"));
profiles.push_back(profile);
}
SetProfiles(&profiles);
// TODO(isherman): once we're sure this test doesn't timeout on any bots, this
// can be removd.
LOG(INFO) << "Created " << kNumProfiles << " profiles in " <<
(base::Time::Now() - start_time).InSeconds() << " seconds.";
GURL url = test_server()->GetURL(
"files/autofill/latency_after_submit_test.html");
ui_test_utils::NavigateToURL(browser(), url);
PopulateForm("NAME_FIRST");
content::WindowedNotificationObserver load_stop_observer(
content::NOTIFICATION_LOAD_STOP,
content::Source<content::NavigationController>(
&browser()->tab_strip_model()->GetActiveWebContents()->
GetController()));
ASSERT_TRUE(content::ExecuteScript(
render_view_host(),
"document.getElementById('testform').submit();"));
// This will ensure the test didn't hang.
load_stop_observer.Wait();
}
// http://crbug.com/150084
#if defined(OS_MACOSX)
#define MAYBE_DisableAutocompleteWhileFilling DisableAutocompleteWhileFilling
#else
#define MAYBE_DisableAutocompleteWhileFilling \
DISABLED_DisableAutocompleteWhileFilling
#endif
// Test that Chrome doesn't crash when autocomplete is disabled while the user
// is interacting with the form. This is a regression test for
// http://crbug.com/160476
IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_DisableAutocompleteWhileFilling) {
CreateTestProfile();
// Load the test page.
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
GURL(std::string(kDataURIPrefix) + kTestFormString)));
// Invoke Autofill: Start filling the first name field with "M" and wait for
// the popup to be shown.
FocusFirstNameField();
SendKeyToPageAndWait(ui::VKEY_M);
// Now that the popup with suggestions is showing, disable autocomplete for
// the active field.
ASSERT_TRUE(content::ExecuteScript(
render_view_host(),
"document.querySelector('input').autocomplete = 'off';"));
// Press the down arrow to select the suggestion and attempt to preview the
// autofilled form.
if (!external_delegate()) {
content::SimulateKeyPress(
browser()->tab_strip_model()->GetActiveWebContents(),
ui::VKEY_DOWN, false, false, false, false);
} else {
content::NativeWebKeyboardEvent event;
event.windowsKeyCode = ui::VKEY_DOWN;
external_delegate()->keyboard_listener()->HandleKeyPressEvent(event);
}
// Wait for any IPCs to complete by performing an action that generates an
// IPC that's easy to wait for. Chrome shouldn't crash.
bool result = false;
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
render_view_host(),
"var city = document.getElementById('city');"
"city.onfocus = function() { domAutomationController.send(true); };"
"city.focus()",
&result));
ASSERT_TRUE(result);
SendKeyToPageAndWait(ui::VKEY_A);
}
// Test that profiles merge for aggregated data with same address.
// The criterion for when two profiles are expected to be merged is when their
// 'Address Line 1' and 'City' data match. When two profiles are merged, any
// remaining address fields are expected to be overwritten. Any non-address
// fields should accumulate multi-valued data.
// DISABLED: http://crbug.com/150084
IN_PROC_BROWSER_TEST_F(AutofillTest,
DISABLED_MergeAggregatedProfilesWithSameAddress) {
AggregateProfilesIntoAutofillPrefs("dataset_2.txt");
ASSERT_EQ(3u, personal_data_manager()->GetProfiles().size());
}
// Test profiles are not merged without mininum address values.
// Mininum address values needed during aggregation are: address line 1, city,
// state, and zip code.
// Profiles are merged when data for address line 1 and city match.
// DISABLED: http://crbug.com/150084
IN_PROC_BROWSER_TEST_F(AutofillTest,
DISABLED_ProfilesNotMergedWhenNoMinAddressData) {
AggregateProfilesIntoAutofillPrefs("dataset_no_address.txt");
ASSERT_EQ(0u, personal_data_manager()->GetProfiles().size());
}
// Test Autofill ability to merge duplicate profiles and throw away junk.
// TODO(isherman): this looks redundant, consider removing.
// DISABLED: http://crbug.com/150084
IN_PROC_BROWSER_TEST_F(AutofillTest,
DISABLED_MergeAggregatedDuplicatedProfiles) {
int num_of_profiles =
AggregateProfilesIntoAutofillPrefs("dataset_no_address.txt");
ASSERT_GT(num_of_profiles,
static_cast<int>(personal_data_manager()->GetProfiles().size()));
}
} // namespace autofill
|
/*
Copyright (c) 2014-2016, Arvid Norberg, Steven Siloti
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
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 <libtorrent/receive_buffer.hpp>
#include <libtorrent/invariant_check.hpp>
namespace libtorrent {
int receive_buffer::max_receive() const
{
return int(m_recv_buffer.size() - m_recv_end);
}
span<char> receive_buffer::reserve(int const size)
{
INVARIANT_CHECK;
TORRENT_ASSERT(size > 0);
TORRENT_ASSERT(m_recv_pos >= 0);
// normalize() must be called before receiving more data
TORRENT_ASSERT(m_recv_start == 0);
if (int(m_recv_buffer.size()) < m_recv_end + size)
{
int const new_size = std::max(m_recv_end + size, m_packet_size);
buffer new_buffer(new_size
, span<char const>(m_recv_buffer.data(), m_recv_end));
m_recv_buffer = std::move(new_buffer);
// since we just increased the size of the buffer, reset the watermark to
// start at our new size (avoid flapping the buffer size)
m_watermark = sliding_average<20>();
}
return span<char>(m_recv_buffer).subspan(m_recv_end, size);
}
void receive_buffer::grow(int const limit)
{
INVARIANT_CHECK;
int const current_size = int(m_recv_buffer.size());
TORRENT_ASSERT(current_size < std::numeric_limits<int>::max() / 3);
// first grow to one piece message, then grow by 50% each time
int const new_size = (current_size < m_packet_size)
? m_packet_size : std::min(current_size * 3 / 2, limit);
// re-allocate the buffer and copy over the part of it that's used
buffer new_buffer(new_size
, span<char const>(m_recv_buffer.data(), m_recv_end));
m_recv_buffer = std::move(new_buffer);
// since we just increased the size of the buffer, reset the watermark to
// start at our new size (avoid flapping the buffer size)
m_watermark = sliding_average<20>();
}
int receive_buffer::advance_pos(int const bytes)
{
INVARIANT_CHECK;
int const limit = m_packet_size > m_recv_pos ? m_packet_size - m_recv_pos : m_packet_size;
int const sub_transferred = (std::min)(bytes, limit);
m_recv_pos += sub_transferred;
return sub_transferred;
}
// size = the packet size to remove from the receive buffer
// packet_size = the next packet size to receive in the buffer
// offset = the offset into the receive buffer where to remove `size` bytes
void receive_buffer::cut(int const size, int const packet_size, int const offset)
{
INVARIANT_CHECK;
TORRENT_ASSERT(packet_size > 0);
TORRENT_ASSERT(int(m_recv_buffer.size()) >= size);
TORRENT_ASSERT(int(m_recv_buffer.size()) >= m_recv_pos);
TORRENT_ASSERT(m_recv_pos >= size + offset);
TORRENT_ASSERT(offset >= 0);
TORRENT_ASSERT(int(m_recv_buffer.size()) >= m_recv_end);
TORRENT_ASSERT(m_recv_start <= m_recv_end);
TORRENT_ASSERT(size >= 0);
if (offset > 0)
{
TORRENT_ASSERT(m_recv_start - size <= m_recv_end);
if (size > 0)
{
std::memmove(&m_recv_buffer[0] + m_recv_start + offset
, &m_recv_buffer[0] + m_recv_start + offset + size
, m_recv_end - m_recv_start - size - offset);
}
m_recv_pos -= size;
m_recv_end -= size;
#if TORRENT_USE_ASSERTS
std::fill(m_recv_buffer.begin() + m_recv_end, m_recv_buffer.end(), 0xcc);
#endif
}
else
{
TORRENT_ASSERT(m_recv_start + size <= m_recv_end);
m_recv_start += size;
m_recv_pos -= size;
}
m_packet_size = packet_size;
}
span<char const> receive_buffer::get() const
{
if (m_recv_buffer.empty())
{
TORRENT_ASSERT(m_recv_pos == 0);
return span<char const>();
}
TORRENT_ASSERT(m_recv_start + m_recv_pos <= int(m_recv_buffer.size()));
return span<char const>(m_recv_buffer).subspan(m_recv_start, m_recv_pos);
}
#if !defined(TORRENT_DISABLE_ENCRYPTION) && !defined(TORRENT_DISABLE_EXTENSIONS)
span<char> receive_buffer::mutable_buffer()
{
INVARIANT_CHECK;
return span<char>(m_recv_buffer).subspan(m_recv_start, m_recv_pos);
}
span<char> receive_buffer::mutable_buffer(int const bytes)
{
INVARIANT_CHECK;
// bytes is the number of bytes we just received, and m_recv_pos has
// already been adjusted for these bytes. The receive pos immediately
// before we received these bytes was (m_recv_pos - bytes)
return span<char>(m_recv_buffer).subspan(m_recv_start + m_recv_pos - bytes, bytes);
}
#endif
// the purpose of this function is to free up and cut off all messages
// in the receive buffer that have been parsed and processed.
// it may also shrink the size of the buffer allocation if we haven't been using
// enough of it lately.
void receive_buffer::normalize(int const force_shrink)
{
INVARIANT_CHECK;
TORRENT_ASSERT(m_recv_end >= m_recv_start);
m_watermark.add_sample(std::max(m_recv_end, m_packet_size));
// if the running average drops below half of the current buffer size,
// reallocate a smaller one.
bool const shrink_buffer = int(m_recv_buffer.size()) / 2 > m_watermark.mean()
&& m_watermark.mean() > (m_recv_end - m_recv_start);
span<char const> bytes_to_shift(
m_recv_buffer.data() + m_recv_start
, m_recv_end - m_recv_start);
if (force_shrink)
{
int const target_size = std::max(std::max(force_shrink
, int(bytes_to_shift.size())), m_packet_size);
buffer new_buffer(target_size, bytes_to_shift);
m_recv_buffer = std::move(new_buffer);
}
else if (shrink_buffer)
{
buffer new_buffer(m_watermark.mean(), bytes_to_shift);
m_recv_buffer = std::move(new_buffer);
}
else if (m_recv_end > m_recv_start
&& m_recv_start > 0)
{
std::memmove(m_recv_buffer.data(), bytes_to_shift.data()
, bytes_to_shift.size());
}
m_recv_end -= m_recv_start;
m_recv_start = 0;
#if TORRENT_USE_ASSERTS
std::fill(m_recv_buffer.begin() + m_recv_end, m_recv_buffer.end(), 0xcc);
#endif
}
void receive_buffer::reset(int const packet_size)
{
INVARIANT_CHECK;
TORRENT_ASSERT(int(m_recv_buffer.size()) >= m_recv_end);
TORRENT_ASSERT(packet_size > 0);
if (m_recv_end > m_packet_size)
{
cut(m_packet_size, packet_size);
return;
}
m_recv_pos = 0;
m_recv_start = 0;
m_recv_end = 0;
m_packet_size = packet_size;
}
#if !defined(TORRENT_DISABLE_ENCRYPTION) && !defined(TORRENT_DISABLE_EXTENSIONS)
bool crypto_receive_buffer::packet_finished() const
{
if (m_recv_pos == INT_MAX)
return m_connection_buffer.packet_finished();
else
return m_packet_size <= m_recv_pos;
}
int crypto_receive_buffer::packet_size() const
{
if (m_recv_pos == INT_MAX)
return m_connection_buffer.packet_size();
else
return m_packet_size;
}
int crypto_receive_buffer::pos() const
{
if (m_recv_pos == INT_MAX)
return m_connection_buffer.pos();
else
return m_recv_pos;
}
void crypto_receive_buffer::cut(int size, int packet_size, int offset)
{
if (m_recv_pos != INT_MAX)
{
TORRENT_ASSERT(size <= m_recv_pos);
m_packet_size = packet_size;
packet_size = m_connection_buffer.packet_size() - size;
m_recv_pos -= size;
}
m_connection_buffer.cut(size, packet_size, offset);
}
void crypto_receive_buffer::reset(int packet_size)
{
if (m_recv_pos != INT_MAX)
{
if (m_connection_buffer.m_recv_end > m_packet_size)
{
cut(m_packet_size, packet_size);
return;
}
m_packet_size = packet_size;
packet_size = m_connection_buffer.packet_size() - m_recv_pos;
m_recv_pos = 0;
}
m_connection_buffer.reset(packet_size);
}
void crypto_receive_buffer::crypto_reset(int packet_size)
{
TORRENT_ASSERT(packet_finished());
TORRENT_ASSERT(crypto_packet_finished());
TORRENT_ASSERT(m_recv_pos == INT_MAX || m_recv_pos == m_connection_buffer.pos());
TORRENT_ASSERT(m_recv_pos == INT_MAX || m_connection_buffer.pos_at_end());
if (packet_size == 0)
{
if (m_recv_pos != INT_MAX)
m_connection_buffer.cut(0, m_packet_size);
m_recv_pos = INT_MAX;
}
else
{
if (m_recv_pos == INT_MAX)
m_packet_size = m_connection_buffer.packet_size();
m_recv_pos = m_connection_buffer.pos();
TORRENT_ASSERT(m_recv_pos >= 0);
m_connection_buffer.cut(0, m_recv_pos + packet_size);
}
}
int crypto_receive_buffer::advance_pos(int bytes)
{
if (m_recv_pos == INT_MAX) return bytes;
int const limit = m_packet_size > m_recv_pos ? m_packet_size - m_recv_pos : m_packet_size;
int const sub_transferred = (std::min)(bytes, limit);
m_recv_pos += sub_transferred;
m_connection_buffer.cut(0, m_connection_buffer.packet_size() + sub_transferred);
return sub_transferred;
}
span<char const> crypto_receive_buffer::get() const
{
span<char const> recv_buffer = m_connection_buffer.get();
if (m_recv_pos < m_connection_buffer.pos())
recv_buffer = recv_buffer.first(m_recv_pos);
return recv_buffer;
}
span<char> crypto_receive_buffer::mutable_buffer(
std::size_t const bytes)
{
int const pending_decryption = (m_recv_pos != INT_MAX)
? m_connection_buffer.packet_size() - m_recv_pos
: int(bytes);
return m_connection_buffer.mutable_buffer(pending_decryption);
}
#endif // TORRENT_DISABLE_ENCRYPTION
} // namespace libtorrent
|
#pragma once
#include "element.hpp"
#include <string>
class String : public Element {
std::string string;
public:
String(const std::string&);
void print(size_t indent = 0) override;
bool find(char);
};
|
#ifdef RD_WG_SIZE_0_0
#define BLOCK_SIZE RD_WG_SIZE_0_0
#elif defined(RD_WG_SIZE_0)
#define BLOCK_SIZE RD_WG_SIZE_0
#elif defined(RD_WG_SIZE)
#define BLOCK_SIZE RD_WG_SIZE
#else
#define BLOCK_SIZE 16
#endif
#define LIMIT -999
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <sys/time.h>
#include "common.h"
// kernel
#define SCORE(i, j) input_itemsets_l[j + i * (BLOCK_SIZE+1)]
#define REF(i, j) reference_l[j + i * BLOCK_SIZE]
int max3( int a, int b, int c){
int k;
if( a <= b )
k = b;
else
k = a;
if( k <=c )
return(c);
else
return(k);
}
//global variables
int blosum62[24][24] = {
{ 4, -1, -2, -2, 0, -1, -1, 0, -2, -1, -1, -1, -1, -2, -1, 1, 0, -3, -2, 0, -2, -1, 0, -4},
{-1, 5, 0, -2, -3, 1, 0, -2, 0, -3, -2, 2, -1, -3, -2, -1, -1, -3, -2, -3, -1, 0, -1, -4},
{-2, 0, 6, 1, -3, 0, 0, 0, 1, -3, -3, 0, -2, -3, -2, 1, 0, -4, -2, -3, 3, 0, -1, -4},
{-2, -2, 1, 6, -3, 0, 2, -1, -1, -3, -4, -1, -3, -3, -1, 0, -1, -4, -3, -3, 4, 1, -1, -4},
{ 0, -3, -3, -3, 9, -3, -4, -3, -3, -1, -1, -3, -1, -2, -3, -1, -1, -2, -2, -1, -3, -3, -2, -4},
{-1, 1, 0, 0, -3, 5, 2, -2, 0, -3, -2, 1, 0, -3, -1, 0, -1, -2, -1, -2, 0, 3, -1, -4},
{-1, 0, 0, 2, -4, 2, 5, -2, 0, -3, -3, 1, -2, -3, -1, 0, -1, -3, -2, -2, 1, 4, -1, -4},
{ 0, -2, 0, -1, -3, -2, -2, 6, -2, -4, -4, -2, -3, -3, -2, 0, -2, -2, -3, -3, -1, -2, -1, -4},
{-2, 0, 1, -1, -3, 0, 0, -2, 8, -3, -3, -1, -2, -1, -2, -1, -2, -2, 2, -3, 0, 0, -1, -4},
{-1, -3, -3, -3, -1, -3, -3, -4, -3, 4, 2, -3, 1, 0, -3, -2, -1, -3, -1, 3, -3, -3, -1, -4},
{-1, -2, -3, -4, -1, -2, -3, -4, -3, 2, 4, -2, 2, 0, -3, -2, -1, -2, -1, 1, -4, -3, -1, -4},
{-1, 2, 0, -1, -3, 1, 1, -2, -1, -3, -2, 5, -1, -3, -1, 0, -1, -3, -2, -2, 0, 1, -1, -4},
{-1, -1, -2, -3, -1, 0, -2, -3, -2, 1, 2, -1, 5, 0, -2, -1, -1, -1, -1, 1, -3, -1, -1, -4},
{-2, -3, -3, -3, -2, -3, -3, -3, -1, 0, 0, -3, 0, 6, -4, -2, -2, 1, 3, -1, -3, -3, -1, -4},
{-1, -2, -2, -1, -3, -1, -1, -2, -2, -3, -3, -1, -2, -4, 7, -1, -1, -4, -3, -2, -2, -1, -2, -4},
{ 1, -1, 1, 0, -1, 0, 0, 0, -1, -2, -2, 0, -1, -2, -1, 4, 1, -3, -2, -2, 0, 0, 0, -4},
{ 0, -1, 0, -1, -1, -1, -1, -2, -2, -1, -1, -1, -1, -2, -1, 1, 5, -2, -2, 0, -1, -1, 0, -4},
{-3, -3, -4, -4, -2, -2, -3, -2, -2, -3, -2, -3, -1, 1, -4, -3, -2, 11, 2, -3, -4, -3, -2, -4},
{-2, -2, -2, -3, -2, -1, -2, -3, 2, -1, -1, -2, -1, 3, -3, -2, -2, 2, 7, -1, -3, -2, -1, -4},
{ 0, -3, -3, -3, -1, -2, -2, -3, -3, 3, 1, -2, 1, -1, -2, -2, 0, -3, -1, 4, -3, -2, -1, -4},
{-2, -1, 3, 4, -3, 0, 1, -1, 0, -3, -4, 0, -3, -3, -2, 0, -1, -4, -3, -3, 4, 1, -1, -4},
{-1, 0, 0, 1, -3, 3, 4, -2, 0, -3, -3, 1, -1, -3, -1, 0, -1, -3, -2, -2, 1, 4, -1, -4},
{ 0, -1, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, 0, 0, -2, -1, -1, -1, -1, -1, -4},
{-4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, 1}
};
// local variables
void usage(int argc, char **argv)
{
fprintf(stderr, "Usage: %s <max_rows/max_cols> <penalty> \n", argv[0]);
fprintf(stderr, "\t<dimension> - x and y dimensions\n");
fprintf(stderr, "\t<penalty> - penalty(positive integer)\n");
exit(1);
}
double get_time() {
struct timeval t;
gettimeofday(&t,NULL);
return t.tv_sec+t.tv_usec*1e-6;
}
int main(int argc, char **argv){
printf("WG size of kernel = %d \n", BLOCK_SIZE);
int max_rows_t, max_cols_t, penalty_t;
// the lengths of the two sequences should be able to divided by 16.
// And at current stage max_rows needs to equal max_cols
if (argc == 3)
{
max_rows_t = atoi(argv[1]);
max_cols_t = atoi(argv[1]);
penalty_t = atoi(argv[2]);
}
else{
usage(argc, argv);
}
if(atoi(argv[1])%16!=0){
fprintf(stderr,"The dimension values must be a multiple of 16\n");
exit(1);
}
// make constant variable to avoid kernel argument set at every loop iteration
const int max_rows = max_rows_t + 1;
const int max_cols = max_cols_t + 1;
const int penalty = penalty_t;
int *reference;
int *input_itemsets;
int *output_itemsets;
reference = (int *)malloc( max_rows * max_cols * sizeof(int) );
input_itemsets = (int *)malloc( max_rows * max_cols * sizeof(int) );
output_itemsets = (int *)malloc( max_rows * max_cols * sizeof(int) );
srand(7);
//initialization
for (int i = 0 ; i < max_cols; i++){
for (int j = 0 ; j < max_rows; j++){
input_itemsets[i*max_cols+j] = 0;
}
}
for( int i=1; i< max_rows ; i++){ //initialize the cols
input_itemsets[i*max_cols] = rand() % 10 + 1;
}
for( int j=1; j< max_cols ; j++){ //initialize the rows
input_itemsets[j] = rand() % 10 + 1;
}
for (int i = 1 ; i < max_cols; i++){
for (int j = 1 ; j < max_rows; j++){
reference[i*max_cols+j] = blosum62[input_itemsets[i*max_cols]][input_itemsets[j]];
}
}
for( int i = 1; i< max_rows ; i++)
input_itemsets[i*max_cols] = -i * penalty;
for( int j = 1; j< max_cols ; j++)
input_itemsets[j] = -j * penalty;
double offload_start = get_time();
{ // SYCL scope
#ifdef USE_GPU
gpu_selector dev_sel;
#else
cpu_selector dev_sel;
#endif
queue q(dev_sel);
int workgroupsize = BLOCK_SIZE;
#ifdef DEBUG
if(workgroupsize < 0){
printf("ERROR: invalid or missing <num_work_items>[/<work_group_size>]\n");
return -1;
}
#endif
// set global and local workitems
const size_t local_work = (size_t)workgroupsize;
size_t global_work;
const int worksize = max_cols - 1;
#ifdef DEBUG
printf("worksize = %d\n", worksize);
#endif
//these two parameters are for extension use, don't worry about it.
const int offset_r = 0;
const int offset_c = 0;
const int block_width = worksize/BLOCK_SIZE ;
const property_list props = property::buffer::use_host_ptr();
buffer<int,1> input_itemsets_d (input_itemsets, max_cols * max_rows, props);
input_itemsets_d.set_final_data( output_itemsets );
buffer<int,1> reference_d (reference, max_cols * max_rows, props);
reference_d.set_final_data( nullptr );
#ifdef DEBUG
printf("Processing upper-left matrix\n");
#endif
for( int blk = 1 ; blk <= block_width ; blk++){
global_work = BLOCK_SIZE * blk; // kernel arg set every iteration
#ifdef DEBUG
printf("global size: %d local size: %d\n", global_work, local_work);
#endif
q.submit([&](handler& cgh) {
auto d_input_itemsets_acc = input_itemsets_d.get_access<sycl_read_write>(cgh);
auto d_reference_acc = reference_d.get_access<sycl_read_write>(cgh);
accessor <int, 1, sycl_read_write, access::target::local> input_itemsets_l ((BLOCK_SIZE + 1) *(BLOCK_SIZE+1), cgh);
accessor <int, 1, sycl_read_write, access::target::local> reference_l (BLOCK_SIZE * BLOCK_SIZE, cgh);
cgh.parallel_for<class kernel1>(
nd_range<1>(range<1>(global_work), range<1>(local_work)), [=] (nd_item<1> item) {
#include "kernel1.sycl"
});
});
}
#ifdef DEBUG
printf("Processing lower-right matrix\n");
#endif
for( int blk = block_width - 1 ; blk >= 1 ; blk--){
global_work = BLOCK_SIZE * blk;
q.submit([&](handler& cgh) {
auto d_input_itemsets_acc = input_itemsets_d.get_access<sycl_read_write>(cgh);
auto d_reference_acc = reference_d.get_access<sycl_read_write>(cgh);
accessor <int, 1, sycl_read_write, access::target::local> input_itemsets_l ((BLOCK_SIZE + 1) *(BLOCK_SIZE+1), cgh);
accessor <int, 1, sycl_read_write, access::target::local> reference_l (BLOCK_SIZE * BLOCK_SIZE, cgh);
cgh.parallel_for<class kernel2>(
nd_range<1>(range<1>(global_work), range<1>(local_work)), [=] (nd_item<1> item) {
#include "kernel2.sycl"
});
});
}
} // SYCL scope
double offload_end = get_time();
printf("Device offloading time = %lf(s)\n", offload_end - offload_start);
#ifdef TRACEBACK
#ifdef USE_GPU
FILE *fpo = fopen("gpu_result.txt","w");
#else
FILE *fpo = fopen("cpu_result.txt","w");
#endif
fprintf(fpo, "print traceback value:\n");
for (int i = max_rows - 2, j = max_rows - 2; i>=0, j>=0;){
int nw, n, w, traceback;
if ( i == max_rows - 2 && j == max_rows - 2 )
fprintf(fpo, "%d ", output_itemsets[ i * max_cols + j]); //print the first element
if ( i == 0 && j == 0 )
break;
if ( i > 0 && j > 0 ){
nw = output_itemsets[(i - 1) * max_cols + j - 1];
w = output_itemsets[ i * max_cols + j - 1 ];
n = output_itemsets[(i - 1) * max_cols + j];
}
else if ( i == 0 ){
nw = n = LIMIT;
w = output_itemsets[ i * max_cols + j - 1 ];
}
else if ( j == 0 ){
nw = w = LIMIT;
n = output_itemsets[(i - 1) * max_cols + j];
}
else{
}
//traceback = max3(nw, w, n);
int new_nw, new_w, new_n;
new_nw = nw + reference[i * max_cols + j];
new_w = w - penalty;
new_n = n - penalty;
traceback = max3(new_nw, new_w, new_n);
if(traceback == new_nw)
traceback = nw;
if(traceback == new_w)
traceback = w;
if(traceback == new_n)
traceback = n;
fprintf(fpo, "%d ", traceback);
if(traceback == nw )
{i--; j--; continue;}
else if(traceback == w )
{j--; continue;}
else if(traceback == n )
{i--; continue;}
else
;
}
fclose(fpo);
#endif
//printf("Computation Done\n");
free(reference);
free(input_itemsets);
free(output_itemsets);
}
|
#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *londinium_strings[] = {
QT_TRANSLATE_NOOP("londinium-core", ""
"(1 = keep tx meta data e.g. account owner and payment request information, 2 "
"= drop tx meta data)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Allow JSON-RPC connections from specified source. Valid for <ip> are a "
"single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or "
"a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"),
QT_TRANSLATE_NOOP("londinium-core", ""
"An error occurred while setting up the RPC address %s port %u for listening: "
"%s"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Bind to given address and always listen on it. Use [host]:port notation for "
"IPv6"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Bind to given address and whitelist peers connecting to it. Use [host]:port "
"notation for IPv6"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Bind to given address to listen for JSON-RPC connections. Use [host]:port "
"notation for IPv6. This option can be specified multiple times (default: "
"bind to all interfaces)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Cannot obtain a lock on data directory %s. Londinium Core is probably already "
"running."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Change automatic finalized budget voting behavior. mode=auto: Vote for only "
"exact finalized budget match to my generated budget. (string, default: auto)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Continuously rate-limit free transactions to <n>*1000 bytes per minute "
"(default:%u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Create new files with system default permissions, instead of umask 077 (only "
"effective with disabled wallet functionality)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Delete all wallet transactions and only recover those parts of the "
"blockchain through -rescan on startup"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Disable all Londinium specific functionality (Masternodes, SwiftTX, "
"Budgeting) (0-1, default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Distributed under the MIT software license, see the accompanying file "
"COPYING or <http://www.opensource.org/licenses/mit-license.php>."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Enable SwiftTX, show confirmations for locked transactions (bool, default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Enable spork administration functionality with the appropriate private key."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Enter regression test mode, which uses a special chain in which blocks can "
"be solved instantly."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Error: Listening for incoming connections failed (listen returned error %s)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Error: The transaction was rejected! This might happen if some of the coins "
"in your wallet were already spent, such as if you used a copy of wallet.dat "
"and coins were spent in the copy but not marked as spent here."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Error: This transaction requires a transaction fee of at least %s because of "
"its amount, complexity, or use of recently received funds!"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Error: Unsupported argument -checklevel found. Checklevel must be level 4."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Error: Unsupported argument -socks found. Setting SOCKS version isn't "
"possible anymore, only SOCKS5 proxies are supported."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Execute command when a relevant alert is received or we see a really long "
"fork (%s in cmd is replaced by message)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Fees (in LON/Kb) smaller than this are considered zero fee for relaying "
"(default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Fees (in LON/Kb) smaller than this are considered zero fee for transaction "
"creation (default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Flush database activity from memory pool to disk log every <n> megabytes "
"(default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"If paytxfee is not set, include enough fee so transactions begin "
"confirmation on average within n blocks (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"In this mode -genproclimit controls how many blocks are generated "
"immediately."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Insufficient or insufficient confirmed funds, you might need to wait a few "
"minutes and try again."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay "
"fee of %s to prevent stuck transactions)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Keep the specified amount available for spending at all times (default: 0)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Log transaction priority and fee per kB when mining blocks (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Maintain a full transaction index, used by the getrawtransaction rpc call "
"(default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Maximum size of data in data carrier transactions we relay and mine "
"(default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Maximum total fees to use in a single wallet transaction, setting too low "
"may abort large transactions (default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Output debugging information (default: %u, supplying <category> is optional)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Query for peer addresses via DNS lookup, if low on addresses (default: 1 "
"unless -connect)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Randomize credentials for every proxy connection. This enables Tor stream "
"isolation (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Require high priority for relaying free or low-fee transactions (default:%u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Send trace/debug info to console instead of debug.log file (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Set the number of script verification threads (%u to %d, 0 = auto, <0 = "
"leave that many cores free, default: %d)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Set the number of threads for coin generation if enabled (-1 = all cores, "
"default: %d)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Show N confirmations for a successfully locked transaction (0-9999, default: "
"%u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Support filtering of blocks and transaction with bloom filters (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"SwiftTX requires inputs with at least 6 confirmations, you might need to wait "
"a few minutes and try again."),
QT_TRANSLATE_NOOP("londinium-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"staking or merchant applications!"),
QT_TRANSLATE_NOOP("londinium-core", ""
"This product includes software developed by the OpenSSL Project for use in "
"the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software "
"written by Eric Young and UPnP software written by Thomas Bernard."),
QT_TRANSLATE_NOOP("londinium-core", ""
"To use londiniumd, or the -server option to londinium-qt, you must set an rpcpassword "
"in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=londiniumrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Londinium Alert\" admin@foo.com\n"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Unable to bind to %s on this computer. Londinium Core is probably already running."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Unable to locate enough funds for this transaction that are not equal 1000 "
"LON."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: "
"%s)"),
QT_TRANSLATE_NOOP("londinium-core", ""
"Warning: -maxtxfee is set very high! Fees this large could be paid on a "
"single transaction."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong Londinium Core will not work properly."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Warning: The network does not appear to fully agree! Some miners appear to "
"be experiencing issues."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Warning: We do not appear to fully agree with our peers! You may need to "
"upgrade, or other nodes may need to upgrade."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Whitelist peers connecting from the given netmask or IP address. Can be "
"specified multiple times."),
QT_TRANSLATE_NOOP("londinium-core", ""
"Whitelisted peers cannot be DoS banned and their transactions are always "
"relayed, even if they are already in the mempool, useful e.g. for a gateway"),
QT_TRANSLATE_NOOP("londinium-core", ""
"You must specify a masternodeprivkey in the configuration. Please see "
"documentation for help."),
QT_TRANSLATE_NOOP("londinium-core", "(9555 could be used only on mainnet)"),
QT_TRANSLATE_NOOP("londinium-core", "(default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", "(default: 1)"),
QT_TRANSLATE_NOOP("londinium-core", "(must be 9555 for mainnet)"),
QT_TRANSLATE_NOOP("londinium-core", "<category> can be:"),
QT_TRANSLATE_NOOP("londinium-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("londinium-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("londinium-core", "Accept public REST requests (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Acceptable ciphers (default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("londinium-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("londinium-core", "Already have that input."),
QT_TRANSLATE_NOOP("londinium-core", "Always query for peer addresses via DNS lookup (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Attempt to force blockchain corruption recovery"),
QT_TRANSLATE_NOOP("londinium-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("londinium-core", "Automatically create Tor hidden service (default: %d)"),
QT_TRANSLATE_NOOP("londinium-core", "Block creation options:"),
QT_TRANSLATE_NOOP("londinium-core", "Can't find random Masternode."),
QT_TRANSLATE_NOOP("londinium-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("londinium-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("londinium-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("londinium-core", "Cannot resolve -whitebind address: '%s'"),
QT_TRANSLATE_NOOP("londinium-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("londinium-core", "Collateral not valid."),
QT_TRANSLATE_NOOP("londinium-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("londinium-core", "Connect through SOCKS5 proxy"),
QT_TRANSLATE_NOOP("londinium-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("londinium-core", "Connection options:"),
QT_TRANSLATE_NOOP("londinium-core", "Copyright (C) 2009-%i The Bitcoin Core Developers"),
QT_TRANSLATE_NOOP("londinium-core", "Copyright (C) 2014-%i The Dash Core Developers"),
QT_TRANSLATE_NOOP("londinium-core", "Copyright (C) 2015-%i The PIVX Core Developers"),
QT_TRANSLATE_NOOP("londinium-core", "Copyright (C) 2017-%i The Londinium Core Developers"),
QT_TRANSLATE_NOOP("londinium-core", "Corrupted block database detected"),
QT_TRANSLATE_NOOP("londinium-core", "Could not parse -rpcbind value %s as network address"),
QT_TRANSLATE_NOOP("londinium-core", "Could not parse masternode.conf"),
QT_TRANSLATE_NOOP("londinium-core", "Debugging/Testing options:"),
QT_TRANSLATE_NOOP("londinium-core", "Delete blockchain folders and resync from scratch"),
QT_TRANSLATE_NOOP("londinium-core", "Disable OS notifications for incoming transactions (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Disable safemode, override a real safe mode event (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("londinium-core", "Display the stake modifier calculations in the debug.log file."),
QT_TRANSLATE_NOOP("londinium-core", "Display verbose coin stake messages in the debug.log file."),
QT_TRANSLATE_NOOP("londinium-core", "Do not load the wallet and disable wallet RPC calls"),
QT_TRANSLATE_NOOP("londinium-core", "Do you want to rebuild the block database now?"),
QT_TRANSLATE_NOOP("londinium-core", "Done loading"),
QT_TRANSLATE_NOOP("londinium-core", "Enable publish hash block in <address>"),
QT_TRANSLATE_NOOP("londinium-core", "Enable publish hash transaction (locked via SwiftTX) in <address>"),
QT_TRANSLATE_NOOP("londinium-core", "Enable publish hash transaction in <address>"),
QT_TRANSLATE_NOOP("londinium-core", "Enable publish raw block in <address>"),
QT_TRANSLATE_NOOP("londinium-core", "Enable publish raw transaction (locked via SwiftTX) in <address>"),
QT_TRANSLATE_NOOP("londinium-core", "Enable publish raw transaction in <address>"),
QT_TRANSLATE_NOOP("londinium-core", "Enable staking functionality (0-1, default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Enable the client to act as a masternode (0-1, default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Entries are full."),
QT_TRANSLATE_NOOP("londinium-core", "Error connecting to Masternode."),
QT_TRANSLATE_NOOP("londinium-core", "Error initializing block database"),
QT_TRANSLATE_NOOP("londinium-core", "Error initializing wallet database environment %s!"),
QT_TRANSLATE_NOOP("londinium-core", "Error loading block database"),
QT_TRANSLATE_NOOP("londinium-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("londinium-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("londinium-core", "Error loading wallet.dat: Wallet requires newer version of Londinium Core"),
QT_TRANSLATE_NOOP("londinium-core", "Error opening block database"),
QT_TRANSLATE_NOOP("londinium-core", "Error reading from database, shutting down."),
QT_TRANSLATE_NOOP("londinium-core", "Error recovering public key."),
QT_TRANSLATE_NOOP("londinium-core", "Error"),
QT_TRANSLATE_NOOP("londinium-core", "Error: A fatal internal error occured, see debug.log for details"),
QT_TRANSLATE_NOOP("londinium-core", "Error: Disk space is low!"),
QT_TRANSLATE_NOOP("londinium-core", "Error: Unsupported argument -tor found, use -onion."),
QT_TRANSLATE_NOOP("londinium-core", "Error: Wallet locked, unable to create transaction!"),
QT_TRANSLATE_NOOP("londinium-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("londinium-core", "Failed to read block index"),
QT_TRANSLATE_NOOP("londinium-core", "Failed to read block"),
QT_TRANSLATE_NOOP("londinium-core", "Failed to write block index"),
QT_TRANSLATE_NOOP("londinium-core", "Fee (in LON/kB) to add to transactions you send (default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", "Finalizing transaction."),
QT_TRANSLATE_NOOP("londinium-core", "Force safe mode (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Found enough users, signing ( waiting %s )"),
QT_TRANSLATE_NOOP("londinium-core", "Found enough users, signing ..."),
QT_TRANSLATE_NOOP("londinium-core", "Generate coins (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "How many blocks to check at startup (default: %u, 0 = all)"),
QT_TRANSLATE_NOOP("londinium-core", "If <category> is not supplied, output all debugging information."),
QT_TRANSLATE_NOOP("londinium-core", "Importing..."),
QT_TRANSLATE_NOOP("londinium-core", "Imports blocks from external blk000??.dat file"),
QT_TRANSLATE_NOOP("londinium-core", "Include IP addresses in debug output (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Incompatible mode."),
QT_TRANSLATE_NOOP("londinium-core", "Incompatible version."),
QT_TRANSLATE_NOOP("londinium-core", "Incorrect or no genesis block found. Wrong datadir for network?"),
QT_TRANSLATE_NOOP("londinium-core", "Information"),
QT_TRANSLATE_NOOP("londinium-core", "Initialization sanity check failed. Londinium Core is shutting down."),
QT_TRANSLATE_NOOP("londinium-core", "Input is not valid."),
QT_TRANSLATE_NOOP("londinium-core", "Insufficient funds"),
QT_TRANSLATE_NOOP("londinium-core", "Insufficient funds."),
QT_TRANSLATE_NOOP("londinium-core", "Invalid -onion address or hostname: '%s'"),
QT_TRANSLATE_NOOP("londinium-core", "Invalid -proxy address or hostname: '%s'"),
QT_TRANSLATE_NOOP("londinium-core", "Invalid amount for -maxtxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("londinium-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("londinium-core", "Invalid amount for -mintxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("londinium-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
QT_TRANSLATE_NOOP("londinium-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("londinium-core", "Invalid amount for -reservebalance=<amount>"),
QT_TRANSLATE_NOOP("londinium-core", "Invalid amount"),
QT_TRANSLATE_NOOP("londinium-core", "Invalid masternodeprivkey. Please see documenation."),
QT_TRANSLATE_NOOP("londinium-core", "Invalid netmask specified in -whitelist: '%s'"),
QT_TRANSLATE_NOOP("londinium-core", "Invalid port detected in masternode.conf"),
QT_TRANSLATE_NOOP("londinium-core", "Invalid private key."),
QT_TRANSLATE_NOOP("londinium-core", "Invalid script detected."),
QT_TRANSLATE_NOOP("londinium-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Limit size of signature cache to <n> entries (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Line: %d"),
QT_TRANSLATE_NOOP("londinium-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Listen for connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("londinium-core", "Loading block index..."),
QT_TRANSLATE_NOOP("londinium-core", "Loading budget cache..."),
QT_TRANSLATE_NOOP("londinium-core", "Loading masternode cache..."),
QT_TRANSLATE_NOOP("londinium-core", "Loading masternode payment cache..."),
QT_TRANSLATE_NOOP("londinium-core", "Loading sporks..."),
QT_TRANSLATE_NOOP("londinium-core", "Loading wallet... (%3.2f %%)"),
QT_TRANSLATE_NOOP("londinium-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("londinium-core", "Lock is already in place."),
QT_TRANSLATE_NOOP("londinium-core", "Lock masternodes from masternode configuration file (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Maintain at most <n> connections to peers (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Masternode options:"),
QT_TRANSLATE_NOOP("londinium-core", "Masternode queue is full."),
QT_TRANSLATE_NOOP("londinium-core", "Masternode:"),
QT_TRANSLATE_NOOP("londinium-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Missing input transaction information."),
QT_TRANSLATE_NOOP("londinium-core", "Need to specify a port with -whitebind: '%s'"),
QT_TRANSLATE_NOOP("londinium-core", "No Masternodes detected."),
QT_TRANSLATE_NOOP("londinium-core", "No compatible Masternode found."),
QT_TRANSLATE_NOOP("londinium-core", "Node relay options:"),
QT_TRANSLATE_NOOP("londinium-core", "Non-standard public key detected."),
QT_TRANSLATE_NOOP("londinium-core", "Not compatible with existing transactions."),
QT_TRANSLATE_NOOP("londinium-core", "Not enough file descriptors available."),
QT_TRANSLATE_NOOP("londinium-core", "Not in the Masternode list."),
QT_TRANSLATE_NOOP("londinium-core", "Number of automatic wallet backups (default: 10)"),
QT_TRANSLATE_NOOP("londinium-core", "Only accept block chain matching built-in checkpoints (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"),
QT_TRANSLATE_NOOP("londinium-core", "Options:"),
QT_TRANSLATE_NOOP("londinium-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("londinium-core", "Preparing for resync..."),
QT_TRANSLATE_NOOP("londinium-core", "Prepend debug output with timestamp (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Print version and exit"),
QT_TRANSLATE_NOOP("londinium-core", "RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)"),
QT_TRANSLATE_NOOP("londinium-core", "RPC server options:"),
QT_TRANSLATE_NOOP("londinium-core", "RPC support for HTTP persistent connections (default: %d)"),
QT_TRANSLATE_NOOP("londinium-core", "Randomly drop 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("londinium-core", "Randomly fuzz 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("londinium-core", "Rebuild block chain index from current blk000??.dat files"),
QT_TRANSLATE_NOOP("londinium-core", "Receive and display P2P network alerts (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Relay and mine data carrier transactions (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Relay non-P2SH multisig (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("londinium-core", "Rescanning..."),
QT_TRANSLATE_NOOP("londinium-core", "Run a thread to flush wallet periodically (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("londinium-core", "Send transactions as zero-fee transactions if possible (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Server certificate file (default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", "Server private key (default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", "Session not complete!"),
QT_TRANSLATE_NOOP("londinium-core", "Session timed out."),
QT_TRANSLATE_NOOP("londinium-core", "Set database cache size in megabytes (%d to %d, default: %d)"),
QT_TRANSLATE_NOOP("londinium-core", "Set external address:port to get to this masternode (example: %s)"),
QT_TRANSLATE_NOOP("londinium-core", "Set key pool size to <n> (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Set maximum block size in bytes (default: %d)"),
QT_TRANSLATE_NOOP("londinium-core", "Set minimum block size in bytes (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Set the Maximum reorg depth (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Set the masternode private key"),
QT_TRANSLATE_NOOP("londinium-core", "Set the number of threads to service RPC calls (default: %d)"),
QT_TRANSLATE_NOOP("londinium-core", "Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Show all debugging options (usage: --help -help-debug)"),
QT_TRANSLATE_NOOP("londinium-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("londinium-core", "Signing failed."),
QT_TRANSLATE_NOOP("londinium-core", "Signing timed out."),
QT_TRANSLATE_NOOP("londinium-core", "Signing transaction failed"),
QT_TRANSLATE_NOOP("londinium-core", "Specify configuration file (default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"),
QT_TRANSLATE_NOOP("londinium-core", "Specify data directory"),
QT_TRANSLATE_NOOP("londinium-core", "Specify masternode configuration file (default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", "Specify pid file (default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", "Specify wallet file (within data directory)"),
QT_TRANSLATE_NOOP("londinium-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("londinium-core", "Spend unconfirmed change when sending transactions (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Staking options:"),
QT_TRANSLATE_NOOP("londinium-core", "Stop running after importing blocks from disk (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Submitted following entries to masternode: %u / %d"),
QT_TRANSLATE_NOOP("londinium-core", "Submitted to masternode, waiting for more entries ( %u / %d ) %s"),
QT_TRANSLATE_NOOP("londinium-core", "Submitted to masternode, waiting in queue %s"),
QT_TRANSLATE_NOOP("londinium-core", "SwiftTX options:"),
QT_TRANSLATE_NOOP("londinium-core", "Synchronization failed"),
QT_TRANSLATE_NOOP("londinium-core", "Synchronization finished"),
QT_TRANSLATE_NOOP("londinium-core", "Synchronization pending..."),
QT_TRANSLATE_NOOP("londinium-core", "Synchronizing budgets..."),
QT_TRANSLATE_NOOP("londinium-core", "Synchronizing masternode winners..."),
QT_TRANSLATE_NOOP("londinium-core", "Synchronizing masternodes..."),
QT_TRANSLATE_NOOP("londinium-core", "Synchronizing sporks..."),
QT_TRANSLATE_NOOP("londinium-core", "This help message"),
QT_TRANSLATE_NOOP("londinium-core", "This is experimental software."),
QT_TRANSLATE_NOOP("londinium-core", "This is intended for regression testing tools and app development."),
QT_TRANSLATE_NOOP("londinium-core", "This is not a Masternode."),
QT_TRANSLATE_NOOP("londinium-core", "Threshold for disconnecting misbehaving peers (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Tor control port password (default: empty)"),
QT_TRANSLATE_NOOP("londinium-core", "Tor control port to use if onion listening enabled (default: %s)"),
QT_TRANSLATE_NOOP("londinium-core", "Transaction amount too small"),
QT_TRANSLATE_NOOP("londinium-core", "Transaction amounts must be positive"),
QT_TRANSLATE_NOOP("londinium-core", "Transaction created successfully."),
QT_TRANSLATE_NOOP("londinium-core", "Transaction fees are too high."),
QT_TRANSLATE_NOOP("londinium-core", "Transaction not valid."),
QT_TRANSLATE_NOOP("londinium-core", "Transaction too large for fee policy"),
QT_TRANSLATE_NOOP("londinium-core", "Transaction too large"),
QT_TRANSLATE_NOOP("londinium-core", "Transmitting final transaction."),
QT_TRANSLATE_NOOP("londinium-core", "Unable to bind to %s on this computer (bind returned error %s)"),
QT_TRANSLATE_NOOP("londinium-core", "Unable to sign spork message, wrong key?"),
QT_TRANSLATE_NOOP("londinium-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("londinium-core", "Unknown state: id = %u"),
QT_TRANSLATE_NOOP("londinium-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("londinium-core", "Use OpenSSL (https) for JSON-RPC connections"),
QT_TRANSLATE_NOOP("londinium-core", "Use UPnP to map the listening port (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Use UPnP to map the listening port (default: 1 when listening)"),
QT_TRANSLATE_NOOP("londinium-core", "Use a custom max chain reorganization depth (default: %u)"),
QT_TRANSLATE_NOOP("londinium-core", "Use the test network"),
QT_TRANSLATE_NOOP("londinium-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("londinium-core", "Verifying blocks..."),
QT_TRANSLATE_NOOP("londinium-core", "Verifying wallet..."),
QT_TRANSLATE_NOOP("londinium-core", "Wallet %s resides outside data directory %s"),
QT_TRANSLATE_NOOP("londinium-core", "Wallet is locked."),
QT_TRANSLATE_NOOP("londinium-core", "Wallet needed to be rewritten: restart Londinium Core to complete"),
QT_TRANSLATE_NOOP("londinium-core", "Wallet options:"),
QT_TRANSLATE_NOOP("londinium-core", "Wallet window title"),
QT_TRANSLATE_NOOP("londinium-core", "Warning"),
QT_TRANSLATE_NOOP("londinium-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("londinium-core", "Warning: Unsupported argument -benchmark ignored, use -debug=bench."),
QT_TRANSLATE_NOOP("londinium-core", "Warning: Unsupported argument -debugnet ignored, use -debug=net."),
QT_TRANSLATE_NOOP("londinium-core", "Will retry..."),
QT_TRANSLATE_NOOP("londinium-core", "You need to rebuild the database using -reindex to change -txindex"),
QT_TRANSLATE_NOOP("londinium-core", "Your entries added successfully."),
QT_TRANSLATE_NOOP("londinium-core", "Your transaction was accepted into the pool!"),
QT_TRANSLATE_NOOP("londinium-core", "Zapping all transactions from wallet..."),
QT_TRANSLATE_NOOP("londinium-core", "ZeroMQ notification options:"),
QT_TRANSLATE_NOOP("londinium-core", "on startup"),
QT_TRANSLATE_NOOP("londinium-core", "wallet.dat corrupt, salvage failed"),
};
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
namespace cv
{
class HausdorffDistanceExtractorImpl : public HausdorffDistanceExtractor
{
public:
/* Constructor */
HausdorffDistanceExtractorImpl(int _distanceFlag = NORM_L1, float _rankProportion=0.6)
{
distanceFlag = _distanceFlag;
rankProportion = _rankProportion;
name_ = "ShapeDistanceExtractor.HAU";
}
/* Destructor */
~HausdorffDistanceExtractorImpl()
{
}
virtual AlgorithmInfo* info() const { return 0; }
//! the main operator
virtual float computeDistance(InputArray contour1, InputArray contour2);
//! Setters/Getters
virtual void setDistanceFlag(int _distanceFlag) {distanceFlag=_distanceFlag;}
virtual int getDistanceFlag() const {return distanceFlag;}
virtual void setRankProportion(float _rankProportion)
{
CV_Assert((_rankProportion>0) && (_rankProportion<=1));
rankProportion=_rankProportion;
}
virtual float getRankProportion() const {return rankProportion;}
//! write/read
virtual void write(FileStorage& fs) const
{
fs << "name" << name_
<< "distance" << distanceFlag
<< "rank" << rankProportion;
}
virtual void read(const FileNode& fn)
{
CV_Assert( (String)fn["name"] == name_ );
distanceFlag = (int)fn["distance"];
rankProportion = (float)fn["rank"];
}
private:
int distanceFlag;
float rankProportion;
protected:
String name_;
};
//! Hausdorff distance for a pair of set of points
static float _apply(const Mat &set1, const Mat &set2, int distType, double propRank)
{
// Building distance matrix //
Mat disMat(set1.cols, set2.cols, CV_32F);
int K = int(propRank*(disMat.rows-1));
for (int r=0; r<disMat.rows; r++)
{
for (int c=0; c<disMat.cols; c++)
{
Point2f diff = set1.at<Point2f>(0,r)-set2.at<Point2f>(0,c);
disMat.at<float>(r,c) = (float)norm(Mat(diff), distType);
}
}
Mat shortest(disMat.rows,1,CV_32F);
for (int ii=0; ii<disMat.rows; ii++)
{
Mat therow = disMat.row(ii);
double mindis;
minMaxIdx(therow, &mindis);
shortest.at<float>(ii,0) = float(mindis);
}
Mat sorted;
cv::sort(shortest, sorted, SORT_EVERY_ROW | SORT_DESCENDING);
return sorted.at<float>(K,0);
}
float HausdorffDistanceExtractorImpl::computeDistance(InputArray contour1, InputArray contour2)
{
Mat set1=contour1.getMat(), set2=contour2.getMat();
if (set1.type() != CV_32F)
set1.convertTo(set1, CV_32F);
if (set2.type() != CV_32F)
set2.convertTo(set2, CV_32F);
CV_Assert((set1.channels()==2) && (set1.cols>0));
CV_Assert((set2.channels()==2) && (set2.cols>0));
return std::max( _apply(set1, set2, distanceFlag, rankProportion),
_apply(set2, set1, distanceFlag, rankProportion) );
}
Ptr <HausdorffDistanceExtractor> createHausdorffDistanceExtractor(int distanceFlag, float rankProp)
{
return Ptr<HausdorffDistanceExtractor>(new HausdorffDistanceExtractorImpl(distanceFlag, rankProp));
}
} // cv
|
// Copyright (c) 2001-2010 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// This example is the equivalent to the following lex program:
/*
//[wcl_flex_version
%{
int c = 0, w = 0, l = 0;
%}
%%
[^ \t\n]+ { ++w; c += yyleng; }
\n { ++c; ++l; }
. { ++c; }
%%
main()
{
yylex();
printf("%d %d %d\n", l, w, c);
}
//]
*/
// Its purpose is to do the word count function of the wc command in UNIX. It
// prints the number of lines, words and characters in a file.
//
// This examples shows how to use semantic actions associated with token
// definitions to directly attach actions to tokens. These get executed
// whenever the corresponding token got matched in the input sequence. Note,
// how this example implements all functionality directly in the lexer
// definition without any need for a parser.
// #define BOOST_SPIRIT_LEXERTL_DEBUG
#include <boost/config/warning_disable.hpp>
//[wcl_includes
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_statement.hpp>
#include <boost/spirit/include/phoenix_algorithm.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
//]
#include <iostream>
#include <string>
#include "example.hpp"
//[wcl_namespaces
namespace lex = boost::spirit::lex;
//]
///////////////////////////////////////////////////////////////////////////////
// Token definition: We use the lexertl based lexer engine as the underlying
// lexer type.
//
// Note, the token definition type is derived from the 'lexertl_actor_lexer'
// template, which is a necessary to being able to use lexer semantic actions.
///////////////////////////////////////////////////////////////////////////////
struct distance_func
{
template <typename Iterator1, typename Iterator2>
struct result : boost::iterator_difference<Iterator1> {};
template <typename Iterator1, typename Iterator2>
typename result<Iterator1, Iterator2>::type
operator()(Iterator1 const& begin, Iterator2 const& end) const
{
return std::distance(begin, end);
}
};
boost::phoenix::function<distance_func> const distance = distance_func();
//[wcl_token_definition
template <typename Lexer>
struct word_count_tokens : lex::lexer<Lexer>
{
word_count_tokens()
: c(0), w(0), l(0)
, word("[^ \t\n]+") // define tokens
, eol("\n")
, any(".")
{
using boost::spirit::lex::_start;
using boost::spirit::lex::_end;
using boost::phoenix::ref;
// associate tokens with the lexer
this->self
= word [++ref(w), ref(c) += distance(_start, _end)]
| eol [++ref(c), ++ref(l)]
| any [++ref(c)]
;
}
std::size_t c, w, l;
lex::token_def<> word, eol, any;
};
//]
///////////////////////////////////////////////////////////////////////////////
//[wcl_main
int main(int argc, char* argv[])
{
/*< Specifying `omit` as the token attribute type generates a token class
not holding any token attribute at all (not even the iterator range of the
matched input sequence), therefore optimizing the token, the lexer, and
possibly the parser implementation as much as possible. Specifying
`mpl::false_` as the 3rd template parameter generates a token
type and an iterator, both holding no lexer state, allowing for even more
aggressive optimizations. As a result the token instances contain the token
ids as the only data member.
>*/ typedef
lex::lexertl::token<char const*, lex::omit, boost::mpl::false_>
token_type;
/*< This defines the lexer type to use
>*/ typedef lex::lexertl::actor_lexer<token_type> lexer_type;
/*< Create the lexer object instance needed to invoke the lexical analysis
>*/ word_count_tokens<lexer_type> word_count_lexer;
/*< Read input from the given file, tokenize all the input, while discarding
all generated tokens
>*/ std::string str (read_from_file(1 == argc ? "word_count.input" : argv[1]));
char const* first = str.c_str();
char const* last = &first[str.size()];
/*< Create a pair of iterators returning the sequence of generated tokens
>*/ lexer_type::iterator_type iter = word_count_lexer.begin(first, last);
lexer_type::iterator_type end = word_count_lexer.end();
/*< Here we simply iterate over all tokens, making sure to break the loop
if an invalid token gets returned from the lexer
>*/ while (iter != end && token_is_valid(*iter))
++iter;
if (iter == end) {
std::cout << "lines: " << word_count_lexer.l
<< ", words: " << word_count_lexer.w
<< ", characters: " << word_count_lexer.c
<< "\n";
}
else {
std::string rest(first, last);
std::cout << "Lexical analysis failed\n" << "stopped at: \""
<< rest << "\"\n";
}
return 0;
}
//]
|
// Copyright (C) 2011 - 2014 David Reid. See included LICENCE.
#include <GTGE/Components/ProximityComponent.hpp>
#include <GTGE/SceneNode.hpp>
namespace GT
{
GTENGINE_IMPL_COMPONENT_ATTRIBS(ProximityComponent, "Proximity")
ProximityComponent::ProximityComponent(SceneNode &node)
: CollisionShapeComponent(node), ghostObject(), m_world(nullptr), sceneNodesInsideVolume()
{
this->ghostObject.setCollisionShape(&this->collisionShape);
this->ghostObject.setCollisionFlags(btCollisionObject::CF_NO_CONTACT_RESPONSE);
this->ghostObject.setUserPointer(&node);
}
ProximityComponent::~ProximityComponent()
{
auto world = this->ghostObject.GetWorld();
if (world != nullptr)
{
world->RemoveGhostObject(this->ghostObject);
}
}
void ProximityComponent::ApplySceneNodeTransformation()
{
btTransform transform;
this->node.GetWorldTransform(transform);
this->ghostObject.setWorldTransform(transform);
}
void ProximityComponent::UpdateContainment(Vector<uint64_t> &sceneNodesEntered, Vector<uint64_t> &sceneNodesLeft)
{
SortedVector<uint64_t> sceneNodesLeaving(this->sceneNodesInsideVolume);
ProximityComponent::Iterator i(*this);
while (i)
{
if (i.otherNode != &this->GetNode())
{
assert(i.otherNode != nullptr);
{
auto otherNodeID = i.otherNode->GetID();
if (!this->sceneNodesInsideVolume.Exists(otherNodeID))
{
this->sceneNodesInsideVolume.Insert(otherNodeID);
sceneNodesEntered.PushBack(otherNodeID);
}
else
{
sceneNodesLeaving.RemoveFirstOccuranceOf(otherNodeID);
}
}
}
++i;
}
// At this point we'll have a list of nodes that have left the volume. We need to copies these over to 'sceneNodesLeft'.
for (size_t j = 0; j < sceneNodesLeaving.count; ++j)
{
sceneNodesLeft.PushBack(sceneNodesLeaving[j]);
this->sceneNodesInsideVolume.RemoveFirstOccuranceOf(sceneNodesLeaving[j]);
}
}
///////////////////////////////////////////////////////
// Serialization/Deserialization.
void ProximityComponent::Serialize(Serializer &serializer) const
{
// All we actually want to write is the collision shapes.
CollisionShapeComponent::Serialize(serializer);
}
void ProximityComponent::Deserialize(Deserializer &deserializer)
{
auto world = this->ghostObject.GetWorld();
if (world != nullptr)
{
world->RemoveGhostObject(this->ghostObject);
}
// First we deserialize the collision shapes.
CollisionShapeComponent::Deserialize(deserializer);
// Now we just need to update the scale and transformation based on the scene node.
this->ApplySceneNodeScaling();
this->ApplySceneNodeTransformation();
if (world != nullptr)
{
world->AddGhostObject(this->ghostObject, this->collisionGroup, this->collisionMask);
}
this->OnChanged();
}
//////////////////////////////////////////
// Private
void ProximityComponent::OnPreCollisionShapeChanged()
{
m_world = this->ghostObject.GetWorld();
if (m_world != nullptr)
{
m_world->RemoveGhostObject(this->ghostObject);
}
}
void ProximityComponent::OnPostCollisionShapeChanged()
{
if (m_world != nullptr)
{
m_world->AddGhostObject(this->ghostObject, this->collisionGroup, this->collisionMask);
}
m_world = nullptr;
}
}
// Iterator
namespace GT
{
ProximityComponent::Iterator::Iterator(ProximityComponent &component)
: component(&component), otherNode(nullptr), manifoldArray(), i(0)
{
++(*this);
}
ProximityComponent::Iterator::Iterator(SceneNode &sceneNode)
: component(sceneNode.GetComponent<ProximityComponent>()), otherNode(nullptr), manifoldArray(), i(0)
{
++(*this);
}
ProximityComponent::Iterator & ProximityComponent::Iterator::operator++()
{
if (this->component != nullptr)
{
this->otherNode = nullptr;
auto world = this->component->ghostObject.GetWorld();
if (world != nullptr)
{
auto overlappingPairCache = this->component->ghostObject.getOverlappingPairCache();
// If it's the first iteration, we need to enable narrow-phase collision detection.
if (this->i == 0)
{
world->GetCollisionDispatcher().dispatchAllCollisionPairs(overlappingPairCache, world->GetInternalDynamicsWorld().getDispatchInfo(), &world->GetCollisionDispatcher());
}
auto &pairArray = overlappingPairCache->getOverlappingPairArray();
SceneNode* nextNode = nullptr;
while (nextNode == nullptr && this->i < pairArray.size())
{
this->manifoldArray.clear();
auto &pair = pairArray[this->i];
auto collisionPair = world->GetInternalDynamicsWorld().getPairCache()->findPair(pair.m_pProxy0, pair.m_pProxy1);
if (collisionPair != nullptr)
{
auto bodyA = static_cast<btCollisionObject*>(pair.m_pProxy0->m_clientObject);
auto bodyB = static_cast<btCollisionObject*>(pair.m_pProxy1->m_clientObject);
if (bodyA == &this->component->ghostObject)
{
nextNode = static_cast<SceneNode*>(bodyB->getUserPointer());
}
else if (bodyB == &this->component->ghostObject)
{
nextNode = static_cast<SceneNode*>(bodyA->getUserPointer());
}
if (nextNode != nullptr)
{
if (this->component->node.IsRelated(*nextNode))
{
nextNode = nullptr;
}
else
{
// Here is where we check the contact manifolds. If we don't find anything here, the nodes aren't touching.
if (collisionPair->m_algorithm)
{
collisionPair->m_algorithm->getAllContactManifolds(manifoldArray);
}
if (manifoldArray.size() > 0)
{
for (int j = 0; j < manifoldArray.size(); ++j)
{
auto manifold = manifoldArray[j];
if (manifold->getNumContacts() == 0)
{
nextNode = nullptr;
}
}
}
else
{
nextNode = nullptr;
}
}
}
}
++this->i;
}
this->otherNode = nextNode;
}
}
return *this;
}
ProximityComponent::Iterator::operator bool() const
{
return this->component != nullptr && this->otherNode != nullptr;
}
}
|
#include <iostream>
#include <memory>
#include <array>
#include <allocators/wrappers/allocator_wrapper.h>
#include <allocators/wrappers/allocator_singleton.h>
#include <allocators/wrappers/smart_allocator.h>
#include <allocators/malloc_allocator.h>
#include <allocators/bitmapped_block.h>
#include <allocators/free_list.h>
#include <allocators/full_free_list.h>
#include <allocators/stack_allocator.h>
class Base
{
public:
Base() { std::cout << "Base()\n"; }
virtual ~Base() { std::cout << "~Base()\n"; }
};
class A : public Base
{
public:
void swap(A & first, A & second) {
using std::swap;
swap(first.a_, second.a_);
}
A() : Base() { std::cout << "A()\n"; }
~A() { std::cout << "~A() a_: " << a_ << '\n'; }
A & operator=(A other) {
swap(*this, other);
std::cout << "operator=(A)\n";
return *this;
}
private:
int a_ { 124002140 };
};
class B : public Base
{
public:
B() : Base() { std::cout << "B()\n"; }
~B() { std::cout << "~B()\n"; }
private:
long b1_ { 10 };
long b2_ { 20 };
};
int main() {
using namespace brh::allocators;
using Type = A;
using TypeArray = std::array<A, 10>;
using BaseAllocator = StackAllocator<std::array, sizeof(Type) * 1024>;
using AllocatorType = SmartAllocator<BaseAllocator>;
AllocatorType allocator;
std::size_t const size {8};
BasicBlock<Type> arr[size];
for (std::size_t i {0}; i < size; ++i) {
arr[i] = allocator.construct<Type>();
std::cout << i << ": " << arr[i].getPtr() << '\n';
}
allocator.destruct(arr[size-1]);
arr[size-1] = allocator.construct<Type>();
auto temp = allocator.construct<TypeArray>();
std::cout << temp.getPtr() << '\n';
allocator.destruct(temp);
std::cout << std::endl;
for (std::size_t i {size}; i > 0; --i) {
std::size_t j = i - 1;
allocator.destruct(arr[j]);
std::cout << j << ": " << arr[j].getPtr() << '\n';
}
return 0;
}
|
//
// composed_4.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/use_future.hpp>
#include <asio/write.hpp>
#include <functional>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
using asio::ip::tcp;
//------------------------------------------------------------------------------
// This composed operation automatically serialises a message, using its I/O
// streams insertion operator, before sending it on the socket. To do this, it
// must allocate a buffer for the encoded message and ensure this buffer's
// validity until the underlying async_write operation completes.
template <typename T, typename CompletionToken>
auto async_write_message(tcp::socket& socket,
const T& message, CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of CompletionToken type and the completion handler's signature. When the
// completion token is a simple callback, the return type is always void.
// In this example, when the completion token is asio::yield_context
// (used for stackful coroutines) the return type would be also be void, as
// there is no non-error argument to the completion handler. When the
// completion token is asio::use_future it would be std::future<void>.
-> typename asio::async_result<
typename std::decay<CompletionToken>::type,
void(std::error_code)>::return_type
{
// Define a type alias for the concrete completion handler, as we will use
// the type in several places in the implementation below.
using completion_handler_type =
typename asio::async_completion<CompletionToken,
void(std::error_code)>::completion_handler_type;
// In this example, the composed operation's intermediate completion handler
// is implemented as a hand-crafted function object, rather than a lambda.
struct intermediate_completion_handler
{
// The intermediate completion handler holds a reference to the socket so
// that it can obtain the I/O executor (see get_executor below).
tcp::socket& socket_;
// The allocated buffer for the encoded message. The std::unique_ptr smart
// pointer is move-only, and as a consequence our intermediate completion
// handler is also move-only.
std::unique_ptr<std::string> encoded_message_;
// The user-supplied completion handler.
completion_handler_type handler_;
// The function call operator matches the completion signature of the
// async_write operation.
void operator()(const std::error_code& error, std::size_t /*n*/)
{
// Deallocate the encoded message before calling the user-supplied
// completion handler.
encoded_message_.reset();
// Call the user-supplied handler with the result of the operation.
// The arguments must match the completion signature of our composed
// operation.
handler_(error);
}
// It is essential to the correctness of our composed operation that we
// preserve the executor of the user-supplied completion handler. With a
// hand-crafted function object we can do this by defining a nested type
// executor_type and member function get_executor. These obtain the
// completion handler's associated executor, and default to the I/O
// executor - in this case the executor of the socket - if the completion
// handler does not have its own.
using executor_type = asio::associated_executor_t<
completion_handler_type, tcp::socket::executor_type>;
executor_type get_executor() const noexcept
{
return asio::get_associated_executor(
handler_, socket_.get_executor());
}
// Although not necessary for correctness, we may also preserve the
// allocator of the user-supplied completion handler. This is achieved by
// defining a nested type allocator_type and member function get_allocator.
// These obtain the completion handler's associated allocator, and default
// to std::allocator<void> if the completion handler does not have its own.
using allocator_type = asio::associated_allocator_t<
completion_handler_type, std::allocator<void>>;
allocator_type get_allocator() const noexcept
{
return asio::get_associated_allocator(
handler_, std::allocator<void>{});
}
};
// The asio::async_completion object takes the completion token and
// from it creates:
//
// - completion.completion_handler:
// A completion handler (i.e. a callback) with the specified signature.
//
// - completion.result:
// An object from which we obtain the result of the initiating function.
asio::async_completion<CompletionToken,
void(std::error_code)> completion(token);
// Encode the message and copy it into an allocated buffer. The buffer will
// be maintained for the lifetime of the asynchronous operation.
std::ostringstream os;
os << message;
std::unique_ptr<std::string> encoded_message(new std::string(os.str()));
// Initiate the underlying async_write operation using our intermediate
// completion handler.
asio::async_write(socket, asio::buffer(*encoded_message),
intermediate_completion_handler{socket, std::move(encoded_message),
std::move(completion.completion_handler)});
// Finally, we return the result of the initiating function.
return completion.result.get();
}
//------------------------------------------------------------------------------
void test_callback()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_message(socket, "Testing callback\r\n",
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Message sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<void> f = async_write_message(
socket, "Testing future\r\n", asio::use_future);
io_context.run();
try
{
// Get the result of the operation.
f.get();
std::cout << "Message sent\n";
}
catch (const std::exception& e)
{
std::cout << "Error: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_future();
}
|
/*
Copyright (c) 2009-2016, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#include <El-lite.hpp>
#ifdef EL_HAVE_MPC
namespace El {
byte* Serialize( Int n, const BigInt* x, byte* buf )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
buf = x[j].Serialize( buf );
return buf;
}
byte* Serialize( Int n, const BigFloat* x, byte* buf )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
buf = x[j].Serialize( buf );
return buf;
}
byte* Serialize( Int n, const Complex<BigFloat>* x, byte* buf )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
buf = x[j].Serialize( buf );
return buf;
}
byte* Serialize( Int n, const ValueInt<BigInt>* x, byte* buf )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
{
buf = x[j].value.Serialize( buf );
std::memcpy( buf, &x[j].index, sizeof(Int) );
buf += sizeof(Int);
}
return buf;
}
byte* Serialize( Int n, const ValueInt<BigFloat>* x, byte* buf )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
{
buf = x[j].value.Serialize( buf );
std::memcpy( buf, &x[j].index, sizeof(Int) );
buf += sizeof(Int);
}
return buf;
}
byte* Serialize( Int n, const ValueInt<Complex<BigFloat>>* x, byte* buf )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
{
buf = x[j].value.Serialize( buf );
std::memcpy( buf, &x[j].index, sizeof(Int) );
buf += sizeof(Int);
}
return buf;
}
byte* Serialize( Int n, const Entry<BigInt>* x, byte* buf )
{
DEBUG_CSE
for( Int k=0; k<n; ++k )
{
std::memcpy( buf, &x[k].i, sizeof(Int) );
buf += sizeof(Int);
std::memcpy( buf, &x[k].j, sizeof(Int) );
buf += sizeof(Int);
buf = x[k].value.Serialize( buf );
}
return buf;
}
byte* Serialize( Int n, const Entry<BigFloat>* x, byte* buf )
{
DEBUG_CSE
for( Int k=0; k<n; ++k )
{
std::memcpy( buf, &x[k].i, sizeof(Int) );
buf += sizeof(Int);
std::memcpy( buf, &x[k].j, sizeof(Int) );
buf += sizeof(Int);
buf = x[k].value.Serialize( buf );
}
return buf;
}
byte* Serialize( Int n, const Entry<Complex<BigFloat>>* x, byte* buf )
{
DEBUG_CSE
for( Int k=0; k<n; ++k )
{
std::memcpy( buf, &x[k].i, sizeof(Int) );
buf += sizeof(Int);
std::memcpy( buf, &x[k].j, sizeof(Int) );
buf += sizeof(Int);
buf = x[k].value.Serialize( buf );
}
return buf;
}
void ReserveSerialized( Int n, const BigInt* x, std::vector<byte>& buf )
{
DEBUG_CSE
if( n == 0 )
{
buf.resize(0);
return;
}
const auto packedSize = x[0].SerializedSize();
buf.resize( n*packedSize );
}
void ReserveSerialized( Int n, const BigFloat* x, std::vector<byte>& buf )
{
DEBUG_CSE
if( n == 0 )
{
buf.resize(0);
return;
}
const auto packedSize = x[0].SerializedSize();
buf.resize( n*packedSize );
}
void ReserveSerialized
( Int n, const Complex<BigFloat>* x, std::vector<byte>& buf )
{
DEBUG_CSE
if( n == 0 )
{
buf.resize(0);
return;
}
const auto packedSize = x[0].SerializedSize();
buf.resize( n*packedSize );
}
void ReserveSerialized
( Int n, const ValueInt<BigInt>* x, std::vector<byte>& buf )
{
DEBUG_CSE
if( n == 0 )
{
buf.resize(0);
return;
}
const auto packedSize = x[0].value.SerializedSize() + sizeof(Int);
buf.resize( n*packedSize );
}
void ReserveSerialized
( Int n, const ValueInt<BigFloat>* x, std::vector<byte>& buf )
{
DEBUG_CSE
if( n == 0 )
{
buf.resize(0);
return;
}
const auto packedSize = x[0].value.SerializedSize() + sizeof(Int);
buf.resize( n*packedSize );
}
void ReserveSerialized
( Int n, const ValueInt<Complex<BigFloat>>* x, std::vector<byte>& buf )
{
DEBUG_CSE
if( n == 0 )
{
buf.resize(0);
return;
}
const auto packedSize = x[0].value.SerializedSize() + sizeof(Int);
buf.resize( n*packedSize );
}
void ReserveSerialized
( Int n, const Entry<BigInt>* x, std::vector<byte>& buf )
{
DEBUG_CSE
if( n == 0 )
{
buf.resize(0);
return;
}
const auto packedSize = x[0].value.SerializedSize() + 2*sizeof(Int);
buf.resize( n*packedSize );
}
void ReserveSerialized
( Int n, const Entry<BigFloat>* x, std::vector<byte>& buf )
{
DEBUG_CSE
if( n == 0 )
{
buf.resize(0);
return;
}
const auto packedSize = x[0].value.SerializedSize() + 2*sizeof(Int);
buf.resize( n*packedSize );
}
void ReserveSerialized
( Int n, const Entry<Complex<BigFloat>>* x, std::vector<byte>& buf )
{
DEBUG_CSE
if( n == 0 )
{
buf.resize(0);
return;
}
const auto packedSize = x[0].value.SerializedSize() + 2*sizeof(Int);
buf.resize( n*packedSize );
}
void Serialize( Int n, const BigInt* x, std::vector<byte>& buf )
{
DEBUG_CSE
ReserveSerialized( n, x, buf );
Serialize( n, x, buf.data() );
}
void Serialize( Int n, const BigFloat* x, std::vector<byte>& buf )
{
DEBUG_CSE
ReserveSerialized( n, x, buf );
Serialize( n, x, buf.data() );
}
void Serialize( Int n, const Complex<BigFloat>* x, std::vector<byte>& buf )
{
DEBUG_CSE
ReserveSerialized( n, x, buf );
Serialize( n, x, buf.data() );
}
void Serialize( Int n, const ValueInt<BigInt>* x, std::vector<byte>& buf )
{
DEBUG_CSE
ReserveSerialized( n, x, buf );
Serialize( n, x, buf.data() );
}
void Serialize( Int n, const ValueInt<BigFloat>* x, std::vector<byte>& buf )
{
DEBUG_CSE
ReserveSerialized( n, x, buf );
Serialize( n, x, buf.data() );
}
void Serialize
( Int n, const ValueInt<Complex<BigFloat>>* x, std::vector<byte>& buf )
{
DEBUG_CSE
ReserveSerialized( n, x, buf );
Serialize( n, x, buf.data() );
}
void Serialize( Int n, const Entry<BigInt>* x, std::vector<byte>& buf )
{
DEBUG_CSE
ReserveSerialized( n, x, buf );
Serialize( n, x, buf.data() );
}
void Serialize( Int n, const Entry<BigFloat>* x, std::vector<byte>& buf )
{
DEBUG_CSE
ReserveSerialized( n, x, buf );
Serialize( n, x, buf.data() );
}
void Serialize
( Int n, const Entry<Complex<BigFloat>>* x, std::vector<byte>& buf )
{
DEBUG_CSE
ReserveSerialized( n, x, buf );
Serialize( n, x, buf.data() );
}
byte* Deserialize( Int n, byte* buf, BigInt* x )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
buf = x[j].Deserialize( buf );
return buf;
}
byte* Deserialize( Int n, byte* buf, BigFloat* x )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
buf = x[j].Deserialize( buf );
return buf;
}
byte* Deserialize( Int n, byte* buf, Complex<BigFloat>* x )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
buf = x[j].Deserialize( buf );
return buf;
}
byte* Deserialize( Int n, byte* buf, ValueInt<BigInt>* x )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
{
buf = x[j].value.Deserialize( buf );
std::memcpy( &x[j].index, buf, sizeof(Int) );
buf += sizeof(Int);
}
return buf;
}
byte* Deserialize( Int n, byte* buf, ValueInt<BigFloat>* x )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
{
buf = x[j].value.Deserialize( buf );
std::memcpy( &x[j].index, buf, sizeof(Int) );
buf += sizeof(Int);
}
return buf;
}
byte* Deserialize( Int n, byte* buf, ValueInt<Complex<BigFloat>>* x )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
{
buf = x[j].value.Deserialize( buf );
std::memcpy( &x[j].index, buf, sizeof(Int) );
buf += sizeof(Int);
}
return buf;
}
byte* Deserialize( Int n, byte* buf, Entry<BigInt>* x )
{
DEBUG_CSE
for( Int k=0; k<n; ++k )
{
std::memcpy( &x[k].i, buf, sizeof(Int) );
buf += sizeof(Int);
std::memcpy( &x[k].j, buf, sizeof(Int) );
buf += sizeof(Int);
buf = x[k].value.Deserialize( buf );
}
return buf;
}
byte* Deserialize( Int n, byte* buf, Entry<BigFloat>* x )
{
DEBUG_CSE
for( Int k=0; k<n; ++k )
{
std::memcpy( &x[k].i, buf, sizeof(Int) );
buf += sizeof(Int);
std::memcpy( &x[k].j, buf, sizeof(Int) );
buf += sizeof(Int);
buf = x[k].value.Deserialize( buf );
}
return buf;
}
byte* Deserialize( Int n, byte* buf, Entry<Complex<BigFloat>>* x )
{
DEBUG_CSE
for( Int k=0; k<n; ++k )
{
std::memcpy( &x[k].i, buf, sizeof(Int) );
buf += sizeof(Int);
std::memcpy( &x[k].j, buf, sizeof(Int) );
buf += sizeof(Int);
buf = x[k].value.Deserialize( buf );
}
return buf;
}
const byte* Deserialize( Int n, const byte* buf, BigInt* x )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
buf = x[j].Deserialize( buf );
return buf;
}
const byte* Deserialize( Int n, const byte* buf, BigFloat* x )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
buf = x[j].Deserialize( buf );
return buf;
}
const byte* Deserialize( Int n, const byte* buf, Complex<BigFloat>* x )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
buf = x[j].Deserialize( buf );
return buf;
}
const byte* Deserialize( Int n, const byte* buf, ValueInt<BigInt>* x )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
{
buf = x[j].value.Deserialize( buf );
std::memcpy( &x[j].index, buf, sizeof(Int) );
buf += sizeof(Int);
}
return buf;
}
const byte* Deserialize( Int n, const byte* buf, ValueInt<BigFloat>* x )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
{
buf = x[j].value.Deserialize( buf );
std::memcpy( &x[j].index, buf, sizeof(Int) );
buf += sizeof(Int);
}
return buf;
}
const byte* Deserialize
( Int n, const byte* buf, ValueInt<Complex<BigFloat>>* x )
{
DEBUG_CSE
for( Int j=0; j<n; ++j )
{
buf = x[j].value.Deserialize( buf );
std::memcpy( &x[j].index, buf, sizeof(Int) );
buf += sizeof(Int);
}
return buf;
}
const byte* Deserialize( Int n, const byte* buf, Entry<BigInt>* x )
{
DEBUG_CSE
for( Int k=0; k<n; ++k )
{
std::memcpy( &x[k].i, buf, sizeof(Int) );
buf += sizeof(Int);
std::memcpy( &x[k].j, buf, sizeof(Int) );
buf += sizeof(Int);
buf = x[k].value.Deserialize( buf );
}
return buf;
}
const byte* Deserialize( Int n, const byte* buf, Entry<BigFloat>* x )
{
DEBUG_CSE
for( Int k=0; k<n; ++k )
{
std::memcpy( &x[k].i, buf, sizeof(Int) );
buf += sizeof(Int);
std::memcpy( &x[k].j, buf, sizeof(Int) );
buf += sizeof(Int);
buf = x[k].value.Deserialize( buf );
}
return buf;
}
const byte* Deserialize( Int n, const byte* buf, Entry<Complex<BigFloat>>* x )
{
DEBUG_CSE
for( Int k=0; k<n; ++k )
{
std::memcpy( &x[k].i, buf, sizeof(Int) );
buf += sizeof(Int);
std::memcpy( &x[k].j, buf, sizeof(Int) );
buf += sizeof(Int);
buf = x[k].value.Deserialize( buf );
}
return buf;
}
void Deserialize( Int n, const std::vector<byte>& buf, BigInt* x )
{
Deserialize( n, buf.data(), x );
}
void Deserialize( Int n, const std::vector<byte>& buf, ValueInt<BigInt>* x )
{
Deserialize( n, buf.data(), x );
}
void Deserialize( Int n, const std::vector<byte>& buf, Entry<BigInt>* x )
{
Deserialize( n, buf.data(), x );
}
void Deserialize( Int n, const std::vector<byte>& buf, BigFloat* x )
{
Deserialize( n, buf.data(), x );
}
void Deserialize( Int n, const std::vector<byte>& buf, ValueInt<BigFloat>* x )
{
Deserialize( n, buf.data(), x );
}
void Deserialize( Int n, const std::vector<byte>& buf, Entry<BigFloat>* x )
{
Deserialize( n, buf.data(), x );
}
void Deserialize
( Int n, const std::vector<byte>& buf, Complex<BigFloat>* x )
{
Deserialize( n, buf.data(), x );
}
void Deserialize
( Int n, const std::vector<byte>& buf, ValueInt<Complex<BigFloat>>* x )
{
Deserialize( n, buf.data(), x );
}
void Deserialize
( Int n, const std::vector<byte>& buf, Entry<Complex<BigFloat>>* x )
{
Deserialize( n, buf.data(), x );
}
} // namespace El
#endif // ifdef EL_HAVE_MPC
|
#include "DeviceContext.h"
#include "SwapChain.h"
#include "VertexBuffer.h"
#include "VertexShader.h"
#include "PixelShader.h"
DeviceContext::DeviceContext(ID3D11DeviceContext* device_context):m_device_context(device_context)
{
}
void DeviceContext::clearRenderTargetColor(SwapChain* swap_chain, float red, float green, float blue, float alpha)
{
FLOAT clear_color[] = { red, green, blue, alpha };
m_device_context->ClearRenderTargetView(swap_chain->m_rtv, clear_color);
m_device_context->OMSetRenderTargets(1, &swap_chain->m_rtv, NULL);
}
void DeviceContext::setVertexBuffer(VertexBuffer* vertex_buffer)
{
UINT stride = vertex_buffer->m_size_vertex;
UINT offset = 0;
m_device_context->IASetVertexBuffers(0, 1, &vertex_buffer->m_buffer, &stride, &offset);
m_device_context->IASetInputLayout(vertex_buffer->m_layout);
}
void DeviceContext::drawTriangleList(UINT vertex_count, UINT start_vertex_index)
{
m_device_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
m_device_context->Draw(vertex_count, start_vertex_index);
}
void DeviceContext::drawTriangleStrip(UINT vertex_count, UINT start_vertex_index)
{
m_device_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
m_device_context->Draw(vertex_count, start_vertex_index);
}
void DeviceContext::setViewportSize(UINT width, UINT height)
{
D3D11_VIEWPORT vp = {};
vp.Width = (FLOAT)width;
vp.Height = (FLOAT)height;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
m_device_context->RSSetViewports(1, &vp);
}
void DeviceContext::setVertexShader(VertexShader* vertex_shader)
{
m_device_context->VSSetShader(vertex_shader->m_vs, nullptr, 0);
}
void DeviceContext::setPixelShader(PixelShader* pixel_shader)
{
m_device_context->PSSetShader(pixel_shader->m_ps, nullptr, 0);
}
bool DeviceContext::release()
{
m_device_context->Release();
delete this;
return true;
}
DeviceContext::~DeviceContext()
{
}
|
//данный тест проверяет наличие ошибки в функции hashtable::erase
#include <stl/hash_map>
int main ()
{
try
{
printf ("Results of hmap4_test:\n");
stl::hash_map<size_t, int> m;
m [1u] = 5;
m [2u] = 5;
m [3u] = 5;
m.erase (1u);
m.erase (2u);
m [1u] = 5;
printf ("before deleting map\n");
}
catch (std::exception& exception)
{
printf ("exception: %s\n", exception.what ());
}
printf ("map deleted successfully\n");
return 0;
}
|
#include <iostream>
// --------------------------------------------------------------------
int main()
{
return 0;
}
|
/*
* $Id$
*
* Author: David Fournier
* Copyright (c) 2008-2012 Regents of the University of California
*/
/**
* \file
* Description not yet available.
*/
#include <df1b2fun.h>
/**
* Description not yet available.
* \param
*/
df1b2variable t_deviate(const df1b2variable& _x,const df1b2variable& _a)
{
df1b2variable& x= (df1b2variable&)(_x);
df1b2variable& a= (df1b2variable&)(_a);
df1b2variable y=cumd_norm(x);
y=.9999*y+.00005;
df1b2variable z=inv_cumd_t(y,a);
return z;
}
|
// Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/string.hpp>
#include <fcppt/text.hpp>
#include <fcppt/enum/array_init.hpp>
#include <fcppt/io/cerr.hpp>
#include <fcppt/io/cout.hpp>
#include <fcppt/log/context.hpp>
#include <fcppt/log/debug.hpp>
#include <fcppt/log/error.hpp>
#include <fcppt/log/level.hpp>
#include <fcppt/log/level_stream.hpp>
#include <fcppt/log/level_stream_array.hpp>
#include <fcppt/log/name.hpp>
#include <fcppt/log/object.hpp>
#include <fcppt/log/optional_level.hpp>
#include <fcppt/log/out.hpp>
#include <fcppt/log/parameters.hpp>
#include <fcppt/log/format/default_level.hpp>
#include <fcppt/log/format/function.hpp>
#include <fcppt/log/format/optional_function.hpp>
namespace
{
//! [logger_formatter_declaration]
fcppt::string
log_formatter(
fcppt::string const &_text
)
{
return
FCPPT_TEXT("This is a formatting test: ")
+
_text;
}
//! [logger_formatter_declaration]
//! [error_formatter_declaration]
// Create a formatter for the error log level. Note that we have to append a
// newline here, because this is normally done by the default formatters for
// each log level.
fcppt::string
error_formatter(
fcppt::string const &_text
)
{
return
FCPPT_TEXT("Horrible error, please fix: ")
+
_text
+
FCPPT_TEXT('\n');
}
//! [error_formatter_declaration]
}
int
main()
{
//! [logger_streams]
fcppt::log::level_stream_array const level_streams(
fcppt::enum_::array_init<
fcppt::log::level_stream_array
>(
[](
fcppt::log::level const _level
)
{
// Create a special sink for the error log level that prints to
// cerr and also has a special formatter.
return
_level
==
fcppt::log::level::error
?
fcppt::log::level_stream(
fcppt::io::cerr(),
fcppt::log::format::optional_function{
fcppt::log::format::function{
error_formatter
}
}
)
:
fcppt::log::level_stream(
fcppt::io::cout(),
fcppt::log::format::optional_function(
fcppt::log::format::default_level(
_level
)
)
)
;
}
)
);
//! [logger_streams]
//! [logger_context]
fcppt::log::context context{
fcppt::log::optional_level{
fcppt::log::level::debug
},
level_streams
};
//! [logger_context]
//! [logger_declaration]
fcppt::log::object log{
context,
fcppt::log::parameters{
fcppt::log::name{
FCPPT_TEXT("fcppt")
},
// Create a special formatter for the whole log
fcppt::log::format::optional_function{
fcppt::log::format::function{
log_formatter
}
}
}
};
//! [logger_declaration]
//! [log_print]
// Prints:
// 'This is a formatting test: fcppt: debug: test'
// to cout.
FCPPT_LOG_DEBUG(
log,
fcppt::log::out
<< FCPPT_TEXT("test")
)
// Prints:
// 'This is a formatting test: fcppt: Horrible error, please fix: some error'
// to cerr.
FCPPT_LOG_ERROR(
log,
fcppt::log::out
<< FCPPT_TEXT("some error")
)
//! [log_print]
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pow.h"
#include "arith_uint256.h"
#include "chain.h"
#include "chainparams.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
#include <math.h>
unsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const Consensus::Params& params) {
const CBlockIndex *BlockLastSolved = pindexLast;
const CBlockIndex *BlockReading = pindexLast;
uint64_t PastBlocksMass = 0;
int64_t PastRateActualSeconds = 0;
int64_t PastRateTargetSeconds = 0;
double PastRateAdjustmentRatio = double(1);
arith_uint256 PastDifficultyAverage;
arith_uint256 PastDifficultyAveragePrev;
double EventHorizonDeviation;
double EventHorizonDeviationFast;
double EventHorizonDeviationSlow;
uint64_t pastSecondsMin = params.nPowTargetTimespan * 0.025;
uint64_t pastSecondsMax = params.nPowTargetTimespan * 7;
uint64_t PastBlocksMin = pastSecondsMin / params.nPowTargetSpacing;
uint64_t PastBlocksMax = pastSecondsMax / params.nPowTargetSpacing;
if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); }
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
PastBlocksMass++;
PastDifficultyAverage.SetCompact(BlockReading->nBits);
if (i > 1) {
// handle negative arith_uint256
if(PastDifficultyAverage >= PastDifficultyAveragePrev)
PastDifficultyAverage = ((PastDifficultyAverage - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev;
else
PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - PastDifficultyAverage) / i);
}
PastDifficultyAveragePrev = PastDifficultyAverage;
PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime();
PastRateTargetSeconds = params.nPowTargetSpacing * PastBlocksMass;
PastRateAdjustmentRatio = double(1);
if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; }
if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds);
}
EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(28.2)), -1.228));
EventHorizonDeviationFast = EventHorizonDeviation;
EventHorizonDeviationSlow = 1 / EventHorizonDeviation;
if (PastBlocksMass >= PastBlocksMin) {
if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast))
{ assert(BlockReading); break; }
}
if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
BlockReading = BlockReading->pprev;
}
arith_uint256 bnNew(PastDifficultyAverage);
if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
bnNew *= PastRateActualSeconds;
bnNew /= PastRateTargetSeconds;
}
if (bnNew > UintToArith256(params.powLimit)) {
bnNew = UintToArith256(params.powLimit);
}
return bnNew.GetCompact();
}
unsigned int static DarkGravityWave(const CBlockIndex* pindexLast, const Consensus::Params& params) {
/* current difficulty formula, combode - DarkGravity v3, written by Evan Duffield - evan@dash.org */
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
int64_t nPastBlocks = 24;
// make sure we have at least (nPastBlocks + 1) blocks, otherwise just return powLimit
if (!pindexLast || pindexLast->nHeight < nPastBlocks) {
return bnPowLimit.GetCompact();
}
const CBlockIndex *pindex = pindexLast;
arith_uint256 bnPastTargetAvg;
for (unsigned int nCountBlocks = 1; nCountBlocks <= nPastBlocks; nCountBlocks++) {
arith_uint256 bnTarget = arith_uint256().SetCompact(pindex->nBits);
if (nCountBlocks == 1) {
bnPastTargetAvg = bnTarget;
} else {
// NOTE: that's not an average really...
bnPastTargetAvg = (bnPastTargetAvg * nCountBlocks + bnTarget) / (nCountBlocks + 1);
}
if(nCountBlocks != nPastBlocks) {
assert(pindex->pprev); // should never fail
pindex = pindex->pprev;
}
}
arith_uint256 bnNew(bnPastTargetAvg);
int64_t nActualTimespan = pindexLast->GetBlockTime() - pindex->GetBlockTime();
// NOTE: is this accurate? nActualTimespan counts it for (nPastBlocks - 1) blocks only...
int64_t nTargetTimespan = nPastBlocks * params.nPowTargetSpacing;
if (nActualTimespan < nTargetTimespan/3)
nActualTimespan = nTargetTimespan/3;
if (nActualTimespan > nTargetTimespan*3)
nActualTimespan = nTargetTimespan*3;
// Retarget
bnNew *= nActualTimespan;
bnNew /= nTargetTimespan;
if (bnNew > bnPowLimit) {
bnNew = bnPowLimit;
}
return bnNew.GetCompact();
}
unsigned int GetNextWorkRequiredBTC(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per interval
if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)
{
if (params.fPowAllowMinDifficultyBlocks)
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 2.5 minutes
// then allow mining of a min-difficulty block.
if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Go back by what we want to be 1 day worth of blocks
int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval()-1);
assert(nHeightFirst >= 0);
const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);
assert(pindexFirst);
return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
// Most recent algo first
if (pindexLast->nHeight + 1 >= params.nPowDGWHeight) {
return DarkGravityWave(pindexLast, params);
}
else if (pindexLast->nHeight + 1 >= params.nPowKGWHeight) {
return KimotoGravityWell(pindexLast, params);
}
else {
return GetNextWorkRequiredBTC(pindexLast, pblock, params);
}
}
// for DIFF_BTC only!
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
if (params.fPowNoRetargeting)
return pindexLast->nBits;
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
LogPrintf(" nActualTimespan = %d before bounds\n", nActualTimespan);
if (nActualTimespan < params.nPowTargetTimespan/4)
nActualTimespan = params.nPowTargetTimespan/4;
if (nActualTimespan > params.nPowTargetTimespan*4)
nActualTimespan = params.nPowTargetTimespan*4;
// Retarget
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
arith_uint256 bnNew;
arith_uint256 bnOld;
bnNew.SetCompact(pindexLast->nBits);
bnOld = bnNew;
bnNew *= nActualTimespan;
bnNew /= params.nPowTargetTimespan;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
/// debug print
LogPrintf("GetNextWorkRequired RETARGET\n");
LogPrintf("params.nPowTargetTimespan = %d nActualTimespan = %d\n", params.nPowTargetTimespan, nActualTimespan);
LogPrintf("Before: %08x %s\n", pindexLast->nBits, bnOld.ToString());
LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString());
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
bool fNegative;
bool fOverflow;
arith_uint256 bnTarget;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
return error("CheckProofOfWork(): nBits below minimum work");
// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)
return error("CheckProofOfWork(): hash doesn't match nBits");
return true;
}
arith_uint256 GetBlockProof(const CBlockIndex& block)
{
arith_uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for a arith_uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}
int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
arith_uint256 r;
int sign = 1;
if (to.nChainWork > from.nChainWork) {
r = to.nChainWork - from.nChainWork;
} else {
r = from.nChainWork - to.nChainWork;
sign = -1;
}
r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
if (r.bits() > 63) {
return sign * std::numeric_limits<int64_t>::max();
}
return sign * r.GetLow64();
}
|
// license:BSD-3-Clause
// copyright-holders:Aaron Giles
/***************************************************************************
Sega System 32/Multi 32 hardware
****************************************************************************
Still to do:
* fix protection
* fix jpark correctly
* priorities in multi32 appear wrong - stadium cross map screen
and title fight ingame backgrounds
* should f1lap be set up as a twin cabinet / direct link or can it
be operated as a single screen, unlike f1en/air rescue
****************************************************************************
Slip Stream (Hispanic 950515)
Sega, 1995
This game runs on Sega System 32 hardware.
PCB Layout
----------
837-7428 171-5964E (C) SEGA 1990
|-------------------------------------------------------------------------------------------|
| TDA1518 8464 8464 |
| HM65256 8464 8464 |
| TL064 HM65256 |---------| |---------| |
| LC7881 |-----| |SEGA | |SEGA | |
| |ASSP | |315-5385 | |315-5388 | |
|CND |5C105| | | | | |
| |1FD07| | | |---------| | | |
| |-----| |---------| CNF |SEGA | |---------| |
| |315-5242 | |
|-| TL062 TL064 84256 | | |
| 84256 | | CNI|
|-| |---------| |---------| |
| YM3438 |SEGA | |
| |-----------| |315-5387 | |
| YM3438 |NEC | 315-5441 | | |
| |D70616R-16 | | | |
|J BAT_5.5V |9105M9 V60 | |---------| |
|A BAT_3.3V |(C)NEC 1986| |
|M | | D42264 |
|M 8464 |-----------| D42264 |
|A D42264 |
| Z80 D42264 |
| HM53461ZP-12 HM53461ZP-12 |
| HM53461ZP-12 HM53461ZP-12 |
| HM53461ZP-12 HM53461ZP-12 |
| HM53461ZP-12 HM53461ZP-12 |-----------| |
|-| HM53461ZP-12 HM53461ZP-12 | SEGA | CNE|
| |-------| HM53461ZP-12 HM53461ZP-12 | 315-5386A | |
|-| |SEGA | HM53461ZP-12 HM53461ZP-12 | | |
| |315- | HM53461ZP-12 HM53461ZP-12 | | |
| |5296 | | | |
| |-------| 3771 3771 |-----------| |
| 93C46 D42264 |
|CNB SW2 D42264 |
| SW1 D42264 |
| CNA DSW1 32MHz 50MHz D42264 |
|-------------------------------------------------------------------------------------------|
Notes:
V60 CPU running at 16.00MHz [32/2]
Z80 CPU running at 8.000MHz [32/4]
YM3438 running at 8.000MHz [32/4]
CNE/F/I - Multi-pin connectors for connection of ROM Board
CND - 4 pin connector for 2nd Speaker for Stereo Output
CNA - 30 pin connector for extra controls PCB
CNB - 26 pin connector (purpose unknown)
SW1 - push-button TEST switch
SW2 - push button SERVICE switch
DSW1 - 4-position DIP Switch
HM53461 - Hitachi 256k Dual Port RAM
D42264 - NEC 256k Dual Port RAM
SEGA Custom ICs:
315-5441 Lattice GAL16V8A (DIP20)
315-5386A (QFP184)
315-5388 (QFP160)
315-5387 (QFP160)
315-5242 (custom ceramic DIP32 containing a small QFP IC and some capacitors/resistors etc)
315-5296 (QFP100)
ASSP 5C105 (QFP80)
315-5385 (QFP128)
ROM Board
---------
837-7429-01
|-------------------------------------------------------------------------------------------|
|JP10-JP27 CNJ CNH JP1-JP9 |
| IC6 |
| IC7 |
| IC13 |
| IC14 |
| 315-5442 |
| IC22 IC25 IC24 IC23 |
| |
| IC26 IC29 IC28 IC27 |
| |
| IC31 CNK IC34 IC23 IC32 |
| |
| IC35 IC38 IC37 IC36 |
| CNG JP28-JP32 |
|-------------------------------------------------------------------------------------------|
Notes:
CNG/H/J - Multi-pin connectors (below PCB) for connection of ROM Board to Main Board
CNK - Custom Sega connector for connection of protection daughterboard (not used)
315-5442 - MMI PAL16L8ACN (DIP20)
Jumpers: (to configure ROM sizes used on Slip Stream. Other games)
(may vary depending on ROM types used)
JP1: 2-3 JP17: 1-2
JP2: 2-3 JP18: 2-3
JP3: 2-3 JP19: 1-2
JP4: 1-2 JP20: 2-3
JP5: 2-3 JP21: 1-2
JP6: 2-3 JP22: 2-3
JP7: 1-2 JP23: 1-2
JP8: 2-3 JP24: 1-2
JP9: 1-2 JP25: 2-3
JP10: 2-3 JP26: 1-2
JP11: 1-2 JP27: 1-2
JP12: 1-2 JP28: 2-3
JP13: 1-2 JP29: 1-2
JP14: 2-3 JP30: 2-3
JP15: 2-3 JP31: 1-2
JP16: 2-3 JP32: 1-2
ROM Locations
-------------
PCB Label CPU P0 CPU P1 CPU D0 CPU D1 SND0 SND1 SND2 SND3 SCR0 SCR1 SCR2 SCR3 OBJ0 OBJ1 OBJ2 OBJ3 OBJ4 OBJ5 OBJ6 OBJ7
IC# IC13 IC6 IC7 IC14 IC35 IC31 - - IC38 IC34 IC29 IC25 IC36 IC32 IC27 IC23 IC37 IC33 IC28 IC24
IC Type - 27C4002 27C4000 27C4000 27C010 27C4000 - - 27C4000 27C4000 27C4000 27C4000 27C4000 27C4000 27C4000 27C4000 27C4000 27C4000 27C4000 27C4000
ROM Label - S32HPRG01 S32DAT00 S32DAT01 S32SND00 S32SND01 - - S32SCR00 S32SCR01 S32SCR02 S32SCR03 S32OBJ00 S32OBJ01 S32OBJ02 S32OBJ03 S32OBJ04 S32OBJ05 S32OBJ06 S32OBJ07
Extra Controls PCB
------------------
837-7536
837-7536-91 (sticker)
|------------------------|
| |
| 74HC74 |
| OKI_M6253 |
| 74HC4053 |
| DAP601 74HC139|
| DAN601 |
|CN2 CN1 |
|------------------------|
Notes:
CN2 - Multi-pin connector for controls
CN1 - Connector joining to CNA on main PCB
*********************************************************************************************
Title Fight (Export Revision)
Sega, 1992
This game runs on Sega System Multi32 hardware.
PCB Layout
----------
837-8676 171-6253C (C) SEGA 1992
834-9324-02 (STICKER)
|-------------------------------------------------------------------------------------------|
| CNF CNH 8464 |
|8464 HM53461ZP-12 (x16) |-----------| HM53461ZP-12 (x16) 8464 |
|8464 | SEGA | 8464 |
|8464 | 315-5386A | 8464 |
|8464 | | |
| | | |
| | | |
| |---------| |---------| |-----------| |---------| |---------| |
| |SEGA | |SEGA | |SEGA | |SEGA | |
| |315-5388 | |315-5387 | HM53461ZP-12 (x8) |315-5388 | |315-5242 | |
| | | | | | | | | |
| | | | | | | | | |
| |---------| |---------| |---------| |---------| |
| CND CNE |
| |---------| MB3771 MB3771 315-5596 |-------| M5M5278P-25|
| |SEGA | |SEGA | |
| |315-5242 | 8464 |315- | M5M5278P-25|
| | |BAT_3.3V |5591 | |
| | |BAT_5.5V |---------| |-------| M5M5278P-25|
| |---------| Z80 50MHz |SEGA | |-----------| DSW1|
| 32MHz |315-5385 | |NEC | M5M5278P-25|
| |------| | | |D70632R-20 | SW4 |
| |SEGA | |-------| | | |9314X9 V70 | 40MHz SW3 |
| |315- | |SEGA | |---------| |(C)NEC 1986| |
| |5560 | YM3438 |315- | | | |
| |------| LC78820 |5296 | |-----------| 93C45 |
|TDA1518 |-------| |-------| |
| SW1 SW2 |SEGA | CNM|
| VOL |315- | |
| |5296 | |
| UPC844 UPC4064 |-------| |
| |
|CNC LED |
--| JAMMA |----| CNJ |----| JAMMA |--|
|------------------------------| |--------------| |------------------------------|
Notes:
V70 CPU running at 20.00MHz [40/2]
Z80 CPU running at 8.000MHz [32/4]
YM3438 running at 8.000MHz [32/4]
315-5560 running at 8.000MHz [32/4]
CND/E/F/H: Multi-pin connectors for connection of ROM Board
CNC : 4 pin connector for 2nd Speaker for Stereo Output
CNJ : 32 pin connector (purpose unknown)
CNM : 30 pin connector (purpose unknown)
SW1 : push-button TEST switch
SW2 : push button SERVICE switch
SW3/4 : push button switches (purpose unknown)
DSW1 : 4-position DIP Switch
SEGA Custom ICs:
315-5596 Lattice GAL16V8A (DIP20)
315-5386A (QFP184)
315-5388 (x2, QFP160)
315-5387 (QFP160)
315-5242 (x2, custom ceramic DIP32 containing a small QFP IC and some capacitors/resistors etc)
315-5296 (x2, QFP100)
315-5560 (QFP80)
315-5385 (QFP128)
315-5591 (QFP100)
ROM Board
---------
837-8890
|-------------------------------------------------------------------------------------------|
| CN3 CN4 |
| |
| IC3 IC14 IC15 IC10 |
| IC1 IC2 JP1-5 |
| |
| IC11 JP6-10 IC22 IC23 IC18 |
| |
| |
| IC36 IC37 |
| 315-5598 IC38 |
| CN5 |
| IC30 IC31 IC39 IC40 |
| CN6 IC41 |
|JP11-16 CN1 CN2 |
|-------------------------------------------------------------------------------------------|
Notes:
CN1/2/3/4 : Multi-pin connectors (below PCB) for connection of ROM Board to Main Board
CN5 : Custom Sega connector for connection of protection daughterboard (not used)
CN6 : Custom Sega connector (purpose unknown)
315-5598 : Lattice GAL16V8A (DIP20)
Jumpers: (to configure ROM sizes used on Title Fight. Other games may vary depending on ROM types used.)
JP1: 1-2
JP2: 1-2
JP3: 2-3
JP4: 2-3
JP5: 2-3
JP6: 1-2
JP7: 2-3
JP8: 2-3
JP9: 1-2
JP10: 1-2
JP11: OPEN
JP12: OPEN
JP13: OPEN
JP14: OPEN
JP15: 1-2
JP16: 2-3
ROM Locations (All known System Multi32 games shown for reference)
-------------
PCB Label CPU P0 CPU P1 CPU D0 CPU D1 SOUND SCR0 SCR1 OBJ0 OBJ1 OBJ2 OBJ3 OBJ4 OBJ5 OBJ6 OBJ7 PCM D0 PCM D1 PCM EP/S
IC# IC37 IC40 IC36 IC39 IC31 IC3 IC11 IC14 IC22 IC15 IC23 IC10 IC18 IC38 IC41 IC1 IC2 IC30
IC Type 27C2048 27C2048 - - 27C1000 8316200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 - -
Title Fight EPR15388 EPR15389 - - EPR15384 MPR15381 MPR15382 MPR15379 MPR15380 MPR15375 MPR15376 MPR15371 MPR15372 MPR15373 MPR15374 MPR15385 - -
IC Type 27C1024 27C1024 27C4200 27C4200 27C040 8316200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 -
OutRunners EPR15618 EPR15619 EPR15538 EPR15539 EPR15550 MPR15548 MPR15549 MPR15540 MPR15541 MPR15542 MPR15543 MPR15544 MPR15545 MPR15546 MPR15547 MPR15551 MPR15552 -
IC Type 27C2048 27C2048 - - 27C1000 534200 534200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 8316200 -
Hard Dunk EPR16512 EPR16509 - - EPR16505 MPR16503 MPR16504 MPR16495 MPR16496 MPR16497 MPR16498 MPR16499 MPR16500 MPR16501 MPR16502 MPR16506 MPR16507 -
Hard Dunk (J) EPR16508 EPR16509 - - EPR16505 MPR16503 MPR16504 MPR16495 MPR16496 MPR16497 MPR16498 MPR16499 MPR16500 MPR16501 MPR16502 MPR16506 MPR16507 -
IC Type 27C2048 27C2048 27C4200 27C4200 27C1000 27C160 27C160 27C160 27C160 27C160 27C160 27C160 27C160 27C160 27C160 27C160 27C160 -
Stadium Cross EPR15093 EPR15094 EPR15018 EPR15019 EPR15192 EPR15020 EPR15021 EPR15022 EPR15023 EPR15024 EPR15025 EPR15026 EPR15027 EPR15028 EPR15029 EPR15031 EPR15032 -
System 32 Multi COMM board
--------------------------
SEGA 1992 837-8792
sticker: 837-9016-03
|--------------------------------------------------------|
| CN3 CN4 |
| |
| 32MHz JP1(1-2) |
| Z80 MB89374 MB89237A MB8421 |
| |
| JP2(1-2) |
| EPR-15033.IC17 |
| JP3(2-3) |
| JP4(1-2) |
| 8464 GAL16V8 GAL16V8 |
| (315-5610) (315-5506) |
| CN1 CN2 |
| CN8 CN9 |
|--------------------------------------------------------|
EPR-15033 - AM27C100 EPROM found on Stadium Cross
MB89374 - Fujitsu MB89374 Data Link Controller. Clock input 8MHz [32/4]
MB89237A - Fujitsu MB89237A DMA Controller
8464 - Fujitsu MB8464 8k x8 SRAM
CN8 - TX connector
CN9 - RX connector
CN1-4 - Joins to Main Board. Connections on top allow plugging in the ROM PCB
*********************************************************************************************
Alien 3 The Gun
The PCB number is 837-7428-03 171-5964-02B
The board matches the documented one for Slipstream in all aspects except
the Sega PCM sound chip is numbered 315-5476A (on Slipstream it's ASSP 5C105)
The EEPROM is a 93C45 at location IC76
The ROM PCB number is 'SYSTEM32 837-8393-01 16M ROM BD'
and the sticker number is '837-9878-02'
The PAL on the ROM board is a GAL16V8 at IC23 and marked '315-5552'
The correct ROM names are....
EPR-15943.IC17 - Main Program
EPR-15942.IC8 |
MPR-15855.IC18 |
MPR-15854.IC9 /
EPR-15859.IC36 - Sound Program
MPR-15858.IC35 - Sound Data
MPR-15857.IC34 |
MPR-15856.IC24 /
MPR-15863.IC14 - Tiles
MPR-15862.IC5 /
MPR-15864.IC32 - Sprites
MPR-15866.IC30 |
MPR-15868.IC28 |
MPR-15870.IC26 |
MPR-15865.IC31 |
MPR-15867.IC29 |
MPR-15869.IC27 |
MPR-15871.IC25 /
93C45_EEPROM.IC76
Alien 3 The Gun Jumpers:
JP1: 2-3
JP2: 2-3
JP3: 1-2
JP4: 1-2
JP5: 1-2
JP6: 1-2
JP7: 1-2
JP8: 1-2
JP9: 2-3
JP10: 2-3
JP11: 2-3
JP12: 1-2
JP13: 2-3
JP14: 1-2
JP15: 2-3
JP16: 1-2
JP17: 2-3
JP18: 1-2
JP19: 1-2
JP20: 2-3
JP21: 1-2
JP22: 2-3
JP23: 2-3
JP24: 1-2
The main board uses the standard I/O board 837-7536 for the gun controls.
*********************************************************************************************
Dark Edge
The PCB number is 171-5964-02B-K (i.e. manufactured in Korea)
The board matches the documented one for Slipstream in all aspects except
the Sega PCM sound chip is numbered 315-5476A (on Slipstream it's ASSP 5C105)
The EEPROM is a 93C45 at location IC76
The ROM PCB number is 'SYSTEM32 837-8393 16M ROM BD'
No game sticker is present.
The PAL on the ROM board is a GAL16V8 at IC23 and marked '315-5552'
The only difference between this board and Alien 3 The Gun is the sockets at
IC9, IC17 & IC18 are not populated. And of course there's a FD1149 security
module 317-0204.
Note the battery is easily accessible from underneath the module. The module is not
sealed and the lower cover snaps off easily.
The battery can not be changed but it is easy to solder wires to the plus/minus terminals
and then wire in a new 3V coin battery and the module will keep going for a few more years.
If the battery needs updating again do not remove any of the existing batteries otherwise
the PCB will die instantly. Just solder in a new battery to the same wires.
Always solder the battery plus to plus and minus to minus. If it's wired in plus to minus
the voltage will double to 6V.
If you have a System 32 board with an FD1149 add another new battery now!
ROM Types:
Main program ROM at IC8 is 27C240
Sound Program at IC36 is 27C100
Sound Data at IC35,34,24 are 838000
Tiles are 834200
Sprites are 8316200
Dark Edge Jumpers:
JP1: 2-3
JP2: 2-3
JP3: 1-2
JP4: 1-2
JP5: 2-3
JP6: 2-3
JP7: 1-2
JP8: 1-2
JP9: 1-2
JP10: 1-2
JP11: 2-3
JP12: 1-2
JP13: 2-3
JP14: 1-2
JP15: 2-3
JP16: 1-2
JP17: 1-2
JP18: 2-3
JP19: 1-2
JP20: 2-3
JP21: 1-2
JP22: 2-3
JP23: 2-3
JP24: 2-3
Extra Controls PCB
------------------
837-7968
|------------------------|
|CN2 PC817(x5) |
| |
| CN3 MB89255B|
| |
| 74F139|
|CN4 A1603C JP1234|
|CN5 CN1 |
|------------------------|
Notes:
CN3 - Multi-pin connector for extra controls (most likely for buttons only)
CN2/4/5 - Purpose unknown (not used on Dark Edge)
CN1 - Connector joining to CNA on main PCB
MB89255B - Fujitsu MB89255B Parallel Data I/O Interface (8-bit data bus & 3x 8-bit parallel I/O ports)
This chip is very small and is a SSOP40 package. The chip is functionally compatible with Intel 8255A.
(The equivalent TMP82C55AM-10 sometimes replaces this on other games using the 837-7968 board.)
A1603C - NEC uPA1603C Quad Monolithic N-Channel Power MOS FET Array
JP1234 - Four 2-pin jumpers. JP3 is shorted, the others are not shorted
JP1/2/3/4 are tied to the 74F139 pins 4,5,6,7 respectively. The 74F139 is tied to CN1 and the MB89255B
Pin 1 of the jumpers is common to all and is tied to pin 6 of the MB89255B (Chip Select)
*********************************************************************************************
On "Super Visual Football: European Sega Cup" and "JLEAGUE" :
JLEAGUE was the original code developed and released in early
1994 in Japan which than got translated and updated to be
released as the European Sega Cup.
So, JLEAGUE is the Original.
and
"Super Visual Football: European Sega Cup" is the clone.
My source of information?
I wrote the simulation ( in assembly ) while working in the SEGA
Haneda ( Tokyo ) office in 1993. We even filed a patent on the
team/individual player task synchronization. After I finished JLEAGE,
we handed it off to the satellite groups for localization.
Cheers,
MIB.42
***************************************************************************
Output Notes:
All outputs are hooked up properly with the following exceptions:
radm: Motors aren't hooked up, as the board isn't emulated. Also the 2nd and 3rd lamps "die" when the cabinet dip is set to deluxe.
They probably get moved over to the motor driver board.
radr: See radm
kokoroj: This driver isn't finished enough to flesh out the outputs, but a space has been reserved in the output functions.
jpark: Since the piston driver board isn't fully emulated, they aren't hooked up. offset 0c of the common chip function seems to have something to do with it.
orunners: Interleaved with the dj and << >> buttons is the data the drives the lcd display.
****************************************************************************/
#include "emu.h"
#include "includes/segas32.h"
#include "bus/scsi/scsi.h"
#include "bus/scsi/scsicd.h"
#include "cpu/z80/z80.h"
#include "cpu/v60/v60.h"
#include "cpu/nec/v25.h"
#include "cpu/upd7725/upd7725.h"
#include "machine/cxd1095.h"
#include "machine/eepromser.h"
#include "machine/i8255.h"
#include "machine/mb8421.h"
#include "machine/mb89352.h"
#include "machine/msm6253.h"
#include "machine/upd4701.h"
#include "machine/315_5296.h"
#include "sound/rf5c68.h"
#include "sound/ymopn.h"
#include "speaker.h"
#include "layout/generic.h"
#include "radr.lh"
/*
* TODO: Kokoroji hangs if CD comms are handled with current mb89352 core.
* We currently hide this behind a compile switch to aid development
*/
#define S32_KOKOROJI_TEST_CD 0
DEFINE_DEVICE_TYPE(SEGA_S32_PCB, segas32_state, "segas32_pcb", "Sega System 32 PCB")
segas32_state::segas32_state(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: segas32_state(mconfig, SEGA_S32_PCB, tag, owner, clock, false)
{
}
segas32_state::segas32_state(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock, bool is_multi32)
: device_t(mconfig, type, tag, owner, clock)
, m_z80_shared_ram(*this,"z80_shared_ram")
, m_system32_workram(*this,"workram")
, m_videoram(*this,"videoram", 0x20000, ENDIANNESS_LITTLE)
, m_spriteram(*this,"spriteram", 0x20000, ENDIANNESS_LITTLE)
, m_soundram(*this, "soundram")
, m_paletteram(*this,"paletteram.%u", 0U, 0x10000U, ENDIANNESS_LITTLE)
, m_maincpu(*this, "maincpu")
, m_soundcpu(*this, "soundcpu")
, m_multipcm(*this, "sega")
, m_gfxdecode(*this, "gfxdecode")
, m_screen(*this, "screen")
, m_palette(*this, "palette")
, m_irq_timer_0(*this, "v60_irq0")
, m_irq_timer_1(*this, "v60_irq1")
, m_s32comm(*this, "s32comm")
, m_sprite_region(*this, "sprites")
, m_maincpu_region(*this, "maincpu")
, m_soundrom_bank(*this, "soundbank")
, m_multipcm_bank_hi(*this, "multipcmbankhi")
, m_multipcm_bank_lo(*this, "multipcmbanklo")
, m_is_multi32(is_multi32)
, m_sound_irq_input(0)
, m_sound_dummy_value(0)
, m_sound_bank(0)
, m_system32_tilebank_external(0)
, m_sprite_render_count(0)
, m_print_count(0)
, m_vblank_end_int_timer(nullptr)
, m_update_sprites_timer(nullptr)
{
std::fill(std::begin(m_v60_irq_control), std::end(m_v60_irq_control), 0);
std::fill(std::begin(m_v60_irq_timer), std::end(m_v60_irq_timer), nullptr);
std::fill(std::begin(m_sound_irq_control), std::end(m_sound_irq_control), 0);
std::fill(std::begin(m_system32_displayenable), std::end(m_system32_displayenable), 0);
std::fill(std::begin(m_arescue_dsp_io), std::end(m_arescue_dsp_io), 0);
std::fill(std::begin(m_sprite_control_latched), std::end(m_sprite_control_latched), 0);
std::fill(std::begin(m_sprite_control), std::end(m_sprite_control), 0);
for (int i = 0; i < 2; i++)
std::fill(std::begin(m_mixer_control[i]), std::end(m_mixer_control[i]), 0);
}
/*************************************
*
* Constants
*
*************************************/
#define MASTER_CLOCK 32215900
#define RFC_CLOCK XTAL(50'000'000)
#define MULTI32_CLOCK XTAL(40'000'000)
#define TIMER_0_CLOCK ((MASTER_CLOCK/2)/2048) /* confirmed */
#define TIMER_1_CLOCK ((RFC_CLOCK/16)/256) /* confirmed */
#define MAIN_IRQ_VBSTART 0
#define MAIN_IRQ_VBSTOP 1
#define MAIN_IRQ_SOUND 2
#define MAIN_IRQ_TIMER0 3
#define MAIN_IRQ_TIMER1 4
#define SOUND_IRQ_YM3438 0
#define SOUND_IRQ_V60 1
/*************************************
*
* Machine init
*
*************************************/
void segas32_v25_state::device_start()
{
segas32_4player_state::device_start();
decrypt_protrom();
}
void segas32_cd_state::device_start()
{
segas32_state::device_start();
m_lamps.resolve();
}
void sega_multi32_analog_state::device_start()
{
sega_multi32_state::device_start();
m_analog_bank = 0;
save_item(NAME(m_analog_bank));
}
void segas32_state::device_reset()
{
/* initialize the interrupt controller */
memset(m_v60_irq_control, 0xff, sizeof(m_v60_irq_control));
/* allocate timers */
m_v60_irq_timer[0] = m_irq_timer_0;
m_v60_irq_timer[1] = m_irq_timer_1;
/* clear IRQ lines */
m_maincpu->set_input_line(0, CLEAR_LINE);
}
/*************************************
*
* Interrupt controller
*
*************************************/
void segas32_state::update_irq_state()
{
uint8_t effirq = m_v60_irq_control[7] & ~m_v60_irq_control[6] & 0x1f;
int vector;
/* loop over interrupt vectors, finding the highest priority one with */
/* an unmasked interrupt pending */
for (vector = 0; vector < 5; vector++)
if (effirq & (1 << vector))
{
m_maincpu->set_input_line_and_vector(0, ASSERT_LINE, vector); // V60
break;
}
/* if we didn't find any, clear the interrupt line */
if (vector == 5)
m_maincpu->set_input_line(0, CLEAR_LINE);
}
void segas32_state::signal_v60_irq(int which)
{
int i;
/* see if this interrupt input is mapped to any vectors; if so, mark them */
for (i = 0; i < 5; i++)
if (m_v60_irq_control[i] == which)
m_v60_irq_control[7] |= 1 << i;
update_irq_state();
}
TIMER_DEVICE_CALLBACK_MEMBER(segas32_state::signal_v60_irq_callback)
{
signal_v60_irq(param);
}
uint8_t segas32_state::int_control_r(offs_t offset)
{
switch (offset)
{
case 8:
/* fix me - should return timer count down value */
break;
case 10:
/* fix me - should return timer count down value */
break;
}
/* return all F's for everything except timer values */
return 0xff;
}
void segas32_state::int_control_w(offs_t offset, uint8_t data)
{
int duration;
// logerror("%06X:int_control_w(%X) = %02X\n", m_maincpu->pc(), offset, data);
switch (offset)
{
case 0:
case 1:
case 2:
case 3:
case 4: /* vectors */
m_v60_irq_control[offset] = data;
break;
case 5: /* unknown */
m_v60_irq_control[offset] = data;
break;
case 6: /* mask */
m_v60_irq_control[offset] = data;
update_irq_state();
break;
case 7: /* acknowledge */
m_v60_irq_control[offset] &= data;
update_irq_state();
break;
case 8:
case 9: /* timer 0 count */
m_v60_irq_control[offset] = data;
duration = m_v60_irq_control[8] + ((m_v60_irq_control[9] << 8) & 0xf00);
if (duration)
{
attotime period = attotime::from_hz(TIMER_0_CLOCK) * duration;
m_v60_irq_timer[0]->adjust(period, MAIN_IRQ_TIMER0);
}
break;
case 10:
case 11: /* timer 1 count */
m_v60_irq_control[offset] = data;
duration = m_v60_irq_control[10] + ((m_v60_irq_control[11] << 8) & 0xf00);
if (duration)
{
attotime period = attotime::from_hz(TIMER_1_CLOCK) * duration;
m_v60_irq_timer[1]->adjust(period, MAIN_IRQ_TIMER1);
}
break;
case 12:
case 13:
case 14:
case 15: /* signal IRQ to sound CPU */
signal_sound_irq(SOUND_IRQ_V60);
break;
}
}
TIMER_CALLBACK_MEMBER(segas32_state::end_of_vblank_int)
{
signal_v60_irq(MAIN_IRQ_VBSTOP);
system32_set_vblank(0);
}
INTERRUPT_GEN_MEMBER(segas32_state::start_of_vblank_int)
{
signal_v60_irq(MAIN_IRQ_VBSTART);
system32_set_vblank(1);
m_vblank_end_int_timer->adjust(m_screen->time_until_pos(0));
if (m_system32_prot_vblank)
(this->*m_system32_prot_vblank)();
if (m_s32comm != nullptr)
m_s32comm->check_vint_irq();
}
/*************************************
*
* I/O chip
*
*************************************/
void segas32_state::misc_output_0_w(uint8_t data)
{
if (m_sw1_output)
(this->*m_sw1_output)(0, data);
//machine().bookkeeping().coin_lockout_w(1 + 2*0, data & 0x08);
//machine().bookkeeping().coin_lockout_w(0 + 2*0, data & 0x04);
machine().bookkeeping().coin_counter_w(1 + 2*0, data & 0x02);
machine().bookkeeping().coin_counter_w(0 + 2*0, data & 0x01);
}
void segas32_state::misc_output_1_w(uint8_t data)
{
if (m_sw1_output)
(this->*m_sw1_output)(1, data);
//machine().bookkeeping().coin_lockout_w(1 + 2*1, data & 0x08);
//machine().bookkeeping().coin_lockout_w(0 + 2*1, data & 0x04);
machine().bookkeeping().coin_counter_w(1 + 2*1, data & 0x02);
machine().bookkeeping().coin_counter_w(0 + 2*1, data & 0x01);
}
void segas32_state::sw2_output_0_w(uint8_t data)
{
if (m_sw2_output)
(this->*m_sw2_output)(0, data);
}
void segas32_state::sw2_output_1_w(uint8_t data)
{
if (m_sw2_output)
(this->*m_sw2_output)(1, data);
}
void segas32_state::tilebank_external_w(uint8_t data)
{
m_system32_tilebank_external = data;
}
template<int Which>
WRITE_LINE_MEMBER(segas32_state::display_enable_w)
{
m_system32_displayenable[Which] = state;
}
/*************************************
*
* Random number generator
*
*************************************/
void segas32_state::random_number_w(offs_t offset, uint16_t data, uint16_t mem_mask)
{
// osd_printf_debug("%06X:random_seed_w(%04X) = %04X & %04X\n", m_maincpu->pc(), offset*2, data, mem_mask);
}
uint16_t segas32_state::random_number_r()
{
return machine().rand();
}
/*************************************
*
* Sound communications
*
*************************************/
uint8_t segas32_state::shared_ram_r(offs_t offset)
{
return m_z80_shared_ram[offset];
}
void segas32_state::shared_ram_w(offs_t offset, uint8_t data)
{
m_z80_shared_ram[offset] = data;
}
/*************************************
*
* Sound interrupt controller
*
*************************************/
void segas32_state::update_sound_irq_state()
{
uint8_t effirq = m_sound_irq_input & ~m_sound_irq_control[3] & 0x07;
int vector;
/* loop over interrupt vectors, finding the highest priority one with */
/* an unmasked interrupt pending */
for (vector = 0; vector < 3; vector++)
if (effirq & (1 << vector))
{
m_soundcpu->set_input_line_and_vector(0, ASSERT_LINE, 2 * vector); // Z80
break;
}
/* if we didn't find any, clear the interrupt line */
if (vector == 3)
m_soundcpu->set_input_line(0, CLEAR_LINE);
}
void segas32_state::signal_sound_irq(int which)
{
/* see if this interrupt input is mapped to any vectors; if so, mark them */
for (int i = 0; i < 3; i++)
if (m_sound_irq_control[i] == which)
m_sound_irq_input |= 1 << i;
update_sound_irq_state();
}
void segas32_state::clear_sound_irq(int which)
{
for (int i = 0; i < 3; i++)
if (m_sound_irq_control[i] == which)
m_sound_irq_input &= ~(1 << i);
update_sound_irq_state();
}
void segas32_state::sound_int_control_lo_w(offs_t offset, uint8_t data)
{
/* odd offsets are interrupt acks */
if (offset & 1)
{
m_sound_irq_input &= data;
update_sound_irq_state();
}
/* high offsets signal an IRQ to the v60 */
if (offset & 4)
signal_v60_irq(MAIN_IRQ_SOUND);
}
void segas32_state::sound_int_control_hi_w(offs_t offset, uint8_t data)
{
m_sound_irq_control[offset] = data;
update_sound_irq_state();
}
WRITE_LINE_MEMBER(segas32_state::ym3438_irq_handler)
{
if (state)
signal_sound_irq(SOUND_IRQ_YM3438);
else
clear_sound_irq(SOUND_IRQ_YM3438);
}
/*************************************
*
* Sound banking
*
*************************************/
void segas32_state::sound_bank_lo_w(uint8_t data)
{
m_sound_bank = (m_sound_bank & ~0x3f) | (data & 0x3f);
m_soundrom_bank->set_entry(m_sound_bank);
}
void segas32_state::sound_bank_hi_w(uint8_t data)
{
m_sound_bank = (m_sound_bank & 0x3f) | ((data & 0x04) << 4) | ((data & 0x03) << 7);
m_soundrom_bank->set_entry(m_sound_bank);
}
void segas32_state::multipcm_bank_w(uint8_t data)
{
m_multipcm_bank_hi->set_entry((data >> 3) & 7);
m_multipcm_bank_lo->set_entry(data & 7);
}
void segas32_state::scross_bank_w(uint8_t data)
{
m_multipcm_bank_hi->set_entry(data & 7);
m_multipcm_bank_lo->set_entry(data & 7);
}
/*************************************
*
* Sound hack (not protection)
*
*************************************/
uint8_t segas32_state::sound_dummy_r()
{
return m_sound_dummy_value;
}
void segas32_state::sound_dummy_w(uint8_t data)
{
m_sound_dummy_value = data;
}
/*************************************
*
* Common palette handling
*
*************************************/
inline uint16_t segas32_state::xBBBBBGGGGGRRRRR_to_xBGRBBBBGGGGRRRR(uint16_t value)
{
int r = (value >> 0) & 0x1f;
int g = (value >> 5) & 0x1f;
int b = (value >> 10) & 0x1f;
value = (value & 0x8000) | ((b & 0x01) << 14) | ((g & 0x01) << 13) | ((r & 0x01) << 12);
value |= ((b & 0x1e) << 7) | ((g & 0x1e) << 3) | ((r & 0x1e) >> 1);
return value;
}
inline uint16_t segas32_state::xBGRBBBBGGGGRRRR_to_xBBBBBGGGGGRRRRR(uint16_t value)
{
int r = ((value >> 12) & 0x01) | ((value << 1) & 0x1e);
int g = ((value >> 13) & 0x01) | ((value >> 3) & 0x1e);
int b = ((value >> 14) & 0x01) | ((value >> 7) & 0x1e);
return (value & 0x8000) | (b << 10) | (g << 5) | (r << 0);
}
inline void segas32_state::update_color(int offset, uint16_t data)
{
/* note that since we use this RAM directly, we don't technically need */
/* to call palette_set_color() at all; however, it does give us that */
/* nice display when you hit F4, which is useful for debugging */
/* set the color */
m_palette->set_pen_color(offset, pal5bit(data >> 0), pal5bit(data >> 5), pal5bit(data >> 10));
}
/*************************************
*
* Palette RAM access
*
*************************************/
template<int Which>
uint16_t segas32_state::paletteram_r(offs_t offset)
{
int convert;
/* the lower half of palette RAM is formatted xBBBBBGGGGGRRRRR */
/* the upper half of palette RAM is formatted xBGRBBBBGGGGRRRR */
/* we store everything if the first format, and convert accesses to the other format */
/* on the fly */
convert = (offset & 0x4000);
offset &= 0x3fff;
if (!convert)
return m_paletteram[Which][offset];
else
return xBBBBBGGGGGRRRRR_to_xBGRBBBBGGGGRRRR(m_paletteram[Which][offset]);
}
template<int Which>
void segas32_state::paletteram_w(offs_t offset, uint16_t data, uint16_t mem_mask)
{
uint16_t value;
int convert;
/* the lower half of palette RAM is formatted xBBBBBGGGGGRRRRR */
/* the upper half of palette RAM is formatted xBGRBBBBGGGGRRRR */
/* we store everything if the first format, and convert accesses to the other format */
/* on the fly */
convert = (offset & 0x4000);
offset &= 0x3fff;
/* read, modify, and write the new value, updating the palette */
value = m_paletteram[Which][offset];
if (convert) value = xBBBBBGGGGGRRRRR_to_xBGRBBBBGGGGRRRR(value);
COMBINE_DATA(&value);
if (convert) value = xBGRBBBBGGGGRRRR_to_xBBBBBGGGGGRRRRR(value);
m_paletteram[Which][offset] = value;
update_color(0x4000*Which + offset, value);
/* if blending is enabled, writes go to both halves of palette RAM */
if (m_mixer_control[Which][0x4e/2] & 0x0880)
{
offset ^= 0x2000;
/* read, modify, and write the new value, updating the palette */
value = m_paletteram[Which][offset];
if (convert) value = xBBBBBGGGGGRRRRR_to_xBGRBBBBGGGGRRRR(value);
COMBINE_DATA(&value);
if (convert) value = xBGRBBBBGGGGRRRR_to_xBBBBBGGGGGRRRRR(value);
m_paletteram[Which][offset] = value;
update_color(0x4000*Which + offset, value);
}
}
/*************************************
*
* Mixer control registers
*
*************************************/
template<int Which>
uint16_t segas32_state::mixer_r(offs_t offset)
{
return m_mixer_control[Which][offset];
}
template<int Which>
void segas32_state::mixer_w(offs_t offset, uint16_t data, uint16_t mem_mask)
{
COMBINE_DATA(&m_mixer_control[Which][offset]);
}
/*************************************
*
* Main CPU memory handlers
*
*************************************/
void segas32_state::system32_map(address_map &map)
{
map.unmap_value_high();
map(0x000000, 0x1fffff).rom();
map(0x200000, 0x20ffff).mirror(0x0f0000).ram().share("workram");
map(0x300000, 0x31ffff).mirror(0x0e0000).rw(FUNC(segas32_state::videoram_r), FUNC(segas32_state::videoram_w));
map(0x400000, 0x41ffff).mirror(0x0e0000).rw(FUNC(segas32_state::spriteram_r), FUNC(segas32_state::spriteram_w));
map(0x500000, 0x50000f).mirror(0x0ffff0).rw(FUNC(segas32_state::sprite_control_r), FUNC(segas32_state::sprite_control_w)).umask16(0x00ff);
map(0x600000, 0x60ffff).mirror(0x0e0000).rw(FUNC(segas32_state::paletteram_r<0>), FUNC(segas32_state::paletteram_w<0>));
map(0x610000, 0x61007f).mirror(0x0eff80).rw(FUNC(segas32_state::mixer_r<0>), FUNC(segas32_state::mixer_w<0>));
map(0x700000, 0x701fff).mirror(0x0fe000).rw(FUNC(segas32_state::shared_ram_r), FUNC(segas32_state::shared_ram_w));
map(0x800000, 0x800fff).rw("s32comm", FUNC(s32comm_device::share_r), FUNC(s32comm_device::share_w)).umask16(0x00ff);
map(0x801000, 0x801000).rw("s32comm", FUNC(s32comm_device::cn_r), FUNC(s32comm_device::cn_w));
map(0x801002, 0x801002).rw("s32comm", FUNC(s32comm_device::fg_r), FUNC(s32comm_device::fg_w));
map(0xc00000, 0xc0001f).mirror(0x0fff80).rw("io_chip", FUNC(sega_315_5296_device::read), FUNC(sega_315_5296_device::write)).umask16(0x00ff);
// 0xc00040-0xc0007f - I/O expansion area
map(0xd00000, 0xd0000f).mirror(0x07fff0).rw(FUNC(segas32_state::int_control_r), FUNC(segas32_state::int_control_w));
map(0xd80000, 0xdfffff).rw(FUNC(segas32_state::random_number_r), FUNC(segas32_state::random_number_w));
map(0xf00000, 0xffffff).rom().region("maincpu", 0);
}
void segas32_state::multi32_map(address_map &map)
{
map.unmap_value_high();
map.global_mask(0xffffff);
map(0x000000, 0x1fffff).rom();
map(0x200000, 0x21ffff).mirror(0x0e0000).ram();
map(0x300000, 0x31ffff).mirror(0x0e0000).rw(FUNC(segas32_state::videoram_r), FUNC(segas32_state::videoram_w));
map(0x400000, 0x41ffff).mirror(0x0e0000).rw(FUNC(segas32_state::spriteram_r), FUNC(segas32_state::spriteram_w));
map(0x500000, 0x50000f).mirror(0x0ffff0).rw(FUNC(segas32_state::sprite_control_r), FUNC(segas32_state::sprite_control_w)).umask32(0x00ff00ff);
map(0x600000, 0x60ffff).mirror(0x060000).rw(FUNC(segas32_state::paletteram_r<0>), FUNC(segas32_state::paletteram_w<0>));
map(0x610000, 0x61007f).mirror(0x06ff80).rw(FUNC(segas32_state::mixer_r<0>), FUNC(segas32_state::mixer_w<0>));
map(0x680000, 0x68ffff).mirror(0x060000).rw(FUNC(segas32_state::paletteram_r<1>), FUNC(segas32_state::paletteram_w<1>));
map(0x690000, 0x69007f).mirror(0x06ff80).rw(FUNC(segas32_state::mixer_r<1>), FUNC(segas32_state::mixer_w<1>));
map(0x700000, 0x701fff).mirror(0x0fe000).rw(FUNC(segas32_state::shared_ram_r), FUNC(segas32_state::shared_ram_w));
map(0x800000, 0x800fff).rw("s32comm", FUNC(s32comm_device::share_r), FUNC(s32comm_device::share_w)).umask32(0x00ff00ff);
map(0x801000, 0x801000).rw("s32comm", FUNC(s32comm_device::cn_r), FUNC(s32comm_device::cn_w));
map(0x801002, 0x801002).rw("s32comm", FUNC(s32comm_device::fg_r), FUNC(s32comm_device::fg_w));
map(0xc00000, 0xc0001f).mirror(0x07ff80).rw("io_chip_0", FUNC(sega_315_5296_device::read), FUNC(sega_315_5296_device::write)).umask32(0x00ff00ff);
// 0xc00040-0xc0007f - I/O expansion area 0
map(0xc80000, 0xc8001f).mirror(0x07ff80).rw("io_chip_1", FUNC(sega_315_5296_device::read), FUNC(sega_315_5296_device::write)).umask32(0x00ff00ff);
// 0xc80040-0xc8007f - I/O expansion area 1
map(0xd00000, 0xd0000f).mirror(0x07fff0).rw(FUNC(segas32_state::int_control_r), FUNC(segas32_state::int_control_w));
map(0xd80000, 0xdfffff).rw(FUNC(segas32_state::random_number_r), FUNC(segas32_state::random_number_w));
map(0xf00000, 0xffffff).rom().region("maincpu", 0);
}
/*************************************
*
* Sound CPU memory handlers
*
*************************************/
void segas32_state::system32_sound_map(address_map &map)
{
map(0x0000, 0x9fff).rom().region("soundcpu", 0);
map(0xa000, 0xbfff).bankr("soundbank");
map(0xc000, 0xdfff).m("rfsnd", FUNC(rf5c68_device::map));
map(0xe000, 0xffff).ram().share("z80_shared_ram");
}
void segas32_state::system32_sound_portmap(address_map &map)
{
map.unmap_value_high();
map.global_mask(0xff);
map(0x80, 0x83).mirror(0x0c).rw("ym1", FUNC(ym3438_device::read), FUNC(ym3438_device::write));
map(0x90, 0x93).mirror(0x0c).rw("ym2", FUNC(ym3438_device::read), FUNC(ym3438_device::write));
map(0xa0, 0xaf).w(FUNC(segas32_state::sound_bank_lo_w));
map(0xb0, 0xbf).w(FUNC(segas32_state::sound_bank_hi_w));
map(0xc0, 0xcf).w(FUNC(segas32_state::sound_int_control_lo_w));
map(0xd0, 0xd3).mirror(0x04).w(FUNC(segas32_state::sound_int_control_hi_w));
map(0xf1, 0xf1).rw(FUNC(segas32_state::sound_dummy_r), FUNC(segas32_state::sound_dummy_w));
}
void segas32_state::rf5c68_map(address_map &map)
{
map.unmap_value_high();
map(0x0000, 0xffff).ram().share("soundram");
}
void segas32_state::multi32_sound_map(address_map &map)
{
map(0x0000, 0x9fff).rom().region("soundcpu", 0);
map(0xa000, 0xbfff).bankr("soundbank");
map(0xc000, 0xdfff).rw("sega", FUNC(multipcm_device::read), FUNC(multipcm_device::write));
map(0xe000, 0xffff).ram().share("z80_shared_ram");
}
void segas32_state::multi32_sound_portmap(address_map &map)
{
map.unmap_value_high();
map.global_mask(0xff);
map(0x80, 0x83).mirror(0x0c).rw("ymsnd", FUNC(ym3438_device::read), FUNC(ym3438_device::write));
map(0xa0, 0xaf).w(FUNC(segas32_state::sound_bank_lo_w));
map(0xb0, 0xbf).w(FUNC(segas32_state::multipcm_bank_w));
map(0xc0, 0xcf).w(FUNC(segas32_state::sound_int_control_lo_w));
map(0xd0, 0xd3).mirror(0x04).w(FUNC(segas32_state::sound_int_control_hi_w));
map(0xf1, 0xf1).rw(FUNC(segas32_state::sound_dummy_r), FUNC(segas32_state::sound_dummy_w));
}
void segas32_state::multipcm_map(address_map &map)
{
map(0x000000, 0x0fffff).rom();
map(0x100000, 0x17ffff).bankr("multipcmbanklo");
map(0x180000, 0x1fffff).bankr("multipcmbankhi");
}
/*************************************
*
* V25 Protection CPU memory handlers
*
*************************************/
void segas32_state::v25_map(address_map &map)
{
map(0x00000, 0x0ffff).rom().region("mcu", 0);
map(0x10000, 0x1ffff).rw("dpram", FUNC(mb8421_device::left_r), FUNC(mb8421_device::left_w));
map(0xf0000, 0xfffff).rom().region("mcu", 0);
}
/*************************************
*
* UPD7725 DSP memory handlers
*
*************************************/
void segas32_state::upd7725_prg_map(address_map &map)
{
map(0x0000, 0x07ff).rom().region("dspprg", 0);
}
void segas32_state::upd7725_data_map(address_map &map)
{
map(0x0000, 0x03ff).rom().region("dspdata", 0);
}
/*************************************
*
* Generic port definitions
*
*************************************/
static INPUT_PORTS_START( system32_generic )
PORT_START("mainpcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY
PORT_START("mainpcb:P2_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(2)
PORT_START("mainpcb:PORTC_A")
PORT_BIT( 0x0f, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:SERVICE12_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_SERVICE1 )
PORT_SERVICE_NO_TOGGLE( 0x02, IP_ACTIVE_LOW )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("mainpcb:SERVICE34_A")
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Unknown ) ) PORT_DIPLOCATION("SW1:1")
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPLOCATION("SW1:2")
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPLOCATION("SW1:3")
PORT_DIPSETTING( 0x04, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPLOCATION("SW1:4")
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_SERVICE3 ) PORT_NAME("Push SW1 (Service)") // on PCB
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_SERVICE4 ) PORT_NAME("Push SW2 (Test)") // on PCB
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_DEVICE_MEMBER("mainpcb:eeprom", eeprom_serial_93cxx_device, do_read)
INPUT_PORTS_END
static INPUT_PORTS_START( system32_generic_slave )
PORT_START("slavepcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(3)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(3)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(3)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(3)
PORT_START("slavepcb:P2_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(4)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(4)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(4)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(4)
PORT_START("slavepcb:PORTC_A")
PORT_BIT( 0x0f, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("slavepcb:SERVICE12_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_SERVICE2 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_OTHER ) PORT_CODE(KEYCODE_F1) PORT_NAME("slavepcb:Service Mode")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN3 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN4 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START3 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START4 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("slavepcb:SERVICE34_A")
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Unknown ) ) PORT_DIPLOCATION("slavepcb_SW1:1")
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPLOCATION("slavepcb_SW1:2")
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPLOCATION("slavepcb_SW1:3")
PORT_DIPSETTING( 0x04, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPLOCATION("slavepcb_SW1:4")
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("slavepcb:Push SW1 (Service)") PORT_CODE(KEYCODE_OPENBRACE)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("slavepcb:Push SW2 (Test)") PORT_CODE(KEYCODE_CLOSEBRACE)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_DEVICE_MEMBER("slavepcb:eeprom", eeprom_serial_93cxx_device, do_read)
INPUT_PORTS_END
static INPUT_PORTS_START( multi32_generic )
PORT_INCLUDE( system32_generic )
PORT_START("mainpcb:P1_B")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:P2_B")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:PORTC_B")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:SERVICE12_B")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_SERVICE2 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_OTHER ) PORT_CODE(KEYCODE_F1) PORT_NAME("Service Mode 2")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0xe0, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("mainpcb:SERVICE34_B")
PORT_BIT( 0x4f, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Push SW3 (Service)") PORT_CODE(KEYCODE_OPENBRACE)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Push SW4 (Test)") PORT_CODE(KEYCODE_CLOSEBRACE)
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_DEVICE_MEMBER("mainpcb:eeprom", eeprom_serial_93cxx_device, do_read)
INPUT_PORTS_END
/*************************************
*
* Game-specific port definitions
*
*************************************/
static INPUT_PORTS_START( arescue )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x30, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:SERVICE34_A")
PORT_BIT( 0x30, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:ANALOG1")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_X ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_REVERSE
PORT_START("mainpcb:ANALOG2")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Y ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10)
PORT_START("mainpcb:ANALOG3")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Z ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10)
PORT_INCLUDE( system32_generic_slave )
PORT_MODIFY("slavepcb:P1_A")
PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2)
PORT_MODIFY("slavepcb:P2_A")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("slavepcb:SERVICE12_A")
PORT_BIT( 0x30, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("slavepcb:SERVICE34_A")
PORT_BIT( 0x30, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("slavepcb:ANALOG1")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_X ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_REVERSE PORT_PLAYER(2)
PORT_START("slavepcb:ANALOG2")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Y ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_PLAYER(2)
PORT_START("slavepcb:ANALOG3")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Z ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_PLAYER(2)
INPUT_PORTS_END
static INPUT_PORTS_START( alien3 )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_SERVICE2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:ANALOG1")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_X ) PORT_SENSITIVITY(50) PORT_KEYDELTA(5)
PORT_START("mainpcb:ANALOG2")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Y ) PORT_SENSITIVITY(50) PORT_KEYDELTA(5)
PORT_START("mainpcb:ANALOG3")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_X ) PORT_SENSITIVITY(50) PORT_KEYDELTA(5) PORT_PLAYER(2)
PORT_START("mainpcb:ANALOG4")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Y ) PORT_SENSITIVITY(50) PORT_KEYDELTA(5) PORT_PLAYER(2)
INPUT_PORTS_END
static INPUT_PORTS_START( arabfgt )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x0c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0x0c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:EXTRA1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(3)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(3)
PORT_BIT( 0x0c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(3)
PORT_START("mainpcb:EXTRA2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(4)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(4)
PORT_BIT( 0x0c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(4)
PORT_START("mainpcb:EXTRA3")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START3 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START4 )
PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNUSED )
INPUT_PORTS_END
static INPUT_PORTS_START( arabfgtu )
PORT_INCLUDE( arabfgt )
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN4 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN3 )
PORT_MODIFY("mainpcb:EXTRA3")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN1 )
INPUT_PORTS_END
static INPUT_PORTS_START( brival )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:EXTRA1")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:EXTRA2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(2)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_PLAYER(2)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON6 ) PORT_PLAYER(2)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_PLAYER(1)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(1)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON6 ) PORT_PLAYER(1)
PORT_START("mainpcb:EXTRA3")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
INPUT_PORTS_END
static INPUT_PORTS_START( darkedge )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2)
PORT_START("mainpcb:EXTRA1")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:EXTRA2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(2)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_PLAYER(2)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(1)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_PLAYER(1)
PORT_START("mainpcb:EXTRA3")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
INPUT_PORTS_END
static INPUT_PORTS_START( dbzvrvs )
PORT_INCLUDE( system32_generic )
PORT_START("mainpcb:ANALOG1")
PORT_BIT( 0xff, 0xff, IPT_UNKNOWN )
PORT_START("mainpcb:ANALOG2")
PORT_BIT( 0xff, 0xff, IPT_UNKNOWN )
PORT_START("mainpcb:ANALOG3")
PORT_BIT( 0xff, 0xff, IPT_UNKNOWN )
INPUT_PORTS_END
static INPUT_PORTS_START( f1en )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CODE(KEYCODE_SPACE) PORT_NAME("mainpcb:Gear Up")
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_CODE(KEYCODE_LSHIFT) PORT_NAME("mainpcb:Gear Down")
PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:ANALOG1")
PORT_BIT( 0xff, 0x80, IPT_PADDLE ) PORT_SENSITIVITY(50) PORT_KEYDELTA(10) PORT_NAME("mainpcb:Steering Wheel")
PORT_START("mainpcb:ANALOG2")
PORT_BIT( 0xff, 0x00, IPT_PEDAL ) PORT_SENSITIVITY(50) PORT_KEYDELTA(10) PORT_NAME("mainpcb:Gas Pedal")
PORT_START("mainpcb:ANALOG3")
PORT_BIT( 0xff, 0x00, IPT_PEDAL2 ) PORT_SENSITIVITY(50) PORT_KEYDELTA(10) PORT_NAME("mainpcb:Brake Pedal")
PORT_INCLUDE( system32_generic_slave )
PORT_MODIFY("slavepcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("slavepcb:Gear Up") PORT_PLAYER(2)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("slavepcb:Gear Down") PORT_PLAYER(2)
PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("slavepcb:P2_A")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("slavepcb:SERVICE12_A")
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("slavepcb:ANALOG1")
PORT_BIT( 0xff, 0x80, IPT_PADDLE ) PORT_SENSITIVITY(50) PORT_KEYDELTA(10) PORT_NAME("slavepcb:Steering Wheel") PORT_PLAYER(2)
PORT_START("slavepcb:ANALOG2")
PORT_BIT( 0xff, 0x00, IPT_PEDAL ) PORT_SENSITIVITY(50) PORT_KEYDELTA(10) PORT_NAME("slavepcb:Gas Pedal") PORT_PLAYER(2)
PORT_START("slavepcb:ANALOG3")
PORT_BIT( 0xff, 0x00, IPT_PEDAL2 ) PORT_SENSITIVITY(50) PORT_KEYDELTA(10) PORT_NAME("slavepcb:Brake Pedal") PORT_PLAYER(2)
INPUT_PORTS_END
static INPUT_PORTS_START( f1lap )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CODE(KEYCODE_SPACE) PORT_NAME("mainpcb:Gear Up")
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_CODE(KEYCODE_LSHIFT) PORT_NAME("mainpcb:Gear Down")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_CODE(KEYCODE_Z) PORT_NAME("mainpcb:Overtake")
PORT_BIT( 0xf8, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:ANALOG1")
PORT_BIT( 0xff, 0x80, IPT_PADDLE ) PORT_SENSITIVITY(50) PORT_KEYDELTA(20) PORT_NAME("mainpcb:Steering Wheel")
PORT_START("mainpcb:ANALOG2")
PORT_BIT( 0xff, 0x00, IPT_PEDAL ) PORT_SENSITIVITY(50) PORT_KEYDELTA(20) PORT_NAME("mainpcb:Gas Pedal")
PORT_START("mainpcb:ANALOG3")
PORT_BIT( 0xff, 0x00, IPT_PEDAL2 ) PORT_SENSITIVITY(50) PORT_KEYDELTA(20) PORT_NAME("mainpcb:Brake Pedal")
INPUT_PORTS_END
static INPUT_PORTS_START( ga2 )
PORT_INCLUDE( system32_generic )
PORT_START("mainpcb:EXTRA1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(3)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(3)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(3)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(3)
PORT_START("mainpcb:EXTRA2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(4)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(4)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(4)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(4)
PORT_START("mainpcb:EXTRA3")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START3 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START4 )
PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNUSED )
INPUT_PORTS_END
static INPUT_PORTS_START( ga2u )
PORT_INCLUDE( ga2 )
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN4 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN3 )
PORT_MODIFY("mainpcb:EXTRA3")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN1 )
INPUT_PORTS_END
static INPUT_PORTS_START( harddunk )
PORT_INCLUDE( multi32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1)
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(2)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(2)
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_MODIFY("mainpcb:P1_B")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(4)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(4)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(4)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(4)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(4)
PORT_MODIFY("mainpcb:P2_B")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(5)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(5)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(5)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(5)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(5)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(5)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(5)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(5)
PORT_MODIFY("mainpcb:SERVICE12_B")
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START4 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START5 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("mainpcb:EXTRA1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(3)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(3)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(3)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(3)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(3)
PORT_START("mainpcb:EXTRA2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(6)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(6)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(6)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(6)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(6)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(6)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(6)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(6)
PORT_START("mainpcb:EXTRA3")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START3 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START6 )
PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
static INPUT_PORTS_START( holo )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x0c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0x0c, IP_ACTIVE_LOW, IPT_UNUSED )
INPUT_PORTS_END
static INPUT_PORTS_START( jpark )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:PORTC_A")
PORT_BIT( 0x07, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_TILT ) PORT_NAME("Emergency") // recognized in input test only?
PORT_START("mainpcb:ANALOG1")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_X ) PORT_SENSITIVITY(50) PORT_KEYDELTA(5)
PORT_START("mainpcb:ANALOG2")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Y ) PORT_SENSITIVITY(50) PORT_KEYDELTA(5)
PORT_START("mainpcb:ANALOG3")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_X ) PORT_SENSITIVITY(50) PORT_KEYDELTA(5) PORT_PLAYER(2)
PORT_START("mainpcb:ANALOG4")
PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Y ) PORT_SENSITIVITY(50) PORT_KEYDELTA(5) PORT_PLAYER(2)
INPUT_PORTS_END
static INPUT_PORTS_START( kokoroj2 )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(2)
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(3)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(3)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(3)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(3)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(4)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(4)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(4)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(4)
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START3 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START4 )
PORT_MODIFY("mainpcb:SERVICE34_A")
PORT_DIPNAME( 0x08, 0x00, "CD & Printer" ) PORT_DIPLOCATION("SW1:4")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x08, DEF_STR( On ) )
PORT_BIT( 0x30, IP_ACTIVE_LOW, IPT_UNUSED )
INPUT_PORTS_END
static INPUT_PORTS_START( orunners )
PORT_INCLUDE( multi32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_CODE(KEYCODE_SPACE) /* shift up */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_CODE(KEYCODE_LSHIFT) /* shift down */
PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1) PORT_CODE(KEYCODE_Z) /* DJ/music */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(1) PORT_CODE(KEYCODE_X) /* << */
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_PLAYER(1) PORT_CODE(KEYCODE_C) /* >> */
PORT_BIT( 0xf8, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_MODIFY("mainpcb:P1_B")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_CODE(KEYCODE_Q) /* shift up */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_CODE(KEYCODE_W) /* shift down */
PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_MODIFY("mainpcb:P2_B")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2) PORT_CODE(KEYCODE_R) /* DJ/music */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(2) PORT_CODE(KEYCODE_T) /* << */
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_PLAYER(2) PORT_CODE(KEYCODE_Y) /* >> */
PORT_BIT( 0xf8, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("mainpcb:ANALOG1")
PORT_BIT( 0xff, 0x80, IPT_PADDLE ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_PLAYER(1)
PORT_START("mainpcb:ANALOG2")
PORT_BIT( 0xff, 0x00, IPT_PEDAL ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_PLAYER(1)
PORT_START("mainpcb:ANALOG3")
PORT_BIT( 0xff, 0x00, IPT_PEDAL2 ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_PLAYER(1)
PORT_START("mainpcb:ANALOG4")
PORT_BIT( 0xff, 0x80, IPT_PADDLE ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_PLAYER(2)
PORT_START("mainpcb:ANALOG7")
PORT_BIT( 0xff, 0x00, IPT_PEDAL ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_PLAYER(2)
PORT_START("mainpcb:ANALOG8")
PORT_BIT( 0xff, 0x00, IPT_PEDAL2 ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_PLAYER(2)
INPUT_PORTS_END
static INPUT_PORTS_START( radm )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CODE(KEYCODE_SPACE) PORT_NAME("mainpcb:Light")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_CODE(KEYCODE_LSHIFT) PORT_NAME("mainpcb:Wiper")
PORT_BIT( 0xf8, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:ANALOG1")
PORT_BIT( 0xff, 0x80, IPT_PADDLE ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10)
PORT_START("mainpcb:ANALOG2")
PORT_BIT( 0xff, 0x00, IPT_PEDAL ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10)
PORT_START("mainpcb:ANALOG3")
PORT_BIT( 0xff, 0x00, IPT_PEDAL2 ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10)
INPUT_PORTS_END
static INPUT_PORTS_START( radr )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CODE(KEYCODE_SPACE) PORT_NAME("mainpcb:Gear Change") PORT_TOGGLE
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:SERVICE34_A")
PORT_DIPNAME( 0x08, 0x08, "Transmission" ) PORT_DIPLOCATION("SW1:4")
PORT_DIPSETTING( 0x08, "Manual" )
PORT_DIPSETTING( 0x00, "Automatic" )
PORT_START("mainpcb:ANALOG1")
PORT_BIT( 0xff, 0x80, IPT_PADDLE ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10)
PORT_START("mainpcb:ANALOG2")
PORT_BIT( 0xff, 0x00, IPT_PEDAL ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10)
PORT_START("mainpcb:ANALOG3")
PORT_BIT( 0xff, 0x00, IPT_PEDAL2 ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10)
INPUT_PORTS_END
static INPUT_PORTS_START( scross )
PORT_INCLUDE( multi32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_CODE(KEYCODE_SPACE) /* P1 Attack */
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_CODE(KEYCODE_LSHIFT) /* P1 Wheelie */
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1) PORT_CODE(KEYCODE_LALT) /* P1 Brake */
PORT_BIT( 0xf8, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_MODIFY("mainpcb:P1_B")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_CODE(KEYCODE_Q) /* P2 Attack */
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_CODE(KEYCODE_W) /* P2 Wheelie */
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2) PORT_CODE(KEYCODE_S) /* P2 Brake */
PORT_BIT( 0xf8, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:ANALOG1")
PORT_BIT( 0xff, 0x80, IPT_PADDLE ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_REVERSE PORT_PLAYER(1)
PORT_START("mainpcb:ANALOG2")
PORT_BIT( 0xff, 0x00, IPT_PEDAL ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_PLAYER(1)
PORT_START("mainpcb:ANALOG3")
PORT_BIT( 0xff, 0x80, IPT_PADDLE ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_REVERSE PORT_PLAYER(2)
PORT_START("mainpcb:ANALOG4")
PORT_BIT( 0xff, 0x00, IPT_PEDAL ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10) PORT_PLAYER(2)
INPUT_PORTS_END
static INPUT_PORTS_START( slipstrm )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CODE(KEYCODE_SPACE) PORT_NAME("mainpcb:Gear Change") PORT_TOGGLE
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:ANALOG1")
PORT_BIT( 0xff, 0x80, IPT_PADDLE ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10)
PORT_START("mainpcb:ANALOG2")
PORT_BIT( 0xff, 0x00, IPT_PEDAL ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10)
PORT_START("mainpcb:ANALOG3")
PORT_BIT( 0xff, 0x00, IPT_PEDAL2 ) PORT_SENSITIVITY(30) PORT_KEYDELTA(10)
INPUT_PORTS_END
static INPUT_PORTS_START( sonic )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(3)
PORT_BIT( 0xf8, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN3 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START3 )
PORT_START("mainpcb:TRACKX1")
PORT_BIT( 0xfff, 0, IPT_TRACKBALL_X ) PORT_SENSITIVITY(100) PORT_KEYDELTA(30) PORT_REVERSE PORT_PLAYER(1)
PORT_START("mainpcb:TRACKY1")
PORT_BIT( 0xfff, 0, IPT_TRACKBALL_Y ) PORT_SENSITIVITY(100) PORT_KEYDELTA(30) PORT_PLAYER(1)
PORT_START("mainpcb:TRACKX2")
PORT_BIT( 0xfff, 0, IPT_TRACKBALL_X ) PORT_SENSITIVITY(100) PORT_KEYDELTA(30) PORT_REVERSE PORT_PLAYER(2)
PORT_START("mainpcb:TRACKY2")
PORT_BIT( 0xfff, 0, IPT_TRACKBALL_Y ) PORT_SENSITIVITY(100) PORT_KEYDELTA(30) PORT_PLAYER(2)
PORT_START("mainpcb:TRACKX3")
PORT_BIT( 0xfff, 0, IPT_TRACKBALL_X ) PORT_SENSITIVITY(100) PORT_KEYDELTA(30) PORT_REVERSE PORT_PLAYER(3)
PORT_START("mainpcb:TRACKY3")
PORT_BIT( 0xfff, 0, IPT_TRACKBALL_Y ) PORT_SENSITIVITY(100) PORT_KEYDELTA(30) PORT_PLAYER(3)
INPUT_PORTS_END
static INPUT_PORTS_START( spidman )
PORT_INCLUDE( system32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x0c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0x0c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("mainpcb:EXTRA1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(3)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(3)
PORT_BIT( 0x0c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(3)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(3)
PORT_START("mainpcb:EXTRA2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(4)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(4)
PORT_BIT( 0x0c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(4)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(4)
PORT_START("mainpcb:EXTRA3")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START3 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START4 )
PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNUSED )
INPUT_PORTS_END
static INPUT_PORTS_START( spidmanu )
PORT_INCLUDE( spidman )
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN4 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN3 )
PORT_MODIFY("mainpcb:EXTRA3")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN1 )
INPUT_PORTS_END
static INPUT_PORTS_START( svf )
PORT_INCLUDE( system32_generic )
INPUT_PORTS_END
static INPUT_PORTS_START( titlef )
PORT_INCLUDE( multi32_generic )
PORT_MODIFY("mainpcb:P1_A")
PORT_BIT( 0x0f, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_DOWN ) PORT_PLAYER(1)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_UP ) PORT_PLAYER(1)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_RIGHT ) PORT_PLAYER(1)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_LEFT ) PORT_PLAYER(1)
PORT_MODIFY("mainpcb:P2_A")
PORT_BIT( 0x0f, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_DOWN ) PORT_PLAYER(1)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_UP ) PORT_PLAYER(1)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_RIGHT ) PORT_PLAYER(1)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_LEFT ) PORT_PLAYER(1)
PORT_MODIFY("mainpcb:SERVICE12_A")
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_MODIFY("mainpcb:P1_B")
PORT_BIT( 0x0f, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_DOWN ) PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_UP ) PORT_PLAYER(2)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_RIGHT ) PORT_PLAYER(2)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_LEFT ) PORT_PLAYER(2)
PORT_MODIFY("mainpcb:P2_B")
PORT_BIT( 0x0f, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_DOWN ) PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_UP ) PORT_PLAYER(2)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_RIGHT ) PORT_PLAYER(2)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_LEFT ) PORT_PLAYER(2)
PORT_MODIFY("mainpcb:SERVICE12_B")
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START3 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START4 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
/*************************************
*
* Graphics definitions
*
*************************************/
static const gfx_layout bgcharlayout =
{
16,16,
RGN_FRAC(1,1),
4,
{ STEP4(0,1) },
{ 0, 4, 16, 20, 8, 12, 24, 28, 32, 36, 48, 52, 40, 44, 56, 60 },
{ STEP16(0,4*16) },
16*64
};
static GFXDECODE_START( gfx_segas32 )
GFXDECODE_ENTRY( "gfx1", 0, bgcharlayout, 0x00, 0x3ff )
GFXDECODE_END
/*************************************
*
* Machine driver
*
*************************************/
void segas32_state::device_add_mconfig(machine_config &config)
{
/* basic machine hardware */
V60(config, m_maincpu, MASTER_CLOCK/2);
m_maincpu->set_addrmap(AS_PROGRAM, &segas32_state::system32_map);
m_maincpu->set_vblank_int("screen", FUNC(segas32_state::start_of_vblank_int));
Z80(config, m_soundcpu, MASTER_CLOCK/4);
m_soundcpu->set_addrmap(AS_PROGRAM, &segas32_state::system32_sound_map);
m_soundcpu->set_addrmap(AS_IO, &segas32_state::system32_sound_portmap);
sega_315_5296_device &io_chip(SEGA_315_5296(config, "io_chip", 0)); // unknown clock
io_chip.in_pa_callback().set_ioport("P1_A");
io_chip.in_pb_callback().set_ioport("P2_A");
io_chip.in_pc_callback().set_ioport("PORTC_A");
io_chip.out_pd_callback().set(FUNC(segas32_state::misc_output_0_w));
io_chip.out_pd_callback().append("eeprom", FUNC(eeprom_serial_93cxx_device::di_write)).bit(7);
io_chip.out_pd_callback().append("eeprom", FUNC(eeprom_serial_93cxx_device::cs_write)).bit(5);
io_chip.out_pd_callback().append("eeprom", FUNC(eeprom_serial_93cxx_device::clk_write)).bit(6);
io_chip.in_pe_callback().set_ioport("SERVICE12_A");
io_chip.in_pf_callback().set_ioport("SERVICE34_A");
io_chip.out_pg_callback().set(FUNC(segas32_state::sw2_output_0_w));
io_chip.out_ph_callback().set(FUNC(segas32_state::tilebank_external_w));
io_chip.out_cnt1_callback().set(FUNC(segas32_state::display_enable_w<0>));
io_chip.out_cnt2_callback().set_inputline(m_soundcpu, INPUT_LINE_RESET).invert();
EEPROM_93C46_16BIT(config, "eeprom");
TIMER(config, "v60_irq0").configure_generic(FUNC(segas32_state::signal_v60_irq_callback));
TIMER(config, "v60_irq1").configure_generic(FUNC(segas32_state::signal_v60_irq_callback));
/* video hardware */
GFXDECODE(config, m_gfxdecode, m_palette, gfx_segas32);
PALETTE(config, m_palette).set_entries(0x4000);
SCREEN(config, m_screen, SCREEN_TYPE_RASTER);
m_screen->set_refresh_hz(60);
m_screen->set_size(52*8, 262);
m_screen->set_visarea(0*8, 52*8-1, 0*8, 28*8-1);
m_screen->set_screen_update(FUNC(segas32_state::screen_update_system32));
/* sound hardware */
SPEAKER(config, "lspeaker").front_left();
SPEAKER(config, "rspeaker").front_right();
ym3438_device &ym1(YM3438(config, "ym1", MASTER_CLOCK/4));
ym1.irq_handler().set(FUNC(segas32_state::ym3438_irq_handler));
ym1.add_route(0, "lspeaker", 0.40);
ym1.add_route(1, "rspeaker", 0.40);
ym3438_device &ym2(YM3438(config, "ym2", MASTER_CLOCK/4));
ym2.add_route(0, "lspeaker", 0.40);
ym2.add_route(1, "rspeaker", 0.40);
rf5c68_device &rfsnd(RF5C68(config, "rfsnd", RFC_CLOCK/4)); // ASSP (RF)5C105 or Sega 315-5476A
rfsnd.add_route(0, "lspeaker", 0.55);
rfsnd.add_route(1, "rspeaker", 0.55);
rfsnd.set_addrmap(0, &segas32_state::rf5c68_map);
S32COMM(config, m_s32comm, 0);
}
DEFINE_DEVICE_TYPE(SEGA_S32_REGULAR_DEVICE, segas32_regular_state, "segas32_pcb_regular", "Sega System 32 regular PCB")
segas32_regular_state::segas32_regular_state(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: segas32_state(mconfig, SEGA_S32_REGULAR_DEVICE, tag, owner, clock, false)
{
}
void segas32_state::system32_analog_map(address_map &map)
{
map.unmap_value_high();
system32_map(map);
map(0xc00050, 0xc00057).mirror(0x0fff80).rw("adc", FUNC(msm6253_device::d7_r), FUNC(msm6253_device::address_w)).umask16(0x00ff);
}
void segas32_analog_state::device_add_mconfig(machine_config &config)
{
segas32_state::device_add_mconfig(config);
m_maincpu->set_addrmap(AS_PROGRAM, &segas32_analog_state::system32_analog_map);
msm6253_device &adc(MSM6253(config, "adc", 0));
adc.set_input_tag<0>("ANALOG1");
adc.set_input_tag<1>("ANALOG2");
adc.set_input_tag<2>("ANALOG3");
adc.set_input_tag<3>("ANALOG4");
}
DEFINE_DEVICE_TYPE(SEGA_S32_ANALOG_DEVICE, segas32_analog_state, "segas32_pcb_analog", "Sega System 32 analog PCB")
segas32_analog_state::segas32_analog_state(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: segas32_analog_state(mconfig, SEGA_S32_ANALOG_DEVICE, tag, owner, clock)
{
}
segas32_analog_state::segas32_analog_state(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock)
: segas32_state(mconfig, type, tag, owner, clock, false)
{
}
void segas32_trackball_state::system32_trackball_map(address_map &map)
{
map.unmap_value_high();
system32_map(map);
//map(0xc00040, 0xc0005f).mirror(0x0fff80).rw(FUNC(segas32_trackball_state::sonic_custom_io_r), FUNC(segas32_trackball_state::sonic_custom_io_w)).umask16(0x00ff);
map(0xc00040, 0xc00047).mirror(0x0fff80).rw("upd1", FUNC(upd4701_device::read_xy), FUNC(upd4701_device::reset_xy_w)).umask16(0x00ff);
map(0xc00048, 0xc0004f).mirror(0x0fff80).rw("upd2", FUNC(upd4701_device::read_xy), FUNC(upd4701_device::reset_xy_w)).umask16(0x00ff);
map(0xc00050, 0xc00057).mirror(0x0fff80).rw("upd3", FUNC(upd4701_device::read_xy), FUNC(upd4701_device::reset_xy_w)).umask16(0x00ff);
}
void segas32_trackball_state::device_add_mconfig(machine_config &config)
{
segas32_state::device_add_mconfig(config);
m_maincpu->set_addrmap(AS_PROGRAM, &segas32_trackball_state::system32_trackball_map);
upd4701_device &upd1(UPD4701A(config, "upd1"));
upd1.set_portx_tag("TRACKX1");
upd1.set_porty_tag("TRACKY1");
upd4701_device &upd2(UPD4701A(config, "upd2"));
upd2.set_portx_tag("TRACKX2");
upd2.set_porty_tag("TRACKY2");
upd4701_device &upd3(UPD4701A(config, "upd3"));
upd3.set_portx_tag("TRACKX3");
upd3.set_porty_tag("TRACKY3");
// 837-8685 I/O board has an unpopulated space for a fourth UPD4701A
}
DEFINE_DEVICE_TYPE(SEGA_S32_TRACKBALL_DEVICE, segas32_trackball_state, "segas32_pcb_trackball", "Sega System 32 trackball PCB")
segas32_trackball_state::segas32_trackball_state(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: segas32_state(mconfig, SEGA_S32_TRACKBALL_DEVICE, tag, owner, clock, false)
{
}
void segas32_state::system32_4player_map(address_map &map)
{
map.unmap_value_high();
system32_map(map);
map(0xc00060, 0xc00067).mirror(0x0fff80).rw("ppi", FUNC(i8255_device::read), FUNC(i8255_device::write)).umask16(0x00ff);
}
void segas32_4player_state::device_add_mconfig(machine_config &config)
{
segas32_state::device_add_mconfig(config);
m_maincpu->set_addrmap(AS_PROGRAM, &segas32_4player_state::system32_4player_map);
i8255_device &ppi(I8255A(config, "ppi"));
ppi.in_pa_callback().set_ioport("EXTRA1");
ppi.in_pb_callback().set_ioport("EXTRA2");
ppi.in_pc_callback().set_ioport("EXTRA3");
}
DEFINE_DEVICE_TYPE(SEGA_S32_4PLAYER_DEVICE, segas32_4player_state, "segas32_pcb_4player", "Sega System 32 4-player/fighting PCB")
segas32_4player_state::segas32_4player_state(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: segas32_4player_state(mconfig, SEGA_S32_4PLAYER_DEVICE, tag, owner, clock)
{
}
segas32_4player_state::segas32_4player_state(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock)
: segas32_state(mconfig, type, tag, owner, clock, false)
{
}
void segas32_state::ga2_main_map(address_map &map)
{
map.unmap_value_high();
system32_4player_map(map);
map(0xa00000, 0xa00fff).rw("dpram", FUNC(mb8421_device::right_r), FUNC(mb8421_device::right_w)).umask16(0x00ff);
}
void segas32_v25_state::device_add_mconfig(machine_config &config)
{
segas32_4player_state::device_add_mconfig(config);
m_maincpu->set_addrmap(AS_PROGRAM, &segas32_v25_state::ga2_main_map);
MB8421(config, "dpram", 0);
/* add a V25 for protection */
v25_device &mcu(V25(config, "mcu", 10000000));
mcu.set_addrmap(AS_PROGRAM, &segas32_v25_state::v25_map);
}
DEFINE_DEVICE_TYPE(SEGA_S32_V25_DEVICE, segas32_v25_state, "segas32_pcb_v25", "Sega System 32 V25 PCB")
segas32_v25_state::segas32_v25_state(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: segas32_4player_state(mconfig, SEGA_S32_V25_DEVICE, tag, owner, clock)
{
}
void segas32_upd7725_state::device_add_mconfig(machine_config &config)
{
segas32_analog_state::device_add_mconfig(config);
/* add a upd7725; this is on the 837-8341 daughterboard which plugs into the socket on the master pcb's ROM board where an fd1149 could go */
upd7725_device &dsp(UPD7725(config, "dsp", 8000000)); // TODO: Find real clock speed for the upd7725; this is a canned oscillator on the 837-8341 pcb
dsp.set_addrmap(AS_PROGRAM, &segas32_upd7725_state::upd7725_prg_map);
dsp.set_addrmap(AS_DATA, &segas32_upd7725_state::upd7725_data_map);
dsp.set_disable(); // TODO: disable for now, needs DMA pins and interrupts implemented in upd7725 core
// TODO: find /INT source for upd7725
// TODO: figure out how the p0 and p1 lines from the upd7725 affect the mainboard; do they select one of four (or 8) latches to/from the mainboard?
// TODO: trace out the 837-8341 pcb
// See HLE of this dsp in /src/mame/machine/segas32.cpp : arescue_dsp_r and arescue_dsp_w
}
DEFINE_DEVICE_TYPE(SEGA_S32_UPD7725_DEVICE, segas32_upd7725_state, "segas32_pcb_upd7725", "Sega System 32 uPD7725 PCB")
segas32_upd7725_state::segas32_upd7725_state(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: segas32_analog_state(mconfig, SEGA_S32_UPD7725_DEVICE, tag, owner, clock)
{
}
void segas32_cd_state::lamps1_w(uint8_t data)
{
for (int i = 0; i < 8; i++)
m_lamps[i] = BIT(data, i);
}
void segas32_cd_state::lamps2_w(uint8_t data)
{
for (int i = 0; i < 8; i++)
m_lamps[8 + i] = BIT(data, i);
}
WRITE_LINE_MEMBER(segas32_cd_state::scsi_irq_w)
{
printf("%02x IRQ\n",state);
// TODO: sent!
}
WRITE_LINE_MEMBER(segas32_cd_state::scsi_drq_w)
{
printf("%02x DRQ\n",state);
}
void segas32_state::system32_cd_map(address_map &map)
{
map.unmap_value_high();
system32_map(map);
#if S32_KOKOROJI_TEST_CD
map(0xc00040, 0xc0005f).mirror(0x0fff80).rw("mb89352", FUNC(mb89352_device::mb89352_r), FUNC(mb89352_device::mb89352_w)).umask16(0x00ff);
#else
map(0xc00040, 0xc0005f).mirror(0x0fff80).noprw();
#endif
map(0xc00060, 0xc0006f).mirror(0x0fff80).rw("cxdio", FUNC(cxd1095_device::read), FUNC(cxd1095_device::write)).umask16(0x00ff);
}
void segas32_cd_state::cdrom_config(device_t *device)
{
cdda_device *cdda = device->subdevice<cdda_device>("cdda");
cdda->add_route(0, "^^lspeaker", 1.0);
cdda->add_route(1, "^^rspeaker", 1.0);
}
void segas32_cd_state::device_add_mconfig(machine_config &config)
{
segas32_state::device_add_mconfig(config);
m_maincpu->set_addrmap(AS_PROGRAM, &segas32_cd_state::system32_cd_map);
mb89352_device &scsictrl(MB89352A(config, "mb89352", 8000000));
scsictrl.set_scsi_port("scsi");
scsictrl.irq_cb().set(FUNC(segas32_cd_state::scsi_irq_w));
scsictrl.drq_cb().set(FUNC(segas32_cd_state::scsi_drq_w));
scsi_port_device &scsi(SCSI_PORT(config, "scsi"));
scsi.set_slot_device(1, "cdrom", SCSICD, DEVICE_INPUT_DEFAULTS_NAME(SCSI_ID_0));
scsi.slot(1).set_option_machine_config("cdrom", cdrom_config);
cxd1095_device &cxdio(CXD1095(config, "cxdio"));
cxdio.out_porta_cb().set(FUNC(segas32_cd_state::lamps1_w));
cxdio.out_portb_cb().set(FUNC(segas32_cd_state::lamps2_w));
cxdio.in_portd_cb().set_constant(0xff); // Ports C-E used for IEEE-488 printer interface
}
DEFINE_DEVICE_TYPE(SEGA_S32_CD_DEVICE, segas32_cd_state, "segas32_pcb_cd", "Sega System 32 CD PCB")
segas32_cd_state::segas32_cd_state(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: segas32_state(mconfig, SEGA_S32_CD_DEVICE, tag, owner, clock, false)
, m_lamps(*this, "lamp%u", 0U)
{
}
void sega_multi32_state::device_add_mconfig(machine_config &config)
{
/* basic machine hardware */
V70(config, m_maincpu, MULTI32_CLOCK/2);
m_maincpu->set_addrmap(AS_PROGRAM, &sega_multi32_state::multi32_map);
m_maincpu->set_vblank_int("screen", FUNC(segas32_state::start_of_vblank_int));
Z80(config, m_soundcpu, MASTER_CLOCK/4);
m_soundcpu->set_addrmap(AS_PROGRAM, &sega_multi32_state::multi32_sound_map);
m_soundcpu->set_addrmap(AS_IO, &sega_multi32_state::multi32_sound_portmap);
sega_315_5296_device &io_chip_0(SEGA_315_5296(config, "io_chip_0", 0)); // unknown clock
io_chip_0.in_pa_callback().set_ioport("P1_A");
io_chip_0.in_pb_callback().set_ioport("P2_A");
io_chip_0.in_pc_callback().set_ioport("PORTC_A");
io_chip_0.out_pd_callback().set(FUNC(segas32_state::misc_output_0_w));
io_chip_0.in_pe_callback().set_ioport("SERVICE12_A");
io_chip_0.in_pf_callback().set_ioport("SERVICE34_A");
io_chip_0.out_pg_callback().set(FUNC(segas32_state::sw2_output_0_w));
io_chip_0.out_ph_callback().set(FUNC(segas32_state::tilebank_external_w));
io_chip_0.out_cnt1_callback().set(FUNC(segas32_state::display_enable_w<0>));
io_chip_0.out_cnt2_callback().set_inputline(m_soundcpu, INPUT_LINE_RESET).invert();
sega_315_5296_device &io_chip_1(SEGA_315_5296(config, "io_chip_1", 0)); // unknown clock
io_chip_1.in_pa_callback().set_ioport("P1_B");
io_chip_1.in_pb_callback().set_ioport("P2_B");
io_chip_1.in_pc_callback().set_ioport("PORTC_B");
io_chip_1.out_pd_callback().set(FUNC(segas32_state::misc_output_1_w));
io_chip_1.in_pe_callback().set_ioport("SERVICE12_B");
io_chip_1.in_pf_callback().set_ioport("SERVICE34_B");
io_chip_1.out_pg_callback().set(FUNC(segas32_state::sw2_output_1_w));
io_chip_1.out_ph_callback().set("eeprom", FUNC(eeprom_serial_93cxx_device::di_write)).bit(7);
io_chip_1.out_ph_callback().append("eeprom", FUNC(eeprom_serial_93cxx_device::cs_write)).bit(5);
io_chip_1.out_ph_callback().append("eeprom", FUNC(eeprom_serial_93cxx_device::clk_write)).bit(6);
io_chip_1.out_cnt1_callback().set(FUNC(segas32_state::display_enable_w<1>));
EEPROM_93C46_16BIT(config, "eeprom");
TIMER(config, "v60_irq0").configure_generic(FUNC(segas32_state::signal_v60_irq_callback));
TIMER(config, "v60_irq1").configure_generic(FUNC(segas32_state::signal_v60_irq_callback));
/* video hardware */
GFXDECODE(config, m_gfxdecode, m_palette, gfx_segas32);
PALETTE(config, m_palette).set_entries(0x8000);
config.set_default_layout(layout_dualhsxs);
SCREEN(config, m_screen, SCREEN_TYPE_RASTER);
m_screen->set_refresh_hz(60);
m_screen->set_size(52*8, 262);
m_screen->set_visarea(0*8, 52*8-1, 0*8, 28*8-1);
m_screen->set_screen_update(FUNC(segas32_state::screen_update_multi32_left));
screen_device &screen2(SCREEN(config, "screen2", SCREEN_TYPE_RASTER));
screen2.set_refresh_hz(60);
screen2.set_size(52*8, 262);
screen2.set_visarea(0*8, 52*8-1, 0*8, 28*8-1);
screen2.set_screen_update(FUNC(segas32_state::screen_update_multi32_right));
/* sound hardware */
SPEAKER(config, "lspeaker").front_left();
SPEAKER(config, "rspeaker").front_right();
ym3438_device &ymsnd(YM3438(config, "ymsnd", MASTER_CLOCK/4));
ymsnd.irq_handler().set(FUNC(segas32_state::ym3438_irq_handler));
ymsnd.add_route(1, "lspeaker", 0.40);
ymsnd.add_route(0, "rspeaker", 0.40);
MULTIPCM(config, m_multipcm, MULTI32_CLOCK/4);
m_multipcm->set_addrmap(0, &sega_multi32_state::multipcm_map);
m_multipcm->add_route(1, "lspeaker", 1.0);
m_multipcm->add_route(0, "rspeaker", 1.0);
S32COMM(config, m_s32comm, 0);
}
DEFINE_DEVICE_TYPE(SEGA_MULTI32_DEVICE, sega_multi32_state, "segas32_pcb_multi", "Sega Multi 32")
sega_multi32_state::sega_multi32_state(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: sega_multi32_state(mconfig, SEGA_MULTI32_DEVICE, tag, owner, clock)
{
}
sega_multi32_state::sega_multi32_state(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock)
: segas32_state(mconfig, type, tag, owner, clock, true)
{
}
void sega_multi32_analog_state::multi32_analog_map(address_map &map)
{
map.unmap_value_high();
map.global_mask(0xffffff);
multi32_map(map);
map(0xc00050, 0xc00057).mirror(0x07ff80).rw("adc", FUNC(msm6253_device::d7_r), FUNC(msm6253_device::address_w)).umask32(0x00ff00ff);
map(0xc00060, 0xc00060).mirror(0x07ff80).w(FUNC(sega_multi32_analog_state::analog_bank_w));
}
void sega_multi32_analog_state::device_add_mconfig(machine_config &config)
{
sega_multi32_state::device_add_mconfig(config);
m_maincpu->set_addrmap(AS_PROGRAM, &sega_multi32_analog_state::multi32_analog_map);
msm6253_device &adc(MSM6253(config, "adc", 0));
adc.set_input_tag<0>("ANALOG1");
adc.set_input_tag<1>("ANALOG2");
adc.set_input_cb<2>(FUNC(sega_multi32_analog_state::in2_analog_read));
adc.set_input_cb<3>(FUNC(sega_multi32_analog_state::in3_analog_read));
}
ioport_value sega_multi32_analog_state::in2_analog_read()
{
return m_analog_ports[m_analog_bank * 4 + 2].read_safe(0);
}
ioport_value sega_multi32_analog_state::in3_analog_read()
{
return m_analog_ports[m_analog_bank * 4 + 3].read_safe(0);
}
void sega_multi32_analog_state::analog_bank_w(uint8_t data)
{
m_analog_bank = data & 1;
}
DEFINE_DEVICE_TYPE(SEGA_MULTI32_ANALOG_DEVICE, sega_multi32_analog_state, "segas32_pcb_multi_analog", "Sega Multi 32 analog PCB")
sega_multi32_analog_state::sega_multi32_analog_state(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: sega_multi32_state(mconfig, SEGA_MULTI32_ANALOG_DEVICE, tag, owner, clock)
, m_analog_ports(*this, "ANALOG%u", 1)
, m_analog_bank(0)
{
}
void segas32_state::multi32_6player_map(address_map &map)
{
map.unmap_value_high();
map.global_mask(0xffffff);
multi32_map(map);
map(0xc00060, 0xc00067).mirror(0x07ff80).rw("ppi", FUNC(i8255_device::read), FUNC(i8255_device::write)).umask32(0x00ff00ff);
}
void sega_multi32_6player_state::device_add_mconfig(machine_config &config)
{
sega_multi32_state::device_add_mconfig(config);
m_maincpu->set_addrmap(AS_PROGRAM, &sega_multi32_6player_state::multi32_6player_map);
i8255_device &ppi(I8255A(config, "ppi"));
ppi.in_pa_callback().set_ioport("EXTRA1");
ppi.in_pb_callback().set_ioport("EXTRA2");
ppi.in_pc_callback().set_ioport("EXTRA3");
}
DEFINE_DEVICE_TYPE(SEGA_MULTI32_6PLAYER_DEVICE, sega_multi32_6player_state, "segas32_pcb_multi_6player", "Sega Multi 32 6-player PCB")
sega_multi32_6player_state::sega_multi32_6player_state(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: sega_multi32_state(mconfig, SEGA_MULTI32_6PLAYER_DEVICE, tag, owner, clock)
{
}
class segas32_new_state : public driver_device
{
public:
segas32_new_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag)
, m_mainpcb(*this, "mainpcb")
, m_slavepcb(*this, "slavepcb")
{ }
void sega_multi32(machine_config &config);
void sega_system32(machine_config &config);
void sega_multi32_analog(machine_config &config);
void sega_multi32_6p(machine_config &config);
void sega_system32_dual_direct_upd7725(machine_config &config);
void sega_system32_dual_direct(machine_config &config);
void sega_system32_track(machine_config &config);
void sega_system32_ga2(machine_config &config);
void sega_system32_cd(machine_config &config);
void sega_system32_arf(machine_config &config);
void sega_system32_analog(machine_config &config);
void sega_system32_4p(machine_config &config);
void init_titlef();
void init_slipstrm();
void init_radm();
void init_holo();
void init_svf();
void init_jleague();
void init_arescue();
void init_jpark();
void init_ga2();
void init_scross();
void init_spidman();
void init_sonicp();
void init_f1en();
void init_dbzvrvs();
void init_brival();
void init_harddunk();
void init_arabfgt();
void init_sonic();
void init_alien3();
void init_darkedge();
void init_radr();
void init_f1lap();
void init_f1lapt();
void init_orunners();
private:
required_device<segas32_state> m_mainpcb;
optional_device<segas32_state> m_slavepcb;
std::unique_ptr<uint16_t[]> m_dual_pcb_comms;
void dual_pcb_comms_w(offs_t offset, uint16_t data, uint16_t mem_mask = ~0);
uint16_t dual_pcb_comms_r(offs_t offset);
uint16_t dual_pcb_masterslave();
uint16_t dual_pcb_slave();
};
void segas32_new_state::sega_system32(machine_config &config)
{
SEGA_S32_REGULAR_DEVICE(config, "mainpcb", 0);
}
void segas32_new_state::sega_system32_analog(machine_config &config)
{
SEGA_S32_ANALOG_DEVICE(config, "mainpcb", 0);
}
void segas32_new_state::sega_system32_track(machine_config &config)
{
SEGA_S32_TRACKBALL_DEVICE(config, "mainpcb", 0);
}
void segas32_new_state::sega_system32_4p(machine_config &config)
{
SEGA_S32_4PLAYER_DEVICE(config, "mainpcb", 0);
}
void segas32_new_state::sega_system32_cd(machine_config &config)
{
SEGA_S32_CD_DEVICE(config, "mainpcb", 0);
}
// for f1en where there is a sub-board containing shared ram sitting underneath the ROM board bridging 2 PCBs (not a network link)
void segas32_new_state::sega_system32_dual_direct(machine_config &config)
{
SEGA_S32_ANALOG_DEVICE(config, "mainpcb", 0);
SEGA_S32_ANALOG_DEVICE(config, "slavepcb", 0);
}
// air rescue is like f1en above but also has the 837-8341 DSP daughterboard on the mainpcb side only
void segas32_new_state::sega_system32_dual_direct_upd7725(machine_config &config)
{
SEGA_S32_UPD7725_DEVICE(config, "mainpcb", 0);
SEGA_S32_ANALOG_DEVICE(config, "slavepcb", 0);
}
void segas32_new_state::sega_system32_ga2(machine_config &config)
{
SEGA_S32_V25_DEVICE(config, "mainpcb", 0);
subdevice<v25_common_device>("mainpcb:mcu")->set_decryption_table(segas32_v25_state::ga2_opcode_table);
}
void segas32_new_state::sega_system32_arf(machine_config &config)
{
SEGA_S32_V25_DEVICE(config, "mainpcb", 0);
subdevice<v25_common_device>("mainpcb:mcu")->set_decryption_table(segas32_v25_state::arf_opcode_table);
}
void segas32_new_state::sega_multi32(machine_config &config)
{
SEGA_MULTI32_DEVICE(config, "mainpcb", 0);
}
void segas32_new_state::sega_multi32_analog(machine_config &config)
{
SEGA_MULTI32_ANALOG_DEVICE(config, "mainpcb", 0);
}
void segas32_new_state::sega_multi32_6p(machine_config &config)
{
SEGA_MULTI32_6PLAYER_DEVICE(config, "mainpcb", 0);
}
/*************************************
*
* ROM definition(s)
*
*************************************/
#define ROM_LOAD_x2(name, base, length, crc) \
ROM_LOAD( name, base + 0 * length, length, crc ) \
ROM_RELOAD( base + 1 * length, length )
#define ROM_LOAD_x4(name, base, length, crc) \
ROM_LOAD( name, base + 0 * length, length, crc ) \
ROM_RELOAD( base + 1 * length, length ) \
ROM_RELOAD( base + 2 * length, length ) \
ROM_RELOAD( base + 3 * length, length )
#define ROM_LOAD_x8(name, base, length, crc) \
ROM_LOAD( name, base + 0 * length, length, crc ) \
ROM_RELOAD( base + 1 * length, length ) \
ROM_RELOAD( base + 2 * length, length ) \
ROM_RELOAD( base + 3 * length, length ) \
ROM_RELOAD( base + 4 * length, length ) \
ROM_RELOAD( base + 5 * length, length ) \
ROM_RELOAD( base + 6 * length, length ) \
ROM_RELOAD( base + 7 * length, length )
#define ROM_LOAD_x16(name, base, length, crc) \
ROM_LOAD( name, base + 0 * length, length, crc ) \
ROM_RELOAD( base + 1 * length, length ) \
ROM_RELOAD( base + 2 * length, length ) \
ROM_RELOAD( base + 3 * length, length ) \
ROM_RELOAD( base + 4 * length, length ) \
ROM_RELOAD( base + 5 * length, length ) \
ROM_RELOAD( base + 6 * length, length ) \
ROM_RELOAD( base + 7 * length, length ) \
ROM_RELOAD( base + 8 * length, length ) \
ROM_RELOAD( base + 9 * length, length ) \
ROM_RELOAD( base + 10 * length, length ) \
ROM_RELOAD( base + 11 * length, length ) \
ROM_RELOAD( base + 12 * length, length ) \
ROM_RELOAD( base + 13 * length, length ) \
ROM_RELOAD( base + 14 * length, length ) \
ROM_RELOAD( base + 15 * length, length )
#define ROM_LOAD16_BYTE_x2(name, base, length, crc) \
ROM_LOAD16_BYTE( name, base + 0 * length, length, crc ) \
ROM_RELOAD( base + 2 * length, length )
#define ROM_LOAD16_BYTE_x4(name, base, length, crc) \
ROM_LOAD16_BYTE( name, base + 0 * length, length, crc ) \
ROM_RELOAD( base + 2 * length, length ) \
ROM_RELOAD( base + 4 * length, length ) \
ROM_RELOAD( base + 6 * length, length )
#define ROM_LOAD32_WORD_x2(name, base, length, crc) \
ROM_LOAD32_WORD( name, base + 0 * length, length, crc ) \
ROM_RELOAD( base + 2 * length, length )
#define ROM_LOAD32_WORD_x4(name, base, length, crc) \
ROM_LOAD32_WORD( name, base + 0 * length, length, crc ) \
ROM_RELOAD( base + 2 * length, length ) \
ROM_RELOAD( base + 4 * length, length ) \
ROM_RELOAD( base + 6 * length, length )
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Air Rescue (Export)
Sega Game ID codes:
Game BD: 833-8508-01 AIR RESCUE (US)
833-8508-02 AIR RESCUE (Export)
833-8508-03 AIR RESCUE (Japan)
ROM PCB No: 834-8526-01 (US)
834-8526-02 (Export)
834-8526-03 (Japan)
834-8526-05 (Export, had the DSP 837-8341 board attached)
Link PCB No: 837-8223-01
A/D BD No: 837-7536 (one for each mainboard)
DSP BD No: 837-8341
requires 2 linked system32 pcbs
requires additional math DSP to be emulated
The link PCB attaches 2 System 32 mainboards together, then ROM boards for each mainboard attaches to the link PCB.
This provides a direct connection between the PCBs (NOT a network link) so they effectively operate as a single boardset
sharing RAM (we should emulate it as such)
Link PCB is a single sparsely populated ROMless PCB but contains
Left side
1x MB8431-12LP (IC2)
2x HD74LS74AP (IC6, IC7)
2x GAL16V8A-25LP (stamped 315-5545) (IC3)
Right side
1x MB8421-12LP (IC1)
1x GAL16V8A-25LP (stamped xxx-xxxx) (IC5)
1x HD74LS74AP (IC8)
1x GAL16V8A-25LP (stamped 315-5545) (IC4)
(todo, full layout)
The left ROM PCB (master?) contains a sub-board on the ROM board with the math DSP, the right ROM PCB does not have this.
*/
ROM_START( arescue )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14542.ic13", 0x000000, 0x020000, CRC(6d39fc18) SHA1(7fbddfb2605a020331e1e81a7bc4466196df17bd) ) /* 834-8526-05 (Export) */
ROM_LOAD_x4( "epr-14541.ic6", 0x080000, 0x020000, CRC(5c3f2ec5) SHA1(d11a24d12917e4c5ac9010ca6db0f1ac9d44475a) )
ROM_LOAD16_BYTE( "epr-14509.ic14", 0x100000, 0x080000, CRC(daa5a356) SHA1(ca87242c59de5ab5f9406635bee758a855fe20bc) )
ROM_LOAD16_BYTE( "epr-14508.ic7", 0x100001, 0x080000, CRC(6702c14d) SHA1(dc9324f16a3e3238f5ccdade9451d6823a50b563) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-14513.ic35", 0x000000, 0x40000, CRC(f9a884cd) SHA1(73010fff5e0257355e08e78838c74af86ed364ce) )
ROM_LOAD_x2( "mpr-14512.ic31", 0x100000, 0x80000, CRC(9da48051) SHA1(2d41148d089a75362ed0fde577eca919213ac666) )
ROM_LOAD_x2( "mpr-14511.ic26", 0x200000, 0x80000, CRC(074c53cc) SHA1(9c89843bbe8058123c25b7f8f86de754ddbca2bb) )
ROM_LOAD_x2( "mpr-14510.ic22", 0x300000, 0x80000, CRC(5ea6d52d) SHA1(d424082468940bb91ab424ac7812839792ed4e88) )
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14496.ic25", 0x000003, 0x080000, CRC(737da16c) SHA1(52247d9bc2924e90d040bef484a541b1f4a9026f) )
ROM_LOAD32_BYTE( "mpr-14497.ic29", 0x000001, 0x080000, CRC(ebd7ed17) SHA1(2307dc28501965432d2ff55a21698efdce014401) )
ROM_LOAD32_BYTE( "mpr-14498.ic34", 0x000002, 0x080000, CRC(d4a764bd) SHA1(8434a9225ed1e01e8b1cfe169268e42cd3ce6ee3) )
ROM_LOAD32_BYTE( "mpr-14499.ic38", 0x000000, 0x080000, CRC(fadc4b2b) SHA1(01c02a4dfad1ab19bac8b81b61d37fdc035bc5c5) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14500.ic24", 0x000007, 0x100000, CRC(0a064e9b) SHA1(264761f4aacaeeac9426528caf180404cd7f6e18) )
ROM_LOAD64_BYTE( "mpr-14501.ic28", 0x000006, 0x100000, CRC(4662bb41) SHA1(80774e680468e9ba9c5dd5eeaa4791fa3b3722fd) )
ROM_LOAD64_BYTE( "mpr-14502.ic33", 0x000005, 0x100000, CRC(988555a9) SHA1(355e44319fd51358329cc7cd226e4c4725e045cb) )
ROM_LOAD64_BYTE( "mpr-14503.ic37", 0x000004, 0x100000, CRC(90556aca) SHA1(24df62af55048db66d50c7034c5460330d231bf5) )
ROM_LOAD64_BYTE( "mpr-14504.ic23", 0x000003, 0x100000, CRC(46dd038d) SHA1(9530a52e2e7388437c20ebcb19bf84c8b3b5086b) )
ROM_LOAD64_BYTE( "mpr-14505.ic27", 0x000002, 0x100000, CRC(be142c1f) SHA1(224631e00c2458c39c6a2ef7978c2b1131fb4da2) )
ROM_LOAD64_BYTE( "mpr-14506.ic32", 0x000001, 0x100000, CRC(5dd8fb6b) SHA1(7d21cacb2c9dba5db2547b6d8e89397e0424ee8e) )
ROM_LOAD64_BYTE( "mpr-14507.ic36", 0x000000, 0x100000, CRC(db3f59ec) SHA1(96dcb3827354773fc2911c62260a27e90dcbe96a) )
ROM_REGION( 0x20000, "mainpcb:dsp", 0 ) /* NEC uPD77P25 DSP Internal ROM */ // ONLY PRESENT ON ONE PCB STACK
ROM_LOAD( "d7725.01", 0x000000, 0x002800, CRC(a7ec5644) SHA1(e9b05c70b639ee289e557dfd9a6c724b36338e2b) )
ROM_REGION32_BE(0x2000, "mainpcb:dspprg", ROMREGION_ERASEFF)
ROM_COPY( "mainpcb:dsp", 0x0000, 0x0000, 0x2000 )
ROM_REGION16_BE(0x800, "mainpcb:dspdata", ROMREGION_ERASEFF)
ROM_COPY( "mainpcb:dsp", 0x2000, 0x0000, 0x0800 )
ROM_REGION( 0x200000, "slavepcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14542.ic13", 0x000000, 0x020000, CRC(6d39fc18) SHA1(7fbddfb2605a020331e1e81a7bc4466196df17bd) ) /* 834-8526-05 (Export) */
ROM_LOAD_x4( "epr-14541.ic6", 0x080000, 0x020000, CRC(5c3f2ec5) SHA1(d11a24d12917e4c5ac9010ca6db0f1ac9d44475a) )
ROM_LOAD16_BYTE( "epr-14509.ic14", 0x100000, 0x080000, CRC(daa5a356) SHA1(ca87242c59de5ab5f9406635bee758a855fe20bc) )
ROM_LOAD16_BYTE( "epr-14508.ic7", 0x100001, 0x080000, CRC(6702c14d) SHA1(dc9324f16a3e3238f5ccdade9451d6823a50b563) )
ROM_REGION( 0x400000, "slavepcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-14513.ic35", 0x000000, 0x40000, CRC(f9a884cd) SHA1(73010fff5e0257355e08e78838c74af86ed364ce) )
ROM_LOAD_x2( "mpr-14512.ic31", 0x100000, 0x80000, CRC(9da48051) SHA1(2d41148d089a75362ed0fde577eca919213ac666) )
ROM_LOAD_x2( "mpr-14511.ic26", 0x200000, 0x80000, CRC(074c53cc) SHA1(9c89843bbe8058123c25b7f8f86de754ddbca2bb) )
ROM_LOAD_x2( "mpr-14510.ic22", 0x300000, 0x80000, CRC(5ea6d52d) SHA1(d424082468940bb91ab424ac7812839792ed4e88) )
ROM_REGION( 0x200000, "slavepcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14496.ic25", 0x000003, 0x080000, CRC(737da16c) SHA1(52247d9bc2924e90d040bef484a541b1f4a9026f) )
ROM_LOAD32_BYTE( "mpr-14497.ic29", 0x000001, 0x080000, CRC(ebd7ed17) SHA1(2307dc28501965432d2ff55a21698efdce014401) )
ROM_LOAD32_BYTE( "mpr-14498.ic34", 0x000002, 0x080000, CRC(d4a764bd) SHA1(8434a9225ed1e01e8b1cfe169268e42cd3ce6ee3) )
ROM_LOAD32_BYTE( "mpr-14499.ic38", 0x000000, 0x080000, CRC(fadc4b2b) SHA1(01c02a4dfad1ab19bac8b81b61d37fdc035bc5c5) )
ROM_REGION32_BE( 0x800000, "slavepcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14500.ic24", 0x000007, 0x100000, CRC(0a064e9b) SHA1(264761f4aacaeeac9426528caf180404cd7f6e18) )
ROM_LOAD64_BYTE( "mpr-14501.ic28", 0x000006, 0x100000, CRC(4662bb41) SHA1(80774e680468e9ba9c5dd5eeaa4791fa3b3722fd) )
ROM_LOAD64_BYTE( "mpr-14502.ic33", 0x000005, 0x100000, CRC(988555a9) SHA1(355e44319fd51358329cc7cd226e4c4725e045cb) )
ROM_LOAD64_BYTE( "mpr-14503.ic37", 0x000004, 0x100000, CRC(90556aca) SHA1(24df62af55048db66d50c7034c5460330d231bf5) )
ROM_LOAD64_BYTE( "mpr-14504.ic23", 0x000003, 0x100000, CRC(46dd038d) SHA1(9530a52e2e7388437c20ebcb19bf84c8b3b5086b) )
ROM_LOAD64_BYTE( "mpr-14505.ic27", 0x000002, 0x100000, CRC(be142c1f) SHA1(224631e00c2458c39c6a2ef7978c2b1131fb4da2) )
ROM_LOAD64_BYTE( "mpr-14506.ic32", 0x000001, 0x100000, CRC(5dd8fb6b) SHA1(7d21cacb2c9dba5db2547b6d8e89397e0424ee8e) )
ROM_LOAD64_BYTE( "mpr-14507.ic36", 0x000000, 0x100000, CRC(db3f59ec) SHA1(96dcb3827354773fc2911c62260a27e90dcbe96a) )
ROM_END
/**************************************************************************************************************************
Air Rescue (US)
Sega Game ID codes:
Game BD: 833-8508-01 AIR RESCUE
ROM PCB No: 834-8526-01
Link PCB No: 837-8223-01
A/D BD No: 837-7536 (one for each mainboard)
DSP BD No: 837-8341
requires 2 linked system32 pcbs
requires additional math DSP to be emulated
*/
ROM_START( arescueu )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14540.ic13", 0x000000, 0x020000, CRC(c2b4e5d0) SHA1(69f8ddded5095df9012663d0ded61b78f1692a8d) )
ROM_LOAD_x4( "epr-14539.ic6", 0x080000, 0x020000, CRC(1a1b5532) SHA1(f3651470222036703b7ecedb6e91e4cdb3d20df7) )
ROM_LOAD16_BYTE( "epr-14509.ic14", 0x100000, 0x080000, CRC(daa5a356) SHA1(ca87242c59de5ab5f9406635bee758a855fe20bc) )
ROM_LOAD16_BYTE( "epr-14508.ic7", 0x100001, 0x080000, CRC(6702c14d) SHA1(dc9324f16a3e3238f5ccdade9451d6823a50b563) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-14513.ic35", 0x000000, 0x40000, CRC(f9a884cd) SHA1(73010fff5e0257355e08e78838c74af86ed364ce) )
ROM_LOAD_x2( "mpr-14512.ic31", 0x100000, 0x80000, CRC(9da48051) SHA1(2d41148d089a75362ed0fde577eca919213ac666) )
ROM_LOAD_x2( "mpr-14511.ic26", 0x200000, 0x80000, CRC(074c53cc) SHA1(9c89843bbe8058123c25b7f8f86de754ddbca2bb) )
ROM_LOAD_x2( "mpr-14510.ic22", 0x300000, 0x80000, CRC(5ea6d52d) SHA1(d424082468940bb91ab424ac7812839792ed4e88) )
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14496.ic25", 0x000003, 0x080000, CRC(737da16c) SHA1(52247d9bc2924e90d040bef484a541b1f4a9026f) )
ROM_LOAD32_BYTE( "mpr-14497.ic29", 0x000001, 0x080000, CRC(ebd7ed17) SHA1(2307dc28501965432d2ff55a21698efdce014401) )
ROM_LOAD32_BYTE( "mpr-14498.ic34", 0x000002, 0x080000, CRC(d4a764bd) SHA1(8434a9225ed1e01e8b1cfe169268e42cd3ce6ee3) )
ROM_LOAD32_BYTE( "mpr-14499.ic38", 0x000000, 0x080000, CRC(fadc4b2b) SHA1(01c02a4dfad1ab19bac8b81b61d37fdc035bc5c5) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14500.ic24", 0x000007, 0x100000, CRC(0a064e9b) SHA1(264761f4aacaeeac9426528caf180404cd7f6e18) )
ROM_LOAD64_BYTE( "mpr-14501.ic28", 0x000006, 0x100000, CRC(4662bb41) SHA1(80774e680468e9ba9c5dd5eeaa4791fa3b3722fd) )
ROM_LOAD64_BYTE( "mpr-14502.ic33", 0x000005, 0x100000, CRC(988555a9) SHA1(355e44319fd51358329cc7cd226e4c4725e045cb) )
ROM_LOAD64_BYTE( "mpr-14503.ic37", 0x000004, 0x100000, CRC(90556aca) SHA1(24df62af55048db66d50c7034c5460330d231bf5) )
ROM_LOAD64_BYTE( "mpr-14504.ic23", 0x000003, 0x100000, CRC(46dd038d) SHA1(9530a52e2e7388437c20ebcb19bf84c8b3b5086b) )
ROM_LOAD64_BYTE( "mpr-14505.ic27", 0x000002, 0x100000, CRC(be142c1f) SHA1(224631e00c2458c39c6a2ef7978c2b1131fb4da2) )
ROM_LOAD64_BYTE( "mpr-14506.ic32", 0x000001, 0x100000, CRC(5dd8fb6b) SHA1(7d21cacb2c9dba5db2547b6d8e89397e0424ee8e) )
ROM_LOAD64_BYTE( "mpr-14507.ic36", 0x000000, 0x100000, CRC(db3f59ec) SHA1(96dcb3827354773fc2911c62260a27e90dcbe96a) )
ROM_REGION( 0x20000, "mainpcb:dsp", 0 ) /* NEC uPD77P25 DSP Internal ROM */ // ONLY PRESENT ON ONE PCB STACK
ROM_LOAD( "d7725.01", 0x000000, 0x002800, CRC(a7ec5644) SHA1(e9b05c70b639ee289e557dfd9a6c724b36338e2b) )
ROM_REGION32_BE(0x2000, "mainpcb:dspprg", ROMREGION_ERASEFF)
ROM_COPY( "mainpcb:dsp", 0x0000, 0x0000, 0x2000 )
ROM_REGION16_BE(0x800, "mainpcb:dspdata", ROMREGION_ERASEFF)
ROM_COPY( "mainpcb:dsp", 0x2000, 0x0000, 0x0800 )
ROM_REGION( 0x200000, "slavepcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14540.ic13", 0x000000, 0x020000, CRC(c2b4e5d0) SHA1(69f8ddded5095df9012663d0ded61b78f1692a8d) )
ROM_LOAD_x4( "epr-14539.ic6", 0x080000, 0x020000, CRC(1a1b5532) SHA1(f3651470222036703b7ecedb6e91e4cdb3d20df7) )
ROM_LOAD16_BYTE( "epr-14509.ic14", 0x100000, 0x080000, CRC(daa5a356) SHA1(ca87242c59de5ab5f9406635bee758a855fe20bc) )
ROM_LOAD16_BYTE( "epr-14508.ic7", 0x100001, 0x080000, CRC(6702c14d) SHA1(dc9324f16a3e3238f5ccdade9451d6823a50b563) )
ROM_REGION( 0x400000, "slavepcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-14513.ic35", 0x000000, 0x40000, CRC(f9a884cd) SHA1(73010fff5e0257355e08e78838c74af86ed364ce) )
ROM_LOAD_x2( "mpr-14512.ic31", 0x100000, 0x80000, CRC(9da48051) SHA1(2d41148d089a75362ed0fde577eca919213ac666) )
ROM_LOAD_x2( "mpr-14511.ic26", 0x200000, 0x80000, CRC(074c53cc) SHA1(9c89843bbe8058123c25b7f8f86de754ddbca2bb) )
ROM_LOAD_x2( "mpr-14510.ic22", 0x300000, 0x80000, CRC(5ea6d52d) SHA1(d424082468940bb91ab424ac7812839792ed4e88) )
ROM_REGION( 0x200000, "slavepcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14496.ic25", 0x000003, 0x080000, CRC(737da16c) SHA1(52247d9bc2924e90d040bef484a541b1f4a9026f) )
ROM_LOAD32_BYTE( "mpr-14497.ic29", 0x000001, 0x080000, CRC(ebd7ed17) SHA1(2307dc28501965432d2ff55a21698efdce014401) )
ROM_LOAD32_BYTE( "mpr-14498.ic34", 0x000002, 0x080000, CRC(d4a764bd) SHA1(8434a9225ed1e01e8b1cfe169268e42cd3ce6ee3) )
ROM_LOAD32_BYTE( "mpr-14499.ic38", 0x000000, 0x080000, CRC(fadc4b2b) SHA1(01c02a4dfad1ab19bac8b81b61d37fdc035bc5c5) )
ROM_REGION32_BE( 0x800000, "slavepcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14500.ic24", 0x000007, 0x100000, CRC(0a064e9b) SHA1(264761f4aacaeeac9426528caf180404cd7f6e18) )
ROM_LOAD64_BYTE( "mpr-14501.ic28", 0x000006, 0x100000, CRC(4662bb41) SHA1(80774e680468e9ba9c5dd5eeaa4791fa3b3722fd) )
ROM_LOAD64_BYTE( "mpr-14502.ic33", 0x000005, 0x100000, CRC(988555a9) SHA1(355e44319fd51358329cc7cd226e4c4725e045cb) )
ROM_LOAD64_BYTE( "mpr-14503.ic37", 0x000004, 0x100000, CRC(90556aca) SHA1(24df62af55048db66d50c7034c5460330d231bf5) )
ROM_LOAD64_BYTE( "mpr-14504.ic23", 0x000003, 0x100000, CRC(46dd038d) SHA1(9530a52e2e7388437c20ebcb19bf84c8b3b5086b) )
ROM_LOAD64_BYTE( "mpr-14505.ic27", 0x000002, 0x100000, CRC(be142c1f) SHA1(224631e00c2458c39c6a2ef7978c2b1131fb4da2) )
ROM_LOAD64_BYTE( "mpr-14506.ic32", 0x000001, 0x100000, CRC(5dd8fb6b) SHA1(7d21cacb2c9dba5db2547b6d8e89397e0424ee8e) )
ROM_LOAD64_BYTE( "mpr-14507.ic36", 0x000000, 0x100000, CRC(db3f59ec) SHA1(96dcb3827354773fc2911c62260a27e90dcbe96a) )
ROM_END
/**************************************************************************************************************************
Air Rescue (Japan)
Sega Game ID codes:
Game BD: 833-8508-03 AIR RESCUE
ROM PCB No: 834-8526-03
Link PCB No: 837-8223-01
A/D BD No: 837-7536 (one for each mainboard)
DSP BD No: 837-8341
requires 2 linked system32 pcbs
requires additional math DSP to be emulated
*/
ROM_START( arescuej )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14515.ic13", 0x000000, 0x020000, CRC(fb5eefbd) SHA1(f2739ad2e168843fe992d7fb546ffd859fa6c17a) )
ROM_LOAD_x4( "epr-14514.ic6", 0x080000, 0x020000, CRC(ebf6dfc5) SHA1(2146dc23f1268124b6ad3cd00416a71fc56130bf) )
ROM_LOAD16_BYTE( "epr-14509.ic14", 0x100000, 0x080000, CRC(daa5a356) SHA1(ca87242c59de5ab5f9406635bee758a855fe20bc) )
ROM_LOAD16_BYTE( "epr-14508.ic7", 0x100001, 0x080000, CRC(6702c14d) SHA1(dc9324f16a3e3238f5ccdade9451d6823a50b563) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-14513.ic35", 0x000000, 0x40000, CRC(f9a884cd) SHA1(73010fff5e0257355e08e78838c74af86ed364ce) )
ROM_LOAD_x2( "mpr-14512.ic31", 0x100000, 0x80000, CRC(9da48051) SHA1(2d41148d089a75362ed0fde577eca919213ac666) )
ROM_LOAD_x2( "mpr-14511.ic26", 0x200000, 0x80000, CRC(074c53cc) SHA1(9c89843bbe8058123c25b7f8f86de754ddbca2bb) )
ROM_LOAD_x2( "mpr-14510.ic22", 0x300000, 0x80000, CRC(5ea6d52d) SHA1(d424082468940bb91ab424ac7812839792ed4e88) )
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14496.ic25", 0x000003, 0x080000, CRC(737da16c) SHA1(52247d9bc2924e90d040bef484a541b1f4a9026f) )
ROM_LOAD32_BYTE( "mpr-14497.ic29", 0x000001, 0x080000, CRC(ebd7ed17) SHA1(2307dc28501965432d2ff55a21698efdce014401) )
ROM_LOAD32_BYTE( "mpr-14498.ic34", 0x000002, 0x080000, CRC(d4a764bd) SHA1(8434a9225ed1e01e8b1cfe169268e42cd3ce6ee3) )
ROM_LOAD32_BYTE( "mpr-14499.ic38", 0x000000, 0x080000, CRC(fadc4b2b) SHA1(01c02a4dfad1ab19bac8b81b61d37fdc035bc5c5) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14500.ic24", 0x000007, 0x100000, CRC(0a064e9b) SHA1(264761f4aacaeeac9426528caf180404cd7f6e18) )
ROM_LOAD64_BYTE( "mpr-14501.ic28", 0x000006, 0x100000, CRC(4662bb41) SHA1(80774e680468e9ba9c5dd5eeaa4791fa3b3722fd) )
ROM_LOAD64_BYTE( "mpr-14502.ic33", 0x000005, 0x100000, CRC(988555a9) SHA1(355e44319fd51358329cc7cd226e4c4725e045cb) )
ROM_LOAD64_BYTE( "mpr-14503.ic37", 0x000004, 0x100000, CRC(90556aca) SHA1(24df62af55048db66d50c7034c5460330d231bf5) )
ROM_LOAD64_BYTE( "mpr-14504.ic23", 0x000003, 0x100000, CRC(46dd038d) SHA1(9530a52e2e7388437c20ebcb19bf84c8b3b5086b) )
ROM_LOAD64_BYTE( "mpr-14505.ic27", 0x000002, 0x100000, CRC(be142c1f) SHA1(224631e00c2458c39c6a2ef7978c2b1131fb4da2) )
ROM_LOAD64_BYTE( "mpr-14506.ic32", 0x000001, 0x100000, CRC(5dd8fb6b) SHA1(7d21cacb2c9dba5db2547b6d8e89397e0424ee8e) )
ROM_LOAD64_BYTE( "mpr-14507.ic36", 0x000000, 0x100000, CRC(db3f59ec) SHA1(96dcb3827354773fc2911c62260a27e90dcbe96a) )
ROM_REGION( 0x20000, "mainpcb:dsp", 0 ) /* NEC uPD77P25 DSP Internal ROM */ // ONLY PRESENT ON ONE PCB STACK
ROM_LOAD( "d7725.01", 0x000000, 0x002800, CRC(a7ec5644) SHA1(e9b05c70b639ee289e557dfd9a6c724b36338e2b) )
ROM_REGION32_BE(0x2000, "mainpcb:dspprg", ROMREGION_ERASEFF)
ROM_COPY( "mainpcb:dsp", 0x0000, 0x0000, 0x2000 )
ROM_REGION16_BE(0x800, "mainpcb:dspdata", ROMREGION_ERASEFF)
ROM_COPY( "mainpcb:dsp", 0x2000, 0x0000, 0x0800 )
ROM_REGION( 0x200000, "slavepcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14515.ic13", 0x000000, 0x020000, CRC(fb5eefbd) SHA1(f2739ad2e168843fe992d7fb546ffd859fa6c17a) )
ROM_LOAD_x4( "epr-14514.ic6", 0x080000, 0x020000, CRC(ebf6dfc5) SHA1(2146dc23f1268124b6ad3cd00416a71fc56130bf) )
ROM_LOAD16_BYTE( "epr-14509.ic14", 0x100000, 0x080000, CRC(daa5a356) SHA1(ca87242c59de5ab5f9406635bee758a855fe20bc) )
ROM_LOAD16_BYTE( "epr-14508.ic7", 0x100001, 0x080000, CRC(6702c14d) SHA1(dc9324f16a3e3238f5ccdade9451d6823a50b563) )
ROM_REGION( 0x400000, "slavepcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-14513.ic35", 0x000000, 0x40000, CRC(f9a884cd) SHA1(73010fff5e0257355e08e78838c74af86ed364ce) )
ROM_LOAD_x2( "mpr-14512.ic31", 0x100000, 0x80000, CRC(9da48051) SHA1(2d41148d089a75362ed0fde577eca919213ac666) )
ROM_LOAD_x2( "mpr-14511.ic26", 0x200000, 0x80000, CRC(074c53cc) SHA1(9c89843bbe8058123c25b7f8f86de754ddbca2bb) )
ROM_LOAD_x2( "mpr-14510.ic22", 0x300000, 0x80000, CRC(5ea6d52d) SHA1(d424082468940bb91ab424ac7812839792ed4e88) )
ROM_REGION( 0x200000, "slavepcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14496.ic25", 0x000003, 0x080000, CRC(737da16c) SHA1(52247d9bc2924e90d040bef484a541b1f4a9026f) )
ROM_LOAD32_BYTE( "mpr-14497.ic29", 0x000001, 0x080000, CRC(ebd7ed17) SHA1(2307dc28501965432d2ff55a21698efdce014401) )
ROM_LOAD32_BYTE( "mpr-14498.ic34", 0x000002, 0x080000, CRC(d4a764bd) SHA1(8434a9225ed1e01e8b1cfe169268e42cd3ce6ee3) )
ROM_LOAD32_BYTE( "mpr-14499.ic38", 0x000000, 0x080000, CRC(fadc4b2b) SHA1(01c02a4dfad1ab19bac8b81b61d37fdc035bc5c5) )
ROM_REGION32_BE( 0x800000, "slavepcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14500.ic24", 0x000007, 0x100000, CRC(0a064e9b) SHA1(264761f4aacaeeac9426528caf180404cd7f6e18) )
ROM_LOAD64_BYTE( "mpr-14501.ic28", 0x000006, 0x100000, CRC(4662bb41) SHA1(80774e680468e9ba9c5dd5eeaa4791fa3b3722fd) )
ROM_LOAD64_BYTE( "mpr-14502.ic33", 0x000005, 0x100000, CRC(988555a9) SHA1(355e44319fd51358329cc7cd226e4c4725e045cb) )
ROM_LOAD64_BYTE( "mpr-14503.ic37", 0x000004, 0x100000, CRC(90556aca) SHA1(24df62af55048db66d50c7034c5460330d231bf5) )
ROM_LOAD64_BYTE( "mpr-14504.ic23", 0x000003, 0x100000, CRC(46dd038d) SHA1(9530a52e2e7388437c20ebcb19bf84c8b3b5086b) )
ROM_LOAD64_BYTE( "mpr-14505.ic27", 0x000002, 0x100000, CRC(be142c1f) SHA1(224631e00c2458c39c6a2ef7978c2b1131fb4da2) )
ROM_LOAD64_BYTE( "mpr-14506.ic32", 0x000001, 0x100000, CRC(5dd8fb6b) SHA1(7d21cacb2c9dba5db2547b6d8e89397e0424ee8e) )
ROM_LOAD64_BYTE( "mpr-14507.ic36", 0x000000, 0x100000, CRC(db3f59ec) SHA1(96dcb3827354773fc2911c62260a27e90dcbe96a) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Alien 3: The Gun (Export)
not protected
Sega Game ID codes:
Game BD: 834-9877-02
ROM PCB No: 837-9878-02
Main PCB: 837-7428-03 (SYSTEM 32 COM)
A/D BD NO. 837-7536
*/
ROM_START( alien3 )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x2( "epr-15943.ic17", 0x000000, 0x040000, CRC(ac4591aa) SHA1(677155a3ebdac6602525e06adb25d287eaf9e089) )
ROM_LOAD_x2( "epr-15942.ic8", 0x080000, 0x040000, CRC(a1e1d0ec) SHA1(10d8d2235a67a4ba475fe98124c6a4a5311592b5) )
ROM_LOAD16_BYTE( "mpr-15855.ic18", 0x100000, 0x080000, CRC(a6fadabe) SHA1(328bbb54651eef197ba13f1bd9228f3f4de7ee5e) )
ROM_LOAD16_BYTE( "mpr-15854.ic9", 0x100001, 0x080000, CRC(d1aec392) SHA1(f48804fe0151e83ad45e912b55db8ae8ddebd2ad) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-15859a.ic36",0x000000, 0x040000, CRC(91b55bd0) SHA1(23b85a006a91c2a5eb1cee14172fd0d8b7732518) )
ROM_LOAD( "mpr-15858.ic35", 0x100000, 0x100000, CRC(2eb64c10) SHA1(b2dbe86b82e889f4a9850cf4aa6596a139c1c3d6) )
ROM_LOAD( "mpr-15857.ic34", 0x200000, 0x100000, CRC(915c56df) SHA1(7031f937c826af17caf7ec8cbb6155d0a55bd38a) )
ROM_LOAD( "mpr-15856.ic24", 0x300000, 0x100000, CRC(a5ef4f1f) SHA1(e8da7a995955e80872a25bd75465c590b649cfab) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15863.ic14", 0x000000, 0x200000, CRC(9d36b645) SHA1(2977047780b615b64c3b4aec78fef0643d40490e) )
ROM_LOAD16_BYTE( "mpr-15862.ic5", 0x000001, 0x200000, CRC(9e277d25) SHA1(9f191484a42391268306a8d2d95c340ce8b2d6cd) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15864.ic32", 0x000000, 0x200000, CRC(58207157) SHA1(d1b0c7edac8b89b1322398d4cd3a976a88bc0b56) )
ROM_LOAD64_WORD( "mpr-15866.ic30", 0x000002, 0x200000, CRC(9c53732c) SHA1(9aa5103cc10b4927c16e0cf102b64a15dd038756) )
ROM_LOAD64_WORD( "mpr-15868.ic28", 0x000004, 0x200000, CRC(62d556e8) SHA1(d70cab0881784a3d4dd06d0c99587ca6054c2dc4) )
ROM_LOAD64_WORD( "mpr-15870.ic26", 0x000006, 0x200000, CRC(d31c0400) SHA1(44c1b2e5236d894d31ff72552a7ad50270dd2fad) )
ROM_LOAD64_WORD( "mpr-15865.ic31", 0x800000, 0x200000, CRC(dd64f87b) SHA1(cfa96c5f2b1221706552f5cef4aa7c61ebe21e39) )
ROM_LOAD64_WORD( "mpr-15867.ic29", 0x800002, 0x200000, CRC(8cf9cb11) SHA1(a77399fccee3f258a5716721edd69a33f94f8daf) )
ROM_LOAD64_WORD( "mpr-15869.ic27", 0x800004, 0x200000, CRC(dd4b137f) SHA1(7316dce32d35bf468defae5e6ed86910a37a2457) )
ROM_LOAD64_WORD( "mpr-15871.ic25", 0x800006, 0x200000, CRC(58eb10ae) SHA1(23f2a72dc7b2d7b5c8a979952f81608296805745) )
ROM_REGION16_BE( 0x80, "mainpcb:eeprom", 0 )
ROM_LOAD16_WORD( "93c45_eeprom.ic76", 0x0000, 0x0080, CRC(6e1d9df3) SHA1(2fd818bc393fb96e945fa37a63c8a3c4aff2f79f) )
ROM_END
/**************************************************************************************************************************
Alien 3: The Gun (US)
not protected
Sega Game ID codes:
Game BD: 834-9877-01
ROM PCB No: 837-9878-01
Main PCB: 837-7428-03 (SYSTEM 32 COM)
A/D BD NO. 837-7536
*/
ROM_START( alien3u )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x2( "epr-15941.ic17", 0x000000, 0x040000, CRC(bf8c257f) SHA1(d08b77d2e3f5af0da7e7d8727fbe7fc0eb1153ff) )
ROM_LOAD_x2( "epr-15940a.ic8", 0x080000, 0x040000, CRC(8840b51e) SHA1(0aa6945000676b1adc535b1557a1455d62aed9f5) )
ROM_LOAD16_BYTE( "mpr-15855.ic18", 0x100000, 0x080000, CRC(a6fadabe) SHA1(328bbb54651eef197ba13f1bd9228f3f4de7ee5e) )
ROM_LOAD16_BYTE( "mpr-15854.ic9", 0x100001, 0x080000, CRC(d1aec392) SHA1(f48804fe0151e83ad45e912b55db8ae8ddebd2ad) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-15859a.ic36",0x000000, 0x040000, CRC(91b55bd0) SHA1(23b85a006a91c2a5eb1cee14172fd0d8b7732518) )
ROM_LOAD( "mpr-15858.ic35", 0x100000, 0x100000, CRC(2eb64c10) SHA1(b2dbe86b82e889f4a9850cf4aa6596a139c1c3d6) )
ROM_LOAD( "mpr-15857.ic34", 0x200000, 0x100000, CRC(915c56df) SHA1(7031f937c826af17caf7ec8cbb6155d0a55bd38a) )
ROM_LOAD( "mpr-15856.ic24", 0x300000, 0x100000, CRC(a5ef4f1f) SHA1(e8da7a995955e80872a25bd75465c590b649cfab) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15863.ic14", 0x000000, 0x200000, CRC(9d36b645) SHA1(2977047780b615b64c3b4aec78fef0643d40490e) )
ROM_LOAD16_BYTE( "mpr-15862.ic5", 0x000001, 0x200000, CRC(9e277d25) SHA1(9f191484a42391268306a8d2d95c340ce8b2d6cd) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15864.ic32", 0x000000, 0x200000, CRC(58207157) SHA1(d1b0c7edac8b89b1322398d4cd3a976a88bc0b56) )
ROM_LOAD64_WORD( "mpr-15866.ic30", 0x000002, 0x200000, CRC(9c53732c) SHA1(9aa5103cc10b4927c16e0cf102b64a15dd038756) )
ROM_LOAD64_WORD( "mpr-15868.ic28", 0x000004, 0x200000, CRC(62d556e8) SHA1(d70cab0881784a3d4dd06d0c99587ca6054c2dc4) )
ROM_LOAD64_WORD( "mpr-15870.ic26", 0x000006, 0x200000, CRC(d31c0400) SHA1(44c1b2e5236d894d31ff72552a7ad50270dd2fad) )
ROM_LOAD64_WORD( "mpr-15865.ic31", 0x800000, 0x200000, CRC(dd64f87b) SHA1(cfa96c5f2b1221706552f5cef4aa7c61ebe21e39) )
ROM_LOAD64_WORD( "mpr-15867.ic29", 0x800002, 0x200000, CRC(8cf9cb11) SHA1(a77399fccee3f258a5716721edd69a33f94f8daf) )
ROM_LOAD64_WORD( "mpr-15869.ic27", 0x800004, 0x200000, CRC(dd4b137f) SHA1(7316dce32d35bf468defae5e6ed86910a37a2457) )
ROM_LOAD64_WORD( "mpr-15871.ic25", 0x800006, 0x200000, CRC(58eb10ae) SHA1(23f2a72dc7b2d7b5c8a979952f81608296805745) )
ROM_REGION16_BE( 0x80, "mainpcb:eeprom", 0 )
ROM_LOAD16_WORD( "93c45_eeprom.ic76", 0x0000, 0x0080, CRC(6e1d9df3) SHA1(2fd818bc393fb96e945fa37a63c8a3c4aff2f79f) )
ROM_END
/**************************************************************************************************************************
Alien 3: The Gun (Japan)
not protected
Sega Game ID codes:
Game BD: 834-9877
ROM PCB No: 837-9878
Main PCB: 837-7428-03 (SYSTEM 32 COM)
A/D BD NO. 837-7536
*/
ROM_START( alien3j )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x2( "epr-15861.ic17", 0x000000, 0x040000, CRC(e970603f) SHA1(b67cf4cb5269d808ff8adc007202cb6e18d5b6a9) )
ROM_LOAD_x2( "epr-15860.ic8", 0x080000, 0x040000, CRC(9af0d996) SHA1(3fb06947712947da4830200db2382d9c433a18a9) )
ROM_LOAD16_BYTE( "mpr-15855.ic18", 0x100000, 0x080000, CRC(a6fadabe) SHA1(328bbb54651eef197ba13f1bd9228f3f4de7ee5e) )
ROM_LOAD16_BYTE( "mpr-15854.ic9", 0x100001, 0x080000, CRC(d1aec392) SHA1(f48804fe0151e83ad45e912b55db8ae8ddebd2ad) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-15859.ic36", 0x000000, 0x040000, CRC(7eeda800) SHA1(d0599730a8a2adbed08fec4160b8b3963e8ac0f6) )
ROM_LOAD( "mpr-15858.ic35", 0x100000, 0x100000, CRC(2eb64c10) SHA1(b2dbe86b82e889f4a9850cf4aa6596a139c1c3d6) )
ROM_LOAD( "mpr-15857.ic34", 0x200000, 0x100000, CRC(915c56df) SHA1(7031f937c826af17caf7ec8cbb6155d0a55bd38a) )
ROM_LOAD( "mpr-15856.ic24", 0x300000, 0x100000, CRC(a5ef4f1f) SHA1(e8da7a995955e80872a25bd75465c590b649cfab) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15863.ic14", 0x000000, 0x200000, CRC(9d36b645) SHA1(2977047780b615b64c3b4aec78fef0643d40490e) )
ROM_LOAD16_BYTE( "mpr-15862.ic5", 0x000001, 0x200000, CRC(9e277d25) SHA1(9f191484a42391268306a8d2d95c340ce8b2d6cd) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15864.ic32", 0x000000, 0x200000, CRC(58207157) SHA1(d1b0c7edac8b89b1322398d4cd3a976a88bc0b56) )
ROM_LOAD64_WORD( "mpr-15866.ic30", 0x000002, 0x200000, CRC(9c53732c) SHA1(9aa5103cc10b4927c16e0cf102b64a15dd038756) )
ROM_LOAD64_WORD( "mpr-15868.ic28", 0x000004, 0x200000, CRC(62d556e8) SHA1(d70cab0881784a3d4dd06d0c99587ca6054c2dc4) )
ROM_LOAD64_WORD( "mpr-15870.ic26", 0x000006, 0x200000, CRC(d31c0400) SHA1(44c1b2e5236d894d31ff72552a7ad50270dd2fad) )
ROM_LOAD64_WORD( "mpr-15865.ic31", 0x800000, 0x200000, CRC(dd64f87b) SHA1(cfa96c5f2b1221706552f5cef4aa7c61ebe21e39) )
ROM_LOAD64_WORD( "mpr-15867.ic29", 0x800002, 0x200000, CRC(8cf9cb11) SHA1(a77399fccee3f258a5716721edd69a33f94f8daf) )
ROM_LOAD64_WORD( "mpr-15869.ic27", 0x800004, 0x200000, CRC(dd4b137f) SHA1(7316dce32d35bf468defae5e6ed86910a37a2457) )
ROM_LOAD64_WORD( "mpr-15871.ic25", 0x800006, 0x200000, CRC(58eb10ae) SHA1(23f2a72dc7b2d7b5c8a979952f81608296805745) )
ROM_REGION16_BE( 0x80, "mainpcb:eeprom", 0 )
ROM_LOAD16_WORD( "93c45_eeprom.ic76", 0x0000, 0x0080, CRC(6e1d9df3) SHA1(2fd818bc393fb96e945fa37a63c8a3c4aff2f79f) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Arabian Fight (Export)
protected via a custom V25 with encrypted code
Sega Game ID codes:
Game BD: 833-8646-05 ARABIAN FIGHT
ROM PCB No: 833-8647-02
V25 sub PCB: 834-8529-01
A/D BD NO. 837-7968
*/
ROM_START( arabfgt )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-14609.ic8", 0x000000, 0x020000, CRC(6a43c7fb) SHA1(70e9f9fa5f867f0455d62ff2690ad19055d79363) )
ROM_LOAD16_BYTE_x2( "epr-14592.ic18", 0x100000, 0x040000, CRC(f7dff316) SHA1(338690a1404dde6e7e66067f23605a247c7d0f5b) )
ROM_LOAD16_BYTE_x2( "epr-14591.ic9", 0x100001, 0x040000, CRC(bbd940fb) SHA1(99c17aba890935eaf7ea468492da03103288eb1b) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU + banks */
ROM_LOAD_x8( "epr-14596.ic36", 0x000000, 0x020000, CRC(bd01faec) SHA1(c909dcb8ef2672c4b0060d911d295e445ca311eb) )
ROM_LOAD( "mpr-14595f.ic35", 0x100000, 0x100000, CRC(5173d1af) SHA1(dccda644488d0c561c8ff7fa9619bd9504d8d9c6) )
ROM_LOAD( "mpr-14594f.ic34", 0x200000, 0x100000, CRC(01777645) SHA1(7bcbe7687bd80b94bd3b2b3099cdd036bf7e0cd3) )
ROM_LOAD( "mpr-14593f.ic24", 0x300000, 0x100000, CRC(aa037047) SHA1(5cb1cfb235bbbf875d2b07ac4a9130ba13d47e57) )
ROM_REGION( 0x10000, "mainpcb:mcu", 0 ) /* Protection CPU */
ROM_LOAD( "epr-14468-01.u3", 0x00000, 0x10000, CRC(c3c591e4) SHA1(53e48066e85b61d0c456618d14334a509b354cb3) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-14599f.ic14", 0x000000, 0x200000, CRC(94f1cf10) SHA1(34ec86487bcb6726c025149c319f00a854eb7a1d) )
ROM_LOAD16_BYTE( "mpr-14598f.ic5", 0x000001, 0x200000, CRC(010656f3) SHA1(31619c022cba4f250ce174f186d3e34444f60faf) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-14600f.ic32", 0x000000, 0x200000, CRC(e860988a) SHA1(328581877c0890519c854f75f0976b0e9c4560f8) )
ROM_LOAD64_WORD( "mpr-14602.ic30", 0x000002, 0x200000, CRC(64524e4d) SHA1(86246185ab5ab638a73991c9e3aeb07c6d51be4f) )
ROM_LOAD64_WORD( "mpr-14604.ic28", 0x000004, 0x200000, CRC(5f8d5167) SHA1(1b08495e5a4cc2530c2895e47abd0e0b75496c68) )
ROM_LOAD64_WORD( "mpr-14606.ic26", 0x000006, 0x200000, CRC(7047f437) SHA1(e806a1cd73c96b33e8edc64e41d99bf7798103e0) )
ROM_LOAD64_WORD( "mpr-14601f.ic31", 0x800000, 0x200000, CRC(a2f3bb32) SHA1(1a60975dead5faf08ad4e9a96a00f98664d5e5ec) )
ROM_LOAD64_WORD( "mpr-14603.ic29", 0x800002, 0x200000, CRC(f6ce494b) SHA1(b3117e34913e855c035ebe37fbfbe0f7466f94f0) )
ROM_LOAD64_WORD( "mpr-14605.ic27", 0x800004, 0x200000, CRC(aaf52697) SHA1(b502a37ae68fc08b60cdf0e2b744898b3474d3b9) )
ROM_LOAD64_WORD( "mpr-14607.ic25", 0x800006, 0x200000, CRC(b70b0735) SHA1(9ef2da6f710bc5c2c7ee30dc144409a61dbe6646) )
ROM_END
/**************************************************************************************************************************
Arabian Fight (US)
protected via a custom V25 with encrypted code
*/
ROM_START( arabfgtu )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-14608.ic8", 0x000000, 0x020000, CRC(cd5efba9) SHA1(a7daf8e95d31359753c984c447e93d40f43a179d) )
ROM_LOAD16_BYTE_x2( "epr-14592.ic18", 0x100000, 0x040000, CRC(f7dff316) SHA1(338690a1404dde6e7e66067f23605a247c7d0f5b) )
ROM_LOAD16_BYTE_x2( "epr-14591.ic9", 0x100001, 0x040000, CRC(bbd940fb) SHA1(99c17aba890935eaf7ea468492da03103288eb1b) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU + banks */
ROM_LOAD_x8( "epr-14596.ic36", 0x000000, 0x020000, CRC(bd01faec) SHA1(c909dcb8ef2672c4b0060d911d295e445ca311eb) )
ROM_LOAD( "mpr-14595f.ic35", 0x100000, 0x100000, CRC(5173d1af) SHA1(dccda644488d0c561c8ff7fa9619bd9504d8d9c6) )
ROM_LOAD( "mpr-14594f.ic34", 0x200000, 0x100000, CRC(01777645) SHA1(7bcbe7687bd80b94bd3b2b3099cdd036bf7e0cd3) )
ROM_LOAD( "mpr-14593f.ic24", 0x300000, 0x100000, CRC(aa037047) SHA1(5cb1cfb235bbbf875d2b07ac4a9130ba13d47e57) )
ROM_REGION( 0x10000, "mainpcb:mcu", 0 ) /* Protection CPU */
ROM_LOAD( "epr-14468-01.u3", 0x00000, 0x10000, CRC(c3c591e4) SHA1(53e48066e85b61d0c456618d14334a509b354cb3) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-14599f.ic14", 0x000000, 0x200000, CRC(94f1cf10) SHA1(34ec86487bcb6726c025149c319f00a854eb7a1d) )
ROM_LOAD16_BYTE( "mpr-14598f.ic5", 0x000001, 0x200000, CRC(010656f3) SHA1(31619c022cba4f250ce174f186d3e34444f60faf) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-14600f.ic32", 0x000000, 0x200000, CRC(e860988a) SHA1(328581877c0890519c854f75f0976b0e9c4560f8) )
ROM_LOAD64_WORD( "mpr-14602.ic30", 0x000002, 0x200000, CRC(64524e4d) SHA1(86246185ab5ab638a73991c9e3aeb07c6d51be4f) )
ROM_LOAD64_WORD( "mpr-14604.ic28", 0x000004, 0x200000, CRC(5f8d5167) SHA1(1b08495e5a4cc2530c2895e47abd0e0b75496c68) )
ROM_LOAD64_WORD( "mpr-14606.ic26", 0x000006, 0x200000, CRC(7047f437) SHA1(e806a1cd73c96b33e8edc64e41d99bf7798103e0) )
ROM_LOAD64_WORD( "mpr-14601f.ic31", 0x800000, 0x200000, CRC(a2f3bb32) SHA1(1a60975dead5faf08ad4e9a96a00f98664d5e5ec) )
ROM_LOAD64_WORD( "mpr-14603.ic29", 0x800002, 0x200000, CRC(f6ce494b) SHA1(b3117e34913e855c035ebe37fbfbe0f7466f94f0) )
ROM_LOAD64_WORD( "mpr-14605.ic27", 0x800004, 0x200000, CRC(aaf52697) SHA1(b502a37ae68fc08b60cdf0e2b744898b3474d3b9) )
ROM_LOAD64_WORD( "mpr-14607.ic25", 0x800006, 0x200000, CRC(b70b0735) SHA1(9ef2da6f710bc5c2c7ee30dc144409a61dbe6646) )
ROM_END
/**************************************************************************************************************************
Arabian Fight (Japan)
protected via a custom V25 with encrypted code
*/
ROM_START( arabfgtj )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-14597.ic8", 0x000000, 0x020000, CRC(7a6fe222) SHA1(f730e9d44ad20dbaa59f6311a077c889e0aec8e4) )
ROM_LOAD16_BYTE_x2( "epr-14592.ic18", 0x100000, 0x040000, CRC(f7dff316) SHA1(338690a1404dde6e7e66067f23605a247c7d0f5b) )
ROM_LOAD16_BYTE_x2( "epr-14591.ic9", 0x100001, 0x040000, CRC(bbd940fb) SHA1(99c17aba890935eaf7ea468492da03103288eb1b) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU + banks */
ROM_LOAD_x8( "epr-14596.ic36", 0x000000, 0x020000, CRC(bd01faec) SHA1(c909dcb8ef2672c4b0060d911d295e445ca311eb) )
ROM_LOAD( "mpr-14595f.ic35", 0x100000, 0x100000, CRC(5173d1af) SHA1(dccda644488d0c561c8ff7fa9619bd9504d8d9c6) )
ROM_LOAD( "mpr-14594f.ic34", 0x200000, 0x100000, CRC(01777645) SHA1(7bcbe7687bd80b94bd3b2b3099cdd036bf7e0cd3) )
ROM_LOAD( "mpr-14593f.ic24", 0x300000, 0x100000, CRC(aa037047) SHA1(5cb1cfb235bbbf875d2b07ac4a9130ba13d47e57) )
ROM_REGION( 0x10000, "mainpcb:mcu", 0 ) /* Protection CPU */
ROM_LOAD( "epr-14468-01.u3", 0x00000, 0x10000, CRC(c3c591e4) SHA1(53e48066e85b61d0c456618d14334a509b354cb3) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-14599f.ic14", 0x000000, 0x200000, CRC(94f1cf10) SHA1(34ec86487bcb6726c025149c319f00a854eb7a1d) )
ROM_LOAD16_BYTE( "mpr-14598f.ic5", 0x000001, 0x200000, CRC(010656f3) SHA1(31619c022cba4f250ce174f186d3e34444f60faf) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-14600f.ic32", 0x000000, 0x200000, CRC(e860988a) SHA1(328581877c0890519c854f75f0976b0e9c4560f8) )
ROM_LOAD64_WORD( "mpr-14602.ic30", 0x000002, 0x200000, CRC(64524e4d) SHA1(86246185ab5ab638a73991c9e3aeb07c6d51be4f) )
ROM_LOAD64_WORD( "mpr-14604.ic28", 0x000004, 0x200000, CRC(5f8d5167) SHA1(1b08495e5a4cc2530c2895e47abd0e0b75496c68) )
ROM_LOAD64_WORD( "mpr-14606.ic26", 0x000006, 0x200000, CRC(7047f437) SHA1(e806a1cd73c96b33e8edc64e41d99bf7798103e0) )
ROM_LOAD64_WORD( "mpr-14601f.ic31", 0x800000, 0x200000, CRC(a2f3bb32) SHA1(1a60975dead5faf08ad4e9a96a00f98664d5e5ec) )
ROM_LOAD64_WORD( "mpr-14603.ic29", 0x800002, 0x200000, CRC(f6ce494b) SHA1(b3117e34913e855c035ebe37fbfbe0f7466f94f0) )
ROM_LOAD64_WORD( "mpr-14605.ic27", 0x800004, 0x200000, CRC(aaf52697) SHA1(b502a37ae68fc08b60cdf0e2b744898b3474d3b9) )
ROM_LOAD64_WORD( "mpr-14607.ic25", 0x800006, 0x200000, CRC(b70b0735) SHA1(9ef2da6f710bc5c2c7ee30dc144409a61dbe6646) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Burning Rival (Export)
protected via FD1149 317-0212
*/
ROM_START( brival )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-15722.ic8", 0x000000, 0x020000, CRC(138141c0) SHA1(aca2a46ee1008e91c65a09e79c76d5175e7df5e8) )
ROM_LOAD16_BYTE( "epr-15723.ic18", 0x100000, 0x080000, CRC(4ff40d39) SHA1(b33a656f976ec7a1a2268e7b9a81d5b84f3d9ca3) )
ROM_LOAD16_BYTE( "epr-15724.ic9", 0x100001, 0x080000, CRC(3ff8a052) SHA1(f484a8e15a022f9ff290e662ab27f96f9f0ad24e) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-15725.ic36", 0x000000, 0x020000, CRC(ea1407d7) SHA1(68b571341f032278e87a38739ba8084b7a6062d3) )
ROM_LOAD( "mpr-15627.ic35", 0x100000, 0x100000, CRC(8a8388c5) SHA1(7ee03feb975cc576a3d8651fd41976ca87d60894) )
ROM_LOAD( "mpr-15626.ic34", 0x200000, 0x100000, CRC(83306d1e) SHA1(feb08902b51c0013d9417832cdf198e36cdfc28c) )
ROM_LOAD( "mpr-15625.ic24", 0x300000, 0x100000, CRC(3ce82932) SHA1(f2107bc2591f46a51c9f0d706933b1ae69db91f9) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15629.ic14", 0x000000, 0x200000, CRC(2c8dd96d) SHA1(4a42a30485c19eb4f4a9d518a3dff3ae11911d01) )
ROM_LOAD16_BYTE( "mpr-15628.ic5", 0x000001, 0x200000, CRC(58d4ca40) SHA1(b1633acc803bba7e8283a9663b49abeda662a74d) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15637.ic32", 0x000000, 0x200000, CRC(b6cf2f05) SHA1(a308d40ce5165e03fccf7fcd615ee111f7840fdc) )
ROM_LOAD64_WORD( "mpr-15635.ic30", 0x000002, 0x200000, CRC(70f2eb2b) SHA1(9868c8b0dd8ce810a0e32f51e702eee7e1c9a967) )
ROM_LOAD64_WORD( "mpr-15633.ic28", 0x000004, 0x200000, CRC(005dfed5) SHA1(f555620d75d3886a890307be9df9c0879bcda695) )
ROM_LOAD64_WORD( "mpr-15631.ic26", 0x000006, 0x200000, CRC(c35e2f21) SHA1(37935aa2eaa1769e57fb58f47f9797ae153d7496) )
ROM_LOAD64_WORD( "mpr-15636.ic31", 0x800000, 0x200000, CRC(d81ca97b) SHA1(a8e64e6cbe822f18ce20f50c8ddb8f1d5ed8b783) )
ROM_LOAD64_WORD( "mpr-15634.ic29", 0x800002, 0x200000, CRC(b0c6c52a) SHA1(04dd7344ca82e38f9d796a764c9e5a631a89aaac) )
ROM_LOAD64_WORD( "mpr-15632.ic27", 0x800004, 0x200000, CRC(8476e52b) SHA1(e89748d34febcaf362580cdae30a5c570e56899a) )
ROM_LOAD64_WORD( "mpr-15630.ic25", 0x800006, 0x200000, CRC(bf7dd2f6) SHA1(ab3fbe9e2b9b57424fb2a147f32b0f573c0b11b8) )
ROM_END
/**************************************************************************************************************************
Burning Rival (Japan)
protected via FD1149 317-0212
*/
ROM_START( brivalj )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-15720.ic8", 0x000000, 0x020000, CRC(0d182d78) SHA1(53e9e5898869ea4a354dc3e9a78d8b8e9a7274c9) )
ROM_LOAD16_BYTE( "epr-15723.ic18", 0x100000, 0x080000, CRC(4ff40d39) SHA1(b33a656f976ec7a1a2268e7b9a81d5b84f3d9ca3) )
ROM_LOAD16_BYTE( "epr-15724.ic9", 0x100001, 0x080000, CRC(3ff8a052) SHA1(f484a8e15a022f9ff290e662ab27f96f9f0ad24e) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-15725.ic36", 0x000000, 0x020000, CRC(ea1407d7) SHA1(68b571341f032278e87a38739ba8084b7a6062d3) )
ROM_LOAD( "mpr-15627.ic35", 0x100000, 0x100000, CRC(8a8388c5) SHA1(7ee03feb975cc576a3d8651fd41976ca87d60894) )
ROM_LOAD( "mpr-15626.ic34", 0x200000, 0x100000, CRC(83306d1e) SHA1(feb08902b51c0013d9417832cdf198e36cdfc28c) )
ROM_LOAD( "mpr-15625.ic24", 0x300000, 0x100000, CRC(3ce82932) SHA1(f2107bc2591f46a51c9f0d706933b1ae69db91f9) )
/* the 10 ROMs below may be bad dumps ... mp14598 / 99 have corrupt tiles when compared to the ROMs
in the parent set, but Sega did change the part numbers so they might be correct, the others
are suspicious, the changes are very similar but the part numbers haven't changed. We really
need a 3rd board to verify */
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-14599f.ic14", 0x000000, 0x200000, CRC(1de17e83) SHA1(04ee14b863f93b42a5bd1b6da71cff54ef11d4b7) ) /* ROM # matches tile ROM # from Arabian Fight ??? */
ROM_LOAD16_BYTE( "mpr-14598f.ic5", 0x000001, 0x200000, CRC(cafb0de9) SHA1(94c6bfc7a4081dee373e9466a7b6f80889696087) ) /* ROM # matches tile ROM # from Arabian Fight ??? */
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "brivalj_mp15637.32", 0x000000, 0x200000, CRC(f39844c0) SHA1(c48dc8cccdd9d3756cf99a983c6a89ed43fcda22) )
ROM_LOAD64_WORD( "brivalj_mp15635.30", 0x000002, 0x200000, CRC(263cf6d1) SHA1(7accd214502fd050edc0901c9929d6069dae4d00) )
ROM_LOAD64_WORD( "brivalj_mp15633.28", 0x000004, 0x200000, CRC(44e9a88b) SHA1(57a930b9c3b83c889df54de60c90f847c2dcb614) )
ROM_LOAD64_WORD( "brivalj_mp15631.26", 0x000006, 0x200000, CRC(e93cf9c9) SHA1(17786cd3ccaef613216db724e923861841c52b45) )
ROM_LOAD64_WORD( "brivalj_mp15636.31", 0x800000, 0x200000, CRC(079ff77f) SHA1(bdd41acef58c39ba58cf85d307229622877dbdf9) )
ROM_LOAD64_WORD( "brivalj_mp15634.29", 0x800002, 0x200000, CRC(1edc14cd) SHA1(80a281c904560b364fe9f2b8987b7a254220a29f) )
ROM_LOAD64_WORD( "brivalj_mp15632.27", 0x800004, 0x200000, CRC(796215f2) SHA1(d7b393781dbba59c9b1cd600d27e6d91e36ea771) )
ROM_LOAD64_WORD( "brivalj_mp15630.25", 0x800006, 0x200000, CRC(8dabb501) SHA1(c5af2187d00e0b9732a82441f9758b303fecbb2c) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Dark Edge (Export)
protected via FD1149 317-0204
*/
ROM_START( darkedge )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x2( "epr-15246.ic8", 0x000000, 0x080000, CRC(c0bdceeb) SHA1(9cf670cf9a8691f259c75c1d9c6cb14e8a70bb72) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-15243.ic36", 0x000000, 0x020000, CRC(08ca5f11) SHA1(c2c48d2f02770941a93794f82cb407d6264904d2) )
ROM_LOAD( "mpr-15242.ic35", 0x100000, 0x100000, CRC(ffb7d917) SHA1(bfeae1a2bd7250edb695b7034f6b1f851f6fd48a) )
ROM_LOAD( "mpr-15241.ic34", 0x200000, 0x100000, CRC(8eccc4fe) SHA1(119724b9b6d2b51ad4f065ebf74d200960090e68) )
ROM_LOAD( "mpr-15240.ic24", 0x300000, 0x100000, CRC(867d59e8) SHA1(fb1c0d26dbb1bde9d8bc86419cd911b8e37bf923) )
ROM_REGION( 0x100000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15248.ic14", 0x000000, 0x080000, CRC(185b308b) SHA1(a49c1b752b3c4355560e0cd712fb9a096140e37b) )
ROM_LOAD16_BYTE( "mpr-15247.ic5", 0x000001, 0x080000, CRC(be21548c) SHA1(2e315aadc2a0b781c3ee3fe71c75eb1f43514eff) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15249.ic32", 0x000000, 0x200000, CRC(2b4371a8) SHA1(47f448bfbc068f2d0cdedd81bcd280823d5758a3) )
ROM_LOAD64_WORD( "mpr-15251.ic30", 0x000002, 0x200000, CRC(efe2d689) SHA1(af22153ea3afdde3732f881087c642170f91d745) )
ROM_LOAD64_WORD( "mpr-15253.ic28", 0x000004, 0x200000, CRC(8356ed01) SHA1(a28747813807361c7d0c722a94e194caea8bfab6) )
ROM_LOAD64_WORD( "mpr-15255.ic26", 0x000006, 0x200000, CRC(ff04a5b0) SHA1(d4548f9da014ba5249c2f75d654a2a88c095aaf8) )
ROM_LOAD64_WORD( "mpr-15250.ic31", 0x800000, 0x200000, CRC(c5cab71a) SHA1(111c69c40a39c3fceef38f5876e1dcf7ac2fbee2) )
ROM_LOAD64_WORD( "mpr-15252.ic29", 0x800002, 0x200000, CRC(f8885fea) SHA1(ef944df5f6fd64813734056ad2a150f518c75459) )
ROM_LOAD64_WORD( "mpr-15254.ic27", 0x800004, 0x200000, CRC(7765424b) SHA1(7cd4c275f6333beeea62dd65a769e11650c68923) )
ROM_LOAD64_WORD( "mpr-15256.ic25", 0x800006, 0x200000, CRC(44c36b62) SHA1(4c7f2cc4347ef2126dcbf43e8dce8500e52b5f8e) )
ROM_END
/**************************************************************************************************************************
Dark Edge (Japan)
protected via FD1149 317-0204
Sega Game ID codes:
Game BD: 833-9230 DARK EDGE
ROM PCB No: 834-9231
A/D BD NO. 837-7968
*/
ROM_START( darkedgej )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x2( "epr-15244.ic8", 0x000000, 0x080000, CRC(0db138cb) SHA1(79ccb754e0d816b395b536a6d9c5a6e93168a913) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-15243.ic36", 0x000000, 0x020000, CRC(08ca5f11) SHA1(c2c48d2f02770941a93794f82cb407d6264904d2) )
ROM_LOAD( "mpr-15242.ic35", 0x100000, 0x100000, CRC(ffb7d917) SHA1(bfeae1a2bd7250edb695b7034f6b1f851f6fd48a) )
ROM_LOAD( "mpr-15241.ic34", 0x200000, 0x100000, CRC(8eccc4fe) SHA1(119724b9b6d2b51ad4f065ebf74d200960090e68) )
ROM_LOAD( "mpr-15240.ic24", 0x300000, 0x100000, CRC(867d59e8) SHA1(fb1c0d26dbb1bde9d8bc86419cd911b8e37bf923) )
ROM_REGION( 0x100000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15248.ic14", 0x000000, 0x080000, CRC(185b308b) SHA1(a49c1b752b3c4355560e0cd712fb9a096140e37b) )
ROM_LOAD16_BYTE( "mpr-15247.ic5", 0x000001, 0x080000, CRC(be21548c) SHA1(2e315aadc2a0b781c3ee3fe71c75eb1f43514eff) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15249.ic32", 0x000000, 0x200000, CRC(2b4371a8) SHA1(47f448bfbc068f2d0cdedd81bcd280823d5758a3) )
ROM_LOAD64_WORD( "mpr-15251.ic30", 0x000002, 0x200000, CRC(efe2d689) SHA1(af22153ea3afdde3732f881087c642170f91d745) )
ROM_LOAD64_WORD( "mpr-15253.ic28", 0x000004, 0x200000, CRC(8356ed01) SHA1(a28747813807361c7d0c722a94e194caea8bfab6) )
ROM_LOAD64_WORD( "mpr-15255.ic26", 0x000006, 0x200000, CRC(ff04a5b0) SHA1(d4548f9da014ba5249c2f75d654a2a88c095aaf8) )
ROM_LOAD64_WORD( "mpr-15250.ic31", 0x800000, 0x200000, CRC(c5cab71a) SHA1(111c69c40a39c3fceef38f5876e1dcf7ac2fbee2) )
ROM_LOAD64_WORD( "mpr-15252.ic29", 0x800002, 0x200000, CRC(f8885fea) SHA1(ef944df5f6fd64813734056ad2a150f518c75459) )
ROM_LOAD64_WORD( "mpr-15254.ic27", 0x800004, 0x200000, CRC(7765424b) SHA1(7cd4c275f6333beeea62dd65a769e11650c68923) )
ROM_LOAD64_WORD( "mpr-15256.ic25", 0x800006, 0x200000, CRC(44c36b62) SHA1(4c7f2cc4347ef2126dcbf43e8dce8500e52b5f8e) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Dragon Ball Z, VRVS
protected via FD1149 317-0215/0217
Sega Game ID codes:
ROM BD. 834-10662
*/
ROM_START( dbzvrvs )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD( "epr-16543", 0x000000, 0x080000, CRC(7b9bc6f5) SHA1(556fd8471bf471e41fc6a50471c2be1bd6b98697) )
ROM_LOAD( "epr-16542a", 0x080000, 0x080000, CRC(6449ab22) SHA1(03e6cdacf77f2ff80dd6798094deac5486f2c840) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-16541", 0x000000, 0x040000, CRC(1d61d836) SHA1(c6b1b54d41d2650abeaf69a31aa76c4462531880) )
ROM_LOAD( "mpr-16540", 0x100000, 0x100000, CRC(b6f9bb43) SHA1(823f29a2fc4b9315e8c58616dbd095d45d366c8b) )
ROM_LOAD( "mpr-16539", 0x200000, 0x100000, CRC(38c26418) SHA1(2442933e13c83209e904c1dec677aeda91b75290) )
ROM_LOAD( "mpr-16538", 0x300000, 0x100000, CRC(4d402c31) SHA1(2df160fd7e70f3d7b52fef2a2082e68966fd1535) )
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16545", 0x000000, 0x100000, CRC(51748bac) SHA1(b1cae16b62a8d29117c0adb140eb09c1092f6c37) )
ROM_LOAD16_BYTE( "mpr-16544", 0x000001, 0x100000, CRC(f6c93dfc) SHA1(a006cedb7d0151ccc8d22e6588b1c39e099da182) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16546", 0x000000, 0x200000, CRC(96f4be31) SHA1(ce3281630180d91de7850e9b1062382817fe0b1d) )
ROM_LOAD64_WORD( "mpr-16548", 0x000002, 0x200000, CRC(00377f59) SHA1(cf0f808d7730f334c5ac80d3171fa457be9ac88e) )
ROM_LOAD64_WORD( "mpr-16550", 0x000004, 0x200000, CRC(168e8966) SHA1(a18ec30f1358b09bcde6d8d2dbe0a82bea3bdae9) )
ROM_LOAD64_WORD( "mpr-16552", 0x000006, 0x200000, CRC(a31dae31) SHA1(2da2c391f29b5fdb87e3f95d9dabd50370fafa5a) )
ROM_LOAD64_WORD( "mpr-16547", 0x800000, 0x200000, CRC(50d328ed) SHA1(c4795299f5d7c9f3a847d684d8cde7012d4486f0) )
ROM_LOAD64_WORD( "mpr-16549", 0x800002, 0x200000, CRC(a5802e9f) SHA1(4cec3ed85a21aaf99b73013795721f212019e619) )
ROM_LOAD64_WORD( "mpr-16551", 0x800004, 0x200000, CRC(dede05fc) SHA1(51e092579e2b81fb68a9cc54165f80026fe71796) )
ROM_LOAD64_WORD( "mpr-16553", 0x800006, 0x200000, CRC(c0a43009) SHA1(e4f73768de512046b3e25c4238da811dcc2dde0b) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
F1 Exhaust Note (Export)
to display the title screen this will require 2 linked system32 boards to be emulated
Sega Game ID codes:
GAME BD NO. 833-8389-02 EXHAUST NOTE
ROM BD. 834-8439-02 or 834-8439-05 for stand alone version
MAIN BD. 837-7428 (SYSTEM 32 COM)
Link PCB NO. 837-8223-01
A/D BD NO. 837-7536
*/
ROM_START( f1en )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-14452a.ic6", 0x000000, 0x020000, CRC(b5b4a9d9) SHA1(6699c15dc1155c3cee33a06d320acbff0ab5ad11) )
ROM_LOAD16_BYTE_x2( "epr-14445.ic14", 0x100000, 0x040000, CRC(d06261ab) SHA1(6e1c4ce4e49a142fd5b1ecac98145960d7afd567) )
ROM_LOAD16_BYTE_x2( "epr-14444.ic7", 0x100001, 0x040000, CRC(07724354) SHA1(9d7f64a80553c4ae0e9cf716478fd5c4b8277470) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-14449.ic35", 0x000000, 0x020000, CRC(2d29699c) SHA1(cae02e5533a0edd3b3b4a54a1a43321285e06416) )
ROM_LOAD_x2( "epr-14448.ic31", 0x100000, 0x080000, CRC(87ca1e8d) SHA1(739274171c13983a60d061176095645419dade49) )
ROM_LOAD_x2( "epr-14447.ic26", 0x200000, 0x080000, CRC(db1cfcbd) SHA1(c76eb2ced5571a548ad00709097dd272747127a2) )
ROM_LOAD_x2( "epr-14446.ic22", 0x300000, 0x080000, CRC(646ec2cb) SHA1(67e453f128ae227e22c68f55d0d3f5831fbeb2f9) )
ROM_REGION( 0x100000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14362.ic38", 0x000000, 0x040000, CRC(fb1c4e79) SHA1(38ee23763b9e5bb62bbc54cab95041415404f0c4) )
ROM_LOAD32_BYTE( "mpr-14361.ic34", 0x000002, 0x040000, CRC(e3204bda) SHA1(34157e80edd6d685bd5a5e23b1e0130a5f3d138a) )
ROM_LOAD32_BYTE( "mpr-14360.ic29", 0x000001, 0x040000, CRC(c5e8da79) SHA1(662a6c146fe3d0b8763d845379c06d0ee6ced1ed) )
ROM_LOAD32_BYTE( "mpr-14359.ic25", 0x000003, 0x040000, CRC(70305c68) SHA1(7a6a1bf7381eba8cc1c3897497b32ca63316972a) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14370.ic36", 0x000000, 0x080000, CRC(fda78289) SHA1(3740affdcc738c50d07ff3e5b592bdf8a8b6be15) )
ROM_LOAD64_BYTE( "mpr-14369.ic32", 0x000001, 0x080000, CRC(7765116d) SHA1(9493148aa84adc90143cf638265d4c55bfb43990) )
ROM_LOAD64_BYTE( "mpr-14368.ic27", 0x000002, 0x080000, CRC(5744a30e) SHA1(98544fb234a8e93716e951d5414a490845e213c5) )
ROM_LOAD64_BYTE( "mpr-14367.ic23", 0x000003, 0x080000, CRC(77bb9003) SHA1(6370fdeab4967976840d752577cd860b9ce8efca) )
ROM_LOAD64_BYTE( "mpr-14366.ic37", 0x000004, 0x080000, CRC(21078e83) SHA1(f35f643c28aad3bf18cb9906b114c4f49b7b4cd1) )
ROM_LOAD64_BYTE( "mpr-14365.ic33", 0x000005, 0x080000, CRC(36913790) SHA1(4a447cffb44b023fe1441277db1e411d4cd119eb) )
ROM_LOAD64_BYTE( "mpr-14364.ic28", 0x000006, 0x080000, CRC(0fa12ecd) SHA1(6a34c7718edffbeddded8786e11cac181b485ebd) )
ROM_LOAD64_BYTE( "mpr-14363.ic24", 0x000007, 0x080000, CRC(f3427a56) SHA1(6a99d7432dfff35470ddcca5cfde36689a77e706) )
ROM_REGION( 0x200000, "slavepcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-14452a.ic6", 0x000000, 0x020000, CRC(b5b4a9d9) SHA1(6699c15dc1155c3cee33a06d320acbff0ab5ad11) )
ROM_LOAD16_BYTE_x2( "epr-14445.ic14", 0x100000, 0x040000, CRC(d06261ab) SHA1(6e1c4ce4e49a142fd5b1ecac98145960d7afd567) )
ROM_LOAD16_BYTE_x2( "epr-14444.ic7", 0x100001, 0x040000, CRC(07724354) SHA1(9d7f64a80553c4ae0e9cf716478fd5c4b8277470) )
ROM_REGION( 0x400000, "slavepcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-14449.ic35", 0x000000, 0x020000, CRC(2d29699c) SHA1(cae02e5533a0edd3b3b4a54a1a43321285e06416) )
ROM_LOAD_x2( "epr-14448.ic31", 0x100000, 0x080000, CRC(87ca1e8d) SHA1(739274171c13983a60d061176095645419dade49) )
ROM_LOAD_x2( "epr-14447.ic26", 0x200000, 0x080000, CRC(db1cfcbd) SHA1(c76eb2ced5571a548ad00709097dd272747127a2) )
ROM_LOAD_x2( "epr-14446.ic22", 0x300000, 0x080000, CRC(646ec2cb) SHA1(67e453f128ae227e22c68f55d0d3f5831fbeb2f9) )
ROM_REGION( 0x100000, "slavepcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14362.ic38", 0x000000, 0x040000, CRC(fb1c4e79) SHA1(38ee23763b9e5bb62bbc54cab95041415404f0c4) )
ROM_LOAD32_BYTE( "mpr-14361.ic34", 0x000002, 0x040000, CRC(e3204bda) SHA1(34157e80edd6d685bd5a5e23b1e0130a5f3d138a) )
ROM_LOAD32_BYTE( "mpr-14360.ic29", 0x000001, 0x040000, CRC(c5e8da79) SHA1(662a6c146fe3d0b8763d845379c06d0ee6ced1ed) )
ROM_LOAD32_BYTE( "mpr-14359.ic25", 0x000003, 0x040000, CRC(70305c68) SHA1(7a6a1bf7381eba8cc1c3897497b32ca63316972a) )
ROM_REGION32_BE( 0x800000, "slavepcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14370.ic36", 0x000000, 0x080000, CRC(fda78289) SHA1(3740affdcc738c50d07ff3e5b592bdf8a8b6be15) )
ROM_LOAD64_BYTE( "mpr-14369.ic32", 0x000001, 0x080000, CRC(7765116d) SHA1(9493148aa84adc90143cf638265d4c55bfb43990) )
ROM_LOAD64_BYTE( "mpr-14368.ic27", 0x000002, 0x080000, CRC(5744a30e) SHA1(98544fb234a8e93716e951d5414a490845e213c5) )
ROM_LOAD64_BYTE( "mpr-14367.ic23", 0x000003, 0x080000, CRC(77bb9003) SHA1(6370fdeab4967976840d752577cd860b9ce8efca) )
ROM_LOAD64_BYTE( "mpr-14366.ic37", 0x000004, 0x080000, CRC(21078e83) SHA1(f35f643c28aad3bf18cb9906b114c4f49b7b4cd1) )
ROM_LOAD64_BYTE( "mpr-14365.ic33", 0x000005, 0x080000, CRC(36913790) SHA1(4a447cffb44b023fe1441277db1e411d4cd119eb) )
ROM_LOAD64_BYTE( "mpr-14364.ic28", 0x000006, 0x080000, CRC(0fa12ecd) SHA1(6a34c7718edffbeddded8786e11cac181b485ebd) )
ROM_LOAD64_BYTE( "mpr-14363.ic24", 0x000007, 0x080000, CRC(f3427a56) SHA1(6a99d7432dfff35470ddcca5cfde36689a77e706) )
ROM_END
/**************************************************************************************************************************
F1 Exhaust Note (US)
to display the title screen this will require 2 linked system32 boards to be emulated
Sega Game ID codes:
GAME BD NO. 833-8389-01 EXHAUST NOTE
ROM BD. 834-8439-01 or 834-8439-04 for stand alone version
MAIN BD. 837-7428 (SYSTEM 32 COM)
Link PCB NO. 837-8223-01
A/D BD NO. 837-7536
*/
ROM_START( f1enu ) // ROM PCB number is 834-8439-04
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-14451a.ic6", 0x000000, 0x020000, CRC(e17259c9) SHA1(be789b7630b7265e19ea2c80f603caff9cec37f8) )
ROM_LOAD16_BYTE_x2( "epr-14445.ic14", 0x100000, 0x040000, CRC(d06261ab) SHA1(6e1c4ce4e49a142fd5b1ecac98145960d7afd567) )
ROM_LOAD16_BYTE_x2( "epr-14444.ic7", 0x100001, 0x040000, CRC(07724354) SHA1(9d7f64a80553c4ae0e9cf716478fd5c4b8277470) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-14449.ic35", 0x000000, 0x020000, CRC(2d29699c) SHA1(cae02e5533a0edd3b3b4a54a1a43321285e06416) )
ROM_LOAD_x2( "epr-14448.ic31", 0x100000, 0x080000, CRC(87ca1e8d) SHA1(739274171c13983a60d061176095645419dade49) )
ROM_LOAD_x2( "epr-14447.ic26", 0x200000, 0x080000, CRC(db1cfcbd) SHA1(c76eb2ced5571a548ad00709097dd272747127a2) )
ROM_LOAD_x2( "epr-14446.ic22", 0x300000, 0x080000, CRC(646ec2cb) SHA1(67e453f128ae227e22c68f55d0d3f5831fbeb2f9) )
ROM_REGION( 0x100000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14362.ic38", 0x000000, 0x040000, CRC(fb1c4e79) SHA1(38ee23763b9e5bb62bbc54cab95041415404f0c4) )
ROM_LOAD32_BYTE( "mpr-14361.ic34", 0x000002, 0x040000, CRC(e3204bda) SHA1(34157e80edd6d685bd5a5e23b1e0130a5f3d138a) )
ROM_LOAD32_BYTE( "mpr-14360.ic29", 0x000001, 0x040000, CRC(c5e8da79) SHA1(662a6c146fe3d0b8763d845379c06d0ee6ced1ed) )
ROM_LOAD32_BYTE( "mpr-14359.ic25", 0x000003, 0x040000, CRC(70305c68) SHA1(7a6a1bf7381eba8cc1c3897497b32ca63316972a) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14370.ic36", 0x000000, 0x080000, CRC(fda78289) SHA1(3740affdcc738c50d07ff3e5b592bdf8a8b6be15) )
ROM_LOAD64_BYTE( "mpr-14369.ic32", 0x000001, 0x080000, CRC(7765116d) SHA1(9493148aa84adc90143cf638265d4c55bfb43990) )
ROM_LOAD64_BYTE( "mpr-14368.ic27", 0x000002, 0x080000, CRC(5744a30e) SHA1(98544fb234a8e93716e951d5414a490845e213c5) )
ROM_LOAD64_BYTE( "mpr-14367.ic23", 0x000003, 0x080000, CRC(77bb9003) SHA1(6370fdeab4967976840d752577cd860b9ce8efca) )
ROM_LOAD64_BYTE( "mpr-14366.ic37", 0x000004, 0x080000, CRC(21078e83) SHA1(f35f643c28aad3bf18cb9906b114c4f49b7b4cd1) )
ROM_LOAD64_BYTE( "mpr-14365.ic33", 0x000005, 0x080000, CRC(36913790) SHA1(4a447cffb44b023fe1441277db1e411d4cd119eb) )
ROM_LOAD64_BYTE( "mpr-14364.ic28", 0x000006, 0x080000, CRC(0fa12ecd) SHA1(6a34c7718edffbeddded8786e11cac181b485ebd) )
ROM_LOAD64_BYTE( "mpr-14363.ic24", 0x000007, 0x080000, CRC(f3427a56) SHA1(6a99d7432dfff35470ddcca5cfde36689a77e706) )
ROM_REGION( 0x200000, "slavepcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-14451a.ic6", 0x000000, 0x020000, CRC(e17259c9) SHA1(be789b7630b7265e19ea2c80f603caff9cec37f8) )
ROM_LOAD16_BYTE_x2( "epr-14445.ic14", 0x100000, 0x040000, CRC(d06261ab) SHA1(6e1c4ce4e49a142fd5b1ecac98145960d7afd567) )
ROM_LOAD16_BYTE_x2( "epr-14444.ic7", 0x100001, 0x040000, CRC(07724354) SHA1(9d7f64a80553c4ae0e9cf716478fd5c4b8277470) )
ROM_REGION( 0x400000, "slavepcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-14449.ic35", 0x000000, 0x020000, CRC(2d29699c) SHA1(cae02e5533a0edd3b3b4a54a1a43321285e06416) )
ROM_LOAD_x2( "epr-14448.ic31", 0x100000, 0x080000, CRC(87ca1e8d) SHA1(739274171c13983a60d061176095645419dade49) )
ROM_LOAD_x2( "epr-14447.ic26", 0x200000, 0x080000, CRC(db1cfcbd) SHA1(c76eb2ced5571a548ad00709097dd272747127a2) )
ROM_LOAD_x2( "epr-14446.ic22", 0x300000, 0x080000, CRC(646ec2cb) SHA1(67e453f128ae227e22c68f55d0d3f5831fbeb2f9) )
ROM_REGION( 0x100000, "slavepcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14362.ic38", 0x000000, 0x040000, CRC(fb1c4e79) SHA1(38ee23763b9e5bb62bbc54cab95041415404f0c4) )
ROM_LOAD32_BYTE( "mpr-14361.ic34", 0x000002, 0x040000, CRC(e3204bda) SHA1(34157e80edd6d685bd5a5e23b1e0130a5f3d138a) )
ROM_LOAD32_BYTE( "mpr-14360.ic29", 0x000001, 0x040000, CRC(c5e8da79) SHA1(662a6c146fe3d0b8763d845379c06d0ee6ced1ed) )
ROM_LOAD32_BYTE( "mpr-14359.ic25", 0x000003, 0x040000, CRC(70305c68) SHA1(7a6a1bf7381eba8cc1c3897497b32ca63316972a) )
ROM_REGION32_BE( 0x800000, "slavepcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14370.ic36", 0x000000, 0x080000, CRC(fda78289) SHA1(3740affdcc738c50d07ff3e5b592bdf8a8b6be15) )
ROM_LOAD64_BYTE( "mpr-14369.ic32", 0x000001, 0x080000, CRC(7765116d) SHA1(9493148aa84adc90143cf638265d4c55bfb43990) )
ROM_LOAD64_BYTE( "mpr-14368.ic27", 0x000002, 0x080000, CRC(5744a30e) SHA1(98544fb234a8e93716e951d5414a490845e213c5) )
ROM_LOAD64_BYTE( "mpr-14367.ic23", 0x000003, 0x080000, CRC(77bb9003) SHA1(6370fdeab4967976840d752577cd860b9ce8efca) )
ROM_LOAD64_BYTE( "mpr-14366.ic37", 0x000004, 0x080000, CRC(21078e83) SHA1(f35f643c28aad3bf18cb9906b114c4f49b7b4cd1) )
ROM_LOAD64_BYTE( "mpr-14365.ic33", 0x000005, 0x080000, CRC(36913790) SHA1(4a447cffb44b023fe1441277db1e411d4cd119eb) )
ROM_LOAD64_BYTE( "mpr-14364.ic28", 0x000006, 0x080000, CRC(0fa12ecd) SHA1(6a34c7718edffbeddded8786e11cac181b485ebd) )
ROM_LOAD64_BYTE( "mpr-14363.ic24", 0x000007, 0x080000, CRC(f3427a56) SHA1(6a99d7432dfff35470ddcca5cfde36689a77e706) )
ROM_END
/**************************************************************************************************************************
F1 Exhaust Note (Japan)
to display the title screen this will require 2 linked system32 boards to be emulated
Sega Game ID codes:
GAME BD NO. 833-8389-03 EXHAUST NOTE
ROM BD. 834-8439-03
MAIN BD. 837-7428 (SYSTEM 32 COM)
Link PCB NO. 837-8223-01
A/D BD NO. 837-7536
*/
ROM_START( f1enj ) // ROM PCB number is 834-8439-04
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-14450a.ic6", 0x000000, 0x020000, CRC(10f62723) SHA1(68fcd6655798f348678e3cc8857c6d1cb46e0987) )
ROM_LOAD16_BYTE_x2( "epr-14445.ic14", 0x100000, 0x040000, CRC(d06261ab) SHA1(6e1c4ce4e49a142fd5b1ecac98145960d7afd567) )
ROM_LOAD16_BYTE_x2( "epr-14444.ic7", 0x100001, 0x040000, CRC(07724354) SHA1(9d7f64a80553c4ae0e9cf716478fd5c4b8277470) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-14449.ic35", 0x000000, 0x020000, CRC(2d29699c) SHA1(cae02e5533a0edd3b3b4a54a1a43321285e06416) )
ROM_LOAD_x2( "epr-14448.ic31", 0x100000, 0x080000, CRC(87ca1e8d) SHA1(739274171c13983a60d061176095645419dade49) )
ROM_LOAD_x2( "epr-14447.ic26", 0x200000, 0x080000, CRC(db1cfcbd) SHA1(c76eb2ced5571a548ad00709097dd272747127a2) )
ROM_LOAD_x2( "epr-14446.ic22", 0x300000, 0x080000, CRC(646ec2cb) SHA1(67e453f128ae227e22c68f55d0d3f5831fbeb2f9) )
ROM_REGION( 0x100000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14362.ic38", 0x000000, 0x040000, CRC(fb1c4e79) SHA1(38ee23763b9e5bb62bbc54cab95041415404f0c4) )
ROM_LOAD32_BYTE( "mpr-14361.ic34", 0x000002, 0x040000, CRC(e3204bda) SHA1(34157e80edd6d685bd5a5e23b1e0130a5f3d138a) )
ROM_LOAD32_BYTE( "mpr-14360.ic29", 0x000001, 0x040000, CRC(c5e8da79) SHA1(662a6c146fe3d0b8763d845379c06d0ee6ced1ed) )
ROM_LOAD32_BYTE( "mpr-14359.ic25", 0x000003, 0x040000, CRC(70305c68) SHA1(7a6a1bf7381eba8cc1c3897497b32ca63316972a) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14370.ic36", 0x000000, 0x080000, CRC(fda78289) SHA1(3740affdcc738c50d07ff3e5b592bdf8a8b6be15) )
ROM_LOAD64_BYTE( "mpr-14369.ic32", 0x000001, 0x080000, CRC(7765116d) SHA1(9493148aa84adc90143cf638265d4c55bfb43990) )
ROM_LOAD64_BYTE( "mpr-14368.ic27", 0x000002, 0x080000, CRC(5744a30e) SHA1(98544fb234a8e93716e951d5414a490845e213c5) )
ROM_LOAD64_BYTE( "mpr-14367.ic23", 0x000003, 0x080000, CRC(77bb9003) SHA1(6370fdeab4967976840d752577cd860b9ce8efca) )
ROM_LOAD64_BYTE( "mpr-14366.ic37", 0x000004, 0x080000, CRC(21078e83) SHA1(f35f643c28aad3bf18cb9906b114c4f49b7b4cd1) )
ROM_LOAD64_BYTE( "mpr-14365.ic33", 0x000005, 0x080000, CRC(36913790) SHA1(4a447cffb44b023fe1441277db1e411d4cd119eb) )
ROM_LOAD64_BYTE( "mpr-14364.ic28", 0x000006, 0x080000, CRC(0fa12ecd) SHA1(6a34c7718edffbeddded8786e11cac181b485ebd) )
ROM_LOAD64_BYTE( "mpr-14363.ic24", 0x000007, 0x080000, CRC(f3427a56) SHA1(6a99d7432dfff35470ddcca5cfde36689a77e706) )
ROM_REGION( 0x200000, "slavepcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-14450a.ic6", 0x000000, 0x020000, CRC(10f62723) SHA1(68fcd6655798f348678e3cc8857c6d1cb46e0987) )
ROM_LOAD16_BYTE_x2( "epr-14445.ic14", 0x100000, 0x040000, CRC(d06261ab) SHA1(6e1c4ce4e49a142fd5b1ecac98145960d7afd567) )
ROM_LOAD16_BYTE_x2( "epr-14444.ic7", 0x100001, 0x040000, CRC(07724354) SHA1(9d7f64a80553c4ae0e9cf716478fd5c4b8277470) )
ROM_REGION( 0x400000, "slavepcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-14449.ic35", 0x000000, 0x020000, CRC(2d29699c) SHA1(cae02e5533a0edd3b3b4a54a1a43321285e06416) )
ROM_LOAD_x2( "epr-14448.ic31", 0x100000, 0x080000, CRC(87ca1e8d) SHA1(739274171c13983a60d061176095645419dade49) )
ROM_LOAD_x2( "epr-14447.ic26", 0x200000, 0x080000, CRC(db1cfcbd) SHA1(c76eb2ced5571a548ad00709097dd272747127a2) )
ROM_LOAD_x2( "epr-14446.ic22", 0x300000, 0x080000, CRC(646ec2cb) SHA1(67e453f128ae227e22c68f55d0d3f5831fbeb2f9) )
ROM_REGION( 0x100000, "slavepcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14362.ic38", 0x000000, 0x040000, CRC(fb1c4e79) SHA1(38ee23763b9e5bb62bbc54cab95041415404f0c4) )
ROM_LOAD32_BYTE( "mpr-14361.ic34", 0x000002, 0x040000, CRC(e3204bda) SHA1(34157e80edd6d685bd5a5e23b1e0130a5f3d138a) )
ROM_LOAD32_BYTE( "mpr-14360.ic29", 0x000001, 0x040000, CRC(c5e8da79) SHA1(662a6c146fe3d0b8763d845379c06d0ee6ced1ed) )
ROM_LOAD32_BYTE( "mpr-14359.ic25", 0x000003, 0x040000, CRC(70305c68) SHA1(7a6a1bf7381eba8cc1c3897497b32ca63316972a) )
ROM_REGION32_BE( 0x800000, "slavepcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14370.ic36", 0x000000, 0x080000, CRC(fda78289) SHA1(3740affdcc738c50d07ff3e5b592bdf8a8b6be15) )
ROM_LOAD64_BYTE( "mpr-14369.ic32", 0x000001, 0x080000, CRC(7765116d) SHA1(9493148aa84adc90143cf638265d4c55bfb43990) )
ROM_LOAD64_BYTE( "mpr-14368.ic27", 0x000002, 0x080000, CRC(5744a30e) SHA1(98544fb234a8e93716e951d5414a490845e213c5) )
ROM_LOAD64_BYTE( "mpr-14367.ic23", 0x000003, 0x080000, CRC(77bb9003) SHA1(6370fdeab4967976840d752577cd860b9ce8efca) )
ROM_LOAD64_BYTE( "mpr-14366.ic37", 0x000004, 0x080000, CRC(21078e83) SHA1(f35f643c28aad3bf18cb9906b114c4f49b7b4cd1) )
ROM_LOAD64_BYTE( "mpr-14365.ic33", 0x000005, 0x080000, CRC(36913790) SHA1(4a447cffb44b023fe1441277db1e411d4cd119eb) )
ROM_LOAD64_BYTE( "mpr-14364.ic28", 0x000006, 0x080000, CRC(0fa12ecd) SHA1(6a34c7718edffbeddded8786e11cac181b485ebd) )
ROM_LOAD64_BYTE( "mpr-14363.ic24", 0x000007, 0x080000, CRC(f3427a56) SHA1(6a99d7432dfff35470ddcca5cfde36689a77e706) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
F1 Super Lap (Export)
protected via FD1149 317-0210
GAME BD NO. 833-9407-02 F1 SUPER LAP
ROM BD. 834-9408-02
A/D BD NO. 837-7536
*/
ROM_START( f1lap )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-15598.ic17", 0x000000, 0x020000, CRC(9feab7cd) SHA1(2a14c0df39e7bdae12a34679fabc6abb7618e27d) )
ROM_LOAD_x4( "epr-15611.ic8", 0x080000, 0x020000, CRC(0d8c97c2) SHA1(863c606c58faddc2bdaeb69f9079266155ff9a96) )
ROM_LOAD16_BYTE_x2( "epr-15596.ic18", 0x100000, 0x040000, CRC(20e92909) SHA1(b974c79e11bfbd1cee61f9041cf79971fd96db3a) )
ROM_LOAD16_BYTE_x2( "epr-15597.ic9", 0x100001, 0x040000, CRC(cd1ccddb) SHA1(ff0371a8010141d1ab81b5eba555ae7c64e5da37) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-15592.ic36", 0x000000, 0x020000, CRC(7c055cc8) SHA1(169beb83dfae86dd408aa92b3c214b8f607825fc) )
ROM_LOAD( "mpr-15593.ic35", 0x100000, 0x100000, CRC(e7300441) SHA1(33c264f0e6326689ba75026932c0932868e83b25) )
ROM_LOAD( "mpr-15594.ic34", 0x200000, 0x100000, CRC(7f4ca3bb) SHA1(dc53a1857d619e574acb4c0587a6ba844df2d283) )
ROM_LOAD( "mpr-15595.ic24", 0x300000, 0x100000, CRC(3fbdad9a) SHA1(573ea2242f79c7d3b6bf0e6745f6b07a621834ac) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15608.ic14", 0x000000, 0x200000, CRC(64462c69) SHA1(9501e83c52e3e16f73b94cef975b5a31b2ee5476) )
ROM_LOAD16_BYTE( "mpr-15609.ic5", 0x000001, 0x200000, CRC(d586e455) SHA1(aea190d31c590216eb19766ba749b1e9b710bdce) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15600.ic32", 0x000000, 0x200000, CRC(d2698d23) SHA1(996fbcc1d0814e6f14fa7e4870ece077ecda54e6) )
ROM_LOAD64_WORD( "mpr-15602.ic30", 0x000002, 0x200000, CRC(1674764d) SHA1(bc39757a5d25df1a088f874ca2442854eb551e48) )
ROM_LOAD64_WORD( "mpr-15604.ic28", 0x000004, 0x200000, CRC(1552bbb9) SHA1(77edd3f9d8dec87fa0445d264309e6164eba9313) )
ROM_LOAD64_WORD( "mpr-15606.ic26", 0x000006, 0x200000, CRC(2b4f5265) SHA1(48b4ccdedb52fbf80661ff380e5a273201fc0a12) )
ROM_LOAD64_WORD( "mpr-15601.ic31", 0x800000, 0x200000, CRC(31a8f40a) SHA1(62798346750dea87e43c8a8b01c33bf886bb50f4) )
ROM_LOAD64_WORD( "mpr-15603.ic29", 0x800002, 0x200000, CRC(3805ecbc) SHA1(54d29250441160f282c70adfd515adb21d2cda33) )
ROM_LOAD64_WORD( "mpr-15605.ic27", 0x800004, 0x200000, CRC(cbdbf35e) SHA1(a1c0900ac3210e72f5848561a6c4a77c804782c6) )
ROM_LOAD64_WORD( "mpr-15607.ic25", 0x800006, 0x200000, CRC(6c8817c9) SHA1(f5d493ed4237caf5042e95373bf9abd1fd16f873) )
ROM_REGION( 0x20000, "user2", 0 ) /* comms board */
ROM_LOAD( "15612", 0x00000, 0x20000, CRC(9d204617) SHA1(8db57121065f5d1ac52fcfb88459bdbdc30e645b) )
ROM_END
/**************************************************************************************************************************
F1 Super Lap (Export) - Unprotected (Test version?)
*/
ROM_START( f1lapt )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-15598.ic17", 0x000000, 0x020000, CRC(9feab7cd) SHA1(2a14c0df39e7bdae12a34679fabc6abb7618e27d) )
ROM_LOAD_x4( "epr-15611t.ic8", 0x080000, 0x020000, CRC(7a57b792) SHA1(77c96c841e90e9292182875822c85a2014d2d125) )
ROM_LOAD16_BYTE_x2( "epr-15596t.ic18", 0x100000, 0x040000, CRC(20e92909) SHA1(b974c79e11bfbd1cee61f9041cf79971fd96db3a) )
ROM_LOAD16_BYTE_x2( "epr-15597t.ic9", 0x100001, 0x040000, CRC(cd1ccddb) SHA1(ff0371a8010141d1ab81b5eba555ae7c64e5da37) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-15592.ic36", 0x000000, 0x020000, CRC(7c055cc8) SHA1(169beb83dfae86dd408aa92b3c214b8f607825fc) )
ROM_LOAD( "mpr-15593.ic35", 0x100000, 0x100000, CRC(e7300441) SHA1(33c264f0e6326689ba75026932c0932868e83b25) )
ROM_LOAD( "mpr-15594.ic34", 0x200000, 0x100000, CRC(7f4ca3bb) SHA1(dc53a1857d619e574acb4c0587a6ba844df2d283) )
ROM_LOAD( "mpr-15595.ic24", 0x300000, 0x100000, CRC(3fbdad9a) SHA1(573ea2242f79c7d3b6bf0e6745f6b07a621834ac) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15608.ic14", 0x000000, 0x200000, CRC(64462c69) SHA1(9501e83c52e3e16f73b94cef975b5a31b2ee5476) )
ROM_LOAD16_BYTE( "mpr-15609.ic5", 0x000001, 0x200000, CRC(d586e455) SHA1(aea190d31c590216eb19766ba749b1e9b710bdce) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15600.ic32", 0x000000, 0x200000, CRC(d2698d23) SHA1(996fbcc1d0814e6f14fa7e4870ece077ecda54e6) )
ROM_LOAD64_WORD( "mpr-15602.ic30", 0x000002, 0x200000, CRC(1674764d) SHA1(bc39757a5d25df1a088f874ca2442854eb551e48) )
ROM_LOAD64_WORD( "mpr-15604.ic28", 0x000004, 0x200000, CRC(1552bbb9) SHA1(77edd3f9d8dec87fa0445d264309e6164eba9313) )
ROM_LOAD64_WORD( "mpr-15606.ic26", 0x000006, 0x200000, CRC(2b4f5265) SHA1(48b4ccdedb52fbf80661ff380e5a273201fc0a12) )
ROM_LOAD64_WORD( "mpr-15601.ic31", 0x800000, 0x200000, CRC(31a8f40a) SHA1(62798346750dea87e43c8a8b01c33bf886bb50f4) )
ROM_LOAD64_WORD( "mpr-15603.ic29", 0x800002, 0x200000, CRC(3805ecbc) SHA1(54d29250441160f282c70adfd515adb21d2cda33) )
ROM_LOAD64_WORD( "mpr-15605.ic27", 0x800004, 0x200000, CRC(cbdbf35e) SHA1(a1c0900ac3210e72f5848561a6c4a77c804782c6) )
ROM_LOAD64_WORD( "mpr-15607.ic25", 0x800006, 0x200000, CRC(6c8817c9) SHA1(f5d493ed4237caf5042e95373bf9abd1fd16f873) )
ROM_REGION( 0x20000, "user2", 0 ) /* comms board */
ROM_LOAD( "15612", 0x00000, 0x20000, CRC(9d204617) SHA1(8db57121065f5d1ac52fcfb88459bdbdc30e645b) )
ROM_END
/**************************************************************************************************************************
F1 Super Lap (Japan)
protected via FD1149 317-0210
Sega Game ID codes:
GAME BD NO. 833-9407 F1 SUPER LAP
A/D BD NO. 837-7536
*/
ROM_START( f1lapj )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-15598.ic17", 0x000000, 0x020000, CRC(9feab7cd) SHA1(2a14c0df39e7bdae12a34679fabc6abb7618e27d) )
ROM_LOAD_x4( "epr-15599.ic8", 0x080000, 0x020000, CRC(5c5ac112) SHA1(2c071946e33f0700a832c7aad36f639acd35f555) )
ROM_LOAD16_BYTE_x2( "epr-15596.ic18", 0x100000, 0x040000, CRC(20e92909) SHA1(b974c79e11bfbd1cee61f9041cf79971fd96db3a) )
ROM_LOAD16_BYTE_x2( "epr-15597.ic9", 0x100001, 0x040000, CRC(cd1ccddb) SHA1(ff0371a8010141d1ab81b5eba555ae7c64e5da37) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-15592.ic36", 0x000000, 0x020000, CRC(7c055cc8) SHA1(169beb83dfae86dd408aa92b3c214b8f607825fc) )
ROM_LOAD( "mpr-15593.ic35", 0x100000, 0x100000, CRC(e7300441) SHA1(33c264f0e6326689ba75026932c0932868e83b25) )
ROM_LOAD( "mpr-15594.ic34", 0x200000, 0x100000, CRC(7f4ca3bb) SHA1(dc53a1857d619e574acb4c0587a6ba844df2d283) )
ROM_LOAD( "mpr-15595.ic24", 0x300000, 0x100000, CRC(3fbdad9a) SHA1(573ea2242f79c7d3b6bf0e6745f6b07a621834ac) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15608.ic14", 0x000000, 0x200000, CRC(64462c69) SHA1(9501e83c52e3e16f73b94cef975b5a31b2ee5476) )
ROM_LOAD16_BYTE( "mpr-15609.ic5", 0x000001, 0x200000, CRC(d586e455) SHA1(aea190d31c590216eb19766ba749b1e9b710bdce) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15600.ic32", 0x000000, 0x200000, CRC(d2698d23) SHA1(996fbcc1d0814e6f14fa7e4870ece077ecda54e6) )
ROM_LOAD64_WORD( "mpr-15602.ic30", 0x000002, 0x200000, CRC(1674764d) SHA1(bc39757a5d25df1a088f874ca2442854eb551e48) )
ROM_LOAD64_WORD( "mpr-15604.ic28", 0x000004, 0x200000, CRC(1552bbb9) SHA1(77edd3f9d8dec87fa0445d264309e6164eba9313) )
ROM_LOAD64_WORD( "mpr-15606.ic26", 0x000006, 0x200000, CRC(2b4f5265) SHA1(48b4ccdedb52fbf80661ff380e5a273201fc0a12) )
ROM_LOAD64_WORD( "mpr-15601.ic31", 0x800000, 0x200000, CRC(31a8f40a) SHA1(62798346750dea87e43c8a8b01c33bf886bb50f4) )
ROM_LOAD64_WORD( "mpr-15603.ic29", 0x800002, 0x200000, CRC(3805ecbc) SHA1(54d29250441160f282c70adfd515adb21d2cda33) )
ROM_LOAD64_WORD( "mpr-15605.ic27", 0x800004, 0x200000, CRC(cbdbf35e) SHA1(a1c0900ac3210e72f5848561a6c4a77c804782c6) )
ROM_LOAD64_WORD( "mpr-15607.ic25", 0x800006, 0x200000, CRC(6c8817c9) SHA1(f5d493ed4237caf5042e95373bf9abd1fd16f873) )
ROM_REGION( 0x20000, "user2", 0 ) /* comms board */
ROM_LOAD( "15612", 0x00000, 0x20000, CRC(9d204617) SHA1(8db57121065f5d1ac52fcfb88459bdbdc30e645b) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Golden Axe: The Revenge of Death Adder (Export)
protected via a custom V25 with encrypted code
Sega Game ID codes:
Game: 833-8932-03 GOLDEN AXE II AC EXP
ROM board: 833-8933-02
Sub board: 834-8529-02
A/D board: 837-7968
*/
ROM_START( ga2 )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14961b.ic17", 0x000000, 0x020000, CRC(d9cd8885) SHA1(dc9d1f01770bd23ba5959e300badbc5093a149bc) )
ROM_LOAD_x4( "epr-14958b.ic8", 0x080000, 0x020000, CRC(0be324a3) SHA1(5e5f457548906453eaa8d326c353b47353eab73d) )
ROM_LOAD16_BYTE_x2( "epr-15148b.ic18", 0x100000, 0x040000, CRC(c477a9fd) SHA1(a9d60f801c12fd067e5ad1801a92c84edd13bd08) )
ROM_LOAD16_BYTE_x2( "epr-15147b.ic9", 0x100001, 0x040000, CRC(1bb676ea) SHA1(125ffd13204f48be23e20b281c42c2307888c40b) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU + banks */
ROM_LOAD_x16( "epr-14945.ic36", 0x000000, 0x010000, CRC(4781d4cb) SHA1(bd1b774b3cd0c3e0290c55e426f66d6820d21d0f) )
ROM_LOAD( "mpr-14944.ic35", 0x100000, 0x100000, CRC(fd4d4b86) SHA1(e14b9cd6004bf9ecd902e37b433b828241361b46) )
ROM_LOAD( "mpr-14943.ic34", 0x200000, 0x100000, CRC(24d40333) SHA1(38faf8f3eac317a163e93bd2247fe98189b13d2d) )
ROM_LOAD( "mpr-14942.ic24", 0x300000, 0x100000, CRC(a89b0e90) SHA1(e14c62418eb7f9a2deb2a6dcf635bedc1c73c253) )
ROM_REGION( 0x10000, "mainpcb:mcu", 0 ) /* Protection CPU */
ROM_LOAD( "epr-14468-02.u3", 0x00000, 0x10000, CRC(77634daa) SHA1(339169d164b9ed7dc3787b084d33effdc8e9efc1) ) /* located on separate sub board */
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-14948.ic14", 0x000000, 0x200000, CRC(75050d4a) SHA1(51d6bc9935abcf30af438e69c2cf4e09f57a803f) )
ROM_LOAD16_BYTE( "mpr-14947.ic5", 0x000001, 0x200000, CRC(b53e62f4) SHA1(5aa0f198e6eb070b77b0d180d30c0228a9bc691e) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-14949.ic32", 0x000000, 0x200000, CRC(152c716c) SHA1(448d16ea036b66e886119c00af543dfa5e53fd84) )
ROM_LOAD64_WORD( "mpr-14951.ic30", 0x000002, 0x200000, CRC(fdb1a534) SHA1(3126b595bf69bf9952fedf8f9c6743eb10489dc6) )
ROM_LOAD64_WORD( "mpr-14953.ic28", 0x000004, 0x200000, CRC(33bd1c15) SHA1(4e16562e3357d4db54b20543073e8f1fd6f74b1f) )
ROM_LOAD64_WORD( "mpr-14955.ic26", 0x000006, 0x200000, CRC(e42684aa) SHA1(12e0f18a11edb46f09e2e8c5c4ba14170d0cf00d) )
ROM_LOAD64_WORD( "mpr-14950.ic31", 0x800000, 0x200000, CRC(15fd0026) SHA1(e918984bd60ad63172fe273b31cc9019100228c8) )
ROM_LOAD64_WORD( "mpr-14952.ic29", 0x800002, 0x200000, CRC(96f96613) SHA1(4c9808866032dab0401de322c28242e8a8775457) )
ROM_LOAD64_WORD( "mpr-14954.ic27", 0x800004, 0x200000, CRC(39b2ac9e) SHA1(74f4c81d85ab9b4c5e8ae4b4d2c6dff766c482ca) )
ROM_LOAD64_WORD( "mpr-14956.ic25", 0x800006, 0x200000, CRC(298fca50) SHA1(16e09b19cc7be3dfc8e82b45348e6d1cf2ed5621) )
ROM_END
/**************************************************************************************************************************
Golden Axe: The Revenge of Death Adder (US)
protected via a custom V25 with encrypted code
Sega Game ID codes:
Game: 833-8932-02 GOLDEN AXE II AC USA
ROM board: 833-8933-01
Sub board: 834-8529-02
A/D board: 837-7968
*/
ROM_START( ga2u )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14960a.ic17", 0x000000, 0x020000, CRC(87182fea) SHA1(bb669ea7091f1ea34589a565490effa934ca44a3) )
ROM_LOAD_x4( "epr-14957a.ic8", 0x080000, 0x020000, CRC(ab787cf4) SHA1(7e19bb3e5d587b5009efc9f9fa52aecaef0eedc4) )
ROM_LOAD16_BYTE_x2( "epr-15146a.ic18", 0x100000, 0x040000, CRC(7293d5c3) SHA1(535a8b4b4a05546b321cee8de6733edfc1f71589) )
ROM_LOAD16_BYTE_x2( "epr-15145a.ic9", 0x100001, 0x040000, CRC(0da61782) SHA1(f0302d747e5d55663095bb38732af423104c33ea) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU + banks */
ROM_LOAD_x16( "epr-14945.ic36", 0x000000, 0x010000, CRC(4781d4cb) SHA1(bd1b774b3cd0c3e0290c55e426f66d6820d21d0f) )
ROM_LOAD( "mpr-14944.ic35", 0x100000, 0x100000, CRC(fd4d4b86) SHA1(e14b9cd6004bf9ecd902e37b433b828241361b46) )
ROM_LOAD( "mpr-14943.ic34", 0x200000, 0x100000, CRC(24d40333) SHA1(38faf8f3eac317a163e93bd2247fe98189b13d2d) )
ROM_LOAD( "mpr-14942.ic24", 0x300000, 0x100000, CRC(a89b0e90) SHA1(e14c62418eb7f9a2deb2a6dcf635bedc1c73c253) )
ROM_REGION( 0x10000, "mainpcb:mcu", 0 ) /* Protection CPU */
ROM_LOAD( "epr-14468-02.u3", 0x00000, 0x10000, CRC(77634daa) SHA1(339169d164b9ed7dc3787b084d33effdc8e9efc1) ) /* located on separate sub board */
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-14948.ic14", 0x000000, 0x200000, CRC(75050d4a) SHA1(51d6bc9935abcf30af438e69c2cf4e09f57a803f) )
ROM_LOAD16_BYTE( "mpr-14947.ic5", 0x000001, 0x200000, CRC(b53e62f4) SHA1(5aa0f198e6eb070b77b0d180d30c0228a9bc691e) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-14949.ic32", 0x000000, 0x200000, CRC(152c716c) SHA1(448d16ea036b66e886119c00af543dfa5e53fd84) )
ROM_LOAD64_WORD( "mpr-14951.ic30", 0x000002, 0x200000, CRC(fdb1a534) SHA1(3126b595bf69bf9952fedf8f9c6743eb10489dc6) )
ROM_LOAD64_WORD( "mpr-14953.ic28", 0x000004, 0x200000, CRC(33bd1c15) SHA1(4e16562e3357d4db54b20543073e8f1fd6f74b1f) )
ROM_LOAD64_WORD( "mpr-14955.ic26", 0x000006, 0x200000, CRC(e42684aa) SHA1(12e0f18a11edb46f09e2e8c5c4ba14170d0cf00d) )
ROM_LOAD64_WORD( "mpr-14950.ic31", 0x800000, 0x200000, CRC(15fd0026) SHA1(e918984bd60ad63172fe273b31cc9019100228c8) )
ROM_LOAD64_WORD( "mpr-14952.ic29", 0x800002, 0x200000, CRC(96f96613) SHA1(4c9808866032dab0401de322c28242e8a8775457) )
ROM_LOAD64_WORD( "mpr-14954.ic27", 0x800004, 0x200000, CRC(39b2ac9e) SHA1(74f4c81d85ab9b4c5e8ae4b4d2c6dff766c482ca) )
ROM_LOAD64_WORD( "mpr-14956.ic25", 0x800006, 0x200000, CRC(298fca50) SHA1(16e09b19cc7be3dfc8e82b45348e6d1cf2ed5621) )
ROM_END
/**************************************************************************************************************************
Golden Axe: The Revenge of Death Adder (Japan)
protected via a custom V25 with encrypted code
ROM board: 833-8933
Sub board: 834-8529-02
A/D board: 837-7968
*/
ROM_START( ga2j )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14959.ic17", 0x000000, 0x020000, CRC(f1929177) SHA1(7dc39c40eff9fb46c2e51d1e83478cd6970e3951) )
ROM_LOAD_x4( "epr-14946.ic8", 0x080000, 0x020000, CRC(eacafe94) SHA1(d41a7e1ee2df9e053b559be0a1a6d2ae520fd3e4) )
ROM_LOAD16_BYTE_x2( "epr-14941.ic18", 0x100000, 0x040000, CRC(0ffb8203) SHA1(b27dce634d203af8abb6ddfb656d4c48eb54af01) )
ROM_LOAD16_BYTE_x2( "epr-14940.ic9", 0x100001, 0x040000, CRC(3b5b3084) SHA1(ea17f6b7fd413fe3808f822cec84c993c9b75aa2) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU + banks */
ROM_LOAD_x16( "epr-14945.ic36", 0x000000, 0x010000, CRC(4781d4cb) SHA1(bd1b774b3cd0c3e0290c55e426f66d6820d21d0f) )
ROM_LOAD( "mpr-14944.ic35", 0x100000, 0x100000, CRC(fd4d4b86) SHA1(e14b9cd6004bf9ecd902e37b433b828241361b46) )
ROM_LOAD( "mpr-14943.ic34", 0x200000, 0x100000, CRC(24d40333) SHA1(38faf8f3eac317a163e93bd2247fe98189b13d2d) )
ROM_LOAD( "mpr-14942.ic24", 0x300000, 0x100000, CRC(a89b0e90) SHA1(e14c62418eb7f9a2deb2a6dcf635bedc1c73c253) )
ROM_REGION( 0x10000, "mainpcb:mcu", 0 ) /* Protection CPU */
ROM_LOAD( "epr-14468-02.u3", 0x00000, 0x10000, CRC(77634daa) SHA1(339169d164b9ed7dc3787b084d33effdc8e9efc1) ) /* located on separate sub board */
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-14948.ic14", 0x000000, 0x200000, CRC(75050d4a) SHA1(51d6bc9935abcf30af438e69c2cf4e09f57a803f) )
ROM_LOAD16_BYTE( "mpr-14947.ic5", 0x000001, 0x200000, CRC(b53e62f4) SHA1(5aa0f198e6eb070b77b0d180d30c0228a9bc691e) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-14949.ic32", 0x000000, 0x200000, CRC(152c716c) SHA1(448d16ea036b66e886119c00af543dfa5e53fd84) )
ROM_LOAD64_WORD( "mpr-14951.ic30", 0x000002, 0x200000, CRC(fdb1a534) SHA1(3126b595bf69bf9952fedf8f9c6743eb10489dc6) )
ROM_LOAD64_WORD( "mpr-14953.ic28", 0x000004, 0x200000, CRC(33bd1c15) SHA1(4e16562e3357d4db54b20543073e8f1fd6f74b1f) )
ROM_LOAD64_WORD( "mpr-14955.ic26", 0x000006, 0x200000, CRC(e42684aa) SHA1(12e0f18a11edb46f09e2e8c5c4ba14170d0cf00d) )
ROM_LOAD64_WORD( "mpr-14950.ic31", 0x800000, 0x200000, CRC(15fd0026) SHA1(e918984bd60ad63172fe273b31cc9019100228c8) )
ROM_LOAD64_WORD( "mpr-14952.ic29", 0x800002, 0x200000, CRC(96f96613) SHA1(4c9808866032dab0401de322c28242e8a8775457) )
ROM_LOAD64_WORD( "mpr-14954.ic27", 0x800004, 0x200000, CRC(39b2ac9e) SHA1(74f4c81d85ab9b4c5e8ae4b4d2c6dff766c482ca) )
ROM_LOAD64_WORD( "mpr-14956.ic25", 0x800006, 0x200000, CRC(298fca50) SHA1(16e09b19cc7be3dfc8e82b45348e6d1cf2ed5621) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Hard Dunk (Export) - Multi-32
not protected
*/
ROM_START( harddunk )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code */
ROM_LOAD32_WORD_x2( "epr-16512.ic37", 0x000000, 0x40000, CRC(1a7de085) SHA1(2e0dac1f7715089b7f6b1035c859ffe2d674932f) )
/* the following is the same as 16509.ic40 but with a different name, unusual for Sega */
ROM_LOAD32_WORD_x2( "epr-16513.ic40", 0x000002, 0x40000, CRC(603dee75) SHA1(32ae964a4b57d470b4900cca6e06329f1a75a6e6) )
ROM_REGION( 0x80000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-16505.ic31", 0x00000, 0x20000, CRC(eeb90a07) SHA1(d1c2132897994b2e85fd5a97222b9fcd61bc421e) )
ROM_REGION( 0x100000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16503.ic3", 0x000000, 0x080000, CRC(ac1b6f1a) SHA1(56482931adf7fe551acf796b74cd8af3773d4fef) )
ROM_LOAD16_BYTE( "mpr-16504.ic11", 0x000001, 0x080000, CRC(7c61fcd8) SHA1(ca4354f90fada752bf11ee22a7798a8aa22b1c61) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16495.ic14", 0x000000, 0x200000, CRC(6e5f26be) SHA1(146761072bbed08f4a9df8a474b34fab61afaa4f) )
ROM_LOAD64_WORD( "mpr-16497.ic15", 0x000002, 0x200000, CRC(42ab5859) SHA1(f50c51eb81186aec5f747ecab4c5c928f8701afc) )
ROM_LOAD64_WORD( "mpr-16499.ic10", 0x000004, 0x200000, CRC(a290ea36) SHA1(2503b44174f23a9d323caab86553977d1d6d9c94) )
ROM_LOAD64_WORD( "mpr-16501.ic38", 0x000006, 0x200000, CRC(f1566620) SHA1(bcf31d11ee669d5afc7dc22c42fa59f4e48c1f50) )
ROM_LOAD64_WORD( "mpr-16496.ic22", 0x800000, 0x200000, CRC(d9d27247) SHA1(d211623478516ed1b89ab16a7fc7969954c5e353) )
ROM_LOAD64_WORD( "mpr-16498.ic23", 0x800002, 0x200000, CRC(c022a991) SHA1(a660a20692f4d9ba7be73577328f69f109be5e47) )
ROM_LOAD64_WORD( "mpr-16500.ic18", 0x800004, 0x200000, CRC(452c0be3) SHA1(af87ce4618bae2d791c1baed34ba7f853af664ff) )
ROM_LOAD64_WORD( "mpr-16502.ic41", 0x800006, 0x200000, CRC(ffc3147e) SHA1(12d882dec3098674d27058a8009e8778555f477a) )
ROM_REGION( 0x400000, "mainpcb:sega", 0 ) /* Sega PCM sound data */
ROM_LOAD( "mpr-16506.1", 0x000000, 0x200000, CRC(e779f5ed) SHA1(462d1bbe8bb12a0c5a6d6c613c720b26ec21cb25) )
ROM_LOAD( "mpr-16507.2", 0x200000, 0x200000, CRC(31e068d3) SHA1(9ac88b15af441fb3b31ce759c565b60a09039571) )
ROM_END
/**************************************************************************************************************************
Hard Dunk (Japan) - Multi-32
not protected
*/
ROM_START( harddunkj )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code */
ROM_LOAD32_WORD_x2( "epr-16508.ic37", 0x000000, 0x40000, CRC(b3713be5) SHA1(8123638a838e41fcc0d32e14382421b521eff94f) )
ROM_LOAD32_WORD_x2( "epr-16509.ic40", 0x000002, 0x40000, CRC(603dee75) SHA1(32ae964a4b57d470b4900cca6e06329f1a75a6e6) )
ROM_REGION( 0x80000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-16505.ic31", 0x00000, 0x20000, CRC(eeb90a07) SHA1(d1c2132897994b2e85fd5a97222b9fcd61bc421e) )
ROM_REGION( 0x100000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16503.ic3", 0x000000, 0x080000, CRC(ac1b6f1a) SHA1(56482931adf7fe551acf796b74cd8af3773d4fef) )
ROM_LOAD16_BYTE( "mpr-16504.ic11", 0x000001, 0x080000, CRC(7c61fcd8) SHA1(ca4354f90fada752bf11ee22a7798a8aa22b1c61) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16495.ic14", 0x000000, 0x200000, CRC(6e5f26be) SHA1(146761072bbed08f4a9df8a474b34fab61afaa4f) )
ROM_LOAD64_WORD( "mpr-16497.ic15", 0x000002, 0x200000, CRC(42ab5859) SHA1(f50c51eb81186aec5f747ecab4c5c928f8701afc) )
ROM_LOAD64_WORD( "mpr-16499.ic10", 0x000004, 0x200000, CRC(a290ea36) SHA1(2503b44174f23a9d323caab86553977d1d6d9c94) )
ROM_LOAD64_WORD( "mpr-16501.ic38", 0x000006, 0x200000, CRC(f1566620) SHA1(bcf31d11ee669d5afc7dc22c42fa59f4e48c1f50) )
ROM_LOAD64_WORD( "mpr-16496.ic22", 0x800000, 0x200000, CRC(d9d27247) SHA1(d211623478516ed1b89ab16a7fc7969954c5e353) )
ROM_LOAD64_WORD( "mpr-16498.ic23", 0x800002, 0x200000, CRC(c022a991) SHA1(a660a20692f4d9ba7be73577328f69f109be5e47) )
ROM_LOAD64_WORD( "mpr-16500.ic18", 0x800004, 0x200000, CRC(452c0be3) SHA1(af87ce4618bae2d791c1baed34ba7f853af664ff) )
ROM_LOAD64_WORD( "mpr-16502.ic41", 0x800006, 0x200000, CRC(ffc3147e) SHA1(12d882dec3098674d27058a8009e8778555f477a) )
ROM_REGION( 0x400000, "mainpcb:sega", 0 ) /* Sega PCM sound data */
ROM_LOAD( "mpr-16506.ic1", 0x000000, 0x200000, CRC(e779f5ed) SHA1(462d1bbe8bb12a0c5a6d6c613c720b26ec21cb25) )
ROM_LOAD( "mpr-16507.ic2", 0x200000, 0x200000, CRC(31e068d3) SHA1(9ac88b15af441fb3b31ce759c565b60a09039571) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Holosseum (US)
not protected
Game: 833-8887-01 HOLOSSEUM
ROM board: 834-8888-01
*/
ROM_START( holo )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14977a", 0x000000, 0x020000, CRC(e0d7e288) SHA1(3126041ba73f21fac0207bf5c63230c61180f564) )
ROM_LOAD_x4( "epr-14976a", 0x080000, 0x020000, CRC(e56f13be) SHA1(3d9e7add8feaa35c4c2e8bda84ae251087bd5e40) )
ROM_LOAD16_BYTE_x4( "epr-15011", 0x100000, 0x020000, CRC(b9f59f59) SHA1(f8c91fa877cf53153bec3d7850eab38227cc18ba) )
ROM_LOAD16_BYTE_x4( "epr-15010", 0x100001, 0x020000, CRC(0c09c57b) SHA1(028a9fe1c625be218ba90906308d25d69d4de4c4) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-14965", 0x000000, 0x020000, CRC(3a918cfe) SHA1(f43ecbc9e774873e868bc921321541b308ea1a3c) )
ROM_LOAD( "mpr-14964", 0x100000, 0x100000, CRC(7ff581d5) SHA1(ab81bd70937319e4edc8924bdb493d5ef1ec096a) )
ROM_LOAD( "mpr-14963", 0x200000, 0x100000, CRC(0974a60e) SHA1(87d770edcee9c9e8f37d36ab28c5aa5d685ea849) )
ROM_LOAD( "mpr-14962", 0x300000, 0x100000, CRC(6b2e694e) SHA1(7874bdfd534231c7756e0e0d9fc7a3d5bdba74d3) )
ROM_REGION( 0x000100, "mainpcb:gfx1", ROMREGION_ERASEFF ) /* tiles */
/* game doesn't use bg tilemaps */
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14973", 0x000000, 0x100000, CRC(b3c3ff6b) SHA1(94e8dbfae37a5b122ee3d471aad1f758e4a39b9e) )
ROM_LOAD64_BYTE( "mpr-14972", 0x000001, 0x100000, CRC(0c161374) SHA1(413ab45deb687ecdbdc06ae98aa32ad8a0d80e0c) )
ROM_LOAD64_BYTE( "mpr-14971", 0x000002, 0x100000, CRC(dfcf6fdf) SHA1(417291b54010be20dd6738a70d372b580615a8bb) )
ROM_LOAD64_BYTE( "mpr-14970", 0x000003, 0x100000, CRC(cae3a745) SHA1(b6cc1f4abb460cda4714967e880928dc727ecf0a) )
ROM_LOAD64_BYTE( "mpr-14969", 0x000004, 0x100000, CRC(c06b7c15) SHA1(8b97a899e6eacf798b9f55af8df95e12ccacadec) )
ROM_LOAD64_BYTE( "mpr-14968", 0x000005, 0x100000, CRC(f413894a) SHA1(d65f57b1e55199e901c7c2f701589c46eeab739a) )
ROM_LOAD64_BYTE( "mpr-14967", 0x000006, 0x100000, CRC(5377fce0) SHA1(baf8f82ab851b24202938fc7213d72324b9b92c0) )
ROM_LOAD64_BYTE( "mpr-14966", 0x000007, 0x100000, CRC(dffba2e9) SHA1(b97e47e78abb8302bc2c87681643382203bd76eb) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Jurassic Park (Export)
not protected
Game: 833-10544 JURASSIC PARK
ROM BD: 834-10545
A/D BD NO: 837-7536-91
*/
ROM_START( jpark )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x2( "epr-16402a.ic8", 0x000000, 0x80000, CRC(c70db239) SHA1(fd79dfd1ce194fcc8ccb58117bc845cdfe9943b1) )
ROM_LOAD16_BYTE( "epr-16395.ic18", 0x100000, 0x80000, CRC(ac5a01d6) SHA1(df6bffdf5723cb8790a9c1c0ab271989a758bdd8) )
ROM_LOAD16_BYTE( "epr-16394.ic9", 0x100001, 0x80000, CRC(c08c3a8a) SHA1(923cf256d863656336401fa75103b42298cb3822) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-16399.ic36", 0x000000, 0x040000, CRC(b09b2fe3) SHA1(bf8d646bab65fcc4ece8c2bd9a3df389e5860ed6) )
ROM_LOAD( "mpr-16398.ic35", 0x100000, 0x100000, CRC(fa710ca6) SHA1(1fd625070eef5f99d7be07606aeeff9282e32532) )
ROM_LOAD( "mpr-16397.ic34", 0x200000, 0x100000, CRC(6e96e0be) SHA1(422b783b72127b80a23043b2dd1c04f5772f436e) )
ROM_LOAD( "mpr-16396.ic24", 0x300000, 0x100000, CRC(f69a2dc4) SHA1(3f02b10976852916c58e852f3161a857784fe36b) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16404.ic14", 0x000000, 0x200000, CRC(11283807) SHA1(99e465c3fc31e640740b8257a349e203f026754a) )
ROM_LOAD16_BYTE( "mpr-16403.ic5", 0x000001, 0x200000, CRC(02530a9b) SHA1(b43e1b47f74c801bfc599cbe893fb8dc13453dd0) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16405.ic32", 0x000000, 0x200000, CRC(b425f182) SHA1(66c6bd29dd3450db816b895c4c9c5208a66aae67) )
ROM_LOAD64_WORD( "mpr-16407.ic30", 0x000002, 0x200000, CRC(bc49ffd9) SHA1(a50ba7ddccfdfd7638c4041978b39c1559afbbb4) )
ROM_LOAD64_WORD( "mpr-16409.ic28", 0x000004, 0x200000, CRC(fe73660d) SHA1(ec1a3ea5303d2ccb9e327da18476969953626e1c) )
ROM_LOAD64_WORD( "mpr-16411.ic26", 0x000006, 0x200000, CRC(71cabbc5) SHA1(9760f57ef43eb251488dadd37711d5682d902434) )
ROM_LOAD64_WORD( "mpr-16406.ic31", 0x800000, 0x200000, CRC(b9ed73d6) SHA1(0dd22e7a21e95d84fc91acd742c737f96529f515) )
ROM_LOAD64_WORD( "mpr-16408.ic29", 0x800002, 0x200000, CRC(7b2f476b) SHA1(da99a9911982ba8aaef8c9aecc2977c9fd6da094) )
ROM_LOAD64_WORD( "mpr-16410.ic27", 0x800004, 0x200000, CRC(49c8f952) SHA1(f26b818711910b10bf520e5f849a1478a6b1d6e6) )
ROM_LOAD64_WORD( "mpr-16412.ic25", 0x800006, 0x200000, CRC(105dc26e) SHA1(fd2ef8c9fe1a78b4f9cc891a6fbd060184e58a1f) )
ROM_REGION( 0x10000, "cpu2", 0 ) /* unused */
ROM_LOAD( "epr-13908.xx", 0x00000, 0x8000, CRC(6228c1d2) SHA1(bd37fe775534fb94c9af80546948ce5f9c47bbf5) ) /* cabinet movement */
ROM_END
/**************************************************************************************************************************
Jurassic Park - Deluxe, Revision A (Japan)
not protected
Game: 833-10544-03 JURASSIC PARK DLX
ROM BD: 834-10545-03
*/
ROM_START( jparkj )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x2( "epr-16400a.ic8", 0x000000, 0x80000, CRC(1e03dbfe) SHA1(b7c274769ff483e687749ff20b1dc0fc38e8ef82) )
ROM_LOAD16_BYTE( "epr-16395.ic18", 0x100000, 0x80000, CRC(ac5a01d6) SHA1(df6bffdf5723cb8790a9c1c0ab271989a758bdd8) )
ROM_LOAD16_BYTE( "epr-16394.ic9", 0x100001, 0x80000, CRC(c08c3a8a) SHA1(923cf256d863656336401fa75103b42298cb3822) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-16399.ic36", 0x000000, 0x040000, CRC(b09b2fe3) SHA1(bf8d646bab65fcc4ece8c2bd9a3df389e5860ed6) )
ROM_LOAD( "mpr-16398.ic35", 0x100000, 0x100000, CRC(fa710ca6) SHA1(1fd625070eef5f99d7be07606aeeff9282e32532) )
ROM_LOAD( "mpr-16397.ic34", 0x200000, 0x100000, CRC(6e96e0be) SHA1(422b783b72127b80a23043b2dd1c04f5772f436e) )
ROM_LOAD( "mpr-16396.ic24", 0x300000, 0x100000, CRC(f69a2dc4) SHA1(3f02b10976852916c58e852f3161a857784fe36b) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16404.ic14", 0x000000, 0x200000, CRC(11283807) SHA1(99e465c3fc31e640740b8257a349e203f026754a) )
ROM_LOAD16_BYTE( "mpr-16403.ic5", 0x000001, 0x200000, CRC(02530a9b) SHA1(b43e1b47f74c801bfc599cbe893fb8dc13453dd0) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16405.ic32", 0x000000, 0x200000, CRC(b425f182) SHA1(66c6bd29dd3450db816b895c4c9c5208a66aae67) )
ROM_LOAD64_WORD( "mpr-16407.ic30", 0x000002, 0x200000, CRC(bc49ffd9) SHA1(a50ba7ddccfdfd7638c4041978b39c1559afbbb4) )
ROM_LOAD64_WORD( "mpr-16409.ic28", 0x000004, 0x200000, CRC(fe73660d) SHA1(ec1a3ea5303d2ccb9e327da18476969953626e1c) )
ROM_LOAD64_WORD( "mpr-16411.ic26", 0x000006, 0x200000, CRC(71cabbc5) SHA1(9760f57ef43eb251488dadd37711d5682d902434) )
ROM_LOAD64_WORD( "mpr-16406.ic31", 0x800000, 0x200000, CRC(b9ed73d6) SHA1(0dd22e7a21e95d84fc91acd742c737f96529f515) )
ROM_LOAD64_WORD( "mpr-16408.ic29", 0x800002, 0x200000, CRC(7b2f476b) SHA1(da99a9911982ba8aaef8c9aecc2977c9fd6da094) )
ROM_LOAD64_WORD( "mpr-16410.ic27", 0x800004, 0x200000, CRC(49c8f952) SHA1(f26b818711910b10bf520e5f849a1478a6b1d6e6) )
ROM_LOAD64_WORD( "mpr-16412.ic25", 0x800006, 0x200000, CRC(105dc26e) SHA1(fd2ef8c9fe1a78b4f9cc891a6fbd060184e58a1f) )
ROM_REGION( 0x10000, "cpu2", 0 ) /* unused */
ROM_LOAD( "epr-13908.xx", 0x00000, 0x8000, CRC(6228c1d2) SHA1(bd37fe775534fb94c9af80546948ce5f9c47bbf5) ) /* cabinet movement */
ROM_END
/**************************************************************************************************************************
Jurassic Park - Deluxe (Japan)
not protected
Game: 833-10544-03 JURASSIC PARK DLX
ROM BD: 834-10545-03
*/
ROM_START( jparkja )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x2( "epr-16400.ic8", 0x000000, 0x80000, CRC(321c3411) SHA1(c53e7ed5f2e523741a521c9cd271123ab557cc4a) )
ROM_LOAD16_BYTE( "epr-16395.ic18", 0x100000, 0x80000, CRC(ac5a01d6) SHA1(df6bffdf5723cb8790a9c1c0ab271989a758bdd8) )
ROM_LOAD16_BYTE( "epr-16394.ic9", 0x100001, 0x80000, CRC(c08c3a8a) SHA1(923cf256d863656336401fa75103b42298cb3822) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-16399.ic36", 0x000000, 0x040000, CRC(b09b2fe3) SHA1(bf8d646bab65fcc4ece8c2bd9a3df389e5860ed6) )
ROM_LOAD( "mpr-16398.ic35", 0x100000, 0x100000, CRC(fa710ca6) SHA1(1fd625070eef5f99d7be07606aeeff9282e32532) )
ROM_LOAD( "mpr-16397.ic34", 0x200000, 0x100000, CRC(6e96e0be) SHA1(422b783b72127b80a23043b2dd1c04f5772f436e) )
ROM_LOAD( "mpr-16396.ic24", 0x300000, 0x100000, CRC(f69a2dc4) SHA1(3f02b10976852916c58e852f3161a857784fe36b) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16404.ic14", 0x000000, 0x200000, CRC(11283807) SHA1(99e465c3fc31e640740b8257a349e203f026754a) )
ROM_LOAD16_BYTE( "mpr-16403.ic5", 0x000001, 0x200000, CRC(02530a9b) SHA1(b43e1b47f74c801bfc599cbe893fb8dc13453dd0) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16405.ic32", 0x000000, 0x200000, CRC(b425f182) SHA1(66c6bd29dd3450db816b895c4c9c5208a66aae67) )
ROM_LOAD64_WORD( "mpr-16407.ic30", 0x000002, 0x200000, CRC(bc49ffd9) SHA1(a50ba7ddccfdfd7638c4041978b39c1559afbbb4) )
ROM_LOAD64_WORD( "mpr-16409.ic28", 0x000004, 0x200000, CRC(fe73660d) SHA1(ec1a3ea5303d2ccb9e327da18476969953626e1c) )
ROM_LOAD64_WORD( "mpr-16411.ic26", 0x000006, 0x200000, CRC(71cabbc5) SHA1(9760f57ef43eb251488dadd37711d5682d902434) )
ROM_LOAD64_WORD( "mpr-16406.ic31", 0x800000, 0x200000, CRC(b9ed73d6) SHA1(0dd22e7a21e95d84fc91acd742c737f96529f515) )
ROM_LOAD64_WORD( "mpr-16408.ic29", 0x800002, 0x200000, CRC(7b2f476b) SHA1(da99a9911982ba8aaef8c9aecc2977c9fd6da094) )
ROM_LOAD64_WORD( "mpr-16410.ic27", 0x800004, 0x200000, CRC(49c8f952) SHA1(f26b818711910b10bf520e5f849a1478a6b1d6e6) )
ROM_LOAD64_WORD( "mpr-16412.ic25", 0x800006, 0x200000, CRC(105dc26e) SHA1(fd2ef8c9fe1a78b4f9cc891a6fbd060184e58a1f) )
ROM_REGION( 0x10000, "cpu2", 0 ) /* unused */
ROM_LOAD( "epr-13908.xx", 0x00000, 0x8000, CRC(6228c1d2) SHA1(bd37fe775534fb94c9af80546948ce5f9c47bbf5) ) /* cabinet movement */
ROM_END
/**************************************************************************************************************************
Jurassic Park - Conversion (Japan)
not protected
Game: 833-10544-03 JURASSIC PARK CVT
ROM BD: 834-10545-03
*/
ROM_START( jparkjc )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x2( "epr-16400a.ic8", 0x000000, 0x80000, CRC(1e03dbfe) SHA1(b7c274769ff483e687749ff20b1dc0fc38e8ef82) )
ROM_LOAD16_BYTE( "epr-16395.ic18", 0x100000, 0x80000, CRC(ac5a01d6) SHA1(df6bffdf5723cb8790a9c1c0ab271989a758bdd8) )
ROM_LOAD16_BYTE( "epr-16394.ic9", 0x100001, 0x80000, CRC(c08c3a8a) SHA1(923cf256d863656336401fa75103b42298cb3822) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-16630.ic36", 0x000000, 0x040000, CRC(955855eb) SHA1(c7a325ba0009139c2cc263cd457dbc0d527c7582) )
ROM_LOAD( "mpr-16398.ic35", 0x100000, 0x100000, CRC(fa710ca6) SHA1(1fd625070eef5f99d7be07606aeeff9282e32532) )
ROM_LOAD( "mpr-16397.ic34", 0x200000, 0x100000, CRC(6e96e0be) SHA1(422b783b72127b80a23043b2dd1c04f5772f436e) )
ROM_LOAD( "mpr-16396.ic24", 0x300000, 0x100000, CRC(f69a2dc4) SHA1(3f02b10976852916c58e852f3161a857784fe36b) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16404.ic14", 0x000000, 0x200000, CRC(11283807) SHA1(99e465c3fc31e640740b8257a349e203f026754a) )
ROM_LOAD16_BYTE( "mpr-16403.ic5", 0x000001, 0x200000, CRC(02530a9b) SHA1(b43e1b47f74c801bfc599cbe893fb8dc13453dd0) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16405.ic32", 0x000000, 0x200000, CRC(b425f182) SHA1(66c6bd29dd3450db816b895c4c9c5208a66aae67) )
ROM_LOAD64_WORD( "mpr-16407.ic30", 0x000002, 0x200000, CRC(bc49ffd9) SHA1(a50ba7ddccfdfd7638c4041978b39c1559afbbb4) )
ROM_LOAD64_WORD( "mpr-16409.ic28", 0x000004, 0x200000, CRC(fe73660d) SHA1(ec1a3ea5303d2ccb9e327da18476969953626e1c) )
ROM_LOAD64_WORD( "mpr-16411.ic26", 0x000006, 0x200000, CRC(71cabbc5) SHA1(9760f57ef43eb251488dadd37711d5682d902434) )
ROM_LOAD64_WORD( "mpr-16406.ic31", 0x800000, 0x200000, CRC(b9ed73d6) SHA1(0dd22e7a21e95d84fc91acd742c737f96529f515) )
ROM_LOAD64_WORD( "mpr-16408.ic29", 0x800002, 0x200000, CRC(7b2f476b) SHA1(da99a9911982ba8aaef8c9aecc2977c9fd6da094) )
ROM_LOAD64_WORD( "mpr-16410.ic27", 0x800004, 0x200000, CRC(49c8f952) SHA1(f26b818711910b10bf520e5f849a1478a6b1d6e6) )
ROM_LOAD64_WORD( "mpr-16412.ic25", 0x800006, 0x200000, CRC(105dc26e) SHA1(fd2ef8c9fe1a78b4f9cc891a6fbd060184e58a1f) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Soreike Kokology Sega System 32 ROM Board '837-8393 16Mb ROM BD' with
sticker 834-9494 and sticker 'REV. A'
No security board.
GAL16V8 at IC23: 315-5552
Jumpers settings:
JP1: 2-3, JP2: 2-3, JP3: 1-2, JP4: 1-2, JP5: 1-2, JP6: 1-2,
JP7: 1-2, JP8: 1-2, JP9: 2-3, JP10: 2-3, JP11: 2-3, JP12: 1-2,
JP13: 2-3, JP14: 1-2, JP15: 2-3, JP16: 1-2, JP17: 1-2,
JP18: 2-3, JP19: 1-2, JP20: 2-3, JP21: 1-2, JP22: 1-2,
JP23: 2-3, JP24: 2-3
*/
ROM_START( kokoroj )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-15524a.ic8", 0x000000, 0x20000, CRC(3b4cc0cf) SHA1(2536c67ac4255cdb6988d37f48f91ad272aebb4f) )
ROM_LOAD16_BYTE( "epr-15521a.ic18", 0x100000, 0x80000, CRC(24c02cf9) SHA1(d2ab8a47ff6541d2a6be7ce50784b8c9a3a215be) )
ROM_LOAD16_BYTE( "epr-15520a.ic9", 0x100001, 0x80000, CRC(bfbae875) SHA1(340c1e07eeb8e15448f82b87cc749d66086130ab) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 )
ROM_LOAD_x8( "epr-15523.ic36", 0x000000, 0x020000, CRC(b3b9d29c) SHA1(22acd747540e8c4558ec5eaeda1aaab68f84a6e2) )
ROM_LOAD_x2( "mpr-15522.ic35", 0x100000, 0x080000, CRC(fb68a351) SHA1(f307c0e4f33786630e8baddbb8c0a5e0f956de76) )
// IC24 & IC34 are not populated
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15526.ic14", 0x000000, 0x100000, CRC(f6907c13) SHA1(d3f65dd02d7cee0fd2f422ba6a54164b2a2b8303) )
ROM_LOAD16_BYTE( "mpr-15525.ic5", 0x000001, 0x100000, CRC(8c0c876f) SHA1(e5335fa7a3e4a0e1d79fc7612bf4aaa50224f4ca) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 )
ROM_LOAD64_WORD( "mpr-15527.ic32", 0x000000, 0x200000, CRC(132f91c6) SHA1(0f854b173bdebfb642dba3b58a307d0e3a157c85) )
ROM_LOAD64_WORD( "mpr-15529.ic30", 0x000002, 0x200000, CRC(c1b826f7) SHA1(00051762074cdcf62b07cea6c744244b11ebf1b1) )
ROM_LOAD64_WORD( "mpr-15531.ic28", 0x000004, 0x200000, CRC(d624e05f) SHA1(f19f173aaeb04a59ab7fe89a3490d1d7c13c77a0) )
ROM_LOAD64_WORD( "mpr-15533.ic26", 0x000006, 0x200000, CRC(aff0e9a8) SHA1(5ced176cfef65426e2b4a3b990a319fdceaa9162) )
ROM_LOAD64_WORD( "mpr-15528.ic31", 0x800000, 0x200000, CRC(2e4bc090) SHA1(67d464ea078a19ae303b2b60f4ab0abd71aea85c) )
ROM_LOAD64_WORD( "mpr-15530.ic29", 0x800002, 0x200000, CRC(307877a8) SHA1(0104a51349f745a9fb7cc238a832ef6abeec2025) )
ROM_LOAD64_WORD( "mpr-15532.ic27", 0x800004, 0x200000, CRC(923ba3e5) SHA1(d26c55e7021c81b5fdaa9fadee20db30f6677981) )
ROM_LOAD64_WORD( "mpr-15534.ic25", 0x800006, 0x200000, CRC(4fa5c56d) SHA1(52926bef0f21ef17dc9d49e3137712bf6d8c29af) )
// Audio CD
DISK_REGION( "mainpcb:scsi:" SCSI_PORT_DEVICE1 ":cdrom" )
DISK_IMAGE_READONLY( "kokoroj", 0, NO_DUMP )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Soreike Kokology Vol. 2
Sega System32 + CD - Sega 1993
ROM Board is 837-8393 16Mb ROM board (Same as godenaxe2 or Arabian Fight)
SCSI CD board is 839-0572-01. It use a Fujitsu MB89352AP for SCSI + a Sony CXD1095Q for I/O + 8Mhz quartz
*/
ROM_START( kokoroj2 )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-16186.ic8", 0x000000, 0x20000, CRC(8c3afb6e) SHA1(68c3c066a943b1ea8e3bee06c7c8279b5a12e7f7) )
ROM_LOAD16_BYTE( "epr-16183.ic18", 0x100000, 0x80000, CRC(4844432f) SHA1(b127169d0f108e0b99ec81814a5c3c45bb82e0b1) )
ROM_LOAD16_BYTE( "epr-16182.ic9", 0x100001, 0x80000, CRC(a27f5f5f) SHA1(c2bbd1632bce0851cf8ab45d3ccbec1076e67f5e) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-16185.ic36", 0x000000, 0x020000, CRC(afb97c4d) SHA1(f6e77d932824f93d89559a9cb3b2d678d5fc6940) )
ROM_LOAD( "mpr-16184.ic35", 0x100000, 0x100000, CRC(d7a19751) SHA1(8ae9f13689c8f9851e1eea995c51285972bed4a2) )
// IC24 & IC34 are not populated
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16188.ic14", 0x000000, 0x200000, CRC(83a450ab) SHA1(1d0b45512d784ed1d82135b84c7c540f92d789f7) )
ROM_LOAD16_BYTE( "mpr-16187.ic5", 0x000001, 0x200000, CRC(98b62f8b) SHA1(eaf98efd9eac7b7c385138a8a4dbc94b0ca38df5) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16189.ic32", 0x000000, 0x200000, CRC(0937f713) SHA1(4b2b09ec8ed97794ad3824d1c57eae7f7e01379c) )
ROM_LOAD64_WORD( "mpr-16191.ic30", 0x000002, 0x200000, CRC(cfef4aaa) SHA1(bc8a252dcbdb8facdd91eda7aed0f56fe7529d15) )
ROM_LOAD64_WORD( "mpr-16193.ic28", 0x000004, 0x200000, CRC(a0706e4e) SHA1(1f36d952971c05db4190b229aa4957db3e5224f1) )
ROM_LOAD64_WORD( "mpr-16195.ic26", 0x000006, 0x200000, CRC(a4ddcd61) SHA1(90ef40f1fc84d1e4d4f78c33b8f0d1f56e04bf90) )
ROM_LOAD64_WORD( "mpr-16190.ic31", 0x800000, 0x200000, CRC(528d408e) SHA1(89f8a2cfc8b59377d6a65555c3172e457b131502) )
ROM_LOAD64_WORD( "mpr-16192.ic29", 0x800002, 0x200000, CRC(efaa93d1) SHA1(2947eaf7fc358ced1c04e7abe7a3f3066c73f2d0) )
ROM_LOAD64_WORD( "mpr-16194.ic27", 0x800004, 0x200000, CRC(39b5efe7) SHA1(2039909a2dd46951d442f1b6377f365525f9f2f1) )
ROM_LOAD64_WORD( "mpr-16196.ic25", 0x800006, 0x200000, CRC(b8e22e05) SHA1(dd667e2c5d421cba356421825e6aca9b5ca0af45) )
/* AUDIO CD */
DISK_REGION( "mainpcb:scsi:" SCSI_PORT_DEVICE1 ":cdrom" )
DISK_IMAGE_READONLY( "cdp-00146", 0, SHA1(0b37e0ea2380ecd9abef2ccd6a8096d76d2ba344) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Outrunners (Export) - Multi-32
not protected
Sega Game ID codes:
GAME BD NO. 834-9559-02
ROM BD. 837-9560-02
MAIN BD. 837-8676 (SYSTEM MULTI)
A/D BD NO. 837-7536
COMM BD. 837-8792
*/
ROM_START( orunners )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code */
ROM_LOAD32_WORD_x4( "epr-15620.ic37", 0x000000, 0x020000, CRC(84f5ad92) SHA1(1f9cb04b42b2d450be93400d9979a7910eaf05d1) )
ROM_LOAD32_WORD_x4( "epr-15621.ic40", 0x000002, 0x020000, CRC(d98b765a) SHA1(b58567e976228267a86af53de2135bc0b247a44a) )
ROM_LOAD32_WORD( "mpr-15538.ic36", 0x100000, 0x080000, CRC(93958820) SHA1(e19b6f18a5707dbb64ae009d63c05eac5bac4a81) )
ROM_LOAD32_WORD( "mpr-15539.ic39", 0x100002, 0x080000, CRC(219760fa) SHA1(bd62a83de9c9542f6da454a87dc4947492f65c52) )
ROM_REGION( 0x80000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD( "epr-15550.ic31", 0x00000, 0x80000, CRC(0205d2ed) SHA1(3475479e1a45fe96eefbe53842758898db7accbf) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15548.ic3", 0x000000, 0x200000, CRC(b6470a66) SHA1(e1544590c02d41f62f82a4d771b893fb0f2734c7) )
ROM_LOAD16_BYTE( "mpr-15549.ic11", 0x000001, 0x200000, CRC(81d12520) SHA1(1555893941e832f00ad3d0b3ad0c34a0d3a1c58a) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15540.ic14", 0x000000, 0x200000, CRC(a10d72b4) SHA1(6d9d5e20be6721b53ce49df4d5a1bbd91f5b3aed) )
ROM_LOAD64_WORD( "mpr-15542.ic15", 0x000002, 0x200000, CRC(40952374) SHA1(c669ef52508bc2f49cf812dc86ac98fb535471fa) )
ROM_LOAD64_WORD( "mpr-15544.ic10", 0x000004, 0x200000, CRC(39e3df45) SHA1(38a7b21617b45613b05509dda388f8f7770b186c) )
ROM_LOAD64_WORD( "mpr-15546.ic38", 0x000006, 0x200000, CRC(e3fcc12c) SHA1(1cf7e05c7873f68789a27a91cddf471df40d7907) )
ROM_LOAD64_WORD( "mpr-15541.ic22", 0x800000, 0x200000, CRC(a2003c2d) SHA1(200a2c7d78d3f5f28909267fdcdbddd58c5f5fa2) )
ROM_LOAD64_WORD( "mpr-15543.ic23", 0x800002, 0x200000, CRC(933e8e7b) SHA1(0d53286f524f47851a483569dc37e9f6d34cc5f4) )
ROM_LOAD64_WORD( "mpr-15545.ic18", 0x800004, 0x200000, CRC(53dd0235) SHA1(4aee5ae1820ff933b6bd8a54bdbf989c0bc95c1a) )
ROM_LOAD64_WORD( "mpr-15547.ic41", 0x800006, 0x200000, CRC(edcb2a43) SHA1(f0bcfcc749ca0267f85bf9838164869912944d00) )
ROM_REGION( 0x400000, "mainpcb:sega", 0 ) /* Sega PCM sound data */
ROM_LOAD( "mpr-15551.ic1", 0x000000, 0x200000, CRC(4894bc73) SHA1(351f5c03fb430fd87df915dfe3a377b5ada622c4) )
ROM_LOAD( "mpr-15552.ic2", 0x200000, 0x200000, CRC(1c4b5e73) SHA1(50a8e9a200575a3522a51bf094aa0e87b90bb0a3) )
ROM_END
/**************************************************************************************************************************
Outrunners (US) - Multi-32
not protected
GAME BD NO. 834-9559-01
ROM BD. 837-9560-01
MAIN BD. 837-8676 (SYSTEM MULTI)
A/D BD NO. 837-7536
COMM BD. 837-8792
*/
ROM_START( orunnersu )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code */
ROM_LOAD32_WORD_x4( "epr-15618.ic37", 0x000000, 0x020000, CRC(25647f76) SHA1(9f882921ebb2f078350295c322b263f75812c053) )
ROM_LOAD32_WORD_x4( "epr-15619.ic40", 0x000002, 0x020000, CRC(2a558f95) SHA1(616ec0a7b251da61a49b933c58895b1a4d39417a) )
ROM_LOAD32_WORD( "mpr-15538.ic36", 0x100000, 0x080000, CRC(93958820) SHA1(e19b6f18a5707dbb64ae009d63c05eac5bac4a81) )
ROM_LOAD32_WORD( "mpr-15539.ic39", 0x100002, 0x080000, CRC(219760fa) SHA1(bd62a83de9c9542f6da454a87dc4947492f65c52) )
ROM_REGION( 0x80000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD( "epr-15550.ic31", 0x00000, 0x80000, CRC(0205d2ed) SHA1(3475479e1a45fe96eefbe53842758898db7accbf) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15548.ic3", 0x000000, 0x200000, CRC(b6470a66) SHA1(e1544590c02d41f62f82a4d771b893fb0f2734c7) )
ROM_LOAD16_BYTE( "mpr-15549.ic11", 0x000001, 0x200000, CRC(81d12520) SHA1(1555893941e832f00ad3d0b3ad0c34a0d3a1c58a) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15540.ic14", 0x000000, 0x200000, CRC(a10d72b4) SHA1(6d9d5e20be6721b53ce49df4d5a1bbd91f5b3aed) )
ROM_LOAD64_WORD( "mpr-15542.ic15", 0x000002, 0x200000, CRC(40952374) SHA1(c669ef52508bc2f49cf812dc86ac98fb535471fa) )
ROM_LOAD64_WORD( "mpr-15544.ic10", 0x000004, 0x200000, CRC(39e3df45) SHA1(38a7b21617b45613b05509dda388f8f7770b186c) )
ROM_LOAD64_WORD( "mpr-15546.ic38", 0x000006, 0x200000, CRC(e3fcc12c) SHA1(1cf7e05c7873f68789a27a91cddf471df40d7907) )
ROM_LOAD64_WORD( "mpr-15541.ic22", 0x800000, 0x200000, CRC(a2003c2d) SHA1(200a2c7d78d3f5f28909267fdcdbddd58c5f5fa2) )
ROM_LOAD64_WORD( "mpr-15543.ic23", 0x800002, 0x200000, CRC(933e8e7b) SHA1(0d53286f524f47851a483569dc37e9f6d34cc5f4) )
ROM_LOAD64_WORD( "mpr-15545.ic18", 0x800004, 0x200000, CRC(53dd0235) SHA1(4aee5ae1820ff933b6bd8a54bdbf989c0bc95c1a) )
ROM_LOAD64_WORD( "mpr-15547.ic41", 0x800006, 0x200000, CRC(edcb2a43) SHA1(f0bcfcc749ca0267f85bf9838164869912944d00) )
ROM_REGION( 0x400000, "mainpcb:sega", 0 ) /* Sega PCM sound data */
ROM_LOAD( "mpr-15551.ic1", 0x000000, 0x200000, CRC(4894bc73) SHA1(351f5c03fb430fd87df915dfe3a377b5ada622c4) )
ROM_LOAD( "mpr-15552.ic2", 0x200000, 0x200000, CRC(1c4b5e73) SHA1(50a8e9a200575a3522a51bf094aa0e87b90bb0a3) )
ROM_END
/**************************************************************************************************************************
Outrunners (Japan) - Multi-32
not protected
GAME BD NO. 834-9559-03
ROM BD. 837-9560-03
MAIN BD. 837-8676 (SYSTEM MULTI)
A/D BD NO. 837-7536
COMM BD. 837-8792
*/
ROM_START( orunnersj )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code */
ROM_LOAD32_WORD_x4( "epr-15616.ic37", 0x000000, 0x020000, CRC(fb550545) SHA1(2f2c36843b115f5417e1f2ccd4a34ebf91265190) ) /* Need to verify the EPR numbers */
ROM_LOAD32_WORD_x4( "epr-15617.ic40", 0x000002, 0x020000, CRC(6bb741e0) SHA1(d92087a2c0b6de4287e569eecf9758615a85d1eb) ) /* Need to verify the EPR numbers */
ROM_LOAD32_WORD( "mpr-15538.ic36", 0x100000, 0x080000, CRC(93958820) SHA1(e19b6f18a5707dbb64ae009d63c05eac5bac4a81) )
ROM_LOAD32_WORD( "mpr-15539.ic39", 0x100002, 0x080000, CRC(219760fa) SHA1(bd62a83de9c9542f6da454a87dc4947492f65c52) )
ROM_REGION( 0x80000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD( "epr-15550.ic31", 0x00000, 0x80000, CRC(0205d2ed) SHA1(3475479e1a45fe96eefbe53842758898db7accbf) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15548.ic3", 0x000000, 0x200000, CRC(b6470a66) SHA1(e1544590c02d41f62f82a4d771b893fb0f2734c7) )
ROM_LOAD16_BYTE( "mpr-15549.ic11", 0x000001, 0x200000, CRC(81d12520) SHA1(1555893941e832f00ad3d0b3ad0c34a0d3a1c58a) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15540.ic14", 0x000000, 0x200000, CRC(a10d72b4) SHA1(6d9d5e20be6721b53ce49df4d5a1bbd91f5b3aed) )
ROM_LOAD64_WORD( "mpr-15542.ic15", 0x000002, 0x200000, CRC(40952374) SHA1(c669ef52508bc2f49cf812dc86ac98fb535471fa) )
ROM_LOAD64_WORD( "mpr-15544.ic10", 0x000004, 0x200000, CRC(39e3df45) SHA1(38a7b21617b45613b05509dda388f8f7770b186c) )
ROM_LOAD64_WORD( "mpr-15546.ic38", 0x000006, 0x200000, CRC(e3fcc12c) SHA1(1cf7e05c7873f68789a27a91cddf471df40d7907) )
ROM_LOAD64_WORD( "mpr-15541.ic22", 0x800000, 0x200000, CRC(a2003c2d) SHA1(200a2c7d78d3f5f28909267fdcdbddd58c5f5fa2) )
ROM_LOAD64_WORD( "mpr-15543.ic23", 0x800002, 0x200000, CRC(933e8e7b) SHA1(0d53286f524f47851a483569dc37e9f6d34cc5f4) )
ROM_LOAD64_WORD( "mpr-15545.ic18", 0x800004, 0x200000, CRC(53dd0235) SHA1(4aee5ae1820ff933b6bd8a54bdbf989c0bc95c1a) )
ROM_LOAD64_WORD( "mpr-15547.ic41", 0x800006, 0x200000, CRC(edcb2a43) SHA1(f0bcfcc749ca0267f85bf9838164869912944d00) )
ROM_REGION( 0x400000, "mainpcb:sega", 0 ) /* Sega PCM sound data */
ROM_LOAD( "mpr-15551.ic1", 0x000000, 0x200000, CRC(4894bc73) SHA1(351f5c03fb430fd87df915dfe3a377b5ada622c4) )
ROM_LOAD( "mpr-15552.ic2", 0x200000, 0x200000, CRC(1c4b5e73) SHA1(50a8e9a200575a3522a51bf094aa0e87b90bb0a3) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Rad Mobile Deluxe Cabinet (Export)
not protected
Sega Game ID codes:
GAME BD NO. 833-7738-01 RAD MOBILE (USA)
833-7738-02 RAD MOBILE (Export)
833-7738-03 RAD MOBILE (Japan)
ROM BD. 834-7739-01 (USA)
834-7739-02 (Export)
834-7739-03 (Japan)
MAIN BD. 837-7428
A/D BD NO. 837-7536
Upright Cabinet:
USA: EPR-13690.ic21 (dumped)
EPR-13691.ic37 (not dumped)
EPR-13692.ic38 (not dumped)
Export: EPR-13693.ic21 (dumped)
EPR-13694.ic37 (not dumped)
EPR-13695.ic38 (not dumped)
Japanese version is undumped. There is likely a Japanese specific sound ROM at IC20 (EPR-13524.ic20 ??)
*/
ROM_START( radm )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-13693.ic21", 0x000000, 0x020000, CRC(3f09a211) SHA1(e0e011d7069745e9bf0395bc1375d0f8b9c46dab) )
ROM_LOAD16_BYTE( "epr-13525.ic37", 0x100000, 0x080000, CRC(62ad83a0) SHA1(b537176ebca15d91db04d5d7ab36aa967d41288e) )
ROM_LOAD16_BYTE( "epr-13526.ic38", 0x100001, 0x080000, CRC(59ea372a) SHA1(e7a5d59586652c59c23e07e0a99ecc740fb6144d) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-13527.ic9", 0x000000, 0x020000, CRC(a2e3fbbe) SHA1(2787bbef696ab3f2b7855ac991867837d3de54cd) )
ROM_LOAD_x2( "epr-13523.ic14", 0x100000, 0x080000, CRC(d5563697) SHA1(eb3fd3dbfea383ac1bb5d2e1552723994cb4693d) )
ROM_LOAD_x2( "epr-13699.ic20", 0x200000, 0x080000, CRC(33fd2913) SHA1(60b664559b4989446b1c7d875432e53a36fe27df) )
ROM_LOAD_x2( "epr-13523.ic22", 0x300000, 0x080000, CRC(d5563697) SHA1(eb3fd3dbfea383ac1bb5d2e1552723994cb4693d) ) /* Deluxe or Upright manuals don't show this ROM */
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-13519.ic3", 0x000000, 0x080000, CRC(bedc9534) SHA1(7b3f7a47b6c0ca6707dc3c1167f3564d43adb32f) )
ROM_LOAD32_BYTE( "mpr-13520.ic7", 0x000002, 0x080000, CRC(3532e91a) SHA1(669c8d27b4b48e1ab9d6d30b0994f5a4e5169118) )
ROM_LOAD32_BYTE( "mpr-13521.ic12", 0x000001, 0x080000, CRC(e9bca903) SHA1(18a73c830b9755262a1c525e3ad5ae084117b64d) )
ROM_LOAD32_BYTE( "mpr-13522.ic18", 0x000003, 0x080000, CRC(25e04648) SHA1(617e794e8f7aa2a435bac917b8968699fe88dafb) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-13511.ic1", 0x000000, 0x100000, CRC(f8f15b11) SHA1(da6c2b8c3a94c4c263583f046823eaea818aff7c) )
ROM_LOAD64_BYTE( "mpr-13512.ic5", 0x000001, 0x100000, CRC(d0be34a6) SHA1(b42a63e30f0f7a94de8a825ca93cf8efdb7a7648) )
ROM_LOAD64_BYTE( "mpr-13513.ic10", 0x000002, 0x100000, CRC(feef1982) SHA1(bdf906317079a12c48ef4fca5bef0d437e9bf050) )
ROM_LOAD64_BYTE( "mpr-13514.ic16", 0x000003, 0x100000, CRC(d0f9ebd1) SHA1(510ebd3d7a52bcab2debea61591770d1dff172a1) )
ROM_LOAD64_BYTE( "mpr-13515.ic2", 0x000004, 0x100000, CRC(77bf2387) SHA1(7215dde5618e238edbe16b3007ede790785fe25f) )
ROM_LOAD64_BYTE( "mpr-13516.ic6", 0x000005, 0x100000, CRC(8c4bc62d) SHA1(3206f623ec0b7558413d063404103b183f26b488) )
ROM_LOAD64_BYTE( "mpr-13517.ic11", 0x000006, 0x100000, CRC(1d7d84a7) SHA1(954cfccfc7250a5bead2eeba42e655d5ac82955f) )
ROM_LOAD64_BYTE( "mpr-13518.ic17", 0x000007, 0x100000, CRC(9ea4b15d) SHA1(7dcfd6d42bb945beca8344cf92e7bd53903a824b) )
ROM_REGION( 0x8000, "user2", 0 ) /* unused (cabinet motor?) */
ROM_LOAD( "epr-13686.bin", 0x00000, 0x8000, CRC(317a2857) SHA1(e0788dc7a7d214d9c4d26b24e44c1a0dc9ae477c) ) /* cabinet movement */
ROM_REGION16_BE( 0x80, "mainpcb:eeprom", 0 )
ROM_LOAD16_WORD( "eeprom-radm.ic76", 0x0000, 0x0080, CRC(b1737c06) SHA1(29448a6effeb53322a93158feb9a62bc6ad31f21) )
ROM_END
/**************************************************************************************************************************
Rad Mobile Deluxe Cabinet (US)
not protected
*/
ROM_START( radmu )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-13690.ic21", 0x000000, 0x020000, CRC(21637dec) SHA1(b9921effb10a72f3bdca4d540149c7f46662b716) )
ROM_LOAD16_BYTE( "epr-13525.ic37", 0x100000, 0x080000, CRC(62ad83a0) SHA1(b537176ebca15d91db04d5d7ab36aa967d41288e) )
ROM_LOAD16_BYTE( "epr-13526.ic38", 0x100001, 0x080000, CRC(59ea372a) SHA1(e7a5d59586652c59c23e07e0a99ecc740fb6144d) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-13527.ic9", 0x000000, 0x020000, CRC(a2e3fbbe) SHA1(2787bbef696ab3f2b7855ac991867837d3de54cd) )
ROM_LOAD_x2( "epr-13523.ic14", 0x100000, 0x080000, CRC(d5563697) SHA1(eb3fd3dbfea383ac1bb5d2e1552723994cb4693d) )
ROM_LOAD_x2( "epr-13699.ic20", 0x200000, 0x080000, CRC(33fd2913) SHA1(60b664559b4989446b1c7d875432e53a36fe27df) )
ROM_LOAD_x2( "epr-13523.ic22", 0x300000, 0x080000, CRC(d5563697) SHA1(eb3fd3dbfea383ac1bb5d2e1552723994cb4693d) ) /* Deluxe or Upright manuals don't show this ROM */
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-13519.ic3", 0x000000, 0x080000, CRC(bedc9534) SHA1(7b3f7a47b6c0ca6707dc3c1167f3564d43adb32f) )
ROM_LOAD32_BYTE( "mpr-13520.ic7", 0x000002, 0x080000, CRC(3532e91a) SHA1(669c8d27b4b48e1ab9d6d30b0994f5a4e5169118) )
ROM_LOAD32_BYTE( "mpr-13521.ic12", 0x000001, 0x080000, CRC(e9bca903) SHA1(18a73c830b9755262a1c525e3ad5ae084117b64d) )
ROM_LOAD32_BYTE( "mpr-13522.ic18", 0x000003, 0x080000, CRC(25e04648) SHA1(617e794e8f7aa2a435bac917b8968699fe88dafb) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-13511.ic1", 0x000000, 0x100000, CRC(f8f15b11) SHA1(da6c2b8c3a94c4c263583f046823eaea818aff7c) )
ROM_LOAD64_BYTE( "mpr-13512.ic5", 0x000001, 0x100000, CRC(d0be34a6) SHA1(b42a63e30f0f7a94de8a825ca93cf8efdb7a7648) )
ROM_LOAD64_BYTE( "mpr-13513.ic10", 0x000002, 0x100000, CRC(feef1982) SHA1(bdf906317079a12c48ef4fca5bef0d437e9bf050) )
ROM_LOAD64_BYTE( "mpr-13514.ic16", 0x000003, 0x100000, CRC(d0f9ebd1) SHA1(510ebd3d7a52bcab2debea61591770d1dff172a1) )
ROM_LOAD64_BYTE( "mpr-13515.ic2", 0x000004, 0x100000, CRC(77bf2387) SHA1(7215dde5618e238edbe16b3007ede790785fe25f) )
ROM_LOAD64_BYTE( "mpr-13516.ic6", 0x000005, 0x100000, CRC(8c4bc62d) SHA1(3206f623ec0b7558413d063404103b183f26b488) )
ROM_LOAD64_BYTE( "mpr-13517.ic11", 0x000006, 0x100000, CRC(1d7d84a7) SHA1(954cfccfc7250a5bead2eeba42e655d5ac82955f) )
ROM_LOAD64_BYTE( "mpr-13518.ic17", 0x000007, 0x100000, CRC(9ea4b15d) SHA1(7dcfd6d42bb945beca8344cf92e7bd53903a824b) )
ROM_REGION( 0x8000, "user2", 0 ) /* unused (cabinet motor?) */
ROM_LOAD( "epr-13686.bin", 0x00000, 0x8000, CRC(317a2857) SHA1(e0788dc7a7d214d9c4d26b24e44c1a0dc9ae477c) ) /* cabinet movement */
ROM_REGION16_BE( 0x80, "mainpcb:eeprom", 0 )
ROM_LOAD16_WORD( "eeprom-radm.ic76", 0x0000, 0x0080, CRC(b1737c06) SHA1(29448a6effeb53322a93158feb9a62bc6ad31f21) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Rad Rally (Export)
not protected
Sega Game ID codes:
Game: 833-8110-02 RAD RALLY
ROM board: 833-8111-02
A/D BD NO. 837-7536
*/
ROM_START( radr )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-14241.ic21", 0x000000, 0x020000, CRC(59a5f63d) SHA1(325a26a09475ddc828de71e71a1d3043f3959cec) )
ROM_LOAD16_BYTE( "epr-14106.ic37", 0x100000, 0x080000, CRC(e73c63bf) SHA1(30fb68eaa7d02a232c873bd7751cac7d0fa08e44) )
ROM_LOAD16_BYTE( "epr-14107.ic38", 0x100001, 0x080000, CRC(832f797a) SHA1(b0c16ef7bd8d37f592975052ba9da3da70a2fc79) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-14108.ic9", 0x000000, 0x020000, CRC(38a99b4d) SHA1(b6455e6b29bfef41c5e0ebe3a8064889b7e5f5fd) )
ROM_LOAD_x2( "epr-14109.ic14", 0x100000, 0x080000, CRC(d5563697) SHA1(eb3fd3dbfea383ac1bb5d2e1552723994cb4693d) ) // same as radm, but different epr code
ROM_LOAD_x2( "epr-14110.ic20", 0x200000, 0x080000, CRC(33fd2913) SHA1(60b664559b4989446b1c7d875432e53a36fe27df) ) // same as radm, but different epr code
ROM_LOAD_x2( "epr-14237.ic22", 0x300000, 0x080000, CRC(0a4b4b29) SHA1(98447a587f903ba03e17d6a145b7c8bfddf25c4d) ) // 1xxxxxxxxxxxxxxxxxx = 0xFF
ROM_REGION( 0x100000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "epr-14102.ic3", 0x000000, 0x040000, CRC(5626e80f) SHA1(9844817295a8cd8a9b09da6681b0c1fbfe82618e) )
ROM_LOAD32_BYTE( "epr-14103.ic7", 0x000002, 0x040000, CRC(08c7e804) SHA1(cf45b1934edc43cb3a0ed72159949cb0dd00d701) )
ROM_LOAD32_BYTE( "epr-14104.ic12", 0x000001, 0x040000, CRC(b0173646) SHA1(1ba4edc033e0e4f5a1e02987e9f6b8b1650b46d7) )
ROM_LOAD32_BYTE( "epr-14105.ic18", 0x000003, 0x040000, CRC(614843b6) SHA1(d4f2cd3b024f7152d6e89237f0da06adea2efe57) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-13511.ic1", 0x000000, 0x100000, CRC(f8f15b11) SHA1(da6c2b8c3a94c4c263583f046823eaea818aff7c) )
ROM_LOAD64_BYTE( "mpr-13512.ic5", 0x000001, 0x100000, CRC(d0be34a6) SHA1(b42a63e30f0f7a94de8a825ca93cf8efdb7a7648) )
ROM_LOAD64_BYTE( "mpr-13513.ic10", 0x000002, 0x100000, CRC(feef1982) SHA1(bdf906317079a12c48ef4fca5bef0d437e9bf050) )
ROM_LOAD64_BYTE( "mpr-13514.ic16", 0x000003, 0x100000, CRC(d0f9ebd1) SHA1(510ebd3d7a52bcab2debea61591770d1dff172a1) )
ROM_LOAD64_BYTE( "mpr-13515.ic2", 0x000004, 0x100000, CRC(77bf2387) SHA1(7215dde5618e238edbe16b3007ede790785fe25f) )
ROM_LOAD64_BYTE( "mpr-13516.ic6", 0x000005, 0x100000, CRC(8c4bc62d) SHA1(3206f623ec0b7558413d063404103b183f26b488) )
ROM_LOAD64_BYTE( "mpr-13517.ic11", 0x000006, 0x100000, CRC(1d7d84a7) SHA1(954cfccfc7250a5bead2eeba42e655d5ac82955f) )
ROM_LOAD64_BYTE( "mpr-13518.ic17", 0x000007, 0x100000, CRC(9ea4b15d) SHA1(7dcfd6d42bb945beca8344cf92e7bd53903a824b) )
ROM_REGION( 0x8000, "user2", 0 ) /* unused */
ROM_LOAD( "epr-14084.17", 0x00000, 0x8000, CRC(f14ed074) SHA1(e1bb23eac85e3236046527c5c7688f6f23d43aef) ) /* cabinet link */
ROM_REGION16_BE( 0x80, "mainpcb:eeprom", 0 )
ROM_LOAD16_WORD( "eeprom-radr.ic76", 0x0000, 0x0080, CRC(602032c6) SHA1(fecf14017e537fe870457d2a8d4f86ec6d442b90) )
ROM_END
/**************************************************************************************************************************
Rad Rally (US)
not protected
Sega Game ID codes:
Game: 833-8110-01 RAD RALLY
ROM board: 833-8111-01
A/D BD NO. 837-7536
*/
ROM_START( radru )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-14240.ic21", 0x000000, 0x020000, CRC(8473e7ab) SHA1(fbd883dc804d7de6ce239b68c6e6ae3a54e9e03c) )
ROM_LOAD16_BYTE( "epr-14106.ic37", 0x100000, 0x080000, CRC(e73c63bf) SHA1(30fb68eaa7d02a232c873bd7751cac7d0fa08e44) )
ROM_LOAD16_BYTE( "epr-14107.ic38", 0x100001, 0x080000, CRC(832f797a) SHA1(b0c16ef7bd8d37f592975052ba9da3da70a2fc79) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-14108.ic9", 0x000000, 0x020000, CRC(38a99b4d) SHA1(b6455e6b29bfef41c5e0ebe3a8064889b7e5f5fd) )
ROM_LOAD_x2( "epr-14109.ic14", 0x100000, 0x080000, CRC(d5563697) SHA1(eb3fd3dbfea383ac1bb5d2e1552723994cb4693d) ) // same as radm, but different epr code
ROM_LOAD_x2( "epr-14110.ic20", 0x200000, 0x080000, CRC(33fd2913) SHA1(60b664559b4989446b1c7d875432e53a36fe27df) ) // same as radm, but different epr code
ROM_LOAD_x2( "epr-14237.ic22", 0x300000, 0x080000, CRC(0a4b4b29) SHA1(98447a587f903ba03e17d6a145b7c8bfddf25c4d) )
ROM_REGION( 0x100000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "epr-14102.ic3", 0x000000, 0x040000, CRC(5626e80f) SHA1(9844817295a8cd8a9b09da6681b0c1fbfe82618e) )
ROM_LOAD32_BYTE( "epr-14103.ic7", 0x000002, 0x040000, CRC(08c7e804) SHA1(cf45b1934edc43cb3a0ed72159949cb0dd00d701) )
ROM_LOAD32_BYTE( "epr-14104.ic12", 0x000001, 0x040000, CRC(b0173646) SHA1(1ba4edc033e0e4f5a1e02987e9f6b8b1650b46d7) )
ROM_LOAD32_BYTE( "epr-14105.ic16", 0x000003, 0x040000, CRC(614843b6) SHA1(d4f2cd3b024f7152d6e89237f0da06adea2efe57) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-13511.ic1", 0x000000, 0x100000, CRC(f8f15b11) SHA1(da6c2b8c3a94c4c263583f046823eaea818aff7c) )
ROM_LOAD64_BYTE( "mpr-13512.ic5", 0x000001, 0x100000, CRC(d0be34a6) SHA1(b42a63e30f0f7a94de8a825ca93cf8efdb7a7648) )
ROM_LOAD64_BYTE( "mpr-13513.ic10", 0x000002, 0x100000, CRC(feef1982) SHA1(bdf906317079a12c48ef4fca5bef0d437e9bf050) )
ROM_LOAD64_BYTE( "mpr-13514.ic16", 0x000003, 0x100000, CRC(d0f9ebd1) SHA1(510ebd3d7a52bcab2debea61591770d1dff172a1) )
ROM_LOAD64_BYTE( "mpr-13515.ic2", 0x000004, 0x100000, CRC(77bf2387) SHA1(7215dde5618e238edbe16b3007ede790785fe25f) )
ROM_LOAD64_BYTE( "mpr-13516.ic6", 0x000005, 0x100000, CRC(8c4bc62d) SHA1(3206f623ec0b7558413d063404103b183f26b488) )
ROM_LOAD64_BYTE( "mpr-13517.ic11", 0x000006, 0x100000, CRC(1d7d84a7) SHA1(954cfccfc7250a5bead2eeba42e655d5ac82955f) )
ROM_LOAD64_BYTE( "mpr-13518.ic17", 0x000007, 0x100000, CRC(9ea4b15d) SHA1(7dcfd6d42bb945beca8344cf92e7bd53903a824b) )
ROM_REGION( 0x8000, "user2", 0 ) /* unused */
ROM_LOAD( "epr-14084.17", 0x00000, 0x8000, CRC(f14ed074) SHA1(e1bb23eac85e3236046527c5c7688f6f23d43aef) ) /* cabinet link */
ROM_REGION16_BE( 0x80, "mainpcb:eeprom", 0 )
ROM_LOAD16_WORD( "eeprom-radr.ic76", 0x0000, 0x0080, CRC(602032c6) SHA1(fecf14017e537fe870457d2a8d4f86ec6d442b90) )
ROM_END
/**************************************************************************************************************************
Rad Rally (Japan)
not protected
Sega Game ID codes:
Game: 833-8110-03 RAD RALLY
ROM board: 833-8111-03
A/D BD NO. 837-7536
*/
ROM_START( radrj )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x8( "epr-14111.ic21", 0x000000, 0x020000, CRC(7adc6d17) SHA1(fc312a30b077ba060b6d98ab6ecccd2e16b32fc2) )
ROM_LOAD16_BYTE( "epr-14106.ic37", 0x100000, 0x080000, CRC(e73c63bf) SHA1(30fb68eaa7d02a232c873bd7751cac7d0fa08e44) )
ROM_LOAD16_BYTE( "epr-14107.ic38", 0x100001, 0x080000, CRC(832f797a) SHA1(b0c16ef7bd8d37f592975052ba9da3da70a2fc79) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-14108.ic9", 0x000000, 0x020000, CRC(38a99b4d) SHA1(b6455e6b29bfef41c5e0ebe3a8064889b7e5f5fd) )
ROM_LOAD_x2( "epr-14109.ic14", 0x100000, 0x080000, CRC(d5563697) SHA1(eb3fd3dbfea383ac1bb5d2e1552723994cb4693d) ) // same as radm, but different epr code
ROM_LOAD_x2( "epr-14110.ic20", 0x200000, 0x080000, CRC(33fd2913) SHA1(60b664559b4989446b1c7d875432e53a36fe27df) ) // same as radm, but different epr code
ROM_LOAD_x2( "epr-14237.ic22", 0x300000, 0x080000, CRC(0a4b4b29) SHA1(98447a587f903ba03e17d6a145b7c8bfddf25c4d) )
ROM_REGION( 0x100000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "epr-14102.ic3", 0x000000, 0x040000, CRC(5626e80f) SHA1(9844817295a8cd8a9b09da6681b0c1fbfe82618e) )
ROM_LOAD32_BYTE( "epr-14103.ic7", 0x000002, 0x040000, CRC(08c7e804) SHA1(cf45b1934edc43cb3a0ed72159949cb0dd00d701) )
ROM_LOAD32_BYTE( "epr-14104.ic12", 0x000001, 0x040000, CRC(b0173646) SHA1(1ba4edc033e0e4f5a1e02987e9f6b8b1650b46d7) )
ROM_LOAD32_BYTE( "epr-14105.ic16", 0x000003, 0x040000, CRC(614843b6) SHA1(d4f2cd3b024f7152d6e89237f0da06adea2efe57) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-13511.ic1", 0x000000, 0x100000, CRC(f8f15b11) SHA1(da6c2b8c3a94c4c263583f046823eaea818aff7c) )
ROM_LOAD64_BYTE( "mpr-13512.ic5", 0x000001, 0x100000, CRC(d0be34a6) SHA1(b42a63e30f0f7a94de8a825ca93cf8efdb7a7648) )
ROM_LOAD64_BYTE( "mpr-13513.ic10", 0x000002, 0x100000, CRC(feef1982) SHA1(bdf906317079a12c48ef4fca5bef0d437e9bf050) )
ROM_LOAD64_BYTE( "mpr-13514.ic16", 0x000003, 0x100000, CRC(d0f9ebd1) SHA1(510ebd3d7a52bcab2debea61591770d1dff172a1) )
ROM_LOAD64_BYTE( "mpr-13515.ic2", 0x000004, 0x100000, CRC(77bf2387) SHA1(7215dde5618e238edbe16b3007ede790785fe25f) )
ROM_LOAD64_BYTE( "mpr-13516.ic6", 0x000005, 0x100000, CRC(8c4bc62d) SHA1(3206f623ec0b7558413d063404103b183f26b488) )
ROM_LOAD64_BYTE( "mpr-13517.ic11", 0x000006, 0x100000, CRC(1d7d84a7) SHA1(954cfccfc7250a5bead2eeba42e655d5ac82955f) )
ROM_LOAD64_BYTE( "mpr-13518.ic17", 0x000007, 0x100000, CRC(9ea4b15d) SHA1(7dcfd6d42bb945beca8344cf92e7bd53903a824b) )
ROM_REGION( 0x8000, "user2", 0 ) /* unused */
ROM_LOAD( "epr-14084.17", 0x00000, 0x8000, CRC(f14ed074) SHA1(e1bb23eac85e3236046527c5c7688f6f23d43aef) ) /* cabinet link */
ROM_REGION16_BE( 0x80, "mainpcb:eeprom", 0 )
ROM_LOAD16_WORD( "eeprom-radr.ic76", 0x0000, 0x0080, CRC(602032c6) SHA1(fecf14017e537fe870457d2a8d4f86ec6d442b90) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Slipstream (Brazil)
GAME BD NO. 833-7429-01
1. ROM BD. 837-7429-01
2. MAIN BD. 837-7428
A/D BD NO. 837-7536
*/
ROM_START( slipstrm )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x2( "s32b_prg01.ic6", 0x000000, 0x080000, CRC(7d066307) SHA1(d87e04167263b435b77830db02ed58651ccc020c) )
ROM_LOAD16_BYTE( "s32_dat00.ic14",0x100000, 0x080000, CRC(c3ff6309) SHA1(dcc857736fe0f15aa7909c3ee88a7e239c8f0228) )
ROM_LOAD16_BYTE( "s32_dat01.ic7", 0x100001, 0x080000, CRC(0e605c81) SHA1(47c64195cab9a07b234d5a375d26168e53ffaa17) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "s32_snd00.ic35", 0x000000, 0x020000, CRC(0fee2278) SHA1(7533a03c3fc46d65dfdd07bddf1e6e0bbc368752) )
ROM_LOAD_x2( "s32_snd01.ic31", 0x100000, 0x080000, CRC(ae7be5f2) SHA1(ba089355e64864435bcc3b0c208e4bce1ea66295) )
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "s32_scr00.ic38", 0x000000, 0x080000, CRC(3cbb2d0b) SHA1(b94006347b72cd60a889b0e279f62f677cedfd2e) )
ROM_LOAD32_BYTE( "s32_scr01.ic34", 0x000002, 0x080000, CRC(4167be55) SHA1(96b34d311b318c00c3fad917e341589a70ba0a15) )
ROM_LOAD32_BYTE( "s32_scr02.ic29", 0x000001, 0x080000, CRC(52c4bb85) SHA1(4fbee1072a19c75c25b5fd269acc75640923d69c) )
ROM_LOAD32_BYTE( "s32_scr03.ic25", 0x000003, 0x080000, CRC(4948604a) SHA1(d5a1b9781fef7976a59a0af9b755a04fcacf9381) )
ROM_REGION32_BE( 0x400000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "s32_obj00.ic36", 0x000000, 0x80000, CRC(cffe9e0d) SHA1(5272d54ff142de927a9abd61f3646e963c7d22c4) )
ROM_LOAD64_BYTE( "s32_obj01.ic32", 0x000001, 0x80000, CRC(4ebd1383) SHA1(ce35f4d15e7904bfde55e58cdde925cba8002763) )
ROM_LOAD64_BYTE( "s32_obj02.ic27", 0x000002, 0x80000, CRC(b3cf4fe2) SHA1(e13199522e1e3e8b9cfe72cc29b33f25dad542ef) )
ROM_LOAD64_BYTE( "s32_obj03.ic23", 0x000003, 0x80000, CRC(c6345391) SHA1(155758097911ffca0c5c0b2a24a8033339dcfcbb) )
ROM_LOAD64_BYTE( "s32_obj04.ic37", 0x000004, 0x80000, CRC(2de4288e) SHA1(8e794f79f506293edb7609187a7908516ce76849) )
ROM_LOAD64_BYTE( "s32_obj05.ic33", 0x000005, 0x80000, CRC(6cfb74fb) SHA1(b74c886959910cd069427418525b23300a9b7b18) )
ROM_LOAD64_BYTE( "s32_obj06.ic28", 0x000006, 0x80000, CRC(53234bf4) SHA1(1eca538dcb86e44c31310ab1ab42a2b66b69c8fe) )
ROM_LOAD64_BYTE( "s32_obj07.ic24", 0x000007, 0x80000, CRC(22c129cf) SHA1(0f64680511a357038f6a556253c13fbb5417dd1a) )
ROM_END
/**************************************************************************************************************************
Slipstream (Hispanic)
GAME BD NO. 833-7429-01
1. ROM BD. 837-7429-01
2. MAIN BD. 837-7428
A/D BD NO. 837-7536
*/
ROM_START( slipstrmh )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x2( "s32h_prg01.ic6", 0x000000, 0x080000, CRC(ab778297) SHA1(e440d44b20f2f7478ef7d86af90af5eb7b9a545a) )
ROM_LOAD16_BYTE( "s32_dat00.ic14",0x100000, 0x080000, CRC(c3ff6309) SHA1(dcc857736fe0f15aa7909c3ee88a7e239c8f0228) )
ROM_LOAD16_BYTE( "s32_dat01.ic7", 0x100001, 0x080000, CRC(0e605c81) SHA1(47c64195cab9a07b234d5a375d26168e53ffaa17) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "s32_snd00.ic35", 0x000000, 0x020000, CRC(0fee2278) SHA1(7533a03c3fc46d65dfdd07bddf1e6e0bbc368752) )
ROM_LOAD_x2( "s32_snd01.ic31", 0x100000, 0x080000, CRC(ae7be5f2) SHA1(ba089355e64864435bcc3b0c208e4bce1ea66295) )
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "s32_scr00.ic38", 0x000000, 0x080000, CRC(3cbb2d0b) SHA1(b94006347b72cd60a889b0e279f62f677cedfd2e) )
ROM_LOAD32_BYTE( "s32_scr01.ic34", 0x000002, 0x080000, CRC(4167be55) SHA1(96b34d311b318c00c3fad917e341589a70ba0a15) )
ROM_LOAD32_BYTE( "s32_scr02.ic29", 0x000001, 0x080000, CRC(52c4bb85) SHA1(4fbee1072a19c75c25b5fd269acc75640923d69c) )
ROM_LOAD32_BYTE( "s32_scr03.ic25", 0x000003, 0x080000, CRC(4948604a) SHA1(d5a1b9781fef7976a59a0af9b755a04fcacf9381) )
ROM_REGION32_BE( 0x400000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "s32_obj00.ic36", 0x000000, 0x80000, CRC(cffe9e0d) SHA1(5272d54ff142de927a9abd61f3646e963c7d22c4) )
ROM_LOAD64_BYTE( "s32_obj01.ic32", 0x000001, 0x80000, CRC(4ebd1383) SHA1(ce35f4d15e7904bfde55e58cdde925cba8002763) )
ROM_LOAD64_BYTE( "s32_obj02.ic27", 0x000002, 0x80000, CRC(b3cf4fe2) SHA1(e13199522e1e3e8b9cfe72cc29b33f25dad542ef) )
ROM_LOAD64_BYTE( "s32_obj03.ic23", 0x000003, 0x80000, CRC(c6345391) SHA1(155758097911ffca0c5c0b2a24a8033339dcfcbb) )
ROM_LOAD64_BYTE( "s32_obj04.ic37", 0x000004, 0x80000, CRC(2de4288e) SHA1(8e794f79f506293edb7609187a7908516ce76849) )
ROM_LOAD64_BYTE( "s32_obj05.ic33", 0x000005, 0x80000, CRC(6cfb74fb) SHA1(b74c886959910cd069427418525b23300a9b7b18) )
ROM_LOAD64_BYTE( "s32_obj06.ic28", 0x000006, 0x80000, CRC(53234bf4) SHA1(1eca538dcb86e44c31310ab1ab42a2b66b69c8fe) )
ROM_LOAD64_BYTE( "s32_obj07.ic24", 0x000007, 0x80000, CRC(22c129cf) SHA1(0f64680511a357038f6a556253c13fbb5417dd1a) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
SegaSonic the Hedgehog - Protected (FD1149 SEGA 317-0213)
Sega ROM BD ID# 834-9496
ROM BD. 837-8393-01
I/O BD NO. 837-8685
*/
ROM_START( sonic )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-15787c.ic17", 0x000000, 0x020000, CRC(25e3c27e) SHA1(8f173cd5c7c817dcccdcad9be5781cfaa081d73e) )
ROM_LOAD_x4( "epr-15786c.ic8", 0x080000, 0x020000, CRC(efe9524c) SHA1(8020e734704a8f989919ee5ad92f70035de717f0) )
ROM_LOAD16_BYTE_x2( "epr-15781c.ic18", 0x100000, 0x040000, CRC(65b06c25) SHA1(9f524012a7adbc71737f90fc556f0ce9adc2bcf8) )
ROM_LOAD16_BYTE_x2( "epr-15780c.ic9", 0x100001, 0x040000, CRC(2db66fd2) SHA1(54582c0d5977649a38fc3a2c0fe4d7b1959abc76) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-15785.ic36", 0x000000, 0x040000, CRC(0fe7422e) SHA1(b7eaf4736ba155965317bb4ef3b33fc122635151) )
ROM_LOAD( "mpr-15784.ic35", 0x100000, 0x100000, CRC(42f06714) SHA1(30e45bb2d9b492f0c1acc4fbe1e5869f0559300b) )
ROM_LOAD( "mpr-15783.ic34", 0x200000, 0x100000, CRC(e4220eea) SHA1(a546c8bfc24e0695cf79c49e1a867d2595a1ed7f) )
ROM_LOAD( "mpr-15782.ic33", 0x300000, 0x100000, CRC(cf56b5a0) SHA1(5786228aab120c3361524ba93b418b24fd5b8ffb) ) // (this is the only ROM unchanged from the prototype)
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15789.ic14", 0x000000, 0x100000, CRC(4378f12b) SHA1(826e0550a3c5f2b6e59c6531ac03658a4f826651) )
ROM_LOAD16_BYTE( "mpr-15788.ic5", 0x000001, 0x100000, CRC(a6ed5d7a) SHA1(d30f26b452d380e7657e044e144f7dbbc4dc13e5) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15790.ic32", 0x000000, 0x200000, CRC(c69d51b1) SHA1(7644fb64457855f9ed87ca25ddc28c21bcb61fd9) )
ROM_LOAD64_WORD( "mpr-15792.ic30", 0x000002, 0x200000, CRC(1006bb67) SHA1(38c752e634aa94b1a23c09c4dba6388b7d0358af) )
ROM_LOAD64_WORD( "mpr-15794.ic28", 0x000004, 0x200000, CRC(8672b480) SHA1(61659e3856cdff0b2bca190a7e60c81b86ea2089) )
ROM_LOAD64_WORD( "mpr-15796.ic26", 0x000006, 0x200000, CRC(95b8011c) SHA1(ebc56ae49a76d04de60b0f81506769219a9885a7) )
// NOTE: these last 4 are in fact 16 megabit ROMs,
// but they were dumped as 8 because the top half
// is "FF" in all of them.
ROM_LOAD64_WORD( "mpr-15791.ic31", 0x800000, 0x100000, CRC(42217066) SHA1(46d14c632da1bed02bc0a637e34ab9cbf356c5de) )
ROM_LOAD64_WORD( "mpr-15793.ic29", 0x800002, 0x100000, CRC(75bafe55) SHA1(ad33dae062c4bdf8d17d3f6f7c333aa2e7da260e) )
ROM_LOAD64_WORD( "mpr-15795.ic27", 0x800004, 0x100000, CRC(7f3dad30) SHA1(84be1c31df35e1c7fef77e83d6d135378789a1ef) )
ROM_LOAD64_WORD( "mpr-15797.ic25", 0x800006, 0x100000, CRC(013c6cab) SHA1(eb9b77d28815d2e225b0882706084a52b11c48ea) )
ROM_END
/**************************************************************************************************************************
SegaSonic the Hedgehog (prototype)
not protected
*/
ROM_START( sonicp )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "sonpg0.bin", 0x000000, 0x20000, CRC(da05dcbb) SHA1(c2ced1f3aee92b0e531d5cd7611d4811f2ae95e7) )
ROM_LOAD_x4( "sonpg1.bin", 0x080000, 0x20000, CRC(c57dc5c5) SHA1(5741bdd52ee7181d883129885838b36f4af8a04c) )
ROM_LOAD16_BYTE_x2( "sonpd0.bin", 0x100000, 0x40000, CRC(a7da7546) SHA1(0a10573b21cd38d58380698bc18b0256dbb24044) )
ROM_LOAD16_BYTE_x2( "sonpd1.bin", 0x100001, 0x40000, CRC(c30e4c70) SHA1(897b6f62921694fe3c63677908f76eaf38b7b92f) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "sonsnd0.bin", 0x000000, 0x040000, CRC(569c8d4b) SHA1(9f1f6da6adbea043cc5ad853806fcb7bf683c832) )
ROM_LOAD( "sonsnd1.bin", 0x100000, 0x100000, CRC(f4fa5a21) SHA1(14a364ba7744ff0b44423d8d6bab990fe534ff29) )
ROM_LOAD( "sonsnd2.bin", 0x200000, 0x100000, CRC(e1bd45a5) SHA1(b411757853d61588e5223b48b5124cc00b3d65dd) )
ROM_LOAD( "sonsnd3.bin", 0x300000, 0x100000, CRC(cf56b5a0) SHA1(5786228aab120c3361524ba93b418b24fd5b8ffb) )
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "sonscl0.bin", 0x000000, 0x080000, CRC(445e31b9) SHA1(5678dfda74a09b5ac673448b222d11df4ca23aff) )
ROM_LOAD32_BYTE( "sonscl1.bin", 0x000002, 0x080000, CRC(3d234181) SHA1(2e8c14ad36be76f5f5fc6a3ee152f1abc8bf0ddd) )
ROM_LOAD32_BYTE( "sonscl2.bin", 0x000001, 0x080000, CRC(a5de28b2) SHA1(49a16ac10cf01b5b8802b8b015a2e403086c206a) )
ROM_LOAD32_BYTE( "sonscl3.bin", 0x000003, 0x080000, CRC(7ce7554b) SHA1(8def3acae6baafbe9e350f18e245a9a833df5cc4) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "sonobj0.bin", 0x000000, 0x100000, CRC(ceea18e3) SHA1(f902a7e2f8e126fd7a7862c55de32ce6352a7716) )
ROM_LOAD64_BYTE( "sonobj1.bin", 0x000001, 0x100000, CRC(6bbc226b) SHA1(5ef4256b6a93891daf1349def6db3bc428e5f4f3) )
ROM_LOAD64_BYTE( "sonobj2.bin", 0x000002, 0x100000, CRC(fcd5ef0e) SHA1(e3e50d4838ac3cce41d69ee6cd31981fbe422a4b) )
ROM_LOAD64_BYTE( "sonobj3.bin", 0x000003, 0x100000, CRC(b99b42ab) SHA1(60d91dc4e8e0adc62809cd2e71833c658124fbfc) )
ROM_LOAD64_BYTE( "sonobj4.bin", 0x000004, 0x100000, CRC(c7ec1456) SHA1(d866b9dff546bd6feb43e317328ac0a2324303b9) )
ROM_LOAD64_BYTE( "sonobj5.bin", 0x000005, 0x100000, CRC(bd5da27f) SHA1(ab3043190a32b555513a29a70e01547daf698cf8) )
ROM_LOAD64_BYTE( "sonobj6.bin", 0x000006, 0x100000, CRC(313c92d1) SHA1(a5134750667502811fd755cc0974a744cdb785e1) )
ROM_LOAD64_BYTE( "sonobj7.bin", 0x000007, 0x100000, CRC(3784c507) SHA1(8ea58c52b09b84643218e26f1ec1fa0ea864346e) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Spiderman (Export)
not protected
Sega Game ID codes:
Game: 833-8331-05 SPIDER-MAN
ROM board: 834-8332-02
ROM board type: 837-7429-01
Input sub board: 837-7968
*/
ROM_START( spidman )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14307.ic13", 0x000000, 0x020000, CRC(d900219c) SHA1(d59654db1fc0ec4d5f8cda9000ab4bd3bb36cdfc) )
ROM_LOAD_x4( "epr-14306.ic7", 0x080000, 0x020000, CRC(64379dc6) SHA1(7efc7175351186c54f141161a395e63b1cc7e7a5) )
ROM_LOAD16_BYTE_x4( "epr-14281.ic14", 0x100000, 0x020000, CRC(8a746c42) SHA1(fa3729ec3aa4b3c59322408146ce2cfbf5a11b98) )
ROM_LOAD16_BYTE_x4( "epr-14280.ic6", 0x100001, 0x020000, CRC(3c8148f7) SHA1(072b7982bb95e7a9ab77844b59020146c262488d) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-14285.ic35", 0x000000, 0x040000, CRC(25aefad6) SHA1(10153f4e773a0f55378f869eb1d85156e85f893f) )
ROM_LOAD_x2( "mpr-14284.ic31", 0x100000, 0x080000, CRC(760542d4) SHA1(dcac73869c02fefd328bd6bdbcbdb3b68b0647da) )
ROM_LOAD_x2( "mpr-14283.ic26", 0x200000, 0x080000, CRC(c863a91c) SHA1(afdc76bbb9b207cfcb47d437248a757d03212f4e) )
ROM_LOAD_x2( "mpr-14282.ic22", 0x300000, 0x080000, CRC(ea20979e) SHA1(9b70ef055da8c7c56da54b7edef2379678e7c50f) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14291-s.ic38", 0x000000, 0x100000, CRC(490f95a1) SHA1(f220788670b76164ac414ed9b16a422f719be267) )
ROM_LOAD32_BYTE( "mpr-14290-s.ic34", 0x000002, 0x100000, CRC(a144162d) SHA1(d43f12dd9f690cdfcebb6c7b515ff7dc7dcaa377) )
ROM_LOAD32_BYTE( "mpr-14289-s.ic29", 0x000001, 0x100000, CRC(38570582) SHA1(a9d810a02a1f5a6849c79d65fbebff21a4b82b59) )
ROM_LOAD32_BYTE( "mpr-14288-s.ic25", 0x000003, 0x100000, CRC(3188b636) SHA1(bc0adeeca5040caa563ee1e0eded9c323ca23446) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14299-h.ic36", 0x000000, 0x100000, CRC(ce59231b) SHA1(bcb1f11b74935694d0617ec8df66db2cc57b6219) )
ROM_LOAD64_BYTE( "mpr-14298-h.ic32", 0x000001, 0x100000, CRC(2745c84c) SHA1(5a0528c921cba7a1047d3a2ece79925103d719a1) )
ROM_LOAD64_BYTE( "mpr-14297-h.ic27", 0x000002, 0x100000, CRC(29cb9450) SHA1(7dc38d23a2f0cee2f4edde05c1a6f0dc83f331db) )
ROM_LOAD64_BYTE( "mpr-14296-h.ic23", 0x000003, 0x100000, CRC(9d8cbd31) SHA1(55a9f9ec9029157da033e69664b58e694a28db47) )
ROM_LOAD64_BYTE( "mpr-14295-h.ic37", 0x000004, 0x100000, CRC(29591f50) SHA1(1ac4ceaf74892e30f210ad77024eb441c5e4a959) )
ROM_LOAD64_BYTE( "mpr-14294-h.ic33", 0x000005, 0x100000, CRC(fa86b794) SHA1(7b6907e5734fbf2fba7bcc213a8551fec5e9f3d5) )
ROM_LOAD64_BYTE( "mpr-14293-s.ic28", 0x000006, 0x100000, CRC(52899269) SHA1(ff809ff88701109e0ca79e785a61402d97335cec) )
ROM_LOAD64_BYTE( "mpr-14292-s.ic24", 0x000007, 0x100000, CRC(41f71443) SHA1(351d40d6159cb5b792519bce5d16490965800cfb) )
ROM_END
/**************************************************************************************************************************
Spiderman (U.S.)
not protected
Sega Game ID codes:
Game: 833-8331-04 SPIDER-MAN
ROM board: 834-8332-01
ROM board type: 837-7429-01
Input sub board: 837-7968
*/
ROM_START( spidmanu )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14303a.ic13", 0x000000, 0x020000, CRC(7f1bd28f) SHA1(cff57e66d09682baf44aace99d698ad305f6a3d5) )
ROM_LOAD_x4( "epr-14302a.ic7", 0x080000, 0x020000, CRC(d954c40a) SHA1(436c81779274861de79dc6ce2c0fcc65bfd52098) )
ROM_LOAD16_BYTE_x4( "epr-14281.ic14", 0x100000, 0x020000, CRC(8a746c42) SHA1(fa3729ec3aa4b3c59322408146ce2cfbf5a11b98) )
ROM_LOAD16_BYTE_x4( "epr-14280.ic6", 0x100001, 0x020000, CRC(3c8148f7) SHA1(072b7982bb95e7a9ab77844b59020146c262488d) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-14285.ic35", 0x000000, 0x040000, CRC(25aefad6) SHA1(10153f4e773a0f55378f869eb1d85156e85f893f) )
ROM_LOAD_x2( "mpr-14284.ic31", 0x100000, 0x080000, CRC(760542d4) SHA1(dcac73869c02fefd328bd6bdbcbdb3b68b0647da) )
ROM_LOAD_x2( "mpr-14283.ic26", 0x200000, 0x080000, CRC(c863a91c) SHA1(afdc76bbb9b207cfcb47d437248a757d03212f4e) )
ROM_LOAD_x2( "mpr-14282.ic22", 0x300000, 0x080000, CRC(ea20979e) SHA1(9b70ef055da8c7c56da54b7edef2379678e7c50f) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14291-s.ic38", 0x000000, 0x100000, CRC(490f95a1) SHA1(f220788670b76164ac414ed9b16a422f719be267) )
ROM_LOAD32_BYTE( "mpr-14290-s.ic34", 0x000002, 0x100000, CRC(a144162d) SHA1(d43f12dd9f690cdfcebb6c7b515ff7dc7dcaa377) )
ROM_LOAD32_BYTE( "mpr-14289-s.ic29", 0x000001, 0x100000, CRC(38570582) SHA1(a9d810a02a1f5a6849c79d65fbebff21a4b82b59) )
ROM_LOAD32_BYTE( "mpr-14288-s.ic25", 0x000003, 0x100000, CRC(3188b636) SHA1(bc0adeeca5040caa563ee1e0eded9c323ca23446) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14299-h.ic36", 0x000000, 0x100000, CRC(ce59231b) SHA1(bcb1f11b74935694d0617ec8df66db2cc57b6219) )
ROM_LOAD64_BYTE( "mpr-14298-h.ic32", 0x000001, 0x100000, CRC(2745c84c) SHA1(5a0528c921cba7a1047d3a2ece79925103d719a1) )
ROM_LOAD64_BYTE( "mpr-14297-h.ic27", 0x000002, 0x100000, CRC(29cb9450) SHA1(7dc38d23a2f0cee2f4edde05c1a6f0dc83f331db) )
ROM_LOAD64_BYTE( "mpr-14296-h.ic23", 0x000003, 0x100000, CRC(9d8cbd31) SHA1(55a9f9ec9029157da033e69664b58e694a28db47) )
ROM_LOAD64_BYTE( "mpr-14295-h.ic37", 0x000004, 0x100000, CRC(29591f50) SHA1(1ac4ceaf74892e30f210ad77024eb441c5e4a959) )
ROM_LOAD64_BYTE( "mpr-14294-h.ic33", 0x000005, 0x100000, CRC(fa86b794) SHA1(7b6907e5734fbf2fba7bcc213a8551fec5e9f3d5) )
ROM_LOAD64_BYTE( "mpr-14293-s.ic28", 0x000006, 0x100000, CRC(52899269) SHA1(ff809ff88701109e0ca79e785a61402d97335cec) )
ROM_LOAD64_BYTE( "mpr-14292-s.ic24", 0x000007, 0x100000, CRC(41f71443) SHA1(351d40d6159cb5b792519bce5d16490965800cfb) )
ROM_END
/**************************************************************************************************************************
Spiderman (Japan)
not protected
Game: 833-8331 SPIDER-MAN
ROM board: 834-8332
ROM board type: 837-7429-01
Input sub board: 837-7968
*/
ROM_START( spidmanj )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-14287.ic13", 0x000000, 0x020000, CRC(403ccdc9) SHA1(4e240c749e362dfa5c579ccbdff18ae3fab58dff) )
ROM_LOAD_x4( "epr-14286.ic7", 0x080000, 0x020000, CRC(5c2b4e2c) SHA1(79229594710416510f85e6e53ea578789afd4091) )
ROM_LOAD16_BYTE_x4( "epr-14281.ic14", 0x100000, 0x020000, CRC(8a746c42) SHA1(fa3729ec3aa4b3c59322408146ce2cfbf5a11b98) )
ROM_LOAD16_BYTE_x4( "epr-14280.ic6", 0x100001, 0x020000, CRC(3c8148f7) SHA1(072b7982bb95e7a9ab77844b59020146c262488d) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-14285.ic35", 0x000000, 0x040000, CRC(25aefad6) SHA1(10153f4e773a0f55378f869eb1d85156e85f893f) )
ROM_LOAD_x2( "mpr-14284.ic31", 0x100000, 0x080000, CRC(760542d4) SHA1(dcac73869c02fefd328bd6bdbcbdb3b68b0647da) )
ROM_LOAD_x2( "mpr-14283.ic26", 0x200000, 0x080000, CRC(c863a91c) SHA1(afdc76bbb9b207cfcb47d437248a757d03212f4e) )
ROM_LOAD_x2( "mpr-14282.ic22", 0x300000, 0x080000, CRC(ea20979e) SHA1(9b70ef055da8c7c56da54b7edef2379678e7c50f) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD32_BYTE( "mpr-14291-s.ic38", 0x000000, 0x100000, CRC(490f95a1) SHA1(f220788670b76164ac414ed9b16a422f719be267) )
ROM_LOAD32_BYTE( "mpr-14290-s.ic34", 0x000002, 0x100000, CRC(a144162d) SHA1(d43f12dd9f690cdfcebb6c7b515ff7dc7dcaa377) )
ROM_LOAD32_BYTE( "mpr-14289-s.ic29", 0x000001, 0x100000, CRC(38570582) SHA1(a9d810a02a1f5a6849c79d65fbebff21a4b82b59) )
ROM_LOAD32_BYTE( "mpr-14288-s.ic25", 0x000003, 0x100000, CRC(3188b636) SHA1(bc0adeeca5040caa563ee1e0eded9c323ca23446) )
ROM_REGION32_BE( 0x800000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_BYTE( "mpr-14299-h.ic36", 0x000000, 0x100000, CRC(ce59231b) SHA1(bcb1f11b74935694d0617ec8df66db2cc57b6219) )
ROM_LOAD64_BYTE( "mpr-14298-h.ic32", 0x000001, 0x100000, CRC(2745c84c) SHA1(5a0528c921cba7a1047d3a2ece79925103d719a1) )
ROM_LOAD64_BYTE( "mpr-14297-h.ic27", 0x000002, 0x100000, CRC(29cb9450) SHA1(7dc38d23a2f0cee2f4edde05c1a6f0dc83f331db) )
ROM_LOAD64_BYTE( "mpr-14296-h.ic23", 0x000003, 0x100000, CRC(9d8cbd31) SHA1(55a9f9ec9029157da033e69664b58e694a28db47) )
ROM_LOAD64_BYTE( "mpr-14295-h.ic37", 0x000004, 0x100000, CRC(29591f50) SHA1(1ac4ceaf74892e30f210ad77024eb441c5e4a959) )
ROM_LOAD64_BYTE( "mpr-14294-h.ic33", 0x000005, 0x100000, CRC(fa86b794) SHA1(7b6907e5734fbf2fba7bcc213a8551fec5e9f3d5) )
ROM_LOAD64_BYTE( "mpr-14293-s.ic28", 0x000006, 0x100000, CRC(52899269) SHA1(ff809ff88701109e0ca79e785a61402d97335cec) )
ROM_LOAD64_BYTE( "mpr-14292-s.ic24", 0x000007, 0x100000, CRC(41f71443) SHA1(351d40d6159cb5b792519bce5d16490965800cfb) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Stadium Cross (Export) - Multi-32
not protected
*/
ROM_START( scross )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code */
ROM_LOAD32_WORD_x2( "epr-15093.ic37", 0x000000, 0x040000, CRC(2adc7a4b) SHA1(dca71f00d94898c0758394704d819e13482bf120) )
ROM_LOAD32_WORD_x2( "epr-15094.ic40", 0x000002, 0x040000, CRC(bbb0ae73) SHA1(0d8837706405f301adf8fa85c8d4813d7600af98) )
ROM_LOAD32_WORD( "mpr-15018.ic36", 0x100000, 0x080000, CRC(3a98385e) SHA1(8088d337655030c28e290da4bbf44cb647dab66c) )
ROM_LOAD32_WORD( "mpr-15019.ic39", 0x100002, 0x080000, CRC(8bf4ac83) SHA1(e594d9d9b42d0765ed8a20a40b7dd92b75124d34) )
ROM_REGION( 0x80000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-15192.ic31", 0x00000, 0x20000, CRC(7524290b) SHA1(ee58be2c0c4293ee19622b96ca493f4ce4da0038) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15020.ic3", 0x000000, 0x100000, CRC(de47006a) SHA1(dbef7b9ff8c39992b8596d38985e65c627d6fa79) )
ROM_LOAD16_BYTE( "mpr-15021.ic11", 0x000001, 0x100000, CRC(3677db02) SHA1(7aeeb85f1632253fcdc8f7881512066e97837e5e) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15022.ic14", 0x000000, 0x100000, CRC(baee6fd5) SHA1(ddf022c61f0805af45a84c65eb5d01006c153c07) )
ROM_LOAD64_WORD( "mpr-15024.ic15", 0x000002, 0x100000, CRC(b9f339e2) SHA1(4b9a392459132a19d62928ef3939e1f2356e3994) )
ROM_LOAD64_WORD( "mpr-15026.ic10", 0x000004, 0x100000, CRC(b72e8df6) SHA1(a7a87f79814b022985121e163c7f88244c50e427) )
ROM_LOAD64_WORD( "mpr-15028.ic38", 0x000006, 0x100000, CRC(183f6eb0) SHA1(5a2172d5afd696af361ff9f8a92f5911e05c578d) )
ROM_LOAD64_WORD( "mpr-15023.ic22", 0x800000, 0x100000, CRC(230735ed) SHA1(36075504e27b8a32d63fa3b8abd7037d17440ebf) )
ROM_LOAD64_WORD( "mpr-15025.ic23", 0x800002, 0x100000, CRC(da4315cb) SHA1(3910c5654e34b17851d6d93615e3404b3b397fea) )
ROM_LOAD64_WORD( "mpr-15027.ic18", 0x800004, 0x100000, CRC(b765efb8) SHA1(61f3865f92b36ca4b3cd20c0716a7121755eea73) )
ROM_LOAD64_WORD( "mpr-15029.ic41", 0x800006, 0x100000, CRC(cf8e3b2b) SHA1(c158810d9d82b10a753bc739d1f56572042dac0b) )
ROM_REGION( 0x400000, "mainpcb:sega", 0 ) /* Sega PCM sound data */
ROM_LOAD( "mpr-15031.ic1", 0x000000, 0x100000, CRC(6af139dc) SHA1(2378c2ad0c52c114eb93206a6fbee723c038d030) )
ROM_LOAD( "mpr-15032.ic2", 0x200000, 0x100000, CRC(915d6096) SHA1(e1f670949b1254f5a3c3131993ca9b3baa4d9f6b) )
ROM_REGION( 0x20000, "user2", 0 ) /* comms board? - might not belong to this game, just going based on epr number */
ROM_LOAD( "epr-15033.ic17", 0x00000, 0x20000, CRC(dc19ac00) SHA1(16bbb5af034e5419673e637be30283b73ab7b290) )
ROM_END
ROM_START( scrossa )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code */
// 37/40 were missing labels
ROM_LOAD32_WORD_x2( "ic37", 0x000000, 0x040000, CRC(240a7655) SHA1(7cfdce002fb4783e8c1debf206922d88647c106e) )
ROM_LOAD32_WORD_x2( "ic40", 0x000002, 0x040000, CRC(3a073060) SHA1(c92c8d8921d94d85c8484c103cbf9cd6ad651333) )
ROM_LOAD32_WORD( "mpr-15018.ic36", 0x100000, 0x080000, CRC(3a98385e) SHA1(8088d337655030c28e290da4bbf44cb647dab66c) )
ROM_LOAD32_WORD( "mpr-15019.ic39", 0x100002, 0x080000, CRC(8bf4ac83) SHA1(e594d9d9b42d0765ed8a20a40b7dd92b75124d34) )
ROM_REGION( 0x80000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-15192.ic31", 0x00000, 0x20000, CRC(7524290b) SHA1(ee58be2c0c4293ee19622b96ca493f4ce4da0038) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15020.ic3", 0x000000, 0x100000, CRC(de47006a) SHA1(dbef7b9ff8c39992b8596d38985e65c627d6fa79) )
ROM_LOAD16_BYTE( "mpr-15021.ic11", 0x000001, 0x100000, CRC(3677db02) SHA1(7aeeb85f1632253fcdc8f7881512066e97837e5e) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15022.ic14", 0x000000, 0x100000, CRC(baee6fd5) SHA1(ddf022c61f0805af45a84c65eb5d01006c153c07) )
ROM_LOAD64_WORD( "mpr-15024.ic15", 0x000002, 0x100000, CRC(b9f339e2) SHA1(4b9a392459132a19d62928ef3939e1f2356e3994) )
ROM_LOAD64_WORD( "mpr-15026.ic10", 0x000004, 0x100000, CRC(b72e8df6) SHA1(a7a87f79814b022985121e163c7f88244c50e427) )
ROM_LOAD64_WORD( "mpr-15028.ic38", 0x000006, 0x100000, CRC(183f6eb0) SHA1(5a2172d5afd696af361ff9f8a92f5911e05c578d) )
ROM_LOAD64_WORD( "mpr-15023.ic22", 0x800000, 0x100000, CRC(230735ed) SHA1(36075504e27b8a32d63fa3b8abd7037d17440ebf) )
ROM_LOAD64_WORD( "mpr-15025.ic23", 0x800002, 0x100000, CRC(da4315cb) SHA1(3910c5654e34b17851d6d93615e3404b3b397fea) )
ROM_LOAD64_WORD( "mpr-15027.ic18", 0x800004, 0x100000, CRC(b765efb8) SHA1(61f3865f92b36ca4b3cd20c0716a7121755eea73) )
ROM_LOAD64_WORD( "mpr-15029.ic41", 0x800006, 0x100000, CRC(cf8e3b2b) SHA1(c158810d9d82b10a753bc739d1f56572042dac0b) )
ROM_REGION( 0x400000, "mainpcb:sega", 0 ) /* Sega PCM sound data */
ROM_LOAD( "mpr-15031.ic1", 0x000000, 0x100000, CRC(6af139dc) SHA1(2378c2ad0c52c114eb93206a6fbee723c038d030) )
ROM_LOAD( "mpr-15032.ic2", 0x200000, 0x100000, CRC(915d6096) SHA1(e1f670949b1254f5a3c3131993ca9b3baa4d9f6b) )
ROM_REGION( 0x20000, "user2", 0 ) /* comms board confirmed */
ROM_LOAD( "epr-15033.ic17", 0x00000, 0x20000, CRC(dc19ac00) SHA1(16bbb5af034e5419673e637be30283b73ab7b290) )
ROM_END
/**************************************************************************************************************************
Stadium Cross (US) - Multi-32
not protected
*/
ROM_START( scrossu )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code */
ROM_LOAD32_WORD_x2( "epr-15091.ic37", 0x000000, 0x040000, CRC(2c572293) SHA1(6377a6eb6084f7332ce6eeaaf0c37200da792d0c) )
ROM_LOAD32_WORD_x2( "epr-15092.ic40", 0x000002, 0x040000, CRC(6e3e175a) SHA1(feaca0720646e2a4b78b376e99dc86788adb98e7) )
ROM_LOAD32_WORD( "epr-15018.ic36", 0x100000, 0x080000, CRC(3a98385e) SHA1(8088d337655030c28e290da4bbf44cb647dab66c) )
ROM_LOAD32_WORD( "epr-15019.ic39", 0x100002, 0x080000, CRC(8bf4ac83) SHA1(e594d9d9b42d0765ed8a20a40b7dd92b75124d34) )
ROM_REGION( 0x80000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-15192.ic31", 0x00000, 0x20000, CRC(7524290b) SHA1(ee58be2c0c4293ee19622b96ca493f4ce4da0038) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15020.ic3", 0x000000, 0x100000, CRC(de47006a) SHA1(dbef7b9ff8c39992b8596d38985e65c627d6fa79) )
ROM_LOAD16_BYTE( "mpr-15021.ic11", 0x000001, 0x100000, CRC(3677db02) SHA1(7aeeb85f1632253fcdc8f7881512066e97837e5e) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15022.ic14", 0x000000, 0x100000, CRC(baee6fd5) SHA1(ddf022c61f0805af45a84c65eb5d01006c153c07) )
ROM_LOAD64_WORD( "mpr-15024.ic15", 0x000002, 0x100000, CRC(b9f339e2) SHA1(4b9a392459132a19d62928ef3939e1f2356e3994) )
ROM_LOAD64_WORD( "mpr-15026.ic10", 0x000004, 0x100000, CRC(b72e8df6) SHA1(a7a87f79814b022985121e163c7f88244c50e427) )
ROM_LOAD64_WORD( "mpr-15028.ic38", 0x000006, 0x100000, CRC(183f6eb0) SHA1(5a2172d5afd696af361ff9f8a92f5911e05c578d) )
ROM_LOAD64_WORD( "mpr-15023.ic22", 0x800000, 0x100000, CRC(230735ed) SHA1(36075504e27b8a32d63fa3b8abd7037d17440ebf) )
ROM_LOAD64_WORD( "mpr-15025.ic23", 0x800002, 0x100000, CRC(da4315cb) SHA1(3910c5654e34b17851d6d93615e3404b3b397fea) )
ROM_LOAD64_WORD( "mpr-15027.ic18", 0x800004, 0x100000, CRC(b765efb8) SHA1(61f3865f92b36ca4b3cd20c0716a7121755eea73) )
ROM_LOAD64_WORD( "mpr-15029.ic41", 0x800006, 0x100000, CRC(cf8e3b2b) SHA1(c158810d9d82b10a753bc739d1f56572042dac0b) )
ROM_REGION( 0x400000, "mainpcb:sega", 0 ) /* Sega PCM sound data */
ROM_LOAD( "mpr-15031.ic1", 0x000000, 0x100000, CRC(6af139dc) SHA1(2378c2ad0c52c114eb93206a6fbee723c038d030) )
ROM_LOAD( "mpr-15032.ic2", 0x200000, 0x100000, CRC(915d6096) SHA1(e1f670949b1254f5a3c3131993ca9b3baa4d9f6b) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Super Visual Football
protected via FD1149 317-0222
Sega Game ID codes:
Game: 833-10851-02
ROM board: 834-10852-02
*/
ROM_START( svf )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-16872a.ic17", 0x000000, 0x020000, CRC(1f383b00) SHA1(c3af01743de5ff09ada19879902842efdbceb595) )
ROM_LOAD_x4( "epr-16871a.ic8", 0x080000, 0x020000, CRC(f7061bd7) SHA1(b46f4f2ecda8f521c0a91f2f2c2445b72cbc2874) )
ROM_LOAD16_BYTE( "epr-16865.ic18", 0x100000, 0x080000, CRC(9198ca9f) SHA1(0f6271ce8a07e4ab7fdce38964055510f2ebfd4e) )
ROM_LOAD16_BYTE( "epr-16864.ic9", 0x100001, 0x080000, CRC(201a940e) SHA1(e19d76141844dbdedee0698ea50edbb898ab55e9) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-16866.ic36", 0x000000, 0x020000, CRC(74431350) SHA1(d3208b595423b5b0f25ee90db213112a09906f8f) )
ROM_LOAD( "mpr-16779.ic35", 0x100000, 0x100000, CRC(7055e859) SHA1(cde27fa4aaf0ee54063ee68794e9a6075581fff5) )
ROM_LOAD( "mpr-16778.ic34", 0x200000, 0x100000, CRC(feedaecf) SHA1(25c14ccb85c467dc0c8e85b61f8f86f4396c0cc7) )
ROM_LOAD( "mpr-16777.ic24", 0x300000, 0x100000, CRC(14b5d5df) SHA1(1b0b0a31294b1bbc16d2046b374d584a1b00a78c) )
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16784.ic14", 0x000000, 0x100000, CRC(4608efe2) SHA1(9b41aa28f50af770e854ef9fdff1a55da7b7b131) )
ROM_LOAD16_BYTE( "mpr-16783.ic5", 0x000001, 0x100000, CRC(042eabe7) SHA1(a11df5c21d85f0c96dbdcaf57be37a79658ad648) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16785.ic32", 0x000000, 0x200000, CRC(51f775ce) SHA1(125b40bf47304d37b92e81df5081c81d9af6c8a2) )
ROM_LOAD64_WORD( "mpr-16787.ic30", 0x000002, 0x200000, CRC(dee7a204) SHA1(29acff4d5dd68609ac46853860788206d18262ab) )
ROM_LOAD64_WORD( "mpr-16789.ic28", 0x000004, 0x200000, CRC(6b6c8ad3) SHA1(97b0078c851845c31dcf0fe4b2a88393dcdf8988) )
ROM_LOAD64_WORD( "mpr-16791.ic26", 0x000006, 0x200000, CRC(4f7236da) SHA1(d1c29f6aa82d60a626217f1430bc8a76ef012007) )
ROM_LOAD64_WORD( "mpr-16860.ic31", 0x800000, 0x200000, CRC(578a7325) SHA1(75a066841fa24952d8ed5ac2d988609295f437a8) )
ROM_LOAD64_WORD( "mpr-16861.ic29", 0x800002, 0x200000, CRC(d79c3f73) SHA1(e4360efb0964a92cfad8c458a5568709fcc81339) )
ROM_LOAD64_WORD( "mpr-16862.ic27", 0x800004, 0x200000, CRC(00793354) SHA1(3b37a89c5100d5f92a3567fc8d2003bc9d6fe0cd) )
ROM_LOAD64_WORD( "mpr-16863.ic25", 0x800006, 0x200000, CRC(42338226) SHA1(106636408d5648fb95fbaee06074c57f6a535a82) )
ROM_END
ROM_START( svfo )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-16872.ic17", 0x000000, 0x020000, CRC(654d8c95) SHA1(0d28d6d8814c07e98fb9c50bd3ecbe17a9dee70a) )
ROM_LOAD_x4( "epr-16871.ic8", 0x080000, 0x020000, CRC(e0d0cac0) SHA1(e9a7d0878a38b93681497489a2366f7337a1abf5) )
ROM_LOAD16_BYTE( "epr-16865.ic18", 0x100000, 0x080000, CRC(9198ca9f) SHA1(0f6271ce8a07e4ab7fdce38964055510f2ebfd4e) )
ROM_LOAD16_BYTE( "epr-16864.ic9", 0x100001, 0x080000, CRC(201a940e) SHA1(e19d76141844dbdedee0698ea50edbb898ab55e9) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x8( "epr-16866.ic36", 0x000000, 0x020000, CRC(74431350) SHA1(d3208b595423b5b0f25ee90db213112a09906f8f) )
ROM_LOAD( "mpr-16779.ic35", 0x100000, 0x100000, CRC(7055e859) SHA1(cde27fa4aaf0ee54063ee68794e9a6075581fff5) )
ROM_LOAD( "mpr-16778.ic34", 0x200000, 0x100000, CRC(feedaecf) SHA1(25c14ccb85c467dc0c8e85b61f8f86f4396c0cc7) )
ROM_LOAD( "mpr-16777.ic24", 0x300000, 0x100000, CRC(14b5d5df) SHA1(1b0b0a31294b1bbc16d2046b374d584a1b00a78c) )
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16784.ic14", 0x000000, 0x100000, CRC(4608efe2) SHA1(9b41aa28f50af770e854ef9fdff1a55da7b7b131) )
ROM_LOAD16_BYTE( "mpr-16783.ic5", 0x000001, 0x100000, CRC(042eabe7) SHA1(a11df5c21d85f0c96dbdcaf57be37a79658ad648) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16785.ic32", 0x000000, 0x200000, CRC(51f775ce) SHA1(125b40bf47304d37b92e81df5081c81d9af6c8a2) )
ROM_LOAD64_WORD( "mpr-16787.ic30", 0x000002, 0x200000, CRC(dee7a204) SHA1(29acff4d5dd68609ac46853860788206d18262ab) )
ROM_LOAD64_WORD( "mpr-16789.ic28", 0x000004, 0x200000, CRC(6b6c8ad3) SHA1(97b0078c851845c31dcf0fe4b2a88393dcdf8988) )
ROM_LOAD64_WORD( "mpr-16791.ic26", 0x000006, 0x200000, CRC(4f7236da) SHA1(d1c29f6aa82d60a626217f1430bc8a76ef012007) )
ROM_LOAD64_WORD( "mpr-16860.ic31", 0x800000, 0x200000, CRC(578a7325) SHA1(75a066841fa24952d8ed5ac2d988609295f437a8) )
ROM_LOAD64_WORD( "mpr-16861.ic29", 0x800002, 0x200000, CRC(d79c3f73) SHA1(e4360efb0964a92cfad8c458a5568709fcc81339) )
ROM_LOAD64_WORD( "mpr-16862.ic27", 0x800004, 0x200000, CRC(00793354) SHA1(3b37a89c5100d5f92a3567fc8d2003bc9d6fe0cd) )
ROM_LOAD64_WORD( "mpr-16863.ic25", 0x800006, 0x200000, CRC(42338226) SHA1(106636408d5648fb95fbaee06074c57f6a535a82) )
ROM_END
/**************************************************************************************************************************
Super Visual Soccer
protected via FD1149 317-0222
*/
ROM_START( svs )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-16883a.ic17", 0x000000, 0x020000, CRC(e1c0c3ce) SHA1(12dd8d9d1a2c2c7bf1ab652a6a6f947384d79577) )
ROM_LOAD_x4( "epr-16882a.ic8", 0x080000, 0x020000, CRC(1161bbbe) SHA1(3cfeed9ea947eed79aeb5674d54de45d15fb6e1f) )
ROM_LOAD16_BYTE( "epr-16865.ic18", 0x100000, 0x080000, CRC(9198ca9f) SHA1(0f6271ce8a07e4ab7fdce38964055510f2ebfd4e) )
ROM_LOAD16_BYTE( "epr-16864.ic9", 0x100001, 0x080000, CRC(201a940e) SHA1(e19d76141844dbdedee0698ea50edbb898ab55e9) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-16868.ic36", 0x000000, 0x040000, CRC(47aa4ec7) SHA1(baea18aaac0314f769f1e36fdbe8aedf62862544) ) /* same as jleague but with a different part number */
ROM_LOAD( "mpr-16779.ic35", 0x100000, 0x100000, CRC(7055e859) SHA1(cde27fa4aaf0ee54063ee68794e9a6075581fff5) )
ROM_LOAD( "mpr-16778.ic34", 0x200000, 0x100000, CRC(feedaecf) SHA1(25c14ccb85c467dc0c8e85b61f8f86f4396c0cc7) )
ROM_LOAD( "mpr-16777.ic24", 0x300000, 0x100000, CRC(14b5d5df) SHA1(1b0b0a31294b1bbc16d2046b374d584a1b00a78c) )
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16784.ic14", 0x000000, 0x100000, CRC(4608efe2) SHA1(9b41aa28f50af770e854ef9fdff1a55da7b7b131) )
ROM_LOAD16_BYTE( "mpr-16783.ic5", 0x000001, 0x100000, CRC(042eabe7) SHA1(a11df5c21d85f0c96dbdcaf57be37a79658ad648) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16785.ic32", 0x000000, 0x200000, CRC(51f775ce) SHA1(125b40bf47304d37b92e81df5081c81d9af6c8a2) )
ROM_LOAD64_WORD( "mpr-16787.ic30", 0x000002, 0x200000, CRC(dee7a204) SHA1(29acff4d5dd68609ac46853860788206d18262ab) )
ROM_LOAD64_WORD( "mpr-16789.ic28", 0x000004, 0x200000, CRC(6b6c8ad3) SHA1(97b0078c851845c31dcf0fe4b2a88393dcdf8988) )
ROM_LOAD64_WORD( "mpr-16791.ic26", 0x000006, 0x200000, CRC(4f7236da) SHA1(d1c29f6aa82d60a626217f1430bc8a76ef012007) )
ROM_LOAD64_WORD( "mpr-16860.ic31", 0x800000, 0x200000, CRC(578a7325) SHA1(75a066841fa24952d8ed5ac2d988609295f437a8) )
ROM_LOAD64_WORD( "mpr-16861.ic29", 0x800002, 0x200000, CRC(d79c3f73) SHA1(e4360efb0964a92cfad8c458a5568709fcc81339) )
ROM_LOAD64_WORD( "mpr-16862.ic27", 0x800004, 0x200000, CRC(00793354) SHA1(3b37a89c5100d5f92a3567fc8d2003bc9d6fe0cd) )
ROM_LOAD64_WORD( "mpr-16863.ic25", 0x800006, 0x200000, CRC(42338226) SHA1(106636408d5648fb95fbaee06074c57f6a535a82) )
ROM_END
/**************************************************************************************************************************
The JLeague '94
protected via FD1149 317-0222
Sega Game ID codes:
Game: 833-10851 J. LEAGUE 1994
ROM board: 834-10852 J.LEAGUE
*/
ROM_START( jleague )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-16782a.ic17", 0x000000, 0x020000, CRC(b399ac47) SHA1(b7a2bfaf6ea2f98e177e3f4542f5b37ec9b00c8a) )
ROM_LOAD_x4( "epr-16781a.ic8", 0x080000, 0x020000, CRC(e6d80225) SHA1(bc9fd6b9e4019e01b9a496064e3b3209f31590e4) )
ROM_LOAD16_BYTE( "epr-16776.ic18", 0x100000, 0x080000, CRC(e8694626) SHA1(d4318a9a6b1cc5c719bff9c25b7398dd2ea1e18b) )
ROM_LOAD16_BYTE( "epr-16775.ic9", 0x100001, 0x080000, CRC(e81e2c3d) SHA1(2900710f1dec6cf71875c82a56584ba45ed3a545) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-16780.ic36", 0x000000, 0x040000, CRC(47aa4ec7) SHA1(baea18aaac0314f769f1e36fdbe8aedf62862544) )
ROM_LOAD( "mpr-16779.ic35", 0x100000, 0x100000, CRC(7055e859) SHA1(cde27fa4aaf0ee54063ee68794e9a6075581fff5) )
ROM_LOAD( "mpr-16778.ic34", 0x200000, 0x100000, CRC(feedaecf) SHA1(25c14ccb85c467dc0c8e85b61f8f86f4396c0cc7) )
ROM_LOAD( "mpr-16777.ic24", 0x300000, 0x100000, CRC(14b5d5df) SHA1(1b0b0a31294b1bbc16d2046b374d584a1b00a78c) )
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16784.ic14", 0x000000, 0x100000, CRC(4608efe2) SHA1(9b41aa28f50af770e854ef9fdff1a55da7b7b131) )
ROM_LOAD16_BYTE( "mpr-16783.ic5", 0x000001, 0x100000, CRC(042eabe7) SHA1(a11df5c21d85f0c96dbdcaf57be37a79658ad648) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16785.ic32", 0x000000, 0x200000, CRC(51f775ce) SHA1(125b40bf47304d37b92e81df5081c81d9af6c8a2) )
ROM_LOAD64_WORD( "mpr-16787.ic30", 0x000002, 0x200000, CRC(dee7a204) SHA1(29acff4d5dd68609ac46853860788206d18262ab) )
ROM_LOAD64_WORD( "mpr-16789.ic28", 0x000004, 0x200000, CRC(6b6c8ad3) SHA1(97b0078c851845c31dcf0fe4b2a88393dcdf8988) )
ROM_LOAD64_WORD( "mpr-16791.ic26", 0x000006, 0x200000, CRC(4f7236da) SHA1(d1c29f6aa82d60a626217f1430bc8a76ef012007) )
ROM_LOAD64_WORD( "mpr-16786.ic31", 0x800000, 0x200000, CRC(d08a2d32) SHA1(baac63cbacbe38e057684174040384a7152eb523) )
ROM_LOAD64_WORD( "mpr-16788.ic29", 0x800002, 0x200000, CRC(cd9d3605) SHA1(7c4402be1a1ddde6766cfdd5fe7e2a088c4a59e8) )
ROM_LOAD64_WORD( "mpr-16790.ic27", 0x800004, 0x200000, CRC(2ea75746) SHA1(c91e5d678917886cc23fbef7a577c5a70665c7b2) )
ROM_LOAD64_WORD( "mpr-16792.ic25", 0x800006, 0x200000, CRC(9f416072) SHA1(18107cf64f918888aa5a54432f8e9137910101b8) )
ROM_END
ROM_START( jleagueo )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code + data */
ROM_LOAD_x4( "epr-16782.ic17", 0x000000, 0x020000, CRC(f0278944) SHA1(49e3842231ee5abdd6205b598309153d6b4ddc02) )
ROM_LOAD_x4( "epr-16781.ic8", 0x080000, 0x020000, CRC(7df9529b) SHA1(de3633f4941ff3877c4cb8b53e080eccea19f22e) )
ROM_LOAD16_BYTE( "epr-16776.ic18", 0x100000, 0x080000, CRC(e8694626) SHA1(d4318a9a6b1cc5c719bff9c25b7398dd2ea1e18b) )
ROM_LOAD16_BYTE( "epr-16775.ic9", 0x100001, 0x080000, CRC(e81e2c3d) SHA1(2900710f1dec6cf71875c82a56584ba45ed3a545) )
ROM_REGION( 0x400000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-16780.ic36", 0x000000, 0x040000, CRC(47aa4ec7) SHA1(baea18aaac0314f769f1e36fdbe8aedf62862544) )
ROM_LOAD( "mpr-16779.ic35", 0x100000, 0x100000, CRC(7055e859) SHA1(cde27fa4aaf0ee54063ee68794e9a6075581fff5) )
ROM_LOAD( "mpr-16778.ic34", 0x200000, 0x100000, CRC(feedaecf) SHA1(25c14ccb85c467dc0c8e85b61f8f86f4396c0cc7) )
ROM_LOAD( "mpr-16777.ic24", 0x300000, 0x100000, CRC(14b5d5df) SHA1(1b0b0a31294b1bbc16d2046b374d584a1b00a78c) )
ROM_REGION( 0x200000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-16784.ic14", 0x000000, 0x100000, CRC(4608efe2) SHA1(9b41aa28f50af770e854ef9fdff1a55da7b7b131) )
ROM_LOAD16_BYTE( "mpr-16783.ic5", 0x000001, 0x100000, CRC(042eabe7) SHA1(a11df5c21d85f0c96dbdcaf57be37a79658ad648) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-16785.ic32", 0x000000, 0x200000, CRC(51f775ce) SHA1(125b40bf47304d37b92e81df5081c81d9af6c8a2) )
ROM_LOAD64_WORD( "mpr-16787.ic30", 0x000002, 0x200000, CRC(dee7a204) SHA1(29acff4d5dd68609ac46853860788206d18262ab) )
ROM_LOAD64_WORD( "mpr-16789.ic28", 0x000004, 0x200000, CRC(6b6c8ad3) SHA1(97b0078c851845c31dcf0fe4b2a88393dcdf8988) )
ROM_LOAD64_WORD( "mpr-16791.ic26", 0x000006, 0x200000, CRC(4f7236da) SHA1(d1c29f6aa82d60a626217f1430bc8a76ef012007) )
ROM_LOAD64_WORD( "mpr-16786.ic31", 0x800000, 0x200000, CRC(d08a2d32) SHA1(baac63cbacbe38e057684174040384a7152eb523) )
ROM_LOAD64_WORD( "mpr-16788.ic29", 0x800002, 0x200000, CRC(cd9d3605) SHA1(7c4402be1a1ddde6766cfdd5fe7e2a088c4a59e8) )
ROM_LOAD64_WORD( "mpr-16790.ic27", 0x800004, 0x200000, CRC(2ea75746) SHA1(c91e5d678917886cc23fbef7a577c5a70665c7b2) )
ROM_LOAD64_WORD( "mpr-16792.ic25", 0x800006, 0x200000, CRC(9f416072) SHA1(18107cf64f918888aa5a54432f8e9137910101b8) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
Title Fight (Export) - Multi-32
not protected
Sega Game ID codes:
Game: 834-9324-02 TITLE FIGHT
ROM board: 834-9413-02
Main BD: 837-8676 (SYSTEM MULTI 32)
*/
ROM_START( titlef )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code */
ROM_LOAD32_WORD_x2( "epr-15388.ic37", 0x000000, 0x40000, CRC(db1eefbd) SHA1(7059a1d5c9364d836c1d922071a108cbde661e0a) )
ROM_LOAD32_WORD_x2( "epr-15389.ic40", 0x000002, 0x40000, CRC(da9f60a3) SHA1(87a7bea04e51e3c241871e83ff7322c6a07bd106) )
ROM_REGION( 0x80000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-15384.ic31", 0x00000, 0x20000, CRC(0f7d208d) SHA1(5425120480f813210fae28951e8bfd5acb08ca53) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15381.ic3", 0x000000, 0x200000, CRC(162cc4d6) SHA1(2369d3d76ab5ef8f033aa45530ab957f0e5ff028) )
ROM_LOAD16_BYTE( "mpr-15382.ic11", 0x000001, 0x200000, CRC(fd03a130) SHA1(040c36383ef5d8298af714958cd5b0a4c7556ae7) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15379.ic14", 0x000000, 0x200000, CRC(e5c74b11) SHA1(67e4460efe5dcd88ffc12024b255efc843e6a8b5) )
ROM_LOAD64_WORD( "mpr-15375.ic15", 0x000002, 0x200000, CRC(046a9b50) SHA1(2b4c53f2a0264835cb7197daa9b3461c212541e8) )
ROM_LOAD64_WORD( "mpr-15371.ic10", 0x000004, 0x200000, CRC(999046c6) SHA1(37ce4e8aaf537b5366eacabaf36e4477b5624121) )
ROM_LOAD64_WORD( "mpr-15373.ic38", 0x000006, 0x200000, CRC(9b3294d9) SHA1(19542f14ce09753385a44098dfd1aaf331e7af0e) )
ROM_LOAD64_WORD( "mpr-15380.ic22", 0x800000, 0x200000, CRC(6ea0e58d) SHA1(1c4b761522157b0b9d086181ba6f6994879d8fdf) )
ROM_LOAD64_WORD( "mpr-15376.ic23", 0x800002, 0x200000, CRC(de3e05c5) SHA1(cac0d04ecd37e5836d246c0809bcfc11430df591) )
ROM_LOAD64_WORD( "mpr-15372.ic18", 0x800004, 0x200000, CRC(c187c36a) SHA1(bb55c2a768a43ef19a7847a4aa113523fee26c20) )
ROM_LOAD64_WORD( "mpr-15374.ic41", 0x800006, 0x200000, CRC(e026aab0) SHA1(75dfaef6d50c3d1d7f27aa5e44fcbc0ff2173c6f) )
ROM_REGION( 0x400000, "mainpcb:sega", 0 ) /* Sega PCM sound data */
ROM_LOAD( "mpr-15385.ic1", 0x000000, 0x200000, CRC(5a9b0aa0) SHA1(d208aa165f9eea05e3b8c3f406ff44374e4f6887) )
ROM_END
/**************************************************************************************************************************
Title Fight (US) - Multi-32
not protected
Sega Game ID codes:
Game: 834-9324-01 TITLE FIGHT
ROM board: 834-9413-01
Main BD: 837-8676 (SYSTEM MULTI 32)
*/
ROM_START( titlefu )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code */
ROM_LOAD32_WORD_x4( "epr-15386.ic37", 0x000000, 0x40000, CRC(e36e2516) SHA1(b6a73d6136ff8a13831b6db0fbc8a585f2acf254) )
ROM_LOAD32_WORD_x4( "epr-15387.ic40", 0x000002, 0x40000, CRC(e63406d3) SHA1(cd105862b2267d1d3af588cda70e6e4c1cca1da2) )
ROM_REGION( 0x80000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-15384.ic31", 0x00000, 0x20000, CRC(0f7d208d) SHA1(5425120480f813210fae28951e8bfd5acb08ca53) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15381.ic3", 0x000000, 0x200000, CRC(162cc4d6) SHA1(2369d3d76ab5ef8f033aa45530ab957f0e5ff028) )
ROM_LOAD16_BYTE( "mpr-15382.ic11", 0x000001, 0x200000, CRC(fd03a130) SHA1(040c36383ef5d8298af714958cd5b0a4c7556ae7) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15379.ic14", 0x000000, 0x200000, CRC(e5c74b11) SHA1(67e4460efe5dcd88ffc12024b255efc843e6a8b5) )
ROM_LOAD64_WORD( "mpr-15375.ic15", 0x000002, 0x200000, CRC(046a9b50) SHA1(2b4c53f2a0264835cb7197daa9b3461c212541e8) )
ROM_LOAD64_WORD( "mpr-15371.ic10", 0x000004, 0x200000, CRC(999046c6) SHA1(37ce4e8aaf537b5366eacabaf36e4477b5624121) )
ROM_LOAD64_WORD( "mpr-15373.ic38", 0x000006, 0x200000, CRC(9b3294d9) SHA1(19542f14ce09753385a44098dfd1aaf331e7af0e) )
ROM_LOAD64_WORD( "mpr-15380.ic22", 0x800000, 0x200000, CRC(6ea0e58d) SHA1(1c4b761522157b0b9d086181ba6f6994879d8fdf) )
ROM_LOAD64_WORD( "mpr-15376.ic23", 0x800002, 0x200000, CRC(de3e05c5) SHA1(cac0d04ecd37e5836d246c0809bcfc11430df591) )
ROM_LOAD64_WORD( "mpr-15372.ic18", 0x800004, 0x200000, CRC(c187c36a) SHA1(bb55c2a768a43ef19a7847a4aa113523fee26c20) )
ROM_LOAD64_WORD( "mpr-15374.ic41", 0x800006, 0x200000, CRC(e026aab0) SHA1(75dfaef6d50c3d1d7f27aa5e44fcbc0ff2173c6f) )
ROM_REGION( 0x400000, "mainpcb:sega", 0 ) /* Sega PCM sound data */
ROM_LOAD( "mpr-15385.ic1", 0x000000, 0x200000, CRC(5a9b0aa0) SHA1(d208aa165f9eea05e3b8c3f406ff44374e4f6887) )
ROM_END
/**************************************************************************************************************************
Title Fight (Japan) - Multi-32
not protected
Sega Game ID codes:
Game: 834-9324-03 TITLE FIGHT
ROM board: 834-9413-03
Main BD: 837-8676 (SYSTEM MULTI 32)
*/
ROM_START( titlefj )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code */
ROM_LOAD32_WORD_x4( "epr-15377.ic37", 0x000000, 0x40000, CRC(1868403c) SHA1(d34a3a05e5a3bb2e6159f95d1e22d264bf553cda) )
ROM_LOAD32_WORD_x4( "epr-15378.ic40", 0x000002, 0x40000, CRC(44487b0a) SHA1(4aefd063bf148334d5f43d69f497766d50ffca30) )
ROM_REGION( 0x80000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr-15384.ic31", 0x00000, 0x20000, CRC(0f7d208d) SHA1(5425120480f813210fae28951e8bfd5acb08ca53) )
ROM_REGION( 0x400000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "mpr-15381.ic3", 0x000000, 0x200000, CRC(162cc4d6) SHA1(2369d3d76ab5ef8f033aa45530ab957f0e5ff028) )
ROM_LOAD16_BYTE( "mpr-15382.ic11", 0x000001, 0x200000, CRC(fd03a130) SHA1(040c36383ef5d8298af714958cd5b0a4c7556ae7) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", 0 ) /* sprites */
ROM_LOAD64_WORD( "mpr-15379.ic14", 0x000000, 0x200000, CRC(e5c74b11) SHA1(67e4460efe5dcd88ffc12024b255efc843e6a8b5) )
ROM_LOAD64_WORD( "mpr-15375.ic15", 0x000002, 0x200000, CRC(046a9b50) SHA1(2b4c53f2a0264835cb7197daa9b3461c212541e8) )
ROM_LOAD64_WORD( "mpr-15371.ic10", 0x000004, 0x200000, CRC(999046c6) SHA1(37ce4e8aaf537b5366eacabaf36e4477b5624121) )
ROM_LOAD64_WORD( "mpr-15373.ic38", 0x000006, 0x200000, CRC(9b3294d9) SHA1(19542f14ce09753385a44098dfd1aaf331e7af0e) )
ROM_LOAD64_WORD( "mpr-15380.ic22", 0x800000, 0x200000, CRC(6ea0e58d) SHA1(1c4b761522157b0b9d086181ba6f6994879d8fdf) )
ROM_LOAD64_WORD( "mpr-15376.ic23", 0x800002, 0x200000, CRC(de3e05c5) SHA1(cac0d04ecd37e5836d246c0809bcfc11430df591) )
ROM_LOAD64_WORD( "mpr-15372.ic18", 0x800004, 0x200000, CRC(c187c36a) SHA1(bb55c2a768a43ef19a7847a4aa113523fee26c20) )
ROM_LOAD64_WORD( "mpr-15374.ic41", 0x800006, 0x200000, CRC(e026aab0) SHA1(75dfaef6d50c3d1d7f27aa5e44fcbc0ff2173c6f) )
ROM_REGION( 0x400000, "mainpcb:sega", 0 ) /* Sega PCM sound data */
ROM_LOAD( "mpr-15385.ic1", 0x000000, 0x200000, CRC(5a9b0aa0) SHA1(d208aa165f9eea05e3b8c3f406ff44374e4f6887) )
ROM_END
/**************************************************************************************************************************
**************************************************************************************************************************
**************************************************************************************************************************
AS-1 - Multi-32
not protected?
*/
ROM_START( as1 )
ROM_REGION( 0x200000, "mainpcb:maincpu", 0 ) /* v60 code */
ROM_LOAD32_WORD_x4( "epr15420.ic37", 0x000000, 0x20000, CRC(1f9747b0) SHA1(51d1fbccf6960967d4458ba26fad42ac51978c67) )
ROM_LOAD32_WORD_x4( "epr15421.ic40", 0x000002, 0x20000, CRC(aa96422a) SHA1(21cf327d102f5c7c4a4e41d889d9b4d10c44de35) )
ROM_REGION( 0x80000, "mainpcb:soundcpu", 0 ) /* sound CPU */
ROM_LOAD_x4( "epr15367.ic31", 0x00000, 0x20000, CRC(0220f078) SHA1(9fab79fc91764ecf678bfa4d38d1b4054e258b76) )
ROM_REGION( 0x100000, "mainpcb:gfx1", 0 ) /* tiles */
ROM_LOAD16_BYTE( "epr15422.ic3", 0x000000, 0x080000, CRC(6c61ba6d) SHA1(b41237ced4a2e8741ae0339c333bea4221903690) )
ROM_LOAD16_BYTE( "epr15423.ic11", 0x000001, 0x080000, CRC(5178912a) SHA1(b637451c28877ddc93c9920bea356888b4c8eea3) )
ROM_REGION32_BE( 0x1000000, "mainpcb:sprites", ROMREGION_ERASEFF ) /* sprites */
// empty
ROM_REGION( 0x400000, "mainpcb:sega", ROMREGION_ERASEFF ) /* Sega PCM sound data */
// empty
ROM_END
/*************************************
*
* Common driver inits
*
*************************************/
void segas32_state::segas32_common_init()
{
if ((m_multipcm_bank_lo.found()) && (m_multipcm_bank_hi.found()))
{
uint8_t *ROM = memregion("sega")->base();
uint32_t size = memregion("sega")->bytes();
m_multipcm_bank_lo->configure_entries(0, size / 0x80000, &ROM[0], 0x80000);
m_multipcm_bank_hi->configure_entries(0, size / 0x80000, &ROM[0], 0x80000);
}
uint8_t *Z80 = memregion("soundcpu")->base();
uint32_t size = memregion("soundcpu")->bytes();
m_soundrom_bank->configure_entries(0, size / 0x2000, &Z80[0], 0x2000);
/* reset the custom handlers and other pointers */
m_system32_prot_vblank = nullptr;
m_sw1_output = nullptr;
m_sw2_output = nullptr;
m_sw3_output = nullptr;
}
/*************************************
*
* Output callbacks
*
* TODO: kokoroj2 and jpark (SW2)
*
* Additional notes:
* - about jpark: the compression switch is broken/inoperative
* and because of that all piston data, which is in this
* section is frozen. bits x01, x04 and x10 when which == 0
* (IO chip 0), seem to have something to do with the sensor
* switches we need to fix
*************************************/
void segas32_state::radm_sw1_output( int which, uint16_t data )
{
if (which == 0)
machine().output().set_value("Start_lamp", BIT(data, 2));
}
void segas32_state::radm_sw2_output( int which, uint16_t data )
{
if (which == 0)
{
machine().output().set_value("Lights_lamp", BIT(data, 0));
machine().output().set_value("Wiper_lamp", BIT(data, 1));
}
}
void segas32_state::radr_sw2_output( int which, uint16_t data )
{
if (which == 0)
{
machine().output().set_value("Entry_lamp", BIT(data, 0));
machine().output().set_value("Winner_lamp", BIT(data, 1));
}
}
void segas32_state::alien3_sw1_output( int which, uint16_t data )
{
if (which == 0)
{
machine().output().set_value("Player1_Gun_Recoil", BIT(data, 2));
machine().output().set_value("Player2_Gun_Recoil", BIT(data, 3));
}
}
void segas32_state::arescue_sw1_output( int which, uint16_t data )
{
if (which == 0)
{
machine().output().set_value("Start_lamp", BIT(data, 2));
machine().output().set_value("Back_lamp", BIT(data, 4));
}
}
void segas32_state::f1lap_sw1_output( int which, uint16_t data )
{
if (which == 0)
{
machine().output().set_value("lamp0", BIT(data, 2));
machine().output().set_value("lamp1", BIT(data, 3));
}
}
void segas32_state::jpark_sw1_output( int which, uint16_t data )
{
if (which == 0)
{
machine().output().set_value("Left_lamp", BIT(data, 2));
machine().output().set_value("Right_lamp", BIT(data, 3));
}
}
void segas32_state::orunners_sw1_output( int which, uint16_t data )
{
/* note ma = monitor A and mb = Monitor B */
if (which == 0)
{
machine().output().set_value("MA_Check_Point_lamp", BIT(data, 1));
machine().output().set_value("MA_Race_Leader_lamp", BIT(data, 3));
machine().output().set_value("MA_Steering_Wheel_motor", BIT(data, 4));
}
else
{
machine().output().set_value("MB_Check_Point_lamp", BIT(data, 1));
machine().output().set_value("MB_Race_Leader_lamp", BIT(data, 3));
machine().output().set_value("MB_Steering_Wheel_motor", BIT(data, 4));
}
}
void segas32_state::orunners_sw2_output( int which, uint16_t data )
{
/* note ma = monitor A and mb = Monitor B */
/* also note that the remaining bits are for the game's lcd display */
/* the bijokkoy driver might be used as an example for handling these outputs */
if (which == 0)
{
machine().output().set_value("MA_DJ_Music_lamp", BIT(data, 0));
machine().output().set_value("MA_<<_>>_lamp", BIT(data, 1));
}
else
{
machine().output().set_value("MB_DJ_Music_lamp", BIT(data, 0));
machine().output().set_value("MB_<<_>>_lamp", BIT(data, 1));
}
}
void segas32_state::harddunk_sw1_output( int which, uint16_t data )
{
if (which == 0)
{
machine().output().set_value("1P_Start_lamp", BIT(data, 2));
machine().output().set_value("2P_Start_lamp", BIT(data, 3));
}
else
{
machine().output().set_value("4P_Start_lamp", BIT(data, 2));
machine().output().set_value("5P_Start_lamp", BIT(data, 3));
}
}
void segas32_state::harddunk_sw2_output( int which, uint16_t data )
{
if (which == 0)
machine().output().set_value("Left_Winner_lamp", BIT(data, 0));
else
machine().output().set_value("Right_Winner_lamp", BIT(data, 0));
}
void segas32_state::harddunk_sw3_output( int which, uint16_t data )
{
machine().output().set_value("3P_Start_lamp", BIT(data, 4));
machine().output().set_value("6P_Start_lamp", BIT(data, 5));
}
void segas32_state::titlef_sw1_output( int which, uint16_t data )
{
if (which == 0)
{
machine().output().set_value("Blue_Button_1P_lamp", BIT(data, 2));
machine().output().set_value("Blue_Button_2P_lamp", BIT(data, 3));
}
else
{
machine().output().set_value("Red_Button_1P_lamp", BIT(data, 2));
machine().output().set_value("Red_Button_2P_lamp", BIT(data, 3));
}
}
void segas32_state::titlef_sw2_output( int which, uint16_t data )
{
if (which == 0)
machine().output().set_value("Blue_Corner_lamp", BIT(data, 0));
else
machine().output().set_value("Red_Corner_lamp", BIT(data, 0));
}
void segas32_state::scross_sw1_output( int which, uint16_t data )
{
/* note ma = monitor A and mb = Monitor B */
if (which == 0)
machine().output().set_value("MA_Start_lamp", BIT(data, 2));
else
machine().output().set_value("MB_Start_lamp", BIT(data, 2));
}
void segas32_state::scross_sw2_output( int which, uint16_t data )
{
/* Note: I'm not an expert on digits, so I didn't know the right map to use, I just added it manually and it seems to work fine. */
if (which == 0)
machine().output().set_value("MA_Digit", data);
else
machine().output().set_value("MB_Digit", data);
}
/*************************************
*
* Game-specific driver inits
*
*************************************/
void segas32_new_state::dual_pcb_comms_w(offs_t offset, uint16_t data, uint16_t mem_mask)
{
COMBINE_DATA(&m_dual_pcb_comms[offset]);
}
uint16_t segas32_new_state::dual_pcb_comms_r(offs_t offset)
{
return m_dual_pcb_comms[offset];
}
/* There must be something on the comms board for this?
Probably not a dip/solder link/trace cut, but maybe
just whichever way the cables are plugged in?
Both f1en and arescue master units try to set bit 1... */
uint16_t segas32_new_state::dual_pcb_masterslave()
{
return 0; // 0/1 master/slave
}
uint16_t segas32_new_state::dual_pcb_slave()
{
return 1; // 0/1 master/slave
}
void segas32_new_state::init_titlef() { m_mainpcb->init_titlef(); }
void segas32_new_state::init_slipstrm() { m_mainpcb->init_slipstrm(); }
void segas32_new_state::init_radm() { m_mainpcb->init_radm(); }
void segas32_new_state::init_holo() { m_mainpcb->init_holo(); }
void segas32_new_state::init_svf() { m_mainpcb->init_svf(); }
void segas32_new_state::init_jleague() { m_mainpcb->init_jleague(); }
void segas32_new_state::init_jpark() { m_mainpcb->init_jpark(); }
void segas32_new_state::init_ga2() { m_mainpcb->init_ga2(); }
void segas32_new_state::init_scross() { m_mainpcb->init_scross(); }
void segas32_new_state::init_spidman() { m_mainpcb->init_spidman(); }
void segas32_new_state::init_sonicp() { m_mainpcb->init_sonicp(); }
void segas32_new_state::init_dbzvrvs() { m_mainpcb->init_dbzvrvs(); }
void segas32_new_state::init_brival() { m_mainpcb->init_brival(); }
void segas32_new_state::init_harddunk() { m_mainpcb->init_harddunk(); }
void segas32_new_state::init_arabfgt() { m_mainpcb->init_arabfgt(); }
void segas32_new_state::init_sonic() { m_mainpcb->init_sonic(); }
void segas32_new_state::init_alien3() { m_mainpcb->init_alien3(); }
void segas32_new_state::init_darkedge() { m_mainpcb->init_darkedge(); }
void segas32_new_state::init_radr() { m_mainpcb->init_radr(); }
void segas32_new_state::init_orunners() { m_mainpcb->init_orunners(); }
void segas32_new_state::init_arescue()
{
m_mainpcb->init_arescue(1);
m_slavepcb->init_arescue(0);
m_dual_pcb_comms = std::make_unique<uint16_t[]>(0x1000/2);
m_mainpcb->maincpu()->space(AS_PROGRAM).install_read_handler(0x810000, 0x810fff, read16sm_delegate(*this, FUNC(segas32_new_state::dual_pcb_comms_r)));
m_mainpcb->maincpu()->space(AS_PROGRAM).install_write_handler(0x810000, 0x810fff, write16s_delegate(*this, FUNC(segas32_new_state::dual_pcb_comms_w)));
m_mainpcb->maincpu()->space(AS_PROGRAM).install_read_handler(0x818000, 0x818003, read16smo_delegate(*this, FUNC(segas32_new_state::dual_pcb_masterslave)));
m_slavepcb->maincpu()->space(AS_PROGRAM).install_read_handler(0x810000, 0x810fff, read16sm_delegate(*this, FUNC(segas32_new_state::dual_pcb_comms_r)));
m_slavepcb->maincpu()->space(AS_PROGRAM).install_write_handler(0x810000, 0x810fff, write16s_delegate(*this, FUNC(segas32_new_state::dual_pcb_comms_w)));
m_slavepcb->maincpu()->space(AS_PROGRAM).install_read_handler(0x818000, 0x818003, read16smo_delegate(*this, FUNC(segas32_new_state::dual_pcb_slave)));
}
void segas32_new_state::init_f1en() {
m_mainpcb->init_f1en();
m_slavepcb->init_f1en();
m_dual_pcb_comms = std::make_unique<uint16_t[]>(0x1000/2);
memset(m_dual_pcb_comms.get(), 0xff, 0x1000 / 2);
m_mainpcb->maincpu()->space(AS_PROGRAM).install_read_handler(0x810000, 0x810fff, read16sm_delegate(*this, FUNC(segas32_new_state::dual_pcb_comms_r)));
m_mainpcb->maincpu()->space(AS_PROGRAM).install_write_handler(0x810000, 0x810fff, write16s_delegate(*this, FUNC(segas32_new_state::dual_pcb_comms_w)));
m_mainpcb->maincpu()->space(AS_PROGRAM).install_read_handler(0x818000, 0x818003, read16smo_delegate(*this, FUNC(segas32_new_state::dual_pcb_masterslave)));
m_slavepcb->maincpu()->space(AS_PROGRAM).install_read_handler(0x810000, 0x810fff, read16sm_delegate(*this, FUNC(segas32_new_state::dual_pcb_comms_r)));
m_slavepcb->maincpu()->space(AS_PROGRAM).install_write_handler(0x810000, 0x810fff, write16s_delegate(*this, FUNC(segas32_new_state::dual_pcb_comms_w)));
m_slavepcb->maincpu()->space(AS_PROGRAM).install_read_handler(0x818000, 0x818003, read16smo_delegate(*this, FUNC(segas32_new_state::dual_pcb_slave)));
}
void segas32_new_state::init_f1lap()
{
m_mainpcb->init_f1lap();
}
void segas32_new_state::init_f1lapt()
{
m_mainpcb->init_f1lapt();
}
void segas32_state::init_alien3()
{
segas32_common_init();
m_sw1_output = &segas32_state::alien3_sw1_output;
}
void segas32_state::init_arescue(int m_hasdsp)
{
segas32_common_init();
if (m_hasdsp) m_maincpu->space(AS_PROGRAM).install_read_handler(0xa00000, 0xa00007, read16sm_delegate(*this, FUNC(segas32_state::arescue_dsp_r)));
if (m_hasdsp) m_maincpu->space(AS_PROGRAM).install_write_handler(0xa00000, 0xa00007, write16s_delegate(*this, FUNC(segas32_state::arescue_dsp_w)));
for (auto & elem : m_arescue_dsp_io)
elem = 0x00;
m_sw1_output = &segas32_state::arescue_sw1_output;
save_item(NAME(m_arescue_dsp_io));
}
void segas32_state::init_arabfgt()
{
segas32_common_init();
}
void segas32_state::init_brival()
{
segas32_common_init();
/* install protection handlers */
m_system32_protram = std::make_unique<uint16_t[]>(0x1000/2);
m_maincpu->space(AS_PROGRAM).install_read_handler(0x20ba00, 0x20ba07, read16s_delegate(*this, FUNC(segas32_state::brival_protection_r)));
m_maincpu->space(AS_PROGRAM).install_write_handler(0xa00000, 0xa00fff, write16sm_delegate(*this, FUNC(segas32_state::brival_protection_w)));
save_pointer(NAME(m_system32_protram), 0x1000/2);
}
void segas32_state::init_darkedge()
{
segas32_common_init();
/* install protection handlers */
m_maincpu->space(AS_PROGRAM).install_readwrite_handler(0xa00000, 0xa7ffff, read16s_delegate(*this, FUNC(segas32_state::darkedge_protection_r)), write16s_delegate(*this, FUNC(segas32_state::darkedge_protection_w)));
m_system32_prot_vblank = &segas32_state::darkedge_fd1149_vblank;
}
void segas32_state::init_dbzvrvs()
{
segas32_common_init();
/* install protection handlers */
m_maincpu->space(AS_PROGRAM).install_read_handler(0xa00000, 0xa7ffff, read16smo_delegate(*this, FUNC(segas32_state::dbzvrvs_protection_r)));
m_maincpu->space(AS_PROGRAM).install_write_handler(0xa00000, 0xa7ffff, write16mo_delegate(*this, FUNC(segas32_state::dbzvrvs_protection_w)));
// 0x810000 to 0x8107ff = link RAM? probably not a dual cabinet, though...
}
void segas32_state::init_f1en()
{
segas32_common_init();
m_sw1_output = &segas32_state::radm_sw1_output;
}
void segas32_state::init_f1lap()
{
segas32_common_init();
m_system32_prot_vblank = &segas32_state::f1lap_fd1149_vblank;
m_sw1_output = &segas32_state::f1lap_sw1_output;
m_s32comm->set_linktype(15612); // EPR-15612
}
void segas32_state::init_f1lapt()
{
segas32_common_init();
m_sw1_output = &segas32_state::f1lap_sw1_output;
m_s32comm->set_linktype(15612); // EPR-15612
}
void segas32_state::init_ga2()
{
segas32_common_init();
}
void segas32_state::init_harddunk()
{
segas32_common_init();
m_sw1_output = &segas32_state::harddunk_sw1_output;
m_sw2_output = &segas32_state::harddunk_sw2_output;
m_sw3_output = &segas32_state::harddunk_sw3_output;
}
void segas32_state::init_holo()
{
segas32_common_init();
}
void segas32_state::init_jpark()
{
/* Temp. Patch until we emulate the 'Drive Board', thanks to Malice */
uint16_t *pROM = (uint16_t *)m_maincpu_region->base();
segas32_common_init();
pROM[0xC15A8/2] = 0xCD70;
pROM[0xC15AA/2] = 0xD8CD;
m_sw1_output = &segas32_state::jpark_sw1_output;
}
void segas32_state::init_orunners()
{
segas32_common_init();
m_sw1_output = &segas32_state::orunners_sw1_output;
m_sw2_output = &segas32_state::orunners_sw2_output;
m_s32comm->set_linktype(15033); // EPR-15033
}
void segas32_state::init_radm()
{
segas32_common_init();
m_sw1_output = &segas32_state::radm_sw1_output;
m_sw2_output = &segas32_state::radm_sw2_output;
}
void segas32_state::init_radr()
{
segas32_common_init();
m_sw1_output = &segas32_state::radm_sw1_output;
m_sw2_output = &segas32_state::radr_sw2_output;
m_s32comm->set_linktype(14084); // EPR-14084
}
void segas32_state::init_scross()
{
segas32_common_init();
m_soundcpu->space(AS_PROGRAM).install_write_handler(0xb0, 0xbf, write8smo_delegate(*this, FUNC(segas32_state::scross_bank_w)));
m_sw1_output = &segas32_state::scross_sw1_output;
m_sw2_output = &segas32_state::scross_sw2_output;
m_s32comm->set_linktype(15033); // EPR-15033
}
void segas32_state::init_slipstrm()
{
segas32_common_init();
}
void segas32_state::init_sonic()
{
segas32_common_init();
/* install protection handlers */
m_maincpu->space(AS_PROGRAM).install_write_handler(0x20E5C4, 0x20E5C5, write16s_delegate(*this, FUNC(segas32_state::sonic_level_load_protection)));
}
void segas32_state::init_sonicp()
{
segas32_common_init();
}
void segas32_state::init_spidman()
{
segas32_common_init();
}
void segas32_state::init_svf()
{
segas32_common_init();
}
void segas32_state::init_jleague()
{
segas32_common_init();
m_maincpu->space(AS_PROGRAM).install_write_handler(0x20F700, 0x20F705, write16_delegate(*this, FUNC(segas32_state::jleague_protection_w)));
}
void segas32_state::init_titlef()
{
segas32_common_init();
m_sw1_output = &segas32_state::titlef_sw1_output;
m_sw2_output = &segas32_state::titlef_sw2_output;
}
/*************************************
*
* Game driver(s)
*
*************************************/
GAME( 1992, arescue, 0, sega_system32_dual_direct_upd7725, arescue, segas32_new_state, init_arescue, ROT0, "Sega", "Air Rescue (World)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, arescueu, arescue, sega_system32_dual_direct_upd7725, arescue, segas32_new_state, init_arescue, ROT0, "Sega", "Air Rescue (US)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, arescuej, arescue, sega_system32_dual_direct_upd7725, arescue, segas32_new_state, init_arescue, ROT0, "Sega", "Air Rescue (Japan)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1993, alien3, 0, sega_system32_analog, alien3, segas32_new_state, init_alien3, ROT0, "Sega", "Alien3: The Gun (World)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1993, alien3u, alien3, sega_system32_analog, alien3, segas32_new_state, init_alien3, ROT0, "Sega", "Alien3: The Gun (US, Rev A)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1993, alien3j, alien3, sega_system32_analog, alien3, segas32_new_state, init_alien3, ROT0, "Sega", "Alien3: The Gun (Japan)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1991, arabfgt, 0, sega_system32_arf, arabfgt, segas32_new_state, init_arabfgt, ROT0, "Sega", "Arabian Fight (World)", MACHINE_IMPERFECT_GRAPHICS ) /* Released in 03.1992 */
GAME( 1991, arabfgtu, arabfgt, sega_system32_arf, arabfgtu, segas32_new_state, init_arabfgt, ROT0, "Sega", "Arabian Fight (US)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1991, arabfgtj, arabfgt, sega_system32_arf, arabfgt, segas32_new_state, init_arabfgt, ROT0, "Sega", "Arabian Fight (Japan)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, brival, 0, sega_system32_4p, brival, segas32_new_state, init_brival, ROT0, "Sega", "Burning Rival (World)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, brivalj, brival, sega_system32_4p, brival, segas32_new_state, init_brival, ROT0, "Sega", "Burning Rival (Japan)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, darkedge, 0, sega_system32_4p, darkedge, segas32_new_state, init_darkedge, ROT0, "Sega", "Dark Edge (World)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, darkedgej, darkedge, sega_system32_4p, darkedge, segas32_new_state, init_darkedge, ROT0, "Sega", "Dark Edge (Japan)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1994, dbzvrvs, 0, sega_system32_analog, dbzvrvs, segas32_new_state, init_dbzvrvs, ROT0, "Sega / Banpresto", "Dragon Ball Z V.R.V.S. (Japan, Rev A)", MACHINE_IMPERFECT_GRAPHICS)
GAME( 1991, f1en, 0, sega_system32_dual_direct, f1en, segas32_new_state, init_f1en, ROT0, "Sega", "F1 Exhaust Note (World, Rev A)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1991, f1enu, f1en, sega_system32_dual_direct, f1en, segas32_new_state, init_f1en, ROT0, "Sega", "F1 Exhaust Note (US, Rev A)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1991, f1enj, f1en, sega_system32_dual_direct, f1en, segas32_new_state, init_f1en, ROT0, "Sega", "F1 Exhaust Note (Japan, Rev A)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1993, f1lap, 0, sega_system32_analog, f1lap, segas32_new_state, init_f1lap, ROT0, "Sega", "F1 Super Lap (World)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1993, f1lapt, f1lap, sega_system32_analog, f1lap, segas32_new_state, init_f1lapt, ROT0, "Sega", "F1 Super Lap (World, Unprotected)", MACHINE_IMPERFECT_GRAPHICS ) /* Factory unprotected */
GAME( 1993, f1lapj, f1lap, sega_system32_analog, f1lap, segas32_new_state, init_f1lap, ROT0, "Sega", "F1 Super Lap (Japan)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, ga2, 0, sega_system32_ga2, ga2, segas32_new_state, init_ga2, ROT0, "Sega", "Golden Axe: The Revenge of Death Adder (World, Rev B)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, ga2u, ga2, sega_system32_ga2, ga2u, segas32_new_state, init_ga2, ROT0, "Sega", "Golden Axe: The Revenge of Death Adder (US, Rev A)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, ga2j, ga2, sega_system32_ga2, ga2, segas32_new_state, init_ga2, ROT0, "Sega", "Golden Axe: The Revenge of Death Adder (Japan)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, holo, 0, sega_system32, holo, segas32_new_state, init_holo, ORIENTATION_FLIP_Y, "Sega", "Holosseum (US, Rev A)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1993, jpark, 0, sega_system32_analog, jpark, segas32_new_state, init_jpark, ROT0, "Sega", "Jurassic Park (World, Rev A)", MACHINE_IMPERFECT_GRAPHICS ) /* Released in 02.1994 */
GAME( 1993, jparkj, jpark, sega_system32_analog, jpark, segas32_new_state, init_jpark, ROT0, "Sega", "Jurassic Park (Japan, Rev A, Deluxe)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1993, jparkja, jpark, sega_system32_analog, jpark, segas32_new_state, init_jpark, ROT0, "Sega", "Jurassic Park (Japan, Deluxe)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1993, jparkjc, jpark, sega_system32_analog, jpark, segas32_new_state, init_jpark, ROT0, "Sega", "Jurassic Park (Japan, Rev A, Conversion)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, kokoroj, 0, sega_system32_cd, kokoroj2, segas32_new_state, init_radr, ROT0, "Sega", "Soreike Kokology (Rev A)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_IMPERFECT_SOUND | MACHINE_NODEVICE_PRINTER) /* uses an Audio CD */
GAME( 1993, kokoroj2, 0, sega_system32_cd, kokoroj2, segas32_new_state, init_radr, ROT0, "Sega", "Soreike Kokology Vol. 2 - Kokoro no Tanteikyoku", MACHINE_IMPERFECT_GRAPHICS | MACHINE_IMPERFECT_SOUND | MACHINE_NODEVICE_PRINTER) /* uses an Audio CD */
GAME( 1990, radm, 0, sega_system32_analog, radm, segas32_new_state, init_radm, ROT0, "Sega", "Rad Mobile (World)", MACHINE_IMPERFECT_GRAPHICS ) /* Released in 02.1991 */
GAME( 1990, radmu, radm, sega_system32_analog, radm, segas32_new_state, init_radm, ROT0, "Sega", "Rad Mobile (US)", MACHINE_IMPERFECT_GRAPHICS )
GAMEL(1991, radr, 0, sega_system32_analog, radr, segas32_new_state, init_radr, ROT0, "Sega", "Rad Rally (World)", MACHINE_IMPERFECT_GRAPHICS, layout_radr )
GAMEL(1991, radru, radr, sega_system32_analog, radr, segas32_new_state, init_radr, ROT0, "Sega", "Rad Rally (US)", MACHINE_IMPERFECT_GRAPHICS, layout_radr )
GAMEL(1991, radrj, radr, sega_system32_analog, radr, segas32_new_state, init_radr, ROT0, "Sega", "Rad Rally (Japan)", MACHINE_IMPERFECT_GRAPHICS, layout_radr )
GAMEL(1995, slipstrm, 0, sega_system32_analog, slipstrm, segas32_new_state, init_slipstrm, ROT0, "Capcom", "Slip Stream (Brazil 950515)", MACHINE_IMPERFECT_GRAPHICS, layout_radr )
GAMEL(1995, slipstrmh, slipstrm, sega_system32_analog, slipstrm, segas32_new_state, init_slipstrm, ROT0, "Capcom", "Slip Stream (Hispanic 950515)", MACHINE_IMPERFECT_GRAPHICS, layout_radr )
GAME( 1992, sonic, 0, sega_system32_track, sonic, segas32_new_state, init_sonic, ROT0, "Sega", "SegaSonic The Hedgehog (Japan, rev. C)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, sonicp, sonic, sega_system32_track, sonic, segas32_new_state, init_sonicp, ROT0, "Sega", "SegaSonic The Hedgehog (Japan, prototype)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1991, spidman, 0, sega_system32_4p, spidman, segas32_new_state, init_spidman, ROT0, "Sega", "Spider-Man: The Videogame (World)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1991, spidmanu, spidman, sega_system32_4p, spidmanu, segas32_new_state, init_spidman, ROT0, "Sega", "Spider-Man: The Videogame (US, Rev A)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1991, spidmanj, spidman, sega_system32_4p, spidman, segas32_new_state, init_spidman, ROT0, "Sega", "Spider-Man: The Videogame (Japan)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1994, svf, 0, sega_system32, svf, segas32_new_state, init_svf, ROT0, "Sega", "Super Visual Football: European Sega Cup (Rev A)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1994, svfo, svf, sega_system32, svf, segas32_new_state, init_svf, ROT0, "Sega", "Super Visual Football: European Sega Cup", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1994, svs, svf, sega_system32, svf, segas32_new_state, init_svf, ROT0, "Sega", "Super Visual Soccer: Sega Cup (US, Rev A)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1994, jleague, svf, sega_system32, svf, segas32_new_state, init_jleague, ROT0, "Sega", "The J.League 1994 (Japan, Rev A)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1994, jleagueo, svf, sega_system32, svf, segas32_new_state, init_jleague, ROT0, "Sega", "The J.League 1994 (Japan)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1994, harddunk, 0, sega_multi32_6p, harddunk, segas32_new_state, init_harddunk, ROT0, "Sega", "Hard Dunk (World)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1994, harddunkj, harddunk, sega_multi32_6p, harddunk, segas32_new_state, init_harddunk, ROT0, "Sega", "Hard Dunk (Japan)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, orunners, 0, sega_multi32_analog, orunners, segas32_new_state, init_orunners, ROT0, "Sega", "OutRunners (World)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, orunnersu, orunners, sega_multi32_analog, orunners, segas32_new_state, init_orunners, ROT0, "Sega", "OutRunners (US)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, orunnersj, orunners, sega_multi32_analog, orunners, segas32_new_state, init_orunners, ROT0, "Sega", "OutRunners (Japan)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, scross, 0, sega_multi32_analog, scross, segas32_new_state, init_scross, ROT0, "Sega", "Stadium Cross (World)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, scrossa, scross, sega_multi32_analog, scross, segas32_new_state, init_scross, ROT0, "Sega", "Stadium Cross (World, alt)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, scrossu, scross, sega_multi32_analog, scross, segas32_new_state, init_scross, ROT0, "Sega", "Stadium Cross (US)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, titlef, 0, sega_multi32, titlef, segas32_new_state, init_titlef, ROT0, "Sega", "Title Fight (World)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, titlefu, titlef, sega_multi32, titlef, segas32_new_state, init_titlef, ROT0, "Sega", "Title Fight (US)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1992, titlefj, titlef, sega_multi32, titlef, segas32_new_state, init_titlef, ROT0, "Sega", "Title Fight (Japan)", MACHINE_IMPERFECT_GRAPHICS )
GAME( 1993, as1, 0, sega_multi32, multi32_generic, segas32_new_state, init_holo, ROT0, "Sega", "AS-1 Controller", MACHINE_NOT_WORKING | MACHINE_IMPERFECT_GRAPHICS | MACHINE_IMPERFECT_SOUND ) // needs laserdisc emulation
|
// 20 may 2015
#include "uipriv_windows.hpp"
// TODO
// - is there extra space on the bottom?
// we as Common Controls 6 users don't need to worry about the height of comboboxes; see http://blogs.msdn.com/b/oldnewthing/archive/2006/03/10/548537.aspx
struct uiCombobox {
uiWindowsControl c;
HWND hwnd;
void (*onSelected)(uiCombobox *, void *);
void *onSelectedData;
};
// TODO: NOT triggered on entering text
static BOOL onWM_COMMAND(uiControl *cc, HWND hwnd, WORD code, LRESULT *lResult)
{
uiCombobox *c = uiCombobox(cc);
if (code != CBN_SELCHANGE)
return FALSE;
(*(c->onSelected))(c, c->onSelectedData);
*lResult = 0;
return TRUE;
}
void uiComboboxDestroy(uiControl *cc)
{
uiCombobox *c = uiCombobox(cc);
uiWindowsUnregisterWM_COMMANDHandler(c->hwnd);
uiWindowsEnsureDestroyWindow(c->hwnd);
uiFreeControl(uiControl(c));
}
uiWindowsControlAllDefaultsExceptDestroy(uiCombobox)
// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing
#define comboboxWidth 107 /* this is actually the shorter progress bar width, but Microsoft only indicates as wide as necessary; TODO */
#define comboboxHeight 14
static void uiComboboxMinimumSize(uiWindowsControl *cc, intmax_t *width, intmax_t *height)
{
uiCombobox *c = uiCombobox(cc);
uiWindowsSizing sizing;
int x, y;
x = comboboxWidth;
y = comboboxHeight;
uiWindowsGetSizing(c->hwnd, &sizing);
uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y);
*width = x;
*height = y;
}
static void defaultOnSelected(uiCombobox *c, void *data)
{
// do nothing
}
void uiComboboxAppend(uiCombobox *c, const char *text)
{
WCHAR *wtext;
LRESULT res;
wtext = toUTF16(text);
res = SendMessageW(c->hwnd, CB_ADDSTRING, 0, (LPARAM) wtext);
if (res == (LRESULT) CB_ERR)
logLastError(L"error appending item to uiCombobox");
else if (res == (LRESULT) CB_ERRSPACE)
logLastError(L"memory exhausted appending item to uiCombobox");
uiFree(wtext);
}
intmax_t uiComboboxSelected(uiCombobox *c)
{
LRESULT n;
n = SendMessage(c->hwnd, CB_GETCURSEL, 0, 0);
if (n == (LRESULT) CB_ERR)
return -1;
return (intmax_t) n;
}
void uiComboboxSetSelected(uiCombobox *c, intmax_t n)
{
// TODO error check
SendMessageW(c->hwnd, CB_SETCURSEL, (WPARAM) n, 0);
}
void uiComboboxOnSelected(uiCombobox *c, void (*f)(uiCombobox *c, void *data), void *data)
{
c->onSelected = f;
c->onSelectedData = data;
}
static uiCombobox *finishNewCombobox(DWORD style)
{
uiCombobox *c;
uiWindowsNewControl(uiCombobox, c);
c->hwnd = uiWindowsEnsureCreateControlHWND(WS_EX_CLIENTEDGE,
L"combobox", L"",
style | WS_TABSTOP,
hInstance, NULL,
TRUE);
uiWindowsRegisterWM_COMMANDHandler(c->hwnd, onWM_COMMAND, uiControl(c));
uiComboboxOnSelected(c, defaultOnSelected, NULL);
return c;
}
uiCombobox *uiNewCombobox(void)
{
return finishNewCombobox(CBS_DROPDOWNLIST);
}
uiCombobox *uiNewEditableCombobox(void)
{
return finishNewCombobox(CBS_DROPDOWN);
}
|
/*
* TextureCubeMap.cpp
* Virtual Vision
*
* Created by Abdallah Dib Abdallah.dib@virtual-vison.net
* Copyright 2011 Virtual Vision. All rights reserved.
*
*/
#include "TextureCubeMap.h"
namespace vvision
{
CTextureCubeMap::CTextureCubeMap()
{
m_uID = 0;
}
CTextureCubeMap::~CTextureCubeMap()
{
Release();
}
void CTextureCubeMap::CreateTexture(GLenum target, uint32 width, uint32 height, GLint internal_format,
GLenum host_data_type ,
GLenum host_data_format ,
void *host_data_xp,
void *host_data_xn,
void *host_data_yp,
void *host_data_yn ,
void *host_data_zp,
void *host_data_zn,
GLint Swrap_mode ,
GLint Twrap_mode ,
GLint min_filter ,
GLint mag_filter,
bool buildMipMap,
GLint mip_level,
GLint border)
{
m_iInternalFormat = internal_format;
m_uWidth = width;
m_uHeight = height;
m_eTarget = target;
m_iSWrapMode = Swrap_mode;
m_iTWrapMode = Twrap_mode;
m_iMinFilter = min_filter;
m_iMagFilter = mag_filter;
glGenTextures(1, &m_uID);
{
// Allocate and bind an OpenGL texture
glBindTexture (m_eTarget, m_uID);
// Set interpolation function t o nearest-neighbor
glTexParameteri(m_eTarget, GL_TEXTURE_MIN_FILTER, m_iMinFilter);
glTexParameteri(m_eTarget, GL_TEXTURE_MAG_FILTER, m_iMagFilter);
// Set desired wrapping type
glTexParameteri(m_eTarget, GL_TEXTURE_WRAP_S, m_iSWrapMode);
glTexParameteri(m_eTarget, GL_TEXTURE_WRAP_T, m_iTWrapMode);
// Set texture format and component count
glTexImage2D (GL_TEXTURE_CUBE_MAP_POSITIVE_X,
mip_level,
internal_format,
width,
height,
border,
host_data_format,
host_data_type,
host_data_xp);
glTexImage2D (GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
mip_level,
internal_format,
width,
height,
border,
host_data_format,
host_data_type,
host_data_xn);
glTexImage2D (GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
mip_level,
internal_format,
width,
height,
border,
host_data_format,
host_data_type,
host_data_yp);
glTexImage2D (GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
mip_level,
internal_format,
width,
height,
border,
host_data_format,
host_data_type,
host_data_yn);
glTexImage2D (GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
mip_level,
internal_format,
width,
height,
border,
host_data_format,
host_data_type,
host_data_zp);
glTexImage2D (GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
mip_level,
internal_format,
width,
height,
border,
host_data_format,
host_data_type,
host_data_zn);
glBindTexture (m_eTarget, 0);
if(buildMipMap)
glGenerateMipmap(GL_TEXTURE_2D);//GL_LINEAR_MIPMAP_LINEAR
}
}
void CTextureCubeMap::Release()
{
if(IsValid())
glDeleteTextures(1, &m_uID);
}
bool CTextureCubeMap::IsValid()
{
return glIsTexture(m_uID);
}
void CTextureCubeMap::ActivateAndBind(GLenum texture_unit)
{
glActiveTexture(texture_unit);
glBindTexture(m_eTarget, m_uID);
}
void CTextureCubeMap::ActivateAndRefresh(GLenum target,void * data, GLsizei width, GLsizei height, GLint xoffset , GLint yoffset , GLint level , GLenum host_format , GLenum host_type)
{
glBindTexture(m_eTarget, m_uID);
glTexSubImage2D(target, level, xoffset, yoffset, width, height, host_format, host_type, data);
}
}
|
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <tuple>
#include <stdbool.h>
#include <bitset>
#include <string>
#include <boost/multiprecision/cpp_int.hpp>
namespace mp = boost::multiprecision;
using namespace std;
// label: a=0, b=1, c=2
void insert(map<mp::cpp_int, vector<int>>& cakes, int n, int label) {
for(int i = 0 ; i < n ; ++i) {
mp::cpp_int v;
cin >> v;
if(!cakes.count(v)) {
cakes[v] = vector<int>(3);
cakes[v][0] = 0;
cakes[v][1] = 0;
cakes[v][2] = 0;
}
cakes[v][label]++;
}
}
int main(void) {
int x,y,z;
mp::cpp_int count;
cin >> x;
cin >> y;
cin >> z;
cin >> count;
map<mp::cpp_int, vector<int>> cakes;
insert(cakes, x, 0);
insert(cakes, y, 1);
insert(cakes, z, 2);
mp::cpp_int now_count = 0;
auto e = cakes.rend();
for(auto i = cakes.rbegin() ; i != e ; ++i) {
// select a
while (i->second[0]) {
mp::cpp_int sum = 0;
i->second[0]--;
sum += i->first;
cout << "sel a sum:" << sum << " num:" << i->first << endl;
// select b
for(auto j = cakes.rbegin() ; j != e ; ++j) {
while (j->second[1]) {
j->second[1]--;
sum += j->first;
cout << "sel b sum:" << sum << " num:" << j->first << endl;
// select c
for(auto k = cakes.rbegin() ; k != e ; ++k) {
while (k->second[2]) {
k->second[2]--;
sum += k->first;
cout << "sel c sum:" << sum << " num:" << k->first << endl;
cout << sum << endl;
// increment and halt
now_count++;
if(count <= now_count) {
return 0;
}
sum -= k->first;
}
}
// c
sum -= j->first;
}
}
// b
}
// a
}
return 0;
}
|
#ifndef EMB_NET_ASYNC_CORE_HPP
#define EMB_NET_ASYNC_CORE_HPP
#include <emb/net/socket.hpp>
#include <emb/callback.hpp>
#include <emb/flags.hpp>
#include <functional>
#include <vector>
#include <sys/epoll.h>
namespace emb::net
{
enum class async_watch : std::uint32_t {
invalid = 0,
in = 1 << 0,
out = 1 << 1,
err = 1 << 2,
hup = 1 << 3
};
using async_watch_flags = emb::flags<async_watch>;
class async_core
{
private:
emb::callback<void (std::uint32_t, async_watch_flags)> callback_;
public:
using node_id = std::uint32_t;
async_core();
~async_core();
void run_once();
void add(std::uint32_t id, net::socket& s, async_watch_flags watch_for);
void modify(std::uint32_t id, net::socket& s, async_watch_flags watch_for);
void remove(net::socket& s);
emb::public_callback<void (std::uint32_t, async_watch_flags)> on_event {callback_};
private:
static constexpr auto MAX_EVENTS = 32;
int epoll_socket_;
epoll_event events_[MAX_EVENTS];
};
}
#endif // EMB_NET_ASYNC_CORE_HPP
|
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
class EggCartons {
public:
int minCartons(int n) {
int sol = 1234567;
for (int i=0; i<1000; ++i) {
for (int j=0; j<1000; ++j) {
if (i*8 + j*6 == n) {
sol = min(sol, i+j);
}
}
}
return sol==1234567 ? -1 : sol;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 20; int Arg1 = 3; verify_case(0, Arg1, minCartons(Arg0)); }
void test_case_1() { int Arg0 = 24; int Arg1 = 3; verify_case(1, Arg1, minCartons(Arg0)); }
void test_case_2() { int Arg0 = 15; int Arg1 = -1; verify_case(2, Arg1, minCartons(Arg0)); }
void test_case_3() { int Arg0 = 4; int Arg1 = -1; verify_case(3, Arg1, minCartons(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
EggCartons ___test;
___test.run_test(-1);
}
// END CUT HERE
|
/*
* Copyright 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "ortc/rtpparametersconversion.h"
#include <set>
#include <sstream>
#include <utility>
#include "media/base/rtputils.h"
namespace webrtc {
RTCErrorOr<cricket::FeedbackParam> ToCricketFeedbackParam(
const RtcpFeedback& feedback) {
switch (feedback.type) {
case RtcpFeedbackType::CCM:
if (!feedback.message_type) {
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
"Missing message type in CCM RtcpFeedback.");
} else if (*feedback.message_type != RtcpFeedbackMessageType::FIR) {
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
"Invalid message type in CCM RtcpFeedback.");
}
return cricket::FeedbackParam(cricket::kRtcpFbParamCcm,
cricket::kRtcpFbCcmParamFir);
case RtcpFeedbackType::NACK:
if (!feedback.message_type) {
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
"Missing message type in NACK RtcpFeedback.");
}
switch (*feedback.message_type) {
case RtcpFeedbackMessageType::GENERIC_NACK:
return cricket::FeedbackParam(cricket::kRtcpFbParamNack);
case RtcpFeedbackMessageType::PLI:
return cricket::FeedbackParam(cricket::kRtcpFbParamNack,
cricket::kRtcpFbNackParamPli);
default:
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
"Invalid message type in NACK RtcpFeedback.");
}
case RtcpFeedbackType::REMB:
if (feedback.message_type) {
LOG_AND_RETURN_ERROR(
RTCErrorType::INVALID_PARAMETER,
"Didn't expect message type in REMB RtcpFeedback.");
}
return cricket::FeedbackParam(cricket::kRtcpFbParamRemb);
case RtcpFeedbackType::TRANSPORT_CC:
if (feedback.message_type) {
LOG_AND_RETURN_ERROR(
RTCErrorType::INVALID_PARAMETER,
"Didn't expect message type in transport-cc RtcpFeedback.");
}
return cricket::FeedbackParam(cricket::kRtcpFbParamTransportCc);
}
// Not reached; avoids compile warning.
FATAL();
}
template <typename C>
static RTCError ToCricketCodecTypeSpecific(const RtpCodecParameters& codec,
C* cricket_codec);
template <>
RTCError ToCricketCodecTypeSpecific<cricket::AudioCodec>(
const RtpCodecParameters& codec,
cricket::AudioCodec* cricket_codec) {
if (codec.kind != cricket::MEDIA_TYPE_AUDIO) {
LOG_AND_RETURN_ERROR(
RTCErrorType::INVALID_PARAMETER,
"Can't use video codec with audio sender or receiver.");
}
if (!codec.num_channels) {
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
"Missing number of channels for audio codec.");
}
if (*codec.num_channels <= 0) {
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_RANGE,
"Number of channels must be positive.");
}
cricket_codec->channels = *codec.num_channels;
if (!codec.clock_rate) {
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
"Missing codec clock rate.");
}
if (*codec.clock_rate <= 0) {
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_RANGE,
"Clock rate must be positive.");
}
cricket_codec->clockrate = *codec.clock_rate;
return RTCError::OK();
}
// Video codecs don't use num_channels or clock_rate, but they should at least
// be validated to ensure the application isn't trying to do something it
// doesn't intend to.
template <>
RTCError ToCricketCodecTypeSpecific<cricket::VideoCodec>(
const RtpCodecParameters& codec,
cricket::VideoCodec*) {
if (codec.kind != cricket::MEDIA_TYPE_VIDEO) {
LOG_AND_RETURN_ERROR(
RTCErrorType::INVALID_PARAMETER,
"Can't use audio codec with video sender or receiver.");
}
if (codec.num_channels) {
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
"Video codec shouldn't have num_channels.");
}
if (!codec.clock_rate) {
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
"Missing codec clock rate.");
}
if (*codec.clock_rate != cricket::kVideoCodecClockrate) {
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
"Video clock rate must be 90000.");
}
return RTCError::OK();
}
template <typename C>
RTCErrorOr<C> ToCricketCodec(const RtpCodecParameters& codec) {
C cricket_codec;
// Start with audio/video specific conversion.
RTCError err = ToCricketCodecTypeSpecific(codec, &cricket_codec);
if (!err.ok()) {
return std::move(err);
}
cricket_codec.name = codec.name;
if (!cricket::IsValidRtpPayloadType(codec.payload_type)) {
std::ostringstream oss;
oss << "Invalid payload type: " << codec.payload_type;
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_RANGE, oss.str());
}
cricket_codec.id = codec.payload_type;
for (const RtcpFeedback& feedback : codec.rtcp_feedback) {
auto result = ToCricketFeedbackParam(feedback);
if (!result.ok()) {
return result.MoveError();
}
cricket_codec.AddFeedbackParam(result.MoveValue());
}
cricket_codec.params.insert(codec.parameters.begin(), codec.parameters.end());
return std::move(cricket_codec);
}
template RTCErrorOr<cricket::AudioCodec> ToCricketCodec(
const RtpCodecParameters& codec);
template RTCErrorOr<cricket::VideoCodec> ToCricketCodec(
const RtpCodecParameters& codec);
template <typename C>
RTCErrorOr<std::vector<C>> ToCricketCodecs(
const std::vector<RtpCodecParameters>& codecs) {
std::vector<C> cricket_codecs;
std::set<int> seen_payload_types;
for (const RtpCodecParameters& codec : codecs) {
auto result = ToCricketCodec<C>(codec);
if (!result.ok()) {
return result.MoveError();
}
if (!seen_payload_types.insert(codec.payload_type).second) {
std::ostringstream oss;
oss << "Duplicate payload type: " << codec.payload_type;
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, oss.str());
}
cricket_codecs.push_back(result.MoveValue());
}
return std::move(cricket_codecs);
}
template RTCErrorOr<std::vector<cricket::AudioCodec>> ToCricketCodecs<
cricket::AudioCodec>(const std::vector<RtpCodecParameters>& codecs);
template RTCErrorOr<std::vector<cricket::VideoCodec>> ToCricketCodecs<
cricket::VideoCodec>(const std::vector<RtpCodecParameters>& codecs);
RTCErrorOr<cricket::RtpHeaderExtensions> ToCricketRtpHeaderExtensions(
const std::vector<RtpHeaderExtensionParameters>& extensions) {
cricket::RtpHeaderExtensions cricket_extensions;
std::ostringstream err_writer;
std::set<int> seen_header_extension_ids;
for (const RtpHeaderExtensionParameters& extension : extensions) {
if (extension.id < RtpHeaderExtensionParameters::kMinId ||
extension.id > RtpHeaderExtensionParameters::kMaxId) {
err_writer << "Invalid header extension id: " << extension.id;
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_RANGE, err_writer.str());
}
if (!seen_header_extension_ids.insert(extension.id).second) {
err_writer << "Duplicate header extension id: " << extension.id;
LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, err_writer.str());
}
cricket_extensions.push_back(extension);
}
return std::move(cricket_extensions);
}
RTCErrorOr<cricket::StreamParamsVec> ToCricketStreamParamsVec(
const std::vector<RtpEncodingParameters>& encodings) {
if (encodings.size() > 1u) {
LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
"ORTC API implementation doesn't currently "
"support simulcast or layered encodings.");
} else if (encodings.empty()) {
return cricket::StreamParamsVec();
}
cricket::StreamParamsVec cricket_streams;
const RtpEncodingParameters& encoding = encodings[0];
if (encoding.rtx && encoding.rtx->ssrc && !encoding.ssrc) {
LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
"Setting an RTX SSRC explicitly while leaving the "
"primary SSRC unset is not currently supported.");
}
if (encoding.ssrc) {
cricket::StreamParams stream_params;
stream_params.add_ssrc(*encoding.ssrc);
if (encoding.rtx && encoding.rtx->ssrc) {
stream_params.AddFidSsrc(*encoding.ssrc, *encoding.rtx->ssrc);
}
cricket_streams.push_back(std::move(stream_params));
}
return std::move(cricket_streams);
}
absl::optional<RtcpFeedback> ToRtcpFeedback(
const cricket::FeedbackParam& cricket_feedback) {
if (cricket_feedback.id() == cricket::kRtcpFbParamCcm) {
if (cricket_feedback.param() == cricket::kRtcpFbCcmParamFir) {
return RtcpFeedback(RtcpFeedbackType::CCM, RtcpFeedbackMessageType::FIR);
} else {
RTC_LOG(LS_WARNING) << "Unsupported parameter for CCM RTCP feedback: "
<< cricket_feedback.param();
return absl::nullopt;
}
} else if (cricket_feedback.id() == cricket::kRtcpFbParamNack) {
if (cricket_feedback.param().empty()) {
return RtcpFeedback(RtcpFeedbackType::NACK,
RtcpFeedbackMessageType::GENERIC_NACK);
} else if (cricket_feedback.param() == cricket::kRtcpFbNackParamPli) {
return RtcpFeedback(RtcpFeedbackType::NACK, RtcpFeedbackMessageType::PLI);
} else {
RTC_LOG(LS_WARNING) << "Unsupported parameter for NACK RTCP feedback: "
<< cricket_feedback.param();
return absl::nullopt;
}
} else if (cricket_feedback.id() == cricket::kRtcpFbParamRemb) {
if (!cricket_feedback.param().empty()) {
RTC_LOG(LS_WARNING) << "Unsupported parameter for REMB RTCP feedback: "
<< cricket_feedback.param();
return absl::nullopt;
} else {
return RtcpFeedback(RtcpFeedbackType::REMB);
}
} else if (cricket_feedback.id() == cricket::kRtcpFbParamTransportCc) {
if (!cricket_feedback.param().empty()) {
RTC_LOG(LS_WARNING)
<< "Unsupported parameter for transport-cc RTCP feedback: "
<< cricket_feedback.param();
return absl::nullopt;
} else {
return RtcpFeedback(RtcpFeedbackType::TRANSPORT_CC);
}
}
RTC_LOG(LS_WARNING) << "Unsupported RTCP feedback type: "
<< cricket_feedback.id();
return absl::nullopt;
}
std::vector<RtpEncodingParameters> ToRtpEncodings(
const cricket::StreamParamsVec& stream_params) {
std::vector<RtpEncodingParameters> rtp_encodings;
for (const cricket::StreamParams& stream_param : stream_params) {
RtpEncodingParameters rtp_encoding;
rtp_encoding.ssrc.emplace(stream_param.first_ssrc());
uint32_t rtx_ssrc = 0;
if (stream_param.GetFidSsrc(stream_param.first_ssrc(), &rtx_ssrc)) {
RtpRtxParameters rtx_param(rtx_ssrc);
rtp_encoding.rtx.emplace(rtx_param);
}
rtp_encodings.push_back(std::move(rtp_encoding));
}
return rtp_encodings;
}
template <typename C>
cricket::MediaType KindOfCodec();
template <>
cricket::MediaType KindOfCodec<cricket::AudioCodec>() {
return cricket::MEDIA_TYPE_AUDIO;
}
template <>
cricket::MediaType KindOfCodec<cricket::VideoCodec>() {
return cricket::MEDIA_TYPE_VIDEO;
}
template <typename C>
static void ToRtpCodecCapabilityTypeSpecific(const C& cricket_codec,
RtpCodecCapability* codec);
template <>
void ToRtpCodecCapabilityTypeSpecific<cricket::AudioCodec>(
const cricket::AudioCodec& cricket_codec,
RtpCodecCapability* codec) {
codec->num_channels = static_cast<int>(cricket_codec.channels);
}
template <>
void ToRtpCodecCapabilityTypeSpecific<cricket::VideoCodec>(
const cricket::VideoCodec& cricket_codec,
RtpCodecCapability* codec) {}
template <typename C>
RtpCodecCapability ToRtpCodecCapability(const C& cricket_codec) {
RtpCodecCapability codec;
codec.name = cricket_codec.name;
codec.kind = KindOfCodec<C>();
codec.clock_rate.emplace(cricket_codec.clockrate);
codec.preferred_payload_type.emplace(cricket_codec.id);
for (const cricket::FeedbackParam& cricket_feedback :
cricket_codec.feedback_params.params()) {
absl::optional<RtcpFeedback> feedback = ToRtcpFeedback(cricket_feedback);
if (feedback) {
codec.rtcp_feedback.push_back(feedback.value());
}
}
ToRtpCodecCapabilityTypeSpecific(cricket_codec, &codec);
codec.parameters.insert(cricket_codec.params.begin(),
cricket_codec.params.end());
return codec;
}
template RtpCodecCapability ToRtpCodecCapability<cricket::AudioCodec>(
const cricket::AudioCodec& cricket_codec);
template RtpCodecCapability ToRtpCodecCapability<cricket::VideoCodec>(
const cricket::VideoCodec& cricket_codec);
template <typename C>
static void ToRtpCodecParametersTypeSpecific(const C& cricket_codec,
RtpCodecParameters* codec);
template <>
void ToRtpCodecParametersTypeSpecific<cricket::AudioCodec>(
const cricket::AudioCodec& cricket_codec,
RtpCodecParameters* codec) {
codec->num_channels = static_cast<int>(cricket_codec.channels);
}
template <>
void ToRtpCodecParametersTypeSpecific<cricket::VideoCodec>(
const cricket::VideoCodec& cricket_codec,
RtpCodecParameters* codec) {}
template <typename C>
RtpCodecParameters ToRtpCodecParameters(const C& cricket_codec) {
RtpCodecParameters codec_param;
codec_param.name = cricket_codec.name;
codec_param.kind = KindOfCodec<C>();
codec_param.clock_rate.emplace(cricket_codec.clockrate);
codec_param.payload_type = cricket_codec.id;
for (const cricket::FeedbackParam& cricket_feedback :
cricket_codec.feedback_params.params()) {
absl::optional<RtcpFeedback> feedback = ToRtcpFeedback(cricket_feedback);
if (feedback) {
codec_param.rtcp_feedback.push_back(feedback.value());
}
}
ToRtpCodecParametersTypeSpecific(cricket_codec, &codec_param);
codec_param.parameters.insert(cricket_codec.params.begin(),
cricket_codec.params.end());
return codec_param;
}
template RtpCodecParameters ToRtpCodecParameters<cricket::AudioCodec>(
const cricket::AudioCodec& cricket_codec);
template RtpCodecParameters ToRtpCodecParameters<cricket::VideoCodec>(
const cricket::VideoCodec& cricket_codec);
template <class C>
RtpCapabilities ToRtpCapabilities(
const std::vector<C>& cricket_codecs,
const cricket::RtpHeaderExtensions& cricket_extensions) {
RtpCapabilities capabilities;
bool have_red = false;
bool have_ulpfec = false;
bool have_flexfec = false;
for (const C& cricket_codec : cricket_codecs) {
if (cricket_codec.name == cricket::kRedCodecName) {
have_red = true;
} else if (cricket_codec.name == cricket::kUlpfecCodecName) {
have_ulpfec = true;
} else if (cricket_codec.name == cricket::kFlexfecCodecName) {
have_flexfec = true;
}
capabilities.codecs.push_back(ToRtpCodecCapability(cricket_codec));
}
for (const RtpExtension& cricket_extension : cricket_extensions) {
capabilities.header_extensions.emplace_back(cricket_extension.uri,
cricket_extension.id);
}
if (have_red) {
capabilities.fec.push_back(FecMechanism::RED);
}
if (have_red && have_ulpfec) {
capabilities.fec.push_back(FecMechanism::RED_AND_ULPFEC);
}
if (have_flexfec) {
capabilities.fec.push_back(FecMechanism::FLEXFEC);
}
return capabilities;
}
template RtpCapabilities ToRtpCapabilities<cricket::AudioCodec>(
const std::vector<cricket::AudioCodec>& cricket_codecs,
const cricket::RtpHeaderExtensions& cricket_extensions);
template RtpCapabilities ToRtpCapabilities<cricket::VideoCodec>(
const std::vector<cricket::VideoCodec>& cricket_codecs,
const cricket::RtpHeaderExtensions& cricket_extensions);
template <class C>
RtpParameters ToRtpParameters(
const std::vector<C>& cricket_codecs,
const cricket::RtpHeaderExtensions& cricket_extensions,
const cricket::StreamParamsVec& stream_params) {
RtpParameters rtp_parameters;
for (const C& cricket_codec : cricket_codecs) {
rtp_parameters.codecs.push_back(ToRtpCodecParameters(cricket_codec));
}
for (const RtpExtension& cricket_extension : cricket_extensions) {
rtp_parameters.header_extensions.emplace_back(cricket_extension.uri,
cricket_extension.id);
}
rtp_parameters.encodings = ToRtpEncodings(stream_params);
return rtp_parameters;
}
template RtpParameters ToRtpParameters<cricket::AudioCodec>(
const std::vector<cricket::AudioCodec>& cricket_codecs,
const cricket::RtpHeaderExtensions& cricket_extensions,
const cricket::StreamParamsVec& stream_params);
template RtpParameters ToRtpParameters<cricket::VideoCodec>(
const std::vector<cricket::VideoCodec>& cricket_codecs,
const cricket::RtpHeaderExtensions& cricket_extensions,
const cricket::StreamParamsVec& stream_params);
} // namespace webrtc
|
// 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.
//
// Tencent is pleased to support the open source community by making WeChat QRCode available.
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Modified from ZXing. Copyright ZXing authors.
// Licensed under the Apache License, Version 2.0 (the "License").
#ifndef __ZXING_QRCODE_DECODER_BITMATRIXPARSER_HPP__
#define __ZXING_QRCODE_DECODER_BITMATRIXPARSER_HPP__
#include "../../common/array.hpp"
#include "../../common/bitmatrix.hpp"
#include "../../common/counted.hpp"
#include "../../errorhandler.hpp"
#include "../format_information.hpp"
#include "../version.hpp"
namespace zxing {
namespace qrcode {
class BitMatrixParser : public Counted {
private:
Ref<BitMatrix> bitMatrix_;
Version *parsedVersion_;
Ref<FormatInformation> parsedFormatInfo_;
bool mirror_;
int copyBit(size_t x, size_t y, int versionBits);
public:
BitMatrixParser(Ref<BitMatrix> bitMatrix, ErrorHandler &err_handler);
Ref<FormatInformation> readFormatInformation(ErrorHandler &err_handler);
Version *readVersion(ErrorHandler &err_handler);
ArrayRef<char> readCodewords(ErrorHandler &err_handler);
public:
void remask();
void setMirror(bool mirror);
void mirror();
void mirrorH();
private:
BitMatrixParser(const BitMatrixParser &);
BitMatrixParser &operator=(const BitMatrixParser &);
};
} // namespace qrcode
} // namespace zxing
#endif // __ZXING_QRCODE_DECODER_BITMATRIXPARSER_HPP__
|
/* TODO: only really acts as a counter, perhaps we can make a real
* inactive thread pool?
*/
#ifndef PJ_INACTIVE_POOL_HPP
#define PJ_INACTIVE_POOL_HPP
#include <iostream>
#include <atomic>
#include <sys/types.h>
namespace pj_runtime
{
class pj_inactive_pool
{
public:
pj_inactive_pool()
{
std::cout << "pj_inactive_pool constructor called\n";
this->count.store(0, std::memory_order_relaxed);
}
~pj_inactive_pool()
{
std::cout << "pj_inactive_pool destructor called\n";
}
void increment()
{
int previous_value = this->count.load(std::memory_order_relaxed);
this->count.store(previous_value--, std::memory_order_relaxed);
}
void decrement()
{
int previous_value = this->count.load(std::memory_order_relaxed);
this->count.store(previous_value++, std::memory_order_relaxed);
}
int get_count()
{
return this->count.load(std::memory_order_relaxed);
}
private:
std::atomic<int32_t> count;
};
}
#endif
|
#include "caffe2/mpi/mpi_common.h"
#include <thread>
#include "caffe2/core/typeid.h"
#include "caffe2/utils/proto_utils.h"
namespace caffe2 {
CAFFE_KNOWN_TYPE(MPICommonWorldWrapper);
static std::mutex gCaffe2MPIMutex;
std::mutex& MPIMutex() {
return gCaffe2MPIMutex;
}
static MPI_Comm gCaffe2MPIComm = MPI_COMM_WORLD;
MPI_Comm GlobalMPIComm() {
return gCaffe2MPIComm;
}
void SetGlobalMPIComm(MPI_Comm new_comm) {
if (gCaffe2MPIComm != MPI_COMM_WORLD) {
MPI_Comm_free(&gCaffe2MPIComm);
}
gCaffe2MPIComm = new_comm;
}
int MPICommSize(MPI_Comm comm) {
int comm_size;
MPI_CHECK(MPI_Comm_size(comm, &comm_size));
return comm_size;
}
int MPICommRank(MPI_Comm comm) {
int comm_rank;
MPI_CHECK(MPI_Comm_rank(comm, &comm_rank));
return comm_rank;
}
/**
* Helper function used to setup MPI intercommunicator.
*/
static MPI_Comm AssimilateComm(MPI_Comm intra, MPI_Comm inter) {
MPI_Comm peer = MPI_COMM_NULL;
MPI_Comm newInterComm = MPI_COMM_NULL;
MPI_Comm newIntraComm = MPI_COMM_NULL;
// The spawned rank will be the "high" rank in the new intra-comm
int high = (MPI_COMM_NULL == intra) ? 1 : 0;
// If this is one of the (two) ranks in the inter-comm,
// create a new intra-comm from the inter-comm
if (MPI_COMM_NULL != inter) {
MPI_CHECK(MPI_Intercomm_merge(inter, high, &peer));
} else {
peer = MPI_COMM_NULL;
}
// Create a new inter-comm between the pre-existing intra-comm
// (all of it, not only rank zero), and the remote (spawned) rank,
// using the just-created intra-comm as the peer communicator.
int tag = 12345;
if (MPI_COMM_NULL != intra) {
// This task is a member of the pre-existing intra-comm
MPI_CHECK(MPI_Intercomm_create(intra, 0, peer, 1, tag, &newInterComm));
} else {
// This is the remote (spawned) task
MPI_CHECK(
MPI_Intercomm_create(MPI_COMM_SELF, 0, peer, 0, tag, &newInterComm));
}
// Now convert this inter-comm into an intra-comm
MPI_CHECK(MPI_Intercomm_merge(newInterComm, high, &newIntraComm));
// Clean up the intermediaries
if (MPI_COMM_NULL != peer) {
MPI_CHECK(MPI_Comm_free(&peer));
}
MPI_CHECK(MPI_Comm_free(&newInterComm));
// Delete the original intra-comm
if (MPI_COMM_NULL != intra && MPI_COMM_WORLD != intra &&
GlobalMPIComm() != intra) {
MPI_CHECK(MPI_Comm_free(&intra));
}
// Return the new intra-comm
return newIntraComm;
}
void MPISetupPeers(
const int replicas,
const string& role,
const string& job_path) {
int flag;
MPI_Initialized(&flag);
if (!flag) {
int mpi_ret;
MPI_CHECK(MPI_Init_thread(nullptr, nullptr, MPI_THREAD_MULTIPLE, &mpi_ret));
if (mpi_ret != MPI_THREAD_MULTIPLE && mpi_ret != MPI_THREAD_SERIALIZED) {
LOG(FATAL) << "This test requires the underlying MPI to support the "
<< "MPI_THREAD_SERIALIZED or MPI_THREAD_MULTIPLE mode.";
return;
}
}
if (MPICommSize(MPI_COMM_WORLD) != 1) {
LOG(ERROR) << "MPI_COMM_WORLD size is not 1: did you already run "
"MPISetupPeers? Note that if you execute your program with "
"mpirun to launch multiple local processes, you should not "
"call MPISetupPeers.";
return;
}
if (role == "server") {
// Open a port to accept connections.
char port_name[MPI_MAX_PORT_NAME] = {'\0'};
MPI_CHECK(MPI_Open_port(MPI_INFO_NULL, port_name));
VLOG(1) << "MPI server: port: " << port_name;
// Writes the port name to the file.
CHECK(WriteStringToFile(std::string(port_name), job_path.c_str()));
VLOG(1) << "MPI server: wrote to file: " << job_path;
int comm_size = MPICommSize(GlobalMPIComm());
while (comm_size < replicas) {
MPI_Comm icomm;
VLOG(1) << "MPI server: waiting for client "
<< "(" << comm_size << "/" << replicas << " have connected)";
MPI_CHECK(
MPI_Comm_accept(port_name, MPI_INFO_NULL, 0, MPI_COMM_SELF, &icomm));
VLOG(1) << "MPI server: accepted client";
MPI_Comm new_intra_comm = AssimilateComm(GlobalMPIComm(), icomm);
SetGlobalMPIComm(new_intra_comm);
comm_size = MPICommSize(new_intra_comm);
}
} else {
// Opens the job path file to obtain server address.
std::string port_name;
while (!ReadStringFromFile(job_path.c_str(), &port_name) ||
port_name.length() == 0) {
/* sleep override */
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// Connect to server.
MPI_Comm icomm;
VLOG(1) << "MPI client: connecting to port: " << port_name;
MPI_CHECK(MPI_Comm_connect(
const_cast<char*>(port_name.c_str()),
MPI_INFO_NULL,
0,
GlobalMPIComm(),
&icomm));
VLOG(1) << "MPI client: connected";
// Join the server's reference intracommunicator.
MPI_Comm new_intra_comm = AssimilateComm(MPI_COMM_NULL, icomm);
SetGlobalMPIComm(new_intra_comm);
// Let other clients join the intracommunicator we're now a part of.
while (MPICommSize(GlobalMPIComm()) < replicas) {
MPI_Comm comm = AssimilateComm(GlobalMPIComm(), MPI_COMM_NULL);
SetGlobalMPIComm(comm);
}
}
// After all peers have assimilated, do a barrier.
MPI_Barrier(GlobalMPIComm());
VLOG(1) << "MPI using a communicator of size: "
<< MPICommSize(GlobalMPIComm());
}
} // namespace caffe2
|
//// Copyright 2020 Egorov Kirill
#include <gtest-mpi-listener.hpp>
#include <gtest/gtest.h>
#include <vector>
#include "./batcher_sort.h"
TEST(basic_functions_tests, shuffle_test) {
int rank, numtasks;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
if (rank == 0) {
std::vector<int> testVec = { 10, 20, 60, 35, 47, 23, 12, 30 };
std::vector<int> checkVec = { 10, 47, 20, 23, 60, 12, 35, 30 };
sh(&testVec, 0, testVec.size());
for (unsigned int i = 0; i < testVec.size(); i++) {
ASSERT_EQ(testVec[i], checkVec[i]);
}
}
}
TEST(basic_functions_tests, unshuffle_test) {
int rank, numtasks;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
if (rank == 0) {
std::vector<int> testVec = { 10, 20, 60, 35, 47, 23, 12, 30 };
std::vector<int> checkVec = { 10, 60, 47, 12, 20, 35, 23, 30 };
uns(&testVec, 0, testVec.size());
for (unsigned int i = 0; i < testVec.size(); i++) {
ASSERT_EQ(testVec[i], checkVec[i]);
}
}
}
TEST(basic_functions_test, shuffle_unshuffle_is_correctly_reversed_test) {
int rank, numtasks;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
if (rank == 0) {
std::vector<int> testVec = { 10, 20, 60, 35, 47, 23, 12, 30 };
std::vector<int> checkVec = { 10, 20, 60, 35, 47, 23, 12, 30 };
sh(&testVec, 0, testVec.size());
uns(&testVec, 0, testVec.size());
for (unsigned int i = 0; i < testVec.size(); i++) {
ASSERT_EQ(testVec[i], checkVec[i]);
}
}
}
TEST(basic_functions_test, unshuffle_shuffle_is_correctly_reversed_test) {
int rank, numtasks;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
if (rank == 0) {
std::vector<int> testVec = { 10, 20, 60, 35, 47, 23, 12, 30 };
std::vector<int> checkVec = { 10, 20, 60, 35, 47, 23, 12, 30 };
uns(&testVec, 0, testVec.size());
sh(&testVec, 0, testVec.size());
for (unsigned int i = 0; i < testVec.size(); i++) {
ASSERT_EQ(testVec[i], checkVec[i]);
}
}
}
TEST(basic_functions_test, simple_sort_test) {
int rank, numtasks;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
if (rank == 0) {
std::vector<int> testVec = getRandomVector(8);
simpleSort(&testVec);
ASSERT_EQ(true, simpleCheck(testVec));
}
}
TEST(sequential_operation_tests, basic_BatcherSort_test) {
int rank, numtasks;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
if (rank == 0) {
std::vector<int> testVec = getRandomVector(8);
BatcherSort(&testVec);
ASSERT_EQ(true, simpleCheck(testVec));
}
}
TEST(sequential_operation_tests, basic_BatcherSort_test_large) {
int rank, numtasks;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
if (rank == 0) {
std::vector<int> testVec = getRandomVector(8192);
BatcherSort(&testVec);
ASSERT_EQ(true, simpleCheck(testVec));
}
}
TEST(sequential_operation_tests, basic_BatcherSort_test_non_grade_of_two) {
int rank, numtasks;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
if (rank == 0) {
std::vector<int> testVec = getRandomVector(12);
BatcherSort(&testVec);
ASSERT_EQ(true, simpleCheck(testVec));
}
}
TEST(parallel_operation_test, batcher_sort_parallel_test) {
std::vector<int> testVec = getRandomVector(40);
int rank, numtasks;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
BatcherSortParallel(&testVec);
if (rank == 0) {
ASSERT_EQ(true, simpleCheck(testVec));
}
}
TEST(parallel_operation_test, batcher_sort_parallel_test_large) {
std::vector<int> testVec = getRandomVector(8192);
int rank, numtasks;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
BatcherSortParallel(&testVec);
if (rank == 0) {
ASSERT_EQ(true, simpleCheck(testVec));
}
}
TEST(efficiency_test, parallel_sequential_times_test_large) {
std::vector<int> testVec = getRandomVector(8192);
int rank, numtasks;
double starttime, endtime, dif_parallel_time;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
starttime = MPI_Wtime();
BatcherSortParallel(&testVec);
endtime = MPI_Wtime();
dif_parallel_time = endtime - starttime;
if (rank == 0) {
clock_t start, end;
double dif_sequential_time;
start = clock();
BatcherSort(&testVec);
end = clock();
dif_sequential_time = static_cast<double>(end - start);
std::cout << "Parallel time " << dif_parallel_time << std::endl;
std::cout << "Sequential time " << dif_sequential_time << std::endl;
ASSERT_TRUE(dif_sequential_time >= dif_parallel_time);
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "base/command_line.h"
#include "gpu/config/gpu_driver_bug_list.h"
#include "gpu/config/gpu_driver_bug_workaround_type.h"
#include "gpu/config/gpu_info.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gpu {
class GpuDriverBugListTest : public testing::Test {
public:
GpuDriverBugListTest() = default;
~GpuDriverBugListTest() override = default;
};
#if defined(OS_ANDROID)
TEST_F(GpuDriverBugListTest, CurrentListForARM) {
std::unique_ptr<GpuDriverBugList> list = GpuDriverBugList::Create();
GPUInfo gpu_info;
gpu_info.gl_vendor = "ARM";
gpu_info.gl_renderer = "MALi_T604";
std::set<int> bugs = list->MakeDecision(
GpuControlList::kOsAndroid, "4.1", gpu_info);
EXPECT_EQ(1u, bugs.count(USE_CLIENT_SIDE_ARRAYS_FOR_STREAM_BUFFERS));
}
TEST_F(GpuDriverBugListTest, CurrentListForImagination) {
std::unique_ptr<GpuDriverBugList> list = GpuDriverBugList::Create();
GPUInfo gpu_info;
gpu_info.gl_vendor = "Imagination Technologies";
gpu_info.gl_renderer = "PowerVR SGX 540";
std::set<int> bugs = list->MakeDecision(
GpuControlList::kOsAndroid, "4.1", gpu_info);
EXPECT_EQ(1u, bugs.count(USE_CLIENT_SIDE_ARRAYS_FOR_STREAM_BUFFERS));
}
#endif // OS_ANDROID
TEST_F(GpuDriverBugListTest, AppendSingleWorkaround) {
base::CommandLine command_line(0, NULL);
command_line.AppendSwitch(GpuDriverBugWorkaroundTypeToString(
DISABLE_CHROMIUM_FRAMEBUFFER_MULTISAMPLE));
std::set<int> workarounds;
workarounds.insert(EXIT_ON_CONTEXT_LOST);
workarounds.insert(INIT_VERTEX_ATTRIBUTES);
EXPECT_EQ(2u, workarounds.size());
GpuDriverBugList::AppendWorkaroundsFromCommandLine(
&workarounds, command_line);
EXPECT_EQ(3u, workarounds.size());
EXPECT_EQ(1u, workarounds.count(DISABLE_CHROMIUM_FRAMEBUFFER_MULTISAMPLE));
}
TEST_F(GpuDriverBugListTest, AppendForceGPUWorkaround) {
base::CommandLine command_line(0, NULL);
command_line.AppendSwitch(
GpuDriverBugWorkaroundTypeToString(FORCE_DISCRETE_GPU));
std::set<int> workarounds;
workarounds.insert(EXIT_ON_CONTEXT_LOST);
workarounds.insert(FORCE_INTEGRATED_GPU);
EXPECT_EQ(2u, workarounds.size());
EXPECT_EQ(1u, workarounds.count(FORCE_INTEGRATED_GPU));
GpuDriverBugList::AppendWorkaroundsFromCommandLine(
&workarounds, command_line);
EXPECT_EQ(2u, workarounds.size());
EXPECT_EQ(0u, workarounds.count(FORCE_INTEGRATED_GPU));
EXPECT_EQ(1u, workarounds.count(FORCE_DISCRETE_GPU));
}
// Test for invariant "Assume the newly last added entry has the largest ID".
// See GpuControlList::GpuControlList.
// It checks gpu_driver_bug_list.json
TEST_F(GpuDriverBugListTest, TestBlacklistIsValid) {
std::unique_ptr<GpuDriverBugList> list(GpuDriverBugList::Create());
auto max_entry_id = list->max_entry_id();
std::vector<uint32_t> indices(list->num_entries());
int current = 0;
std::generate(indices.begin(), indices.end(),
[¤t] () { return current++; });
auto entries = list->GetEntryIDsFromIndices(indices);
auto real_max_entry_id = *std::max_element(entries.begin(), entries.end());
EXPECT_EQ(real_max_entry_id, max_entry_id);
}
} // namespace gpu
|
/*
* Copyright 2012 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkMagnifierImageFilter.h"
#include "SkBitmap.h"
#include "SkColorData.h"
#include "SkColorSpaceXformer.h"
#include "SkImageFilterPriv.h"
#include "SkReadBuffer.h"
#include "SkSpecialImage.h"
#include "SkWriteBuffer.h"
#include "SkValidationUtils.h"
////////////////////////////////////////////////////////////////////////////////
#if SK_SUPPORT_GPU
#include "../private/GrGLSL.h"
#include "GrColorSpaceXform.h"
#include "GrContext.h"
#include "GrCoordTransform.h"
#include "GrTexture.h"
#include "effects/GrMagnifierEffect.h"
#include "glsl/GrGLSLFragmentProcessor.h"
#include "glsl/GrGLSLFragmentShaderBuilder.h"
#include "glsl/GrGLSLProgramDataManager.h"
#include "glsl/GrGLSLUniformHandler.h"
#endif
sk_sp<SkImageFilter> SkMagnifierImageFilter::Make(const SkRect& srcRect, SkScalar inset,
sk_sp<SkImageFilter> input,
const CropRect* cropRect) {
if (!SkScalarIsFinite(inset) || !SkIsValidRect(srcRect)) {
return nullptr;
}
if (inset < 0) {
return nullptr;
}
// Negative numbers in src rect are not supported
if (srcRect.fLeft < 0 || srcRect.fTop < 0) {
return nullptr;
}
return sk_sp<SkImageFilter>(new SkMagnifierImageFilter(srcRect, inset,
std::move(input),
cropRect));
}
////////////////////////////////////////////////////////////////////////////////
SkMagnifierImageFilter::SkMagnifierImageFilter(const SkRect& srcRect,
SkScalar inset,
sk_sp<SkImageFilter> input,
const CropRect* cropRect)
: INHERITED(&input, 1, cropRect)
, fSrcRect(srcRect)
, fInset(inset) {
SkASSERT(srcRect.left() >= 0 && srcRect.top() >= 0 && inset >= 0);
}
sk_sp<SkFlattenable> SkMagnifierImageFilter::CreateProc(SkReadBuffer& buffer) {
SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);
SkRect src;
buffer.readRect(&src);
return Make(src, buffer.readScalar(), common.getInput(0), &common.cropRect());
}
void SkMagnifierImageFilter::flatten(SkWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeRect(fSrcRect);
buffer.writeScalar(fInset);
}
sk_sp<SkSpecialImage> SkMagnifierImageFilter::onFilterImage(SkSpecialImage* source,
const Context& ctx,
SkIPoint* offset) const {
SkIPoint inputOffset = SkIPoint::Make(0, 0);
sk_sp<SkSpecialImage> input(this->filterInput(0, source, ctx, &inputOffset));
if (!input) {
return nullptr;
}
const SkIRect inputBounds = SkIRect::MakeXYWH(inputOffset.x(), inputOffset.y(),
input->width(), input->height());
SkIRect bounds;
if (!this->applyCropRect(ctx, inputBounds, &bounds)) {
return nullptr;
}
SkScalar invInset = fInset > 0 ? SkScalarInvert(fInset) : SK_Scalar1;
SkScalar invXZoom = fSrcRect.width() / bounds.width();
SkScalar invYZoom = fSrcRect.height() / bounds.height();
#if SK_SUPPORT_GPU
if (source->isTextureBacked()) {
GrContext* context = source->getContext();
sk_sp<GrTextureProxy> inputProxy(input->asTextureProxyRef(context));
SkASSERT(inputProxy);
offset->fX = bounds.left();
offset->fY = bounds.top();
bounds.offset(-inputOffset);
GrPixelConfig inputConfig = inputProxy->config();
auto fp = GrMagnifierEffect::Make(std::move(inputProxy),
bounds,
fSrcRect,
invXZoom,
invYZoom,
bounds.width() * invInset,
bounds.height() * invInset);
fp = GrColorSpaceXformEffect::Make(std::move(fp), input->getColorSpace(),
inputConfig, ctx.outputProperties().colorSpace());
if (!fp) {
return nullptr;
}
return DrawWithFP(context, std::move(fp), bounds, ctx.outputProperties());
}
#endif
SkBitmap inputBM;
if (!input->getROPixels(&inputBM)) {
return nullptr;
}
if ((inputBM.colorType() != kN32_SkColorType) ||
(fSrcRect.width() >= inputBM.width()) || (fSrcRect.height() >= inputBM.height())) {
return nullptr;
}
SkASSERT(inputBM.getPixels());
if (!inputBM.getPixels() || inputBM.width() <= 0 || inputBM.height() <= 0) {
return nullptr;
}
const SkImageInfo info = SkImageInfo::MakeN32Premul(bounds.width(), bounds.height());
SkBitmap dst;
if (!dst.tryAllocPixels(info)) {
return nullptr;
}
SkColor* dptr = dst.getAddr32(0, 0);
int dstWidth = dst.width(), dstHeight = dst.height();
for (int y = 0; y < dstHeight; ++y) {
for (int x = 0; x < dstWidth; ++x) {
SkScalar x_dist = SkMin32(x, dstWidth - x - 1) * invInset;
SkScalar y_dist = SkMin32(y, dstHeight - y - 1) * invInset;
SkScalar weight = 0;
static const SkScalar kScalar2 = SkScalar(2);
// To create a smooth curve at the corners, we need to work on
// a square twice the size of the inset.
if (x_dist < kScalar2 && y_dist < kScalar2) {
x_dist = kScalar2 - x_dist;
y_dist = kScalar2 - y_dist;
SkScalar dist = SkScalarSqrt(SkScalarSquare(x_dist) +
SkScalarSquare(y_dist));
dist = SkMaxScalar(kScalar2 - dist, 0);
weight = SkMinScalar(SkScalarSquare(dist), SK_Scalar1);
} else {
SkScalar sqDist = SkMinScalar(SkScalarSquare(x_dist),
SkScalarSquare(y_dist));
weight = SkMinScalar(sqDist, SK_Scalar1);
}
SkScalar x_interp = weight * (fSrcRect.x() + x * invXZoom) + (1 - weight) * x;
SkScalar y_interp = weight * (fSrcRect.y() + y * invYZoom) + (1 - weight) * y;
int x_val = SkTPin(bounds.x() + SkScalarFloorToInt(x_interp), 0, inputBM.width() - 1);
int y_val = SkTPin(bounds.y() + SkScalarFloorToInt(y_interp), 0, inputBM.height() - 1);
*dptr = *inputBM.getAddr32(x_val, y_val);
dptr++;
}
}
offset->fX = bounds.left();
offset->fY = bounds.top();
return SkSpecialImage::MakeFromRaster(SkIRect::MakeWH(bounds.width(), bounds.height()),
dst);
}
sk_sp<SkImageFilter> SkMagnifierImageFilter::onMakeColorSpace(SkColorSpaceXformer* xformer) const {
SkASSERT(1 == this->countInputs());
auto input = xformer->apply(this->getInput(0));
if (input.get() != this->getInput(0)) {
return SkMagnifierImageFilter::Make(fSrcRect, fInset, std::move(input),
this->getCropRectIfSet());
}
return this->refMe();
}
#ifndef SK_IGNORE_TO_STRING
void SkMagnifierImageFilter::toString(SkString* str) const {
str->appendf("SkMagnifierImageFilter: (");
str->appendf("src: (%f,%f,%f,%f) ",
fSrcRect.fLeft, fSrcRect.fTop, fSrcRect.fRight, fSrcRect.fBottom);
str->appendf("inset: %f", fInset);
str->append(")");
}
#endif
|
// Copyright (c) 2014-2019 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "masternode/activemasternode.h"
#include "init.h"
#include "instantsend.h"
#include "key.h"
#include "validation.h"
#include "masternode/masternode-payments.h"
#include "masternode/masternode-sync.h"
#include "masternode/masternode-utils.h"
#include "messagesigner.h"
#include "net.h"
#include "netmessagemaker.h"
#include "protocol.h"
#include "spork.h"
#include "sync.h"
#include "txmempool.h"
#include "util.h"
#include "consensus/validation.h"
#include "validationinterface.h"
#include "warnings.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif // ENABLE_WALLET
#include "llmq/quorums_instantsend.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/thread.hpp>
#ifdef ENABLE_WALLET
extern CWallet* pwalletMain;
#endif // ENABLE_WALLET
extern CTxMemPool mempool;
bool fEnableInstantSend = true;
std::atomic<bool> CInstantSend::isAutoLockBip9Active{false};
const double CInstantSend::AUTO_IX_MEMPOOL_THRESHOLD = 0.1;
CInstantSend instantsend;
const std::string CInstantSend::SERIALIZATION_VERSION_STRING = "CInstantSend-Version-1";
// Transaction Locks
//
// step 1) Some node announces intention to lock transaction inputs via "txlockrequest" message (ix)
// step 2) Top nInstantSendSigsTotal masternodes per each spent outpoint push "txlockvote" message (txlvote)
// step 3) Once there are nInstantSendSigsRequired valid "txlockvote" messages (txlvote) per each spent outpoint
// for a corresponding "txlockrequest" message (ix), all outpoints from that tx are treated as locked
//
// CInstantSend
//
void CInstantSend::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman)
{
if (fLiteMode) return; // disable all Dash specific functionality
if (!llmq::IsOldInstantSendEnabled()) return;
// NOTE: NetMsgType::TXLOCKREQUEST is handled via ProcessMessage() in net_processing.cpp
if (strCommand == NetMsgType::TXLOCKVOTE) { // InstantSend Transaction Lock Consensus Votes
if(pfrom->nVersion < MIN_INSTANTSEND_PROTO_VERSION) {
LogPrint(BCLog::INSTANTSEND, "TXLOCKVOTE -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion);
connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
strprintf("Version must be %d or greater", MIN_INSTANTSEND_PROTO_VERSION)));
return;
}
CTxLockVote vote;
vRecv >> vote;
uint256 nVoteHash = vote.GetHash();
{
LOCK(cs_main);
connman.RemoveAskFor(nVoteHash);
}
// Ignore any InstantSend messages until blockchain is synced
if (!masternodeSync.IsBlockchainSynced()) return;
{
LOCK(cs_instantsend);
auto ret = mapTxLockVotes.emplace(nVoteHash, vote);
if (!ret.second) return;
}
ProcessNewTxLockVote(pfrom, vote, connman);
return;
}
}
bool CInstantSend::ProcessTxLockRequest(const CTxLockRequest& txLockRequest, CConnman& connman)
{
LOCK(cs_main);
#ifdef ENABLE_WALLET
LOCK(pwalletMain ? &pwalletMain->cs_wallet : NULL);
#endif
LOCK2(mempool.cs, cs_instantsend);
uint256 txHash = txLockRequest.GetHash();
// Check to see if we conflict with existing completed lock
for (const auto& txin : txLockRequest.tx->vin) {
std::map<COutPoint, uint256>::iterator it = mapLockedOutpoints.find(txin.prevout);
if (it != mapLockedOutpoints.end() && it->second != txLockRequest.GetHash()) {
// Conflicting with complete lock, proceed to see if we should cancel them both
LogPrintf("CInstantSend::ProcessTxLockRequest -- WARNING: Found conflicting completed Transaction Lock, txid=%s, completed lock txid=%s\n",
txLockRequest.GetHash().ToString(), it->second.ToString());
}
}
// Check to see if there are votes for conflicting request,
// if so - do not fail, just warn user
for (const auto& txin : txLockRequest.tx->vin) {
std::map<COutPoint, std::set<uint256> >::iterator it = mapVotedOutpoints.find(txin.prevout);
if (it != mapVotedOutpoints.end()) {
for (const auto& hash : it->second) {
if (hash != txLockRequest.GetHash()) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::ProcessTxLockRequest -- Double spend attempt! %s\n", txin.prevout.ToStringShort());
// do not fail here, let it go and see which one will get the votes to be locked
// NOTIFY ZMQ
CTransaction txCurrent = *txLockRequest.tx; // currently processed tx
auto itPrevious = mapTxLockCandidates.find(hash);
if (itPrevious != mapTxLockCandidates.end() && itPrevious->second.txLockRequest) {
CTransaction txPrevious = *itPrevious->second.txLockRequest.tx; // previously locked one
GetMainSignals().NotifyInstantSendDoubleSpendAttempt(txCurrent, txPrevious);
}
}
}
}
}
if (!CreateTxLockCandidate(txLockRequest)) {
// smth is not right
LogPrintf("CInstantSend::ProcessTxLockRequest -- CreateTxLockCandidate failed, txid=%s\n", txHash.ToString());
return false;
}
LogPrintf("CInstantSend::ProcessTxLockRequest -- accepted, txid=%s\n", txHash.ToString());
// Masternodes will sometimes propagate votes before the transaction is known to the client.
// If this just happened - process orphan votes, lock inputs, resolve conflicting locks,
// update transaction status forcing external script/zmq notifications.
ProcessOrphanTxLockVotes();
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
TryToFinalizeLockCandidate(itLockCandidate->second);
return true;
}
bool CInstantSend::CreateTxLockCandidate(const CTxLockRequest& txLockRequest)
{
if (!txLockRequest.IsValid()) return false;
LOCK(cs_instantsend);
uint256 txHash = txLockRequest.GetHash();
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate == mapTxLockCandidates.end()) {
LogPrintf("CInstantSend::CreateTxLockCandidate -- new, txid=%s\n", txHash.ToString());
CTxLockCandidate txLockCandidate(txLockRequest);
// all inputs should already be checked by txLockRequest.IsValid() above, just use them now
for (const auto& txin : txLockRequest.tx->vin) {
txLockCandidate.AddOutPointLock(txin.prevout);
}
mapTxLockCandidates.insert(std::make_pair(txHash, txLockCandidate));
} else if (!itLockCandidate->second.txLockRequest) {
// i.e. empty Transaction Lock Candidate was created earlier, let's update it with actual data
itLockCandidate->second.txLockRequest = txLockRequest;
if (itLockCandidate->second.IsTimedOut()) {
LogPrintf("CInstantSend::CreateTxLockCandidate -- timed out, txid=%s\n", txHash.ToString());
return false;
}
LogPrintf("CInstantSend::CreateTxLockCandidate -- update empty, txid=%s\n", txHash.ToString());
// all inputs should already be checked by txLockRequest.IsValid() above, just use them now
for (const auto& txin : txLockRequest.tx->vin) {
itLockCandidate->second.AddOutPointLock(txin.prevout);
}
} else {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::CreateTxLockCandidate -- seen, txid=%s\n", txHash.ToString());
}
return true;
}
void CInstantSend::CreateEmptyTxLockCandidate(const uint256& txHash)
{
if (mapTxLockCandidates.find(txHash) != mapTxLockCandidates.end())
return;
LogPrintf("CInstantSend::CreateEmptyTxLockCandidate -- new, txid=%s\n", txHash.ToString());
const CTxLockRequest txLockRequest = CTxLockRequest();
mapTxLockCandidates.insert(std::make_pair(txHash, CTxLockCandidate(txLockRequest)));
}
void CInstantSend::Vote(const uint256& txHash, CConnman& connman)
{
AssertLockHeld(cs_main);
#ifdef ENABLE_WALLET
LOCK(pwalletMain ? &pwalletMain->cs_wallet : NULL);
#endif
CTxLockRequest dummyRequest;
CTxLockCandidate txLockCandidate(dummyRequest);
{
LOCK(cs_instantsend);
auto itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate == mapTxLockCandidates.end()) return;
txLockCandidate = itLockCandidate->second;
Vote(txLockCandidate, connman);
}
// Let's see if our vote changed smth
LOCK2(mempool.cs, cs_instantsend);
TryToFinalizeLockCandidate(txLockCandidate);
}
void CInstantSend::Vote(CTxLockCandidate& txLockCandidate, CConnman& connman)
{
if (!fMasternodeMode) return;
if (!llmq::IsOldInstantSendEnabled()) return;
AssertLockHeld(cs_main);
AssertLockHeld(cs_instantsend);
uint256 txHash = txLockCandidate.GetHash();
// We should never vote on a Transaction Lock Request that was not (yet) accepted by the mempool
if (mapLockRequestAccepted.find(txHash) == mapLockRequestAccepted.end()) return;
// check if we need to vote on this candidate's outpoints,
// it's possible that we need to vote for several of them
for (auto& outpointLockPair : txLockCandidate.mapOutPointLocks) {
int nPrevoutHeight = GetUTXOHeight(outpointLockPair.first);
if (nPrevoutHeight == -1) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::Vote -- Failed to find UTXO %s\n", outpointLockPair.first.ToStringShort());
return;
}
int nLockInputHeight = nPrevoutHeight + Params().GetConsensus().nInstantSendConfirmationsRequired - 2;
int nRank;
uint256 quorumModifierHash;
if (!CMasternodeUtils::GetMasternodeRank(activeMasternodeInfo.outpoint, nRank, quorumModifierHash, nLockInputHeight)) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::Vote -- Can't calculate rank for masternode %s\n", activeMasternodeInfo.outpoint.ToStringShort());
continue;
}
int nSignaturesTotal = Params().GetConsensus().nInstantSendSigsTotal;
if (nRank > nSignaturesTotal) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::Vote -- Masternode not in the top %d (%d)\n", nSignaturesTotal, nRank);
continue;
}
LogPrint(BCLog::INSTANTSEND, "CInstantSend::Vote -- In the top %d (%d)\n", nSignaturesTotal, nRank);
std::map<COutPoint, std::set<uint256> >::iterator itVoted = mapVotedOutpoints.find(outpointLockPair.first);
// Check to see if we already voted for this outpoint,
// refuse to vote twice or to include the same outpoint in another tx
bool fAlreadyVoted = false;
if (itVoted != mapVotedOutpoints.end()) {
for (const auto& hash : itVoted->second) {
std::map<uint256, CTxLockCandidate>::iterator it2 = mapTxLockCandidates.find(hash);
if (it2->second.HasMasternodeVoted(outpointLockPair.first, activeMasternodeInfo.outpoint)) {
// we already voted for this outpoint to be included either in the same tx or in a competing one,
// skip it anyway
fAlreadyVoted = true;
LogPrintf("CInstantSend::Vote -- WARNING: We already voted for this outpoint, skipping: txHash=%s, outpoint=%s\n",
txHash.ToString(), outpointLockPair.first.ToStringShort());
break;
}
}
}
if (fAlreadyVoted) {
continue; // skip to the next outpoint
}
// we haven't voted for this outpoint yet, let's try to do this now
// Please note that activeMasternodeInfo.proTxHash is only valid after spork15 activation
CTxLockVote vote(txHash, outpointLockPair.first, activeMasternodeInfo.outpoint, quorumModifierHash, activeMasternodeInfo.proTxHash);
if (!vote.Sign()) {
LogPrintf("CInstantSend::Vote -- Failed to sign consensus vote\n");
return;
}
if (!vote.CheckSignature()) {
LogPrintf("CInstantSend::Vote -- Signature invalid\n");
return;
}
// vote constructed sucessfully, let's store and relay it
uint256 nVoteHash = vote.GetHash();
mapTxLockVotes.insert(std::make_pair(nVoteHash, vote));
if (outpointLockPair.second.AddVote(vote)) {
LogPrintf("CInstantSend::Vote -- Vote created successfully, relaying: txHash=%s, outpoint=%s, vote=%s\n",
txHash.ToString(), outpointLockPair.first.ToStringShort(), nVoteHash.ToString());
if (itVoted == mapVotedOutpoints.end()) {
std::set<uint256> setHashes;
setHashes.insert(txHash);
mapVotedOutpoints.insert(std::make_pair(outpointLockPair.first, setHashes));
} else {
mapVotedOutpoints[outpointLockPair.first].insert(txHash);
if (mapVotedOutpoints[outpointLockPair.first].size() > 1) {
// it's ok to continue, just warn user
LogPrintf("CInstantSend::Vote -- WARNING: Vote conflicts with some existing votes: txHash=%s, outpoint=%s, vote=%s\n",
txHash.ToString(), outpointLockPair.first.ToStringShort(), nVoteHash.ToString());
}
}
vote.Relay(connman);
}
}
}
bool CInstantSend::ProcessNewTxLockVote(CNode* pfrom, const CTxLockVote& vote, CConnman& connman)
{
uint256 txHash = vote.GetTxHash();
uint256 nVoteHash = vote.GetHash();
if (!vote.IsValid(pfrom, connman)) {
// could be because of missing MN
LogPrint(BCLog::INSTANTSEND, "CInstantSend::%s -- Vote is invalid, txid=%s\n", __func__, txHash.ToString());
return false;
}
// relay valid vote asap
vote.Relay(connman);
LOCK(cs_main);
#ifdef ENABLE_WALLET
LOCK(pwalletMain ? &pwalletMain->cs_wallet : NULL);
#endif
LOCK2(mempool.cs, cs_instantsend);
// Masternodes will sometimes propagate votes before the transaction is known to the client,
// will actually process only after the lock request itself has arrived
std::map<uint256, CTxLockCandidate>::iterator it = mapTxLockCandidates.find(txHash);
if (it == mapTxLockCandidates.end() || !it->second.txLockRequest) {
// no or empty tx lock candidate
if (it == mapTxLockCandidates.end()) {
// start timeout countdown after the very first vote
CreateEmptyTxLockCandidate(txHash);
}
bool fInserted = mapTxLockVotesOrphan.emplace(nVoteHash, vote).second;
LogPrint(BCLog::INSTANTSEND, "CInstantSend::%s -- Orphan vote: txid=%s masternode=%s %s\n",
__func__, txHash.ToString(), vote.GetMasternodeOutpoint().ToStringShort(), fInserted ? "new" : "seen");
// This tracks those messages and allows only the same rate as of the rest of the network
// TODO: make sure this works good enough for multi-quorum
int nMasternodeOrphanExpireTime = GetTime() + 60*10; // keep time data for 10 minutes
auto itMnOV = mapMasternodeOrphanVotes.find(vote.GetMasternodeOutpoint());
if (itMnOV == mapMasternodeOrphanVotes.end()) {
mapMasternodeOrphanVotes.emplace(vote.GetMasternodeOutpoint(), nMasternodeOrphanExpireTime);
} else {
if (itMnOV->second > GetTime() && itMnOV->second > GetAverageMasternodeOrphanVoteTime()) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::%s -- masternode is spamming orphan Transaction Lock Votes: txid=%s masternode=%s\n",
__func__, txHash.ToString(), vote.GetMasternodeOutpoint().ToStringShort());
// Misbehaving(pfrom->id, 1);
return false;
}
// not spamming, refresh
itMnOV->second = nMasternodeOrphanExpireTime;
}
return true;
}
// We have a valid (non-empty) tx lock candidate
CTxLockCandidate& txLockCandidate = it->second;
if (txLockCandidate.IsTimedOut()) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::%s -- too late, Transaction Lock timed out, txid=%s\n", __func__, txHash.ToString());
return false;
}
LogPrint(BCLog::INSTANTSEND, "CInstantSend::%s -- Transaction Lock Vote, txid=%s\n", __func__, txHash.ToString());
UpdateVotedOutpoints(vote, txLockCandidate);
if (!txLockCandidate.AddVote(vote)) {
// this should never happen
return false;
}
int nSignatures = txLockCandidate.CountVotes();
int nSignaturesMax = txLockCandidate.txLockRequest.GetMaxSignatures();
LogPrint(BCLog::INSTANTSEND, "CInstantSend::%s -- Transaction Lock signatures count: %d/%d, vote hash=%s\n", __func__,
nSignatures, nSignaturesMax, nVoteHash.ToString());
TryToFinalizeLockCandidate(txLockCandidate);
return true;
}
bool CInstantSend::ProcessOrphanTxLockVote(const CTxLockVote& vote)
{
// cs_main, cs_wallet and cs_instantsend should be already locked
AssertLockHeld(cs_main);
#ifdef ENABLE_WALLET
if (pwalletMain)
AssertLockHeld(pwalletMain->cs_wallet);
#endif
AssertLockHeld(cs_instantsend);
uint256 txHash = vote.GetTxHash();
// We shouldn't process orphan votes without a valid tx lock candidate
std::map<uint256, CTxLockCandidate>::iterator it = mapTxLockCandidates.find(txHash);
if (it == mapTxLockCandidates.end() || !it->second.txLockRequest)
return false; // this shouldn never happen
CTxLockCandidate& txLockCandidate = it->second;
if (txLockCandidate.IsTimedOut()) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::%s -- too late, Transaction Lock timed out, txid=%s\n", __func__, txHash.ToString());
return false;
}
LogPrint(BCLog::INSTANTSEND, "CInstantSend::%s -- Transaction Lock Vote, txid=%s\n", __func__, txHash.ToString());
UpdateVotedOutpoints(vote, txLockCandidate);
if (!txLockCandidate.AddVote(vote)) {
// this should never happen
return false;
}
int nSignatures = txLockCandidate.CountVotes();
int nSignaturesMax = txLockCandidate.txLockRequest.GetMaxSignatures();
LogPrint(BCLog::INSTANTSEND, "CInstantSend::%s -- Transaction Lock signatures count: %d/%d, vote hash=%s\n",
__func__, nSignatures, nSignaturesMax, vote.GetHash().ToString());
return true;
}
void CInstantSend::UpdateVotedOutpoints(const CTxLockVote& vote, CTxLockCandidate& txLockCandidate)
{
AssertLockHeld(cs_instantsend);
uint256 txHash = vote.GetTxHash();
std::map<COutPoint, std::set<uint256> >::iterator it1 = mapVotedOutpoints.find(vote.GetOutpoint());
if (it1 != mapVotedOutpoints.end()) {
for (const auto& hash : it1->second) {
if (hash != txHash) {
// same outpoint was already voted to be locked by another tx lock request,
// let's see if it was the same masternode who voted on this outpoint
// for another tx lock request
std::map<uint256, CTxLockCandidate>::iterator it2 = mapTxLockCandidates.find(hash);
if (it2 !=mapTxLockCandidates.end() && it2->second.HasMasternodeVoted(vote.GetOutpoint(), vote.GetMasternodeOutpoint())) {
// yes, it was the same masternode
LogPrintf("CInstantSend::%s -- masternode sent conflicting votes! %s\n", __func__, vote.GetMasternodeOutpoint().ToStringShort());
// mark both Lock Candidates as attacked, none of them should complete,
// or at least the new (current) one shouldn't even
// if the second one was already completed earlier
txLockCandidate.MarkOutpointAsAttacked(vote.GetOutpoint());
it2->second.MarkOutpointAsAttacked(vote.GetOutpoint());
// apply maximum PoSe ban score to this masternode i.e. PoSe-ban it instantly
// TODO Call new PoSe system when it's ready
//mnodeman.PoSeBan(vote.GetMasternodeOutpoint());
// NOTE: This vote must be relayed further to let all other nodes know about such
// misbehaviour of this masternode. This way they should also be able to construct
// conflicting lock and PoSe-ban this masternode.
}
}
}
// store all votes, regardless of them being sent by malicious masternode or not
it1->second.insert(txHash);
} else {
mapVotedOutpoints.emplace(vote.GetOutpoint(), std::set<uint256>({txHash}));
}
}
void CInstantSend::ProcessOrphanTxLockVotes()
{
AssertLockHeld(cs_main);
AssertLockHeld(cs_instantsend);
std::map<uint256, CTxLockVote>::iterator it = mapTxLockVotesOrphan.begin();
while (it != mapTxLockVotesOrphan.end()) {
if (ProcessOrphanTxLockVote(it->second)) {
mapTxLockVotesOrphan.erase(it++);
} else {
++it;
}
}
}
void CInstantSend::TryToFinalizeLockCandidate(const CTxLockCandidate& txLockCandidate)
{
if (!llmq::IsOldInstantSendEnabled()) return;
AssertLockHeld(cs_main);
AssertLockHeld(cs_instantsend);
uint256 txHash = txLockCandidate.txLockRequest.tx->GetHash();
if (txLockCandidate.IsAllOutPointsReady() && !IsLockedInstantSendTransaction(txHash)) {
// we have enough votes now
LogPrint(BCLog::INSTANTSEND, "CInstantSend::TryToFinalizeLockCandidate -- Transaction Lock is ready to complete, txid=%s\n", txHash.ToString());
if (ResolveConflicts(txLockCandidate)) {
LockTransactionInputs(txLockCandidate);
UpdateLockedTransaction(txLockCandidate);
}
}
}
void CInstantSend::UpdateLockedTransaction(const CTxLockCandidate& txLockCandidate)
{
// cs_main, cs_wallet and cs_instantsend should be already locked
AssertLockHeld(cs_main);
#ifdef ENABLE_WALLET
if (pwalletMain) {
AssertLockHeld(pwalletMain->cs_wallet);
}
#endif
AssertLockHeld(cs_instantsend);
uint256 txHash = txLockCandidate.GetHash();
if (!IsLockedInstantSendTransaction(txHash)) return; // not a locked tx, do not update/notify
#ifdef ENABLE_WALLET
if (pwalletMain && pwalletMain->UpdatedTransaction(txHash)) {
// notify an external script once threshold is reached
std::string strCmd = GetArg("-instantsendnotify", "");
if (!strCmd.empty()) {
boost::replace_all(strCmd, "%s", txHash.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
}
#endif
llmq::CInstantSendLock islock;
GetMainSignals().NotifyTransactionLock(*txLockCandidate.txLockRequest.tx, islock);
LogPrint(BCLog::INSTANTSEND, "CInstantSend::UpdateLockedTransaction -- done, txid=%s\n", txHash.ToString());
}
void CInstantSend::LockTransactionInputs(const CTxLockCandidate& txLockCandidate)
{
if (!llmq::IsOldInstantSendEnabled()) return;
LOCK(cs_instantsend);
uint256 txHash = txLockCandidate.GetHash();
if (!txLockCandidate.IsAllOutPointsReady()) return;
for (const auto& pair : txLockCandidate.mapOutPointLocks) {
mapLockedOutpoints.insert(std::make_pair(pair.first, txHash));
}
LogPrint(BCLog::INSTANTSEND, "CInstantSend::LockTransactionInputs -- done, txid=%s\n", txHash.ToString());
}
bool CInstantSend::GetLockedOutPointTxHash(const COutPoint& outpoint, uint256& hashRet)
{
LOCK(cs_instantsend);
std::map<COutPoint, uint256>::iterator it = mapLockedOutpoints.find(outpoint);
if (it == mapLockedOutpoints.end()) return false;
hashRet = it->second;
return true;
}
bool CInstantSend::ResolveConflicts(const CTxLockCandidate& txLockCandidate)
{
AssertLockHeld(cs_main);
AssertLockHeld(cs_instantsend);
uint256 txHash = txLockCandidate.GetHash();
// make sure the lock is ready
if (!txLockCandidate.IsAllOutPointsReady()) return false;
AssertLockHeld(mempool.cs); // protect mempool.mapNextTx
for (const auto& txin : txLockCandidate.txLockRequest.tx->vin) {
uint256 hashConflicting;
if (GetLockedOutPointTxHash(txin.prevout, hashConflicting) && txHash != hashConflicting) {
// completed lock which conflicts with another completed one?
// this means that majority of MNs in the quorum for this specific tx input are malicious!
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
std::map<uint256, CTxLockCandidate>::iterator itLockCandidateConflicting = mapTxLockCandidates.find(hashConflicting);
if (itLockCandidate == mapTxLockCandidates.end() || itLockCandidateConflicting == mapTxLockCandidates.end()) {
// safety check, should never really happen
LogPrintf("CInstantSend::ResolveConflicts -- ERROR: Found conflicting completed Transaction Lock, but one of txLockCandidate-s is missing, txid=%s, conflicting txid=%s\n",
txHash.ToString(), hashConflicting.ToString());
return false;
}
LogPrintf("CInstantSend::ResolveConflicts -- WARNING: Found conflicting completed Transaction Lock, dropping both, txid=%s, conflicting txid=%s\n",
txHash.ToString(), hashConflicting.ToString());
CTxLockRequest txLockRequest = itLockCandidate->second.txLockRequest;
CTxLockRequest txLockRequestConflicting = itLockCandidateConflicting->second.txLockRequest;
itLockCandidate->second.SetConfirmedHeight(0); // expired
itLockCandidateConflicting->second.SetConfirmedHeight(0); // expired
CheckAndRemove(); // clean up
// AlreadyHave should still return "true" for both of them
mapLockRequestRejected.insert(std::make_pair(txHash, txLockRequest));
mapLockRequestRejected.insert(std::make_pair(hashConflicting, txLockRequestConflicting));
// TODO: clean up mapLockRequestRejected later somehow
// (not a big issue since we already PoSe ban malicious masternodes
// and they won't be able to spam)
// TODO: ban all malicious masternodes permanently, do not accept anything from them, ever
// TODO: notify zmq+script about this double-spend attempt
// and let merchant cancel/hold the order if it's not too late...
// can't do anything else, fallback to regular txes
return false;
} else if (mempool.mapNextTx.count(txin.prevout)) {
// check if it's in mempool
hashConflicting = mempool.mapNextTx.find(txin.prevout)->second->GetHash();
if (txHash == hashConflicting) continue; // matches current, not a conflict, skip to next txin
// conflicts with tx in mempool
LogPrintf("CInstantSend::ResolveConflicts -- ERROR: Failed to complete Transaction Lock, conflicts with mempool, txid=%s\n", txHash.ToString());
return false;
}
} // FOREACH
// No conflicts were found so far, check to see if it was already included in block
CTransactionRef txTmp;
uint256 hashBlock;
if (GetTransaction(txHash, txTmp, Params().GetConsensus(), hashBlock, true) && hashBlock != uint256()) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::ResolveConflicts -- Done, %s is included in block %s\n", txHash.ToString(), hashBlock.ToString());
return true;
}
// Not in block yet, make sure all its inputs are still unspent
for (const auto& txin : txLockCandidate.txLockRequest.tx->vin) {
Coin coin;
if (!GetUTXOCoin(txin.prevout, coin)) {
// Not in UTXO anymore? A conflicting tx was mined while we were waiting for votes.
LogPrintf("CInstantSend::ResolveConflicts -- ERROR: Failed to find UTXO %s, can't complete Transaction Lock\n", txin.prevout.ToStringShort());
return false;
}
}
LogPrint(BCLog::INSTANTSEND, "CInstantSend::ResolveConflicts -- Done, txid=%s\n", txHash.ToString());
return true;
}
int64_t CInstantSend::GetAverageMasternodeOrphanVoteTime()
{
LOCK(cs_instantsend);
// NOTE: should never actually call this function when mapMasternodeOrphanVotes is empty
if (mapMasternodeOrphanVotes.empty()) return 0;
int64_t total = 0;
for (const auto& pair : mapMasternodeOrphanVotes) {
total += pair.second;
}
return total / mapMasternodeOrphanVotes.size();
}
void CInstantSend::CheckAndRemove()
{
if (!masternodeSync.IsBlockchainSynced()) return;
LOCK(cs_instantsend);
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.begin();
// remove expired candidates
while (itLockCandidate != mapTxLockCandidates.end()) {
CTxLockCandidate &txLockCandidate = itLockCandidate->second;
uint256 txHash = txLockCandidate.GetHash();
if (txLockCandidate.IsExpired(nCachedBlockHeight)) {
LogPrintf("CInstantSend::CheckAndRemove -- Removing expired Transaction Lock Candidate: txid=%s\n", txHash.ToString());
for (const auto& pair : txLockCandidate.mapOutPointLocks) {
mapLockedOutpoints.erase(pair.first);
mapVotedOutpoints.erase(pair.first);
}
mapLockRequestAccepted.erase(txHash);
mapLockRequestRejected.erase(txHash);
mapTxLockCandidates.erase(itLockCandidate++);
} else {
++itLockCandidate;
}
}
// remove expired votes
std::map<uint256, CTxLockVote>::iterator itVote = mapTxLockVotes.begin();
while (itVote != mapTxLockVotes.end()) {
if (itVote->second.IsExpired(nCachedBlockHeight)) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::CheckAndRemove -- Removing expired vote: txid=%s masternode=%s\n",
itVote->second.GetTxHash().ToString(), itVote->second.GetMasternodeOutpoint().ToStringShort());
mapTxLockVotes.erase(itVote++);
} else {
++itVote;
}
}
// remove timed out orphan votes
std::map<uint256, CTxLockVote>::iterator itOrphanVote = mapTxLockVotesOrphan.begin();
while (itOrphanVote != mapTxLockVotesOrphan.end()) {
if (itOrphanVote->second.IsTimedOut()) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::CheckAndRemove -- Removing timed out orphan vote: txid=%s masternode=%s\n",
itOrphanVote->second.GetTxHash().ToString(), itOrphanVote->second.GetMasternodeOutpoint().ToStringShort());
mapTxLockVotes.erase(itOrphanVote->first);
mapTxLockVotesOrphan.erase(itOrphanVote++);
} else {
++itOrphanVote;
}
}
// remove invalid votes and votes for failed lock attempts
itVote = mapTxLockVotes.begin();
while (itVote != mapTxLockVotes.end()) {
if (itVote->second.IsFailed()) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::CheckAndRemove -- Removing vote for failed lock attempt: txid=%s masternode=%s\n",
itVote->second.GetTxHash().ToString(), itVote->second.GetMasternodeOutpoint().ToStringShort());
mapTxLockVotes.erase(itVote++);
} else {
++itVote;
}
}
// remove timed out masternode orphan votes (DOS protection)
std::map<COutPoint, int64_t>::iterator itMasternodeOrphan = mapMasternodeOrphanVotes.begin();
while (itMasternodeOrphan != mapMasternodeOrphanVotes.end()) {
if (itMasternodeOrphan->second < GetTime()) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::CheckAndRemove -- Removing timed out orphan masternode vote: masternode=%s\n",
itMasternodeOrphan->first.ToStringShort());
mapMasternodeOrphanVotes.erase(itMasternodeOrphan++);
} else {
++itMasternodeOrphan;
}
}
LogPrintf("CInstantSend::CheckAndRemove -- %s\n", ToString());
}
bool CInstantSend::AlreadyHave(const uint256& hash)
{
if (!llmq::IsOldInstantSendEnabled()) {
return true;
}
LOCK(cs_instantsend);
return mapLockRequestAccepted.count(hash) ||
mapLockRequestRejected.count(hash) ||
mapTxLockVotes.count(hash);
}
void CInstantSend::AcceptLockRequest(const CTxLockRequest& txLockRequest)
{
LOCK(cs_instantsend);
mapLockRequestAccepted.insert(std::make_pair(txLockRequest.GetHash(), txLockRequest));
}
void CInstantSend::RejectLockRequest(const CTxLockRequest& txLockRequest)
{
LOCK(cs_instantsend);
mapLockRequestRejected.insert(std::make_pair(txLockRequest.GetHash(), txLockRequest));
}
bool CInstantSend::HasTxLockRequest(const uint256& txHash)
{
CTxLockRequest txLockRequestTmp;
return GetTxLockRequest(txHash, txLockRequestTmp);
}
bool CInstantSend::GetTxLockRequest(const uint256& txHash, CTxLockRequest& txLockRequestRet)
{
if (!llmq::IsOldInstantSendEnabled()) {
return false;
}
LOCK(cs_instantsend);
std::map<uint256, CTxLockCandidate>::iterator it = mapTxLockCandidates.find(txHash);
if (it == mapTxLockCandidates.end() || !it->second.txLockRequest) return false;
txLockRequestRet = it->second.txLockRequest;
return true;
}
bool CInstantSend::GetTxLockVote(const uint256& hash, CTxLockVote& txLockVoteRet)
{
if (!llmq::IsOldInstantSendEnabled()) {
return false;
}
LOCK(cs_instantsend);
std::map<uint256, CTxLockVote>::iterator it = mapTxLockVotes.find(hash);
if (it == mapTxLockVotes.end()) return false;
txLockVoteRet = it->second;
return true;
}
void CInstantSend::Clear()
{
LOCK(cs_instantsend);
mapLockRequestAccepted.clear();
mapLockRequestRejected.clear();
mapTxLockVotes.clear();
mapTxLockVotesOrphan.clear();
mapTxLockCandidates.clear();
mapVotedOutpoints.clear();
mapLockedOutpoints.clear();
mapMasternodeOrphanVotes.clear();
nCachedBlockHeight = 0;
}
bool CInstantSend::IsLockedInstantSendTransaction(const uint256& txHash)
{
if (!fEnableInstantSend || GetfLargeWorkForkFound() || GetfLargeWorkInvalidChainFound() ||
!sporkManager.IsSporkActive(SPORK_3_INSTANTSEND_BLOCK_FILTERING)) return false;
LOCK(cs_instantsend);
// there must be a lock candidate
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate == mapTxLockCandidates.end()) return false;
// which should have outpoints
if (itLockCandidate->second.mapOutPointLocks.empty()) return false;
// and all of these outputs must be included in mapLockedOutpoints with correct hash
for (const auto& pair : itLockCandidate->second.mapOutPointLocks) {
uint256 hashLocked;
if (!GetLockedOutPointTxHash(pair.first, hashLocked) || hashLocked != txHash) return false;
}
return true;
}
int CInstantSend::GetTransactionLockSignatures(const uint256& txHash)
{
if (!fEnableInstantSend) return -1;
if (GetfLargeWorkForkFound() || GetfLargeWorkInvalidChainFound()) return -2;
if (!llmq::IsOldInstantSendEnabled()) return -3;
LOCK(cs_instantsend);
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate != mapTxLockCandidates.end()) {
return itLockCandidate->second.CountVotes();
}
return -1;
}
bool CInstantSend::IsTxLockCandidateTimedOut(const uint256& txHash)
{
if (!fEnableInstantSend) return false;
LOCK(cs_instantsend);
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate != mapTxLockCandidates.end()) {
return !itLockCandidate->second.IsAllOutPointsReady() &&
itLockCandidate->second.IsTimedOut();
}
return false;
}
void CInstantSend::Relay(const uint256& txHash, CConnman& connman)
{
LOCK(cs_instantsend);
std::map<uint256, CTxLockCandidate>::const_iterator itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate != mapTxLockCandidates.end()) {
itLockCandidate->second.Relay(connman);
}
}
void CInstantSend::UpdatedBlockTip(const CBlockIndex *pindex)
{
nCachedBlockHeight = pindex->nHeight;
}
void CInstantSend::SyncTransaction(const CTransactionRef& tx, const CBlockIndex* pindex, int posInBlock)
{
// Update lock candidates and votes if corresponding tx confirmed
// or went from confirmed to 0-confirmed or conflicted.
if (tx->IsCoinBase()) return;
LOCK2(cs_main, cs_instantsend);
uint256 txHash = tx->GetHash();
// When tx is 0-confirmed or conflicted, posInBlock is -1 and nHeightNew should be set to -1
int nHeightNew = (posInBlock == -1 || pindex == nullptr) ? -1 : pindex->nHeight;
LogPrint(BCLog::INSTANTSEND, "CInstantSend::SyncTransaction -- txid=%s nHeightNew=%d\n", txHash.ToString(), nHeightNew);
// Check lock candidates
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate != mapTxLockCandidates.end()) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::SyncTransaction -- txid=%s nHeightNew=%d lock candidate updated\n",
txHash.ToString(), nHeightNew);
itLockCandidate->second.SetConfirmedHeight(nHeightNew);
// Loop through outpoint locks
for (const auto& pair : itLockCandidate->second.mapOutPointLocks) {
// Check corresponding lock votes
for (const auto& vote : pair.second.GetVotes()) {
uint256 nVoteHash = vote.GetHash();
LogPrint(BCLog::INSTANTSEND, "CInstantSend::SyncTransaction -- txid=%s nHeightNew=%d vote %s updated\n",
txHash.ToString(), nHeightNew, nVoteHash.ToString());
const auto& it = mapTxLockVotes.find(nVoteHash);
if (it != mapTxLockVotes.end()) {
it->second.SetConfirmedHeight(nHeightNew);
}
}
}
}
// check orphan votes
for (const auto& pair : mapTxLockVotesOrphan) {
if (pair.second.GetTxHash() == txHash) {
LogPrint(BCLog::INSTANTSEND, "CInstantSend::SyncTransaction -- txid=%s nHeightNew=%d vote %s updated\n",
txHash.ToString(), nHeightNew, pair.first.ToString());
mapTxLockVotes[pair.first].SetConfirmedHeight(nHeightNew);
}
}
}
std::string CInstantSend::ToString() const
{
LOCK(cs_instantsend);
return strprintf("Lock Candidates: %llu, Votes %llu", mapTxLockCandidates.size(), mapTxLockVotes.size());
}
void CInstantSend::DoMaintenance()
{
if (ShutdownRequested()) return;
CheckAndRemove();
}
bool CInstantSend::CanAutoLock()
{
if (!isAutoLockBip9Active || !llmq::IsOldInstantSendEnabled()) {
return false;
}
if (!sporkManager.IsSporkActive(SPORK_16_INSTANTSEND_AUTOLOCKS)) {
return false;
}
return (mempool.UsedMemoryShare() < AUTO_IX_MEMPOOL_THRESHOLD);
}
//
// CTxLockRequest
//
bool CTxLockRequest::IsValid() const
{
if (tx->vout.size() < 1) return false;
if (tx->vin.size() > WARN_MANY_INPUTS) {
LogPrint(BCLog::INSTANTSEND, "CTxLockRequest::IsValid -- WARNING: Too many inputs: tx=%s", ToString());
}
AssertLockHeld(cs_main);
if (!CheckFinalTx(*tx)) {
LogPrint(BCLog::INSTANTSEND, "CTxLockRequest::IsValid -- Transaction is not final: tx=%s", ToString());
return false;
}
CAmount nValueIn = 0;
int nInstantSendConfirmationsRequired = Params().GetConsensus().nInstantSendConfirmationsRequired;
for (const auto& txin : tx->vin) {
Coin coin;
if (!GetUTXOCoin(txin.prevout, coin)) {
LogPrint(BCLog::INSTANTSEND, "CTxLockRequest::IsValid -- Failed to find UTXO %s\n", txin.prevout.ToStringShort());
return false;
}
int nTxAge = chainActive.Height() - coin.nHeight + 1;
// 1 less than the "send IX" gui requires, in case of a block propagating the network at the time
int nConfirmationsRequired = nInstantSendConfirmationsRequired - 1;
if (nTxAge < nConfirmationsRequired) {
LogPrint(BCLog::INSTANTSEND, "CTxLockRequest::IsValid -- outpoint %s too new: nTxAge=%d, nConfirmationsRequired=%d, txid=%s\n",
txin.prevout.ToStringShort(), nTxAge, nConfirmationsRequired, GetHash().ToString());
return false;
}
nValueIn += coin.out.nValue;
}
if (nValueIn > sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE)*COIN) {
LogPrint(BCLog::INSTANTSEND, "CTxLockRequest::IsValid -- Transaction value too high: nValueIn=%d, tx=%s", nValueIn, ToString());
return false;
}
CAmount nValueOut = tx->GetValueOut();
if (nValueIn - nValueOut < GetMinFee(false)) {
LogPrint(BCLog::INSTANTSEND, "CTxLockRequest::IsValid -- did not include enough fees in transaction: fees=%d, tx=%s", nValueOut - nValueIn, ToString());
return false;
}
return true;
}
CAmount CTxLockRequest::GetMinFee(bool fForceMinFee) const
{
if (!fForceMinFee && CInstantSend::CanAutoLock() && IsSimple()) {
return CAmount();
}
CAmount nMinFee = MIN_FEE;
return std::max(nMinFee, CAmount(tx->vin.size() * nMinFee));
}
int CTxLockRequest::GetMaxSignatures() const
{
return tx->vin.size() * Params().GetConsensus().nInstantSendSigsTotal;
}
bool CTxLockRequest::IsSimple() const
{
return (tx->vin.size() <= MAX_INPUTS_FOR_AUTO_IX);
}
//
// CTxLockVote
//
bool CTxLockVote::IsValid(CNode* pnode, CConnman& connman) const
{
auto mnList = deterministicMNManager->GetListAtChainTip();
if (!mnList.HasValidMNByCollateral(outpointMasternode)) {
LogPrint(BCLog::INSTANTSEND, "CTxLockVote::IsValid -- Unknown masternode %s\n", outpointMasternode.ToStringShort());
return false;
}
// Verify that masternodeProTxHash belongs to the same MN referred by the collateral
// This is a leftover from the legacy non-deterministic MN list where we used the collateral to identify MNs
// TODO eventually remove the collateral from CTxLockVote
if (!masternodeProTxHash.IsNull()) {
auto dmn = mnList.GetValidMN(masternodeProTxHash);
if (!dmn || dmn->collateralOutpoint != outpointMasternode) {
LogPrint(BCLog::INSTANTSEND, "CTxLockVote::IsValid -- invalid masternodeProTxHash %s\n", masternodeProTxHash.ToString());
return false;
}
} else {
LogPrint(BCLog::INSTANTSEND, "CTxLockVote::IsValid -- missing masternodeProTxHash\n");
return false;
}
Coin coin;
if (!GetUTXOCoin(outpoint, coin)) {
LogPrint(BCLog::INSTANTSEND, "CTxLockVote::IsValid -- Failed to find UTXO %s\n", outpoint.ToStringShort());
return false;
}
int nLockInputHeight = coin.nHeight + Params().GetConsensus().nInstantSendConfirmationsRequired - 2;
int nRank;
uint256 expectedQuorumModifierHash;
if (!CMasternodeUtils::GetMasternodeRank(outpointMasternode, nRank, expectedQuorumModifierHash, nLockInputHeight)) {
//can be caused by past versions trying to vote with an invalid protocol
LogPrint(BCLog::INSTANTSEND, "CTxLockVote::IsValid -- Can't calculate rank for masternode %s\n", outpointMasternode.ToStringShort());
return false;
}
if (!quorumModifierHash.IsNull()) {
if (quorumModifierHash != expectedQuorumModifierHash) {
LogPrint(BCLog::INSTANTSEND, "CTxLockVote::IsValid -- invalid quorumModifierHash %s, expected %s\n", quorumModifierHash.ToString(), expectedQuorumModifierHash.ToString());
return false;
}
} else {
LogPrint(BCLog::INSTANTSEND, "CTxLockVote::IsValid -- missing quorumModifierHash\n");
return false;
}
LogPrint(BCLog::INSTANTSEND, "CTxLockVote::IsValid -- Masternode %s, rank=%d\n", outpointMasternode.ToStringShort(), nRank);
int nSignaturesTotal = Params().GetConsensus().nInstantSendSigsTotal;
if (nRank > nSignaturesTotal) {
LogPrint(BCLog::INSTANTSEND, "CTxLockVote::IsValid -- Masternode %s is not in the top %d (%d), vote hash=%s\n",
outpointMasternode.ToStringShort(), nSignaturesTotal, nRank, GetHash().ToString());
return false;
}
if (!CheckSignature()) {
LogPrintf("CTxLockVote::IsValid -- Signature invalid\n");
return false;
}
return true;
}
uint256 CTxLockVote::GetHash() const
{
return SerializeHash(*this);
}
uint256 CTxLockVote::GetSignatureHash() const
{
return GetHash();
}
bool CTxLockVote::CheckSignature() const
{
std::string strError;
auto dmn = deterministicMNManager->GetListAtChainTip().GetValidMN(masternodeProTxHash);
if (!dmn) {
LogPrintf("CTxLockVote::CheckSignature -- Unknown Masternode: masternode=%s\n", masternodeProTxHash.ToString());
return false;
}
uint256 hash = GetSignatureHash();
CBLSSignature sig;
sig.SetBuf(vchMasternodeSignature);
if (!sig.IsValid() || !sig.VerifyInsecure(dmn->pdmnState->pubKeyOperator, hash)) {
LogPrintf("CTxLockVote::CheckSignature -- VerifyInsecure() failed\n");
return false;
}
return true;
}
bool CTxLockVote::Sign()
{
uint256 hash = GetSignatureHash();
CBLSSignature sig = activeMasternodeInfo.blsKeyOperator->Sign(hash);
if (!sig.IsValid()) {
return false;
}
sig.GetBuf(vchMasternodeSignature);
return true;
}
void CTxLockVote::Relay(CConnman& connman) const
{
CInv inv(MSG_TXLOCK_VOTE, GetHash());
CTxLockRequest request;
if (instantsend.GetTxLockRequest(txHash, request) && request) {
connman.RelayInvFiltered(inv, *request.tx);
} else {
connman.RelayInvFiltered(inv, txHash);
}
}
bool CTxLockVote::IsExpired(int nHeight) const
{
// Locks and votes expire nInstantSendKeepLock blocks after the block corresponding tx was included into.
return (nConfirmedHeight != -1) && (nHeight - nConfirmedHeight > Params().GetConsensus().nInstantSendKeepLock);
}
bool CTxLockVote::IsTimedOut() const
{
return GetTime() - nTimeCreated > INSTANTSEND_LOCK_TIMEOUT_SECONDS;
}
bool CTxLockVote::IsFailed() const
{
return (GetTime() - nTimeCreated > INSTANTSEND_FAILED_TIMEOUT_SECONDS) && !instantsend.IsLockedInstantSendTransaction(GetTxHash());
}
//
// COutPointLock
//
bool COutPointLock::AddVote(const CTxLockVote& vote)
{
return mapMasternodeVotes.emplace(vote.GetMasternodeOutpoint(), vote).second;
}
std::vector<CTxLockVote> COutPointLock::GetVotes() const
{
std::vector<CTxLockVote> vRet;
for (const auto& pair : mapMasternodeVotes) {
vRet.push_back(pair.second);
}
return vRet;
}
bool COutPointLock::HasMasternodeVoted(const COutPoint& outpointMasternodeIn) const
{
return mapMasternodeVotes.count(outpointMasternodeIn);
}
bool COutPointLock::IsReady() const
{
return !fAttacked && CountVotes() >= Params().GetConsensus().nInstantSendSigsRequired;
}
void COutPointLock::Relay(CConnman& connman) const
{
for (const auto& pair : mapMasternodeVotes) {
pair.second.Relay(connman);
}
}
//
// CTxLockCandidate
//
void CTxLockCandidate::AddOutPointLock(const COutPoint& outpoint)
{
mapOutPointLocks.insert(std::make_pair(outpoint, COutPointLock(outpoint)));
}
void CTxLockCandidate::MarkOutpointAsAttacked(const COutPoint& outpoint)
{
std::map<COutPoint, COutPointLock>::iterator it = mapOutPointLocks.find(outpoint);
if (it != mapOutPointLocks.end())
it->second.MarkAsAttacked();
}
bool CTxLockCandidate::AddVote(const CTxLockVote& vote)
{
std::map<COutPoint, COutPointLock>::iterator it = mapOutPointLocks.find(vote.GetOutpoint());
if (it == mapOutPointLocks.end()) return false;
return it->second.AddVote(vote);
}
bool CTxLockCandidate::IsAllOutPointsReady() const
{
if (mapOutPointLocks.empty()) return false;
for (const auto& pair : mapOutPointLocks) {
if (!pair.second.IsReady()) return false;
}
return true;
}
bool CTxLockCandidate::HasMasternodeVoted(const COutPoint& outpointIn, const COutPoint& outpointMasternodeIn)
{
std::map<COutPoint, COutPointLock>::iterator it = mapOutPointLocks.find(outpointIn);
return it !=mapOutPointLocks.end() && it->second.HasMasternodeVoted(outpointMasternodeIn);
}
int CTxLockCandidate::CountVotes() const
{
// Note: do NOT use vote count to figure out if tx is locked, use IsAllOutPointsReady() instead
int nCountVotes = 0;
for (const auto& pair : mapOutPointLocks) {
nCountVotes += pair.second.CountVotes();
}
return nCountVotes;
}
bool CTxLockCandidate::IsExpired(int nHeight) const
{
// Locks and votes expire nInstantSendKeepLock blocks after the block corresponding tx was included into.
return (nConfirmedHeight != -1) && (nHeight - nConfirmedHeight > Params().GetConsensus().nInstantSendKeepLock);
}
bool CTxLockCandidate::IsTimedOut() const
{
return GetTime() - nTimeCreated > INSTANTSEND_LOCK_TIMEOUT_SECONDS;
}
void CTxLockCandidate::Relay(CConnman& connman) const
{
connman.RelayTransaction(*txLockRequest.tx);
for (const auto& pair : mapOutPointLocks) {
pair.second.Relay(connman);
}
}
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "stdafx.h"
#include "DrillerContext.h"
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/IO/Streamer.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Script/ScriptContext.h>
#include <QMessageBox>
#include <AzToolsFramework/UI/UICore/SaveChangesDialog.hxx>
#include <AzToolsFramework/UI/LegacyFramework/UIFrameworkAPI.h>
#include <Woodpecker/Telemetry/TelemetryBus.h>
#include <AzFramework/Asset/AssetSystemBus.h>
namespace Driller
{
const char* DrillerDebugName = "Profiler";
const char* DrillerInfoName = "Profiler";
class DrillerSavedState
: public AZ::UserSettings
{
public:
AZ_RTTI(DrillerSavedState, "{CBA064FC-B144-4B9D-92B8-F696B0A15E4D}", AZ::UserSettings);
AZ_CLASS_ALLOCATOR(DrillerSavedState, AZ::SystemAllocator, 0);
bool m_MainDrillerWindowIsVisible;
bool m_MainDrillerWindowIsOpen;
DrillerSavedState()
: m_MainDrillerWindowIsVisible(true)
, m_MainDrillerWindowIsOpen(true) {}
static void Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context);
if (serialize)
{
serialize->Class<DrillerSavedState>()
->Version(1)
->Field("m_MainDrillerWindowIsVisible", &DrillerSavedState::m_MainDrillerWindowIsVisible)
->Field("m_MainDrillerWindowIsOpen", &DrillerSavedState::m_MainDrillerWindowIsOpen);
}
}
};
AZ::Uuid ContextID("FB8B7094-63FF-4CD1-9857-3AEFA8E2CFDC");
//////////////////////////////////////////////////////////////////////////
//Context
Context::Context()
: m_pDrillerMainWindow(NULL)
{
}
Context::~Context()
{
}
//////////////////////////////////////////////////////////////////////////
// AZ::Component
void Context::Init()
{
}
void Context::Activate()
{
ContextInterface::Handler::BusConnect(ContextID);
LegacyFramework::CoreMessageBus::Handler::BusConnect();
AzToolsFramework::MainWindowDescription desc;
desc.name = "Profiler";
desc.ContextID = ContextID;
desc.hotkeyDesc = AzToolsFramework::HotkeyDescription(AZ_CRC("DrillerOpen", 0x1cbbd497), "Ctrl+Shift+D", "Open Profiler", "General", 1, AzToolsFramework::HotkeyDescription::SCOPE_WINDOW);
EBUS_EVENT(AzToolsFramework::FrameworkMessages::Bus, AddComponentInfo, desc);
bool connectionSucceeded = false;
EBUS_EVENT_RESULT(connectionSucceeded, AzFramework::AssetSystemRequestBus, Connect, desc.name.c_str());
if (!connectionSucceeded)
{
AZ_TracePrintf(desc.name.c_str(), "%s was not able to connect to the Asset Processor. Please ensure that the Asset Processor is running.", desc.name.c_str());
}
}
void Context::Deactivate()
{
LegacyFramework::CoreMessageBus::Handler::BusDisconnect();
ContextInterface::Handler::BusDisconnect(ContextID);
}
void Context::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context);
if (serialize)
{
DrillerMainWindow::Reflect(context);
DrillerSavedState::Reflect(context);
serialize->Class<Context, AZ::Component>()
->Version(1)
;
}
}
void Context::ApplicationDeactivated()
{
}
void Context::ApplicationActivated()
{
}
void Context::ApplicationShow(AZ::Uuid id)
{
if (ContextID == id)
{
ProvisionalShowAndFocus(true);
}
}
void Context::ApplicationHide(AZ::Uuid id)
{
if (ContextID == id)
{
m_pDrillerMainWindow->hide();
AZStd::intrusive_ptr<DrillerSavedState> newState = AZ::UserSettings::CreateFind<DrillerSavedState>(AZ_CRC("LUA DRILLER CONTEXT STATE", 0x95052376), AZ::UserSettings::CT_GLOBAL);
newState->m_MainDrillerWindowIsVisible = false;
}
}
void Context::ApplicationCensus()
{
AZStd::intrusive_ptr<DrillerSavedState> newState = AZ::UserSettings::CreateFind<DrillerSavedState>(AZ_CRC("LUA DRILLER CONTEXT STATE", 0x95052376), AZ::UserSettings::CT_GLOBAL);
EBUS_EVENT(AzToolsFramework::FrameworkMessages::Bus, ApplicationCensusReply, newState->m_MainDrillerWindowIsVisible);
}
//////////////////////////////////////////////////////////////////////////
// EditorFramework CoreMessages
void Context::OnRestoreState()
{
const AZStd::string k_launchString = "launch";
const AZStd::string k_drillerString = "driller";
bool GUIMode = true;
EBUS_EVENT_RESULT(GUIMode, LegacyFramework::FrameworkApplicationMessages::Bus, IsRunningInGUIMode);
if (!GUIMode)
{
return;
}
const AzFramework::CommandLine* commandLine = nullptr;
EBUS_EVENT_RESULT(commandLine, LegacyFramework::FrameworkApplicationMessages::Bus, GetCommandLineParser);
bool forceShow = false;
bool forceHide = false;
if (commandLine->HasSwitch(k_launchString))
{
forceHide = true;
size_t numSwitchValues = commandLine->GetNumSwitchValues(k_launchString);
for (size_t i = 0; i < numSwitchValues; ++i)
{
AZStd::string inputValue = commandLine->GetSwitchValue(k_launchString, i);
if (inputValue.compare(k_drillerString) == 0)
{
forceShow = true;
forceHide = false;
}
}
}
ProvisionalShowAndFocus(forceShow, forceHide);
}
bool Context::OnGetPermissionToShutDown() // until everyone returns true, we can't shut down.
{
AZ_TracePrintf(DrillerDebugName, "Context::OnGetPermissionToShutDown()\n");
if (m_pDrillerMainWindow)
{
if (!m_pDrillerMainWindow->OnGetPermissionToShutDown())
{
return false;
}
}
return true;
}
// until everyone returns true, we can't shut down.
bool Context::CheckOkayToShutDown()
{
if (m_pDrillerMainWindow)
{
// confirmation that we're quitting.
if (m_pDrillerMainWindow->isVisible())
{
m_pDrillerMainWindow->setEnabled(false);
m_pDrillerMainWindow->hide();
}
}
return true;
}
void Context::OnSaveState()
{
// notify main view to persist?
if (m_pDrillerMainWindow)
{
m_pDrillerMainWindow->SaveWindowState();
}
}
void Context::OnDestroyState()
{
if (m_pDrillerMainWindow)
{
delete m_pDrillerMainWindow;
}
m_pDrillerMainWindow = NULL;
}
//////////////////////////////////////////////////////////////////////////
// Utility
void Context::ProvisionalShowAndFocus(bool forcedShow, bool forcedHide)
{
AZStd::intrusive_ptr<DrillerSavedState> newState = AZ::UserSettings::CreateFind<DrillerSavedState>(AZ_CRC("LUA DRILLER CONTEXT STATE", 0x95052376), AZ::UserSettings::CT_GLOBAL);
if (forcedShow)
{
newState->m_MainDrillerWindowIsOpen = true;
newState->m_MainDrillerWindowIsVisible = true;
}
else if (forcedHide)
{
newState->m_MainDrillerWindowIsOpen = false;
newState->m_MainDrillerWindowIsVisible = false;
}
if (newState->m_MainDrillerWindowIsOpen)
{
if (newState->m_MainDrillerWindowIsVisible)
{
if (!m_pDrillerMainWindow)
{
m_pDrillerMainWindow = aznew DrillerMainWindow();
}
m_pDrillerMainWindow->show();
m_pDrillerMainWindow->raise();
m_pDrillerMainWindow->activateWindow();
m_pDrillerMainWindow->setFocus();
}
else
{
if (m_pDrillerMainWindow)
{
m_pDrillerMainWindow->hide();
}
}
}
}
//////////////////////////////////////////////////////////////////////////
//ContextInterface
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void Context::ShowDrillerView()
{
ProvisionalShowAndFocus(true);
}
}
|
// Copyright 2012 the V8 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.
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <algorithm>
#include <fstream>
#include <unordered_map>
#include <utility>
#include <vector>
#ifdef ENABLE_VTUNE_JIT_INTERFACE
#include "src/third_party/vtune/v8-vtune.h"
#endif
#include "src/d8.h"
#include "src/ostreams.h"
#include "include/libplatform/libplatform.h"
#include "include/libplatform/v8-tracing.h"
#include "src/api.h"
#include "src/base/cpu.h"
#include "src/base/debug/stack_trace.h"
#include "src/base/logging.h"
#include "src/base/platform/platform.h"
#include "src/base/sys-info.h"
#include "src/basic-block-profiler.h"
#include "src/interpreter/interpreter.h"
#include "src/snapshot/natives.h"
#include "src/utils.h"
#include "src/v8.h"
#ifdef V8_INSPECTOR_ENABLED
#include "include/v8-inspector.h"
#endif // V8_INSPECTOR_ENABLED
#if !defined(_WIN32) && !defined(_WIN64)
#include <unistd.h> // NOLINT
#else
#include <windows.h> // NOLINT
#if defined(_MSC_VER)
#include <crtdbg.h> // NOLINT
#endif // defined(_MSC_VER)
#endif // !defined(_WIN32) && !defined(_WIN64)
#ifndef DCHECK
#define DCHECK(condition) assert(condition)
#endif
#ifndef CHECK
#define CHECK(condition) assert(condition)
#endif
namespace v8 {
namespace {
const int MB = 1024 * 1024;
const int kMaxWorkers = 50;
class ShellArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
public:
virtual void* Allocate(size_t length) {
void* data = AllocateUninitialized(length);
return data == NULL ? data : memset(data, 0, length);
}
virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
virtual void Free(void* data, size_t) { free(data); }
};
class MockArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
public:
void* Allocate(size_t length) override {
size_t actual_length = length > 10 * MB ? 1 : length;
void* data = AllocateUninitialized(actual_length);
return data == NULL ? data : memset(data, 0, actual_length);
}
void* AllocateUninitialized(size_t length) override {
return length > 10 * MB ? malloc(1) : malloc(length);
}
void Free(void* p, size_t) override { free(p); }
};
// Predictable v8::Platform implementation. All background and foreground
// tasks are run immediately, delayed tasks are not executed at all.
class PredictablePlatform : public Platform {
public:
PredictablePlatform() {}
void CallOnBackgroundThread(Task* task,
ExpectedRuntime expected_runtime) override {
task->Run();
delete task;
}
void CallOnForegroundThread(v8::Isolate* isolate, Task* task) override {
task->Run();
delete task;
}
void CallDelayedOnForegroundThread(v8::Isolate* isolate, Task* task,
double delay_in_seconds) override {
delete task;
}
void CallIdleOnForegroundThread(v8::Isolate* isolate,
IdleTask* task) override {
UNREACHABLE();
}
bool IdleTasksEnabled(v8::Isolate* isolate) override { return false; }
double MonotonicallyIncreasingTime() override {
return synthetic_time_in_sec_ += 0.00001;
}
using Platform::AddTraceEvent;
uint64_t AddTraceEvent(char phase, const uint8_t* categoryEnabledFlag,
const char* name, const char* scope, uint64_t id,
uint64_t bind_id, int numArgs, const char** argNames,
const uint8_t* argTypes, const uint64_t* argValues,
unsigned int flags) override {
return 0;
}
void UpdateTraceEventDuration(const uint8_t* categoryEnabledFlag,
const char* name, uint64_t handle) override {}
const uint8_t* GetCategoryGroupEnabled(const char* name) override {
static uint8_t no = 0;
return &no;
}
const char* GetCategoryGroupName(
const uint8_t* categoryEnabledFlag) override {
static const char* dummy = "dummy";
return dummy;
}
private:
double synthetic_time_in_sec_ = 0.0;
DISALLOW_COPY_AND_ASSIGN(PredictablePlatform);
};
v8::Platform* g_platform = NULL;
static Local<Value> Throw(Isolate* isolate, const char* message) {
return isolate->ThrowException(
String::NewFromUtf8(isolate, message, NewStringType::kNormal)
.ToLocalChecked());
}
bool FindInObjectList(Local<Object> object, const Shell::ObjectList& list) {
for (int i = 0; i < list.length(); ++i) {
if (list[i]->StrictEquals(object)) {
return true;
}
}
return false;
}
Worker* GetWorkerFromInternalField(Isolate* isolate, Local<Object> object) {
if (object->InternalFieldCount() != 1) {
Throw(isolate, "this is not a Worker");
return NULL;
}
Worker* worker =
static_cast<Worker*>(object->GetAlignedPointerFromInternalField(0));
if (worker == NULL) {
Throw(isolate, "Worker is defunct because main thread is terminating");
return NULL;
}
return worker;
}
} // namespace
namespace tracing {
namespace {
// String options that can be used to initialize TraceOptions.
const char kRecordUntilFull[] = "record-until-full";
const char kRecordContinuously[] = "record-continuously";
const char kRecordAsMuchAsPossible[] = "record-as-much-as-possible";
const char kRecordModeParam[] = "record_mode";
const char kEnableSystraceParam[] = "enable_systrace";
const char kEnableArgumentFilterParam[] = "enable_argument_filter";
const char kIncludedCategoriesParam[] = "included_categories";
const char kExcludedCategoriesParam[] = "excluded_categories";
class TraceConfigParser {
public:
static void FillTraceConfig(v8::Isolate* isolate,
platform::tracing::TraceConfig* trace_config,
const char* json_str) {
HandleScope outer_scope(isolate);
Local<Context> context = Context::New(isolate);
Context::Scope context_scope(context);
HandleScope inner_scope(isolate);
Local<String> source =
String::NewFromUtf8(isolate, json_str, NewStringType::kNormal)
.ToLocalChecked();
Local<Value> result = JSON::Parse(context, source).ToLocalChecked();
Local<v8::Object> trace_config_object = Local<v8::Object>::Cast(result);
trace_config->SetTraceRecordMode(
GetTraceRecordMode(isolate, context, trace_config_object));
if (GetBoolean(isolate, context, trace_config_object,
kEnableSystraceParam)) {
trace_config->EnableSystrace();
}
if (GetBoolean(isolate, context, trace_config_object,
kEnableArgumentFilterParam)) {
trace_config->EnableArgumentFilter();
}
UpdateCategoriesList(isolate, context, trace_config_object,
kIncludedCategoriesParam, trace_config);
UpdateCategoriesList(isolate, context, trace_config_object,
kExcludedCategoriesParam, trace_config);
}
private:
static bool GetBoolean(v8::Isolate* isolate, Local<Context> context,
Local<v8::Object> object, const char* property) {
Local<Value> value = GetValue(isolate, context, object, property);
if (value->IsNumber()) {
Local<Boolean> v8_boolean = value->ToBoolean(context).ToLocalChecked();
return v8_boolean->Value();
}
return false;
}
static int UpdateCategoriesList(
v8::Isolate* isolate, Local<Context> context, Local<v8::Object> object,
const char* property, platform::tracing::TraceConfig* trace_config) {
Local<Value> value = GetValue(isolate, context, object, property);
if (value->IsArray()) {
Local<Array> v8_array = Local<Array>::Cast(value);
for (int i = 0, length = v8_array->Length(); i < length; ++i) {
Local<Value> v = v8_array->Get(context, i)
.ToLocalChecked()
->ToString(context)
.ToLocalChecked();
String::Utf8Value str(v->ToString(context).ToLocalChecked());
if (kIncludedCategoriesParam == property) {
trace_config->AddIncludedCategory(*str);
} else {
trace_config->AddExcludedCategory(*str);
}
}
return v8_array->Length();
}
return 0;
}
static platform::tracing::TraceRecordMode GetTraceRecordMode(
v8::Isolate* isolate, Local<Context> context, Local<v8::Object> object) {
Local<Value> value = GetValue(isolate, context, object, kRecordModeParam);
if (value->IsString()) {
Local<String> v8_string = value->ToString(context).ToLocalChecked();
String::Utf8Value str(v8_string);
if (strcmp(kRecordUntilFull, *str) == 0) {
return platform::tracing::TraceRecordMode::RECORD_UNTIL_FULL;
} else if (strcmp(kRecordContinuously, *str) == 0) {
return platform::tracing::TraceRecordMode::RECORD_CONTINUOUSLY;
} else if (strcmp(kRecordAsMuchAsPossible, *str) == 0) {
return platform::tracing::TraceRecordMode::RECORD_AS_MUCH_AS_POSSIBLE;
}
}
return platform::tracing::TraceRecordMode::RECORD_UNTIL_FULL;
}
static Local<Value> GetValue(v8::Isolate* isolate, Local<Context> context,
Local<v8::Object> object, const char* property) {
Local<String> v8_str =
String::NewFromUtf8(isolate, property, NewStringType::kNormal)
.ToLocalChecked();
return object->Get(context, v8_str).ToLocalChecked();
}
};
} // namespace
static platform::tracing::TraceConfig* CreateTraceConfigFromJSON(
v8::Isolate* isolate, const char* json_str) {
platform::tracing::TraceConfig* trace_config =
new platform::tracing::TraceConfig();
TraceConfigParser::FillTraceConfig(isolate, trace_config, json_str);
return trace_config;
}
} // namespace tracing
class PerIsolateData {
public:
explicit PerIsolateData(Isolate* isolate) : isolate_(isolate), realms_(NULL) {
HandleScope scope(isolate);
isolate->SetData(0, this);
}
~PerIsolateData() {
isolate_->SetData(0, NULL); // Not really needed, just to be sure...
}
inline static PerIsolateData* Get(Isolate* isolate) {
return reinterpret_cast<PerIsolateData*>(isolate->GetData(0));
}
class RealmScope {
public:
explicit RealmScope(PerIsolateData* data);
~RealmScope();
private:
PerIsolateData* data_;
};
private:
friend class Shell;
friend class RealmScope;
Isolate* isolate_;
int realm_count_;
int realm_current_;
int realm_switch_;
Global<Context>* realms_;
Global<Value> realm_shared_;
int RealmIndexOrThrow(const v8::FunctionCallbackInfo<v8::Value>& args,
int arg_offset);
int RealmFind(Local<Context> context);
};
CounterMap* Shell::counter_map_;
base::OS::MemoryMappedFile* Shell::counters_file_ = NULL;
CounterCollection Shell::local_counters_;
CounterCollection* Shell::counters_ = &local_counters_;
base::LazyMutex Shell::context_mutex_;
const base::TimeTicks Shell::kInitialTicks =
base::TimeTicks::HighResolutionNow();
Global<Function> Shell::stringify_function_;
base::LazyMutex Shell::workers_mutex_;
bool Shell::allow_new_workers_ = true;
i::List<Worker*> Shell::workers_;
i::List<SharedArrayBuffer::Contents> Shell::externalized_shared_contents_;
Global<Context> Shell::evaluation_context_;
ArrayBuffer::Allocator* Shell::array_buffer_allocator;
ShellOptions Shell::options;
base::OnceType Shell::quit_once_ = V8_ONCE_INIT;
bool CounterMap::Match(void* key1, void* key2) {
const char* name1 = reinterpret_cast<const char*>(key1);
const char* name2 = reinterpret_cast<const char*>(key2);
return strcmp(name1, name2) == 0;
}
// Converts a V8 value to a C string.
const char* Shell::ToCString(const v8::String::Utf8Value& value) {
return *value ? *value : "<string conversion failed>";
}
ScriptCompiler::CachedData* CompileForCachedData(
Local<String> source, Local<Value> name,
ScriptCompiler::CompileOptions compile_options) {
int source_length = source->Length();
uint16_t* source_buffer = new uint16_t[source_length];
source->Write(source_buffer, 0, source_length);
int name_length = 0;
uint16_t* name_buffer = NULL;
if (name->IsString()) {
Local<String> name_string = Local<String>::Cast(name);
name_length = name_string->Length();
name_buffer = new uint16_t[name_length];
name_string->Write(name_buffer, 0, name_length);
}
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = Shell::array_buffer_allocator;
Isolate* temp_isolate = Isolate::New(create_params);
ScriptCompiler::CachedData* result = NULL;
{
Isolate::Scope isolate_scope(temp_isolate);
HandleScope handle_scope(temp_isolate);
Context::Scope context_scope(Context::New(temp_isolate));
Local<String> source_copy =
v8::String::NewFromTwoByte(temp_isolate, source_buffer,
v8::NewStringType::kNormal,
source_length).ToLocalChecked();
Local<Value> name_copy;
if (name_buffer) {
name_copy = v8::String::NewFromTwoByte(temp_isolate, name_buffer,
v8::NewStringType::kNormal,
name_length).ToLocalChecked();
} else {
name_copy = v8::Undefined(temp_isolate);
}
ScriptCompiler::Source script_source(source_copy, ScriptOrigin(name_copy));
if (!ScriptCompiler::CompileUnboundScript(temp_isolate, &script_source,
compile_options).IsEmpty() &&
script_source.GetCachedData()) {
int length = script_source.GetCachedData()->length;
uint8_t* cache = new uint8_t[length];
memcpy(cache, script_source.GetCachedData()->data, length);
result = new ScriptCompiler::CachedData(
cache, length, ScriptCompiler::CachedData::BufferOwned);
}
}
temp_isolate->Dispose();
delete[] source_buffer;
delete[] name_buffer;
return result;
}
// Compile a string within the current v8 context.
MaybeLocal<Script> Shell::CompileString(
Isolate* isolate, Local<String> source, Local<Value> name,
ScriptCompiler::CompileOptions compile_options) {
Local<Context> context(isolate->GetCurrentContext());
ScriptOrigin origin(name);
if (compile_options == ScriptCompiler::kNoCompileOptions) {
ScriptCompiler::Source script_source(source, origin);
return ScriptCompiler::Compile(context, &script_source, compile_options);
}
ScriptCompiler::CachedData* data =
CompileForCachedData(source, name, compile_options);
ScriptCompiler::Source cached_source(source, origin, data);
if (compile_options == ScriptCompiler::kProduceCodeCache) {
compile_options = ScriptCompiler::kConsumeCodeCache;
} else if (compile_options == ScriptCompiler::kProduceParserCache) {
compile_options = ScriptCompiler::kConsumeParserCache;
} else {
DCHECK(false); // A new compile option?
}
if (data == NULL) compile_options = ScriptCompiler::kNoCompileOptions;
MaybeLocal<Script> result =
ScriptCompiler::Compile(context, &cached_source, compile_options);
CHECK(data == NULL || !data->rejected);
return result;
}
// Executes a string within the current v8 context.
bool Shell::ExecuteString(Isolate* isolate, Local<String> source,
Local<Value> name, bool print_result,
bool report_exceptions) {
HandleScope handle_scope(isolate);
TryCatch try_catch(isolate);
try_catch.SetVerbose(true);
MaybeLocal<Value> maybe_result;
{
PerIsolateData* data = PerIsolateData::Get(isolate);
Local<Context> realm =
Local<Context>::New(isolate, data->realms_[data->realm_current_]);
Context::Scope context_scope(realm);
Local<Script> script;
if (!Shell::CompileString(isolate, source, name, options.compile_options)
.ToLocal(&script)) {
// Print errors that happened during compilation.
if (report_exceptions) ReportException(isolate, &try_catch);
return false;
}
maybe_result = script->Run(realm);
EmptyMessageQueues(isolate);
data->realm_current_ = data->realm_switch_;
}
Local<Value> result;
if (!maybe_result.ToLocal(&result)) {
DCHECK(try_catch.HasCaught());
// Print errors that happened during execution.
if (report_exceptions) ReportException(isolate, &try_catch);
return false;
}
DCHECK(!try_catch.HasCaught());
if (print_result) {
if (options.test_shell) {
if (!result->IsUndefined()) {
// If all went well and the result wasn't undefined then print
// the returned value.
v8::String::Utf8Value str(result);
fwrite(*str, sizeof(**str), str.length(), stdout);
printf("\n");
}
} else {
v8::String::Utf8Value str(Stringify(isolate, result));
fwrite(*str, sizeof(**str), str.length(), stdout);
printf("\n");
}
}
return true;
}
namespace {
std::string ToSTLString(Local<String> v8_str) {
String::Utf8Value utf8(v8_str);
// Should not be able to fail since the input is a String.
CHECK(*utf8);
return *utf8;
}
bool IsAbsolutePath(const std::string& path) {
#if defined(_WIN32) || defined(_WIN64)
// TODO(adamk): This is an incorrect approximation, but should
// work for all our test-running cases.
return path.find(':') != std::string::npos;
#else
return path[0] == '/';
#endif
}
std::string GetWorkingDirectory() {
#if defined(_WIN32) || defined(_WIN64)
char system_buffer[MAX_PATH];
// TODO(adamk): Support Unicode paths.
DWORD len = GetCurrentDirectoryA(MAX_PATH, system_buffer);
CHECK(len > 0);
return system_buffer;
#else
char curdir[PATH_MAX];
CHECK_NOT_NULL(getcwd(curdir, PATH_MAX));
return curdir;
#endif
}
// Returns the directory part of path, without the trailing '/'.
std::string DirName(const std::string& path) {
DCHECK(IsAbsolutePath(path));
size_t last_slash = path.find_last_of('/');
DCHECK(last_slash != std::string::npos);
return path.substr(0, last_slash);
}
// Resolves path to an absolute path if necessary, and does some
// normalization (eliding references to the current directory
// and replacing backslashes with slashes).
std::string NormalizePath(const std::string& path,
const std::string& dir_name) {
std::string result;
if (IsAbsolutePath(path)) {
result = path;
} else {
result = dir_name + '/' + path;
}
std::replace(result.begin(), result.end(), '\\', '/');
size_t i;
while ((i = result.find("/./")) != std::string::npos) {
result.erase(i, 2);
}
return result;
}
// Per-context Module data, allowing sharing of module maps
// across top-level module loads.
class ModuleEmbedderData {
private:
class ModuleGlobalHash {
public:
explicit ModuleGlobalHash(Isolate* isolate) : isolate_(isolate) {}
size_t operator()(const Global<Module>& module) const {
return module.Get(isolate_)->GetIdentityHash();
}
private:
Isolate* isolate_;
};
public:
explicit ModuleEmbedderData(Isolate* isolate)
: module_to_directory_map(10, ModuleGlobalHash(isolate)) {}
// Map from normalized module specifier to Module.
std::unordered_map<std::string, Global<Module>> specifier_to_module_map;
// Map from Module to the directory that Module was loaded from.
std::unordered_map<Global<Module>, std::string, ModuleGlobalHash>
module_to_directory_map;
};
enum {
// The debugger reserves the first slot in the Context embedder data.
kDebugIdIndex = Context::kDebugIdIndex,
kModuleEmbedderDataIndex,
kInspectorClientIndex
};
void InitializeModuleEmbedderData(Local<Context> context) {
context->SetAlignedPointerInEmbedderData(
kModuleEmbedderDataIndex, new ModuleEmbedderData(context->GetIsolate()));
}
ModuleEmbedderData* GetModuleDataFromContext(Local<Context> context) {
return static_cast<ModuleEmbedderData*>(
context->GetAlignedPointerFromEmbedderData(kModuleEmbedderDataIndex));
}
void DisposeModuleEmbedderData(Local<Context> context) {
delete GetModuleDataFromContext(context);
context->SetAlignedPointerInEmbedderData(kModuleEmbedderDataIndex, nullptr);
}
MaybeLocal<Module> ResolveModuleCallback(Local<Context> context,
Local<String> specifier,
Local<Module> referrer) {
Isolate* isolate = context->GetIsolate();
ModuleEmbedderData* d = GetModuleDataFromContext(context);
auto dir_name_it =
d->module_to_directory_map.find(Global<Module>(isolate, referrer));
CHECK(dir_name_it != d->module_to_directory_map.end());
std::string absolute_path =
NormalizePath(ToSTLString(specifier), dir_name_it->second);
auto module_it = d->specifier_to_module_map.find(absolute_path);
CHECK(module_it != d->specifier_to_module_map.end());
return module_it->second.Get(isolate);
}
} // anonymous namespace
MaybeLocal<Module> Shell::FetchModuleTree(Local<Context> context,
const std::string& file_name) {
DCHECK(IsAbsolutePath(file_name));
Isolate* isolate = context->GetIsolate();
TryCatch try_catch(isolate);
try_catch.SetVerbose(true);
Local<String> source_text = ReadFile(isolate, file_name.c_str());
if (source_text.IsEmpty()) {
printf("Error reading '%s'\n", file_name.c_str());
Shell::Exit(1);
}
ScriptOrigin origin(
String::NewFromUtf8(isolate, file_name.c_str(), NewStringType::kNormal)
.ToLocalChecked());
ScriptCompiler::Source source(source_text, origin);
Local<Module> module;
if (!ScriptCompiler::CompileModule(isolate, &source).ToLocal(&module)) {
ReportException(isolate, &try_catch);
return MaybeLocal<Module>();
}
ModuleEmbedderData* d = GetModuleDataFromContext(context);
CHECK(d->specifier_to_module_map
.insert(std::make_pair(file_name, Global<Module>(isolate, module)))
.second);
std::string dir_name = DirName(file_name);
CHECK(d->module_to_directory_map
.insert(std::make_pair(Global<Module>(isolate, module), dir_name))
.second);
for (int i = 0, length = module->GetModuleRequestsLength(); i < length; ++i) {
Local<String> name = module->GetModuleRequest(i);
std::string absolute_path = NormalizePath(ToSTLString(name), dir_name);
if (!d->specifier_to_module_map.count(absolute_path)) {
if (FetchModuleTree(context, absolute_path).IsEmpty()) {
return MaybeLocal<Module>();
}
}
}
return module;
}
bool Shell::ExecuteModule(Isolate* isolate, const char* file_name) {
HandleScope handle_scope(isolate);
PerIsolateData* data = PerIsolateData::Get(isolate);
Local<Context> realm = data->realms_[data->realm_current_].Get(isolate);
Context::Scope context_scope(realm);
std::string absolute_path = NormalizePath(file_name, GetWorkingDirectory());
Local<Module> root_module;
if (!FetchModuleTree(realm, absolute_path).ToLocal(&root_module)) {
return false;
}
TryCatch try_catch(isolate);
try_catch.SetVerbose(true);
MaybeLocal<Value> maybe_result;
if (root_module->Instantiate(realm, ResolveModuleCallback)) {
maybe_result = root_module->Evaluate(realm);
EmptyMessageQueues(isolate);
}
Local<Value> result;
if (!maybe_result.ToLocal(&result)) {
DCHECK(try_catch.HasCaught());
// Print errors that happened during execution.
ReportException(isolate, &try_catch);
return false;
}
DCHECK(!try_catch.HasCaught());
return true;
}
PerIsolateData::RealmScope::RealmScope(PerIsolateData* data) : data_(data) {
data_->realm_count_ = 1;
data_->realm_current_ = 0;
data_->realm_switch_ = 0;
data_->realms_ = new Global<Context>[1];
data_->realms_[0].Reset(data_->isolate_,
data_->isolate_->GetEnteredContext());
}
PerIsolateData::RealmScope::~RealmScope() {
// Drop realms to avoid keeping them alive.
for (int i = 0; i < data_->realm_count_; ++i) {
Global<Context>& realm = data_->realms_[i];
if (realm.IsEmpty()) continue;
DisposeModuleEmbedderData(realm.Get(data_->isolate_));
// TODO(adamk): No need to reset manually, Globals reset when destructed.
realm.Reset();
}
delete[] data_->realms_;
// TODO(adamk): No need to reset manually, Globals reset when destructed.
if (!data_->realm_shared_.IsEmpty())
data_->realm_shared_.Reset();
}
int PerIsolateData::RealmFind(Local<Context> context) {
for (int i = 0; i < realm_count_; ++i) {
if (realms_[i] == context) return i;
}
return -1;
}
int PerIsolateData::RealmIndexOrThrow(
const v8::FunctionCallbackInfo<v8::Value>& args,
int arg_offset) {
if (args.Length() < arg_offset || !args[arg_offset]->IsNumber()) {
Throw(args.GetIsolate(), "Invalid argument");
return -1;
}
int index = args[arg_offset]
->Int32Value(args.GetIsolate()->GetCurrentContext())
.FromMaybe(-1);
if (index < 0 || index >= realm_count_ || realms_[index].IsEmpty()) {
Throw(args.GetIsolate(), "Invalid realm index");
return -1;
}
return index;
}
// performance.now() returns a time stamp as double, measured in milliseconds.
// When FLAG_verify_predictable mode is enabled it returns result of
// v8::Platform::MonotonicallyIncreasingTime().
void Shell::PerformanceNow(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (i::FLAG_verify_predictable) {
args.GetReturnValue().Set(g_platform->MonotonicallyIncreasingTime());
} else {
base::TimeDelta delta =
base::TimeTicks::HighResolutionNow() - kInitialTicks;
args.GetReturnValue().Set(delta.InMillisecondsF());
}
}
// Realm.current() returns the index of the currently active realm.
void Shell::RealmCurrent(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
PerIsolateData* data = PerIsolateData::Get(isolate);
int index = data->RealmFind(isolate->GetEnteredContext());
if (index == -1) return;
args.GetReturnValue().Set(index);
}
// Realm.owner(o) returns the index of the realm that created o.
void Shell::RealmOwner(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
PerIsolateData* data = PerIsolateData::Get(isolate);
if (args.Length() < 1 || !args[0]->IsObject()) {
Throw(args.GetIsolate(), "Invalid argument");
return;
}
int index = data->RealmFind(args[0]
->ToObject(isolate->GetCurrentContext())
.ToLocalChecked()
->CreationContext());
if (index == -1) return;
args.GetReturnValue().Set(index);
}
// Realm.global(i) returns the global object of realm i.
// (Note that properties of global objects cannot be read/written cross-realm.)
void Shell::RealmGlobal(const v8::FunctionCallbackInfo<v8::Value>& args) {
PerIsolateData* data = PerIsolateData::Get(args.GetIsolate());
int index = data->RealmIndexOrThrow(args, 0);
if (index == -1) return;
args.GetReturnValue().Set(
Local<Context>::New(args.GetIsolate(), data->realms_[index])->Global());
}
MaybeLocal<Context> Shell::CreateRealm(
const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
TryCatch try_catch(isolate);
PerIsolateData* data = PerIsolateData::Get(isolate);
Global<Context>* old_realms = data->realms_;
int index = data->realm_count_;
data->realms_ = new Global<Context>[++data->realm_count_];
for (int i = 0; i < index; ++i) {
data->realms_[i].Reset(isolate, old_realms[i]);
old_realms[i].Reset();
}
delete[] old_realms;
Local<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
Local<Context> context = Context::New(isolate, NULL, global_template);
if (context.IsEmpty()) {
DCHECK(try_catch.HasCaught());
try_catch.ReThrow();
return MaybeLocal<Context>();
}
InitializeModuleEmbedderData(context);
data->realms_[index].Reset(isolate, context);
args.GetReturnValue().Set(index);
return context;
}
// Realm.create() creates a new realm with a distinct security token
// and returns its index.
void Shell::RealmCreate(const v8::FunctionCallbackInfo<v8::Value>& args) {
CreateRealm(args);
}
// Realm.createAllowCrossRealmAccess() creates a new realm with the same
// security token as the current realm.
void Shell::RealmCreateAllowCrossRealmAccess(
const v8::FunctionCallbackInfo<v8::Value>& args) {
Local<Context> context;
if (CreateRealm(args).ToLocal(&context)) {
context->SetSecurityToken(
args.GetIsolate()->GetEnteredContext()->GetSecurityToken());
}
}
// Realm.dispose(i) disposes the reference to the realm i.
void Shell::RealmDispose(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
PerIsolateData* data = PerIsolateData::Get(isolate);
int index = data->RealmIndexOrThrow(args, 0);
if (index == -1) return;
if (index == 0 ||
index == data->realm_current_ || index == data->realm_switch_) {
Throw(args.GetIsolate(), "Invalid realm index");
return;
}
DisposeModuleEmbedderData(data->realms_[index].Get(isolate));
data->realms_[index].Reset();
isolate->ContextDisposedNotification();
isolate->IdleNotificationDeadline(g_platform->MonotonicallyIncreasingTime());
}
// Realm.switch(i) switches to the realm i for consecutive interactive inputs.
void Shell::RealmSwitch(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
PerIsolateData* data = PerIsolateData::Get(isolate);
int index = data->RealmIndexOrThrow(args, 0);
if (index == -1) return;
data->realm_switch_ = index;
}
// Realm.eval(i, s) evaluates s in realm i and returns the result.
void Shell::RealmEval(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
PerIsolateData* data = PerIsolateData::Get(isolate);
int index = data->RealmIndexOrThrow(args, 0);
if (index == -1) return;
if (args.Length() < 2 || !args[1]->IsString()) {
Throw(args.GetIsolate(), "Invalid argument");
return;
}
ScriptCompiler::Source script_source(
args[1]->ToString(isolate->GetCurrentContext()).ToLocalChecked());
Local<UnboundScript> script;
if (!ScriptCompiler::CompileUnboundScript(isolate, &script_source)
.ToLocal(&script)) {
return;
}
Local<Context> realm = Local<Context>::New(isolate, data->realms_[index]);
realm->Enter();
Local<Value> result;
if (!script->BindToCurrentContext()->Run(realm).ToLocal(&result)) {
realm->Exit();
return;
}
realm->Exit();
args.GetReturnValue().Set(result);
}
// Realm.shared is an accessor for a single shared value across realms.
void Shell::RealmSharedGet(Local<String> property,
const PropertyCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
PerIsolateData* data = PerIsolateData::Get(isolate);
if (data->realm_shared_.IsEmpty()) return;
info.GetReturnValue().Set(data->realm_shared_);
}
void Shell::RealmSharedSet(Local<String> property,
Local<Value> value,
const PropertyCallbackInfo<void>& info) {
Isolate* isolate = info.GetIsolate();
PerIsolateData* data = PerIsolateData::Get(isolate);
data->realm_shared_.Reset(isolate, value);
}
void Shell::Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
Write(args);
printf("\n");
fflush(stdout);
}
void Shell::Write(const v8::FunctionCallbackInfo<v8::Value>& args) {
for (int i = 0; i < args.Length(); i++) {
HandleScope handle_scope(args.GetIsolate());
if (i != 0) {
printf(" ");
}
// Explicitly catch potential exceptions in toString().
v8::TryCatch try_catch(args.GetIsolate());
Local<Value> arg = args[i];
Local<String> str_obj;
if (arg->IsSymbol()) {
arg = Local<Symbol>::Cast(arg)->Name();
}
if (!arg->ToString(args.GetIsolate()->GetCurrentContext())
.ToLocal(&str_obj)) {
try_catch.ReThrow();
return;
}
v8::String::Utf8Value str(str_obj);
int n = static_cast<int>(fwrite(*str, sizeof(**str), str.length(), stdout));
if (n != str.length()) {
printf("Error in fwrite\n");
Exit(1);
}
}
}
void Shell::Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
String::Utf8Value file(args[0]);
if (*file == NULL) {
Throw(args.GetIsolate(), "Error loading file");
return;
}
Local<String> source = ReadFile(args.GetIsolate(), *file);
if (source.IsEmpty()) {
Throw(args.GetIsolate(), "Error loading file");
return;
}
args.GetReturnValue().Set(source);
}
Local<String> Shell::ReadFromStdin(Isolate* isolate) {
static const int kBufferSize = 256;
char buffer[kBufferSize];
Local<String> accumulator =
String::NewFromUtf8(isolate, "", NewStringType::kNormal).ToLocalChecked();
int length;
while (true) {
// Continue reading if the line ends with an escape '\\' or the line has
// not been fully read into the buffer yet (does not end with '\n').
// If fgets gets an error, just give up.
char* input = NULL;
input = fgets(buffer, kBufferSize, stdin);
if (input == NULL) return Local<String>();
length = static_cast<int>(strlen(buffer));
if (length == 0) {
return accumulator;
} else if (buffer[length-1] != '\n') {
accumulator = String::Concat(
accumulator,
String::NewFromUtf8(isolate, buffer, NewStringType::kNormal, length)
.ToLocalChecked());
} else if (length > 1 && buffer[length-2] == '\\') {
buffer[length-2] = '\n';
accumulator = String::Concat(
accumulator,
String::NewFromUtf8(isolate, buffer, NewStringType::kNormal,
length - 1).ToLocalChecked());
} else {
return String::Concat(
accumulator,
String::NewFromUtf8(isolate, buffer, NewStringType::kNormal,
length - 1).ToLocalChecked());
}
}
}
void Shell::Load(const v8::FunctionCallbackInfo<v8::Value>& args) {
for (int i = 0; i < args.Length(); i++) {
HandleScope handle_scope(args.GetIsolate());
String::Utf8Value file(args[i]);
if (*file == NULL) {
Throw(args.GetIsolate(), "Error loading file");
return;
}
Local<String> source = ReadFile(args.GetIsolate(), *file);
if (source.IsEmpty()) {
Throw(args.GetIsolate(), "Error loading file");
return;
}
if (!ExecuteString(
args.GetIsolate(), source,
String::NewFromUtf8(args.GetIsolate(), *file,
NewStringType::kNormal).ToLocalChecked(),
false, true)) {
Throw(args.GetIsolate(), "Error executing file");
return;
}
}
}
void Shell::WorkerNew(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
HandleScope handle_scope(isolate);
if (args.Length() < 1 || !args[0]->IsString()) {
Throw(args.GetIsolate(), "1st argument must be string");
return;
}
if (!args.IsConstructCall()) {
Throw(args.GetIsolate(), "Worker must be constructed with new");
return;
}
{
base::LockGuard<base::Mutex> lock_guard(workers_mutex_.Pointer());
if (workers_.length() >= kMaxWorkers) {
Throw(args.GetIsolate(), "Too many workers, I won't let you create more");
return;
}
// Initialize the internal field to NULL; if we return early without
// creating a new Worker (because the main thread is terminating) we can
// early-out from the instance calls.
args.Holder()->SetAlignedPointerInInternalField(0, NULL);
if (!allow_new_workers_) return;
Worker* worker = new Worker;
args.Holder()->SetAlignedPointerInInternalField(0, worker);
workers_.Add(worker);
String::Utf8Value script(args[0]);
if (!*script) {
Throw(args.GetIsolate(), "Can't get worker script");
return;
}
worker->StartExecuteInThread(*script);
}
}
void Shell::WorkerPostMessage(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
HandleScope handle_scope(isolate);
Local<Context> context = isolate->GetCurrentContext();
if (args.Length() < 1) {
Throw(isolate, "Invalid argument");
return;
}
Worker* worker = GetWorkerFromInternalField(isolate, args.Holder());
if (!worker) {
return;
}
Local<Value> message = args[0];
ObjectList to_transfer;
if (args.Length() >= 2) {
if (!args[1]->IsArray()) {
Throw(isolate, "Transfer list must be an Array");
return;
}
Local<Array> transfer = Local<Array>::Cast(args[1]);
uint32_t length = transfer->Length();
for (uint32_t i = 0; i < length; ++i) {
Local<Value> element;
if (transfer->Get(context, i).ToLocal(&element)) {
if (!element->IsArrayBuffer() && !element->IsSharedArrayBuffer()) {
Throw(isolate,
"Transfer array elements must be an ArrayBuffer or "
"SharedArrayBuffer.");
break;
}
to_transfer.Add(Local<Object>::Cast(element));
}
}
}
ObjectList seen_objects;
SerializationData* data = new SerializationData;
if (SerializeValue(isolate, message, to_transfer, &seen_objects, data)) {
worker->PostMessage(data);
} else {
delete data;
}
}
void Shell::WorkerGetMessage(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
HandleScope handle_scope(isolate);
Worker* worker = GetWorkerFromInternalField(isolate, args.Holder());
if (!worker) {
return;
}
SerializationData* data = worker->GetMessage();
if (data) {
int offset = 0;
Local<Value> data_value;
if (Shell::DeserializeValue(isolate, *data, &offset).ToLocal(&data_value)) {
args.GetReturnValue().Set(data_value);
}
delete data;
}
}
void Shell::WorkerTerminate(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
HandleScope handle_scope(isolate);
Worker* worker = GetWorkerFromInternalField(isolate, args.Holder());
if (!worker) {
return;
}
worker->Terminate();
}
void Shell::QuitOnce(v8::FunctionCallbackInfo<v8::Value>* args) {
int exit_code = (*args)[0]
->Int32Value(args->GetIsolate()->GetCurrentContext())
.FromMaybe(0);
CleanupWorkers();
OnExit(args->GetIsolate());
Exit(exit_code);
}
void Shell::Quit(const v8::FunctionCallbackInfo<v8::Value>& args) {
base::CallOnce(&quit_once_, &QuitOnce,
const_cast<v8::FunctionCallbackInfo<v8::Value>*>(&args));
}
void Shell::Version(const v8::FunctionCallbackInfo<v8::Value>& args) {
args.GetReturnValue().Set(
String::NewFromUtf8(args.GetIsolate(), V8::GetVersion(),
NewStringType::kNormal).ToLocalChecked());
}
void Shell::ReportException(Isolate* isolate, v8::TryCatch* try_catch) {
HandleScope handle_scope(isolate);
Local<Context> context;
bool enter_context = !isolate->InContext();
if (enter_context) {
context = Local<Context>::New(isolate, evaluation_context_);
context->Enter();
}
v8::String::Utf8Value exception(try_catch->Exception());
const char* exception_string = ToCString(exception);
Local<Message> message = try_catch->Message();
if (message.IsEmpty()) {
// V8 didn't provide any extra information about this error; just
// print the exception.
printf("%s\n", exception_string);
} else {
// Print (filename):(line number): (message).
v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
const char* filename_string = ToCString(filename);
Maybe<int> maybeline = message->GetLineNumber(isolate->GetCurrentContext());
int linenum = maybeline.IsJust() ? maybeline.FromJust() : -1;
printf("%s:%i: %s\n", filename_string, linenum, exception_string);
Local<String> sourceline;
if (message->GetSourceLine(isolate->GetCurrentContext())
.ToLocal(&sourceline)) {
// Print line of source code.
v8::String::Utf8Value sourcelinevalue(sourceline);
const char* sourceline_string = ToCString(sourcelinevalue);
printf("%s\n", sourceline_string);
// Print wavy underline (GetUnderline is deprecated).
int start =
message->GetStartColumn(isolate->GetCurrentContext()).FromJust();
for (int i = 0; i < start; i++) {
printf(" ");
}
int end = message->GetEndColumn(isolate->GetCurrentContext()).FromJust();
for (int i = start; i < end; i++) {
printf("^");
}
printf("\n");
}
Local<Value> stack_trace_string;
if (try_catch->StackTrace(isolate->GetCurrentContext())
.ToLocal(&stack_trace_string) &&
stack_trace_string->IsString()) {
v8::String::Utf8Value stack_trace(
Local<String>::Cast(stack_trace_string));
printf("%s\n", ToCString(stack_trace));
}
}
printf("\n");
if (enter_context) context->Exit();
}
int32_t* Counter::Bind(const char* name, bool is_histogram) {
int i;
for (i = 0; i < kMaxNameSize - 1 && name[i]; i++)
name_[i] = static_cast<char>(name[i]);
name_[i] = '\0';
is_histogram_ = is_histogram;
return ptr();
}
void Counter::AddSample(int32_t sample) {
count_++;
sample_total_ += sample;
}
CounterCollection::CounterCollection() {
magic_number_ = 0xDEADFACE;
max_counters_ = kMaxCounters;
max_name_size_ = Counter::kMaxNameSize;
counters_in_use_ = 0;
}
Counter* CounterCollection::GetNextCounter() {
if (counters_in_use_ == kMaxCounters) return NULL;
return &counters_[counters_in_use_++];
}
void Shell::MapCounters(v8::Isolate* isolate, const char* name) {
counters_file_ = base::OS::MemoryMappedFile::create(
name, sizeof(CounterCollection), &local_counters_);
void* memory = (counters_file_ == NULL) ?
NULL : counters_file_->memory();
if (memory == NULL) {
printf("Could not map counters file %s\n", name);
Exit(1);
}
counters_ = static_cast<CounterCollection*>(memory);
isolate->SetCounterFunction(LookupCounter);
isolate->SetCreateHistogramFunction(CreateHistogram);
isolate->SetAddHistogramSampleFunction(AddHistogramSample);
}
int CounterMap::Hash(const char* name) {
int h = 0;
int c;
while ((c = *name++) != 0) {
h += h << 5;
h += c;
}
return h;
}
Counter* Shell::GetCounter(const char* name, bool is_histogram) {
Counter* counter = counter_map_->Lookup(name);
if (counter == NULL) {
counter = counters_->GetNextCounter();
if (counter != NULL) {
counter_map_->Set(name, counter);
counter->Bind(name, is_histogram);
}
} else {
DCHECK(counter->is_histogram() == is_histogram);
}
return counter;
}
int* Shell::LookupCounter(const char* name) {
Counter* counter = GetCounter(name, false);
if (counter != NULL) {
return counter->ptr();
} else {
return NULL;
}
}
void* Shell::CreateHistogram(const char* name,
int min,
int max,
size_t buckets) {
return GetCounter(name, true);
}
void Shell::AddHistogramSample(void* histogram, int sample) {
Counter* counter = reinterpret_cast<Counter*>(histogram);
counter->AddSample(sample);
}
// Turn a value into a human-readable string.
Local<String> Shell::Stringify(Isolate* isolate, Local<Value> value) {
v8::Local<v8::Context> context =
v8::Local<v8::Context>::New(isolate, evaluation_context_);
if (stringify_function_.IsEmpty()) {
int source_index = i::NativesCollection<i::D8>::GetIndex("d8");
i::Vector<const char> source_string =
i::NativesCollection<i::D8>::GetScriptSource(source_index);
i::Vector<const char> source_name =
i::NativesCollection<i::D8>::GetScriptName(source_index);
Local<String> source =
String::NewFromUtf8(isolate, source_string.start(),
NewStringType::kNormal, source_string.length())
.ToLocalChecked();
Local<String> name =
String::NewFromUtf8(isolate, source_name.start(),
NewStringType::kNormal, source_name.length())
.ToLocalChecked();
ScriptOrigin origin(name);
Local<Script> script =
Script::Compile(context, source, &origin).ToLocalChecked();
stringify_function_.Reset(
isolate, script->Run(context).ToLocalChecked().As<Function>());
}
Local<Function> fun = Local<Function>::New(isolate, stringify_function_);
Local<Value> argv[1] = {value};
v8::TryCatch try_catch(isolate);
MaybeLocal<Value> result = fun->Call(context, Undefined(isolate), 1, argv);
if (result.IsEmpty()) return String::Empty(isolate);
return result.ToLocalChecked().As<String>();
}
Local<ObjectTemplate> Shell::CreateGlobalTemplate(Isolate* isolate) {
Local<ObjectTemplate> global_template = ObjectTemplate::New(isolate);
global_template->Set(
String::NewFromUtf8(isolate, "print", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, Print));
global_template->Set(
String::NewFromUtf8(isolate, "write", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, Write));
global_template->Set(
String::NewFromUtf8(isolate, "read", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, Read));
global_template->Set(
String::NewFromUtf8(isolate, "readbuffer", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, ReadBuffer));
global_template->Set(
String::NewFromUtf8(isolate, "readline", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, ReadLine));
global_template->Set(
String::NewFromUtf8(isolate, "load", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, Load));
// Some Emscripten-generated code tries to call 'quit', which in turn would
// call C's exit(). This would lead to memory leaks, because there is no way
// we can terminate cleanly then, so we need a way to hide 'quit'.
if (!options.omit_quit) {
global_template->Set(
String::NewFromUtf8(isolate, "quit", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, Quit));
}
global_template->Set(
String::NewFromUtf8(isolate, "version", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, Version));
global_template->Set(
Symbol::GetToStringTag(isolate),
String::NewFromUtf8(isolate, "global", NewStringType::kNormal)
.ToLocalChecked());
// Bind the Realm object.
Local<ObjectTemplate> realm_template = ObjectTemplate::New(isolate);
realm_template->Set(
String::NewFromUtf8(isolate, "current", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, RealmCurrent));
realm_template->Set(
String::NewFromUtf8(isolate, "owner", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, RealmOwner));
realm_template->Set(
String::NewFromUtf8(isolate, "global", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, RealmGlobal));
realm_template->Set(
String::NewFromUtf8(isolate, "create", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, RealmCreate));
realm_template->Set(
String::NewFromUtf8(isolate, "createAllowCrossRealmAccess",
NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, RealmCreateAllowCrossRealmAccess));
realm_template->Set(
String::NewFromUtf8(isolate, "dispose", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, RealmDispose));
realm_template->Set(
String::NewFromUtf8(isolate, "switch", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, RealmSwitch));
realm_template->Set(
String::NewFromUtf8(isolate, "eval", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, RealmEval));
realm_template->SetAccessor(
String::NewFromUtf8(isolate, "shared", NewStringType::kNormal)
.ToLocalChecked(),
RealmSharedGet, RealmSharedSet);
global_template->Set(
String::NewFromUtf8(isolate, "Realm", NewStringType::kNormal)
.ToLocalChecked(),
realm_template);
Local<ObjectTemplate> performance_template = ObjectTemplate::New(isolate);
performance_template->Set(
String::NewFromUtf8(isolate, "now", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, PerformanceNow));
global_template->Set(
String::NewFromUtf8(isolate, "performance", NewStringType::kNormal)
.ToLocalChecked(),
performance_template);
Local<FunctionTemplate> worker_fun_template =
FunctionTemplate::New(isolate, WorkerNew);
Local<Signature> worker_signature =
Signature::New(isolate, worker_fun_template);
worker_fun_template->SetClassName(
String::NewFromUtf8(isolate, "Worker", NewStringType::kNormal)
.ToLocalChecked());
worker_fun_template->ReadOnlyPrototype();
worker_fun_template->PrototypeTemplate()->Set(
String::NewFromUtf8(isolate, "terminate", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, WorkerTerminate, Local<Value>(),
worker_signature));
worker_fun_template->PrototypeTemplate()->Set(
String::NewFromUtf8(isolate, "postMessage", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, WorkerPostMessage, Local<Value>(),
worker_signature));
worker_fun_template->PrototypeTemplate()->Set(
String::NewFromUtf8(isolate, "getMessage", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, WorkerGetMessage, Local<Value>(),
worker_signature));
worker_fun_template->InstanceTemplate()->SetInternalFieldCount(1);
global_template->Set(
String::NewFromUtf8(isolate, "Worker", NewStringType::kNormal)
.ToLocalChecked(),
worker_fun_template);
Local<ObjectTemplate> os_templ = ObjectTemplate::New(isolate);
AddOSMethods(isolate, os_templ);
global_template->Set(
String::NewFromUtf8(isolate, "os", NewStringType::kNormal)
.ToLocalChecked(),
os_templ);
return global_template;
}
static void EmptyMessageCallback(Local<Message> message, Local<Value> error) {
// Nothing to be done here, exceptions thrown up to the shell will be reported
// separately by {Shell::ReportException} after they are caught.
}
void Shell::Initialize(Isolate* isolate) {
// Set up counters
if (i::StrLength(i::FLAG_map_counters) != 0)
MapCounters(isolate, i::FLAG_map_counters);
// Disable default message reporting.
isolate->AddMessageListener(EmptyMessageCallback);
}
Local<Context> Shell::CreateEvaluationContext(Isolate* isolate) {
// This needs to be a critical section since this is not thread-safe
base::LockGuard<base::Mutex> lock_guard(context_mutex_.Pointer());
// Initialize the global objects
Local<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
EscapableHandleScope handle_scope(isolate);
Local<Context> context = Context::New(isolate, NULL, global_template);
DCHECK(!context.IsEmpty());
InitializeModuleEmbedderData(context);
Context::Scope scope(context);
i::Factory* factory = reinterpret_cast<i::Isolate*>(isolate)->factory();
i::JSArguments js_args = i::FLAG_js_arguments;
i::Handle<i::FixedArray> arguments_array =
factory->NewFixedArray(js_args.argc);
for (int j = 0; j < js_args.argc; j++) {
i::Handle<i::String> arg =
factory->NewStringFromUtf8(i::CStrVector(js_args[j])).ToHandleChecked();
arguments_array->set(j, *arg);
}
i::Handle<i::JSArray> arguments_jsarray =
factory->NewJSArrayWithElements(arguments_array);
context->Global()
->Set(context,
String::NewFromUtf8(isolate, "arguments", NewStringType::kNormal)
.ToLocalChecked(),
Utils::ToLocal(arguments_jsarray))
.FromJust();
return handle_scope.Escape(context);
}
void Shell::Exit(int exit_code) {
// Use _exit instead of exit to avoid races between isolate
// threads and static destructors.
fflush(stdout);
fflush(stderr);
_exit(exit_code);
}
struct CounterAndKey {
Counter* counter;
const char* key;
};
inline bool operator<(const CounterAndKey& lhs, const CounterAndKey& rhs) {
return strcmp(lhs.key, rhs.key) < 0;
}
void Shell::WriteIgnitionDispatchCountersFile(v8::Isolate* isolate) {
HandleScope handle_scope(isolate);
Local<Context> context = Context::New(isolate);
Context::Scope context_scope(context);
Local<Object> dispatch_counters = reinterpret_cast<i::Isolate*>(isolate)
->interpreter()
->GetDispatchCountersObject();
std::ofstream dispatch_counters_stream(
i::FLAG_trace_ignition_dispatches_output_file);
dispatch_counters_stream << *String::Utf8Value(
JSON::Stringify(context, dispatch_counters).ToLocalChecked());
}
void Shell::OnExit(v8::Isolate* isolate) {
if (i::FLAG_dump_counters) {
int number_of_counters = 0;
for (CounterMap::Iterator i(counter_map_); i.More(); i.Next()) {
number_of_counters++;
}
CounterAndKey* counters = new CounterAndKey[number_of_counters];
int j = 0;
for (CounterMap::Iterator i(counter_map_); i.More(); i.Next(), j++) {
counters[j].counter = i.CurrentValue();
counters[j].key = i.CurrentKey();
}
std::sort(counters, counters + number_of_counters);
printf("+----------------------------------------------------------------+"
"-------------+\n");
printf("| Name |"
" Value |\n");
printf("+----------------------------------------------------------------+"
"-------------+\n");
for (j = 0; j < number_of_counters; j++) {
Counter* counter = counters[j].counter;
const char* key = counters[j].key;
if (counter->is_histogram()) {
printf("| c:%-60s | %11i |\n", key, counter->count());
printf("| t:%-60s | %11i |\n", key, counter->sample_total());
} else {
printf("| %-62s | %11i |\n", key, counter->count());
}
}
printf("+----------------------------------------------------------------+"
"-------------+\n");
delete [] counters;
}
delete counters_file_;
delete counter_map_;
}
static FILE* FOpen(const char* path, const char* mode) {
#if defined(_MSC_VER) && (defined(_WIN32) || defined(_WIN64))
FILE* result;
if (fopen_s(&result, path, mode) == 0) {
return result;
} else {
return NULL;
}
#else
FILE* file = fopen(path, mode);
if (file == NULL) return NULL;
struct stat file_stat;
if (fstat(fileno(file), &file_stat) != 0) return NULL;
bool is_regular_file = ((file_stat.st_mode & S_IFREG) != 0);
if (is_regular_file) return file;
fclose(file);
return NULL;
#endif
}
static char* ReadChars(Isolate* isolate, const char* name, int* size_out) {
FILE* file = FOpen(name, "rb");
if (file == NULL) return NULL;
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (size_t i = 0; i < size;) {
i += fread(&chars[i], 1, size - i, file);
if (ferror(file)) {
fclose(file);
delete[] chars;
return nullptr;
}
}
fclose(file);
*size_out = static_cast<int>(size);
return chars;
}
struct DataAndPersistent {
uint8_t* data;
int byte_length;
Global<ArrayBuffer> handle;
};
static void ReadBufferWeakCallback(
const v8::WeakCallbackInfo<DataAndPersistent>& data) {
int byte_length = data.GetParameter()->byte_length;
data.GetIsolate()->AdjustAmountOfExternalAllocatedMemory(
-static_cast<intptr_t>(byte_length));
delete[] data.GetParameter()->data;
data.GetParameter()->handle.Reset();
delete data.GetParameter();
}
void Shell::ReadBuffer(const v8::FunctionCallbackInfo<v8::Value>& args) {
DCHECK(sizeof(char) == sizeof(uint8_t)); // NOLINT
String::Utf8Value filename(args[0]);
int length;
if (*filename == NULL) {
Throw(args.GetIsolate(), "Error loading file");
return;
}
Isolate* isolate = args.GetIsolate();
DataAndPersistent* data = new DataAndPersistent;
data->data = reinterpret_cast<uint8_t*>(
ReadChars(args.GetIsolate(), *filename, &length));
if (data->data == NULL) {
delete data;
Throw(args.GetIsolate(), "Error reading file");
return;
}
data->byte_length = length;
Local<v8::ArrayBuffer> buffer = ArrayBuffer::New(isolate, data->data, length);
data->handle.Reset(isolate, buffer);
data->handle.SetWeak(data, ReadBufferWeakCallback,
v8::WeakCallbackType::kParameter);
data->handle.MarkIndependent();
isolate->AdjustAmountOfExternalAllocatedMemory(length);
args.GetReturnValue().Set(buffer);
}
// Reads a file into a v8 string.
Local<String> Shell::ReadFile(Isolate* isolate, const char* name) {
int size = 0;
char* chars = ReadChars(isolate, name, &size);
if (chars == NULL) return Local<String>();
Local<String> result =
String::NewFromUtf8(isolate, chars, NewStringType::kNormal, size)
.ToLocalChecked();
delete[] chars;
return result;
}
void Shell::RunShell(Isolate* isolate) {
HandleScope outer_scope(isolate);
v8::Local<v8::Context> context =
v8::Local<v8::Context>::New(isolate, evaluation_context_);
v8::Context::Scope context_scope(context);
PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
Local<String> name =
String::NewFromUtf8(isolate, "(d8)", NewStringType::kNormal)
.ToLocalChecked();
printf("V8 version %s\n", V8::GetVersion());
while (true) {
HandleScope inner_scope(isolate);
printf("d8> ");
Local<String> input = Shell::ReadFromStdin(isolate);
if (input.IsEmpty()) break;
ExecuteString(isolate, input, name, true, true);
}
printf("\n");
}
#ifdef V8_INSPECTOR_ENABLED
class InspectorFrontend final : public v8_inspector::V8Inspector::Channel {
public:
explicit InspectorFrontend(Local<Context> context) {
isolate_ = context->GetIsolate();
context_.Reset(isolate_, context);
}
virtual ~InspectorFrontend() = default;
private:
void sendProtocolResponse(int callId,
const v8_inspector::StringView& message) override {
Send(message);
}
void sendProtocolNotification(
const v8_inspector::StringView& message) override {
Send(message);
}
void flushProtocolNotifications() override {}
void Send(const v8_inspector::StringView& string) {
int length = static_cast<int>(string.length());
DCHECK(length < v8::String::kMaxLength);
Local<String> message =
(string.is8Bit()
? v8::String::NewFromOneByte(
isolate_,
reinterpret_cast<const uint8_t*>(string.characters8()),
v8::NewStringType::kNormal, length)
: v8::String::NewFromTwoByte(
isolate_,
reinterpret_cast<const uint16_t*>(string.characters16()),
v8::NewStringType::kNormal, length))
.ToLocalChecked();
Local<String> callback_name =
v8::String::NewFromUtf8(isolate_, "receive", v8::NewStringType::kNormal)
.ToLocalChecked();
Local<Context> context = context_.Get(isolate_);
Local<Value> callback =
context->Global()->Get(context, callback_name).ToLocalChecked();
if (callback->IsFunction()) {
v8::TryCatch try_catch(isolate_);
Local<Value> args[] = {message};
if (Local<Function>::Cast(callback)
->Call(context, Undefined(isolate_), 1, args)
.IsEmpty()) {
try_catch.ReThrow();
}
}
}
Isolate* isolate_;
Global<Context> context_;
};
class InspectorClient : public v8_inspector::V8InspectorClient {
public:
InspectorClient(Local<Context> context, bool connect) {
if (!connect) return;
isolate_ = context->GetIsolate();
channel_.reset(new InspectorFrontend(context));
inspector_ = v8_inspector::V8Inspector::create(isolate_, this);
session_ =
inspector_->connect(1, channel_.get(), v8_inspector::StringView());
context->SetAlignedPointerInEmbedderData(kInspectorClientIndex, this);
inspector_->contextCreated(v8_inspector::V8ContextInfo(
context, kContextGroupId, v8_inspector::StringView()));
Local<Value> function =
FunctionTemplate::New(isolate_, SendInspectorMessage)
->GetFunction(context)
.ToLocalChecked();
Local<String> function_name =
String::NewFromUtf8(isolate_, "send", NewStringType::kNormal)
.ToLocalChecked();
CHECK(context->Global()->Set(context, function_name, function).FromJust());
context_.Reset(isolate_, context);
}
private:
static v8_inspector::V8InspectorSession* GetSession(Local<Context> context) {
InspectorClient* inspector_client = static_cast<InspectorClient*>(
context->GetAlignedPointerFromEmbedderData(kInspectorClientIndex));
return inspector_client->session_.get();
}
Local<Context> ensureDefaultContextInGroup(int group_id) override {
DCHECK(isolate_);
DCHECK_EQ(kContextGroupId, group_id);
return context_.Get(isolate_);
}
static void SendInspectorMessage(
const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
v8::HandleScope handle_scope(isolate);
Local<Context> context = isolate->GetCurrentContext();
args.GetReturnValue().Set(Undefined(isolate));
Local<String> message = args[0]->ToString(context).ToLocalChecked();
v8_inspector::V8InspectorSession* session =
InspectorClient::GetSession(context);
int length = message->Length();
std::unique_ptr<uint16_t> buffer(new uint16_t[length]);
message->Write(buffer.get(), 0, length);
v8_inspector::StringView message_view(buffer.get(), length);
session->dispatchProtocolMessage(message_view);
args.GetReturnValue().Set(True(isolate));
}
static const int kContextGroupId = 1;
std::unique_ptr<v8_inspector::V8Inspector> inspector_;
std::unique_ptr<v8_inspector::V8InspectorSession> session_;
std::unique_ptr<v8_inspector::V8Inspector::Channel> channel_;
Global<Context> context_;
Isolate* isolate_;
};
#else // V8_INSPECTOR_ENABLED
class InspectorClient {
public:
InspectorClient(Local<Context> context, bool connect) { CHECK(!connect); }
};
#endif // V8_INSPECTOR_ENABLED
SourceGroup::~SourceGroup() {
delete thread_;
thread_ = NULL;
}
void SourceGroup::Execute(Isolate* isolate) {
bool exception_was_thrown = false;
for (int i = begin_offset_; i < end_offset_; ++i) {
const char* arg = argv_[i];
if (strcmp(arg, "-e") == 0 && i + 1 < end_offset_) {
// Execute argument given to -e option directly.
HandleScope handle_scope(isolate);
Local<String> file_name =
String::NewFromUtf8(isolate, "unnamed", NewStringType::kNormal)
.ToLocalChecked();
Local<String> source =
String::NewFromUtf8(isolate, argv_[i + 1], NewStringType::kNormal)
.ToLocalChecked();
Shell::options.script_executed = true;
if (!Shell::ExecuteString(isolate, source, file_name, false, true)) {
exception_was_thrown = true;
break;
}
++i;
continue;
} else if (strcmp(arg, "--module") == 0 && i + 1 < end_offset_) {
// Treat the next file as a module.
arg = argv_[++i];
Shell::options.script_executed = true;
if (!Shell::ExecuteModule(isolate, arg)) {
exception_was_thrown = true;
break;
}
continue;
} else if (arg[0] == '-') {
// Ignore other options. They have been parsed already.
continue;
}
// Use all other arguments as names of files to load and run.
HandleScope handle_scope(isolate);
Local<String> file_name =
String::NewFromUtf8(isolate, arg, NewStringType::kNormal)
.ToLocalChecked();
Local<String> source = ReadFile(isolate, arg);
if (source.IsEmpty()) {
printf("Error reading '%s'\n", arg);
Shell::Exit(1);
}
Shell::options.script_executed = true;
if (!Shell::ExecuteString(isolate, source, file_name, false, true)) {
exception_was_thrown = true;
break;
}
}
if (exception_was_thrown != Shell::options.expected_to_throw) {
Shell::Exit(1);
}
}
Local<String> SourceGroup::ReadFile(Isolate* isolate, const char* name) {
int size;
char* chars = ReadChars(isolate, name, &size);
if (chars == NULL) return Local<String>();
Local<String> result =
String::NewFromUtf8(isolate, chars, NewStringType::kNormal, size)
.ToLocalChecked();
delete[] chars;
return result;
}
base::Thread::Options SourceGroup::GetThreadOptions() {
// On some systems (OSX 10.6) the stack size default is 0.5Mb or less
// which is not enough to parse the big literal expressions used in tests.
// The stack size should be at least StackGuard::kLimitSize + some
// OS-specific padding for thread startup code. 2Mbytes seems to be enough.
return base::Thread::Options("IsolateThread", 2 * MB);
}
void SourceGroup::ExecuteInThread() {
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = Shell::array_buffer_allocator;
Isolate* isolate = Isolate::New(create_params);
for (int i = 0; i < Shell::options.stress_runs; ++i) {
next_semaphore_.Wait();
{
Isolate::Scope iscope(isolate);
{
HandleScope scope(isolate);
PerIsolateData data(isolate);
Local<Context> context = Shell::CreateEvaluationContext(isolate);
{
Context::Scope cscope(context);
InspectorClient inspector_client(context,
Shell::options.enable_inspector);
PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
Execute(isolate);
}
DisposeModuleEmbedderData(context);
}
Shell::CollectGarbage(isolate);
}
done_semaphore_.Signal();
}
isolate->Dispose();
}
void SourceGroup::StartExecuteInThread() {
if (thread_ == NULL) {
thread_ = new IsolateThread(this);
thread_->Start();
}
next_semaphore_.Signal();
}
void SourceGroup::WaitForThread() {
if (thread_ == NULL) return;
done_semaphore_.Wait();
}
void SourceGroup::JoinThread() {
if (thread_ == NULL) return;
thread_->Join();
}
SerializationData::~SerializationData() {
// Any ArrayBuffer::Contents are owned by this SerializationData object if
// ownership hasn't been transferred out via ReadArrayBufferContents.
// SharedArrayBuffer::Contents may be used by multiple threads, so must be
// cleaned up by the main thread in Shell::CleanupWorkers().
for (int i = 0; i < array_buffer_contents_.length(); ++i) {
ArrayBuffer::Contents& contents = array_buffer_contents_[i];
if (contents.Data()) {
Shell::array_buffer_allocator->Free(contents.Data(),
contents.ByteLength());
}
}
}
void SerializationData::WriteTag(SerializationTag tag) { data_.Add(tag); }
void SerializationData::WriteMemory(const void* p, int length) {
if (length > 0) {
i::Vector<uint8_t> block = data_.AddBlock(0, length);
memcpy(&block[0], p, length);
}
}
void SerializationData::WriteArrayBufferContents(
const ArrayBuffer::Contents& contents) {
array_buffer_contents_.Add(contents);
WriteTag(kSerializationTagTransferredArrayBuffer);
int index = array_buffer_contents_.length() - 1;
Write(index);
}
void SerializationData::WriteSharedArrayBufferContents(
const SharedArrayBuffer::Contents& contents) {
shared_array_buffer_contents_.Add(contents);
WriteTag(kSerializationTagTransferredSharedArrayBuffer);
int index = shared_array_buffer_contents_.length() - 1;
Write(index);
}
SerializationTag SerializationData::ReadTag(int* offset) const {
return static_cast<SerializationTag>(Read<uint8_t>(offset));
}
void SerializationData::ReadMemory(void* p, int length, int* offset) const {
if (length > 0) {
memcpy(p, &data_[*offset], length);
(*offset) += length;
}
}
void SerializationData::ReadArrayBufferContents(ArrayBuffer::Contents* contents,
int* offset) const {
int index = Read<int>(offset);
DCHECK(index < array_buffer_contents_.length());
*contents = array_buffer_contents_[index];
// Ownership of this ArrayBuffer::Contents is passed to the caller. Neuter
// our copy so it won't be double-free'd when this SerializationData is
// destroyed.
array_buffer_contents_[index] = ArrayBuffer::Contents();
}
void SerializationData::ReadSharedArrayBufferContents(
SharedArrayBuffer::Contents* contents, int* offset) const {
int index = Read<int>(offset);
DCHECK(index < shared_array_buffer_contents_.length());
*contents = shared_array_buffer_contents_[index];
}
void SerializationDataQueue::Enqueue(SerializationData* data) {
base::LockGuard<base::Mutex> lock_guard(&mutex_);
data_.Add(data);
}
bool SerializationDataQueue::Dequeue(SerializationData** data) {
base::LockGuard<base::Mutex> lock_guard(&mutex_);
*data = NULL;
if (data_.is_empty()) return false;
*data = data_.Remove(0);
return true;
}
bool SerializationDataQueue::IsEmpty() {
base::LockGuard<base::Mutex> lock_guard(&mutex_);
return data_.is_empty();
}
void SerializationDataQueue::Clear() {
base::LockGuard<base::Mutex> lock_guard(&mutex_);
for (int i = 0; i < data_.length(); ++i) {
delete data_[i];
}
data_.Clear();
}
Worker::Worker()
: in_semaphore_(0),
out_semaphore_(0),
thread_(NULL),
script_(NULL),
running_(false) {}
Worker::~Worker() {
delete thread_;
thread_ = NULL;
delete[] script_;
script_ = NULL;
in_queue_.Clear();
out_queue_.Clear();
}
void Worker::StartExecuteInThread(const char* script) {
running_ = true;
script_ = i::StrDup(script);
thread_ = new WorkerThread(this);
thread_->Start();
}
void Worker::PostMessage(SerializationData* data) {
in_queue_.Enqueue(data);
in_semaphore_.Signal();
}
SerializationData* Worker::GetMessage() {
SerializationData* data = NULL;
while (!out_queue_.Dequeue(&data)) {
// If the worker is no longer running, and there are no messages in the
// queue, don't expect any more messages from it.
if (!base::NoBarrier_Load(&running_)) break;
out_semaphore_.Wait();
}
return data;
}
void Worker::Terminate() {
base::NoBarrier_Store(&running_, false);
// Post NULL to wake the Worker thread message loop, and tell it to stop
// running.
PostMessage(NULL);
}
void Worker::WaitForThread() {
Terminate();
thread_->Join();
}
void Worker::ExecuteInThread() {
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = Shell::array_buffer_allocator;
Isolate* isolate = Isolate::New(create_params);
{
Isolate::Scope iscope(isolate);
{
HandleScope scope(isolate);
PerIsolateData data(isolate);
Local<Context> context = Shell::CreateEvaluationContext(isolate);
{
Context::Scope cscope(context);
PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
Local<Object> global = context->Global();
Local<Value> this_value = External::New(isolate, this);
Local<FunctionTemplate> postmessage_fun_template =
FunctionTemplate::New(isolate, PostMessageOut, this_value);
Local<Function> postmessage_fun;
if (postmessage_fun_template->GetFunction(context)
.ToLocal(&postmessage_fun)) {
global->Set(context, String::NewFromUtf8(isolate, "postMessage",
NewStringType::kNormal)
.ToLocalChecked(),
postmessage_fun).FromJust();
}
// First run the script
Local<String> file_name =
String::NewFromUtf8(isolate, "unnamed", NewStringType::kNormal)
.ToLocalChecked();
Local<String> source =
String::NewFromUtf8(isolate, script_, NewStringType::kNormal)
.ToLocalChecked();
if (Shell::ExecuteString(isolate, source, file_name, false, true)) {
// Get the message handler
Local<Value> onmessage =
global->Get(context, String::NewFromUtf8(isolate, "onmessage",
NewStringType::kNormal)
.ToLocalChecked()).ToLocalChecked();
if (onmessage->IsFunction()) {
Local<Function> onmessage_fun = Local<Function>::Cast(onmessage);
// Now wait for messages
while (true) {
in_semaphore_.Wait();
SerializationData* data;
if (!in_queue_.Dequeue(&data)) continue;
if (data == NULL) {
break;
}
int offset = 0;
Local<Value> data_value;
if (Shell::DeserializeValue(isolate, *data, &offset)
.ToLocal(&data_value)) {
Local<Value> argv[] = {data_value};
(void)onmessage_fun->Call(context, global, 1, argv);
}
delete data;
}
}
}
}
DisposeModuleEmbedderData(context);
}
Shell::CollectGarbage(isolate);
}
isolate->Dispose();
// Post NULL to wake the thread waiting on GetMessage() if there is one.
out_queue_.Enqueue(NULL);
out_semaphore_.Signal();
}
void Worker::PostMessageOut(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
HandleScope handle_scope(isolate);
if (args.Length() < 1) {
Throw(isolate, "Invalid argument");
return;
}
Local<Value> message = args[0];
// TODO(binji): Allow transferring from worker to main thread?
Shell::ObjectList to_transfer;
Shell::ObjectList seen_objects;
SerializationData* data = new SerializationData;
if (Shell::SerializeValue(isolate, message, to_transfer, &seen_objects,
data)) {
DCHECK(args.Data()->IsExternal());
Local<External> this_value = Local<External>::Cast(args.Data());
Worker* worker = static_cast<Worker*>(this_value->Value());
worker->out_queue_.Enqueue(data);
worker->out_semaphore_.Signal();
} else {
delete data;
}
}
void SetFlagsFromString(const char* flags) {
v8::V8::SetFlagsFromString(flags, static_cast<int>(strlen(flags)));
}
bool Shell::SetOptions(int argc, char* argv[]) {
bool logfile_per_isolate = false;
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "--stress-opt") == 0) {
options.stress_opt = true;
argv[i] = NULL;
} else if (strcmp(argv[i], "--nostress-opt") == 0) {
options.stress_opt = false;
argv[i] = NULL;
} else if (strcmp(argv[i], "--stress-deopt") == 0) {
options.stress_deopt = true;
argv[i] = NULL;
} else if (strcmp(argv[i], "--mock-arraybuffer-allocator") == 0) {
options.mock_arraybuffer_allocator = true;
argv[i] = NULL;
} else if (strcmp(argv[i], "--noalways-opt") == 0) {
// No support for stressing if we can't use --always-opt.
options.stress_opt = false;
options.stress_deopt = false;
} else if (strcmp(argv[i], "--logfile-per-isolate") == 0) {
logfile_per_isolate = true;
argv[i] = NULL;
} else if (strcmp(argv[i], "--shell") == 0) {
options.interactive_shell = true;
argv[i] = NULL;
} else if (strcmp(argv[i], "--test") == 0) {
options.test_shell = true;
argv[i] = NULL;
} else if (strcmp(argv[i], "--notest") == 0 ||
strcmp(argv[i], "--no-test") == 0) {
options.test_shell = false;
argv[i] = NULL;
} else if (strcmp(argv[i], "--send-idle-notification") == 0) {
options.send_idle_notification = true;
argv[i] = NULL;
} else if (strcmp(argv[i], "--invoke-weak-callbacks") == 0) {
options.invoke_weak_callbacks = true;
// TODO(jochen) See issue 3351
options.send_idle_notification = true;
argv[i] = NULL;
} else if (strcmp(argv[i], "--omit-quit") == 0) {
options.omit_quit = true;
argv[i] = NULL;
} else if (strcmp(argv[i], "-f") == 0) {
// Ignore any -f flags for compatibility with other stand-alone
// JavaScript engines.
continue;
} else if (strcmp(argv[i], "--isolate") == 0) {
options.num_isolates++;
} else if (strcmp(argv[i], "--dump-heap-constants") == 0) {
options.dump_heap_constants = true;
argv[i] = NULL;
} else if (strcmp(argv[i], "--throws") == 0) {
options.expected_to_throw = true;
argv[i] = NULL;
} else if (strncmp(argv[i], "--icu-data-file=", 16) == 0) {
options.icu_data_file = argv[i] + 16;
argv[i] = NULL;
#ifdef V8_USE_EXTERNAL_STARTUP_DATA
} else if (strncmp(argv[i], "--natives_blob=", 15) == 0) {
options.natives_blob = argv[i] + 15;
argv[i] = NULL;
} else if (strncmp(argv[i], "--snapshot_blob=", 16) == 0) {
options.snapshot_blob = argv[i] + 16;
argv[i] = NULL;
#endif // V8_USE_EXTERNAL_STARTUP_DATA
} else if (strcmp(argv[i], "--cache") == 0 ||
strncmp(argv[i], "--cache=", 8) == 0) {
const char* value = argv[i] + 7;
if (!*value || strncmp(value, "=code", 6) == 0) {
options.compile_options = v8::ScriptCompiler::kProduceCodeCache;
} else if (strncmp(value, "=parse", 7) == 0) {
options.compile_options = v8::ScriptCompiler::kProduceParserCache;
} else if (strncmp(value, "=none", 6) == 0) {
options.compile_options = v8::ScriptCompiler::kNoCompileOptions;
} else {
printf("Unknown option to --cache.\n");
return false;
}
argv[i] = NULL;
} else if (strcmp(argv[i], "--enable-tracing") == 0) {
options.trace_enabled = true;
argv[i] = NULL;
} else if (strncmp(argv[i], "--trace-config=", 15) == 0) {
options.trace_config = argv[i] + 15;
argv[i] = NULL;
} else if (strcmp(argv[i], "--enable-inspector") == 0) {
options.enable_inspector = true;
argv[i] = NULL;
}
}
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
// Set up isolated source groups.
options.isolate_sources = new SourceGroup[options.num_isolates];
SourceGroup* current = options.isolate_sources;
current->Begin(argv, 1);
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
if (strcmp(str, "--isolate") == 0) {
current->End(i);
current++;
current->Begin(argv, i + 1);
} else if (strcmp(str, "--module") == 0) {
// Pass on to SourceGroup, which understands this option.
} else if (strncmp(argv[i], "--", 2) == 0) {
printf("Warning: unknown flag %s.\nTry --help for options\n", argv[i]);
} else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
options.script_executed = true;
} else if (strncmp(str, "-", 1) != 0) {
// Not a flag, so it must be a script to execute.
options.script_executed = true;
}
}
current->End(argc);
if (!logfile_per_isolate && options.num_isolates) {
SetFlagsFromString("--nologfile_per_isolate");
}
return true;
}
int Shell::RunMain(Isolate* isolate, int argc, char* argv[], bool last_run) {
for (int i = 1; i < options.num_isolates; ++i) {
options.isolate_sources[i].StartExecuteInThread();
}
{
HandleScope scope(isolate);
Local<Context> context = CreateEvaluationContext(isolate);
if (last_run && options.use_interactive_shell()) {
// Keep using the same context in the interactive shell.
evaluation_context_.Reset(isolate, context);
}
{
Context::Scope cscope(context);
InspectorClient inspector_client(context, options.enable_inspector);
PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
options.isolate_sources[0].Execute(isolate);
}
DisposeModuleEmbedderData(context);
}
CollectGarbage(isolate);
for (int i = 1; i < options.num_isolates; ++i) {
if (last_run) {
options.isolate_sources[i].JoinThread();
} else {
options.isolate_sources[i].WaitForThread();
}
}
CleanupWorkers();
return 0;
}
void Shell::CollectGarbage(Isolate* isolate) {
if (options.send_idle_notification) {
const double kLongIdlePauseInSeconds = 1.0;
isolate->ContextDisposedNotification();
isolate->IdleNotificationDeadline(
g_platform->MonotonicallyIncreasingTime() + kLongIdlePauseInSeconds);
}
if (options.invoke_weak_callbacks) {
// By sending a low memory notifications, we will try hard to collect all
// garbage and will therefore also invoke all weak callbacks of actually
// unreachable persistent handles.
isolate->LowMemoryNotification();
}
}
void Shell::EmptyMessageQueues(Isolate* isolate) {
if (!i::FLAG_verify_predictable) {
while (v8::platform::PumpMessageLoop(g_platform, isolate)) continue;
}
}
bool Shell::SerializeValue(Isolate* isolate, Local<Value> value,
const ObjectList& to_transfer,
ObjectList* seen_objects,
SerializationData* out_data) {
DCHECK(out_data);
Local<Context> context = isolate->GetCurrentContext();
if (value->IsUndefined()) {
out_data->WriteTag(kSerializationTagUndefined);
} else if (value->IsNull()) {
out_data->WriteTag(kSerializationTagNull);
} else if (value->IsTrue()) {
out_data->WriteTag(kSerializationTagTrue);
} else if (value->IsFalse()) {
out_data->WriteTag(kSerializationTagFalse);
} else if (value->IsNumber()) {
Local<Number> num = Local<Number>::Cast(value);
double value = num->Value();
out_data->WriteTag(kSerializationTagNumber);
out_data->Write(value);
} else if (value->IsString()) {
v8::String::Utf8Value str(value);
out_data->WriteTag(kSerializationTagString);
out_data->Write(str.length());
out_data->WriteMemory(*str, str.length());
} else if (value->IsArray()) {
Local<Array> array = Local<Array>::Cast(value);
if (FindInObjectList(array, *seen_objects)) {
Throw(isolate, "Duplicated arrays not supported");
return false;
}
seen_objects->Add(array);
out_data->WriteTag(kSerializationTagArray);
uint32_t length = array->Length();
out_data->Write(length);
for (uint32_t i = 0; i < length; ++i) {
Local<Value> element_value;
if (array->Get(context, i).ToLocal(&element_value)) {
if (!SerializeValue(isolate, element_value, to_transfer, seen_objects,
out_data))
return false;
} else {
Throw(isolate, "Failed to serialize array element.");
return false;
}
}
} else if (value->IsArrayBuffer()) {
Local<ArrayBuffer> array_buffer = Local<ArrayBuffer>::Cast(value);
if (FindInObjectList(array_buffer, *seen_objects)) {
Throw(isolate, "Duplicated array buffers not supported");
return false;
}
seen_objects->Add(array_buffer);
if (FindInObjectList(array_buffer, to_transfer)) {
// Transfer ArrayBuffer
if (!array_buffer->IsNeuterable()) {
Throw(isolate, "Attempting to transfer an un-neuterable ArrayBuffer");
return false;
}
ArrayBuffer::Contents contents = array_buffer->IsExternal()
? array_buffer->GetContents()
: array_buffer->Externalize();
array_buffer->Neuter();
out_data->WriteArrayBufferContents(contents);
} else {
ArrayBuffer::Contents contents = array_buffer->GetContents();
// Clone ArrayBuffer
if (contents.ByteLength() > i::kMaxInt) {
Throw(isolate, "ArrayBuffer is too big to clone");
return false;
}
int32_t byte_length = static_cast<int32_t>(contents.ByteLength());
out_data->WriteTag(kSerializationTagArrayBuffer);
out_data->Write(byte_length);
out_data->WriteMemory(contents.Data(), byte_length);
}
} else if (value->IsSharedArrayBuffer()) {
Local<SharedArrayBuffer> sab = Local<SharedArrayBuffer>::Cast(value);
if (FindInObjectList(sab, *seen_objects)) {
Throw(isolate, "Duplicated shared array buffers not supported");
return false;
}
seen_objects->Add(sab);
if (!FindInObjectList(sab, to_transfer)) {
Throw(isolate, "SharedArrayBuffer must be transferred");
return false;
}
SharedArrayBuffer::Contents contents;
if (sab->IsExternal()) {
contents = sab->GetContents();
} else {
contents = sab->Externalize();
base::LockGuard<base::Mutex> lock_guard(workers_mutex_.Pointer());
externalized_shared_contents_.Add(contents);
}
out_data->WriteSharedArrayBufferContents(contents);
} else if (value->IsObject()) {
Local<Object> object = Local<Object>::Cast(value);
if (FindInObjectList(object, *seen_objects)) {
Throw(isolate, "Duplicated objects not supported");
return false;
}
seen_objects->Add(object);
Local<Array> property_names;
if (!object->GetOwnPropertyNames(context).ToLocal(&property_names)) {
Throw(isolate, "Unable to get property names");
return false;
}
uint32_t length = property_names->Length();
out_data->WriteTag(kSerializationTagObject);
out_data->Write(length);
for (uint32_t i = 0; i < length; ++i) {
Local<Value> name;
Local<Value> property_value;
if (property_names->Get(context, i).ToLocal(&name) &&
object->Get(context, name).ToLocal(&property_value)) {
if (!SerializeValue(isolate, name, to_transfer, seen_objects, out_data))
return false;
if (!SerializeValue(isolate, property_value, to_transfer, seen_objects,
out_data))
return false;
} else {
Throw(isolate, "Failed to serialize property.");
return false;
}
}
} else {
Throw(isolate, "Don't know how to serialize object");
return false;
}
return true;
}
MaybeLocal<Value> Shell::DeserializeValue(Isolate* isolate,
const SerializationData& data,
int* offset) {
DCHECK(offset);
EscapableHandleScope scope(isolate);
Local<Value> result;
SerializationTag tag = data.ReadTag(offset);
switch (tag) {
case kSerializationTagUndefined:
result = Undefined(isolate);
break;
case kSerializationTagNull:
result = Null(isolate);
break;
case kSerializationTagTrue:
result = True(isolate);
break;
case kSerializationTagFalse:
result = False(isolate);
break;
case kSerializationTagNumber:
result = Number::New(isolate, data.Read<double>(offset));
break;
case kSerializationTagString: {
int length = data.Read<int>(offset);
CHECK(length >= 0);
std::vector<char> buffer(length + 1); // + 1 so it is never empty.
data.ReadMemory(&buffer[0], length, offset);
MaybeLocal<String> str =
String::NewFromUtf8(isolate, &buffer[0], NewStringType::kNormal,
length).ToLocalChecked();
if (!str.IsEmpty()) result = str.ToLocalChecked();
break;
}
case kSerializationTagArray: {
uint32_t length = data.Read<uint32_t>(offset);
Local<Array> array = Array::New(isolate, length);
for (uint32_t i = 0; i < length; ++i) {
Local<Value> element_value;
CHECK(DeserializeValue(isolate, data, offset).ToLocal(&element_value));
array->Set(isolate->GetCurrentContext(), i, element_value).FromJust();
}
result = array;
break;
}
case kSerializationTagObject: {
int length = data.Read<int>(offset);
Local<Object> object = Object::New(isolate);
for (int i = 0; i < length; ++i) {
Local<Value> property_name;
CHECK(DeserializeValue(isolate, data, offset).ToLocal(&property_name));
Local<Value> property_value;
CHECK(DeserializeValue(isolate, data, offset).ToLocal(&property_value));
object->Set(isolate->GetCurrentContext(), property_name, property_value)
.FromJust();
}
result = object;
break;
}
case kSerializationTagArrayBuffer: {
int32_t byte_length = data.Read<int32_t>(offset);
Local<ArrayBuffer> array_buffer = ArrayBuffer::New(isolate, byte_length);
ArrayBuffer::Contents contents = array_buffer->GetContents();
DCHECK(static_cast<size_t>(byte_length) == contents.ByteLength());
data.ReadMemory(contents.Data(), byte_length, offset);
result = array_buffer;
break;
}
case kSerializationTagTransferredArrayBuffer: {
ArrayBuffer::Contents contents;
data.ReadArrayBufferContents(&contents, offset);
result = ArrayBuffer::New(isolate, contents.Data(), contents.ByteLength(),
ArrayBufferCreationMode::kInternalized);
break;
}
case kSerializationTagTransferredSharedArrayBuffer: {
SharedArrayBuffer::Contents contents;
data.ReadSharedArrayBufferContents(&contents, offset);
result = SharedArrayBuffer::New(isolate, contents.Data(),
contents.ByteLength());
break;
}
default:
UNREACHABLE();
}
return scope.Escape(result);
}
void Shell::CleanupWorkers() {
// Make a copy of workers_, because we don't want to call Worker::Terminate
// while holding the workers_mutex_ lock. Otherwise, if a worker is about to
// create a new Worker, it would deadlock.
i::List<Worker*> workers_copy;
{
base::LockGuard<base::Mutex> lock_guard(workers_mutex_.Pointer());
allow_new_workers_ = false;
workers_copy.AddAll(workers_);
workers_.Clear();
}
for (int i = 0; i < workers_copy.length(); ++i) {
Worker* worker = workers_copy[i];
worker->WaitForThread();
delete worker;
}
// Now that all workers are terminated, we can re-enable Worker creation.
base::LockGuard<base::Mutex> lock_guard(workers_mutex_.Pointer());
allow_new_workers_ = true;
for (int i = 0; i < externalized_shared_contents_.length(); ++i) {
const SharedArrayBuffer::Contents& contents =
externalized_shared_contents_[i];
Shell::array_buffer_allocator->Free(contents.Data(), contents.ByteLength());
}
externalized_shared_contents_.Clear();
}
static void DumpHeapConstants(i::Isolate* isolate) {
i::Heap* heap = isolate->heap();
// Dump the INSTANCE_TYPES table to the console.
printf("# List of known V8 instance types.\n");
#define DUMP_TYPE(T) printf(" %d: \"%s\",\n", i::T, #T);
printf("INSTANCE_TYPES = {\n");
INSTANCE_TYPE_LIST(DUMP_TYPE)
printf("}\n");
#undef DUMP_TYPE
// Dump the KNOWN_MAP table to the console.
printf("\n# List of known V8 maps.\n");
#define ROOT_LIST_CASE(type, name, camel_name) \
if (n == NULL && o == heap->name()) n = #camel_name;
#define STRUCT_LIST_CASE(upper_name, camel_name, name) \
if (n == NULL && o == heap->name##_map()) n = #camel_name "Map";
i::HeapObjectIterator it(heap->map_space());
printf("KNOWN_MAPS = {\n");
for (i::Object* o = it.Next(); o != NULL; o = it.Next()) {
i::Map* m = i::Map::cast(o);
const char* n = NULL;
intptr_t p = reinterpret_cast<intptr_t>(m) & 0xfffff;
int t = m->instance_type();
ROOT_LIST(ROOT_LIST_CASE)
STRUCT_LIST(STRUCT_LIST_CASE)
if (n == NULL) continue;
printf(" 0x%05" V8PRIxPTR ": (%d, \"%s\"),\n", p, t, n);
}
printf("}\n");
#undef STRUCT_LIST_CASE
#undef ROOT_LIST_CASE
// Dump the KNOWN_OBJECTS table to the console.
printf("\n# List of known V8 objects.\n");
#define ROOT_LIST_CASE(type, name, camel_name) \
if (n == NULL && o == heap->name()) n = #camel_name;
i::OldSpaces spit(heap);
printf("KNOWN_OBJECTS = {\n");
for (i::PagedSpace* s = spit.next(); s != NULL; s = spit.next()) {
i::HeapObjectIterator it(s);
const char* sname = AllocationSpaceName(s->identity());
for (i::Object* o = it.Next(); o != NULL; o = it.Next()) {
const char* n = NULL;
intptr_t p = reinterpret_cast<intptr_t>(o) & 0xfffff;
ROOT_LIST(ROOT_LIST_CASE)
if (n == NULL) continue;
printf(" (\"%s\", 0x%05" V8PRIxPTR "): \"%s\",\n", sname, p, n);
}
}
printf("}\n");
#undef ROOT_LIST_CASE
}
int Shell::Main(int argc, char* argv[]) {
std::ofstream trace_file;
v8::base::debug::EnableInProcessStackDumping();
#if (defined(_WIN32) || defined(_WIN64))
UINT new_flags =
SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX;
UINT existing_flags = SetErrorMode(new_flags);
SetErrorMode(existing_flags | new_flags);
#if defined(_MSC_VER)
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
_set_error_mode(_OUT_TO_STDERR);
#endif // defined(_MSC_VER)
#endif // defined(_WIN32) || defined(_WIN64)
if (!SetOptions(argc, argv)) return 1;
v8::V8::InitializeICUDefaultLocation(argv[0], options.icu_data_file);
g_platform = i::FLAG_verify_predictable
? new PredictablePlatform()
: v8::platform::CreateDefaultPlatform();
v8::V8::InitializePlatform(g_platform);
v8::V8::Initialize();
if (options.natives_blob || options.snapshot_blob) {
v8::V8::InitializeExternalStartupData(options.natives_blob,
options.snapshot_blob);
} else {
v8::V8::InitializeExternalStartupData(argv[0]);
}
SetFlagsFromString("--trace-hydrogen-file=hydrogen.cfg");
SetFlagsFromString("--trace-turbo-cfg-file=turbo.cfg");
SetFlagsFromString("--redirect-code-traces-to=code.asm");
int result = 0;
Isolate::CreateParams create_params;
ShellArrayBufferAllocator shell_array_buffer_allocator;
MockArrayBufferAllocator mock_arraybuffer_allocator;
if (options.mock_arraybuffer_allocator) {
Shell::array_buffer_allocator = &mock_arraybuffer_allocator;
} else {
Shell::array_buffer_allocator = &shell_array_buffer_allocator;
}
create_params.array_buffer_allocator = Shell::array_buffer_allocator;
#ifdef ENABLE_VTUNE_JIT_INTERFACE
create_params.code_event_handler = vTune::GetVtuneCodeEventHandler();
#endif
create_params.constraints.ConfigureDefaults(
base::SysInfo::AmountOfPhysicalMemory(),
base::SysInfo::AmountOfVirtualMemory());
Shell::counter_map_ = new CounterMap();
if (i::FLAG_dump_counters || i::FLAG_track_gc_object_stats) {
create_params.counter_lookup_callback = LookupCounter;
create_params.create_histogram_callback = CreateHistogram;
create_params.add_histogram_sample_callback = AddHistogramSample;
}
Isolate* isolate = Isolate::New(create_params);
{
Isolate::Scope scope(isolate);
Initialize(isolate);
PerIsolateData data(isolate);
if (options.trace_enabled) {
trace_file.open("v8_trace.json");
platform::tracing::TracingController* tracing_controller =
new platform::tracing::TracingController();
platform::tracing::TraceBuffer* trace_buffer =
platform::tracing::TraceBuffer::CreateTraceBufferRingBuffer(
platform::tracing::TraceBuffer::kRingBufferChunks,
platform::tracing::TraceWriter::CreateJSONTraceWriter(
trace_file));
platform::tracing::TraceConfig* trace_config;
if (options.trace_config) {
int size = 0;
char* trace_config_json_str =
ReadChars(nullptr, options.trace_config, &size);
trace_config =
tracing::CreateTraceConfigFromJSON(isolate, trace_config_json_str);
delete[] trace_config_json_str;
} else {
trace_config =
platform::tracing::TraceConfig::CreateDefaultTraceConfig();
}
tracing_controller->Initialize(trace_buffer);
tracing_controller->StartTracing(trace_config);
if (!i::FLAG_verify_predictable) {
platform::SetTracingController(g_platform, tracing_controller);
}
}
if (options.dump_heap_constants) {
DumpHeapConstants(reinterpret_cast<i::Isolate*>(isolate));
return 0;
}
if (options.stress_opt || options.stress_deopt) {
Testing::SetStressRunType(options.stress_opt
? Testing::kStressTypeOpt
: Testing::kStressTypeDeopt);
options.stress_runs = Testing::GetStressRuns();
for (int i = 0; i < options.stress_runs && result == 0; i++) {
printf("============ Stress %d/%d ============\n", i + 1,
options.stress_runs);
Testing::PrepareStressRun(i);
bool last_run = i == options.stress_runs - 1;
result = RunMain(isolate, argc, argv, last_run);
}
printf("======== Full Deoptimization =======\n");
Testing::DeoptimizeAll(isolate);
} else if (i::FLAG_stress_runs > 0) {
options.stress_runs = i::FLAG_stress_runs;
for (int i = 0; i < options.stress_runs && result == 0; i++) {
printf("============ Run %d/%d ============\n", i + 1,
options.stress_runs);
bool last_run = i == options.stress_runs - 1;
result = RunMain(isolate, argc, argv, last_run);
}
} else {
bool last_run = true;
result = RunMain(isolate, argc, argv, last_run);
}
// Run interactive shell if explicitly requested or if no script has been
// executed, but never on --test
if (options.use_interactive_shell()) {
RunShell(isolate);
}
if (i::FLAG_trace_ignition_dispatches &&
i::FLAG_trace_ignition_dispatches_output_file != nullptr) {
WriteIgnitionDispatchCountersFile(isolate);
}
// Shut down contexts and collect garbage.
evaluation_context_.Reset();
stringify_function_.Reset();
CollectGarbage(isolate);
}
OnExit(isolate);
// Dump basic block profiling data.
if (i::BasicBlockProfiler* profiler =
reinterpret_cast<i::Isolate*>(isolate)->basic_block_profiler()) {
i::OFStream os(stdout);
os << *profiler;
}
isolate->Dispose();
V8::Dispose();
V8::ShutdownPlatform();
delete g_platform;
return result;
}
} // namespace v8
#ifndef GOOGLE3
int main(int argc, char* argv[]) {
return v8::Shell::Main(argc, argv);
}
#endif
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "CryLegacy_precompiled.h"
#include "SelectionCondition.h"
#include "SelectionVariables.h"
class SimpleLexer
{
public:
SimpleLexer(const char* buffer)
: m_buffer(buffer)
, m_obuffer(buffer)
{
}
int peek(string* ident = 0)
{
const char* obuffer = m_buffer;
string oident(m_ident);
int tok = operator()();
m_buffer = obuffer;
if (ident)
{
ident->swap(m_ident);
}
m_ident.swap(oident);
return tok;
}
const char* ident() const
{
return m_ident.c_str();
}
const char* buf() const
{
return m_obuffer;
}
int operator()()
{
while (unsigned char ch = *m_buffer++)
{
unsigned char next = *m_buffer;
switch (ch)
{
case '(':
case ')':
return (int)ch;
case '=':
if (next == '=')
{
++m_buffer;
return '==';
}
return ch;
case '!':
if (next == '=')
{
++m_buffer;
return '!=';
}
return ch;
default:
{
if (isalpha(ch) || (ch == '_'))
{
m_ident.clear();
m_ident.push_back(ch);
while ((ch = *m_buffer) && (isalnum(ch) || (ch == '.') || (ch == '_')))
{
++m_buffer;
m_ident.push_back(ch);
}
// keywords
if (!_stricmp(m_ident.c_str(), "or"))
{
return 'or';
}
else if (!_stricmp(m_ident.c_str(), "and"))
{
return 'and';
}
else if (!_stricmp(m_ident.c_str(), "xor"))
{
return 'xor';
}
else if (!_stricmp(m_ident.c_str(), "true"))
{
return 'true';
}
else if (!_stricmp(m_ident.c_str(), "false"))
{
return 'fals';
}
return 'var';
}
else if (isspace(ch))
{
continue;
}
return ch;
}
}
}
return 0;
}
private:
const char* m_buffer;
const char* m_obuffer;
string m_ident;
};
SelectionCondition::SelectionCondition()
: m_rootID(-1)
{
}
SelectionCondition::SelectionCondition(const char* condition, const SelectionVariableDeclarations& variables)
: m_rootID(Parse(condition, variables))
{
if (m_rootID >= 0)
{
Optimise();
}
}
int SelectionCondition::AddOp(const ConditionOp& op)
{
m_conditionOps.push_back(op);
return (int)m_conditionOps.size() - 1;
}
int SelectionCondition::ParseLogical(SimpleLexer& lex, int tok, const SelectionVariableDeclarations& variables)
{
int leftID = ParseCompOp(lex, tok, variables);
if (leftID == -1)
{
return -1;
}
while ((tok = lex.peek()) && (tok == 'and') || (tok == 'or') || (tok == 'xor'))
{
lex();
int rightID = ParseCompOp(lex, lex(), variables);
if (rightID == -1)
{
return -1;
}
switch (tok)
{
case 'or':
leftID = AddOp(ConditionOp(ConditionOp::Or, leftID, rightID));
break;
case 'and':
leftID = AddOp(ConditionOp(ConditionOp::And, leftID, rightID));
break;
case 'xor':
leftID = AddOp(ConditionOp(ConditionOp::Xor, leftID, rightID));
break;
}
}
return leftID;
}
int SelectionCondition::ParseCompOp(SimpleLexer& lex, int tok, const SelectionVariableDeclarations& variables)
{
int leftID = ParseUnary(lex, tok, variables);
if (leftID == -1)
{
return -1;
}
tok = lex.peek();
if ((tok == '==') || (tok == '!='))
{
lex();
int rightID = ParseUnary(lex, lex(), variables);
if (rightID == -1)
{
return -1;
}
switch (tok)
{
case '==':
return AddOp(ConditionOp(ConditionOp::Equal, leftID, rightID));
case '!=':
return AddOp(ConditionOp(ConditionOp::NotEqual, leftID, rightID));
}
}
return leftID;
}
int SelectionCondition::ParseUnary(SimpleLexer& lex, int tok, const SelectionVariableDeclarations& variables)
{
if (tok == '!')
{
int opID = ParseValue(lex, lex(), variables);
if (opID != -1)
{
return AddOp(ConditionOp(ConditionOp::Not, opID, -1));
}
return -1;
}
return ParseValue(lex, tok, variables);
}
int SelectionCondition::ParseValue(SimpleLexer& lex, int tok, const SelectionVariableDeclarations& variables)
{
if (tok == '(')
{
int opID = ParseLogical(lex, lex(), variables);
if ((opID == -1) || (lex() != ')'))
{
return -1;
}
return opID;
}
else if (tok == 'true')
{
return AddOp(ConditionOp(ConditionOp::Constant, true));
}
else if (tok == 'fals')
{
return AddOp(ConditionOp(ConditionOp::Constant, false));
}
else if (tok == 'var')
{
if (SelectionVariableID variableID = variables.GetVariableID(lex.ident()))
{
return AddOp(ConditionOp(ConditionOp::Variable, variableID));
}
else
{
AIWarning("Unknown variable '%s' used in condition '%s'...", lex.ident(), lex.buf());
}
}
return -1;
}
int SelectionCondition::Parse(const char* condition, const SelectionVariableDeclarations& variables)
{
SimpleLexer lex = SimpleLexer(condition);
return ParseLogical(lex, lex(), variables);
}
void SelectionCondition::Optimise()
{
// TODO(Marcio)
}
bool SelectionCondition::EvaluateOp(const SelectionVariables& variables, const ConditionOp& op) const
{
switch (op.opType)
{
case ConditionOp::Variable:
{
bool value = false;
variables.GetVariable(op.variableID, &value);
return value;
}
case ConditionOp::Constant:
return op.value;
case ConditionOp::Or:
return EvaluateOp(variables, m_conditionOps[op.operandLeft])
|| EvaluateOp(variables, m_conditionOps[op.operandRight]);
case ConditionOp::And:
return EvaluateOp(variables, m_conditionOps[op.operandLeft])
&& EvaluateOp(variables, m_conditionOps[op.operandRight]);
case ConditionOp::Xor:
return EvaluateOp(variables, m_conditionOps[op.operandLeft])
^ EvaluateOp(variables, m_conditionOps[op.operandRight]);
case ConditionOp::Not:
return !EvaluateOp(variables, m_conditionOps[op.operandLeft]);
case ConditionOp::Equal:
return EvaluateOp(variables, m_conditionOps[op.operandLeft])
== EvaluateOp(variables, m_conditionOps[op.operandRight]);
case ConditionOp::NotEqual:
return EvaluateOp(variables, m_conditionOps[op.operandLeft])
!= EvaluateOp(variables, m_conditionOps[op.operandRight]);
}
return false;
}
bool SelectionCondition::Evaluate(const SelectionVariables& variables) const
{
if (Valid())
{
return EvaluateOp(variables, m_conditionOps[m_rootID]);
}
return false;
}
bool SelectionCondition::Valid() const
{
return m_rootID >= 0;
}
|
#include <iostream>
#include <set>
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n; std::cin >> n;
std::set<int> ng;
for (int i = 0; i < 3; i++) {
int x; std::cin >> x;
ng.insert(x);
}
if (ng.count(n)) {
std::cout << "NO" << '\n';
return 0;
}
for (int i = 0; i < 100; i++) {
bool ok = false;
for (int j = 3; j > 0; j--) {
if (ng.count(n - j)) continue;
ok = true;
n -= j;
break;
}
if (!ok) {
std::cout << "NO" << '\n';
return 0;
}
if (n <= 0) {
std::cout << "YES" << '\n';
return 0;
}
}
std::cout << "NO" << '\n';
}
|
/////////////////////////////////////////////////////////////////////////////
// Name: src/html/helpdlg.cpp
// Purpose: wxHtmlHelpDialog
// Notes: Based on htmlhelp.cpp, implementing a monolithic
// HTML Help controller class, by Vaclav Slavik
// Author: Harm van der Heijden, Vaclav Slavik and Julian Smart
// Copyright: (c) Harm van der Heijden, Vaclav Slavik and Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h"
#include "wx/wxprec.h"
#if wxUSE_WXHTML_HELP
#ifndef WX_PRECOMP
#include "wx/object.h"
#include "wx/intl.h"
#include "wx/log.h"
#include "wx/sizer.h"
#include "wx/bmpbuttn.h"
#include "wx/statbox.h"
#include "wx/radiobox.h"
#include "wx/menu.h"
#include "wx/msgdlg.h"
#endif // WX_PRECOMP
#include "wx/html/htmlwin.h"
#include "wx/html/helpdlg.h"
#include "wx/html/helpctrl.h"
#include "wx/artprov.h"
wxIMPLEMENT_DYNAMIC_CLASS(wxHtmlHelpDialog, wxDialog);
wxBEGIN_EVENT_TABLE(wxHtmlHelpDialog, wxDialog)
EVT_CLOSE(wxHtmlHelpDialog::OnCloseWindow)
wxEND_EVENT_TABLE()
wxHtmlHelpDialog::wxHtmlHelpDialog(wxWindow* parent, wxWindowID id, const wxString& title,
int style, wxHtmlHelpData* data)
{
Init(data);
Create(parent, id, title, style);
}
void wxHtmlHelpDialog::Init(wxHtmlHelpData* data)
{
// Simply pass the pointer on to the help window
m_Data = data;
m_HtmlHelpWin = NULL;
m_helpController = NULL;
}
// Create: builds the GUI components.
bool wxHtmlHelpDialog::Create(wxWindow* parent, wxWindowID id,
const wxString& WXUNUSED(title), int style)
{
m_HtmlHelpWin = new wxHtmlHelpWindow(m_Data);
wxDialog::Create(parent, id, _("Help"),
wxPoint(m_HtmlHelpWin->GetCfgData().x, m_HtmlHelpWin->GetCfgData().y),
wxSize(m_HtmlHelpWin->GetCfgData().w, m_HtmlHelpWin->GetCfgData().h),
wxDEFAULT_FRAME_STYLE|wxRESIZE_BORDER, wxT("wxHtmlHelp"));
m_HtmlHelpWin->Create(this, wxID_ANY, wxDefaultPosition, GetClientSize(),
wxTAB_TRAVERSAL|wxNO_BORDER, style);
GetPosition(& (m_HtmlHelpWin->GetCfgData().x), & (m_HtmlHelpWin->GetCfgData()).y);
SetIcon(wxArtProvider::GetIcon(wxART_HELP, wxART_HELP_BROWSER));
wxWindow* item1 = this;
wxBoxSizer* item2 = new wxBoxSizer(wxVERTICAL);
item1->SetSizer(item2);
wxWindow* item3 = m_HtmlHelpWin;
item2->Add(item3, 1, wxGROW|wxALL, 5);
wxBoxSizer* item4 = new wxBoxSizer(wxHORIZONTAL);
item2->Add(item4, 0, wxGROW, 5);
item4->Add(5, 5, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxButton* item6 = new wxButton(item1, wxID_OK, _("Close"), wxDefaultPosition, wxDefaultSize, 0);
item4->Add(item6, 0, wxALIGN_CENTER_VERTICAL|wxALL, 10);
#ifdef __WXMAC__
// Add some space for the resize handle
item4->Add(5, 5, 0, wxALIGN_CENTER_VERTICAL, 0);
#endif
Layout();
Centre();
return true;
}
wxHtmlHelpDialog::~wxHtmlHelpDialog()
{
}
void wxHtmlHelpDialog::SetTitleFormat(const wxString& format)
{
m_TitleFormat = format;
}
void wxHtmlHelpDialog::OnCloseWindow(wxCloseEvent& evt)
{
if (!IsIconized())
{
GetSize(& (m_HtmlHelpWin->GetCfgData().w), &(m_HtmlHelpWin->GetCfgData().h));
GetPosition(& (m_HtmlHelpWin->GetCfgData().x), & (m_HtmlHelpWin->GetCfgData().y));
}
if (m_HtmlHelpWin->GetSplitterWindow() && m_HtmlHelpWin->GetCfgData().navig_on)
m_HtmlHelpWin->GetCfgData().sashpos = m_HtmlHelpWin->GetSplitterWindow()->GetSashPosition();
if (m_helpController)
{
m_helpController->OnCloseFrame(evt);
}
evt.Skip();
}
#endif // wxUSE_WXHTML_HELP
|
#ifndef _ML_STANDARD_HPP_
#define _ML_STANDARD_HPP_
#include <modus_core/Preprocessor.hpp>
static_assert(ML_has_cxx14);
#include <cassert>
#include <chrono>
#include <cwchar>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <sstream>
#include <unordered_map>
#include <stdarg.h>
#include <vector>
static_assert(ML_has_cxx17);
#include <any>
#include <filesystem>
#include <memory_resource>
#include <optional>
#include <string_view>
#include <variant>
namespace ml
{
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
namespace std = ::std;
namespace chrono = std::chrono;
namespace fs = std::filesystem;
namespace pmr = std::pmr;
#if (ML_has_cxx20)
namespace ranges = std::ranges;
namespace views = std::ranges::views;
#endif
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
ML_alias byte = typename ML_byte ; //
ML_alias int8 = typename ML_int8 ; //
ML_alias int16 = typename ML_int16 ; //
ML_alias int32 = typename ML_int32 ; //
ML_alias int64 = typename ML_int64 ; //
ML_alias uint8 = typename ML_uint8 ; //
ML_alias uint16 = typename ML_uint16 ; //
ML_alias uint32 = typename ML_uint32 ; //
ML_alias uint64 = typename ML_uint64 ; //
ML_alias float32 = typename ML_float32 ; //
ML_alias float64 = typename ML_float64 ; //
ML_alias float80 = typename ML_float80 ; //
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#if (ML_arch == 32)
ML_alias intmax_t = typename int32 ; //
ML_alias uintmax_t = typename uint32 ; //
#else
ML_alias intmax_t = typename int64 ; //
ML_alias uintmax_t = typename uint64 ; //
#endif
ML_alias double_t = typename float64 ; //
ML_alias float_t = typename float32 ; //
ML_alias hash_t = typename uintmax_t ; //
ML_alias intptr_t = typename intmax_t ; //
ML_alias ptrdiff_t = typename intmax_t ; //
ML_alias size_t = typename uintmax_t ; //
ML_alias max_align_t = typename float64 ; //
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
ML_alias cstring = typename char const * ; //
ML_alias cwstring = typename wchar_t const * ; //
#if (ML_has_cxx20)
ML_alias c8string = typename char8_t const * ; //
#endif
ML_alias c16string = typename char16_t const * ; //
ML_alias c32string = typename char32_t const * ; //
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
}
#endif // !_ML_STANDARD_HPP_
|
/**********************************************************************
* File: search_node.cpp
* Description: Implementation of the Beam Search Node Class
* Author: Ahmad Abdulkader
* Created: 2008
*
* (C) Copyright 2008, Google Inc.
** 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 "search_node.h"
namespace tesseract {
// The constructor updates the best paths and costs:
// mean_char_reco_cost_ (returned by BestRecoCost()) is the mean
// char_reco cost of the best_path, including this node.
// best_path_reco_cost is the total char_reco_cost of the best_path,
// but excludes the char_reco_cost of this node.
// best_cost is the mean mixed cost, i.e., mean_char_reco_cost_ +
// current language model cost, all weighted by the cube context's
// RecoWgt parameter
SearchNode::SearchNode(CubeRecoContext *cntxt, SearchNode *parent_node,
int char_reco_cost, LangModEdge *edge, int col_idx) {
// copy data members
cntxt_ = cntxt;
lang_mod_edge_ = edge;
col_idx_ = col_idx;
parent_node_ = parent_node;
char_reco_cost_ = char_reco_cost;
// the string of this node is the same as that of the language model edge
str_ = (edge == NULL ? NULL : edge->EdgeString());
// compute best path total reco cost
best_path_reco_cost_ = (parent_node_ == NULL) ? 0 :
parent_node_->CharRecoCost() + parent_node_->BestPathRecoCost();
// update best path length
best_path_len_ = (parent_node_ == NULL) ?
1 : parent_node_->BestPathLength() + 1;
if (edge != NULL && edge->IsRoot() && parent_node_ != NULL) {
best_path_len_++;
}
// compute best reco cost mean cost
mean_char_reco_cost_ = static_cast<int>(
(best_path_reco_cost_ + char_reco_cost_) /
static_cast<double>(best_path_len_));
// get language model cost
int lm_cost = LangModCost(lang_mod_edge_, parent_node_);
// compute aggregate best cost
best_cost_ = static_cast<int>(cntxt_->Params()->RecoWgt() *
(best_path_reco_cost_ + char_reco_cost_) /
static_cast<double>(best_path_len_)
) + lm_cost;
}
SearchNode::~SearchNode() {
if (lang_mod_edge_ != NULL) {
delete lang_mod_edge_;
}
}
// update the parent_node node if provides a better (less) cost
bool SearchNode::UpdateParent(SearchNode *new_parent, int new_reco_cost,
LangModEdge *new_edge) {
if (lang_mod_edge_ == NULL) {
if (new_edge != NULL) {
return false;
}
} else {
// to update the parent_node, we have to have the same target
// state and char
if (new_edge == NULL || !lang_mod_edge_->IsIdentical(new_edge) ||
!SearchNode::IdenticalPath(parent_node_, new_parent)) {
return false;
}
}
// compute the path cost and combined cost of the new path
int new_best_path_reco_cost;
int new_cost;
int new_best_path_len;
new_best_path_reco_cost = (new_parent == NULL) ?
0 : new_parent->BestPathRecoCost() + new_parent->CharRecoCost();
new_best_path_len =
(new_parent == NULL) ? 1 : new_parent->BestPathLength() + 1;
// compute the new language model cost
int new_lm_cost = LangModCost(new_edge, new_parent);
new_cost = static_cast<int>(cntxt_->Params()->RecoWgt() *
(new_best_path_reco_cost + new_reco_cost) /
static_cast<double>(new_best_path_len)
) + new_lm_cost;
// update if it is better (less) than the current one
if (best_cost_ > new_cost) {
parent_node_ = new_parent;
char_reco_cost_ = new_reco_cost;
best_path_reco_cost_ = new_best_path_reco_cost;
best_path_len_ = new_best_path_len;
mean_char_reco_cost_ = static_cast<int>(
(best_path_reco_cost_ + char_reco_cost_) /
static_cast<double>(best_path_len_));
best_cost_ = static_cast<int>(cntxt_->Params()->RecoWgt() *
(best_path_reco_cost_ + char_reco_cost_) /
static_cast<double>(best_path_len_)
) + new_lm_cost;
return true;
}
return false;
}
char_32 *SearchNode::PathString() {
SearchNode *node = this;
// compute string length
int len = 0;
while (node != NULL) {
if (node->str_ != NULL) {
len += CubeUtils::StrLen(node->str_);
}
// if the edge is a root and does not have a NULL parent, account for space
LangModEdge *lm_edge = node->LangModelEdge();
if (lm_edge != NULL && lm_edge->IsRoot() && node->ParentNode() != NULL) {
len++;
}
node = node->parent_node_;
}
char_32 *char_ptr = new char_32[len + 1];
if (char_ptr == NULL) {
return NULL;
}
int ch_idx = len;
node = this;
char_ptr[ch_idx--] = 0;
while (node != NULL) {
int str_len = ((node->str_ == NULL) ? 0 : CubeUtils::StrLen(node->str_));
while (str_len > 0) {
char_ptr[ch_idx--] = node->str_[--str_len];
}
// if the edge is a root and does not have a NULL parent, insert a space
LangModEdge *lm_edge = node->LangModelEdge();
if (lm_edge != NULL && lm_edge->IsRoot() && node->ParentNode() != NULL) {
char_ptr[ch_idx--] = (char_32)' ';
}
node = node->parent_node_;
}
return char_ptr;
}
// compares the path of two nodes and checks if its identical
bool SearchNode::IdenticalPath(SearchNode *node1, SearchNode *node2) {
if (node1 != NULL && node2 != NULL &&
node1->best_path_len_ != node2->best_path_len_) {
return false;
}
// backtrack until either a root or a NULL edge is reached
while (node1 != NULL && node2 != NULL) {
if (node1->str_ != node2->str_) {
return false;
}
// stop if either nodes is a root
if (node1->LangModelEdge()->IsRoot() || node2->LangModelEdge()->IsRoot()) {
break;
}
node1 = node1->parent_node_;
node2 = node2->parent_node_;
}
return ((node1 == NULL && node2 == NULL) ||
(node1 != NULL && node1->LangModelEdge()->IsRoot() &&
node2 != NULL && node2->LangModelEdge()->IsRoot()));
}
// Computes the language model cost of a path
int SearchNode::LangModCost(LangModEdge *current_lm_edge,
SearchNode *parent_node) {
int lm_cost = 0;
int node_cnt = 0;
do {
// check if root
bool is_root = ((current_lm_edge != NULL && current_lm_edge->IsRoot()) ||
parent_node == NULL);
if (is_root) {
node_cnt++;
lm_cost += (current_lm_edge == NULL ? 0 : current_lm_edge->PathCost());
}
// continue until we hit a null parent
if (parent_node == NULL) {
break;
}
// get the previous language model edge
current_lm_edge = parent_node->LangModelEdge();
// back track
parent_node = parent_node->ParentNode();
} while (true);
return static_cast<int>(lm_cost / static_cast<double>(node_cnt));
}
} // namespace tesseract
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <float.h>
#include <math.h>
#include "common.h"
// Copyright 2004-present Facebook. All Rights Reserved.
// Constructs a rounding factor used to truncate elements in a sum
// such that the sum of the truncated elements is the same no matter
// what the order of the sum is.
//
// Floating point summation is not associative; using this factor
// makes it associative, so a parallel sum can be performed in any
// order (presumably using atomics).
//
// Follows Algorithm 5: Reproducible Sequential Sum in
// 'Fast Reproducible Floating-Point Summation' by Demmel and Nguyen
// http://www.eecs.berkeley.edu/~hdnguyen/public/papers/ARITH21_Fast_Sum.pdf
//
// For summing x_i, i = 1 to n:
// @param max The maximum seen floating point value abs(x_i)
// @param n The number of elements for the sum, or an upper bound estimate
inline float
createRoundingFactor(float max, int n) {
float delta = (max * (float)n) / (1.f - 2.f * (float)n * FLT_EPSILON);
// Calculate ceil(log_2(delta)).
// frexpf() calculates exp and returns `x` such that
// delta = x * 2^exp, where `x` in (-1.0, -0.5] U [0.5, 1).
// Because |x| < 1, exp is exactly ceil(log_2(delta)).
int exp;
sycl::frexp(delta, &exp);
// return M = 2 ^ ceil(log_2(delta))
return sycl::ldexp(1.f, exp);
}
// Given the rounding factor in `createRoundingFactor` calculated
// using max(|x_i|), truncate `x` to a value that can be used for a
// deterministic, reproducible parallel sum of all x_i.
inline float
truncateWithRoundingFactor(float roundingFactor, float x) {
return (roundingFactor + x) - // rounded
roundingFactor; // exactly
}
void sumArray (
nd_item<1> &item,
const float factor,
const int length,
const float *__restrict__ x,
float *__restrict__ r)
{
for (int i = item.get_global_id(0); i < length;
i += item.get_local_range(0) * item.get_group_range(0)) {
float q = truncateWithRoundingFactor(factor, x[i]);
// atomicAdd(r, q); // sum in any order
auto ao = ext::oneapi::atomic_ref<float,
ext::oneapi::memory_order::relaxed,
ext::oneapi::memory_scope::device,
access::address_space::global_space> (r[0]);
ao.fetch_add(q);
}
}
void sumArrays (
nd_item<1> &item,
const int nArrays,
const int length,
const float *__restrict__ x,
float *__restrict__ r,
const float *__restrict__ maxVal)
{
for (int i = item.get_global_id(0); i < nArrays;
i += item.get_local_range(0) * item.get_group_range(0)) {
x += i * length;
float factor = createRoundingFactor(maxVal[i], length);
float s = 0;
for (int n = length-1; n >= 0; n--) // sum in reverse order
s += truncateWithRoundingFactor(factor, x[n]);
r[i] = s;
}
}
int main(int argc, char* argv[]) {
if (argc != 3) {
printf("Usage: %s <number of arrays> <length of each array>\n", argv[0]);
return 1;
}
const int nArrays = atoi(argv[1]);
const int nElems = atoi(argv[2]);
const size_t narray_size = sizeof(float) * nArrays;
const size_t array_size = narray_size * nElems;
// set of arrays
float *arrays = (float*) malloc (array_size);
// max value of each array
float *maxVal = (float*) malloc (narray_size);
// sum of each array
float *result = (float*) malloc (narray_size);
// rounding factor of each array
float *factor = (float*) malloc (narray_size);
// reference sum of each array
float *result_ref = (float*) malloc (narray_size);
srand(123);
// compute max value and rounding factor of each array on a host
float *arr = arrays;
for (int n = 0; n < nArrays; n++) {
float max = 0;
for (int i = 0; i < nElems; i++) {
arr[i] = (float)rand() / (float)RAND_MAX;
if (rand() % 2) arr[i] = -1.f * arr[i];
max = fmaxf(fabs(arr[i]), max);
}
factor[n] = createRoundingFactor(max, nElems);
maxVal[n] = max;
arr += nElems;
}
// compute the sum of each array on a host
arr = arrays;
for (int n = 0; n < nArrays; n++) {
result_ref[n] = 0;
for (int i = 0; i < nElems; i++)
result_ref[n] += truncateWithRoundingFactor(factor[n], arr[i]);
arr += nElems;
}
#ifdef USE_GPU
gpu_selector dev_sel;
#else
cpu_selector dev_sel;
#endif
queue q(dev_sel);
buffer<float, 1> d_arrays (arrays, nArrays * nElems);
buffer<float, 1> d_maxVal (maxVal, nArrays);
buffer<float, 1> d_result (nArrays);
range<1> gws (256*256);
range<1> lws (256);
// reset results for the sumArray kernel
q.submit([&] (handler &cgh) {
auto acc = d_result.get_access<sycl_discard_write>(cgh);
cgh.fill(acc, 0.f);
});
for (int n = 0; n < nArrays; n++) {
// sum over each array
const float f = factor[n];
q.submit([&] (handler &cgh) {
auto arr = d_arrays.get_access<sycl_read>(cgh, range<1>(nElems), id<1>(n*nElems));
auto out = d_result.get_access<sycl_read_write>(cgh, range<1>(1), id<1>(n));
cgh.parallel_for<class sum_array>(nd_range<1>(gws, lws), [=] (nd_item<1> item) {
sumArray (item, f, nElems, arr.get_pointer(), out.get_pointer());
});
});
}
// bit accurate sum
q.submit([&] (handler &cgh) {
auto acc = d_result.get_access<sycl_read>(cgh);
cgh.copy(acc, result);
}).wait();
bool ok = !memcmp(result_ref, result, narray_size);
printf("%s\n", ok ? "PASS" : "FAIL");
// sum over arrays
q.submit([&] (handler &cgh) {
auto arr = d_arrays.get_access<sycl_read>(cgh);
auto out = d_result.get_access<sycl_discard_write>(cgh);
auto max = d_maxVal.get_access<sycl_read>(cgh);
cgh.parallel_for<class sum_arrays>(nd_range<1>(gws, lws), [=] (nd_item<1> item) {
sumArrays (item, nArrays, nElems, arr.get_pointer(),
out.get_pointer(), max.get_pointer());
});
});
// bit accurate sum
q.submit([&] (handler &cgh) {
auto acc = d_result.get_access<sycl_read>(cgh);
cgh.copy(acc, result);
}).wait();
ok = !memcmp(result_ref, result, narray_size);
printf("%s\n", ok ? "PASS" : "FAIL");
free(arrays);
free(maxVal);
free(result);
free(factor);
free(result_ref);
return 0;
}
|
//
// Created by juan.castellanos on 10/01/20.
//
#include "OCP/Specification.h"
#include "OCP/Product.h"
bool ColorSpecification::is_satisfied(Product* item)
{
return item->color == _color;
}
bool SizeSpecification::is_satisfied(Product* item)
{
return item->size == _size;
}
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file implements the common entry point shared by all Chromoting Host
// processes.
#include "remoting/host/host_main.h"
#include <string>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/i18n/icu_util.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "base/strings/stringize_macros.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "mojo/edk/embedder/embedder.h"
#include "remoting/base/breakpad.h"
#include "remoting/host/host_exit_codes.h"
#include "remoting/host/logging.h"
#include "remoting/host/resources.h"
#include "remoting/host/setup/me2me_native_messaging_host.h"
#include "remoting/host/switches.h"
#include "remoting/host/usage_stats_consent.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif // defined(OS_MACOSX)
#if defined(OS_WIN)
#include <commctrl.h>
#include <shellapi.h>
#endif // defined(OS_WIN)
namespace remoting {
// Known entry points.
int HostProcessMain();
#if defined(OS_WIN)
int DaemonProcessMain();
int DesktopProcessMain();
int RdpDesktopSessionMain();
#endif // defined(OS_WIN)
namespace {
typedef int (*MainRoutineFn)();
const char kUsageMessage[] =
"Usage: %s [options]\n"
"\n"
"Options:\n"
" --audio-pipe-name=<pipe> - Sets the pipe name to capture audio on Linux.\n"
" --console - Runs the daemon interactively.\n"
" --daemon-pipe=<pipe> - Specifies the pipe to connect to the daemon.\n"
" --elevate=<binary> - Runs <binary> elevated.\n"
" --host-config=<config> - Specifies the host configuration.\n"
" --help, -? - Print this message.\n"
" --type - Specifies process type.\n"
" --version - Prints the host version and exits.\n"
" --window-id=<id> - Specifies a window to remote,"
" instead of the whole desktop.\n";
void Usage(const base::FilePath& program_name) {
printf(kUsageMessage, program_name.MaybeAsASCII().c_str());
}
#if defined(OS_WIN)
// Runs the binary specified by the command line, elevated.
int RunElevated() {
const base::CommandLine::SwitchMap& switches =
base::CommandLine::ForCurrentProcess()->GetSwitches();
base::CommandLine::StringVector args =
base::CommandLine::ForCurrentProcess()->GetArgs();
// Create the child process command line by copying switches from the current
// command line.
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
for (base::CommandLine::SwitchMap::const_iterator i = switches.begin();
i != switches.end(); ++i) {
if (i->first != kElevateSwitchName)
command_line.AppendSwitchNative(i->first, i->second);
}
for (base::CommandLine::StringVector::const_iterator i = args.begin();
i != args.end(); ++i) {
command_line.AppendArgNative(*i);
}
// Get the name of the binary to launch.
base::FilePath binary =
base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
kElevateSwitchName);
base::CommandLine::StringType parameters =
command_line.GetCommandLineString();
// Launch the child process requesting elevation.
SHELLEXECUTEINFO info;
memset(&info, 0, sizeof(info));
info.cbSize = sizeof(info);
info.lpVerb = L"runas";
info.lpFile = binary.value().c_str();
info.lpParameters = parameters.c_str();
info.nShow = SW_SHOWNORMAL;
if (!ShellExecuteEx(&info)) {
DWORD exit_code = GetLastError();
PLOG(ERROR) << "Unable to launch '" << binary.value() << "'";
return exit_code;
}
return kSuccessExitCode;
}
#endif // !defined(OS_WIN)
// Select the entry point corresponding to the process type.
MainRoutineFn SelectMainRoutine(const std::string& process_type) {
MainRoutineFn main_routine = nullptr;
if (process_type == kProcessTypeHost) {
main_routine = &HostProcessMain;
#if defined(OS_WIN)
} else if (process_type == kProcessTypeDaemon) {
main_routine = &DaemonProcessMain;
} else if (process_type == kProcessTypeDesktop) {
main_routine = &DesktopProcessMain;
} else if (process_type == kProcessTypeRdpDesktopSession) {
main_routine = &RdpDesktopSessionMain;
#endif // defined(OS_WIN)
}
return main_routine;
}
} // namespace
int HostMain(int argc, char** argv) {
#if defined(OS_MACOSX)
// Needed so we don't leak objects when threads are created.
base::mac::ScopedNSAutoreleasePool pool;
#endif
base::CommandLine::Init(argc, argv);
// Initialize Breakpad as early as possible. On Mac the command-line needs to
// be initialized first, so that the preference for crash-reporting can be
// looked up in the config file.
#if defined(REMOTING_ENABLE_BREAKPAD)
// TODO(nicholss): Commenting out Breakpad. See crbug.com/637884
// if (IsUsageStatsAllowed()) {
// InitializeCrashReporting();
// }
#endif // defined(REMOTING_ENABLE_BREAKPAD)
// This object instance is required by Chrome code (for example,
// LazyInstance, MessageLoop).
base::AtExitManager exit_manager;
// Enable debug logs.
InitHostLogging();
// Register and initialize common controls.
#if defined(OS_WIN)
INITCOMMONCONTROLSEX info;
info.dwSize = sizeof(info);
info.dwICC = ICC_STANDARD_CLASSES;
InitCommonControlsEx(&info);
#endif // defined(OS_WIN)
// Parse the command line.
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(kHelpSwitchName) ||
command_line->HasSwitch(kQuestionSwitchName)) {
Usage(command_line->GetProgram());
return kSuccessExitCode;
}
if (command_line->HasSwitch(kVersionSwitchName)) {
printf("%s\n", STRINGIZE(VERSION));
return kSuccessExitCode;
}
#if defined(OS_WIN)
if (command_line->HasSwitch(kElevateSwitchName)) {
return RunElevated();
}
#endif // defined(OS_WIN)
// Assume the host process by default.
std::string process_type = kProcessTypeHost;
if (command_line->HasSwitch(kProcessTypeSwitchName)) {
process_type = command_line->GetSwitchValueASCII(kProcessTypeSwitchName);
}
MainRoutineFn main_routine = SelectMainRoutine(process_type);
if (!main_routine) {
fprintf(stderr, "Unknown process type '%s' specified.",
process_type.c_str());
Usage(command_line->GetProgram());
return kInvalidCommandLineExitCode;
}
// Required to find the ICU data file, used by some file_util routines.
base::i18n::InitializeICU();
remoting::LoadResources("");
#if defined(REMOTING_MULTI_PROCESS)
mojo::edk::Init();
#endif
// Invoke the entry point.
int exit_code = main_routine();
if (exit_code == kInvalidCommandLineExitCode) {
Usage(command_line->GetProgram());
}
remoting::UnloadResources();
return exit_code;
}
} // namespace remoting
#if !defined(OS_WIN)
int main(int argc, char** argv) {
return remoting::HostMain(argc, argv);
}
#endif // !defined(OS_WIN)
|
/* Copyright 2015 The TensorFlow 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 "tensorflow/core/util/tensor_slice_writer.h"
#include <array>
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/versions.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/public/version.h"
#include "tensorflow/core/util/saved_tensor_slice_util.h"
#include "tensorflow/core/util/tensor_slice_reader.h"
namespace tensorflow {
namespace checkpoint {
class TensorSliceWriteTestHelper {
public:
static void CheckEntries(const string& fname);
static void GetData(TensorSliceReader::Table* table, const string& name,
const TensorSlice& slice, SavedSlice* ss);
};
namespace {
// Testing that an array is what is expected
void ExpectIdenticalFloatArrays(const float* expected, int size,
const float* actual) {
// TODO(yangke): copy some of the Dump* functions over
// LOG(INFO) << "Expected = " << DumpFloatArray(expected, size);
// LOG(INFO) << "Actual = " << DumpFloatArray(actual, size);
for (int i = 0; i < size; ++i) {
EXPECT_NEAR(expected[i], actual[i], 1e-6);
}
}
template <typename T, typename U>
void ExpectIdenticalIntArrays(const T* expected, int size, const U* actual) {
for (int i = 0; i < size; ++i) {
EXPECT_EQ(expected[i], static_cast<T>(actual[i]));
}
}
// Nifty routine to get the size of an array
template <typename T, unsigned SIZE>
inline size_t ArraySize(const T (&v)[SIZE]) {
return SIZE;
}
// A simple test on writing a few tensor slices
// TODO(yangke): refactor into smaller tests: will do as we add more stuff to
// the writer.
TEST(TensorSliceWriteTest, SimpleWrite) {
const string filename = io::JoinPath(testing::TmpDir(), "checkpoint");
TensorSliceWriter writer(filename, CreateTableTensorSliceBuilder);
// Add some int32 tensor slices
{
TensorShape shape({5, 10});
TensorSlice slice = TensorSlice::ParseOrDie("-:0,1");
const int32 data[] = {0, 1, 2, 3, 4};
TF_CHECK_OK(writer.Add("test", shape, slice, data));
}
// Two slices share the same tensor name
{
TensorShape shape({5, 10});
TensorSlice slice = TensorSlice::ParseOrDie("-:3,1");
const int32 data[] = {10, 11, 12, 13, 14};
TF_CHECK_OK(writer.Add("test", shape, slice, data));
}
// Another slice from a different float tensor -- it has a different name and
// should be inserted in front of the previous tensor
{
TensorShape shape({3, 2});
TensorSlice slice = TensorSlice::ParseOrDie("-:-");
const float data[] = {1.2, 1.3, 1.4, 2.1, 2.2, 2.3};
TF_CHECK_OK(writer.Add("AA", shape, slice, data));
}
// A slice with int64 data
{
TensorShape shape({5, 10});
TensorSlice slice = TensorSlice::ParseOrDie("-:3,1");
const int64 data[] = {10, 11, 12, 13, 14};
TF_CHECK_OK(writer.Add("int64", shape, slice, data));
}
// A slice with int16 data
{
TensorShape shape({5, 10});
TensorSlice slice = TensorSlice::ParseOrDie("-:3,1");
const int16 data[] = {10, 11, 12, 13, 14};
TF_CHECK_OK(writer.Add("int16", shape, slice, data));
}
TF_CHECK_OK(writer.Finish());
// Now we examine the checkpoint file manually.
TensorSliceWriteTestHelper::CheckEntries(filename);
}
} // namespace
void TensorSliceWriteTestHelper::GetData(TensorSliceReader::Table* table,
const string& name,
const TensorSlice& slice,
SavedSlice* ss) {
string key = EncodeTensorNameSlice(name, slice);
string value;
EXPECT_TRUE(table->Get(key, &value));
SavedTensorSlices sts;
EXPECT_TRUE(ParseProtoUnlimited(&sts, value));
EXPECT_FALSE(sts.has_meta());
*ss = sts.data();
EXPECT_EQ(name, ss->name());
TensorSlice slice2(ss->slice());
EXPECT_EQ(slice.DebugString(), slice2.DebugString());
}
void TensorSliceWriteTestHelper::CheckEntries(const string& fname) {
TensorSliceReader::Table* tptr;
TF_CHECK_OK(OpenTableTensorSliceReader(fname, &tptr));
std::unique_ptr<TensorSliceReader::Table> table(tptr);
CHECK_NOTNULL(table.get());
// We expect a block of SavedTensorSlices
string value;
ASSERT_TRUE(table->Get(kSavedTensorSlicesKey, &value));
{
SavedTensorSlices sts;
EXPECT_TRUE(ParseProtoUnlimited(&sts, value));
// We also expect two entries for the tensors
EXPECT_TRUE(sts.has_meta());
EXPECT_EQ(4, sts.meta().tensor_size());
// We should have written nontrivial version information
EXPECT_LT(0, TF_CHECKPOINT_VERSION);
EXPECT_EQ(TF_CHECKPOINT_VERSION, sts.meta().versions().producer());
EXPECT_EQ(TF_CHECKPOINT_VERSION_MIN_CONSUMER,
sts.meta().versions().min_consumer());
// We don't expect any data in the first block.
EXPECT_FALSE(sts.has_data());
// The two tensors should be stored in the same order as they are first
// created.
{
// The two slices of the "test" tensor
const SavedSliceMeta& ssm = sts.meta().tensor(0);
EXPECT_EQ("test", ssm.name());
EXPECT_EQ(
"dim { size: 5 } "
"dim { size: 10 }",
ssm.shape().ShortDebugString());
EXPECT_EQ(DT_INT32, ssm.type());
EXPECT_EQ(2, ssm.slice_size());
TensorSlice s0(ssm.slice(0));
TensorSlice s1(ssm.slice(1));
EXPECT_EQ("-:0,1", s0.DebugString());
EXPECT_EQ("-:3,1", s1.DebugString());
}
{
// The "AA" tensor
const SavedSliceMeta& ssm = sts.meta().tensor(1);
EXPECT_EQ("AA", ssm.name());
EXPECT_EQ(
"dim { size: 3 } "
"dim { size: 2 }",
ssm.shape().ShortDebugString());
EXPECT_EQ(DT_FLOAT, ssm.type());
EXPECT_EQ(1, ssm.slice_size());
TensorSlice s0(ssm.slice(0));
EXPECT_EQ("-:-", s0.DebugString());
}
{
// The "int64" tensor
const SavedSliceMeta& ssm = sts.meta().tensor(2);
EXPECT_EQ("int64", ssm.name());
EXPECT_EQ(
"dim { size: 5 } "
"dim { size: 10 }",
ssm.shape().ShortDebugString());
EXPECT_EQ(DT_INT64, ssm.type());
EXPECT_EQ(1, ssm.slice_size());
TensorSlice s0(ssm.slice(0));
EXPECT_EQ("-:3,1", s0.DebugString());
}
{
// The "int16" tensor
const SavedSliceMeta& ssm = sts.meta().tensor(3);
EXPECT_EQ("int16", ssm.name());
EXPECT_EQ(
"dim { size: 5 } "
"dim { size: 10 }",
ssm.shape().ShortDebugString());
EXPECT_EQ(DT_INT16, ssm.type());
EXPECT_EQ(1, ssm.slice_size());
TensorSlice s0(ssm.slice(0));
EXPECT_EQ("-:3,1", s0.DebugString());
}
}
// We expect 5 blocks of tensor data
{
// Block 1: we expect it to be the full slice of the "AA" tensor
SavedSlice ss;
GetData(table.get(), "AA", TensorSlice(2), &ss);
const float data[] = {1.2, 1.3, 1.4, 2.1, 2.2, 2.3};
EXPECT_EQ(ArraySize(data), ss.data().float_val_size());
ExpectIdenticalFloatArrays(data, ArraySize(data),
ss.data().float_val().data());
}
{
// Block 2: we expect it to be the first slice of the "test" tensor
SavedSlice ss;
GetData(table.get(), "test", TensorSlice({{0, -1}, {0, 1}}), &ss);
const int32 data[] = {0, 1, 2, 3, 4};
EXPECT_EQ(ArraySize(data), ss.data().int_val_size());
ExpectIdenticalIntArrays(data, ArraySize(data), ss.data().int_val().data());
}
{
// Block 3: we expect it to be the second slice of the "test" tensor
SavedSlice ss;
GetData(table.get(), "test", TensorSlice({{0, -1}, {3, 1}}), &ss);
const int32 data[] = {10, 11, 12, 13, 14};
EXPECT_EQ(ArraySize(data), ss.data().int_val_size());
ExpectIdenticalIntArrays(data, ArraySize(data), ss.data().int_val().data());
}
{
// Block 4: we expect it to be the slice of the "int64" tensor
SavedSlice ss;
GetData(table.get(), "int64", TensorSlice({{0, -1}, {3, 1}}), &ss);
const int64 data[] = {10, 11, 12, 13, 14};
EXPECT_EQ(ArraySize(data), ss.data().int64_val_size());
ExpectIdenticalIntArrays(data, ArraySize(data),
ss.data().int64_val().data());
}
{
// Block 5: we expect it to be the slice of the "int16" tensor
SavedSlice ss;
GetData(table.get(), "int16", TensorSlice({{0, -1}, {3, 1}}), &ss);
const int16 data[] = {10, 11, 12, 13, 14};
EXPECT_EQ(ArraySize(data), ss.data().int_val_size());
ExpectIdenticalIntArrays(data, ArraySize(data), ss.data().int_val().data());
}
}
template <typename DT>
size_t BytesPerElementHelper(DT value) {
SavedSlice ss;
std::array<DT, 1> lo_data;
std::fill(lo_data.begin(), lo_data.end(), value);
TF_EXPECT_OK(
TensorSliceWriter::SaveData(lo_data.data(), lo_data.size(), &ss));
size_t lo_byte_size = ss.ByteSizeLong();
std::array<DT, 1001> hi_data;
std::fill(hi_data.begin(), hi_data.end(), value);
TF_EXPECT_OK(
TensorSliceWriter::SaveData(hi_data.data(), hi_data.size(), &ss));
size_t hi_byte_size = ss.ByteSizeLong();
return (hi_byte_size - lo_byte_size) / (hi_data.size() - lo_data.size());
}
TEST(TensorSliceWriteTest, CheckpointSize) {
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_BOOL),
BytesPerElementHelper<bool>(false));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_BOOL),
BytesPerElementHelper<bool>(true));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_FLOAT),
BytesPerElementHelper<float>(-1.0));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_DOUBLE),
BytesPerElementHelper<double>(-1.0));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_COMPLEX64),
BytesPerElementHelper<complex64>(-1.0));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_COMPLEX128),
BytesPerElementHelper<complex128>(-1.0));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_INT32),
BytesPerElementHelper<int32>(-1));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_INT64),
BytesPerElementHelper<int64>(-1));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_UINT16),
BytesPerElementHelper<uint16>(std::numeric_limits<uint16>::max()));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_UINT8),
BytesPerElementHelper<uint8>(std::numeric_limits<uint8>::max()));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_INT8),
BytesPerElementHelper<int8>(-1));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_INT16),
BytesPerElementHelper<int16>(-1));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_QINT8),
BytesPerElementHelper<qint8>(-1));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_QUINT8),
BytesPerElementHelper<quint8>(std::numeric_limits<uint8>::max()));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_QINT32),
BytesPerElementHelper<qint32>(-1));
EXPECT_EQ(TensorSliceWriter::MaxBytesPerElement(DT_HALF),
BytesPerElementHelper<Eigen::half>(Eigen::half(-1.0)));
}
TEST(TensorSliceWriteTest, SizeErrors) {
const string filename = io::JoinPath(testing::TmpDir(), "checkpoint");
TensorSliceWriter writer(filename, CreateTableTensorSliceBuilder);
// Add a 300MB int8 tensor slice, which will fail because it expands to 3GB.
{
TensorShape shape({300, 1000000});
TensorSlice slice = TensorSlice::ParseOrDie("-:-");
const std::vector<int8> data(300000000, -1);
Status s = writer.Add("test1", shape, slice, data.data());
EXPECT_EQ(s.code(), error::INVALID_ARGUMENT);
EXPECT_TRUE(StringPiece(s.error_message())
.contains("Tensor slice is too large to serialize"));
}
// Add a large string tensor slice, which will fail.
{
TensorShape shape({256, 1024});
TensorSlice slice = TensorSlice::ParseOrDie("-:-");
const std::vector<string> data(256 * 1024, std::string(8192, 'f'));
Status s = writer.Add("test2", shape, slice, data.data());
EXPECT_EQ(s.code(), error::INVALID_ARGUMENT);
EXPECT_TRUE(StringPiece(s.error_message())
.contains("Tensor slice is too large to serialize"));
}
}
} // namespace checkpoint
} // namespace tensorflow
|
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Kokkos is licensed under 3-clause BSD terms of use:
//
// 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.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
#define KOKKOS_IMPL_COMPILING_LIBRARY true
#include <Kokkos_Core.hpp>
namespace Kokkos {
namespace Impl {
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int*****, LayoutLeft, LayoutRight, Cuda, int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int*****, LayoutLeft, LayoutLeft, Cuda, int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int*****, LayoutLeft, LayoutStride, Cuda, int)
KOKKOS_IMPL_VIEWFILL_ETI_INST(int*****, LayoutLeft, Cuda, int)
} // namespace Impl
} // namespace Kokkos
|
/*
* Brian R Taylor
* brian.taylor@bolderflight.com
*
* Copyright (c) 2021 Bolder Flight Systems Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the “Software”), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "imap.h"
#include <iostream>
int main() {
/* Mapping output, single precision */
bfs::ImapData<float> gyro_mapping;
/*
* Get configuration to map to a signed integer, gyro example (+/-2000 deg/s,
* 0.1 deg/s precision)
*/
gyro_mapping = bfs::ImapConfig(-2000.0f, 2000.0f, 0.1f);
std::cout << "Gyro Map to Signed Integer:" << std::endl;
std::cout << "Bytes: " << gyro_mapping.num_bytes << std::endl;
std::cout << "Scale factor: " << gyro_mapping.scale_factor << std::endl;
std::cout << "Bias: " << gyro_mapping.bias << std::endl << std::endl;
/*
* Get configuration to map to a signed integer using a greedy algorith, which
* will compute the required bytes and fully use the bytes required improving
* the precision. Gyro example (+/-2000 deg/s, 0.1 deg/s precision)
*/
gyro_mapping = bfs::ImapGreedyConfig(-2000.0f, 2000.0f, 0.1f);
std::cout << "Gyro Map to Signed Integer, Greedy:" << std::endl;
std::cout << "Bytes: " << gyro_mapping.num_bytes << std::endl;
std::cout << "Scale factor: " << gyro_mapping.scale_factor << std::endl;
std::cout << "Bias: " << gyro_mapping.bias << std::endl << std::endl;
/*
* Get configuration to map to a unsigned integer, gyro example (+/-2000 deg/s,
* 0.1 deg/s precision)
*/
gyro_mapping = bfs::UimapConfig(-2000.0f, 2000.0f, 0.1f);
std::cout << "Gyro Map to Unsigned Integer:" << std::endl;
std::cout << "Bytes: " << gyro_mapping.num_bytes << std::endl;
std::cout << "Scale factor: " << gyro_mapping.scale_factor << std::endl;
std::cout << "Bias: " << gyro_mapping.bias << std::endl << std::endl;
/*
* Get configuration to map to a unsigned integer using a greedy algorith,
* which will compute the required bytes and fully use the bytes required
* improving the precision. Gyro example (+/-2000 deg/s, 0.1 deg/s precision)
*/
gyro_mapping = bfs::UimapGreedyConfig(-2000.0f, 2000.0f, 0.1f);
std::cout << "Gyro Map to Unsigned Integer, Greedy:" << std::endl;
std::cout << "Bytes: " << gyro_mapping.num_bytes << std::endl;
std::cout << "Scale factor: " << gyro_mapping.scale_factor << std::endl;
std::cout << "Bias: " << gyro_mapping.bias << std::endl << std::endl;
}
|
#pragma once
#include <index>
|
//===----------------- LoopRotationUtils.cpp -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file provides utilities to convert a loop into a loop with bottom test.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/LoopRotationUtils.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/BasicAliasAnalysis.h"
#include "llvm/Analysis/CodeMetrics.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DomTreeUpdater.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
using namespace llvm;
#define DEBUG_TYPE "loop-rotate"
STATISTIC(NumRotated, "Number of loops rotated");
namespace {
/// A simple loop rotation transformation.
class LoopRotate {
const unsigned MaxHeaderSize;
LoopInfo *LI;
const TargetTransformInfo *TTI;
AssumptionCache *AC;
DominatorTree *DT;
ScalarEvolution *SE;
MemorySSAUpdater *MSSAU;
const SimplifyQuery &SQ;
bool RotationOnly;
bool IsUtilMode;
public:
LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
const TargetTransformInfo *TTI, AssumptionCache *AC,
DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode)
: MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
IsUtilMode(IsUtilMode) {}
bool processLoop(Loop *L);
private:
bool rotateLoop(Loop *L, bool SimplifiedLatch);
bool simplifyLoopLatch(Loop *L);
};
} // end anonymous namespace
/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
/// old header into the preheader. If there were uses of the values produced by
/// these instruction that were outside of the loop, we have to insert PHI nodes
/// to merge the two values. Do this now.
static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
BasicBlock *OrigPreheader,
ValueToValueMapTy &ValueMap,
SmallVectorImpl<PHINode*> *InsertedPHIs) {
// Remove PHI node entries that are no longer live.
BasicBlock::iterator I, E = OrigHeader->end();
for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
// Now fix up users of the instructions in OrigHeader, inserting PHI nodes
// as necessary.
SSAUpdater SSA(InsertedPHIs);
for (I = OrigHeader->begin(); I != E; ++I) {
Value *OrigHeaderVal = &*I;
// If there are no uses of the value (e.g. because it returns void), there
// is nothing to rewrite.
if (OrigHeaderVal->use_empty())
continue;
Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
// The value now exits in two versions: the initial value in the preheader
// and the loop "next" value in the original header.
SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
// Visit each use of the OrigHeader instruction.
for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
UE = OrigHeaderVal->use_end();
UI != UE;) {
// Grab the use before incrementing the iterator.
Use &U = *UI;
// Increment the iterator before removing the use from the list.
++UI;
// SSAUpdater can't handle a non-PHI use in the same block as an
// earlier def. We can easily handle those cases manually.
Instruction *UserInst = cast<Instruction>(U.getUser());
if (!isa<PHINode>(UserInst)) {
BasicBlock *UserBB = UserInst->getParent();
// The original users in the OrigHeader are already using the
// original definitions.
if (UserBB == OrigHeader)
continue;
// Users in the OrigPreHeader need to use the value to which the
// original definitions are mapped.
if (UserBB == OrigPreheader) {
U = OrigPreHeaderVal;
continue;
}
}
// Anything else can be handled by SSAUpdater.
SSA.RewriteUse(U);
}
// Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
// intrinsics.
SmallVector<DbgValueInst *, 1> DbgValues;
llvm::findDbgValues(DbgValues, OrigHeaderVal);
for (auto &DbgValue : DbgValues) {
// The original users in the OrigHeader are already using the original
// definitions.
BasicBlock *UserBB = DbgValue->getParent();
if (UserBB == OrigHeader)
continue;
// Users in the OrigPreHeader need to use the value to which the
// original definitions are mapped and anything else can be handled by
// the SSAUpdater. To avoid adding PHINodes, check if the value is
// available in UserBB, if not substitute undef.
Value *NewVal;
if (UserBB == OrigPreheader)
NewVal = OrigPreHeaderVal;
else if (SSA.HasValueForBlock(UserBB))
NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
else
NewVal = UndefValue::get(OrigHeaderVal->getType());
DbgValue->setOperand(0,
MetadataAsValue::get(OrigHeaderVal->getContext(),
ValueAsMetadata::get(NewVal)));
}
}
}
// Look for a phi which is only used outside the loop (via a LCSSA phi)
// in the exit from the header. This means that rotating the loop can
// remove the phi.
static bool shouldRotateLoopExitingLatch(Loop *L) {
BasicBlock *Header = L->getHeader();
BasicBlock *HeaderExit = Header->getTerminator()->getSuccessor(0);
if (L->contains(HeaderExit))
HeaderExit = Header->getTerminator()->getSuccessor(1);
for (auto &Phi : Header->phis()) {
// Look for uses of this phi in the loop/via exits other than the header.
if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
return cast<Instruction>(U)->getParent() != HeaderExit;
}))
continue;
return true;
}
return false;
}
/// Rotate loop LP. Return true if the loop is rotated.
///
/// \param SimplifiedLatch is true if the latch was just folded into the final
/// loop exit. In this case we may want to rotate even though the new latch is
/// now an exiting branch. This rotation would have happened had the latch not
/// been simplified. However, if SimplifiedLatch is false, then we avoid
/// rotating loops in which the latch exits to avoid excessive or endless
/// rotation. LoopRotate should be repeatable and converge to a canonical
/// form. This property is satisfied because simplifying the loop latch can only
/// happen once across multiple invocations of the LoopRotate pass.
bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
// If the loop has only one block then there is not much to rotate.
if (L->getBlocks().size() == 1)
return false;
BasicBlock *OrigHeader = L->getHeader();
BasicBlock *OrigLatch = L->getLoopLatch();
BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
if (!BI || BI->isUnconditional())
return false;
// If the loop header is not one of the loop exiting blocks then
// either this loop is already rotated or it is not
// suitable for loop rotation transformations.
if (!L->isLoopExiting(OrigHeader))
return false;
// If the loop latch already contains a branch that leaves the loop then the
// loop is already rotated.
if (!OrigLatch)
return false;
// Rotate if either the loop latch does *not* exit the loop, or if the loop
// latch was just simplified. Or if we think it will be profitable.
if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
!shouldRotateLoopExitingLatch(L))
return false;
// Check size of original header and reject loop if it is very big or we can't
// duplicate blocks inside it.
{
SmallPtrSet<const Value *, 32> EphValues;
CodeMetrics::collectEphemeralValues(L, AC, EphValues);
CodeMetrics Metrics;
Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
if (Metrics.notDuplicatable) {
LLVM_DEBUG(
dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
<< " instructions: ";
L->dump());
return false;
}
if (Metrics.convergent) {
LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
"instructions: ";
L->dump());
return false;
}
if (Metrics.NumInsts > MaxHeaderSize)
return false;
}
// Now, this loop is suitable for rotation.
BasicBlock *OrigPreheader = L->getLoopPreheader();
// If the loop could not be converted to canonical form, it must have an
// indirectbr in it, just give up.
if (!OrigPreheader || !L->hasDedicatedExits())
return false;
// Anything ScalarEvolution may know about this loop or the PHI nodes
// in its header will soon be invalidated. We should also invalidate
// all outer loops because insertion and deletion of blocks that happens
// during the rotation may violate invariants related to backedge taken
// infos in them.
if (SE)
SE->forgetTopmostLoop(L);
LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
// Find new Loop header. NewHeader is a Header's one and only successor
// that is inside loop. Header's other successor is outside the
// loop. Otherwise loop is not suitable for rotation.
BasicBlock *Exit = BI->getSuccessor(0);
BasicBlock *NewHeader = BI->getSuccessor(1);
if (L->contains(Exit))
std::swap(Exit, NewHeader);
assert(NewHeader && "Unable to determine new loop header");
assert(L->contains(NewHeader) && !L->contains(Exit) &&
"Unable to determine loop header and exit blocks");
// This code assumes that the new header has exactly one predecessor.
// Remove any single-entry PHI nodes in it.
assert(NewHeader->getSinglePredecessor() &&
"New header doesn't have one pred!");
FoldSingleEntryPHINodes(NewHeader);
// Begin by walking OrigHeader and populating ValueMap with an entry for
// each Instruction.
BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
ValueToValueMapTy ValueMap;
// For PHI nodes, the value available in OldPreHeader is just the
// incoming value from OldPreHeader.
for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
// For the rest of the instructions, either hoist to the OrigPreheader if
// possible or create a clone in the OldPreHeader if not.
Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
// Record all debug intrinsics preceding LoopEntryBranch to avoid duplication.
using DbgIntrinsicHash =
std::pair<std::pair<Value *, DILocalVariable *>, DIExpression *>;
auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash {
return {{D->getVariableLocation(), D->getVariable()}, D->getExpression()};
};
SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
for (auto I = std::next(OrigPreheader->rbegin()), E = OrigPreheader->rend();
I != E; ++I) {
if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&*I))
DbgIntrinsics.insert(makeHash(DII));
else
break;
}
while (I != E) {
Instruction *Inst = &*I++;
// If the instruction's operands are invariant and it doesn't read or write
// memory, then it is safe to hoist. Doing this doesn't change the order of
// execution in the preheader, but does prevent the instruction from
// executing in each iteration of the loop. This means it is safe to hoist
// something that might trap, but isn't safe to hoist something that reads
// memory (without proving that the loop doesn't write).
if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
!Inst->mayWriteToMemory() && !Inst->isTerminator() &&
!isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
Inst->moveBefore(LoopEntryBranch);
continue;
}
// Otherwise, create a duplicate of the instruction.
Instruction *C = Inst->clone();
// Eagerly remap the operands of the instruction.
RemapInstruction(C, ValueMap,
RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
// Avoid inserting the same intrinsic twice.
if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
if (DbgIntrinsics.count(makeHash(DII))) {
C->deleteValue();
continue;
}
// With the operands remapped, see if the instruction constant folds or is
// otherwise simplifyable. This commonly occurs because the entry from PHI
// nodes allows icmps and other instructions to fold.
Value *V = SimplifyInstruction(C, SQ);
if (V && LI->replacementPreservesLCSSAForm(C, V)) {
// If so, then delete the temporary instruction and stick the folded value
// in the map.
ValueMap[Inst] = V;
if (!C->mayHaveSideEffects()) {
C->deleteValue();
C = nullptr;
}
} else {
ValueMap[Inst] = C;
}
if (C) {
// Otherwise, stick the new instruction into the new block!
C->setName(Inst->getName());
C->insertBefore(LoopEntryBranch);
if (auto *II = dyn_cast<IntrinsicInst>(C))
if (II->getIntrinsicID() == Intrinsic::assume)
AC->registerAssumption(II);
}
}
// Along with all the other instructions, we just cloned OrigHeader's
// terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
// successors by duplicating their incoming values for OrigHeader.
for (BasicBlock *SuccBB : successors(OrigHeader))
for (BasicBlock::iterator BI = SuccBB->begin();
PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
// Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
// OrigPreHeader's old terminator (the original branch into the loop), and
// remove the corresponding incoming values from the PHI nodes in OrigHeader.
LoopEntryBranch->eraseFromParent();
// Update MemorySSA before the rewrite call below changes the 1:1
// instruction:cloned_instruction_or_value mapping in ValueMap.
if (MSSAU) {
ValueMap[OrigHeader] = OrigPreheader;
MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader, ValueMap);
}
SmallVector<PHINode*, 2> InsertedPHIs;
// If there were any uses of instructions in the duplicated block outside the
// loop, update them, inserting PHI nodes as required
RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
&InsertedPHIs);
// Attach dbg.value intrinsics to the new phis if that phi uses a value that
// previously had debug metadata attached. This keeps the debug info
// up-to-date in the loop body.
if (!InsertedPHIs.empty())
insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
// NewHeader is now the header of the loop.
L->moveToHeader(NewHeader);
assert(L->getHeader() == NewHeader && "Latch block is our new header");
// Inform DT about changes to the CFG.
if (DT) {
// The OrigPreheader branches to the NewHeader and Exit now. Then, inform
// the DT about the removed edge to the OrigHeader (that got removed).
SmallVector<DominatorTree::UpdateType, 3> Updates;
Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
DT->applyUpdates(Updates);
if (MSSAU) {
MSSAU->applyUpdates(Updates, *DT);
if (VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
}
}
// At this point, we've finished our major CFG changes. As part of cloning
// the loop into the preheader we've simplified instructions and the
// duplicated conditional branch may now be branching on a constant. If it is
// branching on a constant and if that constant means that we enter the loop,
// then we fold away the cond branch to an uncond branch. This simplifies the
// loop in cases important for nested loops, and it also means we don't have
// to split as many edges.
BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
assert(PHBI->isConditional() && "Should be clone of BI condbr!");
if (!isa<ConstantInt>(PHBI->getCondition()) ||
PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
NewHeader) {
// The conditional branch can't be folded, handle the general case.
// Split edges as necessary to preserve LoopSimplify form.
// Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
// thus is not a preheader anymore.
// Split the edge to form a real preheader.
BasicBlock *NewPH = SplitCriticalEdge(
OrigPreheader, NewHeader,
CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
NewPH->setName(NewHeader->getName() + ".lr.ph");
// Preserve canonical loop form, which means that 'Exit' should have only
// one predecessor. Note that Exit could be an exit block for multiple
// nested loops, causing both of the edges to now be critical and need to
// be split.
SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
bool SplitLatchEdge = false;
for (BasicBlock *ExitPred : ExitPreds) {
// We only need to split loop exit edges.
Loop *PredLoop = LI->getLoopFor(ExitPred);
if (!PredLoop || PredLoop->contains(Exit))
continue;
if (isa<IndirectBrInst>(ExitPred->getTerminator()))
continue;
SplitLatchEdge |= L->getLoopLatch() == ExitPred;
BasicBlock *ExitSplit = SplitCriticalEdge(
ExitPred, Exit,
CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
ExitSplit->moveBefore(Exit);
}
assert(SplitLatchEdge &&
"Despite splitting all preds, failed to split latch exit?");
} else {
// We can fold the conditional branch in the preheader, this makes things
// simpler. The first step is to remove the extra edge to the Exit block.
Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
NewBI->setDebugLoc(PHBI->getDebugLoc());
PHBI->eraseFromParent();
// With our CFG finalized, update DomTree if it is available.
if (DT) DT->deleteEdge(OrigPreheader, Exit);
// Update MSSA too, if available.
if (MSSAU)
MSSAU->removeEdge(OrigPreheader, Exit);
}
assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
// Now that the CFG and DomTree are in a consistent state again, try to merge
// the OrigHeader block into OrigLatch. This will succeed if they are
// connected by an unconditional branch. This is just a cleanup so the
// emitted code isn't too gross in this common case.
DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
++NumRotated;
return true;
}
/// Determine whether the instructions in this range may be safely and cheaply
/// speculated. This is not an important enough situation to develop complex
/// heuristics. We handle a single arithmetic instruction along with any type
/// conversions.
static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
BasicBlock::iterator End, Loop *L) {
bool seenIncrement = false;
bool MultiExitLoop = false;
if (!L->getExitingBlock())
MultiExitLoop = true;
for (BasicBlock::iterator I = Begin; I != End; ++I) {
if (!isSafeToSpeculativelyExecute(&*I))
return false;
if (isa<DbgInfoIntrinsic>(I))
continue;
switch (I->getOpcode()) {
default:
return false;
case Instruction::GetElementPtr:
// GEPs are cheap if all indices are constant.
if (!cast<GEPOperator>(I)->hasAllConstantIndices())
return false;
// fall-thru to increment case
LLVM_FALLTHROUGH;
case Instruction::Add:
case Instruction::Sub:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr: {
Value *IVOpnd =
!isa<Constant>(I->getOperand(0))
? I->getOperand(0)
: !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
if (!IVOpnd)
return false;
// If increment operand is used outside of the loop, this speculation
// could cause extra live range interference.
if (MultiExitLoop) {
for (User *UseI : IVOpnd->users()) {
auto *UserInst = cast<Instruction>(UseI);
if (!L->contains(UserInst))
return false;
}
}
if (seenIncrement)
return false;
seenIncrement = true;
break;
}
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
// ignore type conversions
break;
}
}
return true;
}
/// Fold the loop tail into the loop exit by speculating the loop tail
/// instructions. Typically, this is a single post-increment. In the case of a
/// simple 2-block loop, hoisting the increment can be much better than
/// duplicating the entire loop header. In the case of loops with early exits,
/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
/// canonical form so downstream passes can handle it.
///
/// I don't believe this invalidates SCEV.
bool LoopRotate::simplifyLoopLatch(Loop *L) {
BasicBlock *Latch = L->getLoopLatch();
if (!Latch || Latch->hasAddressTaken())
return false;
BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
if (!Jmp || !Jmp->isUnconditional())
return false;
BasicBlock *LastExit = Latch->getSinglePredecessor();
if (!LastExit || !L->isLoopExiting(LastExit))
return false;
BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
if (!BI)
return false;
if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
return false;
LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
<< LastExit->getName() << "\n");
// Hoist the instructions from Latch into LastExit.
Instruction *FirstLatchInst = &*(Latch->begin());
LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
Latch->begin(), Jmp->getIterator());
// Update MemorySSA
if (MSSAU)
MSSAU->moveAllAfterMergeBlocks(Latch, LastExit, FirstLatchInst);
unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
BasicBlock *Header = Jmp->getSuccessor(0);
assert(Header == L->getHeader() && "expected a backward branch");
// Remove Latch from the CFG so that LastExit becomes the new Latch.
BI->setSuccessor(FallThruPath, Header);
Latch->replaceSuccessorsPhiUsesWith(LastExit);
Jmp->eraseFromParent();
// Nuke the Latch block.
assert(Latch->empty() && "unable to evacuate Latch");
LI->removeBlock(Latch);
if (DT)
DT->eraseNode(Latch);
Latch->eraseFromParent();
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
return true;
}
/// Rotate \c L, and return true if any modification was made.
bool LoopRotate::processLoop(Loop *L) {
// Save the loop metadata.
MDNode *LoopMD = L->getLoopID();
bool SimplifiedLatch = false;
// Simplify the loop latch before attempting to rotate the header
// upward. Rotation may not be needed if the loop tail can be folded into the
// loop exit.
if (!RotationOnly)
SimplifiedLatch = simplifyLoopLatch(L);
bool MadeChange = rotateLoop(L, SimplifiedLatch);
assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
"Loop latch should be exiting after loop-rotate.");
// Restore the loop metadata.
// NB! We presume LoopRotation DOESN'T ADD its own metadata.
if ((MadeChange || SimplifiedLatch) && LoopMD)
L->setLoopID(LoopMD);
return MadeChange || SimplifiedLatch;
}
/// The utility to convert a loop into a loop with bottom test.
bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
AssumptionCache *AC, DominatorTree *DT,
ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
const SimplifyQuery &SQ, bool RotationOnly = true,
unsigned Threshold = unsigned(-1),
bool IsUtilMode = true) {
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
IsUtilMode);
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
return LR.processLoop(L);
}
|
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
* Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
* Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
* Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
* Copyright (c) 2011, Code Aurora Forum. All rights reserved.
* Copyright (C) Research In Motion Limited 2011. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "sky/engine/core/css/SelectorChecker.h"
#include "sky/engine/core/css/CSSSelector.h"
#include "sky/engine/core/css/CSSSelectorList.h"
#include "sky/engine/core/dom/Document.h"
#include "sky/engine/core/frame/LocalFrame.h"
#include "sky/engine/core/html/parser/HTMLParserIdioms.h"
#include "sky/engine/core/rendering/style/RenderStyle.h"
namespace blink {
SelectorChecker::SelectorChecker(const Element& element)
: m_element(element)
, m_matchedAttributeSelector(false)
, m_matchedHoverSelector(false)
, m_matchedActiveSelector(false)
{
}
bool SelectorChecker::match(const CSSSelector& selector)
{
const CSSSelector* current = &selector;
do {
if (!checkOne(*current))
return false;
current = current->tagHistory();
} while (current);
return true;
}
static bool anyAttributeMatches(const Element& element, CSSSelector::Match match, const CSSSelector& selector)
{
const QualifiedName& selectorAttr = selector.attribute();
ASSERT(selectorAttr.localName() != starAtom); // Should not be possible from the CSS grammar.
if (match == CSSSelector::Set)
return element.hasAttribute(selectorAttr);
ASSERT(match == CSSSelector::Exact);
const AtomicString& selectorValue = selector.value();
const AtomicString& value = element.getAttribute(selectorAttr);
if (value.isNull())
return false;
if (selector.attributeMatchType() == CSSSelector::CaseInsensitive)
return equalIgnoringCase(selectorValue, value);
return selectorValue == value;
}
bool SelectorChecker::checkOne(const CSSSelector& selector)
{
switch (selector.match()) {
case CSSSelector::Tag:
{
const AtomicString& localName = selector.tagQName().localName();
return localName == starAtom || localName == m_element.localName();
}
case CSSSelector::Class:
return m_element.hasClass() && m_element.classNames().contains(selector.value());
case CSSSelector::Id:
return m_element.hasID() && m_element.idForStyleResolution() == selector.value();
case CSSSelector::Exact:
case CSSSelector::Set:
if (anyAttributeMatches(m_element, selector.match(), selector)) {
m_matchedAttributeSelector = true;
return true;
}
return false;
case CSSSelector::PseudoClass:
return checkPseudoClass(selector);
// FIXME(sky): Remove pseudo elements completely.
case CSSSelector::PseudoElement:
case CSSSelector::Unknown:
return false;
}
ASSERT_NOT_REACHED();
return false;
}
bool SelectorChecker::checkPseudoClass(const CSSSelector& selector)
{
switch (selector.pseudoType()) {
case CSSSelector::PseudoHover:
m_matchedHoverSelector = true;
return m_element.hovered();
case CSSSelector::PseudoActive:
m_matchedActiveSelector = true;
return m_element.active();
case CSSSelector::PseudoLang:
{
AtomicString value = m_element.computeInheritedLanguage();
const AtomicString& argument = selector.argument();
if (value.isEmpty() || !value.startsWith(argument, false))
break;
if (value.length() != argument.length() && value[argument.length()] != '-')
break;
return true;
}
case CSSSelector::PseudoHost:
{
// We can only get here if the selector was defined in the right
// scope so we don't need to check it.
// For empty parameter case, i.e. just :host or :host().
if (!selector.selectorList())
return true;
for (const CSSSelector* current = selector.selectorList()->first(); current; current = CSSSelectorList::next(*current)) {
if (match(*current))
return true;
}
return false;
}
case CSSSelector::PseudoUnknown:
case CSSSelector::PseudoNotParsed:
return false;
}
ASSERT_NOT_REACHED();
return false;
}
}
|
// license:BSD-3-Clause
// copyright-holders:Curt Coder
/*****************************************************************************
*
* video/abc802.c
*
****************************************************************************/
#include "emu.h"
#include "includes/abc80x.h"
#include "screen.h"
//-------------------------------------------------
// MC6845_UPDATE_ROW( abc802_update_row )
//-------------------------------------------------
MC6845_UPDATE_ROW( abc802_state::abc802_update_row )
{
/*
PAL16R4 equation:
IF (VCC) *OS = FC + RF / RC
*RG: = HS / *RG + *ATE / *RG + ATD / *RG + LL /
*RG + AT1 / *RG + AT0 / ATE + *ATD + *LL +
*AT1 + *AT0
*RI: = *RI + *INV / *RI + LL / *INV + *LL
*RF: = HS / *RF + *ATE / *RF + ATD / *RF + LL /
*RF + AT1 / *RF + AT0 / ATE + *ATD + *LL +
*AT1 + AT0
*RC: = HS / *RC + *ATE / *RC + *ATD / *RC + LL /
*RC + *ATI / *RC + AT0 / ATE + *LL + *AT1 +
*AT0
IF (VCC) *O0 = *CUR + *AT0 / *CUR + ATE
*O1 = *CUR + *AT1 / *CUR + ATE
+ = AND
/ = OR
* = Inverted
ATD Attribute data
ATE Attribute enable
AT0,AT1 Attribute address
CUR Cursor
FC FLSH clock
HS Horizontal sync
INV Inverted signal input
LL Load when Low
OEL Output Enable when Low
RC Row clear
RF Row flash
RG Row graphic
RI Row inverted
*/
const pen_t *pen = m_palette->pens();
int rf = 0, rc = 0, rg = 0;
y += vbp;
for (int column = 0; column < x_count; column++)
{
uint8_t code = m_char_ram[(ma + column) & 0x7ff];
uint16_t address = code << 4;
uint8_t ra_latch = ra;
uint8_t data;
int ri = (code & ABC802_INV) ? 1 : 0;
if (column == cursor_x)
{
ra_latch = 0x0f;
}
if ((m_flshclk && rf) || rc)
{
ra_latch = 0x0e;
}
if (rg)
{
address |= 0x800;
}
data = m_char_rom->base()[(address + ra_latch) & 0xfff];
if (data & ABC802_ATE)
{
int attr = data & 0x03;
int value = (data & ABC802_ATD) ? 1 : 0;
switch (attr)
{
case 0x00:
// Row Graphic
rg = value;
break;
case 0x01:
// Row Flash
rf = value;
break;
case 0x02:
// Row Clear
rc = value;
break;
case 0x03:
// undefined
break;
}
}
else
{
data <<= 2;
if (m_80_40_mux)
{
for (int bit = 0; bit < ABC800_CHAR_WIDTH; bit++)
{
int x = hbp + ((column + 3) * ABC800_CHAR_WIDTH) + bit;
int color = (BIT(data, 7) ^ ri) && de;
bitmap.pix(y, x) = pen[color];
data <<= 1;
}
}
else
{
for (int bit = 0; bit < ABC800_CHAR_WIDTH; bit++)
{
int x = hbp + ((column + 3) * ABC800_CHAR_WIDTH) + (bit << 1);
int color = (BIT(data, 7) ^ ri) && de;
bitmap.pix(y, x) = pen[color];
bitmap.pix(y, x + 1) = pen[color];
data <<= 1;
}
column++;
}
}
}
}
//-------------------------------------------------
// vs_w - vertical sync write
//-------------------------------------------------
WRITE_LINE_MEMBER( abc802_state::vs_w )
{
if (!state)
{
// flash clock
if (m_flshclk_ctr & 0x20)
{
m_flshclk = !m_flshclk;
m_flshclk_ctr = 0;
}
else
{
m_flshclk_ctr++;
}
}
}
void abc802_state::video_start()
{
// register for state saving
save_item(NAME(m_flshclk_ctr));
save_item(NAME(m_flshclk));
save_item(NAME(m_80_40_mux));
}
//-------------------------------------------------
// machine_config( abc802_video )
//-------------------------------------------------
void abc802_state::abc802_video(machine_config &config)
{
mc6845_device &mc6845(MC6845(config, MC6845_TAG, ABC800_CCLK));
mc6845.set_screen(SCREEN_TAG);
mc6845.set_show_border_area(true);
mc6845.set_char_width(ABC800_CHAR_WIDTH);
mc6845.set_update_row_callback(FUNC(abc802_state::abc802_update_row));
mc6845.out_vsync_callback().set(FUNC(abc802_state::vs_w));
mc6845.out_vsync_callback().append(m_dart, FUNC(z80dart_device::rib_w)).invert();
screen_device &screen(SCREEN(config, SCREEN_TAG, SCREEN_TYPE_RASTER, rgb_t::amber()));
screen.set_screen_update(MC6845_TAG, FUNC(mc6845_device::screen_update));
screen.set_raw(XTAL(12'000'000), 0x300, 0, 0x1e0, 0x13a, 0, 0xf0);
PALETTE(config, m_palette, palette_device::MONOCHROME);
}
|
// Physics_GravityForce.cpp: implementation of the Physics_GravityForce class.
//
//////////////////////////////////////////////////////////////////////
#include "DRGShell.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Physics_GravityForce::Physics_GravityForce( vector3 const&dir )
{
m_Direction = dir;
mType= GRAVITY;
}
Physics_GravityForce::~Physics_GravityForce()
{
}
void Physics_GravityForce::Apply( m_real fTime, Physics_LargeVector &masses, bool bDerivs,
Physics_LargeVector &p,
Physics_LargeVector &v,
Physics_LargeVector &f_int, Physics_LargeVector &f_ext,
Physics_SparseSymmetricMatrix &f_dp, Physics_SparseSymmetricMatrix &f_dv )
{
for( int i=0; i<f_ext.size(); i++ )
{
f_ext[i].x += m_Direction.x * masses[i].x;
f_ext[i].y += m_Direction.y * masses[i].y;
f_ext[i].z += m_Direction.z * masses[i].z;
}
}
|
/*
* Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "slib/core/hash.h"
#include "slib/core/hash_table.h"
#include "slib/core/math.h"
namespace slib
{
/****************************************************
Fowler–Noll–Vo hash function / FNV-1a hash
https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
http://www.isthe.com/chongo/tech/comp/fnv/index.html
****************************************************/
sl_uint32 HashBytes32(const void* _buf, sl_size n) noexcept
{
sl_uint8* buf = (sl_uint8*)_buf;
sl_uint32 hash = 0x811c9dc5;
sl_uint32 prime = 16777619;
for (sl_size i = 0; i < n; i++) {
hash ^= buf[i];
hash *= prime;
}
return hash;
}
sl_uint64 HashBytes64(const void* _buf, sl_size n) noexcept
{
sl_uint8* buf = (sl_uint8*)_buf;
sl_uint64 hash = SLIB_UINT64(0xcbf29ce484222325);
sl_uint64 prime = SLIB_UINT64(1099511628211);
for (sl_size i = 0; i < n; i++) {
hash ^= buf[i];
hash *= prime;
}
return hash;
}
sl_size HashBytes(const void* buf, sl_size n) noexcept
{
#ifdef SLIB_ARCH_IS_64BIT
return HashBytes64(buf, n);
#else
return HashBytes32(buf, n);
#endif
}
namespace priv
{
namespace hash_table
{
#define HASH_TABLE_MIN_CAPACITY 16
#define HASH_TABLE_LOAD_FACTOR_UP 0.75f
#define HASH_TABLE_LOAD_FACTOR_DOWN 0.25f
void Helper::fixCapacityRange(HashTableStructBase* table) noexcept
{
sl_size _capacityMinimum = table->capacityMinimum;
table->capacityMinimum = Math::roundUpToPowerOfTwo(_capacityMinimum);
if (table->capacityMinimum < _capacityMinimum) {
table->capacityMinimum = table->capacityMinimum << 1;
}
if (table->capacityMinimum < HASH_TABLE_MIN_CAPACITY || (sl_reg)(table->capacityMinimum) < 0) {
table->capacityMinimum = HASH_TABLE_MIN_CAPACITY;
}
if (table->capacityMaximum == 0) {
table->capacityMaximum = SLIB_SIZE_MAX;
} else {
if (table->capacityMaximum < table->capacityMinimum) {
table->capacityMaximum = table->capacityMinimum;
}
}
}
void Helper::updateThresholds(HashTableStructBase* table) noexcept
{
if (table->capacity == 0) {
return;
}
table->thresholdDown = (sl_size)(HASH_TABLE_LOAD_FACTOR_DOWN * table->capacity);
if (table->thresholdDown < table->capacityMinimum) {
table->thresholdDown = table->capacityMinimum;
}
table->thresholdUp = (sl_size)(HASH_TABLE_LOAD_FACTOR_UP * table->capacity);
if (table->thresholdUp > table->capacityMaximum) {
table->thresholdUp = table->capacityMaximum;
}
}
void Helper::initialize(HashTableStructBase* table, sl_size capacityMinimum, sl_size capacityMaximum) noexcept
{
table->nodes = sl_null;
table->count = 0;
table->capacity = 0;
table->capacityMinimum = capacityMinimum;
table->capacityMaximum = capacityMaximum;
table->thresholdUp = 0;
table->thresholdDown = 0;
fixCapacityRange(table);
}
void Helper::move(HashTableStructBase* dst, HashTableStructBase* src) noexcept
{
Base::copyMemory(dst, src, sizeof(HashTableStructBase));
clear(src);
}
void Helper::clear(HashTableStructBase* table) noexcept
{
table->nodes = sl_null;
table->count = 0;
table->capacity = 0;
table->thresholdUp = 0;
table->thresholdDown = 0;
}
void Helper::setMinimumCapacity(HashTableStructBase* table, sl_size capacity) noexcept
{
table->capacityMinimum = capacity;
fixCapacityRange(table);
updateThresholds(table);
}
void Helper::setMaximumCapacity(HashTableStructBase* table, sl_size capacity) noexcept
{
table->capacityMaximum = capacity;
fixCapacityRange(table);
updateThresholds(table);
}
sl_bool Helper::validateNodes(HashTableStructBase* table) noexcept
{
if (table->capacity == 0) {
sl_size capacity = table->capacityMinimum;
NODE** nodes = (NODE**)(Base::createMemory(sizeof(NODE*)*capacity));
if (nodes) {
Base::zeroMemory(nodes, sizeof(NODE*)*capacity);
table->nodes = nodes;
table->capacity = capacity;
updateThresholds(table);
return sl_true;
}
return sl_false;
} else {
return sl_true;
}
}
sl_bool Helper::reallocNodes(HashTableStructBase* table, sl_size capacity) noexcept
{
if (capacity > table->capacityMaximum) {
return sl_false;
}
NODE** nodes = (NODE**)(Base::reallocMemory(table->nodes, sizeof(NODE*)*capacity));
if (nodes) {
table->nodes = nodes;
table->capacity = capacity;
updateThresholds(table);
return sl_true;
}
return sl_false;
}
void Helper::expand(HashTableStructBase* table) noexcept
{
if (table->capacity < table->capacityMaximum && table->count >= table->thresholdUp) {
// double capacity
sl_size n = table->capacity;
if (reallocNodes(table, n + n)) {
NODE** nodes = table->nodes;
for (sl_size i = 0; i < n; i++) {
NODE* node = nodes[i];
nodes[i | n] = sl_null;
if (node) {
nodes[i] = sl_null;
sl_size highBitBefore = node->hash & n;
NODE* broken = sl_null;
nodes[i | highBitBefore] = node;
while (NODE* chain = node->next) {
sl_size highBitChain = chain->hash & n;
if (highBitBefore != highBitChain) {
if (broken) {
broken->next = chain;
} else {
nodes[i | highBitChain] = chain;
}
broken = node;
highBitBefore = highBitChain;
}
node = chain;
}
if (broken) {
broken->next = sl_null;
}
}
}
}
}
}
void Helper::shrink(HashTableStructBase* table) noexcept
{
while (table->capacity > table->capacityMinimum && table->count <= table->thresholdDown) {
// half capacity
NODE** nodes = table->nodes;
sl_size n = table->capacity >> 1;
for (sl_size i = 0; i < n; i++) {
NODE** link = nodes + i;
while (NODE* node = *link) {
link = &(node->next);
}
*link = nodes[i | n];
}
reallocNodes(table, n);
}
}
}
}
}
|
/* Copyright 2019 The TensorFlow 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 "tensorflow/lite/delegates/gpu/gl/kernels/softmax.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/memory/memory.h"
#include "tensorflow/lite/delegates/gpu/common/shape.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/types.h"
#include "tensorflow/lite/delegates/gpu/common/util.h"
#include "tensorflow/lite/delegates/gpu/gl/variable.h"
namespace tflite {
namespace gpu {
namespace gl {
namespace {
float4 GetMask(int num_channels) {
float4 mask(0.0f);
const int remainder = num_channels % 4 == 0 ? 4 : num_channels % 4;
for (int i = 0; i < remainder; ++i) mask[i] = 1.0f;
return mask;
}
class Softmax : public NodeShader {
public:
absl::Status GenerateCode(const GenerationContext& ctx,
GeneratedCode* generated_code) const final {
const auto& attr = absl::any_cast<const SoftmaxAttributes&>(ctx.op_attr);
if (ctx.input_shapes[0] != ctx.output_shapes[0]) {
return absl::InvalidArgumentError(
"Input and output shapes do not match.");
}
if (attr.axis != Axis::CHANNELS) {
return absl::UnimplementedError(
"Softmax is only supported for channels axis.");
}
return ctx.input_shapes[0][1] == 1 && ctx.input_shapes[0][2] == 1
? GenerateCodeFor1x1(ctx, generated_code)
: GenerateCodeGeneral(ctx, generated_code);
}
private:
absl::Status GenerateCodeFor1x1(const GenerationContext& ctx,
GeneratedCode* generated_code) const {
const int depth = IntegralDivideRoundUp(ctx.output_shapes[0][3], 4);
std::vector<Variable> shared_variables = {
{"partial_sum", std::vector<float4>(8)},
};
std::vector<Variable> uniform_parameters = {
{"depth", depth},
{"depth_div_32", IntegralDivideRoundUp(depth, 32)},
{"mask", GetMask(ctx.output_shapes[0][3])},
};
std::string source_code = R"(
highp vec4 kOnes = vec4(1.0);
highp float sum = 0.0;
int offset = 0;
int s = 0;
int tid = int(gl_LocalInvocationID.x);
do {
int z = offset + tid;
if (z < $depth$) {
highp vec4 mask_temp = z == $depth$ - 1 ? $mask$ : kOnes;
highp vec4 src = $input_data_0[0, 0, z]$;
sum += dot(mask_temp, exp(src));
offset += 32;
}
s++;
} while (s < $depth_div_32$);
partial_sum[tid / 4][tid % 4] = sum;
memoryBarrierShared();
barrier();
if (tid == 0) {
sum = dot(kOnes, partial_sum[0]);
sum += dot(kOnes, partial_sum[1]);
sum += dot(kOnes, partial_sum[2]);
sum += dot(kOnes, partial_sum[3]);
sum += dot(kOnes, partial_sum[4]);
sum += dot(kOnes, partial_sum[5]);
sum += dot(kOnes, partial_sum[6]);
sum += dot(kOnes, partial_sum[7]);
partial_sum[0][0] = 1.0 / sum;
}
memoryBarrierShared();
barrier();
sum = partial_sum[0][0];
offset = 0;
s = 0;
do {
int z = offset + tid;
if (z < $depth$) {
highp vec4 src = $input_data_0[0, 0, z]$;
highp vec4 temp = exp(src) * sum;
$output_data_0[0, 0, z] = temp$;
offset += 32;
}
s++;
} while (s < $depth_div_32$);
)";
*generated_code = {
/*parameters=*/std::move(uniform_parameters),
/*objects=*/{},
/*shared_variables=*/std::move(shared_variables),
/*workload=*/uint3(32, 1, 1),
/*workgroup=*/uint3(32, 1, 1),
/*source_code=*/std::move(source_code),
/*input=*/IOStructure::ONLY_DEFINITIONS,
/*output=*/IOStructure::ONLY_DEFINITIONS,
};
return absl::OkStatus();
}
absl::Status GenerateCodeGeneral(const GenerationContext& ctx,
GeneratedCode* generated_code) const {
std::vector<Variable> parameters = {
{"src_depth",
IntegralDivideRoundUp(static_cast<int>(ctx.output_shapes[0][3]), 4)},
{"mask", GetMask(ctx.output_shapes[0][3])},
};
std::string source_code = R"(
highp vec4 kOnes = vec4(1.0);
highp float sum = 0.0;
for (int d = 0; d < $src_depth$ - 1; ++d) {
highp vec4 src = $input_data_0[gid.x, gid.y, d]$;
sum += dot(kOnes, exp(src));
}
{
int d = $src_depth$ - 1;
highp vec4 src = $input_data_0[gid.x, gid.y, d]$;
sum += dot($mask$, exp(src));
}
for (int d = 0; d < $src_depth$; ++d) {
highp vec4 src = $input_data_0[gid.x, gid.y, d]$;
highp vec4 temp_sum = exp(src) / sum;
$output_data_0[gid.x, gid.y, d] = temp_sum$;
}
)";
*generated_code = {
/*parameters=*/std::move(parameters),
/*objects=*/{},
/*shared_variables=*/{},
/*workload=*/
uint3(static_cast<int>(ctx.output_shapes[0][2]),
static_cast<int>(ctx.output_shapes[0][1]), 1),
/*workgroup=*/uint3(),
/*source_code=*/std::move(source_code),
/*input=*/IOStructure::ONLY_DEFINITIONS,
/*output=*/IOStructure::ONLY_DEFINITIONS,
};
return absl::OkStatus();
}
};
} // namespace
std::unique_ptr<NodeShader> NewSoftmaxNodeShader() {
return absl::make_unique<Softmax>();
}
} // namespace gl
} // namespace gpu
} // namespace tflite
|
#pragma once
#include <mi.h>
#include "CIMitar.hpp"
#ifndef CIMITAR_VALUE_H_INCLUDED
#define CIMITAR_VALUE_H_INCLUDED
const MI_Type CIMTypeIDTranslator(const CIMitar::CIMTypes Type) noexcept;
const CIMitar::CIMTypes CIMTypeIDTranslator(const MI_Type Type) noexcept;
#endif CIMITAR_VALUE_H_INCLUDED
|
/*
Copyright (c) 2016 InternetWide.org and the ARPA2.net project
All rights reserved. See file LICENSE for exact terms (2-clause BSD license).
Adriaan de Groot <groot@kde.org>
*/
#include "verb.h"
#include <sys/select.h>
void VerbDispatcher::poll()
{
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/codedeploy/model/DeploymentReadyOption.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace CodeDeploy
{
namespace Model
{
DeploymentReadyOption::DeploymentReadyOption() :
m_actionOnTimeout(DeploymentReadyAction::NOT_SET),
m_actionOnTimeoutHasBeenSet(false),
m_waitTimeInMinutes(0),
m_waitTimeInMinutesHasBeenSet(false)
{
}
DeploymentReadyOption::DeploymentReadyOption(JsonView jsonValue) :
m_actionOnTimeout(DeploymentReadyAction::NOT_SET),
m_actionOnTimeoutHasBeenSet(false),
m_waitTimeInMinutes(0),
m_waitTimeInMinutesHasBeenSet(false)
{
*this = jsonValue;
}
DeploymentReadyOption& DeploymentReadyOption::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("actionOnTimeout"))
{
m_actionOnTimeout = DeploymentReadyActionMapper::GetDeploymentReadyActionForName(jsonValue.GetString("actionOnTimeout"));
m_actionOnTimeoutHasBeenSet = true;
}
if(jsonValue.ValueExists("waitTimeInMinutes"))
{
m_waitTimeInMinutes = jsonValue.GetInteger("waitTimeInMinutes");
m_waitTimeInMinutesHasBeenSet = true;
}
return *this;
}
JsonValue DeploymentReadyOption::Jsonize() const
{
JsonValue payload;
if(m_actionOnTimeoutHasBeenSet)
{
payload.WithString("actionOnTimeout", DeploymentReadyActionMapper::GetNameForDeploymentReadyAction(m_actionOnTimeout));
}
if(m_waitTimeInMinutesHasBeenSet)
{
payload.WithInteger("waitTimeInMinutes", m_waitTimeInMinutes);
}
return payload;
}
} // namespace Model
} // namespace CodeDeploy
} // namespace Aws
|
#include "engine.hpp"
#include <iostream>
static int NUM(0);
static std::pair<int, Chromosome> oneBatch()
{
std::cout << "\n==========================================" << std::endl;
std::cout << "run " << NUM << std::endl; ++NUM;
std::cout << "==========================================" << std::endl;
Engine myEngine(100, 42);
for (auto i = 0; i < 100; ++i)
{
std::pair<bool, Chromosome> result = myEngine.hasSolution();
if (result.first)
{
std::cout << "Got a solution in " << i+1 << " turn(s): " << result.second << std::endl;
return std::make_pair(i+1, result.second);
}
myEngine.makeNewGeneration();
}
std::pair<bool, Chromosome> result = myEngine.hasSolution();
if (result.first)
{
std::cout << "Got a solution in 100 turns: " << result.second << std::endl;
return std::make_pair(100, result.second);
} else {
std::cout << "No solution found" << std::endl;
return std::make_pair(0, Chromosome());
}
}
int main()
{
int numberOfSucess(0);
std::map<Chromosome, std::vector<bool> > results;
for (auto i = 0; i < 100; ++i)
{
std::pair<bool, Chromosome> out = oneBatch();
if (out.first != 0)
{
++numberOfSucess;
auto found = results.find(out.second);
if (results.end() != found)
{
results[out.second].push_back(out.first);
} else {
std::vector<bool> res = {out.first};
results[out.second] = res;
}
} else {
}
}
std::cout << "\n==========================================" << std::endl;
std::cout << "Found solution " << numberOfSucess << " times on 100" << std::endl;
std::for_each(
results.begin(),
results.end(),
[](const std::pair<Chromosome, std::vector<bool> >& c) {std::cout << c.first << " has been found " << c.second.size() << " times"<< std::endl;});
return 42;
}
|
/*
* Copyright (c) 2009-2011, NVIDIA Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of NVIDIA Corporation nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* 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 <COPYRIGHT HOLDER> 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 "AmbientProcessor.hpp"
#include "Util.hpp"
#include "base/Hash.hpp"
using namespace FW;
//------------------------------------------------------------------------
AmbientProcessor::AmbientProcessor(OctreeFile* file, int objectID)
: m_file (file),
m_objectID (objectID),
m_raysPerNode (DefaultRaysPerNode),
m_rayLength (1.0f),
m_flipNormals (false),
m_numWarps (256) // initial guess
{
m_compiler.setSourceFile("src/octree/cuda/Ambient.cu");
m_compiler.addOptions("-use_fast_math");
m_compiler.include("src/framework");
failIfError();
FW_ASSERT(file);
m_runtime = new OctreeRuntime(MemoryManager::Mode_Cuda);
CudaModule::checkError("cuEventCreate", cuEventCreate(&m_kernelStartEvent, 0));
CudaModule::checkError("cuEventCreate", cuEventCreate(&m_kernelEndEvent, 0));
}
//------------------------------------------------------------------------
AmbientProcessor::~AmbientProcessor(void)
{
CudaModule::checkError("cuEventDestroy", cuEventDestroy(m_kernelStartEvent));
CudaModule::checkError("cuEventDestroy", cuEventDestroy(m_kernelEndEvent));
delete m_runtime;
}
//------------------------------------------------------------------------
void AmbientProcessor::run(void)
{
Timer timer;
timer.start();
profileStart();
profilePush("AmbientProcessor");
// Select attachments.
OctreeFile::Object object = m_file->getObject(m_objectID);
Array<AttachIO::AttachType> in = object.runtimeAttachTypes;
Array<AttachIO::AttachType>& out = object.runtimeAttachTypes;
out.clear();
for (int i = 0; i < AttachSlot_Max; i++)
out.add(AttachIO::VoidAttach);
// Assign imported attachments.
for (int i = 0; i < in.getSize(); i++)
{
AttachIO::AttachType t = in[i];
switch (t)
{
case AttachIO::ColorNormalPaletteAttach: out[AttachSlot_Attribute] = t; break;
case AttachIO::ColorNormalCornerAttach: out[AttachSlot_Attribute] = t; break;
case AttachIO::ColorNormalDXTAttach: out[AttachSlot_Attribute] = t; break;
case AttachIO::ContourAttach: out[AttachSlot_Contour] = t; break;
case AttachIO::AOAttach: out[AttachSlot_AO] = t; break;
default: break;
}
}
// Set it.
out[AttachSlot_AO] = AttachIO::AOAttach;
m_file->setObject(m_objectID, object);
// Start worrying about CUDA side.
Array<AttachIO::AttachType> inputAttachTypes = out;
// inputAttachTypes.resize(2); // discard everything except contours and colornormals
m_runtime->addObject(m_objectID, object.rootSlice, inputAttachTypes);
// Compile kernel.
m_compiler.clearDefines();
if (inputAttachTypes[AttachSlot_Contour] == AttachIO::ContourAttach)
m_compiler.define("ENABLE_CONTOURS");
switch (inputAttachTypes[AttachSlot_Attribute])
{
case AttachIO::ColorNormalPaletteAttach: m_compiler.define("VOXELATTRIB_PALETTE"); break;
case AttachIO::ColorNormalCornerAttach: m_compiler.define("VOXELATTRIB_CORNER"); break;
case AttachIO::ColorNormalDXTAttach: m_compiler.define("VOXELATTRIB_DXT"); break;
default: fail("AmbientProcessor: Unsupported attribute attachment! (%d)", inputAttachTypes[AttachSlot_Attribute]); break;
}
if (m_flipNormals)
m_compiler.define("FLIP_NORMALS");
m_module = m_compiler.compile();
failIfError();
int nSlices = m_file->getNumSliceIDs();
// init timers
m_kernelTime = 0.0;
m_requestsProcessed = 0;
// load slices into runtime
struct StackEntry
{
S32 sliceID;
OctreeSlice* slice;
bool pop;
};
Array<StackEntry> stack;
stack.add().sliceID = object.rootSlice;
profilePush("Load runtime");
printf("Loading slices into runtime\n");
int cnt = 0;
while (stack.getSize())
{
printf("%d / %d ... \r", ++cnt, nSlices);
S32 sliceID = stack.removeLast().sliceID; // no pops
if (m_file->getSliceState(sliceID) != OctreeFile::SliceState_Complete)
continue;
OctreeSlice slice;
profilePush("readSlice");
m_file->readSlice(sliceID, slice);
profilePop();
int n = slice.getNumChildEntries();
for (int i=0; i < n; i++)
{
int c = slice.getChildEntry(i);
if (c == OctreeSlice::ChildEntry_Split)
continue;
if (c == OctreeSlice::ChildEntry_NoChild)
continue;
stack.add().sliceID = c;
}
for (int i = max(stack.getSize() - NumSlicesToPrefetch, 0); i < stack.getSize(); i++)
m_file->readSlicePrefetch(stack[i].sliceID);
m_runtime->setSliceToLoad(slice);
if (!m_runtime->loadSlice())
fail("out of memory");
}
profilePop();
printf("\n%s\n", m_runtime->getStats().getPtr());
// process slices
printf("\nProcessing slices\n");
profilePush("Process slices");
StackEntry& rootEntry = stack.add();
rootEntry.sliceID = object.rootSlice;
rootEntry.pop = false;
cnt = 0;
// stack for tracking node positions
Array<Array<NodeInfo> > positionStack;
positionStack.reset(25);
{
NodeInfo& metaRoot = positionStack[24].add();
metaRoot.pos.setZero();
metaRoot.validMask = 1;
metaRoot.lastInStrip = true;
metaRoot.secondInPair = false;
}
// make sure the task lists are empty before starting
m_sliceTasks.reset(0);
m_sliceTaskTotal = 0;
m_procTasks.reset(0);
m_procTaskTotal = 0;
Timer ambientTimer;
ambientTimer.start();
while (stack.getSize())
{
printf("%d / %d (%.2f/%.2f MRays/s)... \r",
cnt,
nSlices,
m_kernelTime ? (0.000001 * m_raysPerNode * m_requestsProcessed / m_kernelTime) : 0,
ambientTimer.getElapsed() ? (0.000001 * m_raysPerNode * m_requestsProcessed / ambientTimer.getElapsed()) : 0
);
StackEntry se = stack.removeLast();
if (se.pop)
{
processSlice(se.slice, positionStack[se.slice->getNodeScale()]);
continue;
}
S32 sliceID = se.sliceID;
cnt++;
if (m_file->getSliceState(sliceID) != OctreeFile::SliceState_Complete)
continue;
OctreeSlice* slice = new OctreeSlice;
profilePush("readSlice");
m_file->readSlice(sliceID, *slice);
profilePop();
// get position bits
int scale = slice->getNodeScale();
// track node positions
int idx = 0; // node index
int sidx = 0; // split node index
Array<NodeInfo>& sLevel = positionStack[slice->getNodeScale()];
Array<NodeInfo>& sParent = positionStack[slice->getNodeScale()+1];
sLevel.reset(0);
for (int i=0; i < sParent.getSize(); i++)
{
const NodeInfo& parent = sParent[i];
Vec3i ppos = parent.pos;
if (!isPosInCube(ppos, slice->getCubePos(), slice->getCubeScale()))
continue;
int ncnt = 0;
int iidx = -1;
for (int j=0; j < 8; j++)
{
if (!(parent.validMask & (1<<j)))
continue;
if (!slice->isNodeSplit(idx++))
continue;
iidx = sLevel.getSize();
NodeInfo& info = sLevel.add();
info.pos = ppos + base2ToVec(j) * (1 << scale);
info.validMask = slice->getNodeValidMask(sidx);
info.secondInPair = ((ncnt & 1) == 1);
info.lastInStrip = false;
sidx++;
ncnt++;
}
if (iidx >= 0)
sLevel[iidx].lastInStrip = true;
}
// add pop task for this slice before children
StackEntry& popEntry = stack.add();
popEntry.slice = slice;
popEntry.pop = true;
// child slices
int n = slice->getNumChildEntries();
for (int i=0; i < n; i++)
{
int c = slice->getChildEntry(i);
if (c == OctreeSlice::ChildEntry_Split)
continue;
if (c == OctreeSlice::ChildEntry_NoChild)
continue;
StackEntry& childEntry = stack.add();
childEntry.sliceID = c;
childEntry.pop = false;
}
// prefetch in presence of pop entries
int pcnt = 0;
int spos = stack.getSize()-1;
while (spos >= 0 && pcnt < NumSlicesToPrefetch)
{
if (!stack[spos].pop)
{
pcnt++;
m_file->readSlicePrefetch(stack[spos].sliceID);
}
spos--;
}
}
// flush task list
initiateProcessing();
finishProcessing();
// done
profilePop();
printf("\ntime elapsed: %.2f s\n", timer.end());
profilePop();
profileEnd();
}
//------------------------------------------------------------------------
void AmbientProcessor::processSlice(OctreeSlice* slice, const Array<NodeInfo>& nodes)
{
// find AO attachment if it already exists
S32* attachData = 0;
for (int i=0; i < slice->getNumAttach(); i++)
if (slice->getAttachType(i) == AttachIO::AOAttach)
attachData = slice->getData().getPtr(slice->getAttachOfs(i));
if (!attachData)
{
// reconstruct slice
OctreeSlice src = *slice; // take a copy
if (nodes.getSize() != slice->getNumSplitNodes())
fail("Node count mismatch");
slice->init(src.getNumChildEntries(), src.getNumAttach()+1, src.getNumNodes(), src.getNumSplitNodes());
slice->setID(src.getID());
slice->setState(src.getState());
slice->setCubePos(src.getCubePos());
slice->setCubeScale(src.getCubeScale());
slice->setNodeScale(src.getNodeScale());
memcpy(slice->getChildEntryPtr(), src.getChildEntryPtr(), src.getNumChildEntries() * sizeof(S32));
memcpy(slice->getNodeSplitPtr(), src.getNodeSplitPtr(), ((src.getNumNodes() + 31) >> 5) * 4);
memcpy(slice->getNodeValidMaskPtr(), src.getNodeValidMaskPtr(), src.getNumSplitNodes());
for (int i=0; i < src.getNumAttach(); i++)
{
slice->startAttach(src.getAttachType(i));
slice->getData().add(src.getData().getPtr(src.getAttachOfs(i)), src.getAttachSize(i));
slice->endAttach();
}
// create the new attachment
S32 base = slice->getData().getSize();
slice->startAttach(AttachIO::AOAttach);
for (int i=0; i < slice->getNumSplitNodes(); i++)
if (nodes[i].secondInPair || nodes[i].lastInStrip)
slice->getData().add(0, 2); // all black blocks
slice->endAttach();
attachData = slice->getData().getPtr(base);
}
// count number of ao requests
for (int i=0; i < slice->getNumSplitNodes(); i++)
m_sliceTaskTotal += popc8(slice->getNodeValidMask(i));
// add prepared slice to slice task list
SliceTask* task = new SliceTask;
task->slice = slice;
task->nodes = nodes;
task->attachData = attachData;
m_sliceTasks.add(task);
// check if we have enough AO rays
if (m_sliceTaskTotal * m_raysPerNode >= MinRaysPerBatch)
initiateProcessing();
}
void AmbientProcessor::initiateProcessing(void)
{
// finish previous processing if any
finishProcessing();
// initialize ao request buffer
int numRequests = m_sliceTaskTotal;
// Perform these operations only for non-zero number of requests.
if (numRequests)
{
m_requestBuffer.resizeDiscard(numRequests * sizeof(AmbientRequest));
AmbientRequest* reqPtr = (AmbientRequest*)m_requestBuffer.getMutablePtr();
for (int t=0; t < m_sliceTasks.getSize(); t++)
{
SliceTask* task = m_sliceTasks[t];
OctreeSlice* slice = task->slice;
const Array<NodeInfo>& nodes = task->nodes;
U32 childHalfSize = 1 << (slice->getNodeScale() - 2);
for (int i=0; i < slice->getNumSplitNodes(); i++)
{
U32 validMask = slice->getNodeValidMask(i);
Vec3i base = nodes[i].pos + childHalfSize;
// loop over children
for (int j=0; j < 8; j++)
{
if (!(validMask & (1<<j)))
continue;
AmbientRequest& req = *reqPtr++;
req.pos = base + base2ToVec(j) * 2 * childHalfSize;
req.level = slice->getNodeScale() - 1;
}
}
}
// Reset request buffer size.
m_resultBuffer.resizeDiscard(numRequests * sizeof(AmbientResult));
// thunder and lightning! invoke CUDA
// Clear active warp buffer.
m_activeWarps.resizeDiscard(m_numWarps * sizeof(S32));
memset(m_activeWarps.getMutablePtr(), 0, (size_t)m_activeWarps.getSize());
// Launch all requests.
int maxRequests = max(MaxRaysPerBatch / m_raysPerNode, 1);
for (int firstRequest = 0; firstRequest < numRequests; firstRequest += maxRequests)
{
CudaModule::sync(false); // keep watchdog awake and prevent race conditions
// Set input.
AmbientInput& in = getInput();
in.numRequests = min(numRequests - firstRequest, maxRequests);
in.raysPerNode = m_raysPerNode;
in.rayLength = m_rayLength;
in.requestPtr = m_requestBuffer.getCudaPtr(firstRequest * sizeof(AmbientRequest));
in.resultPtr = m_resultBuffer.getMutableCudaPtr(firstRequest * sizeof(AmbientResult));
in.rootNode = m_runtime->getRootNodeCuda(m_objectID);
in.activeWarps = m_activeWarps.getMutableCudaPtr();
OctreeMatrices& om = in.octreeMatrices;
Mat4f octreeToWorld = m_file->getObject(m_objectID).objectToWorld * m_file->getObject(m_objectID).octreeToObject;
om.octreeToWorld = octreeToWorld * Mat4f::translate(Vec3f(-1.0f));
om.worldToOctree = invert(in.octreeMatrices.octreeToWorld);
om.octreeToWorldN = octreeToWorld.getXYZ().inverted().transposed();
// Determine grid size.
Vec2i blockSize = Vec2i(AMBK_BLOCK_WIDTH, AMBK_BLOCK_HEIGHT);
int blockThreads = blockSize.x * blockSize.y;
Vec2i gridSize = Vec2i((m_numWarps * 32 + blockThreads - 1) / blockThreads, 1);
// Init warp counter.
getWarpCounter() = 0;
m_module->updateGlobals();
// Launch kernel.
if (firstRequest == 0)
{
CudaModule::sync(false); // for accurate timing
CudaModule::checkError("cuEventRecord", cuEventRecord(m_kernelStartEvent, NULL));
}
m_module->getKernel("ambientKernel").setAsync().launch(gridSize * blockSize, blockSize); // async launch
}
CudaModule::checkError("cuEventRecord", cuEventRecord(m_kernelEndEvent, NULL));
}
// move tasks from current queue to processing queue
m_procTasks = m_sliceTasks;
m_procTaskTotal = m_sliceTaskTotal;
m_sliceTasks.reset(0);
m_sliceTaskTotal = 0;
}
void AmbientProcessor::finishProcessing(void)
{
int numRequests = m_procTaskTotal;
// Kernel was launched only if there were any requests.
if (numRequests)
{
// Finish running previous kernel.
profilePush("wait for CUDA");
CudaModule::sync(true);
profilePop();
float kernelTime;
CudaModule::checkError("cuEventElapsedTime", cuEventElapsedTime(&kernelTime, m_kernelStartEvent, m_kernelEndEvent));
m_kernelTime += kernelTime * .001f;
// Adjust the number of warps.
const S32* activeWarps = (const S32*)m_activeWarps.getPtr();
int numWarps = 0;
for (int i = 0; i < m_numWarps; i++)
if (activeWarps[i])
numWarps++;
if (numWarps * 2 > m_numWarps)
{
printf("warp count auto-detected: %d warps \n", numWarps);
m_numWarps = numWarps * 2;
}
// Update request counter.
m_requestsProcessed += numRequests;
// read node results and write to slices
AmbientResult* resPtr = (AmbientResult*)m_resultBuffer.getPtr();
for (int t=0; t < m_procTasks.getSize(); t++)
{
SliceTask* task = m_procTasks[t];
OctreeSlice* slice = task->slice;
S32* attachData = task->attachData;
const Array<NodeInfo>& nodes = task->nodes;
// Collect DXT blocks.
float block[16];
float bmin = 1.f;
float bmax = 0.f;
for (int j=0; j < 16; j++)
block[j] = 0.f;
for (int i=0; i < slice->getNumSplitNodes(); i++)
{
U32 validMask = slice->getNodeValidMask(i);
int obase = nodes[i].secondInPair ? 8 : 0;
for (int j=0; j < 8; j++)
{
if (!(validMask & (1<<j)))
continue;
Vec3f res = (resPtr++)->ao;
float occ = res.x;
bmin = min(bmin, occ);
bmax = max(bmax, occ);
block[obase + j] = occ;
}
if (nodes[i].secondInPair || nodes[i].lastInStrip)
{
// construct block
U8 imin = (U8)min(max(bmin * 255.f, 0.f), 255.f);
U8 imax = (U8)min(max(bmax * 255.f, 0.f), 255.f);
U64 b = imin | (imax << 8);
for (int j=0; j < 16; j++)
{
float val = (block[j] - bmin) / (bmax - bmin) * 7.f;
int ival = (int)(val + .5f);
ival = min(max(ival, 0), 7);
b |= ((U64)ival) << (16 + j*3);
}
// store it
*((U64*)attachData) = b;
attachData += 2;
// clear block data
for (int j=0; j < 16; j++)
block[j] = 0.f;
bmin = 1.f;
bmax = 0.f;
}
}
// write to disk
m_file->writeSlice(*slice);
// delete task and slice
delete task;
delete slice;
}
}
// all done
m_procTasks.clear();
m_procTaskTotal = 0;
}
|
// Copyright (c) 2012-2016 The Bitcoin Core developers
// Copyright (c) 2017 The AmlBitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "serialize.h"
#include "streams.h"
#include "hash.h"
#include "test/test_AmlBitcoin.h"
#include <stdint.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(serialize_tests, BasicTestingSetup)
class CSerializeMethodsTestSingle
{
protected:
int intval;
bool boolval;
std::string stringval;
const char *charstrval;
CTransactionRef txval;
public:
CSerializeMethodsTestSingle() = default;
CSerializeMethodsTestSingle(int intvalin, bool boolvalin, std::string stringvalin, const char *charstrvalin, CTransaction txvalin)
: intval(intvalin), boolval(boolvalin), stringval(std::move(stringvalin)), charstrval(charstrvalin), txval(MakeTransactionRef(txvalin))
{}
ADD_SERIALIZE_METHODS;
template<typename Stream, typename Operation>
inline void SerializationOp(Stream &s, Operation ser_action)
{
READWRITE(intval);
READWRITE(boolval);
READWRITE(stringval);
READWRITE(FLATDATA(charstrval));
READWRITE(txval);
}
bool operator==(const CSerializeMethodsTestSingle &rhs)
{
return intval == rhs.intval && \
boolval == rhs.boolval && \
stringval == rhs.stringval && \
strcmp(charstrval, rhs.charstrval) == 0 && \
*txval == *rhs.txval;
}
};
class CSerializeMethodsTestMany : public CSerializeMethodsTestSingle
{
public:
using CSerializeMethodsTestSingle::CSerializeMethodsTestSingle;
ADD_SERIALIZE_METHODS;
template<typename Stream, typename Operation>
inline void SerializationOp(Stream &s, Operation ser_action)
{
READWRITEMANY(intval, boolval, stringval, FLATDATA(charstrval), txval);
}
};
BOOST_AUTO_TEST_CASE(sizes_test)
{
BOOST_TEST_MESSAGE("Running Sizes Test");
BOOST_CHECK_EQUAL(sizeof(char), GetSerializeSize(char(0), 0));
BOOST_CHECK_EQUAL(sizeof(int8_t), GetSerializeSize(int8_t(0), 0));
BOOST_CHECK_EQUAL(sizeof(uint8_t), GetSerializeSize(uint8_t(0), 0));
BOOST_CHECK_EQUAL(sizeof(int16_t), GetSerializeSize(int16_t(0), 0));
BOOST_CHECK_EQUAL(sizeof(uint16_t), GetSerializeSize(uint16_t(0), 0));
BOOST_CHECK_EQUAL(sizeof(int32_t), GetSerializeSize(int32_t(0), 0));
BOOST_CHECK_EQUAL(sizeof(uint32_t), GetSerializeSize(uint32_t(0), 0));
BOOST_CHECK_EQUAL(sizeof(int64_t), GetSerializeSize(int64_t(0), 0));
BOOST_CHECK_EQUAL(sizeof(uint64_t), GetSerializeSize(uint64_t(0), 0));
BOOST_CHECK_EQUAL(sizeof(float), GetSerializeSize(float(0), 0));
BOOST_CHECK_EQUAL(sizeof(double), GetSerializeSize(double(0), 0));
// Bool is serialized as char
BOOST_CHECK_EQUAL(sizeof(char), GetSerializeSize(bool(0), 0));
// Sanity-check GetSerializeSize and c++ type matching
BOOST_CHECK_EQUAL(GetSerializeSize(char(0), 0), 1);
BOOST_CHECK_EQUAL(GetSerializeSize(int8_t(0), 0), 1);
BOOST_CHECK_EQUAL(GetSerializeSize(uint8_t(0), 0), 1);
BOOST_CHECK_EQUAL(GetSerializeSize(int16_t(0), 0), 2);
BOOST_CHECK_EQUAL(GetSerializeSize(uint16_t(0), 0), 2);
BOOST_CHECK_EQUAL(GetSerializeSize(int32_t(0), 0), 4);
BOOST_CHECK_EQUAL(GetSerializeSize(uint32_t(0), 0), 4);
BOOST_CHECK_EQUAL(GetSerializeSize(int64_t(0), 0), 8);
BOOST_CHECK_EQUAL(GetSerializeSize(uint64_t(0), 0), 8);
BOOST_CHECK_EQUAL(GetSerializeSize(float(0), 0), 4);
BOOST_CHECK_EQUAL(GetSerializeSize(double(0), 0), 8);
BOOST_CHECK_EQUAL(GetSerializeSize(bool(0), 0), 1);
}
BOOST_AUTO_TEST_CASE(floats_conversion_test)
{
BOOST_TEST_MESSAGE("Running Floats Conversion Test");
// Choose values that map unambiguously to binary floating point to avoid
// rounding issues at the compiler side.
BOOST_CHECK_EQUAL(ser_uint32_to_float(0x00000000), 0.0F);
BOOST_CHECK_EQUAL(ser_uint32_to_float(0x3f000000), 0.5F);
BOOST_CHECK_EQUAL(ser_uint32_to_float(0x3f800000), 1.0F);
BOOST_CHECK_EQUAL(ser_uint32_to_float(0x40000000), 2.0F);
BOOST_CHECK_EQUAL(ser_uint32_to_float(0x40800000), 4.0F);
BOOST_CHECK_EQUAL(ser_uint32_to_float(0x44444444), 785.066650390625F);
BOOST_CHECK_EQUAL(ser_float_to_uint32(0.0F), 0x00000000);
BOOST_CHECK_EQUAL(ser_float_to_uint32(0.5F), 0x3f000000);
BOOST_CHECK_EQUAL(ser_float_to_uint32(1.0F), 0x3f800000);
BOOST_CHECK_EQUAL(ser_float_to_uint32(2.0F), 0x40000000);
BOOST_CHECK_EQUAL(ser_float_to_uint32(4.0F), 0x40800000);
BOOST_CHECK_EQUAL(ser_float_to_uint32(785.066650390625F), 0x44444444);
}
BOOST_AUTO_TEST_CASE(doubles_conversion_test)
{
BOOST_TEST_MESSAGE("Running Doubles Conversion Test");
// Choose values that map unambiguously to binary floating point to avoid
// rounding issues at the compiler side.
BOOST_CHECK_EQUAL(ser_uint64_to_double(0x0000000000000000ULL), 0.0);
BOOST_CHECK_EQUAL(ser_uint64_to_double(0x3fe0000000000000ULL), 0.5);
BOOST_CHECK_EQUAL(ser_uint64_to_double(0x3ff0000000000000ULL), 1.0);
BOOST_CHECK_EQUAL(ser_uint64_to_double(0x4000000000000000ULL), 2.0);
BOOST_CHECK_EQUAL(ser_uint64_to_double(0x4010000000000000ULL), 4.0);
BOOST_CHECK_EQUAL(ser_uint64_to_double(0x4088888880000000ULL), 785.066650390625);
BOOST_CHECK_EQUAL(ser_double_to_uint64(0.0), 0x0000000000000000ULL);
BOOST_CHECK_EQUAL(ser_double_to_uint64(0.5), 0x3fe0000000000000ULL);
BOOST_CHECK_EQUAL(ser_double_to_uint64(1.0), 0x3ff0000000000000ULL);
BOOST_CHECK_EQUAL(ser_double_to_uint64(2.0), 0x4000000000000000ULL);
BOOST_CHECK_EQUAL(ser_double_to_uint64(4.0), 0x4010000000000000ULL);
BOOST_CHECK_EQUAL(ser_double_to_uint64(785.066650390625), 0x4088888880000000ULL);
}
/*
Python code to generate the below hashes:
def reversed_hex(x):
return binascii.hexlify(''.join(reversed(x)))
def dsha256(x):
return hashlib.sha256(hashlib.sha256(x).digest()).digest()
reversed_hex(dsha256(''.join(struct.pack('<f', x) for x in range(0,1000)))) == '8e8b4cf3e4df8b332057e3e23af42ebc663b61e0495d5e7e32d85099d7f3fe0c'
reversed_hex(dsha256(''.join(struct.pack('<d', x) for x in range(0,1000)))) == '43d0c82591953c4eafe114590d392676a01585d25b25d433557f0d7878b23f96'
*/
BOOST_AUTO_TEST_CASE(floats_test)
{
BOOST_TEST_MESSAGE("Running Floats Test");
CDataStream ss(SER_DISK, 0);
// encode
for (int i = 0; i < 1000; i++)
{
ss << float(i);
}
BOOST_CHECK(Hash(ss.begin(), ss.end()) == uint256S("8e8b4cf3e4df8b332057e3e23af42ebc663b61e0495d5e7e32d85099d7f3fe0c"));
// decode
for (int i = 0; i < 1000; i++)
{
float j;
ss >> j;
BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
}
}
BOOST_AUTO_TEST_CASE(doubles_test)
{
BOOST_TEST_MESSAGE("Running Doubles Test");
CDataStream ss(SER_DISK, 0);
// encode
for (int i = 0; i < 1000; i++)
{
ss << double(i);
}
BOOST_CHECK(Hash(ss.begin(), ss.end()) == uint256S("43d0c82591953c4eafe114590d392676a01585d25b25d433557f0d7878b23f96"));
// decode
for (int i = 0; i < 1000; i++)
{
double j;
ss >> j;
BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
}
}
BOOST_AUTO_TEST_CASE(varints_test)
{
BOOST_TEST_MESSAGE("Running VarInts Test");
// encode
CDataStream ss(SER_DISK, 0);
CDataStream::size_type size = 0;
for (int i = 0; i < 100000; i++)
{
ss << VARINT(i);
size += ::GetSerializeSize(VARINT(i), 0, 0);
BOOST_CHECK(size == ss.size());
}
for (uint64_t i = 0; i < 100000000000ULL; i += 999999937)
{
ss << VARINT(i);
size += ::GetSerializeSize(VARINT(i), 0, 0);
BOOST_CHECK(size == ss.size());
}
// decode
for (int i = 0; i < 100000; i++)
{
int j = -1;
ss >> VARINT(j);
BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
}
for (uint64_t i = 0; i < 100000000000ULL; i += 999999937)
{
uint64_t j = -1;
ss >> VARINT(j);
BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
}
}
BOOST_AUTO_TEST_CASE(varints_bitpatterns_test)
{
BOOST_TEST_MESSAGE("Running VarInts BitPatterns Test");
CDataStream ss(SER_DISK, 0);
ss << VARINT(0);
BOOST_CHECK_EQUAL(HexStr(ss), "00");
ss.clear();
ss << VARINT(0x7f);
BOOST_CHECK_EQUAL(HexStr(ss), "7f");
ss.clear();
ss << VARINT((int8_t) 0x7f);
BOOST_CHECK_EQUAL(HexStr(ss), "7f");
ss.clear();
ss << VARINT(0x80);
BOOST_CHECK_EQUAL(HexStr(ss), "8000");
ss.clear();
ss << VARINT((uint8_t) 0x80);
BOOST_CHECK_EQUAL(HexStr(ss), "8000");
ss.clear();
ss << VARINT(0x1234);
BOOST_CHECK_EQUAL(HexStr(ss), "a334");
ss.clear();
ss << VARINT((int16_t) 0x1234);
BOOST_CHECK_EQUAL(HexStr(ss), "a334");
ss.clear();
ss << VARINT(0xffff);
BOOST_CHECK_EQUAL(HexStr(ss), "82fe7f");
ss.clear();
ss << VARINT((uint16_t) 0xffff);
BOOST_CHECK_EQUAL(HexStr(ss), "82fe7f");
ss.clear();
ss << VARINT(0x123456);
BOOST_CHECK_EQUAL(HexStr(ss), "c7e756");
ss.clear();
ss << VARINT((int32_t) 0x123456);
BOOST_CHECK_EQUAL(HexStr(ss), "c7e756");
ss.clear();
ss << VARINT(0x80123456U);
BOOST_CHECK_EQUAL(HexStr(ss), "86ffc7e756");
ss.clear();
ss << VARINT((uint32_t) 0x80123456U);
BOOST_CHECK_EQUAL(HexStr(ss), "86ffc7e756");
ss.clear();
ss << VARINT(0xffffffff);
BOOST_CHECK_EQUAL(HexStr(ss), "8efefefe7f");
ss.clear();
ss << VARINT(0x7fffffffffffffffLL);
BOOST_CHECK_EQUAL(HexStr(ss), "fefefefefefefefe7f");
ss.clear();
ss << VARINT(0xffffffffffffffffULL);
BOOST_CHECK_EQUAL(HexStr(ss), "80fefefefefefefefe7f");
ss.clear();
}
BOOST_AUTO_TEST_CASE(compactsize_test)
{
BOOST_TEST_MESSAGE("Running CompactSize Test");
CDataStream ss(SER_DISK, 0);
std::vector<char>::size_type i, j;
for (i = 1; i <= MAX_SIZE; i *= 2)
{
WriteCompactSize(ss, i - 1);
WriteCompactSize(ss, i);
}
for (i = 1; i <= MAX_SIZE; i *= 2)
{
j = ReadCompactSize(ss);
BOOST_CHECK_MESSAGE((i - 1) == j, "decoded:" << j << " expected:" << (i - 1));
j = ReadCompactSize(ss);
BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
}
}
static bool isCanonicalException(const std::ios_base::failure &ex)
{
std::ios_base::failure expectedException("non-canonical ReadCompactSize()");
// The string returned by what() can be different for different platforms.
// Instead of directly comparing the ex.what() with an expected string,
// create an instance of exception to see if ex.what() matches
// the expected explanatory string returned by the exception instance.
return strcmp(expectedException.what(), ex.what()) == 0;
}
BOOST_AUTO_TEST_CASE(noncanonical_test)
{
BOOST_TEST_MESSAGE("Running NonCanonical Test");
// Write some non-canonical CompactSize encodings, and
// make sure an exception is thrown when read back.
CDataStream ss(SER_DISK, 0);
std::vector<char>::size_type n;
// zero encoded with three bytes:
ss.write("\xfd\x00\x00", 3);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// 0xfc encoded with three bytes:
ss.write("\xfd\xfc\x00", 3);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// 0xfd encoded with three bytes is OK:
ss.write("\xfd\xfd\x00", 3);
n = ReadCompactSize(ss);
BOOST_CHECK(n == 0xfd);
// zero encoded with five bytes:
ss.write("\xfe\x00\x00\x00\x00", 5);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// 0xffff encoded with five bytes:
ss.write("\xfe\xff\xff\x00\x00", 5);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// zero encoded with nine bytes:
ss.write("\xff\x00\x00\x00\x00\x00\x00\x00\x00", 9);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// 0x01ffffff encoded with nine bytes:
ss.write("\xff\xff\xff\xff\x01\x00\x00\x00\x00", 9);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
}
BOOST_AUTO_TEST_CASE(insert_delete_test)
{
BOOST_TEST_MESSAGE("Running Insert Delete Test");
// Test inserting/deleting bytes.
CDataStream ss(SER_DISK, 0);
BOOST_CHECK_EQUAL(ss.size(), 0);
ss.write("\x00\x01\x02\xff", 4);
BOOST_CHECK_EQUAL(ss.size(), 4);
char c = (char) 11;
// Inserting at beginning/end/middle:
ss.insert(ss.begin(), c);
BOOST_CHECK_EQUAL(ss.size(), 5);
BOOST_CHECK_EQUAL(ss[0], c);
BOOST_CHECK_EQUAL(ss[1], 0);
ss.insert(ss.end(), c);
BOOST_CHECK_EQUAL(ss.size(), 6);
BOOST_CHECK_EQUAL(ss[4], (char) 0xff);
BOOST_CHECK_EQUAL(ss[5], c);
ss.insert(ss.begin() + 2, c);
BOOST_CHECK_EQUAL(ss.size(), 7);
BOOST_CHECK_EQUAL(ss[2], c);
// Delete at beginning/end/middle
ss.erase(ss.begin());
BOOST_CHECK_EQUAL(ss.size(), 6);
BOOST_CHECK_EQUAL(ss[0], 0);
ss.erase(ss.begin() + ss.size() - 1);
BOOST_CHECK_EQUAL(ss.size(), 5);
BOOST_CHECK_EQUAL(ss[4], (char) 0xff);
ss.erase(ss.begin() + 1);
BOOST_CHECK_EQUAL(ss.size(), 4);
BOOST_CHECK_EQUAL(ss[0], 0);
BOOST_CHECK_EQUAL(ss[1], 1);
BOOST_CHECK_EQUAL(ss[2], 2);
BOOST_CHECK_EQUAL(ss[3], (char) 0xff);
// Make sure GetAndClear does the right thing:
CSerializeData d;
ss.GetAndClear(d);
BOOST_CHECK_EQUAL(ss.size(), 0);
}
BOOST_AUTO_TEST_CASE(class_methods_test)
{
BOOST_TEST_MESSAGE("Running Class Methods Test");
int intval(100);
bool boolval(true);
std::string stringval("testing");
const char *charstrval("testing charstr");
CMutableTransaction txval;
CSerializeMethodsTestSingle methodtest1(intval, boolval, stringval, charstrval, txval);
CSerializeMethodsTestMany methodtest2(intval, boolval, stringval, charstrval, txval);
CSerializeMethodsTestSingle methodtest3;
CSerializeMethodsTestMany methodtest4;
CDataStream ss(SER_DISK, PROTOCOL_VERSION);
BOOST_CHECK(methodtest1 == methodtest2);
ss << methodtest1;
ss >> methodtest4;
ss << methodtest2;
ss >> methodtest3;
BOOST_CHECK(methodtest1 == methodtest2);
BOOST_CHECK(methodtest2 == methodtest3);
BOOST_CHECK(methodtest3 == methodtest4);
CDataStream ss2(SER_DISK, PROTOCOL_VERSION, intval, boolval, stringval, FLATDATA(charstrval), txval);
ss2 >> methodtest3;
BOOST_CHECK(methodtest3 == methodtest4);
}
BOOST_AUTO_TEST_SUITE_END()
|
#ifndef PLAYER_HPP
#define PLAYER_HPP
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<fstream>
#include<sstream>
#include<assert.h>
#include<exception>
class player
{
private:
std::string name;
int hp;
int attack_points;
int defence_points;
int max_hp;
int num_fights = 0;
int level = 1;
int gold = 0;
public:
player(std::string input_name, int start_hp, int max_hp, int start_attackpoints, int start_defencepoints);
virtual ~player();
// Setter functions
// void set_name(std::string name);
void set_hp(int hp);
void set_max_hp(int max_hp);
void set_attackpoints(int attack_points);
void set_defencepoints(int defence_points);
void add_numfights();
void add_level();
void add_gold(int gold_amount);
// Getter functions
std::string get_name();
int get_hp();
int get_max_hp();
int get_attackpoints();
int get_defencepoints();
int get_numfights();
int get_level();
int get_gold();
// Other methods
void showstats(); // show current statistics of the player
bool is_alive(); // check if the player is alive
virtual void restore_hp(); // recover the player, restore the hp to it's max
virtual std::string get_position(); // get the position of the player in the rankings
virtual bool is_criticalstrike(); // check if a player has hit a critical strike
virtual int is_magicused(); // check if player using magic
virtual int magic_attack(int spell_num); // magic attack
};
#endif // player.hpp define closed
|
/**
* @file
*/
#include "AggroTableModel.h"
#include <QColor>
namespace ai {
namespace debug {
AggroTableModel::AggroTableModel(const AIDebugger& debugger, QTableView *tableView) :
QAbstractTableModel(nullptr), _debugger(debugger), _parent(tableView) {
}
AggroTableModel::~AggroTableModel() {
}
void AggroTableModel::update() {
beginResetModel();
endResetModel();
}
int AggroTableModel::rowCount(const QModelIndex & /*parent*/) const {
const std::vector<AIStateAggroEntry>& aggro = _debugger.getAggro();
return aggro.size();
}
int AggroTableModel::columnCount(const QModelIndex & /*parent*/) const {
return 2;
}
QVariant AggroTableModel::headerData(int section, Qt::Orientation orientation, int role) const {
if (orientation != Qt::Horizontal) {
return QVariant();
}
if (role == Qt::DisplayRole) {
switch (section) {
case 0:
return tr("ID");
case 1:
return tr("Aggro");
default:
break;
}
}
return QVariant();
}
QVariant AggroTableModel::data(const QModelIndex &mdlIndex, int role) const {
const std::vector<AIStateAggroEntry>& aggro = _debugger.getAggro();
if (role == Qt::DisplayRole) {
switch (mdlIndex.column()) {
case 0:
return aggro.at(mdlIndex.row()).id;
case 1:
return aggro.at(mdlIndex.row()).aggro;
default:
break;
}
}
return QVariant();
}
}
}
|
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "shufflechannel_vulkan.h"
#include <algorithm>
namespace ncnn {
DEFINE_LAYER_CREATOR(ShuffleChannel_vulkan)
ShuffleChannel_vulkan::ShuffleChannel_vulkan()
{
support_vulkan = true;
pipeline_shufflechannel = 0;
pipeline_shufflechannel_pack4 = 0;
pipeline_shufflechannel_pack8 = 0;
}
int ShuffleChannel_vulkan::create_pipeline(const Option& opt)
{
const Mat& shape = bottom_shapes.empty() ? Mat() : bottom_shapes[0];
const Mat& out_shape = top_shapes.empty() ? Mat() : top_shapes[0];
int elempack = 1;
if (shape.dims == 1) elempack = opt.use_shader_pack8 && shape.w % 8 == 0 ? 8 : shape.w % 4 == 0 ? 4 : 1;
if (shape.dims == 2) elempack = opt.use_shader_pack8 && shape.h % 8 == 0 ? 8 : shape.h % 4 == 0 ? 4 : 1;
if (shape.dims == 3) elempack = opt.use_shader_pack8 && shape.c % 8 == 0 ? 8 : shape.c % 4 == 0 ? 4 : 1;
int out_elempack = 1;
if (out_shape.dims == 1) out_elempack = opt.use_shader_pack8 && out_shape.w % 8 == 0 ? 8 : out_shape.w % 4 == 0 ? 4 : 1;
if (out_shape.dims == 2) out_elempack = opt.use_shader_pack8 && out_shape.h % 8 == 0 ? 8 : out_shape.h % 4 == 0 ? 4 : 1;
if (out_shape.dims == 3) out_elempack = opt.use_shader_pack8 && out_shape.c % 8 == 0 ? 8 : out_shape.c % 4 == 0 ? 4 : 1;
size_t elemsize;
size_t out_elemsize;
if (opt.use_fp16_storage)
{
elemsize = elempack * 2u;
out_elemsize = out_elempack * 2u;
}
else if (opt.use_fp16_packed)
{
elemsize = elempack == 1 ? 4u : elempack * 2u;
out_elemsize = out_elempack == 1 ? 4u : out_elempack * 2u;
}
else
{
elemsize = elempack * 4u;
out_elemsize = out_elempack * 4u;
}
Mat shape_packed;
if (shape.dims == 1) shape_packed = Mat(shape.w / elempack, (void*)0, elemsize, elempack);
if (shape.dims == 2) shape_packed = Mat(shape.w, shape.h / elempack, (void*)0, elemsize, elempack);
if (shape.dims == 3) shape_packed = Mat(shape.w, shape.h, shape.c / elempack, (void*)0, elemsize, elempack);
Mat out_shape_packed;
if (out_shape.dims == 1) out_shape_packed = Mat(out_shape.w / out_elempack, (void*)0, out_elemsize, out_elempack);
if (out_shape.dims == 2) out_shape_packed = Mat(out_shape.w, out_shape.h / out_elempack, (void*)0, out_elemsize, out_elempack);
if (out_shape.dims == 3) out_shape_packed = Mat(out_shape.w, out_shape.h, out_shape.c / out_elempack, (void*)0, out_elemsize, out_elempack);
std::vector<vk_specialization_type> specializations(1 + 10);
specializations[0].i = group;
specializations[1 + 0].i = shape_packed.dims;
specializations[1 + 1].i = shape_packed.w;
specializations[1 + 2].i = shape_packed.h;
specializations[1 + 3].i = shape_packed.c;
specializations[1 + 4].i = shape_packed.cstep;
specializations[1 + 5].i = out_shape_packed.dims;
specializations[1 + 6].i = out_shape_packed.w;
specializations[1 + 7].i = out_shape_packed.h;
specializations[1 + 8].i = out_shape_packed.c;
specializations[1 + 9].i = out_shape_packed.cstep;
Mat local_size_xyz;
if (out_shape_packed.dims != 0)
{
local_size_xyz.w = std::min(4, out_shape_packed.w);
local_size_xyz.h = std::min(4, out_shape_packed.h);
local_size_xyz.c = std::min(4, out_shape_packed.c);
}
// pack1
if (shape.dims == 0 || elempack == 1)
{
pipeline_shufflechannel = new Pipeline(vkdev);
pipeline_shufflechannel->set_optimal_local_size_xyz(local_size_xyz);
pipeline_shufflechannel->create("shufflechannel", opt, specializations, 2, 10);
}
// pack4
if (shape.dims == 0 || elempack == 4)
{
pipeline_shufflechannel_pack4 = new Pipeline(vkdev);
pipeline_shufflechannel_pack4->set_optimal_local_size_xyz(local_size_xyz);
pipeline_shufflechannel_pack4->create("shufflechannel_pack4", opt, specializations, 2, 10);
}
// pack8
if (shape.dims == 0 || elempack == 8)
{
pipeline_shufflechannel_pack8 = new Pipeline(vkdev);
pipeline_shufflechannel_pack8->set_optimal_local_size_xyz(local_size_xyz);
pipeline_shufflechannel_pack8->create("shufflechannel_pack8", opt, specializations, 2, 10);
}
return 0;
}
int ShuffleChannel_vulkan::destroy_pipeline(const Option& /*opt*/)
{
delete pipeline_shufflechannel;
pipeline_shufflechannel = 0;
delete pipeline_shufflechannel_pack4;
pipeline_shufflechannel_pack4 = 0;
delete pipeline_shufflechannel_pack8;
pipeline_shufflechannel_pack8 = 0;
return 0;
}
int ShuffleChannel_vulkan::forward(const VkMat& bottom_blob, VkMat& top_blob, VkCompute& cmd, const Option& opt) const
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int channels = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
top_blob.create(w, h, channels, elemsize, elempack, opt.blob_vkallocator, opt.staging_vkallocator);
if (top_blob.empty())
return -100;
std::vector<VkMat> bindings(2);
bindings[0] = bottom_blob;
bindings[1] = top_blob;
std::vector<vk_constant_type> constants(10);
constants[0].i = bottom_blob.dims;
constants[1].i = bottom_blob.w;
constants[2].i = bottom_blob.h;
constants[3].i = bottom_blob.c;
constants[4].i = bottom_blob.cstep;
constants[5].i = top_blob.dims;
constants[6].i = top_blob.w;
constants[7].i = top_blob.h;
constants[8].i = top_blob.c;
constants[9].i = top_blob.cstep;
const Pipeline* pipeline = elempack == 8 ? pipeline_shufflechannel_pack8
: elempack == 4 ? pipeline_shufflechannel_pack4
: pipeline_shufflechannel;
cmd.record_pipeline(pipeline, bindings, constants, top_blob);
return 0;
}
} // namespace ncnn
|
// Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <base/gserrors.h>
#include <psi/iapi.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
static const unsigned char *g_data;
static size_t g_size;
#define min(x, y) ((x) < (y) ? (x) : (y))
static int gs_stdin(void *inst, char *buf, int len)
{
size_t to_copy = min(len, g_size);
to_copy = min(INT_MAX, to_copy);
memcpy(buf, g_data, to_copy);
g_data += to_copy;
g_size -= to_copy;
return to_copy;
}
static int gs_stdout(void *inst, const char *buf, int len)
{
/* Just discard everything. */
return len;
}
static int gs_to_raster_fuzz(const unsigned char *buf, size_t size)
{
int ret;
void *gs = NULL;
/* Mostly stolen from cups-filters gstoraster. */
char *args[] = {
"gs",
"-K1048576",
"-r200x200",
"-dMediaPosition=1",
"-dcupsColorSpace=1", /* RGB */
"-dQUIET",
"-dPARANOIDSAFER",
"-dNOPAUSE",
"-dBATCH",
"-dNOINTERPOLATE",
"-dNOMEDIAATTRS",
"-sstdout=%stderr",
"-sOutputFile=%stdout",
"-sDEVICE=cups",
"-_",
};
int argc = sizeof(args) / sizeof(args[0]);
/* Stash buffers globally, for gs_stdin(). */
g_data = buf;
g_size = size;
ret = gsapi_new_instance(&gs, NULL);
if (ret < 0) {
fprintf(stderr, "gsapi_new_instance: error %d\n", ret);
return ret;
}
gsapi_set_stdio(gs, gs_stdin, gs_stdout, NULL /* stderr */);
ret = gsapi_set_arg_encoding(gs, GS_ARG_ENCODING_UTF8);
if (ret < 0) {
fprintf(stderr, "gsapi_set_arg_encoding: error %d\n", ret);
gsapi_delete_instance(gs);
return ret;
}
ret = gsapi_init_with_args(gs, argc, args);
if (ret && ret != gs_error_Quit)
/* Just keep going, to cleanup. */
fprintf(stderr, "gsapi_init_with_args: error %d\n", ret);
ret = gsapi_exit(gs);
if (ret < 0 && ret != gs_error_Quit) {
fprintf(stderr, "gsapi_exit: error %d\n", ret);
return ret;
}
gsapi_delete_instance(gs);
return 0;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
gs_to_raster_fuzz(data, size);
return 0;
}
|
#include "MSIM_ProgressFeedback.h"
#include <sstream>
#include <iomanip>
#include <IBK_Time.h>
#include <IBK_messages.h>
namespace MASTER_SIM {
void ProgressFeedback::setup(std::ostream * progressLog, double t0, double tEnd, const std::string & interimMessage,
double elapsedSecondsAtStart, double elapsedSimTimeAtStart)
{
m_progressLog = progressLog;
m_progressT0 = t0;
m_progressTEnd = tEnd;
m_interimMessage = interimMessage;
m_notifyTime = 15; // 15 seconds from now
m_elapsedSecondsAtStart = elapsedSecondsAtStart;
m_elapsedSimTimeAtStart = elapsedSimTimeAtStart;
m_lastElapsedSeconds = m_elapsedSecondsAtStart;
m_lastElapsedSimTime = m_elapsedSimTimeAtStart;
m_lastElapsedSecondsWithOutput= m_elapsedSecondsAtStart;
m_ETC = -1;
// set counter to 41, so that next call to writeOutputs()
// will trigger writing of header line
m_outputCounter = 41;
// write header
if (progressLog != NULL && t0 == 0)
*progressLog << std::setw(15) << "Simtime [s] " << '\t' << std::setw(15) << "Realtime [s]" << '\t' << std::setw(15) << "Percentage [%]" << '\n';
m_stopWatch.start();
}
void ProgressFeedback::writeFeedback(double t, bool betweenOutputs) {
const char * const FUNC_ID = "[SolverFeedback::writeFeedback]";
//if (m_abort) throw IBK_exception("Aborting solver...", "[ModelImpl::writeFeedback]");
// calculate statistics
// compute total elapsed simulation time [s]
double elapsedSimTime = t - m_elapsedSimTimeAtStart;
// compute total elapsed real time, including time spend in previous runs when
// solver was continued.
double elapsedSecondsThisStep = 0.001*m_stopWatch.difference();
double elapsedSeconds = elapsedSecondsThisStep + m_elapsedSecondsAtStart; // in [s]
elapsedSecondsThisStep -= m_lastElapsedSecondsWithOutput; // holds now the time since last written output
// the average speed in [s/s]
double averageSpeed;
if (elapsedSeconds > 0)
averageSpeed = elapsedSimTime/elapsedSeconds;
else
averageSpeed = 0;
// add current time point to m_outputTimes
m_outputTimes.push_back( std::make_pair(elapsedSeconds, t) );
// use different real time range for sliding average calculation, based on mean speed
double ave_real_time = 600; // 10 mins as default
// faster than 1d/s
if (averageSpeed > 24*3600) {
ave_real_time = 5; // 5 seconds
}
// faster than 2h/s
else if (averageSpeed > 2*3600) {
ave_real_time = 60; // one minute
}
// calculate sliding average over past 20 mins
int i = m_outputTimes.size();
double delta_t_real = 0;
while (i > 0) {
--i;
delta_t_real = m_outputTimes.back().first - m_outputTimes[i].first;
if (delta_t_real >= ave_real_time) break; // got enough real time to calculate average
}
// compute sliding average of computation speed
double slidingAverageSpeed;
if (delta_t_real == 0) {
slidingAverageSpeed = 0;
}
else {
double delta_t_sim = m_outputTimes.back().second - m_outputTimes[i].second;
slidingAverageSpeed = delta_t_sim/delta_t_real;
}
// compute estimated time of completion
if (slidingAverageSpeed < 1e-5) m_ETC = -1;
else m_ETC = (m_progressTEnd - t)/slidingAverageSpeed;
m_lastElapsedSimTime = t;
m_lastElapsedSeconds = elapsedSeconds;
// write console output
std::stringstream strm;
if (--m_outputCounter % 20 == 0) {
if (!m_outputCounter) m_outputCounter = 40;
if (m_outputCounter == 20)
strm << m_interimMessage << '\n';
else
strm << "Simtime Simdate Realtime MeanSpeed CurrentSpeed ETC\n";
}
strm << std::setw(11) << std::left << IBK::Time::format_time_difference(t) << " "
<< IBK::Time(0, t).toShortDateFormat() << " "
<< std::setw(11) << std::left << IBK::Time::format_time_difference(elapsedSeconds) << " "
<< std::setw(12) << std::left << (IBK::Time::format_time_difference(averageSpeed)+"/s") << " "
<< std::setw(12) << std::left << (IBK::Time::format_time_difference(slidingAverageSpeed)+"/s") << " "
<< ((m_ETC == -1) ? std::string("---") : IBK::Time::format_time_difference(m_ETC))
<< (betweenOutputs ? " *" : "") << "\n";
// write with higher output priority if at least half a second has passed
if (elapsedSecondsThisStep > 0.5) {
IBK_FastMessage(IBK::VL_STANDARD)( strm.str(), IBK::MSG_PROGRESS, FUNC_ID, IBK::VL_STANDARD);
m_lastElapsedSecondsWithOutput = elapsedSeconds;
}
else
IBK_FastMessage(IBK::VL_INFO)( strm.str(), IBK::MSG_PROGRESS, FUNC_ID, IBK::VL_INFO);
// write progress log
if (m_progressLog != NULL && !betweenOutputs && elapsedSimTime != 0) {
*m_progressLog << std::setprecision(14) << std::setw(15) << std::right << t << '\t'
<< std::setprecision(7) << std::setw(15) << std::right << elapsedSeconds << '\t'
<< std::setprecision(2) << std::setw(15) << std::right << t*100/m_progressTEnd << std::endl;
}
m_notifyTime = 0.001*m_stopWatch.difference() + 15; // Notify again in 15 seconds
}
// ---------------------------------------------------------------------------
// This feedback function is triggered from the solver system function calculateDivergences()
void ProgressFeedback::writeFeedbackFromF(double t) {
double elapsedSeconds = m_stopWatch.difference()*0.001; // *0.001 to convert from ms in s
if (elapsedSeconds < m_notifyTime) return;
//if (m_abort) throw IBK_exception("Aborting solver...", "[SolverFeedback::writeFeedbackFromF]");
// set next notification time point
m_notifyTime += 15; // Every 15 seconds
writeFeedback(t, true);
}
// ---------------------------------------------------------------------------
} // namespace MASTER_SIM
|
//++ BulliT
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "player.h"
#include "weapons.h"
#include "gamerules.h"
extern int gmsgTeamInfo;
extern int gmsgSetFOV;
extern int gmsgSplash;
extern int gmsgGamemode;
extern int g_teamplay;
void CBasePlayer::Spectate_Init()
{
m_fSpectateTime = AgTime();
m_iSpot = 0;
m_hSpectateTarget = NULL;
m_iSpectateWeapon = 0;
m_iSpectateAmmoClip = 0;
}
// Spectate code with parts from Robin Walkers Tutorial.
void CBasePlayer::Spectate_Spectate()
{
ASSERT(NULL != pev);
if (!pev)
return;
if (IsSpectator())
Spectate_Stop();
else
Spectate_Start();
}
bool CBasePlayer::Spectate_HLTV()
{
g_pGameRules->m_bProxyConnected = true;
// This is the valve proxy.
if (g_pGameRules->IsTeamplay())
{
strcpy(m_szTeamName, "");
g_engfuncs.pfnSetClientKeyValue(entindex(), g_engfuncs.pfnGetInfoKeyBuffer(edict()), "model", m_szTeamName);
g_engfuncs.pfnSetClientKeyValue(entindex(), g_engfuncs.pfnGetInfoKeyBuffer(edict()), "team", m_szTeamName);
g_pGameRules->RecountTeams();
}
g_pGameRules->UpdateGameMode(this);
g_pGameRules->ResendScoreBoard();
return true;
}
void CBasePlayer::Spectate_Start(bool bResetScore)
{
ASSERT(NULL != pev);
if (!pev)
return;
if (IsSpectator()) // Don't start it if already spectator or if its a player in the arena.
return;
if (IsProxy())
return;
// CTF
if (CTF == AgGametype())
g_pGameRules->m_CTF.PlayerDropFlag(this);
// Reset.
Spectate_Init();
// Set player as spectator.
pev->iuser1 = OBS_ROAMING;
pev->iuser2 = 0;
m_hSpectateTarget = NULL;
// Remove spectators from this player
for (int i = 1; i <= gpGlobals->maxClients; i++)
{
CBasePlayer* pPlayerLoop = AgPlayerByIndex(i);
if (pPlayerLoop && this != pPlayerLoop)
{
if ((CBaseEntity*)pPlayerLoop->m_hSpectateTarget == (CBaseEntity*)this)
{
// Move to next player.
pPlayerLoop->Spectate_Nextplayer(false);
}
}
}
// clear any clientside entities attached to this player
MESSAGE_BEGIN(MSG_PAS, SVC_TEMPENTITY, pev->origin);
WRITE_BYTE(TE_KILLPLAYERATTACHMENTS);
WRITE_BYTE((BYTE)entindex());
MESSAGE_END();
pev->health = 1; // Remove clientside screentilt. If you find this one helpful - give me credit because I spent 3 hours a friday night figuring it out!
EnableControl(TRUE);
if (m_pTank != NULL)
{
m_pTank->Use(this, this, USE_OFF, 0);
m_pTank = NULL;
}
// clear out the suit message cache so we don't keep chattering
SetSuitUpdate(NULL, FALSE, 0);
RemoveAllItemsNoClientMessage();
pev->deadflag = DEAD_DEAD;
pev->flags |= FL_SPECTATOR;
pev->flags |= FL_NOTARGET;
ClearBits(m_afPhysicsFlags, PFLAG_DUCKING);
ClearBits(pev->flags, FL_DUCKING);
SetBits(m_afPhysicsFlags, PFLAG_OBSERVER);
UTIL_SetSize(pev, VEC_HULL_MIN, VEC_HULL_MAX);
pev->fixangle = TRUE;
pev->solid = SOLID_NOT;
pev->takedamage = DAMAGE_NO;
pev->movetype = MOVETYPE_NOCLIP;
pev->effects |= EF_NODRAW;
pev->view_ofs = g_vecZero;
m_hSpectateTarget = NULL;
// clear attack/use commands from player
m_afButtonPressed = 0;
pev->button = 0;
m_afButtonReleased = 0;
m_iHideHUD |= HIDEHUD_WEAPONS | HIDEHUD_FLASHLIGHT | HIDEHUD_HEALTH;
// reset FOV
pev->fov = m_iFOV = m_iClientFOV = 0;
MESSAGE_BEGIN(MSG_ONE, gmsgSetFOV, NULL, pev);
WRITE_BYTE(0);
MESSAGE_END();
MESSAGE_BEGIN(MSG_ALL, gmsgSpectator);
WRITE_BYTE(ENTINDEX(edict()));
WRITE_BYTE(1);
MESSAGE_END();
// Change teamname
if (g_pGameRules->IsTeamplay())
{
MESSAGE_BEGIN(MSG_ALL, gmsgTeamInfo);
WRITE_BYTE(entindex());
WRITE_STRING(TeamID());
MESSAGE_END();
}
// Reset score
if (bResetScore)
ResetScore();
pev->nextthink = gpGlobals->time + 0.1;
// Tell clients
UTIL_ClientPrintAll(HUD_PRINTNOTIFY, UTIL_VarArgs("%s entered spectator mode\n", GetName()));
// Put up splash screen for 10 secs :)
#ifndef AG_NO_CLIENT_DLL
MESSAGE_BEGIN(MSG_ONE_UNRELIABLE, gmsgSplash, NULL, pev);
WRITE_BYTE(10);
MESSAGE_END();
#endif
}
void CBasePlayer::Spectate_Stop(bool bIntermediateSpawn)
{
ASSERT(NULL != pev);
if (!pev)
return;
if (!IsSpectator())
return;
if (IsProxy())
return;
if (!g_pGameRules->FPlayerCanRespawn(this))
return;
EnableControl(TRUE);
// Reset flags.
Spectate_Init();
pev->flags &= ~FL_SPECTATOR;
pev->flags &= ~FL_NOTARGET;
pev->deadflag = DEAD_RESPAWNABLE;
pev->button = 0;
pev->iuser1 = OBS_NONE;
pev->iuser2 = 0;
pev->effects &= ~EF_NODRAW;
pev->movetype = MOVETYPE_WALK;
m_iRespawnFrames = 0;
m_bDoneFirstSpawn = !bIntermediateSpawn;
m_iHideHUD &= ~HIDEHUD_WEAPONS;
m_iHideHUD &= ~HIDEHUD_FLASHLIGHT;
m_iHideHUD &= ~HIDEHUD_HEALTH;
// Reset fov
pev->fov = m_iFOV = m_iClientFOV = 0;
MESSAGE_BEGIN(MSG_ONE, gmsgSetFOV, NULL, pev);
WRITE_BYTE(0);
MESSAGE_END();
// Remove spec
MESSAGE_BEGIN(MSG_ALL, gmsgSpectator);
WRITE_BYTE(ENTINDEX(edict()));
WRITE_BYTE(0);
MESSAGE_END();
// Change teamname
if (g_pGameRules->IsTeamplay())
{
MESSAGE_BEGIN(MSG_ALL, gmsgTeamInfo);
WRITE_BYTE(entindex());
WRITE_STRING(TeamID());
MESSAGE_END();
}
// Force data to be resent.
m_fKnownItem = FALSE; // Force weaponinit messages.
// Tell client(s)
UTIL_ClientPrintAll(HUD_PRINTNOTIFY, UTIL_VarArgs("%s left spectator mode\n", GetName()));
Spawn();
#ifndef AG_NO_CLIENT_DLL
// Remove splash screen
MESSAGE_BEGIN(MSG_ONE, gmsgSplash, NULL, pev);
WRITE_BYTE(0);
MESSAGE_END();
#endif
}
// Find the next client in the game for this player to spectate
void CBasePlayer::Spectate_Nextplayer(bool bReverse)
{
ASSERT(NULL != pev);
if (!pev)
return;
if (IsProxy())
return;
// MOD AUTHORS: Modify the logic of this function if you want to restrict the observer to watching
// only a subset of the players. e.g. Make it check the target's team.
int iStart;
if (m_hSpectateTarget)
iStart = ENTINDEX(m_hSpectateTarget->edict());
else
iStart = ENTINDEX(edict());
int iCurrent = iStart;
m_hSpectateTarget = NULL;
int iDir = bReverse ? -1 : 1;
do
{
iCurrent += iDir;
// Loop through the clients
if (iCurrent > gpGlobals->maxClients)
iCurrent = 1;
if (iCurrent < 1)
iCurrent = gpGlobals->maxClients;
CBaseEntity* pEnt = AgPlayerByIndex(iCurrent);
if (!pEnt)
continue;
if (pEnt == this)
continue;
// Don't spec observers or invisible players
if (((CBasePlayer*)pEnt)->IsSpectator() || (pEnt->pev->effects == EF_NODRAW))
continue;
if (0 < ag_spec_enable_disable.value && ((CBasePlayer*)pEnt)->DisableSpecs())
continue;
m_hSpectateTarget = pEnt;
break;
} while (iCurrent != iStart);
// Did we find a target?
if (m_hSpectateTarget != NULL && m_hSpectateTarget->pev != NULL)
{
// Store the target in pev so the physics DLL can get to it
pev->iuser2 = ENTINDEX(m_hSpectateTarget->edict());
// Move to the target
UTIL_SetOrigin(pev, m_hSpectateTarget->pev->origin);
// ClientPrint(m_hSpectateTarget->pev, HUD_PRINTNOTIFY, UTIL_VarArgs("You are being watched by %s\n",STRING(pev->netname)));
}
else
{
// Go roaming.
Spectate_SetMode(OBS_ROAMING);
}
}
// Handle buttons in spectate mode
void CBasePlayer::Spectate_HandleButtons()
{
ASSERT(NULL != pev);
if (!pev)
return;
if (IsProxy())
return;
// Slow down mouse clicks
if (m_fSpectateTime > AgTime())
return;
pev->impulse = 0;
// Jump changes from modes: Chase to Roaming
if (m_afButtonPressed & IN_JUMP)
{
// Reset fov
pev->fov = m_iFOV = m_iClientFOV = 0;
MESSAGE_BEGIN(MSG_ONE, gmsgSetFOV, NULL, pev);
WRITE_BYTE(0);
MESSAGE_END();
if (pev->iuser1 == OBS_ROAMING)
Spectate_SetMode(OBS_IN_EYE);
else if (pev->iuser1 == OBS_IN_EYE)
Spectate_SetMode(OBS_CHASE_LOCKED);
else if (pev->iuser1 == OBS_CHASE_LOCKED)
Spectate_SetMode(OBS_CHASE_FREE);
else if (pev->iuser1 == OBS_CHASE_FREE)
Spectate_SetMode(OBS_MAP_CHASE);
else if (pev->iuser1 == OBS_MAP_CHASE)
Spectate_SetMode(OBS_MAP_FREE);
else if (pev->iuser1 == OBS_MAP_FREE)
Spectate_SetMode(OBS_ROAMING);
else
Spectate_SetMode(OBS_ROAMING);
}
// Attack moves to the next player
if (m_afButtonPressed & IN_ATTACK)
{
// Reset fov
pev->fov = m_iFOV = m_iClientFOV = 0;
MESSAGE_BEGIN(MSG_ONE, gmsgSetFOV, NULL, pev);
WRITE_BYTE(0);
MESSAGE_END();
if (pev->iuser2 != 0)
Spectate_Nextplayer(false);
else
Spectate_Nextspot(false);
m_fSpectateTime = AgTime() + 0.2;
}
// Attack2 moves to the prev player
if (m_afButtonPressed & IN_ATTACK2)
{
// Reset fov
pev->fov = m_iFOV = m_iClientFOV = 0;
MESSAGE_BEGIN(MSG_ONE, gmsgSetFOV, NULL, pev);
WRITE_BYTE(0);
MESSAGE_END();
if (pev->iuser2 != 0)
Spectate_Nextplayer(true);
else
Spectate_Nextspot(true);
m_fSpectateTime = AgTime() + 0.2;
}
}
void CBasePlayer::Spectate_UpdatePosition()
{
for (int i = 1; i <= gpGlobals->maxClients; i++)
{
CBasePlayer* pPlayerLoop = AgPlayerByIndex(i);
if (pPlayerLoop && this != pPlayerLoop && pPlayerLoop->IsSpectator())
{
if ((CBaseEntity*)pPlayerLoop->m_hSpectateTarget == (CBaseEntity*)this)
{
if (pPlayerLoop->m_hSpectateTarget->pev)
{
// Update the spectators position
// pPlayerLoop->m_hSpectateTarget = (CBaseEntity*)this;
UTIL_SetOrigin(pPlayerLoop->pev, pev->origin);
}
}
}
}
}
// Attempt to change the spectate mode
void CBasePlayer::Spectate_SetMode(int iMode)
{
ASSERT(NULL != pev);
if (!pev)
return;
if (IsProxy() || !IsSpectator())
return;
// Just abort if we're changing to the mode we're already in
if (iMode == pev->iuser1)
return;
// Changing to Roaming or Map Free?
if (iMode == OBS_ROAMING || iMode == OBS_MAP_FREE)
{
// MOD AUTHORS: If you don't want to allow roaming observers at all in your mod, just abort here.
pev->iuser1 = iMode;
pev->iuser2 = 0;
m_hSpectateTarget = NULL;
pev->weapons &= ~WEAPON_ALLWEAPONS;
m_iHideHUD |= HIDEHUD_WEAPONS | HIDEHUD_FLASHLIGHT | HIDEHUD_HEALTH;
return;
}
// Changing to Chase Lock, Chase Freelook, Map Chase?
if (iMode == OBS_CHASE_FREE || iMode == OBS_MAP_CHASE || iMode == OBS_CHASE_LOCKED)
{
// If changing from Roaming, or starting observing, make sure there is a target
if (m_hSpectateTarget == NULL)
Spectate_Nextplayer(false);
if (m_hSpectateTarget)
{
pev->iuser1 = iMode;
pev->iuser2 = ENTINDEX(m_hSpectateTarget->edict());
pev->maxspeed = 0;
pev->weapons |= (1 << WEAPON_SUIT);
m_iHideHUD |= HIDEHUD_WEAPONS;
m_iHideHUD |= HIDEHUD_FLASHLIGHT;
m_iHideHUD &= ~HIDEHUD_HEALTH;
}
else
{
Spectate_SetMode(OBS_ROAMING);
}
return;
}
// Changing to in-eye?
if (iMode == OBS_IN_EYE)
{
// If changing from Roaming, or starting observing, make sure there is a target
if (m_hSpectateTarget == NULL)
Spectate_Nextplayer(false);
if (m_hSpectateTarget)
{
pev->iuser1 = iMode;
pev->iuser2 = ENTINDEX(m_hSpectateTarget->edict());
pev->maxspeed = 0;
pev->weapons |= (1 << WEAPON_SUIT);
m_iHideHUD &= ~HIDEHUD_WEAPONS;
m_iHideHUD |= HIDEHUD_FLASHLIGHT;
m_iHideHUD &= ~HIDEHUD_HEALTH;
}
else
{
Spectate_SetMode(OBS_ROAMING);
}
return;
}
}
bool CBasePlayer::Spectate_Think()
{
ASSERT(NULL != pev);
if (!pev)
return false;
if (IsProxy())
return false;
if (IsSpectator())
{
Spectate_HandleButtons();
return true;
}
return false;
}
// Find the next info intermission spot
void CBasePlayer::Spectate_Nextspot(bool bReverse)
{
ASSERT(NULL != pev);
if (!pev || !g_pGameRules)
return;
if (IsProxy())
return;
m_iSpot += bReverse ? -1 : 1;
// Check if out of bounds.
if (0 > m_iSpot)
m_iSpot = g_pGameRules->m_InfoInterMission.GetCount() - 1;
else if (m_iSpot >= g_pGameRules->m_InfoInterMission.GetCount())
m_iSpot = 0;
// Move the dude
edict_t* pSpot = g_pGameRules->m_InfoInterMission.GetSpot(m_iSpot);
if (pSpot)
MoveToInfoIntermission(pSpot);
}
bool CBasePlayer::Spectate_Follow(EHANDLE& pPlayer, int iMode)
{
if (IsProxy())
return true;
m_hSpectateTarget = pPlayer;
Spectate_SetMode(iMode);
return true;
}
//-- Martin Webrant
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__int_fscanf_multiply_82_goodG2B.cpp
Label Definition File: CWE191_Integer_Underflow__int.label.xml
Template File: sources-sinks-82_goodG2B.tmpl.cpp
*/
/*
* @description
* CWE: 191 Integer Underflow
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Set data to a small, non-zero number (negative two)
* Sinks: multiply
* GoodSink: Ensure there will not be an underflow before multiplying data by 2
* BadSink : If data is negative, multiply by 2, which can cause an underflow
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE191_Integer_Underflow__int_fscanf_multiply_82.h"
namespace CWE191_Integer_Underflow__int_fscanf_multiply_82
{
void CWE191_Integer_Underflow__int_fscanf_multiply_82_goodG2B::action(int data)
{
if(data < 0) /* ensure we won't have an overflow */
{
/* POTENTIAL FLAW: if (data * 2) < INT_MIN, this will underflow */
int result = data * 2;
printIntLine(result);
}
}
}
#endif /* OMITGOOD */
|
/* Copyright 2020 The TensorFlow 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 <cstdint>
#include <memory>
#include "flatbuffers/flexbuffers.h" // from @flatbuffers
#include "tensorflow/core/util/ragged_to_dense_util_common.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/context.h"
#include "tensorflow/lite/kernels/internal/tensor.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/internal/types.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/model.h"
namespace tflite {
namespace ops {
namespace custom {
namespace ragged {
namespace ragged_tensor_to_tensor {
namespace {
constexpr int kShapeInput = 0;
constexpr int kValuesInput = 1;
constexpr int kDefaultValueInput = 2;
constexpr int kFirstPartitionInputIndex = 3;
constexpr int kOutputTensor = 0;
constexpr char kRowPartitionTypesAttr[] = "row_partition_types";
struct ConversionAttributes {
std::vector<tensorflow::RowPartitionType> partition_types;
int ragged_rank = 0;
tensorflow::RowPartitionType GetRowPartitionTypeByDimension(
int dimension) const {
if (partition_types.front() ==
tensorflow::RowPartitionType::FIRST_DIM_SIZE) {
return partition_types[dimension + 1];
} else {
return partition_types[dimension];
}
}
};
template <typename INDEX_TYPE>
int GetFirstDimensionSizeT(TfLiteContext* context,
const TfLiteTensor& first_partition_input,
const ConversionAttributes* attributes) {
const tensorflow::RowPartitionType first_partition_type =
attributes->partition_types.front();
switch (first_partition_type) {
case tensorflow::RowPartitionType::FIRST_DIM_SIZE:
return *GetTensorData<INDEX_TYPE>(&first_partition_input);
case tensorflow::RowPartitionType::VALUE_ROWIDS:
context->ReportError(context,
"Cannot handle VALUE_ROWIDS in first dimension.");
return -1;
case tensorflow::RowPartitionType::ROW_SPLITS: {
const auto shape = GetTensorShape(&first_partition_input);
return shape.Dims(0) - 1;
}
default:
context->ReportError(
context, "Cannot handle type ",
RowPartitionTypeToString(first_partition_type).c_str());
return -1;
}
}
int GetFirstDimensionSize(TfLiteContext* context,
const TfLiteTensor& first_partition_input,
const ConversionAttributes* attributes) {
switch (first_partition_input.type) {
case kTfLiteInt32:
return GetFirstDimensionSizeT<int32_t>(context, first_partition_input,
attributes);
case kTfLiteInt64:
return GetFirstDimensionSizeT<int64_t>(context, first_partition_input,
attributes);
default:
context->ReportError(context,
"Not supported row partitioning tensor type");
return -1;
}
}
bool ValidateDefaultValueShape(TfLiteContext* context,
const RuntimeShape& default_value_shape,
const RuntimeShape& /*value_shape*/) {
// TF implementation also checks that shapes are not defined, not needed in
// TFLite.
// TODO(mgubin): Only scalar default value sizes are supported.
if (default_value_shape.FlatSize() != 1) {
context->ReportError(context, "Only scalar default value is supported");
return false;
}
return true;
}
RuntimeShape TensorShapeFromTensor(const TfLiteTensor& tensor) {
// TODO(mgubin): No checks, see
// third_party/tensorflow/core/kernels/list_kernels.cc
const RuntimeShape tensor_shape(tensor.dims->size, tensor.dims->data);
if (0 == tensor.dims->size) {
// If the input tensor is scalar then the shape is empty (also scalar).
return RuntimeShape{};
}
RuntimeShape result(tensor_shape.FlatSize());
switch (tensor.type) {
case kTfLiteInt32: {
for (int i = 0; i < tensor_shape.FlatSize(); ++i) {
result.SetDim(i, GetTensorData<int32_t>(&tensor)[i]);
}
} break;
case kTfLiteInt64: {
for (int i = 0; i < tensor_shape.FlatSize(); ++i) {
result.SetDim(i, GetTensorData<int64_t>(&tensor)[i]);
}
} break;
default: {
// Checked in Prepare.
}
}
return result;
}
const TfLiteTensor* GetRowPartitionTensor(
const ConversionAttributes& conversion_attributes,
TfLiteContext* context,
TfLiteNode* node,
int dimension) {
if (conversion_attributes.partition_types.front() ==
tensorflow::RowPartitionType::FIRST_DIM_SIZE) {
return &context->tensors[node->inputs->data[kFirstPartitionInputIndex + 1 +
dimension]];
} else {
return &context->tensors[node->inputs
->data[kFirstPartitionInputIndex + dimension]];
}
}
int GetMaxWidthValueRowID(const TfLiteTensor* tensor) {
const RuntimeShape tensor_shape(tensor->dims->size, tensor->dims->data);
const int index_length = tensor_shape.FlatSize();
if (index_length == 0) {
return 0;
}
auto value_rowids = [tensor](int index) {
switch (tensor->type) {
case kTfLiteInt32:
return static_cast<int>(tensor->data.i32[index]);
case kTfLiteInt64:
return static_cast<int>(tensor->data.i64[index]);
default:
// TODO(mgubin): Add error checks.
return 0;
}
};
int first_equal_index = 0;
int first_equal_index_value = value_rowids(0);
int max_width = 0;
for (int i = 0; i < index_length; ++i) {
const int value = value_rowids(i);
if (value != first_equal_index_value) {
first_equal_index_value = value;
max_width = std::max(i - first_equal_index, max_width);
first_equal_index = i;
}
}
return std::max(index_length - first_equal_index, max_width);
}
int GetMaxWidthRowSplit(const TfLiteTensor* tensor) {
const RuntimeShape tensor_shape(tensor->dims->size, tensor->dims->data);
const int tensor_length = tensor_shape.FlatSize();
if (tensor_length == 0 || tensor_length == 1) {
return 0;
}
auto value_rowsplit = [tensor](int index) {
switch (tensor->type) {
case kTfLiteInt32:
return static_cast<int>(tensor->data.i32[index]);
case kTfLiteInt64:
return static_cast<int>(tensor->data.i64[index]);
default:
// TODO(mgubin): Add error checks.
return 0;
}
};
int max_width = 1;
int prev_split = value_rowsplit(0);
for (int i = 1; i < tensor_length; ++i) {
const int split = value_rowsplit(i);
max_width = std::max(max_width, split - prev_split);
prev_split = split;
}
return max_width;
}
int GetMaxWidth(const ConversionAttributes& conversion_attributes,
TfLiteContext* context,
TfLiteNode* node,
int dimension) {
const TfLiteTensor* tensor = GetRowPartitionTensor(
conversion_attributes, context, node, dimension - 1);
switch (conversion_attributes.GetRowPartitionTypeByDimension(dimension - 1)) {
case tensorflow::RowPartitionType::VALUE_ROWIDS:
return GetMaxWidthValueRowID(tensor);
case tensorflow::RowPartitionType::ROW_SPLITS:
return GetMaxWidthRowSplit(tensor);
default:
context->ReportError(context, "Cannot handle partition type");
return -1;
}
}
RuntimeShape CombineRaggedTensorToTensorShapes(
int ragged_rank,
const RuntimeShape& output_shape,
const RuntimeShape& value_shape) {
// TODO(mgubin): No checks, see
// third_party/tensorflow/core/ops/ragged_to_dense_util.cc
RuntimeShape result(output_shape);
if (output_shape.DimensionsCount() == 0) {
const int output_shape_rank = ragged_rank + value_shape.DimensionsCount();
result.Resize(output_shape_rank);
for (int i = 0; i < output_shape_rank; ++i) {
result.SetDim(i, -1);
}
}
const int need_to_set =
output_shape.DimensionsCount() - value_shape.DimensionsCount();
for (int i = 1; i < value_shape.DimensionsCount(); ++i) {
result.SetDim(need_to_set + i, value_shape.Dims(i));
}
return result;
}
RuntimeShape CalculateOutputSize(
const ConversionAttributes& conversion_attributes,
TfLiteContext* context,
TfLiteNode* node,
int first_dimension,
int ragged_rank,
const TfLiteTensor& values,
const TfLiteTensor& default_value,
const TfLiteTensor& output_shape) {
RuntimeShape values_shape(values.dims->size, values.dims->data);
RuntimeShape default_value_shape(default_value.dims->size,
default_value.dims->data);
if (!ValidateDefaultValueShape(context, default_value_shape, values_shape)) {
return {};
}
RuntimeShape output_shape_shape = TensorShapeFromTensor(output_shape);
RuntimeShape result_shape = CombineRaggedTensorToTensorShapes(
ragged_rank, output_shape_shape, values_shape);
if (result_shape.Dims(0) < 0) {
result_shape.SetDim(0, first_dimension);
}
for (int i = 1; i <= ragged_rank; ++i) {
if (result_shape.Dims(i) < 0) {
result_shape.SetDim(i,
GetMaxWidth(conversion_attributes, context, node, i));
}
}
return result_shape;
}
TfLiteIntArray* IntArrayFromShape(const RuntimeShape& shape) {
TfLiteIntArray* result = TfLiteIntArrayCreate(shape.DimensionsCount());
for (int i = 0; i < shape.DimensionsCount(); ++i) {
result->data[i] = shape.Dims(i);
}
return result;
}
/**
* The output_index represents the index in the output tensor
* where the first element of a particular dimension would be written.
* If it is -1, it indicates that the index is out of scope.
* Example, given first_dimension = 10, first_dimension_output = 6,
* and output_index_multiplier = 100:
* result = [0 100 200 300 400 500 -1 -1 -1 -1]
* If first_dimension_output = 11 instead, then:
* result = [0 100 200 300 400 500 600 700 800 900]
*/
void CalculateFirstParentOutputIndex(int first_dimension,
int output_index_multiplier,
int first_dimension_output,
std::vector<int>* result) {
const int min_dimension = std::min(first_dimension, first_dimension_output);
result->reserve(first_dimension);
int current_output_index = 0;
for (int i = 0; i < min_dimension;
++i, current_output_index += output_index_multiplier) {
result->push_back(current_output_index);
}
for (int i = min_dimension; i < first_dimension; ++i) {
result->push_back(-1);
}
}
// Calculate the output index of the first element of a list.
// The parent_output_index is the same computation for the previous list.
// -1 indicates an element or list that is out of range.
// The output_index_multiplier is the number of output indices one moves
// forward for each column.
// E.g., given:
// value_rowids:[0 1 2 2 2 3 5 5 6]
// parent_output_index:[1000 1100 2000 2100 -1 3000 4000]
// output_index_multiplier: 10
// output_size: 2
// You get:
// result = [1000 1100 2000 2010 -1 2100 -1 -1 3000]
// result[0] = parent_output_index[value_rowids[0]]
// result[1] = parent_output_index[value_rowids[1]]
// result[2] = parent_output_index[value_rowids[2]]
// result[3] = parent_output_index[value_rowids[2] + 10]
// result[4] = -1 because it is the third element the size is 2.
// result[5] = parent_output_index[value_rowids[3]]
// result[6] = -1 because parent_output_index[value_rowids[6]] == -1
// result[7] = -1 because parent_output_index[value_rowids[6]] == -1
// result[8] = parent_output_index[value_rowids[7]]
void CalculateOutputIndexValueRowID(const TfLiteTensor& value_rowids,
const std::vector<int>& parent_output_index,
int output_index_multiplier,
int output_size,
std::vector<int>* result) {
const RuntimeShape tensor_shape(value_rowids.dims->size,
value_rowids.dims->data);
const int index_size = tensor_shape.FlatSize();
result->reserve(index_size);
if (index_size == 0) {
return;
}
auto value_rowids_val = [value_rowids](int index) {
switch (value_rowids.type) {
case kTfLiteInt32:
return static_cast<int>(value_rowids.data.i32[index]);
case kTfLiteInt64:
return static_cast<int>(value_rowids.data.i64[index]);
default:
// TODO(mgubin): Add error checks.
return 0;
}
};
int current_output_column = 0;
int current_value_rowid = value_rowids_val(0);
// DCHECK_LT(current_value_rowid, parent_output_index.size());
int current_output_index = parent_output_index[current_value_rowid];
result->push_back(current_output_index);
for (int i = 1; i < index_size; ++i) {
int next_value_rowid = value_rowids_val(i);
if (next_value_rowid == current_value_rowid) {
if (current_output_index >= 0) {
++current_output_column;
if (current_output_column < output_size) {
current_output_index += output_index_multiplier;
} else {
current_output_index = -1;
}
}
} else {
current_output_column = 0;
current_value_rowid = next_value_rowid;
// DCHECK_LT(next_value_rowid, parent_output_index.size());
current_output_index = parent_output_index[next_value_rowid];
}
result->push_back(current_output_index);
}
// DCHECK_EQ(result->size(), value_rowids.size());
}
void CalculateOutputIndexRowSplit(const TfLiteTensor& row_split,
const std::vector<int>& parent_output_index,
int output_index_multiplier,
int output_size,
std::vector<int>* result) {
const RuntimeShape row_split_shape(row_split.dims->size,
row_split.dims->data);
const int row_split_size = row_split_shape.FlatSize();
auto row_split_val = [row_split](int index) {
switch (row_split.type) {
case kTfLiteInt32:
return static_cast<int>(row_split.data.i32[index]);
case kTfLiteInt64:
return static_cast<int>(row_split.data.i64[index]);
default:
// TODO(mgubin): Add error checks.
return 0;
}
};
if (row_split_size > 0) {
result->reserve(row_split_val(row_split_size - 1));
}
for (int i = 0; i < row_split_size - 1; ++i) {
const int row_length = row_split_val(i + 1) - row_split_val(i);
int real_length = std::min(output_size, row_length);
int parent_output_index_current = parent_output_index[i];
if (parent_output_index_current == -1) {
real_length = 0;
}
for (int j = 0; j < real_length; ++j) {
result->push_back(parent_output_index_current);
parent_output_index_current += output_index_multiplier;
}
for (int j = 0; j < row_length - real_length; ++j) {
result->push_back(-1);
}
}
// if (row_split_size > 0) {
// DCHECK_EQ(result->size(), row_split(row_split_size - 1));
//}
}
TfLiteStatus CalculateOutputIndex(
const ConversionAttributes& conversion_attributes,
TfLiteContext* context,
TfLiteNode* node,
int dimension,
const std::vector<int>& parent_output_index,
int output_index_multiplier,
int output_size,
std::vector<int>* result) {
const TfLiteTensor* row_partition_tensor =
GetRowPartitionTensor(conversion_attributes, context, node, dimension);
auto partition_type =
conversion_attributes.GetRowPartitionTypeByDimension(dimension);
switch (partition_type) {
case tensorflow::RowPartitionType::VALUE_ROWIDS:
CalculateOutputIndexValueRowID(*row_partition_tensor, parent_output_index,
output_index_multiplier, output_size,
result);
return kTfLiteOk;
case tensorflow::RowPartitionType::ROW_SPLITS:
CalculateOutputIndexRowSplit(*row_partition_tensor, parent_output_index,
output_index_multiplier, output_size,
result);
return kTfLiteOk;
default:
context->ReportError(context, "Unsupported partition type");
return kTfLiteError;
}
}
template <typename VALUE_TYPE>
void SetOutputT(TfLiteContext* context,
int ragged_rank,
const std::vector<int>& output_index,
const TfLiteTensor& values_tensor,
const TfLiteTensor& default_value_tensor,
TfLiteTensor* output_tensor) {
const VALUE_TYPE* values_base = GetTensorData<VALUE_TYPE>(&values_tensor);
VALUE_TYPE* output_base = GetTensorData<VALUE_TYPE>(output_tensor);
const VALUE_TYPE* default_value =
GetTensorData<VALUE_TYPE>(&default_value_tensor);
RuntimeShape output_shape = GetTensorShape(output_tensor);
RuntimeShape element_shape =
RuntimeShape(output_shape.DimensionsCount() - ragged_rank - 1,
output_shape.DimsData() + ragged_rank + 1);
// element_shape.RemoveDimRange(0, ragged_rank + 1);
const int value_element_size = element_shape.FlatSize();
size_t output_index_size = output_index.size();
// Loop through the output_index vector, finding contiguous regions that
// should be copied. Once we find the end of a contiguous region, copy it
// and add any necessary padding (with default_value).
int src_start = 0; // Start of contiguous region (in values)
int dst_start = 0; // Destination for contiguous region (in output)
int dst_end = 0; // Destination for contiguous region (in output)
for (int src_i = 0; src_i <= output_index_size; ++src_i) {
// dst_i is the destination where the value at src_i should be copied.
int dst_i = src_i < output_index_size ? output_index[src_i] : -1;
// If we're still in a contiguous region, then update dst_end go to the
// next src_i.
if (dst_i == dst_end) {
++dst_end;
continue;
}
// We found the end of contiguous region. This can be because we found
// a gap (dst_i > dst_end), or a source value that shouldn't be copied
// because it's out-of-bounds (dst_i == -1), or the end of the tensor
// (dst_i = -1).
if (dst_start < dst_end) {
// Copy the contiguous region.
const VALUE_TYPE* src = values_base + src_start * value_element_size;
VALUE_TYPE* dst = output_base + dst_start * value_element_size;
int nvals = (dst_end - dst_start) * value_element_size;
std::copy(src, src + nvals, dst);
// copy_array<VALUE_TYPE, int>(dst, src, nvals);
}
// Add any necessary padding (w/ default_value).
if (src_i >= output_index_size) {
// We reached the end of values: pad to the end of output.
const int output_size = output_shape.FlatSize();
dst_i = output_size / value_element_size;
}
if (dst_i > dst_end) {
std::fill(output_base + dst_end * value_element_size,
output_base + dst_i * value_element_size, *default_value);
dst_end = dst_i;
}
// Update indices.
if (dst_i < 0) {
// src_i should be skipped -- leave it out of the contiguous region.
src_start = src_i + 1;
dst_start = dst_end;
} else {
// src_i should be copied -- include it in the contiguous region.
src_start = src_i;
dst_start = dst_end;
dst_end = dst_start + 1;
}
}
}
void SetOutput(TfLiteContext* context,
int ragged_rank,
const std::vector<int>& output_index,
const TfLiteTensor& values_tensor,
const TfLiteTensor& default_value_tensor,
TfLiteTensor* output_tensor) {
switch (output_tensor->type) {
case kTfLiteInt32:
SetOutputT<int32_t>(context, ragged_rank, output_index, values_tensor,
default_value_tensor, output_tensor);
break;
case kTfLiteInt64:
SetOutputT<int64_t>(context, ragged_rank, output_index, values_tensor,
default_value_tensor, output_tensor);
break;
case kTfLiteFloat32:
SetOutputT<float>(context, ragged_rank, output_index, values_tensor,
default_value_tensor, output_tensor);
break;
default:
context->ReportError(context, "Not supported values type");
}
}
} // namespace
void* Initialize(TfLiteContext* context, const char* buffer, size_t length) {
auto attributes = std::make_unique<ConversionAttributes>();
const uint8_t* buffer_t = reinterpret_cast<const uint8_t*>(buffer);
const flexbuffers::Map& m = flexbuffers::GetRoot(buffer_t, length).AsMap();
// TODO (mgubin): Converting flat buffer to a vector of strings looks not very
// effective but simple. A cleaner way is needed.
const flexbuffers::TypedVector row_partition_types_attr =
m[kRowPartitionTypesAttr].AsTypedVector();
std::vector<std::string> row_partition_types_attr_strings;
row_partition_types_attr_strings.reserve(row_partition_types_attr.size());
for (int i = 0; i < row_partition_types_attr.size(); ++i) {
row_partition_types_attr_strings.emplace_back(
row_partition_types_attr[i].AsString().str());
}
attributes->partition_types =
tensorflow::GetRowPartitionTypesHelper(row_partition_types_attr_strings);
if (attributes->partition_types.size() !=
row_partition_types_attr_strings.size()) {
context->ReportError(context, "Can't parse partition type attribute");
return nullptr;
}
attributes->ragged_rank =
tensorflow::GetRaggedRank(attributes->partition_types);
return attributes.release();
}
void Free(TfLiteContext* /*context*/, void* buffer) {
ConversionAttributes* attributes =
reinterpret_cast<ConversionAttributes*>(buffer);
delete attributes;
}
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
const ConversionAttributes* attributes =
reinterpret_cast<ConversionAttributes*>(node->user_data);
if (attributes == nullptr) {
// Parsing attributes failed, can't prepare.
context->ReportError(context, "Attributes are not initialized");
return kTfLiteError;
}
// The output tensor need to be set to dynamic because it can have different
// size.
TfLiteTensor& output_tensor =
context->tensors[node->outputs->data[kOutputTensor]];
SetTensorToDynamic(&output_tensor);
// Check that input shape tensor is int32 or int64
TfLiteTensor& input_shape = context->tensors[node->inputs->data[kShapeInput]];
if (input_shape.type != kTfLiteInt32 && input_shape.type != kTfLiteInt64) {
context->ReportError(context,
"Input form tensor could be only int32 or int64");
return kTfLiteError;
}
return kTfLiteOk;
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const ConversionAttributes* attributes =
reinterpret_cast<ConversionAttributes*>(node->user_data);
TfLiteTensor& input_shape = context->tensors[node->inputs->data[kShapeInput]];
TfLiteTensor& input_values =
context->tensors[node->inputs->data[kValuesInput]];
TfLiteTensor& default_value =
context->tensors[node->inputs->data[kDefaultValueInput]];
// TODO (mgubin): Only scallar default value is supported.
if (RuntimeShape(default_value.dims->size, default_value.dims->data)
.FlatSize() != 1) {
context->ReportError(context, "Only scallar default value is supported");
return kTfLiteError;
}
TfLiteTensor& first_partition_input =
context->tensors[node->inputs->data[kFirstPartitionInputIndex]];
// Calculate dimensions.
const int first_dimension =
GetFirstDimensionSize(context, first_partition_input, attributes);
if (first_dimension < 0) {
return kTfLiteError;
}
RuntimeShape output_shape = CalculateOutputSize(
*attributes, context, node, first_dimension, attributes->ragged_rank,
input_values, default_value, input_shape);
if (output_shape.DimensionsCount() == 0) {
return kTfLiteError;
}
std::vector<int> multiplier;
multiplier.resize(attributes->ragged_rank + 1);
multiplier.back() = 1;
for (int i = multiplier.size() - 2; i >= 0; --i) {
multiplier[i] = multiplier[i + 1] * output_shape.Dims(i + 1);
}
// Allocate output tensor.
TfLiteTensor& output_tensor =
context->tensors[node->outputs->data[kOutputTensor]];
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, &output_tensor,
IntArrayFromShape(output_shape)));
// Copy data.
const int full_size = multiplier.front() * output_shape.Dims(0);
if (full_size > 0) {
std::vector<int> output_index, new_output_index;
int nvals = input_values.dims->data[0];
output_index.reserve(nvals);
new_output_index.reserve(nvals);
CalculateFirstParentOutputIndex(first_dimension, multiplier[0],
output_shape.Dims(0), &output_index);
for (int i = 1; i <= attributes->ragged_rank; ++i) {
TF_LITE_ENSURE_OK(
context, CalculateOutputIndex(
*attributes, context, node, i - 1, output_index,
multiplier[i], output_shape.Dims(i), &new_output_index));
output_index.swap(new_output_index);
new_output_index.clear();
}
SetOutput(context, attributes->ragged_rank, output_index, input_values,
default_value, &output_tensor);
}
return kTfLiteOk;
}
} // namespace ragged_tensor_to_tensor
} // namespace ragged
TfLiteRegistration* Register_RAGGED_TENSOR_TO_TENSOR() {
static TfLiteRegistration r = {ragged::ragged_tensor_to_tensor::Initialize,
ragged::ragged_tensor_to_tensor::Free,
ragged::ragged_tensor_to_tensor::Prepare,
ragged::ragged_tensor_to_tensor::Eval};
return &r;
}
} // namespace custom
} // namespace ops
} // namespace tflite
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s, r;
cin >> s;
for (char c : s)
{
if (c >= 'A' && c <= 'Z')
{
c += 'a' - 'A';
}
if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u' && c != 'y')
{
r.append(1, '.');
r.append(1, c);
}
}
cout << r << endl;
return 0;
}
|
/* Copyright 2007-2015 QReal Research Group
*
* 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 "realRobotModel.h"
#include <qrkernel/settingsManager.h>
#include "parts/display.h"
#include "parts/speaker.h"
#include "parts/button.h"
#include "parts/motor.h"
#include "parts/led.h"
#include "parts/encoderSensor.h"
#include "parts/touchSensor.h"
#include "parts/lightSensor.h"
#include "parts/rangeSensor.h"
#include "parts/colorSensorFull.h"
#include "parts/colorSensorRed.h"
#include "parts/colorSensorGreen.h"
#include "parts/colorSensorBlue.h"
#include "parts/colorSensorPassive.h"
using namespace ev3::robotModel::real;
using namespace utils::robotCommunication;
using namespace kitBase::robotModel;
RealRobotModel::RealRobotModel(const QString &kitId, const QString &robotId
, utils::robotCommunication::RobotCommunicationThreadInterface *communicationThread)
: Ev3RobotModelBase(kitId, robotId)
, mRobotCommunicator(new RobotCommunicator(this))
{
connect(mRobotCommunicator, &RobotCommunicator::connected, this, &RealRobotModel::connected);
connect(mRobotCommunicator, &RobotCommunicator::disconnected, this, &RealRobotModel::disconnected);
connect(mRobotCommunicator, &RobotCommunicator::errorOccured, this, &RealRobotModel::errorOccured);
mRobotCommunicator->setRobotCommunicationThreadObject(communicationThread);
}
bool RealRobotModel::needsConnection() const
{
return true;
}
void RealRobotModel::connectToRobot()
{
mRobotCommunicator->connect();
}
void RealRobotModel::disconnectFromRobot()
{
mRobotCommunicator->disconnect();
}
void RealRobotModel::checkConnection()
{
mRobotCommunicator->checkConsistency();
}
robotParts::Device *RealRobotModel::createDevice(const PortInfo &port, const DeviceInfo &deviceInfo)
{
if (deviceInfo.isA(speakerInfo())) {
return new parts::Speaker(speakerInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(buttonInfo())) {
return new parts::Button(buttonInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(displayInfo())) {
return new parts::Display(displayInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(motorInfo())) {
return new parts::Motor(motorInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(ledInfo())) {
return new parts::Led(ledInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(encoderInfo())) {
return new parts::EncoderSensor(encoderInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(touchSensorInfo())) {
return new parts::TouchSensor(touchSensorInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(lightSensorInfo())) {
return new parts::LightSensor(lightSensorInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(rangeSensorInfo())) {
return new parts::RangeSensor(rangeSensorInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(colorFullSensorInfo())) {
return new parts::ColorSensorFull(colorFullSensorInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(colorRedSensorInfo())) {
return new parts::ColorSensorRed(colorRedSensorInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(colorGreenSensorInfo())) {
return new parts::ColorSensorGreen(colorGreenSensorInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(colorBlueSensorInfo())) {
return new parts::ColorSensorBlue(colorBlueSensorInfo(), port, *mRobotCommunicator);
}
if (deviceInfo.isA(colorPassiveSensorInfo())) {
return new parts::ColorSensorPassive(colorPassiveSensorInfo(), port, *mRobotCommunicator);
}
return Ev3RobotModelBase::createDevice(port, deviceInfo);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.