hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c1de42b193b07ba46488b2075ec244f652ae78c9 | 15,892 | cc | C++ | execution/run_sample_eval.cc | maksgepner/CodeContests | 3350e202a96314b598c58cdbae1a9a08387d9163 | [
"Apache-2.0"
] | null | null | null | execution/run_sample_eval.cc | maksgepner/CodeContests | 3350e202a96314b598c58cdbae1a9a08387d9163 | [
"Apache-2.0"
] | null | null | null | execution/run_sample_eval.cc | maksgepner/CodeContests | 3350e202a96314b598c58cdbae1a9a08387d9163 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// A simple utility that prints the names of the problems in a dataset. If
// provided multiple filenames as arguments, these are read sequentially.
#include <fcntl.h>
#include <functional>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
#include <sstream>
#include <filesystem>
#include <algorithm>
#include <random>
#include <iterator>
#include "absl/flags/parse.h"
#include "absl/flags/flag.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "contest_problem.pb.h"
#include "execution/py_locations.h"
#include "execution/py_tester_sandboxer.h"
#include "execution/status_macros.h"
#include "execution/tester_sandboxer.h"
#include "riegeli/bytes/fd_reader.h"
#include "riegeli/records/record_reader.h"
// For .json processing
#include "nlohmann/json.hpp"
#include <fstream>
using json = nlohmann::json;
ABSL_FLAG(std::string, test_path, "", "Path to test dataset.");
ABSL_FLAG(std::string, output_dir, "", "Where the .json with results should be saved.");
namespace deepmind::code_contests {
namespace {
int cnt_crashed_tests;
int cnt_passed_tests;
int cnt_failed_tests;
// Option for debugging
bool debug = false;
bool fast_run = false;
json results;
// json single_problem_results;
json all_problem_samples;
json test_results;
json solutions;
std::string soln_lang;
int num_public_tests;
int cnt_passed_public_tests;
int number_passed_problems = 0;
int number_passed_ten_at_k_problems = 0;
int number_evaluated_problems = 0;
absl::StatusOr<ContestProblem> FindProblem(
const absl::string_view filename, std::string target_problem_name) {
riegeli::RecordReader<riegeli::FdReader<>> reader(
std::forward_as_tuple(filename));
ContestProblem problem;
while (reader.ReadRecord(problem)) {
if (problem.name() == target_problem_name) return problem;
}
std::cout << "Problem " << target_problem_name;
return absl::NotFoundError(
" not found inside of the test dataset");
}
std::vector<absl::string_view> GetInputs(const ContestProblem& problem,
int max_size) {
std::vector<absl::string_view> inputs;
for (const auto& test : problem.public_tests()) {
inputs.push_back(test.input());
}
// Used to find which solutions passed all public tests (for 10@k clustering)
num_public_tests = inputs.size();
// std::cout << "\nThe number of public_tests is: " << inputs.size() << "\n";
for (const auto& test : problem.private_tests()) {
inputs.push_back(test.input());
}
for (const auto& test : problem.generated_tests()) {
inputs.push_back(test.input());
}
if (fast_run == true) {
inputs.resize(max_size);
}
// inputs.resize(max_size);
return inputs;
}
std::vector<absl::string_view> GetOutputs(const ContestProblem& problem,
int max_size) {
std::vector<absl::string_view> outputs;
for (const auto& test : problem.public_tests()) {
outputs.push_back(test.output());
}
for (const auto& test : problem.private_tests()) {
outputs.push_back(test.output());
}
for (const auto& test : problem.generated_tests()) {
outputs.push_back(test.output());
}
if (fast_run == true) {
outputs.resize(max_size);
}
// outputs.resize(max_size);
return outputs;
}
void ReportResults(const MultiTestResult& multi_result) {
if (debug==true) {
std::cout << "Compilation "
<< (multi_result.compilation_result.program_status ==
ProgramStatus::kSuccess
? "succeeded"
: "failed")
<< "\nThe compilation stdout output was:\n"
<< (multi_result.compilation_result.stdout)
<< "\nThe compilation stderr output was:\n"
<< (multi_result.compilation_result.stderr)
// << "\nThe runtime output was:\n"
// << (multi_result.test_results)
// << "\nThe runtime stderr output was:\n"
// << (multi_result.test_results.stderr)
<< "\n";
int index = 0;
for (const ExecutionResult& result : multi_result.test_results) {
std::cout << " Test Result " << index++ << ":\n";
std::cout << result << "\n\n";
}
}
int i = 0;
// Tallying up the test results
cnt_crashed_tests = 0;
cnt_passed_tests = 0;
cnt_failed_tests = 0;
cnt_passed_public_tests = 0;
for (const auto& test_result : multi_result.test_results) {
if (!test_result.passed.has_value()) {
// std::cout << "Test " << i << " did not run.\n";
++cnt_crashed_tests;
} else if (*test_result.passed) {
// std::cout << "Test " << i << " passed.\n";
++cnt_passed_tests;
if (i < num_public_tests) {
++cnt_passed_public_tests;
}
} else {
// std::cout << "Test " << i << " failed.\n";
++cnt_failed_tests;
}
++i;
}
if (debug == true){
std::cout << "Tests ";
std::cout << "Passed: " << cnt_passed_tests << "/" << i << " ";
std::cout << "Failed: " << cnt_failed_tests << "/" << i << " ";
std::cout << "Crashed: " << cnt_crashed_tests << "/" << i << "\n";
}
}
json calculate_metrics(json single_problem) {
int n_sample = 0; // for counting the sample size for each problem
int c_passes = 0; // for counting the amount of passes in each sample
std::vector<int> idx_passed_public_tests; // for sampling solns that passed public tests
for (json solution : single_problem["test_results"]) {
if (solution["passed_all_tests"] == true) {
++c_passes;
}
if (solution["passed_public_tests"] == true) {
idx_passed_public_tests.push_back(n_sample);
}
++n_sample;
}
// for (int idx : idx_passed_public_tests) {
// std::cout << "\n idx (passed) = " << idx << "\n";
// }
std::vector<int> idx_sample_ten_at_k;
std::sample(idx_passed_public_tests.begin(), idx_passed_public_tests.end(), std::back_inserter(idx_sample_ten_at_k),
10, std::mt19937{std::random_device{}()});
// for (int idx : idx_sample_ten_at_k) {
// std::cout << "\n idx (sampled) = " << idx << "\n";
// }
int cnt = 0;
int c_cluster = 0;
for (json solution : single_problem["test_results"]) {
if (std::find(idx_sample_ten_at_k.begin(), idx_sample_ten_at_k.end(), cnt) != idx_sample_ten_at_k.end()) {
if (solution["passed_all_tests"] == true) {
++c_cluster;
}
}
++cnt;
}
std::cout << "\n" << single_problem["problem"] << ":\nn = " \
<< n_sample << ", c = " << c_passes << "\n\n";
bool pass_at_k_passed = false;
bool ten_at_k_passed = false;
// pass@k = k@k (only 1 pass needed from the whole sample)
if (c_passes > 0) {
pass_at_k_passed = true;
++number_passed_problems;
}
single_problem["test_metrics"]["pass_at_k_passed"] = pass_at_k_passed;
// 10@k – implementation of appropriate clustering method needed
// (take 10 from the sample pool, then check if at least one passed tests
if (c_cluster == idx_sample_ten_at_k.size() and n_sample != 0 and idx_sample_ten_at_k.size() != 0) {
ten_at_k_passed = true;
++number_passed_ten_at_k_problems;
}
single_problem["test_metrics"]["ten_at_k_passed"] = ten_at_k_passed;
single_problem["test_metrics"]["sample_size"] = n_sample;
single_problem["test_metrics"]["number_passes"] = c_passes;
return single_problem;
}
absl::Status SolveProblem(
const absl::string_view test_filename) {
std::string problem_name = solutions["problem_name"].get<std::string>();
ASSIGN_OR_RETURN(ContestProblem problem_being_solved,
FindProblem(test_filename, problem_name));
const std::vector<absl::string_view> inputs =
GetInputs(problem_being_solved,
/*max_size=*/3);
const std::vector<absl::string_view> outputs =
GetOutputs(problem_being_solved,
/*max_size=*/3);
Py3TesterSandboxer tester(Py3InterpreterPath(), Py3LibraryPaths());
TestOptions options;
options.num_threads = 4;
options.stop_on_first_failure = true;
std::cout << "\n Working on problem: '" << problem_name << "'\n";
if (debug == true){
std::cout << R"(Trying to solve the selected problem.
There are 3 options for the outcome of the tests:
1. (passed) The program runs successfully and gives the correct answer in all the tests.
2. (failed) The program runs successfully, but gives the wrong answer sometimes.
3. (crashed) The program does not compile.
)";
}
json single_problem_results;
single_problem_results["problem"] = problem_name;
int i = 0;
std::string soln_correct;
for (json soln : solutions["generated_solutions"]) {
soln_lang = soln["language"].get<std::string>();
// if (soln["is_correct"].get<bool>() == true) {
// soln_correct = "correct";
// } else {
// soln_correct = "incorrect";
// }
// absl::string_view soln_code = soln["code"].get<absl::string_view>();
// std::cout << "\n\n\nSolution " << i << ", code (" << soln_lang << "):\n-------------------------\n" << soln_code;
if (soln_lang == "python3") {
absl::string_view soln_code = soln["code"].get<absl::string_view>();
ASSIGN_OR_RETURN(MultiTestResult result_output,
tester.Test(soln_code, inputs, options, outputs));
if (debug == true) {
std::cout << "\nSolution " << i << " (" << soln_lang << "): ";
// std::cout << "\nSolution " << i << " (" << soln_lang <<", " << soln_correct << "): ";
}
ReportResults(result_output);
test_results["solution_number"] = i;
test_results["language"] = soln_lang;
test_results["tests_passed"] = cnt_passed_tests;
test_results["tests_failed"] = cnt_failed_tests;
test_results["tests_crashed"] = cnt_crashed_tests;
int cnt_ran_tests = cnt_passed_tests + cnt_failed_tests + cnt_crashed_tests;
if (cnt_ran_tests == 0) {
test_results["compilation"] = "fail";
} else {
test_results["compilation"] = "success";
}
// if passed all unit tests, count that as a pass in pass@k
if (cnt_passed_tests == cnt_ran_tests and cnt_ran_tests != 0) {
test_results["passed_all_tests"] = true;
} else {
test_results["passed_all_tests"] = false;
}
if (cnt_passed_public_tests == num_public_tests and num_public_tests != 0) {
test_results["passed_public_tests"] = true;
} else {
test_results["passed_public_tests"] = false;
}
single_problem_results["test_results"].push_back(test_results);
// if (debug == true) {
// std::cout << "\n" << results << "\n";
// }
}
++i;
}
single_problem_results = calculate_metrics(single_problem_results);
// exclude from output if no solutions in supported language were found
if (single_problem_results["test_metrics"]["sample_size"] != 0) {
results.push_back(single_problem_results);
++number_evaluated_problems;
} else {
std::cout << "\nNo solutions in a supported language were found!\n";
}
return absl::OkStatus();
}
} // namespace
} // namespace deepmind::code_contests
int main(int argc, char* argv[]) {
absl::ParseCommandLine(argc, argv);
std::ifstream sample_solutions_file("/home/maksgepner/CodeGenerationAnalysis/CodeContests/execution/sample_solutions.jsonl");
json single_problem;
std::string line;
int n;
int k;
int c;
double codex_pass_at_1;
double codex_pass_at_10;
double codex_pass_at_100;
double prod;
double pass_at_k;
double ten_at_k;
std::string output_filename;
std::string output_path;
while (std::getline(sample_solutions_file, line)) {
single_problem = json::parse(line);
// std::cout << "\n" << single_problem["generated_solutions"].front() << "\n";
// sample_solutions_file >> deepmind::code_contests::solutions;
// sample_solutions_file >> deepmind::code_contests::all_problem_samples;
// std::cout << "\n" << deepmind::code_contests::all_problem_samples["problem_name"] << "\n";
deepmind::code_contests::solutions = single_problem;
// std::cout << "\n" << single_problem.front() << "\n";
if (absl::Status status = deepmind::code_contests::SolveProblem(
absl::GetFlag(FLAGS_test_path));
!status.ok()) {
std::cerr << "Failed: " << status.message() << std::endl;
}
// Export the (intermediate) results
output_filename = "test_results.json";
output_path = absl::GetFlag(FLAGS_output_dir) + output_filename;
std::ofstream OutputFile1(output_path);
OutputFile1 << deepmind::code_contests::results;
OutputFile1.close();
n = deepmind::code_contests::number_evaluated_problems;
k = deepmind::code_contests::number_evaluated_problems;
c = deepmind::code_contests::number_passed_problems;
pass_at_k = c / (double)k;
ten_at_k = deepmind::code_contests::number_passed_ten_at_k_problems / (double)k;
k = 1;
if (n - c < k) {
codex_pass_at_1 = 1.0;
} else {
prod = 1;
for (double i = n - c + 1; i < n + 1; i++) {
prod = prod * (1 - k / i);
// std::cout << "\n Codex pass@k: " << 1 - prod << "\n";
}
codex_pass_at_1 = 1 - prod;
}
k = 10;
if (n - c < k) {
codex_pass_at_10 = 1.0;
} else {
prod = 1;
for (double i = n - c + 1; i < n + 1; i++) {
prod = prod * (1 - k / i);
// std::cout << "\n Codex pass@k: " << 1 - prod << "\n";
}
codex_pass_at_10 = 1 - prod;
}
k = 100;
if (n - c < k) {
codex_pass_at_100 = 1.0;
} else {
prod = 1;
for (double i = n - c + 1; i < n + 1; i++) {
prod = prod * (1 - k / i);
// std::cout << "\n Codex pass@k: " << 1 - prod << "\n";
}
codex_pass_at_100 = 1 - prod;
}
json result_metrics;
result_metrics["k"] = deepmind::code_contests::number_evaluated_problems;
result_metrics["c"] = c;
result_metrics["c_cluster"] = deepmind::code_contests::number_passed_ten_at_k_problems;
result_metrics["pass_at_k"] = pass_at_k;
result_metrics["ten_at_k"] = pass_at_k;
result_metrics["codex_pass_at_1"] = codex_pass_at_1;
result_metrics["codex_pass_at_10"] = codex_pass_at_10;
result_metrics["codex_pass_at_100"] = codex_pass_at_100;
// Export the (intermediate) metrics
output_filename = "test_metrics.json";
output_path = absl::GetFlag(FLAGS_output_dir) + output_filename;
std::ofstream OutputFile2(output_path);
OutputFile2 << result_metrics;
OutputFile2.close();
}
std::cout << "\n\n\nExperiments finished.\n";
std::cout << "k = " << deepmind::code_contests::number_evaluated_problems << "\n";
std::cout << "c = " << c << "\n";
std::cout << "c_cluster = " << deepmind::code_contests::number_passed_ten_at_k_problems << "\n";
std::cout << "Alphacode pass@k = " << pass_at_k << "\n";
std::cout << "Alphacode 10@k = " << ten_at_k << "\n";
std::cout << "Codex pass@1 = " << codex_pass_at_1 << "\n";
std::cout << "Codex pass@10 = " << codex_pass_at_10 << "\n";
std::cout << "Codex pass@100 = " << codex_pass_at_100 << "\n";
}
| 31.594433 | 127 | 0.636358 | [
"vector"
] |
c1df65164412a710660d9a1256ec3c463a3c4782 | 9,349 | cpp | C++ | algo_linear/algo_dumbo_impl.cpp | arjunradhakrishna/SpaceChessEngine | 4ba49b51b62ed927f07763254fd5cae12d7f3a7f | [
"Apache-2.0"
] | null | null | null | algo_linear/algo_dumbo_impl.cpp | arjunradhakrishna/SpaceChessEngine | 4ba49b51b62ed927f07763254fd5cae12d7f3a7f | [
"Apache-2.0"
] | null | null | null | algo_linear/algo_dumbo_impl.cpp | arjunradhakrishna/SpaceChessEngine | 4ba49b51b62ed927f07763254fd5cae12d7f3a7f | [
"Apache-2.0"
] | null | null | null |
#include "algo_dumbo_impl.h"
#include <chess/board_impl.h>
#include <limits>
namespace algo_dumbo_impl {
void exploreStates(
StateScores & stateScores,
const StateSet& stateSet,
int curDepth,
space::Color whoPlaysNext,
const space::AlgoDumboConfig & config)
{
// termination of recursion
if (curDepth >= config.maxDepth || stateSet.empty())
{
forEachState(
stateSet,
[&config, curDepth](StateHandle stateHandle)
{
double score = computeBasicScore(getState(stateHandle), config);
setScore(stateHandle, curDepth, score);
});
return;
}
// collect states for next level
StateSet nextLevel;
forEachState(
stateSet,
[&stateScores, curDepth, &config, whoPlaysNext, &nextLevel] (StateHandle stateHandle)
{
const auto & state = getState(stateHandle);
auto board = stateToBoard(state);
if (getNumUniqueStates(stateScores) > config.maxNumStates)
{
double score = computeBasicScore(getState(stateHandle), config);
setScore(stateHandle, curDepth, score);
}
else if (board->isCheckMate())
{
double score = config.maxScore * getScoreFactorForColor(whoPlaysNext);
setScore(stateHandle, curDepth, score);
}
else if (board->isStaleMate())
{
setScore(stateHandle, curDepth, 0);
}
else
{
auto validMoves = board->getValidMoves();
for (const auto & mxb: validMoves)
{
const auto & board = mxb.second;
auto state = boardToState(*board);
addState(stateScores, nextLevel, state, config.maxDepth);
}
}
});
// recurse into next level
space::Color opponent = (whoPlaysNext == space::Color::Black ? space::Color::White : space::Color::Black);
exploreStates(stateScores, nextLevel, curDepth + 1, opponent, config);
// compute best score for each state
Comparator secondScoreBetterForMe = getComparatorForColor(whoPlaysNext);
forEachState(
stateSet,
[&stateScores, curDepth, secondScoreBetterForMe](StateHandle stateHandle){
if (!std::isnan(getScore(stateHandle, curDepth)))
return;
const auto & state = getState(stateHandle);
auto board = stateToBoard(state);
auto validMoves = board->getValidMoves();
double bestNextScore = NAN;
for (const auto & mxb: validMoves)
{
const auto & nextBoard = mxb.second;
auto nextState = boardToState(*nextBoard);
double nextScore = getScore(stateScores, nextState, curDepth + 1);
if (std::isnan(bestNextScore) || secondScoreBetterForMe(bestNextScore, nextScore))
bestNextScore = nextScore;
}
setScore(stateHandle, curDepth, bestNextScore);
});
}
double computeBasicScore(
const State& state,
const space::AlgoDumboConfig& config)
{
auto board = stateToBoard(state);
double myScoreFactor = getScoreFactorForColor(board->whoPlaysNext());
double oppScoreFactor = myScoreFactor * -1;
// stalemate is a draw
if (board->isStaleMate())
return 0;
// checkmate is maxScore
if (board->isCheckMate())
// if i'm under check mate then i lost
return config.maxScore * oppScoreFactor;
// init resulting total score to 0
double totalScore = 0;
// score per each valid move of current player
auto validMoves = board->getValidMoves();
totalScore += validMoves.size() * config.validMoveScore * myScoreFactor;
// get score for valid moves of opponent in next state
// averaged across all moves i can make right now
for (const auto & move_x_board : validMoves)
{
const auto & nextBoard = *move_x_board.second;
if (nextBoard.isCheckMate())
// i have a move that forces checkmate, i win
return config.maxScore * myScoreFactor;
totalScore +=
config.validMoveScore // score per valid move
* nextBoard.getValidMoves().size() // number of valid moves for that state
* oppScoreFactor // score factor for opponent
/ validMoves.size(); // average out across all possible next states
}
// TODO: compute score for protecting/threatening pieces
// score for pieces
for (int rank = 0; rank < 8; ++rank)
{
for (int file = 0; file < 8; ++file)
{
space::Position pos(rank, file);
auto optPiece = board->getPiece(pos);
if (optPiece)
{
double scoreFactor = getScoreFactorForColor(optPiece->color);
switch (optPiece->pieceType)
{
case space::PieceType::Pawn:
totalScore += scoreFactor * config.pawnScore;
break;
case space::PieceType::Rook:
totalScore += scoreFactor * config.rookScore;
break;
case space::PieceType::Knight:
totalScore += scoreFactor * config.knightScore;
break;
case space::PieceType::Bishop:
totalScore += scoreFactor * config.bishopScore;
break;
case space::PieceType::Queen:
totalScore += scoreFactor * config.queenScore;
break;
default:
break;
}
}
}
}
return totalScore;
}
//-----------------------------------------------------------------------
// state to board
inline bool getBool(const State& state, int& idx)
{
return state[idx++];
}
inline int getInteger(const State& state, int& idx, int numBits)
{
int result = 0;
while(numBits-- > 0)
{
result = result * 2 + (getBool(state, idx) ? 1 : 0);
}
return result;
}
inline space::PieceType getPieceType(const State& state, int& idx)
{
return static_cast<space::PieceType>(getInteger(state, idx, 3));
}
inline space::Color getColor(const State& state, int& idx)
{
return (getBool(state, idx) ? space::Color::Black : space::Color::White);
}
space::IBoard::Ptr stateToBoard(const State& state)
{
std::array<std::array<space::Piece, 8>, 8> pieces;
int si = 0;
for (int rank = 0; rank < 8; ++rank)
for (int file = 0; file < 8; ++file)
{
auto pieceType = getPieceType(state, si);
auto color = getColor(state, si);
pieces[rank][file] = space::Piece{ pieceType, color };
}
bool canWhiteCastleLeft = getBool(state, si);
bool canWhiteCastleRight = getBool(state, si);
bool canBlackCastleLeft = getBool(state, si);
bool canBlackCastleRight = getBool(state, si);
space::Color whoPlaysNext = getColor(state, si);
return std::make_shared<space::BoardImpl>(
pieces,
canWhiteCastleLeft,
canWhiteCastleRight,
canBlackCastleLeft,
canBlackCastleRight,
whoPlaysNext);
}
//-----------------------------------------------------------------------
// board to state
void setBool(State& state, int& si, bool b)
{
state[si++] = b;
}
void setInteger(State& state, int& si, int numBits, int integer)
{
int reverseInteger = 0;
for (int i = 0; i < numBits; ++i)
{
reverseInteger *= 2;
reverseInteger += (integer % 2);
integer /= 2;
}
while(numBits--)
{
setBool(state, si, (reverseInteger % 2 == 1));
reverseInteger /= 2;
}
}
void setPieceType(State& state, int& si, space::PieceType pieceType)
{
setInteger(state, si, 3, static_cast<int>(pieceType));
}
void setColor(State& state, int & si, space::Color color)
{
setBool(state, si, (color == space::Color::Black));
}
State boardToState(const space::IBoard& board)
{
State state;
int si = 0;
for (int rank = 0; rank < 8; ++rank)
for (int file = 0; file < 8; ++file)
{
auto optPiece = board.getPiece(space::Position(rank, file));
space::PieceType pieceType = (optPiece ? optPiece->pieceType : space::PieceType::None);
space::Color color = (optPiece ? optPiece->color : space::Color::Black);
setPieceType(state, si, pieceType);
setColor(state, si, color);
}
setBool(state, si, board.canCastleLeft(space::Color::White));
setBool(state, si, board.canCastleRight(space::Color::White));
setBool(state, si, board.canCastleLeft(space::Color::Black));
setBool(state, si, board.canCastleRight(space::Color::Black));
setColor(state, si, board.whoPlaysNext());
return state;
}
//-----------------------------------------------------------------------------------------
//state utilities
void addState(StateScores& stateScores, const State& state, int maxDepth)
{
if (!stateScores.count(state))
stateScores[state] = std::vector(maxDepth, std::numeric_limits<double>::quiet_NaN());
}
void setScore(StateScores& stateScores, const State& state, int depth, double score)
{
stateScores[state][depth] = score;
}
double getScore(const StateScores& stateScores, const State& state, int depth)
{
return stateScores.find(state)->second.operator[](depth);
}
void addState(StateScores& stateScores, StateSet& stateSet, const State& state, int maxDepth)
{
auto handle = stateScores.find(state);
if (handle == stateScores.end())
handle = stateScores.insert(std::make_pair(state, std::vector(maxDepth, std::numeric_limits<double>::quiet_NaN()))).first;
stateSet.insert(handle);
}
void addState(StateSet& stateSet, const StateHandle& stateHandle)
{
stateSet.insert(stateHandle);
}
void setScore(StateHandle stateHandle, int curDepth, double score)
{
stateHandle->second.operator[](curDepth) = score;
}
double getScore(StateHandle stateHandle, int curDepth)
{
return stateHandle->second.operator[](curDepth);
}
} // end namespace algo_dumbo_impl
| 26.041783 | 125 | 0.648198 | [
"vector"
] |
c1e1c1ca61b4eb99064cc8c096f986836c26ef68 | 1,265 | hpp | C++ | src/ObjectState.hpp | ronsaldo/radiosity_test | d66a6c1106929f03b5ca9e035449fa4de23f79cc | [
"MIT"
] | 1 | 2018-05-23T02:51:45.000Z | 2018-05-23T02:51:45.000Z | src/ObjectState.hpp | ronsaldo/radiosity_test | d66a6c1106929f03b5ca9e035449fa4de23f79cc | [
"MIT"
] | null | null | null | src/ObjectState.hpp | ronsaldo/radiosity_test | d66a6c1106929f03b5ca9e035449fa4de23f79cc | [
"MIT"
] | null | null | null | #ifndef RADIOSITY_TEST_OBJECT_STATE_HPP
#define RADIOSITY_TEST_OBJECT_STATE_HPP
#include <glm/glm.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#include "GpuAllocator.hpp"
namespace RadiosityTest
{
/**
* Object state
*/
struct ObjectState
{
glm::mat4 transformation;
glm::mat4 inverseTransformation;
glm::mat4 normalTransformation;
glm::mat4 inverseNormalTransformation;
void setTransformation(const glm::mat4 &newTransformation)
{
transformation = newTransformation;
inverseTransformation = glm::inverse(transformation);
buildNormalMatrices();
}
void setAffineTransformation(const glm::mat4 &newTransformation)
{
transformation = newTransformation;
inverseTransformation = glm::affineInverse(transformation);
buildNormalMatrices();
}
void buildNormalMatrices()
{
normalTransformation = glm::transpose(glm::mat3(inverseTransformation));
inverseNormalTransformation = glm::transpose(glm::mat3(transformation));
}
};
typedef GpuUniformObjectAllocator<ObjectState, 30000> ObjectStateAllocator;
typedef ObjectStateAllocator::BufferedObject ObjectStateBufferedObject;
} // End of namespace RadiosityTest
#endif //RADIOSITY_TEST_OBJECT_STATE_HPP
| 25.816327 | 80 | 0.746245 | [
"object"
] |
c1e23a2db958f3e56a97f991132004aca334f615 | 2,146 | cpp | C++ | cpp/example_code/ses/send_templated_email.cpp | dlo/aws-doc-sdk-examples | 305e5c4f6cf268cafad7e1603aa5d2909fcd9c0c | [
"Apache-2.0"
] | null | null | null | cpp/example_code/ses/send_templated_email.cpp | dlo/aws-doc-sdk-examples | 305e5c4f6cf268cafad7e1603aa5d2909fcd9c0c | [
"Apache-2.0"
] | 1 | 2018-10-30T06:11:07.000Z | 2018-10-30T06:11:07.000Z | cpp/example_code/ses/send_templated_email.cpp | dlo/aws-doc-sdk-examples | 305e5c4f6cf268cafad7e1603aa5d2909fcd9c0c | [
"Apache-2.0"
] | 1 | 2018-10-30T06:01:23.000Z | 2018-10-30T06:01:23.000Z | /*
Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
This file is licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License. A copy of
the License is located at
http://aws.amazon.com/apache2.0/
This file 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 <aws/core/Aws.h>
#include <aws/email/SESClient.h>
#include <aws/email/model/SendTemplatedEmailRequest.h>
#include <aws/email/model/SendTemplatedEmailResult.h>
#include <aws/email/model/Destination.h>
#include <iostream>
int main(int argc, char **argv)
{
if (argc != 6)
{
std::cout << "Usage: send_templated_email <template_name> <template_data>"
"<sender_email_address> <cc_address> <reply_to_address> <to_addresses>";
return 1;
}
Aws::SDKOptions options;
Aws::InitAPI(options);
{
Aws::String template_name(argv[1]);
Aws::String template_data(argv[2]);
Aws::String sender_email_address(argv[3]);
Aws::String cc_address(argv[4]);
Aws::String reply_to_address(argv[5]);
Aws::SES::SESClient ses;
Aws::SES::Model::SendTemplatedEmailRequest ste_req;
Aws::SES::Model::Destination destination;
destination.AddCcAddresses(cc_address);
for (int i = 6; i < argc; ++i)
{
destination.AddToAddresses(argv[i]);
}
ste_req.SetDestination(destination);
ste_req.SetTemplate(template_name);
ste_req.SetTemplateData(template_data);
ste_req.SetSource(sender_email_address);
ste_req.AddReplyToAddresses(reply_to_address);
auto ste_out = ses.SendTemplatedEmail(ste_req);
if (ste_out.IsSuccess())
{
std::cout << "Successfully sent templated message " << ste_out.GetResult().GetMessageId()
<< std::endl;
}
else
{
std::cout << "Error sending templated message " << ste_out.GetError().GetMessage()
<< std::endl;
}
}
Aws::ShutdownAPI(options);
return 0;
}
| 30.225352 | 95 | 0.695247 | [
"model"
] |
c1e8e9bb55941efecc67034e701eca637ae911d9 | 6,242 | cpp | C++ | Programming-in-Qt/Qt_Basic/16Qt_Json/main.cpp | huruiyi/Programming-in-Qt | 5d7f1e6048f4cbc4076e9d222a95c1f68c79942b | [
"MIT"
] | null | null | null | Programming-in-Qt/Qt_Basic/16Qt_Json/main.cpp | huruiyi/Programming-in-Qt | 5d7f1e6048f4cbc4076e9d222a95c1f68c79942b | [
"MIT"
] | null | null | null | Programming-in-Qt/Qt_Basic/16Qt_Json/main.cpp | huruiyi/Programming-in-Qt | 5d7f1e6048f4cbc4076e9d222a95c1f68c79942b | [
"MIT"
] | 1 | 2019-07-19T22:36:30.000Z | 2019-07-19T22:36:30.000Z | #include <QCoreApplication>
#include <QJsonObject>
#include <QFile>
#include <QJsonDocument>
#include <QtDebug>
#include <QJsonArray>
#include <QJsonValue>
#define J_ID "id"
#define J_NICK "nick"
#define J_ZHUANYE "zhuanye"
#define J_AGE "age"
enum {
TAG_LOGIN,
TAG_LOGIN_OK,
TAG_LOGIN_FAIL,
TAG_REGISTER,
TAG_REGISTER_OK,
TAG_REGISTER_FAIL,
TAG_FIND_BACK
};
void WriteJson()
{
QJsonObject objArr
{
{"property1", 1},
{"property2", "2"}
};
QJsonArray jsonArr={QJsonValue(QString("员工1")),
QJsonValue(QString("员工2")),
QJsonValue(QString("员工3")),
QJsonValue(QString("员工4")),
QJsonValue(QString("员工5"))};
QJsonObject root, subobj;
// qjsonvalue(QJsonObject)
subobj.insert("ip", "192.168.1.27");
subobj.insert("port", "80");
subobj.insert("pros",objArr);
subobj.insert("employee",jsonArr);
root.insert("web_server", subobj);
// 经obj保存到磁盘
// obj->QJsonDocument
QJsonDocument doc(root);
QByteArray array = doc.toJson();
// 文件IO
QFile file("D:\\test.json");
file.open(QIODevice::WriteOnly);
file.write(array);
file.close();
}
void ReadJson()
{
// 本地磁盘文件加载到内存
QFile file("D:\\test.json");
file.open(QIODevice::ReadOnly);
QByteArray array = file.readAll();
QJsonDocument doc = QJsonDocument::fromJson(array);
// 判断
if(doc.isObject())
{
QJsonObject obj = doc.object();
// 取值
QJsonValue value = obj.value("web_server");
if(value.isObject())
{
QJsonObject sub = value.toObject();
QString ip = sub.value("ip").toString();
QString port = sub.value("port").toString();
QJsonValue jsonArr = sub.value("pros");
if(jsonArr.isObject()){
QJsonObject propertys= jsonArr.toObject();
int property1 = propertys.value("property1").toInt();
QString property2 = propertys.value("property2").toString();
qDebug() << "property1: "<< property1<<", property2: " << property2;
}
QJsonValue objEmp= sub.value("employee");
if(objEmp.isArray())
{
QJsonArray empArr = objEmp.toArray();
int empCount = empArr.count();
for(int i=0;i<empCount;i++)
{
qDebug() << "Name: "<< empArr[i].toString() ;
}
}
qDebug() << "iP: "<< ip<<", Port: " << port;
}
}
}
void JsonStrToOnject()
{
QString jsonStr1= "{'web_server': {'employee': ['员工1','员工2','员工3','员工4','员工5'],'ip': '192.168.1.27','port': '80','pros': {'property1': 1,'property2': '2'}}}";
QString s="x";
}
void Demo1()
{
//对象转json字符串
QMap<QString, QVariant> newData = QMap<QString, QVariant>();
newData.insert("content", "i'm content");
newData.insert("number", "i'm number");
newData.insert("time", "i'm time");
QJsonDocument doc=QJsonDocument::fromVariant(QVariant(newData));
QByteArray jba=doc.toJson();
QString jsonString = QString(jba);
qDebug() << "QMap<QString, QVariant>转环后的json字符串\n" << jsonString;
//字符串转json对象
QByteArray njba = jsonString.toUtf8();
QJsonObject nobj = QJsonObject(QJsonDocument::fromJson(njba).object());
qDebug() << "字符串转换后的对象\n"
<< nobj.take("content").toString() << endl
<< nobj.take("number").toString() << endl
<< nobj.take("time").toString() << endl;
}
void Demo2()
{
// 构造QJSonObject
QJsonObject json_object;
json_object.insert(J_ID, "1263");
json_object.insert(J_NICK, "lin");
json_object.insert(J_AGE, 20);
json_object.insert(J_ZHUANYE, "ruanjiangc");
// 转换成QByteArray
QByteArray byte_array = QJsonDocument(json_object).toJson();
// 这时候发送byte_array
// 另外一端对byte_array进行解析
// QByteArray转换成QJsonObject
QJsonObject json_object2 = QJsonDocument::fromJson(byte_array).object();
qDebug() << json_object2.value(J_ID).toString();
qDebug() << json_object2.value(J_NICK).toString();
qDebug() << json_object2.value(J_AGE).toInt();
qDebug() << json_object2.value(J_ZHUANYE).toString();
}
void Demo3()
{
// 构造QJsonObject(从数据库中读取的时候是在循环里面构造)
QJsonObject json_object;
json_object.insert(J_ID, "1263");
json_object.insert(J_NICK, "lin");
json_object.insert(J_AGE, 20);
json_object.insert(J_ZHUANYE, "ruanjiangc");
QJsonObject json_object2;
json_object2.insert(J_ID, "2345");
json_object2.insert(J_NICK, "jin");
json_object2.insert(J_AGE, 5);
json_object2.insert(J_ZHUANYE, "ruanjiangc");
QJsonObject json_object3;
json_object3.insert(J_ID, "9999");
json_object3.insert(J_NICK, "qiu");
json_object3.insert(J_AGE, 21);
json_object3.insert(J_ZHUANYE, "ruanjiangc");
QJsonObject json_object4;
json_object4.insert(J_ID, "6666");
json_object4.insert(J_NICK, "zhao");
json_object4.insert(J_AGE, 19);
json_object4.insert(J_ZHUANYE, "ruanjiangc");
// 构造QJsonArray
QJsonArray json_array;
json_array.insert(0, TAG_LOGIN);
json_array.insert(1, json_object);
json_array.insert(2, json_object2);
json_array.insert(3, json_object3);
json_array.insert(4, json_object4);
// 转换成QByteArray
QByteArray byte_array = QJsonDocument(json_array).toJson();
// 这时候发送byte_array
// 另外一端对byte_array进行解析
// QByteArray转换成QJsonArray
QJsonArray json_array2 = QJsonDocument::fromJson(byte_array).array();
int tag = json_array2.at(0).toInt();
qDebug() << "tag:" << tag;
for(int i = 1; i < json_array2.size(); ++i) {
QJsonObject json = json_array2.at(i).toObject();
qDebug() << json.value(J_ID).toString();
qDebug() << json.value(J_NICK).toString();
qDebug() << json.value(J_AGE).toInt();
qDebug() << json.value(J_ZHUANYE).toString();
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
WriteJson();
return a.exec();
}
| 29.582938 | 162 | 0.595803 | [
"object"
] |
c1e968516113b5dc8328484ad5bdeb50800b0611 | 2,646 | cc | C++ | RecoTauTag/TauTagTools/plugins/RecoTauPiZeroFlattener.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | RecoTauTag/TauTagTools/plugins/RecoTauPiZeroFlattener.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | RecoTauTag/TauTagTools/plugins/RecoTauPiZeroFlattener.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | /*
* =====================================================================================
* Filename: RecoTauPiZeroFlattener.cc
*
* Description: Produce a plain vector<RecoTauPizero> from the the PiZeros in
* a JetPiZeroAssociation associated to the input jets.
* Created: 10/31/2010 12:33:41
*
* Author: Evan K. Friis (UC Davis), evan.klose.friis@cern.ch
* =====================================================================================
*/
#include <algorithm>
#include "FWCore/Framework/interface/EDProducer.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/JetReco/interface/PFJetCollection.h"
#include "DataFormats/TauReco/interface/JetPiZeroAssociation.h"
#include "DataFormats/Candidate/interface/CandidateFwd.h"
#include "RecoTauTag/RecoTau/interface/RecoTauCommonUtilities.h"
class RecoTauPiZeroFlattener : public edm::EDProducer {
public:
explicit RecoTauPiZeroFlattener(const edm::ParameterSet &pset);
~RecoTauPiZeroFlattener() override {}
void produce(edm::Event& evt, const edm::EventSetup& es) override;
private:
edm::InputTag jetSrc_;
edm::InputTag piZeroSrc_;
};
RecoTauPiZeroFlattener::RecoTauPiZeroFlattener(const edm::ParameterSet& pset) {
jetSrc_ = pset.getParameter<edm::InputTag>("jetSrc");
piZeroSrc_ = pset.getParameter<edm::InputTag>("piZeroSrc");
produces<std::vector<reco::RecoTauPiZero> >();
}
void
RecoTauPiZeroFlattener::produce(edm::Event& evt, const edm::EventSetup& es) {
// Get the jet input collection via a view of Candidates
edm::Handle<reco::CandidateView> jetView;
evt.getByLabel(jetSrc_, jetView);
// Convert to a vector of PFJetRefs
reco::PFJetRefVector jets =
reco::tau::castView<reco::PFJetRefVector>(jetView);
// Get the pizero input collection
edm::Handle<reco::JetPiZeroAssociation> piZeroAssoc;
evt.getByLabel(piZeroSrc_, piZeroAssoc);
// Create output collection
auto output = std::make_unique<std::vector<reco::RecoTauPiZero>>();
// Loop over the jets and append the pizeros for each jet to our output
// collection.
for(auto const& jetRef : jets) {
const std::vector<reco::RecoTauPiZero>& pizeros = (*piZeroAssoc)[reco::JetBaseRef(jetRef)];
output->reserve(output->size() + pizeros.size());
output->insert(output->end(), pizeros.begin(), pizeros.end());
}
evt.put(std::move(output));
}
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(RecoTauPiZeroFlattener);
| 36.246575 | 95 | 0.68972 | [
"vector"
] |
c1ef175b02aa61145fd3201ad6c720cbaa0aa0be | 123 | cpp | C++ | src/final/object/Object.cpp | messo/diploma | e4fcf947482eec77d7426e97563a0d55d266bf2e | [
"MIT"
] | 1 | 2016-03-08T19:19:39.000Z | 2016-03-08T19:19:39.000Z | src/final/object/Object.cpp | messo/diploma | e4fcf947482eec77d7426e97563a0d55d266bf2e | [
"MIT"
] | null | null | null | src/final/object/Object.cpp | messo/diploma | e4fcf947482eec77d7426e97563a0d55d266bf2e | [
"MIT"
] | null | null | null | #include "Object.h"
Object::Object(cv::Mat left, cv::Mat right) : masks(2) {
masks[0] = left;
masks[1] = right;
}
| 17.571429 | 56 | 0.585366 | [
"object"
] |
c1efdf5e414f25e444796d104d1e1ceaf3971a96 | 1,919 | cc | C++ | ui/gfx/geometry/dip_util.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 27 | 2016-04-27T01:02:03.000Z | 2021-12-13T08:53:19.000Z | ui/gfx/geometry/dip_util.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 2 | 2017-03-09T09:00:50.000Z | 2017-09-21T15:48:20.000Z | ui/gfx/geometry/dip_util.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 17 | 2016-04-27T02:06:39.000Z | 2019-12-18T08:07:00.000Z | // Copyright 2014 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 "ui/gfx/geometry/dip_util.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/size_conversions.h"
namespace gfx {
Point ConvertPointToDIP(float scale_factor, const Point& point_in_pixel) {
return ScaleToFlooredPoint(point_in_pixel, 1.0f / scale_factor);
}
PointF ConvertPointToDIP(float scale_factor, const PointF& point_in_pixel) {
return ScalePoint(point_in_pixel, 1.0f / scale_factor);
}
Size ConvertSizeToDIP(float scale_factor, const Size& size_in_pixel) {
return ScaleToFlooredSize(size_in_pixel, 1.0f / scale_factor);
}
Rect ConvertRectToDIP(float scale_factor, const Rect& rect_in_pixel) {
return ToFlooredRectDeprecated(
ScaleRect(RectF(rect_in_pixel), 1.0f / scale_factor));
}
Point ConvertPointToPixel(float scale_factor, const Point& point_in_dip) {
return ScaleToFlooredPoint(point_in_dip, scale_factor);
}
Size ConvertSizeToPixel(float scale_factor, const Size& size_in_dip) {
return ScaleToFlooredSize(size_in_dip, scale_factor);
}
Rect ConvertRectToPixel(float scale_factor, const Rect& rect_in_dip) {
// Use ToEnclosingRect() to ensure we paint all the possible pixels
// touched. ToEnclosingRect() floors the origin, and ceils the max
// coordinate. To do otherwise (such as flooring the size) potentially
// results in rounding down and not drawing all the pixels that are
// touched.
return ToEnclosingRect(
RectF(ScalePoint(gfx::PointF(rect_in_dip.origin()), scale_factor),
ScaleSize(gfx::SizeF(rect_in_dip.size()), scale_factor)));
}
} // namespace gfx
| 35.537037 | 76 | 0.769151 | [
"geometry"
] |
c1fa4125e84b0de9077842e8c7afe013e61dead2 | 10,985 | cc | C++ | tensorflow/compiler/plugin/poplar/tests/dynamic_slice_test.cc | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 74 | 2020-07-06T17:11:39.000Z | 2022-01-28T06:31:28.000Z | tensorflow/compiler/plugin/poplar/tests/dynamic_slice_test.cc | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 9 | 2020-10-13T23:25:29.000Z | 2022-02-10T06:54:48.000Z | tensorflow/compiler/plugin/poplar/tests/dynamic_slice_test.cc | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 12 | 2020-07-08T07:27:17.000Z | 2021-12-27T08:54:27.000Z | /* 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 "absl/types/optional.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/data_initializer.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/util.h"
#include "tensorflow/compiler/plugin/poplar/tests/test_utils.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/execution_options_util.h"
#include "tensorflow/compiler/xla/service/hlo_parser.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
#include "tensorflow/core/lib/core/status_test_util.h"
namespace xla {
namespace poplarplugin {
namespace {
PrimitiveType GetFloatDataType(bool use_half) { return use_half ? F16 : F32; }
PrimitiveType GetIntDataType(bool use_signed) { return use_signed ? S32 : U32; }
string GetTestType(bool is_update) {
return is_update ? "DynamicUpdateSlice" : "DynamicSlice";
}
Literal CreateScalarLiteral(PrimitiveType type, int32 value) {
if (type == S32) {
return LiteralUtil::CreateR0<int32>(value);
} else {
return LiteralUtil::CreateR0<uint32>(value);
}
}
struct DynamicSliceTestSpec {
DynamicSliceTestSpec(const std::vector<int64>& to_slice_shape,
const std::vector<int64>& slice_shape,
const std::vector<int64>& slice_start_indices,
const std::vector<int64>& constant_slice_dims,
bool use_half, bool use_signed)
: to_slice_shape(to_slice_shape),
slice_shape(slice_shape),
slice_start_indices(slice_start_indices),
constant_slice_dims(constant_slice_dims),
use_half(use_half),
use_signed(use_signed) {}
const std::vector<int64> to_slice_shape;
const std::vector<int64> slice_shape;
const std::vector<int64> slice_start_indices;
const std::vector<int64> constant_slice_dims;
bool use_half;
bool use_signed;
friend ::std::ostream& operator<<(::std::ostream& os,
const DynamicSliceTestSpec& spec) {
string str = absl::StrCat(
"to_slice_shape_", absl::StrJoin(spec.to_slice_shape, ","),
"_slice_shape_", absl::StrJoin(spec.slice_shape, ","),
"_slice_start_indices_", absl::StrJoin(spec.slice_start_indices, ","),
"_constant_slice_dims_", absl::StrJoin(spec.constant_slice_dims, ","),
"_use_half_", spec.use_half, "_use_signed_", spec.use_signed);
os << str;
return os;
}
};
static std::vector<DynamicSliceTestSpec> GetTestCases() {
std::vector<DynamicSliceTestSpec> config_set;
for (auto use_half : {true, false}) {
for (auto use_signed : {true, false}) {
// Case 1: slice is shape of input tensor and all slice dims are
// constants.
config_set.push_back(
{{5, 5, 5}, {5, 5, 5}, {}, {}, use_half, use_signed});
// Case 2: constant slice.
config_set.push_back(
{{5, 5, 5}, {1, 5, 5}, {3}, {0}, use_half, use_signed});
// Case 3: slice is shape of input tensor and non of the slice dims are
// constant.
config_set.push_back(
{{5, 5, 5}, {5, 5, 5}, {}, {}, use_half, use_signed});
// Case 4: dynamic slice.
config_set.push_back(
{{5, 5, 5}, {5, 1, 5}, {2}, {1}, use_half, use_signed});
// Case 5: Each dimension is sliced, some const some dynamic.
config_set.push_back(
{{5, 5, 5}, {2, 2, 2}, {1, 2, 3}, {1}, use_half, use_signed});
// Case 6: Slice in dynamic and constant dimensions.
config_set.push_back({{5, 5, 5, 5, 5, 5},
{1, 5, 1, 1, 1, 5},
{2, 1, 2, 3},
{2, 3},
use_half,
use_signed});
}
}
return config_set;
}
// Helper struct for storing literal info.
struct TestCase {
std::unique_ptr<HloComputation> computation;
Literal input;
Literal update;
std::vector<Literal> slice_start_literals;
};
TestCase BuildTestCase(const DynamicSliceTestSpec& spec, bool is_update) {
auto data_type = GetFloatDataType(spec.use_half);
auto indices_type = GetIntDataType(spec.use_signed);
TestCase test_case;
auto builder = HloComputation::Builder(GetTestType(is_update));
size_t next_param_index = 0;
Shape input_shape = ShapeUtil::MakeShape(data_type, spec.to_slice_shape);
Shape slice_shape = ShapeUtil::MakeShape(data_type, spec.slice_shape);
// Create the input.
HloInstruction* input_inst =
builder.AddInstruction(HloInstruction::CreateParameter(
next_param_index++, input_shape, "input"));
test_case.input = DataInitializer::GetDataInitializer("normal")
->GetData(input_shape)
.ValueOrDie();
// Create the slices.
size_t num_dims = spec.slice_shape.size();
std::vector<HloInstruction*> slice_start_insts(num_dims);
size_t num_sliced_dims = 0;
for (size_t dim = 0; dim != num_dims; ++dim) {
HloInstruction* slice_start;
if (spec.to_slice_shape[dim] != spec.slice_shape[dim]) {
size_t start_index = spec.slice_start_indices[num_sliced_dims++];
Literal start_index_literal =
CreateScalarLiteral(indices_type, start_index);
// Slicing.
auto itr = absl::c_find(spec.constant_slice_dims, dim);
if (itr != spec.constant_slice_dims.end()) {
// The slice is with a constant start_index.
slice_start = builder.AddInstruction(
HloInstruction::CreateConstant(std::move(start_index_literal)));
} else {
// The slice is with a dynamic start_index.
slice_start = builder.AddInstruction(HloInstruction::CreateParameter(
next_param_index++, ShapeUtil::MakeShape(indices_type, {}),
"start_index"));
test_case.slice_start_literals.push_back(
std::move(start_index_literal));
}
} else {
// Not slicing, just create zero.
slice_start = builder.AddInstruction(
HloInstruction::CreateConstant(CreateScalarLiteral(indices_type, 0)));
}
slice_start_insts[dim] = slice_start;
}
// Create the actual dynamic (update) slice instruction.
absl::optional<Literal> update;
if (is_update) {
HloInstruction* update_inst =
builder.AddInstruction(HloInstruction::CreateParameter(
next_param_index++, slice_shape, "update"));
test_case.update = DataInitializer::GetDataInitializer("normal")
->GetData(slice_shape)
.ValueOrDie();
builder.AddInstruction(HloInstruction::CreateDynamicUpdateSlice(
input_shape, input_inst, update_inst, slice_start_insts));
} else {
builder.AddInstruction(HloInstruction::CreateDynamicSlice(
slice_shape, input_inst, slice_start_insts, slice_shape.dimensions()));
}
test_case.computation = builder.Build();
return test_case;
}
class DynamicUpdateSliceTest
: public HloTestBase,
public ::testing::WithParamInterface<DynamicSliceTestSpec> {};
INSTANTIATE_TEST_CASE_P(DynamicUpdateSliceTest_Instantiation,
DynamicUpdateSliceTest,
::testing::ValuesIn(GetTestCases()));
POPLAR_TEST_P(DynamicUpdateSliceTest, DoIt) {
VLOG(1) << "Test case " << GetParam();
const DynamicSliceTestSpec& spec = GetParam();
TestCase test_case = BuildTestCase(spec, true);
auto module = CreateNewVerifiedModule();
module->AddEntryComputation(std::move(test_case.computation));
std::vector<Literal*> inputs(2 + test_case.slice_start_literals.size());
inputs[0] = &test_case.input;
absl::c_transform(
test_case.slice_start_literals, std::next(inputs.begin()),
[](const Literal& literal) { return const_cast<Literal*>(&literal); });
inputs.back() = &test_case.update;
Literal result = Execute(std::move(module), inputs).ValueOrDie();
Literal expected = std::move(test_case.input);
size_t num_dims = spec.slice_shape.size();
std::vector<int64> zeros(num_dims, 0);
std::vector<int64> slice_starts(num_dims, 0);
std::vector<int64> slice_sizes = spec.slice_shape;
size_t num_sliced_dims = 0;
for (size_t dim = 0; dim != num_dims; ++dim) {
if (spec.to_slice_shape[dim] != spec.slice_shape[dim]) {
slice_starts[dim] = spec.slice_start_indices[num_sliced_dims++];
}
}
TF_ASSERT_OK(expected.CopySliceFrom(test_case.update, zeros, slice_starts,
slice_sizes));
EXPECT_TRUE(
LiteralTestUtil::NearOrEqual(expected, result, ErrorSpec{1e-3, 1e-3}));
}
class DynamicSliceTest
: public HloTestBase,
public ::testing::WithParamInterface<DynamicSliceTestSpec> {};
INSTANTIATE_TEST_CASE_P(DynamicSliceTest_Instantiation, DynamicSliceTest,
::testing::ValuesIn(GetTestCases()));
POPLAR_TEST_P(DynamicSliceTest, DoIt) {
VLOG(1) << "Test case " << GetParam();
const DynamicSliceTestSpec& spec = GetParam();
TestCase test_case = BuildTestCase(spec, false);
auto module = CreateNewVerifiedModule();
module->AddEntryComputation(std::move(test_case.computation));
std::vector<Literal*> inputs(1 + test_case.slice_start_literals.size());
inputs[0] = &test_case.input;
absl::c_transform(
test_case.slice_start_literals, std::next(inputs.begin()),
[](const Literal& literal) { return const_cast<Literal*>(&literal); });
Literal result = Execute(std::move(module), inputs).ValueOrDie();
size_t num_dims = spec.slice_shape.size();
std::vector<int64> slice_starts(num_dims, 0);
std::vector<int64> slice_ends = spec.to_slice_shape;
size_t num_sliced_dims = 0;
for (size_t dim = 0; dim != num_dims; ++dim) {
if (spec.to_slice_shape[dim] != spec.slice_shape[dim]) {
slice_starts[dim] = spec.slice_start_indices[num_sliced_dims++];
slice_ends[dim] = slice_starts[dim] + spec.slice_shape[dim];
}
}
Literal expected = test_case.input.Slice(slice_starts, slice_ends);
EXPECT_TRUE(
LiteralTestUtil::NearOrEqual(expected, result, ErrorSpec{1e-3, 1e-3}));
}
} // namespace
} // namespace poplarplugin
} // namespace xla
| 39.945455 | 80 | 0.676195 | [
"shape",
"vector"
] |
c1ff1682ae3bdad6b759f4b1d0f92781df363ba9 | 130,164 | cpp | C++ | src/mame/drivers/mw8080bw.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/drivers/mw8080bw.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/drivers/mw8080bw.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Nicola Salmoria, Tormod Tjaberg, Mirko Buffoni,Lee Taylor, Valerio Verrando, Zsolt Vasvari
// thanks-to:Michael Strutts, Marco Cassili
/***************************************************************************
Midway 8080-based black and white hardware
driver by Michael Strutts, Nicola Salmoria, Tormod Tjaberg, Mirko Buffoni,
Lee Taylor, Valerio Verrando, Marco Cassili, Zsolt Vasvari and others
Games supported:
* Sea Wolf
* Gun Fight
* Tornado Baseball
* (Datsun) 280-ZZZAP
* Amazing Maze
* Boot Hill
* Checkmate
* Desert Gun
* Road Runner
* Double Play
* Laguna Racer
* Guided Missile
* M-4
* Clowns
* Space Walk
* Extra Inning
* Shuffleboard
* Dog Patch
* Space Encounters
* Phantom II
* Bowling Alley
* Space Invaders
* Blue Shark
* Space Invaders II (Midway, cocktail version)
* Space Invaders Deluxe (cocktail version)
Other games on this basic hardware:
* Gun Fight (cocktail version)
* 4 Player Bowling Alley (cocktail version)
Notes:
* Most of these games do not actually use the MB14241 shifter IC,
but instead implement equivalent functionality using a bunch of
standard 74XX IC's.
* The Amazing Maze Game" on title screen, but manual, flyer,
cabinet side art all call it just "Amazing Maze"
* Desert Gun was originally named Road Runner. The name was changed
when Midway merged with Bally who had a game by the same title
* Guided Missile: It is a misconception that that this is the same
game as Taito's "Missile X". The latter does not run on a CPU,
akin to Midway's Gun Fight vs Taito's Western Gun.
* Space Invaders: Taito imported this licensed version because of
short supply in Japan. The game is called "Space Invaders M"
The M stands for Midway.
* "Gun Fight" (Midway) is ported version of "Western Gun" (Taito)
* in Japan, Taito released "Tornado Baseball" as "Ball Park",
"Extra Inning" as "Ball Park II".
* "Road Runner" (Midway): To access the test mode, adjust the
"Extended Time At" dipswitch to select "Test Mode". While in
the test mode, hold Fire until the gun alignment screen appears.
Known issues/to-do's:
* Space Encounters: verify strobe light frequency
* Phantom II: cloud generator is implemented according to the schematics,
but it doesn't look right. Cloud color mixing to be verified as well
* Dog Patch: verify all assumptions
* Blue Shark - all sounds are suspicious. Why is there no diver kill sound?
Why does the shark sound so bad and appear rarely?
Schematics need to be verified against real board.
****************************************************************************
Memory map
****************************************************************************
========================================================================
MAIN CPU memory address space
========================================================================
Address (15-bits) Dir Data Description
----------------- --- -------- -----------------------
x0xxxxxxxxxxxxx R xxxxxxxx Program ROM (various amounts populated)
-1xxxxxxxxxxxxx R/W xxxxxxxx Video RAM (256x256x1 bit display)
Portion in VBLANK region used as work RAM
Legend: (x) bit significant
(-) bit ignored
(0/1) bit must be given value
The I/O address space is used differently from game to game.
****************************************************************************
Horizontal sync chain:
The horizontal synch chain is clocked by the pixel clock, which
is the master clock divided by four via the counter @ C7 and
the D flip-flop at B5.
A 4-bit binary counter @ D5 counts 1H,2H,4H and 8H. This counter
cascades into another 4-bit binary counter @ E5, which counts
16H,32H,64H and 128H. The carry-out of this counter enables the
vertical sync chain. It also clocks a D flip-flop @ A5(1). The
output of the flip-flop is HBLANK and it is also used to reset
the two counters. When HBLANK is high, they are reset to 192,
otherwise to 0, thus giving 320 total pixels.
Clock = 19.968000/4MHz
HBLANK ends at H = 0
HBLANK begins at H = 256 (0x100)
HSYNC begins at H = 272 (0x110)
HSYNC ends at H = 288 (0x120)
HTOTAL = 320 (0x140)
Vertical sync chain:
The vertical synch chain is also clocked by the clock, but it is
only enabled counting in HBLANK, when the horizontal synch chain
overflows.
A 4-bit binary counter @ E6 counts 1V,2V,4V and 8V. This counter
cascades into another 4-bit binary counter @ E7, which counts
16V,32V,64V and 128V. The carry-out of this counter clocks a
D flip-flop @ A5(2). The output of the flip-flop is VBLANK and
it is also used to reset the two counters. When VBLANK is high,
they are reset to 218, otherwise to 32, thus giving
(256-218)+(256-32)=262 total pixels.
Clock = 19.968000/4MHz
VBLANK ends at V = 0
VBLANK begins at V = 224 (0x0e0)
VSYNC begins at V = 236 (0x0ec)
VSYNC ends at V = 240 (0x0f0)
VTOTAL = 262 (0x106)
Interrupts:
The CPU's INT line is asserted via a D flip-flop at E3.
The flip-flop is clocked by the expression (!(64V | !128V) | VBLANK).
According to this, the LO to HI transition happens when the vertical
sync chain is 0x80 and 0xda and VBLANK is 0 and 1, respectively.
These correspond to lines 96 and 224 as displayed.
The interrupt vector is provided by the expression:
0xc7 | (64V << 4) | (!64V << 3), giving 0xcf and 0xd7 for the vectors.
The flip-flop, thus the INT line, is later cleared by the CPU via
one of its memory access control signals.
****************************************************************************/
#include "emu.h"
#include "includes/mw8080bw.h"
#include "cpu/i8085/i8085.h"
#include "machine/rescap.h"
#include <algorithm>
#include "280zzzap.lh"
#include "clowns.lh"
#include "gunfight.lh"
#include "invaders.lh"
#include "invad2ct.lh"
#include "lagunar.lh"
#include "maze.lh"
#include "phantom2.lh"
#include "seawolf.lh"
#include "spacwalk.lh"
#include "spcenctr.lh"
INPUT_CHANGED_MEMBER(mw8080bw_state::direct_coin_count)
{
machine().bookkeeping().coin_counter_w(0, newval);
}
/*************************************
*
* Special shifter circuit
*
*************************************/
u8 mw8080bw_state::mw8080bw_shift_result_rev_r()
{
uint8_t ret = m_mb14241->shift_result_r();
return bitswap<8>(ret,0,1,2,3,4,5,6,7);
}
/*************************************
*
* Main CPU memory handlers
*
*************************************/
void mw8080bw_state::main_map(address_map &map)
{
map.global_mask(0x7fff);
map(0x0000, 0x1fff).rom().nopw();
map(0x2000, 0x3fff).mirror(0x4000).ram().share("main_ram");
map(0x4000, 0x5fff).rom().nopw();
}
/*************************************
*
* Root driver structure
*
*************************************/
void mw8080bw_state::mw8080bw_root(machine_config &config)
{
/* basic machine hardware */
I8080(config, m_maincpu, MW8080BW_CPU_CLOCK);
m_maincpu->set_addrmap(AS_PROGRAM, &mw8080bw_state::main_map);
m_maincpu->set_irq_acknowledge_callback(FUNC(mw8080bw_state::interrupt_vector));
MCFG_MACHINE_RESET_OVERRIDE(mw8080bw_state,mw8080bw)
/* video hardware */
SCREEN(config, m_screen, SCREEN_TYPE_RASTER);
m_screen->set_raw(MW8080BW_PIXEL_CLOCK, MW8080BW_HTOTAL, MW8080BW_HBEND, MW8080BW_HPIXCOUNT, MW8080BW_VTOTAL, MW8080BW_VBEND, MW8080BW_VBSTART);
m_screen->set_screen_update(FUNC(mw8080bw_state::screen_update_mw8080bw));
}
/*************************************
*
* Sea Wolf (PCB #596)
*
*************************************/
void seawolf_state::machine_start()
{
mw8080bw_state::machine_start();
m_exp_lamps.resolve();
m_torp_lamps.resolve();
m_ready_lamp.resolve();
m_reload_lamp.resolve();
}
void seawolf_state::explosion_lamp_w(u8 data)
{
/* D0-D3 are column drivers and D4-D7 are row drivers.
The following table shows values that light up individual lamps.
D7 D6 D5 D4 D3 D2 D1 D0 Function
--------------------------------------------------------------------------------------
0 0 0 1 1 0 0 0 Explosion Lamp 0
0 0 0 1 0 1 0 0 Explosion Lamp 1
0 0 0 1 0 0 1 0 Explosion Lamp 2
0 0 0 1 0 0 0 1 Explosion Lamp 3
0 0 1 0 1 0 0 0 Explosion Lamp 4
0 0 1 0 0 1 0 0 Explosion Lamp 5
0 0 1 0 0 0 1 0 Explosion Lamp 6
0 0 1 0 0 0 0 1 Explosion Lamp 7
0 1 0 0 1 0 0 0 Explosion Lamp 8
0 1 0 0 0 1 0 0 Explosion Lamp 9
0 1 0 0 0 0 1 0 Explosion Lamp A
0 1 0 0 0 0 0 1 Explosion Lamp B
1 0 0 0 1 0 0 0 Explosion Lamp C
1 0 0 0 0 1 0 0 Explosion Lamp D
1 0 0 0 0 0 1 0 Explosion Lamp E
1 0 0 0 0 0 0 1 Explosion Lamp F
*/
static constexpr u8 BITS_FOR_LAMPS[] =
{
0x18, 0x14, 0x12, 0x11,
0x28, 0x24, 0x22, 0x21,
0x48, 0x44, 0x42, 0x41,
0x88, 0x84, 0x82, 0x81
};
for (int i = 0; i < 16; i++)
{
u8 const bits_for_lamp(BITS_FOR_LAMPS[i]);
m_exp_lamps[i] = ((data & bits_for_lamp) == bits_for_lamp) ? 1 : 0;
}
}
void seawolf_state::periscope_lamp_w(u8 data)
{
/* the schematics and the connecting diagrams show the torpedo light
order differently, but this order is confirmed by the software */
m_torp_lamps[3] = BIT(data, 0);
m_torp_lamps[2] = BIT(data, 1);
m_torp_lamps[1] = BIT(data, 2);
m_torp_lamps[0] = BIT(data, 3);
m_ready_lamp = BIT(data, 4);
m_reload_lamp = BIT(data, 5);
}
CUSTOM_INPUT_MEMBER(seawolf_state::erase_input_r)
{
return m_erase_sw->read() & m_erase_dip->read();
}
void seawolf_state::io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).r(FUNC(seawolf_state::mw8080bw_shift_result_rev_r));
map(0x01, 0x01).mirror(0x04).portr("IN0");
map(0x02, 0x02).mirror(0x04).portr("IN1");
map(0x03, 0x03).mirror(0x04).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x01, 0x01).w(FUNC(seawolf_state::explosion_lamp_w));
map(0x02, 0x02).w(FUNC(seawolf_state::periscope_lamp_w));
map(0x03, 0x03).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x04, 0x04).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x05, 0x05).w("soundboard", FUNC(seawolf_audio_device::write));
}
// the 30 position encoder is verified
static const ioport_value seawolf_controller_table[30] =
{
0x1e, 0x1c, 0x1d, 0x19, 0x18, 0x1a, 0x1b, 0x13,
0x12, 0x10, 0x11, 0x15, 0x14, 0x16, 0x17, 0x07,
0x06, 0x04, 0x05, 0x01, 0x00, 0x02, 0x03, 0x0b,
0x0a, 0x08, 0x09, 0x0d, 0x0c, 0x0e
};
static INPUT_PORTS_START( seawolf )
PORT_START("IN0")
// the grey code is inverted by buffers
// The wiring diagram shows the encoder has 32 positions.
// But there is a hand written table on the game logic sheet showing only 30 positions.
// The actual commutator pcb (encoder) has 30 positions and works like the table says.
PORT_BIT( 0x1f, 0x0f, IPT_POSITIONAL ) PORT_POSITIONS(30) PORT_REMAP_TABLE(seawolf_controller_table) PORT_INVERT PORT_SENSITIVITY(20) PORT_KEYDELTA(8) PORT_CENTERDELTA(0) PORT_NAME("Periscope axis") PORT_CROSSHAIR(X, ((float)MW8080BW_HPIXCOUNT - 28) / MW8080BW_HPIXCOUNT, 16.0 / MW8080BW_HPIXCOUNT, 32.0 / MW8080BW_VBSTART)
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_DIPNAME( 0xc0, 0x40, DEF_STR( Game_Time ) ) PORT_CONDITION("IN1", 0xe0, NOTEQUALS, 0xe0) PORT_DIPLOCATION("G4:1,2")
PORT_DIPSETTING( 0x00, "60 seconds + 20 extended" ) PORT_CONDITION("IN1", 0xe0, NOTEQUALS, 0x00)
PORT_DIPSETTING( 0x40, "70 seconds + 20 extended" ) PORT_CONDITION("IN1", 0xe0, NOTEQUALS, 0x00)
PORT_DIPSETTING( 0x80, "80 seconds + 20 extended" ) PORT_CONDITION("IN1", 0xe0, NOTEQUALS, 0x00)
PORT_DIPSETTING( 0xc0, "90 seconds + 20 extended" ) PORT_CONDITION("IN1", 0xe0, NOTEQUALS, 0x00)
PORT_DIPSETTING( 0x00, "60 seconds" ) PORT_CONDITION("IN1", 0xe0, EQUALS, 0x00)
PORT_DIPSETTING( 0x40, "70 seconds" ) PORT_CONDITION("IN1", 0xe0, EQUALS, 0x00)
PORT_DIPSETTING( 0x80, "80 seconds" ) PORT_CONDITION("IN1", 0xe0, EQUALS, 0x00)
PORT_DIPSETTING( 0xc0, "90 seconds" ) PORT_CONDITION("IN1", 0xe0, EQUALS, 0x00)
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START1 )
PORT_DIPNAME( 0x0c, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN1", 0xe0, NOTEQUALS, 0xe0) PORT_DIPLOCATION("G4:3,4")
PORT_DIPSETTING( 0x04, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x0c, DEF_STR( 2C_3C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 1C_2C ) )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(seawolf_state, erase_input_r)
PORT_DIPNAME( 0xe0, 0x60, "Extended Time At" ) PORT_DIPLOCATION("G4:6,7,8")
PORT_DIPSETTING( 0x00, DEF_STR( None ) )
PORT_DIPSETTING( 0x20, "2000" )
PORT_DIPSETTING( 0x40, "3000" )
PORT_DIPSETTING( 0x60, "4000" )
PORT_DIPSETTING( 0x80, "5000" )
PORT_DIPSETTING( 0xa0, "6000" )
PORT_DIPSETTING( 0xc0, "7000" )
PORT_DIPSETTING( 0xe0, "Test Mode" )
// 2 fake ports for the 'Reset High Score' input, which has a DIP to enable it
PORT_START(SEAWOLF_ERASE_SW_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_MEMORY_RESET ) PORT_NAME("Reset High Score")
PORT_BIT( 0xfe, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START(SEAWOLF_ERASE_DIP_PORT_TAG)
PORT_DIPNAME( 0x01, 0x01, "Enable Reset High Score Button" ) PORT_DIPLOCATION("G4:5")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x01, DEF_STR( On ) )
PORT_BIT( 0xfe, IP_ACTIVE_HIGH, IPT_UNUSED )
INPUT_PORTS_END
void seawolf_state::seawolf(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &seawolf_state::io_map);
// there is no watchdog
// add shifter
MB14241(config, m_mb14241);
// audio hardware
SEAWOLF_AUDIO(config, "soundboard");
}
/*************************************
*
* Gun Fight (PCB #597)
*
*************************************/
void gunfight_state::io_w(offs_t offset, u8 data)
{
if (offset & 0x01)
m_soundboard->write(data);
if (offset & 0x02)
m_mb14241->shift_count_w(data);
if (offset & 0x04)
m_mb14241->shift_data_w(data);
}
void gunfight_state::io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).portr("IN0");
map(0x01, 0x01).mirror(0x04).portr("IN1");
map(0x02, 0x02).mirror(0x04).portr("IN2");
map(0x03, 0x03).mirror(0x04).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x00, 0x07).w(FUNC(gunfight_state::io_w)); // no decoder, just 3 AND gates
}
static const ioport_value gunfight_controller_table[7] =
{
0x06, 0x02, 0x00, 0x04, 0x05, 0x01, 0x03
};
static INPUT_PORTS_START( gunfight )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1)
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1)
PORT_BIT( 0x70, 0x30, IPT_POSITIONAL_V ) PORT_POSITIONS(7) PORT_REMAP_TABLE(gunfight_controller_table) PORT_INVERT PORT_SENSITIVITY(5) PORT_KEYDELTA(10) PORT_CENTERDELTA(0) PORT_CODE_DEC(KEYCODE_N) PORT_CODE_INC(KEYCODE_H) PORT_PLAYER(1)
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x70, 0x30, IPT_POSITIONAL_V ) PORT_POSITIONS(7) PORT_REMAP_TABLE(gunfight_controller_table) PORT_INVERT PORT_SENSITIVITY(5) PORT_KEYDELTA(10) PORT_CENTERDELTA(0) PORT_CODE_DEC(KEYCODE_M) PORT_CODE_INC(KEYCODE_J) PORT_PLAYER(2)
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_START("IN2")
PORT_DIPNAME( 0x0f, 0x00, DEF_STR( Coinage ) ) PORT_DIPLOCATION("C1:1,2,3,4")
PORT_DIPSETTING( 0x03, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x02, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x07, DEF_STR( 4C_2C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x06, DEF_STR( 3C_2C ) )
PORT_DIPSETTING( 0x0b, DEF_STR( 4C_3C ) )
PORT_DIPSETTING( 0x0f, DEF_STR( 4C_4C ) )
PORT_DIPSETTING( 0x0a, DEF_STR( 3C_3C ) )
PORT_DIPSETTING( 0x05, DEF_STR( 2C_2C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x0e, DEF_STR( 3C_4C ) )
PORT_DIPSETTING( 0x09, DEF_STR( 2C_3C ) )
PORT_DIPSETTING( 0x0d, DEF_STR( 2C_4C ) )
PORT_DIPSETTING( 0x04, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x0c, DEF_STR( 1C_4C ) )
PORT_DIPNAME( 0x30, 0x10, DEF_STR( Game_Time ) ) PORT_DIPLOCATION("C1:5,6")
PORT_DIPSETTING( 0x00, "60 seconds" )
PORT_DIPSETTING( 0x10, "70 seconds" )
PORT_DIPSETTING( 0x20, "80 seconds" )
PORT_DIPSETTING( 0x30, "90 seconds" )
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_COIN1 )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_START1 )
INPUT_PORTS_END
void gunfight_state::gunfight(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &gunfight_state::io_map);
// there is no watchdog
// add shifter
MB14241(config, m_mb14241);
// audio hardware
GUNFIGHT_AUDIO(config, m_soundboard);
}
/*************************************
*
* Tornado Baseball (PCB #605)
*
* Notes:
* -----
*
* In baseball, the Visitor team always hits first and the Home team pitches (throws the ball).
* This rule gives an advantage to the Home team because they get to score last in any baseball game.
* It is also the team that pitches that controls the player on the field, which, in this game,
* is limited to moving the 3 outfielders left and right.
*
* There are 3 types of cabinets using the same software:
*
* Old Upright: One of everything
*
* New Upright: One fielding/pitching controls, but two (Left/Right) hitting buttons
*
* Cocktail: Two of everything, but the pitching/fielding controls are swapped
*
* Interestingly, the "Whistle" sound effect is controlled by a different
* bit on the Old Upright cabinet than the other two types.
*
*************************************/
#define TORNBASE_L_HIT_PORT_TAG ("LHIT")
#define TORNBASE_R_HIT_PORT_TAG ("RHIT")
#define TORNBASE_L_PITCH_PORT_TAG ("LPITCH")
#define TORNBASE_R_PITCH_PORT_TAG ("RPITCH")
#define TORNBASE_SCORE_SW_PORT_TAG ("SCORESW")
#define TORNBASE_SCORE_DIP_PORT_TAG ("ERASEDIP")
#define TORNBASE_CAB_TYPE_PORT_TAG ("CAB")
uint8_t mw8080bw_state::tornbase_get_cabinet_type()
{
return ioport(TORNBASE_CAB_TYPE_PORT_TAG)->read();
}
CUSTOM_INPUT_MEMBER(mw8080bw_state::tornbase_hit_left_input_r)
{
return ioport(TORNBASE_L_HIT_PORT_TAG)->read();
}
CUSTOM_INPUT_MEMBER(mw8080bw_state::tornbase_hit_right_input_r)
{
uint32_t ret;
switch (tornbase_get_cabinet_type())
{
case TORNBASE_CAB_TYPE_UPRIGHT_OLD:
ret = ioport(TORNBASE_L_HIT_PORT_TAG)->read();
break;
case TORNBASE_CAB_TYPE_UPRIGHT_NEW:
case TORNBASE_CAB_TYPE_COCKTAIL:
default:
ret = ioport(TORNBASE_R_HIT_PORT_TAG)->read();
break;
}
return ret;
}
CUSTOM_INPUT_MEMBER(mw8080bw_state::tornbase_pitch_left_input_r)
{
uint32_t ret;
switch (tornbase_get_cabinet_type())
{
case TORNBASE_CAB_TYPE_UPRIGHT_OLD:
case TORNBASE_CAB_TYPE_UPRIGHT_NEW:
ret = ioport(TORNBASE_L_PITCH_PORT_TAG)->read();
break;
case TORNBASE_CAB_TYPE_COCKTAIL:
default:
ret = ioport(TORNBASE_R_PITCH_PORT_TAG)->read();
break;
}
return ret;
}
CUSTOM_INPUT_MEMBER(mw8080bw_state::tornbase_pitch_right_input_r)
{
return ioport(TORNBASE_L_PITCH_PORT_TAG)->read();
}
CUSTOM_INPUT_MEMBER(mw8080bw_state::tornbase_score_input_r)
{
return ioport(TORNBASE_SCORE_SW_PORT_TAG)->read() &
ioport(TORNBASE_SCORE_DIP_PORT_TAG)->read();
}
void mw8080bw_state::tornbase_io_w(offs_t offset, uint8_t data)
{
if (offset & 0x01)
tornbase_audio_w(data);
if (offset & 0x02)
m_mb14241->shift_count_w(data);
if (offset & 0x04)
m_mb14241->shift_data_w(data);
}
void mw8080bw_state::tornbase_io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).portr("IN0");
map(0x01, 0x01).mirror(0x04).portr("IN1");
map(0x02, 0x02).mirror(0x04).portr("IN2");
map(0x03, 0x03).mirror(0x04).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
/* no decoder, just 3 AND gates */
map(0x00, 0x07).w(FUNC(mw8080bw_state::tornbase_io_w));
}
static INPUT_PORTS_START( tornbase )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(mw8080bw_state, tornbase_hit_left_input_r)
PORT_BIT( 0x7e, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(mw8080bw_state, tornbase_pitch_left_input_r)
PORT_DIPNAME( 0x80, 0x00, DEF_STR( Unused ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("B1:7")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x80, DEF_STR( On ) )
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(mw8080bw_state, tornbase_hit_right_input_r)
PORT_BIT( 0x7e, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(mw8080bw_state, tornbase_pitch_right_input_r)
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNUSED) /* not connected */
PORT_START("IN2")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* schematics shows it as "START", but not used by the software */
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(mw8080bw_state, tornbase_score_input_r)
PORT_DIPNAME( 0x78, 0x40, DEF_STR( Coinage ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("B1:2,3,4,5")
PORT_DIPSETTING( 0x18, "4 Coins/1 Inning" )
PORT_DIPSETTING( 0x10, "3 Coins/1 Inning" )
PORT_DIPSETTING( 0x38, "4 Coins/2 Innings" )
PORT_DIPSETTING( 0x08, "2 Coins/1 Inning" )
PORT_DIPSETTING( 0x30, "3 Coins/2 Innings" )
PORT_DIPSETTING( 0x28, "2 Coins/2 Innings" )
PORT_DIPSETTING( 0x00, "1 Coin/1 Inning" )
PORT_DIPSETTING( 0x58, "4 Coins/4 Innings" )
PORT_DIPSETTING( 0x50, "3 Coins/4 Innings" )
PORT_DIPSETTING( 0x48, "2 Coins/4 Innings" )
PORT_DIPSETTING( 0x20, "1 Coin/2 Innings" )
PORT_DIPSETTING( 0x40, "1 Coin/4 Innings" )
PORT_DIPSETTING( 0x78, "4 Coins/9 Innings" )
PORT_DIPSETTING( 0x70, "3 Coins/9 Innings" )
PORT_DIPSETTING( 0x68, "2 Coins/9 Innings" )
PORT_DIPSETTING( 0x60, "1 Coin/9 Innings" )
PORT_SERVICE_DIPLOC( 0x80, IP_ACTIVE_HIGH, "B1:6" )
/* fake ports to handle the various input configurations based on cabinet type */
PORT_START(TORNBASE_L_HIT_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_NAME("P1 Hit") PORT_PLAYER(1)
PORT_BIT( 0xfe, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START(TORNBASE_R_HIT_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_NAME("P2 Hit") PORT_PLAYER(2)
PORT_BIT( 0xfe, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START(TORNBASE_L_PITCH_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_NAME("P1 Move Outfield Left") PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_BUTTON3 ) PORT_NAME("P1 Move Outfield Right") PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_NAME("P1 Pitch Left") PORT_PLAYER(1)
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_NAME("P1 Pitch Right") PORT_PLAYER(1)
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_NAME("P1 Pitch Slow") PORT_PLAYER(1)
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_NAME("P1 Pitch Fast") PORT_PLAYER(1)
PORT_BIT( 0xc0, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START(TORNBASE_R_PITCH_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_NAME("P2 Move Outfield Left") PORT_PLAYER(2)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_BUTTON3 ) PORT_NAME("P2 Move Outfield Right") PORT_PLAYER(2)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_NAME("P2 Pitch Left") PORT_PLAYER(2)
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_NAME("P2 Pitch Right") PORT_PLAYER(2)
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_NAME("P2 Pitch Slow") PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_NAME("P2 Pitch Fast") PORT_PLAYER(2)
PORT_BIT( 0xc0, IP_ACTIVE_HIGH, IPT_UNUSED )
/* 2 fakes port for the 'ERASE' input, which has a DIP to enable it.
This switch is not actually used by the software */
PORT_START(TORNBASE_SCORE_SW_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_OTHER ) PORT_NAME("SCORE Input (Not Used)") PORT_CODE(KEYCODE_F2)
PORT_BIT( 0xfe, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START(TORNBASE_SCORE_DIP_PORT_TAG)
PORT_DIPNAME( 0x01, 0x01, "Enable SCORE Input" ) PORT_DIPLOCATION("B1:1")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x01, DEF_STR( On ) )
PORT_BIT( 0xfe, IP_ACTIVE_HIGH, IPT_UNUSED )
/* fake port for cabinet type */
PORT_START(TORNBASE_CAB_TYPE_PORT_TAG)
PORT_CONFNAME( 0x03, TORNBASE_CAB_TYPE_UPRIGHT_NEW, DEF_STR( Cabinet ) )
PORT_CONFSETTING( TORNBASE_CAB_TYPE_UPRIGHT_OLD, "Upright/w One Hit Button" )
PORT_CONFSETTING( TORNBASE_CAB_TYPE_UPRIGHT_NEW, "Upright/w P1/P2 Hit Buttons" )
PORT_CONFSETTING( TORNBASE_CAB_TYPE_COCKTAIL, DEF_STR( Cocktail ) )
PORT_BIT( 0xfc, IP_ACTIVE_HIGH, IPT_UNUSED )
INPUT_PORTS_END
void mw8080bw_state::tornbase(machine_config &config)
{
mw8080bw_root(config);
/* basic machine hardware */
m_maincpu->set_addrmap(AS_IO, &mw8080bw_state::tornbase_io_map);
/* there is no watchdog */
/* add shifter */
MB14241(config, m_mb14241);
/* audio hardware */
tornbase_audio(config);
}
/*************************************
*
* 280 ZZZAP (PCB #610) / Laguna Racer (PCB #622)
*
*************************************/
void zzzap_state::io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).portr("IN0");
map(0x01, 0x01).mirror(0x04).portr("IN1");
map(0x02, 0x02).mirror(0x04).portr("IN2");
map(0x03, 0x03).mirror(0x04).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x02, 0x02).w("soundboard", FUNC(zzzap_common_audio_device::p1_w));
map(0x03, 0x03).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x04, 0x04).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x05, 0x05).w("soundboard", FUNC(zzzap_common_audio_device::p2_w));
map(0x07, 0x07).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
}
static INPUT_PORTS_START( zzzap )
PORT_START("IN0")
PORT_BIT( 0x0f, 0x00, IPT_PEDAL ) PORT_SENSITIVITY(100) PORT_KEYDELTA(64) PORT_PLAYER(1) /* accelerator */
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_TOGGLE PORT_NAME("P1 Shift") PORT_PLAYER(1)
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNUSED ) /* not connected */
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 ) /* start button, but never used? */
PORT_START("IN1") /* steering wheel */
PORT_BIT( 0xff, 0x7f, IPT_PADDLE ) PORT_MINMAX(0x01,0xfe) PORT_SENSITIVITY(100) PORT_KEYDELTA(10) PORT_REVERSE PORT_PLAYER(1)
PORT_START("IN2")
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN2", 0x0c, NOTEQUALS, 0x04) PORT_DIPLOCATION("E3:1,2")
PORT_DIPSETTING( 0x02, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x03, DEF_STR( 2C_3C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 1C_2C ) )
PORT_DIPNAME( 0x0c, 0x00, DEF_STR( Game_Time ) ) PORT_DIPLOCATION("E3:3,4")
PORT_DIPSETTING( 0x0c, "60 seconds + 30 extended" ) PORT_CONDITION("IN2", 0x30, NOTEQUALS, 0x20)
PORT_DIPSETTING( 0x00, "80 seconds + 40 extended" ) PORT_CONDITION("IN2", 0x30, NOTEQUALS, 0x20)
PORT_DIPSETTING( 0x08, "99 seconds + 50 extended" ) PORT_CONDITION("IN2", 0x30, NOTEQUALS, 0x20)
PORT_DIPSETTING( 0x0c, "60 seconds" ) PORT_CONDITION("IN2", 0x30, EQUALS, 0x20)
PORT_DIPSETTING( 0x00, "80 seconds" ) PORT_CONDITION("IN2", 0x30, EQUALS, 0x20)
PORT_DIPSETTING( 0x08, "99 seconds" ) PORT_CONDITION("IN2", 0x30, EQUALS, 0x20)
PORT_DIPSETTING( 0x04, "Test Mode" )
PORT_DIPNAME( 0x30, 0x00, "Extended Time At" ) PORT_CONDITION("IN2", 0x0c, NOTEQUALS, 0x04) PORT_DIPLOCATION("E3:5,6")
PORT_DIPSETTING( 0x10, "2.00" )
PORT_DIPSETTING( 0x00, "2.50" )
PORT_DIPSETTING( 0x20, DEF_STR( None ) )
/* PORT_DIPSETTING( 0x30, DEF_STR( None ) ) */
PORT_DIPNAME( 0xc0, 0x00, DEF_STR( Language )) PORT_CONDITION("IN2", 0x0c, NOTEQUALS, 0x04) PORT_DIPLOCATION("E3:7,8")
PORT_DIPSETTING( 0x00, DEF_STR( English ) )
PORT_DIPSETTING( 0x40, DEF_STR( German ) )
PORT_DIPSETTING( 0x80, DEF_STR( French ) )
PORT_DIPSETTING( 0xc0, DEF_STR( Spanish ) )
INPUT_PORTS_END
static INPUT_PORTS_START( lagunar )
PORT_INCLUDE( zzzap )
PORT_MODIFY("IN2")
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coinage ) ) PORT_DIPLOCATION("E3:1,2")
PORT_DIPSETTING( 0x02, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x03, DEF_STR( 2C_3C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 1C_2C ) )
PORT_DIPNAME( 0x0c, 0x04, DEF_STR( Game_Time ) ) PORT_CONDITION("IN2", 0xc0, NOTEQUALS, 0x04) PORT_DIPLOCATION("E3:3,4")
PORT_DIPSETTING( 0x00, "45 seconds + 22 extended" ) PORT_CONDITION("IN2", 0xc0, NOTEQUALS, 0xc0)
PORT_DIPSETTING( 0x04, "60 seconds + 30 extended" ) PORT_CONDITION("IN2", 0xc0, NOTEQUALS, 0xc0)
PORT_DIPSETTING( 0x08, "75 seconds + 37 extended" ) PORT_CONDITION("IN2", 0xc0, NOTEQUALS, 0xc0)
PORT_DIPSETTING( 0x0c, "90 seconds + 45 extended" ) PORT_CONDITION("IN2", 0xc0, NOTEQUALS, 0xc0)
PORT_DIPSETTING( 0x00, "45 seconds" ) PORT_CONDITION("IN2", 0xc0, EQUALS, 0xc0)
PORT_DIPSETTING( 0x04, "60 seconds" ) PORT_CONDITION("IN2", 0xc0, EQUALS, 0xc0)
PORT_DIPSETTING( 0x08, "75 seconds" ) PORT_CONDITION("IN2", 0xc0, EQUALS, 0xc0)
PORT_DIPSETTING( 0x0c, "90 seconds" ) PORT_CONDITION("IN2", 0xc0, EQUALS, 0xc0)
PORT_DIPNAME( 0x30, 0x20, "Extended Time At" ) PORT_CONDITION("IN2", 0xc0, NOTEQUALS, 0xc0) PORT_DIPLOCATION("E3:5,6")
PORT_DIPSETTING( 0x00, "350" )
PORT_DIPSETTING( 0x10, "400" )
PORT_DIPSETTING( 0x20, "450" )
PORT_DIPSETTING( 0x30, "500" )
PORT_DIPNAME( 0xc0, 0x00, "Test Modes/Extended Time") PORT_DIPLOCATION("E3:7,8")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x40, "RAM/ROM Test" )
PORT_DIPSETTING( 0x80, "Input Test" )
PORT_DIPSETTING( 0xc0, "No Extended Time" )
INPUT_PORTS_END
void zzzap_state::zzzap_common(machine_config &config)
{
mw8080bw_root(config);
/* basic machine hardware */
m_maincpu->set_addrmap(AS_IO, &zzzap_state::io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(PERIOD_OF_555_MONOSTABLE(RES_M(1), CAP_U(1))); /* 1.1s */
/* add shifter */
MB14241(config, m_mb14241);
/* audio hardware handled by specific machine */
}
void zzzap_state::zzzap(machine_config &config)
{
zzzap_common(config);
/* audio hardware */
ZZZAP_AUDIO(config, "soundboard");
}
void zzzap_state::lagunar(machine_config &config)
{
zzzap_common(config);
/* audio hardware */
LAGUNAR_AUDIO(config, "soundboard");
}
/*************************************
*
* Amazing Maze (PCB #611)
*
*************************************/
/* schematic says 12.5 Hz, but R/C values shown give 8.5Hz */
#define MAZE_555_B1_PERIOD PERIOD_OF_555_ASTABLE(RES_K(33) /* R200 */, RES_K(68) /* R201 */, CAP_U(1) /* C201 */)
void mw8080bw_state::maze_update_discrete()
{
maze_write_discrete(m_maze_tone_timing_state);
}
TIMER_CALLBACK_MEMBER(mw8080bw_state::maze_tone_timing_timer_callback)
{
m_maze_tone_timing_state = !m_maze_tone_timing_state;
maze_write_discrete(m_maze_tone_timing_state);
}
MACHINE_START_MEMBER(mw8080bw_state,maze)
{
mw8080bw_state::machine_start();
/* create astable timer for IC B1 */
m_maze_tone_timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(mw8080bw_state::maze_tone_timing_timer_callback), this));
m_maze_tone_timer->adjust(MAZE_555_B1_PERIOD, 0, MAZE_555_B1_PERIOD);
/* initialize state of Tone Timing FF, IC C1 */
m_maze_tone_timing_state = 0;
/* setup for save states */
save_item(NAME(m_maze_tone_timing_state));
machine().save().register_postload(save_prepost_delegate(FUNC(mw8080bw_state::maze_update_discrete), this));
}
void mw8080bw_state::maze_coin_counter_w(uint8_t data)
{
/* the data is not used, just pulse the counter */
machine().bookkeeping().coin_counter_w(0, 0);
machine().bookkeeping().coin_counter_w(0, 1);
}
void mw8080bw_state::maze_io_w(offs_t offset, uint8_t data)
{
if (offset & 0x01) maze_coin_counter_w(data);
if (offset & 0x02) m_watchdog->watchdog_reset();
}
void mw8080bw_state::maze_io_map(address_map &map)
{
map.global_mask(0x3);
map(0x00, 0x00).portr("IN0");
map(0x01, 0x01).portr("IN1");
/* no decoder, just a couple of AND gates */
map(0x00, 0x03).w(FUNC(mw8080bw_state::maze_io_w));
}
static INPUT_PORTS_START( maze )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_PLAYER(1)
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_PLAYER(1)
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2)
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2)
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_PLAYER(2)
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNUSED ) /* labeled 'Not Used' */
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_COIN1 )
PORT_DIPNAME( 0x30, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN1", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("SW:1,2")
PORT_DIPSETTING( 0x10, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x30, DEF_STR( 2C_3C ) )
PORT_DIPSETTING( 0x20, DEF_STR( 1C_2C ) )
PORT_DIPNAME( 0x40, 0x40, "2 Player Game Time" ) PORT_CONDITION("IN1", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("SW:3")
PORT_DIPSETTING( 0x40, "4 minutes" )
PORT_DIPSETTING( 0x00, "6 minutes" )
PORT_SERVICE_DIPLOC( 0x80, IP_ACTIVE_HIGH, "SW:4" )
INPUT_PORTS_END
void mw8080bw_state::maze(machine_config &config)
{
mw8080bw_root(config);
/* basic machine hardware */
m_maincpu->set_addrmap(AS_IO, &mw8080bw_state::maze_io_map);
MCFG_MACHINE_START_OVERRIDE(mw8080bw_state,maze)
WATCHDOG_TIMER(config, m_watchdog).set_time(PERIOD_OF_555_MONOSTABLE(RES_K(270), CAP_U(10))); /* 2.97s */
/* audio hardware */
maze_audio(config);
}
/*************************************
*
* Boot Hill (PCB #612)
*
*************************************/
void boothill_state::machine_start()
{
mw8080bw_state::machine_start();
m_rev_shift_res = 0U;
save_item(NAME(m_rev_shift_res));
}
u8 boothill_state::reversible_shift_result_r()
{
return m_rev_shift_res ? mw8080bw_shift_result_rev_r() : m_mb14241->shift_result_r();
}
void boothill_state::reversible_shift_count_w(u8 data)
{
m_mb14241->shift_count_w(data);
m_rev_shift_res = BIT(data, 3);
}
void boothill_state::boothill_io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).portr("IN0");
map(0x01, 0x01).mirror(0x04).portr("IN1");
map(0x02, 0x02).mirror(0x04).portr("IN2");
map(0x03, 0x03).mirror(0x04).r(FUNC(boothill_state::reversible_shift_result_r));
map(0x01, 0x01).w(FUNC(boothill_state::reversible_shift_count_w));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x03, 0x03).w("soundboard", FUNC(boothill_audio_device::write));
map(0x04, 0x04).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
map(0x05, 0x05).w("soundboard", FUNC(boothill_audio_device::tone_generator_lo_w));
map(0x06, 0x06).w("soundboard", FUNC(boothill_audio_device::tone_generator_hi_w));
}
static const ioport_value boothill_controller_table[7] =
{
0x00, 0x04, 0x06, 0x07, 0x03, 0x01, 0x05
};
static INPUT_PORTS_START( boothill )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(2)
PORT_BIT( 0x70, 0x30, IPT_POSITIONAL_V ) PORT_POSITIONS(7) PORT_REMAP_TABLE(boothill_controller_table) PORT_SENSITIVITY(5) PORT_KEYDELTA(10) PORT_CODE_DEC(KEYCODE_M) PORT_CODE_INC(KEYCODE_J) PORT_CENTERDELTA(0) PORT_PLAYER(2)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1)
PORT_BIT( 0x70, 0x30, IPT_POSITIONAL_V ) PORT_POSITIONS(7) PORT_REMAP_TABLE(boothill_controller_table) PORT_SENSITIVITY(5) PORT_KEYDELTA(10) PORT_CODE_DEC(KEYCODE_N) PORT_CODE_INC(KEYCODE_H) PORT_CENTERDELTA(0) PORT_PLAYER(1)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_START("IN2")
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN2", 0x10, EQUALS, 0x00) PORT_DIPLOCATION("SW:1,2")
PORT_DIPSETTING( 0x02, "2 Coins per Player" )
PORT_DIPSETTING( 0x03, "2 Coins/1 or 2 Players" )
PORT_DIPSETTING( 0x00, "1 Coin per Player" )
PORT_DIPSETTING( 0x01, "1 Coin/1 or 2 Players" )
PORT_DIPNAME( 0x0c, 0x04, DEF_STR( Game_Time ) ) PORT_CONDITION("IN2", 0x10, EQUALS, 0x00) PORT_DIPLOCATION("SW:3,4")
PORT_DIPSETTING( 0x00, "60 seconds" )
PORT_DIPSETTING( 0x04, "70 seconds" )
PORT_DIPSETTING( 0x08, "80 seconds" )
PORT_DIPSETTING( 0x0c, "90 seconds" )
PORT_SERVICE_DIPLOC (0x10, IP_ACTIVE_HIGH, "SW:5" )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START2 )
INPUT_PORTS_END
void boothill_state::boothill(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &boothill_state::boothill_io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(PERIOD_OF_555_MONOSTABLE(RES_K(270), CAP_U(10))); // 2.97s
// add shifter
MB14241(config, m_mb14241);
// audio hardware
BOOTHILL_AUDIO(config, "soundboard");
}
/*************************************
*
* Checkmate (PCB #615)
*
*************************************/
void mw8080bw_state::checkmat_io_w(offs_t offset, uint8_t data)
{
if (offset & 0x01) checkmat_audio_w(data);
if (offset & 0x02) m_watchdog->watchdog_reset();
}
void mw8080bw_state::checkmat_io_map(address_map &map)
{
map.global_mask(0x3);
map(0x00, 0x00).portr("IN0");
map(0x01, 0x01).portr("IN1");
map(0x02, 0x02).portr("IN2");
map(0x03, 0x03).portr("IN3");
/* no decoder, just a couple of AND gates */
map(0x00, 0x03).w(FUNC(mw8080bw_state::checkmat_io_w));
}
static INPUT_PORTS_START( checkmat )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1)
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1)
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2)
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2)
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2)
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_PLAYER(3)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_PLAYER(3)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_PLAYER(3)
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(3)
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_PLAYER(4)
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_PLAYER(4)
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_PLAYER(4)
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(4)
PORT_START("IN2")
PORT_DIPNAME( 0x01, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("A4:1")
PORT_DIPSETTING( 0x00, "1 Coin/1 or 2 Players" )
PORT_DIPSETTING( 0x01, "1 Coin/1 or 2 Players, 2 Coins/3 or 4 Players" )
PORT_DIPNAME( 0x02, 0x00, DEF_STR( Unused ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("A4:2")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x02, DEF_STR( On ) )
PORT_DIPNAME( 0x0c, 0x04, "Rounds" ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("A4:3,4")
PORT_DIPSETTING( 0x00, "2" )
PORT_DIPSETTING( 0x04, "3" )
PORT_DIPSETTING( 0x08, "4" )
PORT_DIPSETTING( 0x0c, "5" )
PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unused ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("A4:5")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x10, DEF_STR( On ) )
PORT_DIPNAME( 0x60, 0x00, DEF_STR( Language ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("A4:6,7")
PORT_DIPSETTING( 0x00, DEF_STR( English ) )
PORT_DIPSETTING( 0x20, "Language 2" )
PORT_DIPSETTING( 0x40, "Language 3" )
PORT_DIPSETTING( 0x60, "Language 4" )
PORT_SERVICE_DIPLOC( 0x80, IP_ACTIVE_HIGH, "A4:8" )
PORT_START("IN3")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_START3 )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_START4 )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNUSED)
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_COIN1 )
PORT_START("R309")
PORT_ADJUSTER( 50, "Boom Volume" )
PORT_START("R411")
PORT_ADJUSTER( 50, "Tone Volume" )
INPUT_PORTS_END
void mw8080bw_state::checkmat(machine_config &config)
{
mw8080bw_root(config);
/* basic machine hardware */
m_maincpu->set_addrmap(AS_IO, &mw8080bw_state::checkmat_io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(PERIOD_OF_555_MONOSTABLE(RES_K(270), CAP_U(10))); /* 2.97s */
/* audio hardware */
checkmat_audio(config);
}
/*************************************
*
* Desert Gun / Road Runner (PCB #618)
*
*************************************/
void desertgu_state::machine_start()
{
mw8080bw_state::machine_start();
m_controller_select = 0U;
save_item(NAME(m_controller_select));
}
CUSTOM_INPUT_MEMBER(desertgu_state::gun_input_r)
{
return m_gun_port[m_controller_select]->read();
}
CUSTOM_INPUT_MEMBER(desertgu_state::dip_sw_0_1_r)
{
return m_dip_sw_0_1[m_controller_select]->read();
}
void desertgu_state::io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).r(FUNC(desertgu_state::mw8080bw_shift_result_rev_r));
map(0x01, 0x01).mirror(0x04).portr("IN0");
map(0x02, 0x02).mirror(0x04).portr("IN1");
map(0x03, 0x03).mirror(0x04).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x01, 0x01).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x03, 0x03).w("soundboard", FUNC(desertgu_audio_device::p1_w));
map(0x04, 0x04).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
map(0x05, 0x05).w("soundboard", FUNC(desertgu_audio_device::tone_generator_lo_w));
map(0x06, 0x06).w("soundboard", FUNC(desertgu_audio_device::tone_generator_hi_w));
map(0x07, 0x07).w("soundboard", FUNC(desertgu_audio_device::p2_w));
}
static INPUT_PORTS_START( desertgu )
PORT_START("IN0")
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(desertgu_state, gun_input_r)
PORT_START("IN1")
PORT_BIT( 0x03, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(desertgu_state, dip_sw_0_1_r)
PORT_DIPNAME( 0x0c, 0x00, DEF_STR( Language ) ) PORT_CONDITION("IN1", 0x30, NOTEQUALS, 0x30) PORT_DIPLOCATION("C2:5,6")
PORT_DIPSETTING( 0x00, DEF_STR( English ) )
PORT_DIPSETTING( 0x04, DEF_STR( German ) )
PORT_DIPSETTING( 0x08, DEF_STR( French ) )
PORT_DIPSETTING( 0x0c, "Danish" )
PORT_DIPNAME( 0x30, 0x10, "Extended Time At" ) PORT_DIPLOCATION("C2:7,8")
PORT_DIPSETTING( 0x00, "5000" )
PORT_DIPSETTING( 0x10, "7000" )
PORT_DIPSETTING( 0x20, "9000" )
PORT_DIPSETTING( 0x30, "Test Mode" )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 )
/* fake ports for reading the gun's X and Y axis */
PORT_START(DESERTGU_GUN_X_PORT_TAG)
PORT_BIT( 0xff, 0x4d, IPT_LIGHTGUN_X ) PORT_CROSSHAIR(X, 1.0, 0.0, 0) PORT_MINMAX(0x10,0x8e) PORT_SENSITIVITY(70) PORT_KEYDELTA(10)
PORT_START(DESERTGU_GUN_Y_PORT_TAG)
PORT_BIT( 0xff, 0x48, IPT_LIGHTGUN_Y ) PORT_CROSSHAIR(Y, 1.0, 0.0, 0) PORT_MINMAX(0x10,0x7f) PORT_SENSITIVITY(70) PORT_KEYDELTA(10)
/* D0 and D1 in the DIP SW input port can reflect two sets of switches depending on the controller
select bit. These two ports are fakes to handle this case */
PORT_START(DESERTGU_DIP_SW_0_1_SET_1_TAG)
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN1", 0x30, NOTEQUALS, 0x30) PORT_DIPLOCATION("C2:1,2")
PORT_DIPSETTING( 0x02, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x03, DEF_STR( 2C_3C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 1C_2C ) )
PORT_BIT( 0xfc, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START(DESERTGU_DIP_SW_0_1_SET_2_TAG)
PORT_DIPNAME( 0x03, 0x01, DEF_STR( Game_Time ) ) PORT_CONDITION("IN1", 0x30, NOTEQUALS, 0x30) PORT_DIPLOCATION("C2:3,4")
PORT_DIPSETTING( 0x00, "40 seconds + 30 extended" )
PORT_DIPSETTING( 0x01, "50 seconds + 30 extended" )
PORT_DIPSETTING( 0x02, "60 seconds + 30 extended" )
PORT_DIPSETTING( 0x03, "70 seconds + 30 extended" )
PORT_BIT( 0xfc, IP_ACTIVE_HIGH, IPT_UNUSED )
INPUT_PORTS_END
void desertgu_state::desertgu(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &desertgu_state::io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
// add shifter
MB14241(config, m_mb14241);
// audio hardware
DESERTGU_AUDIO(config, "soundboard").ctrl_sel_out().set([this] (int state) { m_controller_select = state ? 1U : 0U; });
}
/*************************************
*
* Double Play (PCB #619) / Extra Inning (PCB #642)
*
* This game comes in an upright and a cocktail cabinet.
* The upright one had a shared joystick and a hitting button for
* each player, while in the cocktail version each player
* had their own set of controls. The display is never flipped,
* as the two players sit diagonally across from each other.
*
*************************************/
#define DPLAY_CAB_TYPE_UPRIGHT (0)
#define DPLAY_CAB_TYPE_COCKTAIL (1)
CUSTOM_INPUT_MEMBER(dplay_state::dplay_pitch_left_input_r)
{
uint32_t ret;
if (m_cab_type->read() == DPLAY_CAB_TYPE_UPRIGHT)
return m_l_pitch->read();
else
return m_r_pitch->read();
return ret;
}
CUSTOM_INPUT_MEMBER(dplay_state::dplay_pitch_right_input_r)
{
return m_l_pitch->read();
}
void dplay_state::io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).portr("IN0");
map(0x01, 0x01).mirror(0x04).portr("IN1");
map(0x02, 0x02).mirror(0x04).portr("IN2");
map(0x03, 0x03).mirror(0x04).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x01, 0x01).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x03, 0x03).w("soundboard", FUNC(dplay_audio_device::write));
map(0x04, 0x04).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
map(0x05, 0x05).w("soundboard", FUNC(dplay_audio_device::tone_generator_lo_w));
map(0x06, 0x06).w("soundboard", FUNC(dplay_audio_device::tone_generator_hi_w));
}
static INPUT_PORTS_START( dplay )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("P1 Hit") PORT_PLAYER(1)
PORT_BIT( 0x7e, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(dplay_state, dplay_pitch_left_input_r)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("P2 Hit") PORT_PLAYER(2)
PORT_BIT( 0x7e, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(dplay_state, dplay_pitch_right_input_r)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START2 )
PORT_START("IN2")
PORT_DIPNAME( 0x07, 0x00, DEF_STR( Coinage )) PORT_CONDITION("IN2", 0x40, EQUALS, 0x40) PORT_DIPLOCATION("C1:1,2,3")
PORT_DIPSETTING( 0x05, "2 Coins/1 Inning/1 Player, 4 Coins/1 Inning/2 Players, 8 Coins/3 Innings/2 Players" )
PORT_DIPSETTING( 0x04, "1 Coin/1 Inning/1 Player, 2 Coins/1 Inning/2 Players, 4 Coins/3 Innings/2 Players" )
PORT_DIPSETTING( 0x02, "2 Coins per Inning" )
PORT_DIPSETTING( 0x03, "2 Coins/1 Inning, 4 Coins/3 Innings" )
PORT_DIPSETTING( 0x00, "1 Coin per Inning" )
// PORT_DIPSETTING( 0x06, "1 Coin per Inning" )
// PORT_DIPSETTING( 0x07, "1 Coin per Inning" )
PORT_DIPSETTING( 0x01, "1 Coin/1 Inning, 2 Coins/3 Innings" )
PORT_DIPNAME( 0x08, 0x00, DEF_STR( Unused ) ) PORT_CONDITION("IN2", 0x40, EQUALS, 0x40) PORT_DIPLOCATION("C1:4")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x08, DEF_STR( On ) )
PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unused ) ) PORT_CONDITION("IN2", 0x40, EQUALS, 0x40) PORT_DIPLOCATION("C1:5")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x10, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unused ) ) PORT_CONDITION("IN2", 0x40, EQUALS, 0x40) PORT_DIPLOCATION("C1:6")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x20, DEF_STR( On ) )
PORT_SERVICE_DIPLOC( 0x40, IP_ACTIVE_LOW, "C1:7" )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN1 )
// fake ports to handle the various input configurations based on cabinet type
PORT_START(DPLAY_L_PITCH_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("P1 Move Outfield Left") PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_NAME("P1 Move Outfield Right") PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_NAME("P1 Pitch Left") PORT_PLAYER(1)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_NAME("P1 Pitch Right") PORT_PLAYER(1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_NAME("P1 Pitch Slow") PORT_PLAYER(1)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_NAME("P1 Pitch Fast") PORT_PLAYER(1)
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START(DPLAY_R_PITCH_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("P2 Move Outfield Left") PORT_PLAYER(2)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_NAME("P2 Move Outfield Right") PORT_PLAYER(2)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_NAME("P2 Pitch Left") PORT_PLAYER(2)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_NAME("P2 Pitch Right") PORT_PLAYER(2)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_NAME("P2 Pitch Slow") PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_NAME("P2 Pitch Fast") PORT_PLAYER(2)
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
// fake port for cabinet type
PORT_START(DPLAY_CAB_TYPE_PORT_TAG)
PORT_CONFNAME( 0x01, DPLAY_CAB_TYPE_UPRIGHT, DEF_STR( Cabinet ) )
PORT_CONFSETTING( DPLAY_CAB_TYPE_UPRIGHT, DEF_STR( Upright ) )
PORT_CONFSETTING( DPLAY_CAB_TYPE_COCKTAIL, DEF_STR( Cocktail ) )
PORT_BIT( 0xfe, IP_ACTIVE_HIGH, IPT_UNUSED )
INPUT_PORTS_END
static INPUT_PORTS_START( einning )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("P1 Hit") PORT_PLAYER(1)
PORT_BIT( 0x7e, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(dplay_state, dplay_pitch_left_input_r)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("P2 Hit") PORT_PLAYER(2)
PORT_BIT( 0x7e, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(dplay_state, dplay_pitch_right_input_r)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START2 )
PORT_START("IN2")
PORT_DIPNAME( 0x07, 0x00, DEF_STR( Coinage )) PORT_CONDITION("IN2", 0x40, EQUALS, 0x40) PORT_DIPLOCATION("C1:1,2,3")
PORT_DIPSETTING( 0x05, "2 Coins/1 Inning/1 Player, 4 Coins/1 Inning/2 Players, 8 Coins/3 Innings/2 Players" )
PORT_DIPSETTING( 0x04, "1 Coin/1 Inning/1 Player, 2 Coins/1 Inning/2 Players, 4 Coins/3 Innings/2 Players" )
PORT_DIPSETTING( 0x02, "2 Coins per Inning" )
PORT_DIPSETTING( 0x03, "2 Coins/1 Inning, 4 Coins/3 Innings" )
PORT_DIPSETTING( 0x00, "1 Coin per Inning" )
// PORT_DIPSETTING( 0x06, "1 Coin per Inning" )
// PORT_DIPSETTING( 0x07, "1 Coin per Inning" )
PORT_DIPSETTING( 0x01, "1 Coin/1 Inning, 2 Coins/3 Innings" )
PORT_DIPNAME( 0x08, 0x00, "Wall Knock Out Behavior" ) PORT_CONDITION("IN2", 0x40, EQUALS, 0x40) PORT_DIPLOCATION("C1:4")
PORT_DIPSETTING( 0x00, "Individually" )
PORT_DIPSETTING( 0x08, "In Pairs" )
PORT_DIPNAME( 0x10, 0x00, "Double Score when Special Lit" ) PORT_CONDITION("IN2", 0x40, EQUALS, 0x40) PORT_DIPLOCATION("C1:5")
PORT_DIPSETTING( 0x00, "Home Run Only" )
PORT_DIPSETTING( 0x10, "Any Hit" )
PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unused ) ) PORT_CONDITION("IN2", 0x40, EQUALS, 0x40) PORT_DIPLOCATION("C1:6")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x20, DEF_STR( On ) )
PORT_SERVICE_DIPLOC( 0x40, IP_ACTIVE_LOW, "C1:7" )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN1 )
// fake ports to handle the various input configurations based on cabinet type
PORT_START(DPLAY_L_PITCH_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("P1 Move Outfield Left") PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_NAME("P1 Move Outfield Right") PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_NAME("P1 Pitch Left") PORT_PLAYER(1)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_NAME("P1 Pitch Right") PORT_PLAYER(1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_NAME("P1 Pitch Slow") PORT_PLAYER(1)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_NAME("P1 Pitch Fast") PORT_PLAYER(1)
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START(DPLAY_R_PITCH_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("P2 Move Outfield Left") PORT_PLAYER(2)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_NAME("P2 Move Outfield Right") PORT_PLAYER(2)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_NAME("P2 Pitch Left") PORT_PLAYER(2)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_NAME("P2 Pitch Right") PORT_PLAYER(2)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_NAME("P2 Pitch Slow") PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_NAME("P2 Pitch Fast") PORT_PLAYER(2)
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
// fake port for cabinet type
PORT_START(DPLAY_CAB_TYPE_PORT_TAG)
PORT_CONFNAME( 0x01, DPLAY_CAB_TYPE_UPRIGHT, DEF_STR( Cabinet ) )
PORT_CONFSETTING( DPLAY_CAB_TYPE_UPRIGHT, DEF_STR( Upright ) )
PORT_CONFSETTING( DPLAY_CAB_TYPE_COCKTAIL, DEF_STR( Cocktail ) )
PORT_BIT( 0xfe, IP_ACTIVE_HIGH, IPT_UNUSED )
INPUT_PORTS_END
void dplay_state::dplay(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &dplay_state::io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
// add shifter
MB14241(config, m_mb14241);
// audio hardware
DPLAY_AUDIO(config, "soundboard");
}
/*************************************
*
* Guided Missile (PCB #623)
*
*************************************/
void boothill_state::gmissile_io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).portr("IN0");
map(0x01, 0x01).mirror(0x04).portr("IN1");
map(0x02, 0x02).mirror(0x04).portr("IN2");
map(0x03, 0x03).mirror(0x04).r(FUNC(boothill_state::reversible_shift_result_r));
map(0x01, 0x01).w(FUNC(boothill_state::reversible_shift_count_w));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x03, 0x03).w("soundboard", FUNC(gmissile_audio_device::p1_w));
map(0x04, 0x04).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
map(0x05, 0x05).w("soundboard", FUNC(gmissile_audio_device::p2_w));
// also writes 0x00 to 0x06, but it is not connected
map(0x07, 0x07).w("soundboard", FUNC(gmissile_audio_device::p3_w));
}
static INPUT_PORTS_START( gmissile )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_PLAYER(2)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_PLAYER(2)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_START("IN2")
PORT_DIPNAME( 0x03, 0x03, DEF_STR( Coinage ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x80) PORT_DIPLOCATION("D1:1,2")
PORT_DIPSETTING( 0x01, "2 Coins per Player" )
PORT_DIPSETTING( 0x00, "2 Coins/1 or 2 Players" )
PORT_DIPSETTING( 0x03, "1 Coin per Player" )
PORT_DIPSETTING( 0x02, "1 Coin/1 or 2 Players" )
PORT_DIPNAME( 0x0c, 0x08, DEF_STR( Game_Time ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x80) PORT_DIPLOCATION("D1:3,4")
PORT_DIPSETTING( 0x00, "60 seconds + 30 extended" )
PORT_DIPSETTING( 0x08, "70 seconds + 35 extended" )
PORT_DIPSETTING( 0x04, "80 seconds + 40 extended" )
PORT_DIPSETTING( 0x0c, "90 seconds + 45 extended" )
PORT_DIPNAME( 0x30, 0x10, "Extended Time At" ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x80) PORT_DIPLOCATION("D1:5,6")
PORT_DIPSETTING( 0x00, "500" )
PORT_DIPSETTING( 0x20, "700" )
PORT_DIPSETTING( 0x10, "1000" )
PORT_DIPSETTING( 0x30, "1300" )
PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unused ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x80) PORT_DIPLOCATION("D1:7")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x40, DEF_STR( On ) )
PORT_SERVICE_DIPLOC( 0x80, IP_ACTIVE_LOW, "D1:8" )
INPUT_PORTS_END
void boothill_state::gmissile(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &boothill_state::gmissile_io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
// add shifter
MB14241(config, m_mb14241);
// audio hardware
GMISSILE_AUDIO(config, "soundboard");
}
/*************************************
*
* M-4 (PCB #626)
*
*************************************/
void boothill_state::m4_io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).portr("IN0");
map(0x01, 0x01).mirror(0x04).portr("IN1");
map(0x02, 0x02).mirror(0x04).portr("IN2");
map(0x03, 0x03).mirror(0x04).r(FUNC(boothill_state::reversible_shift_result_r));
map(0x01, 0x01).w(FUNC(boothill_state::reversible_shift_count_w));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x03, 0x03).w("soundboard", FUNC(m4_audio_device::p1_w));
map(0x04, 0x04).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
map(0x05, 0x05).w("soundboard", FUNC(m4_audio_device::p2_w));
}
static INPUT_PORTS_START( m4 )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_2WAY PORT_PLAYER(2)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_2WAY PORT_PLAYER(2)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("P2 Trigger") PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("P2 Reload") PORT_PLAYER(2)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_2WAY PORT_2WAY PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_2WAY PORT_2WAY PORT_PLAYER(1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("P1 Trigger") PORT_PLAYER(1)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("P1 Reload") PORT_PLAYER(1)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_START("IN2")
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN2", 0x10, EQUALS, 0x10) PORT_DIPLOCATION("C1:1,2")
PORT_DIPSETTING( 0x02, "2 Coins per Player" )
PORT_DIPSETTING( 0x03, "2 Coins/1 or 2 Players" )
PORT_DIPSETTING( 0x00, "1 Coin per Player" )
PORT_DIPSETTING( 0x01, "1 Coin/1 or 2 Players" )
PORT_DIPNAME( 0x0c, 0x04, DEF_STR( Game_Time ) ) PORT_CONDITION("IN2", 0x10, EQUALS, 0x10) PORT_DIPLOCATION("C1:3,4")
PORT_DIPSETTING( 0x00, "60 seconds" )
PORT_DIPSETTING( 0x04, "70 seconds" )
PORT_DIPSETTING( 0x08, "80 seconds" )
PORT_DIPSETTING( 0x0c, "90 seconds" )
PORT_SERVICE_DIPLOC( 0x10, IP_ACTIVE_LOW, "C1:5" )
PORT_DIPNAME( 0x20, 0x00, "Extended Play" ) PORT_DIPLOCATION("C1:6")
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0xc0, 0x00, "Extended Play At" ) PORT_DIPLOCATION("C1:8,7")
PORT_DIPSETTING( 0xc0, "70" )
PORT_DIPSETTING( 0x40, "80" )
PORT_DIPSETTING( 0x80, "100" )
PORT_DIPSETTING( 0x00, "110" )
INPUT_PORTS_END
void boothill_state::m4(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &boothill_state::m4_io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
// add shifter
MB14241(config, m_mb14241);
// audio hardware
M4_AUDIO(config, "soundboard");
}
/*************************************
*
* Clowns (PCB #630)
*
*************************************/
#define CLOWNS_CONTROLLER_P1_TAG ("CONTP1")
#define CLOWNS_CONTROLLER_P2_TAG ("CONTP2")
void clowns_state::machine_start()
{
mw8080bw_state::machine_start();
m_controller_select = 0U;
save_item(NAME(m_controller_select));
}
CUSTOM_INPUT_MEMBER(clowns_state::controller_r)
{
return m_controllers[m_controller_select]->read();
}
void clowns_state::clowns_io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).portr("IN0");
map(0x01, 0x01).mirror(0x04).portr("IN1");
map(0x02, 0x02).mirror(0x04).portr("IN2");
map(0x03, 0x03).mirror(0x04).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x01, 0x01).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x03, 0x03).w("soundboard", FUNC(clowns_audio_device::p1_w));
map(0x04, 0x04).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
map(0x05, 0x05).w("soundboard", FUNC(clowns_audio_device::tone_generator_lo_w));
map(0x06, 0x06).w("soundboard", FUNC(clowns_audio_device::tone_generator_hi_w));
map(0x07, 0x07).w("soundboard", FUNC(clowns_audio_device::p2_w));
}
static INPUT_PORTS_START( clowns )
PORT_START("IN0")
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(clowns_state, controller_r)
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED ) // not connected
PORT_START("IN2")
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("SW:1,2")
PORT_DIPSETTING( 0x03, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x02, DEF_STR( 2C_2C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 1C_2C ) )
PORT_DIPNAME( 0x0c, 0x00, "Bonus Game" ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("SW:3,4")
PORT_DIPSETTING( 0x00, "No Bonus" )
PORT_DIPSETTING( 0x04, "9000" )
PORT_DIPSETTING( 0x08, "11000" )
PORT_DIPSETTING( 0x0c, "13000" )
PORT_DIPNAME( 0x10, 0x00, "Balloon Resets" ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("SW:5")
PORT_DIPSETTING( 0x00, "Each Row" )
PORT_DIPSETTING( 0x10, "All Rows" )
PORT_DIPNAME( 0x20, 0x00, DEF_STR( Bonus_Life ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("SW:6")
PORT_DIPSETTING( 0x00, "3000" )
PORT_DIPSETTING( 0x20, "4000" )
PORT_DIPNAME( 0x40, 0x00, DEF_STR( Lives ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("SW:7")
PORT_DIPSETTING( 0x00, "3" )
PORT_DIPSETTING( 0x40, "4" )
// test mode - press coin button for input test
PORT_SERVICE_DIPLOC( 0x80, IP_ACTIVE_HIGH, "SW:8" )
// fake ports for two analog controls multiplexed
PORT_START(CLOWNS_CONTROLLER_P1_TAG)
PORT_BIT( 0xff, 0x7f, IPT_PADDLE ) PORT_MINMAX(0x01,0xfe) PORT_SENSITIVITY(100) PORT_KEYDELTA(10) PORT_CENTERDELTA(0) PORT_PLAYER(1)
PORT_START(CLOWNS_CONTROLLER_P2_TAG)
PORT_BIT( 0xff, 0x7f, IPT_PADDLE ) PORT_MINMAX(0x01,0xfe) PORT_SENSITIVITY(100) PORT_KEYDELTA(10) PORT_CENTERDELTA(0) PORT_PLAYER(2)
INPUT_PORTS_END
static INPUT_PORTS_START( clowns1 )
PORT_START("IN0")
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(clowns_state, controller_r)
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("IN2")
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("SW:1,2")
PORT_DIPSETTING( 0x03, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x02, DEF_STR( 2C_2C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 1C_2C ) )
PORT_DIPNAME( 0x0c, 0x04, DEF_STR( Lives ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("SW:3,4")
PORT_DIPSETTING( 0x00, "2" )
PORT_DIPSETTING( 0x04, "3" )
PORT_DIPSETTING( 0x08, "4" )
PORT_DIPSETTING( 0x0c, "5" )
PORT_DIPNAME( 0x10, 0x00, "Balloon Resets" ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("SW:5")
PORT_DIPSETTING( 0x00, "Each Row" )
PORT_DIPSETTING( 0x10, "All Rows" )
PORT_DIPNAME( 0x20, 0x00, DEF_STR( Bonus_Life ) ) PORT_CONDITION("IN2", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("SW:6")
PORT_DIPSETTING( 0x00, "3000" )
PORT_DIPSETTING( 0x20, "4000" )
PORT_DIPNAME( 0x40, 0x00, "Input Test" ) PORT_DIPLOCATION("SW:7")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x40, DEF_STR( On ) )
PORT_SERVICE_DIPLOC( 0x80, IP_ACTIVE_HIGH, "SW:8" )
PORT_START(CLOWNS_CONTROLLER_P1_TAG)
PORT_BIT( 0xff, 0x7f, IPT_PADDLE ) PORT_MINMAX(0x01,0xfe) PORT_SENSITIVITY(100) PORT_KEYDELTA(10) PORT_CENTERDELTA(0) PORT_PLAYER(1)
PORT_START(CLOWNS_CONTROLLER_P2_TAG)
PORT_BIT( 0xff, 0x7f, IPT_PADDLE ) PORT_MINMAX(0x01,0xfe) PORT_SENSITIVITY(100) PORT_KEYDELTA(10) PORT_CENTERDELTA(0) PORT_PLAYER(2)
INPUT_PORTS_END
void clowns_state::clowns(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &clowns_state::clowns_io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
// add shifter
MB14241(config, m_mb14241);
// audio hardware
CLOWNS_AUDIO(config, "soundboard").ctrl_sel_out().set([this] (int state) { m_controller_select = state ? 1U : 0U; });
}
/*************************************
*
* Space Walk (PCB #640)
*
*************************************/
void clowns_state::spacwalk_io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).portr("IN0");
map(0x01, 0x01).portr("IN1");
map(0x02, 0x02).portr("IN2");
map(0x03, 0x03).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x01, 0x01).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x03, 0x03).w("soundboard", FUNC(spacwalk_audio_device::p1_w));
map(0x04, 0x04).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
map(0x05, 0x05).w("soundboard", FUNC(spacwalk_audio_device::tone_generator_lo_w));
map(0x06, 0x06).w("soundboard", FUNC(spacwalk_audio_device::tone_generator_hi_w));
map(0x07, 0x07).w("soundboard", FUNC(spacwalk_audio_device::p2_w));
}
static INPUT_PORTS_START( spacwalk )
PORT_START("IN0")
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(clowns_state, controller_r)
PORT_START("IN1")
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_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
// 8 pin DIP Switch on location C2 on PCB A084-90700-D640
/* PCB picture also shows a 2nd DIP Switch on location B2, supposedly for language selection,
but ROM contents suggests it's not connected (no different languages or unmapped reads) */
PORT_START("IN2")
PORT_DIPNAME( 0x03, 0x01, DEF_STR( Game_Time ) ) PORT_DIPLOCATION("C2:1,2")
PORT_DIPSETTING( 0x03, "40 seconds + 20 extended" ) PORT_CONDITION("IN2", 0x30, NOTEQUALS, 0x00) // 45 + 20 for 2 players
PORT_DIPSETTING( 0x02, "50 seconds + 25 extended" ) PORT_CONDITION("IN2", 0x30, NOTEQUALS, 0x00) // 60 + 30 for 2 players
PORT_DIPSETTING( 0x01, "60 seconds + 30 extended" ) PORT_CONDITION("IN2", 0x30, NOTEQUALS, 0x00) // 75 + 35 for 2 players
PORT_DIPSETTING( 0x00, "70 seconds + 35 extended" ) PORT_CONDITION("IN2", 0x30, NOTEQUALS, 0x00) // 90 + 45 for 2 players
PORT_DIPSETTING( 0x03, "40 seconds" ) PORT_CONDITION("IN2", 0x30, EQUALS, 0x00)
PORT_DIPSETTING( 0x02, "50 seconds" ) PORT_CONDITION("IN2", 0x30, EQUALS, 0x00)
PORT_DIPSETTING( 0x01, "60 seconds" ) PORT_CONDITION("IN2", 0x30, EQUALS, 0x00)
PORT_DIPSETTING( 0x00, "70 seconds" ) PORT_CONDITION("IN2", 0x30, EQUALS, 0x00)
PORT_DIPNAME( 0x0c, 0x00, DEF_STR( Coinage ) ) PORT_DIPLOCATION("C2:3,4")
PORT_DIPSETTING( 0x00, "1 Coin per Player" )
PORT_DIPSETTING( 0x04, "1 Coin/1 or 2 Players" )
PORT_DIPSETTING( 0x0c, "2 Coins per Player" )
PORT_DIPSETTING( 0x08, "2 Coins/1 or 2 Players" )
PORT_DIPNAME( 0x30, 0x00, "Extended Time At" ) PORT_DIPLOCATION("C2:5,6")
PORT_DIPSETTING( 0x00, DEF_STR( None ) )
PORT_DIPSETTING( 0x10, "5000" )
PORT_DIPSETTING( 0x20, "6000" )
PORT_DIPSETTING( 0x30, "7000" )
PORT_DIPNAME( 0x40, 0x00, "Springboard Alignment" ) PORT_DIPLOCATION("C2:7")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x40, DEF_STR( On ) )
PORT_SERVICE_DIPLOC(0x80, IP_ACTIVE_HIGH, "C2:8" ) // RAM-ROM Test
// fake ports for two analog controls multiplexed
PORT_START(CLOWNS_CONTROLLER_P1_TAG)
PORT_BIT( 0xff, 0x7f, IPT_PADDLE ) PORT_MINMAX(0x01,0xfe) PORT_SENSITIVITY(100) PORT_KEYDELTA(10) PORT_CENTERDELTA(0) PORT_PLAYER(1)
PORT_START(CLOWNS_CONTROLLER_P2_TAG)
PORT_BIT( 0xff, 0x7f, IPT_PADDLE ) PORT_MINMAX(0x01,0xfe) PORT_SENSITIVITY(100) PORT_KEYDELTA(10) PORT_CENTERDELTA(0) PORT_PLAYER(2)
INPUT_PORTS_END
void clowns_state::spacwalk(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &clowns_state::spacwalk_io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
// add shifter
MB14241(config, m_mb14241);
// audio hardware
SPACWALK_AUDIO(config, "soundboard").ctrl_sel_out().set([this] (int state) { m_controller_select = state ? 1U : 0U; });
}
/*************************************
*
* Shuffleboard (PCB #643)
*
*************************************/
void mw8080bw_state::shuffle_io_map(address_map &map)
{
map.global_mask(0xf); /* yes, 4, and no mirroring on the read handlers */
map(0x01, 0x01).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x02, 0x02).portr("IN0");
map(0x03, 0x03).r(FUNC(mw8080bw_state::mw8080bw_shift_result_rev_r));
map(0x04, 0x04).portr("IN1");
map(0x05, 0x05).portr("IN2");
map(0x06, 0x06).portr("IN3");
map(0x01, 0x01).mirror(0x08).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x02, 0x02).mirror(0x08).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x04, 0x04).mirror(0x08).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
map(0x05, 0x05).mirror(0x08).w(FUNC(mw8080bw_state::shuffle_audio_1_w));
map(0x06, 0x06).mirror(0x08).w(FUNC(mw8080bw_state::shuffle_audio_2_w));
}
static INPUT_PORTS_START( shuffle )
PORT_START("IN0")
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Language ) ) PORT_CONDITION("IN0", 0x80, EQUALS, 0x80) PORT_DIPLOCATION("B3:1,2")
PORT_DIPSETTING( 0x00, DEF_STR( English ) )
PORT_DIPSETTING( 0x01, DEF_STR( French ) )
PORT_DIPSETTING( 0x02, DEF_STR( German ) )
/* PORT_DIPSETTING( 0x03, DEF_STR( German ) ) */
PORT_DIPNAME( 0x0c, 0x04, "Points to Win" ) PORT_CONDITION("IN0", 0x80, EQUALS, 0x80) PORT_DIPLOCATION("B3:3,4")
PORT_DIPSETTING( 0x00, "Game 1 = 25, Game 2 = 11" )
PORT_DIPSETTING( 0x04, "Game 1 = 35, Game 2 = 15" )
PORT_DIPSETTING( 0x08, "Game 1 = 40, Game 2 = 18" )
PORT_DIPSETTING( 0x0c, "Game 1 = 50, Game 2 = 21" )
PORT_DIPNAME( 0x30, 0x10, DEF_STR( Coinage ) ) PORT_CONDITION("IN0", 0x80, EQUALS, 0x80) PORT_DIPLOCATION("B3:5,6")
PORT_DIPSETTING( 0x30, "2 Coins per Player" )
PORT_DIPSETTING( 0x20, "2 Coins/1 or 2 Players" )
PORT_DIPSETTING( 0x10, "1 Coin per Player" )
PORT_DIPSETTING( 0x00, "1 Coin/1 or 2 Players" )
PORT_DIPNAME( 0x40, 0x40, "Time Limit" ) PORT_CONDITION("IN0", 0x80, EQUALS, 0x80) PORT_DIPLOCATION("B3:7")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x40, DEF_STR( On ) )
PORT_SERVICE_DIPLOC( 0x80, IP_ACTIVE_LOW, "B3:8" )
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON1) PORT_NAME("Game Select")
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) /* not connected */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) /* not connected */
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED ) /* not connected */
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED ) /* not connected */
PORT_START("IN2")
PORT_BIT( 0xff, 0, IPT_TRACKBALL_Y ) PORT_SENSITIVITY(10) PORT_KEYDELTA(50) PORT_PLAYER(1)
PORT_START("IN3")
PORT_BIT( 0xff, 0, IPT_TRACKBALL_X ) PORT_SENSITIVITY(10) PORT_KEYDELTA(10) PORT_REVERSE PORT_PLAYER(1)
INPUT_PORTS_END
void mw8080bw_state::shuffle(machine_config &config)
{
mw8080bw_root(config);
/* basic machine hardware */
m_maincpu->set_addrmap(AS_IO, &mw8080bw_state::shuffle_io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
/* add shifter */
MB14241(config, m_mb14241);
/* audio hardware */
shuffle_audio(config);
}
/*************************************
*
* Dog Patch (PCB #644)
*
*************************************/
void mw8080bw_state::dogpatch_io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).portr("IN0");
map(0x01, 0x01).mirror(0x04).portr("IN1");
map(0x02, 0x02).mirror(0x04).portr("IN2");
map(0x03, 0x03).mirror(0x04).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x01, 0x01).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x03, 0x03).w("soundboard", FUNC(dogpatch_audio_device::write));
map(0x04, 0x04).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
map(0x05, 0x05).w("soundboard", FUNC(dogpatch_audio_device::tone_generator_lo_w));
map(0x06, 0x06).w("soundboard", FUNC(dogpatch_audio_device::tone_generator_hi_w));
}
static const ioport_value dogpatch_controller_table[7] =
{
0x07, 0x06, 0x04, 0x05, 0x01, 0x00, 0x02
};
static INPUT_PORTS_START( dogpatch )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x70, 0x30, IPT_POSITIONAL_V ) PORT_POSITIONS(7) PORT_REMAP_TABLE(dogpatch_controller_table) PORT_SENSITIVITY(5) PORT_KEYDELTA(10) PORT_CODE_DEC(KEYCODE_M) PORT_CODE_INC(KEYCODE_J) PORT_CENTERDELTA(0) PORT_REVERSE PORT_PLAYER(2)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x70, 0x30, IPT_POSITIONAL_V ) PORT_POSITIONS(7) PORT_REMAP_TABLE(dogpatch_controller_table) PORT_SENSITIVITY(5) PORT_KEYDELTA(10) PORT_CODE_DEC(KEYCODE_N) PORT_CODE_INC(KEYCODE_H) PORT_CENTERDELTA(0) PORT_PLAYER(1)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_START("IN2")
PORT_DIPNAME( 0x03, 0x02, "Number of Cans" ) PORT_CONDITION("IN2", 0x20, EQUALS, 0x20) PORT_DIPLOCATION("SW:1,2")
PORT_DIPSETTING( 0x03, "10" )
PORT_DIPSETTING( 0x02, "15" )
PORT_DIPSETTING( 0x01, "20" )
PORT_DIPSETTING( 0x00, "25" )
PORT_DIPNAME( 0x0c, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN2", 0x20, EQUALS, 0x20) PORT_DIPLOCATION("SW:3,4")
PORT_DIPSETTING( 0x08, "2 Coins per Player" )
PORT_DIPSETTING( 0x0c, "2 Coins/1 or 2 Players" )
PORT_DIPSETTING( 0x00, "1 Coin per Player" )
PORT_DIPSETTING( 0x04, "1 Coin/1 or 2 Players" )
PORT_DIPNAME( 0x10, 0x10, "Extended Time Reward" ) PORT_CONDITION("IN2", 0x20, EQUALS, 0x20) PORT_DIPLOCATION("SW:5")
PORT_DIPSETTING( 0x10, "3 extra cans" )
PORT_DIPSETTING( 0x00, "5 extra cans" )
PORT_SERVICE_DIPLOC( 0x20, IP_ACTIVE_LOW, "SW:6" )
PORT_DIPNAME( 0xc0, 0x40, "Extended Time At" ) PORT_CONDITION("IN2", 0x20, EQUALS, 0x20) PORT_DIPLOCATION("SW:7,8")
PORT_DIPSETTING( 0xc0, "150" )
PORT_DIPSETTING( 0x80, "175" )
PORT_DIPSETTING( 0x40, "225" )
PORT_DIPSETTING( 0x00, "275" )
INPUT_PORTS_END
void mw8080bw_state::dogpatch(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &mw8080bw_state::dogpatch_io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
// add shifter
MB14241(config, m_mb14241);
// audio hardware
DOGPATCH_AUDIO(config, "soundboard");
}
/*************************************
*
* Space Encounters (PCB #645)
*
*************************************/
void spcenctr_state::machine_start()
{
mw8080bw_state::machine_start();
m_trench_width = 0U;
m_trench_center = 0U;
std::fill(std::begin(m_trench_slope), std::end(m_trench_slope), 0U);
m_bright_control = 0U;
m_brightness = 0U;
save_item(NAME(m_trench_width));
save_item(NAME(m_trench_center));
save_item(NAME(m_trench_slope));
save_item(NAME(m_bright_control));
save_item(NAME(m_brightness));
}
void spcenctr_state::io_w(offs_t offset, u8 data)
{ // A7 A6 A5 A4 A3 A2 A1 A0
if ((offset & 0x07) == 0x00)
// hex flip-flop B5
// bit 3: /BRITE
// bit 2: /NO_PLANET
// bit 1: /SET_WSL
// bit 0: COIN_COUNTER
m_bright_control = BIT(~data, 3); // - - - - - 0 0 0
else if ((offset & 0x5f) == 0x01)
m_soundboard->p1_w(data); // - 0 - 0 0 0 0 1
else if ((offset & 0x5f) == 0x09)
m_soundboard->p2_w(data); // - 0 - 0 1 0 0 1
else if ((offset & 0x5f) == 0x11)
m_soundboard->p3_w(data); // - 0 - 1 0 0 0 1
else if ((offset & 0x07) == 0x02)
m_watchdog->watchdog_reset(); // - - - - - 0 1 0
else if ((offset & 0x07) == 0x03)
{ // - - - - - 0 1 1
m_trench_slope[bitswap<4>(offset, 7, 6, 4, 3)] = data;
}
else if ((offset & 0x07) == 0x04)
m_trench_center = data; // - - - - - 1 0 0
else if ((offset & 0x07) == 0x07)
m_trench_width = data; // - - - - - 1 1 1
else
logerror("%s: Unmapped I/O port write to %02x = %02x\n", machine().describe_context(), offset, data);
}
void spcenctr_state::io_map(address_map &map)
{
map.global_mask(0xff);
map(0x00, 0x00).mirror(0xfc).portr("IN0");
map(0x01, 0x01).mirror(0xfc).portr("IN1");
map(0x02, 0x02).mirror(0xfc).portr("IN2");
map(0x03, 0x03).mirror(0xfc).nopr();
map(0x00, 0xff).w(FUNC(spcenctr_state::io_w)); // complicated addressing logic
}
static const ioport_value spcenctr_controller_table[] =
{
0x3f, 0x3e, 0x3c, 0x3d, 0x39, 0x38, 0x3a, 0x3b,
0x33, 0x32, 0x30, 0x31, 0x35, 0x34, 0x36, 0x37,
0x27, 0x26, 0x24, 0x25, 0x21, 0x20, 0x22, 0x23,
0x2b, 0x2a, 0x28, 0x29, 0x2d, 0x2c, 0x2e, 0x2f,
0x0f, 0x0e, 0x0c, 0x0d, 0x09, 0x08, 0x0a, 0x0b,
0x03, 0x02, 0x00, 0x01, 0x05, 0x04, 0x06, 0x07,
0x17, 0x16, 0x14, 0x15, 0x11, 0x10, 0x12, 0x13,
0x1b, 0x1a, 0x18, 0x19, 0x1d, 0x1c, 0x1e, 0x1f
};
static INPUT_PORTS_START( spcenctr )
PORT_START("IN0")
/* horizontal range is limited to 12 - 46 by stoppers on the control for 35 positions */
PORT_BIT( 0x3f, 17, IPT_POSITIONAL ) PORT_POSITIONS(35) PORT_REMAP_TABLE(spcenctr_controller_table+12) PORT_SENSITIVITY(5) PORT_KEYDELTA(10) PORT_CENTERDELTA(0) PORT_REVERSE /* 6 bit horiz encoder */
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_START("IN1")
/* vertical range is limited to 22 - 41 by stoppers on the control for 20 positions */
PORT_BIT( 0x3f, 19, IPT_POSITIONAL_V ) PORT_POSITIONS(20) PORT_REMAP_TABLE(spcenctr_controller_table+22) PORT_SENSITIVITY(5) PORT_KEYDELTA(10) PORT_CENTERDELTA(0) PORT_REVERSE /* 6 bit vert encoder - pushing control in makes ship move faster */
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED ) /* not connected */
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED ) /* marked as COIN #2, but the software never reads it */
PORT_START("IN2")
PORT_DIPNAME( 0x03, 0x02, DEF_STR( Bonus_Life ) ) PORT_CONDITION("IN2", 0x30, EQUALS, 0x00) PORT_DIPLOCATION("F3:1,2")
PORT_DIPSETTING( 0x00, "2000 4000 8000" )
PORT_DIPSETTING( 0x01, "3000 6000 12000" )
PORT_DIPSETTING( 0x02, "4000 8000 16000" )
PORT_DIPSETTING( 0x03, "5000 10000 20000" )
PORT_DIPNAME( 0x0c, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN2", 0x30, NOTEQUALS, 0x10) PORT_DIPLOCATION("F3:3,4")
PORT_DIPSETTING( 0x04, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x0c, DEF_STR( 2C_3C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 1C_3C ) )
PORT_DIPNAME( 0x30, 0x00, "Bonus/Test Mode" ) PORT_DIPLOCATION("F3:5,6")
PORT_DIPSETTING( 0x00, "Bonus On" )
PORT_DIPSETTING( 0x30, "Bonus Off" )
PORT_DIPSETTING( 0x20, "Cross Hatch" )
PORT_DIPSETTING( 0x10, "Test Mode" )
PORT_DIPNAME( 0xc0, 0x40, "Time" ) PORT_CONDITION("IN2", 0x30, NOTEQUALS, 0x10) PORT_DIPLOCATION("F3:7,8")
PORT_DIPSETTING( 0x00, "45" )
PORT_DIPSETTING( 0x40, "60" )
PORT_DIPSETTING( 0x80, "75" )
PORT_DIPSETTING( 0xc0, "90" )
INPUT_PORTS_END
void spcenctr_state::spcenctr(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &spcenctr_state::io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
// video hardware
m_screen->set_screen_update(FUNC(spcenctr_state::screen_update));
// audio hardware
SPCENCTR_AUDIO(config, m_soundboard);
}
/*************************************
*
* Phantom II (PCB #652)
*
*************************************/
MACHINE_START_MEMBER(mw8080bw_state,phantom2)
{
mw8080bw_state::machine_start();
/* setup for save states */
save_item(NAME(m_phantom2_cloud_counter));
m_phantom2_cloud_counter = 0;
}
void mw8080bw_state::phantom2_io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).r(FUNC(mw8080bw_state::mw8080bw_shift_result_rev_r));
map(0x01, 0x01).mirror(0x04).portr("IN0");
map(0x02, 0x02).mirror(0x04).portr("IN1");
map(0x03, 0x03).mirror(0x04).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x01, 0x01).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x04, 0x04).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
map(0x05, 0x05).w("soundboard", FUNC(phantom2_audio_device::p1_w));
map(0x06, 0x06).w("soundboard", FUNC(phantom2_audio_device::p2_w));
}
static INPUT_PORTS_START( phantom2 )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED ) /* not connected */
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED ) /* not connected */
PORT_START("IN1")
PORT_DIPNAME( 0x01, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN1", 0x20, EQUALS, 0x20) PORT_DIPLOCATION("SW:1")
PORT_DIPSETTING( 0x01, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPNAME( 0x06, 0x06, DEF_STR( Game_Time ) ) PORT_CONDITION("IN1", 0x20, EQUALS, 0x20) PORT_DIPLOCATION("SW:2,3")
PORT_DIPSETTING( 0x00, "45 seconds + 20 extended (at 20 points)" )
PORT_DIPSETTING( 0x02, "60 seconds + 25 extended (at 25 points)" )
PORT_DIPSETTING( 0x04, "75 seconds + 30 extended (at 30 points)" )
PORT_DIPSETTING( 0x06, "90 seconds + 35 extended (at 35 points)" )
PORT_DIPNAME( 0x08, 0x00, DEF_STR( Unused ) ) PORT_CONDITION("IN1", 0x20, EQUALS, 0x20) PORT_DIPLOCATION("SW:4")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x08, DEF_STR( On ) )
PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unused ) ) PORT_CONDITION("IN1", 0x20, EQUALS, 0x20) PORT_DIPLOCATION("SW:5")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x10, DEF_STR( On ) )
PORT_SERVICE_DIPLOC( 0x20, IP_ACTIVE_LOW, "SW:6" )
PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unused ) ) PORT_CONDITION("IN1", 0x20, EQUALS, 0x20) PORT_DIPLOCATION("SW:7")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x40, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x00, DEF_STR( Unused ) ) PORT_CONDITION("IN1", 0x20, EQUALS, 0x20) PORT_DIPLOCATION("SW:8")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x80, DEF_STR( On ) )
INPUT_PORTS_END
void mw8080bw_state::phantom2(machine_config &config)
{
mw8080bw_root(config);
/* basic machine hardware */
m_maincpu->set_addrmap(AS_IO, &mw8080bw_state::phantom2_io_map);
MCFG_MACHINE_START_OVERRIDE(mw8080bw_state,phantom2)
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
/* video hardware */
m_screen->set_screen_update(FUNC(mw8080bw_state::screen_update_phantom2));
m_screen->screen_vblank().set(FUNC(mw8080bw_state::screen_vblank_phantom2));
/* add shifter */
MB14241(config, m_mb14241);
/* audio hardware */
PHANTOM2_AUDIO(config, "soundboard");
}
/*************************************
*
* Bowling Alley (PCB #730)
*
*************************************/
uint8_t mw8080bw_state::bowler_shift_result_r()
{
/* ZV - not too sure why this is needed, I don't see
anything unusual on the schematics that would cause
the bits to flip */
return ~m_mb14241->shift_result_r();
}
void mw8080bw_state::bowler_lights_1_w(uint8_t data)
{
output().set_value("200_LEFT_LIGHT", (data >> 0) & 0x01);
output().set_value("400_LEFT_LIGHT", (data >> 1) & 0x01);
output().set_value("500_LEFT_LIGHT", (data >> 2) & 0x01);
output().set_value("700_LIGHT", (data >> 3) & 0x01);
output().set_value("500_RIGHT_LIGHT", (data >> 4) & 0x01);
output().set_value("400_RIGHT_LIGHT", (data >> 5) & 0x01);
output().set_value("200_RIGHT_LIGHT", (data >> 6) & 0x01);
output().set_value("X_LEFT_LIGHT", (data >> 7) & 0x01);
output().set_value("X_RIGHT_LIGHT", (data >> 7) & 0x01);
}
void mw8080bw_state::bowler_lights_2_w(uint8_t data)
{
output().set_value("REGULATION_GAME_LIGHT", ( data >> 0) & 0x01);
output().set_value("FLASH_GAME_LIGHT", (~data >> 0) & 0x01);
output().set_value("STRAIGHT_BALL_LIGHT", ( data >> 1) & 0x01);
output().set_value("HOOK_BALL_LIGHT", ( data >> 2) & 0x01);
output().set_value("SELECT_GAME_LIGHT", ( data >> 3) & 0x01);
/* D4-D7 are not connected */
}
void mw8080bw_state::bowler_io_map(address_map &map)
{
map.global_mask(0xf); /* no masking on the reads, all 4 bits are decoded */
map(0x01, 0x01).r(FUNC(mw8080bw_state::bowler_shift_result_r));
map(0x02, 0x02).portr("IN0");
map(0x03, 0x03).r(FUNC(mw8080bw_state::mw8080bw_shift_result_rev_r));
map(0x04, 0x04).portr("IN1");
map(0x05, 0x05).portr("IN2");
map(0x06, 0x06).portr("IN3");
map(0x01, 0x01).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x04, 0x04).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
map(0x05, 0x05).w(FUNC(mw8080bw_state::bowler_audio_1_w));
map(0x06, 0x06).w(FUNC(mw8080bw_state::bowler_audio_2_w));
map(0x07, 0x07).w(FUNC(mw8080bw_state::bowler_lights_1_w));
map(0x08, 0x08).w(FUNC(mw8080bw_state::bowler_audio_3_w));
map(0x09, 0x09).w(FUNC(mw8080bw_state::bowler_audio_4_w));
map(0x0a, 0x0a).w(FUNC(mw8080bw_state::bowler_audio_5_w));
map(0x0e, 0x0e).w(FUNC(mw8080bw_state::bowler_lights_2_w));
map(0x0f, 0x0f).w(FUNC(mw8080bw_state::bowler_audio_6_w));
}
static INPUT_PORTS_START( bowler )
PORT_START("IN0")
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Language ) ) PORT_CONDITION("IN0", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("B3:1,2")
PORT_DIPSETTING( 0x00, DEF_STR( English ) )
PORT_DIPSETTING( 0x01, DEF_STR( French ) )
PORT_DIPSETTING( 0x02, DEF_STR( German ) )
/*PORT_DIPSETTING( 0x03, DEF_STR( German ) ) */
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Demo_Sounds ) ) PORT_CONDITION("IN0", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("B3:3")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x04, DEF_STR( On ) ) /* every 17 minutes */
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Game_Time ) ) PORT_CONDITION("IN0", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("B3:4")
PORT_DIPSETTING( 0x00, "No Limit" )
PORT_DIPSETTING( 0x08, "5 Minutes" )
PORT_DIPNAME( 0x10, 0x00, DEF_STR( Coinage ) ) PORT_CONDITION("IN0", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("B3:5")
PORT_DIPSETTING( 0x10, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPNAME( 0x20, 0x20, DEF_STR( Difficulty ) ) PORT_CONDITION("IN0", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("B3:6")
PORT_DIPSETTING( 0x20, DEF_STR( Easy ) )
PORT_DIPSETTING( 0x00, DEF_STR( Hard ) )
PORT_DIPNAME( 0x40, 0x00, DEF_STR( Cabinet ) ) PORT_CONDITION("IN0", 0x80, EQUALS, 0x00) PORT_DIPLOCATION("B3:7")
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x40, "Cocktail (not functional)" )
PORT_SERVICE_DIPLOC( 0x80, IP_ACTIVE_HIGH, "B3:8" )
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_NAME("Hook/Straight") PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_NAME("Game Select") PORT_PLAYER(1)
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("IN2")
PORT_BIT( 0xff, 0, IPT_TRACKBALL_Y ) PORT_SENSITIVITY(10) PORT_KEYDELTA(50) PORT_REVERSE PORT_PLAYER(1)
PORT_START("IN3")
PORT_BIT( 0xff, 0, IPT_TRACKBALL_X ) PORT_SENSITIVITY(10) PORT_KEYDELTA(10) PORT_PLAYER(1)
INPUT_PORTS_END
void mw8080bw_state::bowler(machine_config &config)
{
mw8080bw_root(config);
/* basic machine hardware */
m_maincpu->set_addrmap(AS_IO, &mw8080bw_state::bowler_io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
/* add shifter */
MB14241(config, m_mb14241);
/* audio hardware */
bowler_audio(config);
}
/*************************************
*
* Space Invaders (PCB #739)
*
*************************************/
MACHINE_START_MEMBER(mw8080bw_state,invaders)
{
mw8080bw_state::machine_start();
m_flip_screen = 0U;
save_item(NAME(m_flip_screen));
}
CUSTOM_INPUT_MEMBER(mw8080bw_state::invaders_sw6_sw7_r)
{
// upright PCB : switches visible
// cocktail PCB: HI
if (invaders_is_cabinet_cocktail())
return 0x03;
else
return ioport(INVADERS_SW6_SW7_PORT_TAG)->read();
}
CUSTOM_INPUT_MEMBER(mw8080bw_state::invaders_sw5_r)
{
// upright PCB : switch visible
// cocktail PCB: HI
if (invaders_is_cabinet_cocktail())
return 0x01;
else
return ioport(INVADERS_SW5_PORT_TAG)->read();
}
CUSTOM_INPUT_MEMBER(mw8080bw_state::invaders_in0_control_r)
{
// upright PCB : P1 controls
// cocktail PCB: HI
if (invaders_is_cabinet_cocktail())
return 0x07;
else
return ioport(INVADERS_P1_CONTROL_PORT_TAG)->read();
}
CUSTOM_INPUT_MEMBER(mw8080bw_state::invaders_in1_control_r)
{
return ioport(INVADERS_P1_CONTROL_PORT_TAG)->read();
}
CUSTOM_INPUT_MEMBER(mw8080bw_state::invaders_in2_control_r)
{
// upright PCB : P1 controls
// cocktail PCB: P2 controls
if (invaders_is_cabinet_cocktail())
return ioport(INVADERS_P2_CONTROL_PORT_TAG)->read();
else
return ioport(INVADERS_P1_CONTROL_PORT_TAG)->read();
}
int mw8080bw_state::invaders_is_cabinet_cocktail()
{
return ioport(INVADERS_CAB_TYPE_PORT_TAG)->read();
}
void mw8080bw_state::invaders_io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).portr("IN0");
map(0x01, 0x01).mirror(0x04).portr("IN1");
map(0x02, 0x02).mirror(0x04).portr("IN2");
map(0x03, 0x03).mirror(0x04).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x03, 0x03).w("soundboard", FUNC(invaders_audio_device::p1_w));
map(0x04, 0x04).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x05, 0x05).w("soundboard", FUNC(invaders_audio_device::p2_w));
map(0x06, 0x06).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
}
static INPUT_PORTS_START( invaders )
PORT_START("IN0")
PORT_DIPNAME( 0x01, 0x00, DEF_STR( Unknown ) ) PORT_DIPLOCATION("SW:8")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x01, DEF_STR( On ) )
PORT_BIT( 0x06, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(mw8080bw_state, invaders_sw6_sw7_r)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x70, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(mw8080bw_state, invaders_in0_control_r)
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(mw8080bw_state, invaders_sw5_r)
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_CHANGED_MEMBER(DEVICE_SELF, mw8080bw_state, direct_coin_count, 0)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x70, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(mw8080bw_state, invaders_in1_control_r)
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("IN2")
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW:3,4")
PORT_DIPSETTING( 0x00, "3" )
PORT_DIPSETTING( 0x01, "4" )
PORT_DIPSETTING( 0x02, "5" )
PORT_DIPSETTING( 0x03, "6" )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNUSED ) /* in the software, this is TILI, but not connected on the Midway PCB. Is this correct? */
PORT_DIPNAME( 0x08, 0x00, DEF_STR( Bonus_Life ) ) PORT_DIPLOCATION("SW:2")
PORT_DIPSETTING( 0x08, "1000" )
PORT_DIPSETTING( 0x00, "1500" )
PORT_BIT( 0x70, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(mw8080bw_state, invaders_in2_control_r)
PORT_DIPNAME( 0x80, 0x00, "Display Coinage" ) PORT_DIPLOCATION("SW:1")
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* fake port for cabinet type */
PORT_START(INVADERS_CAB_TYPE_PORT_TAG)
PORT_CONFNAME( 0x01, 0x00, DEF_STR( Cabinet ) )
PORT_CONFSETTING( 0x00, DEF_STR( Upright ) )
PORT_CONFSETTING( 0x01, DEF_STR( Cocktail ) )
PORT_BIT( 0xfe, IP_ACTIVE_HIGH, IPT_UNUSED )
/* fake ports for handling the various input ports based on cabinet type */
PORT_START(INVADERS_SW6_SW7_PORT_TAG)
PORT_DIPNAME( 0x01, 0x00, DEF_STR( Unused ) ) PORT_DIPLOCATION("SW:7")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x01, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, DEF_STR( Unused ) ) PORT_DIPLOCATION("SW:6")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x02, DEF_STR( On ) )
PORT_BIT( 0xfc, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START(INVADERS_SW5_PORT_TAG)
PORT_DIPNAME( 0x01, 0x00, DEF_STR( Unused ) ) PORT_DIPLOCATION("SW:5")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x01, DEF_STR( On ) )
PORT_BIT( 0xfe, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START(INVADERS_P1_CONTROL_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_PLAYER(1)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_PLAYER(1)
PORT_BIT( 0xf8, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START(INVADERS_P2_CONTROL_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_PLAYER(2)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_PLAYER(2)
PORT_BIT( 0xf8, IP_ACTIVE_HIGH, IPT_UNUSED )
INPUT_PORTS_END
void mw8080bw_state::invaders(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &mw8080bw_state::invaders_io_map);
MCFG_MACHINE_START_OVERRIDE(mw8080bw_state,invaders)
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
// video hardware
m_screen->set_screen_update(FUNC(mw8080bw_state::screen_update_invaders));
// add shifter
MB14241(config, m_mb14241);
// audio hardware
INVADERS_AUDIO(config, "soundboard"). // the flip screen line is only connected on the cocktail PCB
flip_screen_out().set([this] (int state) { if (invaders_is_cabinet_cocktail()) m_flip_screen = state ? 1 : 0; });
}
/*************************************
*
* Blue Shark (PCB #742)
*
*************************************/
#define BLUESHRK_COIN_INPUT_PORT_TAG ("COIN")
CUSTOM_INPUT_MEMBER(mw8080bw_state::blueshrk_coin_input_r)
{
uint32_t ret = ioport(BLUESHRK_COIN_INPUT_PORT_TAG)->read();
// FIXME: use PORT_CHANGED_MEMBER or PORT_WRITE_LINE_MEMBER instead of updating here
machine().bookkeeping().coin_counter_w(0, !ret);
return ret;
}
void mw8080bw_state::blueshrk_io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).r(FUNC(mw8080bw_state::mw8080bw_shift_result_rev_r));
map(0x01, 0x01).mirror(0x04).portr("IN0");
map(0x02, 0x02).mirror(0x04).portr("IN1");
map(0x03, 0x03).mirror(0x04).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x01, 0x01).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x03, 0x03).w(FUNC(mw8080bw_state::blueshrk_audio_w));
map(0x04, 0x04).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
}
static INPUT_PORTS_START( blueshrk )
PORT_START(BLUESHRK_SPEAR_PORT_TAG)
PORT_BIT( 0xff, 0x45, IPT_PADDLE ) PORT_CROSSHAIR(X, 1.0, 0.0, 0.139) PORT_MINMAX(0x08,0x82) PORT_SENSITIVITY(100) PORT_KEYDELTA(10) PORT_CENTERDELTA(0) PORT_PLAYER(1)
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(mw8080bw_state, blueshrk_coin_input_r)
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unused ) ) PORT_CONDITION("IN1", 0x80, EQUALS, 0x80) PORT_DIPLOCATION("SW:3")
PORT_DIPSETTING( 0x04, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_TILT ) /* not shown on the schematics, instead DIP SW4 is connected here */
PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unused ) ) PORT_CONDITION("IN1", 0x80, EQUALS, 0x80) PORT_DIPLOCATION("SW:5")
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x60, 0x40, "Replay" ) PORT_CONDITION("IN1", 0x80, EQUALS, 0x80) PORT_DIPLOCATION("SW:6,7")
PORT_DIPSETTING( 0x20, "14000" )
PORT_DIPSETTING( 0x40, "18000" )
PORT_DIPSETTING( 0x60, "22000" )
PORT_DIPSETTING( 0x00, DEF_STR( None ) )
PORT_SERVICE_DIPLOC( 0x80, IP_ACTIVE_LOW, "SW:8" )
/* fake port for reading the coin input */
PORT_START(BLUESHRK_COIN_INPUT_PORT_TAG)
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0xfe, IP_ACTIVE_HIGH, IPT_UNUSED )
INPUT_PORTS_END
void mw8080bw_state::blueshrk(machine_config &config)
{
mw8080bw_root(config);
/* basic machine hardware */
m_maincpu->set_addrmap(AS_IO, &mw8080bw_state::blueshrk_io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
/* add shifter */
MB14241(config, m_mb14241);
/* audio hardware */
blueshrk_audio(config);
}
/*************************************
*
* Space Invaders II (cocktail) (PCB #851)
*
*************************************/
void mw8080bw_state::invad2ct_io_map(address_map &map)
{
map.global_mask(0x7);
map(0x00, 0x00).mirror(0x04).portr("IN0");
map(0x01, 0x01).mirror(0x04).portr("IN1");
map(0x02, 0x02).mirror(0x04).portr("IN2");
map(0x03, 0x03).mirror(0x04).r(m_mb14241, FUNC(mb14241_device::shift_result_r));
map(0x01, 0x01).w("soundboard", FUNC(invad2ct_audio_device::p3_w));
map(0x02, 0x02).w(m_mb14241, FUNC(mb14241_device::shift_count_w));
map(0x03, 0x03).w("soundboard", FUNC(invad2ct_audio_device::p1_w));
map(0x04, 0x04).w(m_mb14241, FUNC(mb14241_device::shift_data_w));
map(0x05, 0x05).w("soundboard", FUNC(invad2ct_audio_device::p2_w));
map(0x06, 0x06).w(m_watchdog, FUNC(watchdog_timer_device::reset_w));
map(0x07, 0x07).w("soundboard", FUNC(invad2ct_audio_device::p4_w));
}
static INPUT_PORTS_START( invad2ct )
PORT_START("IN0")
PORT_SERVICE_DIPLOC( 0x01, IP_ACTIVE_LOW, "SW:8" )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED ) /* labeled NAMED RESET, but not read by the software */
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_CHANGED_MEMBER(DEVICE_SELF, mw8080bw_state, direct_coin_count, 0)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_PLAYER(1)
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_PLAYER(1)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("IN2")
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coinage ) ) PORT_DIPLOCATION("SW:3,4")
PORT_DIPSETTING( 0x02, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x03, DEF_STR( 2C_2C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 1C_2C ) )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("SW:2") /* this switch only changes the orientation of the score */
PORT_DIPSETTING( 0x08, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_PLAYER(2)
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_PLAYER(2)
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Bonus_Life ) ) PORT_DIPLOCATION("SW:1")
PORT_DIPSETTING( 0x80, "1500" )
PORT_DIPSETTING( 0x00, "2000" )
INPUT_PORTS_END
void mw8080bw_state::invad2ct(machine_config &config)
{
mw8080bw_root(config);
// basic machine hardware
m_maincpu->set_addrmap(AS_IO, &mw8080bw_state::invad2ct_io_map);
WATCHDOG_TIMER(config, m_watchdog).set_time(255 * attotime::from_hz(MW8080BW_60HZ));
// add shifter
MB14241(config, m_mb14241);
// audio hardware
INVAD2CT_AUDIO(config, "soundboard");
}
/*************************************
*
* ROM definitions
*
*************************************/
ROM_START( seawolf )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "sw0041.h", 0x0000, 0x0400, CRC(8f597323) SHA1(b538277d3a633dd8a3179cff202f18d322e6fe17) )
ROM_LOAD( "sw0042.g", 0x0400, 0x0400, CRC(db980974) SHA1(cc2a99b18695f61e0540c9f6bf8fe3b391dde4a0) )
ROM_LOAD( "sw0043.f", 0x0800, 0x0400, CRC(e6ffa008) SHA1(385198434b08fe4651ad2c920d44fb49cfe0bc33) )
ROM_LOAD( "sw0044.e", 0x0c00, 0x0400, CRC(c3557d6a) SHA1(bd345dd72fed8ce15da76c381782b025f71b006f) )
ROM_END
ROM_START( seawolfo )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "1.h1", 0x0000, 0x0200, CRC(941b8f2b) SHA1(1a46f91478d902b1452962972d7097ae217488a3) )
ROM_LOAD( "2.g1", 0x0200, 0x0200, CRC(c047ef88) SHA1(e731cbcd849ed0ad0c69a28f24e9986bf02c17e8) )
ROM_LOAD( "3.f1", 0x0400, 0x0200, CRC(9624b1ab) SHA1(a5b234ad3216def8dd006496a0d02ce275b88fa0) )
ROM_LOAD( "4.e1", 0x0600, 0x0200, CRC(553ff531) SHA1(0382f99f8cf148adae4a66db9693c8625250b3f5) )
ROM_LOAD( "5.d1", 0x0800, 0x0200, CRC(e8e07d03) SHA1(053b28edcf34400c809d5195b825469ae7744ddb) )
ROM_LOAD( "6.c1", 0x0a00, 0x0200, CRC(e2ffe499) SHA1(4e62aa14c510504872e76eacc298912d60b2e6fe) )
ROM_LOAD( "7.b1", 0x0c00, 0x0200, CRC(d40a52b5) SHA1(ffa7bb9109248be748f92f173d22b9a8bed3875f) )
ROM_LOAD( "8.a1", 0x0e00, 0x0200, CRC(da61df76) SHA1(49cae7772c0ee99aaba3a5d0981f970c85755872) )
ROM_END
ROM_START( gunfight )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "7609h.bin", 0x0000, 0x0400, CRC(0b117d73) SHA1(99d01313e251818d336281700e206d9003c71dae) )
ROM_LOAD( "7609g.bin", 0x0400, 0x0400, CRC(57bc3159) SHA1(c177e3f72db9af17ab99b2481448ca26318184b9) )
ROM_LOAD( "7609f.bin", 0x0800, 0x0400, CRC(8049a6bd) SHA1(215b068663e431582591001cbe028929fa96d49f) )
ROM_LOAD( "7609e.bin", 0x0c00, 0x0400, CRC(773264e2) SHA1(de3f2e6841122bbe6e2fda5b87d37842c072289a) )
ROM_END
ROM_START( gunfighto )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "gf-h.h", 0x0000, 0x0200, CRC(9d29cc7a) SHA1(3aef38948f1b82539e6c868ada6b9dcf2a743c4e) )
ROM_LOAD( "gf-g.g", 0x0200, 0x0200, CRC(5816911b) SHA1(eeb5835d3db1db1075d78a95f1f0189489910cce) )
ROM_LOAD( "gf-f.f", 0x0400, 0x0200, CRC(58f6ee8d) SHA1(03c3743424772202231d3066ce39d9c386887d22) )
ROM_LOAD( "gf-e.e", 0x0600, 0x0200, CRC(59078036) SHA1(4f3c1f2eb6ce3a1354b4031a225857b37e56cfcd) )
ROM_LOAD( "gf-d.d", 0x0800, 0x0200, CRC(2b64e17f) SHA1(8a5d52a859866f926ecd324ed97609102fa38e54) )
ROM_LOAD( "gf-c.c", 0x0a00, 0x0200, CRC(e0bbf98c) SHA1(eada3fdf09a752af98fdefdfad8de0b59beec422) )
ROM_LOAD( "gf-b.b", 0x0c00, 0x0200, CRC(91114108) SHA1(9480ddb45900b63ec295b983768e2825e06a0d71) )
ROM_LOAD( "gf-a.a", 0x0e00, 0x0200, CRC(3fbf9a91) SHA1(c74986362bc9db2aa3f881b3c98fe44537632979) )
ROM_END
ROM_START( tornbase )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "tb.h", 0x0000, 0x0800, CRC(653f4797) SHA1(feb4c802aa3e0c2a66823cd032496cca5742c883) )
ROM_LOAD( "tb.g", 0x0800, 0x0800, CRC(b63dcdb3) SHA1(bdaa0985bcb5257204ee10faa11a4e02a38b9ac5) )
ROM_LOAD( "tb.f", 0x1000, 0x0800, CRC(215e070c) SHA1(425915b37e5315f9216707de0850290145f69a30) )
ROM_END
ROM_START( 280zzzap )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "zzzaph", 0x0000, 0x0400, CRC(1fa86e1c) SHA1(b9cf16eb037ada73631ed24297e9e3b3bf6ab3cd) )
ROM_LOAD( "zzzapg", 0x0400, 0x0400, CRC(9639bc6b) SHA1(b2e2497e421e79a411d07ebf2eed2bb8dc227003) )
ROM_LOAD( "zzzapf", 0x0800, 0x0400, CRC(adc6ede1) SHA1(206bf2575696c4b14437f3db37a215ba33211943) )
ROM_LOAD( "zzzape", 0x0c00, 0x0400, CRC(472493d6) SHA1(ae5cf4481ee4b78ca0d2f4d560d295e922aa04a7) )
ROM_LOAD( "zzzapd", 0x1000, 0x0400, CRC(4c240ee1) SHA1(972475f80253bb0d24773a10aec26a12f28e7c23) )
ROM_LOAD( "zzzapc", 0x1400, 0x0400, CRC(6e85aeaf) SHA1(ffa6bb84ef1f7c2d72fd26c24bd33aa014aeab7e) )
ROM_END
ROM_START( maze )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "maze.h", 0x0000, 0x0800, CRC(f2860cff) SHA1(62b3fd3d04bf9c5dd9b50964374fb884dc0ab79c) )
ROM_LOAD( "maze.g", 0x0800, 0x0800, CRC(65fad839) SHA1(893f0a7621e7df19f777be991faff0db4a9ad571) )
ROM_END
ROM_START( boothill )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "romh.cpu", 0x0000, 0x0800, CRC(1615d077) SHA1(e59a26c2f2fc67ab24301e22d2e3f33043acdf72) )
ROM_LOAD( "romg.cpu", 0x0800, 0x0800, CRC(65a90420) SHA1(9f36c44b5ae5b912cdbbeb9ff11a42221b8362d2) )
ROM_LOAD( "romf.cpu", 0x1000, 0x0800, CRC(3fdafd79) SHA1(b18e8ac9df40c4687ac1acd5174eb99f2ef60081) )
ROM_LOAD( "rome.cpu", 0x1800, 0x0800, CRC(374529f4) SHA1(18c57b79df0c66052eef40a694779a5ade15d0e0) )
ROM_END
ROM_START( checkmat )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "checkmat.h", 0x0000, 0x0400, CRC(3481a6d1) SHA1(f758599d6393398a6a8e6e7399dc1a3862604f65) )
ROM_LOAD( "checkmat.g", 0x0400, 0x0400, CRC(df5fa551) SHA1(484ff9bfb95166ba09f34c753a7908a73de3cc7d) )
ROM_LOAD( "checkmat.f", 0x0800, 0x0400, CRC(25586406) SHA1(39e0cf502735819a7e1d933e3686945fcfae21af) )
ROM_LOAD( "checkmat.e", 0x0c00, 0x0400, CRC(59330d84) SHA1(453f95dd31968d439339c41e625481170437eb0f) )
ROM_LOAD( "checkmat.d", 0x1000, 0x0400, NO_DUMP ) /* language ROM */
ROM_END
ROM_START( desertgu )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "9316.1h", 0x0000, 0x0800, CRC(c0030d7c) SHA1(4d0a3a59d4f8181c6e30966a6b1d19ba5b29c398) )
ROM_LOAD( "9316.1g", 0x0800, 0x0800, CRC(1ddde10b) SHA1(8fb8e85844a8ec6c0722883013ecdd4eeaeb08c1) )
ROM_LOAD( "9316.1f", 0x1000, 0x0800, CRC(808e46f1) SHA1(1cc4e9b0aa7e9546c133bd40d40ede6f2fbe93ba) )
ROM_LOAD( "desertgu.e", 0x1800, 0x0800, CRC(ac64dc62) SHA1(202433dfb174901bd3b91e843d9d697a8333ef9e) )
ROM_END
ROM_START( roadrunm )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "9316.1h", 0x0000, 0x0800, CRC(c0030d7c) SHA1(4d0a3a59d4f8181c6e30966a6b1d19ba5b29c398) )
ROM_LOAD( "9316.1g", 0x0800, 0x0800, CRC(1ddde10b) SHA1(8fb8e85844a8ec6c0722883013ecdd4eeaeb08c1) )
ROM_LOAD( "9316.1f", 0x1000, 0x0800, CRC(808e46f1) SHA1(1cc4e9b0aa7e9546c133bd40d40ede6f2fbe93ba) )
ROM_LOAD( "9316.1e", 0x1800, 0x0800, CRC(06f01571) SHA1(6a72ff96a68aeeb0aca4834843c00b789c9bdaa0) )
ROM_END
ROM_START( dplay )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "dplay619.h", 0x0000, 0x0800, CRC(6680669b) SHA1(49ad2333f81613c2f27231de60b415cbc254546a) )
ROM_LOAD( "dplay619.g", 0x0800, 0x0800, CRC(0eec7e01) SHA1(2661e77061119d7d95d498807bd29d2630c6b6ab) )
ROM_LOAD( "dplay619.f", 0x1000, 0x0800, CRC(3af4b719) SHA1(3122138ac36b1a129226836ddf1916d763d73e10) )
ROM_LOAD( "dplay619.e", 0x1800, 0x0800, CRC(65cab4fc) SHA1(1ce7cb832e95e4a6d0005bf730eec39225b2e960) )
ROM_END
ROM_START( lagunar )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "lagunar.h", 0x0000, 0x0800, CRC(0cd5a280) SHA1(89a744c912070f11b0b90b0cc92061e238b00b64) )
ROM_LOAD( "lagunar.g", 0x0800, 0x0800, CRC(824cd6f5) SHA1(a74f6983787cf040eab6f19de2669c019962b9cb) )
ROM_LOAD( "lagunar.f", 0x1000, 0x0800, CRC(62692ca7) SHA1(d62051bd1b45ca6e60df83942ff26a64ae25a97b) )
ROM_LOAD( "lagunar.e", 0x1800, 0x0800, CRC(20e098ed) SHA1(e0c52c013f5e93794b363d7762ce0f34ba98c660) )
ROM_END
ROM_START( gmissile )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "gm_623.h", 0x0000, 0x0800, CRC(a3ebb792) SHA1(30d9613de849c1a868056c5e28cf2a8608b63e88) )
ROM_LOAD( "gm_623.g", 0x0800, 0x0800, CRC(a5e740bb) SHA1(963c0984953eb58fe7eab84fabb724ec6e29e706) )
ROM_LOAD( "gm_623.f", 0x1000, 0x0800, CRC(da381025) SHA1(c9d0511567ed571b424459896ce7de0326850388) )
ROM_LOAD( "gm_623.e", 0x1800, 0x0800, CRC(f350146b) SHA1(a07000a979b1a735754eca623cc880988924877f) )
ROM_END
ROM_START( m4 )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "m4.h", 0x0000, 0x0800, CRC(9ee2a0b5) SHA1(b81b4001c90ac6db25edd838652c42913022d9a9) )
ROM_LOAD( "m4.g", 0x0800, 0x0800, CRC(0e84b9cb) SHA1(a7b74851979aaaa16496e506c487a18df14ab6dc) )
ROM_LOAD( "m4.f", 0x1000, 0x0800, CRC(9ded9956) SHA1(449204a50efd3345cde815ca5f1fb596843a30ac) )
ROM_LOAD( "m4.e", 0x1800, 0x0800, CRC(b6983238) SHA1(3f3b99b33135e144c111d2ebaac8f9433c269bc5) )
ROM_END
ROM_START( clowns )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "h2.cpu", 0x0000, 0x0400, CRC(ff4432eb) SHA1(997aee1e3669daa1d8169b4e103d04baaab8ea8d) )
ROM_LOAD( "g2.cpu", 0x0400, 0x0400, CRC(676c934b) SHA1(72b681ca9ef23d820fdd297cc417932aecc9677b) )
ROM_LOAD( "f2.cpu", 0x0800, 0x0400, CRC(00757962) SHA1(ef39211493393e97284a08eea63be0757643ac88) )
ROM_LOAD( "e2.cpu", 0x0c00, 0x0400, CRC(9e506a36) SHA1(8aad486a72d148d8b03e7bec4c12abd14e425c5f) )
ROM_LOAD( "d2.cpu", 0x1000, 0x0400, CRC(d61b5b47) SHA1(6051c0a2e81d6e975e82c2d48d0e52dc0d4723e3) )
ROM_LOAD( "c2.cpu", 0x1400, 0x0400, CRC(154d129a) SHA1(61eebb319ee3a6be598b764b295c18a93a953c1e) )
ROM_END
ROM_START( clowns1 )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "clownsv1.h", 0x0000, 0x0400, CRC(5560c951) SHA1(b6972e1918604263579de577ec58fa6a91e8ff3e) )
ROM_LOAD( "clownsv1.g", 0x0400, 0x0400, CRC(6a571d66) SHA1(e825f95863e901a1b648c74bb47098c8e74f179b) )
ROM_LOAD( "clownsv1.f", 0x0800, 0x0400, CRC(a2d56cea) SHA1(61bc07e6a24a1980216453b4dd2688695193a4ae) )
ROM_LOAD( "clownsv1.e", 0x0c00, 0x0400, CRC(bbd606f6) SHA1(1cbaa21d9834c8d76cf335fd118851591e815c86) )
ROM_LOAD( "clownsv1.d", 0x1000, 0x0400, CRC(37b6ff0e) SHA1(bf83bebb6c14b3663ca86a180f9ae3cddb84e571) )
ROM_LOAD( "clownsv1.c", 0x1400, 0x0400, CRC(12968e52) SHA1(71e4f09d30b992a4ac44b0e88e83b4f8a0f63caa) )
ROM_END
ROM_START( spacwalk )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "sw.h", 0x0000, 0x0400, CRC(1b07fc1f) SHA1(bc6423ebcfcc1d158bc44c1a577485682b0aa79b) )
ROM_LOAD( "sw.g", 0x0400, 0x0400, CRC(52220910) SHA1(2d479b241d6a57f28a91d6a085f10cc3fd6787a1) )
ROM_LOAD( "sw.f", 0x0800, 0x0400, CRC(787d4ef6) SHA1(42b24a80e750bb51b81caeaf418014e62f55810d) )
ROM_LOAD( "sw.e", 0x0c00, 0x0400, CRC(d62d324b) SHA1(1c1ed2f9995d960f6dac79cae53fd4e82cb06640) )
ROM_LOAD( "sw.d", 0x1000, 0x0400, CRC(17dcc591) SHA1(a6c96da27713e51f4d400ef3bb33654a40214aa8))
ROM_LOAD( "sw.c", 0x1400, 0x0400, CRC(61aef726) SHA1(fbb8e90e0a0f7de4e5e5a37b9595a1be626ada9b) )
ROM_LOAD( "sw.b", 0x1800, 0x0400, CRC(c59d45d0) SHA1(5e772772e235ab8c0615ec26334d2e192f297604))
ROM_LOAD( "sw.a", 0x1c00, 0x0400, CRC(d563da07) SHA1(937b683dddfddbc1c0f2e45571657b569c0c4928) )
ROM_END
ROM_START( einning )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "ei.h", 0x0000, 0x0800, CRC(eff9c7af) SHA1(316fffc972bd9935ead5ee4fd629bddc8a8ed5ce) )
ROM_LOAD( "ei.g", 0x0800, 0x0800, CRC(5d1e66cb) SHA1(a5475362e12b7c251a05d67c2fd070cf7d333ad0) )
ROM_LOAD( "ei.f", 0x1000, 0x0800, CRC(ed96785d) SHA1(d5557620227fcf6f30dcf6c8f5edd760d77d30ae) )
ROM_LOAD( "ei.e", 0x1800, 0x0800, CRC(ad096a5d) SHA1(81d48302a0e039b8601a6aed7276e966592af693) )
ROM_LOAD( "ei.b", 0x5000, 0x0800, CRC(56b407d4) SHA1(95e4be5b2f28192df85c6118079de2e68838b67c) )
ROM_END
ROM_START( shuffle )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "shuffle.h", 0x0000, 0x0800, CRC(0d422a18) SHA1(909c5b9e3c1194abd101cbf993a2ed7c8fbeb5d0) )
ROM_LOAD( "shuffle.g", 0x0800, 0x0800, CRC(7db7fcf9) SHA1(f41b568f2340e5307a7a45658946cfd4cf4056bf) )
ROM_LOAD( "shuffle.f", 0x1000, 0x0800, CRC(cd04d848) SHA1(f0f7e9bc483f08934d5c29568b4a7fe084623031) )
ROM_LOAD( "shuffle.e", 0x1800, 0x0800, CRC(2c118357) SHA1(178db02aaa70963dd8dbcb9b8651209913c539af) )
ROM_END
ROM_START( dogpatch )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "dogpatch.h", 0x0000, 0x0800, CRC(74ebdf4d) SHA1(6b31f9563b0f79fe9128ee83e85a3e2f90d7985b) )
ROM_LOAD( "dogpatch.g", 0x0800, 0x0800, CRC(ac246f70) SHA1(7ee356c3218558a78ee0ff495f9f51ef88cac951) )
ROM_LOAD( "dogpatch.f", 0x1000, 0x0800, CRC(a975b011) SHA1(fb807d9eefde7177d7fd7ab06fc2dbdc58ae6fcb) )
ROM_LOAD( "dogpatch.e", 0x1800, 0x0800, CRC(c12b1f60) SHA1(f0504e16d2ce60a0fb3fc2af8c323bfca0143818) )
ROM_END
ROM_START( spcenctr )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "m645h-4m33.h1", 0x0000, 0x0800, CRC(7458b2db) SHA1(c4f41efb8a35fd8bebc75bff0111476affe2b34d) )
ROM_LOAD( "m645g-4m32.g1", 0x0800, 0x0800, CRC(1b873788) SHA1(6cdf0d602a65c7efcf8abe149c6172b4c7ab87a1) )
ROM_LOAD( "m645f-4m31.f1", 0x1000, 0x0800, CRC(d4319c91) SHA1(30830595c220f490fe150ad018fbf4671bb71e02) )
ROM_LOAD( "m645e-4m30.e1", 0x1800, 0x0800, CRC(9b9a1a45) SHA1(8023a05c13e8b541f9e2fe4d389e6a2dcd4766ea) )
ROM_LOAD( "m645d-4m29.d1", 0x4000, 0x0800, CRC(294d52ce) SHA1(0ee63413c5caf60d45ae8bef08f6c07099d30f79) )
ROM_LOAD( "m645c-4m28.c1", 0x4800, 0x0800, CRC(ce44c923) SHA1(9d35908de3194c5fe6fc8495ae413fa722018744) )
ROM_LOAD( "m645b-4m27.b1", 0x5000, 0x0800, CRC(098070ab) SHA1(72ae344591df0174353dc2e3d22daf5a70e2261f) )
ROM_LOAD( "m645a-4m26.a1", 0x5800, 0x0800, CRC(7f1d1f44) SHA1(2f4951171a55e7ac072742fa24eceeee6aca7e39) )
ROM_END
ROM_START( phantom2 )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "phantom2.h", 0x0000, 0x0800, CRC(0e3c2439) SHA1(450182e590845c651530b2c84e1f11fe2451dcf6) )
ROM_LOAD( "phantom2.g", 0x0800, 0x0800, CRC(e8df3e52) SHA1(833925e44e686df4d4056bce4c0ffae3269d57df) )
ROM_LOAD( "phantom2.f", 0x1000, 0x0800, CRC(30e83c6d) SHA1(fe34a3e4519a7e5ffe66e76fe974049988656b71) )
ROM_LOAD( "phantom2.e", 0x1800, 0x0800, CRC(8c641cac) SHA1(c4986daacb7ed9efed59b022c6101240b0eddcdc) )
ROM_REGION( 0x0800, "proms", 0 ) /* cloud graphics */
ROM_LOAD( "p2clouds.f2",0x0000, 0x0800, CRC(dcdd2927) SHA1(d8d42c6594e36c12b40ee6342a9ad01a8bbdef75) )
ROM_END
ROM_START( bowler )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "h.cpu", 0x0000, 0x0800, CRC(74c29b93) SHA1(9cbd5b7b8a4c889406b6bc065360f74c036320b2) )
ROM_LOAD( "g.cpu", 0x0800, 0x0800, CRC(ca26d8b4) SHA1(cf18991cde8044a961cf556f18c6eb60a7ade595) )
ROM_LOAD( "f.cpu", 0x1000, 0x0800, CRC(ba8a0bfa) SHA1(bb017ddac58d031b249596b70ab1068cd1bad499) )
ROM_LOAD( "e.cpu", 0x1800, 0x0800, CRC(4da65a40) SHA1(7795d59870fa722da89888e72152145662554080) )
ROM_LOAD( "d.cpu", 0x4000, 0x0800, CRC(e7dbc9d9) SHA1(05049a69ee588de85db86df188e7670778b77e90) )
ROM_END
ROM_START( invaders )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "invaders.h", 0x0000, 0x0800, CRC(734f5ad8) SHA1(ff6200af4c9110d8181249cbcef1a8a40fa40b7f) )
ROM_LOAD( "invaders.g", 0x0800, 0x0800, CRC(6bfaca4a) SHA1(16f48649b531bdef8c2d1446c429b5f414524350) )
ROM_LOAD( "invaders.f", 0x1000, 0x0800, CRC(0ccead96) SHA1(537aef03468f63c5b9e11dd61e253f7ae17d9743) )
ROM_LOAD( "invaders.e", 0x1800, 0x0800, CRC(14e538b0) SHA1(1d6ca0c99f9df71e2990b610deb9d7da0125e2d8) )
ROM_END
ROM_START( blueshrk )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "blueshrk.h", 0x0000, 0x0800, CRC(4ff94187) SHA1(7cb80e2ccc34983bfd688c549ffc032d6dacf880) )
ROM_LOAD( "blueshrk.g", 0x0800, 0x0800, CRC(e49368fd) SHA1(2495ba48532bb714361e4f0e94c9317161c6c77f) )
ROM_LOAD( "blueshrk.f", 0x1000, 0x0800, CRC(86cca79d) SHA1(7b4633fb8033ee2c0e692135c383ebf57deef0e5) )
ROM_END
/*
CPUs
QTY Type clock position function
1x unknown DIP40 main PCB 2n
7x LM3900N sound PCB ic2-ic8 Quad Operational Amplifier - sound
1x LM377 sound PCB 1k Dual Audio Amplifier - sound
1x oscillator 19.968000 main PCB XTAL 8b
ROMs
QTY Type position status
4x TMS2708 main PCB 1m 1n 1r 1s dumped
2x MCM2708 main PCB 1j 1l dumped
RAMs
QTY Type position
16x D2107C main PCB 1-16
Others
1x 18x2 edge connector (main PCB)
1x 36x2 female connector to sound PCB (main PCB)
1x 36x2 edge connector to main PCB (sound PCB)
1x 15x2 edge connector (sound PCB)
8x trimmer (sound PCB VR1-VR8)
1x 7 DIP switches banks (sound PCB 3j)
1x 4 DIP switches banks (sound PCB 3a)
Notes
main PCB is marked "CS210", "SI" and is labeled "C6902575"
sound PCB is marked "CS214" and is labeled "C6902574", "VOLUME"
*/
ROM_START( blueshrkmr )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "mr14.1s", 0x0000, 0x0400, CRC(ea2ba987) SHA1(929d2c72d81ad15c0f877b8b3421b909fdcc80f6) )
ROM_LOAD( "mr15.1r", 0x0400, 0x0400, CRC(049337a4) SHA1(d0288ec63b170722c7f20e7d2e17f6ceeaacab27) )
ROM_LOAD( "mr16.1n", 0x0800, 0x0400, CRC(3f9793ca) SHA1(859d0f43fcba7282017e8f4985e5e9217225a617) )
ROM_LOAD( "mr17.1m", 0x0c00, 0x0400, CRC(0a73e0eb) SHA1(dfe1c58979642e15f07039d0cec17f975ccd2a48) )
ROM_LOAD( "mr18.1l", 0x1000, 0x0400, CRC(a18bb930) SHA1(36ed5d6d3b3643ddf9bd087001dc6ece7fb8df63) )
ROM_LOAD( "mr19.1j", 0x1400, 0x0400, CRC(23c63d02) SHA1(74ce4bd9fe2528896c5574affaf0ca132e62cf9e) )
ROM_END
ROM_START( blueshrkmr2 )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "mr14.1s", 0x0000, 0x0400, CRC(ea2ba987) SHA1(929d2c72d81ad15c0f877b8b3421b909fdcc80f6) )
ROM_LOAD( "mr15.1r", 0x0400, 0x0400, CRC(049337a4) SHA1(d0288ec63b170722c7f20e7d2e17f6ceeaacab27) )
ROM_LOAD( "mr16.1n", 0x0800, 0x0400, CRC(8776920f) SHA1(10fe501c8260f2f7ea57e704789299420237af90) ) // sldh, label was peeled off
ROM_LOAD( "mr17.1m", 0x0c00, 0x0400, CRC(0a73e0eb) SHA1(dfe1c58979642e15f07039d0cec17f975ccd2a48) )
ROM_LOAD( "mr18.1l", 0x1000, 0x0400, CRC(a18bb930) SHA1(36ed5d6d3b3643ddf9bd087001dc6ece7fb8df63) )
ROM_LOAD( "mr19.1j", 0x1400, 0x0400, CRC(23c63d02) SHA1(74ce4bd9fe2528896c5574affaf0ca132e62cf9e) )
ROM_END
ROM_START( invad2ct )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "invad2ct.h", 0x0000, 0x0800, CRC(51d02a71) SHA1(2fa82ddc2702a72de0a9559ec244b70ab3db3f18) )
ROM_LOAD( "invad2ct.g", 0x0800, 0x0800, CRC(533ac770) SHA1(edb65c289027432dad7861a7d6abbda9223c13b1) )
ROM_LOAD( "invad2ct.f", 0x1000, 0x0800, CRC(d1799f39) SHA1(f7f1ba34d57f9883241ba3ef90e34ed20dfb8003) )
ROM_LOAD( "invad2ct.e", 0x1800, 0x0800, CRC(291c1418) SHA1(0d9f7973ed81d28c43ef8b96f1180d6629871785) )
ROM_LOAD( "invad2ct.b", 0x5000, 0x0800, CRC(8d9a07c4) SHA1(4acbe15185d958b5589508dc0ea3a615fbe3bcca) )
ROM_LOAD( "invad2ct.a", 0x5800, 0x0800, CRC(efdabb03) SHA1(33f4cf249e88e2b7154350e54c479eb4fa86f26f) )
ROM_END
/*************************************
*
* Game drivers
*
*************************************/
// PCB # year rom parent machine inp state init monitor company,fullname,flags
/* 596 */ GAMEL( 1976, seawolf, 0, seawolf, seawolf, seawolf_state, empty_init, ROT0, "Dave Nutting Associates / Midway", "Sea Wolf (set 1)", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE, layout_seawolf )
/* 596 */ GAMEL( 1976, seawolfo, seawolf, seawolf, seawolf, seawolf_state, empty_init, ROT0, "Dave Nutting Associates / Midway", "Sea Wolf (set 2)", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE, layout_seawolf )
/* 597 */ GAMEL( 1975, gunfight, 0, gunfight, gunfight, gunfight_state, empty_init, ROT0, "Dave Nutting Associates / Midway", "Gun Fight (set 1)", MACHINE_SUPPORTS_SAVE, layout_gunfight )
/* 597 */ GAMEL( 1975, gunfighto, gunfight, gunfight, gunfight, gunfight_state, empty_init, ROT0, "Dave Nutting Associates / Midway", "Gun Fight (set 2)", MACHINE_SUPPORTS_SAVE, layout_gunfight )
/* 604 Gun Fight (cocktail, dump does not exist) */
/* 605 */ GAME( 1976, tornbase, 0, tornbase, tornbase, mw8080bw_state, empty_init, ROT0, "Dave Nutting Associates / Midway / Taito", "Tornado Baseball / Ball Park", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
/* 610 */ GAMEL( 1976, 280zzzap, 0, zzzap, zzzap, zzzap_state, empty_init, ROT0, "Dave Nutting Associates / Midway", "280-ZZZAP", MACHINE_SUPPORTS_SAVE, layout_280zzzap )
/* 611 */ GAMEL( 1976, maze, 0, maze, maze, mw8080bw_state, empty_init, ROT0, "Midway", "Amazing Maze", MACHINE_SUPPORTS_SAVE, layout_maze )
/* 612 */ GAME( 1977, boothill, 0, boothill, boothill, boothill_state, empty_init, ROT0, "Dave Nutting Associates / Midway", "Boot Hill", MACHINE_SUPPORTS_SAVE )
/* 615 */ GAME( 1977, checkmat, 0, checkmat, checkmat, mw8080bw_state, empty_init, ROT0, "Dave Nutting Associates / Midway", "Checkmate", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
/* 618 */ GAME( 1977, desertgu, 0, desertgu, desertgu, desertgu_state, empty_init, ROT0, "Dave Nutting Associates / Midway", "Desert Gun", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
/* 618 */ GAME( 1977, roadrunm, desertgu, desertgu, desertgu, desertgu_state, empty_init, ROT0, "Midway", "Road Runner (Midway)", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
/* 619 */ GAME( 1977, dplay, 0, dplay, dplay, dplay_state, empty_init, ROT0, "Midway", "Double Play", MACHINE_SUPPORTS_SAVE )
/* 622 */ GAMEL( 1977, lagunar, 0, lagunar, lagunar, zzzap_state, empty_init, ROT90, "Midway", "Laguna Racer", MACHINE_SUPPORTS_SAVE, layout_lagunar )
/* 623 */ GAME( 1977, gmissile, 0, gmissile, gmissile, boothill_state, empty_init, ROT0, "Midway", "Guided Missile", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
/* 626 */ GAME( 1977, m4, 0, m4, m4, boothill_state, empty_init, ROT0, "Midway", "M-4", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
/* 630 */ GAMEL( 1978, clowns, 0, clowns, clowns, clowns_state, empty_init, ROT0, "Midway", "Clowns (rev. 2)", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE, layout_clowns )
/* 630 */ GAMEL( 1978, clowns1, clowns, clowns, clowns1, clowns_state, empty_init, ROT0, "Midway", "Clowns (rev. 1)", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE, layout_clowns )
/* 640 */ GAMEL( 1978, spacwalk, 0, spacwalk, spacwalk, clowns_state, empty_init, ROT0, "Midway", "Space Walk", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE, layout_spacwalk )
/* 642 */ GAME( 1978, einning, 0, dplay, einning, dplay_state, empty_init, ROT0, "Midway / Taito", "Extra Inning / Ball Park II", MACHINE_SUPPORTS_SAVE )
/* 643 */ GAME( 1978, shuffle, 0, shuffle, shuffle, mw8080bw_state, empty_init, ROT90, "Midway", "Shuffleboard", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
/* 644 */ GAME( 1977, dogpatch, 0, dogpatch, dogpatch, mw8080bw_state, empty_init, ROT0, "Midway", "Dog Patch", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
/* 645 */ GAMEL( 1980, spcenctr, 0, spcenctr, spcenctr, spcenctr_state, empty_init, ROT0, "Midway", "Space Encounters", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE, layout_spcenctr )
/* 652 */ GAMEL( 1979, phantom2, 0, phantom2, phantom2, mw8080bw_state, empty_init, ROT0, "Midway", "Phantom II", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE, layout_phantom2 )
/* 730 */ GAME( 1978, bowler, 0, bowler, bowler, mw8080bw_state, empty_init, ROT90, "Midway", "Bowling Alley", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
/* 739 */ GAMEL( 1978, invaders, 0, invaders, invaders, mw8080bw_state, empty_init, ROT270, "Taito / Midway", "Space Invaders / Space Invaders M", MACHINE_SUPPORTS_SAVE, layout_invaders )
/* 742 */ GAME( 1978, blueshrk, 0, blueshrk, blueshrk, mw8080bw_state, empty_init, ROT0, "Midway", "Blue Shark", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1978, blueshrkmr, blueshrk, blueshrk, blueshrk, mw8080bw_state, empty_init, ROT0, "bootleg (Model Racing)", "Blue Shark (Model Racing bootleg, set 1)", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1978, blueshrkmr2,blueshrk, blueshrk, blueshrk, mw8080bw_state, empty_init, ROT0, "bootleg (Model Racing)", "Blue Shark (Model Racing bootleg, set 2)", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
/* 749 4 Player Bowling Alley (cocktail, dump does not exist) */
/* 851 */ GAMEL( 1980, invad2ct, 0, invad2ct, invad2ct, mw8080bw_state, empty_init, ROT90, "Midway", "Space Invaders II (Midway, cocktail)", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE, layout_invad2ct )
/* 852 Space Invaders Deluxe (color hardware, not in this driver) */
/* 870 Space Invaders Deluxe (cocktail, dump does not exist) */
| 41.413936 | 324 | 0.718855 | [
"vector",
"model"
] |
90075f1752d370db274eaa7ffb64647f999925a8 | 3,753 | cpp | C++ | Program2/main.cpp | TaroBubble/cs280-interpreter | 2a93614518820a9dc75c498f2df9800140f78727 | [
"MIT"
] | null | null | null | Program2/main.cpp | TaroBubble/cs280-interpreter | 2a93614518820a9dc75c498f2df9800140f78727 | [
"MIT"
] | null | null | null | Program2/main.cpp | TaroBubble/cs280-interpreter | 2a93614518820a9dc75c498f2df9800140f78727 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "tokens.h"
#include <fstream>
#include <vector>
#include <stdbool.h>
#include <algorithm>
#include <set>
using namespace std;
int main(int argc, char const *argv[])
{
bool isV = false;
bool isID = false;
bool isSum = false;
bool readFile = false;
int tokencounter = 0;
int stringcounter = 0;
int idCount =0;
Token tok;
int lineNumber=0;
vector<string> idents;
vector<string> filevec;
for(int i = 1; i<argc; i++)
{
if(argv[i][0]=='-')
{
if(strcmp(argv[i],"-v")==0)
{
isV = true;
}
else if(strcmp(argv[i],"-allids")==0)
{
isID = true;
}
else if(strcmp(argv[i],"-sum")==0)
{
isSum = true;
}
else
{
cout << "INVALID FLAG "<<argv[i]<<endl;
return 0;
}
}
else
{
filevec.push_back(argv[i]);
}
}
ifstream infile;
if (filevec.size()>1)
{
cout << "TOO MANY FILE NAMES" << endl;
return 0;
}
else if(filevec.size()==0)
{
return 0;
}
else
{
infile.open(filevec.front());
if(infile.is_open())
{
readFile = true;
istream *in= readFile ? &infile : &cin;
//good file
while((tok=getNextToken(in, &lineNumber))!= DONE && tok != ERR)
{
++tokencounter;
if(tok == IDENT)
{
//do something
idCount++;
idents.push_back(tok.GetLexeme());
}
if(tok == SCONST)
{
//do something
stringcounter++;
}
if(isV)
{
cout << tok << endl;
}
}
if(isID)
{
cout << "IDENTIFIERS: ";
std::sort(idents.begin(),idents.end());
//remove duplicates later
for(int i = 0; i<idents.size(); i++)
{
if(i < idents.size()-1)
{
cout<< idents[i] << ", ";
}
else
{
cout << idents[i] << endl;
}
}
}
if(isSum)
{
cout << "Total lines: " << lineNumber << endl;
cout << "Total tokens: " << tokencounter << endl;
cout << "Total identifiers: " << idCount << endl;
cout << "Total strings: " << stringcounter << endl;
}
if (tok == ERR)
{
cout << "Error on line " << tok.GetLinenum() << " ("<< tok.GetLexeme() << ")" << endl; ;
return 0;
}
}
else
{
cout << "UNABLE TO OPEN " << filevec.front() << endl;
return 0;
}
}
return 0;
} | 25.02 | 108 | 0.322409 | [
"vector"
] |
9007d801ee4155c8ca99bc373fb3f80fa5244e5d | 910 | cpp | C++ | online_judges/Vjudge/ccpl2020r8/l/l.cpp | miaortizma/competitive-programming | ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc | [
"MIT"
] | 2 | 2018-02-20T14:44:57.000Z | 2018-02-20T14:45:03.000Z | online_judges/Vjudge/ccpl2020r8/l/l.cpp | miaortizma/competitive-programming | ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc | [
"MIT"
] | null | null | null | online_judges/Vjudge/ccpl2020r8/l/l.cpp | miaortizma/competitive-programming | ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
// By Miguel Ortiz https://github.com/miaortizma
int dist(vector<int> v, int m) {
int S = 0;
for (auto x : v) {
S += abs(x - m);
}
return S;
}
void solve() {
int S, A, F;
cin >> S >> A >> F;
vector<int> X(F);
vector<int> Y(F);
for (int i = 0; i < F; ++i) {
cin >> X[i] >> Y[i];
}
sort(X.begin(), X.end());
sort(Y.begin(), Y.end());
int x, y;
if (F & 1) {
x = X[F / 2];
y = Y[F / 2];
} else {
int a = F / 2;
int b = (F / 2) - 1;
int A = dist(X, X[a]) + dist(Y, Y[a]);
int B = dist(X, X[b]) + dist(Y, Y[b]);
if (A < B) {
x = X[a];
y = Y[a];
} else {
x = X[b];
y = Y[b];
}
}
cout << "(Street: " << x << ", Avenue: " << y << ")\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
int T;
cin >> T;
while(T--) {
solve();
}
return 0;
}
| 16.851852 | 57 | 0.420879 | [
"vector"
] |
900a274b14a08a94348d49809ae03c1fb28e6fe6 | 4,896 | cpp | C++ | proxyroles/switchrole.cpp | swex/SortFilterProxyModel | c4a598fa1aad5134d3c57e6c297a966e41cb1105 | [
"MIT"
] | null | null | null | proxyroles/switchrole.cpp | swex/SortFilterProxyModel | c4a598fa1aad5134d3c57e6c297a966e41cb1105 | [
"MIT"
] | null | null | null | proxyroles/switchrole.cpp | swex/SortFilterProxyModel | c4a598fa1aad5134d3c57e6c297a966e41cb1105 | [
"MIT"
] | null | null | null | #include "switchrole.h"
#include "qqmlsortfilterproxymodel.h"
#include "filters/filter.h"
#include <QtQml>
namespace qqsfpm {
/*!
\qmltype SwitchRole
\inherits SingleRole
\inqmlmodule SortFilterProxyModel
\brief A role using \l Filter to conditionnaly compute its data
A SwitchRole is a \l ProxyRole that computes its data with the help of \l Filter.
Each top level filters specified in the \l SwitchRole is evaluated on the rows of the model, if a \l Filter evaluates to true, the data of the \l SwitchRole for this row will be the one of the attached \l {value} {SwitchRole.value} property.
If no top level filters evaluate to true, the data will default to the one of the \l defaultRoleName (or the \l defaultValue if no \l defaultRoleName is specified).
In the following example, the \c favoriteOrFirstNameSection role is equal to \c * if the \c favorite role of a row is true, otherwise it's the same as the \c firstName role :
\code
SortFilterProxyModel {
sourceModel: contactModel
proxyRoles: SwitchRole {
name: "favoriteOrFirstNameSection"
filters: ValueFilter {
roleName: "favorite"
value: true
SwitchRole.value: "*"
}
defaultRoleName: "firstName"
}
}
\endcode
*/
SwitchRoleAttached::SwitchRoleAttached(QObject* parent) : QObject (parent)
{
if (!qobject_cast<Filter*>(parent))
qmlInfo(parent) << "SwitchRole must be attached to a Filter";
}
/*!
\qmlattachedproperty var SwitchRole::value
This property attaches a value to a \l Filter.
*/
QVariant SwitchRoleAttached::value() const
{
return m_value;
}
void SwitchRoleAttached::setValue(QVariant value)
{
if (m_value == value)
return;
m_value = value;
Q_EMIT valueChanged();
}
/*!
\qmlproperty string SwitchRole::defaultRoleName
This property holds the default role name of the role.
If no filter match a row, the data of this role will be the data of the role whose name is \c defaultRoleName.
*/
QString SwitchRole::defaultRoleName() const
{
return m_defaultRoleName;
}
void SwitchRole::setDefaultRoleName(const QString& defaultRoleName)
{
if (m_defaultRoleName == defaultRoleName)
return;
m_defaultRoleName = defaultRoleName;
Q_EMIT defaultRoleNameChanged();
invalidate();
}
/*!
\qmlproperty var SwitchRole::defaultValue
This property holds the default value of the role.
If no filter match a row, and no \l defaultRoleName is set, the data of this role will be \c defaultValue.
*/
QVariant SwitchRole::defaultValue() const
{
return m_defaultValue;
}
void SwitchRole::setDefaultValue(const QVariant& defaultValue)
{
if (m_defaultValue == defaultValue)
return;
m_defaultValue = defaultValue;
Q_EMIT defaultValueChanged();
invalidate();
}
/*!
\qmlproperty list<Filter> SwitchRole::filters
This property holds the list of filters for this proxy role.
The data of this role will be equal to the attached \l {value} {SwitchRole.value} property of the first filter that matches the model row.
\sa Filter
*/
void SwitchRole::proxyModelCompleted(const QQmlSortFilterProxyModel& proxyModel)
{
for (Filter* filter : m_filters)
filter->proxyModelCompleted(proxyModel);
}
SwitchRoleAttached* SwitchRole::qmlAttachedProperties(QObject* object)
{
return new SwitchRoleAttached(object);
}
QVariant SwitchRole::data(const QModelIndex &sourceIndex, const QQmlSortFilterProxyModel &proxyModel)
{
for (auto filter: m_filters) {
if (!filter->enabled())
continue;
if (filter->filterAcceptsRow(sourceIndex, proxyModel)) {
auto attached = static_cast<SwitchRoleAttached*>(qmlAttachedPropertiesObject<SwitchRole>(filter, false));
if (!attached) {
qWarning() << "No SwitchRole.value provided for this filter" << filter;
continue;
}
QVariant value = attached->value();
if (!value.isValid()) {
qWarning() << "No SwitchRole.value provided for this filter" << filter;
continue;
}
return value;
}
}
if (!m_defaultRoleName.isEmpty())
return proxyModel.sourceData(sourceIndex, m_defaultRoleName);
return m_defaultValue;
}
void SwitchRole::onFilterAppended(Filter *filter)
{
connect(filter, &Filter::invalidated, this, &SwitchRole::invalidate);
auto attached = static_cast<SwitchRoleAttached*>(qmlAttachedPropertiesObject<SwitchRole>(filter, true));
connect(attached, &SwitchRoleAttached::valueChanged, this, &SwitchRole::invalidate);
invalidate();
}
void SwitchRole::onFilterRemoved(Filter *filter)
{
Q_UNUSED(filter)
invalidate();
}
void SwitchRole::onFiltersCleared()
{
invalidate();
}
}
| 29.493976 | 245 | 0.687908 | [
"object",
"model"
] |
900fcc977f00866be6d7d540b60aa6710a0af5c6 | 1,796 | cpp | C++ | CodeForces/Solutions/269C.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | 5 | 2020-10-03T17:15:26.000Z | 2022-03-29T21:39:22.000Z | CodeForces/Solutions/269C.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | null | null | null | CodeForces/Solutions/269C.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | 1 | 2021-03-01T12:56:50.000Z | 2021-03-01T12:56:50.000Z | // #pragma GCC optimize("Ofast,unroll-loops")
// #pragma GCC target("avx,avx2,fma")
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define dd double
#define ld long double
#define sl(n) scanf("%lld", &n)
#define si(n) scanf("%d", &n)
#define sd(n) scanf("%lf", &n)
#define pll pair <ll, ll>
#define pii pair <int, int>
#define mp make_pair
#define pb push_back
#define all(v) v.begin(), v.end()
#define inf (1LL << 61)
#define loop(i, start, stop, inc) for(ll i = start; i <= stop; i += inc)
#define for1(i, stop) for(ll i = 1; i <= stop; ++i)
#define for0(i, stop) for(ll i = 0; i < stop; ++i)
#define rep1(i, start) for(ll i = start; i >= 1; --i)
#define rep0(i, start) for(ll i = (start-1); i >= 0; --i)
#define ms(n, i) memset(n, i, sizeof(n))
#define casep(n) printf("Case %lld:", ++n)
#define pn printf("\n")
#define pf printf
#define EL '\n'
#define fastio std::ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
const ll sz = 2e5 + 10;
struct node {
ll v, flow, id, dir;
};
vector <node> g[sz];
ll flow[sz];
bool dir[sz], vis[sz];
int main()
{
ll n, m;
cin >> n >> m;
for1(i, m) {
ll u, v, c;
sl(u), sl(v), sl(c);
g[u].pb({v, c, i, 0});
g[v].pb({u, c, i, 1});
flow[u] += c, flow[v] += c;
}
for(ll i = 2; i < n; i++) flow[i] /= 2;
queue <ll> q;
q.push(1);
while(!q.empty()) {
ll u = q.front();
q.pop();
for(node &nd : g[u]) {
if(vis[nd.id])
continue;
vis[nd.id] = 1, dir[nd.id] = nd.dir;
flow[nd.v] -= nd.flow;
if(nd.v != n && flow[nd.v] == 0)
q.push(nd.v);
}
}
for1(i, m) pf("%d\n", (int)dir[i]);
return 0;
} | 22.17284 | 82 | 0.516704 | [
"vector"
] |
90105346054d92b0c342a465860db4351459b6df | 16,944 | cc | C++ | google_apis/common/base_requests.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | google_apis/common/base_requests.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | google_apis/common/base_requests.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // 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 "google_apis/common/base_requests.h"
#include <stddef.h>
#include <algorithm>
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/json/json_reader.h"
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
#include "base/task/task_runner_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "google_apis/common/request_sender.h"
#include "google_apis/common/task_util.h"
#include "net/base/load_flags.h"
#include "net/http/http_util.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
namespace {
// Template for optional OAuth2 authorization HTTP header.
const char kAuthorizationHeaderFormat[] = "Authorization: Bearer %s";
// Template for GData API version HTTP header.
const char kGDataVersionHeader[] = "GData-Version: 3.0";
// Maximum number of attempts for re-authentication per request.
const int kMaxReAuthenticateAttemptsPerRequest = 1;
// Returns response headers as a string. Returns a warning message if
// |response_head| does not contain a valid response. Used only for debugging.
std::string GetResponseHeadersAsString(
const network::mojom::URLResponseHead& response_head) {
// Check that response code indicates response headers are valid (i.e. not
// malformed) before we retrieve the headers.
if (response_head.headers->response_code() == -1)
return "Response headers are malformed!!";
return response_head.headers->raw_headers();
}
} // namespace
namespace google_apis {
absl::optional<std::string> MapJsonErrorToReason(
const std::string& error_body) {
DVLOG(1) << error_body;
const char kErrorKey[] = "error";
const char kErrorErrorsKey[] = "errors";
const char kErrorReasonKey[] = "reason";
const char kErrorMessageKey[] = "message";
const char kErrorCodeKey[] = "code";
std::unique_ptr<const base::Value> value(google_apis::ParseJson(error_body));
const base::DictionaryValue* dictionary = nullptr;
const base::DictionaryValue* error = nullptr;
if (value && value->GetAsDictionary(&dictionary) &&
dictionary->GetDictionaryWithoutPathExpansion(kErrorKey, &error)) {
// Get error message and code.
const std::string* message = error->FindStringKey(kErrorMessageKey);
absl::optional<int> code = error->FindIntKey(kErrorCodeKey);
DLOG(ERROR) << "code: " << (code ? code.value() : OTHER_ERROR)
<< ", message: " << (message ? *message : "");
// Returns the reason of the first error.
const base::ListValue* errors = nullptr;
if (error->GetListWithoutPathExpansion(kErrorErrorsKey, &errors)) {
const base::Value& first_error = errors->GetList()[0];
if (first_error.is_dict()) {
const std::string* reason = first_error.FindStringKey(kErrorReasonKey);
if (reason)
return *reason;
}
}
}
return absl::nullopt;
}
std::unique_ptr<base::Value> ParseJson(const std::string& json) {
base::JSONReader::ValueWithError parsed_json =
base::JSONReader::ReadAndReturnValueWithError(json);
if (!parsed_json.value) {
std::string trimmed_json;
if (json.size() < 80) {
trimmed_json = json;
} else {
// Take the first 50 and the last 10 bytes.
trimmed_json =
base::StringPrintf("%s [%s bytes] %s", json.substr(0, 50).c_str(),
base::NumberToString(json.size() - 60).c_str(),
json.substr(json.size() - 10).c_str());
}
LOG(WARNING) << "Error while parsing entry response: "
<< parsed_json.error_message << ", json:\n"
<< trimmed_json;
return nullptr;
}
return base::Value::ToUniquePtrValue(std::move(*parsed_json.value));
}
UrlFetchRequestBase::UrlFetchRequestBase(
RequestSender* sender,
ProgressCallback upload_progress_callback,
ProgressCallback download_progress_callback)
: re_authenticate_count_(0),
sender_(sender),
upload_progress_callback_(upload_progress_callback),
download_progress_callback_(download_progress_callback),
response_content_length_(-1) {}
UrlFetchRequestBase::~UrlFetchRequestBase() = default;
void UrlFetchRequestBase::Start(const std::string& access_token,
const std::string& custom_user_agent,
ReAuthenticateCallback callback) {
DCHECK(CalledOnValidThread());
DCHECK(!access_token.empty());
DCHECK(callback);
DCHECK(re_authenticate_callback_.is_null());
Prepare(base::BindOnce(&UrlFetchRequestBase::StartAfterPrepare,
weak_ptr_factory_.GetWeakPtr(), access_token,
custom_user_agent, std::move(callback)));
}
void UrlFetchRequestBase::Prepare(PrepareCallback callback) {
DCHECK(CalledOnValidThread());
DCHECK(!callback.is_null());
std::move(callback).Run(HTTP_SUCCESS);
}
void UrlFetchRequestBase::StartAfterPrepare(
const std::string& access_token,
const std::string& custom_user_agent,
ReAuthenticateCallback callback,
ApiErrorCode code) {
DCHECK(CalledOnValidThread());
DCHECK(!access_token.empty());
DCHECK(callback);
DCHECK(re_authenticate_callback_.is_null());
const GURL url = GetURL();
ApiErrorCode error_code;
if (IsSuccessfulErrorCode(code))
error_code = code;
else if (url.is_empty())
error_code = OTHER_ERROR;
else
error_code = HTTP_SUCCESS;
if (error_code != HTTP_SUCCESS) {
// Error is found on generating the url or preparing the request. Send the
// error message to the callback, and then return immediately without trying
// to connect to the server. We need to call CompleteRequestWithError
// asynchronously because client code does not assume result callback is
// called synchronously.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&UrlFetchRequestBase::CompleteRequestWithError,
weak_ptr_factory_.GetWeakPtr(), error_code));
return;
}
re_authenticate_callback_ = callback;
DVLOG(1) << "URL: " << url.spec();
auto request = std::make_unique<network::ResourceRequest>();
request->url = url;
request->method = GetRequestType();
request->load_flags = net::LOAD_DISABLE_CACHE;
request->credentials_mode = network::mojom::CredentialsMode::kOmit;
// Add request headers.
// Note that SetHeader clears the current headers and sets it to the passed-in
// headers, so calling it for each header will result in only the last header
// being set in request headers.
if (!custom_user_agent.empty())
request->headers.SetHeader("User-Agent", custom_user_agent);
request->headers.AddHeaderFromString(kGDataVersionHeader);
request->headers.AddHeaderFromString(
base::StringPrintf(kAuthorizationHeaderFormat, access_token.data()));
for (const auto& header : GetExtraRequestHeaders()) {
request->headers.AddHeaderFromString(header);
DVLOG(1) << "Extra header: " << header;
}
url_loader_ = network::SimpleURLLoader::Create(
std::move(request), sender_->get_traffic_annotation_tag());
url_loader_->SetAllowHttpErrorResults(true /* allow */);
download_data_ = std::make_unique<DownloadData>(blocking_task_runner());
GetOutputFilePath(&download_data_->output_file_path,
&download_data_->get_content_callback);
if (!download_data_->get_content_callback.is_null()) {
download_data_->get_content_callback =
CreateRelayCallback(download_data_->get_content_callback);
}
// Set upload data if available.
std::string upload_content_type;
std::string upload_content;
if (GetContentData(&upload_content_type, &upload_content)) {
url_loader_->AttachStringForUpload(upload_content, upload_content_type);
} else {
base::FilePath local_file_path;
int64_t range_offset = 0;
int64_t range_length = 0;
if (GetContentFile(&local_file_path, &range_offset, &range_length,
&upload_content_type)) {
url_loader_->AttachFileForUpload(local_file_path, upload_content_type,
range_offset, range_length);
}
}
if (!upload_progress_callback_.is_null()) {
url_loader_->SetOnUploadProgressCallback(base::BindRepeating(
&UrlFetchRequestBase::OnUploadProgress, weak_ptr_factory_.GetWeakPtr(),
upload_progress_callback_));
}
if (!download_progress_callback_.is_null()) {
url_loader_->SetOnDownloadProgressCallback(base::BindRepeating(
&UrlFetchRequestBase::OnDownloadProgress,
weak_ptr_factory_.GetWeakPtr(), download_progress_callback_));
}
url_loader_->SetOnResponseStartedCallback(base::BindOnce(
&UrlFetchRequestBase::OnResponseStarted, weak_ptr_factory_.GetWeakPtr()));
url_loader_->DownloadAsStream(sender_->url_loader_factory(), this);
}
void UrlFetchRequestBase::OnDownloadProgress(ProgressCallback progress_callback,
uint64_t current) {
progress_callback.Run(static_cast<int64_t>(current),
response_content_length_);
}
void UrlFetchRequestBase::OnUploadProgress(ProgressCallback progress_callback,
uint64_t position,
uint64_t total) {
progress_callback.Run(static_cast<int64_t>(position),
static_cast<int64_t>(total));
}
void UrlFetchRequestBase::OnResponseStarted(
const GURL& final_url,
const network::mojom::URLResponseHead& response_head) {
DVLOG(1) << "Response headers:\n"
<< GetResponseHeadersAsString(response_head);
response_content_length_ = response_head.content_length;
}
UrlFetchRequestBase::DownloadData::DownloadData(
scoped_refptr<base::SequencedTaskRunner> blocking_task_runner)
: blocking_task_runner_(blocking_task_runner) {}
UrlFetchRequestBase::DownloadData::~DownloadData() {
if (output_file.IsValid()) {
blocking_task_runner_->PostTask(
FROM_HERE,
base::BindOnce([](base::File file) {}, std::move(output_file)));
}
}
// static
bool UrlFetchRequestBase::WriteFileData(std::string file_data,
DownloadData* download_data) {
if (!download_data->output_file.IsValid()) {
download_data->output_file.Initialize(
download_data->output_file_path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
if (!download_data->output_file.IsValid())
return false;
}
if (download_data->output_file.WriteAtCurrentPos(file_data.data(),
file_data.size()) == -1) {
download_data->output_file.Close();
return false;
}
// Even when writing response to a file save the first 1 MiB of the response
// body so that it can be used to get error information in case of server side
// errors. The size limit is to avoid consuming too much redundant memory.
const size_t kMaxStringSize = 1024 * 1024;
if (download_data->response_body.size() < kMaxStringSize) {
size_t bytes_to_copy = std::min(
file_data.size(), kMaxStringSize - download_data->response_body.size());
download_data->response_body.append(file_data.data(), bytes_to_copy);
}
return true;
}
void UrlFetchRequestBase::OnWriteComplete(
std::unique_ptr<DownloadData> download_data,
base::OnceClosure resume,
bool write_success) {
download_data_ = std::move(download_data);
if (!write_success) {
error_code_ = OTHER_ERROR;
url_loader_.reset(); // Cancel the request
// No SimpleURLLoader to call OnComplete() so call it directly.
OnComplete(false);
return;
}
std::move(resume).Run();
}
void UrlFetchRequestBase::OnDataReceived(base::StringPiece string_piece,
base::OnceClosure resume) {
if (!download_data_->get_content_callback.is_null()) {
download_data_->get_content_callback.Run(
HTTP_SUCCESS, std::make_unique<std::string>(string_piece),
download_data_->response_body.empty());
}
if (!download_data_->output_file_path.empty()) {
DownloadData* download_data_ptr = download_data_.get();
base::PostTaskAndReplyWithResult(
blocking_task_runner(), FROM_HERE,
base::BindOnce(&UrlFetchRequestBase::WriteFileData,
std::string(string_piece), download_data_ptr),
base::BindOnce(&UrlFetchRequestBase::OnWriteComplete,
weak_ptr_factory_.GetWeakPtr(),
std::move(download_data_), std::move(resume)));
return;
}
download_data_->response_body.append(string_piece.data(),
string_piece.size());
std::move(resume).Run();
}
void UrlFetchRequestBase::OnComplete(bool success) {
DCHECK(download_data_);
blocking_task_runner()->PostTaskAndReply(
FROM_HERE,
base::BindOnce([](base::File file) {},
std::move(download_data_->output_file)),
base::BindOnce(&UrlFetchRequestBase::OnOutputFileClosed,
weak_ptr_factory_.GetWeakPtr(), success));
}
void UrlFetchRequestBase::OnOutputFileClosed(bool success) {
DCHECK(download_data_);
const network::mojom::URLResponseHead* response_info;
if (url_loader_) {
response_info = url_loader_->ResponseInfo();
if (response_info) {
error_code_ =
static_cast<ApiErrorCode>(response_info->headers->response_code());
} else {
error_code_ =
NetError() == net::ERR_NETWORK_CHANGED ? NO_CONNECTION : OTHER_ERROR;
}
if (!download_data_->response_body.empty()) {
if (!IsSuccessfulErrorCode(error_code_.value())) {
absl::optional<std::string> reason =
MapJsonErrorToReason(download_data_->response_body);
if (reason.has_value())
error_code_ = MapReasonToError(error_code_.value(), reason.value());
}
}
} else {
// If the request is cancelled then error_code_ must be set.
DCHECK(error_code_.has_value());
response_info = nullptr;
}
if (error_code_.value() == HTTP_UNAUTHORIZED) {
if (++re_authenticate_count_ <= kMaxReAuthenticateAttemptsPerRequest) {
// Reset re_authenticate_callback_ so Start() can be called again.
std::move(re_authenticate_callback_).Run(this);
return;
}
OnAuthFailed(GetErrorCode());
return;
}
// Overridden by each specialization
ProcessURLFetchResults(response_info,
std::move(download_data_->output_file_path),
std::move(download_data_->response_body));
}
void UrlFetchRequestBase::OnRetry(base::OnceClosure start_retry) {
NOTREACHED();
}
std::string UrlFetchRequestBase::GetRequestType() const {
return "GET";
}
std::vector<std::string> UrlFetchRequestBase::GetExtraRequestHeaders() const {
return std::vector<std::string>();
}
bool UrlFetchRequestBase::GetContentData(std::string* upload_content_type,
std::string* upload_content) {
return false;
}
bool UrlFetchRequestBase::GetContentFile(base::FilePath* local_file_path,
int64_t* range_offset,
int64_t* range_length,
std::string* upload_content_type) {
return false;
}
void UrlFetchRequestBase::GetOutputFilePath(
base::FilePath* local_file_path,
GetContentCallback* get_content_callback) {}
void UrlFetchRequestBase::Cancel() {
url_loader_.reset();
CompleteRequestWithError(CANCELLED);
}
ApiErrorCode UrlFetchRequestBase::GetErrorCode() const {
DCHECK(error_code_.has_value()) << "GetErrorCode only valid after "
"resource load complete.";
return error_code_.value();
}
int UrlFetchRequestBase::NetError() const {
if (!url_loader_) // If resource load cancelled?
return net::ERR_FAILED;
return url_loader_->NetError();
}
bool UrlFetchRequestBase::CalledOnValidThread() {
return thread_checker_.CalledOnValidThread();
}
base::SequencedTaskRunner* UrlFetchRequestBase::blocking_task_runner() const {
return sender_->blocking_task_runner();
}
void UrlFetchRequestBase::OnProcessURLFetchResultsComplete() {
sender_->RequestFinished(this);
}
void UrlFetchRequestBase::CompleteRequestWithError(ApiErrorCode code) {
RunCallbackOnPrematureFailure(code);
sender_->RequestFinished(this);
}
void UrlFetchRequestBase::OnAuthFailed(ApiErrorCode code) {
CompleteRequestWithError(code);
}
base::WeakPtr<AuthenticatedRequestInterface> UrlFetchRequestBase::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
} // namespace google_apis
| 36.43871 | 80 | 0.693166 | [
"vector"
] |
9016443cdcb4813e0d0f1334e3b47ae9ad5654a6 | 1,664 | cpp | C++ | example-client/src/task.cpp | funbiscuit/qt-rr-tcp | 36ec012b58442472898bc1a1919786bc7b0e58fb | [
"MIT"
] | null | null | null | example-client/src/task.cpp | funbiscuit/qt-rr-tcp | 36ec012b58442472898bc1a1919786bc7b0e58fb | [
"MIT"
] | null | null | null | example-client/src/task.cpp | funbiscuit/qt-rr-tcp | 36ec012b58442472898bc1a1919786bc7b0e58fb | [
"MIT"
] | null | null | null | #include "task.h"
#include "RRTcpClient.h"
#include <binn.h>
#include <iostream>
#include <chrono>
#include <QCoreApplication>
Task::Task(QObject *parent) : QObject(parent) {
}
void Task::run() {
std::cout << "Request-Response Example Server\n";
tcpClient = std::make_shared<RRTcpClient>("localhost", 4141);
binn *request = binn_object();
binn_object_set_double(request, "num", 21);
binn_object_set_double(request, "delay", 50);
std::vector<uint8_t> test(1024 * 1024);
binn_object_set_blob(request, "test", test.data(), (int) test.size());
using namespace std::chrono;
auto t0 = steady_clock::now();
tcpClient->sendRequest(request, [t0](void *response, std::runtime_error *error) {
if (error != nullptr) {
std::cerr << "Error while waiting for response:\n" << error->what() << "\n";
QCoreApplication::quit();
return;
}
auto ms = duration_cast<milliseconds>(steady_clock::now() - t0).count();
std::cout << "Received response (took " << ms << "ms):\n";
binn_iter iter;
binn value;
char key[256];
binn_iter_init(&iter, response, BINN_OBJECT);
while (binn_object_next(&iter, key, &value)) {
std::cout << "[" << key << "] = ";
if (value.type == BINN_STRING) {
std::cout << (char *) value.ptr;
} else if (value.type == BINN_DOUBLE) {
std::cout << value.vdouble;
} else {
std::cout << "?";
}
std::cout << "\n";
}
QCoreApplication::quit();
});
binn_free(request);
}
| 27.733333 | 88 | 0.554087 | [
"vector"
] |
9017d5f67f85c6918908fe9e6422d5c7a1155f46 | 2,373 | cc | C++ | chrome/browser/notifications/system_component_notifier_source_chromeos.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/notifications/system_component_notifier_source_chromeos.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/notifications/system_component_notifier_source_chromeos.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2016 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/browser/notifications/system_component_notifier_source_chromeos.h"
#include "ash/system/system_notifier.h"
#include "chrome/browser/notifications/notifier_state_tracker.h"
#include "chrome/browser/notifications/notifier_state_tracker_factory.h"
#include "chrome/grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/message_center/notifier_settings.h"
#include "ui/strings/grit/ui_strings.h"
SystemComponentNotifierSourceChromeOS::SystemComponentNotifierSourceChromeOS(
Observer* observer)
: observer_(observer) {}
std::vector<std::unique_ptr<message_center::Notifier>>
SystemComponentNotifierSourceChromeOS::GetNotifierList(Profile* profile) {
std::vector<std::unique_ptr<message_center::Notifier>> notifiers;
NotifierStateTracker* const notifier_state_tracker =
NotifierStateTrackerFactory::GetForProfile(profile);
// Screenshot notification feature is only for ChromeOS. See
// crbug.com/238358
const base::string16& screenshot_name =
l10n_util::GetStringUTF16(IDS_MESSAGE_CENTER_NOTIFIER_SCREENSHOT_NAME);
message_center::NotifierId screenshot_notifier_id(
message_center::NotifierId::SYSTEM_COMPONENT,
ash::system_notifier::kNotifierScreenshot);
message_center::Notifier* const screenshot_notifier =
new message_center::Notifier(
screenshot_notifier_id, screenshot_name,
notifier_state_tracker->IsNotifierEnabled(screenshot_notifier_id));
screenshot_notifier->icon =
ui::ResourceBundle::GetSharedInstance().GetImageNamed(
IDR_SCREENSHOT_NOTIFICATION_ICON);
notifiers.emplace_back(screenshot_notifier);
return notifiers;
}
void SystemComponentNotifierSourceChromeOS::SetNotifierEnabled(
Profile* profile,
const message_center::Notifier& notifier,
bool enabled) {
NotifierStateTrackerFactory::GetForProfile(profile)->SetNotifierEnabled(
notifier.notifier_id, enabled);
observer_->OnNotifierEnabledChanged(notifier.notifier_id, enabled);
}
message_center::NotifierId::NotifierType
SystemComponentNotifierSourceChromeOS::GetNotifierType() {
return message_center::NotifierId::SYSTEM_COMPONENT;
}
| 41.631579 | 83 | 0.799831 | [
"vector"
] |
901dcbbef49574de7c1f909c6611e839dc125ca9 | 8,385 | cc | C++ | Core/Grid/Variables/LocallyComputedPatchVarMap.cc | QuocAnh90/Uintah_Aalto | 802c236c331b7eb705d408c352969037e4c5b153 | [
"MIT"
] | 3 | 2020-06-10T08:21:31.000Z | 2020-06-23T18:33:16.000Z | Core/Grid/Variables/LocallyComputedPatchVarMap.cc | QuocAnh90/Uintah_Aalto | 802c236c331b7eb705d408c352969037e4c5b153 | [
"MIT"
] | null | null | null | Core/Grid/Variables/LocallyComputedPatchVarMap.cc | QuocAnh90/Uintah_Aalto | 802c236c331b7eb705d408c352969037e4c5b153 | [
"MIT"
] | 2 | 2019-12-30T05:48:30.000Z | 2020-02-12T16:24:16.000Z | /*
* The MIT License
*
* Copyright (c) 1997-2019 The University of Utah
*
* 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 <Core/Grid/Variables/LocallyComputedPatchVarMap.h>
#include <Core/Grid/Grid.h>
#include <Core/Grid/Level.h>
#include <Core/Parallel/Parallel.h>
#include <Core/Exceptions/InternalError.h>
#include <iostream>
using namespace Uintah;
class PatchRangeQuerier {
public:
typedef Patch::selectType ResultContainer;
PatchRangeQuerier( const Level* level,
std::set<const Patch*>& patches )
: level_(level), patches_(patches)
{
}
void query( IntVector low,
IntVector high,
ResultContainer& result );
void queryNeighbors( IntVector low,
IntVector high,
ResultContainer& result) ;
private:
const Level* level_;
std::set<const Patch*>& patches_;
};
void
PatchRangeQuerier::query( IntVector low,
IntVector high,
ResultContainer& result )
{
std::back_insert_iterator<ResultContainer> result_ii( result );
ResultContainer tmp;
//add the extra cells to the low and subtract them from the high
//this adjusts for the extra cells that may have been included in the low and high
//this assumes the minimum patch size is greater than 2*extra_cells
IntVector offset = level_->getExtraCells();
level_->selectPatches(low + offset, high - offset, tmp);
for (ResultContainer::iterator iter = tmp.begin(); iter != tmp.end(); iter++) {
if (patches_.find(*iter) != patches_.end())
*result_ii++ = *iter;
}
}
void
PatchRangeQuerier::queryNeighbors( IntVector low,
IntVector high,
PatchRangeQuerier::ResultContainer& result )
{
std::back_insert_iterator<ResultContainer> result_ii(result);
ResultContainer tmp;
// query on each of 6 sides (done in pairs of opposite sides)
for (int i = 0; i < 3; i++) {
IntVector sideLow = low;
IntVector sideHigh = high;
sideHigh[i] = sideLow[i]--;
tmp.resize(0);
level_->selectPatches(sideLow, sideHigh, tmp);
for (ResultContainer::iterator iter = tmp.begin(); iter != tmp.end(); iter++) {
if (patches_.find(*iter) != patches_.end())
*result_ii++ = *iter;
}
sideHigh = high;
sideLow = low;
sideLow[i] = sideHigh[i]++;
tmp.resize(0);
level_->selectPatches(sideLow, sideHigh, tmp);
for (ResultContainer::iterator iter = tmp.begin(); iter != tmp.end(); iter++) {
if (patches_.find(*iter) != patches_.end())
*result_ii++ = *iter;
}
}
}
LocallyComputedPatchVarMap::LocallyComputedPatchVarMap()
{
reset();
}
LocallyComputedPatchVarMap::~LocallyComputedPatchVarMap()
{
reset();
}
void
LocallyComputedPatchVarMap::reset()
{
groupsMade = false;
for (unsigned i = 0; i < sets_.size(); i++) {
delete sets_[i];
}
sets_.clear();
}
void
LocallyComputedPatchVarMap::addComputedPatchSet( const PatchSubset* patches )
{
ASSERT(!groupsMade);
if (!patches || !patches->size()) {
return; // don't worry about reduction variables
}
const Level* level = patches->get(0)->getLevel();
#if SCI_ASSERTION_LEVEL >= 1
// Each call to this should contain only one level (one level at a time)
for (int i = 1; i < patches->size(); i++) {
const Patch* patch = patches->get(i);
ASSERT(patch->getLevel() == level);
}
#endif
if ((int)sets_.size() <= level->getIndex()) {
sets_.resize(level->getIndex() + 1);
}
LocallyComputedPatchSet* lcpatches = sets_[level->getIndex()];
if (lcpatches == 0) {
lcpatches = scinew LocallyComputedPatchSet();
sets_[level->getIndex()] = lcpatches;
}
lcpatches->addPatches(patches);
}
const SuperPatch*
LocallyComputedPatchVarMap::getConnectedPatchGroup( const Patch* patch ) const
{
ASSERT(groupsMade);
int l = patch->getLevel()->getIndex();
if (sets_.size() == 0 || sets_[l] == 0) {
return 0;
}
return sets_[l]->getConnectedPatchGroup(patch);
}
const SuperPatchContainer*
LocallyComputedPatchVarMap::getSuperPatches( const Level* level ) const
{
ASSERT(groupsMade);
int l = level->getIndex();
if (sets_.size() == 0 || sets_[l] == 0) {
return 0;
}
return sets_[l]->getSuperPatches();
}
void LocallyComputedPatchVarMap::makeGroups()
{
ASSERT(!groupsMade);
for (unsigned l = 0; l < sets_.size(); l++)
if (sets_[l]) {
sets_[l]->makeGroups();
}
groupsMade = true;
}
LocallyComputedPatchVarMap::LocallyComputedPatchSet::LocallyComputedPatchSet()
{
connectedPatchGroups_ = 0;
}
LocallyComputedPatchVarMap::LocallyComputedPatchSet::~LocallyComputedPatchSet()
{
if (connectedPatchGroups_) {
delete connectedPatchGroups_;
}
}
void LocallyComputedPatchVarMap::LocallyComputedPatchSet::addPatches(const PatchSubset* patches)
{
ASSERT(connectedPatchGroups_ == 0);
for (int i = 0; i < patches->size(); i++) {
if (map_.find(patches->get(i)) == map_.end()) {
map_.insert(std::make_pair(patches->get(i), static_cast<SuperPatch*>(0)));
}
}
}
const SuperPatchContainer*
LocallyComputedPatchVarMap::LocallyComputedPatchSet::getSuperPatches() const
{
ASSERT(connectedPatchGroups_ != 0);
return &connectedPatchGroups_->getSuperBoxes();
}
const SuperPatch*
LocallyComputedPatchVarMap::LocallyComputedPatchSet::getConnectedPatchGroup( const Patch* patch ) const
{
ASSERT(connectedPatchGroups_ != 0);
PatchMapType::const_iterator iter = map_.find(patch);
if (iter == map_.end())
return 0;
return iter->second;
}
void
LocallyComputedPatchVarMap::LocallyComputedPatchSet::makeGroups()
{
ASSERT(connectedPatchGroups_ == 0);
// Need to copy the patch list into a vector (or a set, but a
// vector would do), since the grouper cannot deal with a map
// We know that it is a unique list, because it is a map
std::set<const Patch*> patches;
for (PatchMapType::iterator iter = map_.begin(); iter != map_.end(); ++iter) {
patches.insert(iter->first);
}
ASSERT(patches.begin() != patches.end());
const Level* level = (*patches.begin())->getLevel();
#if SCI_ASSERTION_LEVEL >= 1
for (std::set<const Patch*>::iterator iter = patches.begin(); iter != patches.end(); iter++) {
ASSERT((*iter)->getLevel() == level);
}
#endif
PatchRangeQuerier patchRangeQuerier(level, patches);
connectedPatchGroups_ = SuperPatchSet::makeNearOptimalSuperBoxSet(patches.begin(), patches.end(), patchRangeQuerier);
// std::cerr << "ConnectedPatchGroups: \n" << *connectedPatchGroups_ << "\n";
// map each patch to its SuperBox
const SuperPatchContainer& superBoxes = connectedPatchGroups_->getSuperBoxes();
SuperPatchContainer::const_iterator iter;
for (iter = superBoxes.begin(); iter != superBoxes.end(); iter++) {
const SuperPatch* superBox = *iter;
std::vector<const Patch*>::const_iterator SBiter;
for (SBiter = superBox->getBoxes().begin(); SBiter != superBox->getBoxes().end(); SBiter++) {
map_[*SBiter] = superBox;
}
}
#if SCI_ASSERTION_LEVEL >= 1
for (PatchMapType::iterator iter = map_.begin(); iter != map_.end(); ++iter) {
ASSERT(iter->second != 0);
}
#endif
}
| 30.270758 | 119 | 0.667144 | [
"vector"
] |
9028034c908307ad081e51a6f84c02f76197cdf2 | 35,211 | cpp | C++ | esphome/components/api/api_connection.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 249 | 2018-04-07T12:04:11.000Z | 2019-01-25T01:11:34.000Z | esphome/components/api/api_connection.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 243 | 2018-04-11T16:37:11.000Z | 2019-01-25T16:50:37.000Z | esphome/components/api/api_connection.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 40 | 2018-04-10T05:50:14.000Z | 2019-01-25T15:20:36.000Z | #include "api_connection.h"
#include "esphome/core/entity_base.h"
#include "esphome/core/log.h"
#include "esphome/components/network/util.h"
#include "esphome/core/version.h"
#include "esphome/core/hal.h"
#include <cerrno>
#ifdef USE_DEEP_SLEEP
#include "esphome/components/deep_sleep/deep_sleep_component.h"
#endif
#ifdef USE_HOMEASSISTANT_TIME
#include "esphome/components/homeassistant/time/homeassistant_time.h"
#endif
namespace esphome {
namespace api {
static const char *const TAG = "api.connection";
static const int ESP32_CAMERA_STOP_STREAM = 5000;
APIConnection::APIConnection(std::unique_ptr<socket::Socket> sock, APIServer *parent)
: parent_(parent), initial_state_iterator_(this), list_entities_iterator_(this) {
this->proto_write_buffer_.reserve(64);
#if defined(USE_API_PLAINTEXT)
helper_ = std::unique_ptr<APIFrameHelper>{new APIPlaintextFrameHelper(std::move(sock))};
#elif defined(USE_API_NOISE)
helper_ = std::unique_ptr<APIFrameHelper>{new APINoiseFrameHelper(std::move(sock), parent->get_noise_ctx())};
#else
#error "No frame helper defined"
#endif
}
void APIConnection::start() {
this->last_traffic_ = millis();
APIError err = helper_->init();
if (err != APIError::OK) {
on_fatal_error();
ESP_LOGW(TAG, "%s: Helper init failed: %s errno=%d", client_info_.c_str(), api_error_to_str(err), errno);
return;
}
client_info_ = helper_->getpeername();
helper_->set_log_info(client_info_);
}
void APIConnection::loop() {
if (this->remove_)
return;
if (!network::is_connected()) {
// when network is disconnected force disconnect immediately
// don't wait for timeout
this->on_fatal_error();
ESP_LOGW(TAG, "%s: Network unavailable, disconnecting", client_info_.c_str());
return;
}
if (this->next_close_) {
// requested a disconnect
this->helper_->close();
this->remove_ = true;
return;
}
APIError err = helper_->loop();
if (err != APIError::OK) {
on_fatal_error();
ESP_LOGW(TAG, "%s: Socket operation failed: %s errno=%d", client_info_.c_str(), api_error_to_str(err), errno);
return;
}
ReadPacketBuffer buffer;
err = helper_->read_packet(&buffer);
if (err == APIError::WOULD_BLOCK) {
// pass
} else if (err != APIError::OK) {
on_fatal_error();
if (err == APIError::SOCKET_READ_FAILED && errno == ECONNRESET) {
ESP_LOGW(TAG, "%s: Connection reset", client_info_.c_str());
} else if (err == APIError::CONNECTION_CLOSED) {
ESP_LOGW(TAG, "%s: Connection closed", client_info_.c_str());
} else {
ESP_LOGW(TAG, "%s: Reading failed: %s errno=%d", client_info_.c_str(), api_error_to_str(err), errno);
}
return;
} else {
this->last_traffic_ = millis();
// read a packet
this->read_message(buffer.data_len, buffer.type, &buffer.container[buffer.data_offset]);
if (this->remove_)
return;
}
this->list_entities_iterator_.advance();
this->initial_state_iterator_.advance();
const uint32_t keepalive = 60000;
const uint32_t now = millis();
if (this->sent_ping_) {
// Disconnect if not responded within 2.5*keepalive
if (now - this->last_traffic_ > (keepalive * 5) / 2) {
on_fatal_error();
ESP_LOGW(TAG, "%s didn't respond to ping request in time. Disconnecting...", this->client_info_.c_str());
}
} else if (now - this->last_traffic_ > keepalive) {
ESP_LOGVV(TAG, "Sending keepalive PING...");
this->sent_ping_ = true;
this->send_ping_request(PingRequest());
}
#ifdef USE_ESP32_CAMERA
if (this->image_reader_.available() && this->helper_->can_write_without_blocking()) {
uint32_t to_send = std::min((size_t) 1024, this->image_reader_.available());
auto buffer = this->create_buffer();
// fixed32 key = 1;
buffer.encode_fixed32(1, esp32_camera::global_esp32_camera->get_object_id_hash());
// bytes data = 2;
buffer.encode_bytes(2, this->image_reader_.peek_data_buffer(), to_send);
// bool done = 3;
bool done = this->image_reader_.available() == to_send;
buffer.encode_bool(3, done);
bool success = this->send_buffer(buffer, 44);
if (success) {
this->image_reader_.consume_data(to_send);
}
if (success && done) {
this->image_reader_.return_image();
}
}
#endif
if (state_subs_at_ != -1) {
const auto &subs = this->parent_->get_state_subs();
if (state_subs_at_ >= (int) subs.size()) {
state_subs_at_ = -1;
} else {
auto &it = subs[state_subs_at_];
SubscribeHomeAssistantStateResponse resp;
resp.entity_id = it.entity_id;
resp.attribute = it.attribute.value();
if (this->send_subscribe_home_assistant_state_response(resp)) {
state_subs_at_++;
}
}
}
}
std::string get_default_unique_id(const std::string &component_type, EntityBase *entity) {
return App.get_name() + component_type + entity->get_object_id();
}
DisconnectResponse APIConnection::disconnect(const DisconnectRequest &msg) {
// remote initiated disconnect_client
// don't close yet, we still need to send the disconnect response
// close will happen on next loop
ESP_LOGD(TAG, "%s requested disconnected", client_info_.c_str());
this->next_close_ = true;
DisconnectResponse resp;
return resp;
}
void APIConnection::on_disconnect_response(const DisconnectResponse &value) {
// pass
}
#ifdef USE_BINARY_SENSOR
bool APIConnection::send_binary_sensor_state(binary_sensor::BinarySensor *binary_sensor, bool state) {
if (!this->state_subscription_)
return false;
BinarySensorStateResponse resp;
resp.key = binary_sensor->get_object_id_hash();
resp.state = state;
resp.missing_state = !binary_sensor->has_state();
return this->send_binary_sensor_state_response(resp);
}
bool APIConnection::send_binary_sensor_info(binary_sensor::BinarySensor *binary_sensor) {
ListEntitiesBinarySensorResponse msg;
msg.object_id = binary_sensor->get_object_id();
msg.key = binary_sensor->get_object_id_hash();
msg.name = binary_sensor->get_name();
msg.unique_id = get_default_unique_id("binary_sensor", binary_sensor);
msg.device_class = binary_sensor->get_device_class();
msg.is_status_binary_sensor = binary_sensor->is_status_binary_sensor();
msg.disabled_by_default = binary_sensor->is_disabled_by_default();
msg.icon = binary_sensor->get_icon();
msg.entity_category = static_cast<enums::EntityCategory>(binary_sensor->get_entity_category());
return this->send_list_entities_binary_sensor_response(msg);
}
#endif
#ifdef USE_COVER
bool APIConnection::send_cover_state(cover::Cover *cover) {
if (!this->state_subscription_)
return false;
auto traits = cover->get_traits();
CoverStateResponse resp{};
resp.key = cover->get_object_id_hash();
resp.legacy_state =
(cover->position == cover::COVER_OPEN) ? enums::LEGACY_COVER_STATE_OPEN : enums::LEGACY_COVER_STATE_CLOSED;
resp.position = cover->position;
if (traits.get_supports_tilt())
resp.tilt = cover->tilt;
resp.current_operation = static_cast<enums::CoverOperation>(cover->current_operation);
return this->send_cover_state_response(resp);
}
bool APIConnection::send_cover_info(cover::Cover *cover) {
auto traits = cover->get_traits();
ListEntitiesCoverResponse msg;
msg.key = cover->get_object_id_hash();
msg.object_id = cover->get_object_id();
msg.name = cover->get_name();
msg.unique_id = get_default_unique_id("cover", cover);
msg.assumed_state = traits.get_is_assumed_state();
msg.supports_position = traits.get_supports_position();
msg.supports_tilt = traits.get_supports_tilt();
msg.device_class = cover->get_device_class();
msg.disabled_by_default = cover->is_disabled_by_default();
msg.icon = cover->get_icon();
msg.entity_category = static_cast<enums::EntityCategory>(cover->get_entity_category());
return this->send_list_entities_cover_response(msg);
}
void APIConnection::cover_command(const CoverCommandRequest &msg) {
cover::Cover *cover = App.get_cover_by_key(msg.key);
if (cover == nullptr)
return;
auto call = cover->make_call();
if (msg.has_legacy_command) {
switch (msg.legacy_command) {
case enums::LEGACY_COVER_COMMAND_OPEN:
call.set_command_open();
break;
case enums::LEGACY_COVER_COMMAND_CLOSE:
call.set_command_close();
break;
case enums::LEGACY_COVER_COMMAND_STOP:
call.set_command_stop();
break;
}
}
if (msg.has_position)
call.set_position(msg.position);
if (msg.has_tilt)
call.set_tilt(msg.tilt);
if (msg.stop)
call.set_command_stop();
call.perform();
}
#endif
#ifdef USE_FAN
bool APIConnection::send_fan_state(fan::Fan *fan) {
if (!this->state_subscription_)
return false;
auto traits = fan->get_traits();
FanStateResponse resp{};
resp.key = fan->get_object_id_hash();
resp.state = fan->state;
if (traits.supports_oscillation())
resp.oscillating = fan->oscillating;
if (traits.supports_speed()) {
resp.speed_level = fan->speed;
}
if (traits.supports_direction())
resp.direction = static_cast<enums::FanDirection>(fan->direction);
return this->send_fan_state_response(resp);
}
bool APIConnection::send_fan_info(fan::Fan *fan) {
auto traits = fan->get_traits();
ListEntitiesFanResponse msg;
msg.key = fan->get_object_id_hash();
msg.object_id = fan->get_object_id();
msg.name = fan->get_name();
msg.unique_id = get_default_unique_id("fan", fan);
msg.supports_oscillation = traits.supports_oscillation();
msg.supports_speed = traits.supports_speed();
msg.supports_direction = traits.supports_direction();
msg.supported_speed_count = traits.supported_speed_count();
msg.disabled_by_default = fan->is_disabled_by_default();
msg.icon = fan->get_icon();
msg.entity_category = static_cast<enums::EntityCategory>(fan->get_entity_category());
return this->send_list_entities_fan_response(msg);
}
void APIConnection::fan_command(const FanCommandRequest &msg) {
fan::Fan *fan = App.get_fan_by_key(msg.key);
if (fan == nullptr)
return;
auto call = fan->make_call();
if (msg.has_state)
call.set_state(msg.state);
if (msg.has_oscillating)
call.set_oscillating(msg.oscillating);
if (msg.has_speed_level) {
// Prefer level
call.set_speed(msg.speed_level);
}
if (msg.has_direction)
call.set_direction(static_cast<fan::FanDirection>(msg.direction));
call.perform();
}
#endif
#ifdef USE_LIGHT
bool APIConnection::send_light_state(light::LightState *light) {
if (!this->state_subscription_)
return false;
auto traits = light->get_traits();
auto values = light->remote_values;
auto color_mode = values.get_color_mode();
LightStateResponse resp{};
resp.key = light->get_object_id_hash();
resp.state = values.is_on();
resp.color_mode = static_cast<enums::ColorMode>(color_mode);
resp.brightness = values.get_brightness();
resp.color_brightness = values.get_color_brightness();
resp.red = values.get_red();
resp.green = values.get_green();
resp.blue = values.get_blue();
resp.white = values.get_white();
resp.color_temperature = values.get_color_temperature();
resp.cold_white = values.get_cold_white();
resp.warm_white = values.get_warm_white();
if (light->supports_effects())
resp.effect = light->get_effect_name();
return this->send_light_state_response(resp);
}
bool APIConnection::send_light_info(light::LightState *light) {
auto traits = light->get_traits();
ListEntitiesLightResponse msg;
msg.key = light->get_object_id_hash();
msg.object_id = light->get_object_id();
msg.name = light->get_name();
msg.unique_id = get_default_unique_id("light", light);
msg.disabled_by_default = light->is_disabled_by_default();
msg.icon = light->get_icon();
msg.entity_category = static_cast<enums::EntityCategory>(light->get_entity_category());
for (auto mode : traits.get_supported_color_modes())
msg.supported_color_modes.push_back(static_cast<enums::ColorMode>(mode));
msg.legacy_supports_brightness = traits.supports_color_capability(light::ColorCapability::BRIGHTNESS);
msg.legacy_supports_rgb = traits.supports_color_capability(light::ColorCapability::RGB);
msg.legacy_supports_white_value =
msg.legacy_supports_rgb && (traits.supports_color_capability(light::ColorCapability::WHITE) ||
traits.supports_color_capability(light::ColorCapability::COLD_WARM_WHITE));
msg.legacy_supports_color_temperature = traits.supports_color_capability(light::ColorCapability::COLOR_TEMPERATURE) ||
traits.supports_color_capability(light::ColorCapability::COLD_WARM_WHITE);
if (msg.legacy_supports_color_temperature) {
msg.min_mireds = traits.get_min_mireds();
msg.max_mireds = traits.get_max_mireds();
}
if (light->supports_effects()) {
msg.effects.emplace_back("None");
for (auto *effect : light->get_effects())
msg.effects.push_back(effect->get_name());
}
return this->send_list_entities_light_response(msg);
}
void APIConnection::light_command(const LightCommandRequest &msg) {
light::LightState *light = App.get_light_by_key(msg.key);
if (light == nullptr)
return;
auto call = light->make_call();
if (msg.has_state)
call.set_state(msg.state);
if (msg.has_brightness)
call.set_brightness(msg.brightness);
if (msg.has_color_mode)
call.set_color_mode(static_cast<light::ColorMode>(msg.color_mode));
if (msg.has_color_brightness)
call.set_color_brightness(msg.color_brightness);
if (msg.has_rgb) {
call.set_red(msg.red);
call.set_green(msg.green);
call.set_blue(msg.blue);
}
if (msg.has_white)
call.set_white(msg.white);
if (msg.has_color_temperature)
call.set_color_temperature(msg.color_temperature);
if (msg.has_cold_white)
call.set_cold_white(msg.cold_white);
if (msg.has_warm_white)
call.set_warm_white(msg.warm_white);
if (msg.has_transition_length)
call.set_transition_length(msg.transition_length);
if (msg.has_flash_length)
call.set_flash_length(msg.flash_length);
if (msg.has_effect)
call.set_effect(msg.effect);
call.perform();
}
#endif
#ifdef USE_SENSOR
bool APIConnection::send_sensor_state(sensor::Sensor *sensor, float state) {
if (!this->state_subscription_)
return false;
SensorStateResponse resp{};
resp.key = sensor->get_object_id_hash();
resp.state = state;
resp.missing_state = !sensor->has_state();
return this->send_sensor_state_response(resp);
}
bool APIConnection::send_sensor_info(sensor::Sensor *sensor) {
ListEntitiesSensorResponse msg;
msg.key = sensor->get_object_id_hash();
msg.object_id = sensor->get_object_id();
msg.name = sensor->get_name();
msg.unique_id = sensor->unique_id();
if (msg.unique_id.empty())
msg.unique_id = get_default_unique_id("sensor", sensor);
msg.icon = sensor->get_icon();
msg.unit_of_measurement = sensor->get_unit_of_measurement();
msg.accuracy_decimals = sensor->get_accuracy_decimals();
msg.force_update = sensor->get_force_update();
msg.device_class = sensor->get_device_class();
msg.state_class = static_cast<enums::SensorStateClass>(sensor->get_state_class());
msg.disabled_by_default = sensor->is_disabled_by_default();
msg.entity_category = static_cast<enums::EntityCategory>(sensor->get_entity_category());
return this->send_list_entities_sensor_response(msg);
}
#endif
#ifdef USE_SWITCH
bool APIConnection::send_switch_state(switch_::Switch *a_switch, bool state) {
if (!this->state_subscription_)
return false;
SwitchStateResponse resp{};
resp.key = a_switch->get_object_id_hash();
resp.state = state;
return this->send_switch_state_response(resp);
}
bool APIConnection::send_switch_info(switch_::Switch *a_switch) {
ListEntitiesSwitchResponse msg;
msg.key = a_switch->get_object_id_hash();
msg.object_id = a_switch->get_object_id();
msg.name = a_switch->get_name();
msg.unique_id = get_default_unique_id("switch", a_switch);
msg.icon = a_switch->get_icon();
msg.assumed_state = a_switch->assumed_state();
msg.disabled_by_default = a_switch->is_disabled_by_default();
msg.entity_category = static_cast<enums::EntityCategory>(a_switch->get_entity_category());
msg.device_class = a_switch->get_device_class();
return this->send_list_entities_switch_response(msg);
}
void APIConnection::switch_command(const SwitchCommandRequest &msg) {
switch_::Switch *a_switch = App.get_switch_by_key(msg.key);
if (a_switch == nullptr)
return;
if (msg.state) {
a_switch->turn_on();
} else {
a_switch->turn_off();
}
}
#endif
#ifdef USE_TEXT_SENSOR
bool APIConnection::send_text_sensor_state(text_sensor::TextSensor *text_sensor, std::string state) {
if (!this->state_subscription_)
return false;
TextSensorStateResponse resp{};
resp.key = text_sensor->get_object_id_hash();
resp.state = std::move(state);
resp.missing_state = !text_sensor->has_state();
return this->send_text_sensor_state_response(resp);
}
bool APIConnection::send_text_sensor_info(text_sensor::TextSensor *text_sensor) {
ListEntitiesTextSensorResponse msg;
msg.key = text_sensor->get_object_id_hash();
msg.object_id = text_sensor->get_object_id();
msg.name = text_sensor->get_name();
msg.unique_id = text_sensor->unique_id();
if (msg.unique_id.empty())
msg.unique_id = get_default_unique_id("text_sensor", text_sensor);
msg.icon = text_sensor->get_icon();
msg.disabled_by_default = text_sensor->is_disabled_by_default();
msg.entity_category = static_cast<enums::EntityCategory>(text_sensor->get_entity_category());
return this->send_list_entities_text_sensor_response(msg);
}
#endif
#ifdef USE_CLIMATE
bool APIConnection::send_climate_state(climate::Climate *climate) {
if (!this->state_subscription_)
return false;
auto traits = climate->get_traits();
ClimateStateResponse resp{};
resp.key = climate->get_object_id_hash();
resp.mode = static_cast<enums::ClimateMode>(climate->mode);
resp.action = static_cast<enums::ClimateAction>(climate->action);
if (traits.get_supports_current_temperature())
resp.current_temperature = climate->current_temperature;
if (traits.get_supports_two_point_target_temperature()) {
resp.target_temperature_low = climate->target_temperature_low;
resp.target_temperature_high = climate->target_temperature_high;
} else {
resp.target_temperature = climate->target_temperature;
}
if (traits.get_supports_fan_modes() && climate->fan_mode.has_value())
resp.fan_mode = static_cast<enums::ClimateFanMode>(climate->fan_mode.value());
if (!traits.get_supported_custom_fan_modes().empty() && climate->custom_fan_mode.has_value())
resp.custom_fan_mode = climate->custom_fan_mode.value();
if (traits.get_supports_presets() && climate->preset.has_value()) {
resp.preset = static_cast<enums::ClimatePreset>(climate->preset.value());
resp.legacy_away = resp.preset == enums::CLIMATE_PRESET_AWAY;
}
if (!traits.get_supported_custom_presets().empty() && climate->custom_preset.has_value())
resp.custom_preset = climate->custom_preset.value();
if (traits.get_supports_swing_modes())
resp.swing_mode = static_cast<enums::ClimateSwingMode>(climate->swing_mode);
return this->send_climate_state_response(resp);
}
bool APIConnection::send_climate_info(climate::Climate *climate) {
auto traits = climate->get_traits();
ListEntitiesClimateResponse msg;
msg.key = climate->get_object_id_hash();
msg.object_id = climate->get_object_id();
msg.name = climate->get_name();
msg.unique_id = get_default_unique_id("climate", climate);
msg.disabled_by_default = climate->is_disabled_by_default();
msg.icon = climate->get_icon();
msg.entity_category = static_cast<enums::EntityCategory>(climate->get_entity_category());
msg.supports_current_temperature = traits.get_supports_current_temperature();
msg.supports_two_point_target_temperature = traits.get_supports_two_point_target_temperature();
for (auto mode : traits.get_supported_modes())
msg.supported_modes.push_back(static_cast<enums::ClimateMode>(mode));
msg.visual_min_temperature = traits.get_visual_min_temperature();
msg.visual_max_temperature = traits.get_visual_max_temperature();
msg.visual_temperature_step = traits.get_visual_temperature_step();
msg.legacy_supports_away = traits.supports_preset(climate::CLIMATE_PRESET_AWAY);
msg.supports_action = traits.get_supports_action();
for (auto fan_mode : traits.get_supported_fan_modes())
msg.supported_fan_modes.push_back(static_cast<enums::ClimateFanMode>(fan_mode));
for (auto const &custom_fan_mode : traits.get_supported_custom_fan_modes())
msg.supported_custom_fan_modes.push_back(custom_fan_mode);
for (auto preset : traits.get_supported_presets())
msg.supported_presets.push_back(static_cast<enums::ClimatePreset>(preset));
for (auto const &custom_preset : traits.get_supported_custom_presets())
msg.supported_custom_presets.push_back(custom_preset);
for (auto swing_mode : traits.get_supported_swing_modes())
msg.supported_swing_modes.push_back(static_cast<enums::ClimateSwingMode>(swing_mode));
return this->send_list_entities_climate_response(msg);
}
void APIConnection::climate_command(const ClimateCommandRequest &msg) {
climate::Climate *climate = App.get_climate_by_key(msg.key);
if (climate == nullptr)
return;
auto call = climate->make_call();
if (msg.has_mode)
call.set_mode(static_cast<climate::ClimateMode>(msg.mode));
if (msg.has_target_temperature)
call.set_target_temperature(msg.target_temperature);
if (msg.has_target_temperature_low)
call.set_target_temperature_low(msg.target_temperature_low);
if (msg.has_target_temperature_high)
call.set_target_temperature_high(msg.target_temperature_high);
if (msg.has_legacy_away)
call.set_preset(msg.legacy_away ? climate::CLIMATE_PRESET_AWAY : climate::CLIMATE_PRESET_HOME);
if (msg.has_fan_mode)
call.set_fan_mode(static_cast<climate::ClimateFanMode>(msg.fan_mode));
if (msg.has_custom_fan_mode)
call.set_fan_mode(msg.custom_fan_mode);
if (msg.has_preset)
call.set_preset(static_cast<climate::ClimatePreset>(msg.preset));
if (msg.has_custom_preset)
call.set_preset(msg.custom_preset);
if (msg.has_swing_mode)
call.set_swing_mode(static_cast<climate::ClimateSwingMode>(msg.swing_mode));
call.perform();
}
#endif
#ifdef USE_NUMBER
bool APIConnection::send_number_state(number::Number *number, float state) {
if (!this->state_subscription_)
return false;
NumberStateResponse resp{};
resp.key = number->get_object_id_hash();
resp.state = state;
resp.missing_state = !number->has_state();
return this->send_number_state_response(resp);
}
bool APIConnection::send_number_info(number::Number *number) {
ListEntitiesNumberResponse msg;
msg.key = number->get_object_id_hash();
msg.object_id = number->get_object_id();
msg.name = number->get_name();
msg.unique_id = get_default_unique_id("number", number);
msg.icon = number->get_icon();
msg.disabled_by_default = number->is_disabled_by_default();
msg.entity_category = static_cast<enums::EntityCategory>(number->get_entity_category());
msg.unit_of_measurement = number->traits.get_unit_of_measurement();
msg.mode = static_cast<enums::NumberMode>(number->traits.get_mode());
msg.min_value = number->traits.get_min_value();
msg.max_value = number->traits.get_max_value();
msg.step = number->traits.get_step();
return this->send_list_entities_number_response(msg);
}
void APIConnection::number_command(const NumberCommandRequest &msg) {
number::Number *number = App.get_number_by_key(msg.key);
if (number == nullptr)
return;
auto call = number->make_call();
call.set_value(msg.state);
call.perform();
}
#endif
#ifdef USE_SELECT
bool APIConnection::send_select_state(select::Select *select, std::string state) {
if (!this->state_subscription_)
return false;
SelectStateResponse resp{};
resp.key = select->get_object_id_hash();
resp.state = std::move(state);
resp.missing_state = !select->has_state();
return this->send_select_state_response(resp);
}
bool APIConnection::send_select_info(select::Select *select) {
ListEntitiesSelectResponse msg;
msg.key = select->get_object_id_hash();
msg.object_id = select->get_object_id();
msg.name = select->get_name();
msg.unique_id = get_default_unique_id("select", select);
msg.icon = select->get_icon();
msg.disabled_by_default = select->is_disabled_by_default();
msg.entity_category = static_cast<enums::EntityCategory>(select->get_entity_category());
for (const auto &option : select->traits.get_options())
msg.options.push_back(option);
return this->send_list_entities_select_response(msg);
}
void APIConnection::select_command(const SelectCommandRequest &msg) {
select::Select *select = App.get_select_by_key(msg.key);
if (select == nullptr)
return;
auto call = select->make_call();
call.set_option(msg.state);
call.perform();
}
#endif
#ifdef USE_BUTTON
bool APIConnection::send_button_info(button::Button *button) {
ListEntitiesButtonResponse msg;
msg.key = button->get_object_id_hash();
msg.object_id = button->get_object_id();
msg.name = button->get_name();
msg.unique_id = get_default_unique_id("button", button);
msg.icon = button->get_icon();
msg.disabled_by_default = button->is_disabled_by_default();
msg.entity_category = static_cast<enums::EntityCategory>(button->get_entity_category());
msg.device_class = button->get_device_class();
return this->send_list_entities_button_response(msg);
}
void APIConnection::button_command(const ButtonCommandRequest &msg) {
button::Button *button = App.get_button_by_key(msg.key);
if (button == nullptr)
return;
button->press();
}
#endif
#ifdef USE_LOCK
bool APIConnection::send_lock_state(lock::Lock *a_lock, lock::LockState state) {
if (!this->state_subscription_)
return false;
LockStateResponse resp{};
resp.key = a_lock->get_object_id_hash();
resp.state = static_cast<enums::LockState>(state);
return this->send_lock_state_response(resp);
}
bool APIConnection::send_lock_info(lock::Lock *a_lock) {
ListEntitiesLockResponse msg;
msg.key = a_lock->get_object_id_hash();
msg.object_id = a_lock->get_object_id();
msg.name = a_lock->get_name();
msg.unique_id = get_default_unique_id("lock", a_lock);
msg.icon = a_lock->get_icon();
msg.assumed_state = a_lock->traits.get_assumed_state();
msg.disabled_by_default = a_lock->is_disabled_by_default();
msg.entity_category = static_cast<enums::EntityCategory>(a_lock->get_entity_category());
msg.supports_open = a_lock->traits.get_supports_open();
msg.requires_code = a_lock->traits.get_requires_code();
return this->send_list_entities_lock_response(msg);
}
void APIConnection::lock_command(const LockCommandRequest &msg) {
lock::Lock *a_lock = App.get_lock_by_key(msg.key);
if (a_lock == nullptr)
return;
switch (msg.command) {
case enums::LOCK_UNLOCK:
a_lock->unlock();
break;
case enums::LOCK_LOCK:
a_lock->lock();
break;
case enums::LOCK_OPEN:
a_lock->open();
break;
}
}
#endif
#ifdef USE_MEDIA_PLAYER
bool APIConnection::send_media_player_state(media_player::MediaPlayer *media_player) {
if (!this->state_subscription_)
return false;
MediaPlayerStateResponse resp{};
resp.key = media_player->get_object_id_hash();
resp.state = static_cast<enums::MediaPlayerState>(media_player->state);
resp.volume = media_player->volume;
resp.muted = media_player->is_muted();
return this->send_media_player_state_response(resp);
}
bool APIConnection::send_media_player_info(media_player::MediaPlayer *media_player) {
ListEntitiesMediaPlayerResponse msg;
msg.key = media_player->get_object_id_hash();
msg.object_id = media_player->get_object_id();
msg.name = media_player->get_name();
msg.unique_id = get_default_unique_id("media_player", media_player);
msg.icon = media_player->get_icon();
msg.disabled_by_default = media_player->is_disabled_by_default();
msg.entity_category = static_cast<enums::EntityCategory>(media_player->get_entity_category());
auto traits = media_player->get_traits();
msg.supports_pause = traits.get_supports_pause();
return this->send_list_entities_media_player_response(msg);
}
void APIConnection::media_player_command(const MediaPlayerCommandRequest &msg) {
media_player::MediaPlayer *media_player = App.get_media_player_by_key(msg.key);
if (media_player == nullptr)
return;
auto call = media_player->make_call();
if (msg.has_command) {
call.set_command(static_cast<media_player::MediaPlayerCommand>(msg.command));
}
if (msg.has_volume) {
call.set_volume(msg.volume);
}
if (msg.has_media_url) {
call.set_media_url(msg.media_url);
}
call.perform();
}
#endif
#ifdef USE_ESP32_CAMERA
void APIConnection::send_camera_state(std::shared_ptr<esp32_camera::CameraImage> image) {
if (!this->state_subscription_)
return;
if (this->image_reader_.available())
return;
if (image->was_requested_by(esphome::esp32_camera::API_REQUESTER) ||
image->was_requested_by(esphome::esp32_camera::IDLE))
this->image_reader_.set_image(std::move(image));
}
bool APIConnection::send_camera_info(esp32_camera::ESP32Camera *camera) {
ListEntitiesCameraResponse msg;
msg.key = camera->get_object_id_hash();
msg.object_id = camera->get_object_id();
msg.name = camera->get_name();
msg.unique_id = get_default_unique_id("camera", camera);
msg.disabled_by_default = camera->is_disabled_by_default();
msg.icon = camera->get_icon();
msg.entity_category = static_cast<enums::EntityCategory>(camera->get_entity_category());
return this->send_list_entities_camera_response(msg);
}
void APIConnection::camera_image(const CameraImageRequest &msg) {
if (esp32_camera::global_esp32_camera == nullptr)
return;
if (msg.single)
esp32_camera::global_esp32_camera->request_image(esphome::esp32_camera::API_REQUESTER);
if (msg.stream) {
esp32_camera::global_esp32_camera->start_stream(esphome::esp32_camera::API_REQUESTER);
App.scheduler.set_timeout(this->parent_, "api_esp32_camera_stop_stream", ESP32_CAMERA_STOP_STREAM, []() {
esp32_camera::global_esp32_camera->stop_stream(esphome::esp32_camera::API_REQUESTER);
});
}
}
#endif
#ifdef USE_HOMEASSISTANT_TIME
void APIConnection::on_get_time_response(const GetTimeResponse &value) {
if (homeassistant::global_homeassistant_time != nullptr)
homeassistant::global_homeassistant_time->set_epoch_time(value.epoch_seconds);
}
#endif
bool APIConnection::send_log_message(int level, const char *tag, const char *line) {
if (this->log_subscription_ < level)
return false;
// Send raw so that we don't copy too much
auto buffer = this->create_buffer();
// LogLevel level = 1;
buffer.encode_uint32(1, static_cast<uint32_t>(level));
// string message = 3;
buffer.encode_string(3, line, strlen(line));
// SubscribeLogsResponse - 29
return this->send_buffer(buffer, 29);
}
HelloResponse APIConnection::hello(const HelloRequest &msg) {
this->client_info_ = msg.client_info + " (" + this->helper_->getpeername() + ")";
this->helper_->set_log_info(client_info_);
ESP_LOGV(TAG, "Hello from client: '%s'", this->client_info_.c_str());
HelloResponse resp;
resp.api_version_major = 1;
resp.api_version_minor = 6;
resp.server_info = App.get_name() + " (esphome v" ESPHOME_VERSION ")";
resp.name = App.get_name();
this->connection_state_ = ConnectionState::CONNECTED;
return resp;
}
ConnectResponse APIConnection::connect(const ConnectRequest &msg) {
bool correct = this->parent_->check_password(msg.password);
ConnectResponse resp;
// bool invalid_password = 1;
resp.invalid_password = !correct;
if (correct) {
ESP_LOGD(TAG, "%s: Connected successfully", this->client_info_.c_str());
this->connection_state_ = ConnectionState::AUTHENTICATED;
#ifdef USE_HOMEASSISTANT_TIME
if (homeassistant::global_homeassistant_time != nullptr) {
this->send_time_request();
}
#endif
}
return resp;
}
DeviceInfoResponse APIConnection::device_info(const DeviceInfoRequest &msg) {
DeviceInfoResponse resp{};
resp.uses_password = this->parent_->uses_password();
resp.name = App.get_name();
resp.mac_address = get_mac_address_pretty();
resp.esphome_version = ESPHOME_VERSION;
resp.compilation_time = App.get_compilation_time();
resp.model = ESPHOME_BOARD;
#ifdef USE_DEEP_SLEEP
resp.has_deep_sleep = deep_sleep::global_has_deep_sleep;
#endif
#ifdef ESPHOME_PROJECT_NAME
resp.project_name = ESPHOME_PROJECT_NAME;
resp.project_version = ESPHOME_PROJECT_VERSION;
#endif
#ifdef USE_WEBSERVER
resp.webserver_port = USE_WEBSERVER_PORT;
#endif
return resp;
}
void APIConnection::on_home_assistant_state_response(const HomeAssistantStateResponse &msg) {
for (auto &it : this->parent_->get_state_subs()) {
if (it.entity_id == msg.entity_id && it.attribute.value() == msg.attribute) {
it.callback(msg.state);
}
}
}
void APIConnection::execute_service(const ExecuteServiceRequest &msg) {
bool found = false;
for (auto *service : this->parent_->get_user_services()) {
if (service->execute_service(msg)) {
found = true;
}
}
if (!found) {
ESP_LOGV(TAG, "Could not find matching service!");
}
}
void APIConnection::subscribe_home_assistant_states(const SubscribeHomeAssistantStatesRequest &msg) {
state_subs_at_ = 0;
}
bool APIConnection::send_buffer(ProtoWriteBuffer buffer, uint32_t message_type) {
if (this->remove_)
return false;
if (!this->helper_->can_write_without_blocking()) {
delay(0);
APIError err = helper_->loop();
if (err != APIError::OK) {
on_fatal_error();
ESP_LOGW(TAG, "%s: Socket operation failed: %s errno=%d", client_info_.c_str(), api_error_to_str(err), errno);
return false;
}
if (!this->helper_->can_write_without_blocking()) {
// SubscribeLogsResponse
if (message_type != 29) {
ESP_LOGV(TAG, "Cannot send message because of TCP buffer space");
}
delay(0);
return false;
}
}
APIError err = this->helper_->write_packet(message_type, buffer.get_buffer()->data(), buffer.get_buffer()->size());
if (err == APIError::WOULD_BLOCK)
return false;
if (err != APIError::OK) {
on_fatal_error();
if (err == APIError::SOCKET_WRITE_FAILED && errno == ECONNRESET) {
ESP_LOGW(TAG, "%s: Connection reset", client_info_.c_str());
} else {
ESP_LOGW(TAG, "%s: Packet write failed %s errno=%d", client_info_.c_str(), api_error_to_str(err), errno);
}
return false;
}
// Do not set last_traffic_ on send
return true;
}
void APIConnection::on_unauthenticated_access() {
this->on_fatal_error();
ESP_LOGD(TAG, "%s: tried to access without authentication.", this->client_info_.c_str());
}
void APIConnection::on_no_setup_connection() {
this->on_fatal_error();
ESP_LOGD(TAG, "%s: tried to access without full connection.", this->client_info_.c_str());
}
void APIConnection::on_fatal_error() {
this->helper_->close();
this->remove_ = true;
}
} // namespace api
} // namespace esphome
| 36.525934 | 120 | 0.738434 | [
"model"
] |
902ce566f44ee144f003c0dd1c0c00ab0716345a | 20,889 | cpp | C++ | decoder/tests/snapshot_parser_lib/source/ss_to_dcdtree.cpp | rossburton/OpenCSD | 01d44a34f8fc057f4b041c01f8d9502d77fe612f | [
"BSD-3-Clause"
] | 84 | 2015-08-07T09:40:59.000Z | 2022-03-14T09:04:33.000Z | decoder/tests/snapshot_parser_lib/source/ss_to_dcdtree.cpp | rossburton/OpenCSD | 01d44a34f8fc057f4b041c01f8d9502d77fe612f | [
"BSD-3-Clause"
] | 41 | 2016-07-28T09:14:06.000Z | 2022-03-04T10:47:42.000Z | decoder/tests/snapshot_parser_lib/source/ss_to_dcdtree.cpp | rossburton/OpenCSD | 01d44a34f8fc057f4b041c01f8d9502d77fe612f | [
"BSD-3-Clause"
] | 37 | 2016-06-08T15:40:47.000Z | 2022-02-18T09:29:35.000Z | /*
* \file ss_to_dcdtree.cpp
* \brief OpenCSD :
*
* \copyright Copyright (c) 2015, ARM Limited. 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.
*
* 3. Neither the name of the copyright holder 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 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.
*/
#include "ss_to_dcdtree.h"
#include "ss_key_value_names.h"
CreateDcdTreeFromSnapShot::CreateDcdTreeFromSnapShot() :
m_bInit(false),
m_pDecodeTree(0),
m_pReader(0),
m_pErrLogInterface(0),
m_bPacketProcOnly(false),
m_BufferFileName("")
{
m_errlog_handle = 0;
m_add_create_flags = 0;
}
CreateDcdTreeFromSnapShot::~CreateDcdTreeFromSnapShot()
{
destroyDecodeTree();
}
void CreateDcdTreeFromSnapShot::initialise(SnapShotReader *pReader, ITraceErrorLog *pErrLogInterface)
{
if((pErrLogInterface != 0) && (pReader != 0))
{
m_pReader = pReader;
m_pErrLogInterface = pErrLogInterface;
m_errlog_handle = m_pErrLogInterface->RegisterErrorSource("ss2_dcdtree");
m_bInit = true;
}
}
bool CreateDcdTreeFromSnapShot::createDecodeTree(const std::string &SourceName, bool bPacketProcOnly, uint32_t add_create_flags)
{
m_add_create_flags = add_create_flags;
if(m_bInit)
{
if(!m_pReader->snapshotReadOK())
{
LogError("Supplied snapshot reader has not correctly read the snapshot.\n");
return false;
}
m_bPacketProcOnly = bPacketProcOnly;
Parser::TraceBufferSourceTree tree;
if(m_pReader->getTraceBufferSourceTree(SourceName, tree))
{
int numDecodersCreated = 0; // count how many we create - if none then give up.
uint32_t formatter_flags = OCSD_DFRMTR_FRAME_MEM_ALIGN;
/* make a note of the trace binary file name + path to ss directory */
m_BufferFileName = m_pReader->getSnapShotDir() + tree.buffer_info.dataFileName;
ocsd_dcd_tree_src_t src_format = tree.buffer_info.dataFormat == "source_data" ? OCSD_TRC_SRC_SINGLE : OCSD_TRC_SRC_FRAME_FORMATTED;
if (tree.buffer_info.dataFormat == "dstream_coresight")
formatter_flags = OCSD_DFRMTR_HAS_FSYNCS;
/* create the initial device tree */
// TBD: handle syncs / hsyncs data from TPIU
m_pDecodeTree = DecodeTree::CreateDecodeTree(src_format, formatter_flags);
if(m_pDecodeTree == 0)
{
LogError("Failed to create decode tree object\n");
return false;
}
// use our error logger - don't use the tree default.
m_pDecodeTree->setAlternateErrorLogger(m_pErrLogInterface);
if(!bPacketProcOnly)
{
m_pDecodeTree->createMemAccMapper();
}
/* run through each protocol source to this buffer... */
std::map<std::string, std::string>::iterator it = tree.source_core_assoc.begin();
while(it != tree.source_core_assoc.end())
{
Parser::Parsed *etm_dev, *core_dev;
if(m_pReader->getDeviceData(it->first,&etm_dev))
{
// found the device data for this device.
// see if we have a core name (STM / ITM not associated with a core);
std::string coreDevName = it->second;
if(coreDevName.size() > 0)
{
if(m_pReader->getDeviceData(coreDevName,&core_dev))
{
if(createPEDecoder(core_dev->deviceTypeName,etm_dev))
{
numDecodersCreated++;
if(!bPacketProcOnly &&(core_dev->dumpDefs.size() > 0))
{
processDumpfiles(core_dev->dumpDefs);
}
}
else
{
std::ostringstream oss;
oss << "Failed to create decoder for source " << it->first << ".\n";
LogError(oss.str());
}
}
else
{
// Could not find the device data for the core.
// unexpected - since we created the associations.
std::ostringstream oss;
oss << "Failed to get device data for source " << it->first << ".\n";
LogError(oss.str());
}
}
else
{
// none-core source
if(createSTDecoder(etm_dev))
{
numDecodersCreated++;
}
else
{
std::ostringstream oss;
oss << "Failed to create decoder for none core source " << it->first << ".\n";
LogError(oss.str());
}
}
}
else
{
// TBD: could not find the device data for the source.
// again unexpected - suggests ss format error.
std::ostringstream oss;
oss << "Failed to find device data for source " << it->first << ".\n";
LogError(oss.str());
}
if(src_format == OCSD_TRC_SRC_SINGLE)
it = tree.source_core_assoc.end();
else
it++;
}
if(numDecodersCreated == 0)
{
// nothing useful found
destroyDecodeTree();
}
}
else
{
std::ostringstream oss;
oss << "Failed to get parsed source tree for buffer " << SourceName << ".\n";
LogError(oss.str());
}
}
return (bool)(m_pDecodeTree != 0);
}
void CreateDcdTreeFromSnapShot::destroyDecodeTree()
{
if(m_pDecodeTree)
DecodeTree::DestroyDecodeTree(m_pDecodeTree);
m_pDecodeTree = 0;
m_pReader = 0;
m_pErrLogInterface = 0;
m_errlog_handle = 0;
m_BufferFileName = "";
}
void CreateDcdTreeFromSnapShot::LogError(const std::string &msg)
{
ocsdError err(OCSD_ERR_SEV_ERROR,OCSD_ERR_TEST_SS_TO_DECODER,msg);
m_pErrLogInterface->LogError(m_errlog_handle,&err);
}
void CreateDcdTreeFromSnapShot::LogError(const ocsdError &err)
{
m_pErrLogInterface->LogError(m_errlog_handle,&err);
}
bool CreateDcdTreeFromSnapShot::createPEDecoder(const std::string &coreName, Parser::Parsed *devSrc)
{
bool bCreatedDecoder = false;
std::string devTypeName = devSrc->deviceTypeName;
// split off .x from type name.
std::string::size_type pos = devTypeName.find_first_of('.');
if(pos != std::string::npos)
devTypeName = devTypeName.substr(0,pos);
// split according to protocol
if(devTypeName == ETMv4Protocol)
{
bCreatedDecoder = createETMv4Decoder(coreName,devSrc);
}
else if(devTypeName == ETMv3Protocol)
{
bCreatedDecoder = createETMv3Decoder(coreName,devSrc);
}
else if(devTypeName == PTMProtocol || devTypeName == PFTProtocol)
{
bCreatedDecoder = createPTMDecoder(coreName,devSrc);
}
else if (devTypeName == ETEProtocol)
{
bCreatedDecoder = createETEDecoder(coreName, devSrc);
}
return bCreatedDecoder;
}
// create an ETMv4 decoder based on the deviceN.ini file.
bool CreateDcdTreeFromSnapShot::createETMv4Decoder(const std::string &coreName, Parser::Parsed *devSrc, const bool bDataChannel /* = false*/)
{
bool createdDecoder = false;
bool configOK = true;
// generate the config data from the device data.
ocsd_etmv4_cfg config;
regs_to_access_t regs_to_access[] = {
{ ETMv4RegCfg, true, &config.reg_configr, 0 },
{ ETMv4RegIDR, true, &config.reg_traceidr, 0 },
{ ETMv4RegIDR0, true, &config.reg_idr0, 0 },
{ ETMv4RegIDR1, false, &config.reg_idr1, 0x4100F403 },
{ ETMv4RegIDR2, true, &config.reg_idr2, 0 },
{ ETMv4RegIDR8, false, &config.reg_idr8, 0 },
{ ETMv4RegIDR9, false, &config.reg_idr9, 0 },
{ ETMv4RegIDR10, false, &config.reg_idr10, 0 },
{ ETMv4RegIDR11, false, &config.reg_idr11, 0 },
{ ETMv4RegIDR12, false, &config.reg_idr12, 0 },
{ ETMv4RegIDR13,false, &config.reg_idr13, 0 },
};
// extract registers
configOK = getRegisters(devSrc->regDefs,sizeof(regs_to_access)/sizeof(regs_to_access_t), regs_to_access);
// extract core profile
if(configOK)
configOK = getCoreProfile(coreName,config.arch_ver,config.core_prof);
// good config - generate the decoder on the tree.
if(configOK)
{
ocsd_err_t err = OCSD_OK;
EtmV4Config configObj(&config);
const char *decoderName = bDataChannel ? OCSD_BUILTIN_DCD_ETMV4D : OCSD_BUILTIN_DCD_ETMV4I;
err = m_pDecodeTree->createDecoder(decoderName, m_add_create_flags | (m_bPacketProcOnly ? OCSD_CREATE_FLG_PACKET_PROC : OCSD_CREATE_FLG_FULL_DECODER),&configObj);
if(err == OCSD_OK)
createdDecoder = true;
else
{
std::string msg = "Snapshot processor : failed to create " + (std::string)decoderName + " decoder on decode tree.";
LogError(ocsdError(OCSD_ERR_SEV_ERROR,err,msg));
}
}
return createdDecoder;
}
bool CreateDcdTreeFromSnapShot::createETEDecoder(const std::string &coreName, Parser::Parsed *devSrc)
{
bool createdDecoder = false;
bool configOK = true;
// generate the config data from the device data.
ocsd_ete_cfg config;
// ete regs are same names Etmv4 in places...
regs_to_access_t regs_to_access[] = {
{ ETMv4RegCfg, true, &config.reg_configr, 0 },
{ ETMv4RegIDR, true, &config.reg_traceidr, 0 },
{ ETMv4RegIDR0, true, &config.reg_idr0, 0 },
{ ETMv4RegIDR1, false, &config.reg_idr1, 0x4100F403 },
{ ETMv4RegIDR2, true, &config.reg_idr2, 0 },
{ ETMv4RegIDR8, false, &config.reg_idr8, 0 },
{ ETERegDevArch, false, &config.reg_devarch, 0x47705A13 },
};
// extract registers
configOK = getRegisters(devSrc->regDefs, sizeof(regs_to_access) / sizeof(regs_to_access_t), regs_to_access);
// extract core profile
if (configOK)
configOK = getCoreProfile(coreName, config.arch_ver, config.core_prof);
// good config - generate the decoder on the tree.
if (configOK)
{
ocsd_err_t err = OCSD_OK;
ETEConfig configObj(&config);
const char *decoderName = OCSD_BUILTIN_DCD_ETE;
err = m_pDecodeTree->createDecoder(decoderName, m_add_create_flags | (m_bPacketProcOnly ? OCSD_CREATE_FLG_PACKET_PROC : OCSD_CREATE_FLG_FULL_DECODER), &configObj);
if (err == OCSD_OK)
createdDecoder = true;
else
{
std::string msg = "Snapshot processor : failed to create " + (std::string)decoderName + " decoder on decode tree.";
LogError(ocsdError(OCSD_ERR_SEV_ERROR, err, msg));
}
}
return createdDecoder;
}
// create an ETMv3 decoder based on the register values in the deviceN.ini file.
bool CreateDcdTreeFromSnapShot::createETMv3Decoder(const std::string &coreName, Parser::Parsed *devSrc)
{
bool createdDecoder = false;
bool configOK = true;
// generate the config data from the device data.
ocsd_etmv3_cfg cfg_regs;
regs_to_access_t regs_to_access[] = {
{ ETMv3PTMRegIDR, true, &cfg_regs.reg_idr, 0 },
{ ETMv3PTMRegCR, true, &cfg_regs.reg_ctrl, 0 },
{ ETMv3PTMRegCCER, true, &cfg_regs.reg_ccer, 0 },
{ ETMv3PTMRegTraceIDR, true, &cfg_regs.reg_trc_id, 0}
};
// extract registers
configOK = getRegisters(devSrc->regDefs,sizeof(regs_to_access)/sizeof(regs_to_access_t), regs_to_access);
// extract core profile
if(configOK)
configOK = getCoreProfile(coreName,cfg_regs.arch_ver,cfg_regs.core_prof);
// good config - generate the decoder on the tree.
if(configOK)
{
EtmV3Config config(&cfg_regs);
ocsd_err_t err = OCSD_OK;
err = m_pDecodeTree->createDecoder(OCSD_BUILTIN_DCD_ETMV3, m_bPacketProcOnly ? OCSD_CREATE_FLG_PACKET_PROC : OCSD_CREATE_FLG_FULL_DECODER,&config);
if(err == OCSD_OK)
createdDecoder = true;
else
LogError(ocsdError(OCSD_ERR_SEV_ERROR,err,"Snapshot processor : failed to create ETMV3 decoder on decode tree."));
}
return createdDecoder;
}
bool CreateDcdTreeFromSnapShot::createPTMDecoder(const std::string &coreName, Parser::Parsed *devSrc)
{
bool createdDecoder = false;
bool configOK = true;
// generate the config data from the device data.
ocsd_ptm_cfg config;
regs_to_access_t regs_to_access[] = {
{ ETMv3PTMRegIDR, true, &config.reg_idr, 0 },
{ ETMv3PTMRegCR, true, &config.reg_ctrl, 0 },
{ ETMv3PTMRegCCER, true, &config.reg_ccer, 0 },
{ ETMv3PTMRegTraceIDR, true, &config.reg_trc_id, 0}
};
// extract registers
configOK = getRegisters(devSrc->regDefs,sizeof(regs_to_access)/sizeof(regs_to_access_t), regs_to_access);
// extract core profile
if(configOK)
configOK = getCoreProfile(coreName,config.arch_ver,config.core_prof);
// good config - generate the decoder on the tree.
if(configOK)
{
PtmConfig configObj(&config);
ocsd_err_t err = OCSD_OK;
err = m_pDecodeTree->createDecoder(OCSD_BUILTIN_DCD_PTM, m_bPacketProcOnly ? OCSD_CREATE_FLG_PACKET_PROC : OCSD_CREATE_FLG_FULL_DECODER,&configObj);
if(err == OCSD_OK)
createdDecoder = true;
else
LogError(ocsdError(OCSD_ERR_SEV_ERROR,err,"Snapshot processor : failed to create PTM decoder on decode tree."));
}
return createdDecoder;
}
bool CreateDcdTreeFromSnapShot::createSTDecoder(Parser::Parsed *devSrc)
{
bool bCreatedDecoder = false;
std::string devTypeName = devSrc->deviceTypeName;
// split off .x from type name.
std::string::size_type pos = devTypeName.find_first_of('.');
if(pos != std::string::npos)
devTypeName = devTypeName.substr(0,pos);
if(devTypeName == STMProtocol)
{
bCreatedDecoder = createSTMDecoder(devSrc);
}
return bCreatedDecoder;
}
bool CreateDcdTreeFromSnapShot::createSTMDecoder(Parser::Parsed *devSrc)
{
bool createdDecoder = false;
bool configOK = true;
// generate the config data from the device data.
ocsd_stm_cfg config;
regs_to_access_t regs_to_access[] = {
{ STMRegTCSR, true, &config.reg_tcsr, 0 }
};
configOK = getRegisters(devSrc->regDefs,sizeof(regs_to_access)/sizeof(regs_to_access_t), regs_to_access);
if(configOK)
{
ocsd_err_t err = OCSD_OK;
STMConfig configObj(&config);
err = m_pDecodeTree->createDecoder(OCSD_BUILTIN_DCD_STM, m_bPacketProcOnly ? OCSD_CREATE_FLG_PACKET_PROC : OCSD_CREATE_FLG_FULL_DECODER,&configObj);
if(err == OCSD_OK)
createdDecoder = true;
else
LogError(ocsdError(OCSD_ERR_SEV_ERROR,err,"Snapshot processor : failed to create STM decoder on decode tree."));
}
return createdDecoder;
}
// get a set of register values.
bool CreateDcdTreeFromSnapShot::getRegisters(std::map<std::string, std::string, Util::CaseInsensitiveLess> ®Defs, int numRegs, regs_to_access_t *reg_access_array)
{
bool regsOK = true;
for(int rv = 0; rv < numRegs; rv++)
{
if(!getRegByPrefix( regDefs,reg_access_array[rv]))
regsOK = false;
}
return regsOK;
}
// strip out any parts with brackets
bool CreateDcdTreeFromSnapShot::getRegByPrefix(std::map<std::string, std::string, Util::CaseInsensitiveLess> ®Defs,
regs_to_access_t ®_accessor)
{
std::ostringstream oss;
bool bFound = false;
std::map<std::string, std::string, Util::CaseInsensitiveLess>::iterator it;
std::string prefix_cmp;
std::string::size_type pos;
std::string strval;
*reg_accessor.value = 0;
it = regDefs.begin();
while((it != regDefs.end()) && !bFound)
{
prefix_cmp = it->first;
pos = prefix_cmp.find_first_of('(');
if(pos != std::string::npos)
{
prefix_cmp = prefix_cmp.substr(0, pos);
}
if(prefix_cmp == reg_accessor.pszName)
{
strval = it->second;
bFound = true;
}
it++;
}
if(bFound)
*reg_accessor.value = strtoul(strval.c_str(),0,0);
else
{
ocsd_err_severity_t sev = OCSD_ERR_SEV_ERROR;
if(reg_accessor.failIfMissing)
{
oss << "Error:";
}
else
{
// no fail if missing - set any default and just warn.
bFound = true;
oss << "Warning: Default set for register. ";
sev = OCSD_ERR_SEV_WARN;
*reg_accessor.value = reg_accessor.val_default;
}
oss << "Missing " << reg_accessor.pszName << "\n";
m_pErrLogInterface->LogMessage(m_errlog_handle, sev, oss.str());
}
return bFound;
}
bool CreateDcdTreeFromSnapShot::getCoreProfile(const std::string &coreName, ocsd_arch_version_t &arch_ver, ocsd_core_profile_t &core_prof)
{
bool profileOK = true;
ocsd_arch_profile_t ap = m_arch_profiles.getArchProfile(coreName);
if(ap.arch != ARCH_UNKNOWN)
{
arch_ver = ap.arch;
core_prof = ap.profile;
}
else
{
std::ostringstream oss;
oss << "Unrecognized Core name " << coreName << ". Cannot evaluate profile or architecture.";
LogError(oss.str());
profileOK = false;
}
return profileOK;
}
void CreateDcdTreeFromSnapShot::processDumpfiles(std::vector<Parser::DumpDef> &dumps)
{
std::string dumpFilePathName;
std::vector<Parser::DumpDef>::const_iterator it;
it = dumps.begin();
while(it != dumps.end())
{
dumpFilePathName = m_pReader->getSnapShotDir() + it->path;
ocsd_file_mem_region_t region;
ocsd_err_t err = OCSD_OK;
region.start_address = it->address;
region.file_offset = it->offset;
region.region_size = it->length;
// ensure we respect optional length and offset parameter and
// allow multiple dump entries with same file name to define regions
if (!TrcMemAccessorFile::isExistingFileAccessor(dumpFilePathName))
err = m_pDecodeTree->addBinFileRegionMemAcc(®ion, 1, OCSD_MEM_SPACE_ANY, dumpFilePathName);
else
err = m_pDecodeTree->updateBinFileRegionMemAcc(®ion, 1, OCSD_MEM_SPACE_ANY, dumpFilePathName);
if(err != OCSD_OK)
{
std::ostringstream oss;
oss << "Failed to create memory accessor for file " << dumpFilePathName << ".";
LogError(ocsdError(OCSD_ERR_SEV_ERROR,err,oss.str()));
}
it++;
}
}
/* End of File ss_to_dcdtree.cpp */
| 35.345178 | 171 | 0.614917 | [
"object",
"vector"
] |
9032ca2be6f56fc197499db85b7f8059698e51f0 | 414 | hpp | C++ | exercises/4/seminar/8/Matrix - Complete (7)/Matrix/linearSystem.hpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 19 | 2020-02-21T16:46:50.000Z | 2022-01-26T19:59:49.000Z | exercises/4/seminar/7/Matrix - Complete/Matrix/linearSystem.hpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 1 | 2020-03-14T08:09:45.000Z | 2020-03-14T08:09:45.000Z | exercises/4/seminar/8/Matrix - Complete (7)/Matrix/linearSystem.hpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 11 | 2020-02-23T12:29:58.000Z | 2021-04-11T08:30:12.000Z | #include <iostream>
#include "rational.hpp"
#include "vector.hpp"
#include "matrix.hpp"
using namespace std;
#pragma once
class LinearSystem {
Matrix m;
void rightTriangle();
public:
LinearSystem(const Matrix& m);
Vector getSolution();
void print(ostream& out) const;
void read(istream& in);
};
ostream& operator<<(ostream& out, const LinearSystem& ls);
istream& operator>>(istream& in, LinearSystem& ls); | 20.7 | 58 | 0.731884 | [
"vector"
] |
9036ce43e78d807d6074eeff579c4dd5d066ec9a | 1,225 | cpp | C++ | desktop/Mapper007.cpp | kevlu123/nintondo-enjoyment-service | 3ede5428a122a21f69d7f8f8fa44e89c90badfb7 | [
"MIT"
] | null | null | null | desktop/Mapper007.cpp | kevlu123/nintondo-enjoyment-service | 3ede5428a122a21f69d7f8f8fa44e89c90badfb7 | [
"MIT"
] | null | null | null | desktop/Mapper007.cpp | kevlu123/nintondo-enjoyment-service | 3ede5428a122a21f69d7f8f8fa44e89c90badfb7 | [
"MIT"
] | null | null | null | #include "Mapper007.h"
Mapper007::Mapper007(int mapperNumber, int prgChunks, int chrChunks, std::vector<uint8_t>& prg, std::vector<uint8_t>& chr) :
Mapper(mapperNumber, prgChunks, chrChunks, prg, chr) {
Reset();
}
Mapper007::Mapper007(Savestate& state, std::vector<uint8_t>& prg, std::vector<uint8_t>& chr) :
Mapper(state, prg, chr) {
prgBank = state.Pop<int32_t>();
prgBank &= 0b1111;
mirrorMode = state.Pop<MirrorMode>();
}
Savestate Mapper007::SaveState() const {
auto state = Mapper::SaveState();
state.Push<int32_t>(prgBank);
state.Push<MirrorMode>(mirrorMode);
return state;
}
void Mapper007::Reset() {
prgBank = prgChunks / 2 - 1;
mirrorMode = MirrorMode::OneScreenLo;
}
bool Mapper007::MapCpuRead(uint16_t& addr, uint8_t& data, bool readonly) {
uint32_t newAddr;
if (addr >= 0x8000)
newAddr = 0x8000 + prgBank * 0x8000 + (addr & 0x7FFF);
else
newAddr = addr;
return Mapper::MapCpuRead(newAddr, data);
}
bool Mapper007::MapCpuWrite(uint16_t& addr, uint8_t data) {
if (addr >= 0x8000) {
prgBank = data & 0b1111;
mirrorMode = (data & 0b0001'0000) ? MirrorMode::OneScreenHi : MirrorMode::OneScreenLo;
}
return false;
}
MirrorMode Mapper007::GetMirrorMode() const {
return mirrorMode;
}
| 26.06383 | 124 | 0.710204 | [
"vector"
] |
90386b8e0e562439f24226084dfd18536e13026d | 10,596 | cpp | C++ | third_party/WebKit/Source/core/dom/ElementTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/dom/ElementTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/dom/ElementTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 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 "core/dom/Element.h"
#include <memory>
#include "core/dom/Document.h"
#include "core/editing/EditingTestBase.h"
#include "core/frame/LocalFrameView.h"
#include "core/geometry/DOMRect.h"
#include "core/html/HTMLHtmlElement.h"
#include "core/layout/LayoutBoxModelObject.h"
#include "core/paint/PaintLayer.h"
#include "core/testing/DummyPageHolder.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
class ElementTest : public EditingTestBase {};
TEST_F(ElementTest, SupportsFocus) {
Document& document = GetDocument();
DCHECK(isHTMLHtmlElement(document.documentElement()));
document.setDesignMode("on");
document.View()->UpdateAllLifecyclePhases();
EXPECT_TRUE(document.documentElement()->SupportsFocus())
<< "<html> with designMode=on should be focusable.";
}
TEST_F(ElementTest,
GetBoundingClientRectCorrectForStickyElementsAfterInsertion) {
Document& document = GetDocument();
SetBodyContent(
"<style>body { margin: 0 }"
"#scroller { overflow: scroll; height: 100px; width: 100px; }"
"#sticky { height: 25px; position: sticky; top: 0; left: 25px; }"
"#padding { height: 500px; width: 300px; }</style>"
"<div id='scroller'><div id='writer'></div><div id='sticky'></div>"
"<div id='padding'></div></div>");
Element* scroller = document.getElementById("scroller");
Element* writer = document.getElementById("writer");
Element* sticky = document.getElementById("sticky");
ASSERT_TRUE(scroller);
ASSERT_TRUE(writer);
ASSERT_TRUE(sticky);
scroller->scrollTo(50.0, 200.0);
// The sticky element should remain at (0, 25) relative to the viewport due to
// the constraints.
DOMRect* bounding_client_rect = sticky->getBoundingClientRect();
EXPECT_EQ(0, bounding_client_rect->top());
EXPECT_EQ(25, bounding_client_rect->left());
// Insert a new <div> above the sticky. This will dirty layout and invalidate
// the sticky constraints.
writer->setInnerHTML("<div style='height: 100px; width: 700px;'></div>");
EXPECT_EQ(DocumentLifecycle::kVisualUpdatePending,
document.Lifecycle().GetState());
// Requesting the bounding client rect should cause both layout and
// compositing inputs clean to be run, and the sticky result shouldn't change.
bounding_client_rect = sticky->getBoundingClientRect();
EXPECT_EQ(DocumentLifecycle::kCompositingInputsClean,
document.Lifecycle().GetState());
EXPECT_FALSE(sticky->GetLayoutBoxModelObject()
->Layer()
->NeedsCompositingInputsUpdate());
EXPECT_EQ(0, bounding_client_rect->top());
EXPECT_EQ(25, bounding_client_rect->left());
}
TEST_F(ElementTest, OffsetTopAndLeftCorrectForStickyElementsAfterInsertion) {
Document& document = GetDocument();
SetBodyContent(
"<style>body { margin: 0 }"
"#scroller { overflow: scroll; height: 100px; width: 100px; }"
"#sticky { height: 25px; position: sticky; top: 0; left: 25px; }"
"#padding { height: 500px; width: 300px; }</style>"
"<div id='scroller'><div id='writer'></div><div id='sticky'></div>"
"<div id='padding'></div></div>");
Element* scroller = document.getElementById("scroller");
Element* writer = document.getElementById("writer");
Element* sticky = document.getElementById("sticky");
ASSERT_TRUE(scroller);
ASSERT_TRUE(writer);
ASSERT_TRUE(sticky);
scroller->scrollTo(50.0, 200.0);
// The sticky element should be offset to stay at (0, 25) relative to the
// viewport due to the constraints.
EXPECT_EQ(scroller->scrollTop(), sticky->OffsetTop());
EXPECT_EQ(scroller->scrollLeft() + 25, sticky->OffsetLeft());
// Insert a new <div> above the sticky. This will dirty layout and invalidate
// the sticky constraints.
writer->setInnerHTML("<div style='height: 100px; width: 700px;'></div>");
EXPECT_EQ(DocumentLifecycle::kVisualUpdatePending,
document.Lifecycle().GetState());
// Requesting either offset should cause both layout and compositing inputs
// clean to be run, and the sticky result shouldn't change.
EXPECT_EQ(scroller->scrollTop(), sticky->OffsetTop());
EXPECT_EQ(DocumentLifecycle::kCompositingInputsClean,
document.Lifecycle().GetState());
EXPECT_FALSE(sticky->GetLayoutBoxModelObject()
->Layer()
->NeedsCompositingInputsUpdate());
// Dirty layout again, since |OffsetTop| will have cleaned it.
writer->setInnerHTML("<div style='height: 100px; width: 700px;'></div>");
EXPECT_EQ(DocumentLifecycle::kVisualUpdatePending,
document.Lifecycle().GetState());
// Again requesting an offset should cause layout and compositing to be clean.
EXPECT_EQ(scroller->scrollLeft() + 25, sticky->OffsetLeft());
EXPECT_EQ(DocumentLifecycle::kCompositingInputsClean,
document.Lifecycle().GetState());
EXPECT_FALSE(sticky->GetLayoutBoxModelObject()
->Layer()
->NeedsCompositingInputsUpdate());
}
TEST_F(ElementTest, BoundsInViewportCorrectForStickyElementsAfterInsertion) {
Document& document = GetDocument();
SetBodyContent(
"<style>body { margin: 0 }"
"#scroller { overflow: scroll; height: 100px; width: 100px; }"
"#sticky { height: 25px; position: sticky; top: 0; left: 25px; }"
"#padding { height: 500px; width: 300px; }</style>"
"<div id='scroller'><div id='writer'></div><div id='sticky'></div>"
"<div id='padding'></div></div>");
Element* scroller = document.getElementById("scroller");
Element* writer = document.getElementById("writer");
Element* sticky = document.getElementById("sticky");
ASSERT_TRUE(scroller);
ASSERT_TRUE(writer);
ASSERT_TRUE(sticky);
scroller->scrollTo(50.0, 200.0);
// The sticky element should remain at (0, 25) relative to the viewport due to
// the constraints.
IntRect bounds_in_viewport = sticky->BoundsInViewport();
EXPECT_EQ(0, bounds_in_viewport.Y());
EXPECT_EQ(25, bounds_in_viewport.X());
// Insert a new <div> above the sticky. This will dirty layout and invalidate
// the sticky constraints.
writer->setInnerHTML("<div style='height: 100px; width: 700px;'></div>");
EXPECT_EQ(DocumentLifecycle::kVisualUpdatePending,
document.Lifecycle().GetState());
// Requesting the bounds in viewport should cause both layout and compositing
// inputs clean to be run, and the sticky result shouldn't change.
bounds_in_viewport = sticky->BoundsInViewport();
EXPECT_EQ(DocumentLifecycle::kCompositingInputsClean,
document.Lifecycle().GetState());
EXPECT_FALSE(sticky->GetLayoutBoxModelObject()
->Layer()
->NeedsCompositingInputsUpdate());
EXPECT_EQ(0, bounds_in_viewport.Y());
EXPECT_EQ(25, bounds_in_viewport.X());
}
TEST_F(ElementTest, StickySubtreesAreTrackedCorrectly) {
Document& document = GetDocument();
SetBodyContent(
"<div id='ancestor'>"
" <div id='outerSticky' style='position:sticky;'>"
" <div id='child'>"
" <div id='grandchild'></div>"
" <div id='innerSticky' style='position:sticky;'>"
" <div id='greatGrandchild'></div>"
" </div>"
" </div"
" </div>"
"</div>");
LayoutObject* ancestor =
document.getElementById("ancestor")->GetLayoutObject();
LayoutObject* outer_sticky =
document.getElementById("outerSticky")->GetLayoutObject();
LayoutObject* child = document.getElementById("child")->GetLayoutObject();
LayoutObject* grandchild =
document.getElementById("grandchild")->GetLayoutObject();
LayoutObject* inner_sticky =
document.getElementById("innerSticky")->GetLayoutObject();
LayoutObject* great_grandchild =
document.getElementById("greatGrandchild")->GetLayoutObject();
EXPECT_FALSE(ancestor->StyleRef().SubtreeIsSticky());
EXPECT_TRUE(outer_sticky->StyleRef().SubtreeIsSticky());
EXPECT_TRUE(child->StyleRef().SubtreeIsSticky());
EXPECT_TRUE(grandchild->StyleRef().SubtreeIsSticky());
EXPECT_TRUE(inner_sticky->StyleRef().SubtreeIsSticky());
EXPECT_TRUE(great_grandchild->StyleRef().SubtreeIsSticky());
// This forces 'child' to fork it's StyleRareInheritedData, so that we can
// ensure that the sticky subtree update behavior survives forking.
document.getElementById("child")->SetInlineStyleProperty(
CSSPropertyWebkitRubyPosition, CSSValueAfter);
document.View()->UpdateAllLifecyclePhases();
EXPECT_EQ(DocumentLifecycle::kPaintClean, document.Lifecycle().GetState());
EXPECT_EQ(RubyPosition::kBefore, outer_sticky->StyleRef().GetRubyPosition());
EXPECT_EQ(RubyPosition::kAfter, child->StyleRef().GetRubyPosition());
EXPECT_EQ(RubyPosition::kAfter, grandchild->StyleRef().GetRubyPosition());
EXPECT_EQ(RubyPosition::kAfter, inner_sticky->StyleRef().GetRubyPosition());
EXPECT_EQ(RubyPosition::kAfter,
great_grandchild->StyleRef().GetRubyPosition());
// Setting -webkit-ruby value shouldn't have affected the sticky subtree bit.
EXPECT_TRUE(outer_sticky->StyleRef().SubtreeIsSticky());
EXPECT_TRUE(child->StyleRef().SubtreeIsSticky());
EXPECT_TRUE(grandchild->StyleRef().SubtreeIsSticky());
EXPECT_TRUE(inner_sticky->StyleRef().SubtreeIsSticky());
EXPECT_TRUE(great_grandchild->StyleRef().SubtreeIsSticky());
// Now switch 'outerSticky' back to being non-sticky - all descendents between
// it and the 'innerSticky' should be updated, and the 'innerSticky' should
// fork it's StyleRareInheritedData to maintain the sticky subtree bit.
document.getElementById("outerSticky")
->SetInlineStyleProperty(CSSPropertyPosition, CSSValueStatic);
document.View()->UpdateAllLifecyclePhases();
EXPECT_EQ(DocumentLifecycle::kPaintClean, document.Lifecycle().GetState());
EXPECT_FALSE(outer_sticky->StyleRef().SubtreeIsSticky());
EXPECT_FALSE(child->StyleRef().SubtreeIsSticky());
EXPECT_FALSE(grandchild->StyleRef().SubtreeIsSticky());
EXPECT_TRUE(inner_sticky->StyleRef().SubtreeIsSticky());
EXPECT_TRUE(great_grandchild->StyleRef().SubtreeIsSticky());
}
TEST_F(ElementTest, GetElementsByClassNameCrash) {
// Test for a crash in NodeListsNodeData::AddCache().
ASSERT_TRUE(GetDocument().InQuirksMode());
GetDocument().body()->getElementsByClassName("ABC DEF");
GetDocument().body()->getElementsByClassName("ABC DEF");
// The test passes if no crash happens.
}
} // namespace blink
| 42.047619 | 80 | 0.709796 | [
"geometry"
] |
903908d3bdc48a38ac7490d9d3184cf43d5c3a5d | 1,126 | cpp | C++ | source/ops/gpu/runtime/OpenCLUtil.cpp | ishine/MAI | 64753cd2f59af2949896937c2e5dbfc4d8bab1e0 | [
"Apache-2.0"
] | null | null | null | source/ops/gpu/runtime/OpenCLUtil.cpp | ishine/MAI | 64753cd2f59af2949896937c2e5dbfc4d8bab1e0 | [
"Apache-2.0"
] | null | null | null | source/ops/gpu/runtime/OpenCLUtil.cpp | ishine/MAI | 64753cd2f59af2949896937c2e5dbfc4d8bab1e0 | [
"Apache-2.0"
] | null | null | null | #include "OpenCLUtil.h"
namespace MAI {
MAI_STATUS run1DKernel(OpenCLRuntime* runtime, cl::Kernel& kernel,
std::vector<uint32>& gws, std::vector<uint32>& lws, cl::Event& event) {
//cl::Event event;
ALOGI("run1DKernel");
cl_int ret = runtime->commandQueue().enqueueNDRangeKernel(kernel, 0,
cl::NDRange(gws[0]), cl::NDRange(lws[0]), NULL, &event);
if (ret != CL_SUCCESS) {
ALOGE("enqueueNDRangeKernel error:%s", runtime->openCLErrorCodeToString(ret).c_str());
return MAI_FAILED;
}
ALOGI("run1DKernel wait");
//ALOGI("run1DKernel end cost:%lu us", (end - start));
return MAI_SUCCESS;
}
MAI_STATUS run2DKernel(OpenCLRuntime* runtime, cl::Kernel& kernel,
std::vector<uint32>& gws, std::vector<uint32>& lws) {
cl::Event event;
runtime->commandQueue().enqueueNDRangeKernel(kernel, 0,
cl::NDRange(gws[0], gws[1]), cl::NDRange(lws[0], lws[1]), NULL, &event);
event.wait();
return MAI_SUCCESS;
}
std::vector<uint32> default1DLocalWorkSize(OpenCLRuntime* runtime,
const std::vector<uint32>& gws) {
}
} // namespace MAI
| 32.171429 | 94 | 0.650977 | [
"vector"
] |
903b80c63bd1f10a2dd8a148c728a8b79bfe9138 | 48,873 | cpp | C++ | source/graphics/brdisplayopengl.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 115 | 2015-01-18T17:29:30.000Z | 2022-01-30T04:31:48.000Z | source/graphics/brdisplayopengl.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-22T04:53:38.000Z | 2015-01-31T13:52:40.000Z | source/graphics/brdisplayopengl.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-23T20:06:46.000Z | 2020-05-20T16:06:00.000Z | /***************************************
OpenGL manager class
Copyright (c) 1995-2017 by Rebecca Ann Heineman <becky@burgerbecky.com>
It is released under an MIT Open Source license. Please see LICENSE for
license details. Yes, you can use it in a commercial title without paying
anything, just give me a credit.
Please? It's not like I'm asking you for money!
***************************************/
#include "brdisplayopengl.h"
#if defined(BURGER_OPENGL)
#include "brdebug.h"
#include "brimage.h"
#include "brtextureopengl.h"
#include "brvertexbufferopengl.h"
#include "brnumberto.h"
#include "brmemoryfunctions.h"
// Don't include burger.h
#define __BURGER__
#include "brgl.h"
#include "brglext.h"
// Detect if OpenGL or OpenGL ES version 2.0 is available
#if defined(GL_VERSION_2_0) || defined(GL_ES_VERSION_2_0)
#define USE_GL2
#endif
//
// OpenGL is a derived class for Windows
// to allow multiple API support. All other
// OpenGL based platforms, this is a base class
//
#if !defined(BURGER_WINDOWS)
#define DisplayOpenGL Display
#define TextureOpenGL Texture
#define VertexBufferOpenGL VertexBuffer
#else
#if !defined(DOXYGEN)
BURGER_CREATE_STATICRTTI_PARENT(Burger::DisplayOpenGL,Burger::Display);
#endif
#endif
#if !defined(DOXYGEN)
#define CASE(x) { #x,x }
struct MessageLookup_t {
const char *m_pName;
uint_t m_uEnum;
};
// Used by the shader compiler to force a version match
#if defined(BURGER_OPENGL)
static const char g_Version[] = "#version ";
// Defines inserted into the shader for a vertex or fragment shader
static const char g_VertexShader[] =
"#define VERTEX_SHADER\n"
"#define PIPED varying\n"
"#define VERTEX_INPUT attribute\n";
static const char g_VertexShader140[] =
"#define VERTEX_SHADER\n"
"#define PIPED out\n"
"#define VERTEX_INPUT in\n";
static const char g_FragmentShader[] =
"#define FRAGMENT_SHADER\n"
"#define PIPED varying\n"
"#define FRAGCOLOR_USED\n";
static const char g_FragmentShader140[] =
"#define FRAGMENT_SHADER\n"
"#define PIPED in\n"
"#define FRAGCOLOR_USED out vec4 fragColor;\n"
"#define gl_FragColor fragColor\n"
"#define texture1D texture\n"
"#define texture2D texture\n"
"#define texture3D texture\n"
"#define textureCube texture\n"
"#define textureShadow2D texture\n";
static const GLenum s_SourceFunction[] = {
GL_ZERO, // SRCBLEND_ZERO
GL_ONE, // SRCBLEND_ONE
GL_SRC_COLOR, // SRCBLEND_COLOR
GL_ONE_MINUS_SRC_COLOR, // SRCBLEND_ONE_MINUS_COLOR
GL_SRC_ALPHA, // SRCBLEND_SRC_ALPHA
GL_ONE_MINUS_SRC_ALPHA, // SRCBLEND_ONE_MINUS_SRC_ALPHA
GL_DST_ALPHA, // SRCBLEND_DST_ALPHA,
GL_ONE_MINUS_DST_ALPHA, // SRCBLEND_ONE_MINUS_DST_ALPHA
GL_SRC_ALPHA_SATURATE // SRCBLEND_SRC_ALPHA_SATURATE
};
static const GLenum s_DestFunction[] = {
GL_ZERO, // DSTBLEND_ZERO
GL_ONE, // DSTBLEND_ONE
GL_DST_COLOR, // DSTBLEND_COLOR
GL_ONE_MINUS_DST_COLOR, // DSTBLEND_ONE_MINUS_COLOR
GL_DST_ALPHA, // DSTBLEND_DST_ALPHA
GL_ONE_MINUS_DST_ALPHA, // DSTBLEND_ONE_MINUS_DST_ALPHA
GL_SRC_ALPHA, // DSTBLEND_SRC_ALPHA
GL_ONE_MINUS_SRC_ALPHA // DSTBLEND_ONE_MINUS_SRC_ALPHA
};
static const GLenum s_DepthTest[] = {
GL_NEVER, // DEPTHCMP_NEVER
GL_LESS, // DEPTHCMP_LESS
GL_EQUAL, // DEPTHCMP_EQUAL
GL_LEQUAL, // DEPTHCMP_LESSEQUAL
GL_GREATER, // DEPTHCMP_GREATER
GL_NOTEQUAL, // DEPTHCMP_NOTEQUAL
GL_GEQUAL, // DEPTHCMP_GREATEREQUAL
GL_ALWAYS // DEPTHCMP_ALWAYS
};
static const GLenum s_Prims[] = {
GL_POINTS, // PRIM_POINTS
GL_LINES, // PRIM_LINES,
GL_LINE_STRIP, // PRIM_LINESTRIP,
GL_TRIANGLES, // PRIM_TRIANGLES,
GL_TRIANGLE_STRIP, // PRIM_TRIANGLESTRIP,
GL_TRIANGLE_FAN // PRIM_TRIANGLEFAN
};
#endif
#endif
/*! ************************************
\class Burger::DisplayOpenGL
\brief OpenGL screen setup
Base class for instantiating a video display using OpenGL
\sa Burger::RendererBase, Burger::DisplayBase, Burger::Display, Burger::DisplayDirectX9, Burger::DisplayDirectX11
***************************************/
#if !defined(BURGER_OPENGL) || defined(BURGER_LINUX)
/*! ************************************
\brief Initialize OpenGL
Base class for instantiating a video display using OpenGL
\sa Burger::DisplayOpenGL::~DisplayOpenGL()
***************************************/
Burger::DisplayOpenGL::DisplayOpenGL(Burger::GameApp *pGameApp) :
m_pCompressedFormats(NULL),
m_fOpenGLVersion(0.0f),
m_fShadingLanguageVersion(0.0f),
m_uCompressedFormatCount(0),
m_uMaximumVertexAttributes(0),
m_uMaximumColorAttachments(0),
m_uActiveTexture(0)
{
InitDefaults(pGameApp);
}
/*! ************************************
\brief Start up the OpenGL context
Base class for instantiating a video display using OpenGL
\sa Burger::DisplayOpenGL::PostShutdown()
***************************************/
uint_t Burger::DisplayOpenGL::Init(uint_t,uint_t,uint_t,uint_t)
{
return 10;
}
/*! ************************************
\brief Start up the OpenGL context
Shut down OpenGL
\sa Burger::DisplayOpenGL::PostShutdown()
***************************************/
void Burger::DisplayOpenGL::Shutdown(void)
{
}
void Burger::DisplayOpenGL::BeginScene(void)
{
}
/*! ************************************
\brief Update the video display
Calls SwapBuffers() in OpenGL to draw the rendered scene
\sa Burger::DisplayOpenGL::PreBeginScene()
***************************************/
void Burger::DisplayOpenGL::EndScene(void)
{
}
#endif
Burger::Texture *Burger::DisplayOpenGL::CreateTextureObject(void)
{
return new (Alloc(sizeof(TextureOpenGL))) TextureOpenGL;
}
Burger::VertexBuffer *Burger::DisplayOpenGL::CreateVertexBufferObject(void)
{
return new (Alloc(sizeof(VertexBufferOpenGL))) VertexBufferOpenGL;
}
void Burger::DisplayOpenGL::Resize(uint_t uWidth,uint_t uHeight)
{
SetWidthHeight(uWidth,uHeight);
SetViewport(0,0,uWidth,uHeight);
}
void Burger::DisplayOpenGL::SetViewport(uint_t uX,uint_t uY,uint_t uWidth,uint_t uHeight)
{
glViewport(static_cast<GLint>(uX),static_cast<GLint>(uY),static_cast<GLsizei>(uWidth),static_cast<GLsizei>(uHeight));
}
void Burger::DisplayOpenGL::SetScissorRect(uint_t uX,uint_t uY,uint_t uWidth,uint_t uHeight)
{
// Note: Flip the Y for OpenGL
// Also, the starting Y is the BOTTOM of the rect, not the top
glScissor(static_cast<GLint>(uX),static_cast<GLint>(m_uHeight-(uY+uHeight)),static_cast<GLsizei>(uWidth),static_cast<GLsizei>(uHeight));
}
void Burger::DisplayOpenGL::SetClearColor(float fRed,float fGreen,float fBlue,float fAlpha)
{
glClearColor(fRed,fGreen,fBlue,fAlpha);
}
void Burger::DisplayOpenGL::SetClearDepth(float fDepth)
{
glClearDepth(fDepth);
}
void Burger::DisplayOpenGL::Clear(uint_t uMask)
{
GLbitfield uGLMask = 0;
if (uMask&CLEAR_COLOR) {
uGLMask = GL_COLOR_BUFFER_BIT;
}
if (uMask&CLEAR_DEPTH) {
uGLMask |= GL_DEPTH_BUFFER_BIT;
}
if (uMask&CLEAR_STENCIL) {
uGLMask |= GL_STENCIL_BUFFER_BIT;
}
glClear(uGLMask);
}
void Burger::DisplayOpenGL::Bind(Texture *pTexture,uint_t uIndex)
{
BURGER_ASSERT(uIndex<BURGER_ARRAYSIZE(m_pBoundTextures));
m_pBoundTextures[uIndex] = pTexture;
// Switch to the proper texture unit
uIndex += GL_TEXTURE0;
if (uIndex!=m_uActiveTexture) {
m_uActiveTexture = uIndex;
glActiveTexture(uIndex);
}
// Get the texture ID
if (!pTexture) {
glBindTexture(GL_TEXTURE_2D,0);
} else {
pTexture->CheckLoad(this);
}
}
void Burger::DisplayOpenGL::Bind(Effect *pEffect)
{
#if defined(USE_GL2)
if (!pEffect) {
glUseProgram(0);
} else {
pEffect->CheckLoad(this);
glUseProgram(pEffect->GetProgramID());
}
#else
BURGER_UNUSED(pEffect);
#endif
}
void Burger::DisplayOpenGL::SetBlend(uint_t bEnable)
{
if (bEnable) {
glEnable(GL_BLEND);
} else {
glDisable(GL_BLEND);
}
}
void Burger::DisplayOpenGL::SetBlendFunction(eSourceBlendFactor uSourceFactor,eDestinationBlendFactor uDestFactor)
{
BURGER_ASSERT(uSourceFactor<BURGER_ARRAYSIZE(s_SourceFunction));
BURGER_ASSERT(uDestFactor<BURGER_ARRAYSIZE(s_DestFunction));
glBlendFunc(s_SourceFunction[uSourceFactor],s_DestFunction[uDestFactor]);
}
void Burger::DisplayOpenGL::SetLighting(uint_t bEnable)
{
#if !(defined(BURGER_OPENGLES))
if (bEnable) {
glEnable(GL_LIGHTING);
} else {
glDisable(GL_LIGHTING);
}
#endif
}
void Burger::DisplayOpenGL::SetZWrite(uint_t bEnable)
{
glDepthMask(bEnable!=0);
}
void Burger::DisplayOpenGL::SetDepthTest(eDepthFunction uDepthFunction)
{
BURGER_ASSERT(uDepthFunction<BURGER_ARRAYSIZE(s_DepthTest));
glDepthFunc(s_DepthTest[uDepthFunction]);
if (uDepthFunction==Display::DEPTHCMP_ALWAYS) {
glDisable(GL_DEPTH_TEST);
} else {
glEnable(GL_DEPTH_TEST);
}
}
void Burger::DisplayOpenGL::SetCullMode(eCullMode uCullMode)
{
if (uCullMode==CULL_NONE) {
glDisable(GL_CULL_FACE);
} else if (uCullMode==CULL_CLOCKWISE) {
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
} else if (uCullMode==CULL_COUNTERCLOCKWISE) {
glEnable(GL_CULL_FACE);
glFrontFace(GL_CW);
}
}
void Burger::DisplayOpenGL::SetScissor(uint_t bEnable)
{
if (bEnable) {
glEnable(GL_SCISSOR_TEST);
} else {
glDisable(GL_SCISSOR_TEST);
}
}
void Burger::DisplayOpenGL::DrawPrimitive(ePrimitiveType uPrimitiveType,VertexBuffer *pVertexBuffer)
{
pVertexBuffer->CheckLoad(this);
#if defined(USE_GL2)
glBindVertexArray(static_cast<VertexBufferOpenGL *>(pVertexBuffer)->GetVertexArrayObject());
glDrawArrays(s_Prims[uPrimitiveType],0,static_cast<GLsizei>(static_cast<VertexBufferOpenGL *>(pVertexBuffer)->GetArrayEntryCount()));
#else
BURGER_UNUSED(uPrimitiveType);
BURGER_UNUSED(pVertexBuffer);
#endif
}
void Burger::DisplayOpenGL::DrawElements(ePrimitiveType uPrimitiveType,VertexBuffer *pVertexBuffer)
{
#if defined(USE_GL2)
pVertexBuffer->CheckLoad(this);
glBindVertexArray(static_cast<VertexBufferOpenGL *>(pVertexBuffer)->GetVertexArrayObject());
glDrawElements(s_Prims[uPrimitiveType],static_cast<GLsizei>(static_cast<VertexBufferOpenGL *>(pVertexBuffer)->GetElementEntryCount()),GL_UNSIGNED_SHORT,0);
#else
BURGER_UNUSED(uPrimitiveType);
BURGER_UNUSED(pVertexBuffer);
#endif
}
/*! ************************************
\fn float Burger::DisplayOpenGL::GetOpenGLVersion(void) const
\brief Return the version of the OpenGL implementation
\note This value is valid AFTER the OpenGL driver has been
started up via a call to InitContext().
\return 0.0f if OpenGL is not started or a valid version number, example: 4.4f.
***************************************/
/*! ************************************
\fn float Burger::DisplayOpenGL::GetShadingLanguageVersion(void) const
\brief Return the version of the OpenGL Shader compiler
\note This value is valid AFTER the OpenGL driver has been
started up via a call to InitContext().
\return 0.0f if OpenGL is not started or a valid version number for the compiler, example: 4.4f.
***************************************/
/*! ************************************
\fn uint_t Burger::DisplayOpenGL::GetCompressedFormatCount(void) const
\brief Return the number of supported compressed texture formats
When OpenGL is started, it's queried for the number of compressed texture
formats it natively supports. This will return the number of formats
and GetCompressedFormats() will be an array of this size
with the supported formats.
\note This value is valid AFTER the OpenGL driver has been
started up via a call to InitContext().
\return 0 if OpenGL is not started or no texture compression is supported.
\sa GetCompressedFormats()
***************************************/
/*! ************************************
\fn const uint_t *Burger::DisplayOpenGL::GetCompressedFormats(void) const
\brief Return the pointer to an array of supported compressed texture formats
When OpenGL is started, it's queried for the number of compressed texture
formats it natively supports and the types are stored in this array.
This array size can be retrieved with a call to GetCompressedFormatCount().
\note This value is valid AFTER the OpenGL driver has been
started up via a call to InitContext().
\return \ref NULL if OpenGL is not started or no texture compression is supported or an array of GetCompressedFormatCount() in size.
\sa GetCompressedFormatCount()
***************************************/
/*! ************************************
\brief Initialize the display for supporting OpenGL
Once OpenGL is started, this function queries the driver for
the supported feature list and sets up the rendering status for
best performance in rendering scenes.
\sa InitContext()
***************************************/
#if defined(BURGER_OPENGL) && defined(_DEBUG) && !defined(DOXYGEN)
// Data and a function to dump the OpenGL driver data
// for debugging
struct GLStringIndex_t {
const char *m_pName; // Printable name of the GL string
GLenum m_eEnum; // OpenGL enumeration to check
};
static const GLStringIndex_t g_StringIndexes[] = {
{"OpenGL version",GL_VERSION},
{"Vendor",GL_VENDOR},
{"Renderer",GL_RENDERER},
{"Extensions",GL_EXTENSIONS}
#if defined(USE_GL2)
,{"Shader Language Version",GL_SHADING_LANGUAGE_VERSION}
#endif
};
static const GLStringIndex_t g_TextureIndexes[] = {
{"GL_COMPRESSED_RGB_S3TC_DXT1_EXT",0x83F0},
{"GL_COMPRESSED_RGBA_S3TC_DXT1_EXT",0x83F1},
{"GL_COMPRESSED_RGBA_S3TC_DXT3_EXT",0x83F2},
{"GL_COMPRESSED_RGBA_S3TC_DXT5_EXT",0x83F3},
{"GL_PALETTE4_RGB8_OES",0x8B90},
{"GL_PALETTE4_RGBA8_OES",0x8B91},
{"GL_PALETTE4_R5_G6_B5_OES",0x8B92},
{"GL_PALETTE4_RGBA4_OES",0x8B93},
{"GL_PALETTE4_RGB5_A1_OES",0x8B94},
{"GL_PALETTE8_RGB8_OES",0x8B95},
{"GL_PALETTE8_RGBA8_OES",0x8B96},
{"GL_PALETTE8_R5_G6_B5_OES",0x8B97},
{"GL_PALETTE8_RGBA4_OES",0x8B98},
{"GL_PALETTE8_RGB5_A1_OES",0x8B99},
{"GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG",0x8C00},
{"GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG",0x8C01},
{"GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",0x8C02},
{"GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG",0x8C03},
{"GL_COMPRESSED_R11_EAC",0x9270},
{"GL_COMPRESSED_SIGNED_R11_EAC",0x9271},
{"GL_COMPRESSED_RG11_EAC",0x9272},
{"GL_COMPRESSED_SIGNED_RG11_EAC",0x9273},
{"GL_COMPRESSED_RGB8_ETC2",0x9274},
{"GL_COMPRESSED_SRGB8_ETC2",0x9275},
{"GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2",0x9276},
{"GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2",0x9277},
{"GL_COMPRESSED_RGBA8_ETC2_EAC",0x9278},
{"GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC",0x9279},
{"GL_COMPRESSED_RGBA_ASTC_4x4_KHR",0x93B0},
{"GL_COMPRESSED_RGBA_ASTC_5x4_KHR",0x93B1},
{"GL_COMPRESSED_RGBA_ASTC_5x5_KHR",0x93B2},
{"GL_COMPRESSED_RGBA_ASTC_6x5_KHR",0x93B3},
{"GL_COMPRESSED_RGBA_ASTC_6x6_KHR",0x93B4},
{"GL_COMPRESSED_RGBA_ASTC_8x5_KHR",0x93B5},
{"GL_COMPRESSED_RGBA_ASTC_8x6_KHR",0x93B6},
{"GL_COMPRESSED_RGBA_ASTC_8x8_KHR",0x93B7},
{"GL_COMPRESSED_RGBA_ASTC_10x5_KHR",0x93B8},
{"GL_COMPRESSED_RGBA_ASTC_10x6_KHR",0x93B9},
{"GL_COMPRESSED_RGBA_ASTC_10x8_KHR",0x93BA},
{"GL_COMPRESSED_RGBA_ASTC_10x10_KHR",0x93BB},
{"GL_COMPRESSED_RGBA_ASTC_12x10_KHR",0x93BC},
{"GL_COMPRESSED_RGBA_ASTC_12x12_KHR",0x93BD},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR",0x93D0},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR",0x93D1},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR",0x93D2},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR",0x93D3},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR",0x93D4},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR",0x93D5},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR",0x93D6},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR",0x93D7},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR",0x93D8},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR",0x93D9},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR",0x93DA},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR",0x93DB},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR",0x93DC},
{"GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR",0x93DD}
};
#endif
void BURGER_API Burger::DisplayOpenGL::SetupOpenGL(void)
{
const char *pString;
#if defined(_DEBUG)
// For debug version, dump out OpenGL strings to the console
// or logfile.txt
{
uintptr_t uCount = BURGER_ARRAYSIZE(g_StringIndexes);
const GLStringIndex_t *pWork = g_StringIndexes;
do {
// Get the string for the enumeration
pString = reinterpret_cast<const char *>(glGetString(pWork->m_eEnum));
// If supported, print it
if (pString) {
Debug::Message("%s = ",pWork->m_pName);
// Use String() because pResult can be long enough to overrun the buffer
Debug::PrintString(pString);
Debug::PrintString("\n");
}
++pWork;
} while (--uCount);
}
#endif
//
// Obtain the version of OpenGL found
//
float fVersion = 0.0f;
pString = reinterpret_cast<const char *>(glGetString(GL_VERSION));
if (pString) {
if (!MemoryCompare("OpenGL ES ",pString,10)) {
pString += 10;
}
fVersion = AsciiToFloat(pString);
}
m_fOpenGLVersion = fVersion;
//
// Obtain the version of the OpenGL shader compiler
//
fVersion = 0.0f;
#if defined(USE_GL2)
pString = reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION));
if (pString) {
if (!MemoryCompare("OpenGL ES GLSL ES ",pString,18)) {
pString += 18;
}
fVersion = AsciiToFloat(pString);
}
#endif
m_fShadingLanguageVersion = fVersion;
//
// Obtain the supported compressed texture types
//
Free(m_pCompressedFormats);
m_pCompressedFormats = NULL;
uint_t uTemp = 0;
GLint iTemp = 0;
glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB,&iTemp);
#if defined(_DEBUG)
Debug::Message("GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB = %i\n",iTemp);
#endif
if (iTemp) {
GLint iTemp2 = iTemp;
GLint *pBuffer = static_cast<GLint *>(Alloc(sizeof(GLint)*iTemp2));
if (pBuffer) {
glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS_ARB,pBuffer);
uTemp = static_cast<uint_t>(iTemp);
m_pCompressedFormats = reinterpret_cast<uint_t *>(pBuffer);
// Dump the list on debug builds
#if defined(_DEBUG)
char HexString[16];
HexString[0] = '0';
HexString[1] = 'x';
do {
uint32_t uValue = static_cast<uint32_t>(pBuffer[0]);
const char *pFormatName = HexString;
const GLStringIndex_t *pTextureText = g_TextureIndexes;
do {
if (pTextureText->m_eEnum==uValue) {
pFormatName = pTextureText->m_pName;
break;
}
} while (++pTextureText<&g_TextureIndexes[BURGER_ARRAYSIZE(g_TextureIndexes)]);
if (pFormatName==HexString) {
NumberToAsciiHex(HexString+2,uValue,4);
}
Debug::Message("OpenGL supported compressed format %s\n",pFormatName);
++pBuffer;
} while (--iTemp2);
#endif
}
}
m_uCompressedFormatCount = uTemp;
#if defined(USE_GL2)
GLint iMaxAttributes = 1;
glGetIntegerv(GL_MAX_VERTEX_ATTRIBS,&iMaxAttributes);
m_uMaximumVertexAttributes = static_cast<uint_t>(iMaxAttributes);
#endif
#if defined(_DEBUG)
Debug::Message("m_uMaximumVertexAttributes = %u\n",m_uMaximumVertexAttributes);
#endif
// If not supported, preflight with 1 attachment
GLint iMaxColorattachments = 1;
glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS,&iMaxColorattachments);
m_uMaximumColorAttachments = static_cast<uint_t>(iMaxColorattachments);
#if defined(_DEBUG)
Debug::Message("m_uMaximumColorAttachments = %u\n",m_uMaximumColorAttachments);
#endif
m_uActiveTexture = 0;
}
/*! ************************************
\brief Compile an OpenGL shader
Given a string that has the source to a shader, compile it
with OpenGL's GLSL compiler.
If the source doesn't contain a \#version command as the first line, one
will be inserted with the version of the current shader compiler.
A define of \#define VERTEX_SHADER or \#define FRAGMENT_SHADER will be inserted
into the top of the source to support unified shaders
\code
// Magically inserted code
#if __VERSION__ >=140
#ifdef VERTEX_SHADER
#define PIPED out
#define VERTEX_INPUT in
#else
#define PIPED in
#define VERTEX_INPUT attribute
#define FRAGCOLOR_USED out vec4 fragColor;
#define gl_FragColor fragColor
#define texture2D texture
#endif
#else
#define PIPED varying
#define FRAGCOLOR_USED
#endif
\endcode
If the shader fails compilation, the error returned by OpenGL will be output
to Debug::String()
\param GLEnum OpenGL shader enum GL_VERTEX_SHADER or GL_FRAGMENT_SHADER
\param pShaderCode "C" string of the source code of the shader to compile
\param uShaderCodeLength Length of the source code string. If zero, pShaderCode is assumed to be zero terminated
\return Zero if the code can't be compiled, non-zero is a valid OpenGL shader reference
***************************************/
uint_t BURGER_API Burger::DisplayOpenGL::CompileShader(uint_t GLEnum,const char *pShaderCode,uintptr_t uShaderCodeLength) const
{
// Create a blank shader
GLuint uShader = 0;
#if defined(USE_GL2)
// Valid pointer?
if (pShaderCode) {
// Determine the length of the code
if (!uShaderCodeLength) {
uShaderCodeLength = StringLength(pShaderCode);
}
// Any code to parse?
if (uShaderCodeLength) {
// Create the shader
uShader = glCreateShader(GLEnum);
if (uShader) {
const char *ShaderArray[3]; // Array of shader strings
GLint ShaderLengthArray[3];
char VersionString[64]; // Buffer for the optional "#version xxx\n" string
GLsizei iIndex = 0;
// Get the actual shader compiler version
int32_t iVersion = static_cast<int32_t>(GetShadingLanguageVersion()*100.0f);
// If a version opcode already exists, don't insert one
if ((uShaderCodeLength<8) || MemoryCompare(g_Version,pShaderCode,8)) {
// Since the first line isn't #version, create one
StringCopy(VersionString,g_Version);
NumberToAscii(VersionString+9,iVersion);
uintptr_t uLength = StringLength(VersionString);
// Append with a \n
VersionString[uLength] = '\n';
// Set the string in the array
ShaderArray[0] = VersionString;
ShaderLengthArray[0] = static_cast<GLint>(uLength+1);
iIndex=1;
} else {
// Use the version found in the shader to determine the macros to use
iVersion = AsciiToInteger(pShaderCode+8,iVersion,0,iVersion);
}
// Insert a #define for known shader types so
// unified shaders can compile only what's
// needed
const char *pDefines;
uintptr_t uDefinesLength;
switch (GLEnum) {
case GL_VERTEX_SHADER:
if (iVersion>=140) {
pDefines = g_VertexShader140;
uDefinesLength = sizeof(g_VertexShader140)-1;
} else {
pDefines = g_VertexShader;
uDefinesLength = sizeof(g_VertexShader)-1;
}
break;
case GL_FRAGMENT_SHADER:
if (iVersion>=140) {
pDefines = g_FragmentShader140;
uDefinesLength = sizeof(g_FragmentShader140)-1;
} else {
pDefines = g_FragmentShader;
uDefinesLength = sizeof(g_FragmentShader)-1;
}
break;
default:
pDefines = NULL;
uDefinesLength = 0;
break;
}
if (pDefines) {
ShaderArray[iIndex] = pDefines;
ShaderLengthArray[iIndex] = static_cast<GLint>(uDefinesLength);
++iIndex;
}
// Finally, insert the supplied source code
ShaderArray[iIndex] = pShaderCode;
ShaderLengthArray[iIndex] = static_cast<GLint>(uShaderCodeLength);
// Compile the code
glShaderSource(uShader,iIndex+1,ShaderArray,ShaderLengthArray);
glCompileShader(uShader);
GLint bCompiled = GL_FALSE;
// Did it compile okay?
glGetShaderiv(uShader,GL_COMPILE_STATUS,&bCompiled);
if (bCompiled==GL_FALSE) {
// Dump out what happened so a programmer
// can debug the faulty shader
GLint iLogLength;
glGetShaderiv(uShader,GL_INFO_LOG_LENGTH,&iLogLength);
if (iLogLength > 1) {
// iLogLength includes space for the terminating null at the end of the string
GLchar *pLog = static_cast<GLchar*>(Alloc(static_cast<uintptr_t>(iLogLength)));
glGetShaderInfoLog(uShader,iLogLength,&iLogLength,pLog);
// Note: The log could be so long that it could overflow the
// Debug::Message buffer (Which would assert)
// So use Debug::String() to avoid this
Debug::PrintString("Shader compile log:\n");
Debug::PrintString(pLog);
Debug::PrintString("\n");
Free(pLog);
}
glDeleteShader(uShader);
uShader = 0;
}
}
}
}
#else
BURGER_UNUSED(GLEnum);
BURGER_UNUSED(pShaderCode);
BURGER_UNUSED(uShaderCodeLength);
#endif
return uShader;
}
/*! ************************************
\brief Compile and link a unified OpenGL shader
Given a string that has the source to both a vertex and a
fragment shader, compile them with OpenGL's GLSL compiler
and link them all together.
If the shader fails compilation or linking, the error returned
by OpenGL will be output to Debug::String()
\param pUnifiedShader "C" string of the source code of the shader to compile
\param uLength Length of the source code string. If zero, pProgram is assumed to be zero terminated
\param pPosition Pointer to a "C" string of the label to use to attach to the program the vertex position from the vertex buffer object, set to \ref NULL for no connection.
\param pNormal Pointer to a "C" string of the label to use to attach to the program the vertex normals from the vertex buffer object, set to \ref NULL for no connection.
\param pTexcoord Pointer to a "C" string of the label to use to attach to the program the vertex texture coordinates from the vertex buffer object, set to \ref NULL for no connection.
\return Zero if the code can't be compiled, non-zero is a valid OpenGL shader reference
***************************************/
uint_t BURGER_API Burger::DisplayOpenGL::CompileProgram(const char *pUnifiedShader,uintptr_t uLength,const OpenGLVertexInputs_t *pVertexInputs,const uint_t *pMembers) const
{
return CompileProgram(pUnifiedShader,uLength,pUnifiedShader,uLength,pVertexInputs,pMembers);
}
uint_t BURGER_API Burger::DisplayOpenGL::CompileProgram(const char *pVertexShader,uintptr_t uVSLength,const char *pPixelShader,uintptr_t uPSLength,const OpenGLVertexInputs_t *pVertexInputs,const uint_t *pMembers) const
{
GLuint uProgram = 0;
#if defined(USE_GL2)
// Only if there is source to compile
if (pVertexShader) {
// Create a program object
uProgram = glCreateProgram();
uint_t bSuccess = FALSE; // Assume failure
// If any variable names are passed for position, normal or UVs, bind them
// for linkage to a vertex buffer object
if (pVertexInputs) {
uint_t uIndex = pVertexInputs->m_uIndex;
if (uIndex!=VertexBuffer::USAGE_END) {
if (!pMembers) {
GLuint uGLIndex = 0;
do {
glBindAttribLocation(uProgram,uGLIndex,pVertexInputs->m_pName);
++pVertexInputs;
++uGLIndex;
} while (pVertexInputs->m_uIndex!=VertexBuffer::USAGE_END);
} else {
GLuint uGLIndex = 0;
GLuint uGLIndexUsed;
do {
const uint_t *pTempMembers = pMembers;
uint_t uMember = pTempMembers[0];
uGLIndexUsed = uGLIndex;
if (uMember!=VertexBuffer::USAGE_END) {
do {
if (!((uMember^pVertexInputs->m_uIndex)&VertexBuffer::USAGE_TYPEMASK)) {
uGLIndexUsed = static_cast<GLuint>(pTempMembers-pMembers);
break;
}
++pTempMembers;
uMember = pTempMembers[0];
} while (uMember!=VertexBuffer::USAGE_END);
}
glBindAttribLocation(uProgram,uGLIndexUsed,pVertexInputs->m_pName);
++pVertexInputs;
++uGLIndex;
} while (pVertexInputs->m_uIndex!=VertexBuffer::USAGE_END);
}
}
}
// Compile the vertex shader
GLuint uVertexShader = CompileShader(GL_VERTEX_SHADER,pVertexShader,uVSLength);
if (uVertexShader) {
// Attach the vertex shader to our program
glAttachShader(uProgram,uVertexShader);
// Allow the program to be the sole owner of the shader
glDeleteShader(uVertexShader);
// Compile the fragment shader
GLuint uFragmentShader = CompileShader(GL_FRAGMENT_SHADER,pPixelShader,uPSLength);
if (uFragmentShader) {
// Attach the fragment shader to our program
glAttachShader(uProgram,uFragmentShader);
// Allow the program to be the sole owner of the shader
glDeleteShader(uFragmentShader);
// Link everything together!
glLinkProgram(uProgram);
// Check for link failure
GLint iStatus;
glGetProgramiv(uProgram,GL_LINK_STATUS,&iStatus);
if (iStatus==GL_FALSE) {
Debug::PrintString("Failed to link program\n");
// Print out the log
GLint iLogLength;
glGetProgramiv(uProgram,GL_INFO_LOG_LENGTH,&iLogLength);
if (iLogLength > 1) {
GLchar *pErrorLog = static_cast<GLchar*>(Alloc(static_cast<uintptr_t>(iLogLength)));
glGetProgramInfoLog(uProgram,iLogLength,&iLogLength,pErrorLog);
Debug::PrintString("Program link log:\n");
Debug::PrintString(pErrorLog);
Debug::PrintString("\n");
Free(pErrorLog);
}
} else {
// Verify if it's REALLY okay
glValidateProgram(uProgram);
// Is the all clear signaled?
glGetProgramiv(uProgram,GL_VALIDATE_STATUS,&iStatus);
if (iStatus==GL_FALSE) {
// Dump the log for post link validation failures
GLint iLogLength;
glGetProgramiv(uProgram,GL_INFO_LOG_LENGTH,&iLogLength);
Debug::PrintString("Failed to validate program\n");
if (iLogLength > 1) {
GLchar *pErrorLog = static_cast<GLchar*>(Alloc(static_cast<uintptr_t>(iLogLength)));
glGetProgramInfoLog(uProgram, iLogLength, &iLogLength,pErrorLog);
Debug::PrintString("Program validate log:\n");
Debug::PrintString(pErrorLog);
Debug::PrintString("\n");
Free(pErrorLog);
}
} else {
// All good!!!
bSuccess = TRUE;
}
}
}
}
// On failure, dispose of the program
// to prevent memory leaks
if (!bSuccess) {
glDeleteProgram(uProgram);
uProgram = 0;
}
}
#else
BURGER_UNUSED(pVertexShader);
BURGER_UNUSED(uVSLength);
BURGER_UNUSED(pPixelShader);
BURGER_UNUSED(uPSLength);
BURGER_UNUSED(pVertexInputs);
BURGER_UNUSED(pMembers);
#endif
return uProgram;
}
//
// Create a vertex array object
//
uint_t BURGER_API Burger::DisplayOpenGL::CreateVertexArrayObject(const OpenGLVertexBufferObjectDescription_t *pDescription) const
{
GLuint uVertexArrayObjectID = 0;
#if defined(USE_GL2)
if (pDescription) {
// Create a vertex array object
glGenVertexArrays(1,&uVertexArrayObjectID);
if (uVertexArrayObjectID) {
uint_t bSuccess = TRUE; // Assume success!
glBindVertexArray(uVertexArrayObjectID);
GLuint uBufferID;
//
// Are there vertex positions?
//
if (pDescription->m_uPositionSize) {
// Create a vertex buffer object to store positions
glGenBuffers(1,&uBufferID);
GLuint uPosBufferID = uBufferID;
if (!uPosBufferID) {
bSuccess = FALSE;
} else {
glBindBuffer(GL_ARRAY_BUFFER,uPosBufferID);
// Allocate and load position data into the Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER,static_cast<GLsizeiptr>(pDescription->m_uPositionSize),pDescription->m_pPositions,static_cast<GLenum>(pDescription->m_pPositions ? GL_STATIC_DRAW : GL_STREAM_DRAW));
// Enable the position attribute for this Vertex Buffer Object
glEnableVertexAttribArray(0);
// Get the size of the position type so we can set the stride properly
uintptr_t uPositionTypeSize = GetGLTypeSize(pDescription->m_ePositionType);
// Set up the description of the position array
glVertexAttribPointer(0,
static_cast<GLint>(pDescription->m_uPositionElementCount),pDescription->m_ePositionType,
GL_FALSE,static_cast<GLsizei>(pDescription->m_uPositionElementCount*uPositionTypeSize),NULL);
}
}
//
// Are there vertex normals?
//
if (pDescription->m_uNormalSize) {
// Create a vertex buffer object to store positions
glGenBuffers(1,&uBufferID);
GLuint uNormalBufferID = uBufferID;
if (!uNormalBufferID) {
bSuccess = FALSE;
} else {
glBindBuffer(GL_ARRAY_BUFFER,uNormalBufferID);
// Allocate and load position data into the Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER,static_cast<GLsizeiptr>(pDescription->m_uNormalSize),pDescription->m_pNormals,static_cast<GLenum>(pDescription->m_pNormals ? GL_STATIC_DRAW : GL_STREAM_DRAW));
// Enable the normal attribute for this Vertex Buffer Object
glEnableVertexAttribArray(1);
// Get the size of the normal type so we can set the stride properly
uintptr_t uNormalTypeSize = GetGLTypeSize(pDescription->m_eNormalType);
// Set up the description of the normal array
glVertexAttribPointer(1,
static_cast<GLint>(pDescription->m_uNormalElementCount),pDescription->m_eNormalType,
GL_FALSE,static_cast<GLsizei>(pDescription->m_uNormalElementCount*uNormalTypeSize),NULL);
}
}
//
// Are there texture UV coordinates?
//
if (pDescription->m_uTexcoordSize) {
// Create a vertex buffer object to store UV coordinates
glGenBuffers(1,&uBufferID);
GLuint uUVBufferID = uBufferID;
if (!uUVBufferID) {
bSuccess = FALSE;
} else {
glBindBuffer(GL_ARRAY_BUFFER,uUVBufferID);
// Allocate and load UV coordinates into the Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER,static_cast<GLsizeiptr>(pDescription->m_uTexcoordSize),pDescription->m_pTexcoords,static_cast<GLenum>(pDescription->m_pTexcoords ? GL_STATIC_DRAW : GL_STREAM_DRAW));
// Enable the UV coordinates attribute for this Vertex Buffer Object
glEnableVertexAttribArray(2);
// Get the size of the UV coordinates type so we can set the stride properly
uintptr_t uUVTypeSize = GetGLTypeSize(pDescription->m_eTexcoordType);
// Set up the description of the UV coordinates array
glVertexAttribPointer(2,
static_cast<GLint>(pDescription->m_uTexcoordElementCount),pDescription->m_eTexcoordType,
GL_FALSE,static_cast<GLsizei>(pDescription->m_uTexcoordElementCount*uUVTypeSize),NULL);
}
}
if (pDescription->m_uElementSize) {
// Attach the array of elements to the Vertex Buffer Object
glGenBuffers(1,&uBufferID);
GLuint uElementBufferID = uBufferID;
if (!uElementBufferID) {
bSuccess = FALSE;
} else {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,uElementBufferID);
// Allocate and load vertex array element data into Vertex Buffer Object
glBufferData(GL_ELEMENT_ARRAY_BUFFER,static_cast<GLsizeiptr>(pDescription->m_uElementSize),pDescription->m_pElements,static_cast<GLenum>(pDescription->m_pElements ? GL_STATIC_DRAW : GL_STREAM_DRAW));
}
}
// Was there a failure of one of the generated arrays?
if (!bSuccess) {
DeleteVertexArrayObject(uVertexArrayObjectID);
uVertexArrayObjectID = 0;
}
}
}
#else
BURGER_UNUSED(pDescription);
#endif
return uVertexArrayObjectID;
}
/*! ************************************
\brief Dispose of a vertex array object
Dispose of all the vertex objects (GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING)
and the GL_ELEMENT_ARRAY_BUFFER_BINDING object and then
dispose of the vertex array object.
\param uVertexArrayObject OpenGL vertex array object (0 does nothing)
***************************************/
void BURGER_API Burger::DisplayOpenGL::DeleteVertexArrayObject(uint_t uVertexArrayObject) const
{
#if defined(USE_GL2)
if (uVertexArrayObject) {
// Bind the vertex array object so we can get data from it
glBindVertexArray(uVertexArrayObject);
// For every possible attribute set in the vertex array object
GLint iBufferID;
GLuint uBufferID;
GLuint uIndex = 0;
do {
// Get the vertex array object set for that attribute
glGetVertexAttribiv(uIndex,GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING,&iBufferID);
// If there was a vertex array object set...
if (iBufferID) {
//...delete the vertex array object
uBufferID = static_cast<GLuint>(iBufferID);
glDeleteBuffers(1,&uBufferID);
}
} while (++uIndex<m_uMaximumVertexAttributes);
// Get any element array vertex buffer object set in the vertex array object
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING,&iBufferID);
// If there was a element array vertex buffer object set in the vertex array object
if (iBufferID) {
//...delete the VBO
uBufferID = static_cast<GLuint>(iBufferID);
glDeleteBuffers(1,&uBufferID);
}
glBindVertexArray(0);
// Finally, delete the vertex array object
uBufferID = static_cast<GLuint>(uVertexArrayObject);
glDeleteVertexArrays(1,&uBufferID);
}
#else
BURGER_UNUSED(uVertexArrayObject);
#endif
}
/*! ************************************
\brief Create a render target frame buffer
Given a size in pixels, create a texture of a specific bit depth and clamp
type and attach an optional ZBuffer
This frame buffer can be disposed of with a call to DeleteFrameBufferObject(uint_t)
\param uWidth Width of the new frame buffer in pixels
\param uHeight Height of the new frame buffer in pixels
\param uGLDepth OpenGL type for the pixel type of the color buffer, example GL_RGBA
\param uGLClamp OpenGL clamp type for the edge of the frame buffer texture, example GL_CLAMP_TO_EDGE
\param uGLZDepth OpenGL type for the depth buffer, if any. Zero will not generate a depth buffer, GL_DEPTH_COMPONENT16 or equivalent will generate one.
\return Frame buffer ID or zero on failure
\sa DeleteFrameBufferObject(uint_t) const
***************************************/
uint_t BURGER_API Burger::DisplayOpenGL::BuildFrameBufferObject(uint_t uWidth,uint_t uHeight,uint_t uGLDepth,uint_t uGLClamp,uint_t uGLZDepth) const
{
GLuint uFrontBufferObject = 0;
#if defined(USE_GL2)
// Create the front buffer texture
GLuint uColorTextureID;
glGenTextures(1,&uColorTextureID);
glBindTexture(GL_TEXTURE_2D,uColorTextureID);
// Set up filter and wrap modes for this texture object
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,static_cast<GLint>(uGLClamp));
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,static_cast<GLint>(uGLClamp));
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
// OpenGLES sucks rocks on performance, so use GL_LINEAR
#if defined(BURGER_OPENGLES)
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
#else
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
#endif
// Create an uninitialized frame buffer for the requested pixel type
glTexImage2D(GL_TEXTURE_2D,0,static_cast<GLint>(uGLDepth),static_cast<GLsizei>(uWidth),static_cast<GLsizei>(uHeight),0,uGLDepth,GL_UNSIGNED_BYTE,NULL);
// Create a depth buffer if needed
GLuint uDepthRenderbuffer = 0;
if (uGLZDepth) {
glGenRenderbuffers(1,&uDepthRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER,uDepthRenderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER,uGLZDepth,static_cast<GLsizei>(uWidth),static_cast<GLsizei>(uHeight));
}
// Create the frame buffer
glGenFramebuffers(1,&uFrontBufferObject);
glBindFramebuffer(GL_FRAMEBUFFER,uFrontBufferObject);
// Attach the color texture
glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,uColorTextureID,0);
// Attach the optional depth texture buffer
if (uDepthRenderbuffer) {
glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_RENDERBUFFER,uDepthRenderbuffer);
}
// Is this all kosher? Or are the happy feelings gone?
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
// Dispose everything
DeleteFrameBufferObject(uFrontBufferObject);
uFrontBufferObject = 0;
}
#else
BURGER_UNUSED(uWidth);
BURGER_UNUSED(uHeight);
BURGER_UNUSED(uGLDepth);
BURGER_UNUSED(uGLClamp);
BURGER_UNUSED(uGLZDepth);
#endif
// Exit with the frame buffer or zero
return uFrontBufferObject;
}
/*! ************************************
\brief Dispose of a frame buffer data object's attachment
Given an OpenGL frame buffer attachment like GL_DEPTH_ATTACHMENT, delete
it from the currently bound Framebuffer. It will first query the
attachment to determine if it's a GL_RENDERBUFFER or a GL_TEXTURE
and call the appropriate disposal routine
\param uAttachment OpenGL attachment enumeration
\sa DeleteFrameBufferObject(uint_t) const
***************************************/
void BURGER_API Burger::DisplayOpenGL::DeleteFrameBufferObjectAttachment(uint_t uAttachment)
{
#if defined(USE_GL2)
GLint iObjectID;
// Get the type of frame buffer
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,uAttachment,GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,&iObjectID);
GLuint uObjectID;
// If it's a render buffer, call glDeleteRenderbuffers()
if (GL_RENDERBUFFER == iObjectID) {
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,uAttachment,GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,&iObjectID);
uObjectID = static_cast<GLuint>(iObjectID);
glDeleteRenderbuffers(1,&uObjectID);
// If it's a texture buffer, call glDeleteTextures()
} else if (GL_TEXTURE == iObjectID) {
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,uAttachment,GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,&iObjectID);
uObjectID = static_cast<GLuint>(iObjectID);
glDeleteTextures(1,&uObjectID);
}
#else
BURGER_UNUSED(uAttachment);
#endif
}
/*! ************************************
\brief Dispose of a frame buffer data object
Given an OpenGL frame buffer, dispose of it and everything attached to it.
\param uFrameBufferObject OpenGL frame buffer (Zero does nothing)
\sa BuildFrameBufferObject(uint_t,uint_t,uint_t,uint_t,uint_t) const or DeleteFrameBufferObjectAttachment(uint_t)
***************************************/
void BURGER_API Burger::DisplayOpenGL::DeleteFrameBufferObject(uint_t uFrameBufferObject) const
{
#if defined(USE_GL2)
if (uFrameBufferObject) {
glBindFramebuffer(GL_FRAMEBUFFER,uFrameBufferObject);
uint_t uCount = m_uMaximumColorAttachments;
if (uCount) {
uint_t uColorAttachment = GL_COLOR_ATTACHMENT0;
do {
// For every color buffer attached delete the attachment
DeleteFrameBufferObjectAttachment(uColorAttachment);
++uColorAttachment;
} while (--uCount);
}
// Delete any depth or stencil buffer attached
DeleteFrameBufferObjectAttachment(GL_DEPTH_ATTACHMENT);
DeleteFrameBufferObjectAttachment(GL_STENCIL_ATTACHMENT);
GLuint uObjectID = static_cast<GLuint>(uFrameBufferObject);
glDeleteFramebuffers(1,&uObjectID);
}
#else
BURGER_UNUSED(uFrameBufferObject);
#endif
}
/*! ************************************
\brief Create an OpenGL texture
Given a bit map image, upload it to the OpenGL system while
trying to retain the format as close as possible.
Mip Maps are supported.
\param pImage Pointer to a valid image structure
\param bGenerateMipMap If \ref TRUE and the image is a single image, alert OpenGL to automatically generate mipmaps
\return Zero on failure (OpenGL allocation or Image isn't a format that can be uploaded)
***************************************/
uint_t BURGER_API Burger::DisplayOpenGL::CreateTextureID(const Image *pImage,uint_t bGenerateMipMap)
{
GLuint uTextureID = 0;
Image::ePixelTypes eType = pImage->GetType();
GLenum iType = GL_UNSIGNED_BYTE;
GLenum iFormat = 0;
switch (eType) {
case Image::PIXELTYPE888:
iFormat = GL_RGB;
break;
case Image::PIXELTYPE8888:
iFormat = GL_RGBA;
break;
default:
break;
}
// Is the format supported?
if (iFormat) {
// Start with creating a new texture instance
glGenTextures(1,&uTextureID);
// Got a texture?
if (uTextureID) {
// Bind it
glBindTexture(GL_TEXTURE_2D,uTextureID);
// Set up filter and wrap modes for this texture object
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
GLint iParm = GL_LINEAR;
// Mip mapped?
if (bGenerateMipMap || (pImage->GetMipMapCount()>=2)) {
iParm = GL_LINEAR_MIPMAP_LINEAR;
}
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,iParm);
// Bytes are packed together (Needed for RGB format)
glPixelStorei(GL_UNPACK_ALIGNMENT,1);
// If the bytes in the image are packed together, then
// it's a simple upload, otherwise, do it the hard way
uint_t uMipMap = 0;
do {
uint_t uWidth = pImage->GetWidth(uMipMap);
uint_t uHeight = pImage->GetHeight(uMipMap);
const uint8_t *pSource = pImage->GetImage(uMipMap);
if (uMipMap || (pImage->GetSuggestedStride()==pImage->GetStride())) {
// Allocate and load image data into texture in one go
glTexImage2D(GL_TEXTURE_2D,static_cast<GLint>(uMipMap),static_cast<GLint>(iFormat),static_cast<GLsizei>(uWidth),static_cast<GLsizei>(uHeight),0,iFormat,iType,pSource);
} else {
// Allocate the memory for the texture
glTexImage2D(GL_TEXTURE_2D,0,static_cast<GLint>(iFormat),static_cast<GLsizei>(uWidth),static_cast<GLsizei>(uHeight),0,iFormat,iType,NULL);
// Upload one line at a time to support stride
if (uHeight) {
uint_t uY=0;
uintptr_t uStride = pImage->GetStride(uMipMap);
do {
glTexSubImage2D(GL_TEXTURE_2D,0,0,static_cast<GLsizei>(uY),static_cast<GLsizei>(uWidth),1,iFormat,iType,pSource);
pSource += uStride;
++uY;
} while (--uHeight);
}
}
} while (++uMipMap<pImage->GetMipMapCount());
// If the texture doesn't have a mip map and one is requested, generate it
#if defined(USE_GL2)
if (bGenerateMipMap && (pImage->GetMipMapCount()<2)) {
glGenerateMipmap(GL_TEXTURE_2D);
}
#endif
}
}
return static_cast<uint_t>(uTextureID);
}
/*! ************************************
\brief Convert an OpenGL error enumeration into a string
Given an enum from a call to glGetError(), call this function
convert the number into a string describing the error.
\param uGLErrorEnum OpenGL error enum
\return Pointer to a "C" string with the error message (Don't dispose)
***************************************/
static const MessageLookup_t g_GetErrorString[] = {
CASE(GL_NO_ERROR),
CASE(GL_INVALID_VALUE),
CASE(GL_INVALID_OPERATION),
CASE(GL_STACK_OVERFLOW),
CASE(GL_STACK_UNDERFLOW),
CASE(GL_OUT_OF_MEMORY),
CASE(GL_INVALID_FRAMEBUFFER_OPERATION),
CASE(GL_TABLE_TOO_LARGE),
CASE(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT),
CASE(GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS),
CASE(GL_FRAMEBUFFER_INCOMPLETE_FORMATS),
CASE(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT),
CASE(GL_FRAMEBUFFER_UNSUPPORTED),
CASE(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER),
CASE(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER)
};
const char * BURGER_API Burger::DisplayOpenGL::GetErrorString(uint_t uGLErrorEnum)
{
const char *pResult = "GL_UNKNOWN_ERROR";
uintptr_t uCount = BURGER_ARRAYSIZE(g_GetErrorString);
const MessageLookup_t *pLookup = g_GetErrorString;
do {
if (uGLErrorEnum==pLookup->m_uEnum) {
pResult = pLookup->m_pName;
break;
}
++pLookup;
} while (--uCount);
return pResult;
}
/*! ************************************
\brief Determine an OpenGL type enumeration byte length
Given an OpenGL data type, such as GL_BYTE, GL_SHORT, or GL_FLOAT,
return the number of bytes such a data chunk would occupy
\param uGLTypeEnum OpenGL data type enum
\return Number of bytes for the type or 0 if unknown
***************************************/
uintptr_t BURGER_API Burger::DisplayOpenGL::GetGLTypeSize(uint_t uGLTypeEnum)
{
uintptr_t uResult;
switch (uGLTypeEnum) {
case GL_BYTE:
uResult = sizeof(GLbyte);
break;
case GL_UNSIGNED_BYTE:
uResult = sizeof(GLubyte);
break;
case GL_SHORT:
uResult = sizeof(GLshort);
break;
case GL_UNSIGNED_SHORT:
uResult = sizeof(GLushort);
break;
case GL_INT:
uResult = sizeof(GLint);
break;
case GL_UNSIGNED_INT:
uResult = sizeof(GLuint);
break;
case GL_FLOAT:
uResult = sizeof(GLfloat);
break;
#if defined(GL_2_BYTES)
case GL_2_BYTES:
uResult = 2;
break;
#endif
#if defined(GL_3_BYTES)
case GL_3_BYTES:
uResult = 3;
break;
#endif
#if defined(GL_4_BYTES)
case GL_4_BYTES:
uResult = 4;
break;
#endif
#if defined(GL_DOUBLE)
case GL_DOUBLE:
uResult = sizeof(GLdouble);
break;
#endif
default:
uResult = 0;
}
return uResult;
}
/*! ************************************
\brief Poll OpenGL for errors and print them
Call glGetError(), and if any errors were found,
print them using Debug::Warning().
Used for debugging OpenGL
\param pErrorLocation Pointer to a string that describes where this
error condition could be occurring.
\return \ref TRUE if an error was found, \ref FALSE if not
***************************************/
uint_t BURGER_API Burger::DisplayOpenGL::PrintGLError(const char *pErrorLocation)
{
uint_t uResult = FALSE;
GLenum eError = glGetError();
if (eError != GL_NO_ERROR) {
do {
Debug::Message("GLError %s set in location %s\n",GetErrorString(static_cast<uint_t>(eError)),pErrorLocation);
eError = glGetError();
} while (eError != GL_NO_ERROR);
uResult = TRUE;
}
return uResult;
}
/*! ************************************
\var const Burger::StaticRTTI Burger::DisplayOpenGL::g_StaticRTTI
\brief The global description of the class
This record contains the name of this class and a
reference to the parent (If any)
***************************************/
#endif
| 30.854167 | 218 | 0.724613 | [
"render",
"object"
] |
9042e7e8389a712016c3ff3ee2a5b84a2906c8c5 | 7,343 | cxx | C++ | ThirdParty/QtTesting/vtkqttesting/pqNativeFileDialogEventTranslator.cxx | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2021-07-07T22:53:19.000Z | 2021-07-31T19:29:35.000Z | ThirdParty/QtTesting/vtkqttesting/pqNativeFileDialogEventTranslator.cxx | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2020-11-18T16:50:34.000Z | 2022-01-21T13:31:47.000Z | ThirdParty/QtTesting/vtkqttesting/pqNativeFileDialogEventTranslator.cxx | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | 5 | 2020-10-02T10:14:35.000Z | 2022-03-10T07:50:22.000Z | /*=========================================================================
Program: ParaView
Module: pqNativeFileDialogEventTranslator.cxx
Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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 "pqNativeFileDialogEventTranslator.h"
#include "pqEventTranslator.h"
#include "pqTestUtility.h"
#include <QApplication>
#include <QEvent>
#include <QFileDialog>
#if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
typedef QString (*_qt_filedialog_existing_directory_hook)(
QWidget* parent, const QString& caption, const QString& dir, QFileDialog::Options options);
extern Q_DECL_IMPORT _qt_filedialog_existing_directory_hook qt_filedialog_existing_directory_hook;
typedef QString (*_qt_filedialog_open_filename_hook)(QWidget* parent, const QString& caption,
const QString& dir, const QString& filter, QString* selectedFilter, QFileDialog::Options options);
extern Q_DECL_IMPORT _qt_filedialog_open_filename_hook qt_filedialog_open_filename_hook;
typedef QStringList (*_qt_filedialog_open_filenames_hook)(QWidget* parent, const QString& caption,
const QString& dir, const QString& filter, QString* selectedFilter, QFileDialog::Options options);
extern Q_DECL_IMPORT _qt_filedialog_open_filenames_hook qt_filedialog_open_filenames_hook;
typedef QString (*_qt_filedialog_save_filename_hook)(QWidget* parent, const QString& caption,
const QString& dir, const QString& filter, QString* selectedFilter, QFileDialog::Options options);
extern Q_DECL_IMPORT _qt_filedialog_save_filename_hook qt_filedialog_save_filename_hook;
namespace
{
pqNativeFileDialogEventTranslator* self;
_qt_filedialog_existing_directory_hook old_existing_directory_hook;
_qt_filedialog_open_filename_hook old_open_filename_hook;
_qt_filedialog_open_filenames_hook old_open_filenames_hook;
_qt_filedialog_save_filename_hook old_save_filename_hook;
QString existing_directory_hook(
QWidget* parent, const QString& caption, const QString& dir, QFileDialog::Options options)
{
qt_filedialog_existing_directory_hook = 0;
QString path = QFileDialog::getExistingDirectory(parent, caption, dir, options);
self->record("DirOpen", path);
qt_filedialog_existing_directory_hook = existing_directory_hook;
return path;
}
QString open_filename_hook(QWidget* parent, const QString& caption, const QString& dir,
const QString& filter, QString* selectedFilter, QFileDialog::Options options)
{
qt_filedialog_open_filename_hook = 0;
QString file =
QFileDialog::getOpenFileName(parent, caption, dir, filter, selectedFilter, options);
self->record("FileOpen", file);
qt_filedialog_open_filename_hook = open_filename_hook;
return file;
}
QStringList open_filenames_hook(QWidget* parent, const QString& caption, const QString& dir,
const QString& filter, QString* selectedFilter, QFileDialog::Options options)
{
qt_filedialog_open_filenames_hook = 0;
QStringList files =
QFileDialog::getOpenFileNames(parent, caption, dir, filter, selectedFilter, options);
self->record("FilesOpen", files.join(";"));
qt_filedialog_open_filenames_hook = open_filenames_hook;
return files;
}
QString save_filename_hook(QWidget* parent, const QString& caption, const QString& dir,
const QString& filter, QString* selectedFilter, QFileDialog::Options options)
{
qt_filedialog_save_filename_hook = 0;
QString file =
QFileDialog::getSaveFileName(parent, caption, dir, filter, selectedFilter, options);
self->record("FileSave", file);
qt_filedialog_save_filename_hook = save_filename_hook;
return file;
}
}
pqNativeFileDialogEventTranslator::pqNativeFileDialogEventTranslator(
pqTestUtility* util, QObject* p)
: pqWidgetEventTranslator(p)
, mUtil(util)
{
QObject::connect(mUtil->eventTranslator(), SIGNAL(started()), this, SLOT(start()));
QObject::connect(mUtil->eventTranslator(), SIGNAL(stopped()), this, SLOT(stop()));
}
pqNativeFileDialogEventTranslator::~pqNativeFileDialogEventTranslator()
{
}
void pqNativeFileDialogEventTranslator::start()
{
self = this;
old_existing_directory_hook = qt_filedialog_existing_directory_hook;
qt_filedialog_existing_directory_hook = existing_directory_hook;
old_open_filename_hook = qt_filedialog_open_filename_hook;
qt_filedialog_open_filename_hook = open_filename_hook;
old_open_filenames_hook = qt_filedialog_open_filenames_hook;
qt_filedialog_open_filenames_hook = open_filenames_hook;
old_save_filename_hook = qt_filedialog_save_filename_hook;
qt_filedialog_save_filename_hook = save_filename_hook;
}
void pqNativeFileDialogEventTranslator::stop()
{
self = NULL;
qt_filedialog_existing_directory_hook = old_existing_directory_hook;
qt_filedialog_open_filename_hook = old_open_filename_hook;
qt_filedialog_open_filenames_hook = old_open_filenames_hook;
qt_filedialog_save_filename_hook = old_save_filename_hook;
}
bool pqNativeFileDialogEventTranslator::translateEvent(
QObject* Object, QEvent* pqNotUsed(Event), bool& pqNotUsed(Error))
{
// capture events under a filedialog and consume them
QObject* tmp = Object;
while (tmp)
{
if (qobject_cast<QFileDialog*>(tmp))
{
return true;
}
tmp = tmp->parent();
}
return false;
}
void pqNativeFileDialogEventTranslator::record(const QString& command, const QString& args)
{
QStringList files = args.split(";");
QStringList normalized_files;
foreach (QString file, files)
{
normalized_files.append(mUtil->convertToDataDirectory(file));
}
emit this->recordEvent(QApplication::instance(), command, normalized_files.join(";"));
}
#else
pqNativeFileDialogEventTranslator::pqNativeFileDialogEventTranslator(
pqTestUtility* util, QObject* p)
: pqWidgetEventTranslator(p)
, mUtil(util)
{
}
pqNativeFileDialogEventTranslator::~pqNativeFileDialogEventTranslator()
{
}
void pqNativeFileDialogEventTranslator::start()
{
}
void pqNativeFileDialogEventTranslator::stop()
{
}
bool pqNativeFileDialogEventTranslator::translateEvent(
QObject* pqNotUsed(Object), QEvent* pqNotUsed(Event), bool& pqNotUsed(Error))
{
return false;
}
void pqNativeFileDialogEventTranslator::record(const QString& command, const QString& args)
{
Q_UNUSED(command);
Q_UNUSED(args);
}
#endif
| 33.377273 | 100 | 0.782923 | [
"object"
] |
90439d13587b1a9a3701ab1077629d0d008f4e05 | 8,448 | cpp | C++ | pxr/imaging/lib/hdSt/rprimUtils.cpp | YuqiaoZhang/USD | bf3a21e6e049486441440ebf8c0387db2538d096 | [
"BSD-2-Clause"
] | 5 | 2017-11-06T10:21:18.000Z | 2020-04-02T13:20:55.000Z | pxr/imaging/lib/hdSt/rprimUtils.cpp | YuqiaoZhang/USD | bf3a21e6e049486441440ebf8c0387db2538d096 | [
"BSD-2-Clause"
] | 1 | 2020-07-07T22:39:42.000Z | 2020-07-07T22:39:42.000Z | pxr/imaging/lib/hdSt/rprimUtils.cpp | YuqiaoZhang/USD | bf3a21e6e049486441440ebf8c0387db2538d096 | [
"BSD-2-Clause"
] | null | null | null | //
// Copyright 2019 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "pxr/imaging/hdSt/rprimUtils.h"
#include "pxr/imaging/hd/rprim.h"
#include "pxr/imaging/hd/rprimSharedData.h"
#include "pxr/imaging/hd/types.h"
#include "pxr/imaging/hd/vtBufferSource.h"
PXR_NAMESPACE_OPEN_SCOPE
void
HdStPopulateConstantPrimvars(
HdRprim* prim,
HdRprimSharedData *sharedData,
HdSceneDelegate* delegate,
HdDrawItem *drawItem,
HdDirtyBits *dirtyBits,
HdPrimvarDescriptorVector const& constantPrimvars)
{
HD_TRACE_FUNCTION();
HF_MALLOC_TAG_FUNCTION();
SdfPath const& id = prim->GetId();
SdfPath const& instancerId = prim->GetInstancerId();
HdRenderIndex &renderIndex = delegate->GetRenderIndex();
HdResourceRegistrySharedPtr const &resourceRegistry =
renderIndex.GetResourceRegistry();
// Update uniforms
HdBufferSourceVector sources;
if (HdChangeTracker::IsTransformDirty(*dirtyBits, id)) {
GfMatrix4d transform = delegate->GetTransform(id);
sharedData->bounds.SetMatrix(transform); // for CPU frustum culling
HdBufferSourceSharedPtr source(new HdVtBufferSource(
HdTokens->transform,
transform));
sources.push_back(source);
source.reset(new HdVtBufferSource(HdTokens->transformInverse,
transform.GetInverse()));
sources.push_back(source);
// If this is a prototype (has instancer),
// also push the instancer transform separately.
if (!instancerId.IsEmpty()) {
// Gather all instancer transforms in the instancing hierarchy
VtMatrix4dArray rootTransforms =
prim->GetInstancerTransforms(delegate);
VtMatrix4dArray rootInverseTransforms(rootTransforms.size());
bool leftHanded = transform.IsLeftHanded();
for (size_t i = 0; i < rootTransforms.size(); ++i) {
rootInverseTransforms[i] = rootTransforms[i].GetInverse();
// Flip the handedness if necessary
leftHanded ^= rootTransforms[i].IsLeftHanded();
}
source.reset(new HdVtBufferSource(
HdTokens->instancerTransform,
rootTransforms,
rootTransforms.size()));
sources.push_back(source);
source.reset(new HdVtBufferSource(
HdTokens->instancerTransformInverse,
rootInverseTransforms,
rootInverseTransforms.size()));
sources.push_back(source);
// XXX: It might be worth to consider to have isFlipped
// for non-instanced prims as well. It can improve
// the drawing performance on older-GPUs by reducing
// fragment shader cost, although it needs more GPU memory.
// Set as int (GLSL needs 32-bit align for bool)
source.reset(new HdVtBufferSource(
HdTokens->isFlipped, VtValue(int(leftHanded))));
sources.push_back(source);
}
}
if (HdChangeTracker::IsExtentDirty(*dirtyBits, id)) {
// Note: If the scene description doesn't provide the extents, we use
// the default constructed GfRange3d which is [FLT_MAX, -FLT_MAX],
// which disables frustum culling for the prim.
sharedData->bounds.SetRange(prim->GetExtent(delegate));
GfVec3d const & localMin = drawItem->GetBounds().GetBox().GetMin();
HdBufferSourceSharedPtr sourceMin(new HdVtBufferSource(
HdTokens->bboxLocalMin,
VtValue(GfVec4f(
localMin[0],
localMin[1],
localMin[2],
1.0f))));
sources.push_back(sourceMin);
GfVec3d const & localMax = drawItem->GetBounds().GetBox().GetMax();
HdBufferSourceSharedPtr sourceMax(new HdVtBufferSource(
HdTokens->bboxLocalMax,
VtValue(GfVec4f(
localMax[0],
localMax[1],
localMax[2],
1.0f))));
sources.push_back(sourceMax);
}
if (HdChangeTracker::IsPrimIdDirty(*dirtyBits, id)) {
int32_t primId = prim->GetPrimId();
HdBufferSourceSharedPtr source(new HdVtBufferSource(
HdTokens->primID,
VtValue(primId)));
sources.push_back(source);
}
if (HdChangeTracker::IsAnyPrimvarDirty(*dirtyBits, id)) {
sources.reserve(sources.size()+constantPrimvars.size());
for (const HdPrimvarDescriptor& pv: constantPrimvars) {
if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, pv.name)) {
VtValue value = delegate->Get(id, pv.name);
// XXX Storm doesn't support string primvars yet
if (value.IsHolding<std::string>()) {
continue;
}
if (value.IsArrayValued() && value.GetArraySize() == 0) {
// A value holding an empty array does not count as an
// empty value. Catch that case here.
TF_WARN("Empty array value for constant primvar %s "
"on Rprim %s", pv.name.GetText(), id.GetText());
} else if (!value.IsEmpty()) {
// Given that this is a constant primvar, if it is
// holding VtArray then use that as a single array
// value rather than as one value per element.
HdBufferSourceSharedPtr source(
new HdVtBufferSource(pv.name, value,
value.IsArrayValued() ? value.GetArraySize() : 1));
TF_VERIFY(source->GetTupleType().type != HdTypeInvalid);
TF_VERIFY(source->GetTupleType().count > 0);
sources.push_back(source);
}
}
}
}
// If no sources are found no need to allocate,
// we can early out.
if (sources.empty()){
return;
}
// Allocate a new uniform buffer if not exists.
if (!drawItem->GetConstantPrimvarRange()) {
// establish a buffer range
HdBufferSpecVector bufferSpecs;
HdBufferSpec::GetBufferSpecs(sources, &bufferSpecs);
HdBufferArrayRangeSharedPtr range =
resourceRegistry->AllocateShaderStorageBufferArrayRange(
HdTokens->primvar, bufferSpecs, HdBufferArrayUsageHint());
TF_VERIFY(range->IsValid());
sharedData->barContainer.Set(
drawItem->GetDrawingCoord()->GetConstantPrimvarIndex(), range);
}
TF_VERIFY(drawItem->GetConstantPrimvarRange()->IsValid());
resourceRegistry->AddSources(
drawItem->GetConstantPrimvarRange(), sources);
}
PXR_NAMESPACE_CLOSE_SCOPE
| 42.883249 | 79 | 0.57919 | [
"transform"
] |
90473bfe21dcb031479093bdedd32fb832ae3a83 | 37,621 | cpp | C++ | UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/EditorBuildUtils.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | 1 | 2016-10-01T21:35:52.000Z | 2016-10-01T21:35:52.000Z | UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/EditorBuildUtils.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | null | null | null | UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/EditorBuildUtils.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | 1 | 2021-04-27T08:48:33.000Z | 2021-04-27T08:48:33.000Z | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
EditorBuildUtils.cpp: Utilities for building in the editor
=============================================================================*/
#include "UnrealEd.h"
#include "EditorBuildUtils.h"
#include "ISourceControlModule.h"
#include "LevelUtils.h"
#include "EditorLevelUtils.h"
#include "BusyCursor.h"
#include "Database.h"
#include "Dialogs/SBuildProgress.h"
#include "LightingBuildOptions.h"
#include "Dialogs/Dialogs.h"
#include "MainFrame.h"
#include "AssetToolsModule.h"
#include "MessageLog.h"
#include "Engine/LevelStreaming.h"
#include "GameFramework/WorldSettings.h"
#include "AI/Navigation/NavigationSystem.h"
#include "HierarchicalLOD.h"
#include "ActorEditorUtils.h"
DEFINE_LOG_CATEGORY_STATIC(LogEditorBuildUtils, Log, All);
#define LOCTEXT_NAMESPACE "EditorBuildUtils"
extern UNREALED_API bool GLightmassDebugMode;
extern UNREALED_API bool GLightmassStatsMode;
extern FSwarmDebugOptions GSwarmDebugOptions;
const FName FBuildOptions::BuildGeometry(TEXT("BuildGeometry"));
const FName FBuildOptions::BuildVisibleGeometry(TEXT("BuildVisibleGeometry"));
const FName FBuildOptions::BuildLighting(TEXT("BuildLighting"));
const FName FBuildOptions::BuildAIPaths(TEXT("BuildAIPaths"));
const FName FBuildOptions::BuildSelectedAIPaths(TEXT("BuildSelectedAIPaths"));
const FName FBuildOptions::BuildAll(TEXT("BuildAll"));
const FName FBuildOptions::BuildAllSubmit(TEXT("BuildAllSubmit"));
const FName FBuildOptions::BuildAllOnlySelectedPaths(TEXT("BuildAllOnlySelectedPaths"));
const FName FBuildOptions::BuildHierarchicalLOD(TEXT("BuildHierarchicalLOD"));
bool FEditorBuildUtils::bBuildingNavigationFromUserRequest = false;
TMap<FName, FEditorBuildUtils::FCustomBuildType> FEditorBuildUtils::CustomBuildTypes;
FName FEditorBuildUtils::InProgressBuildId;
/**
* Class that handles potentially-async Build All requests.
*/
class FBuildAllHandler
{
public:
void StartBuild(UWorld* World, FName BuildId, const TWeakPtr<SBuildProgressWidget>& BuildProgressWidget);
void ResumeBuild();
void AddCustomBuildStep(FName Id, FName InsertBefore);
void RemoveCustomBuildStep(FName Id);
static FBuildAllHandler& Get()
{
static FBuildAllHandler Instance;
return Instance;
}
private:
FBuildAllHandler();
FBuildAllHandler(const FBuildAllHandler&);
void ProcessBuild(const TWeakPtr<SBuildProgressWidget>& BuildProgressWidget);
void BuildFinished();
TArray<FName> BuildSteps;
int32 CurrentStep;
UWorld* CurrentWorld;
FName CurrentBuildId;
};
/** Constructor */
FEditorBuildUtils::FEditorAutomatedBuildSettings::FEditorAutomatedBuildSettings()
: BuildErrorBehavior( ABB_PromptOnError ),
UnableToCheckoutFilesBehavior( ABB_PromptOnError ),
NewMapBehavior( ABB_PromptOnError ),
FailedToSaveBehavior( ABB_PromptOnError ),
bUseSCC( true ),
bAutoAddNewFiles( true ),
bShutdownEditorOnCompletion( false )
{}
/**
* Start an automated build of all current maps in the editor. Upon successful conclusion of the build, the newly
* built maps will be submitted to source control.
*
* @param BuildSettings Build settings used to dictate the behavior of the automated build
* @param OutErrorMessages Error messages accumulated during the build process, if any
*
* @return true if the build/submission process executed successfully; false if it did not
*/
bool FEditorBuildUtils::EditorAutomatedBuildAndSubmit( const FEditorAutomatedBuildSettings& BuildSettings, FText& OutErrorMessages )
{
// Assume the build is successful to start
bool bBuildSuccessful = true;
// Keep a set of packages that should be submitted to source control at the end of a successful build. The build preparation and processing
// will add and remove from the set depending on build settings, errors, etc.
TSet<UPackage*> PackagesToSubmit;
// Perform required preparations for the automated build process
bBuildSuccessful = PrepForAutomatedBuild( BuildSettings, PackagesToSubmit, OutErrorMessages );
// If the preparation went smoothly, attempt the actual map building process
if ( bBuildSuccessful )
{
bBuildSuccessful = EditorBuild( GWorld, FBuildOptions::BuildAllSubmit );
// If the map build failed, log the error
if ( !bBuildSuccessful )
{
LogErrorMessage( NSLOCTEXT("UnrealEd", "AutomatedBuild_Error_BuildFailed", "The map build failed or was canceled."), OutErrorMessages );
}
}
// If any map errors resulted from the build, process them according to the behavior specified in the build settings
if ( bBuildSuccessful && FMessageLog("MapCheck").NumMessages( EMessageSeverity::Warning ) > 0 )
{
bBuildSuccessful = ProcessAutomatedBuildBehavior( BuildSettings.BuildErrorBehavior, NSLOCTEXT("UnrealEd", "AutomatedBuild_Error_MapErrors", "Map errors occurred while building.\n\nAttempt to continue the build?"), OutErrorMessages );
}
// If it's still safe to proceed, attempt to save all of the level packages that have been marked for submission
if ( bBuildSuccessful )
{
UPackage* CurOutermostPkg = GWorld->PersistentLevel->GetOutermost();
FString PackagesThatFailedToSave;
// Try to save the p-level if it should be submitted
if ( PackagesToSubmit.Contains( CurOutermostPkg ) && !FEditorFileUtils::SaveLevel( GWorld->PersistentLevel ) )
{
// If the p-level failed to save, remove it from the set of packages to submit
PackagesThatFailedToSave += FString::Printf( TEXT("%s\n"), *CurOutermostPkg->GetName() );
PackagesToSubmit.Remove( CurOutermostPkg );
}
// Try to save each streaming level (if they should be submitted)
for ( TArray<ULevelStreaming*>::TIterator LevelIter( GWorld->StreamingLevels ); LevelIter; ++LevelIter )
{
ULevelStreaming* CurStreamingLevel = *LevelIter;
if ( CurStreamingLevel != NULL )
{
ULevel* Level = CurStreamingLevel->GetLoadedLevel();
if ( Level != NULL )
{
CurOutermostPkg = Level->GetOutermost();
if ( PackagesToSubmit.Contains( CurOutermostPkg ) && !FEditorFileUtils::SaveLevel( Level ) )
{
// If a save failed, remove the streaming level from the set of packages to submit
PackagesThatFailedToSave += FString::Printf( TEXT("%s\n"), *CurOutermostPkg->GetName() );
PackagesToSubmit.Remove( CurOutermostPkg );
}
}
}
}
// If any packages failed to save, process the behavior specified by the build settings to see how the process should proceed
if ( PackagesThatFailedToSave.Len() > 0 )
{
bBuildSuccessful = ProcessAutomatedBuildBehavior( BuildSettings.FailedToSaveBehavior,
FText::Format( NSLOCTEXT("UnrealEd", "AutomatedBuild_Error_FilesFailedSave", "The following assets failed to save and cannot be submitted:\n\n{0}\n\nAttempt to continue the build?"), FText::FromString(PackagesThatFailedToSave) ),
OutErrorMessages );
}
}
// If still safe to proceed, make sure there are actually packages remaining to submit
if ( bBuildSuccessful )
{
bBuildSuccessful = PackagesToSubmit.Num() > 0;
if ( !bBuildSuccessful )
{
LogErrorMessage( NSLOCTEXT("UnrealEd", "AutomatedBuild_Error_NoValidLevels", "None of the current levels are valid for submission; automated build aborted."), OutErrorMessages );
}
}
// Finally, if everything has gone smoothly, submit the requested packages to source control
if ( bBuildSuccessful && BuildSettings.bUseSCC )
{
SubmitPackagesForAutomatedBuild( PackagesToSubmit, BuildSettings );
}
// Check if the user requested the editor shutdown at the conclusion of the automated build
if ( BuildSettings.bShutdownEditorOnCompletion )
{
FPlatformMisc::RequestExit( false );
}
return bBuildSuccessful;
}
static bool IsBuildCancelled()
{
return GEditor->GetMapBuildCancelled();
}
/**
* Perform an editor build with behavior dependent upon the specified id
*
* @param Id Action Id specifying what kind of build is requested
*
* @return true if the build completed successfully; false if it did not (or was manually canceled)
*/
bool FEditorBuildUtils::EditorBuild( UWorld* InWorld, FName Id, const bool bAllowLightingDialog )
{
FMessageLog("MapCheck").NewPage(LOCTEXT("MapCheckNewPage", "Map Check"));
// Make sure to set this flag to false before ALL builds.
GEditor->SetMapBuildCancelled( false );
// Will be set to false if, for some reason, the build does not happen.
bool bDoBuild = true;
// Indicates whether the persistent level should be dirtied at the end of a build.
bool bDirtyPersistentLevel = true;
// Stop rendering thread so we're not wasting CPU cycles.
StopRenderingThread();
// Hack: These don't initialize properly and if you pick BuildAll right off the
// bat when opening a map you will get incorrect values in them.
GSwarmDebugOptions.Touch();
// Show option dialog first, before showing the DlgBuildProgress window.
FLightingBuildOptions LightingBuildOptions;
if ( Id == FBuildOptions::BuildLighting )
{
// Retrieve settings from ini.
GConfig->GetBool( TEXT("LightingBuildOptions"), TEXT("OnlyBuildSelected"), LightingBuildOptions.bOnlyBuildSelected, GEditorPerProjectIni );
GConfig->GetBool( TEXT("LightingBuildOptions"), TEXT("OnlyBuildCurrentLevel"), LightingBuildOptions.bOnlyBuildCurrentLevel, GEditorPerProjectIni );
GConfig->GetBool( TEXT("LightingBuildOptions"), TEXT("OnlyBuildSelectedLevels"),LightingBuildOptions.bOnlyBuildSelectedLevels, GEditorPerProjectIni );
GConfig->GetBool( TEXT("LightingBuildOptions"), TEXT("OnlyBuildVisibility"), LightingBuildOptions.bOnlyBuildVisibility, GEditorPerProjectIni );
GConfig->GetBool( TEXT("LightingBuildOptions"), TEXT("UseErrorColoring"), LightingBuildOptions.bUseErrorColoring, GEditorPerProjectIni );
GConfig->GetBool( TEXT("LightingBuildOptions"), TEXT("ShowLightingBuildInfo"), LightingBuildOptions.bShowLightingBuildInfo, GEditorPerProjectIni );
int32 QualityLevel;
GConfig->GetInt( TEXT("LightingBuildOptions"), TEXT("QualityLevel"), QualityLevel, GEditorPerProjectIni );
QualityLevel = FMath::Clamp<int32>(QualityLevel, Quality_Preview, Quality_Production);
LightingBuildOptions.QualityLevel = (ELightingBuildQuality)QualityLevel;
}
// Show the build progress dialog.
SBuildProgressWidget::EBuildType BuildType = SBuildProgressWidget::BUILDTYPE_Geometry;
if (Id == FBuildOptions::BuildGeometry ||
Id == FBuildOptions::BuildVisibleGeometry ||
Id == FBuildOptions::BuildAll ||
Id == FBuildOptions::BuildAllOnlySelectedPaths)
{
BuildType = SBuildProgressWidget::BUILDTYPE_Geometry;
}
else if (Id == FBuildOptions::BuildLighting)
{
BuildType = SBuildProgressWidget::BUILDTYPE_Lighting;
}
else if (Id == FBuildOptions::BuildAIPaths ||
Id == FBuildOptions::BuildSelectedAIPaths)
{
BuildType = SBuildProgressWidget::BUILDTYPE_Paths;
}
else if (Id == FBuildOptions::BuildHierarchicalLOD)
{
BuildType = SBuildProgressWidget::BUILDTYPE_LODs;
}
else
{
BuildType = SBuildProgressWidget::BUILDTYPE_Unknown;
}
TWeakPtr<class SBuildProgressWidget> BuildProgressWidget = GWarn->ShowBuildProgressWindow();
BuildProgressWidget.Pin()->SetBuildType(BuildType);
bool bShouldMapCheck = true;
if (Id == FBuildOptions::BuildGeometry)
{
// We can't set the busy cursor for all windows, because lighting
// needs a cursor for the lighting options dialog.
const FScopedBusyCursor BusyCursor;
GUnrealEd->Exec( InWorld, TEXT("MAP REBUILD") );
if (GetDefault<ULevelEditorMiscSettings>()->bNavigationAutoUpdate)
{
TriggerNavigationBuilder(InWorld, Id);
}
// No need to dirty the persient level if we're building BSP for a sub-level.
bDirtyPersistentLevel = false;
}
else if (Id == FBuildOptions::BuildVisibleGeometry)
{
// If any levels are hidden, prompt the user about how to proceed
bDoBuild = GEditor->WarnAboutHiddenLevels( InWorld, true );
if ( bDoBuild )
{
// We can't set the busy cursor for all windows, because lighting
// needs a cursor for the lighting options dialog.
const FScopedBusyCursor BusyCursor;
GUnrealEd->Exec( InWorld, TEXT("MAP REBUILD ALLVISIBLE") );
if (GetDefault<ULevelEditorMiscSettings>()->bNavigationAutoUpdate)
{
TriggerNavigationBuilder(InWorld, Id);
}
}
}
else if (Id == FBuildOptions::BuildLighting)
{
if( bDoBuild )
{
bool bBSPRebuildNeeded = false;
// Only BSP brushes affect lighting. Check if there is any BSP in the level and skip the geometry rebuild if there isn't any.
for( TActorIterator<ABrush> ActorIt( InWorld ); ActorIt; ++ActorIt )
{
ABrush* Brush = *ActorIt;
if( !Brush->IsVolumeBrush() && !Brush->IsBrushShape() && !FActorEditorUtils::IsABuilderBrush( Brush ) )
{
// brushes that aren't volumes are considered bsp
bBSPRebuildNeeded = true;
break;
}
}
if( bBSPRebuildNeeded )
{
// BSP export to lightmass relies on current BSP state
GUnrealEd->Exec( InWorld, TEXT("MAP REBUILD ALLVISIBLE") );
}
GUnrealEd->BuildLighting( LightingBuildOptions );
bShouldMapCheck = false;
}
}
else if (Id == FBuildOptions::BuildAIPaths)
{
bDoBuild = GEditor->WarnAboutHiddenLevels( InWorld, false );
if ( bDoBuild )
{
GEditor->ResetTransaction( NSLOCTEXT("UnrealEd", "RebuildNavigation", "Rebuilding Navigation") );
// We can't set the busy cursor for all windows, because lighting
// needs a cursor for the lighting options dialog.
const FScopedBusyCursor BusyCursor;
TriggerNavigationBuilder(InWorld, Id);
}
}
else if (CustomBuildTypes.Contains(Id))
{
const auto& CustomBuild = CustomBuildTypes.FindChecked(Id);
check(CustomBuild.DoBuild.IsBound());
// Invoke custom build.
auto Result = CustomBuild.DoBuild.Execute(InWorld, Id);
bDoBuild = Result != EEditorBuildResult::Skipped;
bShouldMapCheck = Result == EEditorBuildResult::Success;
bDirtyPersistentLevel = Result == EEditorBuildResult::Success;
if (Result == EEditorBuildResult::InProgress)
{
InProgressBuildId = Id;
}
}
else if (Id == FBuildOptions::BuildHierarchicalLOD)
{
bDoBuild = GEditor->WarnAboutHiddenLevels( InWorld, false );
if ( bDoBuild )
{
GEditor->ResetTransaction( NSLOCTEXT("UnrealEd", "BuildHLODMeshes", "Building Hierarchical LOD Meshes") );
// We can't set the busy cursor for all windows, because lighting
// needs a cursor for the lighting options dialog.
const FScopedBusyCursor BusyCursor;
TriggerHierarchicalLODBuilder(InWorld, Id);
}
}
else if (Id == FBuildOptions::BuildAll || Id == FBuildOptions::BuildAllSubmit)
{
// TODO: WarnIfLightingBuildIsCurrentlyRunning should check with FBuildAllHandler
bDoBuild = GEditor->WarnAboutHiddenLevels( InWorld, true );
bool bLightingAlreadyRunning = GUnrealEd->WarnIfLightingBuildIsCurrentlyRunning();
if ( bDoBuild && !bLightingAlreadyRunning )
{
FBuildAllHandler::Get().StartBuild(InWorld, Id, BuildProgressWidget);
}
}
else
{
UE_LOG(LogEditorBuildUtils, Warning, TEXT("Invalid build Id: %s"), *Id.ToString());
bDoBuild = false;
}
// Check map for errors (only if build operation happened)
if ( bShouldMapCheck && bDoBuild && !GEditor->GetMapBuildCancelled() )
{
GUnrealEd->Exec( InWorld, TEXT("MAP CHECK DONTDISPLAYDIALOG") );
}
// Re-start the rendering thread after build operations completed.
if (GUseThreadedRendering)
{
StartRenderingThread();
}
if ( bDoBuild )
{
// Display elapsed build time.
UE_LOG(LogEditorBuildUtils, Log, TEXT("Build time %s"), *BuildProgressWidget.Pin()->BuildElapsedTimeText().ToString() );
}
// Build completed, hide the build progress dialog.
// NOTE: It's important to turn off modalness before hiding the window, otherwise a background
// application may unexpectedly be promoted to the foreground, obscuring the editor.
GWarn->CloseBuildProgressWindow();
GUnrealEd->RedrawLevelEditingViewports();
if ( bDoBuild )
{
if ( bDirtyPersistentLevel )
{
InWorld->MarkPackageDirty();
}
ULevel::LevelDirtiedEvent.Broadcast();
}
// Don't show map check if we cancelled build because it may have some bogus data
const bool bBuildCompleted = bDoBuild && !GEditor->GetMapBuildCancelled();
if( bBuildCompleted )
{
if (bShouldMapCheck)
{
FMessageLog("MapCheck").Open( EMessageSeverity::Warning );
}
FMessageLog("LightingResults").Notify(LOCTEXT("LightingErrorsNotification", "There were lighting errors."), EMessageSeverity::Error);
}
return bBuildCompleted;
}
/**
* Private helper method to log an error both to GWarn and to the build's list of accumulated errors
*
* @param InErrorMessage Message to log to GWarn/add to list of errors
* @param OutAccumulatedErrors List of errors accumulated during a build process so far
*/
void FEditorBuildUtils::LogErrorMessage( const FText& InErrorMessage, FText& OutAccumulatedErrors )
{
OutAccumulatedErrors = FText::Format( LOCTEXT("AccumulateErrors", "{0}\n{1}"), OutAccumulatedErrors, InErrorMessage );
UE_LOG(LogEditorBuildUtils, Warning, TEXT("%s"), *InErrorMessage.ToString() );
}
/**
* Helper method to handle automated build behavior in the event of an error. Depending on the specified behavior, one of three
* results are possible:
* a) User is prompted on whether to proceed with the automated build or not,
* b) The error is regarded as a build-stopper and the method returns failure,
* or
* c) The error is acknowledged but not regarded as a build-stopper, and the method returns success.
* In any event, the error is logged for the user's information.
*
* @param InBehavior Behavior to use to respond to the error
* @param InErrorMsg Error to log
* @param OutAccumulatedErrors List of errors accumulated from the build process so far; InErrorMsg will be added to the list
*
* @return true if the build should proceed after processing the error behavior; false if it should not
*/
bool FEditorBuildUtils::ProcessAutomatedBuildBehavior( EAutomatedBuildBehavior InBehavior, const FText& InErrorMsg, FText& OutAccumulatedErrors )
{
// Assume the behavior should result in the build being successful/proceeding to start
bool bSuccessful = true;
switch ( InBehavior )
{
// In the event the user should be prompted for the error, display a modal dialog describing the error and ask the user
// if the build should proceed or not
case ABB_PromptOnError:
{
bSuccessful = EAppReturnType::Yes == FMessageDialog::Open(EAppMsgType::YesNo, InErrorMsg);
}
break;
// In the event that the specified error should abort the build, mark the processing as a failure
case ABB_FailOnError:
bSuccessful = false;
break;
}
// Log the error message so the user is aware of it
LogErrorMessage( InErrorMsg, OutAccumulatedErrors );
// If the processing resulted in the build inevitably being aborted, write to the log about the abortion
if ( !bSuccessful )
{
LogErrorMessage( NSLOCTEXT("UnrealEd", "AutomatedBuild_Error_AutomatedBuildAborted", "Automated build aborted."), OutAccumulatedErrors );
}
return bSuccessful;
}
/**
* Helper method designed to perform the necessary preparations required to complete an automated editor build
*
* @param BuildSettings Build settings that will be used for the editor build
* @param OutPkgsToSubmit Set of packages that need to be saved and submitted after a successful build
* @param OutErrorMessages Errors that resulted from the preparation (may or may not force the build to stop, depending on build settings)
*
* @return true if the preparation was successful and the build should continue; false if the preparation failed and the build should be aborted
*/
bool FEditorBuildUtils::PrepForAutomatedBuild( const FEditorAutomatedBuildSettings& BuildSettings, TSet<UPackage*>& OutPkgsToSubmit, FText& OutErrorMessages )
{
// Assume the preparation is successful to start
bool bBuildSuccessful = true;
OutPkgsToSubmit.Empty();
ISourceControlProvider& SourceControlProvider = ISourceControlModule::Get().GetProvider();
// Source control is required for the automated build, so ensure that SCC support is compiled in and
// that the server is enabled and available for use
if ( BuildSettings.bUseSCC && !(ISourceControlModule::Get().IsEnabled() && SourceControlProvider.IsAvailable() ) )
{
bBuildSuccessful = false;
LogErrorMessage( NSLOCTEXT("UnrealEd", "AutomatedBuild_Error_SCCError", "Cannot connect to source control; automated build aborted."), OutErrorMessages );
}
TArray<UPackage*> PreviouslySavedWorldPackages;
TArray<UPackage*> PackagesToCheckout;
TArray<ULevel*> LevelsToSave;
if ( bBuildSuccessful )
{
TArray<UWorld*> AllWorlds;
FString UnsavedWorlds;
EditorLevelUtils::GetWorlds( GWorld, AllWorlds, true );
// Check all of the worlds that will be built to ensure they have been saved before and have a filename
// associated with them. If they don't, they won't be able to be submitted to source control.
FString CurWorldPkgFileName;
for ( TArray<UWorld*>::TConstIterator WorldIter( AllWorlds ); WorldIter; ++WorldIter )
{
const UWorld* CurWorld = *WorldIter;
check( CurWorld );
UPackage* CurWorldPackage = CurWorld->GetOutermost();
check( CurWorldPackage );
if ( FPackageName::DoesPackageExist( CurWorldPackage->GetName(), NULL, &CurWorldPkgFileName ) )
{
PreviouslySavedWorldPackages.AddUnique( CurWorldPackage );
// Add all packages which have a corresponding file to the set of packages to submit for now. As preparation continues
// any packages that can't be submitted due to some error will be removed.
OutPkgsToSubmit.Add( CurWorldPackage );
}
else
{
UnsavedWorlds += FString::Printf( TEXT("%s\n"), *CurWorldPackage->GetName() );
}
}
// If any of the worlds haven't been saved before, process the build setting's behavior to see if the build
// should proceed or not
if ( UnsavedWorlds.Len() > 0 )
{
bBuildSuccessful = ProcessAutomatedBuildBehavior( BuildSettings.NewMapBehavior,
FText::Format( NSLOCTEXT("UnrealEd", "AutomatedBuild_Error_UnsavedMap", "The following levels have never been saved before and cannot be submitted:\n\n{0}\n\nAttempt to continue the build?"), FText::FromString(UnsavedWorlds) ),
OutErrorMessages );
}
}
// Load the asset tools module
FAssetToolsModule& AssetToolsModule = FModuleManager::GetModuleChecked<FAssetToolsModule>("AssetTools");
if ( bBuildSuccessful && BuildSettings.bUseSCC )
{
// Update the source control status of any relevant world packages in order to determine which need to be
// checked out, added to the depot, etc.
SourceControlProvider.Execute( ISourceControlOperation::Create<FUpdateStatus>(), SourceControlHelpers::PackageFilenames(PreviouslySavedWorldPackages) );
FString PkgsThatCantBeCheckedOut;
for ( TArray<UPackage*>::TConstIterator PkgIter( PreviouslySavedWorldPackages ); PkgIter; ++PkgIter )
{
UPackage* CurPackage = *PkgIter;
const FString CurPkgName = CurPackage->GetName();
FSourceControlStatePtr SourceControlState = SourceControlProvider.GetState(CurPackage, EStateCacheUsage::ForceUpdate);
if( !SourceControlState.IsValid() ||
(!SourceControlState->IsSourceControlled() &&
!SourceControlState->IsUnknown() &&
!SourceControlState->IsIgnored()))
{
FString CurFilename;
if ( FPackageName::DoesPackageExist( CurPkgName, NULL, &CurFilename ) )
{
if ( IFileManager::Get().IsReadOnly( *CurFilename ) )
{
PkgsThatCantBeCheckedOut += FString::Printf( TEXT("%s\n"), *CurPkgName );
OutPkgsToSubmit.Remove( CurPackage );
}
}
}
else if(SourceControlState->IsCheckedOut())
{
}
else if(SourceControlState->CanCheckout())
{
PackagesToCheckout.Add( CurPackage );
}
else
{
PkgsThatCantBeCheckedOut += FString::Printf( TEXT("%s\n"), *CurPkgName );
OutPkgsToSubmit.Remove( CurPackage );
}
}
// If any of the packages can't be checked out or are read-only, process the build setting's behavior to see if the build
// should proceed or not
if ( PkgsThatCantBeCheckedOut.Len() > 0 )
{
bBuildSuccessful = ProcessAutomatedBuildBehavior( BuildSettings.UnableToCheckoutFilesBehavior,
FText::Format( NSLOCTEXT("UnrealEd", "AutomatedBuild_Error_UnsaveableFiles", "The following assets cannot be checked out of source control (or are read-only) and cannot be submitted:\n\n{0}\n\nAttempt to continue the build?"), FText::FromString(PkgsThatCantBeCheckedOut) ),
OutErrorMessages );
}
}
if ( bBuildSuccessful )
{
// Check out all of the packages from source control that need to be checked out
if ( PackagesToCheckout.Num() > 0 )
{
TArray<FString> PackageFilenames = SourceControlHelpers::PackageFilenames(PackagesToCheckout);
SourceControlProvider.Execute( ISourceControlOperation::Create<FCheckOut>(), PackageFilenames );
// Update the package status of the packages that were just checked out to confirm that they
// were actually checked out correctly
SourceControlProvider.Execute( ISourceControlOperation::Create<FUpdateStatus>(), PackageFilenames );
FString FilesThatFailedCheckout;
for ( TArray<UPackage*>::TConstIterator CheckedOutIter( PackagesToCheckout ); CheckedOutIter; ++CheckedOutIter )
{
UPackage* CurPkg = *CheckedOutIter;
FSourceControlStatePtr SourceControlState = SourceControlProvider.GetState(CurPkg, EStateCacheUsage::ForceUpdate);
// If any of the packages failed to check out, remove them from the set of packages to submit
if ( !SourceControlState.IsValid() || (!SourceControlState->IsCheckedOut() && !SourceControlState->IsAdded() && SourceControlState->IsSourceControlled()) )
{
FilesThatFailedCheckout += FString::Printf( TEXT("%s\n"), *CurPkg->GetName() );
OutPkgsToSubmit.Remove( CurPkg );
}
}
// If any of the packages failed to check out correctly, process the build setting's behavior to see if the build
// should proceed or not
if ( FilesThatFailedCheckout.Len() > 0 )
{
bBuildSuccessful = ProcessAutomatedBuildBehavior( BuildSettings.UnableToCheckoutFilesBehavior,
FText::Format( NSLOCTEXT("UnrealEd", "AutomatedBuild_Error_FilesFailedCheckout", "The following assets failed to checkout of source control and cannot be submitted:\n{0}\n\nAttempt to continue the build?"), FText::FromString(FilesThatFailedCheckout)),
OutErrorMessages );
}
}
}
// Verify there are still actually any packages left to submit. If there aren't, abort the build and warn the user of the situation.
if ( bBuildSuccessful )
{
bBuildSuccessful = OutPkgsToSubmit.Num() > 0;
if ( !bBuildSuccessful )
{
LogErrorMessage( NSLOCTEXT("UnrealEd", "AutomatedBuild_Error_NoValidLevels", "None of the current levels are valid for submission; automated build aborted."), OutErrorMessages );
}
}
// If the build is safe to commence, force all of the levels visible to make sure the build operates correctly
if ( bBuildSuccessful )
{
bool bVisibilityToggled = false;
if ( !FLevelUtils::IsLevelVisible( GWorld->PersistentLevel ) )
{
EditorLevelUtils::SetLevelVisibility( GWorld->PersistentLevel, true, false );
bVisibilityToggled = true;
}
for ( TArray<ULevelStreaming*>::TConstIterator LevelIter( GWorld->StreamingLevels ); LevelIter; ++LevelIter )
{
ULevelStreaming* CurStreamingLevel = *LevelIter;
if ( CurStreamingLevel && !FLevelUtils::IsLevelVisible( CurStreamingLevel ) )
{
CurStreamingLevel->bShouldBeVisibleInEditor = true;
bVisibilityToggled = true;
}
}
if ( bVisibilityToggled )
{
GWorld->FlushLevelStreaming();
}
}
return bBuildSuccessful;
}
/**
* Helper method to submit packages to source control as part of the automated build process
*
* @param InPkgsToSubmit Set of packages which should be submitted to source control
* @param BuildSettings Build settings used during the automated build
*/
void FEditorBuildUtils::SubmitPackagesForAutomatedBuild( const TSet<UPackage*>& InPkgsToSubmit, const FEditorAutomatedBuildSettings& BuildSettings )
{
TArray<FString> LevelsToAdd;
TArray<FString> LevelsToSubmit;
ISourceControlProvider& SourceControlProvider = ISourceControlModule::Get().GetProvider();
// first update the status of the packages
SourceControlProvider.Execute(ISourceControlOperation::Create<FUpdateStatus>(), SourceControlHelpers::PackageFilenames(InPkgsToSubmit.Array()));
// Iterate over the set of packages to submit, determining if they need to be checked in or
// added to the depot for the first time
for ( TSet<UPackage*>::TConstIterator PkgIter( InPkgsToSubmit ); PkgIter; ++PkgIter )
{
const UPackage* CurPkg = *PkgIter;
const FString PkgName = CurPkg->GetName();
const FString PkgFileName = SourceControlHelpers::PackageFilename(CurPkg);
FSourceControlStatePtr SourceControlState = SourceControlProvider.GetState(CurPkg, EStateCacheUsage::ForceUpdate);
if(SourceControlState.IsValid())
{
if ( SourceControlState->IsCheckedOut() || SourceControlState->IsAdded() )
{
LevelsToSubmit.Add( PkgFileName );
}
else if ( BuildSettings.bAutoAddNewFiles && !SourceControlState->IsSourceControlled() && !SourceControlState->IsIgnored() )
{
LevelsToSubmit.Add( PkgFileName );
LevelsToAdd.Add( PkgFileName );
}
}
}
// Then, if we've also opted to check in any packages, iterate over that list as well
if(BuildSettings.bCheckInPackages)
{
TArray<FString> PackageNames = BuildSettings.PackagesToCheckIn;
for ( TArray<FString>::TConstIterator PkgIterName(PackageNames); PkgIterName; PkgIterName++ )
{
const FString& PkgName = *PkgIterName;
const FString PkgFileName = SourceControlHelpers::PackageFilename(PkgName);
FSourceControlStatePtr SourceControlState = SourceControlProvider.GetState(PkgFileName, EStateCacheUsage::ForceUpdate);
if(SourceControlState.IsValid())
{
if ( SourceControlState->IsCheckedOut() || SourceControlState->IsAdded() )
{
LevelsToSubmit.Add( PkgFileName );
}
else if ( !SourceControlState->IsSourceControlled() && !SourceControlState->IsIgnored() )
{
// note we add the files we need to add to the submit list as well
LevelsToSubmit.Add( PkgFileName );
LevelsToAdd.Add( PkgFileName );
}
}
}
}
// first add files that need to be added
SourceControlProvider.Execute( ISourceControlOperation::Create<FMarkForAdd>(), LevelsToAdd, EConcurrency::Synchronous );
// Now check in all the changes, including the files we added above
TSharedRef<FCheckIn, ESPMode::ThreadSafe> CheckInOperation = StaticCastSharedRef<FCheckIn>(ISourceControlOperation::Create<FCheckIn>());
if (BuildSettings.ChangeDescription.IsEmpty())
{
CheckInOperation->SetDescription(NSLOCTEXT("UnrealEd", "AutomatedBuild_AutomaticSubmission", "[Automatic Submission]"));
}
else
{
CheckInOperation->SetDescription(FText::FromString(BuildSettings.ChangeDescription));
}
SourceControlProvider.Execute( CheckInOperation, LevelsToSubmit, EConcurrency::Synchronous );
}
void FEditorBuildUtils::TriggerNavigationBuilder(UWorld* InWorld, FName Id)
{
if( InWorld->GetWorldSettings()->bEnableNavigationSystem &&
InWorld->GetNavigationSystem() )
{
if (Id == FBuildOptions::BuildAIPaths ||
Id == FBuildOptions::BuildSelectedAIPaths ||
Id == FBuildOptions::BuildAllOnlySelectedPaths ||
Id == FBuildOptions::BuildAll ||
Id == FBuildOptions::BuildAllSubmit)
{
bBuildingNavigationFromUserRequest = true;
}
else
{
bBuildingNavigationFromUserRequest = false;
}
// Invoke navmesh generator
InWorld->GetNavigationSystem()->Build();
}
}
/**
* Call this when an async custom build step has completed (successfully or not).
*/
void FEditorBuildUtils::AsyncBuildCompleted()
{
check(InProgressBuildId != NAME_None);
// Reset in-progress id before resuming build all do we don't overwrite something that's just been set.
auto BuildId = InProgressBuildId;
InProgressBuildId = NAME_None;
if (BuildId == FBuildOptions::BuildAll || BuildId == FBuildOptions::BuildAllSubmit)
{
FBuildAllHandler::Get().ResumeBuild();
}
}
/**
* Is there currently an (async) build in progress?
*/
bool FEditorBuildUtils::IsBuildCurrentlyRunning()
{
return InProgressBuildId != NAME_None;
}
/**
* Register a custom build type.
* @param Id The identifier to use for this build type.
* @param DoBuild The delegate to execute to run this build.
* @param BuildAllExtensionPoint If a valid name, run this build *before* running the build with this id when performing a Build All.
*/
void FEditorBuildUtils::RegisterCustomBuildType(FName Id, const FDoEditorBuildDelegate& DoBuild, FName BuildAllExtensionPoint)
{
check(!CustomBuildTypes.Contains(Id));
CustomBuildTypes.Add(Id, FCustomBuildType(DoBuild, BuildAllExtensionPoint));
if (BuildAllExtensionPoint != NAME_None)
{
FBuildAllHandler::Get().AddCustomBuildStep(Id, BuildAllExtensionPoint);
}
}
/**
* Unregister a custom build type.
* @param Id The identifier of the build type to unregister.
*/
void FEditorBuildUtils::UnregisterCustomBuildType(FName Id)
{
CustomBuildTypes.Remove(Id);
FBuildAllHandler::Get().RemoveCustomBuildStep(Id);
}
/**
* Initialise Build All handler.
*/
FBuildAllHandler::FBuildAllHandler()
: CurrentStep(0)
{
// Add built in build steps.
BuildSteps.Add(FBuildOptions::BuildGeometry);
BuildSteps.Add(FBuildOptions::BuildHierarchicalLOD);
BuildSteps.Add(FBuildOptions::BuildAIPaths);
//Lighting must always be the last one when doing a build all
BuildSteps.Add(FBuildOptions::BuildLighting);
}
/**
* Add a custom Build All step.
*/
void FBuildAllHandler::AddCustomBuildStep(FName Id, FName InsertBefore)
{
const int32 InsertionPoint = BuildSteps.Find(InsertBefore);
if (InsertionPoint != INDEX_NONE)
{
BuildSteps.Insert(Id, InsertionPoint);
}
}
/**
* Remove a custom Build All step.
*/
void FBuildAllHandler::RemoveCustomBuildStep(FName Id)
{
BuildSteps.Remove(Id);
}
/**
* Commence a new Build All operation.
*/
void FBuildAllHandler::StartBuild(UWorld* World, FName BuildId, const TWeakPtr<SBuildProgressWidget>& BuildProgressWidget)
{
check(CurrentStep == 0);
check(CurrentWorld == nullptr);
check(CurrentBuildId == NAME_None);
CurrentWorld = World;
CurrentBuildId = BuildId;
ProcessBuild(BuildProgressWidget);
}
/**
* Resume a Build All build from where it was left off.
*/
void FBuildAllHandler::ResumeBuild()
{
// Resuming from async operation, may be about to do slow stuff again so show the progress window again.
TWeakPtr<SBuildProgressWidget> BuildProgressWidget = GWarn->ShowBuildProgressWindow();
ProcessBuild(BuildProgressWidget);
// Synchronous part completed, hide the build progress dialog.
GWarn->CloseBuildProgressWindow();
}
/**
* Internal method that actual does the build.
*/
void FBuildAllHandler::ProcessBuild(const TWeakPtr<SBuildProgressWidget>& BuildProgressWidget)
{
const FScopedBusyCursor BusyCursor;
// Loop until we finish, or we start an async step.
while (true)
{
if (GEditor->GetMapBuildCancelled())
{
// Build cancelled, so bail.
BuildFinished();
break;
}
check(BuildSteps.IsValidIndex(CurrentStep));
FName StepId = BuildSteps[CurrentStep];
if (StepId == FBuildOptions::BuildGeometry)
{
BuildProgressWidget.Pin()->SetBuildType(SBuildProgressWidget::BUILDTYPE_Geometry);
GUnrealEd->Exec(CurrentWorld, TEXT("MAP REBUILD ALLVISIBLE") );
}
else if (StepId == FBuildOptions::BuildHierarchicalLOD)
{
BuildProgressWidget.Pin()->SetBuildType(SBuildProgressWidget::BUILDTYPE_LODs);
FEditorBuildUtils::TriggerHierarchicalLODBuilder(CurrentWorld, CurrentBuildId);
}
else if (StepId == FBuildOptions::BuildAIPaths)
{
BuildProgressWidget.Pin()->SetBuildType(SBuildProgressWidget::BUILDTYPE_Paths);
FEditorBuildUtils::TriggerNavigationBuilder(CurrentWorld, CurrentBuildId);
}
else if (StepId == FBuildOptions::BuildLighting)
{
BuildProgressWidget.Pin()->SetBuildType(SBuildProgressWidget::BUILDTYPE_Lighting);
FLightingBuildOptions LightingOptions;
int32 QualityLevel;
// Force automated builds to always use production lighting
if ( CurrentBuildId == FBuildOptions::BuildAllSubmit )
{
QualityLevel = Quality_Production;
}
else
{
GConfig->GetInt(TEXT("LightingBuildOptions"), TEXT("QualityLevel"), QualityLevel, GEditorPerProjectIni);
QualityLevel = FMath::Clamp<int32>(QualityLevel, Quality_Preview, Quality_Production);
}
LightingOptions.QualityLevel = (ELightingBuildQuality)QualityLevel;
GUnrealEd->BuildLighting(LightingOptions);
// TODO!
//bShouldMapCheck = false;
// Lighting is always the last step (Lightmass isn't set up to resume builds).
BuildFinished();
break;
}
else
{
auto& CustomBuildType = FEditorBuildUtils::CustomBuildTypes[StepId];
auto Result = CustomBuildType.DoBuild.Execute(CurrentWorld, CurrentBuildId);
if (Result == EEditorBuildResult::InProgress)
{
// Build & Submit builds must be synchronous.
check(CurrentBuildId != FBuildOptions::BuildAllSubmit);
// Build step is running asynchronously, so let it run.
FEditorBuildUtils::InProgressBuildId = CurrentBuildId;
break;
}
}
// Next go around we want to do the next step.
CurrentStep++;
}
}
/**
* Called when a build is finished (successfully or not).
*/
void FBuildAllHandler::BuildFinished()
{
CurrentStep = 0;
CurrentWorld = nullptr;
CurrentBuildId = NAME_None;
}
void FEditorBuildUtils::TriggerHierarchicalLODBuilder(UWorld* InWorld, FName Id)
{
// Invoke HLOD generator, with either preview or full build
InWorld->HierarchicalLODBuilder->BuildMeshesForLODActors();
}
#undef LOCTEXT_NAMESPACE | 36.489816 | 277 | 0.750671 | [
"geometry"
] |
904d9726d5e4aadcaa6a51326f6d6e5cb3579cf4 | 5,931 | cpp | C++ | pge/source/pge/constructs/AABB3D.cpp | 222464/PGE | 8801301046a0412c323444a7f9f49e02f9ac87cc | [
"Zlib"
] | 100 | 2016-05-04T00:05:43.000Z | 2021-09-11T17:34:31.000Z | pge/source/pge/constructs/AABB3D.cpp | 222464/PGE | 8801301046a0412c323444a7f9f49e02f9ac87cc | [
"Zlib"
] | 8 | 2016-05-06T12:51:53.000Z | 2017-07-20T20:15:46.000Z | pge/source/pge/constructs/AABB3D.cpp | 222464/PGE | 8801301046a0412c323444a7f9f49e02f9ac87cc | [
"Zlib"
] | 16 | 2016-05-04T06:37:20.000Z | 2020-11-12T17:24:55.000Z | #include <pge/constructs/AABB3D.h>
#include <pge/constructs/Quaternion.h>
#include <limits>
#include <assert.h>
using namespace pge;
AABB3D::AABB3D()
: _lowerBound(0.0f, 0.0f, 0.0f), _upperBound(1.0f, 1.0f, 1.0f),
_center(0.5f, 0.5f, 0.5f), _halfDims(0.5f, 0.5f, 0.5f)
{}
AABB3D::AABB3D(const Vec3f &lowerBound, const Vec3f &upperBound)
: _lowerBound(lowerBound), _upperBound(upperBound)
{
calculateHalfDims();
calculateCenter();
}
void AABB3D::setCenter(const Vec3f ¢er) {
_center = center;
calculateBounds();
}
void AABB3D::incCenter(const Vec3f &increment) {
_center += increment;
calculateBounds();
}
void AABB3D::setHalfDims(const Vec3f &halfDims) {
_halfDims = halfDims;
calculateBounds();
}
bool AABB3D::intersects(const AABB3D &other) const {
if (_upperBound.x < other._lowerBound.x)
return false;
if (_upperBound.y < other._lowerBound.y)
return false;
if (_upperBound.z < other._lowerBound.z)
return false;
if (_lowerBound.x > other._upperBound.x)
return false;
if (_lowerBound.y > other._upperBound.y)
return false;
if (_lowerBound.z > other._upperBound.z)
return false;
return true;
}
bool AABB3D::intersects(const Vec3f& p1, const Vec3f& p2) const {
Vec3f d((p2 - p1) * 0.5f);
Vec3f e((_upperBound - _lowerBound) * 0.5f);
Vec3f c(p1 + d - (_lowerBound + _upperBound) * 0.5f);
Vec3f ad(fabsf(d.x), fabsf(d.y), fabsf(d.z)); // Returns same vector with all components positive
if (fabsf(c.x) > e.x + ad.x)
return false;
if (fabsf(c.y) > e.y + ad.y)
return false;
if (fabsf(c.z) > e.z + ad.z)
return false;
float epsilon = std::numeric_limits<float>::epsilon();
if (fabsf(d.y * c.z - d.z * c.y) > e.y * ad.z + e.z * ad.y + epsilon)
return false;
if (fabsf(d.z * c.x - d.x * c.z) > e.z * ad.x + e.x * ad.z + epsilon)
return false;
if (fabsf(d.x * c.y - d.y * c.x) > e.x * ad.y + e.y * ad.x + epsilon)
return false;
return true;
}
bool AABB3D::intersects(const Vec3f &start, const Vec3f &direction, float &t0, float &t1) const {
Vec3f directionInv = Vec3f(1.0f, 1.0f, 1.0f) / direction;
float tx1 = (_lowerBound.x - start.x) * directionInv.x;
float tx2 = (_upperBound.x - start.x) * directionInv.x;
t0 = std::min(tx1, tx2);
t1 = std::max(tx1, tx2);
float ty1 = (_lowerBound.y - start.y) * directionInv.y;
float ty2 = (_upperBound.y - start.y) * directionInv.y;
t0 = std::max(t0, std::min(ty1, ty2));
t1 = std::min(t1, std::max(ty1, ty2));
float tz1 = (_lowerBound.z - start.z) * directionInv.z;
float tz2 = (_upperBound.z - start.z) * directionInv.z;
t0 = std::max(t0, std::min(tz1, tz2));
t1 = std::min(t1, std::max(tz1, tz2));
return t1 >= t0;
}
bool AABB3D::contains(const AABB3D &other) const {
if (other._lowerBound.x >= _lowerBound.x &&
other._upperBound.x <= _upperBound.x &&
other._lowerBound.y >= _lowerBound.y &&
other._upperBound.y <= _upperBound.y &&
other._lowerBound.z >= _lowerBound.z &&
other._upperBound.z <= _upperBound.z)
return true;
return false;
}
bool AABB3D::contains(const Vec3f &vec) const {
if (vec.x >= _lowerBound.x &&
vec.y >= _lowerBound.y &&
vec.z >= _lowerBound.z &&
vec.x <= _upperBound.x &&
vec.y <= _upperBound.y &&
vec.z <= _upperBound.z)
return true;
return false;
}
AABB3D AABB3D::getTransformedAABB(const Matrix4x4f &mat) const {
AABB3D transformedAABB;
Vec3f newCenter(mat * _center);
transformedAABB._lowerBound = newCenter;
transformedAABB._upperBound = newCenter;
// Loop through all corners, transform, and compare
for (int x = -1; x <= 1; x += 2)
for (int y = -1; y <= 1; y += 2)
for (int z = -1; z <= 1; z += 2) {
Vec3f corner(x * _halfDims.x + _center.x, y * _halfDims.y + _center.y, z * _halfDims.z + _center.z);
// Transform the corner
corner = mat * corner;
// Compare bounds
if (corner.x > transformedAABB._upperBound.x)
transformedAABB._upperBound.x = corner.x;
if (corner.y > transformedAABB._upperBound.y)
transformedAABB._upperBound.y = corner.y;
if (corner.z > transformedAABB._upperBound.z)
transformedAABB._upperBound.z = corner.z;
if (corner.x < transformedAABB._lowerBound.x)
transformedAABB._lowerBound.x = corner.x;
if (corner.y < transformedAABB._lowerBound.y)
transformedAABB._lowerBound.y = corner.y;
if (corner.z < transformedAABB._lowerBound.z)
transformedAABB._lowerBound.z = corner.z;
}
// Move from local into world space
transformedAABB.calculateHalfDims();
transformedAABB.calculateCenter();
return transformedAABB;
}
Vec3f AABB3D::getVertexP(const Vec3f &normal) const {
Vec3f p(_lowerBound);
if (normal.x >= 0.0f)
p.x = _upperBound.x;
if (normal.y >= 0.0f)
p.y = _upperBound.y;
if (normal.z >= 0.0f)
p.z = _upperBound.z;
return p;
}
Vec3f AABB3D::getVertexN(const Vec3f &normal) const {
Vec3f n(_upperBound);
if (normal.x >= 0.0f)
n.x = _lowerBound.x;
if (normal.y >= 0.0f)
n.y = _lowerBound.y;
if (normal.z >= 0.0f)
n.z = _lowerBound.z;
return n;
}
float AABB3D::getRadius() const {
return _halfDims.magnitude();
}
void AABB3D::expand(const Vec3f &point) {
if (point.x < _lowerBound.x)
_lowerBound.x = point.x;
if (point.y < _lowerBound.y)
_lowerBound.y = point.y;
if (point.z < _lowerBound.z)
_lowerBound.z = point.z;
if (point.x > _upperBound.x)
_upperBound.x = point.x;
if (point.y > _upperBound.y)
_upperBound.y = point.y;
if (point.z > _upperBound.z)
_upperBound.z = point.z;
}
void AABB3D::expand(const AABB3D &other) {
if (other._lowerBound.x < _lowerBound.x)
_lowerBound.x = other._lowerBound.x;
if (other._lowerBound.y < _lowerBound.y)
_lowerBound.y = other._lowerBound.y;
if (other._lowerBound.z < _lowerBound.z)
_lowerBound.z = other._lowerBound.z;
if (other._upperBound.x > _upperBound.x)
_upperBound.x = other._upperBound.x;
if (other._upperBound.y > _upperBound.y)
_upperBound.y = other._upperBound.y;
if (other._upperBound.z > _upperBound.z)
_upperBound.z = other._upperBound.z;
} | 26.127753 | 102 | 0.676446 | [
"vector",
"transform"
] |
905092cd50a8b8b2def41094546897033c20c722 | 8,454 | cc | C++ | tools/gn/function_get_path_info.cc | jBarz/gn | d2d7ecb2b20cca203d3b7cda5390f38a869c1b44 | [
"BSD-3-Clause"
] | 36 | 2018-08-20T08:31:24.000Z | 2021-12-04T18:02:57.000Z | tools/gn/function_get_path_info.cc | DanCraft99/gn-standalone-mirror-2 | 0fa107c2744d661d4c182ec0ddc8888571b0e530 | [
"BSD-3-Clause"
] | 5 | 2018-10-01T08:27:35.000Z | 2021-08-25T16:34:13.000Z | tools/gn/function_get_path_info.cc | DanCraft99/gn-standalone-mirror-2 | 0fa107c2744d661d4c182ec0ddc8888571b0e530 | [
"BSD-3-Clause"
] | 8 | 2018-09-28T08:36:56.000Z | 2021-03-13T10:15:32.000Z | // Copyright 2014 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 <stddef.h>
#include "tools/gn/err.h"
#include "tools/gn/filesystem_utils.h"
#include "tools/gn/functions.h"
#include "tools/gn/parse_tree.h"
#include "tools/gn/scope.h"
#include "tools/gn/value.h"
namespace functions {
namespace {
// Corresponds to the various values of "what" in the function call.
enum What {
WHAT_FILE,
WHAT_NAME,
WHAT_EXTENSION,
WHAT_DIR,
WHAT_ABSPATH,
WHAT_GEN_DIR,
WHAT_OUT_DIR,
};
// Returns the directory containing the input (resolving it against the
// |current_dir|), regardless of whether the input is a directory or a file.
SourceDir DirForInput(const Settings* settings,
const SourceDir& current_dir,
const Value& input,
Err* err) {
// Input should already have been validated as a string.
const std::string& input_string = input.string_value();
if (!input_string.empty() && input_string[input_string.size() - 1] == '/') {
// Input is a directory.
return current_dir.ResolveRelativeDir(
input, err, settings->build_settings()->root_path_utf8());
}
// Input is a file.
return current_dir
.ResolveRelativeFile(input, err,
settings->build_settings()->root_path_utf8())
.GetDir();
}
std::string GetOnePathInfo(const Settings* settings,
const SourceDir& current_dir,
What what,
const Value& input,
Err* err) {
if (!input.VerifyTypeIs(Value::STRING, err))
return std::string();
const std::string& input_string = input.string_value();
if (input_string.empty()) {
*err = Err(input, "Calling get_path_info on an empty string.");
return std::string();
}
switch (what) {
case WHAT_FILE: {
return FindFilename(&input_string).as_string();
}
case WHAT_NAME: {
std::string file = FindFilename(&input_string).as_string();
size_t extension_offset = FindExtensionOffset(file);
if (extension_offset == std::string::npos)
return file;
// Trim extension and dot.
return file.substr(0, extension_offset - 1);
}
case WHAT_EXTENSION: {
return FindExtension(&input_string).as_string();
}
case WHAT_DIR: {
base::StringPiece dir_incl_slash = FindDir(&input_string);
if (dir_incl_slash.empty())
return std::string(".");
// Trim slash since this function doesn't return trailing slashes. The
// times we don't do this are if the result is "/" and "//" since those
// slashes can't be trimmed.
if (dir_incl_slash == "/")
return std::string("/.");
if (dir_incl_slash == "//")
return std::string("//.");
return dir_incl_slash.substr(0, dir_incl_slash.size() - 1).as_string();
}
case WHAT_GEN_DIR: {
return DirectoryWithNoLastSlash(GetSubBuildDirAsSourceDir(
BuildDirContext(settings),
DirForInput(settings, current_dir, input, err), BuildDirType::GEN));
}
case WHAT_OUT_DIR: {
return DirectoryWithNoLastSlash(GetSubBuildDirAsSourceDir(
BuildDirContext(settings),
DirForInput(settings, current_dir, input, err), BuildDirType::OBJ));
}
case WHAT_ABSPATH: {
bool as_dir =
!input_string.empty() && input_string[input_string.size() - 1] == '/';
return current_dir.ResolveRelativeAs(
!as_dir, input, err, settings->build_settings()->root_path_utf8(),
&input_string);
}
default:
NOTREACHED();
return std::string();
}
}
} // namespace
const char kGetPathInfo[] = "get_path_info";
const char kGetPathInfo_HelpShort[] =
"get_path_info: Extract parts of a file or directory name.";
const char kGetPathInfo_Help[] =
R"(get_path_info: Extract parts of a file or directory name.
get_path_info(input, what)
The first argument is either a string representing a file or directory name,
or a list of such strings. If the input is a list the return value will be a
list containing the result of applying the rule to each item in the input.
Possible values for the "what" parameter
"file"
The substring after the last slash in the path, including the name and
extension. If the input ends in a slash, the empty string will be
returned.
"foo/bar.txt" => "bar.txt"
"bar.txt" => "bar.txt"
"foo/" => ""
"" => ""
"name"
The substring of the file name not including the extension.
"foo/bar.txt" => "bar"
"foo/bar" => "bar"
"foo/" => ""
"extension"
The substring following the last period following the last slash, or the
empty string if not found. The period is not included.
"foo/bar.txt" => "txt"
"foo/bar" => ""
"dir"
The directory portion of the name, not including the slash.
"foo/bar.txt" => "foo"
"//foo/bar" => "//foo"
"foo" => "."
The result will never end in a slash, so if the resulting is empty, the
system ("/") or source ("//") roots, a "." will be appended such that it
is always legal to append a slash and a filename and get a valid path.
"out_dir"
The output file directory corresponding to the path of the given file,
not including a trailing slash.
"//foo/bar/baz.txt" => "//out/Default/obj/foo/bar"
"gen_dir"
The generated file directory corresponding to the path of the given file,
not including a trailing slash.
"//foo/bar/baz.txt" => "//out/Default/gen/foo/bar"
"abspath"
The full absolute path name to the file or directory. It will be resolved
relative to the current directory, and then the source- absolute version
will be returned. If the input is system- absolute, the same input will
be returned.
"foo/bar.txt" => "//mydir/foo/bar.txt"
"foo/" => "//mydir/foo/"
"//foo/bar" => "//foo/bar" (already absolute)
"/usr/include" => "/usr/include" (already absolute)
If you want to make the path relative to another directory, or to be
system-absolute, see rebase_path().
Examples
sources = [ "foo.cc", "foo.h" ]
result = get_path_info(source, "abspath")
# result will be [ "//mydir/foo.cc", "//mydir/foo.h" ]
result = get_path_info("//foo/bar/baz.cc", "dir")
# result will be "//foo/bar"
# Extract the source-absolute directory name,
result = get_path_info(get_path_info(path, "dir"), "abspath"
)";
Value RunGetPathInfo(Scope* scope,
const FunctionCallNode* function,
const std::vector<Value>& args,
Err* err) {
if (args.size() != 2) {
*err = Err(function, "Expecting two arguments to get_path_info.");
return Value();
}
// Extract the "what".
if (!args[1].VerifyTypeIs(Value::STRING, err))
return Value();
What what;
if (args[1].string_value() == "file") {
what = WHAT_FILE;
} else if (args[1].string_value() == "name") {
what = WHAT_NAME;
} else if (args[1].string_value() == "extension") {
what = WHAT_EXTENSION;
} else if (args[1].string_value() == "dir") {
what = WHAT_DIR;
} else if (args[1].string_value() == "out_dir") {
what = WHAT_OUT_DIR;
} else if (args[1].string_value() == "gen_dir") {
what = WHAT_GEN_DIR;
} else if (args[1].string_value() == "abspath") {
what = WHAT_ABSPATH;
} else {
*err = Err(args[1], "Unknown value for 'what'.");
return Value();
}
const SourceDir& current_dir = scope->GetSourceDir();
if (args[0].type() == Value::STRING) {
return Value(function, GetOnePathInfo(scope->settings(), current_dir, what,
args[0], err));
} else if (args[0].type() == Value::LIST) {
const std::vector<Value>& input_list = args[0].list_value();
Value result(function, Value::LIST);
for (const auto& cur : input_list) {
result.list_value().push_back(Value(
function,
GetOnePathInfo(scope->settings(), current_dir, what, cur, err)));
if (err->has_error())
return Value();
}
return result;
}
*err = Err(args[0], "Path must be a string or a list of strings.");
return Value();
}
} // namespace functions
| 33.547619 | 80 | 0.622664 | [
"vector"
] |
9052194f5b6069eaaa7e06c00ffc005d766c4f48 | 4,870 | cc | C++ | RecoTracker/FinalTrackSelectors/plugins/TrackTfClassifier.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 13 | 2015-11-30T15:49:45.000Z | 2022-02-08T16:11:30.000Z | RecoTracker/FinalTrackSelectors/plugins/TrackTfClassifier.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 640 | 2015-02-11T18:55:47.000Z | 2022-03-31T14:12:23.000Z | RecoTracker/FinalTrackSelectors/plugins/TrackTfClassifier.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 51 | 2015-08-11T21:01:40.000Z | 2022-03-30T07:31:34.000Z | #include "RecoTracker/FinalTrackSelectors/interface/TrackMVAClassifier.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/global/EDProducer.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
#include "FWCore/Framework/interface/ConsumesCollector.h"
#include "getBestVertex.h"
#include "TrackingTools/Records/interface/TfGraphRecord.h"
#include "PhysicsTools/TensorFlow/interface/TensorFlow.h"
#include "RecoTracker/FinalTrackSelectors/interface/TfGraphDefWrapper.h"
namespace {
class TfDnn {
public:
TfDnn(const edm::ParameterSet& cfg)
: tfDnnLabel_(cfg.getParameter<std::string>("tfDnnLabel")),
session_(nullptr)
{}
static const char* name() { return "TrackTfClassifier"; }
static void fillDescriptions(edm::ParameterSetDescription& desc) {
desc.add<std::string>("tfDnnLabel", "trackSelectionTf");
}
void beginStream() {}
void initEvent(const edm::EventSetup& es) {
if (session_ == nullptr) {
edm::ESHandle<TfGraphDefWrapper> tfDnnHandle;
es.get<TfGraphRecord>().get(tfDnnLabel_, tfDnnHandle);
session_ = tfDnnHandle.product()->getSession();
}
}
float operator()(reco::Track const& trk,
reco::BeamSpot const& beamSpot,
reco::VertexCollection const& vertices) const {
const auto& bestVertex = getBestVertex(trk, vertices);
tensorflow::Tensor input1(tensorflow::DT_FLOAT, {1, 29});
tensorflow::Tensor input2(tensorflow::DT_FLOAT, {1, 1});
input1.matrix<float>()(0, 0) = trk.pt();
input1.matrix<float>()(0, 1) = trk.innerMomentum().x();
input1.matrix<float>()(0, 2) = trk.innerMomentum().y();
input1.matrix<float>()(0, 3) = trk.innerMomentum().z();
input1.matrix<float>()(0, 4) = trk.innerMomentum().rho();
input1.matrix<float>()(0, 5) = trk.outerMomentum().x();
input1.matrix<float>()(0, 6) = trk.outerMomentum().y();
input1.matrix<float>()(0, 7) = trk.outerMomentum().z();
input1.matrix<float>()(0, 8) = trk.outerMomentum().rho();
input1.matrix<float>()(0, 9) = trk.ptError();
input1.matrix<float>()(0, 10) = trk.dxy(bestVertex);
input1.matrix<float>()(0, 11) = trk.dz(bestVertex);
input1.matrix<float>()(0, 12) = trk.dxy(beamSpot.position());
input1.matrix<float>()(0, 13) = trk.dz(beamSpot.position());
input1.matrix<float>()(0, 14) = trk.dxyError();
input1.matrix<float>()(0, 15) = trk.dzError();
input1.matrix<float>()(0, 16) = trk.normalizedChi2();
input1.matrix<float>()(0, 17) = trk.eta();
input1.matrix<float>()(0, 18) = trk.phi();
input1.matrix<float>()(0, 19) = trk.etaError();
input1.matrix<float>()(0, 20) = trk.phiError();
input1.matrix<float>()(0, 21) = trk.hitPattern().numberOfValidPixelHits();
input1.matrix<float>()(0, 22) = trk.hitPattern().numberOfValidStripHits();
input1.matrix<float>()(0, 23) = trk.ndof();
input1.matrix<float>()(0, 24) = trk.hitPattern().numberOfLostTrackerHits(reco::HitPattern::MISSING_INNER_HITS);
input1.matrix<float>()(0, 25) = trk.hitPattern().numberOfLostTrackerHits(reco::HitPattern::MISSING_OUTER_HITS);
input1.matrix<float>()(0, 26) =
trk.hitPattern().trackerLayersTotallyOffOrBad(reco::HitPattern::MISSING_INNER_HITS);
input1.matrix<float>()(0, 27) =
trk.hitPattern().trackerLayersTotallyOffOrBad(reco::HitPattern::MISSING_OUTER_HITS);
input1.matrix<float>()(0, 28) = trk.hitPattern().trackerLayersWithoutMeasurement(reco::HitPattern::TRACK_HITS);
//Original algo as its own input, it will enter the graph so that it gets one-hot encoded, as is the preferred
//format for categorical inputs, where the labels do not have any metric amongst them
input2.matrix<float>()(0, 0) = trk.originalAlgo();
//The names for the input tensors get locked when freezing the trained tensorflow model. The NamedTensors must
//match those names
tensorflow::NamedTensorList inputs;
inputs.resize(2);
inputs[0] = tensorflow::NamedTensor("x", input1);
inputs[1] = tensorflow::NamedTensor("y", input2);
std::vector<tensorflow::Tensor> outputs;
//evaluate the input
tensorflow::run(const_cast<tensorflow::Session*>(session_), inputs, {"Identity"}, &outputs);
//scale output to be [-1, 1] due to convention
float output = 2.0 * outputs[0].matrix<float>()(0, 0) - 1.0;
return output;
}
const std::string tfDnnLabel_;
const tensorflow::Session* session_;
};
using TrackTfClassifier = TrackMVAClassifier<TfDnn>;
} // namespace
#include "FWCore/PluginManager/interface/ModuleDef.h"
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(TrackTfClassifier);
| 45.092593 | 117 | 0.670431 | [
"vector",
"model"
] |
90554a1445ac172eeffee50e54adb1f2ab2a9c8e | 6,548 | cpp | C++ | dali/internal/update/rendering/scene-graph-texture-set.cpp | pwisbey/dali-core | 53117f5d4178001b0d688c5bce14d7bf8e861631 | [
"Apache-2.0"
] | 1 | 2016-08-05T09:58:38.000Z | 2016-08-05T09:58:38.000Z | dali/internal/update/rendering/scene-graph-texture-set.cpp | tizenorg/platform.core.uifw.dali-core | dd89513b4bb1fdde74a83996c726e10adaf58349 | [
"Apache-2.0"
] | null | null | null | dali/internal/update/rendering/scene-graph-texture-set.cpp | tizenorg/platform.core.uifw.dali-core | dd89513b4bb1fdde74a83996c726e10adaf58349 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2016 Samsung Electronics Co., Ltd.
*
* 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.
*/
// CLASS HEADER
#include "scene-graph-texture-set.h"
// INTERNAL HEADERS
#include <dali/integration-api/resource-declarations.h>
#include <dali/internal/common/internal-constants.h>
#include <dali/internal/update/resources/texture-metadata.h>
#include <dali/internal/update/resources/resource-manager.h>
#include <dali/internal/common/memory-pool-object-allocator.h>
#include <dali/internal/update/rendering/scene-graph-renderer.h>
namespace //Unnamed namespace
{
//Memory pool used to allocate new texture sets. Memory used by this pool will be released when shutting down DALi
Dali::Internal::MemoryPoolObjectAllocator<Dali::Internal::SceneGraph::TextureSet> gTextureSetMemoryPool;
}
namespace Dali
{
namespace Internal
{
namespace SceneGraph
{
TextureSet* TextureSet::New()
{
return new ( gTextureSetMemoryPool.AllocateRawThreadSafe() ) TextureSet();
}
TextureSet::TextureSet()
: mSamplers(),
mTextureId(),
mRenderers(),
mResourcesReady( true ),
mFinishedResourceAcquisition( true ),
mChanged( true ),
mHasAlpha( false )
{
}
TextureSet::~TextureSet()
{
}
void TextureSet::operator delete( void* ptr )
{
gTextureSetMemoryPool.FreeThreadSafe( static_cast<TextureSet*>( ptr ) );
}
void TextureSet::Prepare( const ResourceManager& resourceManager )
{
if( mChanged && mTextures.Empty() )
{
unsigned int opaqueCount = 0;
unsigned int completeCount = 0;
unsigned int failedCount = 0;
unsigned int frameBufferCount = 0;
const std::size_t textureCount( mTextureId.Count() );
if( textureCount > 0 )
{
for( unsigned int i(0); i<textureCount; ++i )
{
const ResourceId textureId = mTextureId[ i ];
TextureMetadata* metadata = NULL;
if( textureId != Integration::InvalidResourceId )
{
// if there is metadata, resource is loaded
if( resourceManager.GetTextureMetadata( textureId, metadata ) )
{
DALI_ASSERT_DEBUG( metadata );
// metadata is valid pointer from now on
if( metadata->IsFullyOpaque() )
{
++opaqueCount;
}
if( metadata->IsFramebuffer() )
{
if( metadata->HasFrameBufferBeenRenderedTo() )
{
++completeCount;
}
else
{
frameBufferCount++;
}
}
else
{
// loaded so will complete this frame
++completeCount;
}
// no point checking failure as there is no metadata for failed loads
}
// if no metadata, loading can be failed
else if( resourceManager.HasResourceLoadFailed( textureId ) )
{
++failedCount;
}
}
else
{
//If the texture is not valid it is considerer opaque and complete
++opaqueCount;
++completeCount;
}
}
}
mHasAlpha = ( opaqueCount != textureCount );
// ready for rendering when all textures are either successfully loaded or they are FBOs
mResourcesReady = (completeCount + frameBufferCount >= textureCount);
// Texture set is complete if all resources are either loaded or failed or, if they are FBOs have been rendererd to
mFinishedResourceAcquisition = ( completeCount + failedCount == textureCount );
if( mFinishedResourceAcquisition )
{
// Texture set is now considered not changed
mChanged = false;
}
}
}
void TextureSet::SetImage( size_t index, ResourceId imageId )
{
size_t textureCount( mTextureId.Size() );
if( textureCount < index + 1 )
{
mTextureId.Resize( index + 1 );
mSamplers.Resize( index + 1 );
for( size_t i(textureCount); i<=index; ++i )
{
mTextureId[i] = Integration::InvalidResourceId;
mSamplers[i] = NULL;
}
}
mTextureId[index] = imageId;
mChanged = true;
NotifyChangeToRenderers();
}
void TextureSet::SetSampler( size_t index, Render::Sampler* sampler )
{
size_t samplerCount( mSamplers.Size() );
if( samplerCount < index + 1 )
{
mSamplers.Resize( index + 1 );
mTextureId.Resize( index + 1 );
for( size_t i(samplerCount); i<=index; ++i )
{
mTextureId[i] = Integration::InvalidResourceId;
mSamplers[i] = NULL;
}
}
mSamplers[index] = sampler;
NotifyChangeToRenderers();
}
void TextureSet::SetTexture( size_t index, Render::NewTexture* texture )
{
const size_t textureCount( mTextures.Size() );
if( textureCount < index + 1 )
{
mTextures.Resize( index + 1 );
mSamplers.Resize( index + 1 );
for( size_t i(textureCount); i<=index; ++i )
{
mTextures[i] = 0;
mSamplers[i] = 0;
}
}
mTextures[index] = texture;
mHasAlpha |= texture->HasAlphaChannel();
NotifyChangeToRenderers();
}
bool TextureSet::HasAlpha() const
{
return mHasAlpha;
}
void TextureSet::GetResourcesStatus( bool& resourcesReady, bool& finishedResourceAcquisition )
{
resourcesReady = mResourcesReady;
finishedResourceAcquisition = mFinishedResourceAcquisition;
}
void TextureSet::AddObserver( Renderer* renderer )
{
size_t rendererCount( mRenderers.Size() );
for( size_t i(0); i<rendererCount; ++i )
{
if( mRenderers[i] == renderer )
{
//Renderer already in the list
return;
}
}
mRenderers.PushBack( renderer );
}
void TextureSet::RemoveObserver( Renderer* renderer )
{
size_t rendererCount( mRenderers.Size() );
for( size_t i(0); i<rendererCount; ++i )
{
if( mRenderers[i] == renderer )
{
mRenderers.Remove( mRenderers.Begin() + i );
return;
}
}
}
void TextureSet::NotifyChangeToRenderers()
{
size_t rendererCount = mRenderers.Size();
for( size_t i(0); i<rendererCount; ++i )
{
mRenderers[i]->TextureSetChanged();
}
}
} // namespace SceneGraph
} // namespace Internal
} // namespace Dali
| 25.779528 | 119 | 0.647831 | [
"render",
"object"
] |
905852554ab209c82e27af15b4fb6a42dc84e3d4 | 4,048 | cc | C++ | tensorflow_serving/servables/alphafm/feature_mapping.cc | hzy001/xgboost-serving-1 | 163b6dc22e1dd57503d682c7f10a13636638f93f | [
"Apache-2.0"
] | 106 | 2021-06-24T06:47:27.000Z | 2022-03-11T01:52:19.000Z | tensorflow_serving/servables/alphafm/feature_mapping.cc | hzy001/xgboost-serving-1 | 163b6dc22e1dd57503d682c7f10a13636638f93f | [
"Apache-2.0"
] | 1 | 2021-12-30T05:11:10.000Z | 2021-12-30T05:11:10.000Z | tensorflow_serving/servables/alphafm/feature_mapping.cc | hzy001/xgboost-serving-1 | 163b6dc22e1dd57503d682c7f10a13636638f93f | [
"Apache-2.0"
] | 12 | 2021-06-24T02:14:04.000Z | 2021-11-15T05:47:01.000Z | /*
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_serving/servables/alphafm/feature_mapping.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow_serving/util/strings/numeric.h"
#include "tensorflow_serving/util/strings/split.h"
#include <fstream>
#include <vector>
namespace tensorflow {
namespace serving {
FeatureMapping::FeatureMapping() {
LOG(INFO) << "Call the constructor FeatureMapping().";
}
FeatureMapping::FeatureMapping(std::string model_path) {
LOG(INFO) << "Call the constructor FeatureMapping(model_path).";
Status status = LoadModel(model_path);
if (status.ok()) {
LOG(INFO) << "Load the FeatureMapping Model successfully.";
} else {
LOG(ERROR) << "Failed to load the FeatureMapping Model.";
}
}
FeatureMapping::~FeatureMapping() {
LOG(INFO) << "Call the destructor ~FeatureMapping().";
UnloadModel();
}
Status FeatureMapping::LoadModel(std::string model_path) {
LOG(INFO) << "Call the method LoadModel(model_path).";
std::ifstream infile(model_path, std::ios::in | std::ios::binary);
if (!infile) {
LOG(ERROR) << "Failed to open the file: " + model_path;
return errors::Unknown("Failed to open the file: " + model_path);
}
string line;
while (!infile.eof()) {
std::getline(infile, line);
if (line.empty()) {
LOG(WARNING) << "Empty line";
continue;
}
std::vector<string> split_vec;
::SplitStringUsing(line, " \t", &split_vec);
if (split_vec.size() < 2) {
LOG(WARNING) << "Feature mapping line parsing error: " << line;
continue;
}
uint32_t tree_num;
if (!::safe_strtoul(split_vec[0], &tree_num)) {
LOG(WARNING) << "Feature mapping line parsing error: " << line;
continue;
}
auto itr = split_vec.begin() + 1;
for (; itr != split_vec.end(); ++itr) {
std::vector<string> tree_leaf_pair_vec;
::SplitStringUsing(*itr, ":", &tree_leaf_pair_vec);
if (tree_leaf_pair_vec.size() != 2) {
LOG(WARNING) << "Feature mapping line parsing error: " << line;
continue;
}
uint32_t leaf_index;
int feature_id;
if (!::safe_strtoul(tree_leaf_pair_vec[0], &leaf_index) ||
!::safe_strtol(tree_leaf_pair_vec[1], &feature_id)) {
LOG(WARNING) << "Feature mapping line parsing error: " << line;
continue;
}
tree_leaf_feature_map_[tree_num].emplace(leaf_index, feature_id);
}
}
return Status::OK();
}
Status FeatureMapping::GetFeatureId(uint32_t tree_num, uint32_t leaf_index,
uint64_t *feature_id) {
return GetFeatureIdInMap(tree_num, leaf_index, feature_id);
}
Status FeatureMapping::GetFeatureIdInMap(uint32_t tree_num, uint32_t leaf_index,
uint64_t *feature_id) {
auto tree_num_itr = tree_leaf_feature_map_.find(tree_num);
if (tree_num_itr == tree_leaf_feature_map_.end()) {
return errors::Unknown(
"Failed to find the tree_num in the tree_leaf_feature_map.");
}
auto feature_id_itr = tree_num_itr->second.find(leaf_index);
if (feature_id_itr == tree_num_itr->second.end()) {
return errors::Unknown(
"Failed to find the leaf_index in the tree_leaf_feature_map.");
}
*feature_id = feature_id_itr->second;
return Status::OK();
}
void FeatureMapping::UnloadModel() {
LOG(INFO) << "Call the method UnloadModel().";
tree_leaf_feature_map_.clear();
}
} // namespace serving
} // namespace tensorflow
| 33.733333 | 80 | 0.66502 | [
"vector",
"model"
] |
90613ed7dd2fc86cf9dcad04b1221945d0682d32 | 34,193 | cpp | C++ | cpp/tests/strings/split_tests.cpp | brandon-b-miller/cudf | 5d2d68ef231bedd3a7e590b071f4d8e4af7e5f93 | [
"Apache-2.0"
] | 1 | 2020-04-18T23:47:25.000Z | 2020-04-18T23:47:25.000Z | cpp/tests/strings/split_tests.cpp | brandon-b-miller/cudf | 5d2d68ef231bedd3a7e590b071f4d8e4af7e5f93 | [
"Apache-2.0"
] | null | null | null | cpp/tests/strings/split_tests.cpp | brandon-b-miller/cudf | 5d2d68ef231bedd3a7e590b071f4d8e4af7e5f93 | [
"Apache-2.0"
] | 1 | 2021-10-03T20:29:10.000Z | 2021-10-03T20:29:10.000Z | /*
* Copyright (c) 2019, NVIDIA CORPORATION.
*
* 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 <cudf/column/column_factories.hpp>
#include <cudf/table/table.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/strings/split/partition.hpp>
#include <cudf/strings/split/split.hpp>
#include <tests/utilities/base_fixture.hpp>
#include <tests/utilities/column_wrapper.hpp>
#include <tests/utilities/column_utilities.hpp>
#include <tests/utilities/table_utilities.hpp>
#include <tests/strings/utilities.h>
#include <vector>
#include <gmock/gmock.h>
struct StringsSplitTest : public cudf::test::BaseFixture {};
TEST_F(StringsSplitTest, Split)
{
std::vector<const char*> h_strings{ "Héllo thesé", nullptr, "are some", "tést String", "" };
cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view( strings );
std::vector<const char*> h_expected1{ "Héllo", nullptr, "are", "tést", "" };
cudf::test::strings_column_wrapper expected1( h_expected1.begin(), h_expected1.end(),
thrust::make_transform_iterator( h_expected1.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<const char*> h_expected2{ "thesé", nullptr, "some", "String", nullptr };
cudf::test::strings_column_wrapper expected2( h_expected2.begin(), h_expected2.end(),
thrust::make_transform_iterator( h_expected2.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
auto expected = std::make_unique<cudf::experimental::table>(std::move(expected_columns));
auto results = cudf::strings::split(strings_view, cudf::string_scalar(" "));
EXPECT_TRUE( results->num_columns()==2 );
cudf::test::expect_tables_equal(*results,*expected);
}
TEST_F(StringsSplitTest, SplitWhitespace)
{
std::vector<const char*> h_strings{ "Héllo thesé", nullptr, "are\tsome", "tést\nString", " " };
cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view( strings );
std::vector<const char*> h_expected1{ "Héllo", nullptr, "are", "tést", nullptr };
cudf::test::strings_column_wrapper expected1( h_expected1.begin(), h_expected1.end(),
thrust::make_transform_iterator( h_expected1.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<const char*> h_expected2{ "thesé", nullptr, "some", "String", nullptr };
cudf::test::strings_column_wrapper expected2( h_expected2.begin(), h_expected2.end(),
thrust::make_transform_iterator( h_expected2.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
auto expected = std::make_unique<cudf::experimental::table>(std::move(expected_columns));
auto results = cudf::strings::split(strings_view);
EXPECT_TRUE( results->num_columns()==2 );
cudf::test::expect_tables_equal(*results,*expected);
}
TEST_F(StringsSplitTest, RSplit)
{
std::vector<const char*> h_strings{ "héllo", nullptr, "a_bc_déf", "a__bc", "_ab_cd", "ab_cd_", "", " a b ", " a bbb c" };
cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view( strings );
std::vector<const char*> h_expected1{ "héllo", nullptr, "a", "a", "", "ab", "", " a b ", " a bbb c" };
cudf::test::strings_column_wrapper expected1( h_expected1.begin(), h_expected1.end(),
thrust::make_transform_iterator( h_expected1.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<const char*> h_expected2{ nullptr, nullptr, "bc", "", "ab", "cd", nullptr, nullptr, nullptr };
cudf::test::strings_column_wrapper expected2( h_expected2.begin(), h_expected2.end(),
thrust::make_transform_iterator( h_expected2.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<const char*> h_expected3{ nullptr, nullptr, "déf", "bc", "cd", "", nullptr, nullptr, nullptr };
cudf::test::strings_column_wrapper expected3( h_expected3.begin(), h_expected3.end(),
thrust::make_transform_iterator( h_expected3.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
auto expected = std::make_unique<cudf::experimental::table>(std::move(expected_columns));
auto results = cudf::strings::rsplit(strings_view, cudf::string_scalar("_"));
EXPECT_TRUE( results->num_columns()==3 );
cudf::test::expect_tables_equal(*results,*expected);
}
TEST_F(StringsSplitTest, RSplitWhitespace)
{
std::vector<const char*> h_strings{ "héllo", nullptr, "a_bc_déf", "", " a\tb ", " a\r bbb c" };
cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view( strings );
std::vector<const char*> h_expected1{ "héllo", nullptr, "a_bc_déf", nullptr, "a", "a" };
cudf::test::strings_column_wrapper expected1( h_expected1.begin(), h_expected1.end(),
thrust::make_transform_iterator( h_expected1.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<const char*> h_expected2{ nullptr, nullptr, nullptr, nullptr, "b", "bbb" };
cudf::test::strings_column_wrapper expected2( h_expected2.begin(), h_expected2.end(),
thrust::make_transform_iterator( h_expected2.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<const char*> h_expected3{ nullptr, nullptr, nullptr, nullptr, nullptr, "c" };
cudf::test::strings_column_wrapper expected3( h_expected3.begin(), h_expected3.end(),
thrust::make_transform_iterator( h_expected3.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
auto expected = std::make_unique<cudf::experimental::table>(std::move(expected_columns));
auto results = cudf::strings::rsplit(strings_view);
EXPECT_TRUE( results->num_columns()==3 );
cudf::test::expect_tables_equal(*results,*expected);
}
TEST_F(StringsSplitTest, SplitZeroSizeStringsColumns)
{
cudf::column_view zero_size_strings_column( cudf::data_type{cudf::STRING}, 0, nullptr, nullptr, 0);
auto results = cudf::strings::split(zero_size_strings_column);
EXPECT_TRUE( results->num_columns()==1 );
cudf::test::expect_strings_empty(results->get_column(0));
results = cudf::strings::rsplit(zero_size_strings_column);
EXPECT_TRUE( results->num_columns()==1 );
cudf::test::expect_strings_empty(results->get_column(0));
}
// This test specifically for https://github.com/rapidsai/custrings/issues/119
TEST_F(StringsSplitTest, AllNullsCase)
{
std::vector<const char*> h_strings{ nullptr, nullptr, nullptr };
cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
auto results = cudf::strings::split(cudf::strings_column_view(strings));
EXPECT_TRUE( results->num_columns()==1 );
auto column = results->get_column(0);
EXPECT_TRUE( column.size()==3 );
EXPECT_TRUE( column.has_nulls() );
EXPECT_TRUE( column.null_count()==column.size() );
}
TEST_F(StringsSplitTest, ContiguousSplitRecord)
{
std::vector<const char*> h_strings{ " Héllo thesé", nullptr, "are some ", "tést String", "" };
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator(h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view(strings);
std::vector<const char*> h_expected1{ "", "Héllo", "thesé" };
cudf::test::strings_column_wrapper expected1(h_expected1.begin(), h_expected1.end());
std::vector<const char*> h_expected2{};
cudf::test::strings_column_wrapper expected2(h_expected2.begin(), h_expected2.end());
std::vector<const char*> h_expected3{ "are", "some", "", "" };
cudf::test::strings_column_wrapper expected3(h_expected3.begin(), h_expected3.end());
std::vector<const char*> h_expected4{ "tést", "String" };
cudf::test::strings_column_wrapper expected4(h_expected4.begin(), h_expected4.end());
std::vector<const char*> h_expected5{ "" };
cudf::test::strings_column_wrapper expected5(h_expected5.begin(), h_expected5.end());
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
expected_columns.push_back(expected4.release());
expected_columns.push_back(expected5.release());
auto result = cudf::strings::contiguous_split_record(strings_view, cudf::string_scalar(" "));
EXPECT_TRUE(result.column_views.size() == expected_columns.size());
for (size_t i = 0; i < result.column_views.size(); ++i) {
cudf::test::expect_columns_equal(result.column_views[i], *expected_columns[i]);
}
}
TEST_F(StringsSplitTest, ContiguousSplitRecordWithMaxSplit)
{
std::vector<const char*> h_strings{ " Héllo thesé", nullptr, "are some ", "tést String", "" };
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator(h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view(strings);
std::vector<const char*> h_expected1{ "", "Héllo thesé" };
cudf::test::strings_column_wrapper expected1(h_expected1.begin(), h_expected1.end());
std::vector<const char*> h_expected2{};
cudf::test::strings_column_wrapper expected2(h_expected2.begin(), h_expected2.end());
std::vector<const char*> h_expected3{ "are", "some " };
cudf::test::strings_column_wrapper expected3(h_expected3.begin(), h_expected3.end());
std::vector<const char*> h_expected4{ "tést", "String" };
cudf::test::strings_column_wrapper expected4(h_expected4.begin(), h_expected4.end());
std::vector<const char*> h_expected5{ "" };
cudf::test::strings_column_wrapper expected5(h_expected5.begin(), h_expected5.end());
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
expected_columns.push_back(expected4.release());
expected_columns.push_back(expected5.release());
auto result = cudf::strings::contiguous_split_record(strings_view, cudf::string_scalar(" "), 1);
EXPECT_TRUE(result.column_views.size() == expected_columns.size());
for (size_t i = 0; i < result.column_views.size(); ++i) {
cudf::test::expect_columns_equal(result.column_views[i], *expected_columns[i]);
}
}
TEST_F(StringsSplitTest, ContiguousSplitRecordWhitespace)
{
std::vector<const char*> h_strings{ " Héllo thesé", nullptr, "are\tsome ", "tést\nString", " " };
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator(h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view(strings);
std::vector<const char*> h_expected1{ "Héllo", "thesé" };
cudf::test::strings_column_wrapper expected1(h_expected1.begin(), h_expected1.end());
std::vector<const char*> h_expected2{};
cudf::test::strings_column_wrapper expected2(h_expected2.begin(), h_expected2.end());
std::vector<const char*> h_expected3{ "are", "some" };
cudf::test::strings_column_wrapper expected3(h_expected3.begin(), h_expected3.end());
std::vector<const char*> h_expected4{ "tést", "String" };
cudf::test::strings_column_wrapper expected4(h_expected4.begin(), h_expected4.end());
std::vector<const char*> h_expected5{};
cudf::test::strings_column_wrapper expected5(h_expected5.begin(), h_expected5.end());
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
expected_columns.push_back(expected4.release());
expected_columns.push_back(expected5.release());
auto result = cudf::strings::contiguous_split_record(strings_view);
EXPECT_TRUE(result.column_views.size() == expected_columns.size());
for (size_t i = 0; i < result.column_views.size(); ++i) {
cudf::test::expect_columns_equal(result.column_views[i], *expected_columns[i]);
}
}
TEST_F(StringsSplitTest, ContiguousSplitRecordWhitespaceWithMaxSplit)
{
std::vector<const char*> h_strings{ " Héllo thesé ", nullptr, "are\tsome ", "tést\nString", " " };
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator(h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view(strings);
std::vector<const char*> h_expected1{ "Héllo", "thesé " };
cudf::test::strings_column_wrapper expected1(h_expected1.begin(), h_expected1.end());
std::vector<const char*> h_expected2{};
cudf::test::strings_column_wrapper expected2(h_expected2.begin(), h_expected2.end());
std::vector<const char*> h_expected3{ "are", "some " };
cudf::test::strings_column_wrapper expected3(h_expected3.begin(), h_expected3.end());
std::vector<const char*> h_expected4{ "tést", "String" };
cudf::test::strings_column_wrapper expected4(h_expected4.begin(), h_expected4.end());
std::vector<const char*> h_expected5{};
cudf::test::strings_column_wrapper expected5(h_expected5.begin(), h_expected5.end());
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
expected_columns.push_back(expected4.release());
expected_columns.push_back(expected5.release());
auto result = cudf::strings::contiguous_split_record(strings_view, cudf::string_scalar(""), 1);
EXPECT_TRUE(result.column_views.size() == expected_columns.size());
for (size_t i = 0; i < result.column_views.size(); ++i) {
cudf::test::expect_columns_equal(result.column_views[i], *expected_columns[i]);
}
}
TEST_F(StringsSplitTest, ContiguousRSplitRecord)
{
std::vector<const char*> h_strings{ "héllo", nullptr, "a_bc_déf", "a__bc", "_ab_cd", "ab_cd_", "", " a b ", " a bbb c" };
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator(h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view(strings);
std::vector<const char*> h_expected1{ "héllo" };
cudf::test::strings_column_wrapper expected1(h_expected1.begin(), h_expected1.end());
std::vector<const char*> h_expected2{};
cudf::test::strings_column_wrapper expected2(h_expected2.begin(), h_expected2.end());
std::vector<const char*> h_expected3{ "a", "bc", "déf" };
cudf::test::strings_column_wrapper expected3(h_expected3.begin(), h_expected3.end());
std::vector<const char*> h_expected4{ "a", "", "bc" };
cudf::test::strings_column_wrapper expected4(h_expected4.begin(), h_expected4.end());
std::vector<const char*> h_expected5{ "", "ab", "cd" };
cudf::test::strings_column_wrapper expected5(h_expected5.begin(), h_expected5.end());
std::vector<const char*> h_expected6{ "ab", "cd", "" };
cudf::test::strings_column_wrapper expected6(h_expected6.begin(), h_expected6.end());
std::vector<const char*> h_expected7{ "" };
cudf::test::strings_column_wrapper expected7(h_expected7.begin(), h_expected7.end());
std::vector<const char*> h_expected8{ " a b " };
cudf::test::strings_column_wrapper expected8(h_expected8.begin(), h_expected8.end());
std::vector<const char*> h_expected9{ " a bbb c" };
cudf::test::strings_column_wrapper expected9(h_expected9.begin(), h_expected9.end());
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
expected_columns.push_back(expected4.release());
expected_columns.push_back(expected5.release());
expected_columns.push_back(expected6.release());
expected_columns.push_back(expected7.release());
expected_columns.push_back(expected8.release());
expected_columns.push_back(expected9.release());
auto result = cudf::strings::contiguous_rsplit_record(strings_view, cudf::string_scalar("_"));
EXPECT_TRUE(result.column_views.size() == expected_columns.size());
for (size_t i = 0; i < result.column_views.size(); i++) {
cudf::test::expect_columns_equal(result.column_views[i], *expected_columns[i]);
}
}
TEST_F(StringsSplitTest, ContiguousRSplitRecordWithMaxSplit)
{
std::vector<const char*> h_strings{ "héllo", nullptr, "a_bc_déf", "___a__bc", "_ab_cd_", "ab_cd_", "", " a b ___", "___ a bbb c" };
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator(h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view(strings);
std::vector<const char*> h_expected1{ "héllo" };
cudf::test::strings_column_wrapper expected1(h_expected1.begin(), h_expected1.end());
std::vector<const char*> h_expected2{};
cudf::test::strings_column_wrapper expected2(h_expected2.begin(), h_expected2.end());
std::vector<const char*> h_expected3{ "a", "bc", "déf" };
cudf::test::strings_column_wrapper expected3(h_expected3.begin(), h_expected3.end());
std::vector<const char*> h_expected4{ "___a", "", "bc" };
cudf::test::strings_column_wrapper expected4(h_expected4.begin(), h_expected4.end());
std::vector<const char*> h_expected5{ "_ab", "cd", "" };
cudf::test::strings_column_wrapper expected5(h_expected5.begin(), h_expected5.end());
std::vector<const char*> h_expected6{ "ab", "cd", "" };
cudf::test::strings_column_wrapper expected6(h_expected6.begin(), h_expected6.end());
std::vector<const char*> h_expected7{ "" };
cudf::test::strings_column_wrapper expected7(h_expected7.begin(), h_expected7.end());
std::vector<const char*> h_expected8{ " a b _", "", "" };
cudf::test::strings_column_wrapper expected8(h_expected8.begin(), h_expected8.end());
std::vector<const char*> h_expected9{ "_", "", " a bbb c" };
cudf::test::strings_column_wrapper expected9(h_expected9.begin(), h_expected9.end());
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
expected_columns.push_back(expected4.release());
expected_columns.push_back(expected5.release());
expected_columns.push_back(expected6.release());
expected_columns.push_back(expected7.release());
expected_columns.push_back(expected8.release());
expected_columns.push_back(expected9.release());
auto result = cudf::strings::contiguous_rsplit_record(strings_view, cudf::string_scalar("_"), 2);
EXPECT_TRUE(result.column_views.size() == expected_columns.size());
for (size_t i = 0; i < result.column_views.size(); i++) {
cudf::test::expect_columns_equal(result.column_views[i], *expected_columns[i]);
}
}
TEST_F(StringsSplitTest, ContiguousRSplitRecordWhitespace)
{
std::vector<const char*> h_strings{ "héllo", nullptr, "a_bc_déf", "", " a\tb ", " a\r bbb c" };
cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view( strings );
std::vector<const char*> h_expected1{ "héllo" };
cudf::test::strings_column_wrapper expected1(h_expected1.begin(), h_expected1.end());
std::vector<const char*> h_expected2{};
cudf::test::strings_column_wrapper expected2(h_expected2.begin(), h_expected2.end());
std::vector<const char*> h_expected3{ "a_bc_déf" };
cudf::test::strings_column_wrapper expected3(h_expected3.begin(), h_expected3.end());
std::vector<const char*> h_expected4{};
cudf::test::strings_column_wrapper expected4(h_expected4.begin(), h_expected4.end());
std::vector<const char*> h_expected5{ "a", "b" };
cudf::test::strings_column_wrapper expected5(h_expected5.begin(), h_expected5.end());
std::vector<const char*> h_expected6{ "a", "bbb", "c" };
cudf::test::strings_column_wrapper expected6(h_expected6.begin(), h_expected6.end());
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
expected_columns.push_back(expected4.release());
expected_columns.push_back(expected5.release());
expected_columns.push_back(expected6.release());
auto result = cudf::strings::contiguous_rsplit_record(strings_view);
EXPECT_TRUE(result.column_views.size() == expected_columns.size());
for (size_t i = 4; i < 5; i++) {
cudf::test::expect_columns_equal(result.column_views[i], *expected_columns[i]);
}
}
TEST_F(StringsSplitTest, ContiguousRSplitRecordWhitespaceWithMaxSplit)
{
std::vector<const char*> h_strings{ " héllo Asher ", nullptr, " a_bc_déf ", "", " a\tb ", " a\r bbb c" };
cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view( strings );
std::vector<const char*> h_expected1{ " héllo", "Asher" };
cudf::test::strings_column_wrapper expected1(h_expected1.begin(), h_expected1.end());
std::vector<const char*> h_expected2{};
cudf::test::strings_column_wrapper expected2(h_expected2.begin(), h_expected2.end());
std::vector<const char*> h_expected3{ "a_bc_déf" };
cudf::test::strings_column_wrapper expected3(h_expected3.begin(), h_expected3.end());
std::vector<const char*> h_expected4{};
cudf::test::strings_column_wrapper expected4(h_expected4.begin(), h_expected4.end());
std::vector<const char*> h_expected5{ " a", "b" };
cudf::test::strings_column_wrapper expected5(h_expected5.begin(), h_expected5.end());
std::vector<const char*> h_expected6{ " a\r bbb", "c" };
cudf::test::strings_column_wrapper expected6(h_expected6.begin(), h_expected6.end());
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
expected_columns.push_back(expected4.release());
expected_columns.push_back(expected5.release());
expected_columns.push_back(expected6.release());
auto result = cudf::strings::contiguous_rsplit_record(strings_view, cudf::string_scalar(""), 1);
EXPECT_TRUE(result.column_views.size() == expected_columns.size());
for (size_t i = 4; i < 5; i++) {
cudf::test::expect_columns_equal(result.column_views[i], *expected_columns[i]);
}
}
TEST_F(StringsSplitTest, ContiguousSplitRecordZeroSizeStringsColumns)
{
cudf::column_view zero_size_strings_column(cudf::data_type{cudf::STRING}, 0, nullptr, nullptr, 0);
auto split_record_result = cudf::strings::contiguous_split_record(zero_size_strings_column);
EXPECT_TRUE(split_record_result.column_views.size() == 0);
auto rsplit_record_result = cudf::strings::contiguous_rsplit_record(zero_size_strings_column);
EXPECT_TRUE(rsplit_record_result.column_views.size() == 0);
}
TEST_F(StringsSplitTest, Partition)
{
std::vector<const char*> h_strings{ "héllo", nullptr, "a_bc_déf", "a__bc", "_ab_cd", "ab_cd_", "", " a b " };
std::vector<const char*> h_expecteds{ "héllo", nullptr, "a", "a", "", "ab", "", " a b ",
"", nullptr, "_", "_", "_", "_", "", "",
"", nullptr, "bc_déf", "_bc", "ab_cd", "cd_", "", "" };
cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view( strings );
auto results = cudf::strings::partition(strings_view, cudf::string_scalar("_"));
EXPECT_TRUE( results->num_columns()==3 );
auto exp_itr = h_expecteds.begin();
cudf::test::strings_column_wrapper expected1( exp_itr, exp_itr + h_strings.size(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected2( exp_itr, exp_itr + h_strings.size(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected3( exp_itr, exp_itr + h_strings.size(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
auto expected = std::make_unique<cudf::experimental::table>(std::move(expected_columns));
cudf::test::expect_tables_equal(*results,*expected);
}
TEST_F(StringsSplitTest, PartitionWhitespace)
{
std::vector<const char*> h_strings{ "héllo", nullptr, "a bc déf", "a bc", " ab cd", "ab cd ", "", "a_b" };
std::vector<const char*> h_expecteds{ "héllo", nullptr, "a", "a", "", "ab", "", "a_b",
"", nullptr, " ", " ", " ", " ", "", "",
"", nullptr, "bc déf", " bc", "ab cd", "cd ", "", "" };
cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view( strings );
auto results = cudf::strings::partition(strings_view);
EXPECT_TRUE( results->num_columns()==3 );
auto exp_itr = h_expecteds.begin();
cudf::test::strings_column_wrapper expected1( exp_itr, exp_itr + h_strings.size(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected2( exp_itr, exp_itr + h_strings.size(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected3( exp_itr, exp_itr + h_strings.size(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
auto expected = std::make_unique<cudf::experimental::table>(std::move(expected_columns));
cudf::test::expect_tables_equal(*results,*expected);
}
TEST_F(StringsSplitTest, RPartition)
{
std::vector<const char*> h_strings{ "héllo", nullptr, "a_bc_déf", "a__bc", "_ab_cd", "ab_cd_", "", " a b " };
std::vector<const char*> h_expecteds{ "", nullptr, "a_bc", "a_", "_ab", "ab_cd", "", "",
"", nullptr, "_", "_", "_", "_", "", "",
"héllo", nullptr, "déf", "bc", "cd", "", "", " a b " };
cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view( strings );
auto results = cudf::strings::rpartition(strings_view, cudf::string_scalar("_"));
EXPECT_TRUE( results->num_columns()==3 );
auto exp_itr = h_expecteds.begin();
cudf::test::strings_column_wrapper expected1( exp_itr, exp_itr + h_strings.size(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected2( exp_itr, exp_itr + h_strings.size(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected3( exp_itr, exp_itr + h_strings.size(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
auto expected = std::make_unique<cudf::experimental::table>(std::move(expected_columns));
cudf::test::expect_tables_equal(*results,*expected);
}
TEST_F(StringsSplitTest, RPartitionWhitespace)
{
std::vector<const char*> h_strings{ "héllo", nullptr, "a bc déf", "a bc", " ab cd", "ab cd ", "", "a_b" };
std::vector<const char*> h_expecteds{ "", nullptr, "a bc", "a ", " ab", "ab cd", "", "",
"", nullptr, " ", " ", " ", " ", "", "",
"héllo", nullptr, "déf", "bc", "cd", "", "", "a_b" };
cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
cudf::strings_column_view strings_view( strings );
auto results = cudf::strings::rpartition(strings_view);
EXPECT_TRUE( results->num_columns()==3 );
auto exp_itr = h_expecteds.begin();
cudf::test::strings_column_wrapper expected1( exp_itr, exp_itr + h_strings.size(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected2( exp_itr, exp_itr + h_strings.size(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected3( exp_itr, exp_itr + h_strings.size(),
thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
auto expected = std::make_unique<cudf::experimental::table>(std::move(expected_columns));
cudf::test::expect_tables_equal(*results,*expected);
}
TEST_F(StringsSplitTest, PartitionZeroSizeStringsColumns)
{
cudf::column_view zero_size_strings_column( cudf::data_type{cudf::STRING}, 0, nullptr, nullptr, 0);
auto results = cudf::strings::partition(zero_size_strings_column);
EXPECT_TRUE( results->num_columns()==0 );
results = cudf::strings::rpartition(zero_size_strings_column);
EXPECT_TRUE( results->num_columns()==0 );
}
TEST_F(StringsSplitTest, InvalidParameter)
{
std::vector<const char*> h_strings{ "string left intentionally blank" };
cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end() );
auto strings_view = cudf::strings_column_view(strings);
EXPECT_THROW( cudf::strings::split(strings_view,cudf::string_scalar("",false)), cudf::logic_error);
EXPECT_THROW( cudf::strings::rsplit(strings_view,cudf::string_scalar("",false)), cudf::logic_error);
EXPECT_THROW( cudf::strings::partition(strings_view,cudf::string_scalar("",false)), cudf::logic_error);
EXPECT_THROW( cudf::strings::rpartition(strings_view,cudf::string_scalar("",false)), cudf::logic_error);
}
| 56.146141 | 138 | 0.692539 | [
"vector"
] |
9066404fd9455e4c982a686c8803da6f66f4c5ed | 6,141 | cpp | C++ | clustering/compute_clustering.cpp | tibaes/motion | f612cdfc8b9b13d628937e65ff56f69c23404fee | [
"MIT"
] | 1 | 2017-08-21T06:40:39.000Z | 2017-08-21T06:40:39.000Z | clustering/compute_clustering.cpp | tibaes/motion | f612cdfc8b9b13d628937e65ff56f69c23404fee | [
"MIT"
] | null | null | null | clustering/compute_clustering.cpp | tibaes/motion | f612cdfc8b9b13d628937e65ff56f69c23404fee | [
"MIT"
] | null | null | null | /* Compute Clustering using K-Means algorithm and then normalize components
* Input: [rows cols] [x y u v]+
* Output: Gaussian Mixtures YML
*
* Rafael H Tibaes [ra.fael.nl]
* IMAGO Research Group
*/
#include <cv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/ml/ml.hpp>
#include <cmath>
#define NDIM 4
typedef unsigned int uint;
typedef struct Component {
cv::Mat mean, cov;
float weight;
} Component;
cv::Mat getSampleFlow(const char* filename)
{
int rows, cols;
FILE* input = fopen(filename, "r");
fread(&rows, sizeof(int), 1, input);
fread(&cols, sizeof(int), 1, input);
cv::Mat sample = cv::Mat::zeros(rows * cols, NDIM, CV_32F);
int x, y, sid = 0;
float u, v;
while (!feof(input))
{
fread(&x, sizeof(int), 1, input);
fread(&y, sizeof(int), 1, input);
fread(&u, sizeof(float), 1, input);
fread(&v, sizeof(float), 1, input);
float *ps = sample.ptr<float>(sid++);
ps[0] = (float)x;
ps[1] = (float)y;
ps[2] = (float)(u > 0.001)? u: 0.0;
ps[3] = (float)(v > 0.001)? v: 0.0;
}
return sample;
}
void saveMixtures(std::vector<Component>& vcomp, cv::FileStorage& output)
{
output << "GMM" << "[";
for (int i = 0; i < vcomp.size(); ++i) {
output << "{"
<< "mean" << vcomp[i].mean
<< "cov" << vcomp[i].cov
<< "weight" << vcomp[i].weight
<< "}";
}
output << "]";
}
void convFlowFeatures(cv::Mat samples, cv::Mat& conv_samples,
cv::Mat& conv_samples_inv)
{
conv_samples = cv::Mat::zeros(samples.size(), CV_32F);
conv_samples_inv = cv::Mat::zeros(samples.size(), CV_32F);
// Angular reference
cv::Mat mean, cov;
calcCovarMatrix(samples, cov, mean, CV_COVAR_NORMAL | CV_COVAR_ROWS, CV_32F);
cv::Mat cov_xy = cv::Mat::zeros(2, 2, CV_32F);
cov_xy.at<float>(0,0) = cov.at<float>(0,0);
cov_xy.at<float>(0,1) = cov.at<float>(0,1);
cov_xy.at<float>(1,0) = cov.at<float>(1,0);
cov_xy.at<float>(1,1) = cov.at<float>(1,1);
cv::Mat eigenvalues_xy, eigenvectors_xy;
cv::eigen(cov_xy, true, eigenvalues_xy, eigenvectors_xy);
float angle_ref = atan2f(eigenvectors_xy.at<float>(1,0),
eigenvectors_xy.at<float>(0,0)) / M_PI;
// Convert angle_xy
float mean_x = mean.at<float>(0,0);
float mean_y = mean.at<float>(0,1);
for (uint sid = 0; sid < samples.rows; ++sid) {
float x = samples.at<float>(sid,0);
float y = samples.at<float>(sid,1);
float angle_xy = atan2f(y - mean_y, x - mean_x) / M_PI;
conv_samples.at<float>(sid,0) = angle_xy - angle_ref;
conv_samples_inv.at<float>(sid,0) = angle_xy + angle_ref;
}
// Convert intensity_xy
std::vector<float> dist_xy(samples.rows);
float max_xy = 0.0f;
for (uint sid = 0; sid < samples.rows; ++sid) {
float x = samples.at<float>(sid,0);
float y = samples.at<float>(sid,1);
float dx = x - mean_x;
float dy = y - mean_y;
float dist = sqrtf(dx*dx + dy*dy);
dist_xy[sid] = dist;
if (dist > max_xy) max_xy = dist;
}
for (uint sid = 0; sid < samples.rows; ++sid) {
float norm_dist = dist_xy[sid] / max_xy;
conv_samples.at<float>(sid,1) = norm_dist;
conv_samples_inv.at<float>(sid,1) = norm_dist;
}
// convert angle_uv
for (uint sid = 0; sid < samples.rows; ++sid) {
float u = samples.at<float>(sid,2);
float v = samples.at<float>(sid,3);
float angle_uv = atan2f(v, u) / M_PI;
conv_samples.at<float>(sid,2) = angle_uv - angle_ref;
conv_samples_inv.at<float>(sid,2) = angle_uv + angle_ref;
}
// convert intensity_uv
std::vector<float> dist_uv(samples.rows);
float max_uv = 0.0f;
for (uint sid = 0; sid < samples.rows; ++sid) {
float u = samples.at<float>(sid,2);
float v = samples.at<float>(sid,3);
float dist = sqrtf(u*u + v*v);
dist_uv[sid] = dist;
if (dist > max_uv) max_uv = dist;
}
for (uint sid = 0; sid < samples.rows; ++sid) {
float norm_dist = dist_uv[sid] / max_uv;
conv_samples.at<float>(sid,3) = norm_dist;
conv_samples_inv.at<float>(sid,3) = norm_dist;
}
}
std::vector<Component> components(int k, cv::Mat samples)
{
// K-Means clustering over motion features
cv::Mat labels, centers;
kmeans(samples, k, labels, cv::TermCriteria(cv::TermCriteria::EPS
+ cv::TermCriteria::COUNT, 10, 1.0), 3, cv::KMEANS_PP_CENTERS, centers);
// Split samples according the cluster label
std::vector<cv::Mat> clusterSamples;
for (int kid = 0; kid < k; ++kid) {
clusterSamples.push_back(cv::Mat::zeros(0, NDIM, CV_32F));
}
for (uint sid = 0; sid < samples.rows; ++sid) {
clusterSamples[labels.at<int>(sid)].push_back(samples.row(sid));
}
// Statistical measures, i.e. motion components
std::vector<Component> vcomp;
for (int kid = 0; kid < k; ++kid) {
// TODO some component left behind modifies the weight of the others
Component c;
c.weight = (float)clusterSamples[kid].rows / (float)samples.rows;
calcCovarMatrix(clusterSamples[kid], c.cov, c.mean,
CV_COVAR_NORMAL | CV_COVAR_ROWS, CV_32F);
// float ixy = fabsf(c.mean.at<float>(1));
// float iuv = fabsf(c.mean.at<float>(3));
if (/* ixy + iuv > 0.001f && */ fabsf(determinant(c.cov)) > 0.001f) {
vcomp.push_back(c);
}
}
return vcomp;
}
int main(int argc, char** argv)
{
if (argc < 4) {
printf("Use %s <K-Clusters> <output.yml> <output_inv.yml> [input.flo]+\n",
argv[0]);
return -1;
}
int k = atoi(argv[1]);
cv::FileStorage output(argv[2], cv::FileStorage::WRITE);
cv::FileStorage output_inv(argv[3], cv::FileStorage::WRITE);
// read flow vectors
cv::Mat samples = cv::Mat::zeros(0, NDIM, CV_32F);
for (int frameid = 4; frameid < argc; ++frameid) {
cv::Mat s = getSampleFlow(argv[frameid]);
samples.push_back(s);
}
// convert flow vectors (invariance)
cv::Mat conv_samples, conv_samples_inv;
convFlowFeatures(samples, conv_samples, conv_samples_inv);
// compute models
std::vector<Component> vcomp = components(k, conv_samples);
saveMixtures(vcomp, output);
// compute inverted models
std::vector<Component> vcomp_inv = components(k, conv_samples_inv);
saveMixtures(vcomp_inv, output_inv);
return 0;
}
| 27.913636 | 79 | 0.632307 | [
"vector"
] |
9067352e154d6c757d1874755587bf7376ca4a12 | 12,055 | cpp | C++ | Libs/PlatformAux.cpp | dns/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 3 | 2020-04-11T13:00:31.000Z | 2020-12-07T03:19:10.000Z | Libs/PlatformAux.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | null | null | null | Libs/PlatformAux.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 1 | 2020-04-11T13:00:04.000Z | 2020-04-11T13:00:04.000Z | /*
Cafu Engine, http://www.cafu.de/
Copyright (c) Carsten Fuchs and other contributors.
This project is licensed under the terms of the MIT license.
*/
#include "PlatformAux.hpp"
#include "Templates/Array.hpp"
#include "ConsoleCommands/Console.hpp"
#include "FileSys/FileMan.hpp"
#include "MaterialSystem/Renderer.hpp"
#include "SoundSystem/SoundSys.hpp"
#include <cassert>
#ifdef _WIN32
#elif __linux__
#include <cstdio>
#include <cstring>
#include <dirent.h>
#include <dlfcn.h>
#define __stdcall
#define GetProcAddress dlsym
#define FreeLibrary dlclose
#endif
std::vector<std::string> PlatformAux::GetDirectory(const std::string& Name, char Filter)
{
std::vector<std::string> Items;
if (Name == "")
return Items;
#ifdef _WIN32
WIN32_FIND_DATA FindFileData;
HANDLE FindHandle = FindFirstFile((Name + "\\*").c_str(), &FindFileData);
if (FindHandle == INVALID_HANDLE_VALUE)
return Items;
do
{
if (strcmp(FindFileData.cFileName, "." ) == 0) continue;
if (strcmp(FindFileData.cFileName, "..") == 0) continue;
if (Filter)
{
const bool IsDir = (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
if (Filter == 'f' && IsDir) continue;
if (Filter == 'd' && !IsDir) continue;
}
Items.push_back(FindFileData.cFileName);
}
while (FindNextFile(FindHandle, &FindFileData));
if (GetLastError() != ERROR_NO_MORE_FILES)
Console->Warning("Error in GetDirectory() while enumerating directory entries.\n");
FindClose(FindHandle);
#else
DIR* Dir = opendir(Name.c_str());
if (!Dir)
return Items;
for (dirent* DirEnt = readdir(Dir); DirEnt; DirEnt = readdir(Dir))
{
if (strcmp(DirEnt->d_name, "." ) == 0) continue;
if (strcmp(DirEnt->d_name, "..") == 0) continue;
if (Filter)
{
DIR* TempDir = opendir((Name + "/" + DirEnt->d_name).c_str());
const bool IsDir = (TempDir != NULL);
if (TempDir)
closedir(TempDir);
if (Filter == 'f' && IsDir) continue;
if (Filter == 'd' && !IsDir) continue;
}
// For portability, only the 'd_name' member of a 'dirent' may be accessed.
Items.push_back(DirEnt->d_name);
}
closedir(Dir);
#endif
return Items;
}
static void GetDLLs(const std::string& Path, const std::string& Prefix, ArrayT<std::string>& FoundDLLs)
{
const std::vector<std::string> Items = PlatformAux::GetDirectory(Path);
#if defined(_WIN32)
const std::string LibPrefix = Prefix;
const std::string Suffix=".dll";
#else
const std::string LibPrefix = "lib" + Prefix;
const std::string Suffix =".so";
#endif
for (size_t i = 0; i < Items.size(); i++)
{
const std::string& DLLName = Items[i];
// If DLLName doesn't begin with LibPrefix, continue.
if (std::string(DLLName, 0, LibPrefix.length()) != LibPrefix) continue;
// If DLLName doesn't end with Suffix, continue.
if (DLLName.length() < Suffix.length()) continue;
if (std::string(DLLName, DLLName.length() - Suffix.length()) != Suffix) continue;
FoundDLLs.PushBack(Path + "/" + DLLName);
}
}
MatSys::RendererI* PlatformAux::GetRenderer(const std::string& DLLName, HMODULE& OutRendererDLL)
{
#ifdef _WIN32
OutRendererDLL=LoadLibrary(DLLName.c_str());
#else
// Note that RTLD_GLOBAL must *not* be passed-in here, or else we get in trouble with subsequently loaded libraries.
// (E.g. it causes dlsym(OutRendererDLL, "GetRenderer") to return identical results for different OutRendererDLLs.)
// Please refer to the man page of dlopen for more details.
OutRendererDLL=dlopen(DLLName.c_str(), RTLD_NOW);
if (!OutRendererDLL) Console->Print(std::string(dlerror()) + ", ");
#endif
if (!OutRendererDLL) { Console->Print("FAILED - could not load the library at "+DLLName+".\n"); return NULL; }
typedef MatSys::RendererI* (__stdcall *GetRendererT)(cf::ConsoleI* Console_, cf::FileSys::FileManI* FileMan_);
#if defined(_WIN32) && !defined(_WIN64)
GetRendererT GetRendererFunc=(GetRendererT)GetProcAddress(OutRendererDLL, "_GetRenderer@8");
#else
GetRendererT GetRendererFunc=(GetRendererT)GetProcAddress(OutRendererDLL, "GetRenderer");
#endif
if (!GetRendererFunc) { Console->Print("FAILED - could not get the address of the GetRenderer() function.\n"); FreeLibrary(OutRendererDLL); return NULL; }
// When we get here, the console and the file man must already have been initialized.
assert(Console!=NULL);
assert(cf::FileSys::FileMan!=NULL);
MatSys::RendererI* Renderer=GetRendererFunc(Console, cf::FileSys::FileMan);
if (!Renderer) { Console->Print("FAILED - could not get the renderer.\n"); FreeLibrary(OutRendererDLL); return NULL; }
if (!Renderer->IsSupported()) { Console->Print("FAILED - renderer says it's not supported.\n"); FreeLibrary(OutRendererDLL); return NULL; }
return Renderer;
}
MatSys::RendererI* PlatformAux::GetBestRenderer(HMODULE& OutRendererDLL)
{
#ifdef SCONS_BUILD_DIR
#define QUOTE(str) QUOTE_HELPER(str)
#define QUOTE_HELPER(str) #str
std::string Path=std::string("Libs/")+QUOTE(SCONS_BUILD_DIR)+"/MaterialSystem";
#undef QUOTE
#undef QUOTE_HELPER
#else
std::string Path="Renderers";
#endif
ArrayT<std::string> DLLNames;
Console->Print("\n");
Console->Print("Scanning cwd for all available renderers...\n");
GetDLLs(".", "Renderer", DLLNames);
if (DLLNames.Size()==0)
{
Console->Print("Scanning "+Path+" for all available renderers...\n");
GetDLLs(Path, "Renderer", DLLNames);
}
unsigned long BestDLLIndex= 0; // Index into DLLNames.
int BestPrefNr =-1; // The preference number of the renderer related to BestDLLIndex.
for (unsigned long DLLNr=0; DLLNr<DLLNames.Size(); DLLNr++)
{
Console->Print(DLLNames[DLLNr]+" ... ");
HMODULE RendererDLL;
MatSys::RendererI* Renderer=GetRenderer(DLLNames[DLLNr], RendererDLL);
if (!Renderer) continue;
int PrefNr=Renderer->GetPreferenceNr();
Renderer=NULL;
FreeLibrary(RendererDLL);
if (PrefNr<10)
{
// We don't want the Null renderer to be possibly selected for client rendering
// (which can happen in the presence of other errors).
// It would only confuse and worry users to sit in front of a black, apparently frozen screen.
Console->Print(cf::va("SUCCESS - but excluded from auto-selection (Pref# %i).\n", PrefNr));
continue;
}
if (PrefNr>BestPrefNr)
{
Console->Print(cf::va("SUCCESS - %s renderer (Pref# %i).\n", BestPrefNr<0 ? "first supported" : "higher preference", PrefNr));
BestDLLIndex=DLLNr;
BestPrefNr =PrefNr;
}
else Console->Print(cf::va("SUCCESS - but no higher preference (Pref# %i).\n", PrefNr));
}
if (BestPrefNr==-1)
{
Console->Print("No renderer qualified.\n");
return NULL;
}
Console->Print("Reloading previously auto-selected renderer "+DLLNames[BestDLLIndex]+" ...\n");
return GetRenderer(DLLNames[BestDLLIndex], OutRendererDLL);
}
MatSys::TextureMapManagerI* PlatformAux::GetTextureMapManager(HMODULE RendererDLL)
{
typedef MatSys::TextureMapManagerI* (__stdcall *GetTMMT)();
#if defined(_WIN32) && !defined(_WIN64)
GetTMMT GetTMM=(GetTMMT)GetProcAddress(RendererDLL, "_GetTextureMapManager@0");
#else
GetTMMT GetTMM=(GetTMMT)GetProcAddress(RendererDLL, "GetTextureMapManager");
#endif
if (!GetTMM) { Console->Print("FAILED - could not get the address of the GetTextureMapManager() function.\n"); return NULL; }
return GetTMM();
}
SoundSysI* PlatformAux::GetSoundSys(const std::string& DLLName, HMODULE& OutSoundSysDLL)
{
#ifdef _WIN32
OutSoundSysDLL=LoadLibrary(DLLName.c_str());
#else
// Note that RTLD_GLOBAL must *not* be passed-in here, or else we get in trouble with subsequently loaded libraries.
// (E.g. it causes dlsym(OutSoundSysDLL, "GetSoundSys") to return identical results for different OutSoundSysDLLs.)
// Please refer to the man page of dlopen for more details.
OutSoundSysDLL=dlopen(DLLName.c_str(), RTLD_NOW);
if (!OutSoundSysDLL) Console->Print(std::string(dlerror()) + ", ");
#endif
if (!OutSoundSysDLL) { Console->Print("FAILED - could not load the library at "+DLLName+".\n"); return NULL; }
typedef SoundSysI* (__stdcall *GetSoundSys)(cf::ConsoleI* Console_, cf::FileSys::FileManI* FileMan_);
#if defined(_WIN32) && !defined(_WIN64)
GetSoundSys GetSoundSysFunc=(GetSoundSys)GetProcAddress(OutSoundSysDLL, "_GetSoundSys@8");
#else
GetSoundSys GetSoundSysFunc=(GetSoundSys)GetProcAddress(OutSoundSysDLL, "GetSoundSys");
#endif
if (!GetSoundSysFunc) { Console->Print("FAILED - could not get the address of the GetSoundSys() function.\n"); FreeLibrary(OutSoundSysDLL); return NULL; }
// When we get here, the console and the file man must already have been initialized.
assert(Console!=NULL);
assert(cf::FileSys::FileMan!=NULL);
SoundSysI* SoundSys=GetSoundSysFunc(Console, cf::FileSys::FileMan);
if (!SoundSys) { Console->Print("FAILED - could not get the SoundSys.\n"); FreeLibrary(OutSoundSysDLL); return NULL; }
if (!SoundSys->IsSupported()) { Console->Print("FAILED - SoundSys says it's not supported.\n"); FreeLibrary(OutSoundSysDLL); return NULL; }
return SoundSys;
}
SoundSysI* PlatformAux::GetBestSoundSys(HMODULE& OutSoundSysDLL)
{
#ifdef SCONS_BUILD_DIR
#define QUOTE(str) QUOTE_HELPER(str)
#define QUOTE_HELPER(str) #str
std::string Path=std::string("Libs/")+QUOTE(SCONS_BUILD_DIR)+"/SoundSystem";
#undef QUOTE
#undef QUOTE_HELPER
#else
std::string Path="SoundSystem";
#endif
ArrayT<std::string> DLLNames;
Console->Print("\n");
Console->Print("Scanning cwd for all available sound systems...\n");
GetDLLs(".", "SoundSys", DLLNames);
if (DLLNames.Size()==0)
{
Console->Print("Scanning "+Path+" for all available sound systems...\n");
GetDLLs(Path, "SoundSys", DLLNames);
}
unsigned long BestDLLIndex= 0; // Index into DLLNames.
int BestPrefNr =-1; // The preference number of the sound system related to BestDLLIndex.
for (unsigned long DLLNr=0; DLLNr<DLLNames.Size(); DLLNr++)
{
Console->Print(DLLNames[DLLNr]+" ... ");
HMODULE SoundSysDLL;
SoundSysI* SoundSys=GetSoundSys(DLLNames[DLLNr], SoundSysDLL);
if (!SoundSys) continue;
int PrefNr=SoundSys->GetPreferenceNr();
SoundSys=NULL;
FreeLibrary(SoundSysDLL);
if (PrefNr<10)
{
// We don't want the Null sound system to be possibly selected for client
// (which can happen in the presence of other errors).
// It would only confuse and worry users to sit in front of a black, apparently frozen screen.
Console->Print(cf::va("SUCCESS - but excluded from auto-selection (Pref# %i).\n", PrefNr));
continue;
}
if (PrefNr>BestPrefNr)
{
Console->Print(cf::va("SUCCESS - %s sound system (Pref# %i).\n", BestPrefNr<0 ? "first supported" : "higher preference", PrefNr));
BestDLLIndex=DLLNr;
BestPrefNr =PrefNr;
}
else Console->Print(cf::va("SUCCESS - but no higher preference (Pref# %i).\n", PrefNr));
}
if (BestPrefNr==-1)
{
Console->Print("No sound system qualified.\n");
return NULL;
}
Console->Print("Reloading previously auto-selected sound system "+DLLNames[BestDLLIndex]+" ...\n");
return GetSoundSys(DLLNames[BestDLLIndex], OutSoundSysDLL);
}
| 33.579387 | 158 | 0.647947 | [
"vector"
] |
9067837603756c7363b4332503fd292120a48aca | 6,462 | cpp | C++ | src/endpoints/authentication/sig_auth.cpp | Julian-Sequeira/CCF | 363a63b43d9c80d7325901594a0f6465446ede63 | [
"Apache-2.0"
] | null | null | null | src/endpoints/authentication/sig_auth.cpp | Julian-Sequeira/CCF | 363a63b43d9c80d7325901594a0f6465446ede63 | [
"Apache-2.0"
] | null | null | null | src/endpoints/authentication/sig_auth.cpp | Julian-Sequeira/CCF | 363a63b43d9c80d7325901594a0f6465446ede63 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#include "ccf/endpoints/authentication/sig_auth.h"
#include "ccf/crypto/verifier.h"
#include "ccf/rpc_context.h"
#include "ccf/service/tables/members.h"
#include "ccf/service/tables/users.h"
#include "ds/lru.h"
#include "http/http_sig.h"
namespace ccf
{
static std::optional<SignedReq> parse_signed_request(
const std::shared_ptr<enclave::RpcContext>& ctx)
{
return http::HttpSignatureVerifier::parse(
ctx->get_request_verb().c_str(),
ctx->get_request_url(),
ctx->get_request_headers(),
ctx->get_request_body());
}
struct VerifierCache
{
static constexpr size_t DEFAULT_MAX_VERIFIERS = 50;
std::mutex verifiers_lock;
LRU<crypto::Pem, crypto::VerifierPtr> verifiers;
VerifierCache(size_t max_verifiers = DEFAULT_MAX_VERIFIERS) :
verifiers(max_verifiers)
{}
crypto::VerifierPtr get_verifier(const crypto::Pem& pem)
{
std::lock_guard<std::mutex> guard(verifiers_lock);
crypto::VerifierPtr verifier = nullptr;
auto it = verifiers.find(pem);
if (it == verifiers.end())
{
it = verifiers.insert(pem, crypto::make_verifier(pem));
}
return it->second;
}
};
UserSignatureAuthnPolicy::UserSignatureAuthnPolicy() :
verifiers(std::make_unique<VerifierCache>())
{}
UserSignatureAuthnPolicy::~UserSignatureAuthnPolicy() = default;
std::unique_ptr<AuthnIdentity> UserSignatureAuthnPolicy::authenticate(
kv::ReadOnlyTx& tx,
const std::shared_ptr<enclave::RpcContext>& ctx,
std::string& error_reason)
{
std::optional<SignedReq> signed_request = std::nullopt;
try
{
signed_request = parse_signed_request(ctx);
}
catch (const std::exception& e)
{
error_reason = e.what();
return nullptr;
}
if (signed_request.has_value())
{
UserCerts users_certs_table(Tables::USER_CERTS);
auto users_certs = tx.ro(users_certs_table);
auto user_cert = users_certs->get(signed_request->key_id);
if (user_cert.has_value())
{
auto verifier = verifiers->get_verifier(user_cert.value());
if (verifier->verify(
signed_request->req, signed_request->sig, signed_request->md))
{
auto identity = std::make_unique<UserSignatureAuthnIdentity>();
identity->user_id = signed_request->key_id;
identity->user_cert = user_cert.value();
identity->signed_request = signed_request.value();
return identity;
}
else
{
error_reason = "Signature is invalid";
}
}
else
{
error_reason = "Signer is not a known user";
}
}
else
{
error_reason = "Missing signature";
}
return nullptr;
}
void UserSignatureAuthnPolicy::set_unauthenticated_error(
std::shared_ptr<enclave::RpcContext>& ctx, std::string&& error_reason)
{
ctx->set_error(
HTTP_STATUS_UNAUTHORIZED,
ccf::errors::InvalidAuthenticationInfo,
std::move(error_reason));
ctx->set_response_header(
http::headers::WWW_AUTHENTICATE,
fmt::format(
"Signature realm=\"Signed request access\", "
"headers=\"{}\"",
fmt::join(http::required_signature_headers, " ")));
}
const OpenAPISecuritySchema UserSignatureAuthnPolicy::security_schema =
std::make_pair(
UserSignatureAuthnPolicy::SECURITY_SCHEME_NAME,
nlohmann::json{
{"type", "http"},
{"scheme", "signature"},
{"description",
"Request must be signed according to the HTTP Signature scheme. The "
"signer must be a user identity registered with this service."}});
MemberSignatureAuthnPolicy::MemberSignatureAuthnPolicy() :
verifiers(std::make_unique<VerifierCache>())
{}
MemberSignatureAuthnPolicy::~MemberSignatureAuthnPolicy() = default;
std::unique_ptr<AuthnIdentity> MemberSignatureAuthnPolicy::authenticate(
kv::ReadOnlyTx& tx,
const std::shared_ptr<enclave::RpcContext>& ctx,
std::string& error_reason)
{
std::optional<SignedReq> signed_request = std::nullopt;
try
{
signed_request = parse_signed_request(ctx);
}
catch (const std::exception& e)
{
error_reason = e.what();
return nullptr;
}
if (signed_request.has_value())
{
MemberCerts members_certs_table(Tables::MEMBER_CERTS);
auto member_certs = tx.ro(members_certs_table);
auto member_cert = member_certs->get(signed_request->key_id);
if (member_cert.has_value())
{
std::vector<uint8_t> digest;
auto verifier = verifiers->get_verifier(member_cert.value());
if (verifier->verify(
signed_request->req,
signed_request->sig,
signed_request->md,
digest))
{
auto identity = std::make_unique<MemberSignatureAuthnIdentity>();
identity->member_id = signed_request->key_id;
identity->member_cert = member_cert.value();
identity->signed_request = signed_request.value();
identity->request_digest = std::move(digest);
return identity;
}
else
{
error_reason = "Signature is invalid";
}
}
else
{
error_reason = "Signer is not a known member";
}
}
else
{
error_reason = "Missing signature";
}
return nullptr;
}
void MemberSignatureAuthnPolicy::set_unauthenticated_error(
std::shared_ptr<enclave::RpcContext>& ctx, std::string&& error_reason)
{
ctx->set_error(
HTTP_STATUS_UNAUTHORIZED,
ccf::errors::InvalidAuthenticationInfo,
std::move(error_reason));
ctx->set_response_header(
http::headers::WWW_AUTHENTICATE,
fmt::format(
"Signature realm=\"Signed request access\", "
"headers=\"{}\"",
fmt::join(http::required_signature_headers, " ")));
}
const OpenAPISecuritySchema MemberSignatureAuthnPolicy::security_schema =
std::make_pair(
MemberSignatureAuthnPolicy::SECURITY_SCHEME_NAME,
nlohmann::json{
{"type", "http"},
{"scheme", "signature"},
{"description",
"Request must be signed according to the HTTP Signature scheme. The "
"signer must be a member identity registered with this service."}});
}
| 28.977578 | 78 | 0.644383 | [
"vector"
] |
9068af08047836c1034e5a814dfd4e5c989725e7 | 16,040 | cpp | C++ | Engine/Plugins/Editor/BlueprintMaterialTextureNodes/Source/BlueprintMaterialTextureNodes/Private/BlueprintMaterialTextureNodesBPLibrary.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Plugins/Editor/BlueprintMaterialTextureNodes/Source/BlueprintMaterialTextureNodes/Private/BlueprintMaterialTextureNodesBPLibrary.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Plugins/Editor/BlueprintMaterialTextureNodes/Source/BlueprintMaterialTextureNodes/Private/BlueprintMaterialTextureNodesBPLibrary.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "BlueprintMaterialTextureNodesBPLibrary.h"
#include "BlueprintMaterialTextureNodes.h"
#include "CoreMinimal.h"
//RHI gives access to MaxShaderPlatform and FeatureLevel (i.e. GMaxRHIShaderPlatform)
#include "RHI.h"
//includes for asset creation
#include "AssetRegistryModule.h"
#include "AssetToolsModule.h"
#include "IAssetTools.h"
#include "IContentBrowserSingleton.h"
#include "PackageTools.h"
#include "Editor.h"
#include "Factories/MaterialInstanceConstantFactoryNew.h"
#include "MessageLog.h"
#include "Factories/TextureFactory.h"
#include "Factories/Factory.h"
//Material and texture includes
#include "Engine/TextureRenderTarget2D.h"
#include "Materials/MaterialInstance.h"
#include "Materials/MaterialInstanceConstant.h"
#include "MaterialShared.h"
#define LOCTEXT_NAMESPACE "BlueprintMaterialTextureLibrary"
UBlueprintMaterialTextureNodesBPLibrary::UBlueprintMaterialTextureNodesBPLibrary(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
FLinearColor UBlueprintMaterialTextureNodesBPLibrary::Texture2D_SampleUV_EditorOnly(UTexture2D* Texture, FVector2D UV, int Mip)
{
#if WITH_EDITOR
if (Texture != nullptr)
{
int NumMips = Texture->GetNumMips();
Mip = FMath::Min(NumMips, Mip);
FTexture2DMipMap* CurMip = &Texture->PlatformData->Mips[Mip];
FByteBulkData* ImageData = &CurMip->BulkData;
int32 MipWidth = CurMip->SizeX;
int32 MipHeight = CurMip->SizeY;
int32 X = FMath::Clamp(int(UV.X * MipWidth), 0, MipWidth - 1);
int32 Y = FMath::Clamp(int(UV.Y * MipHeight), 0, MipWidth - 1);
if (ImageData->IsBulkDataLoaded() && ImageData->GetBulkDataSize() > 0)
{
int32 texelindex = FMath::Min(MipWidth * MipHeight, Y * MipWidth + X);
if (Texture->GetPixelFormat() == PF_B8G8R8A8)
{
FColor* MipData = static_cast<FColor*>(ImageData->Lock(LOCK_READ_ONLY));
FColor Texel = MipData[texelindex];
ImageData->Unlock();
if (Texture->SRGB)
return Texel;
else
{
return FLinearColor(float(Texel.R), float(Texel.G), float(Texel.B), float(Texel.A)) / 255.0f;
}
}
else if (Texture->GetPixelFormat() == PF_FloatRGBA)
{
FFloat16Color* MipData = static_cast<FFloat16Color*>(ImageData->Lock(LOCK_READ_ONLY));
FFloat16Color Texel = MipData[texelindex];
ImageData->Unlock();
return FLinearColor(float(Texel.R), float(Texel.G), float(Texel.B), float(Texel.A));
}
}
//Read Texture Source if platform data is unavailable
else
{
FTextureSource& TextureSource = Texture->Source;
TArray<uint8> SourceData;
Texture->Source.GetMipData(SourceData, Mip);
ETextureSourceFormat SourceFormat = TextureSource.GetFormat();
int32 Index = ((Y * MipWidth) + X) * TextureSource.GetBytesPerPixel();
if ((SourceFormat == TSF_BGRA8 || SourceFormat == TSF_BGRE8))
{
FColor OutSourceColor;
const uint8* PixelPtr = SourceData.GetData() + Index;
OutSourceColor = *((FColor*)PixelPtr);
if (Texture->SRGB)
{
return FLinearColor::FromSRGBColor(OutSourceColor);
}
return FLinearColor(float(OutSourceColor.R), float(OutSourceColor.G), float(OutSourceColor.B), float(OutSourceColor.A)) / 255.0f;
}
else if ((SourceFormat == TSF_RGBA16 || SourceFormat == TSF_RGBA16F))
{
FFloat16Color OutSourceColor;
const uint8* PixelPtr = SourceData.GetData() + Index;
OutSourceColor = *((FFloat16Color*)PixelPtr);
return FLinearColor(float(OutSourceColor.R), float(OutSourceColor.G), float(OutSourceColor.B), float(OutSourceColor.A));
}
else if (SourceFormat == TSF_G8)
{
FColor OutSourceColor;
const uint8* PixelPtr = SourceData.GetData() + Index;
const uint8 value = *PixelPtr;
if (Texture->SRGB)
{
return FLinearColor::FromSRGBColor(FColor(float(value), 0, 0, 0));
}
return FLinearColor(float(value), 0, 0, 0);
}
FMessageLog("Blueprint").Warning(LOCTEXT("Texture2D_SampleUV_InvalidFormat.", "Texture2D_SampleUV_EditorOnly: Source was unavailable or of unsupported format."));
}
}
FMessageLog("Blueprint").Warning(LOCTEXT("Texture2D_SampleUV_InvalidTexture.", "Texture2D_SampleUV_EditorOnly: Texture2D must be non-null."));
#else
FMessageLog("Blueprint").Error(LOCTEXT("Texture2D cannot be sampled at runtime.", "Texture2D_SampleUV: Can't sample Texture2D at run time."));
#endif
return FLinearColor(0, 0, 0, 0);
}
TArray<FLinearColor> UBlueprintMaterialTextureNodesBPLibrary::RenderTarget_SampleRectangle_EditorOnly(UTextureRenderTarget2D* InRenderTarget, FLinearColor InRect)
{
#if WITH_EDITOR
if (!InRenderTarget)
{
FMessageLog("Blueprint").Warning(LOCTEXT("RenderTargetSampleUV_InvalidRenderTarget.", "RenderTargetSampleUVEditoOnly: Render Target must be non-null."));
return { FLinearColor(0,0,0,0) };
}
else if (!InRenderTarget->Resource)
{
FMessageLog("Blueprint").Warning(LOCTEXT("RenderTargetSampleUV_ReleasedRenderTarget.", "RenderTargetSampleUVEditoOnly: Render Target has been released."));
return { FLinearColor(0,0,0,0) };
}
else
{
ETextureRenderTargetFormat format = (InRenderTarget->RenderTargetFormat);
if ((format == (RTF_RGBA16f)) || (format == (RTF_RGBA32f)) || (format == (RTF_RGBA8)))
{
FTextureRenderTargetResource* RTResource = InRenderTarget->GameThread_GetRenderTargetResource();
InRect.R = FMath::Clamp(int(InRect.R), 0, InRenderTarget->SizeX - 1);
InRect.G = FMath::Clamp(int(InRect.G), 0, InRenderTarget->SizeY - 1);
InRect.B = FMath::Clamp(int(InRect.B), int(InRect.R + 1), InRenderTarget->SizeX);
InRect.A = FMath::Clamp(int(InRect.A), int(InRect.G + 1), InRenderTarget->SizeY);
FIntRect Rect = FIntRect(InRect.R, InRect.G, InRect.B, InRect.A);
FReadSurfaceDataFlags ReadPixelFlags;
TArray<FColor> OutLDR;
TArray<FLinearColor> OutHDR;
TArray<FLinearColor> OutVals;
bool ishdr = ((format == (RTF_R16f)) || (format == (RTF_RG16f)) || (format == (RTF_RGBA16f)) || (format == (RTF_R32f)) || (format == (RTF_RG32f)) || (format == (RTF_RGBA32f)));
if (!ishdr)
{
RTResource->ReadPixels(OutLDR, ReadPixelFlags, Rect);
for (auto i : OutLDR)
{
OutVals.Add(FLinearColor(float(i.R), float(i.G), float(i.B), float(i.A)) / 255.0f);
}
}
else
{
RTResource->ReadLinearColorPixels(OutHDR, ReadPixelFlags, Rect);
return OutHDR;
}
return OutVals;
}
}
FMessageLog("Blueprint").Warning(LOCTEXT("RenderTarget_SampleRectangle_InvalidTexture.", "RenderTarget_SampleRectangle_EditorOnly: Currently only 4 channel formats are supported: RTF_RGBA8, RTF_RGBA16f, and RTF_RGBA32f."));
#else
FMessageLog("Blueprint").Error(LOCTEXT("Render Targets Cannot Be Sampled at run time.", "RenderTarget_SampleRectangle: Can't sample Render Target at run time."));
#endif
return { FLinearColor(0,0,0,0) };
}
FLinearColor UBlueprintMaterialTextureNodesBPLibrary::RenderTarget_SampleUV_EditorOnly(UTextureRenderTarget2D* InRenderTarget, FVector2D UV)
{
#if WITH_EDITOR
if (!InRenderTarget)
{
FMessageLog("Blueprint").Warning(LOCTEXT("RenderTargetSampleUV_InvalidRenderTarget.", "RenderTargetSampleUVEditoOnly: Render Target must be non-null."));
return FLinearColor(0, 0, 0, 0);
}
else if (!InRenderTarget->Resource)
{
FMessageLog("Blueprint").Warning(LOCTEXT("RenderTargetSampleUV_ReleasedRenderTarget.", "RenderTargetSampleUVEditoOnly: Render Target has been released."));
return FLinearColor(0, 0, 0, 0);
}
else
{
ETextureRenderTargetFormat format = (InRenderTarget->RenderTargetFormat);
if ((format == (RTF_RGBA16f)) || (format == (RTF_RGBA32f)) || (format == (RTF_RGBA8)))
{
FTextureRenderTargetResource* RTResource = InRenderTarget->GameThread_GetRenderTargetResource();
UV.X *= InRenderTarget->SizeX;
UV.Y *= InRenderTarget->SizeY;
UV.X = FMath::Clamp(UV.X, 0.0f, float(InRenderTarget->SizeX) - 1);
UV.Y = FMath::Clamp(UV.Y, 0.0f, float(InRenderTarget->SizeY) - 1);
FIntRect Rect = FIntRect(UV.X, UV.Y, UV.X + 1, UV.Y + 1);
FReadSurfaceDataFlags ReadPixelFlags;
TArray<FColor> OutLDR;
TArray<FLinearColor> OutHDR;
TArray<FLinearColor> OutVals;
bool ishdr = ((format == (RTF_R16f)) || (format == (RTF_RG16f)) || (format == (RTF_RGBA16f)) || (format == (RTF_R32f)) || (format == (RTF_RG32f)) || (format == (RTF_RGBA32f)));
if (!ishdr)
{
RTResource->ReadPixels(OutLDR, ReadPixelFlags, Rect);
for (auto i : OutLDR)
{
OutVals.Add(FLinearColor(float(i.R), float(i.G), float(i.B), float(i.A)) / 255.0f);
}
}
else
{
RTResource->ReadLinearColorPixels(OutHDR, ReadPixelFlags, Rect);
return OutHDR[0];
}
return OutVals[0];
}
FMessageLog("Blueprint").Warning(LOCTEXT("RenderTarget_SampleUV_InvalidTexture.", "RenderTarget_SampleUV_EditorOnly: Currently only 4 channel formats are supported: RTF_RGBA8, RTF_RGBA16f, and RTF_RGBA32f."));
}
#else
FMessageLog("Blueprint").Error(LOCTEXT("Render Targets Cannot Be Sampled at run time.", "RenderTarget_SampleUV: Can't sample Render Target at run time."));
#endif
return FLinearColor(0, 0, 0, 0);
}
UMaterialInstanceConstant* UBlueprintMaterialTextureNodesBPLibrary::CreateMIC_EditorOnly(UMaterialInterface* Material, FString InName)
{
#if WITH_EDITOR
TArray<UObject*> ObjectsToSync;
if (Material != nullptr)
{
// Create an appropriate and unique name
FString Name;
FString PackageName;
IAssetTools& AssetTools = FModuleManager::Get().LoadModuleChecked<FAssetToolsModule>("AssetTools").Get();
//Use asset name only if directories are specified, otherwise full path
if (!InName.Contains(TEXT("/")))
{
FString AssetName = Material->GetOutermost()->GetName();
const FString SanitizedBasePackageName = PackageTools::SanitizePackageName(AssetName);
const FString PackagePath = FPackageName::GetLongPackagePath(SanitizedBasePackageName) + TEXT("/");
AssetTools.CreateUniqueAssetName(PackagePath, InName, PackageName, Name);
}
else
{
InName.RemoveFromStart(TEXT("/"));
InName.RemoveFromStart(TEXT("Content/"));
InName.StartsWith(TEXT("Game/")) == true ? InName.InsertAt(0, TEXT("/")) : InName.InsertAt(0, TEXT("/Game/"));
AssetTools.CreateUniqueAssetName(InName, TEXT(""), PackageName, Name);
}
UMaterialInstanceConstantFactoryNew* Factory = NewObject<UMaterialInstanceConstantFactoryNew>();
Factory->InitialParent = Material;
UObject* NewAsset = AssetTools.CreateAsset(Name, FPackageName::GetLongPackagePath(PackageName), UMaterialInstanceConstant::StaticClass(), Factory);
ObjectsToSync.Add(NewAsset);
GEditor->SyncBrowserToObjects(ObjectsToSync);
UMaterialInstanceConstant* MIC = Cast<UMaterialInstanceConstant>(NewAsset);
return MIC;
}
FMessageLog("Blueprint").Warning(LOCTEXT("CreateMIC_InvalidMaterial.", "CreateMIC_EditorOnly: Material must be non-null."));
#else
FMessageLog("Blueprint").Error(LOCTEXT("Material Instance Constants cannot be created at runtime.", "CreateMIC: Can't create MIC at run time."));
#endif
return nullptr;
}
//TODO: make this function properly broadcast update to editor to refresh MIC window
void UBlueprintMaterialTextureNodesBPLibrary::UpdateMIC(UMaterialInstanceConstant* MIC)
{
#if WITH_EDITOR
FMaterialUpdateContext UpdateContext(FMaterialUpdateContext::EOptions::Default, GMaxRHIShaderPlatform);
UpdateContext.AddMaterialInstance(MIC);
MIC->MarkPackageDirty();
#endif
}
bool UBlueprintMaterialTextureNodesBPLibrary::SetMICScalarParam_EditorOnly(UMaterialInstanceConstant* Material, FString ParamName, float Value)
{
#if WITH_EDITOR
FName Name = FName(*ParamName);
if (Material != nullptr)
{
Material->SetScalarParameterValueEditorOnly(Name, Value);
UpdateMIC(Material);
return 1;
}
FMessageLog("Blueprint").Warning(LOCTEXT("SetMICScalarParam_InvalidMIC.", "SetMICScalarParam_EditorOnly: MIC must be non-null."));
#else
FMessageLog("Blueprint").Error(LOCTEXT("Material Instance Constants cannot be modified at runtime.", "SetMICScalarParam: Can't modify MIC at run time."));
#endif
return 0;
}
bool UBlueprintMaterialTextureNodesBPLibrary::SetMICVectorParam_EditorOnly(UMaterialInstanceConstant* Material, FString ParamName, FLinearColor Value)
{
#if WITH_EDITOR
FName Name = FName(*ParamName);
if (Material != nullptr)
{
Material->SetVectorParameterValueEditorOnly(Name, Value);
UpdateMIC(Material);
return 1;
}
FMessageLog("Blueprint").Warning(LOCTEXT("SetMICVectorParam_InvalidMIC.", "SetMICVectorParam_EditorOnly: MIC must be non-null."));
#else
FMessageLog("Blueprint").Error(LOCTEXT("Material Instance Constants cannot be modified at runtime.", "SetMICVectorParam: Can't modify MIC at run time."));
#endif
return 0;
}
bool UBlueprintMaterialTextureNodesBPLibrary::SetMICTextureParam_EditorOnly(UMaterialInstanceConstant* Material, FString ParamName, UTexture2D* Texture)
{
#if WITH_EDITOR
FName Name = FName(*ParamName);
if (Material != nullptr)
{
Material->SetTextureParameterValueEditorOnly(Name, Texture);
UpdateMIC(Material);
return 1;
}
FMessageLog("Blueprint").Warning(LOCTEXT("SetMICTextureParam_InvalidMIC.", "SetMICTextureParam_EditorOnly: MIC must be non-null."));
#else
FMessageLog("Blueprint").Error(LOCTEXT("Material Instance Constants cannot be modified at runtime.", "SetMICTextureParam: Can't modify MIC at run time."));
#endif
return 0;
}
bool UBlueprintMaterialTextureNodesBPLibrary::SetMICShadingModel_EditorOnly(UMaterialInstanceConstant* Material, TEnumAsByte<enum EMaterialShadingModel> ShadingModel)
{
#if WITH_EDITOR
if (Material != nullptr)
{
Material->BasePropertyOverrides.bOverride_ShadingModel = true;
Material->BasePropertyOverrides.ShadingModel = ShadingModel;
UpdateMIC(Material);
return 1;
}
FMessageLog("Blueprint").Warning(LOCTEXT("SetMICShadingModel_InvalidMIC.", "SetMICShadingModel_EditorOnly: MIC must be non-null."));
#else
FMessageLog("Blueprint").Error(LOCTEXT("Material Instance Constants cannot be modified at runtime.", "SetMICShadingModel: Can't modify MIC at run time."));
#endif
return 0;
}
bool UBlueprintMaterialTextureNodesBPLibrary::SetMICBlendMode_EditorOnly(UMaterialInstanceConstant* Material, TEnumAsByte<enum EBlendMode> BlendMode)
{
#if WITH_EDITOR
if (Material != nullptr)
{
Material->BasePropertyOverrides.bOverride_BlendMode = true;
Material->BasePropertyOverrides.BlendMode = BlendMode;
UpdateMIC(Material);
return 1;
}
FMessageLog("Blueprint").Warning(LOCTEXT("SetMICBlendMode_InvalidMIC.", "SetMICBlendMode_EditorOnly: MIC must be non-null."));
#else
FMessageLog("Blueprint").Error(LOCTEXT("Material Instance Constants cannot be modified at runtime.", "SetMICBlendMode: Can't modify MIC at run time."));
#endif
return 0;
}
bool UBlueprintMaterialTextureNodesBPLibrary::SetMICTwoSided_EditorOnly(UMaterialInstanceConstant* Material, bool TwoSided)
{
#if WITH_EDITOR
if (Material != nullptr)
{
Material->BasePropertyOverrides.bOverride_TwoSided = true;
Material->BasePropertyOverrides.TwoSided = TwoSided;
UpdateMIC(Material);
return 1;
}
FMessageLog("Blueprint").Warning(LOCTEXT("SetMICTwoSided_InvalidMIC.", "SetMICTwoSided_EditorOnly: MIC must be non-null."));
#else
FMessageLog("Blueprint").Error(LOCTEXT("Material Instance Constants cannot be modified at runtime.", "SetMICTwoSided: Can't modify MIC at run time."));
#endif
return 0;
}
bool UBlueprintMaterialTextureNodesBPLibrary::SetMICDitheredLODTransition_EditorOnly(UMaterialInstanceConstant* Material, bool DitheredLODTransition)
{
#if WITH_EDITOR
if (Material != nullptr)
{
Material->BasePropertyOverrides.bOverride_DitheredLODTransition = true;
Material->BasePropertyOverrides.DitheredLODTransition = DitheredLODTransition;
UpdateMIC(Material);
return 1;
}
FMessageLog("Blueprint").Warning(LOCTEXT("SetMICDitheredLODTransition_InvalidMIC.", "SetMICDitheredLODTransition_EditorOnly: MIC must be non-null."));
#else
FMessageLog("Blueprint").Error(LOCTEXT("Material Instance Constants cannot be modified at runtime.", "SetMICDitherTransition: Can't modify MIC at run time."));
#endif
return 0;
}
#undef LOCTEXT_NAMESPACE | 35.883669 | 224 | 0.750561 | [
"render"
] |
906a267db4727ecf1dc622224219262e1ea74faf | 6,278 | cpp | C++ | modules/blazingsql/src/addon.cpp | love-lena/node-rapids | 27c9e2468372df4fae3779d859089b54c8d32c4f | [
"Apache-2.0"
] | 1 | 2021-06-24T23:08:49.000Z | 2021-06-24T23:08:49.000Z | modules/blazingsql/src/addon.cpp | love-lena/node-rapids | 27c9e2468372df4fae3779d859089b54c8d32c4f | [
"Apache-2.0"
] | null | null | null | modules/blazingsql/src/addon.cpp | love-lena/node-rapids | 27c9e2468372df4fae3779d859089b54c8d32c4f | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2021, NVIDIA CORPORATION.
//
// 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 "context.hpp"
#include <blazingsql/api.hpp>
#include <blazingsql/cache.hpp>
#include <blazingsql/graph.hpp>
#include <node_cudf/table.hpp>
#include <nv_node/utilities/args.hpp>
struct node_blazingsql : public nv::EnvLocalAddon, public Napi::Addon<node_blazingsql> {
node_blazingsql(Napi::Env env, Napi::Object exports) : nv::EnvLocalAddon(env, exports) {
DefineAddon(
exports,
{InstanceMethod("init", &node_blazingsql::InitAddon),
InstanceMethod<&node_blazingsql::get_table_scan_info>("getTableScanInfo"),
InstanceMethod<&node_blazingsql::run_generate_graph>("runGenerateGraph"),
InstanceMethod<&node_blazingsql::run_generate_physical_graph>("runGeneratePhysicalGraph"),
InstanceMethod<&node_blazingsql::start_execute_graph>("startExecuteGraph"),
InstanceMethod<&node_blazingsql::get_execute_graph_result>("getExecuteGraphResult"),
InstanceValue("_cpp_exports", _cpp_exports.Value()),
InstanceValue("Context", InitClass<nv::Context>(env, exports)),
InstanceValue("CacheMachine", InitClass<nv::CacheMachine>(env, exports)),
InstanceValue("ExecutionGraph", InitClass<nv::ExecutionGraph>(env, exports)),
InstanceValue("ContextWrapper", InitClass<nv::ContextWrapper>(env, exports))});
}
private:
Napi::Value get_table_scan_info(Napi::CallbackInfo const& info) {
auto env = info.Env();
auto [names, steps] = nv::get_table_scan_info(info[0].ToString());
Napi::Array table_names = Napi::Array::New(env, names.size());
Napi::Array table_scans = Napi::Array::New(env, steps.size());
for (std::size_t i = 0; i < names.size(); ++i) {
table_names[i] = Napi::String::New(env, names[i]);
}
for (std::size_t i = 0; i < steps.size(); ++i) {
table_scans[i] = Napi::String::New(env, steps[i]);
}
auto result = Napi::Array::New(env, 2);
result.Set(0u, table_names);
result.Set(1u, table_scans);
return result;
}
Napi::Value run_generate_graph(Napi::CallbackInfo const& info) {
auto env = info.Env();
nv::CallbackArgs args{info};
uint32_t master_index = args[0];
std::vector<std::string> worker_ids = args[1];
Napi::Array data_frames = args[2];
std::vector<std::string> table_names = args[3];
std::vector<std::string> table_scans = args[4];
int32_t ctx_token = args[5];
std::string query = args[6];
std::string sql = args[8];
std::string current_timestamp = args[9];
auto config_options = [&] {
std::map<std::string, std::string> config{};
auto prop = args[7];
if (prop.IsObject() and not prop.IsNull()) {
auto opts = prop.As<Napi::Object>();
auto keys = opts.GetPropertyNames();
for (auto i = 0u; i < keys.Length(); ++i) {
auto name = keys.Get(i).ToString();
config[name] = opts.Get(name).ToString();
}
}
return config;
}();
std::vector<cudf::table_view> table_views;
std::vector<std::vector<std::string>> column_names;
table_views.reserve(data_frames.Length());
column_names.reserve(data_frames.Length());
auto tables = Napi::Array::New(env, data_frames.Length());
for (std::size_t i = 0; i < data_frames.Length(); ++i) {
nv::NapiToCPP::Object df = data_frames.Get(i);
std::vector<std::string> names = df.Get("names");
Napi::Function asTable = df.Get("asTable");
nv::Table::wrapper_t table = asTable.Call(df.val, {}).ToObject();
tables.Set(i, table);
table_views.push_back(*table);
column_names.push_back(names);
}
return nv::run_generate_graph(env,
master_index,
worker_ids,
table_views,
column_names,
table_names,
table_scans,
ctx_token,
query,
sql,
current_timestamp,
config_options);
}
Napi::Value run_generate_physical_graph(Napi::CallbackInfo const& info) {
auto env = info.Env();
nv::CallbackArgs args{info};
uint32_t masterIndex = args[0];
std::vector<std::string> worker_ids = args[1];
int32_t ctx_token = args[2];
std::string query = args[3];
return Napi::String::New(
env, nv::run_generate_physical_graph(masterIndex, worker_ids, ctx_token, query));
}
void start_execute_graph(Napi::CallbackInfo const& info) {
nv::start_execute_graph(info[0].ToObject(), info[1].ToNumber());
}
Napi::Value get_execute_graph_result(Napi::CallbackInfo const& info) {
auto env = info.Env();
auto [bsql_names, bsql_tables] =
nv::get_execute_graph_result(info[0].ToObject(), info[1].ToNumber());
auto result_names = Napi::Array::New(env, bsql_names.size());
for (size_t i = 0; i < bsql_names.size(); ++i) {
result_names.Set(i, Napi::String::New(env, bsql_names[i]));
}
auto result_tables = Napi::Array::New(env, bsql_tables.size());
for (size_t i = 0; i < bsql_tables.size(); ++i) {
result_tables.Set(i, nv::Table::New(env, std::move(bsql_tables[i])));
}
auto result = Napi::Object::New(env);
result.Set("names", result_names);
result.Set("tables", result_tables);
return result;
}
};
NODE_API_ADDON(node_blazingsql);
| 38.515337 | 97 | 0.610226 | [
"object",
"vector"
] |
906c02dc5b0c32c26ba4968d306bd08984f046e7 | 3,180 | cpp | C++ | deps/src/boost_1_65_1/libs/fusion/test/sequence/size.cpp | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 11,356 | 2017-12-08T19:42:32.000Z | 2022-03-31T16:55:25.000Z | deps/src/boost_1_65_1/libs/fusion/test/sequence/size.cpp | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 2,402 | 2017-12-08T22:31:01.000Z | 2022-03-28T19:25:52.000Z | deps/src/boost_1_65_1/libs/fusion/test/sequence/size.cpp | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | /*=============================================================================
Copyright (c) 2014 Kohei Takahashi
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 <boost/config.hpp>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/container/deque.hpp>
#include <boost/fusion/container/list.hpp>
#include <boost/fusion/container/set.hpp>
#include <boost/fusion/container/map.hpp>
#include <boost/fusion/support/pair.hpp>
#include <boost/fusion/sequence/intrinsic/size.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/array.hpp>
#include <boost/fusion/adapted/boost_array.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/fusion/adapted/boost_tuple.hpp>
#if !defined(BOOST_NO_CXX11_HDR_TUPLE) && \
!defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#include <tuple>
#include <boost/fusion/adapted/std_tuple.hpp>
#endif
template <typename LHS, typename RHS>
void check_(LHS const&, RHS const&)
{
BOOST_MPL_ASSERT((boost::is_same<LHS, RHS>));
}
template <typename S>
void check()
{
check_(
boost::fusion::result_of::size<S>::type::value
, boost::fusion::result_of::size<S>::value
);
}
void test()
{
{
check<boost::fusion::vector<> >();
check<boost::fusion::vector<int> >();
check<boost::fusion::vector<int, int> >();
check<boost::fusion::vector<int, int, int> >();
}
{
check<boost::fusion::deque<> >();
check<boost::fusion::deque<int> >();
check<boost::fusion::deque<int, int> >();
check<boost::fusion::deque<int, int, int> >();
}
{
check<boost::fusion::list<> >();
check<boost::fusion::list<int> >();
check<boost::fusion::list<int, int> >();
check<boost::fusion::list<int, int, int> >();
}
{
check<boost::fusion::set<> >();
check<boost::fusion::set<int> >();
check<boost::fusion::set<int, float> >();
check<boost::fusion::set<int, float, double> >();
}
{
check<boost::fusion::map<> >();
check<boost::fusion::map<boost::fusion::pair<int, int> > >();
check<boost::fusion::map<boost::fusion::pair<int, int> , boost::fusion::pair<float, int> > >();
check<boost::fusion::map<boost::fusion::pair<int, int> , boost::fusion::pair<float, int> , boost::fusion::pair<double, int> > >();
}
{
check<boost::array<int, 1> >();
check<boost::array<int, 2> >();
check<boost::array<int, 3> >();
}
{
check<boost::tuples::tuple<> >();
check<boost::tuples::tuple<int> >();
check<boost::tuples::tuple<int, int> >();
check<boost::tuples::tuple<int, int, int> >();
}
#if !defined(BOOST_NO_CXX11_HDR_TUPLE) && \
!defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
{
check<std::tuple<> >();
check<std::tuple<int> >();
check<std::tuple<int, int> >();
check<std::tuple<int, int, int> >();
}
#endif
}
| 30.873786 | 138 | 0.577358 | [
"vector"
] |
906d07a908701bcad3240d36050839f208e70e91 | 3,187 | hh | C++ | src/kinetics/SyntheticDiscreteSource.hh | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 4 | 2015-03-07T16:20:23.000Z | 2020-02-10T13:40:16.000Z | src/kinetics/SyntheticDiscreteSource.hh | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 3 | 2018-02-27T21:24:22.000Z | 2020-12-16T00:56:44.000Z | src/kinetics/SyntheticDiscreteSource.hh | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 9 | 2015-03-07T16:20:26.000Z | 2022-01-29T00:14:23.000Z | //----------------------------------*-C++-*----------------------------------//
/**
* @file SyntheticDiscreteSource.hh
* @brief SyntheticDiscreteSource
* @author Jeremy Roberts
* @date Nov 15, 2012
*/
//---------------------------------------------------------------------------//
#ifndef detran_SYNTHETICDISCRETESOURCE_HH_
#define detran_SYNTHETICDISCRETESOURCE_HH_
#include "SyntheticSource.hh"
namespace detran
{
class KINETICS_EXPORT SyntheticDiscreteSource: public SyntheticSource
{
public:
//-------------------------------------------------------------------------//
// TYPEDEFS
//-------------------------------------------------------------------------//
typedef SyntheticSource Base;
//-------------------------------------------------------------------------//
// CONSTRUCTOR & DESTRUCTOR
//-------------------------------------------------------------------------//
/**
* @brief Constructor
* @param number_groups Number of energy groups
* @param mesh Mesh
* @param quadrature Quadrature
* @param material Material
*/
SyntheticDiscreteSource(const size_t number_groups,
SP_mesh mesh,
SP_quadrature quadrature,
SP_material material);
//-------------------------------------------------------------------------//
// ABSTRACT INTERFACE -- ALL SYNTHETIC SOURCES MUST IMPLEMENT THESE
//-------------------------------------------------------------------------//
/**
* @brief Get moments source for cell.
*
* Units are n/cc-sec
*
* @param cell Mesh cell
* @param group Energy group
*/
double source(const size_t cell,
const size_t group);
/**
* @brief Get discrete source for cell and cardinal angle.
*
* Units are n/cc-ster-sec
*
* @param cell Mesh cell
* @param group Energy group
* @param angle Cardinal angle index
*/
double source(const size_t cell,
const size_t group,
const size_t angle);
/**
* @brief Build the synthetic source given previous iterates
*
* Depending on the order of the method, we may use
*/
virtual void build(const double dt,
const vec_states &states,
const vec_precursors &precursors,
const size_t order);
private:
//-------------------------------------------------------------------------//
// DATA
//-------------------------------------------------------------------------//
/// Discrete source [group][angle][space]
vec3_dbl d_source;
};
} // end namespace detran
//---------------------------------------------------------------------------//
// INLINE MEMBER DEFINITIONS
//---------------------------------------------------------------------------//
#include "SyntheticDiscreteSource.i.hh"
#endif // detran_SYNTHETICDISCRETESOURCE_HH_
//---------------------------------------------------------------------------//
// end of file SyntheticDiscreteSource.hh
//---------------------------------------------------------------------------//
| 29.785047 | 79 | 0.406966 | [
"mesh"
] |
9071bc3abb8bd282016062d1539c38f94dfc6f0e | 4,232 | cpp | C++ | Funambol/source/common/syncml/core/Delete.cpp | wbitos/funambol | 29f76caf9cee51d51ddf5318613411cb1cfb8e4e | [
"MIT"
] | null | null | null | Funambol/source/common/syncml/core/Delete.cpp | wbitos/funambol | 29f76caf9cee51d51ddf5318613411cb1cfb8e4e | [
"MIT"
] | null | null | null | Funambol/source/common/syncml/core/Delete.cpp | wbitos/funambol | 29f76caf9cee51d51ddf5318613411cb1cfb8e4e | [
"MIT"
] | null | null | null | /*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include <Funambol/syncml/core/Delete.h>
#include <Funambol/base/globalsdef.h>
USE_NAMESPACE
Delete::Delete() {
COMMAND_NAME = new char[strlen(DELETE_COMMAND_NAME) + 1];
sprintf(COMMAND_NAME, DELETE_COMMAND_NAME);
}
Delete::~Delete() {
if (COMMAND_NAME) {
delete [] COMMAND_NAME; COMMAND_NAME = NULL;
}
archive = false;
sftDel = false;
}
/**
* Creates a new Delete object with the given command identifier,
* noResponse, archiveData, softDelete, credential, meta and array of item
*
* @param cmdID the command identifier - NOT NULL
* @param noResp true if no response is required
* @param archive true if the deleted data should be archived
* @param sftDel true if this is a "soft delete". If set to false, then
* this delete command is a "hard delete"
* @param cred the authentication credential
* @param meta the meta data
* @param items the array of item - NOT NULL
*
*/
Delete::Delete(CmdID* cmdID,
bool noResp,
bool archive,
bool sftDel,
Cred* cred,
Meta* meta,
ArrayList* items) : ModificationCommand(cmdID, meta, items) {
setCred(cred);
setNoResp(noResp);
setArchive(archive);
setSftDel(sftDel);
COMMAND_NAME = new char[strlen(DELETE_COMMAND_NAME) + 1];
sprintf(COMMAND_NAME, DELETE_COMMAND_NAME);
}
/**
* Gets the command name property
*
* @return the command name property
*/
const char* Delete::getName() {
return COMMAND_NAME;
}
/**
* Gets the Archive property
*
* @return true if the deleted data should be archived
*/
bool Delete::isArchive() {
return archive;
}
/**
* Gets the Boolean archive property
*
* @return archive the Boolean archive property
*/
bool Delete::getArchive() {
return archive;
}
/**
* Sets the archive property
*
* @param archive the Boolean archive object
*/
void Delete::setArchive(bool archive) {
this->archive = archive;
}
/**
* Gets the SftDel property
*
* @return <b>true</b> if this is a "Soft delete"
* <b>false</b> if this is a "hard delete"
*/
bool Delete::isSftDel() {
return sftDel;
}
bool Delete::getSftDel() {
return sftDel;
}
void Delete::setSftDel(bool sftDel) {
this->sftDel = sftDel;
}
ArrayElement* Delete::clone() {
Delete* ret = new Delete(getCmdID(), getNoResp(), archive, sftDel, getCred(), getMeta(), getItems());
return ret;
}
| 28.986301 | 105 | 0.699905 | [
"object"
] |
9078fb7227597daff0bc7114f03a3222ec9c9152 | 4,115 | hh | C++ | agent/base/Observer.hh | automenta/trex-autonomy | fcca1f7596af30735fe53d1bab54b3a0c1f97b89 | [
"BSD-3-Clause"
] | null | null | null | agent/base/Observer.hh | automenta/trex-autonomy | fcca1f7596af30735fe53d1bab54b3a0c1f97b89 | [
"BSD-3-Clause"
] | null | null | null | agent/base/Observer.hh | automenta/trex-autonomy | fcca1f7596af30735fe53d1bab54b3a0c1f97b89 | [
"BSD-3-Clause"
] | null | null | null | #ifndef H_Observer
#define H_Observer
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2007. MBARI.
* 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 TREX Project 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.
*/
/**
* @author Conor McGann
* @file Declares observation related interfaces
*/
#include "TREXDefs.hh"
#include "LabelStr.hh"
#include "AbstractDomain.hh"
#include "PlanDatabaseDefs.hh"
#include "EuropaXML.hh"
namespace TREX {
/**
* @brief An observation is a predicate observed at current time.
*/
class Observation {
public:
/**
* @brief Return the attribute to which the observation applies
*/
const LabelStr& getObjectName() const;
/**
* @brief Return the predicate of the observation
*/
const LabelStr& getPredicate() const;
/**
* @brief Return the number of arguments contained
*/
unsigned int countParameters() const;
/**
* @brief Accessor for the parameter values by position. Pure virtual to allow efficient underlying implementation.
*/
virtual const std::pair<LabelStr, const AbstractDomain*> operator[](unsigned int index) const = 0;
/**
* @brief Utility to help tracing
*/
std::string toString() const;
/** @brief Utility to serialize data in XML format
*
* @sa ObservationLogger
*/
//TiXmlElement *toXML() const;
void printXML(FILE *out) const;
/**
* @brief Utility for getting the tokens timeline
*/
static LabelStr getTimelineName(const TokenId& token);
virtual ~Observation();
protected:
Observation(const LabelStr& objectName, const LabelStr& predicateName, unsigned int parameterCount = 0);
unsigned int m_parameterCount;
private:
const LabelStr m_objectName;
const LabelStr m_predicateName;
};
class ObservationByReference : public Observation {
public:
ObservationByReference(const TokenId& token);
const std::pair<LabelStr, const AbstractDomain*> operator[](unsigned int) const;
private:
const TokenId m_token;
};
class ObservationByValue: public Observation {
public:
ObservationByValue(const LabelStr& objectName, const LabelStr& predicateName);
~ObservationByValue();
const std::pair<LabelStr, const AbstractDomain*> operator[](unsigned int) const;
void push_back(const LabelStr&, AbstractDomain* dom);
private:
std::vector< std::pair<LabelStr, AbstractDomain*> > m_parameters;
};
class Observer {
public:
virtual void notify(const Observation& observation) = 0;
virtual ~Observer(){}
};
}
#endif
| 30.257353 | 119 | 0.702552 | [
"vector"
] |
907b8270b6f36b1c35f940db6fce77e3e2bf244b | 2,123 | cpp | C++ | exercises/05_classes/classes4.cpp | rdjondo/cplings | 599d8ebf38fd6bc71e573192bfe6f4f9f72e5760 | [
"MIT"
] | 1 | 2021-03-24T17:59:23.000Z | 2021-03-24T17:59:23.000Z | exercises/05_classes/classes4.cpp | rdjondo/cplings | 599d8ebf38fd6bc71e573192bfe6f4f9f72e5760 | [
"MIT"
] | null | null | null | exercises/05_classes/classes4.cpp | rdjondo/cplings | 599d8ebf38fd6bc71e573192bfe6f4f9f72e5760 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
// classes4.cpp
// Make me compile! Go to the folder hint if you want a hint :)
// We sometimes encourage you to keep trying things on shape given exercise,
// even after you already figured it out.
// Step 1: Make me compile!
// Write the Circle constructor
struct Point {
static const double epsilon;
double x;
double y;
// When two points are close to each other we assume that they are equal
bool operator==(const Point& p) const{
return (std::abs(x - p.x) < epsilon) &&
(std::abs(y - p.y) < epsilon);
}
};
const double Point::epsilon = 1e-6;
// Display value for a point
std::ostream& operator<< (std::ostream& out, const Point & p) {
return out << "{" << p.x << ", " << p.y << "}";
}
constexpr Point point_zero = { 0.0, 0.0 };
class Shape {
public:
Point center_;
Shape(const Point & centre = point_zero) : center_(centre) { }
virtual Point center() const {
return point_zero;
}
};
class Circle : public Shape {
public:
Circle(const Point& centre = point_zero) : Shape(centre) { }
virtual Point center() const {
return Circle::center_;
}
};
std::vector<Point> test_center() {
const Shape shape;
const Point point_in{ 1.0, 1.0 };
const Circle circle(point_in);
std::vector<Shape*> shape_collection;
shape_collection.push_back(&shape);
shape_collection.push_back(circle); // Fix: Virtual calls work with references and addresses
std::vector<Point> center_collection{ shape_collection[0].center(), // Fix: Virtual calls work with references and addresses
shape_collection[1].center() };
std::cout << "Value :" << center_collection[0] << "\n";
std::cout << "Value :" << center_collection[1] << "\n";
return center_collection;
}
#include <catch2/catch.hpp>
TEST_CASE("test_vtable") {
const Point point_in{ 1.0, 1.0 };
auto center_collection = test_center();
REQUIRE(center_collection[0] == point_zero);
REQUIRE(center_collection[1] == point_in);
}
| 27.934211 | 128 | 0.635422 | [
"shape",
"vector"
] |
908b96369c3f2b32e5d7880c7692577f7f37a9d4 | 1,488 | cpp | C++ | segmenttree/test/point-set-range-composite.test.cpp | rsm9/cplib-cpp | 269064381eb259a049236335abb31f8f73ded7f4 | [
"MIT"
] | 4 | 2020-05-13T05:06:22.000Z | 2020-09-18T17:03:36.000Z | segmenttree/test/point-set-range-composite.test.cpp | rsm9/cplib-cpp | 269064381eb259a049236335abb31f8f73ded7f4 | [
"MIT"
] | 1 | 2019-12-11T13:53:17.000Z | 2019-12-11T13:53:17.000Z | segmenttree/test/point-set-range-composite.test.cpp | rsm9/cplib-cpp | 269064381eb259a049236335abb31f8f73ded7f4 | [
"MIT"
] | 3 | 2019-12-11T06:45:45.000Z | 2020-09-07T13:45:32.000Z | #include "../../modint.hpp"
#include "../point-update-range-get_nonrecursive.hpp"
#include <iostream>
#include <utility>
#define PROBLEM "https://judge.yosupo.jp/problem/point_set_range_composite"
using mint = ModInt<998244353>;
template <typename T>
struct PointSetRangeComposite
: public NonrecursiveSegmentTree<std::pair<T, T>, std::pair<T, T>, bool> {
using T_NODE = std::pair<T, T>;
using SegTree = NonrecursiveSegmentTree<T_NODE, T_NODE, bool>;
T_NODE merge_data(const T_NODE &vl, const T_NODE &vr) override {
return std::make_pair(vl.first * vr.first, vr.first * vl.second + vr.second);
};
T_NODE data2ret(const T_NODE &v, const bool &q) override { return v; }
T_NODE merge_ret(const T_NODE &vl, const T_NODE &vr) override { return merge_data(vl, vr); };
PointSetRangeComposite(const std::vector<T_NODE> &seq) : SegTree::NonrecursiveSegmentTree() {
SegTree::initialize(seq, T_NODE(1, 0));
};
};
int main() {
std::cin.tie(nullptr), std::ios::sync_with_stdio(false);
int N, Q;
std::cin >> N >> Q;
std::vector<std::pair<mint, mint>> A(N);
for (auto &p : A) { std::cin >> p.first >> p.second; }
PointSetRangeComposite<mint> s(A);
while (Q--) {
int q, l, r, x;
std::cin >> q >> l >> r >> x;
if (q) {
auto ret = s.get(l, r);
std::cout << ret.first * x + ret.second << '\n';
} else {
s.update(l, std::make_pair(r, x));
}
}
}
| 35.428571 | 97 | 0.607527 | [
"vector"
] |
908d43d0f763609ec1f96600bb470994eb3734eb | 3,527 | cpp | C++ | tests/ut_vmap_iter.cpp | westfly/st_tree | 5b8e66d994b5336f59ebc645335ff8f7f2e1d6bf | [
"Apache-2.0"
] | 82 | 2015-02-20T12:02:20.000Z | 2022-01-18T03:12:26.000Z | tests/ut_vmap_iter.cpp | westfly/st_tree | 5b8e66d994b5336f59ebc645335ff8f7f2e1d6bf | [
"Apache-2.0"
] | 16 | 2015-01-22T09:01:37.000Z | 2022-03-17T02:04:08.000Z | tests/ut_vmap_iter.cpp | westfly/st_tree | 5b8e66d994b5336f59ebc645335ff8f7f2e1d6bf | [
"Apache-2.0"
] | 19 | 2015-07-23T07:22:51.000Z | 2022-03-09T17:34:00.000Z | #include <boost/test/unit_test.hpp>
#include "st_tree.h"
using namespace st_tree;
using st_tree::detail::valmap_iterator_dispatch;
using st_tree::detail::dref_vmap;
#include "ut_common.h"
using std::vector;
BOOST_AUTO_TEST_SUITE(ut_valmap_iterator_adaptor)
template <typename Iterator, typename ValMap>
struct valmap_iterator_adaptor : public valmap_iterator_dispatch<Iterator, ValMap, typename Iterator::iterator_category>::adaptor_type {
typedef typename valmap_iterator_dispatch<Iterator, ValMap, typename Iterator::iterator_category>::adaptor_type adaptor_type;
typedef typename adaptor_type::iterator_category iterator_category;
typedef typename adaptor_type::value_type value_type;
typedef typename adaptor_type::difference_type difference_type;
typedef typename adaptor_type::pointer pointer;
typedef typename adaptor_type::reference reference;
typedef Iterator base_iterator;
valmap_iterator_adaptor() : adaptor_type() {}
virtual ~valmap_iterator_adaptor() {}
explicit valmap_iterator_adaptor(const valmap_iterator_adaptor& src) : adaptor_type(src) {}
valmap_iterator_adaptor& operator=(const valmap_iterator_adaptor& src) {
if (this == &src) return *this;
adaptor_type::operator=(src);
return *this;
}
operator base_iterator() const { return this->_base; }
valmap_iterator_adaptor(const base_iterator& src) : adaptor_type(src) {}
valmap_iterator_adaptor& operator=(const base_iterator& src) {
adaptor_type::operator=(src);
return *this;
}
};
BOOST_AUTO_TEST_CASE(dref_map) {
int* t1 = new int(4);
dref_vmap<int*> vmap;
BOOST_CHECK_EQUAL(vmap(t1), *t1);
delete t1;
}
BOOST_AUTO_TEST_CASE(dref_map_const) {
const int* t1 = new int(4);
dref_vmap<const int*> vmap;
BOOST_CHECK_EQUAL(vmap(t1), *t1);
delete t1;
}
BOOST_AUTO_TEST_CASE(default_ctor) {
typedef vector<int*> container_type;
typedef container_type::iterator iterator;
typedef valmap_iterator_adaptor<iterator, dref_vmap<iterator::value_type> > vm_iterator;
vm_iterator j;
}
BOOST_AUTO_TEST_CASE(using_dref_map_int_pointer) {
vector<int*> v;
typedef vector<int*>::iterator iterator;
typedef valmap_iterator_adaptor<iterator, dref_vmap<iterator::value_type > > vm_iterator;
v.push_back(new int(1));
v.push_back(new int(2));
v.push_back(new int(3));
iterator r(v.begin());
for (vm_iterator j(v.begin()); j != vm_iterator(v.end()); ++j,++r)
BOOST_CHECK_EQUAL(*j, **r);
*(vm_iterator(v.begin())) = 42;
r = v.begin();
for (vm_iterator j(v.begin()); j != vm_iterator(v.end()); ++j,++r)
BOOST_CHECK_EQUAL(*j, **r);
for (iterator j(v.begin()); j != v.end(); ++j) delete *j;
}
BOOST_AUTO_TEST_CASE(using_dref_map_int_pair_pointer) {
vector<pair<int,int>*> v;
typedef vector<pair<int,int>*>::iterator iterator;
typedef valmap_iterator_adaptor<iterator, dref_vmap<iterator::value_type > > vm_iterator;
v.push_back(new pair<int,int>(1,4));
v.push_back(new pair<int,int>(2,5));
v.push_back(new pair<int,int>(3,6));
iterator r(v.begin());
for (vm_iterator j(v.begin()); j != vm_iterator(v.end()); ++j,++r)
BOOST_CHECK(*j == **r);
(vm_iterator(v.begin()))->first = 42;
r = v.begin();
for (vm_iterator j(v.begin()); j != vm_iterator(v.end()); ++j,++r)
BOOST_CHECK(*j == **r);
for (iterator j(v.begin()); j != v.end(); ++j) delete *j;
}
BOOST_AUTO_TEST_SUITE_END()
| 32.063636 | 136 | 0.693224 | [
"vector"
] |
909951ee0dad2c02746ddd470a2a9bfcb1f00f1f | 1,954 | cpp | C++ | tests/ParserTests.cpp | AEnguerrand/cpp_zia | 165dc970a1f120ff35a358c8f7313ed0297a87da | [
"MIT"
] | 2 | 2018-02-14T16:04:23.000Z | 2019-08-17T08:44:59.000Z | tests/ParserTests.cpp | AEnguerrand/cpp_zia | 165dc970a1f120ff35a358c8f7313ed0297a87da | [
"MIT"
] | 69 | 2018-02-01T17:09:05.000Z | 2018-11-01T11:42:49.000Z | tests/ParserTests.cpp | AEnguerrand/cpp_zia | 165dc970a1f120ff35a358c8f7313ed0297a87da | [
"MIT"
] | 4 | 2018-02-27T13:24:55.000Z | 2021-05-21T09:56:17.000Z | #include "gtest/gtest.h"
#include "../src/Parser/Parser.hh"
#include "../src/Parser/ParserJson.hh"
#include "../src/ModuleLoader/ModuleLoader.hh"
#include "../src/Process/Process.hh"
TEST(Parser, Parser) {
std::vector<std::string> v;
::zia::api::Conf conf;
nz::ModuleLoader moduleLoader(v, v, conf);
moduleLoader.loadAll();
ASSERT_EQ(moduleLoader.getModules().size(), 0);
nz::Process process(moduleLoader);
nz::Parser parser(process, nullptr);
::zia::api::Net::Raw raw = transform::StringToRaw("GET /index.html HTTP/1.1 \nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) \nHost: www.tutorialspoint.com\nAccept-Language: en-us\nAccept-Encoding: gzip, deflate\nConnection: Keep-Alive");
::zia::api::NetInfo netInfo;
netInfo.sock = nullptr;
ASSERT_EQ(netInfo.sock, nullptr);
parser.setNet(nullptr);
parser.callbackRequestReceived(raw, netInfo);
}
TEST(Parser, ParserJsonIncorrectFile) {
std::string output;
//Wrong file
nz::ParserJson parseWrongJson("../conf/config.azdqsd");
parseWrongJson.getConfig();
testing::internal::CaptureStderr();
parseWrongJson.dump();
output = testing::internal::GetCapturedStderr();
ASSERT_STREQ(output.c_str(), "[WARNING] - INVALID_CONF: Configuration file's empty\n");
}
TEST(Parser, ParserJsonCorrectFile) {
std::string output;
//Correct file
nz::ParserJson parserJson("../tests/conf/config.json");
parserJson.getConfig();
testing::internal::CaptureStderr();
parserJson.dump();
output = testing::internal::GetCapturedStderr();
ASSERT_STREQ(output.c_str(), "{\n \"debug\": false,\n \"log_level\": 2,\n \"module_net\": \"network_with_ssh\",\n \"modules\": [\n \"cgibin\",\n \"gzip\",\n \"logger\"\n ],\n \"modules_path\": [\n \".\",\n \"modules\",\n 3\n ],\n \"port\": 80,\n \"port_ssl\": 443\n}\n");
} | 39.08 | 344 | 0.639713 | [
"vector",
"transform"
] |
909e33e8bc9aca5c84190d9acef3c3411b5c90c9 | 20,718 | cpp | C++ | qpcpp/src/qf/qep_msm.cpp | fjpolo/STM23F746Disco-Playground | 446e8cd45b6ab3d771a782977e7630cf92a01a88 | [
"MIT"
] | null | null | null | qpcpp/src/qf/qep_msm.cpp | fjpolo/STM23F746Disco-Playground | 446e8cd45b6ab3d771a782977e7630cf92a01a88 | [
"MIT"
] | null | null | null | qpcpp/src/qf/qep_msm.cpp | fjpolo/STM23F746Disco-Playground | 446e8cd45b6ab3d771a782977e7630cf92a01a88 | [
"MIT"
] | null | null | null | /// @file
/// @brief QP::QMsm implementation
/// @ingroup qep
/// @cond
///***************************************************************************
/// Last updated for version 6.9.2
/// Last updated on 2020-12-17
///
/// Q u a n t u m L e a P s
/// ------------------------
/// Modern Embedded Software
///
/// Copyright (C) 2005-2020 Quantum Leaps. All rights reserved.
///
/// This program is open source software: you can redistribute it and/or
/// modify it under the terms of the GNU General Public License as published
/// by the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// Alternatively, this program may be distributed and modified under the
/// terms of Quantum Leaps commercial licenses, which expressly supersede
/// the GNU General Public License and are specifically designed for
/// licensees interested in retaining the proprietary status of their code.
///
/// 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, see <www.gnu.org/licenses>.
///
/// Contact information:
/// <www.state-machine.com/licensing>
/// <info@state-machine.com>
///***************************************************************************
/// @endcond
#define QP_IMPL // this is QP implementation
#include "qep_port.hpp" // QEP port
#ifdef Q_SPY // QS software tracing enabled?
#include "qs_port.hpp" // QS port
#include "qs_pkg.hpp" // QS facilities for pre-defined trace records
#else
#include "qs_dummy.hpp" // disable the QS software tracing
#endif // Q_SPY
#include "qassert.h" // QP embedded systems-friendly assertions
//! Internal macro to increment the given action table @p act_
/// @note Incrementing a pointer violates the MISRA-C 2004 Rule 17.4(req),
/// pointer arithmetic other than array indexing. Encapsulating this violation
/// in a macro allows to selectively suppress this specific deviation.
#define QEP_ACT_PTR_INC_(act_) (++(act_))
namespace QP {
Q_DEFINE_THIS_MODULE("qep_msm")
//****************************************************************************
QMState const QMsm::msm_top_s = {
nullptr,
nullptr,
nullptr,
nullptr,
nullptr
};
//****************************************************************************
/// @description
/// Performs the first step of initialization by assigning the initial
/// pseudostate to the currently active state of the state machine.
///
/// @param[in] initial the top-most initial transition for the MSM.
///
/// @note
/// The constructor is protected to prevent direct instantiating of the
/// QP::QMsm objects. This class is intended for subclassing only.
///
/// @sa
/// The QP::QMsm example illustrates how to use the QMsm constructor
/// in the constructor initializer list of the derived state machines.
///
QMsm::QMsm(QStateHandler const initial) noexcept
: QHsm(initial)
{
m_state.obj = &msm_top_s;
m_temp.fun = initial;
}
//****************************************************************************
/// @description
/// Executes the top-most initial transition in a MSM.
///
/// @param[in] e pointer to an extra parameter (might be nullptr)
/// @param[in] qs_id QS-id of this state machine (for QS local filter)
///
/// @attention
/// QP::QMsm::init() must be called exactly __once__ before
/// QP::QMsm::dispatch()
///
void QMsm::init(void const * const e, std::uint_fast8_t const qs_id) {
QS_CRIT_STAT_
/// @pre the top-most initial transition must be initialized, and the
/// initial transition must not be taken yet.
Q_REQUIRE_ID(200, (m_temp.fun != nullptr)
&& (m_state.obj == &msm_top_s));
// execute the top-most initial tran.
QState r = (*m_temp.fun)(this, Q_EVT_CAST(QEvt));
// initial tran. must be taken
Q_ASSERT_ID(210, r == Q_RET_TRAN_INIT);
QS_BEGIN_PRE_(QS_QEP_STATE_INIT, qs_id)
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(m_state.obj->stateHandler); // source handler
QS_FUN_PRE_(m_temp.tatbl->target->stateHandler); // target handler
QS_END_PRE_()
// set state to the last tran. target
m_state.obj = m_temp.tatbl->target;
// drill down into the state hierarchy with initial transitions...
do {
r = execTatbl_(m_temp.tatbl, qs_id); // execute the tran-action table
} while (r >= Q_RET_TRAN_INIT);
QS_BEGIN_PRE_(QS_QEP_INIT_TRAN, qs_id)
QS_TIME_PRE_(); // time stamp
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(m_state.obj->stateHandler); // the new current state
QS_END_PRE_()
static_cast<void>(qs_id); // unused parameter (if Q_SPY not defined)
}
//****************************************************************************
/// @description
/// Dispatches an event for processing to a meta state machine (MSM).
/// The processing of an event represents one run-to-completion (RTC) step.
///
/// @param[in] e pointer to the event to be dispatched to the MSM
/// @param[in] qs_id QS-id of this state machine (for QS local filter)
///
/// @note
/// Must be called after QP::QMsm::init().
///
void QMsm::dispatch(QEvt const * const e, std::uint_fast8_t const qs_id) {
QMState const *s = m_state.obj; // store the current state
QMState const *t = s;
QState r;
QS_CRIT_STAT_
/// @pre current state must be initialized
Q_REQUIRE_ID(300, s != nullptr);
QS_BEGIN_PRE_(QS_QEP_DISPATCH, qs_id)
QS_TIME_PRE_(); // time stamp
QS_SIG_PRE_(e->sig); // the signal of the event
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(s->stateHandler); // the current state handler
QS_END_PRE_()
// scan the state hierarchy up to the top state...
do {
r = (*t->stateHandler)(this, e); // call state handler function
// event handled? (the most frequent case)
if (r >= Q_RET_HANDLED) {
break; // done scanning the state hierarchy
}
// event unhandled and passed to the superstate?
else if (r == Q_RET_SUPER) {
t = t->superstate; // advance to the superstate
}
// event unhandled and passed to a submachine superstate?
else if (r == Q_RET_SUPER_SUB) {
t = m_temp.obj; // current host state of the submachie
}
// event unhandled due to a guard?
else if (r == Q_RET_UNHANDLED) {
QS_BEGIN_PRE_(QS_QEP_UNHANDLED, qs_id)
QS_SIG_PRE_(e->sig); // the signal of the event
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(t->stateHandler); // the current state
QS_END_PRE_()
t = t->superstate; // advance to the superstate
}
else {
// no other return value should be produced
Q_ERROR_ID(310);
}
} while (t != nullptr);
// any kind of transition taken?
if (r >= Q_RET_TRAN) {
#ifdef Q_SPY
QMState const * const ts = t; // transition source for QS tracing
// the transition source state must not be nullptr
Q_ASSERT_ID(320, ts != nullptr);
#endif // Q_SPY
do {
// save the transition-action table before it gets clobbered
QMTranActTable const * const tatbl = m_temp.tatbl;
QHsmAttr tmp; // temporary to save intermediate values
// was TRAN, TRAN_INIT, or TRAN_EP taken?
if (r <= Q_RET_TRAN_EP) {
exitToTranSource_(s, t, qs_id);
r = execTatbl_(tatbl, qs_id);
s = m_state.obj;
}
// was a transition segment to history taken?
else if (r == Q_RET_TRAN_HIST) {
tmp.obj = m_state.obj; // save history
m_state.obj = s; // restore the original state
exitToTranSource_(s, t, qs_id);
static_cast<void>(execTatbl_(tatbl, qs_id));
r = enterHistory_(tmp.obj, qs_id);
s = m_state.obj;
}
// was a transition segment to an exit point taken?
else if (r == Q_RET_TRAN_XP) {
tmp.act = m_state.act; // save XP action
m_state.obj = s; // restore the original state
r = (*tmp.act)(this); // execute the XP action
if (r == Q_RET_TRAN) { // XP -> TRAN ?
#ifdef Q_SPY
tmp.tatbl = m_temp.tatbl; // save m_temp
#endif // Q_SPY
exitToTranSource_(s, t, qs_id);
// take the tran-to-XP segment inside submachine
static_cast<void>(execTatbl_(tatbl, qs_id));
s = m_state.obj;
#ifdef Q_SPY
m_temp.tatbl = tmp.tatbl; // restore m_temp
#endif // Q_SPY
}
else if (r == Q_RET_TRAN_HIST) { // XP -> HIST ?
tmp.obj = m_state.obj; // save the history
m_state.obj = s; // restore the original state
#ifdef Q_SPY
s = m_temp.obj; // save m_temp
#endif // Q_SPY
exitToTranSource_(m_state.obj, t, qs_id);
// take the tran-to-XP segment inside submachine
static_cast<void>(execTatbl_(tatbl, qs_id));
#ifdef Q_SPY
m_temp.obj = s; // restore me->temp
#endif // Q_SPY
s = m_state.obj;
m_state.obj = tmp.obj; // restore the history
}
else {
// TRAN_XP must NOT be followed by any other tran type
Q_ASSERT_ID(330, r < Q_RET_TRAN);
}
}
else {
// no other return value should be produced
Q_ERROR_ID(340);
}
t = s; // set target to the current state
} while (r >= Q_RET_TRAN);
QS_BEGIN_PRE_(QS_QEP_TRAN, qs_id)
QS_TIME_PRE_(); // time stamp
QS_SIG_PRE_(e->sig); // the signal of the event
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(ts->stateHandler); // the transition source
QS_FUN_PRE_(s->stateHandler); // the new active state
QS_END_PRE_()
}
#ifdef Q_SPY
// was the event handled?
else if (r == Q_RET_HANDLED) {
// internal tran. source can't be nullptr
Q_ASSERT_ID(340, t != nullptr);
QS_BEGIN_PRE_(QS_QEP_INTERN_TRAN, qs_id)
QS_TIME_PRE_(); // time stamp
QS_SIG_PRE_(e->sig); // the signal of the event
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(t->stateHandler); // the source state
QS_END_PRE_()
}
// event bubbled to the 'top' state?
else if (t == nullptr) {
QS_BEGIN_PRE_(QS_QEP_IGNORED, qs_id)
QS_TIME_PRE_(); // time stamp
QS_SIG_PRE_(e->sig); // the signal of the event
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(s->stateHandler); // the current state
QS_END_PRE_()
}
#endif // Q_SPY
else {
// empty
}
static_cast<void>(qs_id); // unused parameter (if Q_SPY not defined)
}
//****************************************************************************
#ifdef Q_SPY
/// @description
/// Helper function to get the current state handler of QMsm.
///
QStateHandler QMsm::getStateHandler() noexcept {
return m_state.obj->stateHandler;
}
#endif
//****************************************************************************
/// @description
/// Helper function to execute transition sequence in a tran-action table.
///
/// @param[in] tatbl pointer to the transition-action table
/// @param[in] qs_id QS-id of this state machine (for QS local filter)
///
/// @returns
/// the status of the last action from the transition-action table.
///
/// @note
/// This function is for internal use inside the QEP event processor and
/// should __not__ be called directly from the applications.
///
QState QMsm::execTatbl_(QMTranActTable const * const tatbl,
std::uint_fast8_t const qs_id)
{
QActionHandler const *a;
QState r = Q_RET_NULL;
QS_CRIT_STAT_
/// @pre the transition-action table pointer must not be nullptr
Q_REQUIRE_ID(400, tatbl != nullptr);
for (a = &tatbl->act[0]; *a != nullptr; QEP_ACT_PTR_INC_(a)) {
r = (*(*a))(this); // call the action through the 'a' pointer
#ifdef Q_SPY
if (r == Q_RET_ENTRY) {
QS_BEGIN_PRE_(QS_QEP_STATE_ENTRY, qs_id)
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(m_temp.obj->stateHandler); // entered state handler
QS_END_PRE_()
}
else if (r == Q_RET_EXIT) {
QS_BEGIN_PRE_(QS_QEP_STATE_EXIT, qs_id)
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(m_temp.obj->stateHandler); // exited state handler
QS_END_PRE_()
}
else if (r == Q_RET_TRAN_INIT) {
QS_BEGIN_PRE_(QS_QEP_STATE_INIT, qs_id)
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(tatbl->target->stateHandler); // source
QS_FUN_PRE_(m_temp.tatbl->target->stateHandler); // target
QS_END_PRE_()
}
else if (r == Q_RET_TRAN_EP) {
QS_BEGIN_PRE_(QS_QEP_TRAN_EP, qs_id)
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(tatbl->target->stateHandler); // source
QS_FUN_PRE_(m_temp.tatbl->target->stateHandler); // target
QS_END_PRE_()
}
else if (r == Q_RET_TRAN_XP) {
QS_BEGIN_PRE_(QS_QEP_TRAN_XP, qs_id)
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(tatbl->target->stateHandler); // source
QS_FUN_PRE_(m_temp.tatbl->target->stateHandler); // target
QS_END_PRE_()
}
else {
// empty
}
#endif // Q_SPY
}
static_cast<void>(qs_id); // unused parameter (if Q_SPY not defined)
m_state.obj = (r >= Q_RET_TRAN)
? m_temp.tatbl->target
: tatbl->target;
return r;
}
//****************************************************************************
/// @description
/// Helper function to exit the current state configuration to the
/// transition source, which is a hierarchical state machine might be a
/// superstate of the current state.
///
/// @param[in] s pointer to the current state
/// @param[in] ts pointer to the transition source state
/// @param[in] qs_id QS-id of this state machine (for QS local filter)
///
void QMsm::exitToTranSource_(QMState const *s,
QMState const * const ts,
std::uint_fast8_t const qs_id)
{
// exit states from the current state to the tran. source state
while (s != ts) {
// exit action provided in state 's'?
if (s->exitAction != nullptr) {
// execute the exit action
static_cast<void>((*s->exitAction)(this));
QS_CRIT_STAT_
QS_BEGIN_PRE_(QS_QEP_STATE_EXIT, qs_id)
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(s->stateHandler); // the exited state handler
QS_END_PRE_()
}
s = s->superstate; // advance to the superstate
// reached the top of a submachine?
if (s == nullptr) {
s = m_temp.obj; // the superstate from QM_SM_EXIT()
Q_ASSERT_ID(510, s != nullptr);
}
}
static_cast<void>(qs_id); // unused parameter (if Q_SPY not defined)
}
//****************************************************************************
/// @description
/// Static helper function to execute the segment of transition to history
/// after entering the composite state and
///
/// @param[in] hist pointer to the history substate
/// @param[in] qs_id QS-id of this state machine (for QS local filter)
///
/// @returns
/// QP::Q_RET_INIT, if an initial transition has been executed in the last
/// entered state or QP::Q_RET_NULL if no such transition was taken.
///
QState QMsm::enterHistory_(QMState const * const hist,
std::uint_fast8_t const qs_id)
{
QMState const *s = hist;
QMState const *ts = m_state.obj; // transition source
QMState const *epath[MAX_ENTRY_DEPTH_];
QState r;
std::uint_fast8_t i = 0U; // entry path index
QS_CRIT_STAT_
QS_BEGIN_PRE_(QS_QEP_TRAN_HIST, qs_id)
QS_OBJ_PRE_(this); // this state machine object
QS_FUN_PRE_(ts->stateHandler); // source state handler
QS_FUN_PRE_(hist->stateHandler); // target state handler
QS_END_PRE_()
while (s != ts) {
if (s->entryAction != nullptr) {
epath[i] = s;
++i;
Q_ASSERT_ID(620,
i <= static_cast<std::uint_fast8_t>(Q_DIM(epath)));
}
s = s->superstate;
if (s == nullptr) {
ts = s; // force exit from the for-loop
}
}
// retrace the entry path in reverse (desired) order...
while (i > 0U) {
--i;
// run entry action in epath[i]
static_cast<void>((*epath[i]->entryAction)(this));
QS_BEGIN_PRE_(QS_QEP_STATE_ENTRY, qs_id)
QS_OBJ_PRE_(this);
QS_FUN_PRE_(epath[i]->stateHandler); // entered state handler
QS_END_PRE_()
}
m_state.obj = hist; // set current state to the transition target
// initial tran. present?
if (hist->initAction != nullptr) {
r = (*hist->initAction)(this); // execute the transition action
}
else {
r = Q_RET_NULL;
}
static_cast<void>(qs_id); // unused parameter (if Q_SPY not defined)
return r;
}
//****************************************************************************
/// @description
/// Tests if a state machine derived from QMsm is-in a given state.
///
/// @note
/// For a MSM, to "be-in" a state means also to "be-in" a superstate of
/// of the state.
///
/// @param[in] st pointer to the QMState object that corresponds to the
/// tested state.
/// @returns
/// 'true' if the MSM is in the \c st and 'false' otherwise
///
bool QMsm::isInState(QMState const * const st) const noexcept {
bool inState = false; // assume that this MSM is not in 'state'
for (QMState const *s = m_state.obj;
s != nullptr;
s = s->superstate)
{
if (s == st) {
inState = true; // match found, return 'true'
break;
}
}
return inState;
}
//****************************************************************************
///
/// @description
/// Finds the child state of the given @c parent, such that this child state
/// is an ancestor of the currently active state. The main purpose of this
/// function is to support **shallow history** transitions in state machines
/// derived from QMsm.
///
/// @param[in] parent pointer to the state-handler object
///
/// @returns
/// the child of a given @c parent state, which is an ancestor of the
/// currently active state. For the corner case when the currently active
/// state is the given @c parent state, function returns the @c parent state.
///
QMState const *QMsm::childStateObj(QMState const * const parent)
const noexcept
{
QMState const *child = m_state.obj;
bool isFound = false; // start with the child not found
for (QMState const *s = m_state.obj;
s != nullptr;
s = s->superstate)
{
if (s == parent) {
isFound = true; // child is found
break;
}
else {
child = s;
}
}
/// @post the child must be found
Q_ENSURE_ID(810, isFound);
#ifdef Q_NASSERT
// avoid compiler warning about unused variable
static_cast<void>(isFound);
#endif
return child; // return the child
}
} // namespace QP
| 35.415385 | 79 | 0.568346 | [
"object"
] |
909ec60e11ddfe6c38c8fd9626b1f116f83abf8c | 9,176 | hpp | C++ | backend/hdf5/h5x/H5Group.hpp | gicmo/nix | 17a5b90e6c12a22e921c181b79eb2a3db1bf61af | [
"BSD-3-Clause"
] | 1 | 2019-08-17T21:19:13.000Z | 2019-08-17T21:19:13.000Z | backend/hdf5/h5x/H5Group.hpp | tapaswenipathak/nix | 4565c2d7b363f27cac88932b35c085ee8fe975a1 | [
"BSD-3-Clause"
] | 2 | 2017-05-30T21:35:54.000Z | 2017-06-01T10:53:23.000Z | backend/hdf5/h5x/H5Group.hpp | gicmo/nix | 17a5b90e6c12a22e921c181b79eb2a3db1bf61af | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef NIX_GROUP_H
#define NIX_GROUP_H
#include "LocID.hpp"
#include "H5DataSet.hpp"
#include "DataSpace.hpp"
#include <nix/Hydra.hpp>
#include <nix/Platform.hpp>
#include <nix/Compression.hpp>
#include <boost/optional.hpp>
#include <string>
#include <vector>
namespace nix {
namespace hdf5 {
struct optGroup;
/**
* TODO documentation
*/
class NIXAPI H5Group : public LocID {
public:
H5Group();
H5Group(hid_t hid);
H5Group(hid_t hid, bool is_copy) : LocID(hid, is_copy) { }
H5Group(const H5Group &other);
bool hasObject(const std::string &path) const;
ndsize_t objectCount() const;
std::string objectName(ndsize_t index) const;
bool hasData(const std::string &name) const;
DataSet createData(const std::string &name, const h5x::DataType &fileType,
const NDSize &size, const Compression &compression = Compression::Auto,
const NDSize &maxsize = {}, NDSize chunks = {},
bool maxSizeUnlimited = true, bool guessChunks = true) const;
DataSet openData(const std::string &name) const;
void removeData(const std::string &name);
template<typename T>
void setData(const std::string &name, const T &value, const Compression &compression = Compression::Auto);
template<typename T>
bool getData(const std::string &name, T &value) const;
bool hasGroup(const std::string &name) const;
/**
* @brief Open and eventually create a group with the given name
* inside this group. If creation is not allowed (bool
* param is "false") and the group does not exist an error
* is thrown.
*
* @param name The name of the group to create.
* @param create Whether to create the group if it does not yet exist
*
* @return The opened group.
*/
H5Group openGroup(const std::string &name, bool create = true) const;
/**
* @brief Create an {@link optGroup} functor that can be used to
* open and eventually create an optional group inside this
* group.
*
* @param name The name of the group to create.
*
* @return The opened group.
*/
optGroup openOptGroup(const std::string &name);
void removeGroup(const std::string &name);
void renameGroup(const std::string &old_name, const std::string &new_name);
/**
* @brief Look for the first sub-group in the group with the given
* attribute that is set to the given string value and return it
* if found. Return empty optional if not found.
*
* @param attribute The name of the attribute to search.
* @param value The value of the attribute to search.
*
* @return The name of the first group object found.
*/
boost::optional<H5Group> findGroupByAttribute(const std::string &attribute, const std::string &value) const;
/**
* @brief Look for the first sub-data in the group with the given
* attribute that is set to the given string value and return it
* if found. Return empty optional if not found.
*
* @param attribute The name of the attribute to search.
* @param value The value of the attribute to search.
*
* @return The name of the first dataset object found.
*/
boost::optional<DataSet> findDataByAttribute(const std::string &attribute, const std::string &value) const;
/**
* @brief Look for the first sub-data in the group with the given
* name (value). If none cannot be found then search for an attribute that
* is set to the given string value and return that if found.
* Returns an empty optional otherwise.
*
* @param attribute The name of the attribute to search.
* @param value The name of the H5Group or the value of the attribute to look for.
*
* @return Optional containing the located H5Group or empty optional otherwise.
*/
boost::optional<H5Group> findGroupByNameOrAttribute(std::string const &attribute, std::string const &value) const;
/**
* @brief Look for the first sub-data in the group with the given
* name (value). If none cannot be found then search for an attribute that
* is set to the given string value and return that if found.
* Returns an empty optional otherwise.
*
* @param attribute The name of the attribute to search.
* @param value The name of the H5Group or the value of the attribute to look for.
*
* @return Optional containing the located Dataset or empty optional otherwise.
*/
boost::optional<DataSet> findDataByNameOrAttribute(std::string const &attribute, std::string const &value) const;
/**
* @brief Create a new hard link with the given name inside this group,
* that points to the target group.
*
* @param target The target of the link to create.
* @param linkname The name of the link to create.
*
* @return The linked group.
*/
H5Group createLink(const H5Group &target, const std::string &link_name);
/**
* @brief Renames all links of the object defined by the old name.
*
* This method will only change the links where the last part of the path
* is the old name.
*
* @param old_name The old name of the object
* @param new_name The new name of the object
*
* @return True if all links where changed successfully.
*/
bool renameAllLinks(const std::string &old_name, const std::string &new_name);
/**
* @brief Removes all links to the object defined by the given name.
*
* @param name The name of the object to remove.
*
* @return True if all links were deleted.
*/
bool removeAllLinks(const std::string &name);
H5Group &operator=(const H5Group &other) {
H5Object::operator=(other);
return *this;
}
virtual ~H5Group();
private:
bool objectOfType(const std::string &name, H5O_type_t type) const;
}; // group H5Group
//template functions
template<typename T>
void H5Group::setData(const std::string &name, const T &value, const Compression &compression)
{
const Hydra<const T> hydra(value);
DataType dtype = hydra.element_data_type();
NDSize shape = hydra.shape();
DataSet ds;
if (!hasData(name)) {
h5x::DataType fileType = data_type_to_h5_filetype(dtype);
ds = createData(name, fileType, shape, compression);
} else {
ds = openData(name);
ds.setExtent(shape);
}
h5x::DataType memType = data_type_to_h5_memtype(dtype);
DataSpace fileSpace, memSpace;
std::tie(memSpace, fileSpace) = ds.offsetCount2DataSpaces(shape);
const void *data = hydra.data();
if (dtype == DataType::String) {
StringReader reader(shape, data);
ds.write(*reader, memType, memSpace, fileSpace);
} else {
ds.write(data, memType, memSpace, fileSpace);
}
}
template<typename T>
bool H5Group::getData(const std::string &name, T &value) const
{
if (!hasData(name)) {
return false;
}
Hydra<T> hydra(value);
DataSet ds = openData(name);
DataType dtype = hydra.element_data_type();
h5x::DataType memType = data_type_to_h5_memtype(dtype);
NDSize shape = ds.size();
hydra.resize(shape);
DataSpace fileSpace, memSpace;
std::tie(memSpace, fileSpace) = ds.offsetCount2DataSpaces(shape);
void *data = hydra.data();
if (dtype == DataType::String) {
StringWriter writer(shape, data);
ds.read(*writer, memType, memSpace, fileSpace);
writer.finish();
ds.vlenReclaim(memType.h5id(), *writer, &memSpace);
} else {
ds.read(data, memType, memSpace, fileSpace);
}
return true;
}
/**
* Helper struct that works as a functor like {@link H5Group::openGroup}:
*
* Open and optionally create a group with the given name inside
* this group. If creation is not allowed (bool param is "false") and
* the group does not exist an error is thrown. If creation is not
* allowed (bool param is "false") and the group does not exist an
* unset optional is returned.
*/
struct NIXAPI optGroup {
mutable boost::optional<H5Group> g;
H5Group parent;
std::string g_name;
public:
optGroup(const H5Group &parent, const std::string &g_name);
optGroup(){};
/**
* @brief Open and optionally create a group with the given name
* inside this group. If creation is not allowed (bool
* param is "false") and the group does not exist an unset
* optional is returned.
*
* @param create Whether to create the group if it does not yet exist
*
* @return An optional with the opened group or unset.
*/
boost::optional<H5Group> operator() (bool create = false) const;
};
} // namespace hdf5
} // namespace nix
#endif /* NIX_GROUP_H */
| 31.317406 | 118 | 0.656713 | [
"object",
"shape",
"vector"
] |
90a22eaeb72ca83261aef0a0c6a9ca847e1b7557 | 1,596 | cpp | C++ | Codeforces 1183D.cpp | Jvillegasd/Codeforces | ffdd2d5db1dabc7ff76f8f92270c79233a77b933 | [
"MIT"
] | null | null | null | Codeforces 1183D.cpp | Jvillegasd/Codeforces | ffdd2d5db1dabc7ff76f8f92270c79233a77b933 | [
"MIT"
] | null | null | null | Codeforces 1183D.cpp | Jvillegasd/Codeforces | ffdd2d5db1dabc7ff76f8f92270c79233a77b933 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define pb push_back
#define pf push_front
#define pob pop_back
#define fp first
#define sp second
#define mp make_pair
#define ins insert
#define uEdge(u, v) g[u].pb(v), g[v].pb(u)
#define uwEdge(u, v, w) g[u].pb({v, w}), g[v].pb({u, w})
#define dEdge(u, v) g[u].pb(v)
#define dwEdge(u, v, w) g[u].pb({v, w})
#define BOOST ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define minHeap int, vector<int>, greater<int>
using namespace std;
typedef long long int lli;
typedef pair<int, int> pii;
vector<int> g[0];
lli gcd(lli a, lli b){
if(b == 0) return a;
a%=b;
return gcd(b, a);
}
lli lcm(lli a, lli b){
return (a*b)/gcd(a, b);
}
int binsearch(int n, lli arr[], lli sum){
int l = 0, r = n-1, mid;
while(l<=r){
mid = (l+r)/2;
if(arr[mid]==sum) return mid;
if(arr[mid]<sum) l = mid+1;
else r = mid-1;
}
return -1;
}
bool cmp(const pii &a, const pii &b){
return a.sp > b.sp;
}
int main(){
int q, n, ai, cnt;
lli ans;
scanf("%d", &q);
for(int i = 0; i < q; i++){
scanf("%d", &n);
map<int, int> m;
vector<pii> v;
ans = 0;
for(int j = 0; j < n; j++) scanf("%d", &ai), m[ai]++;
for(auto &it : m) v.pb(it);
sort(v.begin(), v.end(), cmp);
ans+=v[0].sp;
cnt = v[0].sp;
for(int j = 1; j < v.size(); j++){
cnt = max(min(cnt-1, v[j].sp), 0);
ans+=cnt;
}
printf("%lld\n", ans);
}
return 0;
}
| 23.470588 | 68 | 0.485589 | [
"vector"
] |
90aa92c586fb3b1323b8ccf1e14b85c087764c03 | 5,030 | cc | C++ | src/Molecule_Lib/smiles_test.cc | IanAWatson/LillyMol-4.0-Bazel | f38f23a919c622c31280222f8a90e6ab7d871b93 | [
"Apache-2.0"
] | 6 | 2020-08-17T15:02:14.000Z | 2022-01-21T19:27:56.000Z | src/Molecule_Lib/smiles_test.cc | IanAWatson/LillyMol-4.0-Bazel | f38f23a919c622c31280222f8a90e6ab7d871b93 | [
"Apache-2.0"
] | null | null | null | src/Molecule_Lib/smiles_test.cc | IanAWatson/LillyMol-4.0-Bazel | f38f23a919c622c31280222f8a90e6ab7d871b93 | [
"Apache-2.0"
] | null | null | null | // Tests for smiles reading and generation
#include "googlemock/include/gmock/gmock.h"
#include "googletest/include/gtest/gtest.h"
#include "coordinate_box.h"
#include "smiles.h"
namespace {
using testing::ElementsAre;
using testing::FloatNear;
// For tests that need an input smiles and an expected output.
struct SmilesAndExpected {
IWString input_smiles;
IWString expected_smiles;
};
// For tests that need an input, a parameter to set, and an expected output.
struct SmilesAndParam {
IWString input_smiles;
int int_param;
IWString expected_smiles;
};
class TestSmilesCharges : public testing::TestWithParam<SmilesAndParam> {
};
TEST_P(TestSmilesCharges, MultiplePlusCharges) {
const auto params = GetParam();
Molecule m;
ASSERT_TRUE(m.build_from_smiles(params.input_smiles));
set_write_formal_charge_as_consecutive_signs(params.int_param);
EXPECT_EQ(m.smiles(), params.expected_smiles);
}
INSTANTIATE_TEST_SUITE_P(TestMultipleCharges, TestSmilesCharges, testing::Values(
SmilesAndParam{"C", 0, "C"},
SmilesAndParam{"C", 1, "C"},
SmilesAndParam{"[Fe+++]", 1, "[Fe+++]"},
SmilesAndParam{"[Fe+++]", 0, "[Fe+3]"},
SmilesAndParam{"[P---]", 1, "[P---]"},
SmilesAndParam{"[P---]", 0, "[P-3]"},
SmilesAndParam{"[Zn--]", 1, "[Zn--]"},
SmilesAndParam{"[Zn--]", 0, "[Zn-2]"}
));
class TestAromaticSmiles : public testing::TestWithParam<SmilesAndExpected> {
public:
void SetUp() {
set_include_aromaticity_in_smiles(1);
}
};
TEST_P(TestAromaticSmiles, AromaticSmiles) {
const auto params = GetParam();
Molecule m;
ASSERT_TRUE(m.build_from_smiles(params.input_smiles));
EXPECT_EQ(m.smiles(), params.expected_smiles);
}
INSTANTIATE_TEST_SUITE_P(TestAromaticSmiles, TestAromaticSmiles, testing::Values(
SmilesAndExpected{"C", "C"},
SmilesAndExpected{"C1=CC=CC=C1", "c1ccccc1"}
));
class TestHOnAromaticNP: public testing::TestWithParam<SmilesAndParam> {
};
TEST_P(TestHOnAromaticNP, TestHOnAromaticNP) {
const auto params = GetParam();
Molecule m;
ASSERT_TRUE(m.build_from_smiles(params.input_smiles));
set_include_implicit_hydrogens_on_aromatic_n_and_p(params.int_param);
EXPECT_EQ(m.unique_smiles(), params.expected_smiles);
}
INSTANTIATE_TEST_SUITE_P(TestHOnAromaticNP, TestHOnAromaticNP, testing::Values(
SmilesAndParam{"C", 1, "C"},
SmilesAndParam{"C1=CC=CN1", 1, "[nH]1cccc1"},
SmilesAndParam{"C1=CC=CN1", 0, "n1cccc1"}
));
class TestAddHToIsotopes : public testing::TestWithParam<SmilesAndParam> {
};
TEST_P(TestAddHToIsotopes, TestAddHToIsotopes) {
const auto params = GetParam();
set_unset_implicit_hydrogens_known_if_possible(params.int_param);
Molecule m;
ASSERT_TRUE(m.build_from_smiles(params.input_smiles));
EXPECT_EQ(m.unique_smiles(), params.expected_smiles);
}
INSTANTIATE_TEST_SUITE_P(TestAddHToIsotopes, TestAddHToIsotopes, testing::Values(
SmilesAndParam{"C", 1, "C"},
SmilesAndParam{"[2C]", 1, "[2C]"},
SmilesAndParam{"[2C]C", 1, "[2C]C"},
SmilesAndParam{"C[2C]C", 1, "C[2C]C"}
//SmilesAndParam{"[9C]1=CC=CC=C1", 1, "[9cH]1ccccc1"} not sure why this does not work, investigate.
));
class TestBoxedCoordinates : public testing::Test {
void SetUp() {
set_append_coordinate_box_after_each_atom(1);
}
void TearDown() {
set_append_coordinate_box_after_each_atom(0);
}
};
TEST_F(TestBoxedCoordinates, TestBoxedCoordinates0) {
const_IWSubstring smiles("C{{B0:0}}");
Molecule m;
ASSERT_TRUE(m.build_from_smiles(smiles));
EXPECT_EQ(m.x(0), 0.0f);
EXPECT_EQ(m.y(0), 0.0f);
EXPECT_EQ(m.z(0), 0.0f);
}
TEST_F(TestBoxedCoordinates, TestBoxedCoordinates1) {
Coordinates coords(1.0f, 2.0f, 0.5f);
coordinate_box::ConcentricBox box;
const coordinate_box::LayerPosition layer_position = box.Position(coords);
IWString smiles("CC");
smiles << "{{B" << layer_position << "}}";
constexpr float kAbsDiff = 0.001;
Molecule m;
ASSERT_TRUE(m.build_from_smiles(smiles));
EXPECT_THAT(m.atom(1).ToResizableArray(),
ElementsAre(FloatNear(coords.x(), kAbsDiff),
FloatNear(coords.y(), kAbsDiff),
FloatNear(coords.z(), kAbsDiff)));
}
TEST_F(TestBoxedCoordinates, TestBoxedCoordinates2) {
constexpr int matoms = 10;
std::vector<Coordinates> coords(matoms);
for (int i = 0; i < matoms; ++i) {
coords[i].setxyz(i, 2 * i, i + 8);
}
coordinate_box::ConcentricBox box;
IWString smiles;
for (int i = 0; i < matoms; ++i) {
smiles << 'C';
const coordinate_box::LayerPosition layer_position = box.Position(coords[i]);
smiles << "{{B" << layer_position << "}}";
}
Molecule m;
ASSERT_TRUE(m.build_from_smiles(smiles));
constexpr float kAbsDiff = 0.001;
ASSERT_EQ(m.natoms(), matoms);
for (int i = 0; i < matoms; ++i) {
EXPECT_THAT(m.atom(i).ToResizableArray(),
ElementsAre(FloatNear(coords[i].x(), kAbsDiff),
FloatNear(coords[i].y(), kAbsDiff),
FloatNear(coords[i].z(), kAbsDiff)));
}
}
} // namespace
| 29.075145 | 100 | 0.696024 | [
"vector"
] |
90afd9a76d72fdcd72e2381ee7be3c84854b7990 | 19,892 | cpp | C++ | 14_fullerror/syntax.cpp | AkiraHakuta/antlr4_TAPL | 0570528f0f223624efd2c4e6d8d0abd98dcaaa16 | [
"BSD-3-Clause"
] | null | null | null | 14_fullerror/syntax.cpp | AkiraHakuta/antlr4_TAPL | 0570528f0f223624efd2c4e6d8d0abd98dcaaa16 | [
"BSD-3-Clause"
] | null | null | null | 14_fullerror/syntax.cpp | AkiraHakuta/antlr4_TAPL | 0570528f0f223624efd2c4e6d8d0abd98dcaaa16 | [
"BSD-3-Clause"
] | null | null | null | #include "fullerror.h"
/* ------------------------ Context management ------------------------ */
vector<pair_sb> _context ={};
vector<pair_sb>* _context_ptr = &_context;
string index2name(int db_index){
int context_size = _context_ptr->size();
if (db_index < 0 || _context_ptr->size() - 1 < db_index){
cout << "Variable lookup failure: offset:" << db_index << "context size:" << context_size << endl;
exit(1);
}
return _context_ptr->at(_context_ptr->size() - db_index -1).first;
}
bool isnamebound(string v_str) {
bool result_b = false;
auto itr = _context_ptr->rbegin();
for(; itr != _context_ptr->rend(); ++itr) {
if (itr->first == v_str){
result_b = true;
break;
}
}
return result_b;
}
string pickfreshname(string v_str){
string result_str = v_str;
if (isnamebound(v_str))
result_str = pickfreshname(v_str + "'");
else{
_context.push_back(pair_sb(v_str, new Binding(NameBind)));
result_str = v_str;
}
return result_str;
}
int name2index(string var_str){
int index;
auto itr = _context_ptr->rbegin();
for(; itr != _context_ptr->rend(); ++itr) {
if (itr->first == var_str){
index = distance(_context_ptr->rbegin(), itr);
break;
}
}
if (itr == _context_ptr->rend()){
cout << "Identifier \'" << var_str << "\' is unbound" << endl;
exit(1);
}
return index;
}
/* ------------------------ class member functions ------------------------ */
string Term::getTerm_str() {
string result_str;
string ty_str;
string v_str;
Binding* binding;
switch (_t_name) {
case TmVar:
result_str = index2name(_db_index);
break;
case TmAbs:
ty_str =_ty->getTy_str();
v_str = pickfreshname(_var_str);
result_str = "(lambda " + v_str + ":" + ty_str + ". " + _term0->getTerm_str() + ")";
_context.pop_back();
break;
case TmApp:
result_str = "(" + _term0->getTerm_str() + " " + _term1->getTerm_str() + ")";
break;
case TmTrue:
result_str = "true";
break;
case TmFalse:
result_str = "false";
break;
case TmError:
result_str = "error";
break;
case TmIf:
result_str = "if " + _term0->getTerm_str() + " then " + _term1->getTerm_str()+ " else " + _term2->getTerm_str();
break;
case TmTry:
result_str = "try " + _term0->getTerm_str() + " with " + _term1->getTerm_str();
break;
}
return result_str;
}
string Ty::getTy_str() {
string result_str;
switch (_typ) {
case TyBool:
result_str = "Bool";
break;
case TyBot:
result_str = "Bot";
break;
case TyTop:
result_str = "Top";
break;
case TyArr:
result_str = "(" + _ty0->getTy_str() + " -> " + _ty1->getTy_str() + ")";
break;
case TyVar:
result_str = index2name(_db_index);
break;
}
return result_str;
}
string Binding::getBing_str() {
string result_str;
switch (_binding_name){
case NameBind:
result_str = "";
break;
case VarBind:
result_str = ":" + _ty->getTy_str();
break;
case TmAbbBind:
if (_ty->_typ == TyNone)
result_str = ":" + typeOf(_term)->getTy_str();
else
result_str = ":" + _ty->getTy_str();
break;
case TyVarBind:
result_str = "";
break;
case TyAbbBind:
result_str = ":: *";
break;
}
return result_str;
}
void showErrorMsg(Term* t, string msg) { cout << t->_info << + ": error: " + msg << endl; }
/************************** copy functions ******************************/
Term* copyTerm(Term* t){
Term* result_t;
int i;
switch (t->_t_name) {
case TmVar:
result_t = new Term(t->_t_name, t->_info, t->_db_index);
break;
case TmAbs:
result_t = new Term(t->_t_name, t->_info, t->_var_str, copyTy(t->_ty), copyTerm(t->_term0));
break;
case TmApp:
case TmTry:
result_t = new Term(t->_t_name, t->_info, copyTerm(t->_term0), copyTerm(t->_term1));
break;
case TmTrue:
case TmFalse:
result_t = new Term(t->_t_name, t->_info);
break;
case TmIf:
result_t = new Term(t->_t_name, t->_info, copyTerm(t->_term0), copyTerm(t->_term1), copyTerm(t->_term2));
break;
}
return result_t;
}
Ty* copyTy(Ty* ty){
Ty* result_ty;
switch (ty->_typ) {
case TyBool:
case TyBot:
case TyTop:
case TYNoRuleApplies:
result_ty = new Ty(ty->_typ);
break;
case TyArr:
result_ty = new Ty(TyArr, copyTy(ty->_ty0), copyTy(ty->_ty1));
break;
case TyVar:
result_ty = new Ty(TyVar, ty->_db_index);
break;
}
return result_ty;
}
Binding* copyBinding(Binding* b){
Binding* result_bind;
switch (b->_binding_name){
case NameBind:
case TyVarBind:
result_bind = new Binding(b->_binding_name);
break;
case VarBind:
case TyAbbBind:
result_bind = new Binding(b->_binding_name, copyTy(b->_ty));
break;
case TmAbbBind:
result_bind = new Binding(TmAbbBind, copyTerm(b->_term), copyTy(b->_ty));
break;
}
return result_bind;
}
/* ------------------------ Shifting ------------------------ */
Term* termShiftAbove(int d, int c, Term* t) {
Term* result_t;
t = copyTerm(t);
switch (t->_t_name) {
case TmVar:
if (t->_db_index >= c)
t->_db_index += d;
result_t = t;
break;
case TmAbs:
t->_term0 = termShiftAbove(d, c + 1, t->_term0);
t->_ty = typeShiftAbove(d, c, t->_ty);
result_t = t;
break;
case TmApp:
t->_term0 = termShiftAbove(d, c, t->_term0);
t->_term1 = termShiftAbove(d, c, t->_term1);
result_t = t;
break;
case TmTrue:
case TmFalse:
case TmError:
result_t = t;
break;
case TmIf:
t->_term0 = termShiftAbove(d, c, t->_term0);
t->_term1 = termShiftAbove(d, c, t->_term1);
t->_term2 = termShiftAbove(d, c, t->_term2);
result_t = t;
break;
case TmTry:
t->_term0 = termShiftAbove(d, c, t->_term0);
t->_term1 = termShiftAbove(d, c, t->_term1);
result_t = t;
break;
}
return result_t;
}
Term* termShift(int d, Term* t) { return termShiftAbove(d, 0, t); }
/* ------------------------ Substitution ------------------------ */
Term* termSubst(int var_num, Term* s_term, Term* t) {
Term* result_t;
Term *t0, *t1, *t2;
switch (t->_t_name) {
case TmVar:
if (t->_db_index == var_num){
result_t = termShift(t->_db_index, s_term);
}
else
result_t = new Term(TmVar, t->_info, t->_db_index);
break;
case TmAbs:
t0 = termSubst(var_num + 1, s_term, t->_term0);
result_t = new Term(TmAbs, t->_info, t->_var_str, t->_ty, t0);
break;
case TmApp:
t0 = termSubst(var_num, s_term, t->_term0);
t1 = termSubst(var_num, s_term, t->_term1);
result_t = new Term(TmApp, t->_info, t0, t1);
break;
case TmTrue:
case TmFalse:
case TmError:
result_t = new Term(t->_t_name, t->_info);
break;
case TmIf:
t0 = termSubst(var_num, s_term, t->_term0);
t1 = termSubst(var_num, s_term, t->_term1);
t2 = termSubst(var_num, s_term, t->_term2);
result_t = new Term(TmIf, t->_info, t0, t1, t2);
break;
case TmTry:
t0 = termSubst(var_num, s_term, t->_term0);
t1 = termSubst(var_num, s_term, t->_term1);
result_t = new Term(TmTry, t->_info, t0, t1);
break;
}
return result_t;
}
Term* termSubstTop(Term* s_term, Term* t) { return termShift(-1, termSubst(0, termShift(1, s_term), t));}
/* ------------------------ TYPING ------------------------ */
Ty* typeShiftAbove(int d, int c, Ty* ty) {
Ty* result_ty;
Ty* ty0;
int i;
switch (ty->_typ){
case TyArr:
result_ty = new Ty(TyArr, typeShiftAbove(d, c, ty->_ty0), typeShiftAbove(d, c, ty->_ty1));
break;
case TyBool:
case TyBot:
case TyTop:
result_ty = new Ty(ty->_typ);
break;
case TyVar:
if (ty->_db_index >= c)
result_ty = new Ty(TyVar, ty->_db_index + d);
else
result_ty = new Ty(TyVar, ty->_db_index);
break;
}
return result_ty;
}
Ty* typeShift(int d, Ty* ty){ return typeShiftAbove(d, 0, ty);}
Binding* bindingshift(int d, Binding* bind) {
Binding* result_bind;
Term* t;
switch (bind->_binding_name){
case NameBind:
case TyVarBind:
result_bind = new Binding(bind->_binding_name);
break;
case TmAbbBind:
t = termShift(d, bind->_term);
if (bind->_ty->_typ == TyNone)
result_bind = new Binding(TmAbbBind, t, new Ty(TyNone));
else{
result_bind = new Binding(TmAbbBind, t, typeShift(d, bind->_ty));
}
break;
case VarBind:
case TyAbbBind:
result_bind = new Binding(bind->_binding_name, typeShift(d, bind->_ty));
break;
}
return result_bind;
}
Binding* getbinding (int db_index){
int context_size = _context_ptr->size();
if (db_index < 0 || _context_ptr->size() - 1 < db_index){
cout << "getbinding :Variable lookup failure: offset:" << db_index << "context size:" << context_size << endl;
exit(1);
}
Binding* b = _context_ptr->at(_context_ptr->size() - db_index -1).second;
return bindingshift(db_index + 1, copyBinding(b));
}
Binding* evalbinding(Binding* b){
Binding* result_bind = b;
bool NoRuleApplies = false;
if (b->_binding_name == TmAbbBind){
b->_term = eval(b->_term, &NoRuleApplies);
result_bind = b;
}
return result_bind;
}
bool istyabb(int i){
bool result_b = false;
Binding* b = getbinding(i);
if (b->_binding_name == TyAbbBind)
result_b = true;
return result_b;
}
Ty* gettyabb(int i){
Ty* result_ty;
Binding* b = getbinding(i);
if (b->_binding_name == TyAbbBind)
result_ty = b->_ty;
else
result_ty = new Ty(TYNoRuleApplies);
return result_ty;
}
Ty* computety(Ty* ty){
Ty* result_ty;
if (ty->_typ == TyVar && istyabb(ty->_db_index))
result_ty = gettyabb(ty->_db_index);
else
result_ty = new Ty(TYNoRuleApplies);
return result_ty;
}
Ty* simplifyty(Ty* ty) {
Ty* ty1 = computety(ty);
if (ty1->_typ != TYNoRuleApplies)
return simplifyty(ty1);
else
return ty;
}
bool tyeqv (Ty* ty0, Ty* ty1) {
bool result_b = false;
Ty* tyS = simplifyty(ty0);
Ty* tyT = simplifyty(ty1);
if (tyS->_typ == TyBool && tyT->_typ == TyBool)
result_b = true;
else if (tyS->_typ == TyBot && tyT->_typ == TyBot)
result_b = true;
else if (tyS->_typ == TyArr && tyT->_typ == TyArr)
result_b = tyeqv (tyS->_ty0, tyT->_ty0) && tyeqv (tyS->_ty1, tyT->_ty1);
else if (tyS->_typ == TyTop && tyT->_typ == TyTop)
result_b = true;
else if (tyS->_typ == TyVar && istyabb(tyS->_db_index))
result_b = tyeqv(gettyabb(tyS->_db_index), tyT);
else if (tyT->_typ == TyVar && istyabb(tyT->_db_index))
result_b = tyeqv(tyS, gettyabb(tyT->_db_index));
else if (tyS->_typ == TyVar && tyT->_typ == TyVar)
result_b = (tyS->_db_index == tyT->_db_index);
return result_b;
}
bool subtype (Ty* ty0, Ty* ty1) {
bool result_b1 = false;
bool result_b2 = false;
result_b1 = tyeqv(ty0, ty1);
Ty* tyS = simplifyty(ty0);
Ty* tyT = simplifyty(ty1);
if (tyS->_typ == TyBot)
result_b2 = true;
else if (tyT->_typ == TyTop)
result_b2 = true;
else if (tyS->_typ == TyArr && tyT->_typ == TyArr)
result_b2 = subtype (tyS->_ty0, tyT->_ty0) && subtype (tyS->_ty1, tyT->_ty1);
else
result_b2 = false;
return result_b1 || result_b2;
}
Ty* meet (Ty* ty0, Ty* ty1);
Ty* join (Ty* ty0, Ty* ty1) {
Ty* result_ty;
if (subtype(ty0, ty1)){
result_ty = ty1;
}
else if (subtype(ty1, ty0)){
result_ty = ty0;
}
else {
Ty* tyS = simplifyty(ty0);
Ty* tyT = simplifyty(ty1);
if (tyS->_typ == TyArr && tyT->_typ == TyArr)
result_ty = new Ty(TyArr, meet(tyS->_ty0, tyT->_ty0), join(tyS->_ty1, tyT->_ty1));
else
result_ty = new Ty(TyTop);
}
return result_ty;
}
Ty* meet (Ty* ty0, Ty* ty1) {
Ty* result_ty;
if (subtype(ty0, ty1))
result_ty = ty0;
else if (subtype(ty1, ty0))
result_ty = ty1;
else {
Ty* tyS = simplifyty(ty0);
Ty* tyT = simplifyty(ty1);
if (tyS->_typ == TyArr && tyT->_typ == TyArr)
result_ty = new Ty(TyArr, join(tyS->_ty0, tyT->_ty0), meet(tyS->_ty1, tyT->_ty1));
else
result_ty = new Ty(TyBot);
}
return result_ty;
}
Ty* getTypeFromContext(Term* t, int db_index) {
Ty* result_ty;
Binding* bind = getbinding(db_index);
switch (bind->_binding_name){
case VarBind:
result_ty = bind->_ty;
break;
case TmAbbBind:
if (bind->_ty->_typ == TyNone){
showErrorMsg(t, "No type recorded for variable " + index2name(db_index));
exit(1);
}
result_ty = bind->_ty;
break;
default:
showErrorMsg(t, "getTypeFromContext: Wrong kind of binding for variable " + index2name(db_index));
exit(1);
}
return result_ty;
}
Ty* typeOf(Term* t) {
Ty* result_ty;
Binding* binding;
Ty *ty0, *ty1, *ty2, *tyT1, *tyTi;
int i, j;
switch (t->_t_name){
case TmVar:
result_ty = getTypeFromContext(t, t->_db_index);
break;
case TmAbs:
binding = new Binding(VarBind, t->_ty);
_context.push_back(pair_sb(t->_var_str, binding));
result_ty = new Ty(TyArr, t->_ty, typeShift(-1, typeOf(t->_term0)));
_context.pop_back();
break;
case TmApp:
ty1 = typeOf(t->_term1);
ty0 = simplifyty(typeOf(t->_term0));
if (ty0->_typ == TyArr)
if (subtype(ty1, ty0->_ty0))
result_ty = ty0->_ty1;
else{
showErrorMsg(t, "parameter type mismatch");
exit(1);
}
else if (ty0->_typ == TyBot)
result_ty = new Ty(TyBot);
else{
showErrorMsg(t, "arrow type expected");
exit(1);
}
break;
case TmTrue:
case TmFalse:
result_ty = new Ty(TyBool);
break;
case TmIf:
if (subtype(typeOf(t->_term0), new Ty(TyBool)))
result_ty = join(typeOf(t->_term1), typeOf(t->_term2));
else {
showErrorMsg(t, "guard of conditional not a boolean");
exit(1);
}
break;
case TmError:
result_ty = new Ty(TyBot);
break;
case TmTry:
result_ty = join(typeOf(t->_term0), typeOf(t->_term1));
break;
default:
break;
}
return result_ty;
}
Binding* checkbinding(Binding* b){
Binding* result_bind;
Ty* ty;
switch (b->_binding_name){
case NameBind:
case VarBind:
case TyAbbBind:
case TyVarBind:
result_bind = b;
break;
case TmAbbBind:
if (b->_ty->_typ == TyNone){
result_bind = new Binding(TmAbbBind, b->_term, typeOf(b->_term));
}
else{
ty = typeOf(b->_term);
if (tyeqv(ty, b->_ty))
result_bind = b;
else{
cout << "Type of binding does not match declared type" << endl;
exit(1);
}
}
break;
}
return result_bind;
}
/* ------------------------ EVALUATION ------------------------ */
bool isval(Term* t) {
bool result_b;
switch(t->_t_name){
case TmTrue:
case TmFalse:
case TmAbs:
result_b = true;
break;
default:
result_b = false;
break;
}
return result_b;
}
Term* eval1(Term* t, bool* NoRuleApplies){
Term* result_t;
Binding* b;
Term* t0;
int i;
switch(t->_t_name){
case TmIf:
if (t->_term0->_t_name == TmTrue)
result_t = t->_term1;
else if (t->_term0->_t_name == TmFalse)
result_t = t->_term2;
else if (t->_term0->_t_name == TmError)
result_t = t->_term0;
else{
t->_term0 = eval1(t->_term0, NoRuleApplies);
result_t = t;
}
break;
case TmVar:
b = getbinding(t->_db_index);
if(b->_binding_name == TmAbbBind)
result_t = b->_term;
else{
result_t = t;
*NoRuleApplies = true;
}
break;
case TmApp:
if (t->_term0->_t_name == TmError)
result_t = t->_term0;
else if (t->_term1->_t_name == TmError && isval(t->_term0))
result_t = t->_term1;
else if (t->_term0->_t_name == TmAbs && isval(t->_term1))
result_t = termSubstTop(t->_term1, t->_term0->_term0);
else if (isval(t->_term0)){
t->_term1 = eval1(t->_term1, NoRuleApplies);
result_t = t;
}
else {
t->_term0 = eval1(t->_term0, NoRuleApplies);
result_t = t;
}
break;
case TmTry:
if (isval(t->_term0))
result_t = t->_term0;
else if (t->_term0->_t_name == TmError)
result_t = t->_term1;
else {
t->_term0 = eval1(t->_term0, NoRuleApplies);
result_t = t;
}
break;
default:
result_t = t;
*NoRuleApplies = true;
break;
}
return result_t;
}
Term* eval(Term* t, bool* NoRuleApplies){
if (*NoRuleApplies)
return t;
else
return eval(eval1(t, NoRuleApplies), NoRuleApplies);
}
| 28.376605 | 126 | 0.489544 | [
"vector"
] |
90b07edc3785faa408039b0ac9328bb1b770d5e3 | 3,196 | cpp | C++ | answers/lintcode/Count of Smaller Number.cpp | FeiZhan/Algo-Collection | 708c4a38112e0b381864809788b9e44ac5ae4d05 | [
"MIT"
] | 3 | 2015-09-04T21:32:31.000Z | 2020-12-06T00:37:32.000Z | answers/lintcode/Count of Smaller Number.cpp | FeiZhan/Algo-Collection | 708c4a38112e0b381864809788b9e44ac5ae4d05 | [
"MIT"
] | null | null | null | answers/lintcode/Count of Smaller Number.cpp | FeiZhan/Algo-Collection | 708c4a38112e0b381864809788b9e44ac5ae4d05 | [
"MIT"
] | null | null | null | //@result TLE
class Solution {
public:
/**
* @param A: An integer array
* @return: The number of element in the array that
* are smaller that the given integer
*/
vector<int> countOfSmallerNumber(vector<int> &A, vector<int> &queries) {
// write your code here
SegmentTreeNode *root = new SegmentTreeNode(0, 2000);
for (size_t i = 0; i < A.size(); ++ i) {
root->add(A[i]);
}
vector<int> count_list;
for (size_t i = 0; i < queries.size(); ++ i) {
count_list.push_back(root->query(0, queries[i]));
}
return count_list;
}
class SegmentTreeNode {
public:
SegmentTreeNode(int l, int r) : min(l), max(r), value(0), left(NULL), right(NULL) {
if (min + 1 < max) {
int middle = (min + max) / 2;
left = new SegmentTreeNode(min, middle);
right = new SegmentTreeNode(middle, max);
}
}
int min;
int max;
int value;
SegmentTreeNode *left;
SegmentTreeNode *right;
void add(int num) {
if (num < min || num >= max) {
return;
}
//cout << "debug " << num << " (" << min << ", " << max << ")" << endl;
++ value;
if (left) {
left->add(num);
}
if (right) {
right->add(num);
}
}
int query(int l, int r) {
if (l <= min && r >= max) {
return value;
}
else {
return (left ? left->query(l, r) : 0) + (right ? right->query(l, r) : 0);
}
}
};
};
#include <iostream>
using namespace std;
class Solution {
public:
/**
* @param A: An integer array
* @return: The number of element in the array that
* are smaller that the given integer
*/
vector<int> countOfSmallerNumber(vector<int> &A, vector<int> &queries) {
// write your code here
vector<int> count_list;
sort(A.begin(), A.end());
for (size_t i = 0; i < queries.size(); ++ i) {
size_t left = 0;
size_t right = A.size() - 1;
bool flag = false;
while (left <= right && right < A.size()) {
size_t middle = (left + right) / 2;
if (A[middle] == queries[i]) {
if (0 == middle || A[middle - 1] != queries[i]) {
flag = true;
break;
}
else {
right = middle - 1;
}
}
else if (A[middle] > queries[i]) {
right = middle - 1;
}
else {
left = middle + 1;
}
}
size_t pos = (left + right) / 2 + ! flag;
count_list.push_back(pos);
}
return count_list;
}
};
int main() {
// your code goes here
Solution s;
vector<int> ans = s.countOfSmallerNumber(A, queries);
return 0;
} | 29.592593 | 91 | 0.428035 | [
"vector"
] |
90b2701e0d2e800a22b9192869b9c7fa94763cca | 6,467 | hpp | C++ | DT3Core/Resources/Importers/ImporterGeometryTWM.hpp | nemerle/DT3 | 801615d507eda9764662f3a34339aa676170e93a | [
"MIT"
] | 3 | 2016-01-27T13:17:18.000Z | 2019-03-19T09:18:25.000Z | DT3Core/Resources/Importers/ImporterGeometryTWM.hpp | nemerle/DT3 | 801615d507eda9764662f3a34339aa676170e93a | [
"MIT"
] | 1 | 2016-01-28T14:39:49.000Z | 2016-01-28T22:12:07.000Z | DT3Core/Resources/Importers/ImporterGeometryTWM.hpp | adderly/DT3 | e2605be091ec903d3582e182313837cbaf790857 | [
"MIT"
] | 3 | 2016-01-25T16:44:51.000Z | 2021-01-29T19:59:45.000Z | #pragma once
#ifndef DT3_IMPORTERGEOMETRYTWM
#define DT3_IMPORTERGEOMETRYTWM
//==============================================================================
///
/// File: ImporterGeometryTWM.hpp
///
/// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "DT3Core/Resources/Importers/ImporterGeometry.hpp"
#include "DT3Core/Types/Math/Vector2.hpp"
#include "DT3Core/Types/Math/Vector3.hpp"
#include "DT3Core/Types/Math/Weights.hpp"
#include "DT3Core/Types/Math/Triangle.hpp"
#include "DT3Core/Types/Math/Matrix4.hpp"
#include "DT3Core/Types/Animation/SkeletonJoint.hpp"
#include "DT3Core/Types/FileBuffer/FilePath.hpp"
#include "DT3Core/Types/Graphics/Mesh.hpp"
#include <vector>
#include <list>
//==============================================================================
//==============================================================================
namespace DT3 {
//==============================================================================
/// Forward declarations
//==============================================================================
class BinaryFileStream;
//==============================================================================
/// Class
//==============================================================================
class ImporterGeometryTWM: public ImporterGeometry {
public:
DEFINE_TYPE(ImporterGeometryTWM,ImporterGeometry)
DEFINE_CREATE
ImporterGeometryTWM (void);
private:
ImporterGeometryTWM (const ImporterGeometryTWM &rhs);
ImporterGeometryTWM & operator = (const ImporterGeometryTWM &rhs);
public:
virtual ~ImporterGeometryTWM(void);
public:
/// Imports an geometry into an GeometryResource
/// \param target object to import geometry into
/// \param args arguments to importer
/// \retrun error code
virtual DTerr import (GeometryResource *target, std::string args);
private:
enum {
MAGIC = 0x5E11E70D,
FILE = 0,
MESHES = 1,
MESHES_MESH = 2,
MESHES_MESH_NAME = 3,
MESHES_MESH_POSITIONS = 4,
MESHES_MESH_NORMALS = 5,
MESHES_MESH_UV_SETS = 6,
MESHES_MESH_UVS = 7,
MESHES_MESH_SKINNING = 8,
MESHES_MESH_SKINNING_JOINTS = 9,
MESHES_MESH_SKINNING_INFLUENCES = 10,
MESHES_MESH_INDICES = 12,
SKELETON = 13
};
//
// Meshes
//
struct UVset {
std::vector<Vector2> _uvs;
};
struct MeshData {
std::string _name;
std::vector<Vector3> _vertices;
std::vector<Vector3> _normals;
std::vector<UVset> _uv_sets;
std::vector<std::string> _joint_names;
std::vector<Weights> _weights;
std::vector<Triangle> _indices;
};
std::vector<MeshData> _meshes;
//
// Skeleton
//
struct Joint {
std::vector<Joint> _children;
std::string _name;
Matrix4 _local_transform;
Matrix4 _world_transform;
};
struct SkeletonData {
std::vector<Joint> _joints;
};
SkeletonData _skeleton;
// Some book keeping
DTuint _normals_count;
DTuint _uv_set_0_count;
DTuint _uv_set_1_count;
DTuint _weights_count;
void read_mesh_name (BinaryFileStream &file, DTuint remaining_size, std::string &name);
void read_mesh_positions (BinaryFileStream &file, DTuint remaining_size, std::vector<Vector3> &positions);
void read_mesh_normals (BinaryFileStream &file, DTuint remaining_size, std::vector<Vector3> &normals);
void read_mesh_uvs (BinaryFileStream &file, DTuint remaining_size, std::vector<Vector2> &uvs);
void read_mesh_uv_sets (BinaryFileStream &file, DTuint remaining_size, std::vector<UVset> &uvs_sets);
void read_mesh_joints (BinaryFileStream &file, DTuint remaining_size, std::vector<std::string> &joints);
void read_mesh_influences(BinaryFileStream &file, DTuint remaining_size, std::vector<Weights> &weights);
void read_mesh_skinning (BinaryFileStream &file, DTuint remaining_size, std::vector<std::string> &joints, std::vector<Weights> &weights);
void read_mesh_indices (BinaryFileStream &file, DTuint remaining_size, std::vector<Triangle> &indices);
void read_mesh (BinaryFileStream &file, DTuint remaining_size, MeshData &mesh);
void read_meshes (BinaryFileStream &file, DTuint remaining_size, std::vector<MeshData> &meshes);
void read_skeleton_joints(BinaryFileStream &file, DTuint remaining_size, std::vector<Joint> &joints);
void read_skeleton (BinaryFileStream &file, DTuint remaining_size, SkeletonData &skeleton);
void read_file (BinaryFileStream &file, DTuint remaining_size);
// Recursive function to build the skeleton
void build_skeleton (std::vector<std::string> &joint_names, std::vector<Joint> &src_joints, std::vector<SkeletonJoint> &dst_joints);
};
//==============================================================================
//==============================================================================
} // DT3
#endif
| 40.41875 | 157 | 0.487398 | [
"mesh",
"geometry",
"object",
"vector"
] |
ff96de042eacff7cee1484f9c3e7f2f1210aa2aa | 4,189 | cpp | C++ | src/mainlib/stream/mp3/huffman/HuffmanParser.cpp | priera/aixa | faa5d9cd99fcec47703f2b82a64b465dbc4fd3bc | [
"MIT"
] | null | null | null | src/mainlib/stream/mp3/huffman/HuffmanParser.cpp | priera/aixa | faa5d9cd99fcec47703f2b82a64b465dbc4fd3bc | [
"MIT"
] | 3 | 2021-05-12T08:45:11.000Z | 2021-05-12T09:09:25.000Z | src/mainlib/stream/mp3/huffman/HuffmanParser.cpp | priera/aixa | faa5d9cd99fcec47703f2b82a64b465dbc4fd3bc | [
"MIT"
] | null | null | null | #include "HuffmanParser.h"
HuffmanParser::HuffmanParser(const std::filesystem::path& filePath) : f(filePath) {
if (!f) {
throw std::runtime_error("Could not find huffman tables file");
}
}
HuffmanSet* HuffmanParser::build() {
std::vector<std::unique_ptr<Huffman>> tables(Huffman::NR_HUFFMAN_TABLES);
Huffman::Tree lastTree;
bool fileProcessed = false;
while (!(fileProcessed || f.eof())) {
std::string line;
std::getline(f, line);
if (line.size() <= 1 || line[0] == '#') continue;
bool storeTable = false;
auto tokenEnd = line.find_first_of(" \n\r");
auto token = line.substr(1, tokenEnd - 1);
if (token == "table") {
lastTree = decodeTableHeader(line.substr(tokenEnd));
} else if (token == "treedata") {
buildTree(lastTree);
storeTable = true;
} else if (token == "reference") {
buildReferenceTree(tables, lastTree, line.substr((tokenEnd)));
storeTable = true;
} else if (token == "end") {
fileProcessed = true;
}
if (storeTable) {
tables[lastTree.id] = std::make_unique<Huffman>(lastTree);
lastTree = Huffman::Tree();
}
}
if (!fileProcessed) throw std::runtime_error("Invalid huffman file");
return new HuffmanSet(tables);
}
Huffman::Tree HuffmanParser::decodeTableHeader(const std::string& def) {
std::stringstream s(def);
Huffman::Tree t;
s >> t.id >> t.length >> t.xLength >> t.yLength >> t.linbits;
return t;
}
void HuffmanParser::buildTree(Huffman::Tree& tree) {
auto serializedTree = extractSerializedTree();
if (!serializedTree.empty()) {
tree.root = std::make_shared<Huffman::Node>();
buildNodeOfIndex(*tree.root, 0, serializedTree);
}
}
std::vector<Huffman::Symbols> HuffmanParser::extractSerializedTree() {
std::string line;
std::getline(f, line);
std::vector<Huffman::Symbols> serializedTree;
unsigned int nodesCaptured;
while (line.size() > 1) {
std::istringstream s(line);
auto& hexStream = s >> std::hex;
nodesCaptured = 0;
while (hexStream && nodesCaptured < MAX_NODES_PER_LINE) {
int s1, s2;
hexStream >> s1 >> s2;
serializedTree.emplace_back(s1, s2);
nodesCaptured++;
}
std::getline(f, line);
}
return serializedTree;
}
void HuffmanParser::buildNodeOfIndex(Huffman::Node& parent, std::size_t i,
const std::vector<Huffman::Symbols>& serializedTree) {
auto chooseValue = [](const Huffman::Symbols& p, bool ones) -> unsigned char {
return (ones) ? p.second : p.first;
};
auto computeNextOffset = [&serializedTree, &chooseValue](std::size_t initial, bool ones) -> std::size_t {
auto ret = initial;
auto value = chooseValue(serializedTree[ret], ones);
while (value >= MAX_OFFSET) {
ret += value;
value = chooseValue(serializedTree[ret], ones);
}
ret += value;
return ret;
};
const auto& entry = serializedTree[i];
if (entry.first == 0) {
unsigned char s1, s2;
s1 = entry.second >> 4;
s2 = entry.second & 0x0F;
parent.symbols = std::make_pair(s1, s2);
} else {
parent.left = std::make_unique<Huffman::Node>();
parent.right = std::make_unique<Huffman::Node>();
auto zeroesOffset = computeNextOffset(i, false);
auto onesOffset = computeNextOffset(i, true);
buildNodeOfIndex(*parent.left, zeroesOffset, serializedTree);
buildNodeOfIndex(*parent.right, onesOffset, serializedTree);
}
}
void HuffmanParser::buildReferenceTree(const std::vector<std::unique_ptr<Huffman>>& tables,
Huffman::Tree& tree, const std::string& referenceId) {
std::stringstream s(referenceId);
std::size_t id;
s >> id;
auto referenced = tables[id]->getTable().root;
if (!referenced) {
throw std::runtime_error("Referencing wrong table");
}
tree.root = referenced;
}
| 31.02963 | 109 | 0.593459 | [
"vector"
] |
ff996e127b7d9ca9eb64491e9bcae9dd2571d6fa | 10,437 | cpp | C++ | Helios/HeliosConfig/Source/HeliosConfig/Private/HeliosConfigBPLibrary.cpp | HeliosInteractive/UE4-HeliosConfig | 008a5f80cf281b6ad956b1a1dca3422d73fdb555 | [
"MIT"
] | 1 | 2018-05-31T16:51:06.000Z | 2018-05-31T16:51:06.000Z | Helios/HeliosConfig/Source/HeliosConfig/Private/HeliosConfigBPLibrary.cpp | HeliosInteractive/UE4-HeliosConfig | 008a5f80cf281b6ad956b1a1dca3422d73fdb555 | [
"MIT"
] | null | null | null | Helios/HeliosConfig/Source/HeliosConfig/Private/HeliosConfigBPLibrary.cpp | HeliosInteractive/UE4-HeliosConfig | 008a5f80cf281b6ad956b1a1dca3422d73fdb555 | [
"MIT"
] | 1 | 2020-02-21T00:18:09.000Z | 2020-02-21T00:18:09.000Z | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "HeliosConfigPrivatePCH.h"
#include "HeliosConfigBPLibrary.h"
bool UHeliosConfigBPLibrary::bInitialized = false;
TSharedPtr<FJsonObject> UHeliosConfigBPLibrary::JsonObject = MakeShareable(new FJsonObject);
FString UHeliosConfigBPLibrary::GetString(const FString& VariableName, FString DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
FString TheValue = DefaultValue;
if (!JsonObject->TryGetStringField(VariableName, TheValue))
{
SetString(VariableName, DefaultValue);
}
return TheValue;
}
void UHeliosConfigBPLibrary::SetString(const FString& VariableName, const FString& Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
JsonObject->SetStringField(VariableName, Value);
}
int32 UHeliosConfigBPLibrary::GetInt(const FString& VariableName, int32 DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
int32 TheValue = DefaultValue;
if (!JsonObject->TryGetNumberField(VariableName, TheValue))
{
SetInt(VariableName, DefaultValue);
}
return TheValue;
}
void UHeliosConfigBPLibrary::SetInt(const FString& VariableName, const int32 Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
JsonObject->SetNumberField(VariableName, Value);
}
float UHeliosConfigBPLibrary::GetFloat(const FString& VariableName, float DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
double TheValue = DefaultValue;
if (!JsonObject->TryGetNumberField(VariableName, TheValue))
{
SetFloat(VariableName, DefaultValue);
}
return (float)TheValue;
}
void UHeliosConfigBPLibrary::SetFloat(const FString& VariableName, const float Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
JsonObject->SetNumberField(VariableName, Value);
}
FLinearColor UHeliosConfigBPLibrary::GetColor(const FString& VariableName, FLinearColor DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
const TArray<TSharedPtr<FJsonValue>>* rgb;
if (!JsonObject->TryGetArrayField(VariableName, rgb))
{
SetColor(VariableName, DefaultValue);
return DefaultValue;
}
bool bHasAlpha = (rgb->Num() > 3); // if rgb contains more than three variables it has an alpha value set.
FLinearColor color;
if (bHasAlpha)
{
color = FLinearColor((float)rgb[0][0].Get()->AsNumber(), (float)rgb[0][1].Get()->AsNumber(), (float)rgb[0][2].Get()->AsNumber(), (float)rgb[0][3].Get()->AsNumber());
}
else
{
color = FLinearColor((float)rgb[0][0].Get()->AsNumber(), (float)rgb[0][1].Get()->AsNumber(), (float)rgb[0][2].Get()->AsNumber(), 1);
}
return color;
}
void UHeliosConfigBPLibrary::SetColor(const FString & VariableName, FLinearColor Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
TArray<TSharedPtr<FJsonValue>> ColorValues;
ColorValues.Add(MakeShareable(new FJsonValueNumber(Value.R)));
ColorValues.Add(MakeShareable(new FJsonValueNumber(Value.G)));
ColorValues.Add(MakeShareable(new FJsonValueNumber(Value.B)));
if (Value.A < 1)
{
// alpha defaults to one on GetColor, so only write out alpha if the value is != 1
ColorValues.Add(MakeShareable(new FJsonValueNumber(Value.A)));
}
JsonObject->SetArrayField(VariableName, ColorValues);
}
bool UHeliosConfigBPLibrary::GetBool(const FString& VariableName, bool DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
bool TheValue = DefaultValue;
if (!JsonObject->TryGetBoolField(VariableName, TheValue))
{
SetBool(VariableName, DefaultValue);
}
return TheValue;
}
void UHeliosConfigBPLibrary::SetBool(const FString& VariableName, bool Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
JsonObject->SetBoolField(VariableName, Value);
}
FVector UHeliosConfigBPLibrary::GetVector(const FString & VariableName, FVector DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
FVector Vector = DefaultValue;
const TArray<TSharedPtr<FJsonValue>> *VectorValues;
if (!JsonObject->TryGetArrayField(VariableName, VectorValues))
{
SetVector(VariableName, DefaultValue);
return DefaultValue;
}
return FVector((float)(*VectorValues)[0]->AsNumber(), (float)(*VectorValues)[1]->AsNumber(), (float)(*VectorValues)[2]->AsNumber());
}
void UHeliosConfigBPLibrary::SetVector(const FString & VariableName, FVector Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
TArray<TSharedPtr<FJsonValue>> VectorValues;
VectorValues.Add(MakeShareable(new FJsonValueNumber(Value.X)));
VectorValues.Add(MakeShareable(new FJsonValueNumber(Value.Y)));
VectorValues.Add(MakeShareable(new FJsonValueNumber(Value.Z)));
JsonObject->SetArrayField(VariableName, VectorValues);
}
FVector2D UHeliosConfigBPLibrary::GetVector2D(const FString & VariableName, FVector2D DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
FVector2D Vector = DefaultValue;
const TArray<TSharedPtr<FJsonValue>> *VectorValues;
if (!JsonObject->TryGetArrayField(VariableName, VectorValues))
{
SetVector2D(VariableName, DefaultValue);
return DefaultValue;
}
return FVector2D((float)(*VectorValues)[0]->AsNumber(), (float)(*VectorValues)[1]->AsNumber());
}
void UHeliosConfigBPLibrary::SetVector2D(const FString & VariableName, FVector2D Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
TArray<TSharedPtr<FJsonValue>> VectorValues;
VectorValues.Add(MakeShareable(new FJsonValueNumber(Value.X)));
VectorValues.Add(MakeShareable(new FJsonValueNumber(Value.Y)));
JsonObject->SetArrayField(VariableName, VectorValues);
}
/*=====================================================================
BLUEPRINT
=====================================================================*/
FString UHeliosConfigBPLibrary::BP_GetString(UObject* WorldContextObject, const FString& VariableName, FString DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
return GetString(VariableName, DefaultValue);
}
void UHeliosConfigBPLibrary::BP_SetString(UObject* WorldContextObject, const FString& VariableName, const FString& Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
SetString(VariableName, Value);
}
int32 UHeliosConfigBPLibrary::BP_GetInt(UObject* WorldContextObject, const FString& VariableName, int32 DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
return GetInt(VariableName, DefaultValue);
}
void UHeliosConfigBPLibrary::BP_SetInt(UObject* WorldContextObject, const FString& VariableName, const int32 Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
SetInt(VariableName, Value);
}
float UHeliosConfigBPLibrary::BP_GetFloat(UObject* WorldContextObject, const FString& VariableName, float DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
return GetFloat(VariableName, DefaultValue);
}
void UHeliosConfigBPLibrary::BP_SetFloat(UObject* WorldContextObject, const FString& VariableName, const float Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
SetInt(VariableName, Value);
}
FLinearColor UHeliosConfigBPLibrary::BP_GetColor(UObject* WorldContextObject, const FString& VariableName, FLinearColor DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
return GetColor(VariableName, DefaultValue);
}
void UHeliosConfigBPLibrary::BP_SetColor(UObject * WorldContextObject, const FString & VariableName, FLinearColor Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
SetColor(VariableName, Value);
}
bool UHeliosConfigBPLibrary::BP_GetBool(UObject* WorldContextObject, const FString& VariableName, bool DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
return GetBool(VariableName, DefaultValue);
}
void UHeliosConfigBPLibrary::BP_SetBool(UObject* WorldContextObject, const FString& VariableName, bool Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
SetBool(VariableName, Value);
}
FVector UHeliosConfigBPLibrary::BP_GetVector(UObject * WorldContextObject, const FString & VariableName, FVector DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
return GetVector(VariableName, DefaultValue);
}
void UHeliosConfigBPLibrary::BP_SetVector(UObject * WorldContextObject, const FString & VariableName, FVector Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
SetVector(VariableName, Value);
}
FVector2D UHeliosConfigBPLibrary::BP_GetVector2D(UObject * WorldContextObject, const FString & VariableName, FVector2D DefaultValue)
{
#if WITH_EDITOR
return DefaultValue;
#endif // With_EDITOR
Initialize();
return GetVector2D(VariableName, DefaultValue);
}
void UHeliosConfigBPLibrary::BP_SetVector2D(UObject * WorldContextObject, const FString & VariableName, FVector2D Value)
{
#if WITH_EDITOR
return;
#endif // With_EDITOR
Initialize();
SetVector2D(VariableName, Value);
}
void UHeliosConfigBPLibrary::BeginDestroy()
{
SerializeJson(JsonObject);
Super::BeginDestroy();
}
void UHeliosConfigBPLibrary::Initialize()
{
if (!bInitialized)
{
DeserializeJson(JsonObject);
bInitialized = true;
}
}
void UHeliosConfigBPLibrary::DeserializeJson(TSharedPtr<FJsonObject> &JsonObject)
{
FString JsonText;
FFileHelper::LoadFileToString(JsonText, *GetConfigPath());
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(JsonText);
FJsonSerializer::Deserialize(Reader, JsonObject);
}
void UHeliosConfigBPLibrary::SerializeJson(TSharedPtr<FJsonObject> &JsonObject)
{
FString OutputString;
TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&OutputString);
FJsonSerializer::Serialize(JsonObject.ToSharedRef(), Writer);
FFileHelper::SaveStringToFile(OutputString, *GetConfigPath());
}
FString UHeliosConfigBPLibrary::GetConfigPath()
{
// Get Game Directory
// Editor: GameDirectory of .uproject on disk
// Runtime: InstallDir/WindowsNoEditor/GameName
FString GameName = FApp::GetGameName();
UE_LOG(LogTemp, Error, TEXT("%s"), *GameName);
FString ThePath = FPaths::ConvertRelativePathToFull(FPaths::GameDir());
ThePath += "HeliosConfig_" + GameName + ".json";
return ThePath;
}
| 23.720455 | 167 | 0.763246 | [
"vector"
] |
ff9dd5b201716c6e84a64580d89df07404440ce9 | 8,459 | cpp | C++ | jni/WiEngine/impl/json/wyJSONParser.cpp | stubma/WiEngine | 7e80641fe15a77a2fc43db90f15dad6aa2c2860a | [
"MIT"
] | 39 | 2015-01-23T10:01:31.000Z | 2021-06-10T03:01:18.000Z | jni/WiEngine/impl/json/wyJSONParser.cpp | luckypen/WiEngine | 7e80641fe15a77a2fc43db90f15dad6aa2c2860a | [
"MIT"
] | 1 | 2015-04-15T08:07:47.000Z | 2015-04-15T08:07:47.000Z | jni/WiEngine/impl/json/wyJSONParser.cpp | luckypen/WiEngine | 7e80641fe15a77a2fc43db90f15dad6aa2c2860a | [
"MIT"
] | 20 | 2015-01-20T07:36:10.000Z | 2019-09-15T01:02:19.000Z | /*
* Copyright (c) 2010 WiYun Inc.
* Author: luma(stubma@gmail.com)
*
* For all entities this program is free software; you can redistribute
* it and/or modify it under the terms of the 'WiEngine' license with
* the additional provision that 'WiEngine' must be credited in a manner
* that can be be observed by end users, for example, in the credits or during
* start up. (please find WiEngine logo in sdk's logo folder)
*
* 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 "wyJSONParser.h"
#include "wyJSONObject.h"
#include "yajl_parse.h"
#include "yajl_gen.h"
#include "wyMemoryInputStream.h"
#include "wyLog.h"
#include "wyTypes.h"
#include "wyUtils.h"
#include "wyJSONArray.h"
// context for json parsing
typedef struct {
yajl_gen g;
char* key;
size_t keyLen;
wyObject* root;
vector<wyObject*>* objStack;
vector<bool>* flagStack;
} wyJSONContext;
static int reformat_null(void* ctx) {
wyJSONContext* jc = (wyJSONContext*)ctx;
bool array = *(jc->flagStack->rbegin());
if(array) {
wyJSONArray* p = (wyJSONArray*)(*(jc->objStack->rbegin()));
p->addNull();
} else {
wyJSONObject* p = (wyJSONObject*)(*(jc->objStack->rbegin()));
char old = jc->key[jc->keyLen];
jc->key[jc->keyLen] = 0;
p->addNull(jc->key);
jc->key[jc->keyLen] = old;
}
return yajl_gen_status_ok == yajl_gen_null(jc->g);
}
static int reformat_boolean(void* ctx, int boolean) {
wyJSONContext* jc = (wyJSONContext*)ctx;
bool array = *(jc->flagStack->rbegin());
if(array) {
wyJSONArray* p = (wyJSONArray*)(*(jc->objStack->rbegin()));
p->addBool(boolean);
} else {
wyJSONObject* p = (wyJSONObject*)(*(jc->objStack->rbegin()));
char old = jc->key[jc->keyLen];
jc->key[jc->keyLen] = 0;
p->addBool(jc->key, boolean);
jc->key[jc->keyLen] = old;
}
return yajl_gen_status_ok == yajl_gen_bool(jc->g, boolean);
}
static int reformat_number(void* ctx, const char * stringVal, size_t stringLen) {
wyJSONContext* jc = (wyJSONContext*)ctx;
char* s = (char*)stringVal;
char oldChar = s[stringLen];
s[stringLen] = 0;
bool array = *(jc->flagStack->rbegin());
if(array) {
wyJSONArray* p = (wyJSONArray*)(*(jc->objStack->rbegin()));
p->addString((const char*)stringVal);
} else {
wyJSONObject* p = (wyJSONObject*)(*(jc->objStack->rbegin()));
char old = jc->key[jc->keyLen];
jc->key[jc->keyLen] = 0;
p->addString(jc->key, s);
jc->key[jc->keyLen] = old;
}
s[stringLen] = oldChar;
return yajl_gen_status_ok == yajl_gen_number(jc->g, stringVal, stringLen);
}
static int reformat_string(void* ctx, const unsigned char* stringVal, size_t stringLen) {
wyJSONContext* jc = (wyJSONContext*)ctx;
char* s = (char*)stringVal;
char oldChar = s[stringLen];
s[stringLen] = 0;
bool array = *(jc->flagStack->rbegin());
if(array) {
wyJSONArray* p = (wyJSONArray*)(*(jc->objStack->rbegin()));
p->addString(s);
} else {
wyJSONObject* p = (wyJSONObject*)(*(jc->objStack->rbegin()));
char old = jc->key[jc->keyLen];
jc->key[jc->keyLen] = 0;
p->addString(jc->key, s);
jc->key[jc->keyLen] = old;
}
s[stringLen] = oldChar;
return yajl_gen_status_ok == yajl_gen_string(jc->g, stringVal, stringLen);
}
static int reformat_map_key(void* ctx, const unsigned char* stringVal, size_t stringLen) {
wyJSONContext* jc = (wyJSONContext*)ctx;
jc->key = (char*)stringVal;
jc->keyLen = stringLen;
return yajl_gen_status_ok == yajl_gen_string(jc->g, stringVal, stringLen);
}
static int reformat_start_map(void* ctx) {
wyJSONContext* jc = (wyJSONContext*)ctx;
if(jc->root) {
wyJSONObject* jo = wyJSONObject::make();
bool array = *(jc->flagStack->rbegin());
if(array) {
wyJSONArray* p = (wyJSONArray*)(*(jc->objStack->rbegin()));
p->addObject(jo);
} else {
wyJSONObject* p = (wyJSONObject*)(*(jc->objStack->rbegin()));
char old = jc->key[jc->keyLen];
jc->key[jc->keyLen] = 0;
p->addObject(jc->key, jo);
jc->key[jc->keyLen] = old;
}
jc->objStack->push_back(jo);
jc->flagStack->push_back(false);
} else {
jc->root = wyJSONObject::make();
jc->objStack->push_back(jc->root);
jc->flagStack->push_back(false);
}
return yajl_gen_status_ok == yajl_gen_map_open(jc->g);
}
static int reformat_end_map(void* ctx) {
wyJSONContext* jc = (wyJSONContext*)ctx;
jc->objStack->pop_back();
jc->flagStack->pop_back();
return yajl_gen_status_ok == yajl_gen_map_close(jc->g);
}
static int reformat_start_array(void* ctx) {
wyJSONContext* jc = (wyJSONContext*)ctx;
if(jc->root) {
wyJSONArray* ja = wyJSONArray::make();
bool array = *(jc->flagStack->rbegin());
if(array) {
wyJSONArray* p = (wyJSONArray*)(*(jc->objStack->rbegin()));
p->addArray(ja);
} else {
wyJSONObject* p = (wyJSONObject*)(*(jc->objStack->rbegin()));
char old = jc->key[jc->keyLen];
jc->key[jc->keyLen] = 0;
p->addArray(jc->key, ja);
jc->key[jc->keyLen] = old;
}
jc->objStack->push_back(ja);
jc->flagStack->push_back(true);
} else {
jc->root = wyJSONArray::make();
jc->objStack->push_back(jc->root);
jc->flagStack->push_back(true);
}
return yajl_gen_status_ok == yajl_gen_array_open(jc->g);
}
static int reformat_end_array(void* ctx) {
wyJSONContext* jc = (wyJSONContext*)ctx;
jc->objStack->pop_back();
jc->flagStack->pop_back();
return yajl_gen_status_ok == yajl_gen_array_close(jc->g);
}
static yajl_callbacks callbacks = {
reformat_null,
reformat_boolean,
NULL,
NULL,
reformat_number,
reformat_string,
reformat_start_map,
reformat_map_key,
reformat_end_map,
reformat_start_array,
reformat_end_array
};
wyObject* wyJSONParser::load(const char* json, size_t length) {
// use memory input stream
wyMemoryInputStream* mis = wyMemoryInputStream::make((char*)json, length);
// status of yajl
yajl_status stat;
// get gen instance
yajl_gen g = yajl_gen_alloc(NULL);
// register callback
wyJSONContext ctx = {
g,
NULL,
0,
NULL,
WYNEW vector<wyObject*>(),
WYNEW vector<bool>()
};
yajl_handle hand = yajl_alloc(&callbacks, NULL, (void*)&ctx);
// config yajl
yajl_gen_config(g, yajl_gen_beautify, 1);
yajl_gen_config(g, yajl_gen_validate_utf8, 1);
yajl_config(hand, yajl_allow_comments, 1);
// parse
char buf[4096];
while(true) {
// read data
int rd = mis->read(buf, 4096);
if (rd == 0)
break;
// parese data
stat = yajl_parse(hand, (const unsigned char*)buf, rd);
// if parse error, break
if (stat != yajl_status_ok)
break;
}
// complete parse
stat = yajl_complete_parse(hand);
// check error
if (stat != yajl_status_ok) {
unsigned char* str = yajl_get_error(hand, 1, (const unsigned char*)json, length);
LOGW("parse json error: %s", str);
yajl_free_error(hand, str);
// when error, doesn't return anything
ctx.root = NULL;
}
// free
yajl_gen_free(g);
yajl_free(hand);
WYDELETE(ctx.objStack);
WYDELETE(ctx.flagStack);
// return
return ctx.root;
}
wyObject* wyJSONParser::load(int resId) {
size_t len;
char* data = wyUtils::loadRaw(resId, &len);
wyObject* ret = load(data, len);
wyFree(data);
return ret;
}
wyObject* wyJSONParser::load(const char* path, bool isFile) {
size_t len;
char* data = wyUtils::loadRaw(path, isFile, &len);
wyObject* ret = load(data, len);
wyFree(data);
return ret;
}
wyObject* wyJSONParser::loadMemory(const char* mfsName) {
size_t len;
char* data = wyUtils::loadRaw(mfsName, &len);
wyObject* ret = load(data, len);
wyFree(data);
return ret;
}
| 27.112179 | 90 | 0.681996 | [
"vector"
] |
ffa166fca20c0a98baa400a199cefac785cfda8a | 6,603 | cpp | C++ | openstudiocore/src/model/AirLoopHVACZoneSplitter.cpp | zhouchong90/OpenStudio | f8570cb8297547b5e9cc80fde539240d8f7b9c24 | [
"BSL-1.0",
"blessing"
] | null | null | null | openstudiocore/src/model/AirLoopHVACZoneSplitter.cpp | zhouchong90/OpenStudio | f8570cb8297547b5e9cc80fde539240d8f7b9c24 | [
"BSL-1.0",
"blessing"
] | null | null | null | openstudiocore/src/model/AirLoopHVACZoneSplitter.cpp | zhouchong90/OpenStudio | f8570cb8297547b5e9cc80fde539240d8f7b9c24 | [
"BSL-1.0",
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2014, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include "AirLoopHVAC.hpp"
#include "AirLoopHVACZoneSplitter.hpp"
#include "AirLoopHVACZoneSplitter_Impl.hpp"
#include "HVACComponent.hpp"
#include "HVACComponent_Impl.hpp"
#include "Node.hpp"
#include "ThermalZone.hpp"
#include "ThermalZone_Impl.hpp"
#include "AirTerminalSingleDuctUncontrolled.hpp"
#include "Model.hpp"
#include "Model_Impl.hpp"
#include <utilities/idd/OS_AirLoopHVAC_ZoneSplitter_FieldEnums.hxx>
#include "../utilities/core/Compare.hpp"
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail{
AirLoopHVACZoneSplitter_Impl::AirLoopHVACZoneSplitter_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle):
Splitter_Impl(idfObject,model, keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == AirLoopHVACZoneSplitter::iddObjectType());
}
AirLoopHVACZoneSplitter_Impl::AirLoopHVACZoneSplitter_Impl(
const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle)
: Splitter_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == AirLoopHVACZoneSplitter::iddObjectType());
}
AirLoopHVACZoneSplitter_Impl::AirLoopHVACZoneSplitter_Impl(
const AirLoopHVACZoneSplitter_Impl& other,
Model_Impl* model,
bool keepHandle)
: Splitter_Impl(other,model,keepHandle)
{
}
AirLoopHVACZoneSplitter_Impl::~AirLoopHVACZoneSplitter_Impl()
{
}
const std::vector<std::string>& AirLoopHVACZoneSplitter_Impl::outputVariableNames() const
{
static std::vector<std::string> result;
if (result.empty()){
}
return result;
}
IddObjectType AirLoopHVACZoneSplitter_Impl::iddObjectType() const {
return AirLoopHVACZoneSplitter::iddObjectType();
}
std::vector<openstudio::IdfObject> AirLoopHVACZoneSplitter_Impl::remove()
{
if( this->airLoopHVAC() )
{
return std::vector<openstudio::IdfObject>();
}
else
{
OptionalAirLoopHVACZoneSplitter self = model().getModelObject<AirLoopHVACZoneSplitter>(handle());
model().disconnect(*self,inletPort());
for( int i = 0; i < int(nextBranchIndex()) - 1; i++ )
{
model().disconnect(*self,outletPort(i));
}
return HVACComponent_Impl::remove();
}
}
void AirLoopHVACZoneSplitter_Impl::disconnect()
{
ModelObject mo = this->getObject<ModelObject>();
model().disconnect(mo,inletPort());
for( int i = 0; i < int(nextBranchIndex()); i++ )
{
model().disconnect(mo,outletPort(i));
}
}
unsigned AirLoopHVACZoneSplitter_Impl::inletPort()
{
return OS_AirLoopHVAC_ZoneSplitterFields::InletNodeName;
}
unsigned AirLoopHVACZoneSplitter_Impl::outletPort(unsigned branchIndex)
{
unsigned result;
result = numNonextensibleFields();
result = result + branchIndex;
return result;
}
unsigned AirLoopHVACZoneSplitter_Impl::nextOutletPort()
{
return outletPort( this->nextBranchIndex() );
}
std::vector<ThermalZone> AirLoopHVACZoneSplitter_Impl::thermalZones()
{
std::vector<ThermalZone> zones;
std::vector<ModelObject> modelObjects;
//std::vector<ModelObject> _outletModelObjects = outletModelObjects();
OptionalAirLoopHVAC _airLoopHVAC = airLoopHVAC();
OptionalNode demandOutletNode;
OptionalNode demandInletNode;
if( _airLoopHVAC )
{
demandOutletNode = _airLoopHVAC->demandOutletNode();
demandInletNode = _airLoopHVAC->demandInletNode();
}
else
{
return zones;
}
modelObjects = _airLoopHVAC->demandComponents( demandInletNode.get(),
demandOutletNode.get(),
ThermalZone::iddObjectType() );
for( const auto & modelObject : modelObjects )
{
OptionalThermalZone zone;
zone = modelObject.optionalCast<ThermalZone>();
if( zone )
{
zones.push_back(*zone);
}
}
return zones;
}
} // detail
AirLoopHVACZoneSplitter::AirLoopHVACZoneSplitter(const Model& model)
: Splitter(AirLoopHVACZoneSplitter::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::AirLoopHVACZoneSplitter_Impl>());
}
AirLoopHVACZoneSplitter::AirLoopHVACZoneSplitter(std::shared_ptr<detail::AirLoopHVACZoneSplitter_Impl> p)
: Splitter(p)
{}
std::vector<openstudio::IdfObject> AirLoopHVACZoneSplitter::remove()
{
return getImpl<detail::AirLoopHVACZoneSplitter_Impl>()->remove();
}
unsigned AirLoopHVACZoneSplitter::inletPort()
{
return getImpl<detail::AirLoopHVACZoneSplitter_Impl>()->inletPort();
}
unsigned AirLoopHVACZoneSplitter::outletPort(unsigned branchIndex)
{
return getImpl<detail::AirLoopHVACZoneSplitter_Impl>()->outletPort(branchIndex);
}
unsigned AirLoopHVACZoneSplitter::nextOutletPort()
{
return getImpl<detail::AirLoopHVACZoneSplitter_Impl>()->nextOutletPort();
}
IddObjectType AirLoopHVACZoneSplitter::iddObjectType() {
IddObjectType result(IddObjectType::OS_AirLoopHVAC_ZoneSplitter);
return result;
}
std::vector<ThermalZone> AirLoopHVACZoneSplitter::thermalZones()
{
return getImpl<detail::AirLoopHVACZoneSplitter_Impl>()->thermalZones();
}
void AirLoopHVACZoneSplitter::disconnect()
{
return getImpl<detail::AirLoopHVACZoneSplitter_Impl>()->disconnect();
}
} // model
} // openstudio
| 31.146226 | 106 | 0.670604 | [
"vector",
"model"
] |
ffa39884a7ad46458dbc343eee335f11094403b3 | 635 | cpp | C++ | lite/load_and_run/src/strategys/strategy_fitting.cpp | Olalaye/MegEngine | 695d24f24517536e6544b07936d189dbc031bbce | [
"Apache-2.0"
] | 1 | 2022-03-21T03:13:45.000Z | 2022-03-21T03:13:45.000Z | lite/load_and_run/src/strategys/strategy_fitting.cpp | Olalaye/MegEngine | 695d24f24517536e6544b07936d189dbc031bbce | [
"Apache-2.0"
] | null | null | null | lite/load_and_run/src/strategys/strategy_fitting.cpp | Olalaye/MegEngine | 695d24f24517536e6544b07936d189dbc031bbce | [
"Apache-2.0"
] | null | null | null | /**
* \file lite/load_and_run/src/strategys/strategy_fitting.cpp
*
* This file is part of MegEngine, a deep learning framework developed by
* Megvii.
*
* \copyright Copyright (c) 2020-2021 Megvii Inc. All rights reserved.
*/
#include "strategy.h"
using namespace lar;
FittingStrategy::FittingStrategy(std::string) {
mgb_assert("this version don't support Fitting Strategy");
};
void FittingStrategy::run() {
mgb_assert("this version don't support Fitting Strategy");
};
DEFINE_bool(
fitting, false,
"whether to use the fitting model, which will auto profile and get "
"the best option set!"); | 26.458333 | 76 | 0.705512 | [
"model"
] |
ffa88ac857a9acb5337a8e535587ebc51fa5f37b | 11,397 | cc | C++ | addons/differentiation/ConstraintsFDC.cc | mkudruss/rbdl_derivatives | 0fec930aad4a6fb3084aa5aa2bb27bcfd7409a1e | [
"Zlib"
] | 1 | 2021-02-21T09:31:56.000Z | 2021-02-21T09:31:56.000Z | addons/differentiation/ConstraintsFDC.cc | mkudruss/rbdl_derivatives | 0fec930aad4a6fb3084aa5aa2bb27bcfd7409a1e | [
"Zlib"
] | null | null | null | addons/differentiation/ConstraintsFDC.cc | mkudruss/rbdl_derivatives | 0fec930aad4a6fb3084aa5aa2bb27bcfd7409a1e | [
"Zlib"
] | 1 | 2022-03-31T05:03:17.000Z | 2022-03-31T05:03:17.000Z | #include "ConstraintsFDC.h"
#include "ModelEntryFDC.h"
#include <cfloat>
#include <cmath>
using namespace std;
// -----------------------------------------------------------------------------
namespace RigidBodyDynamics {
// -----------------------------------------------------------------------------
namespace FDC {
// -----------------------------------------------------------------------------
using namespace RigidBodyDynamics::Math;
// define constant difference perturbation according to theory,
// i.e. EPS = eps^(1/3) = cubic_root(eps).
// Here, we us cmath cubic root implementation, i.e. cubic_root = cbrt.
// NOTE assumes that directions are normalized to one
const double EPS = cbrt(DBL_EPSILON);
const double EPSx2 = 2*EPS; // for convenience, we directly compute the denominator
RBDL_DLLAPI
void CalcConstrainedSystemVariables (
Model &model,
ADModel *fd_model, // NULL means execution without fd_model update
const VectorNd &q,
const MatrixNd &q_dirs,
const VectorNd &qdot,
const MatrixNd &qdot_dirs,
const VectorNd &tau,
const MatrixNd &tau_dirs,
ConstraintSet &cs,
ADConstraintSet *fd_cs // NULL means execution without fd_model update
) {
unsigned const ndirs = q_dirs.cols();
assert(ndirs == qdot_dirs.cols());
assert(ndirs == tau_dirs.cols());
for (unsigned idir = 0; idir < ndirs; idir++) {
Model * modelh;
if (fd_model) {
modelh = new Model(model);
} else {
modelh = &model;
}
ConstraintSet * csh;
if (fd_cs) {
csh = new ConstraintSet(cs);
} else {
csh = &cs;
}
// forward perturbation
CalcConstrainedSystemVariables(
*modelh,
q + EPS * q_dirs.col(idir),
qdot + EPS * qdot_dirs.col(idir),
tau + EPS * tau_dirs.col(idir),
*csh
);
// backward perturbation
CalcConstrainedSystemVariables(
model,
q - EPS * q_dirs.col(idir),
qdot - EPS * qdot_dirs.col(idir),
tau - EPS * tau_dirs.col(idir),
cs
);
if (fd_model) {
computeFDCEntry(*modelh, model, EPS, idir, *fd_model);
delete modelh;
}
if (fd_cs) {
computeFDCEntry(*csh, cs, EPS, idir, *fd_cs);
delete csh;
}
}
// nominal evaluation
CalcConstrainedSystemVariables(model, q, qdot, tau, cs);
}
RBDL_DLLAPI void ForwardDynamicsConstraintsDirect (
Model &model,
ADModel *fd_model,
const VectorNd &q,
const MatrixNd &q_dirs,
const VectorNd &qdot,
const MatrixNd &qdot_dirs,
const VectorNd &tau,
const MatrixNd &tau_dirs,
ConstraintSet &cs,
ADConstraintSet *fd_cs,
VectorNd &qddot,
MatrixNd &fd_qddot
) {
unsigned const ndirs = q_dirs.cols();
assert(ndirs == qdot_dirs.cols());
assert(ndirs == tau_dirs.cols());
assert(ndirs == fd_qddot.cols());
ConstraintSet const cs_in = cs;
// temporary variables
VectorNd qddotph (qddot);
VectorNd qddotmh (qddot);
for (unsigned idir = 0; idir < ndirs; idir++) {
Model * modelh;
if (fd_model) {
modelh = new Model(model);
} else {
modelh = &model;
}
ConstraintSet * csh;
if (fd_cs) {
csh = new ConstraintSet(cs);
} else {
csh = &cs;
}
ForwardDynamicsConstraintsDirect(
*modelh,
q + EPS * q_dirs.col(idir),
qdot + EPS * qdot_dirs.col(idir),
tau + EPS * tau_dirs.col(idir),
*csh,
qddotph
);
ForwardDynamicsConstraintsDirect(
model,
q - EPS * q_dirs.col(idir),
qdot - EPS * qdot_dirs.col(idir),
tau - EPS * tau_dirs.col(idir),
cs,
qddotmh
);
fd_qddot.col(idir) = (qddotph - qddotmh) / EPSx2;
if (fd_model) {
computeFDCEntry(*modelh, model, EPS, idir, *fd_model);
delete modelh;
}
if (fd_cs) {
computeFDCEntry(*csh, cs, EPS, idir, *fd_cs);
delete csh;
}
}
ForwardDynamicsConstraintsDirect(model, q, qdot, tau, cs, qddot);
}
RBDL_DLLAPI void ForwardDynamicsContactsKokkevis (
Model &model,
ADModel *fd_model,
const VectorNd &q,
const MatrixNd &q_dirs,
const VectorNd &qdot,
const MatrixNd &qdot_dirs,
const VectorNd &tau,
const MatrixNd &tau_dirs,
ConstraintSet &cs,
ADConstraintSet &fd_cs,
VectorNd &qddot,
MatrixNd &fd_qddot
) {
unsigned const ndirs = q_dirs.cols();
assert(ndirs == qdot_dirs.cols());
assert(ndirs == tau_dirs.cols());
assert(ndirs == fd_qddot.cols());
ConstraintSet const cs_in = cs;
ForwardDynamicsContactsKokkevis(model, q, qdot, tau, cs, qddot);
// temporary variables
VectorNd qddotph (qddot);
VectorNd qddotmh (qddot);
for (unsigned idir = 0; idir < ndirs; idir++) {
Model * modelhp;
Model * modelhm;
ConstraintSet * cshp;
ConstraintSet * cshm;
if (fd_model) {
} else {
modelhp = &model;
modelhm = &model;
cshp = &cs;
cshm = &cs;
}
cshp = new ConstraintSet(cs_in);
cshm = new ConstraintSet(cs_in);
modelhp = new Model(model);
modelhm = new Model(model);
ForwardDynamicsContactsKokkevis(
*modelhp,
q + EPS * q_dirs.col(idir),
qdot + EPS * qdot_dirs.col(idir),
tau + EPS * tau_dirs.col(idir),
*cshp,
qddotph
);
ForwardDynamicsContactsKokkevis(
*modelhm,
q - EPS * q_dirs.col(idir),
qdot - EPS * qdot_dirs.col(idir),
tau - EPS * tau_dirs.col(idir),
*cshm,
qddotmh
);
fd_qddot.col(idir) = (qddotph - qddotmh) / EPSx2;
// TODO add pointer arithmetic for fd_cs
// computeFDEntry(cs, csh, EPS, idir, fd_cs);
if (fd_model) {
computeFDCEntry(*modelhp, *modelhm, EPS, idir, *fd_model);
computeFDCEntry(*cshp, *cshm, EPS, idir, fd_cs);
}
delete cshp;
delete cshm;
delete modelhp;
delete modelhm;
}
}
RBDL_DLLAPI void CalcConstraintsJacobian(
Model & model,
ADModel * fd_model,
const VectorNd & q,
const MatrixNd & q_dirs,
ConstraintSet & cs,
ADConstraintSet * fd_cs,
MatrixNd & G,
vector<MatrixNd> & G_dirs
) {
unsigned const ndirs = q_dirs.cols();
assert(ndirs == G_dirs.size());
bool const update_kinematics = true;
for (unsigned idir = 0; idir < ndirs; idir++) {
Model * modelh;
if (fd_model) {
modelh = new Model(model);
} else {
modelh = &model;
}
ConstraintSet * csh;
if (fd_cs) {
csh = new ConstraintSet(cs);
} else {
csh = &cs;
}
MatrixNd Ghp = MatrixNd::Zero (G.rows(), G.cols());
MatrixNd Ghm = MatrixNd::Zero (G.rows(), G.cols());
CalcConstraintsJacobian(
*modelh,
q + EPS * q_dirs.col(idir),
*csh,
Ghp,
update_kinematics
);
CalcConstraintsJacobian(
model,
q - EPS * q_dirs.col(idir),
cs,
Ghm,
update_kinematics
);
G_dirs[idir] = (Ghp - Ghm) / EPSx2;
if (fd_model) {
computeFDCEntry(*modelh, model, EPS, idir, *fd_model);
delete modelh;
}
if (fd_cs) {
computeFDCEntry(*csh, cs, EPS, idir, *fd_cs);
delete csh;
}
}
CalcConstraintsJacobian(model, q, cs, G, update_kinematics);
}
/*
RBDL_DLLAPI void ComputeConstraintImpulsesDirect (
Model & model,
ADModel * fd_model,
const VectorNd & q,
const MatrixNd & q_dirs,
const VectorNd & qdot_minus,
const MatrixNd & qdot_minus_dirs,
ConstraintSet & cs,
ADConstraintSet * fd_cs,
VectorNd & qdot_plus,
MatrixNd & fd_qdot_plus
) {
unsigned ndirs = q_dirs.cols();
assert(ndirs == qdot_minus_dirs.cols());
assert(ndirs == fd_qdot_plus.cols());
ConstraintSet cs_in = cs;
ComputeConstraintImpulsesDirect(model, q, qdot_minus, cs, qdot_plus);
for (unsigned idir = 0; idir < ndirs; idir++) {
Model * modelh;
if (fd_model) {
modelh = new Model(model);
} else {
modelh = &model;
}
ConstraintSet csh = cs_in;
VectorNd qh = q + EPS * q_dirs.col(idir);
VectorNd qdh = qdot_minus + EPS * qdot_minus_dirs.col(idir);
VectorNd qdot_plush(model.dof_count);
ComputeConstraintImpulsesDirect(*modelh, qh, qdh, csh, qdot_plush);
fd_qdot_plus.col(idir) = (qdot_plush - qdot_plus) / EPS;
if (fd_cs) {
computeFDCEntry(cs, csh, EPS, idir, *fd_cs);
}
if (fd_model) {
computeFDCEntry(model, *modelh, EPS, idir, *fd_model);
delete modelh;
}
}
}
*/
/*
RBDL_DLLAPI
void ComputeConstraintImpulsesDirect (
Model & model,
ADModel * fd_model,
const VectorNd & q,
const MatrixNd & q_dirs,
const VectorNd & qdot_minus,
const MatrixNd & qdot_minus_dirs,
ConstraintSet & cs,
ADConstraintSet * fd_cs,
MatrixNd & fd_b,
vector<MatrixNd> & fd_A,
VectorNd & qdot_plus,
MatrixNd & fd_qdot_plus
) {
unsigned ndirs = q_dirs.cols();
assert(ndirs == qdot_minus_dirs.cols());
assert(ndirs == fd_qdot_plus.cols());
ConstraintSet cs_in = cs;
ComputeConstraintImpulsesDirect(model, q, qdot_minus, cs, qdot_plus);
VectorNd b_ref = cs.b;
MatrixNd A_ref = cs.A;
for (unsigned idir = 0; idir < ndirs; idir++) {
Model * modelh;
if (fd_model) {
modelh = new Model(model);
} else {
modelh = &model;
}
ConstraintSet csh = cs_in;
VectorNd qh = q + EPS * q_dirs.col(idir);
VectorNd qdh = qdot_minus + EPS * qdot_minus_dirs.col(idir);
VectorNd qdot_plush(model.dof_count);
ComputeConstraintImpulsesDirect(*modelh, qh, qdh, csh, qdot_plush);
fd_qdot_plus.col(idir) = (qdot_plush - qdot_plus) / EPS;
fd_b.col(idir) = (cs.b - b_ref) / EPS;
fd_A[idir] = (cs.A - A_ref) / EPS;
if (fd_cs) {
computeFDCEntry(cs, csh, EPS, idir, *fd_cs);
}
if (fd_model) {
computeFDCEntry(model, *modelh, EPS, idir, *fd_model);
delete modelh;
}
}
}
*/
RBDL_DLLAPI
void SolveConstrainedSystemDirect (
const MatrixNd &H,
const vector<MatrixNd> & H_dirs,
const MatrixNd &G,
const vector<MatrixNd> & G_dirs,
const VectorNd & c,
const MatrixNd & c_dirs,
const VectorNd & gamma,
const MatrixNd & gamma_dirs,
MatrixNd & A,
vector<MatrixNd> & A_dirs,
VectorNd & b,
MatrixNd & b_dirs,
VectorNd & x,
MatrixNd & x_fd,
LinearSolver & linear_solver,
int ndirs
) {
VectorNd qddot(H.rows());
VectorNd lambda(H.rows());
MatrixNd Ah(A);
VectorNd bh(b);
VectorNd xh(x);
for (int i = 0; i < ndirs; i++) {
RigidBodyDynamics::SolveConstrainedSystemDirect (
H + EPS * H_dirs[i],
G + EPS * G_dirs[i],
c + EPS * c_dirs.col(i),
gamma + EPS * gamma_dirs.col(i),
qddot, lambda,
Ah, bh, xh,
linear_solver
);
RigidBodyDynamics::SolveConstrainedSystemDirect (
H - EPS * H_dirs[i],
G - EPS * G_dirs[i],
c - EPS * c_dirs.col(i),
gamma - EPS * gamma_dirs.col(i),
qddot, lambda,
A, b, x,
linear_solver
);
A_dirs[i] = (Ah - A) / EPSx2;
b_dirs.col(i) = (bh - b) / EPSx2;
x_fd.col(i) = (xh - x) / EPSx2;
}
RigidBodyDynamics::SolveConstrainedSystemDirect(
H, G, c, gamma, qddot, lambda,
A, b, x, linear_solver);
}
// -----------------------------------------------------------------------------
} // namespace FD
// -----------------------------------------------------------------------------
} // namespace RigidBodyDynamics
// -----------------------------------------------------------------------------
| 24.248936 | 83 | 0.590594 | [
"vector",
"model"
] |
ffad7676cbb7b2f9f9bb4c58d89a3d81e2babdb7 | 1,521 | cpp | C++ | usaco/pieaters.cpp | jamesrayman/sport | a24b4512e3268f09574d6803fa71c98e9d7b50b1 | [
"MIT"
] | null | null | null | usaco/pieaters.cpp | jamesrayman/sport | a24b4512e3268f09574d6803fa71c98e9d7b50b1 | [
"MIT"
] | null | null | null | usaco/pieaters.cpp | jamesrayman/sport | a24b4512e3268f09574d6803fa71c98e9d7b50b1 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
long long n, m;
struct Cow {
int a, b, w;
};
vector<Cow> v;
unordered_map<long long, unordered_map<long long, long long>> d;
vector<vector<vector<long long>>> w;
long long f (int i, int j) {
if (i > j) return 0;
if (d[i].count(j)) return d[i][j];
long long r = 0;
for (int k = i; k <= j; k++) {
r = max(r, w[i][k][j] + f(i, k-1) + f(k+1, j));
//if (j - i == n-1) cout << k << " " << r << " " << w[i][k][j] << "\n";
}
return d[i][j] = r;
}
int main() {
ifstream input ("pieaters.in");
ofstream output ("pieaters.out");
input >> n >> m;
while (m-->0) {
int a, b, w;
input >> w >> a >> b;
a--;
b--;
v.push_back({ a, b, w });
}
w.resize(n, vector<vector<long long>>(n, vector<long long>(n, 0)));
for (auto& cow : v) {
for (int k = cow.a; k <= cow.b; k++) {
w[cow.a][k][cow.b] = max(w[cow.a][k][cow.b], (long long)cow.w);
}
}
for (int len = 0; len < n; len++) {
for (int i = 0; i + len < n; i++) {
int j = i + len;
for (int k = i; k <= j; k++) {
if (i < k) w[i][k][j] = max(w[i][k][j], w[i+1][k][j]);
if (k < j) w[i][k][j] = max(w[i][k][j], w[i][k][j-1]);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
f(i, j);
}
}
output << f(0, n-1) << "\n";
return 0;
}
| 20.554054 | 79 | 0.392505 | [
"vector"
] |
ffbad31a47b66310e83b169c2b7d4b4983b4bcba | 2,471 | hh | C++ | extern/glow/src/glow/objects/NamedObject.hh | huzjkevin/portal_maze_zgl | efb32b1c3430f20638c1401095999ecb4d0af5aa | [
"MIT"
] | null | null | null | extern/glow/src/glow/objects/NamedObject.hh | huzjkevin/portal_maze_zgl | efb32b1c3430f20638c1401095999ecb4d0af5aa | [
"MIT"
] | null | null | null | extern/glow/src/glow/objects/NamedObject.hh | huzjkevin/portal_maze_zgl | efb32b1c3430f20638c1401095999ecb4d0af5aa | [
"MIT"
] | null | null | null | #pragma once
#include <glow/common/non_copyable.hh>
#include <glow/gl.hh>
#include <glow/glow.hh>
#include <sstream>
#include <string>
#include <vector>
namespace glow
{
template <typename T, GLenum glNamespace>
class NamedObject
{
GLOW_NON_COPYABLE(NamedObject);
protected:
NamedObject() = default;
public:
// returns the OpenGL Object Label
std::string getObjectLabel() const
{
checkValidGLOW();
GLsizei len = 0;
glGetObjectLabel(glNamespace, static_cast<T const*>(this)->getObjectName(), 0, &len, nullptr);
std::vector<char> label;
label.resize(len + 1);
glGetObjectLabel(glNamespace, static_cast<T const*>(this)->getObjectName(), len + 1, nullptr, label.data());
return label.data(); // convert to string
}
// sets the OpenGL Object Label
void setObjectLabel(const std::string& label, size_t maxLength = 200)
{
checkValidGLOW();
if (label.size() > maxLength)
{
auto s = label.substr(0, maxLength) + "...";
glObjectLabel(glNamespace, static_cast<T const*>(this)->getObjectName(), -1, s.c_str());
}
else
glObjectLabel(glNamespace, static_cast<T const*>(this)->getObjectName(), -1, label.c_str());
}
};
template <typename T, GLenum glNamespace>
std::string to_string(NamedObject<T, glNamespace> const* obj)
{
std::ostringstream oss;
oss << "[";
switch (glNamespace)
{
case GL_BUFFER:
oss << "Buffer ";
break;
case GL_SHADER:
oss << "Shader ";
break;
case GL_PROGRAM:
oss << "Program ";
break;
case GL_VERTEX_ARRAY:
oss << "VertexArray ";
break;
case GL_QUERY:
oss << "Query ";
break;
case GL_PROGRAM_PIPELINE:
oss << "ProgramPipeline ";
break;
case GL_TRANSFORM_FEEDBACK:
oss << "TransformFeedback ";
break;
case GL_SAMPLER:
oss << "Sampler ";
break;
case GL_TEXTURE:
oss << "Texture ";
break;
case GL_RENDERBUFFER:
oss << "Renderbuffer ";
break;
case GL_FRAMEBUFFER:
oss << "Framebuffer ";
break;
default:
oss << "UNKNOWN ";
break;
}
oss << static_cast<T const*>(obj)->getObjectName();
auto label = obj->getObjectLabel();
if (!label.empty())
oss << ": " << label;
oss << "]";
return oss.str();
}
}
| 23.759615 | 116 | 0.577499 | [
"object",
"vector"
] |
ffbbab61d68801c7db69a31b88ed7dc89b0832a2 | 37,650 | cpp | C++ | native/cocos/core/geometry/Intersect.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | native/cocos/core/geometry/Intersect.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | native/cocos/core/geometry/Intersect.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | #include "core/geometry/Intersect.h"
#include <cmath>
#include <limits>
#include "3d/assets/Mesh.h"
#include "base/std/container/array.h"
#include "core/TypedArray.h"
#include "core/geometry/AABB.h"
#include "core/geometry/Capsule.h"
#include "core/geometry/Line.h"
#include "core/geometry/Obb.h"
#include "core/geometry/Plane.h"
#include "core/geometry/Ray.h"
#include "core/geometry/Spec.h"
#include "core/geometry/Sphere.h"
#include "core/geometry/Triangle.h"
#include "math/Mat3.h"
#include "math/Math.h"
#include "math/Vec3.h"
#include "renderer/gfx-base/GFXDef.h"
#include "scene/Model.h"
namespace cc {
namespace geometry {
float rayPlane(const Ray &ray, const Plane &plane) {
auto denom = Vec3::dot(ray.d, plane.n);
if (abs(denom) < math::EPSILON) {
return 0;
}
auto t = (plane.n * plane.d - ray.o).dot(plane.n) / denom;
return t < 0 ? 0 : t;
}
// based on http://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/raytri/
float rayTriangle(const Ray &ray, const Triangle &triangle, bool doubleSided) {
Vec3 pvec{};
Vec3 qvec{};
auto ab = triangle.b - triangle.a;
auto ac = triangle.c - triangle.a;
Vec3::cross(ray.d, ac, &pvec);
float det = Vec3::dot(ab, pvec);
if (det < math::EPSILON && (!doubleSided || det > -math::EPSILON)) {
return 0;
}
float invDet = 1.0F / det;
auto ao = ray.o - triangle.a;
auto u = Vec3::dot(ao, pvec) * invDet;
if (u < 0 || u > 1) {
return 0;
}
Vec3::cross(ao, ab, &qvec);
auto v = Vec3::dot(ray.d, qvec) * invDet;
if (v < 0 || u + v > 1) {
return 0;
}
auto t = Vec3::dot(ac, qvec) * invDet;
return t < 0 ? 0 : t;
}
float raySphere(const Ray &ray, const Sphere &sphere) {
auto rSq = sphere.getRadius() * sphere.getRadius();
auto e = sphere.getCenter() - ray.o;
auto eSq = e.lengthSquared();
auto aLength = Vec3::dot(e, ray.d); // assume ray direction already normalized
auto fSq = rSq - (eSq - aLength * aLength);
if (fSq < 0) {
return 0;
}
auto f = sqrt(fSq);
auto t = eSq < rSq ? aLength + f : aLength - f;
return t < 0 ? 0 : t;
}
float rayAABB2(const Ray &ray, const Vec3 &min, const Vec3 &max) {
const auto &o = ray.o;
auto d = ray.d;
auto ix = 1.0F / d.x;
auto iy = 1.0F / d.y;
auto iz = 1.0F / d.z;
auto tx1 = (min.x - o.x) * ix;
auto tx2 = (max.x - o.x) * ix;
auto ty1 = (min.y - o.y) * iy;
auto ty2 = (max.y - o.y) * iy;
auto tz1 = (min.z - o.z) * iz;
auto tz2 = (max.z - o.z) * iz;
auto tmin = std::max(std::max(std::min(tx1, tx2), std::min(ty1, ty2)), std::min(tz1, tz2));
auto tmax = std::min(std::min(std::max(tx1, tx2), std::max(ty1, ty2)), std::max(tz1, tz2));
if (tmax < 0 || tmin > tmax) {
return 0;
}
return tmin > 0 ? tmin : tmax; // ray origin inside aabb
}
float rayAABB(const Ray &ray, const AABB &aabb) {
auto minV = aabb.getCenter() - aabb.getHalfExtents();
auto maxV = aabb.getCenter() + aabb.getHalfExtents();
return rayAABB2(ray, minV, maxV);
}
float rayOBB(const Ray &ray, const OBB &obb) {
ccstd::array<float, 6> t;
ccstd::array<float, 3> size = {obb.halfExtents.x, obb.halfExtents.y, obb.halfExtents.z};
const auto & center = obb.center;
auto const & d = ray.d;
Vec3 x = {obb.orientation.m[0], obb.orientation.m[1], obb.orientation.m[2]};
Vec3 y = {obb.orientation.m[3], obb.orientation.m[4], obb.orientation.m[5]};
Vec3 z = {obb.orientation.m[6], obb.orientation.m[7], obb.orientation.m[8]};
Vec3 p = center - ray.o;
// The cos values of the ray on the X, Y, Z
ccstd::array<float, 3> f = {Vec3::dot(x, d), Vec3::dot(y, d), Vec3::dot(z, d)};
// The projection length of P on X, Y, Z
ccstd::array<float, 3> e{Vec3::dot(x, p), Vec3::dot(y, p), Vec3::dot(z, p)};
for (auto i = 0; i < 3; ++i) {
if (f[i] == 0) {
if (-e[i] - size[i] > 0 || -e[i] + size[i] < 0) {
return 0;
}
// Avoid div by 0!
f[i] = 0.000001F;
}
// min
t[i * 2 + 0] = (e[i] + size[i]) / f[i];
// max
t[i * 2 + 1] = (e[i] - size[i]) / f[i];
}
auto tmin = std::max(std::max(std::min(t[0], t[1]), std::min(t[2], t[3])), std::min(t[4], t[5]));
auto tmax = std::min(std::min(std::max(t[0], t[1]), std::max(t[2], t[3])), std::max(t[4], t[5]));
if (tmax < 0 || tmin > tmax) {
return 0;
}
return tmin > 0 ? tmin : tmax; // ray origin inside aabb
}
float rayCapsule(const Ray &ray, const Capsule &capsule) {
Sphere sphere;
auto radiusSqr = capsule.radius * capsule.radius;
auto vRayNorm = ray.d.getNormalized();
auto aa = capsule.ellipseCenter0;
auto bb = capsule.ellipseCenter1;
auto ba = bb - aa;
if (ba == Vec3::ZERO) {
sphere.setRadius(capsule.radius);
sphere.setCenter(capsule.ellipseCenter0);
return raySphere(ray, sphere);
}
auto oa = ray.o - aa;
Vec3 VxBA; //NOLINT(readability-identifier-naming)
Vec3::cross(vRayNorm, ba, &VxBA);
auto a = VxBA.lengthSquared();
if (a == 0.0F) {
sphere.setRadius(capsule.radius);
auto bo = bb - ray.o;
if (oa.lengthSquared() < bo.lengthSquared()) {
sphere.setCenter(capsule.ellipseCenter0);
} else {
sphere.setCenter(capsule.ellipseCenter1);
}
return raySphere(ray, sphere);
}
Vec3 OAxBA; //NOLINT(readability-identifier-naming)
Vec3::cross(oa, ba, &OAxBA);
auto ab2 = ba.lengthSquared();
auto b = 2.0F * Vec3::dot(VxBA, OAxBA);
auto c = OAxBA.lengthSquared() - (radiusSqr * ab2);
auto d = b * b - 4 * a * c;
if (d < 0) {
return 0;
}
auto t = (-b - std::sqrt(d)) / (2.0F * a);
if (t < 0.0F) {
sphere.setRadius(capsule.radius);
auto bo = bb - ray.o;
if (oa.lengthSquared() < bo.lengthSquared()) {
sphere.setCenter(capsule.ellipseCenter0);
} else {
sphere.setCenter(capsule.ellipseCenter1);
}
return raySphere(ray, sphere);
}
// Limit intersection between the bounds of the cylinder's end caps.
auto iPos = ray.o + vRayNorm * t;
auto iPosLen = iPos - aa;
auto tLimit = Vec3::dot(iPosLen, ba) / ab2;
if (tLimit >= 0 && tLimit <= 1) {
return t;
}
if (tLimit < 0) {
sphere.setRadius(capsule.radius);
sphere.setCenter(capsule.ellipseCenter0);
return raySphere(ray, sphere);
}
if (tLimit > 1) {
sphere.setRadius(capsule.radius);
sphere.setCenter(capsule.ellipseCenter1);
return raySphere(ray, sphere);
}
return 0;
}
namespace {
void fillResult(float *minDis, ERaycastMode m, float d, float i0, float i1, float i2, cc::optional<ccstd::vector<IRaySubMeshResult>> &r) {
if (m == ERaycastMode::CLOSEST) {
if (*minDis > d || *minDis == 0.0F) {
*minDis = d;
if (r) {
if (r->empty()) {
r->emplace_back(IRaySubMeshResult{d, static_cast<uint32_t>(i0 / 3), static_cast<uint32_t>(i1 / 3), static_cast<uint32_t>(i2 / 3)});
} else {
(*r)[0].distance = d;
(*r)[0].vertexIndex0 = static_cast<uint32_t>(i0 / 3);
(*r)[0].vertexIndex1 = static_cast<uint32_t>(i1 / 3);
(*r)[0].vertexIndex2 = static_cast<uint32_t>(i2 / 3);
}
}
}
} else {
*minDis = d;
if (r) r->emplace_back(IRaySubMeshResult{d, static_cast<uint32_t>(i0 / 3), static_cast<uint32_t>(i1 / 3), static_cast<uint32_t>(i2 / 3)});
}
}
float narrowphase(float *minDis, const Float32Array &vb, const IBArray &ib, gfx::PrimitiveMode pm, const Ray &ray, IRaySubMeshOptions *opt) {
Triangle tri;
auto ibSize = cc::visit([](auto &arr) { return arr.length(); }, ib);
return cc::visit([&](auto &ib) {
if (pm == gfx::PrimitiveMode::TRIANGLE_LIST) {
auto cnt = ibSize;
for (auto j = 0; j < cnt; j += 3) {
auto i0 = ib[j] * 3;
auto i1 = ib[j + 1] * 3;
auto i2 = ib[j + 2] * 3;
tri.a = {vb[i0], vb[i0 + 1], vb[i0 + 2]};
tri.b = {vb[i1], vb[i1 + 1], vb[i1 + 2]};
tri.c = {vb[i2], vb[i2 + 1], vb[i2 + 2]};
auto dist = rayTriangle(ray, tri, opt->doubleSided);
if (dist == 0.0F || dist > opt->distance) continue;
fillResult(minDis, opt->mode, dist, static_cast<float>(i0), static_cast<float>(i1), static_cast<float>(i2), opt->result);
if (opt->mode == ERaycastMode::ANY) return dist;
}
} else if (pm == gfx::PrimitiveMode::TRIANGLE_STRIP) {
auto cnt = ibSize - 2;
int32_t rev = 0;
for (auto j = 0; j < cnt; j += 1) {
auto i0 = ib[j - rev] * 3;
auto i1 = ib[j + rev + 1] * 3;
auto i2 = ib[j + 2] * 3;
tri.a = {vb[i0], vb[i0 + 1], vb[i0 + 2]};
tri.b = {vb[i1], vb[i1 + 1], vb[i1 + 2]};
tri.c = {vb[i2], vb[i2 + 1], vb[i2 + 2]};
rev = ~rev;
auto dist = rayTriangle(ray, tri, opt->doubleSided);
if (dist == 0.0F || dist > opt->distance) continue;
fillResult(minDis, opt->mode, dist, static_cast<float>(i0), static_cast<float>(i1), static_cast<float>(i2), opt->result);
if (opt->mode == ERaycastMode::ANY) return dist;
}
} else if (pm == gfx::PrimitiveMode::TRIANGLE_FAN) {
auto cnt = ibSize - 1;
auto i0 = ib[0] * 3;
tri.a = {vb[i0], vb[i0 + 1], vb[i0 + 2]};
for (auto j = 1; j < cnt; j += 1) {
auto i1 = ib[j] * 3;
auto i2 = ib[j + 1] * 3;
tri.b = {vb[i1], vb[i1 + 1], vb[i1 + 2]};
tri.c = {vb[i2], vb[i2 + 1], vb[i2 + 2]};
auto dist = rayTriangle(ray, tri, opt->doubleSided);
if (dist == 0.0 || dist > opt->distance) continue;
fillResult(minDis, opt->mode, dist, static_cast<float>(i0), static_cast<float>(i1), static_cast<float>(i2), opt->result);
if (opt->mode == ERaycastMode::ANY) return dist;
}
}
return *minDis;
},
ib);
}
} // namespace
float raySubMesh(const Ray &ray, const RenderingSubMesh &submesh, IRaySubMeshOptions *options) {
Triangle tri;
IRaySubMeshOptions deOpt;
deOpt.mode = ERaycastMode::ANY;
deOpt.distance = FLT_MAX;
deOpt.doubleSided = false;
float minDis = 0.0F;
auto &mesh = const_cast<RenderingSubMesh &>(submesh);
if (mesh.getGeometricInfo().positions.empty()) return minDis;
IRaySubMeshOptions *opt = options ? options : &deOpt;
auto min = mesh.getGeometricInfo().boundingBox.min;
auto max = mesh.getGeometricInfo().boundingBox.max;
if (rayAABB2(ray, min, max) != 0.0F) {
const auto &pm = mesh.getPrimitiveMode();
const auto &info = mesh.getGeometricInfo();
narrowphase(&minDis, info.positions, info.indices.value(), pm, ray, opt);
}
return minDis;
}
float rayMesh(const Ray &ray, const Mesh &mesh, IRayMeshOptions *option) {
float minDis = 0.0F;
IRayMeshOptions deOpt;
deOpt.distance = std::numeric_limits<float>::max();
deOpt.doubleSided = false;
deOpt.mode = ERaycastMode::ANY;
IRayMeshOptions *opt = option ? option : &deOpt;
auto length = mesh.getSubMeshCount();
auto min = mesh.getStruct().minPosition;
auto max = mesh.getStruct().maxPosition;
if (min.has_value() && max.has_value() && rayAABB2(ray, min.value(), max.value()) == 0.0F) return minDis;
for (uint32_t i = 0; i < length; i++) {
const auto &sm = const_cast<Mesh &>(mesh).getRenderingSubMeshes()[i];
float dis = raySubMesh(ray, *sm, opt);
if (dis != 0.0F) {
if (opt->mode == ERaycastMode::CLOSEST) {
if (minDis == 0.0F || minDis > dis) {
minDis = dis;
if (opt->subIndices.has_value()) {
if (opt->subIndices->empty()) {
opt->subIndices->resize(1);
}
opt->subIndices.value()[0] = i;
}
}
} else {
minDis = dis;
if (opt->subIndices.has_value()) opt->subIndices->emplace_back(i);
if (opt->mode == ERaycastMode::ANY) {
return dis;
}
}
}
}
if (minDis != 0.0F && opt->mode == ERaycastMode::CLOSEST) {
if (opt->result.has_value()) {
opt->result.value()[0].distance = minDis;
opt->result.value().resize(1);
}
if (opt->subIndices.has_value()) opt->subIndices.value().resize(1);
}
return minDis;
}
float rayModel(const Ray &ray, const scene::Model &model, IRayModelOptions *option) {
float minDis = 0.0F;
IRayModelOptions deOpt;
deOpt.distance = std::numeric_limits<float>::max();
deOpt.doubleSided = false;
deOpt.mode = ERaycastMode::ANY;
IRayModelOptions *opt = option ? option : &deOpt;
const auto * wb = model.getWorldBounds();
if (wb && rayAABB(ray, *wb) == 0.0F) {
return minDis;
}
Ray modelRay{ray};
if (model.getNode()) {
Mat4 m4 = model.getNode()->getWorldMatrix().getInversed();
Vec3::transformMat4(ray.o, m4, &modelRay.o);
Vec3::transformMat4Normal(ray.d, m4, &modelRay.d);
}
const auto &subModels = model.getSubModels();
for (auto i = 0; i < subModels.size(); i++) {
const auto &subMesh = subModels[i]->getSubMesh();
float dis = raySubMesh(modelRay, *subMesh, opt);
if (dis != 0.0F) {
if (opt->mode == ERaycastMode::CLOSEST) {
if (minDis == 0.0F || minDis > dis) {
minDis = dis;
if (opt->subIndices.has_value()) {
if (opt->subIndices->empty()) {
opt->subIndices->resize(1);
}
opt->subIndices.value()[0] = i;
}
}
} else {
minDis = dis;
if (opt->subIndices.has_value()) opt->subIndices->emplace_back(i);
if (opt->mode == ERaycastMode::ANY) {
return dis;
}
}
}
}
if (minDis != 0.0F && opt->mode == ERaycastMode::CLOSEST) {
if (opt->result.has_value()) {
opt->result.value()[0].distance = minDis;
opt->result.value().resize(1);
}
if (opt->subIndices.has_value()) opt->subIndices->resize(1);
}
return minDis;
}
float linePlane(const Line &line, const Plane &plane) {
auto ab = line.e - line.s;
auto t = (plane.d - Vec3::dot(line.s, plane.n)) / Vec3::dot(ab, plane.n);
return (t < 0 || t > 1) ? 0 : t;
}
int lineTriangle(const Line &line, const Triangle &triangle, Vec3 *outPt) {
Vec3 n;
Vec3 e;
auto ab = triangle.b - triangle.a;
auto ac = triangle.c - triangle.a;
auto qp = line.s - line.e;
Vec3::cross(ab, ac, &n);
auto det = Vec3::dot(qp, n);
if (det <= 0.0F) {
return 0;
}
auto ap = line.s - triangle.a;
auto t = Vec3::dot(ap, n);
if (t < 0 || t > det) {
return 0;
}
Vec3::cross(qp, ap, &e);
auto v = Vec3::dot(ac, e);
if (v < 0.0F || v > det) {
return 0;
}
auto w = -Vec3::dot(ab, e);
if (w < 0.0F || v + w > det) {
return 0;
}
if (outPt) {
auto invDet = 1.0F / det;
v *= invDet;
w *= invDet;
auto u = 1.0F - v - w;
// outPt = u*a + v*d + w*c;
*outPt = {triangle.a.x * u + triangle.b.x * v + triangle.c.x * w,
triangle.a.y * u + triangle.b.y * v + triangle.c.y * w,
triangle.a.z * u + triangle.b.z * v + triangle.c.z * w};
}
return 1;
}
float lineAABB(const Line &line, const AABB &aabb) {
Ray ray;
ray.o.set(line.s);
ray.d = line.e - line.s;
ray.d.normalize();
auto min = rayAABB(ray, aabb);
return min < line.length() ? min : 0.0F;
}
float lineOBB(const Line &line, const OBB &obb) {
Ray ray;
ray.o.set(line.s);
ray.d = line.e - line.s;
ray.d.normalize();
auto min = rayOBB(ray, obb);
return min < line.length() ? min : 0.0F;
}
float lineSphere(const Line &line, const Sphere &sphere) {
Ray ray;
ray.o.set(line.s);
ray.d = line.e - line.s;
ray.d.normalize();
auto min = raySphere(ray, sphere);
return min < line.length() ? min : 0.0F;
}
bool aabbWithAABB(const AABB &aabb1, const AABB &aabb2) {
auto aMin = aabb1.getCenter() - aabb1.getHalfExtents();
auto aMax = aabb1.getCenter() + aabb1.getHalfExtents();
auto bMin = aabb2.getCenter() - aabb2.getHalfExtents();
auto bMax = aabb2.getCenter() + aabb2.getHalfExtents();
return (aMin.x <= bMax.x && aMax.x >= bMin.x) && (aMin.y <= bMax.y && aMax.y >= bMin.y) && (aMin.z <= bMax.z && aMax.z >= bMin.z);
}
static void getAABBVertices(const Vec3 &min, const Vec3 &max, ccstd::array<Vec3, 8> *out) {
*out = {
Vec3{min.x, max.y, max.z},
Vec3{min.x, max.y, min.z},
Vec3{min.x, min.y, max.z},
Vec3{min.x, min.y, min.z},
Vec3{max.x, max.y, max.z},
Vec3{max.x, max.y, min.z},
Vec3{max.x, min.y, max.z},
Vec3{max.x, min.y, min.z},
};
}
static void getOBBVertices(const Vec3 &c, const Vec3 &e,
const Vec3 &a1, const Vec3 &a2, const Vec3 &a3,
ccstd::array<Vec3, 8> *out) {
*out = {Vec3{
c.x + a1.x * e.x + a2.x * e.y + a3.x * e.z,
c.y + a1.y * e.x + a2.y * e.y + a3.y * e.z,
c.z + a1.z * e.x + a2.z * e.y + a3.z * e.z},
Vec3{
c.x - a1.x * e.x + a2.x * e.y + a3.x * e.z,
c.y - a1.y * e.x + a2.y * e.y + a3.y * e.z,
c.z - a1.z * e.x + a2.z * e.y + a3.z * e.z},
Vec3{
c.x + a1.x * e.x - a2.x * e.y + a3.x * e.z,
c.y + a1.y * e.x - a2.y * e.y + a3.y * e.z,
c.z + a1.z * e.x - a2.z * e.y + a3.z * e.z},
Vec3{
c.x + a1.x * e.x + a2.x * e.y - a3.x * e.z,
c.y + a1.y * e.x + a2.y * e.y - a3.y * e.z,
c.z + a1.z * e.x + a2.z * e.y - a3.z * e.z},
Vec3{
c.x - a1.x * e.x - a2.x * e.y - a3.x * e.z,
c.y - a1.y * e.x - a2.y * e.y - a3.y * e.z,
c.z - a1.z * e.x - a2.z * e.y - a3.z * e.z},
Vec3{
c.x + a1.x * e.x - a2.x * e.y - a3.x * e.z,
c.y + a1.y * e.x - a2.y * e.y - a3.y * e.z,
c.z + a1.z * e.x - a2.z * e.y - a3.z * e.z},
Vec3{
c.x - a1.x * e.x + a2.x * e.y - a3.x * e.z,
c.y - a1.y * e.x + a2.y * e.y - a3.y * e.z,
c.z - a1.z * e.x + a2.z * e.y - a3.z * e.z},
Vec3{
c.x - a1.x * e.x - a2.x * e.y + a3.x * e.z,
c.y - a1.y * e.x - a2.y * e.y + a3.y * e.z,
c.z - a1.z * e.x - a2.z * e.y + a3.z * e.z}};
}
struct Interval {
float min;
float max;
};
static Interval getInterval(const ccstd::array<Vec3, 8> &vertices, const Vec3 &axis) {
auto min = std::numeric_limits<float>::max();
auto max = std::numeric_limits<float>::min();
for (auto i = 0; i < 8; ++i) {
auto projection = Vec3::dot(axis, vertices[i]);
min = std::min(projection, min);
max = std::max(projection, max);
}
return Interval{min, max};
}
int aabbWithOBB(const AABB &aabb, const OBB &obb) {
ccstd::array<Vec3, 15> test;
ccstd::array<Vec3, 8> vertices;
ccstd::array<Vec3, 8> vertices2;
test[0] = {1, 0, 0};
test[1] = {0, 1, 0};
test[2] = {0, 0, 1};
test[3] = {obb.orientation.m[0], obb.orientation.m[1], obb.orientation.m[2]};
test[4] = {obb.orientation.m[3], obb.orientation.m[4], obb.orientation.m[5]};
test[5] = {obb.orientation.m[6], obb.orientation.m[7], obb.orientation.m[8]};
for (auto i = 0; i < 3; ++i) { // Fill out rest of axis
Vec3::cross(test[i], test[3], &test[6 + i * 3 + 0]);
Vec3::cross(test[i], test[4], &test[6 + i * 3 + 1]);
Vec3::cross(test[i], test[5], &test[6 + i * 3 + 2]);
}
auto min = aabb.getCenter() - aabb.getHalfExtents();
auto max = aabb.getCenter() + aabb.getHalfExtents();
getAABBVertices(min, max, &vertices);
getOBBVertices(obb.center, obb.halfExtents, test[3], test[4], test[5], &vertices2);
for (auto j = 0; j < 15; ++j) {
auto a = getInterval(vertices, test[j]);
auto b = getInterval(vertices2, test[j]);
if (b.min > a.max || a.min > b.max) {
return 0; // Seperating axis found
}
}
return 1;
}
int aabbPlane(const AABB &aabb, const Plane &plane) {
auto r = aabb.getHalfExtents().x * std::abs(plane.n.x) + aabb.getHalfExtents().y * std::abs(plane.n.y) + aabb.getHalfExtents().z * std::abs(plane.n.z);
auto dot = Vec3::dot(plane.n, aabb.getCenter());
if (dot + r < plane.d) {
return -1;
}
if (dot - r > plane.d) {
return 0;
}
return 1;
}
int aabbFrustum(const AABB &aabb, const Frustum &frustum) {
for (const auto &plane : frustum.planes) {
// frustum plane normal points to the inside
if (aabbPlane(aabb, *plane) == -1) {
return 0;
}
} // completely outside
return 1;
}
// https://cesium.com/blog/2017/02/02/tighter-frustum-culling-and-why-you-may-want-to-disregard-it/
int aabbFrustumAccurate(const AABB &aabb, const Frustum &frustum) {
ccstd::array<Vec3, 8> tmp;
int out1 = 0;
int out2 = 0;
int result = 0;
bool intersects = false;
// 1. aabb inside/outside frustum test
for (const auto &plane : frustum.planes) {
result = aabbPlane(aabb, *plane);
// frustum plane normal points to the inside
if (result == -1) {
return 0; // completely outside
}
if (result == 1) {
intersects = true;
}
}
if (!intersects) {
return 1;
} // completely inside
// in case of false positives
// 2. frustum inside/outside aabb test
for (auto i = 0; i < frustum.vertices.size(); i++) {
tmp[i] = frustum.vertices[i] - aabb.getCenter();
}
out1 = 0;
out2 = 0;
for (auto i = 0; i < frustum.vertices.size(); i++) {
if (tmp[i].x > aabb.getHalfExtents().x) {
out1++;
} else if (tmp[i].x < -aabb.getHalfExtents().x) {
out2++;
}
}
if (out1 == frustum.vertices.size() || out2 == frustum.vertices.size()) {
return 0;
}
out1 = 0;
out2 = 0;
for (auto i = 0; i < frustum.vertices.size(); i++) {
if (tmp[i].y > aabb.getHalfExtents().y) {
out1++;
} else if (tmp[i].y < -aabb.getHalfExtents().y) {
out2++;
}
}
if (out1 == frustum.vertices.size() || out2 == frustum.vertices.size()) {
return 0;
}
out1 = 0;
out2 = 0;
for (auto i = 0; i < frustum.vertices.size(); i++) {
if (tmp[i].z > aabb.getHalfExtents().z) {
out1++;
} else if (tmp[i].z < -aabb.getHalfExtents().z) {
out2++;
}
}
if (out1 == frustum.vertices.size() || out2 == frustum.vertices.size()) {
return 0;
}
return 1;
}
bool obbPoint(const OBB &obb, const Vec3 &point) {
Mat3 m3;
auto lessThan = [](const Vec3 &a, const Vec3 &b) -> bool {
return std::abs(a.x) < b.x && std::abs(a.y) < b.y && std::abs(a.z) < b.z;
};
auto tmp = point - obb.center;
Mat3::transpose(obb.orientation, &m3);
tmp.transformMat3(tmp, m3);
return lessThan(tmp, obb.halfExtents);
};
int obbPlane(const OBB &obb, const Plane &plane) {
auto absDot = [](const Vec3 &n, float x, float y, float z) -> float {
return std::abs(n.x * x + n.y * y + n.z * z);
};
// Real-Time Collision Detection, Christer Ericson, p. 163.
auto r = obb.halfExtents.x * absDot(plane.n, obb.orientation.m[0], obb.orientation.m[1], obb.orientation.m[2]) +
obb.halfExtents.y * absDot(plane.n, obb.orientation.m[3], obb.orientation.m[4], obb.orientation.m[5]) +
obb.halfExtents.z * absDot(plane.n, obb.orientation.m[6], obb.orientation.m[7], obb.orientation.m[8]);
auto dot = Vec3::dot(plane.n, obb.center);
if (dot + r < plane.d) {
return -1;
}
if (dot - r > plane.d) {
return 0;
}
return 1;
}
int obbFrustum(const OBB &obb, const Frustum &frustum) {
for (const auto &plane : frustum.planes) {
// frustum plane normal points to the inside
if (obbPlane(obb, *plane) == -1) {
return 0;
}
} // completely outside
return 1;
};
// https://cesium.com/blog/2017/02/02/tighter-frustum-culling-and-why-you-may-want-to-disregard-it/
int obbFrustumAccurate(const OBB &obb, const Frustum &frustum) {
ccstd::array<Vec3, 8> tmp = {};
float dist = 0.0F;
size_t out1 = 0;
size_t out2 = 0;
auto dot = [](const Vec3 &n, float x, float y, float z) -> float {
return n.x * x + n.y * y + n.z * z;
};
int result = 0;
auto intersects = false;
// 1. obb inside/outside frustum test
for (const auto &plane : frustum.planes) {
result = obbPlane(obb, *plane);
// frustum plane normal points to the inside
if (result == -1) {
return 0; // completely outside
}
if (result == 1) {
intersects = true;
}
}
if (!intersects) {
return 1;
} // completely inside
// in case of false positives
// 2. frustum inside/outside obb test
for (auto i = 0; i < frustum.vertices.size(); i++) {
tmp[i] = frustum.vertices[i] - obb.center;
}
out1 = 0;
out2 = 0;
for (auto i = 0; i < frustum.vertices.size(); i++) {
dist = dot(tmp[i], obb.orientation.m[0], obb.orientation.m[1], obb.orientation.m[2]);
if (dist > obb.halfExtents.x) {
out1++;
} else if (dist < -obb.halfExtents.x) {
out2++;
}
}
if (out1 == frustum.vertices.size() || out2 == frustum.vertices.size()) {
return 0.0F;
}
out1 = 0;
out2 = 0;
for (auto i = 0; i < frustum.vertices.size(); i++) {
dist = dot(tmp[i], obb.orientation.m[3], obb.orientation.m[4], obb.orientation.m[5]);
if (dist > obb.halfExtents.y) {
out1++;
} else if (dist < -obb.halfExtents.y) {
out2++;
}
}
if (out1 == frustum.vertices.size() || out2 == frustum.vertices.size()) {
return 0;
}
out1 = 0;
out2 = 0;
for (auto i = 0; i < frustum.vertices.size(); i++) {
dist = dot(tmp[i], obb.orientation.m[6], obb.orientation.m[7], obb.orientation.m[8]);
if (dist > obb.halfExtents.z) {
out1++;
} else if (dist < -obb.halfExtents.z) {
out2++;
}
}
if (out1 == frustum.vertices.size() || out2 == frustum.vertices.size()) {
return 0;
}
return 1;
}
int obbWithOBB(const OBB &obb1, const OBB &obb2) {
ccstd::array<Vec3, 8> vertices;
ccstd::array<Vec3, 8> vertices2;
ccstd::array<Vec3, 15> test;
test[0] = {obb1.orientation.m[0], obb1.orientation.m[1], obb1.orientation.m[2]};
test[1] = {obb1.orientation.m[3], obb1.orientation.m[4], obb1.orientation.m[5]};
test[2] = {obb1.orientation.m[6], obb1.orientation.m[7], obb1.orientation.m[8]};
test[3] = {obb2.orientation.m[0], obb2.orientation.m[1], obb2.orientation.m[2]};
test[4] = {obb2.orientation.m[3], obb2.orientation.m[4], obb2.orientation.m[5]};
test[5] = {obb2.orientation.m[6], obb2.orientation.m[7], obb2.orientation.m[8]};
for (auto i = 0; i < 3; ++i) { // Fill out rest of axis
Vec3::cross(test[i], test[3], &test[6 + i * 3 + 0]);
Vec3::cross(test[i], test[4], &test[6 + i * 3 + 1]);
Vec3::cross(test[i], test[5], &test[6 + i * 3 + 2]);
}
getOBBVertices(obb1.center, obb1.halfExtents, test[0], test[1], test[2], &vertices);
getOBBVertices(obb2.center, obb2.halfExtents, test[3], test[4], test[5], &vertices2);
for (auto i = 0; i < 15; ++i) {
auto a = getInterval(vertices, test[i]);
auto b = getInterval(vertices2, test[i]);
if (b.min > a.max || a.min > b.max) {
return 0; // Seperating axis found
}
}
return 1;
}
// https://github.com/diku-dk/bvh-tvcg18/blob/1fd3348c17bc8cf3da0b4ae60fdb8f2aa90a6ff0/FOUNDATION/GEOMETRY/GEOMETRY/include/overlap/geometry_overlap_obb_capsule.h
int obbCapsule(const OBB &obb, const Capsule &capsule) {
Sphere sphere{};
ccstd::array<Vec3, 8> v3Verts8{};
ccstd::array<Vec3, 8> v3Axis8{};
auto h = capsule.ellipseCenter0.distanceSquared(capsule.ellipseCenter1);
if (h == 0.0F) {
sphere.setRadius(capsule.radius);
sphere.setCenter(capsule.ellipseCenter0);
return sphereOBB(sphere, obb);
}
Vec3 v3Tmp0 = {
obb.orientation.m[0],
obb.orientation.m[1],
obb.orientation.m[2]};
Vec3 v3Tmp1 = {
obb.orientation.m[3],
obb.orientation.m[4],
obb.orientation.m[5]};
Vec3 v3Tmp2 = {
obb.orientation.m[6],
obb.orientation.m[7],
obb.orientation.m[8]};
getOBBVertices(obb.center, obb.halfExtents, v3Tmp0, v3Tmp1, v3Tmp2, &v3Verts8);
auto axes = v3Axis8;
auto a0 = axes[0] = v3Tmp0;
auto a1 = axes[1] = v3Tmp1;
auto a2 = axes[2] = v3Tmp2;
auto cc = axes[3] = capsule.center - obb.center;
auto bb = axes[4] = capsule.ellipseCenter0 - capsule.ellipseCenter1;
cc.normalize();
bb.normalize();
Vec3::cross(a0, bb, &axes[5]);
Vec3::cross(a1, bb, &axes[6]);
Vec3::cross(a2, bb, &axes[7]);
for (auto i = 0; i < 8; ++i) {
auto a = getInterval(v3Verts8, axes[i]);
auto d0 = Vec3::dot(axes[i], capsule.ellipseCenter0);
auto d1 = Vec3::dot(axes[i], capsule.ellipseCenter1);
auto dMin = std::min(d0, d1) - capsule.radius;
auto dMax = std::max(d0, d1) + capsule.radius;
if (dMin > a.max || a.min > dMax) {
return 0; // Seperating axis found
}
}
return 1;
}
int spherePlane(const Sphere &sphere, const Plane &plane) {
auto dot = Vec3::dot(plane.n, sphere.getCenter());
auto r = sphere.getRadius() * plane.n.length();
if (dot + r < plane.d) {
return -1;
}
if (dot - r > plane.d) {
return 0;
}
return 1;
}
int sphereFrustum(const Sphere &sphere, const Frustum &frustum) {
for (const auto &plane : frustum.planes) {
// frustum plane normal points to the inside
if (spherePlane(sphere, *plane) == -1) {
return 0;
}
} // completely outside
return 1;
}
int sphereFrustumAccurate(const Sphere &sphere, const Frustum &frustum) {
const static ccstd::array<int, 6> MAP = {1, -1, 1, -1, 1, -1};
for (auto i = 0; i < 6; i++) {
const auto &plane = frustum.planes[i];
const auto &n = plane->n;
const auto &d = plane->d;
auto r = sphere.getRadius();
const auto &c = sphere.getCenter();
auto dot = Vec3::dot(n, c);
// frustum plane normal points to the inside
if (dot + r < d) {
return 0; // completely outside
}
if (dot - r > d) {
continue;
}
// in case of false positives
// has false negatives, still working on it
auto pt = c + n * r;
for (auto j = 0; j < 6; j++) {
if (j == i || j == i + MAP[i]) {
continue;
}
const auto &test = frustum.planes[j];
if (Vec3::dot(test->n, pt) < test->d) {
return 0;
}
}
}
return 1;
}
bool sphereWithSphere(const Sphere &sphere0, const Sphere &sphere1) {
auto r = sphere0.getRadius() + sphere1.getRadius();
return sphere0.getCenter().distanceSquared(sphere1.getCenter()) < r * r;
}
bool sphereAABB(const Sphere &sphere, const AABB &aabb) {
Vec3 pt;
ptPointAabb(&pt, sphere.getCenter(), aabb);
return sphere.getCenter().distanceSquared(pt) < sphere.getRadius() * sphere.getRadius();
}
bool sphereOBB(const Sphere &sphere, const OBB &obb) {
Vec3 pt;
ptPointObb(&pt, sphere.getCenter(), obb);
return sphere.getCenter().distanceSquared(pt) < sphere.getRadius() * sphere.getRadius();
}
bool sphereCapsule(const Sphere &sphere, const Capsule &capsule) {
auto r = sphere.getRadius() + capsule.radius;
auto squaredR = r * r;
auto h = capsule.ellipseCenter0.distanceSquared(capsule.ellipseCenter1);
if (h == 0.0F) {
return sphere.getCenter().distanceSquared(capsule.center) < squaredR;
}
auto v3Tmp0 = sphere.getCenter() - capsule.ellipseCenter0;
auto v3Tmp1 = capsule.ellipseCenter1 - capsule.ellipseCenter0;
auto t = Vec3::dot(v3Tmp0, v3Tmp1) / h;
if (t < 0) {
return sphere.getCenter().distanceSquared(capsule.ellipseCenter0) < squaredR;
}
if (t > 1) {
return sphere.getCenter().distanceSquared(capsule.ellipseCenter1) < squaredR;
}
v3Tmp0 = capsule.ellipseCenter0 + t * v3Tmp1;
return sphere.getCenter().distanceSquared(v3Tmp0) < squaredR;
}
bool capsuleWithCapsule(const Capsule &capsuleA, const Capsule &capsuleB) {
auto u = capsuleA.ellipseCenter1 - capsuleA.ellipseCenter0;
auto v = capsuleB.ellipseCenter1 - capsuleB.ellipseCenter0;
auto w = capsuleA.ellipseCenter0 - capsuleB.ellipseCenter0;
auto a = Vec3::dot(u, u); // always >= 0
auto b = Vec3::dot(u, v);
auto c = Vec3::dot(v, v); // always >= 0
auto d = Vec3::dot(u, w);
auto e = Vec3::dot(v, w);
auto dd = a * c - b * b; // always >= 0
float sN;
float sD = dd; // sc = sN / sD, default sD = dd >= 0
float tN;
float tD = dd; // tc = tN / tD, default tD = dd >= 0
// compute the line parameters of the two closest points
if (dd < math::EPSILON) { // the lines are almost parallel
sN = 0.0F; // force using point P0 on segment S1
sD = 1.0F; // to prevent possible division by 0.0 later
tN = e;
tD = c;
} else { // get the closest points on the infinite lines
sN = (b * e - c * d);
tN = (a * e - b * d);
if (sN < 0.0F) { // sc < 0 => the s=0 edge is visible
sN = 0.0F;
tN = e;
tD = c;
} else if (sN > sD) { // sc > 1 => the s=1 edge is visible
sN = sD;
tN = e + b;
tD = c;
}
}
if (tN < 0.0F) { // tc < 0 => the t=0 edge is visible
tN = 0.0F;
// recompute sc for this edge
if (-d < 0.0F) {
sN = 0.0F;
} else if (-d > a) {
sN = sD;
} else {
sN = -d;
sD = a;
}
} else if (tN > tD) { // tc > 1 => the t=1 edge is visible
tN = tD;
// recompute sc for this edge
if ((-d + b) < 0.0F) {
sN = 0.0F;
} else if ((-d + b) > a) {
sN = sD;
} else {
sN = (-d + b);
sD = a;
}
}
// finally do the division to get sc and tc
auto sc = (std::abs(sN) < math::EPSILON ? 0.0F : sN / sD);
auto tc = (std::abs(tN) < math::EPSILON ? 0.0F : tN / tD);
// get the difference of the two closest points
auto dP = w;
dP = dP + u * sc;
dP = dP - v * tc;
auto radius = capsuleA.radius + capsuleB.radius;
return dP.lengthSquared() < radius * radius;
}
int dynObbFrustum(const OBB &obb, const Frustum &frustum) {
if (frustum.getType() == ShapeEnum::SHAPE_FRUSTUM_ACCURATE) {
return obbFrustumAccurate(obb, frustum);
}
return obbFrustum(obb, frustum);
}
int dynSphereFrustum(const Sphere &sphere, const Frustum &frustum) {
if (frustum.getType() == ShapeEnum::SHAPE_FRUSTUM_ACCURATE) {
return sphereFrustumAccurate(sphere, frustum);
}
return sphereFrustum(sphere, frustum);
}
int dynAabbFrustum(const AABB &aabb, const Frustum &frustum) {
if (frustum.getType() == ShapeEnum::SHAPE_FRUSTUM_ACCURATE) {
return aabbFrustumAccurate(aabb, frustum);
}
return aabbFrustum(aabb, frustum);
}
} // namespace geometry
} // namespace cc
| 35.619678 | 162 | 0.52178 | [
"mesh",
"geometry",
"vector",
"model",
"3d"
] |
ffbe44050f53f9f15472bf6e73f4585d5b79aa73 | 2,839 | cpp | C++ | src/GUI/Checkbox.cpp | Reewr/master | 76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b | [
"MIT"
] | 4 | 2017-05-22T04:14:06.000Z | 2022-02-09T19:15:10.000Z | src/GUI/Checkbox.cpp | Reewr/master | 76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b | [
"MIT"
] | null | null | null | src/GUI/Checkbox.cpp | Reewr/master | 76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b | [
"MIT"
] | null | null | null | #include "Checkbox.hpp"
#include <tinyxml2.h>
#include "../GLSL/Program.hpp"
#include "../Input/Event.hpp"
#include "../Resource/ResourceManager.hpp"
#include "../Resource/Texture.hpp"
#include "../Shape/GL/Rectangle.hpp"
#include "../Utils/Asset.hpp"
#include "Text.hpp"
Checkbox::Checkbox(const mmm::vec2& pos)
: Logging::Log("Checkbox"), mIsTicked(false) {
mBoundingBox = Rectangle(pos, mmm::vec2(21, 21));
mSquare = new GLRectangle();
mTick = new Text("Font::Dejavu", "", mmm::vec2(pos.x, pos.y - 3), 20);
mTick->setColor(Text::WHITE);
mSquare->setTexture(mAsset->rManager()->get<Texture>("Texture::Checkbox"));
mSquare->change(mBoundingBox);
}
/**
* @brief
* This loads the checkbox from XML. The syntax for the xml is:
*
* ```
* <checkbox x="50" y="20"/>
*
* It can also be within menues:
*
* <guimenu name="Something">
* <item name="SomethingElse">
* <checkbox x="50" y="20"/>
* </item>
* </guimenu>
* ```
*
* @param element
*
* @return a newly allocated checkbox. Has to be deleted manually
*/
Checkbox* Checkbox::fromXML(tinyxml2::XMLElement* element) {
mmm::vec2 position;
if (element->QueryFloatAttribute("x", &position.x) != 0) {
throw std::runtime_error("XMLElement has no float attribute 'x'");
}
if (element->QueryFloatAttribute("y", &position.y) != 0) {
throw std::runtime_error("XMLElement has no float attribute 'y'");
}
return new Checkbox(position);
}
Checkbox::~Checkbox() {
delete mTick;
delete mSquare;
}
/**
* @brief
* Sets whether or not the checkbox
* should be selected (ticked) based
* on the given screen position
*
* @param position
* screen position
*/
bool Checkbox::setSelected(const mmm::vec2& position) {
bool inside = isInside(position);
if (inside) {
mTick->setText((mIsTicked) ? "" : "X");
mIsTicked = !mIsTicked;
}
return inside;
}
/**
* @brief
* Sets the offset of the checkbox and
* all its elements
*
* @param offset
*/
void Checkbox::setOffset(const mmm::vec2& offset) {
mOffset = offset;
mTick->setOffset(offset);
}
/**
* @brief
*
* The default handler for the Dropbox is called whenever input()
* is called. This can be overriden by setting a handler using
* setInputHandler()
*
* The input handler set through this function can also
* call the default input handler, if the context is avaible.
*
* @param event
*
* @return
*/
void Checkbox::defaultInputHandler(const Input::Event& event) {
if (event.buttonPressed(GLFW_MOUSE_BUTTON_LEFT))
return;
if (setSelected(event.position()))
event.stopPropgation();
}
/**
* @brief
* Draws the checkbox and all its elements
*/
void Checkbox::draw() {
mGUIProgram->bind();
mGUIProgram->setUniform("guiOffset", mOffset);
mSquare->draw();
mTick->draw();
}
| 22.179688 | 79 | 0.650581 | [
"shape"
] |
ffc0afb17c6e3cde6e4baf4f6849ccd1f412a433 | 14,908 | cpp | C++ | libnd4j/tests_cpu/layers_tests/DeclarableOpsTests10.cpp | iKitkat/deeplearning4j | 13363d4bca532ec4badffaaeaec574c6e7fc4117 | [
"Apache-2.0"
] | 1 | 2018-08-29T05:46:54.000Z | 2018-08-29T05:46:54.000Z | libnd4j/tests_cpu/layers_tests/DeclarableOpsTests10.cpp | iKitkat/deeplearning4j | 13363d4bca532ec4badffaaeaec574c6e7fc4117 | [
"Apache-2.0"
] | null | null | null | libnd4j/tests_cpu/layers_tests/DeclarableOpsTests10.cpp | iKitkat/deeplearning4j | 13363d4bca532ec4badffaaeaec574c6e7fc4117 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// Created by raver on 8/4/2018.
//
#include "testlayers.h"
#include <ops/declarable/CustomOperations.h>
#include <NDArray.h>
#include <ops/ops.h>
#include <GradCheck.h>
using namespace nd4j;
class DeclarableOpsTests10 : public testing::Test {
public:
DeclarableOpsTests10() {
printf("\n");
fflush(stdout);
}
};
TEST_F(DeclarableOpsTests10, Test_ArgMax_1) {
NDArray<double> x('c', {3, 3});
NDArray<double> e(8);
x.linspace(1.0);
nd4j::ops::argmax<double> op;
auto result = op.execute({&x}, {}, {});
ASSERT_EQ(Status::OK(), result->status());
auto z = *result->at(0);
ASSERT_EQ(e, z);
delete result;
}
TEST_F(DeclarableOpsTests10, Test_ArgMax_2) {
NDArray<double> x('c', {3, 3});
NDArray<double> y('c', {1}, {1.0});
NDArray<double> e('c', {3}, {2.0, 2.0, 2.0});
x.linspace(1.0);
nd4j::ops::argmax<double> op;
auto result = op.execute({&x, &y}, {}, {});
ASSERT_EQ(Status::OK(), result->status());
auto z = *result->at(0);
//z.printIndexedBuffer("z");
//z.printShapeInfo("z shape");
ASSERT_EQ(e, z);
delete result;
}
TEST_F(DeclarableOpsTests10, Test_And_1) {
NDArray<double> x('c', {4}, {1, 1, 0, 1});
NDArray<double> y('c', {4}, {0, 0, 0, 1});
NDArray<double> e('c', {4}, {0, 0, 0, 1});
nd4j::ops::boolean_and<double> op;
auto result = op.execute({&x, &y}, {}, {});
ASSERT_EQ(Status::OK(), result->status());
ASSERT_EQ(e, *result->at(0));
delete result;
}
TEST_F(DeclarableOpsTests10, Test_Or_1) {
NDArray<double> x('c', {4}, {1, 1, 0, 1});
NDArray<double> y('c', {4}, {0, 0, 0, 1});
NDArray<double> e('c', {4}, {1, 1, 0, 1});
nd4j::ops::boolean_or<double> op;
auto result = op.execute({&x, &y}, {}, {});
ASSERT_EQ(Status::OK(), result->status());
ASSERT_EQ(e, *result->at(0));
delete result;
}
TEST_F(DeclarableOpsTests10, Test_Not_1) {
NDArray<double> x('c', {4}, {1, 1, 0, 1});
NDArray<double> y('c', {4}, {0, 0, 0, 1});
NDArray<double> e('c', {4}, {1, 1, 1, 0});
nd4j::ops::boolean_not<double> op;
auto result = op.execute({&x, &y}, {}, {});
ASSERT_EQ(Status::OK(), result->status());
ASSERT_EQ(e, *result->at(0));
delete result;
}
TEST_F(DeclarableOpsTests10, Test_Size_at_1) {
NDArray<double> x('c', {10, 20, 30});
NDArray<double> e(20.0);
nd4j::ops::size_at<double> op;
auto result = op.execute({&x}, {}, {1});
ASSERT_EQ(Status::OK(), result->status());
ASSERT_EQ(e, *result->at(0));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, Pad_SGO_Test_1) {
NDArray<double> in({1., 1., 1., 1., 1.});
// NDArray<double> pad('c', {1, 2}, {1., 1.});// = Nd4j.create(new double[]{1, 1}, new long[]{1, 2});
NDArray<double> pad('c', {1, 2}, {1., 1.});
// NDArray<double> value(10.0);
NDArray<double> exp({10., 1., 1., 1., 1., 1., 10.});
nd4j::ops::pad<double> op;
auto res = op.execute({&in, &pad}, {10.0}, {0});
ASSERT_EQ(res->status(), ND4J_STATUS_OK);
ASSERT_TRUE(exp.equalsTo(res->at(0)));
delete res;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, Unique_SGO_Test_1) {
NDArray<double> input({3., 4., 3., 1., 3., 0., 2., 4., 2., 4.});
NDArray<double> expIdx({0., 1., 0., 2., 0., 3., 4., 1., 4., 1.});
NDArray<double> exp({3., 4., 1., 0., 2.});
nd4j::ops::unique<double> op;
auto res = op.execute({&input}, {}, {});
ASSERT_TRUE(res->status() == ND4J_STATUS_OK);
//res->at(0)->printIndexedBuffer("Unique values");
//res->at(1)->printIndexedBuffer("Unique idxs");
ASSERT_TRUE(exp.equalsTo(res->at(0)));
ASSERT_TRUE(expIdx.equalsTo(res->at(1)));
delete res;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, Where_SGO_Test_1) {
NDArray<double> input('c', {3, 3}, {1., 0., 0., 1., 1., 0., 1., 1., 1.});
//NDArray<double> expIdx({0., 1., 0., 2., 0., 3., 4., 1., 4., 1.});
NDArray<double> exp('c', {6, 2}, {0., 0., 1., 0., 1., 1., 2., 0., 2., 1., 2., 2.});
nd4j::ops::Where<double> op;
auto res = op.execute({&input}, {}, {});
ASSERT_TRUE(res->status() == ND4J_STATUS_OK);
NDArray<double>* resA = res->at(0);
ASSERT_TRUE(exp.equalsTo(resA));
ASSERT_TRUE(exp.isSameShape(resA));
// ASSERT_TRUE(expIdx.equalsTo(res->at(1)));
delete res;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, WhereNP_SGO_Test_1) {
NDArray<double> cond3d('c', {2, 2, 2}, {1., 0., 0., 1., 1., 1., 1., 0.});
// NDArray<double> expIdx({0., 1., 0., 2., 0., 3., 4., 1., 4., 1.});
NDArray<double> exp1({0., 0., 1., 1., 1.});
NDArray<double> exp2({0., 1., 0., 0., 1.});
NDArray<double> exp3({0., 1., 0., 1., 0.});
nd4j::ops::where_np<double> op;
auto res = op.execute({&cond3d}, {}, {});
ASSERT_TRUE(res->size() == 3);
ASSERT_TRUE(res->status() == ND4J_STATUS_OK);
ASSERT_TRUE(exp1.equalsTo(res->at(0)));
ASSERT_TRUE(exp2.equalsTo(res->at(1)));
ASSERT_TRUE(exp3.equalsTo(res->at(2)));
//ASSERT_TRUE(expIdx.equalsTo(res->at(1)));
delete res;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, WhereNP_SGO_Test_2) {
NDArray<double> cond2d('c', {3, 5}, {1., 1., 0., 0., 1., 1., 1., 1., 1., 1., 0., 1., 1., 1., 1.});
// NDArray<double> expIdx({0., 1., 0., 2., 0., 3., 4., 1., 4., 1.});
NDArray<double> exp1({0., 0., 0., 1., 1., 1., 1., 1., 2., 2., 2., 2.});
NDArray<double> exp2({0., 1., 4., 0., 1., 2., 3., 4., 1., 2., 3., 4.});
nd4j::ops::where_np<double> op;
auto res = op.execute({&cond2d}, {}, {});
ASSERT_TRUE(res->size() == 2);
ASSERT_TRUE(res->status() == ND4J_STATUS_OK);
ASSERT_TRUE(exp1.equalsTo(res->at(0)));
ASSERT_TRUE(exp2.equalsTo(res->at(1)));
//ASSERT_TRUE(expIdx.equalsTo(res->at(1)));
delete res;
}
///////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, svd_test11) {
NDArray<double> x('c', {3,3}, {1.,2.,3.,4.,5.,6.,7.,8.,9.});
NDArray<double> expS('c', {3});
NDArray<double> expU('c', {3,3});
NDArray<double> expV('c', {3,3});
nd4j::ops::svd<double> op;
nd4j::ResultSet<double>* results = op.execute({&x}, {}, {0, 1, 16});
ASSERT_EQ(ND4J_STATUS_OK, results->status());
NDArray<double> *s = results->at(0);
NDArray<double> *u = results->at(1);
NDArray<double> *v = results->at(2);
ASSERT_TRUE(expS.isSameShape(s));
ASSERT_TRUE(expU.isSameShape(u));
ASSERT_TRUE(expV.isSameShape(v));
delete results;
}
//////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, atan2_test1) {
NDArray<double> y('c', {2, 3, 4}, {-1.001 ,-0.915 ,-0.829 ,-0.743 ,-0.657 ,-0.571 ,-0.485 ,-0.399 ,-0.313 ,-0.227 ,-0.141 ,-0.055 ,0.031 ,0.117 ,0.203 ,0.289 ,0.375 ,0.461 ,0.547 ,0.633 ,0.719 ,0.805 ,0.891 ,0.977});
NDArray<double> x('c', {2, 3, 4}, {-0.51, -0.46, -0.41, -0.36, -0.31, -0.26, -0.21, -0.16, -0.11, -0.06, -0.01, 0.04, 0.09, 0.14, 0.19, 0.24, 0.29, 0.34, 0.39, 0.44, 0.49, 0.54, 0.59, 0.61});
NDArray<double> exp('c', {2,3,4}, {-2.04201, -2.03663, -2.03009, -2.02199,-2.01166, -1.99808, -1.97941, -1.95217,-1.90875, -1.8292 , -1.6416 , -0.942 ,
0.33172, 0.69614, 0.81846, 0.87776, 0.91253, 0.93533, 0.95141, 0.96336, 0.97259, 0.97993, 0.98591, 1.01266,});
nd4j::ops::tf_atan2<double> op;
auto result = op.execute({&y, &x}, {}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto z = result->at(0);
ASSERT_TRUE(exp.isSameShape(z));
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
//////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, atan2_test2) {
NDArray<double> y('c', {2, 3, 4}, {-1.001 ,-0.915 ,-0.829 ,-0.743 ,-0.657 ,-0.571 ,-0.485 ,-0.399 ,-0.313 ,-0.227 ,-0.141 ,-0.055 ,0.031 ,0.117 ,0.203 ,0.289 ,0.375 ,0.461 ,0.547 ,0.633 ,0.719 ,0.805 ,0.891 ,0.977});
NDArray<double> x('c', { 3, 4}, {-1.05, -0.82, -0.639, -0.458, -0.277, -0.096, 0.085, 0.266, 0.447, 0.628, 0.809, 0.99});
NDArray<double> exp('c', {2,3,4}, {-2.38008, -2.30149, -2.22748, -2.1232 ,-1.96979, -1.73736, -1.3973 , -0.98279,-0.61088, -0.34685, -0.17256, -0.0555 ,
3.11208, 2.99987, 2.83399, 2.57869, 2.207 , 1.77611, 1.41664, 1.17298, 1.01458, 0.90829, 0.8336 , 0.77879});
nd4j::ops::tf_atan2<double> op;
auto result = op.execute({&y, &x}, {}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto z = result->at(0);
ASSERT_TRUE(exp.isSameShape(z));
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
//////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, atan2_test3) {
NDArray<double> y('c', {2, 3, 4}, {-1.001 ,-0.915 ,-0.829 ,-0.743 ,-0.657 ,-0.571 ,-0.485 ,-0.399 ,-0.313 ,-0.227 ,-0.141 ,-0.055 ,0.031 ,0.117 ,0.203 ,0.289 ,0.375 ,0.461 ,0.547 ,0.633 ,0.719 ,0.805 ,0.891 ,0.977});
NDArray<double> x('c', { 3, 4}, {-1.05, -0.82, -0.639, -0.458, -0.277, -0.096, 0.085, 0.266, 0.447, 0.628, 0.809, 0.99});
NDArray<double> exp('c', {2,3,4}, {-2.33231, -2.41089, -2.48491, -2.58919,-2.74259, -2.97502, 2.9681 , 2.55359, 2.18167, 1.91765, 1.74335, 1.62629,
-1.54128, -1.42907, -1.2632 , -1.00789,-0.63621, -0.20531, 0.15416, 0.39782, 0.55622, 0.6625 , 0.7372 , 0.79201});
nd4j::ops::tf_atan2<double> op;
auto result = op.execute({&x, &y}, {}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto z = result->at(0);
ASSERT_TRUE(exp.isSameShape(z));
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
//////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, atan2_test4) {
NDArray<double> y('c', {1, 3, 4}, {-1.001 ,-0.829 ,-0.657 ,-0.485 ,-0.313 ,-0.141 ,0.031 ,0.203 ,0.375 ,0.547 ,0.719 ,0.891});
NDArray<double> x('c', {2, 3, 1}, {-0.82, -0.458, -0.096, 0.085, 0.447, 0.809});
NDArray<double> exp('c', {2,3,4}, {-2.45527, -2.36165, -2.24628, -2.10492,-2.1703 , -1.86945, -1.50321, -1.15359,-0.25062, -0.17373, -0.13273, -0.10733,
3.05688, 3.03942, 3.01293, 2.9681 , 2.18167, 1.87635, 1.50156, 1.14451, 1.13674, 0.97626, 0.84423, 0.7372 });
nd4j::ops::tf_atan2<double> op;
auto result = op.execute({&x, &y}, {}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto z = result->at(0);
ASSERT_TRUE(exp.isSameShape(z));
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
//////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, atan2_test5) {
NDArray<double> y('c', {1, 3, 4}, {-1.001 ,-0.829 ,-0.657 ,-0.485 ,-0.313 ,-0.141 ,0.031 ,0.203 ,0.375 ,0.547 ,0.719 ,0.891});
NDArray<double> x('c', {2, 3, 1}, {-0.82, -0.458, -0.096, 0.085, 0.447, 0.809});
NDArray<double> exp('c', {2,3,4}, {-2.25712, -2.35074, -2.46611, -2.60747,-2.54209, -2.84294, 3.07401, 2.72438, 1.82141, 1.74453, 1.70353, 1.67813,
-1.48608, -1.46862, -1.44214, -1.3973 ,-0.61088, -0.30556, 0.06924, 0.42629, 0.43405, 0.59453, 0.72657, 0.8336 });
nd4j::ops::tf_atan2<double> op;
auto result = op.execute({&y, &x}, {}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto z = result->at(0);
ASSERT_TRUE(exp.isSameShape(z));
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
//////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, atan2_test6) {
NDArray<double> y('c', {1, 3, 4}, {-1.001 ,-0.829 ,-0.657 ,-0.485 ,-0.313 ,-0.141 ,0.031 ,0.203 ,0.375 ,0.547 ,0.719 ,0.891});
NDArray<double> x('c', { 4}, {-0.82, -0.096, 0.085, 0.809});
NDArray<double> exp('c', {1,3,4}, {-2.25712, -1.68608, -1.44214, -0.54006,-2.77695, -2.16855, 0.34972, 0.24585, 2.71267, 1.74453, 1.45312, 0.8336 });
nd4j::ops::tf_atan2<double> op;
auto result = op.execute({&y, &x}, {}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto z = result->at(0);
ASSERT_TRUE(exp.isSameShape(z));
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
//////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, range_test10) {
NDArray<double> limit('c', {1, 3, 4});
limit = 5.;
NDArray<double> exp('c', {5}, {0.,1.,2.,3.,4.});
nd4j::ops::range<double> op;
auto result = op.execute({&limit}, {}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto z = result->at(0);
ASSERT_TRUE(exp.isSameShape(z));
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
//////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, range_test11) {
NDArray<double> limit('c', {1, 3, 4});
NDArray<double> start('c', {2, 4});
limit = 5.;
start = 0.5;
NDArray<double> exp('c', {5}, {0.5,1.5,2.5,3.5,4.5});
nd4j::ops::range<double> op;
auto result = op.execute({&start, &limit}, {}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto z = result->at(0);
ASSERT_TRUE(exp.isSameShape(z));
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
//////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests10, range_test12) {
NDArray<double> exp('c', {9}, {0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5});
nd4j::ops::range<double> op;
auto result = op.execute({}, {0.5, 5, 0.5}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto z = result->at(0);
ASSERT_TRUE(exp.isSameShape(z));
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
| 35.077647 | 220 | 0.513751 | [
"shape"
] |
ffc8d73adcb5ad93456e306b0cf748384ae55b84 | 8,109 | cpp | C++ | SourceCode/append_to_output_tables.cpp | ChristinaB/Topnet-WM | abfed11a3792a43ad23000cbf3b2cb9161f19218 | [
"MIT"
] | null | null | null | SourceCode/append_to_output_tables.cpp | ChristinaB/Topnet-WM | abfed11a3792a43ad23000cbf3b2cb9161f19218 | [
"MIT"
] | 17 | 2018-03-19T17:26:04.000Z | 2019-06-06T00:15:35.000Z | SourceCode/append_to_output_tables.cpp | ChristinaB/Topnet-WM | abfed11a3792a43ad23000cbf3b2cb9161f19218 | [
"MIT"
] | 2 | 2018-03-25T01:55:20.000Z | 2019-05-09T22:12:50.000Z | /* Copyright 2017 Lambert Rubash
This file is part of TopNetCpp, a translation and enhancement of
Fortran TopNet.
TopNetCpp 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, either version 3 of the License, or
(at your option) any later version.
TopNetCpp 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 TopNetCpp. If not, see <http://www.gnu.org/licenses/>.
*/
#include "topnet.hh"
#include <iomanip>
using namespace constant_definitions;
using namespace input_structures;
using namespace other_structures;
using namespace TimeVaryingOutput;
using namespace std;
int Append_To_Output_Tables(const int Timestep, const int dt,
const int NumStreamNode, const int yyyymmdd, const int hhmmss,
const int NumLink, const int NumNode, const int Nsteps, const int NumUser)
{
int ius, ids, i, n, j, nfound, *ifound;
double ThisDrainageOutflow;
string LocationTypeString;
string fmtstr;
string str;
static ofstream outFile;
#if TRACE
static int ncalls = 0;
double tm0 = static_cast<double>(clock())/static_cast<double>(CLOCKS_PER_SEC);
string save_caller = caller;
if (ncalls < MAX_TRACE) {
traceFile << setw(30) << caller << " -> Append_To_Output_Tables(" << ncalls << ")" << std::endl;
}
caller = "Append_To_Output_Tables";
#endif
DateTime_yyyymmdd_hhmmss[Timestep-1][0] = yyyymmdd; //Timestep Date Time
DateTime_yyyymmdd_hhmmss[Timestep-1][1] = hhmmss; //Timestep Date Time
for (i = 1; i <= NumLink; i++) {
FlowInLinks_cms[Timestep-1][i-1] = Link[i-1].Flow/(double)(dt); //m3/s = m3/step / (s/step)
}
// considered writing outputs as we go here to avoid having to save all the time steps
// but FlowInLinks is used in a post processing calculation of WWTP outflows in Write_Output_tables
// so can not do this without restructuring that.
// find1()
nfound = 0; //none found
ifound = new int[NumNode];
ifound[nfound] = 0;
for (n = 0; n < NumNode; n++) {
if (Node[n].Type == ReservoirNodeCode) {
nfound++;
ifound[nfound-1] = n+1;
}
}
for (i = 1; i <= nfound; i++) {
ReservoirStorage_m3[Timestep-1][Node[ifound[i-1]-1].SelfID-1] = Node[ifound[i-1]-1].Store;
}
delete [] ifound;
// Flow through stream nodes
// first the drainage outlets
// new routing method
// there are two components to flow at any node
// 1. the local runoff - use FracRunoff (see read_inputs) to calculate this (we do not route this water from node to node)
// 2. flow(s) from drainages which flow directly into the drainage containing this node, and whose flowpaths do pass through this node
for (i = 0; i < NumStreamNode; i++) {
FlowAtStreamNodes_cms[i] = 0.0;
}
for (i = 1; i <= NumStreamNode; i++) {
// if(i.eq.107)then
// FlowAtStreamNodes_cms(1)=FlowAtStreamNodes_cms(1)
// endif
if (StreamNode[i-1].DOutFlag == 1) { //we need to propagate this flow to any internal stream nodes
// DGT 8/21/05 replaced DrainageOutFlow by Link%Flow because DrainageOutFlow is lacking management
// effects like diversions
ThisDrainageOutflow = Link[StreamNode[i-1].DrainageID*3-1].Flow/(double)dt; // DGT 8/21/05 Rely on the fact that LinkID is 3*DrainageID
//RAW 29-Aug-2005 look for user that is InStreamReservoirReleaseUseCode
//This is the user that sends spill flow and environmental releases to the downstream drainage
//To make this code faster, do this find2 ahead of time in the first call to watermgmt, and store the results
//or check for the existence of an instream reservoir located in this drainage
// find2()
nfound = 0; //none found
ifound = new int[NumUser];
ifound[nfound] = 0;
for (n = 0; n < NumUser; n++) {
if (User[n].UsersType == InStreamReservoirReleaseUseCode && User[n].POU_ID == StreamNode[i-1].DrainageID) {
nfound++;
ifound[nfound-1] = n+1;
}
}
if (nfound == 1) {
ThisDrainageOutflow += User[ifound[0]].Withdrawal[Timestep-1]/(double)dt;
}
delete [] ifound;
// find2()
nfound = 0; //none found
ifound = new int[NumUser];
ifound[nfound] = 0;
for (n = 0; n < NumUser; n++) {
if (User[n].UsersType == DownstreamReservoirReleaseUseCode && User[n].POU_ID == StreamNode[i-1].DrainageID) {
nfound++;
ifound[nfound-1] = n+1;
}
}
for (j = 1; j <= nfound; j++) {
ThisDrainageOutflow += User[ifound[j-1]-1].Withdrawal[Timestep-1]/(double)dt;
}
delete [] ifound;
// Code to also append Instreamflowuse
// find2()
nfound = 0; //none found
ifound = new int[NumUser];
ifound[nfound] = 0;
for (n = 0; n < NumUser; n++) {
if (User[n].UsersType == InstreamFlowUseCode && User[n].POU_ID == StreamNode[i-1].DrainageID) {
nfound++;
ifound[nfound-1] = n+1;
}
}
for (j = 1; j <= nfound; j++) {
ThisDrainageOutflow += User[ifound[j-1]-1].Withdrawal[Timestep-1]/(double)dt;
}
delete [] ifound;
// FlowAtStreamNodes_cms(i)=DrainageOutFlow(StreamNode[i-1].DrainageID)/float(dt)
FlowAtStreamNodes_cms[i-1] = ThisDrainageOutflow;
//now propagate this flow thru stream nodes down to next drainage outlet or end of network
ius = i;
// call find1(StreamNode%NodeId,StreamNode(ius)%DownNodeID,NumStreamNode) !would be more efficient to do this find back in watermgmt
// ids=ifound(1) !now start propagating downstream until we reach next drainage outlet, or end of network
ids = StreamNode[ius-1].DownNodeID; // find not necessary. Rely on node numbers in nodelinks.txt being a counting sequence starting at 1
if (ids >= 1) { // avoid addressing error
while (StreamNode[ius-1].DownNodeID != -1 && StreamNode[ids-1].DOutFlag != 1) {
FlowAtStreamNodes_cms[ids-1] += ThisDrainageOutflow;
// DrainageOutFlow(StreamNode[i-1].DrainageID)/float(dt)
ius = ids;
// call find1(StreamNode%NodeId,StreamNode(ius)%DownNodeId,NumStreamNode) !would be more efficient to do this find back in watermgmt
// ids=ifound(1)
ids = StreamNode[ius-1].DownNodeID; // find not necessary
if(ids < 1)
break; // avoid addressing error
} //while
}
} else {// this is an internal streamnode, we need to calculate local runoff to it
j = StreamNode[i-1].DrainageID; // j indicates the drainage which contains this node
FlowAtStreamNodes_cms[i-1] += StreamNode[i-1].FracRunoff*Runoff[Timestep-1].Rate[j-1]/(double)dt;
}
} //i
// all the water management calculations take place at the drainage outlet
// this calculation point is downstream of all "internal" stream nodes
// this model does not know whereabouts inside the drainage any water mgmt activity occurs
// thus the values of FlowAtStreamNodes_cms for nodes that are not at drainage outlets will not
// reflect the within-drainage water management
// if more spatial detail is requried then a finer drainage discretisation must be used
// Write the outputs as we go to save having to store all the time steps
if (Timestep == 1) {
outFile.open("results/FlowAtStreamNodes_cms.txt");
LocationTypeString = "Node";
outFile << setw(12) << "TimeStep";
for (i = 1; i <= NumStreamNode; i++) {
outFile << setw(15) << LocationTypeString << i;
}
outFile << '\n';
}
outFile << dec << setw(12) << Timestep;
for (j = 0; j < NumStreamNode; j++) {
outFile << scientific << setw(15) << setprecision(7) << FlowAtStreamNodes_cms[j];
}
outFile << '\n';
if(Timestep == Nsteps) {
outFile.close();
}
#if TRACE
double tm1 = static_cast<double>(clock())/static_cast<double>(CLOCKS_PER_SEC);
caller = save_caller;
if (ncalls < MAX_TRACE) {
traceFile << setw(30) << caller << " <- Leaving Append_To_Output_Tables(" << ncalls << ") ";
traceFile << tm1 - tm0 << " seconds\n\n";
}
ncalls++;
#endif
return 0;
}
| 38.614286 | 141 | 0.685658 | [
"model"
] |
ffcb5242d217c338c569bf60b5598692262f95bd | 880 | hpp | C++ | src/org/apache/poi/ss/usermodel/RichTextString.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/ss/usermodel/RichTextString.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/ss/usermodel/RichTextString.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/ss/usermodel/RichTextString.java
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <org/apache/poi/ss/usermodel/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct poi::ss::usermodel::RichTextString
: public virtual ::java::lang::Object
{
virtual void applyFont(int32_t startIndex, int32_t endIndex, int16_t fontIndex) = 0;
virtual void applyFont(int32_t startIndex, int32_t endIndex, Font* font) = 0;
virtual void applyFont(Font* font) = 0;
virtual void clearFormatting() = 0;
virtual ::java::lang::String* getString() = 0;
virtual int32_t length() = 0;
virtual int32_t numFormattingRuns() = 0;
virtual int32_t getIndexOfFormattingRun(int32_t index) = 0;
virtual void applyFont(int16_t fontIndex) = 0;
// Generated
static ::java::lang::Class *class_();
};
| 33.846154 | 88 | 0.711364 | [
"object"
] |
ffcf8fec797ae83c7ece75cafca74c60686232de | 2,839 | cpp | C++ | examples/Switch.System/BitConverterGetBytesDouble/BitConverterGetBytesDouble.cpp | victor-timoshin/Switch | 8e8e687a8bdc4f79d482680da3968e9b3e464b8b | [
"MIT"
] | 4 | 2020-02-11T13:22:58.000Z | 2022-02-24T00:37:43.000Z | examples/Switch.System/BitConverterGetBytesDouble/BitConverterGetBytesDouble.cpp | sgf/Switch | 8e8e687a8bdc4f79d482680da3968e9b3e464b8b | [
"MIT"
] | null | null | null | examples/Switch.System/BitConverterGetBytesDouble/BitConverterGetBytesDouble.cpp | sgf/Switch | 8e8e687a8bdc4f79d482680da3968e9b3e464b8b | [
"MIT"
] | 2 | 2020-02-01T02:19:01.000Z | 2021-12-30T06:44:00.000Z | #include <Switch/Switch>
using namespace System;
namespace Examples {
class Program {
public:
static const string formatter;
// Convert a double argument to a byte array and display it.
static void GetBytesDouble(double argument) {
Array<byte> byteArray = BitConverter::GetBytes(argument);
Console::WriteLine(formatter, argument, BitConverter::ToString(byteArray));
}
// The main entry point for the application.
static void Main() {
Console::WriteLine("This example of the BitConverter.GetBytes(double) "
"\nmethod generates the following output.\n");
Console::WriteLine(formatter, "double", "byte array");
Console::WriteLine(formatter, "------", "----------");
// Convert double values and display the results.
GetBytesDouble(0.0);
GetBytesDouble(1.0);
GetBytesDouble(255.0);
GetBytesDouble(4294967295.0);
GetBytesDouble(0.00390625);
GetBytesDouble(0.00000000023283064365386962890625);
GetBytesDouble(1.23456789012345E-300);
GetBytesDouble(1.2345678901234565);
GetBytesDouble(1.2345678901234567);
GetBytesDouble(1.2345678901234569);
GetBytesDouble(1.23456789012345678E+300);
GetBytesDouble(Double::MinValue);
GetBytesDouble(Double::MaxValue);
GetBytesDouble(Double::Epsilon);
GetBytesDouble(Double::NaN);
GetBytesDouble(Double::NegativeInfinity);
GetBytesDouble(Double::PositiveInfinity);
}
};
const string Program::formatter = "{0,25:E16}{1,30}";
}
startup_(Examples::Program);
// This code produces the following output:
//
// This example of the BitConverter.GetBytes( double )
// method generates the following output.
//
// double byte array
// ------ ----------
// 0.0000000000000000E+000 00-00-00-00-00-00-00-00
// 1.0000000000000000E+000 00-00-00-00-00-00-F0-3F
// 2.5500000000000000E+002 00-00-00-00-00-E0-6F-40
// 4.2949672950000000E+009 00-00-E0-FF-FF-FF-EF-41
// 3.9062500000000000E-003 00-00-00-00-00-00-70-3F
// 2.3283064365386963E-010 00-00-00-00-00-00-F0-3D
// 1.2345678901234500E-300 DF-88-1E-1C-FE-74-AA-01
// 1.2345678901234565E+000 FA-59-8C-42-CA-C0-F3-3F
// 1.2345678901234567E+000 FB-59-8C-42-CA-C0-F3-3F
// 1.2345678901234569E+000 FC-59-8C-42-CA-C0-F3-3F
// 1.2345678901234568E+300 52-D3-BB-BC-E8-7E-3D-7E
// -1.7976931348623157E+308 FF-FF-FF-FF-FF-FF-EF-FF
// 1.7976931348623157E+308 FF-FF-FF-FF-FF-FF-EF-7F
// 4.9406564584124654E-324 01-00-00-00-00-00-00-00
// NaN 00-00-00-00-00-00-F8-7F
// -Infinity 00-00-00-00-00-00-F0-FF
// Infinity 00-00-00-00-00-00-F0-7F
| 38.890411 | 81 | 0.630504 | [
"3d"
] |
ffd10c8ea5e68df1de4516e3c77dcf52d87bd9e1 | 2,978 | cpp | C++ | aws-cpp-sdk-kms/source/model/EncryptionAlgorithmSpec.cpp | grujicbr/aws-sdk-cpp | bdd43c178042f09c6739645e3f6cd17822a7c35c | [
"Apache-2.0"
] | 1 | 2020-03-11T05:36:20.000Z | 2020-03-11T05:36:20.000Z | aws-cpp-sdk-kms/source/model/EncryptionAlgorithmSpec.cpp | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-kms/source/model/EncryptionAlgorithmSpec.cpp | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/kms/model/EncryptionAlgorithmSpec.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace KMS
{
namespace Model
{
namespace EncryptionAlgorithmSpecMapper
{
static const int SYMMETRIC_DEFAULT_HASH = HashingUtils::HashString("SYMMETRIC_DEFAULT");
static const int RSAES_OAEP_SHA_1_HASH = HashingUtils::HashString("RSAES_OAEP_SHA_1");
static const int RSAES_OAEP_SHA_256_HASH = HashingUtils::HashString("RSAES_OAEP_SHA_256");
EncryptionAlgorithmSpec GetEncryptionAlgorithmSpecForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == SYMMETRIC_DEFAULT_HASH)
{
return EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT;
}
else if (hashCode == RSAES_OAEP_SHA_1_HASH)
{
return EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1;
}
else if (hashCode == RSAES_OAEP_SHA_256_HASH)
{
return EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<EncryptionAlgorithmSpec>(hashCode);
}
return EncryptionAlgorithmSpec::NOT_SET;
}
Aws::String GetNameForEncryptionAlgorithmSpec(EncryptionAlgorithmSpec enumValue)
{
switch(enumValue)
{
case EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT:
return "SYMMETRIC_DEFAULT";
case EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1:
return "RSAES_OAEP_SHA_1";
case EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256:
return "RSAES_OAEP_SHA_256";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace EncryptionAlgorithmSpecMapper
} // namespace Model
} // namespace KMS
} // namespace Aws
| 33.840909 | 98 | 0.670584 | [
"model"
] |
ffd35df09900a5b8d08a12d39ab519413b3daa16 | 12,532 | hpp | C++ | src/serac/physics/utilities/variant.hpp | jamiebramwell/serac | a839f8dc1560b1ec2b3d542f23a5f2ac71f2a962 | [
"BSD-3-Clause"
] | 1 | 2021-07-21T05:34:18.000Z | 2021-07-21T05:34:18.000Z | src/serac/physics/utilities/variant.hpp | jamiebramwell/serac | a839f8dc1560b1ec2b3d542f23a5f2ac71f2a962 | [
"BSD-3-Clause"
] | null | null | null | src/serac/physics/utilities/variant.hpp | jamiebramwell/serac | a839f8dc1560b1ec2b3d542f23a5f2ac71f2a962 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2019-2021, Lawrence Livermore National Security, LLC and
// other Serac Project Developers. See the top-level LICENSE file for
// details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
/**
* @file variant.hpp
*
* @brief This file contains the declaration of a two-element variant type
*
* This is necessary to work around an issue reported to LC in April 2021 regarding
* the use of the GCC 8 libstdc++ variant header with NVCC 11. As of July 2021 this
* has not been fixed. Additionally, the non-recursive implementation here should reduce
* compile times, though this effect may be limited for a variant with only two alternatives.
*/
#pragma once
#include <memory>
#include <type_traits>
namespace serac {
namespace detail {
/**
* @brief Storage abstraction to provide trivial destructor when both variant types are trivially destructible
* @tparam T0 The type of the first variant element
* @tparam T1 The type of the second variant element
* @tparam SFINAE Used to switch between the trivially destructible and not-trivially destructible implementations
*/
template <typename T0, typename T1, typename SFINAE = void>
struct variant_storage {
/**
* @brief The index of the active member
*/
int index_ = 0;
union {
T0 t0_;
T1 t1_;
};
/**
* @brief Copy constructor for nontrivial types
* Placement-new is required to correctly initialize the union
* @param[in] other The variant_storage to copy from
*/
constexpr variant_storage(const variant_storage& other) : index_(other.index_)
{
switch (index_) {
case 0: {
new (&t0_) T0(other.t0_);
break;
}
case 1: {
new (&t1_) T1(other.t1_);
break;
}
}
};
/**
* @brief Move constructor for nontrivial types
* Placement-new is required to correctly initialize the union
* @param[in] other The variant_storage to move from
*/
constexpr variant_storage(variant_storage&& other) : index_(other.index_)
{
switch (index_) {
case 0: {
new (&t0_) T0(std::move(other.t0_));
break;
}
case 1: {
new (&t1_) T1(std::move(other.t1_));
break;
}
}
};
/**
* @brief Resets the union by destroying the active member
* FIXME: The index is technically invalid here after this function is called
*/
constexpr void clear()
{
switch (index_) {
case 0: {
t0_.~T0();
break;
}
case 1: {
t1_.~T1();
break;
}
}
}
/**
* @brief Default constructor
* Default initializes the first member of the variant
*/
constexpr variant_storage() : index_{0}, t0_{} {}
/**
* @brief Destroys the variant by calling the destructor of the active member
*/
~variant_storage() { clear(); }
};
template <typename T0, typename T1>
struct variant_storage<T0, T1,
std::enable_if_t<std::is_trivially_destructible_v<T0> && std::is_trivially_destructible_v<T1>>> {
/**
* @brief The index of the active member
*/
int index_ = 0;
union {
T0 t0_;
T1 t1_;
};
/**
* @brief Default constructor
* Default initializes the first member of the variant
*/
constexpr variant_storage() : index_{0}, t0_{} {}
/**
* @brief No-op clear as both member types are trivially destructible
*/
constexpr void clear() {}
};
/**
* @brief Determines if T can be assigned to a variant<T0, T1>
* @tparam T The type on the right-hand side of the assignment
* @tparam T0 The first member type of the variant
* @tparam T1 The second member type of the variant
*/
template <typename T, typename T0, typename T1>
struct is_variant_assignable {
// FIXME: Is having just the is_assignable good enough?
constexpr static bool value = std::is_same_v<std::decay_t<T>, T0> || std::is_assignable_v<T0, T> ||
std::is_same_v<std::decay_t<T>, T1> || std::is_assignable_v<T1, T>;
};
} // namespace detail
// FIXME: Should we just #include <variant> for std::variant_alternative?? Probably don't want to pull in the full
// header
/**
* @brief Obtains the type at index @p I of a variant<T0, T1>
* @tparam I The index to find the corresponding type for
* @tparam T0 The first member type of the variant
* @tparam T1 The second member type of the variant
*/
template <int I, typename T0, typename T1>
struct variant_alternative;
template <typename T0, typename T1>
struct variant_alternative<0, T0, T1> {
using type = T0;
};
template <typename T0, typename T1>
struct variant_alternative<1, T0, T1> {
using type = T1;
};
/**
* @brief A simple variant type that supports only two elements
*
* Avoids the recursive template instantiation associated with std::variant
* and provides a (roughly) identical interface that is fully constexpr (when both types are
* trivially destructible)
* @tparam T0 The first member type of the variant
* @tparam T1 The second member type of the variant
*/
template <typename T0, typename T1>
struct variant {
/**
* @brief Storage abstraction used to provide constexpr functionality when applicable
*/
detail::variant_storage<T0, T1> storage_;
/**
* @brief Default constructor - will default-initialize first member of the variant
*/
constexpr variant() = default;
// These are needed explicitly so the variant(T&&) doesn't match first
constexpr variant(const variant&) = default;
constexpr variant(variant&&) = default;
/**
* @brief "Parameterized" constructor with which a value can be assigned
* @tparam T The type of the parameter to assign to one of the variant elements
* @param[in] t The parameter to assign to the variant's contents
* @pre The parameter type @p T must be equal to or assignable to either @p T0 or @p T1
* @note If the conversion is ambiguous, i.e., if @a t is equal or convertible to *both* @p T0 and @p T1,
* the first element of the variant - of type @p T0 - will be assigned to
*/
template <typename T, typename SFINAE = std::enable_if_t<detail::is_variant_assignable<T, T0, T1>::value>>
constexpr variant(T&& t)
{
if constexpr (std::is_same_v<std::decay_t<T>, T0> || std::is_assignable_v<T0, T>) {
storage_.index_ = 0;
new (&storage_.t0_) T0(std::forward<T>(t));
} else if constexpr (std::is_same_v<std::decay_t<T>, T1> || std::is_assignable_v<T1, T>) {
storage_.index_ = 1;
new (&storage_.t1_) T1(std::forward<T>(t));
} else {
static_assert(sizeof(T) < 0, "Type not supported");
}
}
// These are needed explicitly so the operator=(T&&) doesn't match first
constexpr variant& operator=(const variant&) = default;
constexpr variant& operator=(variant&&) = default;
/**
* "Parameterized" assignment with which a value can be assigned
* @tparam T The type of the parameter to assign to one of the variant elements
* @param[in] t The parameter to assign to the variant's contents
* @see variant::variant(T&& t) for notes and preconditions
*/
template <typename T, typename SFINAE = std::enable_if_t<detail::is_variant_assignable<T, T0, T1>::value>>
constexpr variant& operator=(T&& t)
{
// FIXME: Things that are convertible to T0 etc
if constexpr (std::is_same_v<std::decay_t<T>, T0>) {
if (storage_.index_ != 0) {
storage_.clear();
}
storage_.t0_ = std::forward<T>(t);
storage_.index_ = 0;
} else if constexpr (std::is_same_v<std::decay_t<T>, T1>) {
if (storage_.index_ != 1) {
storage_.clear();
}
storage_.t1_ = std::forward<T>(t);
storage_.index_ = 1;
} else {
static_assert(sizeof(T) < 0, "Type not supported");
}
return *this;
}
/**
* @brief Returns the index of the active variant member
*/
constexpr int index() const { return storage_.index_; }
/**
* @brief Returns the variant member at the provided index
* @tparam I The index of the element to retrieve
* @param[in] v The variant to return the element of
* @see std::variant::get
*/
template <int I>
friend constexpr typename variant_alternative<I, T0, T1>::type& get(variant& v)
{
if constexpr (I == 0) {
return v.storage_.t0_;
} else if constexpr (I == 1) {
return v.storage_.t1_;
}
}
/// @overload
template <int I>
friend constexpr const typename variant_alternative<I, T0, T1>::type& get(const variant& v)
{
if constexpr (I == 0) {
return v.storage_.t0_;
} else if constexpr (I == 1) {
return v.storage_.t1_;
}
}
};
/**
* @brief Returns the variant member of specified type
* @tparam T The type of the element to retrieve
* @tparam T0 The first member type of the variant
* @tparam T1 The second member type of the variant
* @param[in] v The variant to return the element of
* @see std::variant::get
* @pre T must be either @p T0 or @p T1
* @note If T == T0 == T1, the element at index 0 will be returned
*/
template <typename T, typename T0, typename T1>
constexpr T& get(variant<T0, T1>& v)
{
if constexpr (std::is_same_v<T, T0>) {
return get<0>(v);
} else if constexpr (std::is_same_v<T, T1>) {
return get<1>(v);
}
}
/// @overload
template <typename T, typename T0, typename T1>
constexpr const T& get(const variant<T0, T1>& v)
{
if constexpr (std::is_same_v<T, T0>) {
return get<0>(v);
} else if constexpr (std::is_same_v<T, T1>) {
return get<1>(v);
}
}
/**
* @brief Applies a functor to the active variant element
* @param[in] visitor The functor to apply
* @param[in] v The variant to apply the functor to
* @see std::visit
*/
template <typename Visitor, typename Variant>
constexpr decltype(auto) visit(Visitor visitor, Variant&& v)
{
if (v.index() == 0) {
return visitor(get<0>(v));
} else {
return visitor(get<1>(v));
}
}
/**
* @brief Checks whether a variant's active member is of a certain type
* @tparam T The type to check for
* @param[in] v The variant to check
* @see std::holds_alternative
*/
template <typename T, typename T0, typename T1>
bool holds_alternative(const variant<T0, T1>& v)
{
if constexpr (std::is_same_v<T, T0>) {
return v.index() == 0;
} else if constexpr (std::is_same_v<T, T1>) {
return v.index() == 1;
}
return false;
}
/**
* @brief Returns the member of requested type if it's active, otherwise @p nullptr
* @tparam T The type to check for
* @param[in] v The variant to check/retrieve from
* @see std::get_if
*/
template <typename T, typename T0, typename T1>
T* get_if(variant<T0, T1>* v)
{
if constexpr (std::is_same_v<T, T0>) {
return (v->index() == 0) ? &get<0>(*v) : nullptr;
} else if constexpr (std::is_same_v<T, T1>) {
return (v->index() == 1) ? &get<1>(*v) : nullptr;
}
return nullptr;
}
/// @overload
template <typename T, typename T0, typename T1>
const T* get_if(const variant<T0, T1>* v)
{
if constexpr (std::is_same_v<T, T0>) {
return (v->index() == 0) ? &get<0>(*v) : nullptr;
} else if constexpr (std::is_same_v<T, T1>) {
return (v->index() == 1) ? &get<1>(*v) : nullptr;
}
return nullptr;
}
namespace detail {
/**
* @brief A helper type for uniform semantics over owning/non-owning pointers
*
* This logic is needed to integrate with the mesh and field reconstruction logic
* provided by Sidre's MFEMSidreDataCollection. When a Serac restart occurs, the
* saved data is used to construct fully functional mfem::(Par)Mesh and
* mfem::(Par)GridFunction objects. The FiniteElementCollection and (Par)FiniteElementSpace
* objects are intermediates in the construction of these objects and are therefore owned
* by the MFEMSidreDataCollection in the case of a restart/reconstruction. In a normal run,
* Serac constructs the mesh and fields, so these FEColl and FESpace objects are owned
* by Serac. In both cases, the MFEMSidreDataCollection maintains ownership of the mesh
* and field objects themselves.
*/
template <typename T>
using MaybeOwningPointer = variant<T*, std::unique_ptr<T>>;
/**
* @brief Retrieves a reference to the underlying object in a MaybeOwningPointer
* @param[in] obj The object to dereference
*/
template <typename T>
static T& retrieve(MaybeOwningPointer<T>& obj)
{
return visit([](auto&& ptr) -> T& { return *ptr; }, obj);
}
/// @overload
template <typename T>
static const T& retrieve(const MaybeOwningPointer<T>& obj)
{
return visit([](auto&& ptr) -> const T& { return *ptr; }, obj);
}
} // namespace detail
} // namespace serac
| 30.270531 | 120 | 0.66406 | [
"mesh",
"object"
] |
ffd40f7b7ce83b8763ed3720015434853f5c247a | 446 | cpp | C++ | src/flatten_iterator_sample.cpp | Fadis/hermit | 1b378fb94165e0348d11d8065d3259d14c49977b | [
"BSD-2-Clause"
] | 1 | 2015-03-09T05:54:01.000Z | 2015-03-09T05:54:01.000Z | src/flatten_iterator_sample.cpp | Fadis/hermit | 1b378fb94165e0348d11d8065d3259d14c49977b | [
"BSD-2-Clause"
] | null | null | null | src/flatten_iterator_sample.cpp | Fadis/hermit | 1b378fb94165e0348d11d8065d3259d14c49977b | [
"BSD-2-Clause"
] | null | null | null | #include <hermit/flatten_iterator.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector< std::vector< int > > vec = { { 1, 2 }, { 3, 4 } };
hermit::flatten_iterator< std::vector< std::vector< int > >::iterator > begin( vec.begin() );
hermit::flatten_iterator< std::vector< std::vector< int > >::iterator > end( vec.end() );
std::for_each( begin, end, []( int x ) { std::cout << x << std::endl; } );
}
| 34.307692 | 95 | 0.612108 | [
"vector"
] |
ffd9b84298fdbf8ef4e6e106e521c1635e63acbd | 3,750 | cpp | C++ | generator/aipr.cpp | RuoAndo/Usenix_LISA19 | 966ee9593cf924ef8a8ace45cdb826b74b3b9001 | [
"MIT"
] | null | null | null | generator/aipr.cpp | RuoAndo/Usenix_LISA19 | 966ee9593cf924ef8a8ace45cdb826b74b3b9001 | [
"MIT"
] | null | null | null | generator/aipr.cpp | RuoAndo/Usenix_LISA19 | 966ee9593cf924ef8a8ace45cdb826b74b3b9001 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <random>
#include <vector>
#include <bitset>
#include<fstream>
#include <functional> //for std::function
#include <algorithm> //for std::generate_n
typedef std::vector<char> char_array;
char_array charset()
{
//Change this to suit
return char_array(
{'0','1','2','3','4',
'5','6','7','8','9',
'A','B','C','D','E','F',
'G','H','I','J','K',
'L','M','N','O','P',
'Q','R','S','T','U',
'V','W','X','Y','Z',
'a','b','c','d','e','f',
'g','h','i','j','k',
'l','m','n','o','p',
'q','r','s','t','u',
'v','w','x','y','z'
});
};
std::string random_string( size_t length, std::function<char(void)> rand_char )
{
std::string str(length,0);
std::generate_n( str.begin(), length, rand_char );
return str;
}
int GetRandom(int min,int max);
using namespace std;
std::vector<std::string> split_string_2(std::string str, char del) {
int first = 0;
int last = str.find_first_of(del);
std::vector<std::string> result;
while (first < str.size()) {
std::string subStr(str, first, last - first);
result.push_back(subStr);
first = last + 1;
last = str.find_first_of(del, first);
if (last == std::string::npos) {
last = str.size();
}
}
return result;
}
int main( int argc, char* argv[] )
{
int i;
int N = atoi(argv[1]);
if (argc != 2){
printf("usage: ./9 LINE_NUMBER");
exit(1);
}
/*
for (i = 0;i < 10;i++) {
printf("%d\n",GetRandom(1,6));
}
*/
std::random_device rnd;
std::mt19937 mt(rnd());
std::uniform_int_distribution<long> randD(20190702, 20190702);
std::uniform_int_distribution<long> randH(0, 23);
std::uniform_int_distribution<long> randM(0, 59);
std::uniform_int_distribution<long> randS(0, 59);
std::uniform_int_distribution<long> randMS(0, 1000);
long date;
long hour;
long minute;
long second;
long msec;
std::vector<long> tms;
string tmpstring;
string tmp_hour;
string tmp_minute;
string tmp_second;
string tmp_msec;
long long r;
for (int i = 0; i < N; ++i) {
date = randD(mt);
hour = randH(mt);
minute = randM(mt);
second = randS(mt);
msec = randMS(mt);
if(hour < 10)
tmp_hour = "0" + to_string(hour);
else
tmp_hour = to_string(hour);
if(minute < 10)
tmp_minute = "0" + to_string(minute);
else
tmp_minute = to_string(minute);
if(second < 10)
tmp_second = "0" + to_string(second);
else
tmp_second = to_string(second);
if(msec < 10)
tmp_msec = "00" + to_string(msec);
else if(msec < 100)
tmp_msec = "0" + to_string(msec);
else
tmp_msec = to_string(msec);
// cout << tmp_msec << endl;
tmpstring = to_string(date) + tmp_hour + tmp_hour + tmp_minute + tmp_msec;
// cout << tmpstring << endl;
r = stoll(tmpstring);
tms.push_back(r);
}
std::sort(tms.begin(), tms.end());
ofstream outputfile("random_data.txt");
for (int i = 0; i < N; ++i) {
tmpstring = to_string(tms[i]);
outputfile << "\"" << tmpstring.substr( 0, 4 )
<< "/"
<< tmpstring.substr( 4, 2 )
<< "/"
<< tmpstring.substr( 6, 2 )
<< " "
<< tmpstring.substr( 8, 2 )
<< ":"
<< tmpstring.substr( 10, 2 )
<< ":"
<< tmpstring.substr( 12, 2 )
<< "."
<< tmpstring.substr( 14, 3 )
<< "\"" << "," ;
outputfile << "\"" << GetRandom(1,1000) << "\"";
outputfile << "," << "\"" << GetRandom(1,65535) << "\"";
outputfile << endl;
}
outputfile.close();
return 0;
}
int GetRandom(int min,int max)
{
return min + (int)(rand()*(max-min+1.0)/(1.0+RAND_MAX));
}
| 20.27027 | 79 | 0.548 | [
"vector"
] |
ffda3702a972395a7473a33d9ac4b744f1720abb | 2,217 | cpp | C++ | Source/SprueEngine/Libs/igl/matlab/parse_rhs.cpp | Qt-Widgets/TexGraph | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | [
"MIT"
] | 35 | 2017-04-07T22:49:41.000Z | 2021-08-03T13:59:20.000Z | Source/SprueEngine/Libs/igl/matlab/parse_rhs.cpp | Qt-Widgets/TexGraph | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | [
"MIT"
] | 1 | 2017-04-13T17:43:54.000Z | 2017-04-15T04:17:37.000Z | Source/SprueEngine/Libs/igl/matlab/parse_rhs.cpp | Qt-Widgets/TexGraph | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | [
"MIT"
] | 7 | 2019-03-11T19:26:53.000Z | 2021-03-04T07:17:10.000Z | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2015 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "parse_rhs.h"
#include <algorithm>
template <typename DerivedV>
IGL_INLINE void igl::matlab::parse_rhs_double(
const mxArray *prhs[],
Eigen::PlainObjectBase<DerivedV> & V)
{
using namespace std;
using namespace Eigen;
// set number of mesh vertices
const int n = mxGetM(prhs[0]);
// set vertex position pointers
double * Vp = mxGetPr(prhs[0]);
const int dim = mxGetN(prhs[0]);
typedef typename DerivedV::Scalar Scalar;
Matrix<Scalar, DerivedV::ColsAtCompileTime, DerivedV::RowsAtCompileTime, RowMajor> VT;
Scalar * V_data;
if(DerivedV::IsRowMajor)
{
VT.resize(dim,n);
V_data = VT.data();
}else
{
V.resize(n,dim);
V_data = V.data();
}
copy(Vp,Vp+n*dim,V_data);
if(DerivedV::IsRowMajor)
{
V = VT.transpose();
}
}
template <typename DerivedV>
IGL_INLINE void igl::matlab::parse_rhs_index(
const mxArray *prhs[],
Eigen::PlainObjectBase<DerivedV> & V)
{
parse_rhs_double(prhs,V);
V.array() -= 1;
}
#ifdef IGL_STATIC_LIBRARY
template void igl::matlab::parse_rhs_index<Eigen::Matrix<int, -1, 1, 0, -1, 1> >(mxArray_tag const**, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::matlab::parse_rhs_index<Eigen::Matrix<int, -1, -1, 0, -1, -1> >(mxArray_tag const**, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
template void igl::matlab::parse_rhs_double<Eigen::Matrix<double, -1, -1, 0, -1, -1> >(mxArray_tag const**, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
template void igl::matlab::parse_rhs_index<Eigen::Matrix<int, -1, 3, 1, -1, 3> >(mxArray_tag const**, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> >&);
template void igl::matlab::parse_rhs_double<Eigen::Matrix<double, -1, 3, 1, -1, 3> >(mxArray_tag const**, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> >&);
#endif
| 37.576271 | 176 | 0.676139 | [
"mesh",
"geometry"
] |
ffdc5d0d10b42194c4294c67fe2fbe23cb343530 | 1,031 | hh | C++ | thirdparty/vpp/vpp/core/colorspace_conversions.hh | pdebus/MTVMTL | 65a7754b34d1f6a1e86d15e3c2d4346b9418414f | [
"MIT"
] | 3 | 2017-05-08T12:40:46.000Z | 2019-06-02T05:11:01.000Z | thirdparty/vpp/vpp/core/colorspace_conversions.hh | pdebus/MTVMTL | 65a7754b34d1f6a1e86d15e3c2d4346b9418414f | [
"MIT"
] | null | null | null | thirdparty/vpp/vpp/core/colorspace_conversions.hh | pdebus/MTVMTL | 65a7754b34d1f6a1e86d15e3c2d4346b9418414f | [
"MIT"
] | null | null | null | #ifndef VPP_CORE_COLORSPACE_CONVERSIONS_HH__
# define VPP_CORE_COLORSPACE_CONVERSIONS_HH__
# include <vpp/core/pixel_wise.hh>
namespace vpp
{
template <typename T, typename U>
void rgb_to_graylevel(const vector<U, 3>& i, vector<T, 1>& o)
{
o[0] = (i[0] + i[1] + i[2]) / 3;
}
template <typename T, typename U, unsigned N>
imageNd<T, N> rgb_to_graylevel(const imageNd<vector<U, 3>, N>& in)
{
typedef T out_type;
typedef vector<U, 3> in_type;
imageNd<out_type, N> out(in.domain(), _border = in.border());
pixel_wise(in, out) | [] (const in_type& i, out_type& o)
{
o = T((i[0] + i[1] + i[2]) / 3);
};
return out;
}
template <typename T, typename U, unsigned N>
imageNd<T, N> graylevel_to_rgb(const imageNd<U, N>& in)
{
typedef T out_type;
typedef U in_type;
imageNd<out_type, N> out(in.domain(), _border = in.border());
pixel_wise(in, out) | [] (const in_type& i, out_type& o)
{
o = out_type(i, i, i);
};
return out;
}
};
#endif
| 22.911111 | 68 | 0.611057 | [
"vector"
] |
ffdc7d4cfdf3a1903f49523730e3ff795a0de126 | 882 | cpp | C++ | UVa Online Judge/11679.cpp | xiezeju/ACM-Code-Archives | db135ed0953adcf5c7ab37a00b3f9458291ce0d7 | [
"MIT"
] | 1 | 2022-02-24T12:44:30.000Z | 2022-02-24T12:44:30.000Z | UVa Online Judge/11679.cpp | xiezeju/ACM-Code-Archives | db135ed0953adcf5c7ab37a00b3f9458291ce0d7 | [
"MIT"
] | null | null | null | UVa Online Judge/11679.cpp | xiezeju/ACM-Code-Archives | db135ed0953adcf5c7ab37a00b3f9458291ce0d7 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
const int INF = 1e9;
const long long LLINF = 4e18;
const double EPS = 1e-9;
int reserves[22];
int main() {
ios::sync_with_stdio(false);
int b, n, from, to, value;
while (~scanf("%d%d", &b, &n) && n + b) {
for (int i = 1; i <= b; ++ i)
scanf("%d", &reserves[i]);
for (int i = 1; i <= n; ++ i) {
scanf("%d%d%d", &from, &to, &value);
reserves[from] -= value;
reserves[to] += value;
}
int flag = 1;
for (int i = 1; i <= b; ++ i) {
if (reserves[i] < 0) {
flag = 0;
break;
}
}
if (flag)
puts("S");
else
puts("N");
}
return 0;
}
| 21.512195 | 48 | 0.441043 | [
"vector"
] |
ffdcc1ad9c347052f3399674e3eed6415cd79cc8 | 6,426 | cpp | C++ | src/cascadia/UnitTests_TerminalCore/SelectionTest.cpp | peterdn/terminal | 315abf6fa6e096f0ad8ba7db68fa8a3fd9a591b1 | [
"MIT"
] | 1 | 2021-03-24T02:51:15.000Z | 2021-03-24T02:51:15.000Z | src/cascadia/UnitTests_TerminalCore/SelectionTest.cpp | lhmrnfrzrfr/terminal | 315abf6fa6e096f0ad8ba7db68fa8a3fd9a591b1 | [
"MIT"
] | null | null | null | src/cascadia/UnitTests_TerminalCore/SelectionTest.cpp | lhmrnfrzrfr/terminal | 315abf6fa6e096f0ad8ba7db68fa8a3fd9a591b1 | [
"MIT"
] | 1 | 2019-08-09T11:28:33.000Z | 2019-08-09T11:28:33.000Z | /*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*
* This File was generated using the VisualTAEF C++ Project Wizard.
* Class Name: SelectionTest
*/
#include "precomp.h"
#include <WexTestClass.h>
#include "../cascadia/TerminalCore/Terminal.hpp"
#include "../renderer/inc/DummyRenderTarget.hpp"
#include "consoletaeftemplates.hpp"
using namespace WEX::Logging;
using namespace WEX::TestExecution;
using namespace Microsoft::Terminal::Core;
using namespace Microsoft::Console::Render;
namespace TerminalCoreUnitTests
{
class SelectionTest
{
TEST_CLASS(SelectionTest);
TEST_METHOD(SelectUnit)
{
Terminal term = Terminal();
DummyRenderTarget emptyRT;
term.Create({ 100, 100 }, 0, emptyRT);
// Simulate click at (x,y) = (5,10)
auto clickPos = COORD{ 5, 10 };
term.SetSelectionAnchor(clickPos);
// Simulate renderer calling TriggerSelection and acquiring selection area
auto selectionRects = term.GetSelectionRects();
// Validate selection area
VERIFY_ARE_EQUAL(selectionRects.size(), static_cast<size_t>(1));
auto selection = term.GetViewport().ConvertToOrigin(selectionRects.at(0)).ToInclusive();
VerifyCompareTraits<SMALL_RECT>::AreEqual({ 5, 10, 10, 5 }, selection);
}
TEST_METHOD(SelectArea)
{
Terminal term = Terminal();
DummyRenderTarget emptyRT;
term.Create({ 100, 100 }, 0, emptyRT);
// Used for two things:
// - click y-pos
// - keep track of row we're verifying
SHORT rowValue = 10;
// Simulate click at (x,y) = (5,10)
term.SetSelectionAnchor({ 5, rowValue });
// Simulate move to (x,y) = (15,20)
term.SetEndSelectionPosition({ 15, 20 });
// Simulate renderer calling TriggerSelection and acquiring selection area
auto selectionRects = term.GetSelectionRects();
// Validate selection area
VERIFY_ARE_EQUAL(selectionRects.size(), static_cast<size_t>(11));
auto viewport = term.GetViewport();
SHORT rightBoundary = viewport.RightInclusive();
for (auto selectionRect : selectionRects)
{
auto selection = viewport.ConvertToOrigin(selectionRect).ToInclusive();
if (rowValue == 10)
{
// Verify top line
VerifyCompareTraits<SMALL_RECT>::AreEqual({ 5, 10, rightBoundary, 10 }, selection);
}
else if (rowValue == 20)
{
// Verify bottom line
VerifyCompareTraits<SMALL_RECT>::AreEqual({ 0, 20, 15, 20 }, selection);
}
else
{
// Verify other lines (full)
VerifyCompareTraits<SMALL_RECT>::AreEqual({ 0, rowValue, rightBoundary, rowValue }, selection);
}
rowValue++;
}
}
TEST_METHOD(SelectBoxArea)
{
Terminal term = Terminal();
DummyRenderTarget emptyRT;
term.Create({ 100, 100 }, 0, emptyRT);
// Used for two things:
// - click y-pos
// - keep track of row we're verifying
SHORT rowValue = 10;
// Simulate ALT + click at (x,y) = (5,10)
term.SetSelectionAnchor({ 5, rowValue });
term.SetBoxSelection(true);
// Simulate move to (x,y) = (15,20)
term.SetEndSelectionPosition({ 15, 20 });
// Simulate renderer calling TriggerSelection and acquiring selection area
auto selectionRects = term.GetSelectionRects();
// Validate selection area
VERIFY_ARE_EQUAL(selectionRects.size(), static_cast<size_t>(11));
auto viewport = term.GetViewport();
for (auto selectionRect : selectionRects)
{
auto selection = viewport.ConvertToOrigin(selectionRect).ToInclusive();
// Verify all lines
VerifyCompareTraits<SMALL_RECT>::AreEqual({ 5, rowValue, 15, rowValue }, selection);
rowValue++;
}
}
TEST_METHOD(SelectAreaAfterScroll)
{
Terminal term = Terminal();
DummyRenderTarget emptyRT;
SHORT scrollbackLines = 5;
term.Create({ 100, 100 }, scrollbackLines, emptyRT);
// Used for two things:
// - click y-pos
// - keep track of row we're verifying
SHORT rowValue = 10;
// Simulate click at (x,y) = (5,10)
term.SetSelectionAnchor({ 5, rowValue });
// Simulate move to (x,y) = (15,20)
term.SetEndSelectionPosition({ 15, 20 });
// Simulate renderer calling TriggerSelection and acquiring selection area
auto selectionRects = term.GetSelectionRects();
// Validate selection area
VERIFY_ARE_EQUAL(selectionRects.size(), static_cast<size_t>(11));
auto viewport = term.GetViewport();
SHORT rightBoundary = viewport.RightInclusive();
for (auto selectionRect : selectionRects)
{
auto selection = viewport.ConvertToOrigin(selectionRect).ToInclusive();
if (rowValue == 10)
{
// Verify top line
VerifyCompareTraits<SMALL_RECT>::AreEqual({ 5, 10, rightBoundary, 10 }, selection);
}
else if (rowValue == 20)
{
// Verify bottom line
VerifyCompareTraits<SMALL_RECT>::AreEqual({ 0, 20, 15, 20 }, selection);
}
else
{
// Verify other lines (full)
VerifyCompareTraits<SMALL_RECT>::AreEqual({ 0, rowValue, rightBoundary, rowValue }, selection);
}
rowValue++;
}
}
};
} | 35.307692 | 116 | 0.528945 | [
"render"
] |
ffdd0953cd334c8de03f25ab54964d86a2a15451 | 47,096 | cpp | C++ | python_sdk_18.04/samples/gui/QtCheetahPythonGainUI/QtCheetahPythonGainUI.cpp | vignesh-narayanaswamy/camsdk | 5c6aa96d0715cd77c42abb90449b740a2940d8a0 | [
"Apache-2.0"
] | null | null | null | python_sdk_18.04/samples/gui/QtCheetahPythonGainUI/QtCheetahPythonGainUI.cpp | vignesh-narayanaswamy/camsdk | 5c6aa96d0715cd77c42abb90449b740a2940d8a0 | [
"Apache-2.0"
] | null | null | null | python_sdk_18.04/samples/gui/QtCheetahPythonGainUI/QtCheetahPythonGainUI.cpp | vignesh-narayanaswamy/camsdk | 5c6aa96d0715cd77c42abb90449b740a2940d8a0 | [
"Apache-2.0"
] | null | null | null | #include "QtCheetahPythonGainUI.h"
//Imperx Camera API Functions
#include "IpxCameraApi.h"
//Imperx Image Functions
#include "IpxImage.h"
//Imperx Camera API Functions
#include "IpxCameraGuiApi.h"
//Imperx Display Functions
#include "IpxDisplay.h"
#include <string>
#include <algorithm>
#include <iostream>
#include <stdio.h>
#include <map>
#include <cmath>
// ===========================================================================
// QtCheetahPythonGainUI Constructor
//
// The Constructor initializes the ThreadDisplay, Camera, IpxDisplay, IpxStream, IpxDeviceInfo
// modules to null. Then, it loads the Imperx Icon and initializes the System of the
// GenTL Module Hierachy.
// =============================================================================
QtCheetahPythonGainUI::QtCheetahPythonGainUI(QWidget *parent)
: QMainWindow(parent)
, m_grabThread(nullptr)
, m_camera(nullptr)
, m_display(IpxDisplay::CreateComponent())
, m_stream(nullptr)
, m_devInfo(nullptr)
, m_parameterView(nullptr)
, m_isConnected (false)
, m_bNewXml( false )
{
ui.setupUi(this);
CreateLayout();
SetupToolbarConnects();
UpdateToolbarButtons();
// Gets The System object that is the entry point to the GenTL Producer software driver
m_system = IpxCam::IpxCam_GetSystem();
// Initialize the display
if(m_display)
{
m_display->Initialize(m_displayLabel);
ZoomFitToWnd();
}
else
{
QMessageBox::critical(this, "", "ERROR: Unable to create the Display Object.");
}
}
// =============================================================================
// The QtCheetahPythonGainUI Destructor
//
// The Destructor is Delete the IpxDisplay Component Module
// =============================================================================
QtCheetahPythonGainUI::~QtCheetahPythonGainUI()
{
// Deletes the grabbing thread
if(m_grabThread)
delete m_grabThread;
// Deletes the IpcDisplay Component Module object
if(m_display)
{
IpxDisplay::DeleteComponent(m_display);
//Reset the pointer to null
m_display = nullptr;
}
if(m_displayLabel)
delete m_displayLabel;
}
void QtCheetahPythonGainUI::cameraConnect()
{
if(!m_system)
m_system = IpxCam::IpxCam_GetSystem();
// Open Discovery dialog
IpxGui::IpxCameraSelectorDialog cameraSelectionDlg(m_system);
IpxCam::DeviceInfo *devInfo = nullptr;
if(cameraSelectionDlg.exec() == QDialog::Accepted && (devInfo = cameraSelectionDlg.selectedCamera()))
{
}
}
bool QtCheetahPythonGainUI::SetupToolbarConnects()
{
// Connect the GUI signals with slots
connect(ui.actionConnect, SIGNAL(triggered(bool)), this, SLOT(OnBnClickedConnectButton()));
connect(ui.actionDisconnect, SIGNAL(triggered(bool)), this, SLOT(OnBnClickedDisconnectButton()));
connect(ui.actionPlay, SIGNAL(triggered(bool)), this, SLOT(OnBnClickedStart()));
connect(ui.actionStop, SIGNAL(triggered(bool)), this, SLOT(OnBnClickedStop()));
connect(ui.actionGenICamTree, SIGNAL(triggered(bool)), this, SLOT(OnBnClickedGenICamButton()));
connect(ui.actionZoomIn, SIGNAL(triggered(bool)), this, SLOT(OnZoomIn()));
connect(ui.actionZoomOut, SIGNAL(triggered(bool)), this, SLOT(OnZoomOut()));
connect(ui.actionFitToWindow, SIGNAL(triggered(bool)), this, SLOT(OnZoomFitToWnd()));
connect(ui.actionActualSize, SIGNAL(triggered(bool)), this, SLOT(OnZoom100()));
connect(ui.actionSpreadToWindow, SIGNAL(triggered(bool)), this, SLOT(OnZoomSpreadToWnd()));
connect(ui.actionCenterImage, SIGNAL(triggered(bool)), this, SLOT(OnCenterImage()));
return true;
}
void QtCheetahPythonGainUI::closeEvent(QCloseEvent * event)
{
if(m_isConnected)
Disconnect();
// Delete the grabbing thread
if(m_grabThread)
delete m_grabThread;
m_grabThread = nullptr;
if(m_display)
{
IpxDisplay::DeleteComponent(m_display);
m_display = nullptr;
}
QMainWindow::closeEvent(event);
}
void QtCheetahPythonGainUI::InitFromCamera()
{
//////////////////////////////////////////////////////////////////////
/// example how to map enum parameter with combo box
//////////////////////////////////////////////////////////////////////
// Get GenICam parameter value
auto paramArray = m_camera->GetCameraParameters();
if (!paramArray)
return;
if(m_bNewXml)
{
m_mapData.mapEnumParam(paramArray->GetEnum("AnalogGain", nullptr), m_cbAnalogGain);
m_mapData.mapEnumParam(paramArray->GetEnum("BlackLevelAuto", nullptr), m_cbBlackLevelAutoCal);
}
else
{
m_mapData.mapEnumParam(paramArray->GetEnum("Frame_AnalogGain", nullptr), m_cbAnalogGain);
m_mapData.mapEnumParam(paramArray->GetEnum("Frame_BlackLevelAutoCalibration", nullptr), m_cbBlackLevelAutoCal);
}
IpxCamErr err;
//Retrieve the Digital Gain Value
int64_t DigitalGainCode=0;
double DigitalGain=0., DigitalGainDB=0.;
if(m_bNewXml)
{
DigitalGainCode = paramArray->GetIntegerValue("DigitalGainRaw",&err);
if( err != IPX_CAM_ERR_OK)
QMessageBox::critical(this, "Error", "DigitalGain get failed");
}
else
{
DigitalGainCode = paramArray->GetIntegerValue("Frame_DigitalGain",&err);
if( err != IPX_CAM_ERR_OK)
QMessageBox::critical(this, "Error","Frame_DigitalGain get failed");
}
// Update the Edit Box with the Frame_DigitalGain value retrieved
m_edDigitalGainCode->setText(QString::number(DigitalGainCode));
// Calculate the DigitalGain in times(x)
DigitalGain = floor(10.*.0009765625*DigitalGainCode + 0.5f)/10;
// Display Digital Gain Value
m_edDigitalGain->setText(QString::number(DigitalGain, 'f', 1));
//Convert and display Digital Gain Decibels
DigitalGainDB = 20.0*log10(DigitalGain);
m_edDigitalGainDB->setText(QString::number(DigitalGainDB, 'f', 1));
int calEn = m_cbBlackLevelAutoCal->currentIndex();
//If BlackLevelAutoCalibration is Off, then retrieve the Black Level Offset and display its value
if(calEn == 0)
{
int64_t prev_black_level = 0;
int64_t int_prev_black_level=0;
IpxCamErr err=IPX_CAM_ERR_OK;
if(m_bNewXml)
{
prev_black_level = (int64_t)paramArray->GetFloatValue("BlackLevel", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
{
QMessageBox::critical(this, "ERROR", "Unable to retrieve BlackLevel\r\n" );
return;
}
}
else
{
prev_black_level = paramArray->GetIntegerValue("Frame_BlackLevelOffset", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
{
QMessageBox::critical(this, "ERROR", "Unable to retrieve Frame_BlackLevelOffset\r\n" );
return;
}
}
int signed_value = (prev_black_level&0x200) >> 9;
if(signed_value)
int_prev_black_level = -1*(prev_black_level&0x1ff);
else
int_prev_black_level = prev_black_level&0x1ff;
m_edBlackLevel->setText(QString::number(int_prev_black_level));
m_edBlackLevel->setEnabled(true);
}
else
{
m_edBlackLevel->setText("N/A");
m_edBlackLevel->setEnabled(0);
}
// Enable GUI
EnableControls(true);
}
// =============================================================================
// Connect the Imperx Camera
// =============================================================================
void QtCheetahPythonGainUI::Connect()
{
if(m_stream)
m_stream->Release();
m_stream = nullptr;
if(m_camera)
m_camera->Release();
m_camera = nullptr;
// Open camera selection dialog
m_devInfo = IpxGui::SelectCameraW(m_system, L"Get Device Selection");
// Check if any camera was selected
if(m_devInfo == nullptr)
return;
// Create the Device object from DeviceInfo of selected Camera
m_camera = IpxCam::IpxCam_CreateDevice(m_devInfo);
if(!m_camera)
{
QMessageBox::critical(this, "ERROR", "Unable to retrieve camera device.\nMake sure an Imperx Python Camera is connected.\r\n" );
return;
}
// Get the camera basic information and show it on GUI
IpxCamErr err=IPX_CAM_ERR_OK;
auto paramArray = m_camera->GetCameraParameters();
if(!paramArray)
{
QMessageBox::critical(this, "ERROR", "Unable to retrieve Camera Parameters\r\n" );
return;
}
//Register the Event Sink
IpxGenParam::Param* param;
m_bNewXml = (paramArray->GetParam("AnalogGain", &err))? true:false;
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
{
QMessageBox::critical(this, "ERROR", "Unable to get AnalogGain\r\n" );
return;
}
if(m_bNewXml)
{
param = paramArray->GetParam("DigitalGainRaw", &err);// new XML
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
{
QMessageBox::critical(this, "ERROR", "Unable to retrieve proper camera parameters.\nMake sure an Imperx Python Camera is connected.\r\n" );
return;
}
param->RegisterEventSink(this);
param = paramArray->GetParam("BlackLevel", &err);// new XML
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
{
QMessageBox::critical(this, "ERROR", "Unable to retrieve proper camera parameters.\nMake sure an Imperx Python Camera is connected.\r\n" );
return;
}
param->RegisterEventSink(this);
}
else
{
// Old XML
param = paramArray->GetParam("Frame_DigitalGain", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
{
QMessageBox::critical(this, "ERROR", "Unable to retrieve proper camera parameters.\nMake sure an Imperx Python Camera is connected.\r\n" );
return;
}
param->RegisterEventSink(this);
param = paramArray->GetParam("Frame_BlackLevelOffset", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
{
QMessageBox::critical(this, "ERROR", "Unable to retrieve proper camera parameters.\nMake sure an Imperx Python Camera is connected.\r\n" );
return;
}
param->RegisterEventSink(this);
}
IpxGenParam::String* lManufacturer = paramArray->GetString("DeviceVendorName", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve DeviceVendorName");
IpxGenParam::String* lModelName = paramArray->GetString("DeviceModelName", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve DeviceModelName");
IpxGenParam::String* lNameParam = paramArray->GetString("DeviceUserDefinedName", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
{
lNameParam = paramArray->GetString("DeviceUserID", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "DeviceUserID set failed");
}
IpxGenParam::String* lDeviceFamily = paramArray->GetString("DeviceFamilyName", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve DeviceFamilyName");
IpxGenParam::String* lVersion = paramArray->GetString("DeviceVersion", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve DeviceVersion");
IpxGenParam::String* lSerialNbr = paramArray->GetString("DeviceSerialNumber", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retriever DeviceSerialNumber");
QString lModelNameStr((lModelName != 0) ? lModelName->GetValue() : "");
QString lNameStr((lNameParam != 0) ? lNameParam->GetValue() : "");
QString lManufacturerStr((lManufacturer != 0) ? lManufacturer->GetValue(): "");
QString lDeviceFamilyStr((lDeviceFamily != 0) ? lDeviceFamily->GetValue(): "");
QString lVersionStr((lVersion != 0) ? lVersion->GetValue() : "");
QString lSerialNbrStr((lSerialNbr != 0) ? lSerialNbr->GetValue() : "" );
//Fill the edit boxes with the information retrieved from the camera
mModelEdit->setText(lModelNameStr);
mNameEdit->setText(lNameStr);
mManufacturerEdit->setText(lManufacturerStr);
mDeviceFamilyEdit->setText(lDeviceFamilyStr);
mVersionEdit->setText(lVersionStr);
mSerialNbrEdit->setText(lSerialNbrStr);
// Create the Buffers queue for video acquisition
CreateStreamBuffer();
// Create the grabbing thread
m_grabThread = new GrabbingThread(m_stream, m_display);
//Set State of Imperx Camera connect
m_isConnected = true; //Imperx Camera is connected
// Sync up GUI
UpdateToolbarButtons();
//Camera Connected
if(m_camera)
InitFromCamera();
}
// =============================================================================
// Disconnect the Imperx Camera
// =============================================================================
void QtCheetahPythonGainUI::Disconnect()
{
IpxCamErr err;
// Unregister all events of the parameters in the device's node map
auto paramArray = m_camera->GetCameraParameters();
// crear mapper in case is not empty
m_mapData.clear(paramArray);
IpxGenParam::Param* param;
if(m_bNewXml)
{
param = paramArray->GetParam("DigitalGainRaw", &err); // new XML
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve DigitalGainRaw");
param->UnregisterEventSink(this);
param = paramArray->GetParam("BlackLevel", &err); // new XML
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve BlackLevel");
param->UnregisterEventSink(this);
}
else
{
//UnRegisters the Event Sink
param = paramArray->GetParam("Frame_DigitalGain", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve Frame_DigitalGain");
param->UnregisterEventSink(this);
param = paramArray->GetParam("Frame_BlackLevelOffset", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve Frame_BlackLevelOffset");
param->UnregisterEventSink(this);
}
mModelEdit->setText("");
mNameEdit->setText("");
mManufacturerEdit->setText("");
mDeviceFamilyEdit->setText("");
mVersionEdit->setText("");
mSerialNbrEdit->setText("");
// Stop the Acquisition
if(m_grabThread->IsStarted())
OnBnClickedStop();
// Delete the grabbing thread
if(m_grabThread)
{
delete m_grabThread;
m_grabThread = nullptr;
}
m_isConnected = false;
//Update the toolbar
UpdateToolbarButtons();
// Destroy the parameter view
if(m_parameterView)
{
m_parameterView->clearParams();
DestroyGenParamTreeView(m_parameterView);
m_parameterView = nullptr;
}
// Release the Stream object
if(m_stream)
m_stream->Release();
m_stream = nullptr;
// Release the Camera object
if(m_camera)
m_camera->Release();
m_camera = nullptr;
}
// =============================================================================
// OnBnClickedGenICamButton creates/generates the Parameter Tree View of the
// Camera
// =============================================================================
void QtCheetahPythonGainUI::OnBnClickedGenICamButton()
{
if(m_parameterView)
{
m_parameterView->clearParams();
DestroyGenParamTreeView(m_parameterView);
}
m_parameterView = IpxGui::CreateGenParamTreeViewForArrayW(m_camera->GetCameraParameters(), L"Camera Parameters - Gen<i>Cam");
}
// =============================================================================
// CreateBuffer will create the stream buffer queue
// =============================================================================
void QtCheetahPythonGainUI::CreateStreamBuffer()
{
struct CreateStreamBuffer_error : std::runtime_error
{
CreateStreamBuffer_error()
: std::runtime_error("ERROR: Start grab failed")
{}
};
//Check if the Camera Device Object exists
if ( m_camera != nullptr)
{
try
{
// Get first Stream from the Camera
if(m_camera->GetNumStreams() < 1)
throw CreateStreamBuffer_error();
if(!m_stream)
m_stream = m_camera->GetStreamByIndex(0);
if(!m_stream)
throw CreateStreamBuffer_error();
// Release buffer queue, just in case, if it was previously allocated
m_stream->ReleaseBufferQueue();
}
catch(const CreateStreamBuffer_error&)
{
//Release the Camera Device Object
m_camera->Release();
m_camera = nullptr;
return;
}
}
}
bool QtCheetahPythonGainUI::StartGrabbing()
{
//
// Start the video acquisition on Stream
IpxCamErr err = m_stream->StartAcquisition();
if(IPX_CAM_ERR_OK!=err)
{
QMessageBox::critical(this, "ERROR", "Sorry! Cannot start streaming\r\nCheck if there is enough memory.\r\n"
"Particularly, on Linux machine!");
return false;
}
m_grabThread->Start();
return true;
}
bool QtCheetahPythonGainUI::StopGrabbing()
{
m_grabThread->Stop();
// Stop the Acquisition on Stream
IpxCamErr err = m_stream->StopAcquisition(1);
if(IPX_CAM_ERR_OK != err)
{
return false;
}
return true;
}
// =============================================================================
// Start the Acquisition engine on the host. It will call the GenTL consumer to
// start the transfer
// =============================================================================
void QtCheetahPythonGainUI::StartAcquisition()
{
struct StartAcquisition_error : std::runtime_error
{
StartAcquisition_error()
: std::runtime_error("ERROR: AcquireImages failed")
{}
};
try
{
IpxCamErr err(IPX_CAM_ERR_OK);
// Allocate the minimal required buffer queue
err = m_stream->AllocBufferQueue(this, m_stream->GetMinNumBuffers());
if(err != ((IpxCamErr)0))
throw StartAcquisition_error();
// Get camera parrameters array
auto genParams = m_camera->GetCameraParameters();
if(genParams)
{
// Set the TLParamsLocked parameter to lock the parameters effecting to the Transport Layer
err = genParams->SetIntegerValue("TLParamsLocked", 1);
if(err != ((IpxCamErr)0))
throw StartAcquisition_error();
// Start the grabbing thread
StartGrabbing();
// Run AcquisitionStart command to start the acquisition
err = genParams->ExecuteCommand("AcquisitionStart");
if(err != ((IpxCamErr)0))
throw StartAcquisition_error();
}
}
catch(const StartAcquisition_error&)
{
// reset the camera to non-acquisition state
m_camera->GetCameraParameters()->ExecuteCommand("AcquisitionAbort");
StopGrabbing();
m_camera->GetCameraParameters()->SetIntegerValue("TLParamsLocked", 0);
m_stream->ReleaseBufferQueue();
//
//Release the Stream Object
m_stream->Release();
m_stream = nullptr;
//Release the Camera Device Object
m_camera->Release();
m_camera = nullptr;
}
}
// =============================================================================
// Stop the Acquisition engine on the host. It will call the GenTL consumer to
// stop the transfer
// =============================================================================
void QtCheetahPythonGainUI::StopAcquisition()
{
// Get camera parrameters array
auto genParams = m_camera->GetCameraParameters();
if(genParams)
{
// Run AcquisitionStop command to start the acquisition
IpxCamErr err = genParams->ExecuteCommand("AcquisitionStop");
// If any error occured with AcquisitionStop, run AcquisitionAbort
if(err != IPX_CAM_ERR_OK )
err = genParams->ExecuteCommand("AcquisitionAbort");
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to execute AcquisitionAbort");
StopGrabbing();
// Reset the TLParamsLocked parameter to unlock the parameters effecting to the Transport Layer
genParams->SetIntegerValue("TLParamsLocked", 0);
m_stream->ReleaseBufferQueue();
}
}
// =============================================================================
// OnBnClickedStart will start the video acquistion process
// =============================================================================
void QtCheetahPythonGainUI::OnBnClickedStart()
{
//Check if the Imperx Camera is Connected
if ( !m_isConnected)
{
return;
}
// Start the video acquisition
StartAcquisition();
UpdateToolbarButtons();
}
// =============================================================================
// OnBnClickedStop will stop the video acquisition process
// =============================================================================
void QtCheetahPythonGainUI::OnBnClickedStop()
{
//Check if the Imperx Camera is Connected
if ( !m_isConnected )
{
return;
}
// Stop the video acquisition
StopAcquisition();
// Update the Toolbar state
UpdateToolbarButtons();
}
// =============================================================================
// OnBnClickedConnectButton will call Connect() function that connects the
// camera and enables the dialog box to be able to perform the acquisition and
// control commands
// =============================================================================
void QtCheetahPythonGainUI::OnBnClickedConnectButton()
{
//connects the camera and enables the dialog box to be able to perform actions
Connect();
}
// =============================================================================
// OnBnClickedDisconnectButton will call DisConnect() function that disconnects
// the camera and disables the dialog box to be able to perform the acquisition
// and control commands
// =============================================================================
void QtCheetahPythonGainUI::OnBnClickedDisconnectButton()
{
//Disconnects the camera and disables the dialog box to be able to perform any actions
Disconnect();
}
bool QtCheetahPythonGainUI::ZoomIn()
{
return (0 == m_display->GetComponent()->RunCommand((char*)IDPC_CMD_VIEW_ZOOM_IN));
}
bool QtCheetahPythonGainUI::ZoomOut()
{
return (0 == m_display->GetComponent()->RunCommand((char*)IDPC_CMD_VIEW_ZOOM_OUT));
}
bool QtCheetahPythonGainUI::Zoom100()
{
return (0 == m_display->GetComponent()->SetParamInt((char*)IDP_VIEW_FIT, 3));
}
bool QtCheetahPythonGainUI::ZoomFitToWnd()
{
return (0 == m_display->GetComponent()->SetParamInt((char*)IDP_VIEW_FIT, 1));
}
bool QtCheetahPythonGainUI::ZoomSpreadToWnd()
{
return (0 == m_display->GetComponent()->SetParamInt((char*)IDP_VIEW_FIT, 2));
}
bool QtCheetahPythonGainUI::CenterImage()
{
return (0 == m_display->GetComponent()->RunCommand((char*)IDPC_CMD_VIEW_ATCENTER));
}
void QtCheetahPythonGainUI::CreateLayout()
{
QGroupBox *lConnectionBox = CreateConnectGroup();
QGroupBox *lGainBox = CreateGain();
QVBoxLayout *lLayoutLeft = new QVBoxLayout();
lLayoutLeft->addWidget( lConnectionBox, Qt::AlignTop );
lLayoutLeft->addStretch();
lLayoutLeft->addWidget( lGainBox, Qt::AlignTop );
m_displayLabel = new QLabel;
m_displayLabel->setMinimumSize(240, 160);
m_displayLabel->setAlignment(Qt::AlignCenter);
m_displayLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QVBoxLayout *displayLayout = new QVBoxLayout;
displayLayout->addWidget(m_displayLabel);
QGroupBox *lDisplayBox = new QGroupBox(tr("Display"));
lDisplayBox->setLayout(displayLayout);
lDisplayBox->setMinimumWidth(600);
QHBoxLayout *lMainLayout = new QHBoxLayout;
lMainLayout->addLayout( lLayoutLeft, Qt::AlignLeft );
lMainLayout->addWidget( lDisplayBox);
QFrame *lMainBox = new QFrame;
lMainBox->setLayout( lMainLayout );
setCentralWidget( lMainBox );
setWindowTitle( tr( "QtCheetahPythonGainUI" ) );
}
QGroupBox *QtCheetahPythonGainUI::CreateConnectGroup()
{
QLabel *lManufacturerLabel = new QLabel( tr( "Manufacturer" ) );
mManufacturerEdit = new QLineEdit;
mManufacturerEdit->setReadOnly( true );
mManufacturerEdit->setFocusPolicy(Qt::NoFocus);
QLabel *lDeviceFamilyLabel = new QLabel( tr( "Device Family" ) );
mDeviceFamilyEdit = new QLineEdit;
mDeviceFamilyEdit->setReadOnly( true );
mDeviceFamilyEdit->setFocusPolicy(Qt::NoFocus);
QLabel *lModelLabel = new QLabel( tr( "Model" ) );
mModelEdit = new QLineEdit;
mModelEdit->setReadOnly( true );
mModelEdit->setFocusPolicy(Qt::NoFocus);
QLabel *lNameLabel = new QLabel( tr( "Name" ) );
mNameEdit = new QLineEdit;
mNameEdit->setReadOnly( true );
mNameEdit->setFocusPolicy(Qt::NoFocus);
QLabel *lVersionLabel = new QLabel( tr( "Version" ) );
mVersionEdit = new QLineEdit;
mVersionEdit->setReadOnly( true );
mVersionEdit->setFocusPolicy(Qt::NoFocus);
QLabel *lSerialNbrLabel = new QLabel( tr( "SerialNumber" ) );
mSerialNbrEdit = new QLineEdit;
mSerialNbrEdit->setReadOnly( true );
mSerialNbrEdit->setFocusPolicy(Qt::NoFocus);
QGridLayout *lGridLayout = new QGridLayout;
lGridLayout->addWidget( lManufacturerLabel, 0, 0 );
lGridLayout->addWidget( mManufacturerEdit, 0, 1 );
lGridLayout->addWidget( lDeviceFamilyLabel, 1, 0 );
lGridLayout->addWidget( mDeviceFamilyEdit, 1, 1 );
lGridLayout->addWidget( lModelLabel, 2, 0 );
lGridLayout->addWidget( mModelEdit, 2, 1 );
lGridLayout->addWidget( lNameLabel, 3, 0 );
lGridLayout->addWidget( mNameEdit, 3, 1 );
lGridLayout->addWidget( lVersionLabel, 4, 0 );
lGridLayout->addWidget( mVersionEdit, 4, 1 );
lGridLayout->addWidget( lSerialNbrLabel, 5, 0 );
lGridLayout->addWidget( mSerialNbrEdit, 5, 1 );
QVBoxLayout *lBoxLayout = new QVBoxLayout;
lBoxLayout->addLayout( lGridLayout );
lBoxLayout->addStretch();
QGroupBox *lConnectionBox = new QGroupBox( tr( "Device Info" ) );
lConnectionBox->setLayout( lBoxLayout );
lConnectionBox->setMinimumWidth( 300);
lConnectionBox->setMaximumWidth( 300 );
lConnectionBox->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
return lConnectionBox;
}
///
/// \brief Create Gain group box
///
QGroupBox *QtCheetahPythonGainUI::CreateGain()
{
QLabel *lAnalogGainLabel = new QLabel( tr( "Analog gain:" ) );
m_cbAnalogGain = new QComboBox;
m_cbAnalogGain->setEnabled( false );
QLabel *lDigitalGainLabel = new QLabel( tr( "Digital Gain Value:" ) );
m_edDigitalGainCode = new QLineEdit;
m_edDigitalGainCode->setReadOnly( false );
m_edDigitalGainCode->setEnabled( false );
m_btDigitalGainSet = new QPushButton( tr( "Set" ) );
m_btDigitalGainSet->setMinimumHeight( 27 );
QLabel *lDigitalGainLabel2 = new QLabel(tr("=> Digital Gain"));
m_edDigitalGain = new QLineEdit;
m_edDigitalGain->setReadOnly( true );
m_edDigitalGain->setEnabled( false );
QLabel *lDigitalGainDecibels = new QLabel(tr("=> Decibels"));
m_edDigitalGainDB = new QLineEdit;
m_edDigitalGainDB->setReadOnly( true );
m_edDigitalGainDB->setEnabled( false );
QLabel *lDigitalGainDB = new QLabel(tr("dB"));
QLabel *lBlackLevelAutoCalLabel = new QLabel(tr("BlackLevelAutoCalibration:"));
m_cbBlackLevelAutoCal = new QComboBox;
m_cbBlackLevelAutoCal->setEnabled( false );
QLabel *lBlackLevelLabel = new QLabel( tr( "Black level:" ) );
m_edBlackLevel = new QLineEdit;
m_edBlackLevel->setReadOnly( false );
m_edBlackLevel->setEnabled( false );
m_btBlackLevelSet = new QPushButton( tr( "Set" ) );
m_btBlackLevelSet->setMinimumHeight( 27 );
connect( m_btDigitalGainSet, SIGNAL( clicked() ), this, SLOT( OnBnClickedBtDigitalGain() ) );
connect( m_btBlackLevelSet, SIGNAL( clicked() ), this, SLOT( OnBnClickedBtBlackLevel() ) );
QGridLayout *lExpGridLayout = new QGridLayout;
lExpGridLayout->addWidget( lAnalogGainLabel, 0, 0, 1, 3 );
lExpGridLayout->addWidget( m_cbAnalogGain, 0, 4, 1, 4 );
lExpGridLayout->addWidget( lDigitalGainLabel, 1, 0, 1, 3 );
lExpGridLayout->addWidget( m_edDigitalGainCode, 1, 4, 1, 3 );
lExpGridLayout->addWidget( m_btDigitalGainSet, 1, 7, 1, 1);
lExpGridLayout->addWidget( lDigitalGainLabel2, 2, 0, 1, 4 );
lExpGridLayout->addWidget( m_edDigitalGain, 2, 4, 1, 3);
lExpGridLayout->addWidget( lDigitalGainDecibels, 3, 0, 1, 4 );
lExpGridLayout->addWidget( m_edDigitalGainDB, 3, 4, 1, 3 );
lExpGridLayout->addWidget( lDigitalGainDB, 3, 7, 1, 1);
QGridLayout *lExpGridFrameLayout = new QGridLayout;
lExpGridFrameLayout->addWidget( lBlackLevelAutoCalLabel, 0, 0, 1, 3);
lExpGridFrameLayout->addWidget( m_cbBlackLevelAutoCal, 0, 4, 1, 4);
lExpGridFrameLayout->addWidget( lBlackLevelLabel, 1, 0, 1, 3);
lExpGridFrameLayout->addWidget( m_edBlackLevel, 1, 2, 1, 2 );
lExpGridFrameLayout->addWidget( m_btBlackLevelSet, 1, 4, 1, 1);
QVBoxLayout *lExpLayout = new QVBoxLayout;
lExpLayout->addLayout( lExpGridLayout );
lExpLayout->addLayout( lExpGridFrameLayout);
lExpLayout->addStretch();
QGroupBox *lGainBox = new QGroupBox( tr( "Gain" ) );
lGainBox->setLayout( lExpLayout );
lGainBox->setMinimumWidth( 300 );
lGainBox->setMaximumWidth( 300 );
return lGainBox;
}
// =============================================================================
// UpdateToolBarButtons will enable/disable the Toolbar buttons according the connection state
// =============================================================================
void QtCheetahPythonGainUI::UpdateToolbarButtons()
{
// Update the toolbar according the camera state
if(m_isConnected)
{
QList<QAction*> actions = (ui).toolBarFile->actions();
QList<QAction*>::iterator ia;
for (ia = actions.begin(); ia != actions.end(); ia++)
{
(*ia)->setEnabled(true);
if((*ia)->objectName() == "actionConnect")
(*ia)->setEnabled(false);
if((*ia)->objectName() == "actionStop")
(*ia)->setEnabled(false);
}
//Disable Buttons
actions = (ui).toolBarDisplay->actions();
for (ia = actions.begin(); ia != actions.end(); ia++)
{
(*ia)->setEnabled(true);
}
actions = (ui).toolBarView->actions();
for (ia = actions.begin(); ia != actions.end(); ia++)
{
(*ia)->setEnabled(true);
}
if(!m_grabThread)
{
ui.actionPlay->setEnabled(true);
ui.actionStop->setEnabled(false);
}
else
{ if(!m_grabThread->IsStarted())
{
ui.actionPlay->setEnabled(true);
ui.actionStop->setEnabled(false);
}
else
{
ui.actionPlay->setEnabled(false);
ui.actionStop->setEnabled(true);
}
}
}
else
{
QList<QAction*> actions = (ui).toolBarFile->actions();
QList<QAction*>::iterator ia;
for (ia = actions.begin(); ia != actions.end(); ia++)
{
(*ia)->setEnabled(false);
if((*ia)->objectName() == "actionConnect")
(*ia)->setEnabled(true);
}
//Disable Buttons
actions = (ui).toolBarDisplay->actions();
for (ia = actions.begin(); ia != actions.end(); ia++)
{
(*ia)->setEnabled(false);
}
actions = (ui).toolBarView->actions();
for (ia = actions.begin(); ia != actions.end(); ia++)
{
(*ia)->setEnabled(false);
}
ui.actionPlay->setEnabled(false);
ui.actionStop->setEnabled(false);
}
EnableControls(m_isConnected);
}
// =============================================================================
// EnableControls will enable/disable the GUI controls
// =============================================================================
void QtCheetahPythonGainUI::EnableControls(bool en)
{
m_btDigitalGainSet->setEnabled(en);
m_edDigitalGainCode->setEnabled(en);
m_btBlackLevelSet->setEnabled(en);
m_edBlackLevel->setEnabled(en);
m_edDigitalGain->setEnabled(en);
m_edDigitalGainDB->setEnabled(en);
}
// =============================================================================
// OnBnClickedBtDigitalGain
// =============================================================================
void QtCheetahPythonGainUI::OnBnClickedBtDigitalGain()
{
// Get DigitalGain value form GUI
IpxCamErr err;
QString strVal = m_edDigitalGainCode->text();
unsigned int digital_gain_code = (unsigned int)strVal.toLongLong();
int64_t prev_digital_code = 0;
// Set Parameter value
auto paramArray = m_camera->GetCameraParameters();
if(m_bNewXml)
{
prev_digital_code = paramArray->GetIntegerValue("DigitalGainRaw", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve DigitalGainRaw");
}
else
{
prev_digital_code = paramArray->GetIntegerValue("Frame_DigitalGain", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve Frame_DigitalGain");
}
if(digital_gain_code >= 1024 && digital_gain_code <= 16383)
{
if(m_bNewXml)
err = paramArray->SetIntegerValue("DigitalGainRaw",digital_gain_code);
else
err = paramArray->SetIntegerValue("Frame_DigitalGain",digital_gain_code);
if( err != IPX_CAM_ERR_OK)
{
QMessageBox::critical(this,"Error", "Digital Gain set failed");
}
else
{
//digital gain
double digital_gainVal = floor(10*.0009765625*digital_gain_code + 0.5f)/10;
m_edDigitalGain->setText(QString::number(digital_gainVal, 'f', 1));
//digital gain in decibels
double digital_gainDB = 20.0*log10(digital_gainVal);
m_edDigitalGainDB->setText(QString::number(digital_gainDB, 'f', 1));
}
}
else
{
m_edDigitalGainCode->setText(QString::number(prev_digital_code));
//digital gain
double digital_gainVal = floor(10*.0009765625*prev_digital_code + 0.5f)/10;
m_edDigitalGain->setText(QString::number(digital_gainVal, 'f', 1));
//digital gain in decibels
double digital_gainDB = 20.0*log10(digital_gainVal);
m_edDigitalGainDB->setText(QString::number(digital_gainDB, 'f', 1));
QString msg;
msg.sprintf("The value of %d is not valid.\nThis value is out of the specified range(1024, 16383).\nUnable to update", digital_gain_code);
QMessageBox::critical(this, "Error", msg);
}
}
// =============================================================================
// OnBnClickedBtBlackLevel
// =============================================================================
void QtCheetahPythonGainUI::OnBnClickedBtBlackLevel()
{
IpxCamErr err;
int64_t prev_black_level = 0;
// Set Parameter value
auto paramArray = m_camera->GetCameraParameters();
if(m_bNewXml)
{
prev_black_level = (int64_t)paramArray->GetFloatValue("BlackLevel", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve BlackLevel");
}
else
{
//This featurs retrieves the black level offset for all taps
prev_black_level = paramArray->GetIntegerValue("Frame_BlackLevelOffset", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve Frame_BlackLevelOffset");
}
int signed_value;
int int_prev_black_level;
signed_value = (prev_black_level&0x200) >> 9;
if(signed_value)
int_prev_black_level = -1*(prev_black_level&0x1ff);
else
int_prev_black_level = prev_black_level&0x1ff;
// Set Black Level
int BlackLevel = m_edBlackLevel->text().toInt();
int64_t black_level_reg_val = 0;
if(BlackLevel <= 511 && BlackLevel >= -511)
{
if(BlackLevel < 0)
{
black_level_reg_val = (0x200) | (abs(BlackLevel)&0x1ff);
}
else
{
black_level_reg_val = BlackLevel&0x1ff;
}
if(m_bNewXml)
err = paramArray->SetFloatValue("BlackLevel",(double)black_level_reg_val);
else
err = paramArray->SetIntegerValue("Frame_BlackLevelOffset",black_level_reg_val);
if( err != IPX_CAM_ERR_OK)
{
QMessageBox::critical(this, "Error", "Black Level set failed");
}
}
else
{
QString strVal;
strVal.sprintf("%i", int_prev_black_level);
m_edBlackLevel->setText(strVal);
QString msg;
msg.sprintf("The black level value of %d is not valid.\nThis value is out of the specified range.\nUnable to update", BlackLevel);
QMessageBox::critical(this, "Error", msg);
QMessageBox::critical(this, "Error", "The Black Level value must be in the range of -511 to 511");
}
return;
}
// =============================================================================
// OnParameterUpdate occurs during an event callback
// =============================================================================
void QtCheetahPythonGainUI::OnParameterUpdate(IpxGenParam::Param* param)
{
if(m_camera)
{
if(param->GetType() == IpxGenParam::ParamFloat)
{
IpxGenParam::Float *parameter = dynamic_cast<IpxGenParam::Float *>(param);
if (parameter && parameter->IsReadable())
{
const char *paramName = parameter->GetDisplayName();
//This feature controls the Digital Gain for all taps
if (strcmp("Frame_DigitalGain", paramName) == 0)
{
int64_t DigitalGainCode = parameter->GetValue();
//Update the Edit Box with the Frame_DigitalGain value retrieved
m_edDigitalGainCode->setText(QString::number(DigitalGainCode));
//Convert and display Digital Gain Value
double DigitalGain = floor(10*.0009765625*DigitalGainCode + 0.5f)/10;
m_edDigitalGain->setText(QString::number(DigitalGain, 'f', 1));
//Convert and display Digital Gain Decibels
double DigitalGainDB = 20.0*log10(DigitalGain);
m_edDigitalGainDB->setText(QString::number(DigitalGainDB));
m_edDigitalGainDB->setEnabled(0);
}
else if (strcmp("DigitalGainRaw", paramName) == 0)
{
int64_t DigitalGainCode = parameter->GetValue();
//Update the Edit Box with the Frame_DigitalGain value retrieved
m_edDigitalGainCode->setText(QString::number(DigitalGainCode));
//Convert and display Digital Gain Value
double DigitalGain = floor(10*.0009765625*DigitalGainCode + 0.5f)/10;
m_edDigitalGain->setText(QString::number(DigitalGain));
//Convert and display Digital Gain Decibels
double DigitalGainDB = 20.0*log10(DigitalGain);
m_edDigitalGainDB->setText(QString::number(DigitalGainDB, 'f', 1));
m_edDigitalGainDB->setEnabled(0);
}
//This feature controls the Black Level Offset for all taps
else if((strcmp("Frame_BlackLevelOffset", paramName) == 0) || (strcmp("BlackLevel", paramName) == 0))
{
int calEn = m_cbBlackLevelAutoCal->currentIndex();
//If BlackLevelAutoCalibration is Off, then retrieve the Black Level Offset and display its value
if(calEn == 0)
{
int64_t prev_black_level = 0;
int64_t int_prev_black_level;
IpxCamErr err;
auto paramArray = m_camera->GetCameraParameters();
if(m_bNewXml)
prev_black_level = (int64_t)(paramArray->GetFloatValue("BlackLevel", &err));
else
prev_black_level = paramArray->GetIntegerValue("Frame_BlackLevelOffset", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve BlackLevel");
int signed_value = (prev_black_level&0x200) >> 9;
if(signed_value)
int_prev_black_level = -1*(prev_black_level&0x1ff);
else
int_prev_black_level = prev_black_level&0x1ff;
m_edBlackLevel->setText(QString::number(int_prev_black_level));
}
}
}
}
else if(param->GetType() == IpxGenParam::ParamInt)
{
IpxGenParam::Int *parameter = dynamic_cast<IpxGenParam::Int *>(param);
if (parameter && parameter->IsReadable())
{
const char *paramName = parameter->GetDisplayName();
//This feature controls the Digital Gain for all taps
if (strcmp("Frame_DigitalGain", paramName) == 0)
{
int64_t DigitalGainCode = parameter->GetValue();
//Update the Edit Box with the Frame_DigitalGain value retrieved
m_edDigitalGainCode->setText(QString::number(DigitalGainCode));
//Convert and display Digital Gain Value
double DigitalGain = floor(10*.0009765625*DigitalGainCode + 0.5f)/10;
m_edDigitalGain->setText(QString::number(DigitalGain, 'f', 1));
//Convert and display Digital Gain Decibels
double DigitalGainDB = 20.0*log10(DigitalGain);
m_edDigitalGainDB->setText(QString::number(DigitalGainDB, 'f', 1));
}
else if (strcmp("DigitalGainRaw", paramName) == 0)
{
int64_t DigitalGainCode = parameter->GetValue();
//Update the Edit Box with the Frame_DigitalGain value retrieved
m_edDigitalGainCode->setText(QString::number(DigitalGainCode));
//Convert and display Digital Gain Value
double DigitalGain = floor(10*.0009765625*DigitalGainCode + 0.5f)/10;
m_edDigitalGain->setText(QString::number(DigitalGain, 'f', 1));
//Convert and display Digital Gain Decibels
double DigitalGainDB = 20.0*log10(DigitalGain);
m_edDigitalGainDB->setText(QString::number(DigitalGainDB, 'f', 1));
}
//This feature controls the Black Level Offset for all taps
else if((strcmp("Frame_BlackLevelOffset", paramName) == 0) || (strcmp("BlackLevel", paramName) == 0))
{
int calEn = m_cbBlackLevelAutoCal->currentIndex();
//If BlackLevelAutoCalibration is Off, then retrieve the Black Level Offset and display its value
if(calEn == 0)
{
int64_t prev_black_level = 0;
int64_t int_prev_black_level;
IpxCamErr err;
auto paramArray = m_camera->GetCameraParameters();
if(m_bNewXml)
prev_black_level = (int64_t)(paramArray->GetFloatValue("BlackLevel", &err));
else
prev_black_level = paramArray->GetIntegerValue("Frame_BlackLevelOffset", &err);
if(err != ((IpxCamErr)IPX_CAM_ERR_OK))
QMessageBox::critical(this, "Error", "Unable to retrieve BlackLevel");
int signed_value = (prev_black_level&0x200) >> 9;
if(signed_value)
int_prev_black_level = -1*(prev_black_level&0x1ff);
else
int_prev_black_level = prev_black_level&0x1ff;
m_edBlackLevel->setText(QString::number(int_prev_black_level));
}
}
}
}
}
}
| 36.996072 | 152 | 0.57697 | [
"object",
"model"
] |
ffe02c5c74af425510ac737ae84ffc167f02971f | 4,090 | cpp | C++ | src/simple_schedule/main.cpp | trajectory-capstone/trajectory-capstone-2020 | bc69ce95ee5e7a72049e7116b954cf61ec440d9f | [
"MIT"
] | null | null | null | src/simple_schedule/main.cpp | trajectory-capstone/trajectory-capstone-2020 | bc69ce95ee5e7a72049e7116b954cf61ec440d9f | [
"MIT"
] | null | null | null | src/simple_schedule/main.cpp | trajectory-capstone/trajectory-capstone-2020 | bc69ce95ee5e7a72049e7116b954cf61ec440d9f | [
"MIT"
] | null | null | null | //!
//! \file
//!
//! \brief This is an example of running a simple schedule that includes an Application, a LPPM, an Attack, and a Metric
#include "include/Public.h"
using namespace lpm;
int f(int user_start, int user_end, int tr_start, int tr_end, int loc_start, int loc_end,int lppm1,float lppm2, float lppm3, float ap, string actual_trace, string know,string output,int metric);
int convert_int(string ip);
float convert_float(string ip);
int convert_int(string ip){
stringstream s(ip);
int tmp;
//s << ip;
s >> tmp;
//cout<<"converstion "<<tmp<<"\n";
return tmp;
}
float convert_float(string ip){
stringstream s(ip);
float tmp;
//s << ip;
s >> tmp;
//cout<<"converstion "<<tmp<<"\n";
return tmp;
}
int main(int argc, char **argv){
int user_start,user_end, tr_start, tr_end, loc_start, loc_end,lppm1,metric;
string actual_trace, know,output;
float lppm2, lppm3, ap;
fstream newfile;
newfile.open("sample_sch.csv",ios::in);
if(newfile.is_open()){
string tp,tmp;
while(getline(newfile,tp)){
stringstream s(tp),str_cnv;
vector<string> v;
while (s >> tmp) v.push_back(tmp);
if (v.size() == 16){
if (v[0] != "percent_sample"){
user_start = convert_int(v[2]);
user_end = convert_int(v[3]);
metric = convert_int(v[4]);
output = v[5];
tr_start = convert_int(v[6]);
tr_end = convert_int(v[7]);
loc_start = convert_int(v[8]);
loc_end = convert_int(v[9]);
lppm1 = convert_int(v[10]);
lppm2 = convert_float(v[11]);
lppm3 = convert_float(v[12]);
ap = convert_float(v[13]);
actual_trace = v[14];
know = v[15];
f(user_start,user_end,tr_start,tr_end,loc_start,loc_end, lppm1, lppm2, lppm3, ap, actual_trace, know,output,metric);
}
}
}
newfile.close();
}
}
int f(int user_start, int user_end, int tr_start, int tr_end, int loc_start, int loc_end, int lppm1, float lppm2, float lppm3, float ap, string actual_trace, string know,string output,int metric)
{
LPM* lpm = LPM::GetInstance(); // get a pointer to the LPM engine (core class)
Parameters::GetInstance()->AddUsersRange(user_start, user_end); // {2}
Parameters::GetInstance()->SetTimestampsRange(tr_start, tr_end); // consider only timestamps 7, 8, ..., 18, 19
Parameters::GetInstance()->SetLocationstampsRange(loc_start, loc_end); // consider only locationstamps 1, 2, 3, 4, 5, 6, 7, 8
Log::GetInstance()->SetEnabled(true); // [optional] enable the logging facilities
Log::GetInstance()->SetOutputFileName(output); // [optional] set the log file name (here: output.log)
// Tweak the template's parameters'
SimpleScheduleTemplate::GetInstance()->SetApplicationParameters(Basic, ap);
SimpleScheduleTemplate::GetInstance()->SetLPPMParameters(lppm1, GeneralStatisticsSelection, lppm2, lppm3);
SimpleScheduleTemplate::GetInstance()->SetAttackParameter(Strong);
if(metric == 1){
SimpleScheduleTemplate::GetInstance()->SetMetricParameters(Anonymity);
}else if(metric == 2){
SimpleScheduleTemplate::GetInstance()->SetMetricParameters(Distortion);
}else{
SimpleScheduleTemplate::GetInstance()->SetMetricParameters(Entropy);
}
File knowledge(know);
Schedule* schedule = SimpleScheduleTemplate::GetInstance()->BuildSchedule(&knowledge, "simple"); // build the schedule
if(schedule == NULL)
{
std::cout << Errors::GetInstance()->GetLastErrorMessage() << endl; // print the error message
return -1;
}
std::cout << schedule->GetDetailString() << endl; // print a description of the schedule
std::cout << "Running schedule...";
File input(actual_trace);
if(lpm->RunSchedule(schedule, &input, "output") == false) // run the schedule
{
std::cout << Errors::GetInstance()->GetLastErrorMessage() << endl; // print the error message
return -1;
}
std::cout << " done!" << endl;
schedule->Release(); // release the schedule object (since it is no longer needed)
return 0;
}
| 33.252033 | 195 | 0.659658 | [
"object",
"vector"
] |
ffe04381303c36e929f1f6bb5e5cb4f6af4b2b44 | 274 | cpp | C++ | src/RRTStar.cpp | Ch0p1k3/PathPlanningAlgorithms-RRT-RRTstar- | ece79c012f60285b4c397cb34c0b1ea49aebf7a4 | [
"MIT"
] | 4 | 2021-04-25T17:35:38.000Z | 2021-07-07T12:48:33.000Z | src/RRTStar.cpp | Ch0p1k3/PathPlanningAlgorithms-RRT-RRTstar- | ece79c012f60285b4c397cb34c0b1ea49aebf7a4 | [
"MIT"
] | null | null | null | src/RRTStar.cpp | Ch0p1k3/PathPlanningAlgorithms-RRT-RRTstar- | ece79c012f60285b4c397cb34c0b1ea49aebf7a4 | [
"MIT"
] | 1 | 2021-07-07T12:48:38.000Z | 2021-07-07T12:48:38.000Z | #include "RRTStar.hpp"
void RRTStar::changeEdge(Tree::Node* parent, Tree::Node* son, Tree::Node* newParent)
{
tree.changeEdge(parent, son, newParent);
}
void RRTStar::getNear(const Geometry::Point& x, std::vector<Tree::Node*>& res)
{
tree.getNear(x, gamma, res);
} | 24.909091 | 84 | 0.689781 | [
"geometry",
"vector"
] |
ffe0aab62d5b68ac76e627e501ba05805208cbd0 | 14,541 | cpp | C++ | dbms/src/Interpreters/Set.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 85 | 2022-03-25T09:03:16.000Z | 2022-03-25T09:45:03.000Z | dbms/src/Interpreters/Set.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 7 | 2022-03-25T08:59:10.000Z | 2022-03-25T09:40:13.000Z | dbms/src/Interpreters/Set.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 11 | 2022-03-25T09:15:36.000Z | 2022-03-25T09:45:07.000Z | // Copyright 2022 PingCAP, Ltd.
//
// 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 <Columns/ColumnTuple.h>
#include <Columns/ColumnsNumber.h>
#include <Common/FieldVisitors.h>
#include <Common/typeid_cast.h>
#include <Core/Field.h>
#include <Core/Row.h>
#include <DataStreams/IProfilingBlockInputStream.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypeTuple.h>
#include <Flash/Coprocessor/DAGUtils.h>
#include <Interpreters/NullableUtils.h>
#include <Interpreters/Set.h>
#include <Interpreters/convertFieldToType.h>
#include <Interpreters/evaluateConstantExpression.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTLiteral.h>
#include <Storages/Transaction/TypeMapping.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int SET_SIZE_LIMIT_EXCEEDED;
extern const int TYPE_MISMATCH;
extern const int INCORRECT_ELEMENT_OF_SET;
extern const int NUMBER_OF_COLUMNS_DOESNT_MATCH;
extern const int COP_BAD_DAG_REQUEST;
} // namespace ErrorCodes
template <typename Method>
void NO_INLINE Set::insertFromBlockImpl(
Method & method,
const ColumnRawPtrs & key_columns,
size_t rows,
SetVariants & variants,
ConstNullMapPtr null_map)
{
if (null_map)
insertFromBlockImplCase<Method, true>(method, key_columns, rows, variants, null_map);
else
insertFromBlockImplCase<Method, false>(method, key_columns, rows, variants, null_map);
}
template <typename Method, bool has_null_map>
void NO_INLINE Set::insertFromBlockImplCase(
Method & method,
const ColumnRawPtrs & key_columns,
size_t rows,
SetVariants & variants,
ConstNullMapPtr null_map)
{
typename Method::State state(key_columns, key_sizes, collators);
std::vector<String> sort_key_containers;
sort_key_containers.resize(key_columns.size(), "");
/// For all rows
for (size_t i = 0; i < rows; ++i)
{
if (has_null_map && (*null_map)[i])
continue;
state.emplaceKey(method.data, i, variants.string_pool, sort_key_containers);
}
}
void Set::setHeader(const Block & block)
{
std::unique_lock lock(rwlock);
if (!empty())
return;
keys_size = block.columns();
ColumnRawPtrs key_columns;
key_columns.reserve(keys_size);
data_types.reserve(keys_size);
/// The constant columns to the right of IN are not supported directly. For this, they first materialize.
Columns materialized_columns;
/// Remember the columns we will work with
for (size_t i = 0; i < keys_size; ++i)
{
key_columns.emplace_back(block.safeGetByPosition(i).column.get());
data_types.emplace_back(block.safeGetByPosition(i).type);
if (ColumnPtr converted = key_columns.back()->convertToFullColumnIfConst())
{
materialized_columns.emplace_back(converted);
key_columns.back() = materialized_columns.back().get();
}
}
/// We will insert to the Set only keys, where all components are not NULL.
ColumnPtr null_map_holder;
ConstNullMapPtr null_map{};
extractNestedColumnsAndNullMap(key_columns, null_map_holder, null_map);
/// Choose data structure to use for the set.
data.init(data.chooseMethod(key_columns, key_sizes));
}
bool Set::insertFromBlock(const Block & block, bool fill_set_elements)
{
std::unique_lock lock(rwlock);
if (empty())
throw Exception("Method Set::setHeader must be called before Set::insertFromBlock", ErrorCodes::LOGICAL_ERROR);
ColumnRawPtrs key_columns;
key_columns.reserve(keys_size);
/// The constant columns to the right of IN are not supported directly. For this, they first materialize.
Columns materialized_columns;
/// Remember the columns we will work with
for (size_t i = 0; i < keys_size; ++i)
{
key_columns.emplace_back(block.safeGetByPosition(i).column.get());
if (ColumnPtr converted = key_columns.back()->convertToFullColumnIfConst())
{
materialized_columns.emplace_back(converted);
key_columns.back() = materialized_columns.back().get();
}
}
size_t rows = block.rows();
/// We will insert to the Set only keys, where all components are not NULL.
ColumnPtr null_map_holder;
ConstNullMapPtr null_map{};
extractNestedColumnsAndNullMap(key_columns, null_map_holder, null_map);
switch (data.type)
{
case SetVariants::Type::EMPTY:
break;
#define M(NAME) \
case SetVariants::Type::NAME: \
insertFromBlockImpl(*data.NAME, key_columns, rows, data, null_map); \
break;
APPLY_FOR_SET_VARIANTS(M)
#undef M
}
if (fill_set_elements)
{
for (size_t i = 0; i < rows; ++i)
{
std::vector<Field> new_set_elements;
for (size_t j = 0; j < keys_size; ++j)
new_set_elements.push_back((*key_columns[j])[i]);
set_elements->emplace_back(std::move(new_set_elements));
}
}
return limits.check(getTotalRowCount(), getTotalByteCount(), "IN-set", ErrorCodes::SET_SIZE_LIMIT_EXCEEDED);
}
static Field extractValueFromNode(ASTPtr & node, const IDataType & type, const Context & context)
{
if (ASTLiteral * lit = typeid_cast<ASTLiteral *>(node.get()))
{
return convertFieldToType(lit->value, type);
}
else if (typeid_cast<ASTFunction *>(node.get()))
{
std::pair<Field, DataTypePtr> value_raw = evaluateConstantExpression(node, context);
return convertFieldToType(value_raw.first, type, value_raw.second.get());
}
else
throw Exception("Incorrect element of set. Must be literal or constant expression.", ErrorCodes::INCORRECT_ELEMENT_OF_SET);
}
void Set::createFromAST(const DataTypes & types, ASTPtr node, const Context & context, bool fill_set_elements)
{
/// Will form a block with values from the set.
Block header;
size_t num_columns = types.size();
for (size_t i = 0; i < num_columns; ++i)
header.insert(ColumnWithTypeAndName(types[i]->createColumn(), types[i], "_" + toString(i)));
setHeader(header);
MutableColumns columns = header.cloneEmptyColumns();
Row tuple_values;
ASTExpressionList & list = typeid_cast<ASTExpressionList &>(*node);
for (auto & elem : list.children)
{
if (num_columns == 1)
{
Field value = extractValueFromNode(elem, *types[0], context);
if (!value.isNull())
columns[0]->insert(value);
else
setContainsNullValue(true);
}
else if (ASTFunction * func = typeid_cast<ASTFunction *>(elem.get()))
{
if (func->name != "tuple")
throw Exception("Incorrect element of set. Must be tuple.", ErrorCodes::INCORRECT_ELEMENT_OF_SET);
size_t tuple_size = func->arguments->children.size();
if (tuple_size != num_columns)
throw Exception("Incorrect size of tuple in set: " + toString(tuple_size) + " instead of " + toString(num_columns),
ErrorCodes::INCORRECT_ELEMENT_OF_SET);
if (tuple_values.empty())
tuple_values.resize(tuple_size);
size_t i = 0;
for (; i < tuple_size; ++i)
{
Field value = extractValueFromNode(func->arguments->children[i], *types[i], context);
/// If at least one of the elements of the tuple has an impossible (outside the range of the type) value, then the entire tuple too.
if (value.isNull())
break;
tuple_values[i] = value;
}
if (i == tuple_size)
for (i = 0; i < tuple_size; ++i)
columns[i]->insert(tuple_values[i]);
}
else
throw Exception("Incorrect element of set", ErrorCodes::INCORRECT_ELEMENT_OF_SET);
}
Block block = header.cloneWithColumns(std::move(columns));
insertFromBlock(block, fill_set_elements);
}
std::vector<const tipb::Expr *> Set::createFromDAGExpr(const DataTypes & types, const tipb::Expr & expr, bool fill_set_elements)
{
/// Will form a block with values from the set.
Block header;
size_t num_columns = types.size();
if (num_columns != 1)
{
throw Exception("Incorrect element of set, tuple in is not supported yet", ErrorCodes::INCORRECT_ELEMENT_OF_SET);
}
for (size_t i = 0; i < num_columns; ++i)
header.insert(ColumnWithTypeAndName(types[i]->createColumn(), types[i], "_" + toString(i)));
setHeader(header);
MutableColumns columns = header.cloneEmptyColumns();
std::vector<const tipb::Expr *> remainingExprs;
// if left arg is null constant, just return without decode children expr
if (types[0]->onlyNull())
return remainingExprs;
for (int i = 1; i < expr.children_size(); i++)
{
auto & child = expr.children(i);
// todo support constant expression by constant folding
if (!isLiteralExpr(child))
{
remainingExprs.push_back(&child);
continue;
}
Field value = decodeLiteral(child);
DataTypePtr type = types[0];
value = convertFieldToType(value, *type);
if (!value.isNull())
columns[0]->insert(value);
else
setContainsNullValue(true);
}
Block block = header.cloneWithColumns(std::move(columns));
insertFromBlock(block, fill_set_elements);
return remainingExprs;
}
ColumnPtr Set::execute(const Block & block, bool negative) const
{
size_t num_key_columns = block.columns();
if (0 == num_key_columns)
throw Exception("Logical error: no columns passed to Set::execute method.", ErrorCodes::LOGICAL_ERROR);
auto res = ColumnUInt8::create();
ColumnUInt8::Container & vec_res = res->getData();
vec_res.resize(block.safeGetByPosition(0).column->size());
std::shared_lock lock(rwlock);
/// If the set is empty.
if (data_types.empty())
{
if (negative)
memset(&vec_res[0], 1, vec_res.size());
else
memset(&vec_res[0], 0, vec_res.size());
return res;
}
if (data_types.size() != num_key_columns)
{
std::stringstream message;
message << "Number of columns in section IN doesn't match. "
<< num_key_columns << " at left, " << data_types.size() << " at right.";
throw Exception(message.str(), ErrorCodes::NUMBER_OF_COLUMNS_DOESNT_MATCH);
}
/// Remember the columns we will work with. Also check that the data types are correct.
ColumnRawPtrs key_columns;
key_columns.reserve(num_key_columns);
/// The constant columns to the left of IN are not supported directly. For this, they first materialize.
Columns materialized_columns;
for (size_t i = 0; i < num_key_columns; ++i)
{
key_columns.push_back(block.safeGetByPosition(i).column.get());
if (!removeNullable(data_types[i])->equals(*removeNullable(block.safeGetByPosition(i).type)))
throw Exception("Types of column " + toString(i + 1) + " in section IN don't match: "
+ data_types[i]->getName() + " on the right, " + block.safeGetByPosition(i).type->getName() + " on the left.",
ErrorCodes::TYPE_MISMATCH);
if (ColumnPtr converted = key_columns.back()->convertToFullColumnIfConst())
{
materialized_columns.emplace_back(converted);
key_columns.back() = materialized_columns.back().get();
}
}
/// We will check existence in Set only for keys, where all components are not NULL.
ColumnPtr null_map_holder;
ConstNullMapPtr null_map{};
extractNestedColumnsAndNullMap(key_columns, null_map_holder, null_map);
executeOrdinary(key_columns, vec_res, negative, null_map);
return res;
}
template <typename Method>
void NO_INLINE Set::executeImpl(
Method & method,
const ColumnRawPtrs & key_columns,
ColumnUInt8::Container & vec_res,
bool negative,
size_t rows,
ConstNullMapPtr null_map) const
{
if (null_map)
executeImplCase<Method, true>(method, key_columns, vec_res, negative, rows, null_map);
else
executeImplCase<Method, false>(method, key_columns, vec_res, negative, rows, null_map);
}
template <typename Method, bool has_null_map>
void NO_INLINE Set::executeImplCase(
Method & method,
const ColumnRawPtrs & key_columns,
ColumnUInt8::Container & vec_res,
bool negative,
size_t rows,
ConstNullMapPtr null_map) const
{
Arena pool;
typename Method::State state(key_columns, key_sizes, collators);
std::vector<String> sort_key_containers;
sort_key_containers.resize(key_columns.size(), "");
/// NOTE Optimization is not used for consecutive identical values.
/// For all rows
for (size_t i = 0; i < rows; ++i)
{
if (has_null_map && (*null_map)[i])
vec_res[i] = negative;
else
{
auto find_result = state.findKey(method.data, i, pool, sort_key_containers);
vec_res[i] = negative ^ find_result.isFound();
}
}
}
void Set::executeOrdinary(
const ColumnRawPtrs & key_columns,
ColumnUInt8::Container & vec_res,
bool negative,
ConstNullMapPtr null_map) const
{
size_t rows = key_columns[0]->size();
switch (data.type)
{
case SetVariants::Type::EMPTY:
break;
#define M(NAME) \
case SetVariants::Type::NAME: \
executeImpl(*data.NAME, key_columns, vec_res, negative, rows, null_map); \
break;
APPLY_FOR_SET_VARIANTS(M)
#undef M
}
}
} // namespace DB
| 32.972789 | 148 | 0.647823 | [
"vector"
] |
fff241320ed9f5ba774ef4169ae7f4aa5e880c0e | 873 | hpp | C++ | hlt/log.hpp | robert-ko/halite2 | c3d452a4ac6d0dc5206c51f2eb6b78331e08bf01 | [
"MIT"
] | 29 | 2018-01-23T19:40:03.000Z | 2019-07-14T00:40:17.000Z | hlt/log.hpp | robert-ko/halite2 | c3d452a4ac6d0dc5206c51f2eb6b78331e08bf01 | [
"MIT"
] | null | null | null | hlt/log.hpp | robert-ko/halite2 | c3d452a4ac6d0dc5206c51f2eb6b78331e08bf01 | [
"MIT"
] | 5 | 2018-01-25T18:55:06.000Z | 2019-11-17T19:31:16.000Z | #pragma once
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
namespace hlt {
struct Log {
private:
std::vector<std::string> logs;
std::ofstream file;
void initialize(const std::string& filename) {
file.open(filename, std::ios::trunc | std::ios::out);
}
public:
static Log& get() {
static Log instance{};
return instance;
}
static void open(const std::string& filename) {
get().initialize(filename);
}
static void clear() {
get().logs.clear();
}
static void print() {
for (std::string &s : get().logs) {
std::cout << s << std::endl;
}
}
static void log(const std::string& message) {
get().logs.push_back(message);
get().file << message << std::endl;
}
};
}
| 19.4 | 65 | 0.530355 | [
"vector"
] |
fff67e97d3009992984ef09474930d954eeaa55b | 9,491 | cpp | C++ | modules/SofaMiscCollision/SpatialGridPointModel.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | modules/SofaMiscCollision/SpatialGridPointModel.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | modules/SofaMiscCollision/SpatialGridPointModel.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* 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 Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <SofaMiscCollision/SpatialGridPointModel.h>
#include <sofa/core/visual/VisualParams.h>
#include <SofaBaseCollision/CubeModel.h>
#include <sofa/core/ObjectFactory.h>
#include <vector>
#include <sofa/helper/system/gl.h>
namespace sofa
{
namespace component
{
namespace collision
{
SOFA_DECL_CLASS(SpatialGridPointModel)
int SpatialGridPointModelClass = core::RegisterObject("Collision model which represents a set of points, spatially grouped using a SpatialGridContainer")
.add< SpatialGridPointModel >()
;
SpatialGridPointModel::SpatialGridPointModel()
: d_leafScale(initData(&d_leafScale,0,"leafScale","at which level should the first cube layer be constructed.\nNote that this must not be greater than GRIDDIM_LOG2"))
, grid(NULL)
{
}
void SpatialGridPointModel::init()
{
this->PointModel::init();
this->getContext()->get(grid);
if (grid==NULL)
{
serr <<"SpatialGridPointModel requires a Vec3 SpatialGridContainer" << sendl;
return;
}
}
bool SpatialGridPointModel::OctreeSorter::operator()(const Grid::Key& k1, const Grid::Key& k2)
{
for (int scale = root_shift; scale >= 0; --scale)
{
for (int c=k1.size()-1; c>=0; --c)
{
if ((k1[c]>>scale) < (k2[c]>>scale))
return true;
if ((k1[c]>>scale) > (k2[c]>>scale))
return false;
}
}
// they are equal
return false;
}
void SpatialGridPointModel::computeBoundingTree(int maxDepth)
{
if (!grid)
{
this->PointModel::computeBoundingTree(maxDepth);
return;
}
const bool verbose = this->f_printLog.getValue();
int lscale = d_leafScale.getValue();
if (lscale > Grid::GRIDDIM_LOG2) lscale = Grid::GRIDDIM_LOG2;
int ldim = (1<<lscale);
int nleaf = Grid::GRIDDIM/ldim;
CubeModel* cubeModel = createPrevious<CubeModel>();
const int npoints = mstate->getSize();
bool updated = false;
if (npoints != size)
{
resize(npoints);
updated = true;
}
if (updated) cubeModel->resize(0);
if (!isMoving() && !cubeModel->empty() && !updated) return; // No need to recompute BBox if immobile
std::vector<OctreeCell> cells;
Grid* g = grid->getGrid();
Grid::const_iterator itgbegin = g->gridBegin();
Grid::const_iterator itgend = g->gridEnd();
//sout << "input: ";
bool sorted = true;
for (Grid::const_iterator itg = itgbegin; itg != itgend; ++itg)
{
Grid::Key k = itg->first;
Grid::Grid* g = itg->second;
if (g->empty) continue;
for (int z0 = 0; z0<nleaf; z0++)
for (int y0 = 0; y0<nleaf; y0++)
for (int x0 = 0; x0<nleaf; x0++)
{
int pfirst = -1;
int plast = -1;
Grid::Key k2;
k2[0] = k[0]*nleaf + x0;
k2[1] = k[1]*nleaf + y0;
k2[2] = k[2]*nleaf + z0;
for (int z = 0; z<ldim; z++)
for (int y = 0; y<ldim; y++)
for (int x = 0; x<ldim; x++)
{
Grid::Cell* c = g->cell+((z0*ldim+z)*Grid::DZ+(y0*ldim+y)*Grid::DY+(x0*ldim+x)*Grid::DX);
if (!c->plist.empty())
{
if (pfirst==-1)
pfirst = c->plist.front().index;
else if (c->plist.front().index != plast+1)
sorted = false;
plast = c->plist.back().index;
if (c->plist.back().index - c->plist.front().index +1 != (int)c->plist.size())
sorted = false;
}
}
if (pfirst == -1) continue;
cells.push_back(OctreeCell(k2, pfirst, plast));
//sout << " " << k2;
}
/*
int pfirst = -1;
int plast = -1;
for (int i=0; i<Grid::NCELL; ++i)
{
Grid::Cell* c = g->cell+i;
if (!c->plist.empty())
{
pfirst = c->plist.front().index;
break;
}
}
if (pfirst == -1) continue; // empty
for (int i=Grid::NCELL-1; i>=0; --i)
{
Grid::Cell* c = g->cell+i;
if (!c->plist.empty())
{
plast = c->plist.back().index;
break;
}
}
cells.push_back(OctreeCell(k, pfirst, plast));
//sout << " " << k;
*/
}
if (!sorted)
{
serr << "ERROR(SpatialGridPointModel): points are not sorted in spatial grid."<<sendl;
}
//sout << sendl;
cubeModel->resize(cells.size());
if (cells.empty()) return;
OctreeSorter s(maxDepth);
defaulttype::Vector3::value_type cellSize = g->getCellWidth()*ldim; // *GRIDDIM;
std::sort(cells.begin(), cells.end(), s);
//sout << "sorted: ";
for (unsigned int i=0; i<cells.size(); i++)
{
Grid::Key k = cells[i].k;
//sout << " " << k;
int pfirst = cells[i].pfirst;
int plast = cells[i].plast;
defaulttype::Vector3 minElem, maxElem;
for (unsigned int c=0; c<k.size(); ++c)
{
minElem[c] = k[c]*cellSize;
maxElem[c] = (k[c]+1)*cellSize;
}
cubeModel->setLeafCube(i, std::make_pair(Iterator(this,pfirst),Iterator(this,plast+1)), minElem, maxElem); // define the bounding box of the current cell
}
//sout << sendl;
//cubeModel->computeBoundingTree(maxDepth);
int depth = 0;
while (depth < maxDepth && cells.size() > 8)
{
if (verbose) sout << "SpatialGridPointModel: cube depth "<<depth<<": "<<cells.size()<<" cells ("<<(size*100/cells.size())*0.01<<" points/cell)."<<sendl;
// compact cells inplace
int parent = -1;
for (unsigned int i=0; i<cells.size(); ++i)
{
Grid::Key k = cells[i].k;
//sout << " " << k;
for (unsigned int c=0; c<k.size(); ++c)
k[c] >>= 1;
if (parent == -1 || !(k == cells[parent].k))
{
// new parent
//sout << "->"<<k;
++parent;
cells[parent].k = k;
cells[parent].pfirst = i;
cells[parent].plast = i;
}
else
{
// continuing
cells[parent].plast = i;
}
}
//sout << sendl;
if (cells.size() > (unsigned int)parent+1)
{
cells.resize(parent+1);
CubeModel* prevCubeModel = cubeModel;
cubeModel = cubeModel->createPrevious<CubeModel>();
cubeModel->resize(0);
for (unsigned int i=0; i<cells.size(); ++i)
{
//Grid::Key k = cells[i].k;
int pfirst = cells[i].pfirst;
int plast = cells[i].plast;
Cube cfirst(prevCubeModel, pfirst);
Cube clast(prevCubeModel, plast);
cubeModel->addCube(Cube(prevCubeModel,pfirst),Cube(prevCubeModel,plast+1));
}
}
++depth;
}
CubeModel* root = cubeModel->createPrevious<CubeModel>();
while (dynamic_cast<CubeModel*>(root->getPrevious()) != NULL)
{
root = dynamic_cast<CubeModel*>(root->getPrevious());
}
root->resize(0);
root->addCube(Cube(cubeModel,0), Cube(cubeModel,cubeModel->getSize()));
}
} // namespace collision
} // namespace component
} // namespace sofa
| 36.929961 | 170 | 0.477505 | [
"vector",
"model"
] |
fffc4c9240f6ee243034220770c326f9dc752c1e | 6,875 | cc | C++ | third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 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 "third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_fullscreen_video_status.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
#include "third_party/blink/renderer/core/layout/intersection_geometry.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
namespace {
constexpr double kCheckFullscreenIntervalSeconds = 1.0f;
constexpr float kMostlyFillViewportThresholdOfOccupationProportion = 0.85f;
constexpr float kMostlyFillViewportThresholdOfVisibleProportion = 0.75f;
} // anonymous namespace
MediaCustomControlsFullscreenDetector::MediaCustomControlsFullscreenDetector(
HTMLVideoElement& video)
: EventListener(kCPPEventListenerType),
video_element_(video),
check_viewport_intersection_timer_(
video.GetDocument().GetTaskRunner(TaskType::kInternalMedia),
this,
&MediaCustomControlsFullscreenDetector::
OnCheckViewportIntersectionTimerFired) {
if (VideoElement().isConnected())
Attach();
}
bool MediaCustomControlsFullscreenDetector::operator==(
const EventListener& other) const {
return this == &other;
}
void MediaCustomControlsFullscreenDetector::Attach() {
VideoElement().addEventListener(EventTypeNames::loadedmetadata, this, true);
VideoElement().GetDocument().addEventListener(
EventTypeNames::webkitfullscreenchange, this, true);
VideoElement().GetDocument().addEventListener(
EventTypeNames::fullscreenchange, this, true);
}
void MediaCustomControlsFullscreenDetector::Detach() {
VideoElement().removeEventListener(EventTypeNames::loadedmetadata, this,
true);
VideoElement().GetDocument().removeEventListener(
EventTypeNames::webkitfullscreenchange, this, true);
VideoElement().GetDocument().removeEventListener(
EventTypeNames::fullscreenchange, this, true);
check_viewport_intersection_timer_.Stop();
if (VideoElement().GetWebMediaPlayer()) {
VideoElement().GetWebMediaPlayer()->SetIsEffectivelyFullscreen(
blink::WebFullscreenVideoStatus::kNotEffectivelyFullscreen);
}
}
bool MediaCustomControlsFullscreenDetector::ComputeIsDominantVideoForTests(
const IntRect& target_rect,
const IntRect& root_rect,
const IntRect& intersection_rect) {
if (target_rect.IsEmpty() || root_rect.IsEmpty())
return false;
const float x_occupation_proportion =
1.0f * intersection_rect.Width() / root_rect.Width();
const float y_occupation_proportion =
1.0f * intersection_rect.Height() / root_rect.Height();
// If the viewport is mostly occupied by the video, return true.
if (std::min(x_occupation_proportion, y_occupation_proportion) >=
kMostlyFillViewportThresholdOfOccupationProportion) {
return true;
}
// If neither of the dimensions of the viewport is mostly occupied by the
// video, return false.
if (std::max(x_occupation_proportion, y_occupation_proportion) <
kMostlyFillViewportThresholdOfOccupationProportion) {
return false;
}
// If the video is mostly visible in the indominant dimension, return true.
// Otherwise return false.
if (x_occupation_proportion > y_occupation_proportion) {
return target_rect.Height() *
kMostlyFillViewportThresholdOfVisibleProportion <
intersection_rect.Height();
}
return target_rect.Width() * kMostlyFillViewportThresholdOfVisibleProportion <
intersection_rect.Width();
}
void MediaCustomControlsFullscreenDetector::handleEvent(
ExecutionContext* context,
Event* event) {
DCHECK(event->type() == EventTypeNames::loadedmetadata ||
event->type() == EventTypeNames::webkitfullscreenchange ||
event->type() == EventTypeNames::fullscreenchange);
// Video is not loaded yet.
if (VideoElement().getReadyState() < HTMLMediaElement::kHaveMetadata)
return;
if (!VideoElement().isConnected() || !IsVideoOrParentFullscreen()) {
check_viewport_intersection_timer_.Stop();
if (VideoElement().GetWebMediaPlayer()) {
VideoElement().GetWebMediaPlayer()->SetIsEffectivelyFullscreen(
blink::WebFullscreenVideoStatus::kNotEffectivelyFullscreen);
}
return;
}
check_viewport_intersection_timer_.StartOneShot(
kCheckFullscreenIntervalSeconds, FROM_HERE);
}
void MediaCustomControlsFullscreenDetector::ContextDestroyed() {
// This method is called by HTMLVideoElement when it observes context destroy.
// The reason is that when HTMLMediaElement observes context destroy, it will
// destroy webMediaPlayer() thus the final
// setIsEffectivelyFullscreen(kNotEffectivelyFullscreen) is not called.
Detach();
}
void MediaCustomControlsFullscreenDetector::
OnCheckViewportIntersectionTimerFired(TimerBase*) {
DCHECK(IsVideoOrParentFullscreen());
IntersectionGeometry geometry(nullptr, VideoElement(), Vector<Length>(),
true);
geometry.ComputeGeometry();
bool is_dominant = ComputeIsDominantVideoForTests(
geometry.TargetIntRect(), geometry.RootIntRect(),
geometry.IntersectionIntRect());
if (!VideoElement().GetWebMediaPlayer())
return;
if (!is_dominant) {
VideoElement().GetWebMediaPlayer()->SetIsEffectivelyFullscreen(
blink::WebFullscreenVideoStatus::kNotEffectivelyFullscreen);
return;
}
// Picture-in-Picture can be disabled by the website when the API is enabled.
bool picture_in_picture_allowed =
!RuntimeEnabledFeatures::PictureInPictureEnabled() &&
!VideoElement().FastHasAttribute(HTMLNames::disablepictureinpictureAttr);
if (picture_in_picture_allowed) {
VideoElement().GetWebMediaPlayer()->SetIsEffectivelyFullscreen(
blink::WebFullscreenVideoStatus::kFullscreenAndPictureInPictureEnabled);
} else {
VideoElement().GetWebMediaPlayer()->SetIsEffectivelyFullscreen(
blink::WebFullscreenVideoStatus::
kFullscreenAndPictureInPictureDisabled);
}
}
bool MediaCustomControlsFullscreenDetector::IsVideoOrParentFullscreen() {
Element* fullscreen_element =
Fullscreen::FullscreenElementFrom(VideoElement().GetDocument());
if (!fullscreen_element)
return false;
return fullscreen_element->contains(&VideoElement());
}
void MediaCustomControlsFullscreenDetector::Trace(blink::Visitor* visitor) {
EventListener::Trace(visitor);
visitor->Trace(video_element_);
}
} // namespace blink
| 37.162162 | 97 | 0.757527 | [
"geometry",
"vector"
] |
08031222c316c79bcd7f1d4a8ccfa19a0355b147 | 92,826 | cpp | C++ | src/mame/drivers/thomson.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/drivers/thomson.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/drivers/thomson.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Antoine Mine
/**********************************************************************
Copyright (C) Antoine Mine' 2006
Thomson 8-bit micro-computers.
A 6809E-based French family of personal computers developed in the 80's.
Despite their rather high price and poor design , they were quite popular
in France, probably due to the government plan "Informatique pour tous"
(Computer Science for Everyone) to put a network of MO5 computers in every
school during 1984-1986. And maybe their very popular light-pen.
Drivers
- t9000 Thomson T9000 (early TO7 prototype, oct 1980)
- to7 Thomson TO7 (nov 1982)
- to770 Thomson TO7/70 (scarcely enhanced TO7, 1984)
- mo5 Thomson MO5 (entry-game, TO7-incompatible, jun 1984)
- to9 Thomson TO9 (high-end TO7/70 successor, sep 1985)
- mo5e Thomson MO5E (export MO5 version, 1986)
- to8 Thomson TO8 (next generation of TO7/70, sep 1986)
- to9p Thomson TO9+ (improved TO9 with TO8 technology, sep 1986)
- mo6 Thomson MO6 (improved MO5 with TO8 technology, sep 1986)
- mo5nr Thomson MO5NR (network-enhanced MO6, 1986)
- to8d Thomson TO8D (TO8 with integrated floppy, dec 1987)
- pro128 Olivetti Prodest PC 128 (Italian MO6, built by Thomson, 1986)
We do not consider here the few 16-bit computers built by Thomson
(68000-based Micromega 32, 8088-based Micromega 16 or the TO16: Thomson's own
8088-based PC).
You may distinguish three families:
* TO7,TO7/70,TO8,TO8D (family computers)
* TO9,TO9+ (professional desktop look with separate keyboard and monitor)
* MO5,MO5E,MO5NR,MO6 (cheaper, less extensible family)
Computers in both TO families are compatible. Computers in the MO family are
compatible. However, the TO and MO families are incompatible
(different memory-mapping).
Note that the TO8, TO9+ and MO6 were produced at the same time, using very
similar technologies, but with different cost/feature trade-offs and
different compatibility (MO6 is MO5-compatible, TO9+ is TO9-compatible and
TO8 and TO9+ are TO7-compatible).
Also note that the MO5NR is actually based on MO6 design, not MO5
(although both MO5NR and MO6 are MO5-compatible)
Also of interest are the Platini and Hinault versions of the MO5
(plain MO5 inside, but with custom, signed box-case).
There were several versions of TO7/70 and MO5 with alternate keyboards.
Thomson stopped producing micro-computers in jan 1990.
**********************************************************************/
/* TODO (roughly in decreasing priority order):
----
- many copy-protected cassettes that work in DCMOTO fail to load correctly
(mostly by Infogrames and Loriciels)
- floppy issues still remain (such as many recent TO8 slideshows giving I/O errors)
- MO6/MO5NR cartridge is completely broken (garbage screen/hangs)
- TO8/TO9+ cassette is completely broken (I/O error)
- add several clones that are emulated in DCMOTO
- internal, keyboard-attached TO9 mouse port (untested)
- floppy: 2-sided or 4-sided .fd images, modernization
- printer post-processing => postscript
- RS232 serial port extensions: CC 90-232, RF 57-932
- modem, teltel extension: MD 90-120 / MD 90-333 (need controller ROM?)
- IEEE extension
- TV overlay (IN 57-001) (@)
- digitisation extension (DI 90-011) (@)
- barcode reader (@)
(@) means MAME is lacking support for this kind of device / feature anyway
*/
#include "emu.h"
#include "includes/thomson.h"
#include "bus/centronics/ctronics.h"
#include "bus/rs232/rs232.h"
#include "bus/thomson/cd90_015.h"
#include "bus/thomson/cq90_028.h"
#include "bus/thomson/cd90_351.h"
#include "bus/thomson/cd90_640.h"
#include "bus/thomson/nanoreseau.h"
#include "machine/6821pia.h"
#include "machine/clock.h"
#include "machine/ram.h"
#include "machine/wd_fdc.h"
#include "softlist.h"
#include "speaker.h"
#include "formats/basicdsk.h"
#include "formats/cd90_640_dsk.h"
/**************************** common *******************************/
#define KEY(pos,name,key) \
PORT_BIT ( 1<<(pos), IP_ACTIVE_LOW, IPT_KEYBOARD ) \
PORT_NAME ( name ) \
PORT_CODE ( KEYCODE_##key )
#define PAD(mask,player,name,port,dir,key) \
PORT_BIT ( mask, IP_ACTIVE_LOW, IPT_##port ) \
PORT_NAME ( "P" #player " " name ) \
PORT_CODE( KEYCODE_##key ) \
PORT_PLAYER ( player )
/* ------------- game port ------------- */
/*
Two generations of game port extensions were developed
- CM 90-112 (model 1)
connect up to two 8-position 1-button game pads
- SX 90-018 (model 2)
connect either two 8-position 2-button game pads
or a 2-button mouse (not both at the same time!)
We emulate the SX 90-018 as it is fully compatible with the CM 90-112.
Notes:
* all extensions are compatible with all Thomson computers.
* the SX 90-018 extension is integrated within the TO8(D)
* the TO9 has its own, different mouse port
* all extensions are based on a Motorola 6821 PIA
* all extensions include a 6-bit sound DAC
* most pre-TO8 software (including TO9) do not recognise the mouse nor the
second button of each pad
* the mouse cannot be used at the same time as the pads: they use the same
6821 input ports & physical port; we use a config switch to tell MESS
whether pads or a mouse is connected
* the mouse should not be used at the same time as the sound DAC: they use
the same 6821 ports, either as input or output; starting from the TO8,
there is a 'mute' signal to cut the DAC output and avoid producing an
audible buzz whenever the mouse is moved; unfortunately, mute is not
available on the TO7(/70), TO9 and MO5.
*/
static INPUT_PORTS_START( thom_game_port )
/* joysticks, common to CM 90-112 & SX 90-018 */
PORT_START ( "game_port_directions" )
PAD ( 0x01, 1, UTF8_UP, JOYSTICK_UP, UP, UP)
PAD ( 0x02, 1, UTF8_DOWN, JOYSTICK_DOWN, DOWN, DOWN )
PAD ( 0x04, 1, UTF8_LEFT, JOYSTICK_LEFT, LEFT, LEFT )
PAD ( 0x08, 1, UTF8_RIGHT, JOYSTICK_RIGHT, RIGHT, RIGHT )
PAD ( 0x10, 2, UTF8_UP, JOYSTICK_UP, UP, 8_PAD )
PAD ( 0x20, 2, UTF8_DOWN, JOYSTICK_DOWN, DOWN, 2_PAD )
PAD ( 0x40, 2, UTF8_LEFT, JOYSTICK_LEFT, LEFT, 4_PAD )
PAD ( 0x80, 2, UTF8_RIGHT, JOYSTICK_RIGHT, RIGHT, 6_PAD )
PORT_START ( "game_port_buttons" )
PAD ( 0x40, 1, "Action A", BUTTON1, BUTTON1, LCONTROL )
PAD ( 0x80, 2, "Action A", BUTTON1, BUTTON1, RCONTROL )
/* joysticks, SX 90-018 specific */
PAD ( 0x04, 1, "Action B", BUTTON2, BUTTON2, LALT )
PAD ( 0x08, 2, "Action B", BUTTON2, BUTTON2, RALT )
PORT_BIT ( 0x30, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_BIT ( 0x03, IP_ACTIVE_HIGH, IPT_UNUSED ) /* ? */
/* mouse, SX 90-018 specific */
PORT_START ( "mouse_x" )
PORT_BIT ( 0xffff, 0x00, IPT_MOUSE_X )
PORT_NAME ( "Mouse X" )
PORT_SENSITIVITY ( 150 )
PORT_PLAYER (1)
PORT_START ( "mouse_y" )
PORT_BIT ( 0xffff, 0x00, IPT_MOUSE_Y )
PORT_NAME ( "Mouse Y" )
PORT_SENSITIVITY ( 150 )
PORT_PLAYER (1)
PORT_START ( "mouse_button" )
PORT_BIT ( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_NAME ( "Left Mouse Button" )
PORT_CODE( MOUSECODE_BUTTON1 )
PORT_BIT ( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_NAME ( "Right Mouse Button" )
INPUT_PORTS_END
/* ------------ lightpen ------------ */
static INPUT_PORTS_START( thom_lightpen )
PORT_START ( "lightpen_x" )
PORT_BIT ( 0xffff, THOM_TOTAL_WIDTH/2, IPT_LIGHTGUN_X )
PORT_NAME ( "Lightpen X" )
PORT_MINMAX( 0, THOM_TOTAL_WIDTH )
PORT_SENSITIVITY( 50 )
PORT_CROSSHAIR(X, 1.0, 0.0, 0)
PORT_START ( "lightpen_y" )
PORT_BIT ( 0xffff, THOM_TOTAL_HEIGHT/2, IPT_LIGHTGUN_Y )
PORT_NAME ( "Lightpen Y" )
PORT_MINMAX ( 0, THOM_TOTAL_HEIGHT )
PORT_SENSITIVITY( 50 )
PORT_CROSSHAIR(Y, 1.0, 0.0, 0)
PORT_START ( "lightpen_button" )
PORT_BIT ( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON1 )
PORT_NAME ( "Lightpen Button" )
PORT_CODE( MOUSECODE_BUTTON1 )
INPUT_PORTS_END
/************************** T9000 / TO7 *******************************
TO7 (1982)
---
First computer by Thomson.
Note that the computer comes with only a minimal BIOS and requires an
external cartridge to be usable.
Most software are distributed on cassette and require the BASIC 1.0 cartridge
to be present (-cart basic.m7), as only it provides the necessary OS
capabilities (e.g., a cassette loader).
To use disks, you will need both a BASIC 1.0 cartridge and a BASIC DOS
boot floppy.
* chips:
- 1 MHz Motorola 6809E CPU
- 1 Motorola 6821 PIA (+3 for I/O, game, and modem extensions)
- 1 Motorola 6846 timer, I/O, ROM
* memory:
- 8 KB base user RAM
+ 16 KB extended user RAM (EM 90-016) = 24 KB total user RAM emulated
+ homebrew 8 KB RAM extension (Theophile magazine 6, sept 1984)
- 6 KB BIOS ROM
- 6-bit x 8 K color RAM + 8-bit x 8 K point RAM, bank switched
- 2 to 8 KB ROM comes with the floppy drive / network controller
* video:
320x200 pixels with color constraints (2 colors per horizontal
8-pixel span), 8-color pixel palette,
50 Hz (tweaked SECAM)
* devices:
- AZERTY keyboard, 58-keys, French with accents
- cartridge 16 KB (up to 64 KB using bank-switching),
the MAME cartridge device is named -cart
- cassette 900 bauds (frequency signals: 0=4.5 kHz, 1=6.3 kHz)
the MAME cassette device is named -cass
- 1-bit internal buzzer
- lightpen, with 8-pixel horizontal resolution, 1-pixel vertical
- SX 90-018 game & music extension
. 6-bit DAC sound
. two 8-position 2-button game pads
. 2-button mouse
. based on a Motorola 6821 PIA
- CC 90-232 I/O extension:
. CENTRONICS (printer)
. RS232 (unemulated)
. based on a Motorola 6821 PIA
. NOTE: you cannot use the CENTRONICS and RS232 at the same time
- RF 57-932: RS232 extension, based on a SY 6551 ACIA (unemulated)
- MD 90-120: MODEM, TELETEL extension (unemulated)
. 1 Motorola 6850 ACIA
. 1 Motorola 6821 PIA
. 1 EFB 7513 MODEM FSK V13, full duplex
. PTT-, VELI7Y-, and V23-compatible MODEM (up to 1200 bauds)
. seems to come with an extra ROM
- 5"1/2 floppy drive extension
. CD 90-640 floppy controller, based on a Western Digital 2793
. DD 90-320 double-density double-sided 5"1/4 floppy
(2 drives considered as 4 simple-face drives: 0/1 for the first drive,
2/3 for the second drive, 1 and 3 for upper sides, 0 and 2 for lower
sides)
. floppies are 40 tracks/side, 16 sectors/track, 128 or 256 bytes/sector
= from 80 KB one-sided single-density, to 320 KB two-sided double-density
. MAME floppy devices are named -flop0 to -flop3
- alternate 5"1/2 floppy drive extension
. CD 90-015 floppy controller, based on a HD 46503 S
. UD 90-070 5"1/4 single-sided single density floppy drive
- alternate 3"1/2 floppy drive extension
. CD 90-351 floppy controller, based on a custom Thomson gate-array
. DD 90-352 3"1/2 floppy drives
- alternate QDD floppy drive extension
. CQ 90-028 floppy controller, based on a Motorola 6852 SSDA
. QD 90-028 quickdrive 2"8 (QDD), only one drive, single side
- speech synthesis extension: based on a Philips / Signetics MEA 8000
(cannot be used with the MODEM)
- MIDIPAK MIDI extension, uses a EF 6850 ACIA
- NR 07-005: network extension, MC 6854 based, 2 KB ROM & 64 KB RAM
(build by the French Leanord company)
T9000 (1980)
-----
Early TO7 prototype.
The hardware seems to be the exactly same. Only the BIOS is different.
It has some bug that were corrected later for the TO7.
Actually, the two computers are indistinguishable, except for the different
startup screen, and a couple BIOS addresses.
They can run the same software and accept the same devices and extensions.
**********************************************************************/
/* ------------ address maps ------------ */
void thomson_state::to7_map(address_map &map)
{
map(0x0000, 0x3fff).bankr(THOM_CART_BANK).w(FUNC(thomson_state::to7_cartridge_w)); /* 4 * 16 KB */
map(0x4000, 0x5fff).bankr(THOM_VRAM_BANK).w(FUNC(thomson_state::to7_vram_w));
map(0x6000, 0x7fff).bankrw(THOM_BASE_BANK); /* 1 * 8 KB */
map(0x8000, 0xdfff).bankrw(THOM_RAM_BANK); /* 16 or 24 KB (for extension) */
map(0xe7c0, 0xe7c7).rw(m_mc6846, FUNC(mc6846_device::read), FUNC(mc6846_device::write));
map(0xe7c8, 0xe7cb).rw("pia_0", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7cc, 0xe7cf).rw("pia_1", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7e0, 0xe7e3).rw("to7_io:pia_2", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7e8, 0xe7eb).rw("acia", FUNC(mos6551_device::read), FUNC(mos6551_device::write));
map(0xe7f2, 0xe7f3).rw(FUNC(thomson_state::to7_midi_r), FUNC(thomson_state::to7_midi_w));
map(0xe7f8, 0xe7fb).rw("pia_3", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7fe, 0xe7ff).rw(FUNC(thomson_state::to7_modem_mea8000_r), FUNC(thomson_state::to7_modem_mea8000_w));
map(0xe800, 0xffff).rom(); /* system bios */
/* 0x10000 - 0x1ffff: 64 KB external ROM cartridge */
/* 18 KB floppy / network ROM controllers */
/* RAM mapping:
0x0000 - 0x3fff: 16 KB video RAM (actually 8 K x 8 bits + 8 K x 6 bits)
0x4000 - 0x5fff: 8 KB base RAM
0x6000 - 0x9fff: 16 KB extended RAM
0xa000 - 0xbfff: 8 KB more extended RAM
*/
}
/* ------------ ROMS ------------ */
ROM_START ( to7 )
ROM_REGION ( 0x10000, "maincpu", 0 )
ROM_LOAD ( "to7.rom", 0xe800, 0x1800,
CRC(0e7826da)
SHA1(23a2f84b03c01d385cc1923c8ece95c43756297a) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL ( 0x00000, 0x10000, 0x39 )
ROM_END
ROM_START ( t9000 )
ROM_REGION ( 0x10000, "maincpu", 0 )
ROM_LOAD ( "t9000.rom", 0xe800, 0x1800,
CRC(daa8cfbf)
SHA1(a5735db1ad4e529804fc46603f838d3f4ccaf5cf) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL ( 0x00000, 0x10000, 0x39 )
ROM_END
/* ------------ inputs ------------ */
static INPUT_PORTS_START ( to7_config )
PORT_START ( "config" )
PORT_CONFNAME ( 0x01, 0x00, "Game Port" )
PORT_CONFSETTING ( 0x00, DEF_STR( Joystick ) )
PORT_CONFSETTING ( 0x01, "Mouse" )
INPUT_PORTS_END
static INPUT_PORTS_START ( to7_vconfig )
PORT_START ( "vconfig" )
PORT_CONFNAME ( 0x03, 0x00, "Border" )
PORT_CONFSETTING ( 0x00, "Normal (56x47)" )
PORT_CONFSETTING ( 0x01, "Small (16x16)" )
PORT_CONFSETTING ( 0x02, DEF_STR ( None ) )
PORT_CONFNAME ( 0x0c, 0x08, "Resolution" )
PORT_CONFSETTING ( 0x00, DEF_STR ( Low ) )
PORT_CONFSETTING ( 0x04, DEF_STR ( High ) )
PORT_CONFSETTING ( 0x08, "Auto" )
INPUT_PORTS_END
static INPUT_PORTS_START ( to7_mconfig )
PORT_START ( "mconfig" )
PORT_CONFNAME ( 0x01, 0x01, "E7FE-F port" )
PORT_CONFSETTING ( 0x00, "Modem (unemulated)" )
PORT_CONFSETTING ( 0x01, "Speech" )
INPUT_PORTS_END
static INPUT_PORTS_START ( to7_keyboard )
PORT_START ( "keyboard.0" )
KEY ( 0, "Shift", LSHIFT ) PORT_CODE ( KEYCODE_RSHIFT ) PORT_CHAR(UCHAR_SHIFT_1)
PORT_BIT ( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START ( "keyboard.1" )
KEY ( 0, "W", W ) PORT_CHAR('W')
KEY ( 1, UTF8_UP, UP ) PORT_CHAR(UCHAR_MAMEKEY(UP))
KEY ( 2, "C \303\247", C ) PORT_CHAR('C')
KEY ( 3, "Clear", ESC ) PORT_CHAR(UCHAR_MAMEKEY(ESC))
KEY ( 4, "Enter", ENTER ) PORT_CHAR(13)
KEY ( 5, "Control", LCONTROL ) PORT_CHAR(UCHAR_MAMEKEY(LCONTROL))
KEY ( 6, "Accent", END ) PORT_CHAR(UCHAR_MAMEKEY(END))
KEY ( 7, "Stop", TAB ) PORT_CHAR(27)
PORT_START ( "keyboard.2" )
KEY ( 0, "X", X ) PORT_CHAR('X')
KEY ( 1, UTF8_LEFT, LEFT ) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
KEY ( 2, "V", V ) PORT_CHAR('V')
KEY ( 3, "Q", Q ) PORT_CHAR('Q')
KEY ( 4, "* :", QUOTE ) PORT_CHAR('*') PORT_CHAR(':')
KEY ( 5, "A", A ) PORT_CHAR('A')
KEY ( 6, "+ ;", EQUALS ) PORT_CHAR('+') PORT_CHAR(';')
KEY ( 7, "1 !", 1 ) PORT_CHAR('1') PORT_CHAR('!')
PORT_START ( "keyboard.3" )
KEY ( 0, "Space Caps-Lock", SPACE ) PORT_CHAR(' ') PORT_CHAR(UCHAR_MAMEKEY(CAPSLOCK))
KEY ( 1, UTF8_DOWN, DOWN ) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
KEY ( 2, "B", B ) PORT_CHAR('B')
KEY ( 3, "S", S ) PORT_CHAR('S')
KEY ( 4, "/ ?", SLASH ) PORT_CHAR('/') PORT_CHAR('?')
KEY ( 5, "Z \305\223", Z) PORT_CHAR('Z')
KEY ( 6, "- =", MINUS ) PORT_CHAR('-') PORT_CHAR('=')
KEY ( 7, "2 \" \302\250", 2 ) PORT_CHAR('2') PORT_CHAR('"')
PORT_START ( "keyboard.4" )
KEY ( 0, "@ \342\206\221", TILDE ) PORT_CHAR('@')
KEY ( 1, UTF8_RIGHT, RIGHT ) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
KEY ( 2, "M", M ) PORT_CHAR('M')
KEY ( 3, "D", D ) PORT_CHAR('D')
KEY ( 4, "P", P ) PORT_CHAR('P')
KEY ( 5, "E", E ) PORT_CHAR('E')
KEY ( 6, "0 \140", 0 ) PORT_CHAR('0') PORT_CHAR( 0140 )
KEY ( 7, "3 #", 3 ) PORT_CHAR('3') PORT_CHAR('#')
PORT_START ( "keyboard.5" )
KEY ( 0, ". >", STOP ) PORT_CHAR('.') PORT_CHAR('>')
KEY ( 1, "Home", HOME ) PORT_CHAR(UCHAR_MAMEKEY(HOME))
KEY ( 2, "L", L ) PORT_CHAR('L')
KEY ( 3, "F", F ) PORT_CHAR('F')
KEY ( 4, "O", O ) PORT_CHAR('O')
KEY ( 5, "R", R ) PORT_CHAR('R')
KEY ( 6, "9 )", 9 ) PORT_CHAR('9') PORT_CHAR(')')
KEY ( 7, "4 $", 4 ) PORT_CHAR('4') PORT_CHAR('$')
PORT_START ( "keyboard.6" )
KEY ( 0, ", <", COMMA ) PORT_CHAR(',') PORT_CHAR('<')
KEY ( 1, "Insert", INSERT ) PORT_CHAR(UCHAR_MAMEKEY(INSERT))
KEY ( 2, "K", K ) PORT_CHAR('K')
KEY ( 3, "G", G ) PORT_CHAR('G')
KEY ( 4, "I", I ) PORT_CHAR('I')
KEY ( 5, "T", T ) PORT_CHAR('T')
KEY ( 6, "8 (", 8 ) PORT_CHAR('8') PORT_CHAR('(')
KEY ( 7, "5 %", 5 ) PORT_CHAR('5') PORT_CHAR('%')
PORT_START ( "keyboard.7" )
KEY ( 0, "N", N ) PORT_CHAR('N')
KEY ( 1, "Delete", DEL ) PORT_CHAR(8)
KEY ( 2, "J \305\222", J ) PORT_CHAR('J')
KEY ( 3, "H \302\250", H ) PORT_CHAR('H')
KEY ( 4, "U", U ) PORT_CHAR('U')
KEY ( 5, "Y", Y ) PORT_CHAR('Y')
KEY ( 6, "7 ' \302\264", 7 ) PORT_CHAR('7') PORT_CHAR('\'')
KEY ( 7, "6 &", 6 ) PORT_CHAR('6') PORT_CHAR('&')
/* unused */
PORT_START ( "keyboard.8" )
PORT_START ( "keyboard.9" )
INPUT_PORTS_END
static INPUT_PORTS_START ( to7 )
PORT_INCLUDE ( thom_lightpen )
PORT_INCLUDE ( thom_game_port )
PORT_INCLUDE ( to7_keyboard )
PORT_INCLUDE ( to7_config )
PORT_INCLUDE ( to7_vconfig )
PORT_INCLUDE ( to7_mconfig )
INPUT_PORTS_END
static INPUT_PORTS_START ( t9000 )
PORT_INCLUDE ( to7 )
INPUT_PORTS_END
/* ------------ driver ------------ */
void thomson_state::to7_base(machine_config &config, bool is_mo)
{
MCFG_MACHINE_START_OVERRIDE( thomson_state, to7 )
MCFG_MACHINE_RESET_OVERRIDE( thomson_state, to7 )
/* cpu */
MC6809E(config, m_maincpu, 16_MHz_XTAL / 16);
m_maincpu->set_addrmap(AS_PROGRAM, &thomson_state::to7_map);
INPUT_MERGER_ANY_HIGH(config, "mainirq").output_handler().set_inputline(m_maincpu, M6809_IRQ_LINE);
INPUT_MERGER_ANY_HIGH(config, "mainfirq").output_handler().set_inputline(m_maincpu, M6809_FIRQ_LINE);
/* video */
SCREEN(config, m_screen, SCREEN_TYPE_RASTER);
m_screen->set_refresh_hz(/*50*/ 1./0.019968);
m_screen->set_size(THOM_TOTAL_WIDTH * 2, THOM_TOTAL_HEIGHT);
m_screen->set_visarea(0, THOM_TOTAL_WIDTH * 2 - 1, 0, THOM_TOTAL_HEIGHT - 1);
m_screen->set_screen_update(FUNC(thomson_state::screen_update_thom));
m_screen->screen_vblank().set(FUNC(thomson_state::thom_vblank));
m_screen->set_palette("palette");
PALETTE(config, "palette", FUNC(thomson_state::thom_palette), 4097); // 12-bit color + transparency
/* sound */
SPEAKER(config, "speaker").front_center();
DAC_1BIT(config, "buzzer", 0).add_route(ALL_OUTPUTS, "speaker", 0.5);
DAC_6BIT_R2R(config, m_dac, 0).add_route(ALL_OUTPUTS, "speaker", 0.5); // 6-bit game extension R-2R DAC (R=10K)
/* speech synthesis */
MEA8000(config, m_mea8000, 3840000).add_route(ALL_OUTPUTS, "speaker", 1.0);
/* cassette */
CASSETTE(config, m_cassette);
m_cassette->set_formats(to7_cassette_formats);
m_cassette->set_default_state(CASSETTE_PLAY | CASSETTE_MOTOR_DISABLED | CASSETTE_SPEAKER_ENABLED);
m_cassette->set_interface("to_cass");
/* extension port */
THOMSON_EXTENSION(config, m_extension);
m_extension->option_add("cd90_015", CD90_015);
m_extension->option_add("cq90_028", CQ90_028);
m_extension->option_add("cd90_351", CD90_351);
m_extension->option_add("cd90_640", CD90_640);
if(is_mo)
m_extension->option_add("nanoreseau", NANORESEAU_MO);
else
m_extension->option_add("nanoreseau", NANORESEAU_TO);
/* pia */
PIA6821(config, m_pia_sys, 0);
m_pia_sys->readpa_handler().set(FUNC(thomson_state::to7_sys_porta_in));
m_pia_sys->readpb_handler().set(FUNC(thomson_state::to7_sys_portb_in));
m_pia_sys->writepb_handler().set(FUNC(thomson_state::to7_sys_portb_out));
m_pia_sys->ca2_handler().set(FUNC(thomson_state::to7_set_cassette_motor));
m_pia_sys->cb2_handler().set(FUNC(thomson_state::to7_sys_cb2_out));
m_pia_sys->irqa_handler().set("mainfirq", FUNC(input_merger_device::in_w<1>));
m_pia_sys->irqb_handler().set("mainfirq", FUNC(input_merger_device::in_w<1>));
PIA6821(config, m_pia_game, 0);
m_pia_game->readpa_handler().set(FUNC(thomson_state::to7_game_porta_in));
m_pia_game->readpb_handler().set(FUNC(thomson_state::to7_game_portb_in));
m_pia_game->writepb_handler().set(FUNC(thomson_state::to7_game_portb_out));
m_pia_game->cb2_handler().set(FUNC(thomson_state::to7_game_cb2_out));
m_pia_game->irqa_handler().set("mainirq", FUNC(input_merger_device::in_w<1>));
m_pia_game->irqb_handler().set("mainirq", FUNC(input_merger_device::in_w<1>));
/* TODO: CONVERT THIS TO A SLOT DEVICE (RF 57-932) */
mos6551_device &acia(MOS6551(config, "acia", 0));
acia.set_xtal(1.8432_MHz_XTAL);
acia.txd_handler().set("rs232", FUNC(rs232_port_device::write_txd));
/// 2400 7N2
rs232_port_device &rs232(RS232_PORT(config, "rs232", default_rs232_devices, nullptr));
rs232.rxd_handler().set("acia", FUNC(mos6551_device::write_rxd));
rs232.dcd_handler().set("acia", FUNC(mos6551_device::write_dcd));
rs232.dsr_handler().set("acia", FUNC(mos6551_device::write_dsr));
rs232.cts_handler().set("acia", FUNC(mos6551_device::write_cts));
/* TODO: CONVERT THIS TO A SLOT DEVICE (CC 90-232) */
TO7_IO_LINE(config, "to7_io", 0);
/* TODO: CONVERT THIS TO A SLOT DEVICE (MD 90-120) */
PIA6821(config, THOM_PIA_MODEM, 0);
ACIA6850(config, m_acia, 0);
m_acia->txd_handler().set(FUNC(thomson_state::to7_modem_tx_w));
m_acia->irq_handler().set(FUNC(thomson_state::to7_modem_cb));
clock_device &acia_clock(CLOCK(config, "acia_clock", 1200)); /* 1200 bauds, might be divided by 16 */
acia_clock.signal_handler().set(FUNC(thomson_state::write_acia_clock));
/* cartridge */
GENERIC_CARTSLOT(config, "cartslot", generic_plain_slot, "to_cart", "m7,rom").set_device_load(FUNC(thomson_state::to7_cartridge));
/* internal ram */
RAM(config, m_ram).set_default_size("40K").set_extra_options("24K,48K");
/* software lists */
SOFTWARE_LIST(config, "to7_cart_list").set_original("to7_cart");
SOFTWARE_LIST(config, "to7_cass_list").set_original("to7_cass");
SOFTWARE_LIST(config, "to_flop_list").set_original("to_flop");
SOFTWARE_LIST(config, "to7_qd_list").set_original("to7_qd");
}
void thomson_state::to7(machine_config &config)
{
to7_base(config, false);
/* timer */
MC6846(config, m_mc6846, 16_MHz_XTAL / 16);
m_mc6846->out_port().set(FUNC(thomson_state::to7_timer_port_out));
m_mc6846->in_port().set(FUNC(thomson_state::to7_timer_port_in));
m_mc6846->cp2().set("buzzer", FUNC(dac_bit_interface::write));
m_mc6846->cto().set(FUNC(thomson_state::to7_set_cassette));
m_mc6846->irq().set("mainirq", FUNC(input_merger_device::in_w<0>));
}
void thomson_state::t9000(machine_config &config)
{
to7(config);
}
COMP( 1982, to7, 0, 0, to7, to7, thomson_state, empty_init, "Thomson", "TO7", 0 )
COMP( 1980, t9000, to7, 0, t9000, t9000, thomson_state, empty_init, "Thomson", "T9000", 0 )
/***************************** TO7/70 *********************************
TO7/70 ( 1984)
------
Enhanced TO7.
The TO7/70 supports virtually all TO7 software and most TO7 devices and
extensions (floppy, game, communucation, etc.).
As the TO7, it is only usable with a cartridge, and most software require
the BASIC 1.0 cartridge to be present.
Though, you may also use the more advanced BASIC 128 (-cart basic128.m7):
it allows BASIC programs to access all the memory and the video capabilities,
includes its own DOS (no need for a boot disk), but may not be compatible
with all games.
It has the following modifications:
* chips:
- custom logics for video, lightpen, address map has been replaced with an
integrated Gate-Array (Motorola MC 1300 ALS)
* memory:
- 48 KB user base RAM (16 KB unswitchable + 2 switchable banks of 16 KB)
+ 64 KB user extended RAM (EM 97-064, as 4 extra 16 KB banks)
= 112 KB total user RAM emulated
- now 8-bit x 8 K color RAM (instead of 6-bit x 8 K)
* video:
- 16-color fixed palette instead of 8-color (but same constraints)
- IN 57-001: TV overlay extension, not implemented
(black becomes transparent and shows the TV image)
* devices:
- lightpen management has changed, it now has 1-pixel horizontal resolution
- keyboard management has changed (but the keys are the same)
TO7/70 arabic (198?)
-------------
TO7/70 with an alternate ROM.
Together with a special (64 KB) BASIC 128 cartridge (-cart basic128a.m7),
it allows typing in arabic.
Use Ctrl+W to switch to arabic, and Ctrl+F to switch back to latin.
In latin mode, Ctrl+U / Ctrl+X to start / stop typing in-line arabic.
In arabic mode, Ctrl+E / Ctrl+X to start / stop typing in-line latin.
**********************************************************************/
void thomson_state::to770_map(address_map &map)
{
map(0x0000, 0x3fff).bankr(THOM_CART_BANK).w(FUNC(thomson_state::to7_cartridge_w)); /* 4 * 16 KB */
map(0x4000, 0x5fff).bankr(THOM_VRAM_BANK).w(FUNC(thomson_state::to770_vram_w));
map(0x6000, 0x9fff).bankrw(THOM_BASE_BANK); /* 16 KB */
map(0xa000, 0xdfff).bankrw(THOM_RAM_BANK); /* 6 * 16 KB */
map(0xe7c0, 0xe7c7).rw(m_mc6846, FUNC(mc6846_device::read), FUNC(mc6846_device::write));
map(0xe7c8, 0xe7cb).rw("pia_0", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7cc, 0xe7cf).rw("pia_1", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7e0, 0xe7e3).rw("to7_io:pia_2", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7e4, 0xe7e7).rw(FUNC(thomson_state::to770_gatearray_r), FUNC(thomson_state::to770_gatearray_w));
map(0xe7e8, 0xe7eb).rw("acia", FUNC(mos6551_device::read), FUNC(mos6551_device::write));
map(0xe7f2, 0xe7f3).rw(FUNC(thomson_state::to7_midi_r), FUNC(thomson_state::to7_midi_w));
map(0xe7f8, 0xe7fb).rw("pia_3", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7fe, 0xe7ff).rw(FUNC(thomson_state::to7_modem_mea8000_r), FUNC(thomson_state::to7_modem_mea8000_w));
map(0xe800, 0xffff).rom(); /* system bios */
/* 0x10000 - 0x1ffff: 64 KB external ROM cartridge */
/* 18 KB floppy / network ROM controllers */
/* RAM mapping:
0x00000 - 0x03fff: 16 KB video RAM
0x04000 - 0x07fff: 16 KB unbanked base RAM
0x08000 - 0x1ffff: 6 * 16 KB banked extended RAM
*/
}
/* ------------ ROMS ------------ */
ROM_START ( to770 )
ROM_REGION ( 0x10000, "maincpu", 0 )
ROM_LOAD ( "to770.rom", 0xe800, 0x1800, /* BIOS */
CRC(89518862)
SHA1(cd34474c0bcc758f6d71c90fbd40cef379d61374) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL ( 0x00000, 0x10000, 0x39 )
ROM_END
ROM_START ( to770a )
ROM_REGION ( 0x10000, "maincpu", 0 )
ROM_LOAD ( "to770a.rom", 0xe800, 0x1800,
CRC(378ea808)
SHA1(f4575b537dfdb46ff2a0e7cbe8dfe4ba63161b8e) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL ( 0x00000, 0x10000, 0x39 )
ROM_END
/* ------------ inputs ------------ */
static INPUT_PORTS_START ( to770 )
PORT_INCLUDE ( to7 )
PORT_MODIFY ( "keyboard.1" )
KEY ( 2, "C \302\250 \303\247", C ) PORT_CHAR('C')
PORT_MODIFY ( "keyboard.4" )
KEY ( 6, "0 \140 \303\240", 0 ) PORT_CHAR('0') PORT_CHAR( 0140 )
PORT_MODIFY ( "keyboard.5" )
KEY ( 6, "9 ) \303\247", 9 ) PORT_CHAR('9') PORT_CHAR(')')
PORT_MODIFY ( "keyboard.6" )
KEY ( 6, "8 ( \303\271", 8 ) PORT_CHAR('8') PORT_CHAR('(')
PORT_MODIFY ( "keyboard.7" )
KEY ( 6, "7 ' \303\250 \302\264", 7 ) PORT_CHAR('7') PORT_CHAR('\'')
KEY ( 7, "6 & \303\251", 6 ) PORT_CHAR('6') PORT_CHAR('&')
INPUT_PORTS_END
/* arabic version (QWERTY keyboard) */
static INPUT_PORTS_START ( to770a )
PORT_INCLUDE ( to770 )
PORT_MODIFY ( "keyboard.1" )
KEY ( 0, "Z", Z ) PORT_CHAR('Z')
PORT_MODIFY ( "keyboard.2" )
KEY ( 3, "A", A ) PORT_CHAR('A')
KEY ( 4, "/ ?", QUOTE ) PORT_CHAR('/') PORT_CHAR('?')
KEY ( 5, "Q", Q ) PORT_CHAR('Q')
PORT_MODIFY ( "keyboard.3" )
KEY ( 4, "* :", SLASH ) PORT_CHAR('*') PORT_CHAR(':')
KEY ( 5, "W", W) PORT_CHAR('W')
PORT_MODIFY ( "keyboard.4" )
KEY ( 0, ". >", STOP ) PORT_CHAR('.') PORT_CHAR('>')
KEY ( 2, "@ \342\206\221", TILDE ) PORT_CHAR('@') PORT_CHAR('^')
KEY ( 6, "0 \302\243 \302\260 \140", 0 ) PORT_CHAR('0') PORT_CHAR( 0140 )
PORT_MODIFY ( "keyboard.5" )
KEY ( 0, ", <", COMMA ) PORT_CHAR(',') PORT_CHAR('<')
KEY ( 6, "9 ) \303\261", 9 ) PORT_CHAR('9') PORT_CHAR(')')
PORT_MODIFY ( "keyboard.6" )
KEY ( 0, "M", M ) PORT_CHAR('M')
KEY ( 6, "8 ( \303\274", 8 ) PORT_CHAR('8') PORT_CHAR('(')
PORT_MODIFY ( "keyboard.7" )
KEY ( 6, "7 ' \303\266 \302\264", 7 ) PORT_CHAR('7') PORT_CHAR('\'')
KEY ( 7, "6 & \303\244", 6 ) PORT_CHAR('6') PORT_CHAR('&')
INPUT_PORTS_END
/* ------------ driver ------------ */
void thomson_state::to770(machine_config &config)
{
to7(config);
MCFG_MACHINE_START_OVERRIDE( thomson_state, to770 )
MCFG_MACHINE_RESET_OVERRIDE( thomson_state, to770 )
m_maincpu->set_addrmap(AS_PROGRAM, &thomson_state::to770_map);
m_pia_sys->readpa_handler().set(FUNC(thomson_state::to770_sys_porta_in));
m_pia_sys->readpb_handler().set_constant(0);
m_pia_sys->writepb_handler().set(FUNC(thomson_state::to770_sys_portb_out));
m_pia_sys->cb2_handler().set(FUNC(thomson_state::to770_sys_cb2_out));
m_mc6846->out_port().set(FUNC(thomson_state::to770_timer_port_out));
/* internal ram */
m_ram->set_default_size("128K").set_extra_options("64K");
SOFTWARE_LIST(config, "t770_cart_list").set_original("to770_cart");
SOFTWARE_LIST(config.replace(), "to7_cart_list").set_compatible("to7_cart");
}
void thomson_state::to770a(machine_config &config)
{
to770(config);
config.device_remove("t770_cart_list");
SOFTWARE_LIST(config, "t770a_cart_list").set_original("to770a_cart");
}
COMP( 1984, to770, 0, 0, to770, to770, thomson_state, empty_init, "Thomson", "TO7/70", 0 )
COMP( 1984, to770a, to770, 0, to770a, to770a, thomson_state, empty_init, "Thomson", "TO7/70 (Arabic)", 0 )
/************************* MO5 / MO5E *********************************
MO5 (1984)
---
The MO5 is Thomson's attempt to provide a less costly micro-computer, using
the same technology as the TO7/70.
It has less memory and is less expandable. The MC6846 timer has disappeared.
The BIOS has been throughly rewritten and uses a more compact call scheme.
This, and the fact that the address map has changed, makes the MO5 completely
TO7 software incompatible (except for pure BASIC programs).
Moreover, the MO5 has incompatible cassette and cartridge formats.
Unlike the TO7, the BASIC 1.0 is integrated and the MO5 can be used "as-is".
* chips:
- 1 MHz Motorola 6809E CPU
- 1 Motorola 6821 PIA (+3 for I/O, game, and modem extensions)
- Motorola 1300 ALS Gate-Array
* memory:
- 32 KB base user RAM
- 64 KB extended user RAM (4 x 16 KB banks) with the network extension
(no available to BASIC programs)
- 16 KB combined BASIC and BIOS ROM
- 8 KB color RAM + 8 KB point RAM, bank switched
- 2 to 8 KB floppy ROM comes with the floppy drive / network extension
* video:
- as the TO7/70 but with different color encoding,
320x200 pixels with color constraints, 16-color fixed palette
- IN 57-001: TV overlay extension (not implemented)
* devices:
- AZERTY keyboard, 58-keys, slightlty different from the TO7
. the right SHIFT key has been replaced with a BASIC key
. no caps-lock led
- the famous lightpen is optional
- cassette 1200 bauds (frequency signals: 0=4.5kHz, 1=6.3kHz),
TO7-incompatible
- optional cartridge, up to 64 KB, incompatible with TO7,
masks the integrated BASIC ROM
- game & music, I/O, floppy, network extensions: identical to TO7
- speech synthesis extension: identical to TO7
- MIDIPAK MIDI extension: identical to TO7
MO5E (1986)
----
This is a special MO5 version for the export market (mainly Germany).
Although coming in a different (nicer) case, it is internally similar to
the MO5 and is fully compatible.
Differences include:
- much better keyboard; some are QWERTY instead of AZERTY (we emulate QWERTY)
- a different BIOS and integrated BASIC
- the game extension is integrated
**********************************************************************/
void mo5_state::mo5_map(address_map &map)
{
map(0x0000, 0x1fff).bankr(THOM_VRAM_BANK).w(FUNC(mo5_state::to770_vram_w));
map(0x2000, 0x9fff).bankrw(THOM_BASE_BANK);
map(0xa7c0, 0xa7c3).rw("pia_0", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xa7cb, 0xa7cb).w(FUNC(mo5_state::mo5_ext_w));
map(0xa7cc, 0xa7cf).rw("pia_1", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xa7e0, 0xa7e3).rw("to7_io:pia_2", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xa7e4, 0xa7e7).rw(FUNC(mo5_state::mo5_gatearray_r), FUNC(mo5_state::mo5_gatearray_w));
map(0xa7e8, 0xa7eb).rw("acia", FUNC(mos6551_device::read), FUNC(mos6551_device::write));
map(0xa7f2, 0xa7f3).rw(FUNC(mo5_state::to7_midi_r), FUNC(mo5_state::to7_midi_w));
map(0xa7fe, 0xa7ff).rw(m_mea8000, FUNC(mea8000_device::read), FUNC(mea8000_device::write));
map(0xb000, 0xefff).bankr(THOM_CART_BANK).w(FUNC(mo5_state::mo5_cartridge_w));
map(0xf000, 0xffff).rom(); /* system bios */
/* 0x10000 - 0x1ffff: 16 KB integrated BASIC / 64 KB external cartridge */
/* 18 KB floppy / network ROM controllers */
/* RAM mapping:
0x00000 - 0x03fff: 16 KB video RAM
0x04000 - 0x0bfff: 32 KB unbanked base RAM
0x0c000 - 0x1bfff: 4 * 16 KB bank extended RAM
*/
}
/* ------------ ROMS ------------ */
ROM_START ( mo5 )
ROM_REGION ( 0x14000, "maincpu", 0 )
ROM_LOAD ( "mo5.rom", 0xf000, 0x1000,
CRC(f0ea9140)
SHA1(36ce2d3df1866ec2fe368c1c28757e2f5401cf44) )
ROM_LOAD ( "basic5.rom", 0x11000, 0x3000,
CRC(c2c11b9d)
SHA1(512dd40fb45bc2b51a24c84b3723a32bc8e80c06) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL( 0x00000, 0x10000, 0x39 )
ROM_END
ROM_START ( mo5e )
ROM_REGION ( 0x14000, "maincpu", 0 )
ROM_LOAD ( "mo5e.rom", 0xf000, 0x1000,
CRC(6520213a)
SHA1(f17a7a59baf2819ec80991b34b204795536a5e01) )
ROM_LOAD ( "basic5e.rom", 0x11000, 0x3000,
CRC(934a72b2)
SHA1(b37e2b1afbfba368c19be87b3bf61dfe6ad8b0bb) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL( 0x00000, 0x10000, 0x39 )
ROM_END
/* ------------ inputs ------------ */
static INPUT_PORTS_START ( mo5 )
PORT_INCLUDE ( to770 )
PORT_MODIFY ( "keyboard.0" )
KEY ( 1, "BASIC", RCONTROL) PORT_CHAR(UCHAR_MAMEKEY(RCONTROL))
PORT_BIT ( 0xfc, IP_ACTIVE_LOW, IPT_UNUSED )
INPUT_PORTS_END
/* QWERTY version */
static INPUT_PORTS_START ( mo5e )
PORT_INCLUDE ( mo5 )
PORT_MODIFY ( "keyboard.1" )
KEY ( 0, "Z", Z ) PORT_CHAR('Z')
PORT_MODIFY ( "keyboard.2" )
KEY ( 3, "A", A ) PORT_CHAR('A')
KEY ( 5, "Q", Q ) PORT_CHAR('Q')
PORT_MODIFY ( "keyboard.3" )
KEY ( 5, "W", W) PORT_CHAR('W')
PORT_MODIFY ( "keyboard.4" )
KEY ( 0, ". >", STOP ) PORT_CHAR('.') PORT_CHAR('>')
KEY ( 2, "@ \342\206\221", TILDE ) PORT_CHAR('@') PORT_CHAR('^')
KEY ( 6, "0 \302\243 \302\260 \140", 0 ) PORT_CHAR('0') PORT_CHAR( 0140 )
PORT_MODIFY ( "keyboard.5" )
KEY ( 0, ", <", COMMA ) PORT_CHAR(',') PORT_CHAR('<')
KEY ( 6, "9 ) \303\261", 9 ) PORT_CHAR('9') PORT_CHAR(')')
PORT_MODIFY ( "keyboard.6" )
KEY ( 0, "M", M ) PORT_CHAR('M')
KEY ( 6, "8 ( \303\274", 8 ) PORT_CHAR('8') PORT_CHAR('(')
PORT_MODIFY ( "keyboard.7" )
KEY ( 6, "7 ' \303\266 \302\264", 7 ) PORT_CHAR('7') PORT_CHAR('\'')
KEY ( 7, "6 & \303\244", 6 ) PORT_CHAR('6') PORT_CHAR('&')
INPUT_PORTS_END
/* ------------ driver ------------ */
void mo5_state::mo5(machine_config &config)
{
to7_base(config, true);
MCFG_MACHINE_START_OVERRIDE( mo5_state, mo5 )
MCFG_MACHINE_RESET_OVERRIDE( mo5_state, mo5 )
m_maincpu->set_addrmap(AS_PROGRAM, &mo5_state::mo5_map);
m_cassette->set_formats(mo5_cassette_formats);
m_cassette->set_interface("mo_cass");
subdevice<palette_device>("palette")->set_init(FUNC(mo5_state::mo5_palette));
m_pia_sys->readpa_handler().set(FUNC(mo5_state::mo5_sys_porta_in));
m_pia_sys->readpb_handler().set(FUNC(mo5_state::mo5_sys_portb_in));
m_pia_sys->writepa_handler().set(FUNC(mo5_state::mo5_sys_porta_out));
m_pia_sys->writepb_handler().set("buzzer", FUNC(dac_bit_interface::data_w));
m_pia_sys->ca2_handler().set(FUNC(mo5_state::mo5_set_cassette_motor));
m_pia_sys->cb2_handler().set_nop();
m_pia_sys->irqb_handler().set("mainirq", FUNC(input_merger_device::in_w<1>)); // WARNING: differs from TO7 !
GENERIC_CARTSLOT(config.replace(), "cartslot", generic_plain_slot, "mo_cart", "m5,rom").set_device_load(FUNC(mo5_state::mo5_cartridge));
config.device_remove("to7_cart_list");
config.device_remove("to7_cass_list");
config.device_remove("to_flop_list");
config.device_remove("to7_qd_list");
SOFTWARE_LIST(config, "mo5_cart_list").set_original("mo5_cart");
SOFTWARE_LIST(config, "mo5_cass_list").set_original("mo5_cass");
SOFTWARE_LIST(config, "mo5_flop_list").set_original("mo5_flop");
SOFTWARE_LIST(config, "mo5_qd_list").set_original("mo5_qd");
/* internal ram */
m_ram->set_default_size("112K");
}
void mo5_state::mo5e(machine_config &config)
{
mo5(config);
}
COMP( 1984, mo5, 0, 0, mo5, mo5, mo5_state, empty_init, "Thomson", "MO5", 0 )
COMP( 1986, mo5e, mo5, 0, mo5e, mo5e, mo5_state, empty_init, "Thomson", "MO5E", 0 )
/********************************* TO9 *******************************
TO9 (1985)
---
The TO9 is the successor of the TO7/70.
It is a high-end product: it integrates 96 KB of base RAM, 128 KB of
software in ROM, a floppy drive. It has improved graphics capabilities
(several video modes, a palette of 4096 colors, thanks to the use of
a dedicated video gate-array).
The ROM contains the old BASIC 1.0 for compatibility and the newer BASIC 128.
It has a more professional, desktop look, with a separate keyboard, and an
optional mouse.
It is also quite compatible with the TO7 and TO7/70 (but not the MO5).
However, it also has many problems. The integrated BASIC 128 can only access
128 KB of memory, which forces the 64 KB extension to be managed as a virtual
disk. The early versions of the software ROM has many bugs. The integrated
floppy drive is one-sided.
It was replaced quickly with the improved TO9+.
* chips:
- 1 MHz Motorola 6809E CPU
- 1 Motorola 6821 PIA (+2 for game, modem extensions)
- 1 Motorola 6846 timer, PIA
- 1 Motorola 6805 + 1 Motorola 6850 (keyboard & mouse control)
- 1 Western Digital 2793 (disk controller)
- 3 gate-arrays (address decoding, system, video)
* memory:
- 112 KB base RAM
- 64 KB extension RAM (as virtual disk)
- 6 KB BIOS ROM + 2 KB floppy BIOS
- 128 KB software ROM (BASIC 1, BASIC 128, extended BIOS,
DOS and configuration GUI, two software: "Paragraphe" and
"Fiches et dossiers")
- 16 KB video RAM
* video:
- 8 video modes:
o 320x200, 16 colors with constraints (TO7/70 compatible)
o 320x200, 4 colors without constraints
o 160x200, 16 colors without constraints
o 640x200, 2 colors
o 320x200, 2 colors, two pages
. page one
. page two
. pages overlaid
o 160x200, 2 colors, four pages overlaid
- palette: 16 colors can be chosen among 4096
* devices:
- AZERTY keyboard, 81-keys, French with accents, keypad & function keys
- cartridge, up to 64 KB, TO7 compatible
- two-button mouse connected to the keyboard (not working yet)
- lightpen, with 1-pixel vertical and horizontal resolution
- 1-bit internal buzzer
- cassette 900 bauds, TO7 compatible
- integrated parallel CENTRONICS (printer emulated)
- SX 90-018: game extension (identical to the TO7)
- RF 57-932: RS232 extension (identical to the TO7)
- MD 90-120: MODEM extension (identical to the TO7)
- IEEE extension ? (unemulated)
- floppy:
. integrated floppy controller, based on WD2793
. integrated one-sided double-density 3''1/2
. external two-sided double-density 3''1/2, 5''1/4 or QDD (extension)
. floppies are TO7 and MO5 compatible
- speech synthesis extension: identical to TO7
- MIDIPAK MIDI extension: identical to TO7
**********************************************************************/
void to9_state::to9_map(address_map &map)
{
map(0x0000, 0x3fff).bankr(THOM_CART_BANK).w(FUNC(to9_state::to9_cartridge_w));/* 4 * 16 KB */
map(0x4000, 0x5fff).bankr(THOM_VRAM_BANK).w(FUNC(to9_state::to770_vram_w));
map(0x6000, 0x9fff).bankrw(THOM_BASE_BANK); /* 16 KB */
map(0xa000, 0xdfff).bankrw(THOM_RAM_BANK); /* 10 * 16 KB */
map(0xe7c0, 0xe7c7).rw(m_mc6846, FUNC(mc6846_device::read), FUNC(mc6846_device::write));
map(0xe7c8, 0xe7cb).rw("pia_0", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7cc, 0xe7cf).rw("pia_1", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7da, 0xe7dd).rw(FUNC(to9_state::to9_vreg_r), FUNC(to9_state::to9_vreg_w));
map(0xe7de, 0xe7df).rw(FUNC(to9_state::to9_kbd_r), FUNC(to9_state::to9_kbd_w));
map(0xe7e4, 0xe7e7).rw(FUNC(to9_state::to9_gatearray_r), FUNC(to9_state::to9_gatearray_w));
map(0xe7e8, 0xe7eb).rw("acia", FUNC(mos6551_device::read), FUNC(mos6551_device::write));
/* map(0xe7f0, 0xe7f7).rw(FUNC(to9_state::to9_ieee_r), FUNC(to9_state::to9_ieee_w )); */
map(0xe7f2, 0xe7f3).rw(FUNC(to9_state::to7_midi_r), FUNC(to9_state::to7_midi_w));
map(0xe7f8, 0xe7fb).rw("pia_3", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7fe, 0xe7ff).rw(FUNC(to9_state::to7_modem_mea8000_r), FUNC(to9_state::to7_modem_mea8000_w));
map(0xe800, 0xffff).rom(); /* system bios */
/* 0x10000 - 0x1ffff: 64 KB external ROM cartridge */
/* 0x20000 - 0x3ffff: 128 KB internal software ROM */
/* 18 KB external floppy / network ROM controllers */
/* RAM mapping:
0x00000 - 0x03fff: 16 KB video RAM
0x04000 - 0x07fff: 16 KB unbanked base RAM
0x08000 - 0x2ffff: 10 * 16 KB banked extended RAM
*/
}
/* ------------ ROMS ------------ */
/* NOT WORKING
these bios seem heavily patched (probably to work with specific emulators
that trap some bios calls)
*/
ROM_START ( to9 )
ROM_REGION ( 0x30000, "maincpu", 0 )
ROM_LOAD ( "to9.rom", 0xe000, 0x2000, /* BIOS & floppy controller */
CRC(f9278bf7)
SHA1(9e99e6ae0285950f007b19161de642a4031fe46e) )
/* BASIC & software */
ROM_LOAD ( "basic9-0.rom", 0x10000, 0x4000,
CRC(c7bac620)
SHA1(4b2a8b30cf437858ce978ba7b0dfa2bbd57eb38a) )
ROM_LOAD ( "basic9-1.rom", 0x14000, 0x4000,
CRC(ea5f3e43)
SHA1(5e58a29c2d117fcdb1f5e7ca31dbfffa0f9218f2) )
ROM_LOAD ( "basic9-2.rom", 0x18000, 0x4000,
CRC(0f5581b3)
SHA1(93815ca78d3532192aaa56cbf65b68b0f10f1b8a) )
ROM_LOAD ( "basic9-3.rom", 0x1c000, 0x4000,
CRC(6b5b19e3)
SHA1(0e832670c185694d9abbcebcc3ad90e94eed585d) )
ROM_LOAD ( "soft9-0a.rom", 0x20000, 0x4000,
CRC(8cee157e)
SHA1(f32fc39b95890c00571e9f3fbcc2d8e0596fc4a1) )
ROM_LOAD ( "soft9-1a.rom", 0x24000, 0x4000,
CRC(cf39ac93)
SHA1(b97e6b7389398e5706624973c11ee7ddba323ce1) )
ROM_LOAD ( "soft9-0b.rom", 0x28000, 0x4000,
CRC(033aee3f)
SHA1(f3604e500329ec0489b05dbab05530322e9463c5) )
ROM_LOAD ( "soft9-1b.rom", 0x2c000, 0x4000,
CRC(214fe527)
SHA1(0d8e3f1ca347026e906c3d00a0371e8238c44a60) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL( 0x00000, 0x10000, 0x39 )
ROM_END
/* ------------ inputs ------------ */
static INPUT_PORTS_START ( to9_keyboard )
PORT_START ( "keyboard.0" )
KEY ( 0, "F2 F7", F2 ) PORT_CHAR(UCHAR_MAMEKEY(F2)) PORT_CHAR(UCHAR_MAMEKEY(F7))
KEY ( 1, "_ 6", 6 ) PORT_CHAR('_') PORT_CHAR('6')
KEY ( 2, "Y", Y ) PORT_CHAR('Y')
KEY ( 3, "H \302\250", H ) PORT_CHAR('H')
KEY ( 4, UTF8_UP, UP ) PORT_CHAR(UCHAR_MAMEKEY(UP))
KEY ( 5, UTF8_RIGHT, RIGHT ) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
KEY ( 6, "Home Clear", HOME ) PORT_CHAR(UCHAR_MAMEKEY(HOME)) PORT_CHAR(UCHAR_MAMEKEY(ESC))
KEY ( 7, "N", N ) PORT_CHAR('N')
PORT_START ( "keyboard.1" )
KEY ( 0, "F3 F8", F3 ) PORT_CHAR(UCHAR_MAMEKEY(F3)) PORT_CHAR(UCHAR_MAMEKEY(F8))
KEY ( 1, "( 5", 5 ) PORT_CHAR('(') PORT_CHAR('5')
KEY ( 2, "T", T ) PORT_CHAR('T')
KEY ( 3, "G", G ) PORT_CHAR('G')
KEY ( 4, "= +", EQUALS ) PORT_CHAR('=') PORT_CHAR('+')
KEY ( 5, UTF8_LEFT, LEFT ) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
KEY ( 6, "Insert", INSERT ) PORT_CHAR(UCHAR_MAMEKEY(INSERT))
KEY ( 7, "B \302\264", B ) PORT_CHAR('B')
PORT_START ( "keyboard.2" )
KEY ( 0, "F4 F9", F4 ) PORT_CHAR(UCHAR_MAMEKEY(F4)) PORT_CHAR(UCHAR_MAMEKEY(F9))
KEY ( 1, "' 4", 4 ) PORT_CHAR('\'') PORT_CHAR('4')
KEY ( 2, "R", R ) PORT_CHAR('R')
KEY ( 3, "F", F ) PORT_CHAR('F')
KEY ( 4, "Accent", END ) PORT_CHAR(UCHAR_MAMEKEY(END))
KEY ( 5, "Keypad 1", 1_PAD ) PORT_CHAR(UCHAR_MAMEKEY(1_PAD))
KEY ( 6, "Delete Backspace", DEL ) PORT_CHAR(8) PORT_CHAR(UCHAR_MAMEKEY(BACKSPACE))
KEY ( 7, "V", V ) PORT_CHAR('V')
PORT_START ( "keyboard.3" )
KEY ( 0, "F5 F10", F5 ) PORT_CHAR(UCHAR_MAMEKEY(F5)) PORT_CHAR(UCHAR_MAMEKEY(F10))
KEY ( 1, "\" 3", 3 ) PORT_CHAR('"') PORT_CHAR('3')
KEY ( 2, "E", E ) PORT_CHAR('E')
KEY ( 3, "D", D ) PORT_CHAR('D')
KEY ( 4, "Keypad 7", 7_PAD ) PORT_CHAR(UCHAR_MAMEKEY(7_PAD))
KEY ( 5, "Keypad 4", 4_PAD ) PORT_CHAR(UCHAR_MAMEKEY(4_PAD))
KEY ( 6, "Keypad 0", 0_PAD ) PORT_CHAR(UCHAR_MAMEKEY(0_PAD))
KEY ( 7, "C \136", C ) PORT_CHAR('C')
PORT_START ( "keyboard.4" )
KEY ( 0, "F1 F6", F1 ) PORT_CHAR(UCHAR_MAMEKEY(F1)) PORT_CHAR(UCHAR_MAMEKEY(F6))
KEY ( 1, "\303\251 2", 2 ) PORT_CHAR( 0xe9 ) PORT_CHAR('2')
KEY ( 2, "Z", Z ) PORT_CHAR('Z')
KEY ( 3, "S", S ) PORT_CHAR('S')
KEY ( 4, "Keypad 8", 8_PAD ) PORT_CHAR(UCHAR_MAMEKEY(8_PAD))
KEY ( 5, "Keypad 2", 2_PAD ) PORT_CHAR(UCHAR_MAMEKEY(2_PAD))
KEY ( 6, "Keypad .", DEL_PAD ) PORT_CHAR(UCHAR_MAMEKEY(DEL_PAD))
KEY ( 7, "X", X ) PORT_CHAR('X')
PORT_START ( "keyboard.5" )
KEY ( 0, "# @", TILDE ) PORT_CHAR('#') PORT_CHAR('@')
KEY ( 1, "* 1", 1 ) PORT_CHAR('*') PORT_CHAR('1')
KEY ( 2, "A \140", A ) PORT_CHAR('A')
KEY ( 3, "Q", Q ) PORT_CHAR('Q')
KEY ( 4, "[ {", QUOTE ) PORT_CHAR('[') PORT_CHAR('{')
KEY ( 5, "Keypad 5", 5_PAD ) PORT_CHAR(UCHAR_MAMEKEY(5_PAD))
KEY ( 6, "Keypad 6", 6_PAD ) PORT_CHAR(UCHAR_MAMEKEY(6_PAD))
KEY ( 7, "W", W ) PORT_CHAR('W')
PORT_START ( "keyboard.6" )
KEY ( 0, "Stop", TAB ) PORT_CHAR(27)
KEY ( 1, "\303\250 7", 7 ) PORT_CHAR( 0xe8 ) PORT_CHAR('7')
KEY ( 2, "U", U ) PORT_CHAR('U')
KEY ( 3, "J", J ) PORT_CHAR('J')
KEY ( 4, "Space", SPACE ) PORT_CHAR(' ')
KEY ( 5, "Keypad 9", 9_PAD ) PORT_CHAR(UCHAR_MAMEKEY(9_PAD))
KEY ( 6, "Keypad Enter", ENTER_PAD ) PORT_CHAR(UCHAR_MAMEKEY(ENTER_PAD))
KEY ( 7, ", ?", COMMA ) PORT_CHAR(',') PORT_CHAR('?')
PORT_START ( "keyboard.7" )
KEY ( 0, "Control", LCONTROL ) PORT_CHAR(UCHAR_MAMEKEY(LCONTROL))
KEY ( 1, "! 8", 8 ) PORT_CHAR('!') PORT_CHAR('8')
KEY ( 2, "I", I ) PORT_CHAR('I')
KEY ( 3, "K", K ) PORT_CHAR('K')
KEY ( 4, "$ &", CLOSEBRACE ) PORT_CHAR('$') PORT_CHAR('&')
KEY ( 5, UTF8_DOWN, DOWN ) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
KEY ( 6, "] }", BACKSLASH ) PORT_CHAR(']') PORT_CHAR('}')
KEY ( 7, "; .", STOP ) PORT_CHAR(';') PORT_CHAR('.')
PORT_START ( "keyboard.8" )
KEY ( 0, "Caps-Lock", CAPSLOCK ) PORT_CHAR(UCHAR_MAMEKEY(CAPSLOCK))
KEY ( 1, "\303\247 9", 9 ) PORT_CHAR( 0xe7 ) PORT_CHAR('9')
KEY ( 2, "O", O ) PORT_CHAR('O')
KEY ( 3, "L", L ) PORT_CHAR('L')
KEY ( 4, "- \\", BACKSPACE ) PORT_CHAR('-') PORT_CHAR('\\')
KEY ( 5, "\303\271 %", COLON ) PORT_CHAR( 0xf9 ) PORT_CHAR('%')
KEY ( 6, "Enter", ENTER ) PORT_CHAR(13)
KEY ( 7, ": /", SLASH ) PORT_CHAR(':') PORT_CHAR('/')
PORT_START ( "keyboard.9" )
KEY ( 0, "Shift", LSHIFT ) PORT_CODE ( KEYCODE_RSHIFT ) PORT_CHAR(UCHAR_SHIFT_1)
KEY ( 1, "\303\240 0", 0 ) PORT_CHAR( 0xe0 ) PORT_CHAR('0')
KEY ( 2, "P", P ) PORT_CHAR('P')
KEY ( 3, "M", M ) PORT_CHAR('M')
KEY ( 4, ") \302\260", MINUS ) PORT_CHAR(')') PORT_CHAR( 0xb0 )
KEY ( 5, "\342\206\221 \302\250", OPENBRACE ) PORT_CHAR('^') PORT_CHAR( 0xa8 )
KEY ( 6, "Keypad 3", 3_PAD ) PORT_CHAR(UCHAR_MAMEKEY(3_PAD))
KEY ( 7, "> <", BACKSLASH2 ) PORT_CHAR('>') PORT_CHAR('<')
INPUT_PORTS_END
static INPUT_PORTS_START ( to9 )
PORT_INCLUDE ( thom_lightpen )
PORT_INCLUDE ( thom_game_port )
PORT_INCLUDE ( to9_keyboard )
PORT_INCLUDE ( to7_config )
PORT_INCLUDE ( to7_vconfig )
PORT_INCLUDE ( to7_mconfig )
INPUT_PORTS_END
/* ------------ driver ------------ */
void to9_state::to9(machine_config &config)
{
to7(config);
MCFG_MACHINE_START_OVERRIDE( to9_state, to9 )
MCFG_MACHINE_RESET_OVERRIDE( to9_state, to9 )
m_maincpu->set_addrmap(AS_PROGRAM, &to9_state::to9_map);
m_pia_sys->readpa_handler().set(FUNC(to9_state::to9_sys_porta_in));
m_pia_sys->readpb_handler().set_constant(0);
m_pia_sys->writepa_handler().set(FUNC(to9_state::to9_sys_porta_out));
m_pia_sys->writepb_handler().set(FUNC(to9_state::to9_sys_portb_out));
m_pia_sys->cb2_handler().set_nop();
m_pia_sys->irqa_handler().set_nop();
m_mc6846->out_port().set(FUNC(to9_state::to9_timer_port_out));
CENTRONICS(config, m_centronics, centronics_devices, "printer");
m_centronics->busy_handler().set(FUNC(to9_state::write_centronics_busy));
/* internal ram */
m_ram->set_default_size("192K").set_extra_options("128K");
}
COMP( 1985, to9, 0, 0, to9, to9, to9_state, empty_init, "Thomson", "TO9", MACHINE_IMPERFECT_COLORS )
/******************************** TO8 ********************************
TO8 (1986)
---
The TO8 was meant to replace the TO7/70 as a home-computer.
It includes and improves on the technology from the TO9 (improved video,
256 KB of RAM fully managed by the new BASIC 512, more integrated gate-array).
It has a more compact Amiga-like look, no separate keyboard, no integrated
floppy drive (although the controller is integrated), no software in ROM,
less extension slots. Also, the game & music extension is now integrated.
It is quite compatible with the TO7 and TO7/70, and with the TO9 to some
extent.
The TO8 was quite popular and became the de-facto gamming computer in the
Thomson family.
* chips:
- 1 MHz Motorola 6809E CPU
- 2 Motorola 6821 PIAs (system, game, +1 in modem extension)
- 1 Motorola 6846 timer, PIA
- 1 Motorola 6804 (keyboard)
- 2 gate-arrays (system & video, floppy controller)
* memory:
- 256 KB base RAM
+ 256 KB extended RAM (EM 88-256) = 512 KB total RAM emulated
- 16 KB BIOS ROM
- 64 KB software ROM (BASIC 1, BASIC 512, extended BIOS)
- unified memory view via improved bank switching
* video:
improved wrt TO9: a 9-th video mode, 4 video pages (shared with main RAM)
border color has its 4-th index bit inverted
* devices:
- same keyboard as T09: AZERTY 81-keys
(but no 6850 controller, the 6804 is directly connected to the 6821 & 6846)
- cartridge, up to 64 KB, TO7 compatible
- two-button serial mouse (TO9-incompatible)
- lightpen, with 1-pixel vertical and horizontal resolution
- two 8-position 2-button game pads (SX 90-018 extension integrated)
- 6-bit DAC sound (NOTE: 1-bit buzzer is gone)
- cassette 900 bauds, TO7 compatible
- integrated parallel CENTRONICS (printer emulated)
- RF 57-932: RS232 extension (identical to the TO7)
- MD 90-120: MODEM extension (identical to the TO7?)
- IEEE extension ?
- floppy:
. integrated floppy controller, based on custom Thomson gate-array
. no integrated drive
. up to two external two-sided double-density 3"1/2, 5"1/4 or QDD drives
. floppies are TO7 and MO5 compatible
- speech synthesis extension: identical to TO7
- MIDIPAK MIDI extension: identical to TO7
TO8D (1987)
----
The TO8D is simply a TO8 with an integrated 3"1/2 floppy drive.
**********************************************************************/
void to9_state::to8_map(address_map &map)
{
map(0x0000, 0x3fff).bankr(THOM_CART_BANK).w(FUNC(to9_state::to8_cartridge_w)); /* 4 * 16 KB */
map(0x4000, 0x5fff).bankr(THOM_VRAM_BANK).w(FUNC(to9_state::to770_vram_w));
map(0x6000, 0x7fff).bankr(TO8_SYS_LO).w(FUNC(to9_state::to8_sys_lo_w));
map(0x8000, 0x9fff).bankr(TO8_SYS_HI).w(FUNC(to9_state::to8_sys_hi_w));
map(0xa000, 0xbfff).bankr(TO8_DATA_LO).w(FUNC(to9_state::to8_data_lo_w));
map(0xc000, 0xdfff).bankr(TO8_DATA_HI).w(FUNC(to9_state::to8_data_hi_w));
map(0xe7c0, 0xe7c7).rw(m_mc6846, FUNC(mc6846_device::read), FUNC(mc6846_device::write));
map(0xe7c8, 0xe7cb).rw("pia_0", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7cc, 0xe7cf).rw("pia_1", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7da, 0xe7dd).rw(FUNC(to9_state::to8_vreg_r), FUNC(to9_state::to8_vreg_w));
map(0xe7e4, 0xe7e7).rw(FUNC(to9_state::to8_gatearray_r), FUNC(to9_state::to8_gatearray_w));
map(0xe7e8, 0xe7eb).rw("acia", FUNC(mos6551_device::read), FUNC(mos6551_device::write));
/* map(0xe7f0, 0xe7f7).rw(FUNC(to9_state::to9_ieee_r), FUNC(to9_state::to9_ieee_w )); */
map(0xe7f2, 0xe7f3).rw(FUNC(to9_state::to7_midi_r), FUNC(to9_state::to7_midi_w));
map(0xe7f8, 0xe7fb).rw("pia_3", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7fe, 0xe7ff).rw(FUNC(to9_state::to7_modem_mea8000_r), FUNC(to9_state::to7_modem_mea8000_w));
map(0xe800, 0xffff).bankr(TO8_BIOS_BANK); /* 2 * 6 KB */
/* 0x10000 - 0x1ffff: 64 KB external ROM cartridge */
/* 0x20000 - 0x2ffff: 64 KB internal software ROM */
/* 0x30000 - 0x33fff: 16 KB BIOS ROM */
/* 18 KB external floppy / network ROM controllers */
/* RAM mapping: 512 KB flat (including video) */
}
/* ------------ ROMS ------------ */
ROM_START ( to8 )
ROM_REGION ( 0x24000, "maincpu", 0 )
/* BIOS & floppy */
ROM_LOAD ( "to8-0.rom", 0x20000, 0x2000,
CRC(3c4a640a)
SHA1(0a4952f0ca002d82ac83755e1f694d56399413b2) )
ROM_LOAD ( "to8-1.rom", 0x22000, 0x2000,
CRC(cb9bae2d)
SHA1(a4a55a6e2c74bca15951158c5164970e922fc1c1) )
/* BASIC */
ROM_LOAD ( "basic8-0.rom", 0x10000, 0x4000,
CRC(e5a00fb3)
SHA1(281e535ed9b0f76e620253e9103292b8ff623d02) )
ROM_LOAD ( "basic8-1.rom", 0x14000, 0x4000,
CRC(4b241e63)
SHA1(ca8941a10db6cc069bf84c773f5e7d7d2c18449e) )
ROM_LOAD ( "basic8-2.rom", 0x18000, 0x4000,
CRC(0f5581b3)
SHA1(93815ca78d3532192aaa56cbf65b68b0f10f1b8a) )
ROM_LOAD ( "basic8-3.rom", 0x1c000, 0x4000,
CRC(f552e7e3)
SHA1(3208e0d7d90241a327ed24e4921303f16e167bd5) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL( 0x00000, 0x10000, 0x39 )
ROM_END
ROM_START ( to8d )
ROM_REGION ( 0x24000, "maincpu", 0 )
/* BIOS & floppy */
ROM_LOAD ( "to8d-0.rom", 0x20000, 0x2000,
CRC(30ea4950)
SHA1(6705100cd337fffb26ce999302b55fb71557b128) )
ROM_LOAD ( "to8d-1.rom", 0x22000, 0x2000,
CRC(926cf0ca)
SHA1(8521613ac00e04dd94b69e771aeaefbf4fe97bf7) )
/* BASIC */
ROM_LOAD ( "basic8-0.rom", 0x10000, 0x4000,
CRC(e5a00fb3)
SHA1(281e535ed9b0f76e620253e9103292b8ff623d02) )
ROM_LOAD ( "basic8-1.rom", 0x14000, 0x4000,
CRC(4b241e63)
SHA1(ca8941a10db6cc069bf84c773f5e7d7d2c18449e) )
ROM_LOAD ( "basic8-2.rom", 0x18000, 0x4000,
CRC(0f5581b3)
SHA1(93815ca78d3532192aaa56cbf65b68b0f10f1b8a) )
ROM_LOAD ( "basic8-3.rom", 0x1c000, 0x4000,
CRC(f552e7e3)
SHA1(3208e0d7d90241a327ed24e4921303f16e167bd5) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL( 0x00000, 0x10000, 0x39 )
ROM_END
/* ------------ inputs ------------ */
static INPUT_PORTS_START ( to8_config )
PORT_START ( "config" )
PORT_CONFNAME ( 0x01, 0x00, "Game Port" )
PORT_CONFSETTING ( 0x00, DEF_STR( Joystick ) )
PORT_CONFSETTING ( 0x01, "Mouse" )
PORT_CONFNAME ( 0x02, 0x00, "Keyboard" )
PORT_CONFSETTING ( 0x00, "Enabled" )
PORT_CONFSETTING ( 0x02, "Disabled" )
INPUT_PORTS_END
static INPUT_PORTS_START ( to8 )
PORT_INCLUDE ( thom_lightpen )
PORT_INCLUDE ( thom_game_port )
PORT_INCLUDE ( to9_keyboard )
PORT_INCLUDE ( to8_config )
PORT_INCLUDE ( to7_vconfig )
PORT_INCLUDE ( to7_mconfig )
INPUT_PORTS_END
static INPUT_PORTS_START ( to8d )
PORT_INCLUDE ( to8 )
INPUT_PORTS_END
/* ------------ driver ------------ */
void to9_state::to8(machine_config &config)
{
to7(config);
MCFG_MACHINE_START_OVERRIDE( to9_state, to8 )
MCFG_MACHINE_RESET_OVERRIDE( to9_state, to8 )
m_maincpu->set_addrmap(AS_PROGRAM, &to9_state::to8_map);
//MC6804(config, "kbdmcu", 11_MHz_XTAL);
m_pia_sys->readpa_handler().set(FUNC(to9_state::to8_sys_porta_in));
m_pia_sys->readpb_handler().set_constant(0);
m_pia_sys->writepa_handler().set(FUNC(to9_state::to9_sys_porta_out));
m_pia_sys->writepb_handler().set(FUNC(to9_state::to8_sys_portb_out));
m_pia_sys->cb2_handler().set_nop();
m_pia_sys->irqa_handler().set_nop();
CENTRONICS(config, m_centronics, centronics_devices, "printer");
m_centronics->busy_handler().set(FUNC(to9_state::write_centronics_busy));
m_mc6846->out_port().set(FUNC(to9_state::to8_timer_port_out));
m_mc6846->in_port().set(FUNC(to9_state::to8_timer_port_in));
m_mc6846->cp2().set(FUNC(to9_state::to8_timer_cp2_out));
/* internal ram */
m_ram->set_default_size("512K").set_extra_options("256K");
SOFTWARE_LIST(config, "to8_cass_list").set_original("to8_cass");
SOFTWARE_LIST(config, "to8_qd_list").set_original("to8_qd");
SOFTWARE_LIST(config.replace(), "to7_cass_list").set_compatible("to7_cass");
SOFTWARE_LIST(config.replace(), "to7_qd_list").set_compatible("to7_qd");
}
void to9_state::to8d(machine_config &config)
{
to8(config);
}
COMP( 1986, to8, 0, 0, to8, to8, to9_state, empty_init, "Thomson", "TO8", 0 )
COMP( 1987, to8d, to8, 0, to8d, to8d, to9_state, empty_init, "Thomson", "TO8D", 0 )
/******************************** TO9+ *******************************
TO9+ (1986)
----
The TO9+ is the direct successor of the T09 as Thomson's high-end
product: desktop look, 512 KB of RAM, integrated floppy drive and
modem. Some software integrated in ROM on the TO9 are now supplied on
floppies.
Internally, the TO9+ is based more on TO8 technology than T09
(same gate-arrays).
It has enhanced communication capabilities by integrating either the
MODEM or the RS232 extension.
It should be compatible with the TO9 and, to some extent, with the TO7, TO7/70
and TO8.
It uses the same video gate-array and floppy controller.
The differences with the TO8 are:
* chips:
- 1 Motorola 6805 + 1 Motorola 6850 (keyboard)
- 3 Motorola 6821 PIAs (system, game, modem)
* memory:
- 512 KB RAM (not extendable)
* devices:
- same keyboard as T08/TO9 (AZERTY 81-keys) but different controller
- RF 57-932: RS232 (identical to the TO7) sometimes integrated
- MD 90-120: MODEM (identical to the TO7?) sometimes integrated
- IEEE extension ?
- floppy: one two-sided double-density 3''1/2 floppy drive is integrated
- RS 52-932 RS232 extension ?
- digitisation extension
**********************************************************************/
void to9_state::to9p_map(address_map &map)
{
map(0x0000, 0x3fff).bankr(THOM_CART_BANK).w(FUNC(to9_state::to8_cartridge_w)); /* 4 * 16 KB */
map(0x4000, 0x5fff).bankr(THOM_VRAM_BANK).w(FUNC(to9_state::to770_vram_w));
map(0x6000, 0x7fff).bankr(TO8_SYS_LO).w(FUNC(to9_state::to8_sys_lo_w));
map(0x8000, 0x9fff).bankr(TO8_SYS_HI).w(FUNC(to9_state::to8_sys_hi_w));
map(0xa000, 0xbfff).bankr(TO8_DATA_LO).w(FUNC(to9_state::to8_data_lo_w));
map(0xc000, 0xdfff).bankr(TO8_DATA_HI).w(FUNC(to9_state::to8_data_hi_w));
map(0xe7c0, 0xe7c7).rw(m_mc6846, FUNC(mc6846_device::read), FUNC(mc6846_device::write));
map(0xe7c8, 0xe7cb).rw("pia_0", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7cc, 0xe7cf).rw("pia_1", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7da, 0xe7dd).rw(FUNC(to9_state::to8_vreg_r), FUNC(to9_state::to8_vreg_w));
map(0xe7de, 0xe7df).rw(FUNC(to9_state::to9_kbd_r), FUNC(to9_state::to9_kbd_w));
map(0xe7e4, 0xe7e7).rw(FUNC(to9_state::to8_gatearray_r), FUNC(to9_state::to8_gatearray_w));
map(0xe7e8, 0xe7eb).rw("acia", FUNC(mos6551_device::read), FUNC(mos6551_device::write));
/* map(0xe7f0, 0xe7f7).rw(FUNC(to9_state::to9_ieee_r), FUNC(to9_state::to9_ieee_w )); */
map(0xe7f2, 0xe7f3).rw(FUNC(to9_state::to7_midi_r), FUNC(to9_state::to7_midi_w));
map(0xe7f8, 0xe7fb).rw("pia_3", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xe7fe, 0xe7ff).rw(FUNC(to9_state::to7_modem_mea8000_r), FUNC(to9_state::to7_modem_mea8000_w));
map(0xe800, 0xffff).bankr(TO8_BIOS_BANK); /* 2 * 6 KB */
/* 0x10000 - 0x1ffff: 64 KB external ROM cartridge */
/* 0x20000 - 0x2ffff: 64 KB internal software ROM */
/* 0x30000 - 0x33fff: 16 KB BIOS ROM */
/* 18 KB external floppy / network ROM controllers */
/* RAM mapping: 512 KB flat (including video) */
}
/* ------------ ROMS ------------ */
ROM_START ( to9p )
ROM_REGION ( 0x24000, "maincpu", 0 )
/* BIOS & floppy */
ROM_LOAD ( "to9p-0.rom", 0x20000, 0x2000,
CRC(a2731296)
SHA1(b30e06127d6e99d4ac5a5bb67881df27bbd9a7e5) )
ROM_LOAD ( "to9p-1.rom", 0x22000, 0x2000,
CRC(c52ce315)
SHA1(7eacbd796e76bc72b872f9700c9b90414899ea0f) )
/* BASIC */
ROM_LOAD ( "basicp-0.rom", 0x10000, 0x4000,
CRC(e5a00fb3)
SHA1(281e535ed9b0f76e620253e9103292b8ff623d02) )
ROM_LOAD ( "basicp-1.rom", 0x14000, 0x4000,
CRC(4b241e63)
SHA1(ca8941a10db6cc069bf84c773f5e7d7d2c18449e) )
ROM_LOAD ( "basicp-2.rom", 0x18000, 0x4000,
CRC(0f5581b3)
SHA1(93815ca78d3532192aaa56cbf65b68b0f10f1b8a) )
ROM_LOAD ( "basicp-3.rom", 0x1c000, 0x4000,
CRC(ebe9c8d9)
SHA1(b667ad09a1181f65059a2cbb4c95421bc544a334) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL( 0x00000, 0x10000, 0x39 )
ROM_END
/* ------------ inputs ------------ */
static INPUT_PORTS_START ( to9p )
PORT_INCLUDE ( thom_lightpen )
PORT_INCLUDE ( thom_game_port )
PORT_INCLUDE ( to9_keyboard )
PORT_INCLUDE ( to7_config )
PORT_INCLUDE ( to7_vconfig )
PORT_INCLUDE ( to7_mconfig )
INPUT_PORTS_END
/* ------------ driver ------------ */
void to9_state::to9p(machine_config &config)
{
to7(config);
MCFG_MACHINE_START_OVERRIDE( to9_state, to9p )
MCFG_MACHINE_RESET_OVERRIDE( to9_state, to9p )
m_maincpu->set_addrmap(AS_PROGRAM, &to9_state::to9p_map);
m_pia_sys->readpa_handler().set(FUNC(to9_state::to8_sys_porta_in));
m_pia_sys->readpb_handler().set_constant(0);
m_pia_sys->writepa_handler().set(FUNC(to9_state::to9_sys_porta_out));
m_pia_sys->writepb_handler().set(FUNC(to9_state::to8_sys_portb_out));
m_pia_sys->cb2_handler().set_nop();
m_pia_sys->irqa_handler().set_nop();
m_pia_sys->irqb_handler().set("mainfirq", FUNC(input_merger_device::in_w<1>));
CENTRONICS(config, m_centronics, centronics_devices, "printer");
m_centronics->busy_handler().set(FUNC(to9_state::write_centronics_busy));
m_mc6846->out_port().set(FUNC(to9_state::to9p_timer_port_out));
m_mc6846->in_port().set(FUNC(to9_state::to9p_timer_port_in));
m_mc6846->cp2().set(FUNC(to9_state::to8_timer_cp2_out));
/* internal ram */
m_ram->set_default_size("512K");
SOFTWARE_LIST(config, "to8_cass_list").set_original("to8_cass");
SOFTWARE_LIST(config, "to8_qd_list").set_original("to8_qd");
SOFTWARE_LIST(config.replace(), "to7_cass_list").set_compatible("to7_cass");
SOFTWARE_LIST(config.replace(), "to7_qd_list").set_compatible("to7_qd");
}
COMP( 1986, to9p, 0, 0, to9p, to9p, to9_state, empty_init, "Thomson", "TO9+", 0 )
/******************************** MO6 ********************************
MO6 (1986)
---
The MO6 is the (long awaited) successor to the MO5.
It is based on TO8 technology (same system & video gate-array).
However, it is lower-end and cheaper: less memory (128 KB RAM, not
extensible), no floppy controller but an integrated cassette recorder.
The MO6 is MO5 compatible, but not compatible with the TO family.
* chips:
- 1 MHz Motorola 6809E CPU
- 2 Motorola 6821 PIAs (system, game)
- 1 gate-array (system & video, identical to the TO8)
* memory:
- 128 KB RAM (not extendable)
- 8 KB BIOS ROM
- 24 KB BASIC 1 ROM
- 32 KB BASIC 128 & extended BIOS ROM
* video:
all modes from the TO8, but the TO7/70-compatible mode is replaced with
an MO5-compatible one
* devices:
- AZERTY keyboard, 69 keys, no keyboard controller (scanning is done
periodically by the 6809)
- MO5-compatible cartridge
- two-button mouse (TO8-like)
- optional lightpen
- integrated game port (similar to SX 90-018)
. 6-bit DAC sound
. two 8-position 2-button game pads
. two-button mouse
- integrated cassette reader 1200 bauds (MO5 compatible) and 2400 bauds
- parallel CENTRONICS (printer emulated)
- RF 57-932: RS232 extension (identical to the TO7), or RF 90-932 (???)
- IEEE extension ?
- no integrated controller, but external TO7 floppy controllers & drives
are possible
- speech synthesis extension: identical to TO7 ?
- MIDIPAK MIDI extension: identical to TO7 ?
Olivetti Prodest PC 128 (1986)
-----------------------
Italian version of the MO6, built by Thomson and sold by Olivetti.
Except from the ROM, it is very similar to the MO6.
Do not confuse with the Olivetti Prodest PC 128 Systema (or 128s) which is
based on the Acorn BBC Master Compact. Or with the Olivetti PC 1, which is
a PC XT.
**********************************************************************/
void mo6_state::mo6_map(address_map &map)
{
map(0x0000, 0x1fff).bankr(THOM_VRAM_BANK).w(FUNC(mo6_state::to770_vram_w));
map(0x2000, 0x3fff).bankr(TO8_SYS_LO).w(FUNC(mo6_state::to8_sys_lo_w));
map(0x4000, 0x5fff).bankr(TO8_SYS_HI).w(FUNC(mo6_state::to8_sys_hi_w));
map(0x6000, 0x7fff).bankr(TO8_DATA_LO).w(FUNC(mo6_state::to8_data_lo_w));
map(0x8000, 0x9fff).bankr(TO8_DATA_HI).w(FUNC(mo6_state::to8_data_hi_w));
map(0xa7c0, 0xa7c3).rw("pia_0", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xa7cb, 0xa7cb).w(FUNC(mo6_state::mo6_ext_w));
map(0xa7cc, 0xa7cf).rw("pia_1", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xa7da, 0xa7dd).rw(FUNC(mo6_state::mo6_vreg_r), FUNC(mo6_state::mo6_vreg_w));
map(0xa7e4, 0xa7e7).rw(FUNC(mo6_state::mo6_gatearray_r), FUNC(mo6_state::mo6_gatearray_w));
map(0xa7e8, 0xa7eb).rw("acia", FUNC(mos6551_device::read), FUNC(mos6551_device::write));
/* map(0xa7f0, 0xa7f7).rw(FUNC(mo6_state::to9_ieee_r), FUNC(homson_state::to9_ieee_w));*/
map(0xa7f2, 0xa7f3).rw(FUNC(mo6_state::to7_midi_r), FUNC(mo6_state::to7_midi_w));
map(0xa7fe, 0xa7ff).rw(m_mea8000, FUNC(mea8000_device::read), FUNC(mea8000_device::write));
map(0xb000, 0xbfff).bankr(MO6_CART_LO).w(FUNC(mo6_state::mo6_cartridge_w));
map(0xc000, 0xefff).bankr(MO6_CART_HI).w(FUNC(mo6_state::mo6_cartridge_w));
map(0xf000, 0xffff).bankr(TO8_BIOS_BANK);
/* 0x10000 - 0x1ffff: 64 KB external ROM cartridge */
/* 0x20000 - 0x2ffff: 64 KB BIOS ROM */
/* 16 KB floppy / network ROM controllers */
/* RAM mapping: 128 KB flat (including video) */
}
/* ------------ ROMS ------------ */
ROM_START ( mo6 )
ROM_REGION ( 0x20000, "maincpu", 0 )
/* BIOS */
ROM_LOAD ( "mo6-0.rom", 0x13000, 0x1000,
CRC(0446eef6)
SHA1(b57fcda69c95f0c97c5cb0605d17c49a0c630300) )
ROM_LOAD ( "mo6-1.rom", 0x17000, 0x1000,
CRC(eb6df8d4)
SHA1(24e2232f582ce04f260acd8e9ec710468a81505c) )
/* BASIC */
ROM_LOAD ( "basic6-0.rom", 0x10000, 0x3000,
CRC(18789833)
SHA1(fccbf69cbc6deba45a767a26cd6454cf0eedfc2b) )
ROM_LOAD ( "basic6-1.rom", 0x14000, 0x3000,
CRC(c9b4d6f4)
SHA1(47487d2bc4c9a9c09c733bd89c49693c52e262de) )
ROM_LOAD ( "basic6-2.rom", 0x18000, 0x4000,
CRC(08eac9bb)
SHA1(c0231fdb3bcccbbb10c1f93cc529fc3b96dd3f4d) )
ROM_LOAD ( "basic6-3.rom", 0x1c000, 0x4000,
CRC(19d66dc4)
SHA1(301b6366269181b74cb5d7ccdf5455b7290ae99b) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL ( 0x00000, 0x10000, 0x39 )
ROM_END
ROM_START ( pro128 )
ROM_REGION ( 0x20000, "maincpu", 0 )
/* BIOS */
ROM_LOAD ( "pro128-0.rom", 0x13000, 0x1000,
CRC(a8aef291)
SHA1(2685cca841f405a37ef48b0115f90c865ce79d0f) )
ROM_LOAD ( "pro128-1.rom", 0x17000, 0x1000,
CRC(5b3340ec)
SHA1(269f2eb3e3452014b8d1f0f9e1c63fe56375a863) )
/* BASIC */
ROM_LOAD ( "basico-0.rom", 0x10000, 0x3000,
CRC(98b10d5e)
SHA1(d6b77e694fa85e1114293448e5a64f6e2cf46c22) )
ROM_LOAD ( "basico-1.rom", 0x14000, 0x3000,
CRC(721d2124)
SHA1(51db1cd03b3891e212a24aa6563b09968930d897) )
ROM_LOAD ( "basico-2.rom", 0x18000, 0x4000,
CRC(135438ab)
SHA1(617d4e4979842bea2c21ef7f8c50f3b08b15239a) )
ROM_LOAD ( "basico-3.rom", 0x1c000, 0x4000,
CRC(2c2befa6)
SHA1(3e94e182bacbb55bb07be2af4c76c0b0df47b3bf) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL ( 0x00000, 0x10000, 0x39 )
ROM_END
/* ------------ inputs ------------ */
static INPUT_PORTS_START ( mo6_keyboard )
PORT_START ( "keyboard.0" )
KEY ( 0, "N", N ) PORT_CHAR('N')
KEY ( 1, ", ?", COMMA ) PORT_CHAR(',') PORT_CHAR('?')
KEY ( 2, "; .", STOP ) PORT_CHAR(';') PORT_CHAR('.')
KEY ( 3, "# @", TILDE ) PORT_CHAR('#') PORT_CHAR('@')
KEY ( 4, "Space", SPACE ) PORT_CHAR(' ')
KEY ( 5, "X", X ) PORT_CHAR('X')
KEY ( 6, "W", W ) PORT_CHAR('W')
KEY ( 7, "Shift", LSHIFT ) PORT_CODE ( KEYCODE_RSHIFT ) PORT_CHAR(UCHAR_SHIFT_1)
PORT_START ( "keyboard.1" )
KEY ( 0, "Delete Backspace", DEL ) PORT_CHAR(8) PORT_CHAR(UCHAR_MAMEKEY(BACKSPACE))
KEY ( 1, "Insert", INSERT ) PORT_CHAR(UCHAR_MAMEKEY(INSERT))
KEY ( 2, "> <", BACKSLASH2 ) PORT_CHAR('>') PORT_CHAR('<')
KEY ( 3, UTF8_RIGHT, RIGHT ) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
KEY ( 4, UTF8_DOWN, DOWN ) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
KEY ( 5, UTF8_LEFT, LEFT ) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
KEY ( 6, UTF8_UP, UP ) PORT_CHAR(UCHAR_MAMEKEY(UP))
KEY ( 7, "BASIC", RCONTROL ) PORT_CHAR(UCHAR_MAMEKEY(RCONTROL))
PORT_START ( "keyboard.2" )
KEY ( 0, "J", J ) PORT_CHAR('J')
KEY ( 1, "K", K ) PORT_CHAR('K')
KEY ( 2, "L", L ) PORT_CHAR('L')
KEY ( 3, "M", M ) PORT_CHAR('M')
KEY ( 4, "B \302\264", B ) PORT_CHAR('B')
KEY ( 5, "V", V ) PORT_CHAR('V')
KEY ( 6, "C \136", C ) PORT_CHAR('C')
KEY ( 7, "Caps-Lock", CAPSLOCK ) PORT_CHAR(UCHAR_MAMEKEY(CAPSLOCK))
PORT_START ( "keyboard.3" )
KEY ( 0, "H \302\250", H ) PORT_CHAR('H')
KEY ( 1, "G", G ) PORT_CHAR('G')
KEY ( 2, "F", F ) PORT_CHAR('F')
KEY ( 3, "D", D ) PORT_CHAR('D')
KEY ( 4, "S", S ) PORT_CHAR('S')
KEY ( 5, "Q", Q ) PORT_CHAR('Q')
KEY ( 6, "Home Clear", HOME ) PORT_CHAR(UCHAR_MAMEKEY(HOME)) PORT_CHAR(UCHAR_MAMEKEY(ESC))
KEY ( 7, "F1 F6", F1 ) PORT_CHAR(UCHAR_MAMEKEY(F1)) PORT_CHAR(UCHAR_MAMEKEY(F6))
PORT_START ( "keyboard.4" )
KEY ( 0, "U", U ) PORT_CHAR('U')
KEY ( 1, "I", I ) PORT_CHAR('I')
KEY ( 2, "O", O ) PORT_CHAR('O')
KEY ( 3, "P", P ) PORT_CHAR('P')
KEY ( 4, ": /", SLASH ) PORT_CHAR(':') PORT_CHAR('/')
KEY ( 5, "$ &", CLOSEBRACE ) PORT_CHAR('$') PORT_CHAR('&')
KEY ( 6, "Enter", ENTER ) PORT_CHAR(13)
KEY ( 7, "F2 F7", F2 ) PORT_CHAR(UCHAR_MAMEKEY(F2)) PORT_CHAR(UCHAR_MAMEKEY(F7))
PORT_START ( "keyboard.5" )
KEY ( 0, "Y", Y ) PORT_CHAR('Y')
KEY ( 1, "T", T ) PORT_CHAR('T')
KEY ( 2, "R", R ) PORT_CHAR('R')
KEY ( 3, "E", E ) PORT_CHAR('E')
KEY ( 4, "Z", Z ) PORT_CHAR('Z')
KEY ( 5, "A \140", A ) PORT_CHAR('A')
KEY ( 6, "Control", LCONTROL ) PORT_CHAR(UCHAR_MAMEKEY(LCONTROL))
KEY ( 7, "F3 F8", F3 ) PORT_CHAR(UCHAR_MAMEKEY(F3)) PORT_CHAR(UCHAR_MAMEKEY(F8))
PORT_START ( "keyboard.6" )
KEY ( 0, "7 \303\250", 7 ) PORT_CHAR('7') PORT_CHAR( 0xe8 )
KEY ( 1, "8 !", 8 ) PORT_CHAR('8') PORT_CHAR('!')
KEY ( 2, "9 \303\247", 9 ) PORT_CHAR('9') PORT_CHAR( 0xe7 )
KEY ( 3, "0 \303\240", 0 ) PORT_CHAR('0') PORT_CHAR( 0xe0 )
KEY ( 4, "- \\", BACKSPACE ) PORT_CHAR('-') PORT_CHAR('\\')
KEY ( 5, "= +", EQUALS ) PORT_CHAR('=') PORT_CHAR('+')
KEY ( 6, "Accent", END ) PORT_CHAR(UCHAR_MAMEKEY(END))
KEY ( 7, "F4 F9", F4 ) PORT_CHAR(UCHAR_MAMEKEY(F4)) PORT_CHAR(UCHAR_MAMEKEY(F9))
PORT_START ( "keyboard.7" )
KEY ( 0, "6 _", 6 ) PORT_CHAR('6') PORT_CHAR('_')
KEY ( 1, "5 (", 5 ) PORT_CHAR('5') PORT_CHAR('(')
KEY ( 2, "4 '", 4 ) PORT_CHAR('4') PORT_CHAR('\'')
KEY ( 3, "3 \"", 3 ) PORT_CHAR('3') PORT_CHAR('"')
KEY ( 4, "2 \303\251", 2 ) PORT_CHAR('2') PORT_CHAR( 0xe9 )
KEY ( 5, "1 *", 1 ) PORT_CHAR('1') PORT_CHAR('*')
KEY ( 6, "Stop", TAB ) PORT_CHAR(27)
KEY ( 7, "F5 F10", F5 ) PORT_CHAR(UCHAR_MAMEKEY(F5)) PORT_CHAR(UCHAR_MAMEKEY(F10))
PORT_START ( "keyboard.8" )
KEY ( 0, "[ {", QUOTE ) PORT_CHAR('[') PORT_CHAR('{')
KEY ( 1, "] }", BACKSLASH ) PORT_CHAR(']') PORT_CHAR('}')
KEY ( 2, ") \302\260", MINUS ) PORT_CHAR(')') PORT_CHAR( 0xb0 )
KEY ( 3, "\342\206\221 \302\250", OPENBRACE ) PORT_CHAR('^') PORT_CHAR( 0xa8 )
KEY ( 4, "\303\271 %", COLON ) PORT_CHAR( 0xf9 ) PORT_CHAR('%')
PORT_BIT ( 0xe0, IP_ACTIVE_LOW, IPT_UNUSED )
/* unused */
PORT_START ( "keyboard.9" )
INPUT_PORTS_END
/* QWERTY version */
static INPUT_PORTS_START ( pro128_keyboard )
PORT_INCLUDE ( mo6_keyboard )
PORT_MODIFY ( "keyboard.0" )
KEY ( 1, "M", M ) PORT_CHAR('M')
KEY ( 2, ", ;", COMMA ) PORT_CHAR(',') PORT_CHAR(';')
KEY ( 3, "[ {", QUOTE ) PORT_CHAR('[') PORT_CHAR('{')
KEY ( 6, "Z", Z ) PORT_CHAR('Z')
KEY ( 7, "Shift", LSHIFT ) PORT_CODE ( KEYCODE_RSHIFT ) PORT_CHAR(UCHAR_SHIFT_1)
PORT_MODIFY ( "keyboard.1" )
KEY ( 2, "- _", MINUS ) PORT_CHAR('-') PORT_CHAR('_')
PORT_MODIFY ( "keyboard.2" )
KEY ( 3, "\303\221", TILDE ) PORT_CHAR( 0xd1 )
PORT_MODIFY ( "keyboard.3" )
KEY ( 5, "A \140", A ) PORT_CHAR('A')
PORT_MODIFY ( "keyboard.4" )
KEY ( 4, ". :", STOP ) PORT_CHAR('.') PORT_CHAR(':')
KEY ( 5, "+ *", BACKSPACE ) PORT_CHAR('+') PORT_CHAR('*')
PORT_MODIFY ( "keyboard.5" )
KEY ( 4, "W", W ) PORT_CHAR('W')
KEY ( 5, "Q", Q ) PORT_CHAR('Q')
PORT_MODIFY ( "keyboard.6" )
KEY ( 0, "7 /", 7 ) PORT_CHAR('7') PORT_CHAR('/')
KEY ( 1, "8 (", 8 ) PORT_CHAR('8') PORT_CHAR('(')
KEY ( 2, "9 )", 9 ) PORT_CHAR('9') PORT_CHAR(')')
KEY ( 3, "0 =", 0 ) PORT_CHAR('0') PORT_CHAR('=')
KEY ( 4, "' \302\243", CLOSEBRACE ) PORT_CHAR('\'') PORT_CHAR( 0xa3 )
KEY ( 5, "] }", BACKSLASH ) PORT_CHAR(']') PORT_CHAR('}')
PORT_MODIFY ( "keyboard.7" )
KEY ( 0, "6 &", 6 ) PORT_CHAR('6') PORT_CHAR('&')
KEY ( 1, "5 %", 5 ) PORT_CHAR('5') PORT_CHAR('%')
KEY ( 2, "4 $", 4 ) PORT_CHAR('4') PORT_CHAR('$')
KEY ( 3, "3 \302\247", 3 ) PORT_CHAR('3') PORT_CHAR( 0xa7 )
KEY ( 4, "2 \"", 2 ) PORT_CHAR('2') PORT_CHAR('"')
KEY ( 5, "1 !", 1 ) PORT_CHAR('1') PORT_CHAR('!')
PORT_MODIFY ( "keyboard.8" )
KEY ( 0, "> <", BACKSLASH2 ) PORT_CHAR('>') PORT_CHAR('<')
KEY ( 1, "# \342\206\221", EQUALS ) PORT_CHAR('#') PORT_CHAR('^')
KEY ( 2, "\303\247 ?", COLON ) PORT_CHAR( 0xe7 ) PORT_CHAR('?')
KEY ( 3, "\302\277 @", SLASH ) PORT_CHAR( 0xbf ) PORT_CHAR('@')
KEY ( 4, "\302\241 \302\250", OPENBRACE ) PORT_CHAR( 0xa1 ) PORT_CHAR( 0xa8 )
INPUT_PORTS_END
static INPUT_PORTS_START ( mo6 )
PORT_INCLUDE ( thom_lightpen )
PORT_INCLUDE ( thom_game_port )
PORT_INCLUDE ( mo6_keyboard )
PORT_INCLUDE ( to7_config )
PORT_INCLUDE ( to7_vconfig )
INPUT_PORTS_END
static INPUT_PORTS_START ( pro128 )
PORT_INCLUDE ( thom_lightpen )
PORT_INCLUDE ( thom_game_port )
PORT_INCLUDE ( pro128_keyboard )
PORT_INCLUDE ( to7_config )
PORT_INCLUDE ( to7_vconfig )
INPUT_PORTS_END
/* ------------ driver ------------ */
void mo6_state::mo6(machine_config &config)
{
to7_base(config, true);
MCFG_MACHINE_START_OVERRIDE( mo6_state, mo6 )
MCFG_MACHINE_RESET_OVERRIDE( mo6_state, mo6 )
m_maincpu->set_addrmap(AS_PROGRAM, &mo6_state::mo6_map);
m_cassette->set_formats(mo5_cassette_formats);
m_cassette->set_interface("mo_cass");
m_pia_sys->readpa_handler().set(FUNC(mo6_state::mo6_sys_porta_in));
m_pia_sys->readpb_handler().set(FUNC(mo6_state::mo6_sys_portb_in));
m_pia_sys->writepa_handler().set(FUNC(mo6_state::mo6_sys_porta_out));
m_pia_sys->writepb_handler().set("buzzer", FUNC(dac_bit_interface::data_w));
m_pia_sys->ca2_handler().set(FUNC(mo6_state::mo5_set_cassette_motor));
m_pia_sys->cb2_handler().set(FUNC(mo6_state::mo6_sys_cb2_out));
m_pia_sys->irqb_handler().set("mainirq", FUNC(input_merger_device::in_w<1>)); // differs from TO
m_pia_game->writepa_handler().set(FUNC(mo6_state::mo6_game_porta_out));
m_pia_game->cb2_handler().set(FUNC(mo6_state::mo6_game_cb2_out));
CENTRONICS(config, m_centronics, centronics_devices, "printer");
m_centronics->busy_handler().set(FUNC(mo6_state::write_centronics_busy));
OUTPUT_LATCH(config, m_cent_data_out);
m_centronics->set_output_latch(*m_cent_data_out);
GENERIC_CARTSLOT(config.replace(), "cartslot", generic_plain_slot, "mo_cart", "m5,rom").set_device_load(FUNC(mo6_state::mo5_cartridge));
/* internal ram */
m_ram->set_default_size("128K");
config.device_remove("to7_cart_list");
config.device_remove("to7_cass_list");
config.device_remove("to_flop_list");
config.device_remove("to7_qd_list");
SOFTWARE_LIST(config, "mo6_cass_list").set_original("mo6_cass");
SOFTWARE_LIST(config, "mo6_flop_list").set_original("mo6_flop");
SOFTWARE_LIST(config, "mo5_cart_list").set_compatible("mo5_cart");
SOFTWARE_LIST(config, "mo5_cass_list").set_compatible("mo5_cass");
SOFTWARE_LIST(config, "mo5_flop_list").set_compatible("mo5_flop");
SOFTWARE_LIST(config, "mo5_qd_list").set_compatible("mo5_qd");
}
void mo6_state::pro128(machine_config &config)
{
mo6(config);
config.device_remove("mo6_cass_list");
config.device_remove("mo6_flop_list");
config.device_remove("mo5_cart_list");
config.device_remove("mo5_cass_list");
config.device_remove("mo5_flop_list");
config.device_remove("mo5_qd_list");
SOFTWARE_LIST(config, "p128_cart_list").set_original("pro128_cart");
SOFTWARE_LIST(config, "p128_cass_list").set_original("pro128_cass");
SOFTWARE_LIST(config, "p128_flop_list").set_original("pro128_flop");
}
COMP( 1986, mo6, 0, 0, mo6, mo6, mo6_state, empty_init, "Thomson", "MO6", 0 )
COMP( 1986, pro128, mo6, 0, pro128, pro128, mo6_state, empty_init, "Olivetti / Thomson", "Prodest PC 128", 0 )
/****************************** MO5NR ********************************
MO5 NR (1986)
------
Despite its name, the MO5 NR is much more related to the MO6 than to the MO5.
It can be though as the network-enhanced version of the MO6.
It is both MO5 and MO6 compatible (but not TO-compatible).
Here are the differences between the MO6 and MO5NR:
* chips:
- integrated MC 6854 network controller
* memory:
- extra 2 KB ROM for the integrated network controller,
can be masked by the ROM from the external floppy controller
* video: identical
* devices:
- AZERTY keyboard has only 58 keys, and no caps-lock led
- CENTRONICS printer handled differently
- MO5-compatible network (probably identical to NR 07-005 extension)
- extern floppy controller & drive possible, masks the network
**********************************************************************/
void mo5nr_state::mo5nr_map(address_map &map)
{
map(0x0000, 0x1fff).bankr(THOM_VRAM_BANK).w(FUNC(mo5nr_state::to770_vram_w));
map(0x2000, 0x3fff).bankr(TO8_SYS_LO).w(FUNC(mo5nr_state::to8_sys_lo_w));
map(0x4000, 0x5fff).bankr(TO8_SYS_HI).w(FUNC(mo5nr_state::to8_sys_hi_w));
map(0x6000, 0x7fff).bankr(TO8_DATA_LO).w(FUNC(mo5nr_state::to8_data_lo_w));
map(0x8000, 0x9fff).bankr(TO8_DATA_HI).w(FUNC(mo5nr_state::to8_data_hi_w));
map(0xa000, 0xa7ff).view(m_extension_view);
map(0xa7c0, 0xa7c3).rw("pia_0", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xa7cb, 0xa7cb).w(FUNC(mo5nr_state::mo6_ext_w));
map(0xa7cc, 0xa7cf).rw("pia_1", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
m_extension_view[1](0xa7d8, 0xa7d9).r(FUNC(mo5nr_state::id_r));
map(0xa7da, 0xa7dd).rw(FUNC(mo5nr_state::mo6_vreg_r), FUNC(mo5nr_state::mo6_vreg_w));
map(0xa7e1, 0xa7e1).r("cent_data_in", FUNC(input_buffer_device::read));
map(0xa7e1, 0xa7e1).w(m_cent_data_out, FUNC(output_latch_device::write));
map(0xa7e3, 0xa7e3).rw(FUNC(mo5nr_state::mo5nr_prn_r), FUNC(mo5nr_state::mo5nr_prn_w));
map(0xa7e4, 0xa7e7).rw(FUNC(mo5nr_state::mo6_gatearray_r), FUNC(mo5nr_state::mo6_gatearray_w));
map(0xa7e8, 0xa7eb).rw("acia", FUNC(mos6551_device::read), FUNC(mos6551_device::write));
/* map(0xa7f0, 0xa7f7).rw(FUNC(mo5nr_state::to9_ieee_r), FUNC(homson_state::to9_ieee_w));*/
map(0xa7f2, 0xa7f3).rw(FUNC(mo5nr_state::to7_midi_r), FUNC(mo5nr_state::to7_midi_w));
map(0xa7f8, 0xa7fb).rw("pia_3", FUNC(pia6821_device::read_alt), FUNC(pia6821_device::write_alt));
map(0xa7fe, 0xa7ff).rw(m_mea8000, FUNC(mea8000_device::read), FUNC(mea8000_device::write));
map(0xb000, 0xbfff).bankr(MO6_CART_LO).w(FUNC(mo5nr_state::mo6_cartridge_w));
map(0xc000, 0xefff).bankr(MO6_CART_HI).w(FUNC(mo5nr_state::mo6_cartridge_w));
map(0xf000, 0xffff).bankr(TO8_BIOS_BANK);
/* 0x10000 - 0x1ffff: 64 KB external ROM cartridge */
/* 0x20000 - 0x2ffff: 64 KB BIOS ROM */
/* 16 KB floppy / network ROM controllers */
/* RAM mapping: 128 KB flat (including video) */
}
/* ------------ ROMS ------------ */
ROM_START ( mo5nr )
ROM_REGION ( 0x20000, "maincpu", 0 )
/* BIOS */
ROM_LOAD ( "mo5nr-0.rom", 0x13000, 0x1000,
CRC(06e31115)
SHA1(7429cc0c15475398b5ab514cb3d3efdc71cf082f) )
ROM_LOAD ( "mo5nr-1.rom", 0x17000, 0x1000,
CRC(7cda17c9)
SHA1(2ff6480ce9e30acc4c89b6113d7c8ea6095d90a5) )
/* BASIC */
ROM_LOAD ( "basicn-0.rom", 0x10000, 0x3000,
CRC(fae9e691)
SHA1(62fbfd6d4ca837f6cb8ed37f828eca97f80e6200) )
ROM_LOAD ( "basicn-1.rom", 0x14000, 0x3000,
CRC(cf134dd7)
SHA1(1bd961314e16e460d37a65f5e7f4acf5604fbb17) )
ROM_LOAD ( "basicn-2.rom", 0x18000, 0x4000,
CRC(b69d2e0d)
SHA1(ea3220bbae991e08259d38a7ea24533b2bb86418) )
ROM_LOAD ( "basicn-3.rom", 0x1c000, 0x4000,
CRC(7785610f)
SHA1(c38b0be404d8af6f409a1b52cb79a4e10fc33177) )
ROM_REGION ( 0x10000, "cartridge", 0 )
ROM_FILL ( 0x00000, 0x10000, 0x39 ) /* TODO: network ROM */
ROM_END
/* ------------ inputs ------------ */
static INPUT_PORTS_START ( mo5nr_keyboard )
PORT_START ( "keyboard.0" )
KEY ( 0, "N", N ) PORT_CHAR('N')
KEY ( 1, ", <", COMMA ) PORT_CHAR(',') PORT_CHAR('<')
KEY ( 2, ". >", STOP ) PORT_CHAR('.') PORT_CHAR('>')
KEY ( 3, "@ \342\206\221", TILDE ) PORT_CHAR('@') PORT_CHAR('^')
KEY ( 4, "Space Caps-Lock", SPACE ) PORT_CHAR(' ') PORT_CHAR(UCHAR_MAMEKEY(CAPSLOCK))
KEY ( 5, "X", X ) PORT_CHAR('X')
KEY ( 6, "W", W ) PORT_CHAR('W')
KEY ( 7, "Shift", LSHIFT ) PORT_CODE ( KEYCODE_RSHIFT ) PORT_CHAR(UCHAR_SHIFT_1)
PORT_START ( "keyboard.1" )
KEY ( 0, "Delete Backspace", DEL ) PORT_CHAR(8) PORT_CHAR(UCHAR_MAMEKEY(BACKSPACE))
KEY ( 1, "Insert", INSERT ) PORT_CHAR(UCHAR_MAMEKEY(INSERT))
KEY ( 2, "Home", HOME ) PORT_CHAR(UCHAR_MAMEKEY(HOME))
KEY ( 3, UTF8_RIGHT, RIGHT ) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
KEY ( 4, UTF8_DOWN, DOWN ) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
KEY ( 5, UTF8_LEFT, LEFT ) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
KEY ( 6, UTF8_UP, UP ) PORT_CHAR(UCHAR_MAMEKEY(UP))
KEY ( 7, "BASIC", RCONTROL )
PORT_START ( "keyboard.2" )
KEY ( 0, "J", J ) PORT_CHAR('J')
KEY ( 1, "K", K ) PORT_CHAR('K')
KEY ( 2, "L", L ) PORT_CHAR('L')
KEY ( 3, "M", M ) PORT_CHAR('M')
KEY ( 4, "B \140", B ) PORT_CHAR('B')
KEY ( 5, "V", V ) PORT_CHAR('V')
KEY ( 6, "C \136", C ) PORT_CHAR('C')
PORT_BIT ( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START ( "keyboard.3" )
KEY ( 0, "H \302\250", H ) PORT_CHAR('H')
KEY ( 1, "G", G ) PORT_CHAR('G')
KEY ( 2, "F", F ) PORT_CHAR('F')
KEY ( 3, "D", D ) PORT_CHAR('D')
KEY ( 4, "S", S ) PORT_CHAR('S')
KEY ( 5, "Q", Q ) PORT_CHAR('Q')
KEY ( 6, "Clear", ESC ) PORT_CHAR(UCHAR_MAMEKEY(ESC))
PORT_BIT ( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START ( "keyboard.4" )
KEY ( 0, "U", U ) PORT_CHAR('U')
KEY ( 1, "I", I ) PORT_CHAR('I')
KEY ( 2, "O", O ) PORT_CHAR('O')
KEY ( 3, "P", P ) PORT_CHAR('P')
KEY ( 4, "/ ?", SLASH ) PORT_CHAR('/') PORT_CHAR('?')
KEY ( 5, "* :", QUOTE ) PORT_CHAR('*') PORT_CHAR(':')
KEY ( 6, "Enter", ENTER ) PORT_CHAR(13)
PORT_BIT ( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START ( "keyboard.5" )
KEY ( 0, "Y", Y ) PORT_CHAR('Y')
KEY ( 1, "T", T ) PORT_CHAR('T')
KEY ( 2, "R", R ) PORT_CHAR('R')
KEY ( 3, "E", E ) PORT_CHAR('E')
KEY ( 4, "Z", Z ) PORT_CHAR('Z')
KEY ( 5, "A \140", A ) PORT_CHAR('A')
KEY ( 6, "Control", LCONTROL ) PORT_CHAR(UCHAR_MAMEKEY(LCONTROL))
PORT_BIT ( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START ( "keyboard.6" )
KEY ( 0, "7 ' \303\250", 7 ) PORT_CHAR('7') PORT_CHAR('\'' )
KEY ( 1, "8 ( \303\271", 8 ) PORT_CHAR('8') PORT_CHAR('(')
KEY ( 2, "9 ) \303\247", 9 ) PORT_CHAR('9') PORT_CHAR(')')
KEY ( 3, "0 \303\240", 0 ) PORT_CHAR('0') PORT_CHAR( 0xe0 )
KEY ( 4, "- =", MINUS ) PORT_CHAR('-') PORT_CHAR('=')
KEY ( 5, "+ ;", EQUALS ) PORT_CHAR('+') PORT_CHAR(';')
KEY ( 6, "Accent", END ) PORT_CHAR(UCHAR_MAMEKEY(END))
PORT_BIT ( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START ( "keyboard.7" )
KEY ( 0, "6 & \303\251", 6 ) PORT_CHAR('6') PORT_CHAR('&')
KEY ( 1, "5 %", 5 ) PORT_CHAR('5') PORT_CHAR('%')
KEY ( 2, "4 $", 4 ) PORT_CHAR('4') PORT_CHAR('$')
KEY ( 3, "3 #", 3 ) PORT_CHAR('3') PORT_CHAR('#')
KEY ( 4, "2 \"", 2 ) PORT_CHAR('2') PORT_CHAR('"')
KEY ( 5, "1 !", 1 ) PORT_CHAR('1') PORT_CHAR('!')
KEY ( 6, "Stop", TAB ) PORT_CHAR(27)
PORT_BIT ( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
/* unused */
PORT_START ( "keyboard.8" )
PORT_START ( "keyboard.9" )
INPUT_PORTS_END
static INPUT_PORTS_START ( mo5nr )
PORT_INCLUDE ( thom_lightpen )
PORT_INCLUDE ( thom_game_port )
PORT_INCLUDE ( mo5nr_keyboard )
PORT_INCLUDE ( to7_config )
PORT_INCLUDE ( to7_vconfig )
PORT_START ( "nanoreseau_config" )
PORT_DIPNAME(0x01, 0x01, "Extension selection") PORT_DIPLOCATION("SW03:1")
PORT_DIPSETTING(0x00, "Extension port")
PORT_DIPSETTING(0x01, "Internal networking")
PORT_DIPNAME(0x3e, 0x02, "Network ID") PORT_DIPLOCATION("SW03:2,3,4,5,6")
PORT_DIPSETTING(0x00, "0 (Master)")
PORT_DIPSETTING(0x02, "1")
PORT_DIPSETTING(0x04, "2")
PORT_DIPSETTING(0x06, "3")
PORT_DIPSETTING(0x08, "4")
PORT_DIPSETTING(0x0a, "5")
PORT_DIPSETTING(0x0c, "6")
PORT_DIPSETTING(0x0e, "7")
PORT_DIPSETTING(0x10, "8")
PORT_DIPSETTING(0x12, "9")
PORT_DIPSETTING(0x14, "10")
PORT_DIPSETTING(0x16, "11")
PORT_DIPSETTING(0x18, "12")
PORT_DIPSETTING(0x1a, "13")
PORT_DIPSETTING(0x1c, "14")
PORT_DIPSETTING(0x1e, "15")
PORT_DIPSETTING(0x20, "16")
PORT_DIPSETTING(0x22, "17")
PORT_DIPSETTING(0x24, "18")
PORT_DIPSETTING(0x26, "19")
PORT_DIPSETTING(0x28, "20")
PORT_DIPSETTING(0x2a, "21")
PORT_DIPSETTING(0x2c, "22")
PORT_DIPSETTING(0x2e, "23")
PORT_DIPSETTING(0x30, "24")
PORT_DIPSETTING(0x32, "25")
PORT_DIPSETTING(0x34, "26")
PORT_DIPSETTING(0x36, "27")
PORT_DIPSETTING(0x38, "28")
PORT_DIPSETTING(0x3a, "29")
PORT_DIPSETTING(0x3c, "30")
PORT_DIPSETTING(0x3e, "31")
INPUT_PORTS_END
/* ------------ driver ------------ */
void mo5nr_state::mo5nr(machine_config &config)
{
to7_base(config, true);
MCFG_MACHINE_START_OVERRIDE( mo5nr_state, mo5nr )
MCFG_MACHINE_RESET_OVERRIDE( mo5nr_state, mo5nr )
m_maincpu->set_addrmap(AS_PROGRAM, &mo5nr_state::mo5nr_map);
m_cassette->set_formats(mo5_cassette_formats);
m_cassette->set_interface("mo_cass");
m_pia_sys->readpa_handler().set(FUNC(mo5nr_state::mo6_sys_porta_in));
m_pia_sys->readpb_handler().set(FUNC(mo5nr_state::mo5nr_sys_portb_in));
m_pia_sys->writepa_handler().set(FUNC(mo5nr_state::mo5nr_sys_porta_out));
m_pia_sys->writepb_handler().set("buzzer", FUNC(dac_bit_interface::data_w));
m_pia_sys->ca2_handler().set(FUNC(mo5nr_state::mo5_set_cassette_motor));
m_pia_sys->cb2_handler().set(FUNC(mo5nr_state::mo6_sys_cb2_out));
m_pia_sys->irqb_handler().set("mainirq", FUNC(input_merger_device::in_w<1>)); // differs from TO
m_pia_game->writepa_handler().set(FUNC(mo5nr_state::mo6_game_porta_out));
CENTRONICS(config, m_centronics, centronics_devices, "printer");
m_centronics->set_data_input_buffer("cent_data_in");
m_centronics->busy_handler().set(FUNC(mo5nr_state::write_centronics_busy));
INPUT_BUFFER(config, "cent_data_in");
OUTPUT_LATCH(config, m_cent_data_out);
m_centronics->set_output_latch(*m_cent_data_out);
GENERIC_CARTSLOT(config.replace(), "cartslot", generic_plain_slot, "mo_cart", "m5,rom").set_device_load(FUNC(mo5nr_state::mo5_cartridge));
NANORESEAU_MO(config, m_nanoreseau, 0, true);
/* internal ram */
m_ram->set_default_size("128K");
config.device_remove("to7_cart_list");
config.device_remove("to7_cass_list");
config.device_remove("to_flop_list");
config.device_remove("to7_qd_list");
SOFTWARE_LIST(config, "mo6_cass_list").set_original("mo6_cass");
SOFTWARE_LIST(config, "mo6_flop_list").set_original("mo6_flop");
SOFTWARE_LIST(config, "mo5_cart_list").set_compatible("mo5_cart");
SOFTWARE_LIST(config, "mo5_cass_list").set_compatible("mo5_cass");
SOFTWARE_LIST(config, "mo5_flop_list").set_compatible("mo5_flop");
SOFTWARE_LIST(config, "mo5_qd_list").set_compatible("mo5_qd");
}
COMP( 1986, mo5nr, 0, 0, mo5nr, mo5nr, mo5nr_state, empty_init, "Thomson", "MO5 NR", 0 )
| 39.703165 | 139 | 0.656228 | [
"model"
] |
0803b039b400f2e9a6c83dd1eac061cc221fad31 | 3,554 | cpp | C++ | weex_core/Source/core/render/node/render_appbar.cpp | wyon/incubator-weex | fcd225f42b6647b27bd96e25cef344b7f1fd4bcf | [
"Apache-2.0"
] | 1 | 2019-09-24T07:57:49.000Z | 2019-09-24T07:57:49.000Z | weex_core/Source/core/render/node/render_appbar.cpp | wyon/incubator-weex | fcd225f42b6647b27bd96e25cef344b7f1fd4bcf | [
"Apache-2.0"
] | 2 | 2017-08-14T02:18:45.000Z | 2019-05-30T08:30:22.000Z | weex_core/Source/core/render/node/render_appbar.cpp | wyon/incubator-weex | fcd225f42b6647b27bd96e25cef344b7f1fd4bcf | [
"Apache-2.0"
] | 3 | 2019-05-30T09:30:43.000Z | 2019-10-10T11:09:42.000Z | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <utility>
#include "base/ViewUtils.h"
#include "core/config/core_environment.h"
#include "core/css/constants_name.h"
#include "core/render/node/render_appbar.h"
namespace WeexCore {
std::map<std::string, std::string> *RenderAppBar::GetDefaultStyle() {
this->default_nav_width_ = getFloat(
WXCoreEnvironment::getInstance()->GetOption("defaultNavWidth").c_str());
this->default_overflow_width_ =
getFloat(WXCoreEnvironment::getInstance()
->GetOption("defaultOverflowWidth")
.c_str());
std::string appbar_color =
WXCoreEnvironment::getInstance()->GetOption("appbar_color");
std::string appbar_background_color =
WXCoreEnvironment::getInstance()->GetOption("appbar_background_color");
std::map<std::string, std::string> *style =
new std::map<std::string, std::string>();
#if OS_IOS
style->insert(std::pair<std::string, std::string>(PADDING_LEFT, "44"));
style->insert(std::pair<std::string, std::string>(PADDING_RIGHT, "44"));
#else
style->insert(std::pair<std::string, std::string>(PADDING_LEFT, "0"));
style->insert(std::pair<std::string, std::string>(PADDING_RIGHT, "0"));
#endif
if (!appbar_color.empty() && appbar_color != "" && !StyleExist(COLOR))
style->insert(std::pair<std::string, std::string>(COLOR, appbar_color));
if (!appbar_background_color.empty() && appbar_background_color != "" &&
!StyleExist(BACKGROUND_COLOR))
style->insert(std::pair<std::string, std::string>(BACKGROUND_COLOR,
appbar_background_color));
return style;
}
bool RenderAppBar::StyleExist(const std::string &key) {
std::string value = GetStyle(key);
return !value.empty() && value != "";
}
StyleType RenderAppBar::ApplyStyle(const std::string &key,
const std::string &value,
const bool updating) {
if (key == PADDING) {
UpdateStyleInternal(key, value, 0, [=](float foo) {
setPadding(kPaddingLeft, foo + this->default_nav_width_);
setPadding(kPaddingRight, foo + this->default_overflow_width_);
setPadding(kPaddingTop, foo);
setPadding(kPaddingBottom, foo);
});
return kTypePadding;
} else if (key == PADDING_LEFT) {
UpdateStyleInternal(key, value, 0, [=](float foo) {
setPadding(kPaddingLeft, foo + this->default_nav_width_);
});
return kTypePadding;
} else if (key == PADDING_RIGHT) {
UpdateStyleInternal(key, value, 0, [=](float foo) {
setPadding(kPaddingRight, foo + this->default_overflow_width_);
});
return kTypePadding;
} else {
return RenderObject::ApplyStyle(key, value, updating);
}
}
} // namespace WeexCore
| 38.630435 | 80 | 0.674451 | [
"render"
] |
0805a3b259032adcbf73a879734e2bcc55bb66d2 | 252 | hpp | C++ | include/SearchA2DMatrixII.hpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | include/SearchA2DMatrixII.hpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | include/SearchA2DMatrixII.hpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #ifndef SEARCH_A_2D_MATRIX_II_HPP_
#define SEARCH_A_2D_MATRIX_II_HPP_
#include <vector>
using namespace std;
class SearchA2DMatrixII {
public:
bool searchMatrix(vector<vector<int>> &matrix, int target);
};
#endif // SEARCH_A_2D_MATRIX_II_HPP_
| 16.8 | 63 | 0.789683 | [
"vector"
] |
080dd3bafe9059de8df0932e7a3b69565f12d0e2 | 8,667 | cxx | C++ | Applications/SlicerApp/Main.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | Applications/SlicerApp/Main.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | Applications/SlicerApp/Main.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Copyright (c) Kitware Inc.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
and was partially funded by NIH grant 3P41RR013218-12S1
==============================================================================*/
// Qt includes
#include <QList>
#include <QSettings>
#include <QSplashScreen>
#include <QString>
#include <QStyleFactory>
#include <QSysInfo>
#include <QTimer>
// Slicer includes
#include "vtkSlicerConfigure.h"
// CTK includes
#include <ctkAbstractLibraryFactory.h>
#ifdef Slicer_USE_PYTHONQT
# include <ctkPythonConsole.h>
#endif
// Slicer includes
#include "vtkSlicerVersionConfigure.h" // For Slicer_VERSION_FULL, Slicer_BUILD_CLI_SUPPORT
// SlicerApp includes
#include "qSlicerApplication.h"
#include "qSlicerApplicationHelper.h"
#ifdef Slicer_BUILD_CLI_SUPPORT
# include "qSlicerCLIExecutableModuleFactory.h"
# include "qSlicerCLILoadableModuleFactory.h"
#endif
#include "qSlicerAppMainWindow.h"
#include "qSlicerCommandOptions.h"
#include "qSlicerModuleFactoryManager.h"
#include "qSlicerModuleManager.h"
#include "qSlicerStyle.h"
// ITK includes
#include <itkFactoryRegistration.h>
// VTK includes
//#include <vtkObject.h>
#include <vtksys/SystemTools.hxx>
#if defined (_WIN32) && !defined (Slicer_BUILD_WIN32_CONSOLE)
# include <windows.h>
# include <vtksys/Encoding.hxx>
#endif
namespace
{
#ifdef Slicer_USE_QtTesting
//-----------------------------------------------------------------------------
void setEnableQtTesting()
{
if (qSlicerApplication::application()->commandOptions()->enableQtTesting() ||
qSlicerApplication::application()->userSettings()->value("QtTesting/Enabled").toBool())
{
QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuBar);
}
}
#endif
//----------------------------------------------------------------------------
void splashMessage(QScopedPointer<QSplashScreen>& splashScreen, const QString& message)
{
if (splashScreen.isNull())
{
return;
}
splashScreen->showMessage(message, Qt::AlignBottom | Qt::AlignHCenter);
}
//----------------------------------------------------------------------------
int SlicerAppMain(int argc, char* argv[])
{
itk::itkFactoryRegistration();
#if QT_VERSION >= 0x040803
#ifdef Q_OS_MACX
if (QSysInfo::MacintoshVersion > QSysInfo::MV_10_8)
{
// Fix Mac OS X 10.9 (mavericks) font issue
// https://bugreports.qt-project.org/browse/QTBUG-32789
QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
}
#endif
#endif
// Allow a custom appliction name so that the settings
// can be distinct for differently named applications
QString applicationName("Slicer");
if (argv[0])
{
std::string name = vtksys::SystemTools::GetFilenameWithoutExtension(argv[0]);
applicationName = QString::fromLocal8Bit(name.c_str());
applicationName.remove(QString("App-real"));
}
QCoreApplication::setApplicationName(applicationName);
QCoreApplication::setApplicationVersion(Slicer_VERSION_FULL);
//vtkObject::SetGlobalWarningDisplay(false);
QApplication::setDesktopSettingsAware(false);
QApplication::setStyle(new qSlicerStyle());
qSlicerApplication app(argc, argv);
if (app.returnCode() != -1)
{
return app.returnCode();
}
app.installEventFilter(app.style());
#ifdef Slicer_USE_QtTesting
setEnableQtTesting(); // disabled the native menu bar.
#endif
bool enableMainWindow = !app.commandOptions()->noMainWindow();
enableMainWindow = enableMainWindow && !app.commandOptions()->runPythonAndExit();
bool showSplashScreen = !app.commandOptions()->noSplash() && enableMainWindow;
QScopedPointer<QSplashScreen> splashScreen;
if (showSplashScreen)
{
QPixmap pixmap(":/SplashScreen.png");
splashScreen.reset(new QSplashScreen(pixmap));
splashMessage(splashScreen, "Initializing...");
splashScreen->show();
}
qSlicerModuleManager * moduleManager = qSlicerApplication::application()->moduleManager();
qSlicerModuleFactoryManager * moduleFactoryManager = moduleManager->factoryManager();
QStringList additionalModulePaths;
foreach(const QString& extensionOrModulePath, app.commandOptions()->additonalModulePaths())
{
QStringList modulePaths = moduleFactoryManager->modulePaths(extensionOrModulePath);
if (!modulePaths.empty())
{
additionalModulePaths << modulePaths;
}
else
{
additionalModulePaths << extensionOrModulePath;
}
}
moduleFactoryManager->addSearchPaths(additionalModulePaths);
qSlicerApplicationHelper::setupModuleFactoryManager(moduleFactoryManager);
// Set list of modules to ignore
foreach(const QString& moduleToIgnore, app.commandOptions()->modulesToIgnore())
{
moduleFactoryManager->addModuleToIgnore(moduleToIgnore);
}
// Register and instantiate modules
splashMessage(splashScreen, "Registering modules...");
moduleFactoryManager->registerModules();
if (app.commandOptions()->verbose())
{
qDebug() << "Number of registered modules:"
<< moduleFactoryManager->registeredModuleNames().count();
}
splashMessage(splashScreen, "Instantiating modules...");
moduleFactoryManager->instantiateModules();
if (app.commandOptions()->verbose())
{
qDebug() << "Number of instantiated modules:"
<< moduleFactoryManager->instantiatedModuleNames().count();
}
// Create main window
splashMessage(splashScreen, "Initializing user interface...");
QScopedPointer<qSlicerAppMainWindow> window;
if (enableMainWindow)
{
window.reset(new qSlicerAppMainWindow);
window->setWindowTitle(window->windowTitle()+ " " + Slicer_VERSION_FULL);
}
else if (app.commandOptions()->showPythonInteractor()
&& !app.commandOptions()->runPythonAndExit())
{
// there is no main window but we need to show Python interactor
#ifdef Slicer_USE_PYTHONQT
ctkPythonConsole* pythonConsole = app.pythonConsole();
pythonConsole->setWindowTitle("Slicer Python Interactor");
pythonConsole->resize(600, 280);
pythonConsole->show();
pythonConsole->activateWindow();
pythonConsole->raise();
#endif
}
// Load all available modules
foreach(const QString& name, moduleFactoryManager->instantiatedModuleNames())
{
Q_ASSERT(!name.isNull());
splashMessage(splashScreen, "Loading module \"" + name + "\"...");
moduleFactoryManager->loadModule(name);
}
if (app.commandOptions()->verbose())
{
qDebug() << "Number of loaded modules:" << moduleManager->modulesNames().count();
}
splashMessage(splashScreen, QString());
if (window)
{
window->setHomeModuleCurrent();
window->show();
}
if (splashScreen && window)
{
splashScreen->finish(window.data());
}
// Process command line argument after the event loop is started
QTimer::singleShot(0, &app, SLOT(handleCommandLineArguments()));
// qSlicerApplicationHelper::showMRMLEventLoggerWidget();
// Look at QApplication::exec() documentation, it is recommended to connect
// clean up code to the aboutToQuit() signal
return app.exec();
}
} // end of anonymous namespace
#if defined (_WIN32) && !defined (Slicer_BUILD_WIN32_CONSOLE)
int __stdcall WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nShowCmd)
{
Q_UNUSED(hInstance);
Q_UNUSED(hPrevInstance);
Q_UNUSED(nShowCmd);
// CommandLineToArgvW has no narrow-character version, so we get the arguments in wide strings
// and then convert to regular string.
int argc;
LPWSTR* argvStringW = CommandLineToArgvW(GetCommandLineW(), &argc);
std::vector< const char* > argv(argc); // usual const char** array used in main() functions
std::vector< std::string > argvString(argc); // this stores the strings that the argv pointers point to
for(int i=0; i<argc; i++)
{
argvString[i] = vtksys::Encoding::ToNarrow(argvStringW[i]);
argv[i] = argvString[i].c_str();
}
LocalFree(argvStringW);
return SlicerAppMain(argc, const_cast< char** >(&argv[0]));
}
#else
int main(int argc, char *argv[])
{
return SlicerAppMain(argc, argv);
}
#endif
| 30.953571 | 105 | 0.692166 | [
"vector",
"3d"
] |
080f09405b37fd3103719ba210b5deff766ea955 | 6,892 | cpp | C++ | src/trunk/apps/tools/scxmlmerge/scxmlmerge.cpp | damb/seiscomp3 | 560a8f7ae43737ae7826fb1ffca76a9f601cf9dc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 94 | 2015-02-04T13:57:34.000Z | 2021-11-01T15:10:06.000Z | src/trunk/apps/tools/scxmlmerge/scxmlmerge.cpp | damb/seiscomp3 | 560a8f7ae43737ae7826fb1ffca76a9f601cf9dc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 233 | 2015-01-28T15:16:46.000Z | 2021-08-23T11:31:37.000Z | src/trunk/apps/tools/scxmlmerge/scxmlmerge.cpp | damb/seiscomp3 | 560a8f7ae43737ae7826fb1ffca76a9f601cf9dc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 95 | 2015-02-13T15:53:30.000Z | 2021-11-02T14:54:54.000Z | /***************************************************************************
* Copyright (C) by gempa GmbH *
* EMail: jabe@gempa.de *
* *
* You can redistribute and/or modify this program under the *
* terms of the SeisComP Public 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 *
* SeisComP Public License for more details. *
***************************************************************************/
#include <seiscomp3/client/application.h>
#include <seiscomp3/datamodel/config.h>
#include <seiscomp3/datamodel/dataavailability.h>
#include <seiscomp3/datamodel/diff.h>
#include <seiscomp3/datamodel/eventparameters.h>
#include <seiscomp3/datamodel/inventory.h>
#include <seiscomp3/datamodel/object.h>
#include <seiscomp3/datamodel/qualitycontrol.h>
#include <seiscomp3/datamodel/routing.h>
#include <seiscomp3/io/archive/xmlarchive.h>
#include <iostream>
class XMLMerge : public Seiscomp::Client::Application {
public:
XMLMerge(int argc, char **argv) : Seiscomp::Client::Application(argc, argv) {
setMessagingEnabled(false);
setDatabaseEnabled(false, false);
setDaemonEnabled(false);
}
bool init() {
if ( !Seiscomp::Client::Application::init() )
return false;
_files = commandline().unrecognizedOptions();
if ( _files.empty() ) {
std::cerr << "No input files given" << std::endl;
printUsage();
return false;
}
return true;
}
void printUsage() const {
std::cout << std::endl << "Description:" << std::endl;
std::cout << " Merge the content of multiple XML files. "
"Different root elements like EventParameters and "
"Inventory may be combined."
<< std::endl
<< std::endl << "Synopsis:" << std::endl
<< " scxmlmerge [options] inputFiles" << std::endl;
Seiscomp::Client::Application::printUsage();
std::cout << "Examples:" << std::endl;
std::cout << " scxmlmerge file1.xml file2.xml > file.xml"
<< std::endl << std::endl
<< " Merges all SeisComP3 elements the from 2 XML files into a single XML file "
<< std::endl << std::endl;
std::cout << " scxmlmerge -E -C file1.xml file2.xml > file.xml"
<< std::endl << std::endl
<< " Merges the EventParameters and Config elements from 2 "
"XML files into a single XML file "
<< std::endl;
}
void createCommandLineDescription() {
commandline().addGroup("Dump");
commandline().addOption("Dump", "event,E", "Include EventParameters");
commandline().addOption("Dump", "inventory,I", "Include Inventory");
commandline().addOption("Dump", "config,C", "Include Config");
commandline().addOption("Dump", "routing,R", "Include Routing");
commandline().addOption("Dump", "quality,Q", "Include QualityControl");
commandline().addOption("Dump", "availability,Y", "Include DataAvailability");
}
bool run() {
Seiscomp::DataModel::PublicObject::SetRegistrationEnabled(false);
std::vector<Seiscomp::DataModel::ObjectPtr> storage;
// set up root objects to collect
bool collectEP = commandline().hasOption("event");
bool collectInv = commandline().hasOption("inventory");
bool collectCfg = commandline().hasOption("config");
bool collectRouting = commandline().hasOption("routing");
bool collectQC = commandline().hasOption("quality");
bool collectDA = commandline().hasOption("availability");
bool collectAll = !collectEP && !collectInv && !collectCfg &&
!collectRouting && !collectQC && !collectDA;
if ( collectAll || collectEP )
registerRootObject(Seiscomp::DataModel::EventParameters::ClassName());
if ( collectAll || collectInv )
registerRootObject(Seiscomp::DataModel::Inventory::ClassName());
if ( collectAll || collectCfg )
registerRootObject(Seiscomp::DataModel::Config::ClassName());
if ( collectAll || collectRouting )
registerRootObject(Seiscomp::DataModel::Routing::ClassName());
if ( collectAll || collectQC )
registerRootObject(Seiscomp::DataModel::QualityControl::ClassName());
if ( collectAll || collectDA )
registerRootObject(Seiscomp::DataModel::DataAvailability::ClassName());
std::map<std::string, Objects>::iterator it;
for ( size_t i = 0; i < _files.size(); ++i ) {
Seiscomp::IO::XMLArchive ar;
if ( !ar.open(_files[i].c_str()) ) {
std::cerr << "Failed to open file: " << _files[i] << std::endl;
return false;
}
std::cerr << "+ " << _files[i] << std::endl;
Seiscomp::DataModel::ObjectPtr obj;
bool first = true;
while ( true ) {
Seiscomp::Core::Generic::ObjectIterator
<Seiscomp::DataModel::ObjectPtr> objIt(obj, first);
first = false;
ar >> objIt;
if ( !obj ) break;
std::cerr << " " << obj->className();
it = _objectBins.find(obj->className());
if ( it == _objectBins.end() ) {
std::cerr << " (ignored)";
}
else {
storage.push_back(obj.get());
it->second.push_back(obj.get());
}
std::cerr << std::endl;
}
ar.close();
}
Seiscomp::DataModel::DiffMerge merger;
merger.setLoggingLevel(4);
Seiscomp::IO::XMLArchive ar;
ar.create("-");
ar.setFormattedOutput(true);
for ( it = _objectBins.begin(); it != _objectBins.end(); ++it ) {
const std::string &name = it->first;
Objects &objs = it->second;
if ( objs.size() == 1 ) {
std::cerr << "writing " << name << " object" << std::endl;
ar << objs.front();
}
else if ( objs.size() > 1 ) {
std::cerr << "merging " << objs.size()
<< " " << name << " objects" << std::endl;
Seiscomp::DataModel::ObjectPtr obj =
dynamic_cast<Seiscomp::DataModel::Object*>(
Seiscomp::Core::ClassFactory::Create(it->first));
merger.merge(obj.get(), objs);
merger.showLog();
ar << obj;
}
}
ar.close();
return true;
}
private:
void registerRootObject(const std::string &name) {
_objectBins[name] = std::vector<Seiscomp::DataModel::Object*>();
}
private:
typedef std::vector<Seiscomp::DataModel::Object*> Objects;
std::vector<std::string> _files;
std::map<std::string, Objects> _objectBins;
};
int main(int argc, char **argv) {
XMLMerge app(argc, argv);
return app();
}
| 35.163265 | 94 | 0.581834 | [
"object",
"vector"
] |
080f51e384ac2d627f76ff5223590c499932b1ca | 8,404 | cpp | C++ | eval/src/vespa/eval/instruction/sparse_112_dot_product.cpp | Anlon-Burke/vespa | 5ecd989b36cc61716bf68f032a3482bf01fab726 | [
"Apache-2.0"
] | null | null | null | eval/src/vespa/eval/instruction/sparse_112_dot_product.cpp | Anlon-Burke/vespa | 5ecd989b36cc61716bf68f032a3482bf01fab726 | [
"Apache-2.0"
] | null | null | null | eval/src/vespa/eval/instruction/sparse_112_dot_product.cpp | Anlon-Burke/vespa | 5ecd989b36cc61716bf68f032a3482bf01fab726 | [
"Apache-2.0"
] | null | null | null | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "sparse_112_dot_product.h"
#include <vespa/eval/eval/fast_value.hpp>
#include <vespa/vespalib/util/typify.h>
#include <vespa/vespalib/util/require.h>
#include <vespa/eval/eval/visit_stuff.h>
#include <algorithm>
namespace vespalib::eval {
using namespace tensor_function;
using namespace operation;
using namespace instruction;
namespace {
template <typename T, size_t N>
ConstArrayRef<T> as_car(std::array<T, N> &array) {
return {array.data(), array.size()};
}
template <typename T, size_t N>
ConstArrayRef<const T *> as_ccar(std::array<T *, N> &array) {
return {array.data(), array.size()};
}
template <typename T>
ConstArrayRef<T> as_car(T &value) {
return {&value, 1};
}
constexpr std::array<size_t, 2> both_dims = { 0, 1 };
template <typename CT>
double my_sparse_112_dot_product_fallback(const Value::Index &a_idx, const Value::Index &b_idx, const Value::Index &c_idx,
const CT *a_cells, const CT *b_cells, const CT *c_cells) __attribute__((noinline));
template <typename CT>
double my_sparse_112_dot_product_fallback(const Value::Index &a_idx, const Value::Index &b_idx, const Value::Index &c_idx,
const CT *a_cells, const CT *b_cells, const CT *c_cells)
{
double result = 0.0;
size_t a_space = 0;
size_t b_space = 0;
size_t c_space = 0;
std::array<string_id, 2> c_addr;
std::array<string_id*, 2> c_addr_ref = {&c_addr[0], &c_addr[1]};
auto outer = a_idx.create_view({});
auto inner = b_idx.create_view({});
auto model = c_idx.create_view({&both_dims[0], 2});
outer->lookup({});
while (outer->next_result(as_car(c_addr_ref[0]), a_space)) {
inner->lookup({});
while (inner->next_result(as_car(c_addr_ref[1]), b_space)) {
model->lookup(as_ccar(c_addr_ref));
if (model->next_result({}, c_space)) {
result += (a_cells[a_space] * b_cells[b_space] * c_cells[c_space]);
}
}
}
return result;
}
template <typename CT>
double my_fast_sparse_112_dot_product(const FastAddrMap *a_map, const FastAddrMap *b_map, const FastAddrMap *c_map,
const CT *a_cells, const CT *b_cells, const CT *c_cells)
{
double result = 0.0;
std::array<string_id, 2> c_addr;
const auto &a_labels = a_map->labels();
for (size_t a_space = 0; a_space < a_labels.size(); ++a_space) {
if (a_cells[a_space] != 0.0) { // handle pseudo-sparse input
c_addr[0] = a_labels[a_space];
const auto &b_labels = b_map->labels();
for (size_t b_space = 0; b_space < b_labels.size(); ++b_space) {
if (b_cells[b_space] != 0.0) { // handle pseudo-sparse input
c_addr[1] = b_labels[b_space];
auto c_space = c_map->lookup(as_car(c_addr));
if (c_space != FastAddrMap::npos()) {
result += (a_cells[a_space] * b_cells[b_space] * c_cells[c_space]);
}
}
}
}
}
return result;
}
template <typename CT>
void my_sparse_112_dot_product_op(InterpretedFunction::State &state, uint64_t) {
const auto &a_idx = state.peek(2).index();
const auto &b_idx = state.peek(1).index();
const auto &c_idx = state.peek(0).index();
const CT *a_cells = state.peek(2).cells().unsafe_typify<CT>().cbegin();
const CT *b_cells = state.peek(1).cells().unsafe_typify<CT>().cbegin();
const CT *c_cells = state.peek(0).cells().unsafe_typify<CT>().cbegin();
double result = __builtin_expect(are_fast(a_idx, b_idx, c_idx), true)
? my_fast_sparse_112_dot_product<CT>(&as_fast(a_idx).map, &as_fast(b_idx).map, &as_fast(c_idx).map,
a_cells, b_cells, c_cells)
: my_sparse_112_dot_product_fallback<CT>(a_idx, b_idx, c_idx, a_cells, b_cells, c_cells);
state.pop_pop_pop_push(state.stash.create<DoubleValue>(result));
}
struct MyGetFun {
template <typename CT>
static auto invoke() { return my_sparse_112_dot_product_op<CT>; }
};
using MyTypify = TypifyValue<TypifyCellType>;
// Try to collect input nodes and organize them into a dot product
// between (n sparse non-overlapping single-dimension tensors) and (a
// sparse n-dimensional tensor) all having the same cell type.
struct InputState {
std::vector<const TensorFunction *> single;
const TensorFunction *multi = nullptr;
bool collision = false;
void collect(const TensorFunction &node) {
const auto &type = node.result_type();
if (type.is_sparse()) {
if (type.dimensions().size() == 1) {
single.push_back(&node);
} else {
if (multi) {
collision = true;
} else {
multi = &node;
}
}
}
}
void finalize() {
std::sort(single.begin(), single.end(), [](const auto *a, const auto *b)
{ return (a->result_type().dimensions()[0].name < b->result_type().dimensions()[0].name); });
}
bool verify(size_t n) const {
if (collision || (single.size() != n) || (multi == nullptr) || (multi->result_type().dimensions().size() != n)) {
return false;
}
const auto &multi_type = multi->result_type();
for (size_t i = 0; i < n; ++i) {
const auto &single_type = single[i]->result_type();
if ((single_type.cell_type() != multi_type.cell_type()) ||
(single_type.dimensions()[0].name != multi_type.dimensions()[i].name))
{
return false;
}
}
return true;
}
};
// Try to find inputs that form a 112 dot product.
struct FindInputs {
const TensorFunction *a = nullptr;
const TensorFunction *b = nullptr;
const TensorFunction *c = nullptr;
bool try_match(const TensorFunction &one, const TensorFunction &two) {
auto join = as<Join>(two);
if (join && (join->function() == Mul::f)) {
InputState state;
state.collect(one);
state.collect(join->lhs());
state.collect(join->rhs());
state.finalize();
if (state.verify(2)) {
a = state.single[0];
b = state.single[1];
c = state.multi;
return true;
}
}
return false;
}
};
} // namespace <unnamed>
Sparse112DotProduct::Sparse112DotProduct(const TensorFunction &a_in,
const TensorFunction &b_in,
const TensorFunction &c_in)
: tensor_function::Node(DoubleValue::shared_type()),
_a(a_in),
_b(b_in),
_c(c_in)
{
}
InterpretedFunction::Instruction
Sparse112DotProduct::compile_self(const ValueBuilderFactory &, Stash &) const
{
REQUIRE_EQ(_a.get().result_type().cell_type(), _b.get().result_type().cell_type());
REQUIRE_EQ(_a.get().result_type().cell_type(), _c.get().result_type().cell_type());
auto op = typify_invoke<1,MyTypify,MyGetFun>(_a.get().result_type().cell_type());
return InterpretedFunction::Instruction(op);
}
void
Sparse112DotProduct::push_children(std::vector<Child::CREF> &children) const
{
children.emplace_back(_a);
children.emplace_back(_b);
children.emplace_back(_c);
}
void
Sparse112DotProduct::visit_children(vespalib::ObjectVisitor &visitor) const
{
::visit(visitor, "a", _a.get());
::visit(visitor, "b", _b.get());
::visit(visitor, "c", _c.get());
}
const TensorFunction &
Sparse112DotProduct::optimize(const TensorFunction &expr, Stash &stash)
{
auto reduce = as<Reduce>(expr);
if (reduce && (reduce->aggr() == Aggr::SUM) && expr.result_type().is_double()) {
auto join = as<Join>(reduce->child());
if (join && (join->function() == Mul::f)) {
FindInputs inputs;
if (inputs.try_match(join->lhs(), join->rhs()) ||
inputs.try_match(join->rhs(), join->lhs()))
{
return stash.create<Sparse112DotProduct>(*inputs.a, *inputs.b, *inputs.c);
}
}
}
return expr;
}
} // namespace
| 35.459916 | 125 | 0.59674 | [
"vector",
"model"
] |
080feed9e38b454746e262dea9a7ee342e7257bb | 2,268 | cpp | C++ | CODEFORCES/306/c.cpp | henviso/contests | aa8a5ce9ed4524e6c3130ee73af7640e5a86954c | [
"Apache-2.0"
] | null | null | null | CODEFORCES/306/c.cpp | henviso/contests | aa8a5ce9ed4524e6c3130ee73af7640e5a86954c | [
"Apache-2.0"
] | null | null | null | CODEFORCES/306/c.cpp | henviso/contests | aa8a5ce9ed4524e6c3130ee73af7640e5a86954c | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <stack>
#include <algorithm>
#include <cctype>
#include <vector>
#include <queue>
#include <tr1/unordered_map>
#include <cmath>
#include <map>
#include <bitset>
#include <set>
#include <iomanip>
#include <cstring>
#include <unistd.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector< ii > vii;
///////////////////////////////UTIL/////////////////////////////////
#define ALL(x) (x).begin(),x.end()
#define CLEAR0(v) memset(v, 0, sizeof(v))
#define CLEAR(v, x) memset(v, x, sizeof(v))
#define COPY(a, b) memcpy(a, b, sizeof(a))
#define CMP(a, b) memcmp(a, b, sizeof(a))
#define REP(i,n) for(int i = 0; i<n; i++)
#define REPP(i,a,n) for(int i = a; i<n; i++)
#define REPD(i,n) for(int i = n-1; i>-1; i--)
#define REPDP(i,a,n) for(int i = n-1; i>=a; i--)
#define pb push_back
#define pf push_front
#define sz size()
#define mp make_pair
/////////////////////////////NUMERICAL//////////////////////////////
#define INF 0x3f3f3f3f
#define EPS 1e-9
/////////////////////////////BITWISE////////////////////////////////
#define CHECK(S, j) (S & (1 << j))
#define CHECKFIRST(S) (S & (-S))
#define SET(S, j) S |= (1 << j)
#define SETALL(S, j) S = (1 << j)-1
#define UNSET(S, j) S &= ~(1 << j)
#define TOOGLE(S, j) S ^= (1 << j)
///////////////////////////////64 BITS//////////////////////////////
#define LCHECK(S, j) (S & (1ULL << j))
#define LSET(S, j) S |= (1ULL << j)
#define LSETALL(S, j) S = (1ULL << j)-1ULL
#define LUNSET(S, j) S &= ~(1ULL << j)
#define LTOOGLE(S, j) S ^= (1ULL << j)
//__builtin_popcount(m)
//scanf(" %d ", &t);
deque<int> a, b;
ll fact(ll x){
if(x <= 1LL) return 1LL;
else return fact(x-1)*x;
}
int main(){
ll n, x, y, z;
cin >> n >> x;
REP(i, x){ cin >> z; a.push_back(z); }
cin >> y;
REP(i, y){ cin >> z; b.push_back(z); }
ll ans = 0, lim = fact(n)*(n+1), lst = -1;
while(!a.empty() && !b.empty() && ans <= lim){
ans++;
int A = a.front(), B = b.front(); a.pop_front(); b.pop_front();
if(A > B){ lst = 1; a.push_back(B); a.push_back(A); }
else{ lst = 2; b.push_back(A); b.push_back(B); }
}
if(ans > lim) cout << "-1\n";
else cout << ans << " " << lst << endl;
}
| 28.708861 | 68 | 0.527778 | [
"vector"
] |
08107f935f09daebaa7366bda02f32ea6aece0e7 | 2,585 | hpp | C++ | include/eve/detail/function/simd/common/swizzle_helpers.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | include/eve/detail/function/simd/common/swizzle_helpers.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | include/eve/detail/function/simd/common/swizzle_helpers.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | //==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#pragma once
#include <eve/detail/meta.hpp>
#include <eve/detail/abi.hpp>
#include <eve/detail/function/bit_cast.hpp>
#include <eve/pattern.hpp>
namespace eve::detail
{
//----------------------------------------------------------------------------------------------
// Handle Zeroing
template<typename Pack, typename Pattern>
EVE_FORCEINLINE auto process_zeros( Pack const& v, Pattern p ) noexcept
{
constexpr auto sz = cardinal_v<Pack>;
using type = typename Pack::value_type;
if constexpr( p.has_zeros() )
{
// Turn pattern into 0/~0 then mask
auto const impl = [=](auto... i)
{
using i_t = as_integer_t<type,unsigned>;
constexpr i_t nz = ~i_t(0), zz = i_t(0);
return Pack(bit_cast((p(i,sz) == na_ ? zz : nz),as_<type>())...);
};
return v & apply<sz>(impl);
}
else
{
return v;
}
}
//----------------------------------------------------------------------------------------------
// Pattern to Index wide conversion
template<simd_value Wide, shuffle_pattern Pattern>
EVE_FORCEINLINE auto as_indexes(Pattern const&)
{
using i_t = as_integer_t<Wide>;
using c_t = cardinal_t<Wide>;
return []<std::size_t... I>(std::index_sequence<I...>)
{
Pattern q;
return i_t{q(I,c_t::value)...};
}(std::make_index_sequence<c_t::value>{});
}
//----------------------------------------------------------------------------------------------
// Index to bytes conversion
template<typename Pack, typename Shuffler, std::size_t... I>
EVE_FORCEINLINE constexpr auto as_bytes_impl(Shuffler p, std::index_sequence<I...> const &)
{
constexpr auto sz = Shuffler::size();
constexpr auto b = sizeof(typename Pack::value_type);
return values< (p(I/b,sz) == na_ ? 0xFF : p(I/b,sz)*b+I%b)... >{};
}
template<typename Pack, typename Shuffler, typename Bytes>
EVE_FORCEINLINE constexpr auto as_bytes(Shuffler p, as_<Bytes> const&) noexcept
{
constexpr auto bytes = as_bytes_impl<Pack>(p, std::make_index_sequence<Bytes::size()>{});
return apply( [](auto... v) { return Bytes{ std::uint8_t(v)... }; }, bytes);
}
}
| 34.013158 | 100 | 0.495164 | [
"vector"
] |
081a6f8f4f34606021caf0c0b982cf8f355c43b7 | 2,380 | cpp | C++ | graph-source-code/141-D/4306374.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/141-D/4306374.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/141-D/4306374.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll ;
const int MAXN = 2*(int)1e5 + 10 ;
int n,L;
vector<int> v ;
int st[MAXN],ed[MAXN];
ll cost[MAXN] ;
map<int,int> num ;
vector< pair<int,pair<int,int> > > e[MAXN] ;
bool visit[MAXN] ;
ll d[MAXN] ;
int pre[MAXN] , px[MAXN] ;
int main(){
scanf("%d%d",&n,&L);
v.push_back(0) ; v.push_back(L);
for (int i=0;i<n;i++){
int t,p;
scanf("%d%d%d%d",&st[i],&ed[i],&t,&p);
ed[i]+=st[i];
st[i]-=p;
cost[i] = t+p ;
v.push_back(st[i]);
v.push_back(ed[i]);
}
sort(v.begin() , v.end()) ;
int N = 0 ;
vector<int> list ;
for (int i = 0 ; i < v.size() ; i++)
if (i==0 || v[i]!=v[i-1]) num[v[i]] = N++ , list.push_back(v[i]);
for (int i = 0 ; i < N-1 ; i++)
{
e[i].push_back(make_pair(-1,make_pair(i+1,list[i+1]-list[i])));
e[i+1].push_back(make_pair(-1,make_pair(i,list[i+1]-list[i])));
}
for (int i=0;i<n;i++){
if (st[i]<0) continue ;
e[num[st[i]]].push_back(make_pair(i+1,make_pair(num[ed[i]],cost[i])));
}
priority_queue< pair<ll,int> > q ;
for (int i = 0 ; i < N ; i++) d[i] = 1000000000LL*1000000000LL ;
d[num[0]] = 0LL ; q.push(make_pair(0,num[0])) ;
px[num[0]] = -1 ;
while (!q.empty()){
int u = q.top().second ; q.pop() ;
if (visit[u]) continue ;
visit[u] = true ;
for (int i = 0 ; i < e[u].size() ; i++){
int v = e[u][i].second.first ;
if (visit[v]) continue ;
if (d[v] > d[u] + e[u][i].second.second){
d[v] = d[u] + e[u][i].second.second ;
px[v] = u ;
pre[v] = e[u][i].first ;
q.push(make_pair(-d[v],v));
}
}
}
cout << d[num[L]] << endl ;
int x = num[L] ;
vector<int> res ;
while (x!=-1){
if (px[x]==-1) break ;
if (pre[x]!=-1) res.push_back(pre[x]) ;
x=px[x] ;
}
reverse(res.begin(),res.end()) ;
printf("%d\n",res.size()) ;
for (int i = 0 ; i < res.size() ; i++)
printf("%d ",res[i]);
printf("\n");
return 0 ;
}
| 27.045455 | 79 | 0.447899 | [
"vector"
] |
081cd8fac83fb1e0e86e3b3ce6e451ffc6e124bd | 93,025 | cpp | C++ | HTML_Lectures/Virtualization_Lecture/vbox/src/VBox/Main/src-client/GuestSessionImplTasks.cpp | roughk/CSCI-49XX-OpenSource | 74268cbca8bcda3023b2350d046e2dca2853a3ef | [
"BSD-2-Clause",
"CC-BY-4.0"
] | null | null | null | HTML_Lectures/Virtualization_Lecture/vbox/src/VBox/Main/src-client/GuestSessionImplTasks.cpp | roughk/CSCI-49XX-OpenSource | 74268cbca8bcda3023b2350d046e2dca2853a3ef | [
"BSD-2-Clause",
"CC-BY-4.0"
] | null | null | null | HTML_Lectures/Virtualization_Lecture/vbox/src/VBox/Main/src-client/GuestSessionImplTasks.cpp | roughk/CSCI-49XX-OpenSource | 74268cbca8bcda3023b2350d046e2dca2853a3ef | [
"BSD-2-Clause",
"CC-BY-4.0"
] | null | null | null | /* $Id: GuestSessionImplTasks.cpp 73040 2018-07-10 16:08:51Z vboxsync $ */
/** @file
* VirtualBox Main - Guest session tasks.
*/
/*
* Copyright (C) 2012-2018 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_MAIN_GUESTSESSION
#include "LoggingNew.h"
#include "GuestImpl.h"
#ifndef VBOX_WITH_GUEST_CONTROL
# error "VBOX_WITH_GUEST_CONTROL must defined in this file"
#endif
#include "GuestSessionImpl.h"
#include "GuestSessionImplTasks.h"
#include "GuestCtrlImplPrivate.h"
#include "Global.h"
#include "AutoCaller.h"
#include "ConsoleImpl.h"
#include "ProgressImpl.h"
#include <memory> /* For auto_ptr. */
#include <iprt/env.h>
#include <iprt/file.h> /* For CopyTo/From. */
#include <iprt/dir.h>
#include <iprt/path.h>
#include <iprt/fsvfs.h>
/*********************************************************************************************************************************
* Defines *
*********************************************************************************************************************************/
/**
* (Guest Additions) ISO file flags.
* Needed for handling Guest Additions updates.
*/
#define ISOFILE_FLAG_NONE 0
/** Copy over the file from host to the
* guest. */
#define ISOFILE_FLAG_COPY_FROM_ISO RT_BIT(0)
/** Execute file on the guest after it has
* been successfully transfered. */
#define ISOFILE_FLAG_EXECUTE RT_BIT(7)
/** File is optional, does not have to be
* existent on the .ISO. */
#define ISOFILE_FLAG_OPTIONAL RT_BIT(8)
// session task classes
/////////////////////////////////////////////////////////////////////////////
GuestSessionTask::GuestSessionTask(GuestSession *pSession)
: ThreadTask("GenericGuestSessionTask")
{
mSession = pSession;
switch (mSession->i_getPathStyle())
{
case PathStyle_DOS:
mfPathStyle = RTPATH_STR_F_STYLE_DOS;
mPathStyle = "\\";
break;
default:
mfPathStyle = RTPATH_STR_F_STYLE_UNIX;
mPathStyle = "/";
break;
}
}
GuestSessionTask::~GuestSessionTask(void)
{
}
int GuestSessionTask::createAndSetProgressObject(ULONG cOperations /* = 1 */)
{
LogFlowThisFunc(("cOperations=%ld\n", cOperations));
/* Create the progress object. */
ComObjPtr<Progress> pProgress;
HRESULT hr = pProgress.createObject();
if (FAILED(hr))
return VERR_COM_UNEXPECTED;
hr = pProgress->init(static_cast<IGuestSession*>(mSession),
Bstr(mDesc).raw(),
TRUE /* aCancelable */, cOperations, Bstr(mDesc).raw());
if (FAILED(hr))
return VERR_COM_UNEXPECTED;
mProgress = pProgress;
LogFlowFuncLeave();
return VINF_SUCCESS;
}
int GuestSessionTask::RunAsync(const Utf8Str &strDesc, ComObjPtr<Progress> &pProgress)
{
LogFlowThisFunc(("strDesc=%s\n", strDesc.c_str()));
mDesc = strDesc;
mProgress = pProgress;
HRESULT hrc = createThreadWithType(RTTHREADTYPE_MAIN_HEAVY_WORKER);
LogFlowThisFunc(("Returning hrc=%Rhrc\n", hrc));
return Global::vboxStatusCodeToCOM(hrc);
}
int GuestSessionTask::getGuestProperty(const ComObjPtr<Guest> &pGuest,
const Utf8Str &strPath, Utf8Str &strValue)
{
ComObjPtr<Console> pConsole = pGuest->i_getConsole();
const ComPtr<IMachine> pMachine = pConsole->i_machine();
Assert(!pMachine.isNull());
Bstr strTemp, strFlags;
LONG64 i64Timestamp;
HRESULT hr = pMachine->GetGuestProperty(Bstr(strPath).raw(),
strTemp.asOutParam(),
&i64Timestamp, strFlags.asOutParam());
if (SUCCEEDED(hr))
{
strValue = strTemp;
return VINF_SUCCESS;
}
return VERR_NOT_FOUND;
}
int GuestSessionTask::setProgress(ULONG uPercent)
{
if (mProgress.isNull()) /* Progress is optional. */
return VINF_SUCCESS;
BOOL fCanceled;
if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
&& fCanceled)
return VERR_CANCELLED;
BOOL fCompleted;
if ( SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
&& fCompleted)
{
AssertMsgFailed(("Setting value of an already completed progress\n"));
return VINF_SUCCESS;
}
HRESULT hr = mProgress->SetCurrentOperationProgress(uPercent);
if (FAILED(hr))
return VERR_COM_UNEXPECTED;
return VINF_SUCCESS;
}
int GuestSessionTask::setProgressSuccess(void)
{
if (mProgress.isNull()) /* Progress is optional. */
return VINF_SUCCESS;
BOOL fCompleted;
if ( SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
&& !fCompleted)
{
HRESULT hr = mProgress->i_notifyComplete(S_OK);
if (FAILED(hr))
return VERR_COM_UNEXPECTED; /** @todo Find a better rc. */
}
return VINF_SUCCESS;
}
HRESULT GuestSessionTask::setProgressErrorMsg(HRESULT hr, const Utf8Str &strMsg)
{
LogFlowFunc(("hr=%Rhrc, strMsg=%s\n",
hr, strMsg.c_str()));
if (mProgress.isNull()) /* Progress is optional. */
return hr; /* Return original rc. */
BOOL fCanceled;
BOOL fCompleted;
if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
&& !fCanceled
&& SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
&& !fCompleted)
{
HRESULT hr2 = mProgress->i_notifyComplete(hr,
COM_IIDOF(IGuestSession),
GuestSession::getStaticComponentName(),
strMsg.c_str());
if (FAILED(hr2))
return hr2;
}
return hr; /* Return original rc. */
}
/**
* Creates a directory on the guest.
*
* @return VBox status code. VERR_ALREADY_EXISTS if directory on the guest already exists.
* @param strPath Absolute path to directory on the guest (guest style path) to create.
* @param enmDirectoryCreateFlags Directory creation flags.
* @param uMode Directory mode to use for creation.
* @param fFollowSymlinks Whether to follow symlinks on the guest or not.
*/
int GuestSessionTask::directoryCreate(const com::Utf8Str &strPath,
DirectoryCreateFlag_T enmDirectoryCreateFlags, uint32_t uMode, bool fFollowSymlinks)
{
LogFlowFunc(("strPath=%s, fFlags=0x%x, uMode=%RU32, fFollowSymlinks=%RTbool\n",
strPath.c_str(), enmDirectoryCreateFlags, uMode, fFollowSymlinks));
GuestFsObjData objData; int rcGuest;
int rc = mSession->i_directoryQueryInfo(strPath, fFollowSymlinks, objData, &rcGuest);
if (RT_SUCCESS(rc))
{
return VERR_ALREADY_EXISTS;
}
else
{
switch (rc)
{
case VERR_GSTCTL_GUEST_ERROR:
{
switch (rcGuest)
{
case VERR_FILE_NOT_FOUND:
case VERR_PATH_NOT_FOUND:
rc = mSession->i_directoryCreate(strPath.c_str(), uMode, enmDirectoryCreateFlags, &rcGuest);
break;
default:
break;
}
break;
}
default:
break;
}
}
if (RT_FAILURE(rc))
{
if (rc == VERR_GSTCTL_GUEST_ERROR)
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
}
else
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Error creating directory on the guest: %Rrc"), strPath.c_str(), rc));
}
LogFlowFuncLeaveRC(rc);
return rc;
}
/**
* Main function for copying a file from guest to the host.
*
* @return VBox status code.
* @param srcFile Guest file (source) to copy to the host. Must be in opened and ready state already.
* @param phDstFile Pointer to host file handle (destination) to copy to. Must be in opened and ready state already.
* @param fFileCopyFlags File copy flags.
* @param offCopy Offset (in bytes) where to start copying the source file.
* @param cbSize Size (in bytes) to copy from the source file.
*/
int GuestSessionTask::fileCopyFromGuestInner(ComObjPtr<GuestFile> &srcFile, PRTFILE phDstFile, FileCopyFlag_T fFileCopyFlags,
uint64_t offCopy, uint64_t cbSize)
{
RT_NOREF(fFileCopyFlags);
BOOL fCanceled = FALSE;
uint64_t cbWrittenTotal = 0;
uint64_t cbToRead = cbSize;
uint32_t uTimeoutMs = 30 * 1000; /* 30s timeout. */
int rc = VINF_SUCCESS;
if (offCopy)
{
uint64_t offActual;
rc = srcFile->i_seekAt(offCopy, GUEST_FILE_SEEKTYPE_BEGIN, uTimeoutMs, &offActual);
if (RT_FAILURE(rc))
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Seeking to offset %RU64 failed: %Rrc"), offCopy, rc));
return rc;
}
}
BYTE byBuf[_64K];
while (cbToRead)
{
uint32_t cbRead;
const uint32_t cbChunk = RT_MIN(cbToRead, sizeof(byBuf));
rc = srcFile->i_readData(cbChunk, uTimeoutMs, byBuf, sizeof(byBuf), &cbRead);
if (RT_FAILURE(rc))
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Reading %RU32 bytes @ %RU64 from guest failed: %Rrc"), cbChunk, cbWrittenTotal, rc));
break;
}
rc = RTFileWrite(*phDstFile, byBuf, cbRead, NULL /* No partial writes */);
if (RT_FAILURE(rc))
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Writing %RU32 bytes to file on host failed: %Rrc"), cbRead, rc));
break;
}
Assert(cbToRead >= cbRead);
cbToRead -= cbRead;
/* Update total bytes written to the guest. */
cbWrittenTotal += cbRead;
Assert(cbWrittenTotal <= cbSize);
/* Did the user cancel the operation above? */
if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
&& fCanceled)
break;
rc = setProgress((ULONG)(cbWrittenTotal / ((uint64_t)cbSize / 100.0)));
if (RT_FAILURE(rc))
break;
}
if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
&& fCanceled)
return VINF_SUCCESS;
if (RT_FAILURE(rc))
return rc;
/*
* Even if we succeeded until here make sure to check whether we really transfered
* everything.
*/
if ( cbSize > 0
&& cbWrittenTotal == 0)
{
/* If nothing was transfered but the file size was > 0 then "vbox_cat" wasn't able to write
* to the destination -> access denied. */
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Writing guest file to host failed: Access denied")));
rc = VERR_ACCESS_DENIED;
}
else if (cbWrittenTotal < cbSize)
{
/* If we did not copy all let the user know. */
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Copying guest file to host to failed (%RU64/%RU64 bytes transfered)"),
cbWrittenTotal, cbSize));
rc = VERR_INTERRUPTED;
}
LogFlowFuncLeaveRC(rc);
return rc;
}
/**
* Copies a file from the guest to the host.
*
* @return VBox status code. VINF_NO_CHANGE if file was skipped.
* @param strSource Full path of source file on the guest to copy.
* @param strDest Full destination path and file name (host style) to copy file to.
* @param fFileCopyFlags File copy flags.
*/
int GuestSessionTask::fileCopyFromGuest(const Utf8Str &strSource, const Utf8Str &strDest, FileCopyFlag_T fFileCopyFlags)
{
LogFlowThisFunc(("strSource=%s, strDest=%s, enmFileCopyFlags=0x%x\n", strSource.c_str(), strDest.c_str(), fFileCopyFlags));
GuestFileOpenInfo srcOpenInfo;
RT_ZERO(srcOpenInfo);
srcOpenInfo.mFileName = strSource;
srcOpenInfo.mOpenAction = FileOpenAction_OpenExisting;
srcOpenInfo.mAccessMode = FileAccessMode_ReadOnly;
srcOpenInfo.mSharingMode = FileSharingMode_All; /** @todo Use _Read when implemented. */
ComObjPtr<GuestFile> srcFile;
GuestFsObjData srcObjData;
int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
int rc = mSession->i_fsQueryInfo(strSource, TRUE /* fFollowSymlinks */, srcObjData, &rcGuest);
if (RT_FAILURE(rc))
{
switch (rc)
{
case VERR_GSTCTL_GUEST_ERROR:
setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestFile::i_guestErrorToString(rcGuest));
break;
default:
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Source file lookup for \"%s\" failed: %Rrc"),
strSource.c_str(), rc));
break;
}
}
else
{
switch (srcObjData.mType)
{
case FsObjType_File:
break;
case FsObjType_Symlink:
if (!(fFileCopyFlags & FileCopyFlag_FollowLinks))
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Source file \"%s\" is a symbolic link"),
strSource.c_str(), rc));
rc = VERR_IS_A_SYMLINK;
}
break;
default:
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Source element \"%s\" is not a file"), strSource.c_str()));
rc = VERR_NOT_A_FILE;
break;
}
}
if (RT_FAILURE(rc))
return rc;
rc = mSession->i_fileOpen(srcOpenInfo, srcFile, &rcGuest);
if (RT_FAILURE(rc))
{
switch (rc)
{
case VERR_GSTCTL_GUEST_ERROR:
setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestFile::i_guestErrorToString(rcGuest));
break;
default:
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Source file \"%s\" could not be opened: %Rrc"),
strSource.c_str(), rc));
break;
}
}
if (RT_FAILURE(rc))
return rc;
char *pszDstFile = NULL;
RTFSOBJINFO dstObjInfo;
RT_ZERO(dstObjInfo);
bool fSkip = false; /* Whether to skip handling the file. */
if (RT_SUCCESS(rc))
{
rc = RTPathQueryInfo(strDest.c_str(), &dstObjInfo, RTFSOBJATTRADD_NOTHING);
if (RT_SUCCESS(rc))
{
if (fFileCopyFlags & FileCopyFlag_NoReplace)
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination file \"%s\" already exists"), strDest.c_str()));
rc = VERR_ALREADY_EXISTS;
}
if (fFileCopyFlags & FileCopyFlag_Update)
{
RTTIMESPEC srcModificationTimeTS;
RTTimeSpecSetSeconds(&srcModificationTimeTS, srcObjData.mModificationTime);
if (RTTimeSpecCompare(&srcModificationTimeTS, &dstObjInfo.ModificationTime) <= 0)
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination file \"%s\" has same or newer modification date"),
strDest.c_str()));
fSkip = true;
}
}
}
else
{
if (rc != VERR_FILE_NOT_FOUND) /* Destination file does not exist (yet)? */
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination file lookup for \"%s\" failed: %Rrc"),
strDest.c_str(), rc));
}
}
if (fSkip)
{
int rc2 = srcFile->i_closeFile(&rcGuest);
AssertRC(rc2);
return VINF_SUCCESS;
}
if (RT_SUCCESS(rc))
{
if (RTFS_IS_FILE(dstObjInfo.Attr.fMode))
{
if (fFileCopyFlags & FileCopyFlag_NoReplace)
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination file \"%s\" already exists"),
strDest.c_str(), rc));
rc = VERR_ALREADY_EXISTS;
}
else
pszDstFile = RTStrDup(strDest.c_str());
}
else if (RTFS_IS_DIRECTORY(dstObjInfo.Attr.fMode))
{
/* Build the final file name with destination path (on the host). */
char szDstPath[RTPATH_MAX];
RTStrPrintf2(szDstPath, sizeof(szDstPath), "%s", strDest.c_str());
if ( !strDest.endsWith("\\")
&& !strDest.endsWith("/"))
RTPathAppend(szDstPath, sizeof(szDstPath), "/"); /* IPRT can handle / on all hosts. */
RTPathAppend(szDstPath, sizeof(szDstPath), RTPathFilenameEx(strSource.c_str(), mfPathStyle));
pszDstFile = RTStrDup(szDstPath);
}
else if (RTFS_IS_SYMLINK(dstObjInfo.Attr.fMode))
{
if (!(fFileCopyFlags & FileCopyFlag_FollowLinks))
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination file \"%s\" is a symbolic link"),
strDest.c_str(), rc));
rc = VERR_IS_A_SYMLINK;
}
else
pszDstFile = RTStrDup(strDest.c_str());
}
else
{
LogFlowThisFunc(("Object type %RU32 not implemented yet\n", dstObjInfo.Attr.fMode));
rc = VERR_NOT_IMPLEMENTED;
}
}
else if (rc == VERR_FILE_NOT_FOUND)
pszDstFile = RTStrDup(strDest.c_str());
if ( RT_SUCCESS(rc)
|| rc == VERR_FILE_NOT_FOUND)
{
if (!pszDstFile)
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("No memory to allocate destination file path")));
rc = VERR_NO_MEMORY;
}
else
{
RTFILE hDstFile;
rc = RTFileOpen(&hDstFile, pszDstFile,
RTFILE_O_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_DENY_WRITE); /** @todo Use the correct open modes! */
if (RT_SUCCESS(rc))
{
LogFlowThisFunc(("Copying '%s' to '%s' (%RI64 bytes) ...\n", strSource.c_str(), pszDstFile, srcObjData.mObjectSize));
rc = fileCopyFromGuestInner(srcFile, &hDstFile, fFileCopyFlags, 0 /* Offset, unused */, (uint64_t)srcObjData.mObjectSize);
int rc2 = RTFileClose(hDstFile);
AssertRC(rc2);
}
else
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Opening/creating destination file \"%s\" failed: %Rrc"),
pszDstFile, rc));
}
}
RTStrFree(pszDstFile);
int rc2 = srcFile->i_closeFile(&rcGuest);
AssertRC(rc2);
LogFlowFuncLeaveRC(rc);
return rc;
}
/**
* Main function for copying a file from host to the guest.
*
* @return VBox status code.
* @param hVfsFile The VFS file handle to read from.
* @param dstFile Guest file (destination) to copy to the guest. Must be in opened and ready state already.
* @param fFileCopyFlags File copy flags.
* @param offCopy Offset (in bytes) where to start copying the source file.
* @param cbSize Size (in bytes) to copy from the source file.
*/
int GuestSessionTask::fileCopyToGuestInner(RTVFSFILE hVfsFile, ComObjPtr<GuestFile> &dstFile, FileCopyFlag_T fFileCopyFlags,
uint64_t offCopy, uint64_t cbSize)
{
RT_NOREF(fFileCopyFlags);
BOOL fCanceled = FALSE;
uint64_t cbWrittenTotal = 0;
uint64_t cbToRead = cbSize;
uint32_t uTimeoutMs = 30 * 1000; /* 30s timeout. */
int rc = VINF_SUCCESS;
if (offCopy)
{
uint64_t offActual;
rc = RTVfsFileSeek(hVfsFile, offCopy, RTFILE_SEEK_END, &offActual);
if (RT_FAILURE(rc))
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Seeking to offset %RU64 failed: %Rrc"), offCopy, rc));
return rc;
}
}
BYTE byBuf[_64K];
while (cbToRead)
{
size_t cbRead;
const uint32_t cbChunk = RT_MIN(cbToRead, sizeof(byBuf));
rc = RTVfsFileRead(hVfsFile, byBuf, cbChunk, &cbRead);
if (RT_FAILURE(rc))
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Reading %RU32 bytes @ %RU64 from host failed: %Rrc"), cbChunk, cbWrittenTotal, rc));
break;
}
rc = dstFile->i_writeData(uTimeoutMs, byBuf, (uint32_t)cbRead, NULL /* No partial writes */);
if (RT_FAILURE(rc))
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Writing %zu bytes to file on guest failed: %Rrc"), cbRead, rc));
break;
}
Assert(cbToRead >= cbRead);
cbToRead -= cbRead;
/* Update total bytes written to the guest. */
cbWrittenTotal += cbRead;
Assert(cbWrittenTotal <= cbSize);
/* Did the user cancel the operation above? */
if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
&& fCanceled)
break;
rc = setProgress((ULONG)(cbWrittenTotal / ((uint64_t)cbSize / 100.0)));
if (RT_FAILURE(rc))
break;
}
if (RT_FAILURE(rc))
return rc;
/*
* Even if we succeeded until here make sure to check whether we really transfered
* everything.
*/
if ( cbSize > 0
&& cbWrittenTotal == 0)
{
/* If nothing was transfered but the file size was > 0 then "vbox_cat" wasn't able to write
* to the destination -> access denied. */
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Writing to destination file failed: Access denied")));
rc = VERR_ACCESS_DENIED;
}
else if (cbWrittenTotal < cbSize)
{
/* If we did not copy all let the user know. */
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Copying to destination failed (%RU64/%RU64 bytes transfered)"),
cbWrittenTotal, cbSize));
rc = VERR_INTERRUPTED;
}
LogFlowFuncLeaveRC(rc);
return rc;
}
/**
* Copies a file from the guest to the host.
*
* @return VBox status code. VINF_NO_CHANGE if file was skipped.
* @param strSource Full path of source file on the host to copy.
* @param strDest Full destination path and file name (guest style) to copy file to.
* @param fFileCopyFlags File copy flags.
*/
int GuestSessionTask::fileCopyToGuest(const Utf8Str &strSource, const Utf8Str &strDest, FileCopyFlag_T fFileCopyFlags)
{
LogFlowThisFunc(("strSource=%s, strDest=%s, fFileCopyFlags=0x%x\n", strSource.c_str(), strDest.c_str(), fFileCopyFlags));
Utf8Str strDestFinal = strDest;
GuestFsObjData dstObjData;
int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
int rc = mSession->i_fsQueryInfo(strDest, TRUE /* fFollowSymlinks */, dstObjData, &rcGuest);
if (RT_FAILURE(rc))
{
switch (rc)
{
case VERR_GSTCTL_GUEST_ERROR:
if (rcGuest == VERR_FILE_NOT_FOUND) /* File might not exist on the guest yet. */
{
rc = VINF_SUCCESS;
}
else
setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestFile::i_guestErrorToString(rcGuest));
break;
default:
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination file lookup for \"%s\" failed: %Rrc"),
strDest.c_str(), rc));
break;
}
}
else
{
switch (dstObjData.mType)
{
case FsObjType_Directory:
{
/* Build the final file name with destination path (on the host). */
char szDstPath[RTPATH_MAX];
RTStrPrintf2(szDstPath, sizeof(szDstPath), "%s", strDest.c_str());
if ( !strDest.endsWith("\\")
&& !strDest.endsWith("/"))
RTStrCat(szDstPath, sizeof(szDstPath), "/");
RTStrCat(szDstPath, sizeof(szDstPath), RTPathFilename(strSource.c_str()));
strDestFinal = szDstPath;
break;
}
case FsObjType_File:
if (fFileCopyFlags & FileCopyFlag_NoReplace)
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination file \"%s\" already exists"),
strDest.c_str(), rc));
rc = VERR_ALREADY_EXISTS;
}
break;
case FsObjType_Symlink:
if (!(fFileCopyFlags & FileCopyFlag_FollowLinks))
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination file \"%s\" is a symbolic link"),
strDest.c_str(), rc));
rc = VERR_IS_A_SYMLINK;
}
break;
default:
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination element \"%s\" not supported"), strDest.c_str()));
rc = VERR_NOT_SUPPORTED;
break;
}
}
if (RT_FAILURE(rc))
return rc;
GuestFileOpenInfo dstOpenInfo;
RT_ZERO(dstOpenInfo);
dstOpenInfo.mFileName = strDestFinal;
if (fFileCopyFlags & FileCopyFlag_NoReplace)
dstOpenInfo.mOpenAction = FileOpenAction_CreateNew;
else
dstOpenInfo.mOpenAction = FileOpenAction_CreateOrReplace;
dstOpenInfo.mAccessMode = FileAccessMode_WriteOnly;
dstOpenInfo.mSharingMode = FileSharingMode_All; /** @todo Use _Read when implemented. */
ComObjPtr<GuestFile> dstFile;
rc = mSession->i_fileOpen(dstOpenInfo, dstFile, &rcGuest);
if (RT_FAILURE(rc))
{
switch (rc)
{
case VERR_GSTCTL_GUEST_ERROR:
setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestFile::i_guestErrorToString(rcGuest));
break;
default:
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination file \"%s\" could not be opened: %Rrc"),
strDestFinal.c_str(), rc));
break;
}
}
if (RT_FAILURE(rc))
return rc;
char szSrcReal[RTPATH_MAX];
RTFSOBJINFO srcObjInfo;
RT_ZERO(srcObjInfo);
bool fSkip = false; /* Whether to skip handling the file. */
if (RT_SUCCESS(rc))
{
rc = RTPathReal(strSource.c_str(), szSrcReal, sizeof(szSrcReal));
if (RT_FAILURE(rc))
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Source path lookup for \"%s\" failed: %Rrc"),
strSource.c_str(), rc));
}
else
{
rc = RTPathQueryInfo(szSrcReal, &srcObjInfo, RTFSOBJATTRADD_NOTHING);
if (RT_SUCCESS(rc))
{
if (fFileCopyFlags & FileCopyFlag_Update)
{
RTTIMESPEC dstModificationTimeTS;
RTTimeSpecSetSeconds(&dstModificationTimeTS, dstObjData.mModificationTime);
if (RTTimeSpecCompare(&dstModificationTimeTS, &srcObjInfo.ModificationTime) <= 0)
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination file \"%s\" has same or newer modification date"),
strDestFinal.c_str()));
fSkip = true;
}
}
}
else
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Source file lookup for \"%s\" failed: %Rrc"),
szSrcReal, rc));
}
}
}
if (fSkip)
{
int rc2 = dstFile->i_closeFile(&rcGuest);
AssertRC(rc2);
return VINF_SUCCESS;
}
if (RT_SUCCESS(rc))
{
RTVFSFILE hSrcFile;
rc = RTVfsFileOpenNormal(szSrcReal, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE, &hSrcFile); /** @todo Use the correct open modes! */
if (RT_SUCCESS(rc))
{
LogFlowThisFunc(("Copying '%s' to '%s' (%RI64 bytes) ...\n",
szSrcReal, strDestFinal.c_str(), srcObjInfo.cbObject));
rc = fileCopyToGuestInner(hSrcFile, dstFile, fFileCopyFlags, 0 /* Offset, unused */, srcObjInfo.cbObject);
int rc2 = RTVfsFileRelease(hSrcFile);
AssertRC(rc2);
}
else
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Opening source file \"%s\" failed: %Rrc"),
szSrcReal, rc));
}
int rc2 = dstFile->i_closeFile(&rcGuest);
AssertRC(rc2);
LogFlowFuncLeaveRC(rc);
return rc;
}
/**
* Adds a guest file system entry to a given list.
*
* @return VBox status code.
* @param strFile Path to file system entry to add.
* @param fsObjData Guest file system information of entry to add.
*/
int FsList::AddEntryFromGuest(const Utf8Str &strFile, const GuestFsObjData &fsObjData)
{
LogFlowFunc(("Adding '%s'\n", strFile.c_str()));
FsEntry *pEntry = NULL;
try
{
pEntry = new FsEntry();
pEntry->fMode = fsObjData.GetFileMode();
pEntry->strPath = strFile;
mVecEntries.push_back(pEntry);
}
catch (...)
{
if (pEntry)
delete pEntry;
return VERR_NO_MEMORY;
}
return VINF_SUCCESS;
}
/**
* Adds a host file system entry to a given list.
*
* @return VBox status code.
* @param strFile Path to file system entry to add.
* @param pcObjInfo File system information of entry to add.
*/
int FsList::AddEntryFromHost(const Utf8Str &strFile, PCRTFSOBJINFO pcObjInfo)
{
LogFlowFunc(("Adding '%s'\n", strFile.c_str()));
FsEntry *pEntry = NULL;
try
{
pEntry = new FsEntry();
pEntry->fMode = pcObjInfo->Attr.fMode & RTFS_TYPE_MASK;
pEntry->strPath = strFile;
mVecEntries.push_back(pEntry);
}
catch (...)
{
if (pEntry)
delete pEntry;
return VERR_NO_MEMORY;
}
return VINF_SUCCESS;
}
FsList::FsList(const GuestSessionTask &Task)
: mTask(Task)
{
}
FsList::~FsList()
{
Destroy();
}
/**
* Initializes a file list.
*
* @return VBox status code.
* @param strSrcRootAbs Source root path (absolute) for this file list.
* @param strDstRootAbs Destination root path (absolute) for this file list.
* @param SourceSpec Source specification to use.
*/
int FsList::Init(const Utf8Str &strSrcRootAbs, const Utf8Str &strDstRootAbs,
const GuestSessionFsSourceSpec &SourceSpec)
{
mSrcRootAbs = strSrcRootAbs;
mDstRootAbs = strDstRootAbs;
mSourceSpec = SourceSpec;
/* If the source is a directory, make sure the path is properly terminated already. */
if (mSourceSpec.enmType == FsObjType_Directory)
{
if ( !mSrcRootAbs.endsWith("/")
&& !mSrcRootAbs.endsWith("\\"))
mSrcRootAbs += "/";
if ( !mDstRootAbs.endsWith("/")
&& !mDstRootAbs.endsWith("\\"))
mDstRootAbs += "/";
}
return VINF_SUCCESS;
}
/**
* Destroys a file list.
*/
void FsList::Destroy(void)
{
LogFlowFuncEnter();
FsEntries::iterator itEntry = mVecEntries.begin();
while (itEntry != mVecEntries.end())
{
FsEntry *pEntry = *itEntry;
delete pEntry;
mVecEntries.erase(itEntry);
itEntry = mVecEntries.begin();
}
Assert(mVecEntries.empty());
LogFlowFuncLeave();
}
/**
* Builds a guest file list from a given path (and optional filter).
*
* @return VBox status code.
* @param strPath Directory on the guest to build list from.
* @param strSubDir Current sub directory path; needed for recursion.
* Set to an empty path.
*/
int FsList::AddDirFromGuest(const Utf8Str &strPath, const Utf8Str &strSubDir /* = "" */)
{
Utf8Str strPathAbs = strPath;
if ( !strPathAbs.endsWith("/")
&& !strPathAbs.endsWith("\\"))
strPathAbs += "/";
Utf8Str strPathSub = strSubDir;
if ( strPathSub.isNotEmpty()
&& !strPathSub.endsWith("/")
&& !strPathSub.endsWith("\\"))
strPathSub += "/";
strPathAbs += strPathSub;
LogFlowFunc(("Entering '%s' (sub '%s')\n", strPathAbs.c_str(), strPathSub.c_str()));
GuestDirectoryOpenInfo dirOpenInfo;
dirOpenInfo.mFilter = "";
dirOpenInfo.mPath = strPathAbs;
dirOpenInfo.mFlags = 0; /** @todo Handle flags? */
const ComObjPtr<GuestSession> &pSession = mTask.GetSession();
ComObjPtr <GuestDirectory> pDir; int rcGuest;
int rc = pSession->i_directoryOpen(dirOpenInfo, pDir, &rcGuest);
if (RT_FAILURE(rc))
{
switch (rc)
{
case VERR_INVALID_PARAMETER:
break;
case VERR_GSTCTL_GUEST_ERROR:
break;
default:
break;
}
return rc;
}
if (strPathSub.isNotEmpty())
{
GuestFsObjData fsObjData;
fsObjData.mType = FsObjType_Directory;
rc = AddEntryFromGuest(strPathSub, fsObjData);
}
if (RT_SUCCESS(rc))
{
ComObjPtr<GuestFsObjInfo> fsObjInfo;
while (RT_SUCCESS(rc = pDir->i_readInternal(fsObjInfo, &rcGuest)))
{
FsObjType_T enmObjType = FsObjType_Unknown; /* Shut up MSC. */
HRESULT hr2 = fsObjInfo->COMGETTER(Type)(&enmObjType);
AssertComRC(hr2);
com::Bstr bstrName;
hr2 = fsObjInfo->COMGETTER(Name)(bstrName.asOutParam());
AssertComRC(hr2);
Utf8Str strEntry = strPathSub + Utf8Str(bstrName);
LogFlowFunc(("Entry '%s'\n", strEntry.c_str()));
switch (enmObjType)
{
case FsObjType_Directory:
{
if ( bstrName.equals(".")
|| bstrName.equals(".."))
{
break;
}
if (!(mSourceSpec.Type.Dir.fRecursive))
break;
rc = AddDirFromGuest(strPath, strEntry);
break;
}
case FsObjType_Symlink:
{
if (mSourceSpec.Type.Dir.fFollowSymlinks)
{
/** @todo Symlink handling from guest is not imlemented yet.
* See IGuestSession::symlinkRead(). */
LogRel2(("Guest Control: Warning: Symlink support on guest side not available, skipping \"%s\"",
strEntry.c_str()));
}
break;
}
case FsObjType_File:
{
rc = AddEntryFromGuest(strEntry, fsObjInfo->i_getData());
break;
}
default:
break;
}
}
if (rc == VERR_NO_MORE_FILES) /* End of listing reached? */
rc = VINF_SUCCESS;
}
int rc2 = pDir->i_closeInternal(&rcGuest);
if (RT_SUCCESS(rc))
rc = rc2;
return rc;
}
/**
* Builds a host file list from a given path (and optional filter).
*
* @return VBox status code.
* @param strPath Directory on the host to build list from.
* @param strSubDir Current sub directory path; needed for recursion.
* Set to an empty path.
*/
int FsList::AddDirFromHost(const Utf8Str &strPath, const Utf8Str &strSubDir)
{
Utf8Str strPathAbs = strPath;
if ( !strPathAbs.endsWith("/")
&& !strPathAbs.endsWith("\\"))
strPathAbs += "/";
Utf8Str strPathSub = strSubDir;
if ( strPathSub.isNotEmpty()
&& !strPathSub.endsWith("/")
&& !strPathSub.endsWith("\\"))
strPathSub += "/";
strPathAbs += strPathSub;
LogFlowFunc(("Entering '%s' (sub '%s')\n", strPathAbs.c_str(), strPathSub.c_str()));
RTFSOBJINFO objInfo;
int rc = RTPathQueryInfo(strPathAbs.c_str(), &objInfo, RTFSOBJATTRADD_NOTHING);
if (RT_SUCCESS(rc))
{
if (RTFS_IS_DIRECTORY(objInfo.Attr.fMode))
{
if (strPathSub.isNotEmpty())
rc = AddEntryFromHost(strPathSub, &objInfo);
if (RT_SUCCESS(rc))
{
RTDIR hDir;
rc = RTDirOpen(&hDir, strPathAbs.c_str());
if (RT_SUCCESS(rc))
{
do
{
/* Retrieve the next directory entry. */
RTDIRENTRYEX Entry;
rc = RTDirReadEx(hDir, &Entry, NULL, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK);
if (RT_FAILURE(rc))
{
if (rc == VERR_NO_MORE_FILES)
rc = VINF_SUCCESS;
break;
}
Utf8Str strEntry = strPathSub + Utf8Str(Entry.szName);
LogFlowFunc(("Entry '%s'\n", strEntry.c_str()));
switch (Entry.Info.Attr.fMode & RTFS_TYPE_MASK)
{
case RTFS_TYPE_DIRECTORY:
{
/* Skip "." and ".." entries. */
if (RTDirEntryExIsStdDotLink(&Entry))
break;
if (!(mSourceSpec.Type.Dir.fRecursive))
break;
rc = AddDirFromHost(strPath, strEntry);
break;
}
case RTFS_TYPE_FILE:
{
rc = AddEntryFromHost(strEntry, &Entry.Info);
break;
}
case RTFS_TYPE_SYMLINK:
{
if (mSourceSpec.Type.Dir.fFollowSymlinks)
{
Utf8Str strEntryAbs = strPathAbs + Utf8Str(Entry.szName);
char szPathReal[RTPATH_MAX];
rc = RTPathReal(strEntryAbs.c_str(), szPathReal, sizeof(szPathReal));
if (RT_SUCCESS(rc))
{
rc = RTPathQueryInfo(szPathReal, &objInfo, RTFSOBJATTRADD_NOTHING);
if (RT_SUCCESS(rc))
{
LogFlowFunc(("Symlink '%s' -> '%s'\n", strEntryAbs.c_str(), szPathReal));
if (RTFS_IS_DIRECTORY(objInfo.Attr.fMode))
{
LogFlowFunc(("Symlink to directory\n"));
rc = AddDirFromHost(strPath, strEntry);
}
else if (RTFS_IS_FILE(objInfo.Attr.fMode))
{
LogFlowFunc(("Symlink to file\n"));
rc = AddEntryFromHost(strEntry, &objInfo);
}
else
rc = VERR_NOT_SUPPORTED;
}
else
LogFlowFunc(("Unable to query symlink info for '%s', rc=%Rrc\n", szPathReal, rc));
}
else
{
LogFlowFunc(("Unable to resolve symlink for '%s', rc=%Rrc\n", strPathAbs.c_str(), rc));
if (rc == VERR_FILE_NOT_FOUND) /* Broken symlink, skip. */
rc = VINF_SUCCESS;
}
}
break;
}
default:
break;
}
} while (RT_SUCCESS(rc));
RTDirClose(hDir);
}
}
}
else if (RTFS_IS_FILE(objInfo.Attr.fMode))
{
rc = VERR_IS_A_FILE;
}
else if (RTFS_IS_SYMLINK(objInfo.Attr.fMode))
{
rc = VERR_IS_A_SYMLINK;
}
else
rc = VERR_NOT_SUPPORTED;
}
else
LogFlowFunc(("Unable to query '%s', rc=%Rrc\n", strPathAbs.c_str(), rc));
LogFlowFuncLeaveRC(rc);
return rc;
}
GuestSessionTaskOpen::GuestSessionTaskOpen(GuestSession *pSession, uint32_t uFlags, uint32_t uTimeoutMS)
: GuestSessionTask(pSession)
, mFlags(uFlags)
, mTimeoutMS(uTimeoutMS)
{
m_strTaskName = "gctlSesOpen";
}
GuestSessionTaskOpen::~GuestSessionTaskOpen(void)
{
}
int GuestSessionTaskOpen::Run(void)
{
LogFlowThisFuncEnter();
AutoCaller autoCaller(mSession);
if (FAILED(autoCaller.rc())) return autoCaller.rc();
int vrc = mSession->i_startSession(NULL /*pvrcGuest*/);
/* Nothing to do here anymore. */
LogFlowFuncLeaveRC(vrc);
return vrc;
}
GuestSessionCopyTask::GuestSessionCopyTask(GuestSession *pSession)
: GuestSessionTask(pSession)
{
}
GuestSessionCopyTask::~GuestSessionCopyTask()
{
FsLists::iterator itList = mVecLists.begin();
while (itList != mVecLists.end())
{
FsList *pFsList = (*itList);
pFsList->Destroy();
delete pFsList;
mVecLists.erase(itList);
itList = mVecLists.begin();
}
Assert(mVecLists.empty());
}
GuestSessionTaskCopyFrom::GuestSessionTaskCopyFrom(GuestSession *pSession, GuestSessionFsSourceSet vecSrc, const Utf8Str &strDest)
: GuestSessionCopyTask(pSession)
{
m_strTaskName = "gctlCpyFrm";
mSources = vecSrc;
mDest = strDest;
}
GuestSessionTaskCopyFrom::~GuestSessionTaskCopyFrom(void)
{
}
HRESULT GuestSessionTaskCopyFrom::Init(const Utf8Str &strTaskDesc)
{
setTaskDesc(strTaskDesc);
/* Create the progress object. */
ComObjPtr<Progress> pProgress;
HRESULT hr = pProgress.createObject();
if (FAILED(hr))
return hr;
mProgress = pProgress;
int rc = VINF_SUCCESS;
ULONG cOperations = 0;
Utf8Str strErrorInfo;
/**
* Note: We need to build up the file/directory here instead of GuestSessionTaskCopyFrom::Run
* because the caller expects a ready-for-operation progress object on return.
* The progress object will have a variable operation count, based on the elements to
* be processed.
*/
GuestSessionFsSourceSet::iterator itSrc = mSources.begin();
while (itSrc != mSources.end())
{
Utf8Str strSrc = itSrc->strSource;
Utf8Str strDst = mDest;
bool fFollowSymlinks;
if (itSrc->enmType == FsObjType_Directory)
{
/* If the source does not end with a slash, copy over the entire directory
* (and not just its contents). */
if ( !strSrc.endsWith("/")
&& !strSrc.endsWith("\\"))
{
if ( !strDst.endsWith("/")
&& !strDst.endsWith("\\"))
strDst += "/";
strDst += Utf8StrFmt("%s", RTPathFilenameEx(strSrc.c_str(), mfPathStyle));
}
fFollowSymlinks = itSrc->Type.Dir.fFollowSymlinks;
}
else
{
fFollowSymlinks = RT_BOOL(itSrc->Type.File.fCopyFlags & FileCopyFlag_FollowLinks);
}
LogFlowFunc(("strSrc=%s, strDst=%s, fFollowSymlinks=%RTbool\n", strSrc.c_str(), strDst.c_str(), fFollowSymlinks));
GuestFsObjData srcObjData; int rcGuest;
rc = mSession->i_fsQueryInfo(strSrc, fFollowSymlinks, srcObjData, &rcGuest);
if (RT_FAILURE(rc))
{
strErrorInfo = Utf8StrFmt(GuestSession::tr("No such source file/directory: %s"), strSrc.c_str());
break;
}
if (srcObjData.mType == FsObjType_Directory)
{
if (itSrc->enmType != FsObjType_Directory)
{
strErrorInfo = Utf8StrFmt(GuestSession::tr("Source is not a file: %s"), strSrc.c_str());
rc = VERR_NOT_A_FILE;
break;
}
}
else
{
if (itSrc->enmType != FsObjType_File)
{
strErrorInfo = Utf8StrFmt(GuestSession::tr("Source is not a directory: %s"), strSrc.c_str());
rc = VERR_NOT_A_DIRECTORY;
break;
}
}
FsList *pFsList = NULL;
try
{
pFsList = new FsList(*this);
rc = pFsList->Init(strSrc, strDst, *itSrc);
if (RT_SUCCESS(rc))
{
if (itSrc->enmType == FsObjType_Directory)
{
rc = pFsList->AddDirFromGuest(strSrc);
}
else
rc = pFsList->AddEntryFromGuest(RTPathFilename(strSrc.c_str()), srcObjData);
}
if (RT_FAILURE(rc))
{
delete pFsList;
strErrorInfo = Utf8StrFmt(GuestSession::tr("Error adding source '%s' to list: %Rrc"), strSrc.c_str(), rc);
break;
}
mVecLists.push_back(pFsList);
}
catch (...)
{
rc = VERR_NO_MEMORY;
break;
}
AssertPtr(pFsList);
cOperations += (ULONG)pFsList->mVecEntries.size();
itSrc++;
}
if (cOperations) /* Use the first element as description (if available). */
{
Assert(mVecLists.size());
Assert(mVecLists[0]->mVecEntries.size());
Utf8Str strFirstOp = mDest + mVecLists[0]->mVecEntries[0]->strPath;
hr = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
TRUE /* aCancelable */, cOperations + 1 /* Number of operations */,
Bstr(strFirstOp).raw());
}
else /* If no operations have been defined, go with an "empty" progress object when will be used for error handling. */
hr = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
TRUE /* aCancelable */, 1 /* cOperations */, Bstr(mDesc).raw());
if (RT_FAILURE(rc))
{
Assert(strErrorInfo.isNotEmpty());
setProgressErrorMsg(VBOX_E_IPRT_ERROR, strErrorInfo);
}
LogFlowFunc(("Returning %Rhrc (%Rrc)\n", hr, rc));
return rc;
}
int GuestSessionTaskCopyFrom::Run(void)
{
LogFlowThisFuncEnter();
AutoCaller autoCaller(mSession);
if (FAILED(autoCaller.rc())) return autoCaller.rc();
int rc = VINF_SUCCESS;
FsLists::const_iterator itList = mVecLists.begin();
while (itList != mVecLists.end())
{
FsList *pList = *itList;
AssertPtr(pList);
const bool fCopyIntoExisting = pList->mSourceSpec.Type.Dir.fCopyFlags & DirectoryCopyFlag_CopyIntoExisting;
const uint32_t fDirMode = 0700; /** @todo Play safe by default; implement ACLs. */
LogFlowFunc(("List: srcRootAbs=%s, dstRootAbs=%s\n", pList->mSrcRootAbs.c_str(), pList->mDstRootAbs.c_str()));
/* Create the root directory. */
if (pList->mSourceSpec.enmType == FsObjType_Directory)
{
rc = RTDirCreate(pList->mDstRootAbs.c_str(), fDirMode, 0 /* fCreate */);
if ( rc == VWRN_ALREADY_EXISTS
&& !fCopyIntoExisting)
{
break;
}
}
FsEntries::const_iterator itEntry = pList->mVecEntries.begin();
while (itEntry != pList->mVecEntries.end())
{
FsEntry *pEntry = *itEntry;
AssertPtr(pEntry);
Utf8Str strSrcAbs = pList->mSrcRootAbs;
Utf8Str strDstAbs = pList->mDstRootAbs;
if (pList->mSourceSpec.enmType == FsObjType_Directory)
{
strSrcAbs += pEntry->strPath;
strDstAbs += pEntry->strPath;
if (pList->mSourceSpec.enmPathStyle == PathStyle_DOS)
strDstAbs.findReplace('\\', '/');
}
switch (pEntry->fMode & RTFS_TYPE_MASK)
{
case RTFS_TYPE_DIRECTORY:
LogFlowFunc(("Directory '%s': %s -> %s\n", pEntry->strPath.c_str(), strSrcAbs.c_str(), strDstAbs.c_str()));
if (!pList->mSourceSpec.fDryRun)
{
rc = RTDirCreate(strDstAbs.c_str(), fDirMode, 0 /* fCreate */);
if (rc == VERR_ALREADY_EXISTS)
{
if (!fCopyIntoExisting)
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination directory \"%s\" already exists"),
strDstAbs.c_str()));
break;
}
rc = VINF_SUCCESS;
}
if (RT_FAILURE(rc))
break;
}
break;
case RTFS_TYPE_FILE:
LogFlowFunc(("File '%s': %s -> %s\n", pEntry->strPath.c_str(), strSrcAbs.c_str(), strDstAbs.c_str()));
if (!pList->mSourceSpec.fDryRun)
rc = fileCopyFromGuest(strSrcAbs, strDstAbs, FileCopyFlag_None);
break;
default:
LogFlowFunc(("Warning: Type %d for '%s' is not supported\n",
pEntry->fMode & RTFS_TYPE_MASK, strSrcAbs.c_str()));
break;
}
if (RT_FAILURE(rc))
break;
mProgress->SetNextOperation(Bstr(strSrcAbs).raw(), 1);
++itEntry;
}
if (RT_FAILURE(rc))
break;
++itList;
}
if (RT_SUCCESS(rc))
rc = setProgressSuccess();
LogFlowFuncLeaveRC(rc);
return rc;
}
GuestSessionTaskCopyTo::GuestSessionTaskCopyTo(GuestSession *pSession, GuestSessionFsSourceSet vecSrc, const Utf8Str &strDest)
: GuestSessionCopyTask(pSession)
{
m_strTaskName = "gctlCpyTo";
mSources = vecSrc;
mDest = strDest;
}
GuestSessionTaskCopyTo::~GuestSessionTaskCopyTo(void)
{
}
HRESULT GuestSessionTaskCopyTo::Init(const Utf8Str &strTaskDesc)
{
LogFlowFuncEnter();
setTaskDesc(strTaskDesc);
/* Create the progress object. */
ComObjPtr<Progress> pProgress;
HRESULT hr = pProgress.createObject();
if (FAILED(hr))
return hr;
mProgress = pProgress;
int rc = VINF_SUCCESS;
ULONG cOperations = 0;
Utf8Str strErrorInfo;
/**
* Note: We need to build up the file/directory here instead of GuestSessionTaskCopyTo::Run
* because the caller expects a ready-for-operation progress object on return.
* The progress object will have a variable operation count, based on the elements to
* be processed.
*/
GuestSessionFsSourceSet::iterator itSrc = mSources.begin();
while (itSrc != mSources.end())
{
Utf8Str strSrc = itSrc->strSource;
Utf8Str strDst = mDest;
if (itSrc->enmType == FsObjType_Directory)
{
/* If the source does not end with a slash, copy over the entire directory
* (and not just its contents). */
if ( !strSrc.endsWith("/")
&& !strSrc.endsWith("\\"))
{
if ( !strDst.endsWith("/")
&& !strDst.endsWith("\\"))
strDst += "/";
strDst += Utf8StrFmt("%s", RTPathFilenameEx(strSrc.c_str(), mfPathStyle));
}
}
LogFlowFunc(("strSrc=%s, strDst=%s\n", strSrc.c_str(), strDst.c_str()));
RTFSOBJINFO srcFsObjInfo;
rc = RTPathQueryInfo(strSrc.c_str(), &srcFsObjInfo, RTFSOBJATTRADD_NOTHING);
if (RT_FAILURE(rc))
{
strErrorInfo = Utf8StrFmt(GuestSession::tr("No such source file/directory: %s"), strSrc.c_str());
break;
}
if (RTFS_IS_DIRECTORY(srcFsObjInfo.Attr.fMode))
{
if (itSrc->enmType != FsObjType_Directory)
{
strErrorInfo = Utf8StrFmt(GuestSession::tr("Source is not a file: %s"), strSrc.c_str());
rc = VERR_NOT_A_FILE;
break;
}
}
else
{
if (itSrc->enmType == FsObjType_Directory)
{
strErrorInfo = Utf8StrFmt(GuestSession::tr("Source is not a directory: %s"), strSrc.c_str());
rc = VERR_NOT_A_DIRECTORY;
break;
}
}
FsList *pFsList = NULL;
try
{
pFsList = new FsList(*this);
rc = pFsList->Init(strSrc, strDst, *itSrc);
if (RT_SUCCESS(rc))
{
if (itSrc->enmType == FsObjType_Directory)
{
rc = pFsList->AddDirFromHost(strSrc);
}
else
rc = pFsList->AddEntryFromHost(RTPathFilename(strSrc.c_str()), &srcFsObjInfo);
}
if (RT_FAILURE(rc))
{
delete pFsList;
strErrorInfo = Utf8StrFmt(GuestSession::tr("Error adding source '%s' to list: %Rrc"), strSrc.c_str(), rc);
break;
}
mVecLists.push_back(pFsList);
}
catch (...)
{
rc = VERR_NO_MEMORY;
break;
}
AssertPtr(pFsList);
cOperations += (ULONG)pFsList->mVecEntries.size();
itSrc++;
}
if (cOperations) /* Use the first element as description (if available). */
{
Assert(mVecLists.size());
Assert(mVecLists[0]->mVecEntries.size());
Utf8Str strFirstOp = mDest + mVecLists[0]->mVecEntries[0]->strPath;
hr = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
TRUE /* aCancelable */, cOperations + 1 /* Number of operations */,
Bstr(strFirstOp).raw());
}
else /* If no operations have been defined, go with an "empty" progress object when will be used for error handling. */
hr = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
TRUE /* aCancelable */, 1 /* cOperations */, Bstr(mDesc).raw());
if (RT_FAILURE(rc))
{
Assert(strErrorInfo.isNotEmpty());
setProgressErrorMsg(VBOX_E_IPRT_ERROR, strErrorInfo);
}
LogFlowFunc(("Returning %Rhrc (%Rrc)\n", hr, rc));
return hr;
}
int GuestSessionTaskCopyTo::Run(void)
{
LogFlowThisFuncEnter();
AutoCaller autoCaller(mSession);
if (FAILED(autoCaller.rc())) return autoCaller.rc();
int rc = VINF_SUCCESS;
FsLists::const_iterator itList = mVecLists.begin();
while (itList != mVecLists.end())
{
FsList *pList = *itList;
AssertPtr(pList);
bool fCopyIntoExisting = false;
bool fFollowSymlinks = false;
uint32_t fDirMode = 0700; /** @todo Play safe by default; implement ACLs. */
LogFlowFunc(("List: srcRootAbs=%s, dstRootAbs=%s\n", pList->mSrcRootAbs.c_str(), pList->mDstRootAbs.c_str()));
/* Create the root directory. */
if (pList->mSourceSpec.enmType == FsObjType_Directory)
{
fCopyIntoExisting = pList->mSourceSpec.Type.Dir.fCopyFlags & DirectoryCopyFlag_CopyIntoExisting;
fFollowSymlinks = pList->mSourceSpec.Type.Dir.fFollowSymlinks;
rc = directoryCreate(pList->mDstRootAbs.c_str(), DirectoryCreateFlag_None, fDirMode,
pList->mSourceSpec.Type.Dir.fFollowSymlinks);
if ( rc == VWRN_ALREADY_EXISTS
&& !fCopyIntoExisting)
{
break;
}
}
else if (pList->mSourceSpec.enmType == FsObjType_File)
{
fCopyIntoExisting = !RT_BOOL(pList->mSourceSpec.Type.File.fCopyFlags & FileCopyFlag_NoReplace);
fFollowSymlinks = RT_BOOL(pList->mSourceSpec.Type.File.fCopyFlags & FileCopyFlag_FollowLinks);
}
else
AssertFailed();
FsEntries::const_iterator itEntry = pList->mVecEntries.begin();
while (itEntry != pList->mVecEntries.end())
{
FsEntry *pEntry = *itEntry;
AssertPtr(pEntry);
Utf8Str strSrcAbs = pList->mSrcRootAbs;
Utf8Str strDstAbs = pList->mDstRootAbs;
if (pList->mSourceSpec.enmType == FsObjType_Directory)
{
strSrcAbs += pEntry->strPath;
strDstAbs += pEntry->strPath;
}
switch (pEntry->fMode & RTFS_TYPE_MASK)
{
case RTFS_TYPE_DIRECTORY:
LogFlowFunc(("Directory '%s': %s -> %s\n", pEntry->strPath.c_str(), strSrcAbs.c_str(), strDstAbs.c_str()));
if (!pList->mSourceSpec.fDryRun)
{
rc = directoryCreate(strDstAbs.c_str(), DirectoryCreateFlag_None, fDirMode, fFollowSymlinks);
if ( rc == VERR_ALREADY_EXISTS
&& !fCopyIntoExisting)
{
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination directory \"%s\" already exists"),
strDstAbs.c_str()));
break;
}
}
break;
case RTFS_TYPE_FILE:
LogFlowFunc(("File '%s': %s -> %s\n", pEntry->strPath.c_str(), strSrcAbs.c_str(), strDstAbs.c_str()));
if (!pList->mSourceSpec.fDryRun)
rc = fileCopyToGuest(strSrcAbs, strDstAbs, pList->mSourceSpec.Type.File.fCopyFlags);
break;
default:
LogFlowFunc(("Warning: Type %d for '%s' is not supported\n",
pEntry->fMode & RTFS_TYPE_MASK, strSrcAbs.c_str()));
break;
}
if (RT_FAILURE(rc))
break;
mProgress->SetNextOperation(Bstr(strSrcAbs).raw(), 1);
++itEntry;
}
if (RT_FAILURE(rc))
break;
++itList;
}
if (RT_SUCCESS(rc))
rc = setProgressSuccess();
LogFlowFuncLeaveRC(rc);
return rc;
}
GuestSessionTaskUpdateAdditions::GuestSessionTaskUpdateAdditions(GuestSession *pSession,
const Utf8Str &strSource,
const ProcessArguments &aArguments,
uint32_t fFlags)
: GuestSessionTask(pSession)
{
m_strTaskName = "gctlUpGA";
mSource = strSource;
mArguments = aArguments;
mFlags = fFlags;
}
GuestSessionTaskUpdateAdditions::~GuestSessionTaskUpdateAdditions(void)
{
}
int GuestSessionTaskUpdateAdditions::addProcessArguments(ProcessArguments &aArgumentsDest, const ProcessArguments &aArgumentsSource)
{
int rc = VINF_SUCCESS;
try
{
/* Filter out arguments which already are in the destination to
* not end up having them specified twice. Not the fastest method on the
* planet but does the job. */
ProcessArguments::const_iterator itSource = aArgumentsSource.begin();
while (itSource != aArgumentsSource.end())
{
bool fFound = false;
ProcessArguments::iterator itDest = aArgumentsDest.begin();
while (itDest != aArgumentsDest.end())
{
if ((*itDest).equalsIgnoreCase((*itSource)))
{
fFound = true;
break;
}
++itDest;
}
if (!fFound)
aArgumentsDest.push_back((*itSource));
++itSource;
}
}
catch(std::bad_alloc &)
{
return VERR_NO_MEMORY;
}
return rc;
}
int GuestSessionTaskUpdateAdditions::copyFileToGuest(GuestSession *pSession, RTVFS hVfsIso,
Utf8Str const &strFileSource, const Utf8Str &strFileDest,
bool fOptional)
{
AssertPtrReturn(pSession, VERR_INVALID_POINTER);
AssertReturn(hVfsIso != NIL_RTVFS, VERR_INVALID_POINTER);
RTVFSFILE hVfsFile = NIL_RTVFSFILE;
int rc = RTVfsFileOpen(hVfsIso, strFileSource.c_str(), RTFILE_O_OPEN | RTFILE_O_READ, &hVfsFile);
if (RT_SUCCESS(rc))
{
uint64_t cbSrcSize = 0;
rc = RTVfsFileGetSize(hVfsFile, &cbSrcSize);
if (RT_SUCCESS(rc))
{
LogRel(("Copying Guest Additions installer file \"%s\" to \"%s\" on guest ...\n",
strFileSource.c_str(), strFileDest.c_str()));
GuestFileOpenInfo dstOpenInfo;
RT_ZERO(dstOpenInfo);
dstOpenInfo.mFileName = strFileDest;
dstOpenInfo.mOpenAction = FileOpenAction_CreateOrReplace;
dstOpenInfo.mAccessMode = FileAccessMode_WriteOnly;
dstOpenInfo.mSharingMode = FileSharingMode_All; /** @todo Use _Read when implemented. */
ComObjPtr<GuestFile> dstFile; int rcGuest;
rc = mSession->i_fileOpen(dstOpenInfo, dstFile, &rcGuest);
if (RT_FAILURE(rc))
{
switch (rc)
{
case VERR_GSTCTL_GUEST_ERROR:
setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestFile::i_guestErrorToString(rcGuest));
break;
default:
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Destination file \"%s\" could not be opened: %Rrc"),
strFileDest.c_str(), rc));
break;
}
}
else
{
rc = fileCopyToGuestInner(hVfsFile, dstFile, FileCopyFlag_None, 0 /*cbOffset*/, cbSrcSize);
int rc2 = dstFile->i_closeFile(&rcGuest);
AssertRC(rc2);
}
}
RTVfsFileRelease(hVfsFile);
if (RT_FAILURE(rc))
return rc;
}
else
{
if (fOptional)
return VINF_SUCCESS;
return rc;
}
return rc;
}
int GuestSessionTaskUpdateAdditions::runFileOnGuest(GuestSession *pSession, GuestProcessStartupInfo &procInfo)
{
AssertPtrReturn(pSession, VERR_INVALID_POINTER);
LogRel(("Running %s ...\n", procInfo.mName.c_str()));
GuestProcessTool procTool;
int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
int vrc = procTool.init(pSession, procInfo, false /* Async */, &rcGuest);
if (RT_SUCCESS(vrc))
{
if (RT_SUCCESS(rcGuest))
vrc = procTool.wait(GUESTPROCESSTOOL_WAIT_FLAG_NONE, &rcGuest);
if (RT_SUCCESS(vrc))
vrc = procTool.getTerminationStatus();
}
if (RT_FAILURE(vrc))
{
switch (vrc)
{
case VERR_GSTCTL_PROCESS_EXIT_CODE:
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Running update file \"%s\" on guest failed: %Rrc"),
procInfo.mExecutable.c_str(), procTool.getRc()));
break;
case VERR_GSTCTL_GUEST_ERROR:
setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
break;
case VERR_INVALID_STATE: /** @todo Special guest control rc needed! */
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Update file \"%s\" reported invalid running state"),
procInfo.mExecutable.c_str()));
break;
default:
setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Error while running update file \"%s\" on guest: %Rrc"),
procInfo.mExecutable.c_str(), vrc));
break;
}
}
return vrc;
}
int GuestSessionTaskUpdateAdditions::Run(void)
{
LogFlowThisFuncEnter();
ComObjPtr<GuestSession> pSession = mSession;
Assert(!pSession.isNull());
AutoCaller autoCaller(pSession);
if (FAILED(autoCaller.rc())) return autoCaller.rc();
int rc = setProgress(10);
if (RT_FAILURE(rc))
return rc;
HRESULT hr = S_OK;
LogRel(("Automatic update of Guest Additions started, using \"%s\"\n", mSource.c_str()));
ComObjPtr<Guest> pGuest(mSession->i_getParent());
#if 0
/*
* Wait for the guest being ready within 30 seconds.
*/
AdditionsRunLevelType_T addsRunLevel;
uint64_t tsStart = RTTimeSystemMilliTS();
while ( SUCCEEDED(hr = pGuest->COMGETTER(AdditionsRunLevel)(&addsRunLevel))
&& ( addsRunLevel != AdditionsRunLevelType_Userland
&& addsRunLevel != AdditionsRunLevelType_Desktop))
{
if ((RTTimeSystemMilliTS() - tsStart) > 30 * 1000)
{
rc = VERR_TIMEOUT;
break;
}
RTThreadSleep(100); /* Wait a bit. */
}
if (FAILED(hr)) rc = VERR_TIMEOUT;
if (rc == VERR_TIMEOUT)
hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
Utf8StrFmt(GuestSession::tr("Guest Additions were not ready within time, giving up")));
#else
/*
* For use with the GUI we don't want to wait, just return so that the manual .ISO mounting
* can continue.
*/
AdditionsRunLevelType_T addsRunLevel;
if ( FAILED(hr = pGuest->COMGETTER(AdditionsRunLevel)(&addsRunLevel))
|| ( addsRunLevel != AdditionsRunLevelType_Userland
&& addsRunLevel != AdditionsRunLevelType_Desktop))
{
if (addsRunLevel == AdditionsRunLevelType_System)
hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
Utf8StrFmt(GuestSession::tr("Guest Additions are installed but not fully loaded yet, aborting automatic update")));
else
hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
Utf8StrFmt(GuestSession::tr("Guest Additions not installed or ready, aborting automatic update")));
rc = VERR_NOT_SUPPORTED;
}
#endif
if (RT_SUCCESS(rc))
{
/*
* Determine if we are able to update automatically. This only works
* if there are recent Guest Additions installed already.
*/
Utf8Str strAddsVer;
rc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/Version", strAddsVer);
if ( RT_SUCCESS(rc)
&& RTStrVersionCompare(strAddsVer.c_str(), "4.1") < 0)
{
hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
Utf8StrFmt(GuestSession::tr("Guest has too old Guest Additions (%s) installed for automatic updating, please update manually"),
strAddsVer.c_str()));
rc = VERR_NOT_SUPPORTED;
}
}
Utf8Str strOSVer;
eOSType osType = eOSType_Unknown;
if (RT_SUCCESS(rc))
{
/*
* Determine guest OS type and the required installer image.
*/
Utf8Str strOSType;
rc = getGuestProperty(pGuest, "/VirtualBox/GuestInfo/OS/Product", strOSType);
if (RT_SUCCESS(rc))
{
if ( strOSType.contains("Microsoft", Utf8Str::CaseInsensitive)
|| strOSType.contains("Windows", Utf8Str::CaseInsensitive))
{
osType = eOSType_Windows;
/*
* Determine guest OS version.
*/
rc = getGuestProperty(pGuest, "/VirtualBox/GuestInfo/OS/Release", strOSVer);
if (RT_FAILURE(rc))
{
hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
Utf8StrFmt(GuestSession::tr("Unable to detected guest OS version, please update manually")));
rc = VERR_NOT_SUPPORTED;
}
/* Because Windows 2000 + XP and is bitching with WHQL popups even if we have signed drivers we
* can't do automated updates here. */
/* Windows XP 64-bit (5.2) is a Windows 2003 Server actually, so skip this here. */
if ( RT_SUCCESS(rc)
&& RTStrVersionCompare(strOSVer.c_str(), "5.0") >= 0)
{
if ( strOSVer.startsWith("5.0") /* Exclude the build number. */
|| strOSVer.startsWith("5.1") /* Exclude the build number. */)
{
/* If we don't have AdditionsUpdateFlag_WaitForUpdateStartOnly set we can't continue
* because the Windows Guest Additions installer will fail because of WHQL popups. If the
* flag is set this update routine ends successfully as soon as the installer was started
* (and the user has to deal with it in the guest). */
if (!(mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
{
hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
Utf8StrFmt(GuestSession::tr("Windows 2000 and XP are not supported for automatic updating due to WHQL interaction, please update manually")));
rc = VERR_NOT_SUPPORTED;
}
}
}
else
{
hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
Utf8StrFmt(GuestSession::tr("%s (%s) not supported for automatic updating, please update manually"),
strOSType.c_str(), strOSVer.c_str()));
rc = VERR_NOT_SUPPORTED;
}
}
else if (strOSType.contains("Solaris", Utf8Str::CaseInsensitive))
{
osType = eOSType_Solaris;
}
else /* Everything else hopefully means Linux :-). */
osType = eOSType_Linux;
#if 1 /* Only Windows is supported (and tested) at the moment. */
if ( RT_SUCCESS(rc)
&& osType != eOSType_Windows)
{
hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
Utf8StrFmt(GuestSession::tr("Detected guest OS (%s) does not support automatic Guest Additions updating, please update manually"),
strOSType.c_str()));
rc = VERR_NOT_SUPPORTED;
}
#endif
}
}
if (RT_SUCCESS(rc))
{
/*
* Try to open the .ISO file to extract all needed files.
*/
RTVFSFILE hVfsFileIso;
rc = RTVfsFileOpenNormal(mSource.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, &hVfsFileIso);
if (RT_SUCCESS(rc))
{
RTVFS hVfsIso;
rc = RTFsIso9660VolOpen(hVfsFileIso, 0 /*fFlags*/, &hVfsIso, NULL);
if (RT_FAILURE(rc))
{
hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Unable to open Guest Additions .ISO file \"%s\": %Rrc"),
mSource.c_str(), rc));
}
else
{
/* Set default installation directories. */
Utf8Str strUpdateDir = "/tmp/";
if (osType == eOSType_Windows)
strUpdateDir = "C:\\Temp\\";
rc = setProgress(5);
/* Try looking up the Guest Additions installation directory. */
if (RT_SUCCESS(rc))
{
/* Try getting the installed Guest Additions version to know whether we
* can install our temporary Guest Addition data into the original installation
* directory.
*
* Because versions prior to 4.2 had bugs wrt spaces in paths we have to choose
* a different location then.
*/
bool fUseInstallDir = false;
Utf8Str strAddsVer;
rc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/Version", strAddsVer);
if ( RT_SUCCESS(rc)
&& RTStrVersionCompare(strAddsVer.c_str(), "4.2r80329") > 0)
{
fUseInstallDir = true;
}
if (fUseInstallDir)
{
if (RT_SUCCESS(rc))
rc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/InstallDir", strUpdateDir);
if (RT_SUCCESS(rc))
{
if (osType == eOSType_Windows)
{
strUpdateDir.findReplace('/', '\\');
strUpdateDir.append("\\Update\\");
}
else
strUpdateDir.append("/update/");
}
}
}
if (RT_SUCCESS(rc))
LogRel(("Guest Additions update directory is: %s\n",
strUpdateDir.c_str()));
/* Create the installation directory. */
int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
rc = pSession->i_directoryCreate(strUpdateDir, 755 /* Mode */, DirectoryCreateFlag_Parents, &rcGuest);
if (RT_FAILURE(rc))
{
switch (rc)
{
case VERR_GSTCTL_GUEST_ERROR:
hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
break;
default:
hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Error creating installation directory \"%s\" on the guest: %Rrc"),
strUpdateDir.c_str(), rc));
break;
}
}
if (RT_SUCCESS(rc))
rc = setProgress(10);
if (RT_SUCCESS(rc))
{
/* Prepare the file(s) we want to copy over to the guest and
* (maybe) want to run. */
switch (osType)
{
case eOSType_Windows:
{
/* Do we need to install our certificates? We do this for W2K and up. */
bool fInstallCert = false;
/* Only Windows 2000 and up need certificates to be installed. */
if (RTStrVersionCompare(strOSVer.c_str(), "5.0") >= 0)
{
fInstallCert = true;
LogRel(("Certificates for auto updating WHQL drivers will be installed\n"));
}
else
LogRel(("Skipping installation of certificates for WHQL drivers\n"));
if (fInstallCert)
{
static struct { const char *pszDst, *pszIso; } const s_aCertFiles[] =
{
{ "vbox.cer", "CERT/VBOX.CER" },
{ "vbox-sha1.cer", "CERT/VBOX_SHA1.CER" },
{ "vbox-sha256.cer", "CERT/VBOX_SHA256.CER" },
{ "vbox-sha256-r3.cer", "CERT/VBOX_SHA256_R3.CER" },
{ "oracle-vbox.cer", "CERT/ORACLE_VBOX.CER" },
};
uint32_t fCopyCertUtil = ISOFILE_FLAG_COPY_FROM_ISO;
for (uint32_t i = 0; i < RT_ELEMENTS(s_aCertFiles); i++)
{
/* Skip if not present on the ISO. */
RTFSOBJINFO ObjInfo;
rc = RTVfsQueryPathInfo(hVfsIso, s_aCertFiles[i].pszIso, &ObjInfo, RTFSOBJATTRADD_NOTHING,
RTPATH_F_ON_LINK);
if (RT_FAILURE(rc))
continue;
/* Copy the certificate certificate. */
Utf8Str const strDstCert(strUpdateDir + s_aCertFiles[i].pszDst);
mFiles.push_back(ISOFile(s_aCertFiles[i].pszIso,
strDstCert,
ISOFILE_FLAG_COPY_FROM_ISO | ISOFILE_FLAG_OPTIONAL));
/* Out certificate installation utility. */
/* First pass: Copy over the file (first time only) + execute it to remove any
* existing VBox certificates. */
GuestProcessStartupInfo siCertUtilRem;
siCertUtilRem.mName = "VirtualBox Certificate Utility, removing old VirtualBox certificates";
siCertUtilRem.mArguments.push_back(Utf8Str("remove-trusted-publisher"));
siCertUtilRem.mArguments.push_back(Utf8Str("--root")); /* Add root certificate as well. */
siCertUtilRem.mArguments.push_back(strDstCert);
siCertUtilRem.mArguments.push_back(strDstCert);
mFiles.push_back(ISOFile("CERT/VBOXCERTUTIL.EXE",
strUpdateDir + "VBoxCertUtil.exe",
fCopyCertUtil | ISOFILE_FLAG_EXECUTE | ISOFILE_FLAG_OPTIONAL,
siCertUtilRem));
fCopyCertUtil = 0;
/* Second pass: Only execute (but don't copy) again, this time installng the
* recent certificates just copied over. */
GuestProcessStartupInfo siCertUtilAdd;
siCertUtilAdd.mName = "VirtualBox Certificate Utility, installing VirtualBox certificates";
siCertUtilAdd.mArguments.push_back(Utf8Str("add-trusted-publisher"));
siCertUtilAdd.mArguments.push_back(Utf8Str("--root")); /* Add root certificate as well. */
siCertUtilAdd.mArguments.push_back(strDstCert);
siCertUtilAdd.mArguments.push_back(strDstCert);
mFiles.push_back(ISOFile("CERT/VBOXCERTUTIL.EXE",
strUpdateDir + "VBoxCertUtil.exe",
ISOFILE_FLAG_EXECUTE | ISOFILE_FLAG_OPTIONAL,
siCertUtilAdd));
}
}
/* The installers in different flavors, as we don't know (and can't assume)
* the guest's bitness. */
mFiles.push_back(ISOFile("VBOXWINDOWSADDITIONS_X86.EXE",
strUpdateDir + "VBoxWindowsAdditions-x86.exe",
ISOFILE_FLAG_COPY_FROM_ISO));
mFiles.push_back(ISOFile("VBOXWINDOWSADDITIONS_AMD64.EXE",
strUpdateDir + "VBoxWindowsAdditions-amd64.exe",
ISOFILE_FLAG_COPY_FROM_ISO));
/* The stub loader which decides which flavor to run. */
GuestProcessStartupInfo siInstaller;
siInstaller.mName = "VirtualBox Windows Guest Additions Installer";
/* Set a running timeout of 5 minutes -- the Windows Guest Additions
* setup can take quite a while, so be on the safe side. */
siInstaller.mTimeoutMS = 5 * 60 * 1000;
siInstaller.mArguments.push_back(Utf8Str("/S")); /* We want to install in silent mode. */
siInstaller.mArguments.push_back(Utf8Str("/l")); /* ... and logging enabled. */
/* Don't quit VBoxService during upgrade because it still is used for this
* piece of code we're in right now (that is, here!) ... */
siInstaller.mArguments.push_back(Utf8Str("/no_vboxservice_exit"));
/* Tell the installer to report its current installation status
* using a running VBoxTray instance via balloon messages in the
* Windows taskbar. */
siInstaller.mArguments.push_back(Utf8Str("/post_installstatus"));
/* Add optional installer command line arguments from the API to the
* installer's startup info. */
rc = addProcessArguments(siInstaller.mArguments, mArguments);
AssertRC(rc);
/* If the caller does not want to wait for out guest update process to end,
* complete the progress object now so that the caller can do other work. */
if (mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly)
siInstaller.mFlags |= ProcessCreateFlag_WaitForProcessStartOnly;
mFiles.push_back(ISOFile("VBOXWINDOWSADDITIONS.EXE",
strUpdateDir + "VBoxWindowsAdditions.exe",
ISOFILE_FLAG_COPY_FROM_ISO | ISOFILE_FLAG_EXECUTE, siInstaller));
break;
}
case eOSType_Linux:
/** @todo Add Linux support. */
break;
case eOSType_Solaris:
/** @todo Add Solaris support. */
break;
default:
AssertReleaseMsgFailed(("Unsupported guest type: %d\n", osType));
break;
}
}
if (RT_SUCCESS(rc))
{
/* We want to spend 40% total for all copying operations. So roughly
* calculate the specific percentage step of each copied file. */
uint8_t uOffset = 20; /* Start at 20%. */
uint8_t uStep = 40 / (uint8_t)mFiles.size(); Assert(mFiles.size() <= 10);
LogRel(("Copying over Guest Additions update files to the guest ...\n"));
std::vector<ISOFile>::const_iterator itFiles = mFiles.begin();
while (itFiles != mFiles.end())
{
if (itFiles->fFlags & ISOFILE_FLAG_COPY_FROM_ISO)
{
bool fOptional = false;
if (itFiles->fFlags & ISOFILE_FLAG_OPTIONAL)
fOptional = true;
rc = copyFileToGuest(pSession, hVfsIso, itFiles->strSource, itFiles->strDest, fOptional);
if (RT_FAILURE(rc))
{
hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Error while copying file \"%s\" to \"%s\" on the guest: %Rrc"),
itFiles->strSource.c_str(), itFiles->strDest.c_str(), rc));
break;
}
}
rc = setProgress(uOffset);
if (RT_FAILURE(rc))
break;
uOffset += uStep;
++itFiles;
}
}
/* Done copying, close .ISO file. */
RTVfsRelease(hVfsIso);
if (RT_SUCCESS(rc))
{
/* We want to spend 35% total for all copying operations. So roughly
* calculate the specific percentage step of each copied file. */
uint8_t uOffset = 60; /* Start at 60%. */
uint8_t uStep = 35 / (uint8_t)mFiles.size(); Assert(mFiles.size() <= 10);
LogRel(("Executing Guest Additions update files ...\n"));
std::vector<ISOFile>::iterator itFiles = mFiles.begin();
while (itFiles != mFiles.end())
{
if (itFiles->fFlags & ISOFILE_FLAG_EXECUTE)
{
rc = runFileOnGuest(pSession, itFiles->mProcInfo);
if (RT_FAILURE(rc))
break;
}
rc = setProgress(uOffset);
if (RT_FAILURE(rc))
break;
uOffset += uStep;
++itFiles;
}
}
if (RT_SUCCESS(rc))
{
LogRel(("Automatic update of Guest Additions succeeded\n"));
rc = setProgressSuccess();
}
}
RTVfsFileRelease(hVfsFileIso);
}
}
if (RT_FAILURE(rc))
{
if (rc == VERR_CANCELLED)
{
LogRel(("Automatic update of Guest Additions was canceled\n"));
hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
Utf8StrFmt(GuestSession::tr("Installation was canceled")));
}
else
{
Utf8Str strError = Utf8StrFmt("No further error information available (%Rrc)", rc);
if (!mProgress.isNull()) /* Progress object is optional. */
{
com::ProgressErrorInfo errorInfo(mProgress);
if ( errorInfo.isFullAvailable()
|| errorInfo.isBasicAvailable())
{
strError = errorInfo.getText();
}
}
LogRel(("Automatic update of Guest Additions failed: %s (%Rhrc)\n",
strError.c_str(), hr));
}
LogRel(("Please install Guest Additions manually\n"));
}
/** @todo Clean up copied / left over installation files. */
LogFlowFuncLeaveRC(rc);
return rc;
}
| 37.135729 | 195 | 0.510056 | [
"object",
"vector"
] |
081e22d08d776cd75cd3ee21dfa52edb18117eed | 26,619 | cc | C++ | sparse_operation_kit/kit_cc/kit_cc_infra/src/parameters/raw_param.cc | marsmiao/HugeCTR | c9ff359a69565200fcc0c7aae291d9c297bea70e | [
"Apache-2.0"
] | null | null | null | sparse_operation_kit/kit_cc/kit_cc_infra/src/parameters/raw_param.cc | marsmiao/HugeCTR | c9ff359a69565200fcc0c7aae291d9c297bea70e | [
"Apache-2.0"
] | null | null | null | sparse_operation_kit/kit_cc/kit_cc_infra/src/parameters/raw_param.cc | marsmiao/HugeCTR | c9ff359a69565200fcc0c7aae291d9c297bea70e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* 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 "parameters/raw_param.h"
#include "tensor_buffer/tensor2_wrapper.h"
#include "embeddings/embedding_layer.h"
#include "parameters/dumping_functions.h"
#include "common.h"
#include <system_error>
#include <fstream>
namespace SparseOperationKit {
RawParam::RawParam(const std::string& initializer, const std::vector<size_t> shape,
const std::shared_ptr<ResourcesManager>& resource_mgr,
const std::vector<std::shared_ptr<HugeCTR::GeneralBuffer2<HugeCTR::CudaAllocator>>>& buffers,
const std::string var_name, const bool trainable)
: resource_mgr_(resource_mgr),
hashtables_(resource_mgr->get_local_gpu_count()),
max_vocabulary_size_per_gpu_(shape[0]), embedding_vector_size_(shape[1]),
var_name_(var_name), trainable_(trainable), initializer_(Initializer::Get(initializer)),
has_hashtable_(true)
{
emb_table_tensors_.reserve(resource_mgr_->get_local_gpu_count());
emb_table_tensors_interface_.reserve(resource_mgr_->get_local_gpu_count());
HugeCTR::CudaDeviceContext device_context;
for (size_t dev_id = 0; dev_id < resource_mgr->get_local_gpu_count(); ++dev_id) {
device_context.set_device(resource_mgr_->get_local_gpu(dev_id)->get_local_device_id());
// reserve spaces for embedding table
{
Tensor2<float> tensor;
buffers[dev_id]->reserve(shape, &tensor);
emb_table_tensors_.push_back(tensor);
emb_table_tensors_interface_.push_back(Tensor2Wrapper<float>::create(tensor));
}
// construct hashtable
{
hashtables_[dev_id].reset(new NvHashTable(max_vocabulary_size_per_gpu_));
}
} // for dev_id
if (emb_table_tensors_.size() != emb_table_tensors_interface_.size())
throw std::runtime_error(ErrorBase + "The size of embedding table tensors and its interface if not equal.");
}
RawParam::~RawParam() {}
std::shared_ptr<RawParam> RawParam::create(const std::string& initializer, const bool use_hashtable,
const std::vector<size_t> shape,
const std::shared_ptr<ResourcesManager>& resource_mgr,
const std::vector<std::shared_ptr<HugeCTR::GeneralBuffer2<HugeCTR::CudaAllocator>>>& buffers,
const std::string var_name, const bool trainable) {
if (use_hashtable)
return std::shared_ptr<RawParam>(new RawParam(initializer, shape, resource_mgr, buffers, var_name, trainable));
else
throw std::runtime_error(ErrorBase + "Not implemented yet.");
}
size_t RawParam::get_max_vocabulary_size_per_gpu() const {
return max_vocabulary_size_per_gpu_;
}
size_t RawParam::get_embedding_vec_size() const {
return embedding_vector_size_;
}
void RawParam::init(const size_t global_replica_id) {
const size_t local_replica_id = resource_mgr_->cal_local_id_from_global_id(global_replica_id);
MESSAGE("Variable: " + var_name_ + " on global_replica_id: " +
std::to_string(global_replica_id) + " start initialization");
if (local_replica_id >= emb_table_tensors_.size())
throw std::runtime_error(ErrorBase + "local_replica_id is out of the range of emb_table_tensors.size().");
const auto &local_gpu = resource_mgr_->get_local_gpu(local_replica_id);
initializer_->fill(emb_table_tensors_interface_[local_replica_id],
local_gpu->get_sm_count(),
local_gpu->get_variant_curand_gen(),
local_gpu->get_stream());
resource_mgr_->sync_gpu(local_replica_id);
MESSAGE("Variable: " + var_name_ + " on global_replica_id: " +
std::to_string(global_replica_id) + " initialization done.");
}
bool RawParam::trainable() const {
return trainable_;
}
void RawParam::set_user(std::shared_ptr<EmbeddingLayer>& embedding) {
user_ = embedding;
}
auto RawParam::get_hashtable(const size_t local_replica_id) -> std::shared_ptr<NvHashTable>& {
if (has_hashtable_) return hashtables_[local_replica_id];
else throw std::runtime_error(ErrorBase + "Hashtable is not valid.");
}
std::shared_ptr<Tensor>& RawParam::get_embedding_table_tensor(const size_t local_replica_id) {
if (local_replica_id >= emb_table_tensors_.size())
throw std::runtime_error(ErrorBase + "local_replica_id is out of the range of emb_table_tensors.size().");
return emb_table_tensors_interface_[local_replica_id];
}
std::string RawParam::get_var_name() const {
return var_name_;
}
void RawParam::dump_to_file(const std::string filepath) {
// if embedding lookuper already saved parameters to file. then skip the following codes.
if (user_->save_params(filepath)) return;
const size_t local_gpu_count = resource_mgr_->get_local_gpu_count();
const size_t worker_id = resource_mgr_->get_worker_id();
const size_t worker_num = resource_mgr_->get_workers_num();
// step 1: get the count of key-index pairs on each hashtable on local worker.
std::unique_ptr<size_t []> count;
size_t local_worker_max_count = 0;
if (0 == worker_id) { // chief worker
count.reset(new size_t[worker_num * local_gpu_count]());
} else {
count.reset(new size_t[local_gpu_count]());
}
HugeCTR::CudaDeviceContext device_context;
for (size_t dev_id = 0; dev_id < local_gpu_count; dev_id++) {
const auto &local_gpu = resource_mgr_->get_local_gpu(dev_id);
device_context.set_device(local_gpu->get_local_device_id());
const size_t hashtable_size = hashtables_[dev_id]->get_size(local_gpu->get_stream());
if (hashtable_size != hashtables_[dev_id]->get_value_head(local_gpu->get_stream()))
throw std::runtime_error(ErrorBase + " hashtable get_value_head() not equal to get_size().");
if (hashtable_size > max_vocabulary_size_per_gpu_)
throw std::runtime_error(ErrorBase + " keys count on GPU: " + std::to_string(dev_id) +
" is out of the range of max_vocabulary_size_per_gpu.");
count[dev_id] = hashtable_size;
MESSAGE("Worker: " + std::to_string(worker_id) + ", GPU: " + std::to_string(dev_id) +
" key-index count = " + std::to_string(hashtable_size));
local_worker_max_count = (local_worker_max_count > count[dev_id]) ? local_worker_max_count : count[dev_id];
} // for dev_id in local_gpu_count
// step 2: gather count among all workers
size_t *d_global_max_count = nullptr;
std::vector<size_t *> d_count(local_gpu_count);
size_t *d_count_aggregation = nullptr;
for (size_t dev_id = 0; dev_id < local_gpu_count; dev_id++) {
const auto &local_gpu = resource_mgr_->get_local_gpu(dev_id);
device_context.set_device(local_gpu->get_local_device_id());
if (0 == worker_id && 0 == dev_id) { // chief worker and chief GPU
CK_CUDA(cudaMalloc(&d_global_max_count, sizeof(size_t) * 1));
CK_CUDA(cudaMalloc(&d_count_aggregation, sizeof(size_t) * worker_num * local_gpu_count));
}
CK_CUDA(cudaMalloc(&d_count[dev_id], sizeof(size_t) * 1));
CK_CUDA(cudaMemcpyAsync(d_count[dev_id], &count[dev_id], sizeof(size_t) * 1,
cudaMemcpyHostToDevice,
local_gpu->get_stream()));
} // for dev_id in local_gpu_count
resource_mgr_->sync_all_workers();
CK_NCCL(ncclGroupStart());
for (size_t dev_id = 0; dev_id < local_gpu_count; dev_id++) {
const auto &local_gpu = resource_mgr_->get_local_gpu(dev_id);
CK_NCCL(ncclReduce(d_count[dev_id], d_global_max_count, 1, ncclUint64, ncclMax,
/*root=*/0, local_gpu->get_nccl(), local_gpu->get_stream()));
} // for dev_id in local_gpu_count
CK_NCCL(ncclGroupEnd());
CK_NCCL(ncclGroupStart());
if (0 == worker_id) { // chief worker
const auto &local_gpu = resource_mgr_->get_local_gpu(0);
device_context.set_device(local_gpu->get_local_device_id());
for (size_t rank = 0; rank < resource_mgr_->get_global_gpu_count(); rank++) {
CK_NCCL(ncclRecv(d_count_aggregation + rank, 1, ncclUint64, /*peer=*/rank,
local_gpu->get_nccl(),
local_gpu->get_stream()));
} // for rank in global_gpu_count
}
for (size_t dev_id = 0; dev_id < local_gpu_count; dev_id++) {
const auto &local_gpu = resource_mgr_->get_local_gpu(dev_id);
CK_NCCL(ncclSend(d_count[dev_id], 1, ncclUint64, /*peer=*/0,
local_gpu->get_nccl(),
local_gpu->get_stream()));
} // for dev_id in local_gpu_count
CK_NCCL(ncclGroupEnd());
if (0 == worker_id) { // chief worker
const auto &local_gpu = resource_mgr_->get_local_gpu(0);
device_context.set_device(local_gpu->get_local_device_id());
local_worker_max_count = 0;
CK_CUDA(cudaMemcpyAsync(&local_worker_max_count, d_global_max_count, sizeof(size_t) * 1,
cudaMemcpyDeviceToHost,
local_gpu->get_stream()));
CK_CUDA(cudaMemcpyAsync(count.get(), d_count_aggregation,
sizeof(size_t) * worker_num * local_gpu_count,
cudaMemcpyDeviceToHost,
local_gpu->get_stream()));
CK_CUDA(cudaStreamSynchronize(local_gpu->get_stream()));
}
// step 3: allocate temp spaces for dump parameters from GPU to CPU
std::unique_ptr<int64_t *[]> h_hash_table_key(new int64_t *[local_gpu_count]);
std::unique_ptr<int64_t *[]> d_hash_table_key(new int64_t *[local_gpu_count]);
std::unique_ptr<size_t *[]> d_hash_table_value_index(new size_t *[local_gpu_count]);
std::unique_ptr<float *[]> h_hash_table_value(new float *[local_gpu_count]);
std::unique_ptr<float *[]> d_hash_table_value(new float *[local_gpu_count]);
std::unique_ptr<size_t *[]> d_dump_counter(new size_t *[local_gpu_count]);
for (size_t dev_id = 0; dev_id < local_gpu_count; ++dev_id) {
const auto &local_gpu = resource_mgr_->get_local_gpu(dev_id);
device_context.set_device(local_gpu->get_local_device_id());
// TODO: use count[dev_id] instead of local_worker_max_count??
CK_CUDA(cudaMallocHost(&h_hash_table_key[dev_id], local_worker_max_count * sizeof(int64_t)));
CK_CUDA(cudaMalloc(&d_hash_table_key[dev_id], local_worker_max_count * sizeof(int64_t)));
CK_CUDA(cudaMalloc(&d_hash_table_value_index[dev_id], local_worker_max_count * sizeof(size_t)));
CK_CUDA(cudaMallocHost(&h_hash_table_value[dev_id], local_worker_max_count * embedding_vector_size_ * sizeof(float)));
CK_CUDA(cudaMalloc(&d_hash_table_value[dev_id], local_worker_max_count * embedding_vector_size_ * sizeof(float)));
CK_CUDA(cudaMalloc(&d_dump_counter[dev_id], 1 * sizeof(size_t))); // FIXME: ???
} // for dev_id in local_gpu_count
resource_mgr_->sync_all_workers();
// step 4: dump parameters to temp spaces
for (size_t dev_id = 0; dev_id < local_gpu_count; dev_id++) {
if (0 == count[dev_id]) continue;
const auto &local_gpu = resource_mgr_->get_local_gpu(dev_id);
device_context.set_device(local_gpu->get_local_device_id());
MESSAGE("Worker: " + std::to_string(worker_id) + ", GPU: " + std::to_string(dev_id) +
": dumping parameters from hashtable..");
// get hashtable key-index pairs.
hashtables_[dev_id]->dump(d_hash_table_key[dev_id], d_hash_table_value_index[dev_id],
d_dump_counter[dev_id], local_gpu->get_stream());
// get embedding vector by sorted index
get_hash_value(count[dev_id], embedding_vector_size_, d_hash_table_value_index[dev_id],
emb_table_tensors_[dev_id].get_ptr(), d_hash_table_value[dev_id],
local_gpu->get_stream());
} // for dev_id in local_gpu_count
// step 5: save parameters to file stream.
// Only cheif worker needs to copy parameters from GPU to CPU, and then write it to file,
// all the other workers only send their datas to cheif worker via NCCL.
constexpr size_t key_size = sizeof(int64_t);
const size_t values_size = sizeof(float) * embedding_vector_size_;
std::unique_ptr<char []> key_buf(new char[local_worker_max_count * key_size]());
std::unique_ptr<char []> embedding_value_buf(new char[local_worker_max_count * values_size]());
if (0 == worker_id) { // on cheif worker
const std::string key_filename = filepath + "/" + var_name_ + "_keys.file";
const std::string values_filename = filepath + "/" + var_name_ + "_values.file";
std::ofstream key_stream(key_filename, std::ios::binary | std::ios::out);
std::ofstream values_stream(values_filename, std::ios::binary | std::ios::out);
for (size_t worker = 0; worker < worker_num; worker++) {
if (worker_id != worker) { /*cheif worker receives data from other workers*/
CK_NCCL(ncclGroupStart());
for (size_t recv_worker = 1; recv_worker < worker_num; recv_worker++) {
if (worker == recv_worker) { /*cheif worker receives valid data from other worker*/
for (size_t dev_id = 0; dev_id < local_gpu_count; dev_id++) {
const int32_t peer = worker * local_gpu_count + dev_id;
const auto &local_gpu = resource_mgr_->get_local_gpu(dev_id);
const size_t pair_count = count[recv_worker * local_gpu_count + dev_id];
CK_NCCL(ncclRecv(d_hash_table_key[dev_id],
pair_count,
ncclInt64, /*peer=*/peer,
local_gpu->get_nccl(),
local_gpu->get_stream()));
CK_NCCL(ncclRecv(d_hash_table_value[dev_id],
pair_count * embedding_vector_size_,
ncclFloat32, /*peer=*/peer,
local_gpu->get_nccl(),
local_gpu->get_stream()));
} // for dev_id in local_gpu_count
MESSAGE("Worker: " + std::to_string(worker) + "'s data is received by cheif node.");
} else { /*cheif worker receives dummy data from other worker*/
for (size_t dev_id = 0; dev_id < local_gpu_count; dev_id++) {
CK_NCCL(ncclRecv(d_count[dev_id], 1, ncclUint64,
/*peer=*/recv_worker * local_gpu_count + dev_id,
resource_mgr_->get_local_gpu(dev_id)->get_nccl(),
resource_mgr_->get_local_gpu(dev_id)->get_stream()));
} // for dev_id in local_gpu_count
}
} // for recv_worker in [1, worker_num)
CK_NCCL(ncclGroupEnd());
}
/*cheif worker copy data from GPU to CPU, and save it to file stream.*/
for (size_t dev_id = 0; dev_id < local_gpu_count; dev_id++) {
const size_t pair_count = count[worker * local_gpu_count + dev_id];
const auto &local_gpu = resource_mgr_->get_local_gpu(dev_id);
CK_CUDA(cudaMemcpyAsync(h_hash_table_key[dev_id], d_hash_table_key[dev_id],
pair_count * sizeof(int64_t),
cudaMemcpyDeviceToHost,
local_gpu->get_stream()));
CK_CUDA(cudaMemcpyAsync(h_hash_table_value[dev_id], d_hash_table_value[dev_id],
pair_count * embedding_vector_size_ * sizeof(float),
cudaMemcpyDeviceToHost,
local_gpu->get_stream()));
} // for dev_id in local_gpu_count
resource_mgr_->sync_local_gpus();
/*save to file stream*/
for (size_t dev_id = 0; dev_id < local_gpu_count; dev_id++) {
const size_t pair_count = count[worker * local_gpu_count + dev_id];
// save sorted keys
std::memcpy(key_buf.get(), h_hash_table_key[dev_id], pair_count * key_size);
key_stream.write(key_buf.get(), pair_count * key_size);
// save embedding vectors
std::memcpy(embedding_value_buf.get(), h_hash_table_value[dev_id], pair_count * values_size);
values_stream.write(embedding_value_buf.get(), pair_count * values_size);
MESSAGE("Worker: " + std::to_string(worker) + ", GPU: " + std::to_string(dev_id) +
"'s parameters saved to file.");
} // for dev_id in local_gpu_count
} // for worker in worker_num
key_stream.close();
values_stream.close();
} else { // non-cheif worker
for (size_t worker = 1; worker < worker_num; worker++) {
if (worker == worker_id) { /*sub worker send valid data to cheif worker*/
CK_NCCL(ncclGroupStart());
for (size_t dev_id = 0; dev_id < local_gpu_count; dev_id++) {
const size_t pair_count = count[dev_id];
const auto &local_gpu = resource_mgr_->get_local_gpu(dev_id);
const int32_t peer = 0 * local_gpu_count + dev_id;
CK_NCCL(ncclSend(d_hash_table_key[dev_id],
pair_count, ncclInt64,
/*peer=*/peer,
local_gpu->get_nccl(), local_gpu->get_stream()));
CK_NCCL(ncclSend(d_hash_table_value[dev_id],
pair_count * embedding_vector_size_,
ncclFloat32, /*peer=*/peer,
local_gpu->get_nccl(), local_gpu->get_stream()));
} // for dev_id in local_gpu_count
CK_NCCL(ncclGroupEnd());
MESSAGE("Worker: " + std::to_string(worker) + "'s data sent to cheif worker.");
} else { /*sub worker send dummy data to cheif worker*/
CK_NCCL(ncclGroupStart());
for (size_t dev_id = 0; dev_id < local_gpu_count; dev_id++) {
CK_NCCL(ncclSend(d_count[dev_id], 1, ncclUint64,
/*peer=*/0 * local_gpu_count + dev_id,
resource_mgr_->get_local_gpu(dev_id)->get_nccl(),
resource_mgr_->get_local_gpu(dev_id)->get_stream()));
}
CK_NCCL(ncclGroupEnd());
}
} // for worker in [1, worker_num)
}
// step 6: synchronize all workers
resource_mgr_->sync_all_workers();
// finnaly: release temp spaces.
for (size_t dev_id = 0; dev_id < local_gpu_count; dev_id++) {
const auto &local_gpu = resource_mgr_->get_local_gpu(dev_id);
device_context.set_device(local_gpu->get_local_device_id());
if (0 == worker_id && 0 == dev_id) {
CK_CUDA(cudaFree(d_global_max_count));
CK_CUDA(cudaFree(d_count_aggregation));
}
CK_CUDA(cudaFree(d_count[dev_id]));
CK_CUDA(cudaFreeHost(h_hash_table_key[dev_id]));
CK_CUDA(cudaFree(d_hash_table_key[dev_id]));
CK_CUDA(cudaFree(d_hash_table_value_index[dev_id]));
CK_CUDA(cudaFreeHost(h_hash_table_value[dev_id]));
CK_CUDA(cudaFree(d_hash_table_value[dev_id]));
CK_CUDA(cudaFree(d_dump_counter[dev_id]));
} // for dev_id in local_gpu_count
}
void RawParam::let_user_dump_to_file(const std::string filepath) {
user_->dump_to_file(filepath);
}
void RawParam::restore_from_file(const std::string filepath) {
const std::string key_filename = filepath + "/" + var_name_ + "_keys.file";
const std::string values_filename = filepath + "/" + var_name_ + "_values.file";
std::ifstream key_stream(key_filename, std::ios::binary | std::ios::in);
std::ifstream values_stream(values_filename, std::ios::binary | std::ios::in);
// step 1: check whether the number of content is consistent and valid.
key_stream.seekg(0, key_stream.end);
const size_t key_size_in_bytes = key_stream.tellg();
key_stream.seekg(0, key_stream.beg);
values_stream.seekg(0, values_stream.end);
const size_t values_size_in_bytes = values_stream.tellg();
values_stream.seekg(0, values_stream.beg);
if (key_size_in_bytes == 0 || values_size_in_bytes == 0)
throw std::runtime_error(ErrorBase + "Invalid files, several file(s) size is 0 bytes, where "
"key: " + std::to_string(key_size_in_bytes) + "bytes, values: " +
std::to_string(values_size_in_bytes) + "bytes.");
if (key_size_in_bytes % sizeof(int64_t) != 0)
throw std::runtime_error(ErrorBase + "Invalid file stream for keys, because the count of "
"keys is not divisible by sizeof(int64).");
if (values_size_in_bytes % (sizeof(float) * embedding_vector_size_) != 0)
throw std::runtime_error(ErrorBase + "Invalid file stream for embedding values, because the "
"count of embedding values is not divisible by "
"sizeof(float) * embedding_vector_size.");
const size_t key_count = key_size_in_bytes / sizeof(int64_t);
const size_t values_count = values_size_in_bytes / (sizeof(float) * embedding_vector_size_);
if (key_count ^ values_count)
throw std::runtime_error(ErrorBase + "The count of key and values are not consistent, which are "
"key: " + std::to_string(key_count) + ", values: " +
std::to_string(values_count) + " respectively.");
// step 2: allocate temp spaces
std::shared_ptr<HugeCTR::GeneralBuffer2<HugeCTR::CudaHostAllocator>> host_buffer =
HugeCTR::GeneralBuffer2<HugeCTR::CudaHostAllocator>::create();
HugeCTR::Tensor2<int64_t> keys;
host_buffer->reserve({key_count}, &keys);
HugeCTR::Tensor2<float> embedding_values;
host_buffer->reserve({values_count, embedding_vector_size_}, &embedding_values);
host_buffer->allocate();
MESSAGE("Allocated temporary pinned buffer for loading parameters.");
// step 3: read content from file to pinned memory
key_stream.read(reinterpret_cast<char *>(keys.get_ptr()), key_size_in_bytes);
values_stream.read(reinterpret_cast<char *>(embedding_values.get_ptr()), values_size_in_bytes);
key_stream.close();
values_stream.close();
// step 4: upload content to GPU memory
// because how to load parameters to each GPU is related to
// how will the embedding lookuper use those parameters.
// so that delegate this loading job to embedding lookuper
user_->restore_params(/*keys=*/Tensor2Wrapper<int64_t>::create(keys),
/*embedding_values=*/Tensor2Wrapper<float>::create(embedding_values),
/*num_total_keys=*/key_count);
// finnaly: synchronize all workers.
resource_mgr_->sync_all_workers();
}
void RawParam::let_user_restore_from_file(const std::string filepath) {
user_->restore_from_file(filepath);
}
void RawParam::load_embedding_values(const std::vector<std::shared_ptr<Tensor>>& tensor_list) {
// step 1: allocate temp spaces
size_t total_key_count = 0;
for (const auto &tensor : tensor_list) {
total_key_count += (tensor->get_num_elements() / embedding_vector_size_);
} // iter on tensors
std::shared_ptr<HugeCTR::GeneralBuffer2<HugeCTR::CudaHostAllocator>> host_buffer =
HugeCTR::GeneralBuffer2<HugeCTR::CudaHostAllocator>::create();
Tensor2<int64_t> keys;
host_buffer->reserve({total_key_count}, &keys);
Tensor2<float> embedding_values;
host_buffer->reserve({total_key_count, embedding_vector_size_}, &embedding_values);
host_buffer->allocate();
MESSAGE("Allocated temporary buffer for loading embedding values.");
// step 2: generate keys and copy content to temp spaces.
for (size_t i = 0; i < total_key_count; i++) keys.get_ptr()[i] = static_cast<int64_t>(i);
size_t offset = 0;
for (const auto &tensor : tensor_list) {
std::memcpy(embedding_values.get_ptr() + offset,
tensor->GetPtrWithType<float>(),
tensor->get_size_in_bytes());
offset += tensor->get_num_elements();
} // iter on tensors
if (embedding_values.get_num_elements() != offset)
throw std::runtime_error(ErrorBase + "Error happened in copy tensor content.");
// step 3: upload content to GPU memory
// because how to load parameters to each GPU is related to
// how will the embedding lookuper use those parameters.
// so delegate this loading job to embedding lookuper
user_->restore_params(/*keys=*/Tensor2Wrapper<int64_t>::create(keys),
/*embedding_values=*/Tensor2Wrapper<float>::create(embedding_values),
/*num_total_keys=*/total_key_count);
resource_mgr_->sync_all_workers();
}
void RawParam::let_user_load_embedding_values(const std::vector<std::shared_ptr<Tensor>>& tensor_list) {
user_->load_embedding_values(tensor_list);
}
} // namespace SparseOperationKit | 52.29666 | 126 | 0.630039 | [
"shape",
"vector"
] |
081ef68e0915eeb36be26943e21f7cc58625a240 | 19,064 | cpp | C++ | Programs/ResourceEditor/Classes/PropertyPanel/Private/PropertyModelExt.cpp | stinvi/dava.engine | 2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e | [
"BSD-3-Clause"
] | 26 | 2018-09-03T08:48:22.000Z | 2022-02-14T05:14:50.000Z | Programs/ResourceEditor/Classes/PropertyPanel/Private/PropertyModelExt.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | null | null | null | Programs/ResourceEditor/Classes/PropertyPanel/Private/PropertyModelExt.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | 45 | 2018-05-11T06:47:17.000Z | 2022-02-03T11:30:55.000Z | #include "Classes/PropertyPanel/PropertyModelExt.h"
#include "Classes/PropertyPanel/PropertyPanelCommon.h"
#include "Classes/Qt/DockParticleEditor/TimeLineWidget.h"
#include <REPlatform/Commands/AddComponentCommand.h>
#include <REPlatform/Commands/KeyedArchiveCommand.h>
#include <REPlatform/Commands/SetFieldValueCommand.h>
#include <REPlatform/DataNodes/SceneData.h>
#include <TArc/Controls/ComboBox.h>
#include <TArc/Controls/CommonStrings.h>
#include <TArc/Controls/PropertyPanel/PropertyModelExtensions.h>
#include <TArc/Controls/PropertyPanel/PropertyPanelMeta.h>
#include <TArc/Controls/Widget.h>
#include <TArc/Utils/QtConnections.h>
#include <TArc/Utils/ReflectionHelpers.h>
#include <TArc/Utils/Utils.h>
#include <TArc/Utils/ReflectedPairsVector.h>
#include <Base/Any.h>
#include <Base/FastName.h>
#include <Base/StaticSingleton.h>
#include <Base/TypeInheritance.h>
#include <Engine/PlatformApiQt.h>
#include <Entity/ComponentManager.h>
#include <Entity/Component.h>
#include <FileSystem/KeyedArchive.h>
#include <Functional/Function.h>
#include <Reflection/ReflectedMeta.h>
#include <Reflection/ReflectedTypeDB.h>
#include <Reflection/Reflection.h>
#include <Scene3D/Entity.h>
#include <QHBoxLayout>
#include <QPalette>
#include <QToolButton>
namespace PropertyModelExtDetails
{
using namespace DAVA;
struct ComponentCreator : public StaticSingleton<ComponentCreator>
{
const ReflectedType* componentType = nullptr;
};
const char* chooseComponentTypeString = "Choose component type for Add";
struct TypeInitializer : public StaticSingleton<ComponentCreator>
{
using TypePair = std::pair<String, const ReflectedType*>;
struct TypePairLess
{
bool operator()(const TypePair& p1, const TypePair& p2) const
{
if (p1.second == nullptr && p2.second == nullptr)
{
return false;
}
if (p2.second == nullptr)
{
return false;
}
if (p1.second == nullptr)
{
return true;
}
return p1.first < p2.first;
}
};
TypeInitializer()
{
AnyCast<TypePair, String>::Register([](const Any& v) -> String
{
return v.Get<TypePair>().first;
});
types.emplace(String(chooseComponentTypeString), nullptr);
InitDerivedTypes(Type::Instance<DAVA::Component>());
}
void InitDerivedTypes(const Type* type)
{
const TypeInheritance* inheritance = type->GetInheritance();
Vector<TypeInheritance::Info> derivedTypes = inheritance->GetDerivedTypes();
for (const TypeInheritance::Info& derived : derivedTypes)
{
const ReflectedType* refType = ReflectedTypeDB::GetByType(derived.type);
if (refType == nullptr)
{
continue;
}
const std::unique_ptr<ReflectedMeta>& meta = refType->GetStructure()->meta;
if (meta != nullptr && (nullptr != meta->GetMeta<M::CantBeCreatedManualyComponent>()))
{
continue;
}
if (refType->GetCtor(derived.type->Pointer()) != nullptr)
{
types.emplace(refType->GetPermanentName(), refType);
}
InitDerivedTypes(derived.type);
}
}
Set<TypePair, TypePairLess> types;
};
class ComponentCreatorComponentValue : public BaseComponentValue
{
public:
ComponentCreatorComponentValue() = default;
bool IsSpannedControl() const override
{
return true;
}
protected:
Any GetMultipleValue() const override
{
return DAVA::Any();
}
bool IsValidValueToSet(const Any& newValue, const Any& currentValue) const override
{
return false;
}
ControlProxy* CreateEditorWidget(QWidget* parent, const Reflection& model, DataWrappersProcessor* wrappersProcessor) override
{
Widget* w = new Widget(parent);
QHBoxLayout* layout = new QHBoxLayout();
layout->setMargin(0);
layout->setSpacing(2);
w->SetLayout(layout);
ComponentCreatorComponentValue* nonConstThis = const_cast<ComponentCreatorComponentValue*>(this);
nonConstThis->toolButton = new QToolButton(w->ToWidgetCast());
nonConstThis->toolButton->setIcon(SharedIcon(":/QtIcons/addcomponent.png"));
nonConstThis->toolButton->setIconSize(toolButtonIconSize);
nonConstThis->toolButton->setToolTip(QStringLiteral("Add component"));
nonConstThis->toolButton->setAutoRaise(true);
layout->addWidget(nonConstThis->toolButton.data());
nonConstThis->connections.AddConnection(nonConstThis->toolButton.data(), &QToolButton::clicked, MakeFunction(nonConstThis, &ComponentCreatorComponentValue::AddComponent));
ComboBox::Params params(GetAccessor(), GetUI(), GetWindowKey());
params.fields[ComboBox::Fields::Enumerator] = "types";
params.fields[ComboBox::Fields::Value] = "currentType";
w->AddControl(new ComboBox(params, wrappersProcessor, model, w->ToWidgetCast()));
return w;
}
private:
TypeInitializer::TypePair GetType() const
{
const ReflectedType* type = ComponentCreator::Instance()->componentType;
if (type == nullptr)
{
toolButton->setEnabled(false);
return TypeInitializer::TypePair(String(chooseComponentTypeString), nullptr);
}
toolButton->setEnabled(true);
return TypeInitializer::TypePair(type->GetPermanentName(), type);
}
void SetType(const TypeInitializer::TypePair& type)
{
toolButton->setEnabled(type.second != nullptr);
ComponentCreator::Instance()->componentType = type.second;
}
const Set<TypeInitializer::TypePair, TypeInitializer::TypePairLess>& GetTypes() const
{
static TypeInitializer t;
return t.types;
}
void AddComponent()
{
ComponentCreator* componentCreator = ComponentCreator::Instance();
const ReflectedType* componentType = componentCreator->componentType;
DVASSERT(componentType != nullptr);
String description = Format("Add component: %s", componentType->GetPermanentName().c_str());
ModifyExtension::MultiCommandInterface cmdInterface = GetModifyInterface()->GetMultiCommandInterface(description, static_cast<uint32>(nodes.size()));
for (std::shared_ptr<PropertyNode>& node : nodes)
{
Entity* entity = node->field.ref.GetValueObject().GetPtr<Entity>();
Any newComponent = componentType->CreateObject(ReflectedType::CreatePolicy::ByPointer);
Component* component = newComponent.Cast<Component*>();
cmdInterface.Exec(std::make_unique<DAVA::AddComponentCommand>(entity, component));
}
componentCreator->componentType = nullptr;
}
DAVA_VIRTUAL_REFLECTION_IN_PLACE(ComponentCreatorComponentValue, DAVA::BaseComponentValue)
{
DAVA::ReflectionRegistrator<ComponentCreatorComponentValue>::Begin()
.Field("currentType", &ComponentCreatorComponentValue::GetType, &ComponentCreatorComponentValue::SetType)
.Field("types", &ComponentCreatorComponentValue::GetTypes, nullptr)
.End();
}
QPointer<QToolButton> toolButton;
QtConnections connections;
};
class ParticlePropertyLineComponentValue : public DAVA::BaseComponentValue
{
protected:
DAVA::Any GetMultipleValue() const override
{
return DAVA::Any();
}
bool IsValidValueToSet(const DAVA::Any& newValue, const DAVA::Any& currentValue) const override
{
DVASSERT(currentValue.IsEmpty() == false);
return true;
}
DAVA::ControlProxy* CreateEditorWidget(QWidget* parent, const DAVA::Reflection& model, DAVA::DataWrappersProcessor* wrappersProcessor) override
{
using namespace DAVA;
Widget* widget = new Widget(parent);
QHBoxLayout* layout = new QHBoxLayout();
widget->SetLayout(layout);
timeLineWidget = new TimeLineWidget(widget->ToWidgetCast());
timeLineWidget->setMinimumHeight(800);
connections.AddConnection(timeLineWidget, &TimeLineWidget::ValueChanged, MakeFunction(this, &ParticlePropertyLineComponentValue::OnWidgetDataChanged));
layout->addWidget(timeLineWidget);
UpdateValue();
wrapper.SetListener(nullptr);
wrapper = GetDataProcessor()->CreateWrapper([this](const DataContext*) {
return Reflection::Create(ReflectedObject(this));
},
nullptr);
wrapper.SetListener(&dummyListener);
widgetInited = false;
return widget;
}
bool IsSpannedControl() const override
{
return true;
}
private:
void OnWidgetDataChanged()
{
DAVA::PropLineWrapper<DAVA::float32> prop;
timeLineWidget->GetValue(0, prop.GetPropsPtr());
SetValue(prop.GetPropLine());
}
bool UpdateValueHack() const
{
const_cast<ParticlePropertyLineComponentValue*>(this)->UpdateValue();
return true;
}
void UpdateValue()
{
using namespace DAVA;
using PropKey = PropertyLine<float32>::PropertyKey;
auto isEqualFn = [](const Vector<PropKey>& keyCollection1, const Vector<PropKey>& keyCollection2)
{
if (keyCollection1.size() != keyCollection2.size())
{
return false;
}
for (size_t i = 0; i < keyCollection1.size(); ++i)
{
const PropKey& key1 = keyCollection1[i];
const PropKey& key2 = keyCollection2[i];
if (key1.t != key2.t || key1.value != key2.value)
{
return false;
}
}
return true;
};
DAVA::Any val = GetValue();
if (val.IsEmpty() == false)
{
RefPtr<PropertyLine<float32>> accVal = val.Cast<RefPtr<PropertyLine<float32>>>();
if (widgetInited == false || prevValues != accVal)
{
widgetInited = true;
prevValues = accVal;
timeLineWidget->Init(0, 1, false);
timeLineWidget->AddLine(0, PropLineWrapper<float32>(PropertyLineHelper::GetValueLine(accVal)).GetProps(), Qt::red, "Stripe edge size over life");
}
}
else
{
timeLineWidget->setEnabled(false);
}
}
class DummnyListener : public DAVA::DataListener
{
public:
void OnDataChanged(const DataWrapper& wrapper, const Vector<Any>& fields) override
{
}
};
bool widgetInited = false;
RefPtr<PropertyLine<float32>> prevValues;
QPointer<TimeLineWidget> timeLineWidget;
DAVA::QtConnections connections;
DAVA::DataWrapper wrapper;
DummnyListener dummyListener;
DAVA_VIRTUAL_REFLECTION_IN_PLACE(ParticlePropertyLineComponentValue, DAVA::BaseComponentValue)
{
DAVA::ReflectionRegistrator<ParticlePropertyLineComponentValue>::Begin()
.Field("updateValue", &ParticlePropertyLineComponentValue::UpdateValueHack, nullptr)
.End();
}
};
}
namespace DAVA
{
template <>
struct AnyCompare<PropertyModelExtDetails::TypeInitializer::TypePair>
{
static bool IsEqual(const Any& v1, const Any& v2)
{
using T = PropertyModelExtDetails::TypeInitializer::TypePair;
return v1.Get<T>().second == v2.Get<T>().second;
}
};
} // namespace DAVA
REModifyPropertyExtension::REModifyPropertyExtension(DAVA::ContextAccessor* accessor_)
: accessor(accessor_)
{
}
void REModifyPropertyExtension::ProduceCommand(const DAVA::Reflection::Field& field, const DAVA::Any& newValue)
{
GetScene()->Exec(std::make_unique<DAVA::SetFieldValueCommand>(field, newValue));
}
void REModifyPropertyExtension::ProduceCommand(const std::shared_ptr<DAVA::PropertyNode>& node, const DAVA::Any& newValue)
{
std::shared_ptr<DAVA::PropertyNode> parent = node->parent.lock();
DVASSERT(parent != nullptr);
if (parent->cachedValue.CanCast<DAVA::KeyedArchive*>())
{
DAVA::String key = node->field.key.Cast<DAVA::String>();
DAVA::KeyedArchive* archive = parent->cachedValue.Cast<DAVA::KeyedArchive*>();
DVASSERT(archive != nullptr);
if (archive != nullptr)
{
DVASSERT(archive->Count(key) > 0);
DAVA::VariantType* currentValue = archive->GetVariant(key);
DVASSERT(currentValue != nullptr);
DAVA::VariantType value = DAVA::PrepareValueForKeyedArchive(newValue, currentValue->GetType());
DVASSERT(value.GetType() != DAVA::VariantType::TYPE_NONE);
GetScene()->Exec(std::make_unique<DAVA::KeyeadArchiveSetValueCommand>(archive, node->field.key.Cast<DAVA::String>(), value));
}
}
else
{
ProduceCommand(node->field, newValue);
}
}
void REModifyPropertyExtension::Exec(std::unique_ptr<DAVA::Command>&& command)
{
GetScene()->Exec(std::move(command));
}
void REModifyPropertyExtension::EndBatch()
{
GetScene()->EndBatch();
}
void REModifyPropertyExtension::BeginBatch(const DAVA::String& text, DAVA::uint32 commandCount)
{
GetScene()->BeginBatch(text, commandCount);
}
DAVA::SceneEditor2* REModifyPropertyExtension::GetScene() const
{
using namespace DAVA;
DataContext* ctx = accessor->GetActiveContext();
DVASSERT(ctx != nullptr);
SceneData* data = ctx->GetData<SceneData>();
DVASSERT(data != nullptr);
return data->GetScene().Get();
}
void EntityChildCreator::ExposeChildren(const std::shared_ptr<DAVA::PropertyNode>& parent, DAVA::Vector<std::shared_ptr<DAVA::PropertyNode>>& children) const
{
using namespace DAVA;
if (parent->propertyType == PropertyPanel::AddComponentProperty)
{
return;
}
if (parent->propertyType == PropertyNode::SelfRoot &&
parent->cachedValue.GetType() == DAVA::Type::Instance<DAVA::Entity*>())
{
DAVA::Reflection::Field f(Any("Entity"), Reflection(parent->field.ref), nullptr);
std::shared_ptr<PropertyNode> entityNode = allocator->CreatePropertyNode(parent, std::move(f), -1, PropertyNode::GroupProperty);
children.push_back(entityNode);
{
Entity* entity = parent->field.ref.GetValueObject().GetPtr<Entity>();
ComponentManager* cm = GetEngineContext()->componentManager;
for (const Type* type : cm->GetRegisteredSceneComponents())
{
uint32 countOftype = entity->GetComponentCount(type);
for (uint32 componentIndex = 0; componentIndex < countOftype; ++componentIndex)
{
Component* component = entity->GetComponent(type, componentIndex);
Reflection ref = Reflection::Create(ReflectedObject(component));
String permanentName = GetValueReflectedType(ref)->GetPermanentName();
DAVA::Reflection::Field f(permanentName, Reflection(ref), nullptr);
if (CanBeExposed(f))
{
std::shared_ptr<PropertyNode> node = allocator->CreatePropertyNode(parent, std::move(f), cm->GetSortedComponentId(type), PropertyNode::RealProperty);
node->idPostfix = FastName(Format("%u", componentIndex));
children.push_back(node);
}
}
}
Reflection::Field addComponentField;
addComponentField.key = "Add Component";
addComponentField.ref = parent->field.ref;
std::shared_ptr<PropertyNode> addComponentNode = allocator->CreatePropertyNode(parent, std::move(addComponentField), DAVA::PropertyNode::InvalidSortKey - 1, PropertyPanel::AddComponentProperty);
children.push_back(addComponentNode);
}
}
else if (parent->propertyType == PropertyNode::GroupProperty &&
parent->cachedValue.GetType() == DAVA::Type::Instance<DAVA::Entity*>())
{
DAVA::ForEachField(parent->field.ref, [&](Reflection::Field&& field)
{
if (field.ref.GetValueType() != DAVA::Type::Instance<DAVA::Vector<DAVA::Component*>>() && CanBeExposed(field))
{
children.push_back(allocator->CreatePropertyNode(parent, std::move(field), static_cast<int32>(children.size()), PropertyNode::RealProperty));
}
});
}
else
{
ChildCreatorExtension::ExposeChildren(parent, children);
}
}
std::unique_ptr<DAVA::BaseComponentValue> EntityEditorCreator::GetEditor(const std::shared_ptr<const DAVA::PropertyNode>& node) const
{
if (node->propertyType == PropertyPanel::AddComponentProperty)
{
std::unique_ptr<DAVA::BaseComponentValue> editor = std::make_unique<PropertyModelExtDetails::ComponentCreatorComponentValue>();
DAVA::BaseComponentValue::Style style;
style.fontBold = true;
style.fontItalic = true;
style.fontColor = QPalette::ButtonText;
style.bgColor = QPalette::AlternateBase;
editor->SetStyle(style);
return std::unique_ptr<DAVA::BaseComponentValue>(std::move(editor));
}
const DAVA::Type* valueType = node->cachedValue.GetType();
static const DAVA::Type* componentType = DAVA::Type::Instance<DAVA::Component*>();
static const DAVA::Type* entityType = DAVA::Type::Instance<DAVA::Entity*>();
if ((node->propertyType == DAVA::PropertyNode::GroupProperty && valueType == entityType)
|| (DAVA::TypeInheritance::CanCast(node->cachedValue.GetType(), DAVA::Type::Instance<DAVA::Component*>()) == true))
{
std::unique_ptr<DAVA::BaseComponentValue> editor = EditorComponentExtension::GetEditor(node);
DAVA::BaseComponentValue::Style style;
style.fontBold = true;
style.fontColor = QPalette::ButtonText;
style.bgColor = QPalette::AlternateBase;
editor->SetStyle(style);
return std::unique_ptr<DAVA::BaseComponentValue>(std::move(editor));
}
return EditorComponentExtension::GetEditor(node);
}
std::unique_ptr<DAVA::BaseComponentValue> ParticleForceCreator::GetEditor(const std::shared_ptr<const DAVA::PropertyNode>& node) const
{
using namespace DAVA;
using namespace PropertyModelExtDetails;
const DAVA::Type* valueType = node->cachedValue.GetType();
const Type* propertyLineType = Type::Instance<RefPtr<PropertyLine<float32>>>();
if (node->propertyType == DAVA::PropertyNode::RealProperty && valueType == propertyLineType)
{
return std::make_unique<ParticlePropertyLineComponentValue>();
}
return EditorComponentExtension::GetEditor(node);
}
| 36.037807 | 206 | 0.646664 | [
"vector",
"model"
] |
08213d7968e8fb47998da42dc10a1752f15f42b3 | 8,140 | cc | C++ | src/worker.cc | amchiclet/cloud-profiler-java | 4ce94fee4fafcb450f589c0989af844186e4588a | [
"Apache-2.0"
] | 23 | 2018-07-11T04:18:56.000Z | 2022-03-29T22:18:18.000Z | src/worker.cc | amchiclet/cloud-profiler-java | 4ce94fee4fafcb450f589c0989af844186e4588a | [
"Apache-2.0"
] | 31 | 2018-07-11T01:53:10.000Z | 2022-03-15T11:06:09.000Z | src/worker.cc | amchiclet/cloud-profiler-java | 4ce94fee4fafcb450f589c0989af844186e4588a | [
"Apache-2.0"
] | 19 | 2018-07-11T00:40:11.000Z | 2022-01-26T00:13:27.000Z | // Copyright 2018 Google LLC
//
// 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 "src/worker.h"
#include "src/clock.h"
#include "src/profiler.h"
#include "src/throttler_api.h"
#include "src/throttler_timed.h"
#include "google/devtools/cloudprofiler/v2/profiler.grpc.pb.h"
#include "third_party/javaprofiler/heap_sampler.h"
DEFINE_bool(cprof_enabled, true,
"when unset, unconditionally disable the profiling");
DEFINE_string(
cprof_profile_filename, "",
"when set to a path, store profiles locally at the specified prefix");
DEFINE_int32(cprof_cpu_sampling_period_msec, 10,
"sampling period for CPU time profiling, in milliseconds");
DEFINE_int32(cprof_wall_sampling_period_msec, 100,
"sampling period for wall time profiling, in milliseconds");
namespace cloud {
namespace profiler {
namespace {
namespace api = google::devtools::cloudprofiler::v2;
std::string JavaVersion(JNIEnv *jni) {
const std::string kUnknownVersion = "unknown_version";
jclass system_class = jni->FindClass("java/lang/System");
if (system_class == nullptr) {
return kUnknownVersion;
}
jmethodID get_property_method = jni->GetStaticMethodID(
system_class, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
if (get_property_method == nullptr) {
return kUnknownVersion;
}
jstring jstr = reinterpret_cast<jstring>(jni->CallStaticObjectMethod(
system_class, get_property_method, jni->NewStringUTF("java.version")));
if (jstr == nullptr) {
return kUnknownVersion;
}
// Copy the returned value and release the memory allocated by JNI.
const char *s = jni->GetStringUTFChars(jstr, nullptr);
std::string ret = std::string(s);
jni->ReleaseStringUTFChars(jstr, s);
return ret;
}
} // namespace
std::atomic<bool> Worker::enabled_;
void Worker::Start(JNIEnv *jni) {
jclass cls = jni->FindClass("java/lang/Thread");
jmethodID constructor = jni->GetMethodID(cls, "<init>", "()V");
jobject thread = jni->NewGlobalRef(jni->NewObject(cls, constructor));
if (thread == nullptr) {
LOG(ERROR) << "Failed to construct cloud profiler worker thread";
return;
}
std::string java_version = JavaVersion(jni);
LOG(INFO) << "Java version: " << java_version;
std::vector<google::devtools::cloudprofiler::v2::ProfileType> types = {
api::CPU, api::WALL};
if (google::javaprofiler::HeapMonitor::Enabled()) {
LOG(INFO) << "Heap allocation sampling supported for this JDK";
types.push_back(api::HEAP);
}
// Initialize the throttler here rather in the constructor, since the
// constructor is invoked too early, before the heap profiler is initialized.
throttler_ = FLAGS_cprof_profile_filename.empty()
? std::unique_ptr<Throttler>(
new APIThrottler(types, "java", java_version))
: std::unique_ptr<Throttler>(
new TimedThrottler(FLAGS_cprof_profile_filename));
// Pass 'this' as the arg to access members from the worker thread.
jvmtiError err = jvmti_->RunAgentThread(thread, ProfileThread, this,
JVMTI_THREAD_MIN_PRIORITY);
if (err) {
LOG(ERROR) << "Failed to start cloud profiler worker thread";
return;
}
enabled_ = FLAGS_cprof_enabled;
}
void Worker::Stop() {
stopping_.store(true, std::memory_order_release);
// Close the throttler which will initiate cancellation of WaitNext / Upload.
throttler_->Close();
// Wait till the worker thread is done.
std::lock_guard<std::mutex> lock(mutex_);
}
namespace {
std::string Collect(Profiler *p, JNIEnv *env,
google::javaprofiler::NativeProcessInfo *native_info) {
const char *profile_type = p->ProfileType();
if (!p->Collect()) {
LOG(ERROR) << "Failure: Could not collect " << profile_type << " profile";
return "";
}
native_info->Refresh();
return p->SerializeProfile(env, *native_info);
}
class JNILocalFrame {
public:
explicit JNILocalFrame(JNIEnv *jni_env) : jni_env_(jni_env) {
// Put 100, it doesn't really matter: new spec implementations don't care.
jni_env_->PushLocalFrame(100);
}
~JNILocalFrame() { jni_env_->PopLocalFrame(nullptr); }
// Not copyable or movable.
JNILocalFrame(const JNILocalFrame &) = delete;
JNILocalFrame &operator=(const JNILocalFrame &) = delete;
private:
JNIEnv *jni_env_;
};
} // namespace
void Worker::EnableProfiling() { enabled_ = true; }
void Worker::DisableProfiling() { enabled_ = false; }
void Worker::ProfileThread(jvmtiEnv *jvmti_env, JNIEnv *jni_env, void *arg) {
Worker *w = static_cast<Worker *>(arg);
std::lock_guard<std::mutex> lock(w->mutex_);
google::javaprofiler::NativeProcessInfo n("/proc/self/maps");
while (w->throttler_->WaitNext()) {
if (w->stopping_) {
// The worker is exiting.
break;
}
if (!enabled_) {
// Skip the collection and upload steps when profiling is disabled.
continue;
}
// There are a number of JVMTI functions the agent uses that return
// local references. Normally, local references are freed when a JNI
// call returns to Java. E.g. in the internal /profilez profiler
// those would get freed when the C++ code returns back to the request
// handler. But in case of the cloud agent the agent thread never exits
// and so the local references keep accumulating. Adding an explicit
// local frame around each profiling iteration fixes this.
// Note: normally the various JNIHandles are properly lifetime managed
// now (via b/133409114) and there should be no leaks; but leaving this in
// so that, if ever JNI handle leaks do happen again, this will release the
// handles automatically.
JNILocalFrame local_frame(jni_env);
std::string profile;
std::string pt = w->throttler_->ProfileType();
if (pt == kTypeCPU) {
CPUProfiler p(w->jvmti_, w->threads_, w->throttler_->DurationNanos(),
FLAGS_cprof_cpu_sampling_period_msec * kNanosPerMilli);
profile = Collect(&p, jni_env, &n);
} else if (pt == kTypeWall) {
// Note that the requested sampling period for the wall profiling may be
// increased if the number of live threads is too large.
WallProfiler p(w->jvmti_, w->threads_, w->throttler_->DurationNanos(),
FLAGS_cprof_wall_sampling_period_msec * kNanosPerMilli);
profile = Collect(&p, jni_env, &n);
} else if (pt == kTypeHeap) {
if (!google::javaprofiler::HeapMonitor::Enabled()) {
LOG(WARNING) << "Asked for a heap sampler but it is disabled";
continue;
}
// Note: we do not force GC here, instead we rely on what was seen as
// still live at the last GC; this means that technically:
// - Some objects might be dead now.
// - Some other objects might be sampled but not show up yet.
// On the flip side, this allows the profile collection to not provoke a
// GC.
perftools::profiles::Builder::Marshal(
*google::javaprofiler::HeapMonitor::GetHeapProfiles(
jni_env, false /* force_gc */),
&profile);
} else {
LOG(ERROR) << "Unknown profile type '" << pt << "', skipping the upload";
continue;
}
if (profile.empty()) {
LOG(ERROR) << "No profile bytes collected, skipping the upload";
continue;
}
if (!w->throttler_->Upload(profile)) {
LOG(ERROR) << "Error on profile upload, discarding the profile";
}
}
LOG(INFO) << "Exiting the profiling loop";
}
} // namespace profiler
} // namespace cloud
| 36.666667 | 79 | 0.678256 | [
"vector"
] |
083396895ab1357bf57327af6dfd4d290f6b3372 | 1,738 | cpp | C++ | src/rfx/rendering/MaterialNode.cpp | rfruesmer/rfx | 96c15a11ee8e2192c9d2ff233924eee884835f17 | [
"MIT"
] | null | null | null | src/rfx/rendering/MaterialNode.cpp | rfruesmer/rfx | 96c15a11ee8e2192c9d2ff233924eee884835f17 | [
"MIT"
] | null | null | null | src/rfx/rendering/MaterialNode.cpp | rfruesmer/rfx | 96c15a11ee8e2192c9d2ff233924eee884835f17 | [
"MIT"
] | null | null | null | #include "rfx/pch.h"
#include "rfx/rendering/MaterialNode.h"
#include <utility>
using namespace rfx;
using namespace std;
// ---------------------------------------------------------------------------------------------------------------------
MaterialNode::MaterialNode(
const MaterialPtr& material,
const MaterialShaderPtr& shader,
const ModelPtr& model)
: material(material),
shader(shader)
{
add(material, model);
}
// ---------------------------------------------------------------------------------------------------------------------
void MaterialNode::add(
const MaterialPtr& material,
const ModelPtr& model)
{
for (const auto& mesh : model->getMeshes())
{
MeshNode childNode(mesh, material, shader);
if (!childNode.isEmpty()) {
childNodes.push_back(childNode);
}
}
}
// ---------------------------------------------------------------------------------------------------------------------
void MaterialNode::record(const CommandBufferPtr& commandBuffer) const
{
bindMaterial(commandBuffer, shader);
for (const auto& meshNode : childNodes) {
meshNode.record(commandBuffer);
}
}
// ---------------------------------------------------------------------------------------------------------------------
void MaterialNode::bindMaterial(
const CommandBufferPtr& commandBuffer,
const MaterialShaderPtr& shader) const
{
commandBuffer->bindDescriptorSet(
VK_PIPELINE_BIND_POINT_GRAPHICS,
shader->getPipelineLayout(),
2,
material->getDescriptorSet());
}
// ---------------------------------------------------------------------------------------------------------------------
| 28.032258 | 120 | 0.435558 | [
"mesh",
"model"
] |
083738d3746fe8445de61b3a80fa2cb8b204fd1a | 27,442 | cpp | C++ | B2G/system/media/wilhelm/src/android/MediaPlayer_to_android.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/system/media/wilhelm/src/android/MediaPlayer_to_android.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/system/media/wilhelm/src/android/MediaPlayer_to_android.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /*
* Copyright (C) 2010 The Android Open Source Project
*
* 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 "sles_allinclusive.h"
#include "utils/RefBase.h"
#include "android_prompts.h"
// LocAVPlayer and StreamPlayer derive from GenericMediaPlayer,
// so no need to #include "android_GenericMediaPlayer.h"
#include "android_LocAVPlayer.h"
#include "android_StreamPlayer.h"
//-----------------------------------------------------------------------------
static void player_handleMediaPlayerEventNotifications(int event, int data1, int data2, void* user)
{
// FIXME This code is derived from similar code in sfplayer_handlePrefetchEvent. The two
// versions are quite similar, but still different enough that they need to be separate.
// At some point they should be re-factored and merged if feasible.
// As with other OpenMAX AL implementation code, this copy mostly uses SL_ symbols
// rather than XA_ unless the difference is significant.
if (NULL == user) {
return;
}
CMediaPlayer* mp = (CMediaPlayer*) user;
if (!android::CallbackProtector::enterCbIfOk(mp->mCallbackProtector)) {
// it is not safe to enter the callback (the media player is about to go away)
return;
}
union {
char c[sizeof(int)];
int i;
} u;
u.i = event;
SL_LOGV("player_handleMediaPlayerEventNotifications(event='%c%c%c%c' (%d), data1=%d, data2=%d, "
"user=%p) from AVPlayer", u.c[3], u.c[2], u.c[1], u.c[0], event, data1, data2, user);
switch(event) {
case android::GenericPlayer::kEventPrepared: {
SL_LOGV("Received AVPlayer::kEventPrepared for CMediaPlayer %p", mp);
// assume no callback
slPrefetchCallback callback = NULL;
void* callbackPContext = NULL;
object_lock_exclusive(&mp->mObject);
// mark object as prepared; same state is used for successfully or unsuccessful prepare
mp->mAndroidObjState = ANDROID_READY;
// AVPlayer prepare() failed prefetching, there is no event in XAPrefetchStatus to
// indicate a prefetch error, so we signal it by sending simulataneously two events:
// - SL_PREFETCHEVENT_FILLLEVELCHANGE with a level of 0
// - SL_PREFETCHEVENT_STATUSCHANGE with a status of SL_PREFETCHSTATUS_UNDERFLOW
if (PLAYER_SUCCESS != data1 && IsInterfaceInitialized(&mp->mObject, MPH_XAPREFETCHSTATUS)) {
mp->mPrefetchStatus.mLevel = 0;
mp->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
if (!(~mp->mPrefetchStatus.mCallbackEventsMask &
(SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE))) {
callback = mp->mPrefetchStatus.mCallback;
callbackPContext = mp->mPrefetchStatus.mContext;
}
}
object_unlock_exclusive(&mp->mObject);
// callback with no lock held
if (NULL != callback) {
(*callback)(&mp->mPrefetchStatus.mItf, callbackPContext,
SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);
}
break;
}
case android::GenericPlayer::kEventHasVideoSize: {
SL_LOGV("Received AVPlayer::kEventHasVideoSize (%d,%d) for CMediaPlayer %p",
data1, data2, mp);
object_lock_exclusive(&mp->mObject);
// remove an existing video info entry (here we only have one video stream)
for(size_t i=0 ; i < mp->mStreamInfo.mStreamInfoTable.size() ; i++) {
if (XA_DOMAINTYPE_VIDEO == mp->mStreamInfo.mStreamInfoTable.itemAt(i).domain) {
mp->mStreamInfo.mStreamInfoTable.removeAt(i);
break;
}
}
// update the stream information with a new video info entry
StreamInfo streamInfo;
streamInfo.domain = XA_DOMAINTYPE_VIDEO;
streamInfo.videoInfo.codecId = 0;// unknown, we don't have that info FIXME
streamInfo.videoInfo.width = (XAuint32)data1;
streamInfo.videoInfo.height = (XAuint32)data2;
streamInfo.videoInfo.bitRate = 0;// unknown, we don't have that info FIXME
streamInfo.videoInfo.frameRate = 0;
streamInfo.videoInfo.duration = XA_TIME_UNKNOWN;
StreamInfo &contInfo = mp->mStreamInfo.mStreamInfoTable.editItemAt(0);
contInfo.containerInfo.numStreams = 1;
ssize_t index = mp->mStreamInfo.mStreamInfoTable.add(streamInfo);
xaStreamEventChangeCallback callback = mp->mStreamInfo.mCallback;
void* callbackPContext = mp->mStreamInfo.mContext;
object_unlock_exclusive(&mp->mObject);
// enqueue notification (outside of lock) that the stream information has been updated
if ((NULL != callback) && (index >= 0)) {
#ifndef USE_ASYNCHRONOUS_STREAMCBEVENT_PROPERTYCHANGE_CALLBACK
(*callback)(&mp->mStreamInfo.mItf, XA_STREAMCBEVENT_PROPERTYCHANGE /*eventId*/,
1 /*streamIndex, only one stream supported here, 0 is reserved*/,
NULL /*pEventData, always NULL in OpenMAX AL 1.0.1*/,
callbackPContext /*pContext*/);
#else
SLresult res = EnqueueAsyncCallback_piipp(mp, callback,
/*p1*/ &mp->mStreamInfo.mItf,
/*i1*/ XA_STREAMCBEVENT_PROPERTYCHANGE /*eventId*/,
/*i2*/ 1 /*streamIndex, only one stream supported here, 0 is reserved*/,
/*p2*/ NULL /*pEventData, always NULL in OpenMAX AL 1.0.1*/,
/*p3*/ callbackPContext /*pContext*/);
LOGW_IF(SL_RESULT_SUCCESS != res,
"Callback %p(%p, XA_STREAMCBEVENT_PROPERTYCHANGE, 1, NULL, %p) dropped",
callback, &mp->mStreamInfo.mItf, callbackPContext);
#endif
}
break;
}
case android::GenericPlayer::kEventEndOfStream: {
SL_LOGV("Received AVPlayer::kEventEndOfStream for CMediaPlayer %p", mp);
object_lock_exclusive(&mp->mObject);
// should be xaPlayCallback but we're sharing the itf between SL and AL
slPlayCallback playCallback = NULL;
void * playContext = NULL;
// XAPlayItf callback or no callback?
if (mp->mPlay.mEventFlags & XA_PLAYEVENT_HEADATEND) {
playCallback = mp->mPlay.mCallback;
playContext = mp->mPlay.mContext;
}
mp->mPlay.mState = XA_PLAYSTATE_PAUSED;
object_unlock_exclusive(&mp->mObject);
// enqueue callback with no lock held
if (NULL != playCallback) {
#ifndef USE_ASYNCHRONOUS_PLAY_CALLBACK
(*playCallback)(&mp->mPlay.mItf, playContext, XA_PLAYEVENT_HEADATEND);
#else
SLresult res = EnqueueAsyncCallback_ppi(mp, playCallback, &mp->mPlay.mItf, playContext,
XA_PLAYEVENT_HEADATEND);
LOGW_IF(SL_RESULT_SUCCESS != res,
"Callback %p(%p, %p, SL_PLAYEVENT_HEADATEND) dropped", playCallback,
&mp->mPlay.mItf, playContext);
#endif
}
break;
}
case android::GenericPlayer::kEventChannelCount: {
SL_LOGV("kEventChannelCount channels = %d", data1);
object_lock_exclusive(&mp->mObject);
if (UNKNOWN_NUMCHANNELS == mp->mNumChannels && UNKNOWN_NUMCHANNELS != data1) {
mp->mNumChannels = data1;
android_Player_volumeUpdate(mp);
}
object_unlock_exclusive(&mp->mObject);
}
break;
case android::GenericPlayer::kEventPrefetchFillLevelUpdate: {
SL_LOGV("kEventPrefetchFillLevelUpdate");
if (!IsInterfaceInitialized(&mp->mObject, MPH_XAPREFETCHSTATUS)) {
break;
}
slPrefetchCallback callback = NULL;
void* callbackPContext = NULL;
// SLPrefetchStatusItf callback or no callback?
interface_lock_exclusive(&mp->mPrefetchStatus);
if (mp->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
callback = mp->mPrefetchStatus.mCallback;
callbackPContext = mp->mPrefetchStatus.mContext;
}
mp->mPrefetchStatus.mLevel = (SLpermille)data1;
interface_unlock_exclusive(&mp->mPrefetchStatus);
// callback with no lock held
if (NULL != callback) {
(*callback)(&mp->mPrefetchStatus.mItf, callbackPContext,
SL_PREFETCHEVENT_FILLLEVELCHANGE);
}
}
break;
case android::GenericPlayer::kEventPrefetchStatusChange: {
SL_LOGV("kEventPrefetchStatusChange");
if (!IsInterfaceInitialized(&mp->mObject, MPH_XAPREFETCHSTATUS)) {
break;
}
slPrefetchCallback callback = NULL;
void* callbackPContext = NULL;
// SLPrefetchStatusItf callback or no callback?
object_lock_exclusive(&mp->mObject);
if (mp->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_STATUSCHANGE) {
callback = mp->mPrefetchStatus.mCallback;
callbackPContext = mp->mPrefetchStatus.mContext;
}
if (data1 >= android::kStatusIntermediate) {
mp->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_SUFFICIENTDATA;
} else if (data1 < android::kStatusIntermediate) {
mp->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
}
object_unlock_exclusive(&mp->mObject);
// callback with no lock held
if (NULL != callback) {
(*callback)(&mp->mPrefetchStatus.mItf, callbackPContext, SL_PREFETCHEVENT_STATUSCHANGE);
}
}
break;
case android::GenericPlayer::kEventPlay: {
SL_LOGV("kEventPlay");
interface_lock_shared(&mp->mPlay);
slPlayCallback callback = mp->mPlay.mCallback;
void* callbackPContext = mp->mPlay.mContext;
interface_unlock_shared(&mp->mPlay);
if (NULL != callback) {
(*callback)(&mp->mPlay.mItf, callbackPContext, (SLuint32) data1); // SL_PLAYEVENT_HEAD*
}
}
break;
case android::GenericPlayer::kEventErrorAfterPrepare: {
SL_LOGV("kEventErrorAfterPrepare");
// assume no callback
slPrefetchCallback callback = NULL;
void* callbackPContext = NULL;
object_lock_exclusive(&mp->mObject);
if (IsInterfaceInitialized(&mp->mObject, MPH_XAPREFETCHSTATUS)) {
mp->mPrefetchStatus.mLevel = 0;
mp->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
if (!(~mp->mPrefetchStatus.mCallbackEventsMask &
(SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE))) {
callback = mp->mPrefetchStatus.mCallback;
callbackPContext = mp->mPrefetchStatus.mContext;
}
}
object_unlock_exclusive(&mp->mObject);
// FIXME there's interesting information in data1, but no API to convey it to client
SL_LOGE("Error after prepare: %d", data1);
// callback with no lock held
if (NULL != callback) {
(*callback)(&mp->mPrefetchStatus.mItf, callbackPContext,
SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);
}
}
break;
default: {
SL_LOGE("Received unknown event %d, data %d from AVPlayer", event, data1);
}
}
mp->mCallbackProtector->exitCb();
}
//-----------------------------------------------------------------------------
XAresult android_Player_checkSourceSink(CMediaPlayer *mp) {
XAresult result = XA_RESULT_SUCCESS;
const SLDataSource *pSrc = &mp->mDataSource.u.mSource;
const SLDataSink *pAudioSnk = &mp->mAudioSink.u.mSink;
// format check:
const SLuint32 sourceLocatorType = *(SLuint32 *)pSrc->pLocator;
const SLuint32 sourceFormatType = *(SLuint32 *)pSrc->pFormat;
const SLuint32 audioSinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator;
//const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSnk->pFormat;
// Source check
switch(sourceLocatorType) {
case XA_DATALOCATOR_ANDROIDBUFFERQUEUE: {
switch (sourceFormatType) {
case XA_DATAFORMAT_MIME: {
SLDataFormat_MIME *df_mime = (SLDataFormat_MIME *) pSrc->pFormat;
if (SL_CONTAINERTYPE_MPEG_TS != df_mime->containerType) {
SL_LOGE("Cannot create player with XA_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
"that is not fed MPEG-2 TS data");
return SL_RESULT_CONTENT_UNSUPPORTED;
}
} break;
default:
SL_LOGE("Cannot create player with XA_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
"without SL_DATAFORMAT_MIME format");
return XA_RESULT_CONTENT_UNSUPPORTED;
}
} break;
case XA_DATALOCATOR_URI: // intended fall-through
case XA_DATALOCATOR_ANDROIDFD:
break;
default:
SL_LOGE("Cannot create media player with data locator type 0x%x",
(unsigned) sourceLocatorType);
return SL_RESULT_PARAMETER_INVALID;
}// switch (locatorType)
// Audio sink check: only playback is supported here
switch(audioSinkLocatorType) {
case XA_DATALOCATOR_OUTPUTMIX:
break;
default:
SL_LOGE("Cannot create media player with audio sink data locator of type 0x%x",
(unsigned) audioSinkLocatorType);
return XA_RESULT_PARAMETER_INVALID;
}// switch (locaaudioSinkLocatorTypeorType)
return result;
}
//-----------------------------------------------------------------------------
XAresult android_Player_create(CMediaPlayer *mp) {
XAresult result = XA_RESULT_SUCCESS;
// FIXME verify data source
const SLDataSource *pDataSrc = &mp->mDataSource.u.mSource;
// FIXME verify audio data sink
const SLDataSink *pAudioSnk = &mp->mAudioSink.u.mSink;
// FIXME verify image data sink
const SLDataSink *pVideoSnk = &mp->mImageVideoSink.u.mSink;
XAuint32 sourceLocator = *(XAuint32 *)pDataSrc->pLocator;
switch(sourceLocator) {
// FIXME support Android simple buffer queue as well
case XA_DATALOCATOR_ANDROIDBUFFERQUEUE:
mp->mAndroidObjType = AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE;
break;
case XA_DATALOCATOR_URI: // intended fall-through
case SL_DATALOCATOR_ANDROIDFD:
mp->mAndroidObjType = AUDIOVIDEOPLAYER_FROM_URIFD;
break;
case XA_DATALOCATOR_ADDRESS: // intended fall-through
default:
SL_LOGE("Unable to create MediaPlayer for data source locator 0x%x", sourceLocator);
result = XA_RESULT_PARAMETER_INVALID;
break;
}
// FIXME duplicates an initialization also done by higher level
mp->mAndroidObjState = ANDROID_UNINITIALIZED;
mp->mStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE;
mp->mSessionId = android::AudioSystem::newAudioSessionId();
mp->mCallbackProtector = new android::CallbackProtector();
return result;
}
//-----------------------------------------------------------------------------
// FIXME abstract out the diff between CMediaPlayer and CAudioPlayer
XAresult android_Player_realize(CMediaPlayer *mp, SLboolean async) {
SL_LOGV("android_Player_realize_l(%p)", mp);
XAresult result = XA_RESULT_SUCCESS;
const SLDataSource *pDataSrc = &mp->mDataSource.u.mSource;
const SLuint32 sourceLocator = *(SLuint32 *)pDataSrc->pLocator;
AudioPlayback_Parameters ap_params;
ap_params.sessionId = mp->mSessionId;
ap_params.streamType = mp->mStreamType;
switch(mp->mAndroidObjType) {
case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: {
mp->mAVPlayer = new android::StreamPlayer(&ap_params, true /*hasVideo*/,
&mp->mAndroidBufferQueue, mp->mCallbackProtector);
mp->mAVPlayer->init(player_handleMediaPlayerEventNotifications, (void*)mp);
}
break;
case AUDIOVIDEOPLAYER_FROM_URIFD: {
mp->mAVPlayer = new android::LocAVPlayer(&ap_params, true /*hasVideo*/);
mp->mAVPlayer->init(player_handleMediaPlayerEventNotifications, (void*)mp);
switch (mp->mDataSource.mLocator.mLocatorType) {
case XA_DATALOCATOR_URI:
((android::LocAVPlayer*)mp->mAVPlayer.get())->setDataSource(
(const char*)mp->mDataSource.mLocator.mURI.URI);
break;
case XA_DATALOCATOR_ANDROIDFD: {
int64_t offset = (int64_t)mp->mDataSource.mLocator.mFD.offset;
((android::LocAVPlayer*)mp->mAVPlayer.get())->setDataSource(
(int)mp->mDataSource.mLocator.mFD.fd,
offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
(int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
(int64_t)mp->mDataSource.mLocator.mFD.length);
}
break;
default:
SL_LOGE("Invalid or unsupported data locator type %u for data source",
mp->mDataSource.mLocator.mLocatorType);
result = XA_RESULT_PARAMETER_INVALID;
}
}
break;
case INVALID_TYPE: // intended fall-through
default:
SL_LOGE("Unable to realize MediaPlayer, invalid internal Android object type");
result = XA_RESULT_PARAMETER_INVALID;
break;
}
if (XA_RESULT_SUCCESS == result) {
// if there is a video sink
if (XA_DATALOCATOR_NATIVEDISPLAY ==
mp->mImageVideoSink.mLocator.mLocatorType) {
ANativeWindow *nativeWindow = (ANativeWindow *)
mp->mImageVideoSink.mLocator.mNativeDisplay.hWindow;
// we already verified earlier that hWindow is non-NULL
assert(nativeWindow != NULL);
result = android_Player_setNativeWindow(mp, nativeWindow);
}
}
return result;
}
// Called with a lock on MediaPlayer, and blocks until safe to destroy
XAresult android_Player_preDestroy(CMediaPlayer *mp) {
SL_LOGV("android_Player_preDestroy(%p)", mp);
// Not yet clear why this order is important, but it reduces detected deadlocks
object_unlock_exclusive(&mp->mObject);
if (mp->mCallbackProtector != 0) {
mp->mCallbackProtector->requestCbExitAndWait();
}
object_lock_exclusive(&mp->mObject);
if (mp->mAVPlayer != 0) {
mp->mAVPlayer->preDestroy();
}
SL_LOGV("android_Player_preDestroy(%p) after mAVPlayer->preDestroy()", mp);
return XA_RESULT_SUCCESS;
}
//-----------------------------------------------------------------------------
XAresult android_Player_destroy(CMediaPlayer *mp) {
SL_LOGV("android_Player_destroy(%p)", mp);
mp->mAVPlayer.clear();
mp->mCallbackProtector.clear();
// explicit destructor
mp->mAVPlayer.~sp();
mp->mCallbackProtector.~sp();
return XA_RESULT_SUCCESS;
}
void android_Player_usePlayEventMask(CMediaPlayer *mp) {
if (mp->mAVPlayer != 0) {
IPlay *pPlayItf = &mp->mPlay;
mp->mAVPlayer->setPlayEvents((int32_t) pPlayItf->mEventFlags,
(int32_t) pPlayItf->mMarkerPosition, (int32_t) pPlayItf->mPositionUpdatePeriod);
}
}
XAresult android_Player_getDuration(IPlay *pPlayItf, XAmillisecond *pDurMsec) {
CMediaPlayer *avp = (CMediaPlayer *)pPlayItf->mThis;
switch (avp->mAndroidObjType) {
case AUDIOVIDEOPLAYER_FROM_URIFD: {
int dur = ANDROID_UNKNOWN_TIME;
if (avp->mAVPlayer != 0) {
avp->mAVPlayer->getDurationMsec(&dur);
}
if (dur == ANDROID_UNKNOWN_TIME) {
*pDurMsec = XA_TIME_UNKNOWN;
} else {
*pDurMsec = (XAmillisecond)dur;
}
} break;
case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
default:
*pDurMsec = XA_TIME_UNKNOWN;
break;
}
return XA_RESULT_SUCCESS;
}
XAresult android_Player_getPosition(IPlay *pPlayItf, XAmillisecond *pPosMsec) {
SL_LOGD("android_Player_getPosition()");
XAresult result = XA_RESULT_SUCCESS;
CMediaPlayer *avp = (CMediaPlayer *)pPlayItf->mThis;
switch (avp->mAndroidObjType) {
case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
case AUDIOVIDEOPLAYER_FROM_URIFD: {
int pos = ANDROID_UNKNOWN_TIME;
if (avp->mAVPlayer != 0) {
avp->mAVPlayer->getPositionMsec(&pos);
}
if (pos == ANDROID_UNKNOWN_TIME) {
*pPosMsec = 0;
} else {
*pPosMsec = (XAmillisecond)pos;
}
} break;
default:
// we shouldn't be here
assert(false);
break;
}
return result;
}
//-----------------------------------------------------------------------------
/**
* pre-condition: mp != NULL
*/
void android_Player_volumeUpdate(CMediaPlayer* mp)
{
android::GenericPlayer* avp = mp->mAVPlayer.get();
if (avp != NULL) {
float volumes[2];
// MediaPlayer does not currently support EffectSend or MuteSolo
android_player_volumeUpdate(volumes, &mp->mVolume, mp->mNumChannels, 1.0f, NULL);
float leftVol = volumes[0], rightVol = volumes[1];
avp->setVolume(leftVol, rightVol);
}
}
//-----------------------------------------------------------------------------
/**
* pre-condition: gp != 0
*/
XAresult android_Player_setPlayState(const android::sp<android::GenericPlayer> &gp,
SLuint32 playState,
AndroidObjectState* pObjState)
{
XAresult result = XA_RESULT_SUCCESS;
AndroidObjectState objState = *pObjState;
switch (playState) {
case SL_PLAYSTATE_STOPPED: {
SL_LOGV("setting AVPlayer to SL_PLAYSTATE_STOPPED");
gp->stop();
}
break;
case SL_PLAYSTATE_PAUSED: {
SL_LOGV("setting AVPlayer to SL_PLAYSTATE_PAUSED");
switch(objState) {
case ANDROID_UNINITIALIZED:
*pObjState = ANDROID_PREPARING;
gp->prepare();
break;
case ANDROID_PREPARING:
break;
case ANDROID_READY:
gp->pause();
break;
default:
SL_LOGE("Android object in invalid state");
break;
}
}
break;
case SL_PLAYSTATE_PLAYING: {
SL_LOGV("setting AVPlayer to SL_PLAYSTATE_PLAYING");
switch(objState) {
case ANDROID_UNINITIALIZED:
*pObjState = ANDROID_PREPARING;
gp->prepare();
// intended fall through
case ANDROID_PREPARING:
// intended fall through
case ANDROID_READY:
gp->play();
break;
default:
SL_LOGE("Android object in invalid state");
break;
}
}
break;
default:
// checked by caller, should not happen
break;
}
return result;
}
/**
* pre-condition: mp != NULL
*/
XAresult android_Player_seek(CMediaPlayer *mp, SLmillisecond posMsec) {
XAresult result = XA_RESULT_SUCCESS;
switch (mp->mAndroidObjType) {
case AUDIOVIDEOPLAYER_FROM_URIFD:
if (mp->mAVPlayer !=0) {
mp->mAVPlayer->seek(posMsec);
}
break;
case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
default: {
result = XA_RESULT_FEATURE_UNSUPPORTED;
}
}
return result;
}
/**
* pre-condition: mp != NULL
*/
XAresult android_Player_loop(CMediaPlayer *mp, SLboolean loopEnable) {
XAresult result = XA_RESULT_SUCCESS;
switch (mp->mAndroidObjType) {
case AUDIOVIDEOPLAYER_FROM_URIFD:
if (mp->mAVPlayer !=0) {
mp->mAVPlayer->loop(loopEnable);
}
break;
case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
default: {
result = XA_RESULT_FEATURE_UNSUPPORTED;
}
}
return result;
}
//-----------------------------------------------------------------------------
void android_Player_androidBufferQueue_clear_l(CMediaPlayer *mp) {
if ((mp->mAndroidObjType == AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE)
&& (mp->mAVPlayer != 0)) {
android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(mp->mAVPlayer.get());
splr->appClear_l();
}
}
void android_Player_androidBufferQueue_onRefilled_l(CMediaPlayer *mp) {
if ((mp->mAndroidObjType == AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE)
&& (mp->mAVPlayer != 0)) {
android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(mp->mAVPlayer.get());
splr->queueRefilled();
}
}
/*
* pre-conditions:
* mp != NULL
* mp->mAVPlayer != 0 (player is realized)
* nativeWindow can be NULL, but if NULL it is treated as an error
*/
SLresult android_Player_setNativeWindow(CMediaPlayer *mp, ANativeWindow *nativeWindow)
{
assert(mp != NULL);
assert(mp->mAVPlayer != 0);
if (nativeWindow == NULL) {
SL_LOGE("ANativeWindow is NULL");
return SL_RESULT_PARAMETER_INVALID;
}
SLresult result;
int err;
int value;
// this could crash if app passes in a bad parameter, but that's OK
err = (*nativeWindow->query)(nativeWindow, NATIVE_WINDOW_CONCRETE_TYPE, &value);
if (0 != err) {
SL_LOGE("Query NATIVE_WINDOW_CONCRETE_TYPE on ANativeWindow * %p failed; "
"errno %d", nativeWindow, err);
result = SL_RESULT_PARAMETER_INVALID;
} else {
switch (value) {
case NATIVE_WINDOW_SURFACE: { // Surface
SL_LOGV("Displaying on ANativeWindow of type NATIVE_WINDOW_SURFACE");
android::sp<android::Surface> nativeSurface(
static_cast<android::Surface *>(nativeWindow));
mp->mAVPlayer->setVideoSurfaceTexture(
nativeSurface->getSurfaceTexture());
result = SL_RESULT_SUCCESS;
} break;
case NATIVE_WINDOW_SURFACE_TEXTURE_CLIENT: { // SurfaceTextureClient
SL_LOGV("Displaying on ANativeWindow of type NATIVE_WINDOW_SURFACE_TEXTURE_CLIENT");
android::sp<android::SurfaceTextureClient> surfaceTextureClient(
static_cast<android::SurfaceTextureClient *>(nativeWindow));
android::sp<android::ISurfaceTexture> nativeSurfaceTexture(
surfaceTextureClient->getISurfaceTexture());
mp->mAVPlayer->setVideoSurfaceTexture(nativeSurfaceTexture);
result = SL_RESULT_SUCCESS;
} break;
case NATIVE_WINDOW_FRAMEBUFFER: // FramebufferNativeWindow
// fall through
default:
SL_LOGE("ANativeWindow * %p has unknown or unsupported concrete type %d",
nativeWindow, value);
result = SL_RESULT_PARAMETER_INVALID;
break;
}
}
return result;
}
| 36.638184 | 100 | 0.626412 | [
"object"
] |
36b4c1eaf55df70c6f1e87a6f2f1a2f1d9ba518f | 1,348 | cpp | C++ | android/face-recognition/app/src/main/cpp/face-recognition.cpp | wang-junjian/face-recognition-services | 54fb33eeb83de36d2080dd8bd08770b56d02f9de | [
"MIT"
] | 1 | 2020-06-01T03:55:01.000Z | 2020-06-01T03:55:01.000Z | android/face-recognition/app/src/main/cpp/face-recognition.cpp | wang-junjian/face-recognition-services | 54fb33eeb83de36d2080dd8bd08770b56d02f9de | [
"MIT"
] | null | null | null | android/face-recognition/app/src/main/cpp/face-recognition.cpp | wang-junjian/face-recognition-services | 54fb33eeb83de36d2080dd8bd08770b56d02f9de | [
"MIT"
] | null | null | null | #include <jni.h>
#include <string>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_io.h>
#include "jni/com_wangjunjian_facerecognition_FaceRecognition.h"
using namespace dlib;
using namespace std;
JNIEXPORT void JNICALL Java_com_wangjunjian_facerecognition_FaceRecognition_detect
(JNIEnv *env, jobject clazz, jstring filename, jobject rect)
{
const char* pfilename = env->GetStringUTFChars(filename, JNI_FALSE);
static frontal_face_detector detector = get_frontal_face_detector();
array2d<unsigned char> img;
load_image(img, pfilename);
env->ReleaseStringUTFChars(filename, pfilename);
std::vector<rectangle> dets = detector(img, 0);
if (dets.size() > 0)
{
rectangle faceRect = dets[0];
jclass rectClass = env->GetObjectClass(rect);
jfieldID fidLeft = env->GetFieldID(rectClass, "left", "I");
env->SetIntField(rect, fidLeft, faceRect.left());
jfieldID fidTop = env->GetFieldID(rectClass, "top", "I");
env->SetIntField(rect, fidTop, faceRect.top());
jfieldID fidRight = env->GetFieldID(rectClass, "right", "I");
env->SetIntField(rect, fidRight, faceRect.right());
jfieldID fidBottom = env->GetFieldID(rectClass, "bottom", "I");
env->SetIntField(rect, fidBottom, faceRect.bottom());
}
}
| 33.7 | 82 | 0.696588 | [
"vector"
] |
36b7ed729e8b7385025fe86d9419f5bd98664e9a | 804 | cpp | C++ | C++/smallest-k-length-subsequence-with-occurrences-of-a-letter.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/smallest-k-length-subsequence-with-occurrences-of-a-letter.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/smallest-k-length-subsequence-with-occurrences-of-a-letter.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n)
// Space: O(n)
class Solution {
public:
string smallestSubsequence(string s, int k, char letter, int repetition) {
string stk;
vector<int> suffix(size(s) + 1);
for (int i = size(suffix) - 2; i >= 0; --i) {
suffix[i] = suffix[i + 1] + (s[i] == letter);
}
for (int i = 0; i < size(s); ++i) {
while (!empty(stk) && stk.back() > s[i] && size(stk) + (size(s) - i) > k && (stk.back() != letter || repetition + 1 <= suffix[i])) {
repetition += (stk.back() == letter); stk.pop_back();
}
if (size(stk) < min(k - (repetition - (s[i] == letter)), k)) {
repetition -= (s[i] == letter);
stk.push_back(s[i]);
}
}
return stk;
}
};
| 33.5 | 144 | 0.440299 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.