hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 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 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | 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 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
31410c8491c5c51571bb9c7f467cd97df0e9483d
| 240
|
cpp
|
C++
|
1177.cpp
|
fenatan/URI-Online-Judge
|
983cadd364e658cdebcbc2c0165e8f54e023a823
|
[
"MIT"
] | null | null | null |
1177.cpp
|
fenatan/URI-Online-Judge
|
983cadd364e658cdebcbc2c0165e8f54e023a823
|
[
"MIT"
] | null | null | null |
1177.cpp
|
fenatan/URI-Online-Judge
|
983cadd364e658cdebcbc2c0165e8f54e023a823
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
int main(){
int t, cont;
scanf("%d", &t);
cont = 0;
for(int i =0; i < 1000; i++){
printf("N[%d] = %d\n", i,cont);
cont++;
if(cont == t)
cont = 0;
}
return 0;
}
| 16
| 39
| 0.383333
|
fenatan
|
31456f3d1416156987e215907a737654e51918fa
| 765
|
hpp
|
C++
|
src/sandbox/ProgramArgs.hpp
|
maxisoft/sandboxtank
|
ee1f37e3bda3dc27c8dfa64630166eed8a1af08d
|
[
"MIT"
] | null | null | null |
src/sandbox/ProgramArgs.hpp
|
maxisoft/sandboxtank
|
ee1f37e3bda3dc27c8dfa64630166eed8a1af08d
|
[
"MIT"
] | 3
|
2020-08-30T09:10:53.000Z
|
2020-08-30T09:41:57.000Z
|
src/sandbox/ProgramArgs.hpp
|
maxisoft/sandboxtank
|
ee1f37e3bda3dc27c8dfa64630166eed8a1af08d
|
[
"MIT"
] | 1
|
2021-09-23T00:34:13.000Z
|
2021-09-23T00:34:13.000Z
|
#pragma once
#include <cassert>
#include <filesystem>
#include <array>
#include <optional>
#include <map>
#include <vector>
#include <tchar.h>
#include <cstdio>
namespace maxisoft::sandbox
{
struct ProgramArgs
{
size_t argc;
std::filesystem::path program;
std::filesystem::path config;
std::optional<std::wstring> sessionid;
std::vector<std::wstring> additional_args;
std::optional<std::wstring> user;
std::optional<std::wstring> password;
std::optional<std::wstring> domain;
std::filesystem::path working_directory;
[[nodiscard]] std::wstring to_child_args(bool prepend_current_process) const;
static ProgramArgs parse_args(int argc, wchar_t *argv[]);
};
}
| 22.5
| 85
| 0.657516
|
maxisoft
|
31466ca33813793ae064846b15401a505b804744
| 1,349
|
hpp
|
C++
|
src/img_set.hpp
|
yytdfc/libtorch-mnasnet
|
f7f025bdcaa3f2a1654b4ad5786a91f6179bf3c5
|
[
"MIT"
] | 1
|
2019-02-05T16:40:29.000Z
|
2019-02-05T16:40:29.000Z
|
src/img_set.hpp
|
yytdfc/libtorch-mnasnet
|
f7f025bdcaa3f2a1654b4ad5786a91f6179bf3c5
|
[
"MIT"
] | null | null | null |
src/img_set.hpp
|
yytdfc/libtorch-mnasnet
|
f7f025bdcaa3f2a1654b4ad5786a91f6179bf3c5
|
[
"MIT"
] | null | null | null |
#include <torch/data/datasets/base.h>
#include <torch/data/example.h>
#include <torch/types.h>
class ImgSet : public Dataset<ImgSet> {
public:
/// The mode in which the dataset is loaded.
enum class Mode { kTrain, kTest };
/// Loads the MNIST dataset from the `root` path.
///
/// The supplied `root` path should contain the *content* of the unzipped
/// MNIST dataset, available from http://yann.lecun.com/exdb/mnist.
explicit MNIST(const std::string& root, Mode mode = Mode::kTrain)
:images_(read_images(root, mode == Mode::kTrain)),
targets_(read_targets(root, mode == Mode::kTrain)) {};
/// Returns the `Example` at the given `index`.
Example<> get(size_t index) override{
return {images_[index], targets_[index]};
};
/// Returns the size of the dataset.
optional<size_t> size() const override{
return images_.size(0);
};
/// Returns true if this is the training subset of MNIST.
bool is_train() const noexcept{
return images_.size(0) == kTrainSize;
};
/// Returns all images stacked into a single tensor.
const Tensor& images() const{
return images_;
};
/// Returns all targets stacked into a single tensor.
const Tensor& targets() const{
return targets_;
};
private:
Tensor images_, targets_;
};
| 28.702128
| 77
| 0.644922
|
yytdfc
|
3149634d70ee92dca8decb62f5436e91c12b97c1
| 648
|
cpp
|
C++
|
Strings_Equalization.cpp
|
De-Fau-Lt/Solutions
|
2539f815ab5c77769b3e3cc00fe0e7a7ec940ad5
|
[
"MIT"
] | null | null | null |
Strings_Equalization.cpp
|
De-Fau-Lt/Solutions
|
2539f815ab5c77769b3e3cc00fe0e7a7ec940ad5
|
[
"MIT"
] | null | null | null |
Strings_Equalization.cpp
|
De-Fau-Lt/Solutions
|
2539f815ab5c77769b3e3cc00fe0e7a7ec940ad5
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
string s, t;
cin >> s >> t;
unordered_set<char> s1;
unordered_set<char> s2;
for (auto x : s)
s1.insert(x);
for (auto x : t)
s2.insert(x);
int c = 0;
for (auto it = s1.begin(); it != s1.end(); it++)
{
if (s2.count(*it) > 0)
{
c = 1;
cout << "YES\n";
break;
}
}
if (c == 0)
cout << "NO\n";
}
}
| 18.514286
| 57
| 0.322531
|
De-Fau-Lt
|
314c654635e645dde3a91ba4ad5a0d5d348d2b75
| 5,253
|
cpp
|
C++
|
source/geometry/GeometryPooling3D.cpp
|
WillTao-RD/MNN
|
48575121859093bab8468d6992596962063b7aff
|
[
"Apache-2.0"
] | 2
|
2020-12-15T13:56:31.000Z
|
2022-01-26T03:20:28.000Z
|
source/geometry/GeometryPooling3D.cpp
|
qaz734913414/MNN
|
a5d5769789054a76c6e4dce2ef97d1f45b0e7e2d
|
[
"Apache-2.0"
] | null | null | null |
source/geometry/GeometryPooling3D.cpp
|
qaz734913414/MNN
|
a5d5769789054a76c6e4dce2ef97d1f45b0e7e2d
|
[
"Apache-2.0"
] | 1
|
2021-11-24T06:26:27.000Z
|
2021-11-24T06:26:27.000Z
|
//
// GeometryPooling3D.cpp
// MNN
//
// Created by MNN on 2020/7/28.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "ConvertUtils.hpp"
#include "geometry/GeometryComputer.hpp"
#include "core/OpCommonUtils.hpp"
#include "geometry/GeometryComputerUtils.hpp"
namespace MNN {
class GeometryPooling3D : public GeometryComputer {
public:
virtual bool onCompute(const Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, Context& context, CommandBuffer& res) const override {
MNN_ASSERT(1 == inputs.size());
MNN_ASSERT(1 == outputs.size());
auto input = inputs[0];
auto output = outputs[0];
MNN_ASSERT(input->dimensions() == 5);
auto kernelSize = op->main_as_Pool3D()->kernels();
auto strideSize = op->main_as_Pool3D()->strides();
auto padSize = op->main_as_Pool3D()->pads();
auto poolType = op->main_as_Pool3D()->type();
auto padType = op->main_as_Pool3D()->padType();
const int kernelDepth = kernelSize->Get(0), kernelHeight = kernelSize->Get(1), kernelWidth = kernelSize->Get(2);
const int strideDepth = strideSize->Get(0), strideHeight = strideSize->Get(1), strideWidth = strideSize->Get(2);
const int padDepth = padSize->Get(0), padHeight = padSize->Get(1), padWidth = padSize->Get(2);
const int outputDepth = output->length(2), outputHeight = output->length(3), outputWidth = output->length(4);
const int inputDepth = input->length(2), inputHeight = input->length(3), inputWidth = input->length(4);
const int channel = input->length(1), batch = input->length(0);
std::shared_ptr<Tensor> reshapeInput;
{
reshapeInput.reset(Tensor::createDevice<float>({batch*inputDepth, channel, inputHeight, inputWidth}));
auto outputDes = TensorUtils::getDescribe(reshapeInput.get());
outputDes->regions.clear();
outputDes->dimensionFormat = MNN_DATA_FORMAT_NC4HW4;
outputDes->memoryType = Tensor::InsideDescribe::MEMORY_VIRTUAL;
auto totalSlice = TensorUtils::makeFullSlice(input);
outputDes->regions.emplace_back(std::move(totalSlice));
res.extras.emplace_back(reshapeInput);
}
std::shared_ptr<Tensor> pool2dTmp1;
{
pool2dTmp1.reset(Tensor::createDevice<float>({batch*inputDepth, channel, outputHeight, outputWidth}));
auto outputDes = TensorUtils::getDescribe(pool2dTmp1.get());
outputDes->dimensionFormat = MNN_DATA_FORMAT_NC4HW4;
flatbuffers::FlatBufferBuilder builder;
builder.Finish(GeometryComputerUtils::makePool(builder, std::make_pair(kernelWidth, kernelHeight), std::make_pair(strideWidth, strideHeight), poolType, padType, std::make_pair(padWidth, padHeight), false));
auto cmd = GeometryComputerUtils::makeCommand(builder, {reshapeInput.get()}, {pool2dTmp1.get()});
res.extras.emplace_back(pool2dTmp1);
res.command.emplace_back(std::move(cmd));
}
std::shared_ptr<Tensor> reshapeTmp1;
{
reshapeTmp1.reset(Tensor::createDevice<float>({batch, channel, inputDepth, outputHeight*outputWidth}));
auto outputDes = TensorUtils::getDescribe(reshapeTmp1.get());
outputDes->regions.clear();
outputDes->dimensionFormat = MNN_DATA_FORMAT_NC4HW4;
outputDes->memoryType = Tensor::InsideDescribe::MEMORY_VIRTUAL;
auto totalSlice = TensorUtils::makeFullSlice(pool2dTmp1.get());
outputDes->regions.emplace_back(std::move(totalSlice));
res.extras.emplace_back(reshapeTmp1);
}
std::shared_ptr<Tensor> pool2dTmp2;
{
pool2dTmp2.reset(Tensor::createDevice<float>({batch, channel, outputDepth, outputHeight*outputWidth}));
TensorUtils::getDescribe(pool2dTmp2.get())->dimensionFormat = MNN_DATA_FORMAT_NC4HW4;
auto countType = AvgPoolCountType_DEFAULT;
if (poolType == PoolType_AVEPOOL) {
countType = AvgPoolCountType_EXCLUDE_PADDING;
}
flatbuffers::FlatBufferBuilder builder;
builder.Finish(GeometryComputerUtils::makePool(builder, std::make_pair(1, kernelDepth), std::make_pair(1, strideDepth), poolType, padType, std::make_pair(0, padDepth), false, countType));
auto cmd = GeometryComputerUtils::makeCommand(builder, {reshapeTmp1.get()}, {pool2dTmp2.get()});
res.extras.emplace_back(pool2dTmp2);
res.command.emplace_back(std::move(cmd));
}
{
auto outputDes = TensorUtils::getDescribe(output);
outputDes->dimensionFormat = MNN_DATA_FORMAT_NC4HW4;
outputDes->memoryType = Tensor::InsideDescribe::MEMORY_VIRTUAL;
auto totalSlice = TensorUtils::makeFullSlice(pool2dTmp2.get());
outputDes->regions.emplace_back(std::move(totalSlice));
}
return true;
}
};
static void _create() {
std::shared_ptr<GeometryComputer> comp(new GeometryPooling3D);
GeometryComputer::registerGeometryComputer(comp, {OpType_Pooling3D});
}
REGISTER_GEOMETRY(GeometryPooling3D, _create);
} // namespace MNN
| 52.009901
| 218
| 0.665905
|
WillTao-RD
|
315125966bd503336d33f24b102415ee0c389169
| 3,355
|
cpp
|
C++
|
AutoCompleteComboBox.cpp
|
joeriedel/Tread3.0A2
|
337c4aa74d554e21b50d6bd4406ce0f67aa39144
|
[
"MIT"
] | 1
|
2020-07-19T10:19:18.000Z
|
2020-07-19T10:19:18.000Z
|
AutoCompleteComboBox.cpp
|
joeriedel/Tread3.0A2
|
337c4aa74d554e21b50d6bd4406ce0f67aa39144
|
[
"MIT"
] | null | null | null |
AutoCompleteComboBox.cpp
|
joeriedel/Tread3.0A2
|
337c4aa74d554e21b50d6bd4406ce0f67aa39144
|
[
"MIT"
] | null | null | null |
// ComboBoxEx.cpp : implementation file
//
// Autocompleting combo-box (like the URL edit box in netscape)
//
// Written by Chris Maunder (Chris.Maunder@cbr.clw.csiro.au)
// Copyright (c) 1998.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name is included. If
// the source code in this file is used in any commercial application
// then acknowledgement must be made to the author of this file
// (in whatever form you wish).
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability if it causes any damage to your
// computer, causes your pet cat to fall ill, increases baldness or
// makes you car start emitting strange noises when you start it up.
//
// Expect bugs.
//
// Please use and enjoy. Please let me know of any bugs/mods/improvements
// that you have found/implemented and I will fix/incorporate them into this
// file.
//
// Modified: 12 Sep 1998 Setting correct cursor position after
// auto-complete: Petr Stejskal and Ryan Schneider
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "AutoCompleteComboBox.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CComboBoxEx
CAutoCompleteComboBox::CAutoCompleteComboBox()
{
m_bAutoComplete = TRUE;
}
CAutoCompleteComboBox::~CAutoCompleteComboBox()
{
}
BEGIN_MESSAGE_MAP(CAutoCompleteComboBox, CComboBox)
//{{AFX_MSG_MAP(CComboBoxEx)
ON_CONTROL_REFLECT(CBN_EDITUPDATE, OnEditUpdate)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CComboBoxEx message handlers
BOOL CAutoCompleteComboBox::PreTranslateMessage(MSG* pMsg)
{
// Need to check for backspace/delete. These will modify the text in
// the edit box, causing the auto complete to just add back the text
// the user has just tried to delete.
if (pMsg->message == WM_KEYDOWN)
{
m_bAutoComplete = TRUE;
int nVirtKey = (int) pMsg->wParam;
if (nVirtKey == VK_DELETE || nVirtKey == VK_BACK)
m_bAutoComplete = FALSE;
}
return CComboBox::PreTranslateMessage(pMsg);
}
void CAutoCompleteComboBox::OnEditUpdate()
{
// if we are not to auto update the text, get outta here
if (!m_bAutoComplete)
return;
// Get the text in the edit box
CString str;
GetWindowText(str);
int nLength = str.GetLength();
// Currently selected range
DWORD dwCurSel = GetEditSel();
WORD dStart = LOWORD(dwCurSel);
WORD dEnd = HIWORD(dwCurSel);
// Search for, and select in, and string in the combo box that is prefixed
// by the text in the edit box
if (SelectString(-1, str) == CB_ERR)
{
SetWindowText(str); // No text selected, so restore what was there before
if (dwCurSel != CB_ERR)
SetEditSel(dStart, dEnd); //restore cursor postion
}
// Set the text selection as the additional text that we have added
if (dEnd < nLength && dwCurSel != CB_ERR)
SetEditSel(dStart, dEnd);
else
SetEditSel(nLength, -1);
}
| 29.955357
| 80
| 0.668554
|
joeriedel
|
3153e009a72700cb3dd8943ee0734bddeb83e78c
| 2,897
|
hxx
|
C++
|
src/dbl/service/server/service_connection.hxx
|
mcptr/dbl-service
|
9af5aee06be0a4b909782b251bf6078513399d33
|
[
"MIT"
] | null | null | null |
src/dbl/service/server/service_connection.hxx
|
mcptr/dbl-service
|
9af5aee06be0a4b909782b251bf6078513399d33
|
[
"MIT"
] | null | null | null |
src/dbl/service/server/service_connection.hxx
|
mcptr/dbl-service
|
9af5aee06be0a4b909782b251bf6078513399d33
|
[
"MIT"
] | 1
|
2018-10-09T06:30:03.000Z
|
2018-10-09T06:30:03.000Z
|
#ifndef DBL_SERVICE_SERVER_SERVICE_CONNECTION_HXX
#define DBL_SERVICE_SERVER_SERVICE_CONNECTION_HXX
#include "connection.hxx"
#include "dbl/auth/auth.hxx"
#include "dbl/types/types.hxx"
#include <memory>
namespace dbl {
namespace service {
namespace server {
class ServiceOperationError : public std::runtime_error
{
public:
ServiceOperationError() = default;
explicit ServiceOperationError(const std::string& msg)
: std::runtime_error(msg)
{
}
explicit ServiceOperationError(
const std::string& msg,
const types::Errors_t& errors)
: std::runtime_error(msg),
errors_(errors)
{
}
~ServiceOperationError() = default;
virtual inline const types::Errors_t& get_errors() const
{
return errors_;
}
protected:
const types::Errors_t errors_;
};
class ServiceConnection : public Connection
{
public:
ServiceConnection() = delete;
ServiceConnection(std::shared_ptr<core::Api> api,
boost::asio::ip::tcp::socket socket);
virtual ~ServiceConnection() = default;
protected:
auth::Auth auth_;
bool is_authenticated_ = false;
virtual void process_request(const std::string& request,
std::string& response);
void dispatch(const std::string& cmd,
const Json::Value& data,
Json::Value& value);
// op handlers
void handle_status(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors) const;
void handle_flush_dns(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors) const;
void handle_block(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors) const;
void handle_unblock(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors) const;
void handle_set_service_password(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors);
void handle_remove_service_password(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors);
void handle_import_domain_list(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors) const;
void handle_get_domain_lists(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors) const;
void handle_get_domain_list(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors) const;
void handle_delete_domain_list(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors) const;
void handle_get_version(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors) const;
void handle_get_domain(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors) const;
void handle_get_domains(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors) const;
void handle_reload(
const Json::Value& data,
Json::Value& response,
types::Errors_t& errors);
};
} // server
} // service
} // dbl
#endif
| 20.692857
| 57
| 0.722126
|
mcptr
|
3157f68bbb610485664b1c94a911623fb91d84c2
| 487
|
cpp
|
C++
|
WeatherViewer/main.cpp
|
ajstacher/CST276SRS01
|
bea416c7479cc590ff09d48dbe695ba1b07edb03
|
[
"MIT"
] | null | null | null |
WeatherViewer/main.cpp
|
ajstacher/CST276SRS01
|
bea416c7479cc590ff09d48dbe695ba1b07edb03
|
[
"MIT"
] | null | null | null |
WeatherViewer/main.cpp
|
ajstacher/CST276SRS01
|
bea416c7479cc590ff09d48dbe695ba1b07edb03
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "station.h"
#include "current.h"
#include "statistics.h"
int main()
{
//for rand() in station
srand(time(NULL));
//create
WeatherStation::Station weather_station;
//attached upon construction
WeatherViewer::Current current_weather(weather_station);
WeatherViewer::Statistics statistics(weather_station);
//get data and notify observers
for(auto i = 0; i < 3; i++)
{
weather_station.measure();
weather_station.notify();
}
return 0;
}
| 18.037037
| 57
| 0.716632
|
ajstacher
|
316002e48643abdc8582e51b55bed3dc64dc6876
| 16,859
|
cpp
|
C++
|
opengl/src/Rendering/ImageEffects/DepthOfFieldImageEffect.cpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 36
|
2015-03-12T10:42:36.000Z
|
2022-01-12T04:20:40.000Z
|
opengl/src/Rendering/ImageEffects/DepthOfFieldImageEffect.cpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 1
|
2015-12-17T00:25:43.000Z
|
2016-02-20T12:00:57.000Z
|
opengl/src/Rendering/ImageEffects/DepthOfFieldImageEffect.cpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 6
|
2017-06-17T07:57:53.000Z
|
2019-04-09T21:11:24.000Z
|
/*
* Copyright (c) 2013, Hernan Saez
* 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 <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "DepthOfFieldImageEffect.hpp"
#include "Rendering/OpenGLUtils.hpp"
#include <Rendering/FrameBufferObject.hpp>
#include <Rendering/RenderTarget.hpp>
#include <Rendering/RenderPasses/RenderPass.hpp>
#include <SceneGraph/Camera.hpp>
using namespace crimild;
using namespace crimild::opengl;
const char *dof_generic_vs = R"(
CRIMILD_GLSL_ATTRIBUTE( 0 ) vec3 aPosition;
CRIMILD_GLSL_ATTRIBUTE( 4 ) vec2 aTextureCoord;
CRIMILD_GLSL_VARYING_OUT vec2 vTextureCoord;
void main()
{
vTextureCoord = aTextureCoord;
CRIMILD_GLSL_VERTEX_OUTPUT = vec4( aPosition, 1.0 );
}
)";
const char *dof_generic_fs = R"(
CRIMILD_GLSL_PRECISION_FLOAT_HIGH
CRIMILD_GLSL_VARYING_IN vec2 vTextureCoord;
uniform sampler2D uColorMap;
CRIMILD_GLSL_DECLARE_FRAGMENT_OUTPUT
void main( void )
{
CRIMILD_GLSL_FRAGMENT_OUTPUT = CRIMILD_GLSL_FN_TEXTURE_2D( uColorMap, vTextureCoord );
}
)";
const char *dof_blur_fs = R"(
CRIMILD_GLSL_PRECISION_FLOAT_HIGH
CRIMILD_GLSL_VARYING_IN vec2 vTextureCoord;
CRIMILD_GLSL_DECLARE_FRAGMENT_OUTPUT
uniform vec2 uTexelSize;
uniform sampler2D uColorMap;
uniform sampler2D uDepthMap;
uniform int uOrientation;
uniform float uBlurCoefficient;
uniform float uFocusDistance;
uniform float uNear;
uniform float uFar;
uniform float uPPM;
float linearDepth( float z )
{
z = 2.0 * z - 1.0;
return ( 2.0 * uNear * uFar ) / ( uFar + uNear - z * ( uFar - uNear ) );
}
// Calculate the blur diameter to apply on the image.
float GetBlurDiameter( float d )
{
float Dd = d;
float xd = abs( Dd - uFocusDistance );
float xdd = ( Dd < uFocusDistance ) ? ( uFocusDistance - xd ) : ( uFocusDistance + xd );
float b = uBlurCoefficient * ( xd / xdd );
return b * uPPM;
}
void main ()
{
const float MAX_BLUR_RADIUS = 10.0;
float depth = linearDepth( CRIMILD_GLSL_FN_TEXTURE_2D( uDepthMap, vTextureCoord ).x );
float blurAmount = GetBlurDiameter( depth );
blurAmount = min( floor( blurAmount ), MAX_BLUR_RADIUS );
float count = 0.0;
vec4 colour = vec4( 0.0 );
vec2 texelOffset;
if ( uOrientation == 0 ) {
texelOffset = vec2( uTexelSize.x, 0.0);
}
else {
texelOffset = vec2(0.0, uTexelSize.y);
}
if ( blurAmount >= 1.0 ) {
float halfBlur = blurAmount * 0.5;
for ( float i = 0.0; i < MAX_BLUR_RADIUS; ++i ) {
if ( i >= blurAmount ) {
break;
}
float offset = i - halfBlur;
vec2 vOffset = vTextureCoord + ( texelOffset * offset );
colour += CRIMILD_GLSL_FN_TEXTURE_2D( uColorMap, vOffset );
++count;
}
}
if ( count > 0.0 ) {
CRIMILD_GLSL_FRAGMENT_OUTPUT = colour / count;
}
else {
CRIMILD_GLSL_FRAGMENT_OUTPUT = CRIMILD_GLSL_FN_TEXTURE_2D( uColorMap, vTextureCoord );
}
}
)";
const char *dof_composite_fs = R"(
CRIMILD_GLSL_PRECISION_FLOAT_HIGH
CRIMILD_GLSL_VARYING_IN vec2 vTextureCoord;
CRIMILD_GLSL_DECLARE_FRAGMENT_OUTPUT
uniform sampler2D uColorMap;
uniform sampler2D uDepthMap;
uniform sampler2D uBlurMap;
uniform float uBlurCoefficient;
uniform float uFocusDistance;
uniform float uNear;
uniform float uFar;
uniform float uPPM;
float linearDepth( float z )
{
z = 2.0 * z - 1.0;
return ( 2.0 * uNear * uFar ) / ( uFar + uNear - z * ( uFar - uNear ) );
}
// Calculate the blur diameter to apply on the image.
float GetBlurDiameter (float d)
{
float Dd = d;
float xd = abs( Dd - uFocusDistance );
float xdd = (Dd < uFocusDistance) ? (uFocusDistance - xd) : (uFocusDistance + xd);
float b = uBlurCoefficient * (xd / xdd);
return b * uPPM;
}
void main ()
{
const float MAX_BLUR_RADIUS = 10.0;
vec4 colour = CRIMILD_GLSL_FN_TEXTURE_2D( uColorMap, vTextureCoord );
float depth = linearDepth( CRIMILD_GLSL_FN_TEXTURE_2D( uDepthMap, vTextureCoord ).x );
vec4 blur = CRIMILD_GLSL_FN_TEXTURE_2D( uBlurMap, vTextureCoord );
float blurAmount = GetBlurDiameter( depth );
float lerp = min( blurAmount / MAX_BLUR_RADIUS, 1.0 );
CRIMILD_GLSL_FRAGMENT_OUTPUT = ( colour * ( 1.0 - lerp ) ) + ( blur * lerp );
}
)";
DepthOfFieldImageEffect::DoFBlurShaderProgram::DoFBlurShaderProgram( void )
: ShaderProgram( OpenGLUtils::getVertexShaderInstance( dof_generic_vs ), OpenGLUtils::getFragmentShaderInstance( dof_blur_fs ) )
{
registerStandardLocation( ShaderLocation::Type::ATTRIBUTE, ShaderProgram::StandardLocation::POSITION_ATTRIBUTE, "aPosition" );
registerStandardLocation( ShaderLocation::Type::ATTRIBUTE, ShaderProgram::StandardLocation::TEXTURE_COORD_ATTRIBUTE, "aTextureCoord" );
registerStandardLocation( ShaderLocation::Type::UNIFORM, ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM, "uColorMap" );
registerStandardLocation( ShaderLocation::Type::UNIFORM, ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM, "uDepthMap" );
_uOrientation = crimild::alloc< IntUniform >( "uOrientation", 0 );
_uTexelSize = crimild::alloc< Vector2fUniform >( "uTexelSize", Vector2f::ZERO );
_uBlurCoefficient = crimild::alloc< FloatUniform >( "uBlurCoefficient", 0.0f );
_uFocusDistance = crimild::alloc< FloatUniform >( "uFocusDistance", 0.0f );
_uPPM = crimild::alloc< FloatUniform >( "uPPM", 0.0f );
_uNear = crimild::alloc< FloatUniform >( "uNear", 0.0f );
_uFar = crimild::alloc< FloatUniform >( "uFar", 0.0f );
attachUniform( _uTexelSize );
attachUniform( _uOrientation );
attachUniform( _uBlurCoefficient );
attachUniform( _uFocusDistance );
attachUniform( _uNear );
attachUniform( _uFar );
attachUniform( _uPPM );
}
DepthOfFieldImageEffect::DoFBlurShaderProgram::~DoFBlurShaderProgram( void )
{
}
DepthOfFieldImageEffect::DoFCompositeShaderProgram::DoFCompositeShaderProgram( void )
: ShaderProgram( OpenGLUtils::getVertexShaderInstance( dof_generic_vs ), OpenGLUtils::getFragmentShaderInstance( dof_composite_fs ) )
{
registerStandardLocation( ShaderLocation::Type::ATTRIBUTE, ShaderProgram::StandardLocation::POSITION_ATTRIBUTE, "aPosition" );
registerStandardLocation( ShaderLocation::Type::ATTRIBUTE, ShaderProgram::StandardLocation::TEXTURE_COORD_ATTRIBUTE, "aTextureCoord" );
registerStandardLocation( ShaderLocation::Type::UNIFORM, ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM, "uColorMap" );
registerStandardLocation( ShaderLocation::Type::UNIFORM, ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM, "uDepthMap" );
registerLocation( crimild::alloc< ShaderLocation >( ShaderLocation::Type::UNIFORM, "uBlurMap" ) );
_uBlurCoefficient = crimild::alloc< FloatUniform >( "uBlurCoefficient", 0.0f );
_uFocusDistance = crimild::alloc< FloatUniform >( "uFocusDistance", 0.0f );
_uPPM = crimild::alloc< FloatUniform >( "uPPM", 0.0f );
_uNear = crimild::alloc< FloatUniform >( "uNear", 0.0f );
_uFar = crimild::alloc< FloatUniform >( "uFar", 0.0f );
attachUniform( _uBlurCoefficient );
attachUniform( _uFocusDistance );
attachUniform( _uNear );
attachUniform( _uFar );
attachUniform( _uPPM );
}
DepthOfFieldImageEffect::DoFCompositeShaderProgram::~DoFCompositeShaderProgram( void )
{
}
DepthOfFieldImageEffect::DepthOfFieldImageEffect( void )
: DepthOfFieldImageEffect( 1024 )
{
}
DepthOfFieldImageEffect::DepthOfFieldImageEffect( int resolution )
: _resolution( resolution ),
_focalDistance( crimild::alloc< FloatUniform >( "uFocalDistance", 50.0f ) ),
_focusDistance( crimild::alloc< FloatUniform >( "uFocusDistance", 10000.0f ) ),
_fStop( crimild::alloc< FloatUniform >( "uFStop", 2.8f ) ),
_aperture( crimild::alloc< FloatUniform >( "uAperture", 35.0f ) )
{
_auxFBOs.push_back( crimild::alloc< StandardFrameBufferObject >( resolution, resolution ) );
_auxFBOs.push_back( crimild::alloc< StandardFrameBufferObject >( resolution, resolution ) );
_dofBlurProgram = crimild::alloc< DoFBlurShaderProgram >();
_dofCompositeProgram = crimild::alloc< DoFCompositeShaderProgram >();
}
DepthOfFieldImageEffect::~DepthOfFieldImageEffect( void )
{
}
void DepthOfFieldImageEffect::compute( Renderer *renderer, Camera *camera )
{
auto sceneFBO = renderer->getFrameBuffer( RenderPass::S_BUFFER_NAME );
if ( sceneFBO == nullptr ) {
Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot find FBO named '", RenderPass::S_BUFFER_NAME, "'" );
return;
}
auto colorTarget = sceneFBO->getRenderTargets()[ RenderPass::S_BUFFER_COLOR_TARGET_NAME ];
if ( colorTarget == nullptr ) {
Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot get color target from scene" );
return;
}
auto depthTarget = sceneFBO->getRenderTargets()[ RenderPass::S_BUFFER_DEPTH_TARGET_NAME ];
if ( depthTarget->getTexture() == nullptr ) {
Log::error( CRIMILD_CURRENT_CLASS_NAME, "Depth texture is null" );
return;
}
auto blurFBO = renderer->getFrameBuffer( Renderer::FBO_AUX_1024 );
if ( blurFBO == nullptr ) {
Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot find FBO named '", Renderer::FBO_AUX_1024, "'" );
return;
}
float f = getFocalDistance();
float Ds = getFocusDistance();
float ms = f / ( Ds - f );
float N = getFStop();
float PPM = Numericf::sqrt( ( getResolution() * getResolution() ) + ( getResolution() * getResolution() ) ) / getAperture();
float b = f * ms / N;
auto fboA = getAuxFBO( 0 );
auto fboB = getAuxFBO( 1 );
getBlurProgram()->setTexelSize( Vector2f( 1.0f / ( float ) getResolution(), 1.0f / ( float ) getResolution() ) );
getBlurProgram()->setBlurCoefficient( b );
getBlurProgram()->setFocusDistance( Ds );
getBlurProgram()->setPPM( PPM );
getBlurProgram()->setNear( 1000.0f * camera->getFrustum().getDMin() );
getBlurProgram()->setFar( 1000.0f * camera->getFrustum().getDMax() );
getBlurProgram()->setOrientation( 0 );
renderer->bindFrameBuffer( fboA );
renderer->bindProgram( getBlurProgram() );
renderer->bindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM ), colorTarget->getTexture() );
renderer->bindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM ), depthTarget->getTexture() );
renderer->drawScreenPrimitive( getBlurProgram() );
renderer->unbindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM ), colorTarget->getTexture() );
renderer->unbindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM ), depthTarget->getTexture() );
renderer->unbindProgram( getBlurProgram() );
renderer->unbindFrameBuffer( fboA );
auto aColorTarget = fboA->getRenderTargets()[ RenderTarget::RENDER_TARGET_NAME_COLOR ];
if ( aColorTarget == nullptr ) {
Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot get color target from scene" );
return;
}
getBlurProgram()->setOrientation( 0 );
renderer->bindFrameBuffer( fboB );
renderer->bindProgram( getBlurProgram() );
renderer->bindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM ), aColorTarget->getTexture() );
renderer->bindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM ), depthTarget->getTexture() );
renderer->drawScreenPrimitive( getBlurProgram() );
renderer->unbindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM ), aColorTarget->getTexture() );
renderer->unbindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM ), depthTarget->getTexture() );
renderer->unbindProgram( getBlurProgram() );
renderer->unbindFrameBuffer( fboB );
}
void DepthOfFieldImageEffect::apply( crimild::Renderer *renderer, crimild::Camera *camera )
{
auto sceneFBO = renderer->getFrameBuffer( RenderPass::S_BUFFER_NAME );
if ( sceneFBO == nullptr ) {
Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot find FBO named '", RenderPass::S_BUFFER_NAME, "'" );
return;
}
auto colorTarget = sceneFBO->getRenderTargets()[ RenderPass::S_BUFFER_COLOR_TARGET_NAME ];
if ( colorTarget->getTexture() == nullptr ) {
Log::error( CRIMILD_CURRENT_CLASS_NAME, "Color texture is null" );
return;
}
auto depthTarget = sceneFBO->getRenderTargets()[ RenderPass::S_BUFFER_DEPTH_TARGET_NAME ];
if ( depthTarget->getTexture() == nullptr ) {
Log::error( CRIMILD_CURRENT_CLASS_NAME, "Depth texture is null" );
return;
}
auto blurFBO = getAuxFBO( 1 );
if ( blurFBO == nullptr ) {
Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot find FBO named 'dof/fbo/fboB'" );
return;
}
auto blurTarget = blurFBO->getRenderTargets()[ RenderTarget::RENDER_TARGET_NAME_COLOR ];
if ( blurTarget->getTexture() == nullptr || blurTarget->getTexture()->getCatalog() == nullptr ) {
Log::error( CRIMILD_CURRENT_CLASS_NAME, "Blur texture is null" );
return;
}
float f = getFocalDistance();
float Ds = getFocusDistance();
float ms = f / ( Ds - f );
float N = getFStop();
float PPM = Numericf::sqrt( ( getResolution() * getResolution() ) + ( getResolution() * getResolution() ) ) / getAperture();
float b = f * ms / N;
getCompositeProgram()->setBlurCoefficient( b );
getCompositeProgram()->setFocusDistance( Ds );
getCompositeProgram()->setPPM( PPM );
getCompositeProgram()->setNear( 1000.0f * camera->getFrustum().getDMin() );
getCompositeProgram()->setFar( 1000.0f * camera->getFrustum().getDMax() );
renderer->bindProgram( getCompositeProgram() );
renderer->bindTexture( getCompositeProgram()->getStandardLocation( ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM ), colorTarget->getTexture() );
renderer->bindTexture( getCompositeProgram()->getStandardLocation( ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM ), depthTarget->getTexture() );
renderer->bindTexture( getCompositeProgram()->getLocation( "uBlurMap" ), blurTarget->getTexture() );
renderer->drawScreenPrimitive( getCompositeProgram() );
renderer->unbindTexture( getCompositeProgram()->getStandardLocation( ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM ), colorTarget->getTexture() );
renderer->unbindTexture( getCompositeProgram()->getStandardLocation( ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM ), depthTarget->getTexture() );
renderer->unbindTexture( getCompositeProgram()->getLocation( "uBlurMap" ), blurTarget->getTexture() );
renderer->unbindProgram( getCompositeProgram() );
}
| 40.722222
| 155
| 0.690314
|
hhsaez
|
3168e4a09c0e78c678ed89b72d7f03167fa4ac03
| 4,186
|
cpp
|
C++
|
src/MResProvider_Textures.cpp
|
viktorcpp/endless2.0save
|
9824aebd56346f1b9526b730063b84918bd6ac08
|
[
"MIT"
] | null | null | null |
src/MResProvider_Textures.cpp
|
viktorcpp/endless2.0save
|
9824aebd56346f1b9526b730063b84918bd6ac08
|
[
"MIT"
] | null | null | null |
src/MResProvider_Textures.cpp
|
viktorcpp/endless2.0save
|
9824aebd56346f1b9526b730063b84918bd6ac08
|
[
"MIT"
] | null | null | null |
namespace endless
{
//MResProvider_Textures
void MResProvider_Textures::Load( MTexture::TextureInternalData::Component& comp, const char* path )
{
if( path == 0 )
{
LOGE( "%s : path == 0", __FUNCTION__ );
return;
}
std::string _error_buffer;
D3D11_SHADER_RESOURCE_VIEW_DESC _srv_desc;
TexMetadata _tex_metadata;
ScratchImage _scratch_image;
D3D11_SAMPLER_DESC _sampler_desc;
ID3D11Resource* _texture_res = nullptr;
ID3D11ShaderResourceView* _shader_resview = nullptr;
ID3D11SamplerState* _samplerstate = nullptr;
ID3D11Device* _device = const_cast<ID3D11Device*>( MCore::GetMRendererDriver()->GetDevice() );
ZeroMemory( &_srv_desc, sizeof( D3D11_SHADER_RESOURCE_VIEW_DESC ) );
ZeroMemory( &_tex_metadata, sizeof( TexMetadata ) );
ZeroMemory( &_sampler_desc, sizeof( D3D11_SAMPLER_DESC ) );
std::wstring wpath;
MUtils::LtoW( path, wpath);
__TRY__
HRESULT hr = LoadFromDDSFile( wpath.c_str(), DDS_FLAGS_NONE, nullptr, _scratch_image );
if( FAILED(hr) )
{
MUtils::TranslateLastError(_error_buffer);
LOGE( "%s : LoadFromDDSFile FAILED <%s> at <%s>\n", __FUNCTION__, _error_buffer.c_str(), path );
return;
}
_tex_metadata = _scratch_image.GetMetadata();
_srv_desc.Format = _tex_metadata.format;
hr = CreateTexture( _device, _scratch_image.GetImages(), _scratch_image.GetImageCount(), _tex_metadata, &_texture_res );
if( FAILED(hr) )
{
MUtils::TranslateLastError(_error_buffer);
LOGE( "%s : CreateTexture FAILED <%s>\n", __FUNCTION__, _error_buffer.c_str() );
return;
}
if( _tex_metadata.arraySize > 1 )
{
_srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY;
_srv_desc.Texture1DArray.MipLevels = (UINT)_tex_metadata.mipLevels;
_srv_desc.Texture1DArray.ArraySize = (UINT)_tex_metadata.arraySize;
}
else
{
_srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
_srv_desc.Texture1D.MipLevels = (UINT)_tex_metadata.mipLevels;
}
hr = _device->CreateShaderResourceView( _texture_res, &_srv_desc, &_shader_resview );
if( FAILED(hr) )
{
MUtils::TranslateLastError(_error_buffer);
LOGE( "%s : CreateShaderResourceView FAILED <%s>\n", __FUNCTION__, _error_buffer.c_str() );
return;
}
// Sampler State default
_sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
_sampler_desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
_sampler_desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
_sampler_desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
_sampler_desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
_sampler_desc.MinLOD = 0;
_sampler_desc.MaxLOD = D3D11_FLOAT32_MAX;
_sampler_desc.MipLODBias = 0.0f;
_sampler_desc.MaxAnisotropy = 1;
_sampler_desc.BorderColor[0] = 0;
_sampler_desc.BorderColor[1] = 0;
_sampler_desc.BorderColor[2] = 0;
_sampler_desc.BorderColor[3] = 0;
hr = _device->CreateSamplerState( &_sampler_desc, &_samplerstate );
if( FAILED( hr ) )
{
MUtils::TranslateLastError(_error_buffer);
LOGE( "%s : CreateSamplerState FAILED <%s>\n", __FUNCTION__, _error_buffer.c_str() );
return;
}
comp.resource = _texture_res;
comp.sampler_state = _samplerstate;
comp.shader_res_view = _shader_resview;
__CATCH__
} // Load
MResProvider_Textures::MResProvider_Textures()
{}
MResProvider_Textures::MResProvider_Textures(MResProvider_Textures&)
{}
MResProvider_Textures::~MResProvider_Textures()
{}
} // namespace endless
| 37.711712
| 128
| 0.605351
|
viktorcpp
|
3168fefb5f1222fdcea6c08eb2d03c2e93d7a926
| 1,148
|
hpp
|
C++
|
src/FCFS.hpp
|
zwimer/CPU-Simulator
|
9e2e52a17e01258d36ac2780fb342319b922ca10
|
[
"MIT"
] | null | null | null |
src/FCFS.hpp
|
zwimer/CPU-Simulator
|
9e2e52a17e01258d36ac2780fb342319b922ca10
|
[
"MIT"
] | null | null | null |
src/FCFS.hpp
|
zwimer/CPU-Simulator
|
9e2e52a17e01258d36ac2780fb342319b922ca10
|
[
"MIT"
] | null | null | null |
/* Operating Systems Project 1
* Alex Slanski, Owen Stenson, Zac Wimer
*/
#ifndef FCFS_hpp
#define FCFS_hpp
//My includes
#include "Algo.hpp"
//System includes
#include <set>
#include <list>
//FCFS algorithm class
class FCFS : public Algo {
private:
//Representation
bool ProcessRunning;
uint FinishContextSwitch;
std::list<Process*> Queued;
public:
//Constructor
FCFS();
//Destructor
~FCFS();
//Get the current queue
const std::ostringstream* getQ() const;
//Returns true if the ready queue is empty
bool queueEmpty() const;
//Returns the amount of time until you want
void addProcess(Process *p);
//The algorithm will return an int specifying
//the next time it wants to be notified of the time
//Return's -1 is done, otherwise returns a positive number
int nextNotify() const;
//Returns an event to do at time t
//This will only be called at time t!
//Returns NULL if there is no new event
//If this returns an event, a context swtich will start
Event* getNextAction();
};
#endif /* FCFS_hpp */
| 20.5
| 62
| 0.649826
|
zwimer
|
3169678165a9a86ed8a9c281b07f7acef6a94a72
| 16,593
|
cpp
|
C++
|
src/ossim/imaging/ossimConvolutionSource.cpp
|
rkanavath/ossim18
|
d2e8204d11559a6a868755a490f2ec155407fa96
|
[
"MIT"
] | null | null | null |
src/ossim/imaging/ossimConvolutionSource.cpp
|
rkanavath/ossim18
|
d2e8204d11559a6a868755a490f2ec155407fa96
|
[
"MIT"
] | null | null | null |
src/ossim/imaging/ossimConvolutionSource.cpp
|
rkanavath/ossim18
|
d2e8204d11559a6a868755a490f2ec155407fa96
|
[
"MIT"
] | 1
|
2019-09-25T00:43:35.000Z
|
2019-09-25T00:43:35.000Z
|
// Copyright (C) 2000 ImageLinks Inc.
//
// License: MIT
//
// See LICENSE.txt file in the top level directory for more details.
//
// Author: Garrett Potts
//
//*******************************************************************
// $Id: ossimConvolutionSource.cpp 23664 2015-12-14 14:17:27Z dburken $
#include <ossim/imaging/ossimConvolutionSource.h>
#include <ossim/imaging/ossimImageData.h>
#include <ossim/imaging/ossimDiscreteConvolutionKernel.h>
#include <ossim/imaging/ossimImageDataFactory.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimKeyword.h>
static const ossimKeyword NUMBER_OF_MATRICES = ossimKeyword("number_of_matrices", "");
static const ossimKeyword NUMBER_OF_ROWS = ossimKeyword("rows", "");
static const ossimKeyword NUMBER_OF_COLS = ossimKeyword("cols", "");
RTTI_DEF1(ossimConvolutionSource, "ossimConvolutionSource", ossimImageSourceFilter);
ossimConvolutionSource::ossimConvolutionSource()
: ossimImageSourceFilter(),
theTile(NULL)
{
}
ossimConvolutionSource::ossimConvolutionSource(ossimImageSource* inputSource,
const NEWMAT::Matrix& convolutionMatrix)
: ossimImageSourceFilter(inputSource),
theTile(NULL)
{
theConvolutionKernelList.push_back(new ossimDiscreteConvolutionKernel(convolutionMatrix));
setKernelInformation();
initialize();
}
ossimConvolutionSource::ossimConvolutionSource(ossimImageSource* inputSource,
const vector<NEWMAT::Matrix>& convolutionList)
: ossimImageSourceFilter(inputSource),
theTile(NULL)
{
setConvolutionList(convolutionList);
}
ossimConvolutionSource::~ossimConvolutionSource()
{
deleteConvolutionList();
}
void ossimConvolutionSource::setConvolution(const double* kernel,
int nrows,
int ncols,
bool doWeightedAverage)
{
NEWMAT::Matrix m(nrows, ncols);
const double* tempPtr = kernel;
for(int row = 0; row < nrows; ++row)
{
for(int col = 0; col < ncols; ++col)
{
m[row][col] =*tempPtr;
++tempPtr;
}
}
setConvolution(m, doWeightedAverage);
}
void ossimConvolutionSource::setConvolutionList(const vector<NEWMAT::Matrix>& convolutionList,
bool doWeightedAverage)
{
deleteConvolutionList();
ossim_uint32 idx;
for(idx = 0; idx < convolutionList.size(); ++idx)
{
theConvolutionKernelList.push_back(new ossimDiscreteConvolutionKernel(convolutionList[idx],
doWeightedAverage));
}
setKernelInformation();
}
ossimRefPtr<ossimImageData> ossimConvolutionSource::getTile(
const ossimIrect& tileRect,
ossim_uint32 resLevel)
{
if(!theInputConnection) return ossimRefPtr<ossimImageData>();
if((!isSourceEnabled())||
(theConvolutionKernelList.size() < 1))
{
return theInputConnection->getTile(tileRect, resLevel);
}
if(!theTile.valid())
{
allocate();
if(!theTile.valid()) // Throw exception???
{
return theInputConnection->getTile(tileRect, resLevel);
}
}
ossim_uint32 w = tileRect.width();
ossim_uint32 h = tileRect.height();
ossim_uint32 tw = theTile->getWidth();
ossim_uint32 th = theTile->getHeight();
theTile->setWidth(w);
theTile->setHeight(h);
if((w*h)!=(tw*th))
{
theTile->initialize();
theTile->makeBlank();
}
else
{
theTile->makeBlank();
}
theTile->setOrigin(tileRect.ul());
long offsetX = (theMaxKernelWidth)/2;
long offsetY = (theMaxKernelHeight)/2;
ossimIrect requestRect(tileRect.ul().x - offsetX,
tileRect.ul().y - offsetY,
tileRect.lr().x + offsetX,
tileRect.lr().y + offsetY);
ossimRefPtr<ossimImageData> input = theInputConnection->getTile(requestRect,
resLevel);
if(!input.valid() ||
(input->getDataObjectStatus() == OSSIM_NULL)||
(input->getDataObjectStatus() == OSSIM_EMPTY))
{
return input;
}
switch(theTile->getScalarType())
{
case OSSIM_UCHAR:
{
if(theConvolutionKernelList.size() == 1)
{
convolve(static_cast<ossim_uint8>(0),
input,
theConvolutionKernelList[0]);
}
else
{
ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size();
ossim_uint32 idx;
for(idx = 0; idx < upperBound; ++idx)
{
convolve(static_cast<ossim_uint8>(0),
input,
theConvolutionKernelList[idx]);
input->loadTile(theTile.get());
}
}
break;
}
case OSSIM_USHORT16:
case OSSIM_USHORT11:
{
if(theConvolutionKernelList.size() == 1)
{
convolve(static_cast<ossim_uint16>(0),
input,
theConvolutionKernelList[0]);
}
else
{
ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size();
ossim_uint32 idx;
for(idx = 0; idx < upperBound; ++idx)
{
convolve(static_cast<ossim_uint16>(0),
input,
theConvolutionKernelList[idx]);
input->loadTile(theTile.get());
}
}
break;
}
case OSSIM_SSHORT16:
{
if(theConvolutionKernelList.size() == 1)
{
convolve(static_cast<ossim_sint16>(0),
input,
theConvolutionKernelList[0]);
}
else
{
ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size();
ossim_uint32 idx;
for(idx = 0; idx < upperBound; ++idx)
{
convolve(static_cast<ossim_sint16>(0),
input,
theConvolutionKernelList[idx]);
input->loadTile(theTile.get());
}
}
break;
}
case OSSIM_FLOAT:
case OSSIM_NORMALIZED_FLOAT:
{
if(theConvolutionKernelList.size() == 1)
{
convolve(static_cast<float>(0),
input,
theConvolutionKernelList[0]);
}
else
{
ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size();
ossim_uint32 idx;
for(idx = 0; idx < upperBound; ++idx)
{
convolve(static_cast<float>(0),
input,
theConvolutionKernelList[idx]);
input->loadTile(theTile.get());
}
}
break;
}
case OSSIM_DOUBLE:
case OSSIM_NORMALIZED_DOUBLE:
{
if(theConvolutionKernelList.size() == 1)
{
convolve(static_cast<double>(0),
input,
theConvolutionKernelList[0]);
}
else
{
ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size();
ossim_uint32 idx;
for(idx = 0; idx < upperBound; ++idx)
{
convolve(static_cast<double>(0),
input,
theConvolutionKernelList[idx]);
input->loadTile(theTile.get());
}
}
break;
}
default:
{
theTile->loadTile(input.get());
}
}
theTile->validate();
return theTile;
}
template <class T>
void ossimConvolutionSource::convolve(T /* dummyVariable */,
ossimRefPtr<ossimImageData> inputTile,
ossimDiscreteConvolutionKernel* kernel)
{
ossimIpt startOrigin = theTile->getOrigin();
// Make sure that the patch is not empty or NULL
//
ossimIpt startDelta(startOrigin.x - inputTile->getOrigin().x,
startOrigin.y - inputTile->getOrigin().y);
ossimDataObjectStatus status = inputTile->getDataObjectStatus();
// let's setup some variables that we will need to do the
// convolution algorithm.
//
ossimIrect patchRect = inputTile->getImageRectangle();
long tileHeight = theTile->getHeight();
long tileWidth = theTile->getWidth();
long outputBands = theTile->getNumberOfBands();
long convolutionWidth = kernel->getWidth();
long convolutionHeight = kernel->getHeight();
long convolutionOffsetX= convolutionWidth/2;
long convolutionOffsetY= convolutionHeight/2;
long patchWidth = patchRect.width();
long convolutionTopLeftOffset = 0;
long convolutionCenterOffset = 0;
long outputOffset = 0;
T np = 0;
const double minPix = ossim::defaultMin(getOutputScalarType());
const double maxPix = ossim::defaultMax(getOutputScalarType());
// const double* maxPix = inputTile->getMaxPix();
const double* nullPix = inputTile->getNullPix();
double convolveResult = 0;
if(status == OSSIM_PARTIAL) // must check for NULLS
{
for(long y = 0; y <tileHeight; y++)
{
convolutionCenterOffset = patchWidth*(startDelta.y + y) + startDelta.x;
convolutionTopLeftOffset = patchWidth*(startDelta.y + y - convolutionOffsetY) + startDelta.x-convolutionOffsetX;
for(long x =0; x < tileWidth; x++)
{
if(!inputTile->isNull(convolutionCenterOffset))
{
for(long b = 0; b < outputBands; ++b)
{
T* buf = (T*)(inputTile->getBuf(b)) + convolutionTopLeftOffset;
T* outBuf = (T*)(theTile->getBuf(b));
kernel->convolveSubImage(buf,
patchWidth,
convolveResult,
(T)nullPix[b]);
convolveResult = convolveResult < minPix? minPix:convolveResult;
convolveResult = convolveResult > maxPix? maxPix:convolveResult;
outBuf[outputOffset] = (T)convolveResult;
}
}
else
{
theTile->setNull(outputOffset);
}
++convolutionCenterOffset;
++convolutionTopLeftOffset;
++outputOffset;
}
}
}
else // do not need to check for nulls here.
{
for(long b = 0; b < outputBands; ++b)
{
double convolveResult = 0;
const T* buf = (const T*)inputTile->getBuf(b);
T* outBuf = (T*)(theTile->getBuf(b));
np =(T)nullPix[b];
outputOffset = 0;
for(long y = 0; y <tileHeight; y++)
{
convolutionTopLeftOffset = patchWidth*(startDelta.y + y - convolutionOffsetY) + startDelta.x-convolutionOffsetX;
for(long x =0; x < tileWidth; x++)
{
kernel->convolveSubImage(&buf[convolutionTopLeftOffset],
patchWidth,
convolveResult,
np);
// NOT SURE IF I WANT TO CLAMP IN A CONVOLUTION SOURCE
// seems better to clamp to a scalar range instead of an input min max
convolveResult = convolveResult < minPix? (T)minPix:convolveResult;
convolveResult = convolveResult > maxPix?(T)maxPix:convolveResult;
outBuf[outputOffset] = (T)convolveResult;
++outputOffset;
++convolutionTopLeftOffset;
}
}
}
}
}
void ossimConvolutionSource::initialize()
{
ossimImageSourceFilter::initialize();
theTile = NULL;
}
void ossimConvolutionSource::allocate()
{
if(theInputConnection)
{
theTile = ossimImageDataFactory::instance()->create(this,
theInputConnection);
theTile->initialize();
}
}
bool ossimConvolutionSource::saveState(ossimKeywordlist& kwl,
const char* prefix)const
{
ossim_uint32 numberOfMatrices = 0;
for(ossim_uint32 m = 0; m < theConvolutionKernelList.size();++m)
{
if(theConvolutionKernelList[m])
{
++numberOfMatrices;
const NEWMAT::Matrix& kernel = theConvolutionKernelList[m]->getKernel();
ossimString mPrefix = "m" +
ossimString::toString(numberOfMatrices) +
".";
kwl.add(prefix,
(mPrefix + "rows").c_str(),
kernel.Nrows(),
true);
kwl.add(prefix,
(mPrefix + "cols").c_str(),
kernel.Ncols(),
true);
for(ossim_int32 row = 0; row < kernel.Nrows(); ++row)
{
for(ossim_int32 col =0; col < kernel.Ncols(); ++col)
{
ossimString newPrefix = mPrefix +
ossimString::toString(row+1) + "_" +
ossimString::toString(col+1);
kwl.add(prefix,
newPrefix,
kernel[row][col],
true);
}
}
}
}
kwl.add(prefix,
NUMBER_OF_MATRICES,
numberOfMatrices,
true);
return ossimImageSourceFilter::saveState(kwl, prefix);
}
bool ossimConvolutionSource::loadState(const ossimKeywordlist& kwl,
const char* prefix)
{
deleteConvolutionList();
const char* numberOfMatrices = kwl.find(prefix, NUMBER_OF_MATRICES);
ossim_int32 matrixCount = ossimString(numberOfMatrices).toLong();
ossim_int32 numberOfMatches = 0;
ossim_int32 index = 0;
while(numberOfMatches < matrixCount)
{
ossimString newPrefix = prefix;
newPrefix += ossimString("m");
newPrefix += ossimString::toString(index);
newPrefix += ossimString(".");
const char* rows = kwl.find((newPrefix+NUMBER_OF_ROWS.key()).c_str());
const char* cols = kwl.find((newPrefix+NUMBER_OF_COLS.key()).c_str());
if(rows&&cols)
{
++numberOfMatches;
ossim_int32 numberOfRows = ossimString(rows).toLong();
ossim_int32 numberOfCols = ossimString(cols).toLong();
NEWMAT::Matrix convolutionMatrix(numberOfRows, numberOfCols);
for(ossim_int32 r = 1; r <= numberOfRows; r++)
{
for(ossim_int32 c = 1; c <= numberOfCols; c++)
{
convolutionMatrix[r-1][c-1] = 0.0;
ossimString value = ossimString::toString(r);
value += "_";
value += ossimString::toString(c);
const char* v = kwl.find(newPrefix.c_str(),
value.c_str());
if(v)
{
convolutionMatrix[r-1][c-1] = ossimString(v).toDouble();
}
}
}
theConvolutionKernelList.push_back(new ossimDiscreteConvolutionKernel(convolutionMatrix));
}
++index;
}
setKernelInformation();
return ossimImageSourceFilter::loadState(kwl, prefix);
}
void ossimConvolutionSource::setKernelInformation()
{
ossim_uint32 index;
if(theConvolutionKernelList.size() > 0)
{
theMaxKernelWidth = theConvolutionKernelList[0]->getWidth();
theMaxKernelHeight = theConvolutionKernelList[0]->getHeight();
for(index = 1; index < theConvolutionKernelList.size(); ++index)
{
ossim_int32 w = theConvolutionKernelList[index]->getWidth();
ossim_int32 h = theConvolutionKernelList[index]->getHeight();
theMaxKernelWidth = theMaxKernelWidth < w?w:theMaxKernelWidth;
theMaxKernelHeight = theMaxKernelHeight < h?h:theMaxKernelHeight;
}
}
}
void ossimConvolutionSource::deleteConvolutionList()
{
for(ossim_int32 index = 0; index < (ossim_int32)theConvolutionKernelList.size(); ++index)
{
delete theConvolutionKernelList[index];
}
theConvolutionKernelList.clear();
}
void ossimConvolutionSource::setConvolution(const NEWMAT::Matrix& convolutionMatrix, bool doWeightedAverage)
{
std::vector<NEWMAT::Matrix> m;
m.push_back(convolutionMatrix);
setConvolutionList(m, doWeightedAverage);
}
| 31.426136
| 124
| 0.560779
|
rkanavath
|
316f7fa87e927b61a192ca89ff949b36a2db3016
| 5,071
|
cpp
|
C++
|
src/source/TMC2660Stepper.cpp
|
ManuelMcLure/TMCStepper
|
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
|
[
"MIT"
] | 336
|
2018-03-26T13:51:46.000Z
|
2022-03-21T21:58:47.000Z
|
src/source/TMC2660Stepper.cpp
|
ManuelMcLure/TMCStepper
|
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
|
[
"MIT"
] | 218
|
2017-07-28T06:13:53.000Z
|
2022-03-26T16:41:21.000Z
|
src/source/TMC2660Stepper.cpp
|
ManuelMcLure/TMCStepper
|
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
|
[
"MIT"
] | 176
|
2018-09-11T22:16:27.000Z
|
2022-03-26T13:04:03.000Z
|
#include "TMCStepper.h"
#include "SW_SPI.h"
TMC2660Stepper::TMC2660Stepper(uint16_t pinCS, float RS) :
_pinCS(pinCS),
Rsense(RS)
{}
TMC2660Stepper::TMC2660Stepper(uint16_t pinCS, uint16_t pinMOSI, uint16_t pinMISO, uint16_t pinSCK) :
_pinCS(pinCS),
Rsense(default_RS)
{
SW_SPIClass *SW_SPI_Obj = new SW_SPIClass(pinMOSI, pinMISO, pinSCK);
TMC_SW_SPI = SW_SPI_Obj;
}
TMC2660Stepper::TMC2660Stepper(uint16_t pinCS, float RS, uint16_t pinMOSI, uint16_t pinMISO, uint16_t pinSCK) :
_pinCS(pinCS),
Rsense(RS)
{
SW_SPIClass *SW_SPI_Obj = new SW_SPIClass(pinMOSI, pinMISO, pinSCK);
TMC_SW_SPI = SW_SPI_Obj;
}
void TMC2660Stepper::switchCSpin(bool state) {
// Allows for overriding in child class to make use of fast io
digitalWrite(_pinCS, state);
}
uint32_t TMC2660Stepper::read() {
uint32_t response = 0UL;
uint32_t dummy = ((uint32_t)DRVCONF_register.address<<17) | DRVCONF_register.sr;
if (TMC_SW_SPI != nullptr) {
switchCSpin(LOW);
response |= TMC_SW_SPI->transfer((dummy >> 16) & 0xFF);
response <<= 8;
response |= TMC_SW_SPI->transfer((dummy >> 8) & 0xFF);
response <<= 8;
response |= TMC_SW_SPI->transfer(dummy & 0xFF);
} else {
SPI.beginTransaction(SPISettings(spi_speed, MSBFIRST, SPI_MODE3));
switchCSpin(LOW);
response |= SPI.transfer((dummy >> 16) & 0xFF);
response <<= 8;
response |= SPI.transfer((dummy >> 8) & 0xFF);
response <<= 8;
response |= SPI.transfer(dummy & 0xFF);
SPI.endTransaction();
}
switchCSpin(HIGH);
return response >> 4;
}
void TMC2660Stepper::write(uint8_t addressByte, uint32_t config) {
uint32_t data = (uint32_t)addressByte<<17 | config;
if (TMC_SW_SPI != nullptr) {
switchCSpin(LOW);
TMC_SW_SPI->transfer((data >> 16) & 0xFF);
TMC_SW_SPI->transfer((data >> 8) & 0xFF);
TMC_SW_SPI->transfer(data & 0xFF);
} else {
SPI.beginTransaction(SPISettings(spi_speed, MSBFIRST, SPI_MODE3));
switchCSpin(LOW);
SPI.transfer((data >> 16) & 0xFF);
SPI.transfer((data >> 8) & 0xFF);
SPI.transfer(data & 0xFF);
SPI.endTransaction();
}
switchCSpin(HIGH);
}
void TMC2660Stepper::begin() {
//set pins
pinMode(_pinCS, OUTPUT);
switchCSpin(HIGH);
//TODO: Push shadow registers
toff(8); //off_time(8);
tbl(1); //blank_time(24);
}
bool TMC2660Stepper::isEnabled() { return toff() > 0; }
uint8_t TMC2660Stepper::test_connection() {
uint32_t drv_status = DRVSTATUS();
switch (drv_status) {
case 0xFFCFF: return 1;
case 0: return 2;
default: return 0;
}
}
/*
Requested current = mA = I_rms/1000
Equation for current:
I_rms = (CS+1)/32 * V_fs/R_sense * 1/sqrt(2)
Solve for CS ->
CS = 32*sqrt(2)*I_rms*R_sense/V_fs - 1
Example:
vsense = 0b0 -> V_fs = 0.310V //Typical
mA = 1650mA = I_rms/1000 = 1.65A
R_sense = 0.100 Ohm
->
CS = 32*sqrt(2)*1.65*0.100/0.310 - 1 = 24,09
CS = 24
*/
uint16_t TMC2660Stepper::cs2rms(uint8_t CS) {
return (float)(CS+1)/32.0 * (vsense() ? 0.165 : 0.310)/(Rsense+0.02) / 1.41421 * 1000;
}
uint16_t TMC2660Stepper::rms_current() {
return cs2rms(cs());
}
void TMC2660Stepper::rms_current(uint16_t mA) {
uint8_t CS = 32.0*1.41421*mA/1000.0*Rsense/0.310 - 1;
// If Current Scale is too low, turn on high sensitivity R_sense and calculate again
if (CS < 16) {
vsense(true);
CS = 32.0*1.41421*mA/1000.0*Rsense/0.165 - 1;
} else { // If CS >= 16, turn off high_sense_r
vsense(false);
}
if (CS > 31)
CS = 31;
cs(CS);
//val_mA = mA;
}
void TMC2660Stepper::push() {
DRVCTRL( sdoff() ? DRVCTRL_1_register.sr : DRVCTRL_0_register.sr);
CHOPCONF(CHOPCONF_register.sr);
SMARTEN(SMARTEN_register.sr);
SGCSCONF(SGCSCONF_register.sr);
DRVCONF(DRVCONF_register.sr);
}
void TMC2660Stepper::hysteresis_end(int8_t value) { hend(value+3); }
int8_t TMC2660Stepper::hysteresis_end() { return hend()-3; };
void TMC2660Stepper::hysteresis_start(uint8_t value) { hstrt(value-1); }
uint8_t TMC2660Stepper::hysteresis_start() { return hstrt()+1; }
void TMC2660Stepper::microsteps(uint16_t ms) {
switch(ms) {
case 256: mres(0); break;
case 128: mres(1); break;
case 64: mres(2); break;
case 32: mres(3); break;
case 16: mres(4); break;
case 8: mres(5); break;
case 4: mres(6); break;
case 2: mres(7); break;
case 0: mres(8); break;
default: break;
}
}
uint16_t TMC2660Stepper::microsteps() {
switch(mres()) {
case 0: return 256;
case 1: return 128;
case 2: return 64;
case 3: return 32;
case 4: return 16;
case 5: return 8;
case 6: return 4;
case 7: return 2;
case 8: return 0;
}
return 0;
}
void TMC2660Stepper::blank_time(uint8_t value) {
switch (value) {
case 16: tbl(0b00); break;
case 24: tbl(0b01); break;
case 36: tbl(0b10); break;
case 54: tbl(0b11); break;
}
}
uint8_t TMC2660Stepper::blank_time() {
switch (tbl()) {
case 0b00: return 16;
case 0b01: return 24;
case 0b10: return 36;
case 0b11: return 54;
}
return 0;
}
| 25.872449
| 111
| 0.649576
|
ManuelMcLure
|
31716dc44479baf6e425aa2d736e7ba7ce0731b8
| 2,504
|
cpp
|
C++
|
decorator.cpp
|
retorillo/twitter-header
|
f00aa4899f6e2ebbbea68566c7e1329663faf966
|
[
"MIT"
] | null | null | null |
decorator.cpp
|
retorillo/twitter-header
|
f00aa4899f6e2ebbbea68566c7e1329663faf966
|
[
"MIT"
] | null | null | null |
decorator.cpp
|
retorillo/twitter-header
|
f00aa4899f6e2ebbbea68566c7e1329663faf966
|
[
"MIT"
] | null | null | null |
#include "decorator.h"
int main(int argc, char** argv) {
if (!PeekNamedPipe(GetStdHandle(STD_INPUT_HANDLE), NULL, NULL, NULL, NULL, NULL)) {
printf("error: no piping input\n");
return -1;
}
std::ostringstream figletout;
char buf[256];
while (fgets(buf, sizeof(buf), stdin))
figletout << buf;
std::string figlet = figletout.str();
auto parseint = [](const char* str) {
// TODO: throws format error
return std::atoi(str);
};
int optc;
int mode = 0;
int padl = 0, padr = 0, padt = 0, padb = 0;
while ((optc = getopt(argc, argv, "m:l:r:t:b:")) != -1) {
switch (optc) {
case 'm': mode = parseint(optarg); break;
case 'l': padl = parseint(optarg); break;
case 'r': padr = parseint(optarg); break;
case 't': padt = parseint(optarg); break;
case 'b': padb = parseint(optarg); break;
}
}
enum mode_t {
mode_mixed = 0,
mode_figlet = 1,
mode_background = 2,
};
int maxw = 0;
for (auto l : lines(figlet))
maxw = std::max(maxw, (int)l.size());
std::string randomstr = "0123456789ABCDEF";
std::random_device rdev;
auto getch = [mode, &rdev, &randomstr]() {
if (mode == mode_figlet) return std::string(" ");
auto min = std::random_device::min(), max = std::random_device::max();
double r = static_cast<double>(rdev() - min) / (max - min);
return randomstr.substr(round(r * (randomstr.size() - 1)), 1);
};
auto padvert = [maxw, padl, padr, getch](int h) {
int w = maxw + padl + padr;
for (int c = 0; c < h * w; c++)
printf(c > 0 && (c + 1) % w == 0 ? "%s\n" : "%s", getch().c_str());
};
padvert(padt);
for (auto l : lines(figlet)) {
for (int c = -padl; c < maxw + padr; c++) {
if (c < 0 || c >= l.size()) {
printf(getch().c_str());
}
else {
if (l[c] == 0x20)
printf(getch().c_str());
else
printf(mode == mode_background ? " " : l.substr(c, 1).c_str());
}
}
printf("\n");
}
padvert(padb);
return 0;
}
std::vector<std::string> lines(std::string str) {
std::regex r("\\r?\\n");
std::string norm = std::regex_replace(str, r, "\n", std::regex_constants::match_any);
std::ostringstream ostr;
std::vector<std::string> vec;
auto push = [&vec, &ostr]() {
if (ostr.str().size() > 0)
vec.push_back(ostr.str());
ostr.str("");
};
for (int c = 0; c < norm.size(); c++) {
if (norm[c] == '\n') push();
else ostr << norm[c];
}
push();
return vec;
}
| 28.781609
| 87
| 0.545927
|
retorillo
|
317eb30a5430c2b6b4f38957885c41795d17e487
| 3,718
|
hpp
|
C++
|
src/stdplus/fd/ops.hpp
|
pzh2386034/stdplus
|
9148977c89406ee3b096dc5a3bd9e8f22abb7764
|
[
"Apache-2.0"
] | 4
|
2018-11-05T10:44:47.000Z
|
2020-11-20T08:16:15.000Z
|
src/stdplus/fd/ops.hpp
|
pzh2386034/stdplus
|
9148977c89406ee3b096dc5a3bd9e8f22abb7764
|
[
"Apache-2.0"
] | 1
|
2020-11-18T22:40:50.000Z
|
2020-11-19T16:14:18.000Z
|
src/stdplus/fd/ops.hpp
|
pzh2386034/stdplus
|
9148977c89406ee3b096dc5a3bd9e8f22abb7764
|
[
"Apache-2.0"
] | 2
|
2018-11-05T10:44:35.000Z
|
2022-01-14T01:47:39.000Z
|
#pragma once
#include <stdplus/fd/intf.hpp>
#include <stdplus/raw.hpp>
#include <stdplus/types.hpp>
#include <utility>
namespace stdplus
{
namespace fd
{
namespace detail
{
void readExact(Fd& fd, span<std::byte> data);
void recvExact(Fd& fd, span<std::byte> data, RecvFlags flags);
void writeExact(Fd& fd, span<const std::byte> data);
void sendExact(Fd& fd, span<const std::byte> data, SendFlags flags);
span<std::byte> readAligned(Fd& fd, size_t align, span<std::byte> buf);
span<std::byte> recvAligned(Fd& fd, size_t align, span<std::byte> buf,
RecvFlags flags);
span<const std::byte> writeAligned(Fd& fd, size_t align,
span<const std::byte> data);
span<const std::byte> sendAligned(Fd& fd, size_t align,
span<const std::byte> data, SendFlags flags);
template <typename Fun, typename Container, typename... Args>
auto alignedOp(Fun&& fun, Fd& fd, Container&& c, Args&&... args)
{
using Data = raw::detail::dataType<Container>;
auto ret = fun(fd, sizeof(Data), raw::asSpan<std::byte>(c),
std::forward<Args>(args)...);
return span<Data>(std::begin(c), ret.size() / sizeof(Data));
}
} // namespace detail
template <typename Container>
inline auto read(Fd& fd, Container&& c)
{
return detail::alignedOp(detail::readAligned, fd,
std::forward<Container>(c));
}
template <typename Container>
inline auto recv(Fd& fd, Container&& c, RecvFlags flags)
{
return detail::alignedOp(detail::recvAligned, fd,
std::forward<Container>(c), flags);
}
template <typename Container>
inline auto write(Fd& fd, Container&& c)
{
return detail::alignedOp(detail::writeAligned, fd,
std::forward<Container>(c));
}
template <typename Container>
inline auto send(Fd& fd, Container&& c, SendFlags flags)
{
return detail::alignedOp(detail::sendAligned, fd,
std::forward<Container>(c), flags);
}
template <typename T>
inline void readExact(Fd& fd, T&& t)
{
detail::readExact(fd, raw::asSpan<std::byte>(t));
}
template <typename T>
inline void recvExact(Fd& fd, T&& t, RecvFlags flags)
{
detail::recvExact(fd, raw::asSpan<std::byte>(t), flags);
}
template <typename T>
inline void writeExact(Fd& fd, T&& t)
{
detail::writeExact(fd, raw::asSpan<std::byte>(t));
}
template <typename T>
inline void sendExact(Fd& fd, T&& t, SendFlags flags)
{
detail::sendExact(fd, raw::asSpan<std::byte>(t), flags);
}
inline size_t lseek(Fd& fd, off_t offset, Whence whence)
{
return fd.lseek(offset, whence);
}
inline void truncate(Fd& fd, off_t size)
{
return fd.truncate(size);
}
template <typename SockAddr>
inline void bind(Fd& fd, SockAddr&& sockaddr)
{
return fd.bind(raw::asSpan<std::byte>(sockaddr));
}
template <typename Opt>
inline void setsockopt(Fd& fd, SockLevel level, SockOpt optname, Opt&& opt)
{
return fd.setsockopt(level, optname, raw::asSpan<std::byte>(opt));
}
template <typename Data>
inline int constIoctl(const Fd& fd, unsigned long id, Data&& data)
{
return fd.constIoctl(id, raw::asSpan<std::byte>(data).data());
}
template <typename Data>
inline int ioctl(Fd& fd, unsigned long id, Data&& data)
{
return fd.ioctl(id, raw::asSpan<std::byte>(data).data());
}
inline FdFlags getFdFlags(const Fd& fd)
{
return fd.fcntlGetfd();
}
inline void setFdFlags(Fd& fd, FdFlags flags)
{
return fd.fcntlSetfd(flags);
}
inline FileFlags getFileFlags(const Fd& fd)
{
return fd.fcntlGetfl();
}
inline void setFileFlags(Fd& fd, FileFlags flags)
{
return fd.fcntlSetfl(flags);
}
} // namespace fd
} // namespace stdplus
| 25.465753
| 79
| 0.653846
|
pzh2386034
|
317faaa00b1b6a123534476f089e762e2bddba9d
| 4,257
|
cpp
|
C++
|
SampleOSXCocoaPodsProject/Pods/BRCLucene/src/core/CLucene/search/ConjunctionScorer.cpp
|
zaubara/BRFullTextSearch
|
e742f223a1c203eacb576711dd57b1187aee3deb
|
[
"Apache-2.0"
] | 151
|
2015-01-17T06:29:38.000Z
|
2022-02-17T11:27:38.000Z
|
SampleOSXCocoaPodsProject/Pods/BRCLucene/src/core/CLucene/search/ConjunctionScorer.cpp
|
yonglam/BRFullTextSearch
|
e742f223a1c203eacb576711dd57b1187aee3deb
|
[
"Apache-2.0"
] | 28
|
2015-03-01T20:14:42.000Z
|
2019-07-22T09:23:54.000Z
|
SampleOSXCocoaPodsProject/Pods/BRCLucene/src/core/CLucene/search/ConjunctionScorer.cpp
|
yonglam/BRFullTextSearch
|
e742f223a1c203eacb576711dd57b1187aee3deb
|
[
"Apache-2.0"
] | 28
|
2015-03-05T13:24:12.000Z
|
2022-03-26T09:16:29.000Z
|
/*------------------------------------------------------------------------------
* Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team
*
* Distributable under the terms of either the Apache License (Version 2.0) or
* the GNU Lesser General Public License, as specified in the COPYING file.
------------------------------------------------------------------------------*/
#include "CLucene/_ApiHeader.h"
#include "_ConjunctionScorer.h"
#include "Similarity.h"
#include "CLucene/util/_Arrays.h"
#include <assert.h>
#include <algorithm>
CL_NS_USE(index)
CL_NS_USE(util)
CL_NS_DEF(search)
ConjunctionScorer::ConjunctionScorer(Similarity* similarity, ScorersType* _scorers):
Scorer(similarity),
firstTime(true),
more(false),
coord(0.0),
lastDoc(-1)
{
this->scorers = _CLNEW CL_NS(util)::ObjectArray<Scorer>(_scorers->size());
_scorers->toArray(this->scorers->values);
coord = getSimilarity()->coord(this->scorers->length, this->scorers->length);
}
ConjunctionScorer::ConjunctionScorer(Similarity* similarity, const CL_NS(util)::ArrayBase<Scorer*>* _scorers):
Scorer(similarity),
firstTime(true),
more(false),
coord(0.0),
lastDoc(-1)
{
this->scorers = _CLNEW CL_NS(util)::ObjectArray<Scorer>(_scorers->length);
memcpy(this->scorers->values, _scorers->values, _scorers->length * sizeof(Scorer*));
coord = getSimilarity()->coord(this->scorers->length, this->scorers->length);
}
ConjunctionScorer::~ConjunctionScorer(){
_CLLDELETE(scorers);
}
TCHAR* ConjunctionScorer::toString(){
return stringDuplicate(_T("ConjunctionScorer"));
}
int32_t ConjunctionScorer::doc() const{
return lastDoc;
}
bool ConjunctionScorer::next() {
if (firstTime) {
init(0);
} else if (more) {
more = scorers->values[(scorers->length-1)]->next();
}
return doNext();
}
bool ConjunctionScorer::doNext() {
int32_t first=0;
Scorer* lastScorer = scorers->values[scorers->length-1];
Scorer* firstScorer;
while (more && (firstScorer=scorers->values[first])->doc() < (lastDoc=lastScorer->doc())) {
more = firstScorer->skipTo(lastDoc);
lastScorer = firstScorer;
first = (first == (scorers->length-1)) ? 0 : first+1;
}
return more;
}
bool ConjunctionScorer::skipTo(int32_t target) {
if (firstTime)
return init(target);
else if (more)
more = scorers->values[(scorers->length-1)]->skipTo(target);
return doNext();
}
int ConjunctionScorer_sort(const void* _elem1, const void* _elem2){
const Scorer* elem1 = *(const Scorer**)_elem1;
const Scorer* elem2 = *(const Scorer**)_elem2;
return elem1->doc() - elem2->doc();
}
bool ConjunctionScorer::init(int32_t target) {
firstTime = false;
more = scorers->length>1;
for (size_t i=0; i<scorers->length; i++) {
more = target==0 ? scorers->values[i]->next() : scorers->values[i]->skipTo(target);
if (!more)
return false;
}
// Sort the array the first time...
// We don't need to sort the array in any future calls because we know
// it will already start off sorted (all scorers on same doc).
// note that this comparator is not consistent with equals!
qsort(scorers->values,scorers->length, sizeof(Scorer*), ConjunctionScorer_sort);
doNext();
// If first-time skip distance is any predictor of
// scorer sparseness, then we should always try to skip first on
// those scorers.
// Keep last scorer in it's last place (it will be the first
// to be skipped on), but reverse all of the others so that
// they will be skipped on in order of original high skip.
int32_t end=(scorers->length-1)-1;
for (int32_t i=0; i<(end>>1); i++) {
Scorer* tmp = scorers->values[i];
scorers->values[i] = scorers->values[end-i];
scorers->values[end-i] = tmp;
}
return more;
}
float_t ConjunctionScorer::score(){
float_t sum = 0.0f;
for (size_t i = 0; i < scorers->length; i++) {
sum += scorers->values[i]->score();
}
return sum * coord;
}
Explanation* ConjunctionScorer::explain(int32_t /*doc*/) {
_CLTHROWA(CL_ERR_UnsupportedOperation,"UnsupportedOperationException: ConjunctionScorer::explain");
}
CL_NS_END
| 31.768657
| 112
| 0.641532
|
zaubara
|
31862c317577bdfcae93770f62f5e108f41bf31c
| 89,640
|
cpp
|
C++
|
Commands.cpp
|
UKTailwind/MMB4W
|
cda50487f2ce23ea1b2a8da79b7b38be46cdece2
|
[
"Unlicense"
] | 3
|
2022-02-20T11:32:27.000Z
|
2022-03-02T21:22:50.000Z
|
Commands.cpp
|
UKTailwind/MMB4W
|
cda50487f2ce23ea1b2a8da79b7b38be46cdece2
|
[
"Unlicense"
] | null | null | null |
Commands.cpp
|
UKTailwind/MMB4W
|
cda50487f2ce23ea1b2a8da79b7b38be46cdece2
|
[
"Unlicense"
] | null | null | null |
/***********************************************************************************************************************
MMBasic for Windows
Commands.cpp
<COPYRIGHT HOLDERS> Geoff Graham, Peter Mather
Copyright (c) 2021, <COPYRIGHT HOLDERS> 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. The name MMBasic be used when referring to the interpreter in any documentation and promotional material and the original copyright message be displayed
on the console at startup (additional copyright messages may be added).
4. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed
by the <copyright holder>.
5. 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 <COPYRIGHT HOLDERS> AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDERS> 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 "olcPixelGameEngine.h"
#include "MainThread.h"
#include "MMBasic_Includes.h"
#include <math.h>
void flist(int, int, int);
//void clearprog(void);
void ListNewLine(int* ListCnt, int all);
void ListProgramFlash(unsigned char* p, int all);
char MMErrMsg[MAXERRMSG]; // the error message
unsigned char* KeyInterrupt = NULL;
volatile int Keycomplete = 0;
int keyselect = 0;
char runcmd[STRINGSIZE] = { 0 };
// stack to keep track of nested FOR/NEXT loops
struct s_forstack forstack[MAXFORLOOPS + 1];
int forindex;
// stack to keep track of nested DO/LOOP loops
struct s_dostack dostack[MAXDOLOOPS];
int doindex; // counts the number of nested DO/LOOP loops
// stack to keep track of GOSUBs, SUBs and FUNCTIONs
unsigned char* gosubstack[MAXGOSUB];
unsigned char* errorstack[MAXGOSUB];
int gosubindex;
unsigned char DimUsed = false; // used to catch OPTION BASE after DIM has been used
int TraceOn; // used to track the state of TRON/TROFF
unsigned char* TraceBuff[TRACE_BUFF_SIZE];
int TraceBuffIndex; // used for listing the contents of the trace buffer
int OptionErrorSkip=0; // how to handle an error
int MMerrno=0; // the error number
int ListCnt;
sa_data datastore[MAXRESTORE];
int restorepointer = 0;
const unsigned int CaseOption = 0xffffffff; // used to store the case of the listed output
void cmd_null(void) {
// do nothing (this is just a placeholder for commands that have no action)
}
// utility routine used by DoDim() below and other places in the interpreter
// checks if the type has been explicitly specified as in DIM FLOAT A, B, ... etc
extern "C" unsigned char* CheckIfTypeSpecified(unsigned char* p, int* type, int AllowDefaultType) {
unsigned char* tp;
if((tp = checkstring(p, (unsigned char*)"INTEGER")) != NULL)
*type = T_INT | T_IMPLIED;
else if((tp = checkstring(p, (unsigned char*)"STRING")) != NULL)
*type = T_STR | T_IMPLIED;
else if((tp = checkstring(p, (unsigned char*)"FLOAT")) != NULL)
*type = T_NBR | T_IMPLIED;
else {
if(!AllowDefaultType) error((char *)"Variable type");
tp = p;
*type = DefaultType; // if the type is not specified use the default
}
return tp;
}
void execute_one_command(unsigned char* p) {
int cmd, i;
CheckAbort();
targ = T_CMD;
skipspace(p); // skip any whitespace
if(*p >= C_BASETOKEN && *p - C_BASETOKEN < CommandTableSize - 1 && (commandtbl[*p - C_BASETOKEN].type & T_CMD)) {
cmd = *p - C_BASETOKEN;
if(*p == cmdWHILE || *p == cmdDO || *p == cmdFOR) error((char*)"Invalid inside THEN ... ELSE");
cmdtoken = *p;
cmdline = p + 1;
skipspace(cmdline);
commandtbl[cmd].fptr(); // execute the command
}
else {
if(!isnamestart(*p)) error((char*)"Invalid character");
i = FindSubFun(p, false); // it could be a defined command
if(i >= 0) // >= 0 means it is a user defined command
DefinedSubFun(false, p, i, NULL, NULL, NULL, NULL);
else
error((char*)"Unknown command");
}
ClearTempMemory(); // at the end of each command we need to clear any temporary string vars
}
void cmd_quit(void) {
SystemMode = MODE_QUIT;
}
void cmd_inc(void) {
unsigned char* p, *q;
int vtype;
getargs(&cmdline, 3, (unsigned char *)",");
if(argc == 1) {
p = (unsigned char *)findvar(argv[0], V_FIND);
if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant");
vtype = TypeMask(vartbl[VarIndex].type);
if(vtype & T_STR) error((char *)"Invalid variable"); // sanity check
if(vtype & T_NBR)
(*(MMFLOAT*)p) = (*(MMFLOAT*)p) + 1.0;
else if(vtype & T_INT)*(long long int*)p = *(long long int*)p + 1;
else error((char *)"Syntax");
}
else {
p = (unsigned char*)findvar(argv[0], V_FIND);
if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant");
vtype = TypeMask(vartbl[VarIndex].type);
if(vtype & T_STR) {
q = getstring(argv[2]);
if (*p + *q > MAXSTRLEN) error((char*)"String too long");
Mstrcat(p, q);
}
else if(vtype & T_NBR) {
(*(MMFLOAT*)p) = (*(MMFLOAT*)p) + getnumber(argv[2]);
}
else if(vtype & T_INT) {
*(long long int*)p = *(long long int*)p + getinteger(argv[2]);
}
else error((char *)"syntax");
}
}
// the PRINT command
void cmd_print(void) {
unsigned char* s, * p;
unsigned char* ss;
MMFLOAT f;
long long int i64;
int i, t, fnbr;
int docrlf; // this is used to suppress the cr/lf if needed
getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, (unsigned char*)";,"); // this is a macro and must be the first executable stmt
// s = 0; *s = 56; // for testing the exception handler
docrlf = true;
if(argc > 0 && *argv[0] == '#') { // check if the first arg is a file number
argv[0]++;
if((*argv[0] == 'G') || (*argv[0] == 'g')) {
argv[0]++;
if(!((*argv[0] == 'P') || (*argv[0] == 'p')))error((char *)"Syntax");
argv[0]++;
if(!((*argv[0] == 'S') || (*argv[0] == 's')))error((char *)"Syntax");
if(!GPSchannel) error((char *)"GPS not activated");
if(argc != 3) error((char *)"Only a single string parameter allowed");
p = argv[2];
t = T_NOTYPE;
p = evaluate(p, &f, &i64, &s, &t, true); // get the value and type of the argument
ss = (unsigned char*)s;
if(!(t & T_STR)) error((char *)"Only a single string parameter allowed");
int i, xsum = 0;
if(ss[1] != '$' || ss[ss[0]] != '*')error((char *)"GPS command must start with dollar and end with star");
for (i = 1; i <= ss[0]; i++) {
SerialPutchar(GPSchannel, s[i]);
if(s[i] == '$')xsum = 0;
if(s[i] != '*')xsum ^= s[i];
}
i = xsum / 16;
i = i + '0';
if(i > '9')i = i - '0' + 'A';
SerialPutchar(GPSchannel, i);
i = xsum % 16;
i = i + '0';
if(i > '9')i = i - '0' + 'A';
SerialPutchar(GPSchannel, i);
SerialPutchar(GPSchannel, 13);
SerialPutchar(GPSchannel, 10);
return;
}
else {
fnbr = (int)getinteger(argv[0]); // get the number
i = 1;
if(argc >= 2 && *argv[1] == ',') i = 2; // and set the next argument to be looked at
}
}
else {
fnbr = 0; // no file number so default to the standard output
i = 0;
}
if (argc >= 3) {
if (checkstring(argv[2], (unsigned char*)"BREAK")) {
if (FileTable[fnbr].com == 0 || FileTable[fnbr].com > MAXCOMPORTS)error((char*)"Syntax");
SendBreak(fnbr);
return;
}
}
for (; i < argc; i++) { // step through the arguments
if(*argv[i] == ',') {
MMfputc('\t', fnbr); // print a tab for a comma
docrlf = false; // a trailing comma should suppress CR/LF
}
else if(*argv[i] == ';') {
docrlf = false; // other than suppress cr/lf do nothing for a semicolon
}
else { // we have a normal expression
p = argv[i];
while (*p) {
t = T_NOTYPE;
p = evaluate(p, &f, &i64, &s, &t, true); // get the value and type of the argument
if(t & T_NBR) {
*inpbuf = ' '; // preload a space
FloatToStr((char *)(inpbuf + ((f >= 0) ? 1 : 0)), f, 0, STR_AUTO_PRECISION, ' ');// if positive output a space instead of the sign
MMfputs((unsigned char*)CtoM(inpbuf), fnbr); // convert to a MMBasic string and output
}
else if(t & T_INT) {
*inpbuf = ' '; // preload a space
IntToStr((char *)(inpbuf + ((i64 >= 0) ? 1 : 0)), i64, 10); // if positive output a space instead of the sign
MMfputs((unsigned char*)CtoM(inpbuf), fnbr); // convert to a MMBasic string and output
}
else if(t & T_STR) {
MMfputs((unsigned char*)s, fnbr); // print if a string (s is a MMBasic string)
}
else error((char *)"Attempt to print reserved word");
}
docrlf = true;
}
}
if(docrlf) MMfputs((unsigned char*)"\2\r\n", fnbr); // print the terminating cr/lf unless it has been suppressed
PrintPixelMode = 0;
}
void cmd_debug(void) {
unsigned char* s, * p;
MMFLOAT f;
long long int i64;
int i, t, fnbr;
int docrlf; // this is used to suppress the cr/lf if needed
getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, (unsigned char*)";,"); // this is a macro and must be the first executable stmt
// s = 0; *s = 56; // for testing the exception handler
docrlf = true;
{
fnbr = 99999; // no file number so default to the standard output
i = 0;
}
for (; i < argc; i++) { // step through the arguments
if (*argv[i] == ',') {
MMfputc('\t', fnbr); // print a tab for a comma
docrlf = false; // a trailing comma should suppress CR/LF
}
else if (*argv[i] == ';') {
docrlf = false; // other than suppress cr/lf do nothing for a semicolon
}
else { // we have a normal expression
p = argv[i];
while (*p) {
t = T_NOTYPE;
p = evaluate(p, &f, &i64, &s, &t, true); // get the value and type of the argument
if (t & T_NBR) {
*inpbuf = ' '; // preload a space
FloatToStr((char*)(inpbuf + ((f >= 0) ? 1 : 0)), f, 0, STR_AUTO_PRECISION, ' ');// if positive output a space instead of the sign
MMfputs((unsigned char*)CtoM(inpbuf), fnbr); // convert to a MMBasic string and output
}
else if (t & T_INT) {
*inpbuf = ' '; // preload a space
IntToStr((char*)(inpbuf + ((i64 >= 0) ? 1 : 0)), i64, 10); // if positive output a space instead of the sign
MMfputs((unsigned char*)CtoM(inpbuf), fnbr); // convert to a MMBasic string and output
}
else if (t & T_STR) {
MMfputs((unsigned char*)s, fnbr); // print if a string (s is a MMBasic string)
}
else error((char*)"Attempt to print reserved word");
}
docrlf = true;
}
}
if (docrlf) MMfputs((unsigned char*)"\2\r\n", fnbr); // print the terminating cr/lf unless it has been suppressed
PrintPixelMode = 0;
}
// the LET command
// because the LET is implied (ie, line does not have a recognisable command)
// it ends up as the place where mistyped commands are discovered. This is why
// the error message is "Unknown command"
void cmd_let(void) {
int t, size;
MMFLOAT f;
long long int i64;
unsigned char* s;
unsigned char* p1, *p2;
p1 = cmdline;
// search through the line looking for the equals sign
while (*p1 && tokenfunction(*p1) != op_equal) p1++;
if(!*p1) error((char *)"Unknown command");
// check that we have a straight forward variable
p2 = skipvar(cmdline, false);
skipspace(p2);
if(p1 != p2) error((char *)"Syntax");
// create the variable and get the length if it is a string
p2 = (unsigned char *)findvar(cmdline, V_FIND);
size = vartbl[VarIndex].size;
if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant");
// step over the equals sign, evaluate the rest of the command and save in the variable
p1++;
if(vartbl[VarIndex].type & T_STR) {
t = T_STR;
p1 = evaluate(p1, &f, &i64, &s, &t, false);
if(*s > size) error((char *)"String too long");
Mstrcpy(p2, s);
}
else if(vartbl[VarIndex].type & T_NBR) {
t = T_NBR;
p1 = evaluate(p1, &f, &i64, &s, &t, false);
if(t & T_NBR)
(*(MMFLOAT*)p2) = f;
else
(*(MMFLOAT*)p2) = (MMFLOAT)i64;
}
else {
t = T_INT;
p1 = evaluate(p1, &f, &i64, &s, &t, false);
if(t & T_INT)
(*(long long int*)p2) = i64;
else
(*(long long int*)p2) = FloatToInt64(f);
}
checkend(p1);
}
int as_strcmpi(const char* s1, const char* s2)
{
const unsigned char* p1 = (const unsigned char*)s1;
const unsigned char* p2 = (const unsigned char*)s2;
unsigned char c1, c2;
if(p1 == p2)
return 0;
do
{
c1 = tolower(*p1++);
c2 = tolower(*p2++);
if(c1 == '\0')
break;
} while (c1 == c2);
return c1 - c2;
}
void sortStrings(char** arr, int n)
{
char temp[16];
int i, j;
// Sorting strings using bubble sort
for (j = 0; j < n - 1; j++)
{
for (i = j + 1; i < n; i++)
{
if(as_strcmpi(arr[j], arr[i]) > 0)
{
strcpy(temp, arr[j]);
strcpy(arr[j], arr[i]);
strcpy(arr[i], temp);
}
}
}
}
void sortPorts(char** arr, int n)
{
char temp[16];
int i, j;
// Sorting strings using bubble sort
for (j = 0; j < n - 1; j++)
{
for (i = j + 1; i < n; i++)
{
char** c=NULL;
int a = strtol((const char *) & arr[j][3], c, 10);
int b = strtol((const char*)&arr[i][3], c, 10);
if (a>b)
{
strcpy(temp, arr[j]);
strcpy(arr[j], arr[i]);
strcpy(arr[i], temp);
}
}
}
}
void ListFile(char* pp, int all) {
/****** char buff[STRINGSIZE];
FRESULT fr;
FILINFO fno;
int fnbr;
int i, ListCnt = 1;
fr = f_stat(pp, &fno);
if(fr == FR_OK && !(fno.fattrib & AM_DIR)) {
fnbr = FindFreeFileNbr();
if(!BasicFileOpen(pp, fnbr, FA_READ)) return;
while (!FileEOF(fnbr)) { // while waiting for the end of file
memset(buff, 0, 256);
MMgetline(fnbr, (char*)buff); // get the input line
for (i = 0; i < strlen(buff); i++)if(buff[i] == TAB) buff[i] = ' ';
MMPrintString(buff);
ListCnt += strlen(buff) / OptionWidth;
ListNewLine(&ListCnt, all);
}
FileClose(fnbr);
}
else error((char *)"File not found");*/
}
void QueryKey(HKEY hKey)
{
LPSTR achKey=(LPSTR)GetTempMemory(STRINGSIZE); // buffer for subkey name
TCHAR achClass[MAX_PATH] = TEXT(""); // buffer for class name
DWORD cchClassName = MAX_PATH; // size of class string
DWORD cSubKeys = 0; // number of subkeys
DWORD cbMaxSubKey; // longest subkey size
DWORD cchMaxClass; // longest class string
DWORD cValues; // number of values for key
DWORD cchMaxValue; // longest value name
DWORD cbMaxValueData; // longest value data
DWORD cbSecurityDescriptor; // size of security descriptor
FILETIME ftLastWriteTime; // last write time
DWORD i, retCode;
DWORD cchValue = 255;
// Get the class name and the value count.
retCode = RegQueryInfoKey(
hKey, // key handle
achClass, // buffer for class name
&cchClassName, // size of class string
NULL, // reserved
&cSubKeys, // number of subkeys
&cbMaxSubKey, // longest subkey size
&cchMaxClass, // longest class string
&cValues, // number of values for this key
&cchMaxValue, // longest value name
&cbMaxValueData, // longest value data
&cbSecurityDescriptor, // security descriptor
&ftLastWriteTime); // last write time
// Enumerate the subkeys, until RegEnumKeyEx fails.
// Enumerate the key values.
if (cValues>0 && cValues<=128 && retCode== ERROR_SUCCESS)
{
char** c = (char**)GetTempMemory((cValues) * sizeof(*c) + (cValues) *(cchMaxValue + 1));
MMPrintString((char *)"Number of com ports : ");
PInt(cValues);
PRet();
char *b = (char *)GetTempMemory(cbMaxValueData+1);
LPSTR achValue = (LPSTR)GetTempMemory(cchMaxValue+1);
DWORD fred= cbMaxValueData+1;
for (i = 0, retCode = ERROR_SUCCESS; i < cValues; i++)
{
cchValue = 255;
achValue[0] = '\0';
memset(b,0, cbMaxValueData + 1);
fred = cbMaxValueData + 1;
retCode = RegEnumValueA(hKey, i,
achValue,
&cchValue,
NULL,
NULL,
(LPBYTE)b,
&fred);
if (retCode == ERROR_SUCCESS)
{
c[i] = (char*)((int)c + sizeof(char*) * (cValues) + i * (cchMaxValue + 1));
strcpy(c[i], b);
}
}
sortPorts(c, cValues);
for (int j = 0; j < (int)cValues; j++) {
MMPrintString(c[j]);
PRet();
}
}
}
void cmd_list(void) {
unsigned char* p;
int i, j, k, m, step;
if((p = checkstring(cmdline, (unsigned char*)"ALL"))) {
if(!(*p == 0 || *p == '\'')) {
getargs(&p, 1, (unsigned char *)",");
char* buff = (char *)GetTempMemory(STRINGSIZE);
strcpy(buff, (const char *)getCstring(argv[0]));
if(strchr(buff, '.') == NULL) strcat(buff, ".BAS");
ListProgram((unsigned char*)buff, true);
}
else {
ListProgram(NULL, true);
checkend(p);
}
}
else if ((p = checkstring(cmdline, (unsigned char*)"FLASH"))) {
ListProgramFlash((unsigned char*)ProgMemory, false);
checkend(p);
}
else if (p = checkstring(cmdline, (unsigned char *)"PAGES")) {
PO("MODE ", 3); MMPrintString((char*)" has "); PInt(MAXPAGES+1); MMPrintString((char*)" pages\r\n");
MMPrintString((char*)"Page no. Page Address Width Height Size "); PRet();
for (int i = 0; i <= MAXPAGES; i++) {
MMPrintString((char*)" ");
if (i < 10)MMPrintString((char*)" ");
PInt(i);
MMPrintString((char *)" &H");
PIntH((uint32_t)PageTable[i].address);
if (PageTable[i].xmax < 1000)MMPrintString((char*)" ");
else MMPrintString((char*)" ");
PInt((uint32_t)PageTable[i].xmax);
MMPrintString((char*)" ");
PInt((uint32_t)PageTable[i].ymax);
if (PageTable[i].size < 0xFFFF)MMPrintString((char*)" ");
MMPrintString((char*)" &H");
PIntH((uint32_t)PageTable[i].size);
PRet();
}
}
else if ((p = checkstring(cmdline, (unsigned char*)"COM PORTS"))) {
HKEY hregkey;
LSTATUS res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DEVICEMAP\\SERIALCOMM"), 0, KEY_READ, &hregkey);
QueryKey(hregkey);
RegCloseKey((HKEY)hregkey);
}
else if ((p = checkstring(cmdline, (unsigned char*)"FILE ALL"))) {
getargs(&p, 1, (unsigned char*)",");
char* buff = (char*)GetTempMemory(STRINGSIZE);
strcpy(buff, (char*)getCstring(argv[0]));
if (strchr(buff, '.') == NULL) strcat(buff, ".BAS");
ListProgram((unsigned char*)buff, true);
}
else if ((p = checkstring(cmdline, (unsigned char*)"FILE"))) {
getargs(&p, 1, (unsigned char *)",");
char* buff = (char *)GetTempMemory(STRINGSIZE);
strcpy(buff, (char *)getCstring(argv[0]));
if (strchr(buff, '.') == NULL) strcat(buff, ".BAS");
ListProgram((unsigned char *)buff, false);
}
else if ((p = checkstring(cmdline, (unsigned char*)"COMMANDS"))) {
step = OptionWidth/18;
m = 0;
char** c = (char **)GetTempMemory((CommandTableSize + 5) * sizeof(*c) + (CommandTableSize + 5) * 18);
for (i = 0; i < CommandTableSize + 5; i++) {
c[m] = (char*)((int)c + sizeof(char*) * (CommandTableSize + 5) + m * 18);
if(m < CommandTableSize)strcpy(c[m], (const char *)commandtbl[i].name);
else if(m == CommandTableSize)strcpy(c[m], "Color");
else if(m == CommandTableSize + 1)strcpy(c[m], "Else If");
else if(m == CommandTableSize + 2)strcpy(c[m], "End If");
else if(m == CommandTableSize + 3)strcpy(c[m], "Exit Do");
else strcpy(c[m], "Cat");
if(strcasecmp(c[m],"CSub")!=0 && strcasecmp(c[m], "End CSub") != 0)m++;
}
sortStrings(c, m);
for (i = 1; i < m; i += step) {
for (k = 0; k < step; k++) {
if(i + k < m) {
MMPrintString(c[i + k]);
if(k != (step - 1))for (j = strlen(c[i + k]); j < 15; j++)MMputchar(' ');
}
}
MMPrintString((char *)"\r\n");
}
MMPrintString((char *)"Total of "); PInt(m - 1); MMPrintString((char *)" commands\r\n");
}
else if((p = checkstring(cmdline, (unsigned char*)"FUNCTIONS"))) {
m = 0;
step = OptionWidth / 18;
char** c = (char**)GetTempMemory((TokenTableSize + 5) * sizeof(*c) + (TokenTableSize + 5) * 18);
for (i = 0; i < TokenTableSize + 5; i++) {
c[m] = (char*)((int)c + sizeof(char*) * (TokenTableSize + 5) + m * 18);
if(m < TokenTableSize)strcpy(c[m], (const char*)tokentbl[i].name);
else if(m == TokenTableSize)strcpy(c[m], "=>");
else if(m == TokenTableSize + 1)strcpy(c[m], "=<");
/* else if(m==TokenTableSize+2)strcpy(c[m],"OCT$(");
else if(m==TokenTableSize+3)strcpy(c[m],"HEX$(");
else if(m==TokenTableSize+4)strcpy(c[m],"MM.I2C");
*/ else if(m == TokenTableSize + 2)strcpy(c[m], "MM.Fontheight");
else if(m == TokenTableSize + 3)strcpy(c[m], "MM.Fontwidth");
else strcpy(c[m], "MM.Info$(");
m++;
}
sortStrings(c, m);
for (i = 1; i < m; i += step) {
for (k = 0; k < step; k++) {
if(i + k < m) {
MMPrintString(c[i + k]);
if(k != (step - 1))for (j = strlen(c[i + k]); j < 15; j++)MMputchar(' ');
}
}
MMPrintString((char *)"\r\n");
}
MMPrintString((char *)"Total of "); PInt(m - 1); MMPrintString((char *)" functions and operators\r\n");
}
else {
if(!(*cmdline == 0 || *cmdline == '\'')) {
getargs(&cmdline, 1, (unsigned char *)",");
char* buff = (char *)GetTempMemory(STRINGSIZE);
strcpy(buff, (const char*)getCstring(argv[0]));
if(strchr(buff, '.') == NULL) strcat(buff, ".BAS");
ListProgram((unsigned char*)buff, false);
}
else {
ListProgram(NULL, false);
checkend(cmdline);
}
}
}
void ListNewLine(int* ListCnt, int all) {
MMPrintString((char *)"\r\n");
(*ListCnt)++;
if(!all && *ListCnt >= OptionHeight) {
MMPrintString((char *)"PRESS ANY KEY ...");
MMgetchar();
MMPrintString((char *)"\r \r");
*ListCnt = 1;
}
}
void ListProgramFlash(unsigned char* p, int all) {
char b[STRINGSIZE];
char* pp;
int ListCnt = 1;
while (!(*p == 0 || *p == 0xff)) { // normally a LIST ends at the break so this is a safety precaution
if(*p == T_NEWLINE) {
p = llist((unsigned char*) b, (unsigned char *)p); // otherwise expand the line
pp = b;
while (*pp) {
if(MMCharPos >= OptionWidth) ListNewLine(&ListCnt, all);
MMputchar(*pp++);
}
ListNewLine(&ListCnt, all);
if(p[0] == 0 && p[1] == 0) break; // end of the listing ?
}
}
}
void ListProgram(unsigned char* pp, int all) {
char buff[STRINGSIZE];
int fnbr;
int i, ListCnt = 1;
if (pp == NULL) {
if (!*lastfileedited)error((char*)"Nothing to list");
strcpy(buff, lastfileedited);
}
else {
fullfilename((char *)pp, buff, NULL);
}
if(!existsfile(buff))error((char*)"File not found");
fnbr = FindFreeFileNbr();
if (!BasicFileOpen((char *)buff, fnbr, (char *)"rb")) return;
while (!MMfeof(fnbr)) { // while waiting for the end of file
memset(buff, 0, 256);
MMgetline(fnbr, (char*)buff); // get the input line
for (i = 0; i < (int)strlen(buff); i++)if (buff[i] == TAB) buff[i] = ' ';
MMPrintString(buff);
ListCnt += strlen(buff) / OptionWidth;
ListNewLine(&ListCnt, all);
}
FileClose(fnbr);
}
void execute(char* mycmd) {
// char *temp_tknbuf;
unsigned char* ttp;
int i = 0, toggle = 0;
// temp_tknbuf = GetTempStrMemory();
// strcpy(temp_tknbuf, tknbuf);
// first save the current token buffer in case we are in immediate mode
// we have to fool the tokeniser into thinking that it is processing a program line entered at the console
skipspace(mycmd);
strcpy((char *)inpbuf, (const char *)getCstring((unsigned char *)mycmd)); // then copy the argument
if (!(toupper(inpbuf[0]) == 'R' && toupper(inpbuf[1]) == 'U' && toupper(inpbuf[2]) == 'N')) { //convert the string to upper case
while (inpbuf[i]) {
if (inpbuf[i] == 34) {
if (toggle == 0)toggle = 1;
else toggle = 0;
}
if (!toggle) {
if (inpbuf[i] == ':')error((char *)"Only single statements allowed");
inpbuf[i] = toupper(inpbuf[i]);
}
i++;
}
tokenise(true); // and tokenise it (the result is in tknbuf)
memset(inpbuf, 0, STRINGSIZE);
tknbuf[strlen((char *)tknbuf)] = 0;
tknbuf[strlen((char*)tknbuf) + 1] = 0;
ttp = nextstmt; // save the globals used by commands
ScrewUpTimer = 1000;
ExecuteProgram(tknbuf); // execute the function's code
ScrewUpTimer = 0;
// TempMemoryIsChanged = true; // signal that temporary memory should be checked
nextstmt = ttp;
return;
}
else {
unsigned char* p = inpbuf;
char * s=NULL;
char fn[STRINGSIZE] = { 0 };
p[0] = GetCommandValue((unsigned char *)"RUN");
memmove(&p[1], &p[4], strlen((char *)p) - 4);
p[strlen((char*)p) - 3] = 0;
// MMPrintString(fn); PRet();
CloseAudio(1);
strcpy((char *)tknbuf, (char*)inpbuf);
longjmp(jmprun, 1);
}
}
void cmd_execute(void) {
execute((char*)cmdline);
}
void cmd_run(void) {
skipspace(cmdline);
memset(runcmd, 0, STRINGSIZE);
memcpy(runcmd, cmdline, strlen((char *)cmdline));
if (*cmdline && *cmdline != '\'') {
if (!FileLoadProgram(cmdline, 0)) return;
}
else {
if (*lastfileedited == 0)error((char*)"Nothing to run");
if (!FileLoadProgram((unsigned char *)lastfileedited, 1)) return;
}
ClearRuntime();
WatchdogSet = false;
PrepareProgram(true);
IgnorePIN = false;
if(*ProgMemory != T_NEWLINE) return; // no program to run
nextstmt = ProgMemory;
}
void cmd_continue(void) {
if(*cmdline == tokenFOR) {
if(forindex == 0) error((char *)"No FOR loop is in effect");
nextstmt = forstack[forindex - 1].nextptr;
return;
}
if(checkstring(cmdline, (unsigned char*)"DO")) {
if(doindex == 0) error((char *)"No DO loop is in effect");
nextstmt = dostack[doindex - 1].loopptr;
return;
}
// must be a normal CONTINUE
checkend(cmdline);
if(CurrentLinePtr) error((char *)"Invalid in a program");
if(ContinuePoint == NULL) error((char *)"Cannot continue");
// IgnorePIN = false;
nextstmt = ContinuePoint;
}
void cmd_new(void) {
checkend(cmdline);
ClearProgram();
uSec(250000);
memset(inpbuf, 0, STRINGSIZE);
memset(lastfileedited, 0, STRINGSIZE);
memset(Option.lastfilename, 0, STRINGSIZE);
SaveOptions();
longjmp(mark, 1); // jump back to the input prompt
}
void cmd_erase(void) {
int i, j, k, len;
char p[MAXVARLEN + 1], * s, * x;
getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, (unsigned char *)","); // getargs macro must be the first executable stmt in a block
if((argc & 0x01) == 0) error((char *)"Argument count");
for (i = 0; i < argc; i += 2) {
strcpy((char*)p, (const char *)argv[i]);
while (!isnamechar(p[strlen(p) - 1])) p[strlen(p) - 1] = 0;
makeupper((unsigned char *)p); // all variables are stored as uppercase
for (j = MAXVARS / 2; j < MAXVARS; j++) {
s = p; x = vartbl[j].name; len = strlen(p);
while (len > 0 && *s == *x) { // compare the variable to the name that we have
len--; s++; x++;
}
if(!(len == 0 && (*x == 0 || strlen(p) == MAXVARLEN))) continue;
// found the variable
if(((vartbl[i].type & T_STR) || vartbl[i].dims[0] != 0) && !(vartbl[i].type & T_PTR)) {
FreeMemory((unsigned char *)vartbl[i].val.s); // free any memory (if allocated)
vartbl[i].val.s = NULL;
}
k = i + 1;
if(k == MAXVARS)k = MAXVARS / 2;
if(vartbl[k].type) {
vartbl[j].name[0] = '~';
vartbl[j].type = T_BLOCKED;
}
else {
vartbl[j].name[0] = 0;
vartbl[j].type = T_NOTYPE;
}
vartbl[i].dims[0] = 0; // and again
vartbl[i].level = 0;
Globalvarcnt--;
break;
}
if(j == MAXVARS) error((char *)"Cannot find $", p);
}
}
void cmd_clear(void) {
checkend(cmdline);
if(LocalIndex)error((char *)"Invalid in a subroutine");
ClearVars(0);
}
void cmd_goto(void) {
if(isnamestart(*cmdline))
nextstmt = findlabel(cmdline); // must be a label
else
nextstmt = findline((int)getinteger(cmdline), true); // try for a line number
CurrentLinePtr = nextstmt;
}
void cmd_if(void) {
int r, i, testgoto, testelseif;
unsigned char ss[3]; // this will be used to split up the argument line
unsigned char* p, * tp;
unsigned char* rp = NULL;
ss[0] = tokenTHEN;
ss[1] = tokenELSE;
ss[2] = 0;
testgoto = false;
testelseif = false;
retest_an_if:
{ // start a new block
getargs(&cmdline, 20, ss); // getargs macro must be the first executable stmt in a block
if(testelseif && argc > 2) error((char *)"Unexpected text");
// if there is no THEN token retry the test with a GOTO. If that fails flag an error
if(argc < 2 || *argv[1] != ss[0]) {
if(testgoto) error((char *)"IF without THEN");
ss[0] = tokenGOTO;
testgoto = true;
goto retest_an_if;
}
// allow for IF statements embedded inside this IF
if(argc >= 3 && *argv[2] == cmdIF) argc = 3; // this is IF xx=yy THEN IF ... so we want to evaluate only the first 3
if(argc >= 5 && *argv[4] == cmdIF) argc = 5; // this is IF xx=yy THEN cmd ELSE IF ... so we want to evaluate only the first 5
if(argc == 4 || (argc == 5 && *argv[3] != ss[1])) error((char *)"Syntax");
r = (getnumber(argv[0]) != 0); // evaluate the expression controlling the if statement
if(r) {
// the test returned TRUE
// first check if it is a multiline if(ie, only 2 args)
if(argc == 2) {
// if multiline do nothing, control will fall through to the next line (which is what we want to execute next)
;
}
else {
// This is a standard single line IF statement
// Because the test was TRUE we are just interested in the THEN cmd stage.
if(*argv[1] == tokenGOTO) {
cmdline = argv[2];
cmd_goto();
return;
}
else if(isdigit(*argv[2])) {
nextstmt = findline((int)getinteger(argv[2]), true);
}
else {
if(argc == 5) {
// this is a full IF THEN ELSE and the statement we want to execute is between the THEN & ELSE
// this is handled by a special routine
execute_one_command((unsigned char *)argv[2]);
}
else {
// easy - there is no ELSE clause so just point the next statement pointer to the byte after the THEN token
for (p = cmdline; *p && *p != ss[0]; p++); // search for the token
nextstmt = p + 1; // and point to the byte after
}
}
}
}
else {
// the test returned FALSE so we are just interested in the ELSE stage (if present)
// first check if it is a multiline if(ie, only 2 args)
if(argc == 2) {
// search for the next ELSE, or ENDIF and pass control to the following line
// if an ELSEIF is found re execute this function to evaluate the condition following the ELSEIF
i = 1; p = nextstmt;
while (1) {
p = GetNextCommand(p, &rp, (unsigned char *)"No matching ENDIF");
if(*p == cmdtoken) {
// found a nested IF command, we now need to determine if it is a single or multiline IF
// search for a THEN, then check if only white space follows. If so, it is multiline.
tp = p + 1;
while (*tp && *tp != ss[0]) tp++;
if(*tp) tp++; // step over the THEN
skipspace(tp);
if(*tp == 0 || *tp == '\'') // yes, only whitespace follows
i++; // count it as a nested IF
else // no, it is a single line IF
skipelement(p); // skip to the end so that we avoid an ELSE
continue;
}
if(*p == cmdELSE && i == 1) {
// found an ELSE at the same level as this IF. Step over it and continue with the statement after it
skipelement(p);
nextstmt = p;
break;
}
if((*p == cmdELSEIF) && i == 1) {
// we have found an ELSEIF statement at the same level as our IF statement
// setup the environment to make this function evaluate the test following ELSEIF and jump back
// to the start of the function. This is not very clean (it uses the dreaded goto for a start) but it works
p++; // step over the token
skipspace(p);
CurrentLinePtr = rp;
if(*p == 0) error((char *)"Syntax"); // there must be a test after the elseif
cmdline = p;
skipelement(p);
nextstmt = p;
testgoto = false;
testelseif = true;
goto retest_an_if;
}
if(*p == cmdENDIF) i--; // found an ENDIF so decrement our nested counter
if(i == 0) {
// found our matching ENDIF stmt. Step over it and continue with the statement after it
skipelement(p);
nextstmt = p;
break;
}
}
}
else {
// this must be a single line IF statement
// check if there is an ELSE on the same line
if(argc == 5) {
// there is an ELSE command
if(isdigit(*argv[4]))
// and it is just a number, so get it and find the line
nextstmt = findline((int)getinteger(argv[4]), true);
else {
// there is a statement after the ELSE clause so just point to it (the byte after the ELSE token)
for (p = cmdline; *p && *p != ss[1]; p++); // search for the token
nextstmt = p + 1; // and point to the byte after
}
}
else {
// no ELSE on a single line IF statement, so just continue with the next statement
skipline(cmdline);
nextstmt = cmdline;
}
}
}
}
}
void cmd_else(void) {
int i;
unsigned char* p, * tp;
// search for the next ENDIF and pass control to the following line
i = 1; p = nextstmt;
if(cmdtoken == cmdELSE) checkend(cmdline);
while (1) {
p = GetNextCommand(p, NULL, (unsigned char *)"No matching ENDIF");
if(*p == cmdIF) {
// found a nested IF command, we now need to determine if it is a single or multiline IF
// search for a THEN, then check if only white space follows. If so, it is multiline.
tp = p + 1;
while (*tp && *tp != tokenTHEN) tp++;
if(*tp) tp++; // step over the THEN
skipspace(tp);
if(*tp == 0 || *tp == '\'') // yes, only whitespace follows
i++; // count it as a nested IF
}
if(*p == cmdENDIF) i--; // found an ENDIF so decrement our nested counter
if(i == 0) break; // found our matching ENDIF stmt
}
// found a matching ENDIF. Step over it and continue with the statement after it
skipelement(p);
nextstmt = p;
}
void cmd_end(void) {
checkend(cmdline);
memset(inpbuf, 0, STRINGSIZE);
longjmp(mark, 1); // jump back to the input prompt
}
void cmd_select(void) {
int i, type;
unsigned char* p, * rp = NULL, * SaveCurrentLinePtr;
void* v;
MMFLOAT f = 0;
long long int i64 = 0;
unsigned char s[STRINGSIZE];
// these are the tokens that we will be searching for
// they are cached the first time this command is called
type = T_NOTYPE;
v = DoExpression(cmdline, &type); // evaluate the select case value
type = TypeMask(type);
if(type & T_NBR) f = *(MMFLOAT*)v;
if(type & T_INT) i64 = *(long long int*)v;
if(type & T_STR) Mstrcpy((unsigned char*)s, (unsigned char*)v);
// now search through the program looking for a matching CASE statement
// i tracks the nesting level of any nested SELECT CASE commands
SaveCurrentLinePtr = CurrentLinePtr; // save where we are because we will have to fake CurrentLinePtr to get errors reported correctly
i = 1; p = nextstmt;
while(1) {
p = GetNextCommand(p, &rp, (unsigned char*)"No matching END SELECT");
if(*p == cmdSELECT_CASE) i++; // found a nested SELECT CASE command, increase the nested count and carry on searching
// is this a CASE stmt at the same level as this SELECT CASE.
if(*p == cmdCASE && i == 1) {
int t;
MMFLOAT ft, ftt;
long long int i64t, i64tt;
unsigned char* st, * stt;
CurrentLinePtr = rp; // and report errors at the line we are on
// loop through the comparison elements on the CASE line. Each element is separated by a comma
do {
p++;
skipspace(p);
t = type;
// check for CASE IS, eg CASE IS > 5 -or- CASE > 5 and process it if it is
// an operator can be >, <>, etc but it can also be a prefix + or - so we must not catch them
if((SaveCurrentLinePtr = checkstring(p, (unsigned char*)"IS")) || ((tokentype(*p) & T_OPER) && !(*p == GetTokenValue((unsigned char*)"+") || *p == GetTokenValue((unsigned char*)"-")))) {
int o;
if(SaveCurrentLinePtr) p += 2;
skipspace(p);
if(tokentype(*p) & T_OPER)
o = *p++ - C_BASETOKEN; // get the operator
else
error((char *)"Syntax");
if(type & T_NBR) ft = f;
if(type & T_INT) i64t = i64;
if(type & T_STR) st = s;
while (o != E_END) p = doexpr(p, &ft, &i64t, &st, &o, &t); // get the right hand side of the expression and evaluate the operator in o
if(!(t & T_INT)) error((char *)"Syntax"); // comparisons must always return an integer
if(i64t) { // evaluates to true
skipelement(p);
nextstmt = p;
CurrentLinePtr = SaveCurrentLinePtr;
return; // if we have a match just return to the interpreter and let it execute the code
}
else { // evaluates to false
skipspace(p);
continue;
}
}
// it must be either a single value (eg, "foo") or a range (eg, "foo" TO "zoo")
// evaluate the first value
p = evaluate(p, &ft, &i64t, &st, &t, true);
skipspace(p);
if(*p == tokenTO) { // is there is a TO keyword?
p++;
t = type;
p = evaluate(p, &ftt, &i64tt, &stt, &t, false); // evaluate the right hand side of the TO expression
if(((type & T_NBR) && f >= ft && f <= ftt) || ((type & T_INT) && i64 >= i64t && i64 <= i64tt) || (((type & T_STR) && Mstrcmp(s, st) >= 0) && (Mstrcmp(s, stt) <= 0))) {
skipelement(p);
nextstmt = p;
CurrentLinePtr = SaveCurrentLinePtr;
return; // if we have a match just return to the interpreter and let it execute the code
}
else {
skipspace(p);
continue; // otherwise continue searching
}
}
// if we got to here the element must be just a single match. So make the test
if(((type & T_NBR) && f == ft) || ((type & T_INT) && i64 == i64t) || ((type & T_STR) && Mstrcmp(s, st) == 0)) {
skipelement(p);
nextstmt = p;
CurrentLinePtr = SaveCurrentLinePtr;
return; // if we have a match just return to the interpreter and let it execute the code
}
skipspace(p);
} while (*p == ','); // keep looping through the elements on the CASE line
checkend(p);
CurrentLinePtr = SaveCurrentLinePtr;
}
// test if we have found a CASE ELSE statement at the same level as this SELECT CASE
// if true it means that we did not find a matching CASE - so execute this code
if(*p == cmdCASE_ELSE && i == 1) {
p++; // step over the token
checkend(p);
skipelement(p);
nextstmt = p;
CurrentLinePtr = SaveCurrentLinePtr;
return;
}
if(*p == cmdEND_SELECT) i--; // found an END SELECT so decrement our nested counter
if(i == 0) {
// found our matching END SELECT stmt. Step over it and continue with the statement after it
skipelement(p);
nextstmt = p;
CurrentLinePtr = SaveCurrentLinePtr;
return;
}
}
}
// if we have hit a CASE or CASE ELSE we must search for a END SELECT at this level and resume at that point
void cmd_case(void) {
int i;
unsigned char* p;
// search through the program looking for a END SELECT statement
// i tracks the nesting level of any nested SELECT CASE commands
i = 1; p = nextstmt;
while (1) {
p = GetNextCommand(p, NULL, (unsigned char *)"No matching END SELECT");
if(*p == cmdSELECT_CASE) i++; // found a nested SELECT CASE command, we now need to search for its END CASE
if(*p == cmdEND_SELECT) i--; // found an END SELECT so decrement our nested counter
if(i == 0) {
// found our matching END SELECT stmt. Step over it and continue with the statement after it
skipelement(p);
nextstmt = p;
break;
}
}
}
void cmd_input(void) {
unsigned char s[STRINGSIZE];
unsigned char* p, * sp, * tp;
int i, fnbr;
getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, (unsigned char*)",;"); // this is a macro and must be the first executable stmt
// is the first argument a file number specifier? If so, get it
if(argc >= 3 && *argv[0] == '#') {
argv[0]++;
fnbr = (int)getinteger(argv[0]);
i = 2;
}
else {
fnbr = 0;
// is the first argument a prompt?
// if so, print it followed by an optional question mark
if(argc >= 3 && *argv[0] == '"' && (*argv[1] == ',' || *argv[1] == ';')) {
*(argv[0] + strlen((char*)argv[0]) - 1) = 0;
argv[0]++;
MMPrintString((char*)argv[0]);
if(*argv[1] == ';') MMPrintString((char*)"? ");
i = 2;
}
else {
MMPrintString((char*)"? "); // no prompt? then just print the question mark
i = 0;
}
}
if(argc - i < 1) error((char *)"Syntax"); // no variable to input to
*inpbuf = 0; // start with an empty buffer
MMgetline(fnbr, (char *)inpbuf); // get the line
p = inpbuf;
// step through the variables listed for the input statement
// and find the next item on the line and assign it to the variable
for (; i < argc; i++) {
sp = s; // sp is a temp pointer into s[]
if(*argv[i] == ',' || *argv[i] == ';') continue;
skipspace(p);
if(*p != 0) {
if(*p == '"') { // if it is a quoted string
p++; // step over the quote
while (*p && *p != '"') *sp++ = *p++; // and copy everything upto the next quote
while (*p && *p != ',') p++; // then find the next comma
}
else { // otherwise it is a normal string of characters
while (*p && *p != ',') *sp++ = *p++; // copy up to the comma
while (sp > s && sp[-1] == ' ') sp--; // and trim trailing whitespace
}
}
*sp = 0; // terminate the string
tp = (unsigned char*)findvar((unsigned char*)argv[i], V_FIND); // get the variable and save its new value
if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant");
if(vartbl[VarIndex].type & T_STR) {
if(strlen((char*)s) > vartbl[VarIndex].size) error((char *)"String too long");
strcpy((char*)tp, (char*)s);
CtoM(tp); // convert to a MMBasic string
}
else
if(vartbl[VarIndex].type & T_INT) {
*((long long int*)tp) = strtoll((char*)s, (char**)&sp, 10); // convert to an integer
}
else
*((MMFLOAT*)tp) = (MMFLOAT)atof((char*)s);
if(*p == ',') p++;
}
}
void cmd_trace(void) {
if (checkstring(cmdline, (unsigned char *)"ON"))
TraceOn = true;
else if (checkstring(cmdline, (unsigned char*)"OFF"))
TraceOn = false;
else if (checkstring(cmdline, (unsigned char*)"LIST")) {
int i;
cmdline += 4;
skipspace(cmdline);
if (*cmdline == 0 || *cmdline == '\'') //'
i = TRACE_BUFF_SIZE - 1;
else
i = (int)getint(cmdline, 0, TRACE_BUFF_SIZE - 1);
i = TraceBuffIndex - i;
if (i < 0) i += TRACE_BUFF_SIZE;
while (i != TraceBuffIndex) {
TraceLines((char *)TraceBuff[i]);
if (++i >= TRACE_BUFF_SIZE) i = 0;
}
}
else
error((char *)"Unknown command");
}
// FOR command
void cmd_for(void) {
int i, t, vlen, test;
unsigned char ss[4]; // this will be used to split up the argument line
unsigned char* p, * tp, * xp;
void* vptr;
unsigned char* vname, vtype;
// static unsigned char fortoken, nexttoken;
// cache these tokens for speed
// if(!fortoken) fortoken = GetCommandValue((unsigned char *)"For");
// if(!nexttoken) nexttoken = GetCommandValue((unsigned char *)"Next");
ss[0] = tokenEQUAL;
ss[1] = tokenTO;
ss[2] = tokenSTEP;
ss[3] = 0;
{ // start a new block
getargs(&cmdline, 7, ss); // getargs macro must be the first executable stmt in a block
if(argc < 5 || argc == 6 || *argv[1] != ss[0] || *argv[3] != ss[1]) error((char *)"FOR with misplaced = or TO");
if(argc == 6 || (argc == 7 && *argv[5] != ss[2])) error((char *)"Syntax");
// get the variable name and trim any spaces
vname = argv[0];
if(*vname && *vname == ' ') vname++;
while (*vname && vname[strlen((char*)vname) - 1] == ' ') vname[strlen((char*)vname) - 1] = 0;
vlen = strlen((char*)vname);
vptr = findvar(argv[0], V_FIND); // create the variable
if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant");
vtype = TypeMask(vartbl[VarIndex].type);
if(vtype & T_STR) error((char *)"Invalid variable"); // sanity check
// check if the FOR variable is already in the stack and remove it if it is
// this is necessary as the program can jump out of the loop without hitting
// the NEXT statement and this will eventually result in a stack overflow
for (i = 0; i < forindex; i++) {
if(forstack[i].var == vptr && forstack[i].level == LocalIndex) {
while (i < forindex - 1) {
forstack[i].forptr = forstack[i + 1].forptr;
forstack[i].nextptr = forstack[i + 1].nextptr;
forstack[i].var = forstack[i + 1].var;
forstack[i].vartype = forstack[i + 1].vartype;
forstack[i].level = forstack[i + 1].level;
forstack[i].tovalue.i = forstack[i + 1].tovalue.i;
forstack[i].stepvalue.i = forstack[i + 1].stepvalue.i;
i++;
}
forindex--;
break;
}
}
if(forindex == MAXFORLOOPS) error((char *)"Too many nested FOR loops");
forstack[forindex].var = vptr; // save the variable index
forstack[forindex].vartype = vtype; // save the type of the variable
forstack[forindex].level = LocalIndex; // save the level of the variable in terms of sub/funs
forindex++; // incase functions use for loops
if(vtype & T_NBR) {
*(MMFLOAT*)vptr = getnumber(argv[2]); // get the starting value for a float and save
forstack[forindex - 1].tovalue.f = getnumber(argv[4]); // get the to value and save
if(argc == 7)
forstack[forindex - 1].stepvalue.f = getnumber(argv[6]);// get the step value for a float and save
else
forstack[forindex - 1].stepvalue.f = 1.0; // default is +1
}
else {
*(long long int*)vptr = getinteger(argv[2]); // get the starting value for an integer and save
forstack[forindex - 1].tovalue.i = getinteger(argv[4]); // get the to value and save
if(argc == 7)
forstack[forindex - 1].stepvalue.i = getinteger(argv[6]);// get the step value for an integer and save
else
forstack[forindex - 1].stepvalue.i = 1; // default is +1
}
forindex--;
forstack[forindex].forptr = nextstmt + 1; // return to here when looping
// now find the matching NEXT command
t = 1; p = nextstmt;
while (1) {
p = GetNextCommand(p, &tp, (unsigned char*)"No matching NEXT");
// if(*p == fortoken) t++; // count the FOR
// if(*p == nexttoken) { // is it NEXT
if(*p == cmdFOR) t++; // count the FOR
if(*p == cmdNEXT) { // is it NEXT
xp = p + 1; // point to after the NEXT token
while (*xp && mystrncasecmp(xp, vname, vlen)) xp++; // step through looking for our variable
if(*xp && !isnamechar(xp[vlen])) // is it terminated correctly?
t = 0; // yes, found the matching NEXT
else
t--; // no luck, just decrement our stack counter
}
if(t == 0) { // found the matching NEXT
forstack[forindex].nextptr = p; // pointer to the start of the NEXT command
break;
}
}
// test the loop value at the start
if(forstack[forindex].vartype & T_INT)
test = (forstack[forindex].stepvalue.i >= 0 && *(long long int*)vptr > forstack[forindex].tovalue.i) || (forstack[forindex].stepvalue.i < 0 && *(long long int*)vptr < forstack[forindex].tovalue.i);
else
test = (forstack[forindex].stepvalue.f >= 0 && *(MMFLOAT*)vptr > forstack[forindex].tovalue.f) || (forstack[forindex].stepvalue.f < 0 && *(MMFLOAT*)vptr < forstack[forindex].tovalue.f);
if(test) {
// loop is invalid at the start, so go to the end of the NEXT command
skipelement(p); // find the command after the NEXT command
nextstmt = p; // this is where we will continue
}
else {
forindex++; // save the loop data and continue on with the command after the FOR statement
}
}
}
void cmd_next(void) {
int i, vindex, test;
void* vtbl[MAXFORLOOPS];
int vcnt;
unsigned char* p;
getargs(&cmdline, MAXFORLOOPS * 2, (unsigned char*)(unsigned char *)","); // getargs macro must be the first executable stmt in a block
vindex = 0; // keep lint happy
for (vcnt = i = 0; i < argc; i++) {
if(i & 0x01) {
if(*argv[i] != ',') error((char *)"Syntax");
}
else
vtbl[vcnt++] = findvar(argv[i], V_FIND | V_NOFIND_ERR); // find the variable and error if not found
}
loopback:
// first search the for stack for a loop with the same variable specified on the NEXT's line
if(vcnt) {
for (i = forindex - 1; i >= 0; i--)
for (vindex = vcnt - 1; vindex >= 0; vindex--)
if(forstack[i].var == vtbl[vindex])
goto breakout;
}
else {
// if no variables specified search the for stack looking for an entry with the same program position as
// this NEXT statement. This cheats by using the cmdline as an identifier and may not work inside an IF THEN ELSE
for (i = 0; i < forindex; i++) {
p = forstack[i].nextptr + 1;
skipspace(p);
if(p == cmdline) goto breakout;
}
}
error((char *)"Cannot find a matching FOR");
breakout:
// found a match
// apply the STEP value to the variable and test against the TO value
if(forstack[i].vartype & T_INT) {
*(long long int*)forstack[i].var += forstack[i].stepvalue.i;
test = (forstack[i].stepvalue.i >= 0 && *(long long int*)forstack[i].var > forstack[i].tovalue.i) || (forstack[i].stepvalue.i < 0 && *(long long int*)forstack[i].var < forstack[i].tovalue.i);
}
else {
*(MMFLOAT*)forstack[i].var += forstack[i].stepvalue.f;
test = (forstack[i].stepvalue.f >= 0 && *(MMFLOAT*)forstack[i].var > forstack[i].tovalue.f) || (forstack[i].stepvalue.f < 0 && *(MMFLOAT*)forstack[i].var < forstack[i].tovalue.f);
}
if(test) {
// the loop has terminated
// remove the entry in the table, then skip forward to the next element and continue on from there
while (i < forindex - 1) {
forstack[i].forptr = forstack[i + 1].forptr;
forstack[i].nextptr = forstack[i + 1].nextptr;
forstack[i].var = forstack[i + 1].var;
forstack[i].vartype = forstack[i + 1].vartype;
forstack[i].level = forstack[i + 1].level;
forstack[i].tovalue.i = forstack[i + 1].tovalue.i;
forstack[i].stepvalue.i = forstack[i + 1].stepvalue.i;
i++;
}
forindex--;
if(vcnt > 0) {
// remove that entry from our FOR stack
for (; vindex < vcnt - 1; vindex++) vtbl[vindex] = vtbl[vindex + 1];
vcnt--;
if(vcnt > 0)
goto loopback;
else
return;
}
}
else {
// we have not reached the terminal value yet, so go back and loop again
nextstmt = forstack[i].forptr;
}
}
void cmd_do(void) {
int i;
unsigned char* p, * tp, * evalp;
if(cmdtoken == cmdWHILE)error((char *)"Unknown command");
// if it is a DO loop find the WHILE token and (if found) get a pointer to its expression
while (*cmdline && *cmdline != tokenWHILE) cmdline++;
if(*cmdline == tokenWHILE) {
evalp = ++cmdline;
}
else
evalp = NULL;
// check if this loop is already in the stack and remove it if it is
// this is necessary as the program can jump out of the loop without hitting
// the LOOP or WEND stmt and this will eventually result in a stack overflow
for (i = 0; i < doindex; i++) {
if(dostack[i].doptr == nextstmt) {
while (i < doindex - 1) {
dostack[i].evalptr = dostack[i + 1].evalptr;
dostack[i].loopptr = dostack[i + 1].loopptr;
dostack[i].doptr = dostack[i + 1].doptr;
dostack[i].level = dostack[i + 1].level;
i++;
}
doindex--;
break;
}
}
// add our pointers to the top of the stack
if(doindex == MAXDOLOOPS) error((char *)"Too many nested DO or WHILE loops");
dostack[doindex].evalptr = evalp;
dostack[doindex].doptr = nextstmt;
dostack[doindex].level = LocalIndex;
// now find the matching LOOP command
i = 1; p = nextstmt;
while (1) {
p = GetNextCommand(p, &tp, (unsigned char*)"No matching LOOP");
if(*p == cmdtoken) i++; // entered a nested DO or WHILE loop
if(*p == cmdLOOP) i--; // exited a nested loop
if(i == 0) { // found our matching LOOP or WEND stmt
dostack[doindex].loopptr = p;
break;
}
}
if(dostack[doindex].evalptr != NULL) {
// if this is a DO WHILE ... LOOP statement
// search the LOOP statement for a WHILE or UNTIL token (p is pointing to the matching LOOP statement)
p++;
while (*p && *p < 0x80) p++;
if(*p == tokenWHILE) error((char *)"LOOP has a WHILE test");
if(*p == tokenUNTIL) error((char *)"LOOP has an UNTIL test");
}
doindex++;
// do the evaluation (if there is something to evaluate) and if false go straight to the command after the LOOP or WEND statement
if(dostack[doindex - 1].evalptr != NULL && getnumber(dostack[doindex - 1].evalptr) == 0) {
doindex--; // remove the entry in the table
nextstmt = dostack[doindex].loopptr; // point to the LOOP or WEND statement
skipelement(nextstmt); // skip to the next command
}
}
void cmd_loop(void) {
unsigned char* p;
int tst = 0; // initialise tst to stop the compiler from complaining
int i;
// search the do table looking for an entry with the same program position as this LOOP statement
for (i = 0; i < doindex; i++) {
p = dostack[i].loopptr + 1;
skipspace(p);
if(p == cmdline) {
// found a match
// first check if the DO statement had a WHILE component
// if not find the WHILE statement here and evaluate it
if(dostack[i].evalptr == NULL) { // if it was a DO without a WHILE
if(*cmdline >= 0x80) { // if there is something
if(*cmdline == tokenWHILE)
tst = (getnumber(++cmdline) != 0); // evaluate the expression
else if(*cmdline == tokenUNTIL)
tst = (getnumber(++cmdline) == 0); // evaluate the expression
else
error((char *)"Syntax");
}
else {
tst = 1; // and loop forever
checkend(cmdline); // make sure that there is nothing else
}
}
else { // if was DO WHILE
tst = (getnumber(dostack[i].evalptr) != 0); // evaluate its expression
checkend(cmdline); // make sure that there is nothing else
}
// test the expression value and reset the program pointer if we are still looping
// otherwise remove this entry from the do stack
if(tst)
nextstmt = dostack[i].doptr; // loop again
else{
// the loop has terminated
// remove the entry in the table, then just let the default nextstmt run and continue on from there
doindex = i;
// just let the default nextstmt run
}
return;
}
}
error((char *)"LOOP without a matching DO");
}
void cmd_exitfor(void) {
if(forindex == 0) error((char *)"No FOR loop is in effect");
nextstmt = forstack[--forindex].nextptr;
checkend(cmdline);
skipelement(nextstmt);
}
void cmd_exit(void) {
if(doindex == 0) error((char *)"No DO loop is in effect");
nextstmt = dostack[--doindex].loopptr;
checkend(cmdline);
skipelement(nextstmt);
}
void cmd_error(void) {
char* s, p[STRINGSIZE];
if (*cmdline && *cmdline != '\'') {
s = (char *)getCstring(cmdline);
if (CurrentX != 0) MMPrintString((char*)"\r\n"); // error message should be on a new line
strcpy(p, s);
error(p);
}
else
error((char *)"");
}
void cmd_randomize(void) {
int i;
getargs(&cmdline, 1, (unsigned char *)",");
if(argc == 1)i = (int)getinteger(argv[0]);
else {
int64_t j;
QueryPerformanceCounter((LARGE_INTEGER*)&j);
i = (int)(j & 0xFFFFFFFF);
}
if(i < 0) error((char *)"Number out of bounds");
srand(i);
}
// this is the Sub or Fun command
// it simply skips over text until it finds the end of it
void cmd_subfun(void) {
unsigned char* p, returntoken, errtoken;
if(gosubindex != 0) error((char *)"No matching END declaration"); // we have hit a SUB/FUN while in another SUB or FUN
if(cmdtoken == cmdSUB) {
returntoken = cmdENDSUB;
errtoken = cmdENDFUNCTION;
}
else {
returntoken = cmdENDFUNCTION;
errtoken = cmdENDSUB;
}
p = nextstmt;
while (1) {
p = GetNextCommand(p, NULL, (unsigned char *)"No matching END declaration");
if(*p == cmdSUB || *p == cmdFUN || *p == errtoken) error((char *)"No matching END declaration");
if(*p == returntoken) { // found the next return
skipelement(p);
nextstmt = p; // point to the next command
break;
}
}
}
void cmd_gosub(void) {
if(gosubindex >= MAXGOSUB) error((char *)"Too many nested GOSUB");
errorstack[gosubindex] = CurrentLinePtr;
gosubstack[gosubindex++] = nextstmt;
LocalIndex++;
if(isnamestart(*cmdline))
nextstmt = findlabel(cmdline); // must be a label
else
nextstmt = findline((int)getinteger(cmdline), true); // try for a line number
CurrentLinePtr = nextstmt;
}
void cmd_mid(void) {
unsigned char* p;
getargs(&cmdline, 5, (unsigned char *)",");
findvar(argv[0], V_NOFIND_ERR);
if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant");
if(!(vartbl[VarIndex].type & T_STR)) error((char *)"Not a string");
unsigned char* sourcestring = getstring(argv[0]);
int start = (int)getint(argv[2], 1, sourcestring[0]);
int num = 0;
if(argc == 5)num = (int)getint(argv[4], 1, sourcestring[0]);
if(start + num - 1 > sourcestring[0])error((char *)"Selection exceeds length of string");
while (*cmdline && tokenfunction(*cmdline) != op_equal) cmdline++;
if(!*cmdline) error((char *)"Syntax");
++cmdline;
if(!*cmdline) error((char *)"Syntax");
char* value = (char*)getstring(cmdline);
if(num == 0)num = value[0];
if(num > value[0])error((char *)"Supplied string too short");
p = (unsigned char*)&value[1];
memcpy(&sourcestring[start], p, num);
}
void cmd_return(void) {
checkend(cmdline);
if(gosubindex == 0 || gosubstack[gosubindex - 1] == NULL) error((char *)"Nothing to return to");
ClearVars(LocalIndex--); // delete any local variables
TempMemoryIsChanged = true; // signal that temporary memory should be checked
nextstmt = gosubstack[--gosubindex]; // return to the caller
CurrentLinePtr = errorstack[gosubindex];
}
void cmd_endfun(void) {
checkend(cmdline);
if(gosubindex == 0 || gosubstack[gosubindex - 1] != NULL) error((char *)"Nothing to return to");
nextstmt = (unsigned char*)"\0\0\0"; // now terminate this run of ExecuteProgram()
}
void cmd_read(void) {
int i, j, k, len, card;
unsigned char *p, datatoken, *lineptr = NULL, *ptr;
int vcnt, vidx, num_to_read = 0;
if (checkstring(cmdline, (unsigned char*)"SAVE")) {
if(restorepointer== MAXRESTORE - 1)error((char*)"Too many saves");
datastore[restorepointer].SaveNextDataLine = NextDataLine;
datastore[restorepointer].SaveNextData = NextData;
restorepointer++;
return;
}
if (checkstring(cmdline, (unsigned char*)"RESTORE")) {
if (!restorepointer)error((char*)"Nothing to restore");
restorepointer--;
NextDataLine = datastore[restorepointer].SaveNextDataLine;
NextData = datastore[restorepointer].SaveNextData;
return;
}
getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, (unsigned char *)","); // getargs macro must be the first executable stmt in a block
if(argc == 0) error((char *)"Syntax");
// first count the elements and do the syntax checking
for(vcnt = i = 0; i < argc; i++) {
if(i & 0x01) {
if(*argv[i] != ',') error((char *)"Syntax");
}
else{
findvar(argv[i], V_FIND | V_EMPTY_OK);
if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant");
card = 1;
if(emptyarray) { //empty array
for(k = 0; k < MAXDIM; k++) {
j = (vartbl[VarIndex].dims[k] - OptionBase + 1);
if(j)card *= j;
}
}
num_to_read += card;
}
}
char** vtbl = (char **)GetTempMemory(num_to_read * sizeof(char*));
int* vtype = (int *)GetTempMemory(num_to_read * sizeof(int));
int* vsize = (int *)GetTempMemory(num_to_read * sizeof(int));
// step through the arguments and save the pointer and type
for(vcnt = i = 0; i < argc; i += 2) {
vtbl[vcnt] = (char *)findvar(argv[i], V_FIND | V_EMPTY_OK);
ptr = (unsigned char *)vtbl[vcnt];
card = 1;
if(emptyarray) { //empty array
for (k = 0; k < MAXDIM; k++) {
j = (vartbl[VarIndex].dims[k] - OptionBase + 1);
if(j)card *= j;
}
}
for (k = 0; k < card; k++) {
if(k) {
if(vartbl[VarIndex].type & (T_INT | T_NBR))ptr += 8;
else ptr += vartbl[VarIndex].size + 1;
vtbl[vcnt] = (char*)ptr;
}
vtype[vcnt] = TypeMask(vartbl[VarIndex].type);
vsize[vcnt] = vartbl[VarIndex].size;
vcnt++;
}
}
// setup for a search through the whole memory
vidx = 0;
datatoken = GetCommandValue((unsigned char *)"Data");
p = lineptr = NextDataLine;
if(*p == 0xff) error((char *)"No DATA to read"); // error if there is no program
// search looking for a DATA statement. We keep returning to this point until all the data is found
search_again:
while (1) {
if(*p == 0) p++; // if it is at the end of an element skip the zero marker
if(*p == 0 || *p == 0xff) error((char *)"No DATA to read"); // end of the program and we still need more data
if(*p == T_NEWLINE) lineptr = p++;
if(*p == T_LINENBR) p += 3;
skipspace(p);
if(*p == T_LABEL) { // if there is a label here
p += p[1] + 2; // skip over the label
skipspace(p); // and any following spaces
}
if(*p == datatoken) break; // found a DATA statement
while (*p) p++; // look for the zero marking the start of the next element
}
NextDataLine = lineptr;
p++; // step over the token
skipspace(p);
if(!*p || *p == '\'') { CurrentLinePtr = lineptr; error((char *)"No DATA to read"); }
// we have a DATA statement, first split the line into arguments
{ // new block, the getargs macro must be the first executable stmt in a block
getargs(&p, (MAX_ARG_COUNT * 2) - 1, (unsigned char *)",");
if((argc & 1) == 0) { CurrentLinePtr = lineptr; error((char *)"Syntax"); }
// now step through the variables on the READ line and get their new values from the argument list
// we set the line number to the number of the DATA stmt so that any errors are reported correctly
while (vidx < vcnt) {
// check that there is some data to read if not look for another DATA stmt
if(NextData > argc) {
skipline(p);
NextData = 0;
goto search_again;
}
CurrentLinePtr = lineptr;
if(vtype[vidx] & T_STR) {
char* p1, * p2;
if(*argv[NextData] == '"') { // if quoted string
for (len = 0, p1 = vtbl[vidx], p2 = (char*)argv[NextData] + 1; *p2 && *p2 != '"'; len++, p1++, p2++) {
*p1 = *p2; // copy up to the quote
}
}
else { // else if not quoted
for (len = 0, p1 = vtbl[vidx], p2 = (char*)argv[NextData]; *p2 && *p2 != '\''; len++, p1++, p2++) {
if(*p2 < 0x20 || *p2 >= 0x7f) error((char *)"Invalid character");
*p1 = *p2; // copy up to the comma
}
}
if(len > vsize[vidx]) error((char *)"String too long");
*p1 = 0; // terminate the string
CtoM((unsigned char*)vtbl[vidx]); // convert to a MMBasic string
}
else if(vtype[vidx] & T_INT)
*((long long int*)vtbl[vidx]) = getinteger(argv[NextData]); // much easier if integer variable
else
*((MMFLOAT*)vtbl[vidx]) = getnumber(argv[NextData]); // same for numeric variable
vidx++;
NextData += 2;
}
}
}
void cmd_call(void) {
int i;
unsigned char* q;
unsigned char* p = getCstring(cmdline); //get the command we want to call
/* q=p;
while(*q){ //convert to upper case for the match
*q=mytoupper(*q);
q++;
}*/
q = cmdline;
while (*q) {
if(*q == ',' || *q == '\'')break;
q++;
}
if(*q == ',')q++;
i = FindSubFun(p, false); // it could be a defined command
strcat((char *)p, " ");
strcat((char*)p, (const char *)q);
// MMPrintString(p);PRet();
if(i >= 0) { // >= 0 means it is a user defined command
DefinedSubFun(false, p, i, NULL, NULL, NULL, NULL);
}
else
error((char *)"Unknown user subroutine");
}
void cmd_restore(void) {
if(*cmdline == 0 || *cmdline == '\'') {
NextDataLine = ProgMemory;
NextData = 0;
}
else {
skipspace(cmdline);
if(*cmdline == '"') {
NextDataLine = findlabel(getCstring(cmdline));
NextData = 0;
}
else if(isdigit(*cmdline) || *cmdline == GetTokenValue((unsigned char*)"+") || *cmdline == GetTokenValue((unsigned char*)"-") || *cmdline == '.') {
NextDataLine = findline((int)getinteger(cmdline), true); // try for a line number
NextData = 0;
}
else {
void* ptr = findvar(cmdline, V_NOFIND_NULL);
if(ptr) {
if(vartbl[VarIndex].type & T_NBR) {
if(vartbl[VarIndex].dims[0] > 0) { // Not an array
error((char *)"Syntax");
}
NextDataLine = findline((int)getinteger(cmdline), true);
}
else if(vartbl[VarIndex].type & T_INT) {
if(vartbl[VarIndex].dims[0] > 0) { // Not an array
error((char *)"Syntax");
}
NextDataLine = findline((int)getinteger(cmdline), true);
}
else {
NextDataLine = findlabel(getCstring(cmdline)); // must be a label
}
}
else if(isnamestart(*cmdline)) {
NextDataLine = findlabel(cmdline); // must be a label
}
NextData = 0;
}
}
}
void cmd_lineinput(void) {
unsigned char* vp;
int i, fnbr;
getargs(&cmdline, 3, (unsigned char*)",;"); // this is a macro and must be the first executable stmt
if(argc == 0 || argc == 2) error((char *)"Syntax");
i = 0;
fnbr = 0;
if(argc == 3) {
// is the first argument a file number specifier? If so, get it
if(*argv[0] == '#' && *argv[1] == ',') {
argv[0]++;
fnbr = (int)getinteger(argv[0]);
}
else {
// is the first argument a prompt? if so, print it otherwise there are too many arguments
if(*argv[1] != ',' && *argv[1] != ';') error((char *)"Syntax");
MMfputs((unsigned char*)getstring(argv[0]), 0);
}
i = 2;
}
if(argc - i != 1) error((char *)"Syntax");
vp = (unsigned char*)findvar(argv[i], V_FIND);
if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant");
if(!(vartbl[VarIndex].type & T_STR)) error((char *)"Invalid variable");
MMgetline(fnbr, (char *)inpbuf); // get the input line
if(strlen((char*)inpbuf) > vartbl[VarIndex].size) error((char *)"String too long");
strcpy((char*)vp, (char*)inpbuf);
CtoM(vp); // convert to a MMBasic string
}
void cmd_on(void) {
int r;
unsigned char ss[4]; // this will be used to split up the argument line
unsigned char* p;
// first check if this is: ON KEY location
p = checkstring(cmdline, (unsigned char*)"KEY");
if(p) {
getargs(&p, 3, (unsigned char *)",");
if(argc == 1) {
if(*argv[0] == '0' && !isdigit(*(argv[0] + 1))) {
OnKeyGOSUB = NULL; // the program wants to turn the interrupt off
}
else {
OnKeyGOSUB = GetIntAddress(argv[0]); // get a pointer to the interrupt routine
InterruptUsed = true;
}
return;
}
else {
keyselect = (int)getint(argv[0], 0, 255);
if(keyselect == 0) {
KeyInterrupt = NULL; // the program wants to turn the interrupt off
}
else {
if(*argv[2] == '0' && !isdigit(*(argv[2] + 1))) {
KeyInterrupt = NULL; // the program wants to turn the interrupt off
}
else {
KeyInterrupt = GetIntAddress((unsigned char *)argv[2]); // get a pointer to the interrupt routine
InterruptUsed = true;
}
}
return;
}
}
p = checkstring(cmdline, (unsigned char *)"ERROR");
if (p) {
if (checkstring(p, (unsigned char*)"ABORT")) {
OptionErrorSkip = 0;
return;
}
MMerrno = 0; // clear the error flags
*MMErrMsg = 0;
if (checkstring(p, (unsigned char*)"CLEAR")) return;
if (checkstring(p, (unsigned char*)"IGNORE")) {
OptionErrorSkip = -1;
return;
}
if ((p = checkstring(p, (unsigned char*)"SKIP"))) {
if (*p == 0 || *p == '\'')
OptionErrorSkip = 1;
else
OptionErrorSkip = (int)getint(p, 1, 10000);
return;
}
error((char*)"Syntax");
}
// if we got here the command must be the traditional: ON nbr GOTO|GOSUB line1, line2,... etc
ss[0] = tokenGOTO;
ss[1] = tokenGOSUB;
ss[2] = ',';
ss[3] = 0;
{ // start a new block
getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, ss); // getargs macro must be the first executable stmt in a block
if(argc < 3 || !(*argv[1] == ss[0] || *argv[1] == ss[1])) error((char *)"Syntax");
if(argc % 2 == 0) error((char *)"Syntax");
r = (int)getint(argv[0], 0, 255); // evaluate the expression controlling the statement
if(r == 0 || r > argc / 2) return; // microsoft say that we just go on to the next line
if(*argv[1] == ss[1]) {
// this is a GOSUB, same as a GOTO but we need to first push the return pointer
if(gosubindex >= MAXGOSUB) error((char *)"Too many nested GOSUB");
errorstack[gosubindex] = CurrentLinePtr;
gosubstack[gosubindex++] = nextstmt;
LocalIndex++;
}
if(isnamestart(*argv[r * 2]))
nextstmt = findlabel(argv[r * 2]); // must be a label
else
nextstmt = findline((int)getinteger(argv[r * 2]), true); // try for a line number
}
// IgnorePIN = false;
}
unsigned char* SetValue(unsigned char* p, int t, void* v) {
MMFLOAT f;
long long int i64;
unsigned char* s;
char TempCurrentSubFunName[MAXVARLEN + 1];
strcpy(TempCurrentSubFunName, (char*)CurrentSubFunName); // save the current sub/fun name
if(t & T_STR) {
p = evaluate(p, &f, &i64, &s, &t, true);
Mstrcpy((unsigned char *)v, s);
}
else if(t & T_NBR) {
p = evaluate(p, &f, &i64, &s, &t, false);
if(t & T_NBR)
(*(MMFLOAT*)v) = f;
else
(*(MMFLOAT*)v) = (MMFLOAT)i64;
}
else {
p = evaluate(p, &f, &i64, &s, &t, false);
if(t & T_INT)
(*(long long int*)v) = i64;
else
(*(long long int*)v) = FloatToInt64(f);
}
strcpy((char*)CurrentSubFunName, TempCurrentSubFunName); // restore the current sub/fun name
return p;
}
// define a variable
// DIM [AS INTEGER|FLOAT|STRING] var[(d1 [,d2,...]] [AS INTEGER|FLOAT|STRING] [, ..., ...]
// LOCAL also uses this function the routines only differ in that LOCAL can only be used in a sub/fun
void cmd_dim(void) {
int i, j, k, type, typeSave, ImpliedType = 0, VIndexSave, StaticVar = false;
unsigned char* p, chSave, * chPosit;
unsigned char VarName[(MAXVARLEN * 2) + 1];
void* v, * tv;
if(*cmdline == tokenAS) cmdline++; // this means that we can use DIM AS INTEGER a, b, etc
p = CheckIfTypeSpecified(cmdline, &type, true); // check for DIM FLOAT A, B, ...
ImpliedType = type;
{ // getargs macro must be the first executable stmt in a block
getargs(&p, (MAX_ARG_COUNT * 2) - 1, (unsigned char*)(unsigned char *)",");
if((argc & 0x01) == 0) error((char *)"Syntax");
for (i = 0; i < argc; i += 2) {
p = skipvar(argv[i], false); // point to after the variable
while (!(*p == 0 || *p == tokenAS || *p == (unsigned char)'\'' || *p == tokenEQUAL))
p++; // skip over a LENGTH keyword if there and see if we can find "AS"
chSave = *p; chPosit = p; *p = 0; // save the char then terminate the string so that LENGTH is evaluated correctly
if(chSave == tokenAS) { // are we using Microsoft syntax (eg, AS INTEGER)?
if(ImpliedType & T_IMPLIED) error((char *)"Type specified twice");
p++; // step over the AS token
p = CheckIfTypeSpecified(p, &type, true); // and get the type
if(!(type & T_IMPLIED)) error((char *)"Variable type");
}
if(cmdtoken == cmdLOCAL) {
if(LocalIndex == 0) error((char *)"Invalid here");
type |= V_LOCAL; // local if defined in a sub/fun
}
if(cmdtoken == cmdSTATIC) {
if(LocalIndex == 0) error((char *)"Invalid here");
// create a unique global name
if(*CurrentInterruptName)
strcpy((char *)VarName, (const char *)CurrentInterruptName); // we must be in an interrupt sub
else
strcpy((char*)VarName, (const char*)CurrentSubFunName); // normal sub/fun
for (k = 1; k <= MAXVARLEN; k++) if(!isnamechar(VarName[k])) {
VarName[k] = 0; // terminate the string on a non valid char
break;
}
strcat((char*)VarName, (const char*)argv[i]); // by prefixing the var name with the sub/fun name
StaticVar = true;
}
else
strcpy((char*)VarName, (const char*)argv[i]);
v = findvar(VarName, type | V_NOFIND_NULL); // check if the variable exists
typeSave = type;
VIndexSave = VarIndex;
if(v == NULL) { // if not found
v = findvar(VarName, type | V_FIND | V_DIM_VAR); // create the variable
type = TypeMask(vartbl[VarIndex].type);
VIndexSave = VarIndex;
*chPosit = chSave; // restore the char previously removed
if(vartbl[VarIndex].dims[0] == -1) error((char *)"Array dimensions");
if(vartbl[VarIndex].dims[0] > 0) {
DimUsed = true; // prevent OPTION BASE from being used
v = vartbl[VarIndex].val.s;
}
while (*p && *p != '\'' && tokenfunction(*p) != op_equal) p++; // search through the line looking for the equals sign
if(tokenfunction(*p) == op_equal) {
p++; // step over the equals sign
skipspace(p);
if(vartbl[VarIndex].dims[0] > 0 && *p == '(') {
// calculate the overall size of the array
for (j = 1, k = 0; k < MAXDIM && vartbl[VIndexSave].dims[k]; k++) {
j *= (vartbl[VIndexSave].dims[k] + 1 - OptionBase);
}
do {
p++; // step over the opening bracket or terminating comma
p = SetValue(p, type, v);
if(type & T_STR) v = (char*)v + vartbl[VIndexSave].size + 1;
if(type & T_NBR) v = (char*)v + sizeof(MMFLOAT);
if(type & T_INT) v = (char*)v + sizeof(long long int);
skipspace(p); j--;
} while (j > 0 && *p == ',');
if(*p != ')') error((char *)"Number of initialising values");
if(j != 0) error((char *)"Number of initialising values");
}
else
SetValue(p, type, v);
}
type = ImpliedType;
}
else {
if(!StaticVar) error((char *)"$ already declared", VarName);
}
// if it is a STATIC var create a local var pointing to the global var
if(StaticVar) {
tv = findvar(argv[i], typeSave | V_LOCAL | V_NOFIND_NULL); // check if the local variable exists
if(tv != NULL) error((char *)"$ already declared", argv[i]);
tv = findvar(argv[i], typeSave | V_LOCAL | V_FIND | V_DIM_VAR); // create the variable
if(vartbl[VIndexSave].dims[0] > 0 || (vartbl[VIndexSave].type & T_STR)) {
FreeMemory((unsigned char *)tv); // we don't need the memory allocated to the local
vartbl[VarIndex].val.s = vartbl[VIndexSave].val.s; // point to the memory of the global variable
}
else
vartbl[VarIndex].val.ia = &(vartbl[VIndexSave].val.i); // point to the data of the variable
vartbl[VarIndex].type = vartbl[VIndexSave].type | T_PTR; // set the type to a pointer
vartbl[VarIndex].size = vartbl[VIndexSave].size; // just in case it is a string copy the size
for (j = 0; j < MAXDIM; j++) vartbl[VarIndex].dims[j] = vartbl[VIndexSave].dims[j]; // just in case it is an array copy the dimensions
}
}
}
}
void cmd_const(void) {
unsigned char* p;
void* v;
int i, type;
getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, (unsigned char*)(unsigned char *)","); // getargs macro must be the first executable stmt in a block
if((argc & 0x01) == 0) error((char *)"Syntax");
for (i = 0; i < argc; i += 2) {
p = skipvar(argv[i], false); // point to after the variable
skipspace(p);
if(tokenfunction(*p) != op_equal) error((char *)"Syntax"); // must be followed by an equals sign
p++; // step over the equals sign
type = T_NOTYPE;
v = DoExpression(p, &type); // evaluate the constant's value
type = TypeMask(type);
type |= V_FIND | V_DIM_VAR | T_CONST | T_IMPLIED;
if(LocalIndex != 0) type |= V_LOCAL; // local if defined in a sub/fun
findvar(argv[i], type); // create the variable
if(vartbl[VarIndex].dims[0] != 0) error((char *)"Invalid constant");
if(TypeMask(vartbl[VarIndex].type) != TypeMask(type)) error((char *)"Invalid constant");
else {
if(type & T_NBR) vartbl[VarIndex].val.f = *(MMFLOAT*)v; // and set its value
if(type & T_INT) vartbl[VarIndex].val.i = *(long long int*)v;
if(type & T_STR) Mstrcpy((unsigned char*)vartbl[VarIndex].val.s, (unsigned char*)v);
}
}
}
// utility function used by llist() below
// it copys a command or function honouring the case selected by the user
void strCopyWithCase(unsigned char* d, unsigned char* s) {
if(Option.Listcase == CONFIG_LOWER) {
while (*s) *d++ = tolower(*s++);
}
else if(Option.Listcase == CONFIG_UPPER) {
while (*s) *d++ = mytoupper(*s++);
}
else {
while (*s) *d++ = *s++;
}
*d = 0;
}
// list a line into a buffer (b) given a pointer to the beginning of the line (p).
// the returned string is a C style string (terminated with a zero)
// this is used by cmd_list(), cmd_edit() and cmd_xmodem()
unsigned char* llist(unsigned char* b, unsigned char* p) {
int i, firstnonwhite = true;
unsigned char* b_start = b;
while (1) {
if (*p == T_NEWLINE) {
p++;
firstnonwhite = true;
continue;
}
if (*p == T_LINENBR) {
i = (((p[1]) << 8) | (p[2])); // get the line number
p += 3; // and step over the number
IntToStr((char *)b, i, 10);
b += strlen((char*)b);
if (*p != ' ') *b++ = ' ';
}
if (*p == T_LABEL) { // got a label
for (i = p[1], p += 2; i > 0; i--)
*b++ = *p++; // copy to the buffer
*b++ = ':'; // terminate with a colon
if (*p && *p != ' ') *b++ = ' '; // and a space if necessary
firstnonwhite = true;
} // this deliberately drops through in case the label is the only thing on the line
if (*p >= C_BASETOKEN) {
if (firstnonwhite) {
if (*p == GetCommandValue((unsigned char*)"Let"))
*b = 0; // use nothing if it LET
else {
strCopyWithCase(b, commandname(*p)); // expand the command (if it is not LET)
b += strlen((char*)b); // update pointer to the end of the buffer
if (isalpha(*(b - 1))) *b++ = ' '; // add a space to the end of the command name
}
firstnonwhite = false;
}
else { // not a command so must be a token
strCopyWithCase(b, tokenname(*p)); // expand the token
b += strlen((char*)b); // update pointer to the end of the buffer
if (*p == tokenTHEN || *p == tokenELSE)
firstnonwhite = true;
else
firstnonwhite = false;
}
p++;
continue;
}
// hey, an ordinary char, just copy it to the output
if (*p) {
*b = *p; // place the char in the buffer
if (*p != ' ') firstnonwhite = false;
p++; b++; // move the pointers
continue;
}
// at this point the char must be a zero
// zero char can mean both a separator or end of line
if (!(p[1] == T_NEWLINE || p[1] == 0)) {
*b++ = ':'; // just a separator
firstnonwhite = true;
p++;
continue;
}
// must be the end of a line - so return to the caller
while (*(b - 1) == ' ' && b > b_start) --b; // eat any spaces on the end of the line
*b = 0; // terminate the output buffer
return ++p;
} // end while
}
// get the file name for the RUN, LOAD, SAVE, KILL, COPY, DRIVE, FILES, FONT LOAD, LOADBMP, SAVEBMP, SPRITE LOAD and EDIT commands
// this function allows the user to omit the quote marks around a string constant when in immediate mode
// the first argument is a pointer to the file name (normally on the command line of the command)
// the second argument is a pointer to the LastFile buffer. If this pointer is NULL the LastFile buffer feature will not be used
// This returns a temporary string to the filename
unsigned char* GetFileName(unsigned char* CmdLinePtr, unsigned char* LastFilePtr) {
unsigned char* tp, * t;
if(CurrentLinePtr) return getCstring(CmdLinePtr); // if running a program get the filename as an expression
// if we reach here we are in immediate mode
if(*CmdLinePtr == 0 && LastFilePtr != NULL) return LastFilePtr; // if the command line is empty and we have a pointer to the last file, return that
if(strchr((char*)CmdLinePtr, '"') == NULL && strchr((char*)CmdLinePtr, '$') == NULL) {// quotes or a $ symbol indicate that it is an expression
tp = (unsigned char*)GetTempMemory(STRINGSIZE); // this will last for the life of the command
strcpy((char*)tp, (char*)CmdLinePtr); // save the string
t = (unsigned char*)strchr((char*)tp, ' '); if(t) *t = 0; // trim any trailing spaces
for (t = tp; *t; t++) if(*t <= ' ' || *t > 'z') error((char *)"Filename must be quoted");
return tp;
}
else
return getCstring(CmdLinePtr); // treat the command line as a string expression and get its value
}
// lists the program to a specified file handle
// this decodes line numbers and tokens and outputs them in plain english
// LISTing a program is exactly the same as listing to a file (ie, SAVE)
void flist(int fnbr, int fromnbr, int tonbr) {
unsigned char* fromp = ProgMemory + 1;
unsigned char b[STRINGSIZE];
int i;
if(fromnbr != 1) fromp = findline(fromnbr, (fromnbr == tonbr) ? true : false); // set our pointer to the start line
ListCnt = 1;
while (1) {
if(*fromp == T_LINENBR) {
i = (((fromp[1]) << 8) | (fromp[2])); // get the line number
if(i != NOLINENBR && i > tonbr) break; // end of the listing
fromp = llist(b, fromp); // otherwise expand the line
MMfputs((unsigned char*)CtoM(b), fnbr); // convert to a MMBasic string and output
// #if defined(DOS)
// MMfputs((unsigned char *)"\1\n", fnbr); // print the terminating lf
// #else
MMfputs((unsigned char*)"\2\r\n", fnbr); // print the terminating cr/lf
// #endif
if(i != NOLINENBR && i >= tonbr) break; // end of the listing
// check if it is more than a screenfull
if(fnbr == 0 && ListCnt >= VCHARS && !(fromp[0] == 0 && fromp[1] == 0)) {
MMPrintString((char*)"PRESS ANY KEY ...");
MMgetchar();
MMPrintString((char*)"\r \r");
ListCnt = 1;
}
}
//else
// error((char *)"Internal error in flist()");
// finally, is it the end of the program?
if(fromp[0] == 0) break;
}
if(fnbr != 0) FileClose(fnbr);
}
| 37.102649
| 201
| 0.564179
|
UKTailwind
|
318739c084517a6d383cd9ac430c2f2687e34845
| 570
|
cpp
|
C++
|
uva/11498_Division_of_Nlogonia.cpp
|
st3v3nmw/competitive-programming
|
581d36c1c128e0e3ee3a0b52628e932ab43821d4
|
[
"MIT"
] | null | null | null |
uva/11498_Division_of_Nlogonia.cpp
|
st3v3nmw/competitive-programming
|
581d36c1c128e0e3ee3a0b52628e932ab43821d4
|
[
"MIT"
] | null | null | null |
uva/11498_Division_of_Nlogonia.cpp
|
st3v3nmw/competitive-programming
|
581d36c1c128e0e3ee3a0b52628e932ab43821d4
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
int k = -1, dx, dy, x, y;
while (k != 0) {
cin >> k;
cin >> dx >> dy;
for (int i = 0; i < k; i++) {
cin >> x >> y;
if (x == dx || y == dy)
cout << "divisa\n";
else if (x > dx && y > dy)
cout << "NE\n";
else if (x > dx && y < dy)
cout << "SE\n";
else if (x < dx && y > dy)
cout << "NO\n";
else
cout << "SO\n";
}
}
}
| 24.782609
| 38
| 0.301754
|
st3v3nmw
|
318c6ebd7514a2f693cd89e691ad21183b611873
| 289
|
cpp
|
C++
|
node_modules/lzz-gyp/lzz-source/smtc_CreateUnnamedNs.cpp
|
SuperDizor/dizornator
|
9f57dbb3f6af80283b4d977612c95190a3d47900
|
[
"ISC"
] | 3
|
2019-09-18T16:44:33.000Z
|
2021-03-29T13:45:27.000Z
|
node_modules/lzz-gyp/lzz-source/smtc_CreateUnnamedNs.cpp
|
SuperDizor/dizornator
|
9f57dbb3f6af80283b4d977612c95190a3d47900
|
[
"ISC"
] | null | null | null |
node_modules/lzz-gyp/lzz-source/smtc_CreateUnnamedNs.cpp
|
SuperDizor/dizornator
|
9f57dbb3f6af80283b4d977612c95190a3d47900
|
[
"ISC"
] | 2
|
2019-03-29T01:06:38.000Z
|
2019-09-18T16:44:34.000Z
|
// smtc_CreateUnnamedNs.cpp
//
#include "smtc_CreateUnnamedNs.h"
// semantic
#include "smtc_UnnamedNs.h"
#define LZZ_INLINE inline
namespace smtc
{
NsPtr createUnnamedNs (NsPtr const & encl_ns, util::Loc const & loc)
{
return new UnnamedNs (encl_ns, loc);
}
}
#undef LZZ_INLINE
| 18.0625
| 70
| 0.730104
|
SuperDizor
|
318d069fc3f208237efcde7f2b6d3cbc02f4c724
| 1,474
|
hpp
|
C++
|
lib/geometry/circle_intersection.hpp
|
hareku/cpp-algorithm
|
455339645d5797f0e6b211694345e1a221fc131c
|
[
"Apache-2.0"
] | null | null | null |
lib/geometry/circle_intersection.hpp
|
hareku/cpp-algorithm
|
455339645d5797f0e6b211694345e1a221fc131c
|
[
"Apache-2.0"
] | null | null | null |
lib/geometry/circle_intersection.hpp
|
hareku/cpp-algorithm
|
455339645d5797f0e6b211694345e1a221fc131c
|
[
"Apache-2.0"
] | null | null | null |
#ifndef LIB_GEOMETRY_CIRCLE_INTERSECTION
#define LIB_GEOMETRY_CIRCLE_INTERSECTION 1
#include <bits/stdc++.h>
namespace lib::geometry {
// circles_cross checks whether circle a and circle b intersect.
template <class T> bool circles_cross(std::complex<T> a, T ar, std::complex<T> b, T br, const T eps = std::numeric_limits<T>::epsilon()) {
T d = std::abs(a - b);
return (ar + br - d) > eps;
};
// circles_circumscribed checks whether is a or b circle is circumscribed in the other circle.
template <class T> bool circles_circumscribed(std::complex<T> a, T ar, std::complex<T> b, T br, const T eps = std::numeric_limits<T>::epsilon()) {
T d = std::abs(a - b);
return std::abs(ar + br - d) < eps;
};
// circles_inscribed checks whether is a or b circle is inscribed in the other circle.
template <class T> bool circles_inscribed(std::complex<T> a, T ar, std::complex<T> b, T br, const T eps = std::numeric_limits<T>::epsilon()) {
T d = std::abs(a - b);
return std::abs(std::abs(ar - br) - d) < eps;
};
// circle_includes checks whether does circle include other circle.
template <class T> bool circle_includes(std::complex<T> a, T ar, std::complex<T> b, T br, const T eps = std::numeric_limits<T>::epsilon()) {
// set the small circle to a
if(ar > br) {
std::swap(a, b);
std::swap(ar, br);
}
return br - (std::abs(a - b) + ar) >- eps;
};
} // namespace lib::geometry
#endif // LIB_GEOMETRY_CIRCLE_INTERSECTION
| 36.85
| 146
| 0.661465
|
hareku
|
3194ae5c521496fbfaa45774e10505c6011afb62
| 15,222
|
cpp
|
C++
|
SoftbodySimulation/src/Scenario/ObstacleCourseScenario.cpp
|
GitDaroth/SoftbodySimulation
|
21b32dfb7a72be1f2fe54de8d2863bbf6a100288
|
[
"MIT"
] | 3
|
2021-02-28T23:48:17.000Z
|
2021-11-02T15:08:34.000Z
|
SoftbodySimulation/src/Scenario/ObstacleCourseScenario.cpp
|
GitDaroth/SoftbodySimulation
|
21b32dfb7a72be1f2fe54de8d2863bbf6a100288
|
[
"MIT"
] | null | null | null |
SoftbodySimulation/src/Scenario/ObstacleCourseScenario.cpp
|
GitDaroth/SoftbodySimulation
|
21b32dfb7a72be1f2fe54de8d2863bbf6a100288
|
[
"MIT"
] | null | null | null |
#include "Scenario/ObstacleCourseScenario.h"
#include <Constraint/BoxConstraint.h>
#include <Constraint/RigidShapeConstraint.h>
#include <Constraint/SoftShapeLinearConstraint.h>
#include <Constraint/SoftShapeQuadraticConstraint.h>
const QString ObstacleCourseScenario::NAME = "ObstacleCourse";
ObstacleCourseScenario::ObstacleCourseScenario()
{
}
ObstacleCourseScenario::~ObstacleCourseScenario()
{
}
void ObstacleCourseScenario::onInitialize()
{
m_dynamicObstacles.clear();
m_elapsedTime = 0.f;
std::shared_ptr<ShapeConstraint> shapeConstraint = std::make_shared<SoftShapeLinearConstraint>("assets/points/bunny_normal.pts", "assets/meshes/bunny_normal.obj");
shapeConstraint->initialize(true);
shapeConstraint->setStartPosition(QVector3D(-8.f, 15.f, 0.f));
m_pbdSolver->addConstraint(shapeConstraint);
for (auto particle : shapeConstraint->getParticles())
m_pbdSolver->addParticle(particle);
shapeConstraint = std::make_shared<SoftShapeLinearConstraint>("assets/points/dragon.pts", "assets/meshes/dragon.obj");
shapeConstraint->initialize(true);
shapeConstraint->setStartPosition(QVector3D(-8.f, 15.f, 2.f));
m_pbdSolver->addConstraint(shapeConstraint);
for (auto particle : shapeConstraint->getParticles())
m_pbdSolver->addParticle(particle);
shapeConstraint = std::make_shared<SoftShapeLinearConstraint>("assets/points/armadillo.pts", "assets/meshes/armadillo.obj");
shapeConstraint->initialize(true);
shapeConstraint->setStartPosition(QVector3D(-8.f, 17.f, -2.f));
m_pbdSolver->addConstraint(shapeConstraint);
for (auto particle : shapeConstraint->getParticles())
m_pbdSolver->addParticle(particle);
shapeConstraint = std::make_shared<SoftShapeLinearConstraint>("assets/points/patrick.pts", "assets/meshes/patrick.obj");
shapeConstraint->initialize(true);
shapeConstraint->setStartPosition(QVector3D(-8.f, 16.5f, 0.f));
m_pbdSolver->addConstraint(shapeConstraint);
for (auto particle : shapeConstraint->getParticles())
m_pbdSolver->addParticle(particle);
shapeConstraint = std::make_shared<SoftShapeLinearConstraint>("assets/points/octopus2.pts", "assets/meshes/octopus2.obj");
shapeConstraint->initialize(true);
shapeConstraint->setStartPosition(QVector3D(-8.f, 16.5f, 2.f));
m_pbdSolver->addConstraint(shapeConstraint);
for (auto particle : shapeConstraint->getParticles())
m_pbdSolver->addParticle(particle);
shapeConstraint = std::make_shared<SoftShapeLinearConstraint>("assets/points/bunny_big.pts", "assets/meshes/bunny_big.obj");
shapeConstraint->initialize(true);
shapeConstraint->setStartPosition(QVector3D(-8.f, 15.f, -2.f));
m_pbdSolver->addConstraint(shapeConstraint);
for (auto particle : shapeConstraint->getParticles())
m_pbdSolver->addParticle(particle);
std::shared_ptr<BoxConstraint> boxBoundaryConstraint = std::make_shared<BoxConstraint>(QVector3D(-0.5f, 2.5f, 0.f), QVector3D(9.75f, 17.5f, 15.25f));
boxBoundaryConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f));
boxBoundaryConstraint->setIsBoundary(true);
m_pbdSolver->addConstraint(boxBoundaryConstraint);
// moving wall 1 -----------------------------------------
std::shared_ptr<BoxConstraint> boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(-8.f, 14.f, 0.f), QVector3D(2.f, 0.25f, 4.f));
boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(-9.75f, 17.125f, 0.f), QVector3D(0.25f, 2.87f, 4.f));
boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
m_dynamicObstacles.push_back(boxObstacleConstraint);
// -------------------------------------------------------
// moving wall 2 -----------------------------------------
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -3.5f, -11.25f), QVector3D(7.25f, 0.25f, 4.f));
boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -1.22f, -19.25f), QVector3D(7.25f, 2.f, 4.f));
boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
m_dynamicObstacles.push_back(boxObstacleConstraint);
// -------------------------------------------------------
// moving wall 3 -----------------------------------------
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -3.5f, 11.25f), QVector3D(7.25f, 0.25f, 4.f));
boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -1.22f, 19.25f), QVector3D(7.25f, 2.f, 4.f));
boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
m_dynamicObstacles.push_back(boxObstacleConstraint);
// -------------------------------------------------------
// ramp 1 -----------------------------------------
QVector3D rampPosition = QVector3D(-2.661f, 12.033f, 0.f);
boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition, QVector3D(4.f, 0.25f, 4.f));
boxObstacleConstraint->setRotation(-30.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition + QVector3D(0.381f, 0.617f, 3.8f), QVector3D(4.f, 1.f, 0.25f));
boxObstacleConstraint->setRotation(-30.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition + QVector3D(0.381f, 0.617f, -3.8f), QVector3D(4.f, 1.f, 0.25f));
boxObstacleConstraint->setRotation(-30.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
// ------------------------------------------------
// ramp 2 -----------------------------------------
rampPosition = QVector3D(5.f, 3.f, -3.4f);
boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition, QVector3D(4.f, 0.25f, 4.f));
boxObstacleConstraint->setRotation(-30.f, QVector3D(1.f, 0.f, 0.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition + QVector3D(3.8f, 0.617f, -0.381f), QVector3D(0.25, 1.f, 4.f));
boxObstacleConstraint->setRotation(-30.f, QVector3D(1.f, 0.f, 0.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition + QVector3D(-3.8f, 0.617f, -0.381f), QVector3D(0.25, 1.f, 4.f));
boxObstacleConstraint->setRotation(-30.f, QVector3D(1.f, 0.f, 0.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
// ------------------------------------------------
// ramp 3 -----------------------------------------
rampPosition = QVector3D(5.f, 3.f, 3.4f);
boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition, QVector3D(4.f, 0.25f, 4.f));
boxObstacleConstraint->setRotation(30.f, QVector3D(1.f, 0.f, 0.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition + QVector3D(3.8f, 0.617f, 0.381f), QVector3D(0.25, 1.f, 4.f));
boxObstacleConstraint->setRotation(30.f, QVector3D(1.f, 0.f, 0.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition + QVector3D(-3.8f, 0.617f, 0.381f), QVector3D(0.25, 1.f, 4.f));
boxObstacleConstraint->setRotation(30.f, QVector3D(1.f, 0.f, 0.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
// ------------------------------------------------
// funnel -----------------------------------------
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(6.5f, -5.f, 0.f), QVector3D(3.f, 0.25f, 7.f));
boxObstacleConstraint->setRotation(30.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(-2.5f, -5.f, 0.f), QVector3D(3.f, 0.25f, 7.f));
boxObstacleConstraint->setRotation(-30.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(1.95f, -5.f, -4.55f), QVector3D(7.f, 0.25f, 3.f));
boxObstacleConstraint->setRotation(30.f, QVector3D(1.f, 0.f, 0.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(1.95f, -5.f, 4.55f), QVector3D(7.f, 0.25f, 3.f));
boxObstacleConstraint->setRotation(-30.f, QVector3D(1.f, 0.f, 0.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(9.f, -5.f, 0.f), QVector3D(0.25f, 1.75f, 7.25f));
boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(-5.f, -5.f, 0.f), QVector3D(0.25f, 1.75f, 7.25f));
boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -5.f, 7.f), QVector3D(7.25f, 1.75f, 0.25f));
boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -5.f, -7.f), QVector3D(7.25f, 1.75f, 0.25f));
boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
// ------------------------------------------------
// spinning box 1 -----------------------------------------
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.5f, 10.f, 0.f), QVector3D(1.5f, 0.25f, 4.f));
boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
m_dynamicObstacles.push_back(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.5f, 10.f, 0.f), QVector3D(1.5f, 0.25f, 4.f));
boxObstacleConstraint->setRotation(90.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
m_dynamicObstacles.push_back(boxObstacleConstraint);
// --------------------------------------------------------
// spinning box 2 -----------------------------------------
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(5.f, 8.f, 0.f), QVector3D(1.5f, 0.25f, 4.f));
boxObstacleConstraint->setRotation(67.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
m_dynamicObstacles.push_back(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(5.f, 8.f, 0.f), QVector3D(1.5f, 0.25f, 4.f));
boxObstacleConstraint->setRotation(90.f + 67.f, QVector3D(0.f, 0.f, 1.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
m_dynamicObstacles.push_back(boxObstacleConstraint);
// --------------------------------------------------------
// spinning box 3 -----------------------------------------
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -8.5f, 1.7f), QVector3D(3.f, 0.25f, 1.5f));
boxObstacleConstraint->setRotation(0.f, QVector3D(1.f, 0.f, 0.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
m_dynamicObstacles.push_back(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -8.5f, 1.7f), QVector3D(3.f, 0.25f, 1.5f));
boxObstacleConstraint->setRotation(90.f, QVector3D(1.f, 0.f, 0.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
m_dynamicObstacles.push_back(boxObstacleConstraint);
// --------------------------------------------------------
// spinning box 4 -----------------------------------------
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -8.5f, -1.7f), QVector3D(3.f, 0.25f, 1.5f));
boxObstacleConstraint->setRotation(0.f, QVector3D(1.f, 0.f, 0.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
m_dynamicObstacles.push_back(boxObstacleConstraint);
boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -8.5f, -1.7f), QVector3D(3.f, 0.25f, 1.5f));
boxObstacleConstraint->setRotation(90.f, QVector3D(1.f, 0.f, 0.f));
boxObstacleConstraint->setIsBoundary(false);
m_pbdSolver->addConstraint(boxObstacleConstraint);
m_dynamicObstacles.push_back(boxObstacleConstraint);
// --------------------------------------------------------
}
void ObstacleCourseScenario::onUpdate(float deltaTime)
{
m_elapsedTime += deltaTime;
m_dynamicObstacles[0]->setPosition(3.5f * 0.5f * (-cosf(m_elapsedTime) + 1.f) * QVector3D(1.f, 0.f, 0.f) + QVector3D(-9.75f, 17.125f, 0.f));
m_dynamicObstacles[1]->setPosition(8.f * 0.5f * (-cosf(m_elapsedTime) + 1.f) * QVector3D(0.f, 0.f, 1.f) + QVector3D(2.f, -1.22f, -19.25f));
m_dynamicObstacles[2]->setPosition(-8.f * 0.5f * (-cosf(m_elapsedTime) + 1.f) * QVector3D(0.f, 0.f, 1.f) + QVector3D(2.f, -1.22f, 19.25f));
m_dynamicObstacles[3]->setRotation(-100.f * m_elapsedTime, QVector3D(0.f, 0.f, 1.f));
m_dynamicObstacles[4]->setRotation(90.f - 100.f * m_elapsedTime, QVector3D(0.f, 0.f, 1.f));
m_dynamicObstacles[5]->setRotation(67.f + 100.f * m_elapsedTime, QVector3D(0.f, 0.f, 1.f));
m_dynamicObstacles[6]->setRotation(90.f + 67.f + 100.f * m_elapsedTime, QVector3D(0.f, 0.f, 1.f));
m_dynamicObstacles[7]->setRotation(-100.f * m_elapsedTime, QVector3D(1.f, 0.f, 0.f));
m_dynamicObstacles[8]->setRotation(90.f - 100.f * m_elapsedTime, QVector3D(1.f, 0.f, 0.f));
m_dynamicObstacles[9]->setRotation(100.f * m_elapsedTime, QVector3D(1.f, 0.f, 0.f));
m_dynamicObstacles[10]->setRotation(90.f + 100.f * m_elapsedTime, QVector3D(1.f, 0.f, 0.f));
}
| 54.953069
| 164
| 0.711207
|
GitDaroth
|
31a5ff702f960fee81fcf44662d4581fe0f5620a
| 1,414
|
cpp
|
C++
|
src/io/github/technicalnotes/programming/basics/47-parameterpassing.cpp
|
chiragbhatia94/programming-cpp
|
efd6aa901deacf416a3ab599e6599845a8111eac
|
[
"MIT"
] | null | null | null |
src/io/github/technicalnotes/programming/basics/47-parameterpassing.cpp
|
chiragbhatia94/programming-cpp
|
efd6aa901deacf416a3ab599e6599845a8111eac
|
[
"MIT"
] | null | null | null |
src/io/github/technicalnotes/programming/basics/47-parameterpassing.cpp
|
chiragbhatia94/programming-cpp
|
efd6aa901deacf416a3ab599e6599845a8111eac
|
[
"MIT"
] | null | null | null |
#include "bits/stdc++.h"
using namespace std;
// here a & b are formal parameters
void swapByValue(int a, int b);
void swapByReference(int &a, int &b);
void swapByPointer(int *a, int *b);
int main(int argc, char **argv)
{
// here i & j are actual parameters
int i = 10, j = 20;
cout << "Initial value: "
<< "i = " << i << " & j = " << j << endl;
cout << "Call by value:" << endl;
swapByValue(i, j);
cout << "i = " << i << " & j = " << j << endl;
cout << "Call by reference:" << endl;
swapByReference(i, j);
cout << "i = " << i << " & j = " << j << endl;
cout << "Call by pointer:" << endl;
swapByPointer(&i, &j);
cout << "&i = " << &i << " & &j = " << &j << endl;
cout << "i = " << i << " & j = " << j << endl;
}
void swapByValue(int a, int b)
{
int c = b;
b = a;
a = c;
cout << "a = " << a << " & b = " << b << endl;
}
void swapByReference(int &a, int &b)
{
int c = b;
b = a;
a = c;
cout << "a = " << a << " & b = " << b << endl;
}
void swapByPointer(int *a, int *b)
{
// Pass by pointer is actually pass by value itself as the value of a & b are the addresses of i & j but their addresses are different, and we are just manipulating the pointers to swap the values
int c = *b;
*b = *a;
*a = c;
cout << "*a = " << *a << " & *b = " << *b << endl;
cout << "&a = " << &a << " & &b = " << &b << endl;
cout << "a = " << a << " & b = " << b << endl;
}
| 27.192308
| 198
| 0.483027
|
chiragbhatia94
|
31aa3f0bd9ddc9a5b2a36cb268a119be9267a82e
| 2,086
|
cpp
|
C++
|
src/ShadowVolumeRender.cpp
|
Loic-Corenthy/miniGL
|
47976ea80e253e115eafae5934ec3ebdd2275d16
|
[
"MIT"
] | 1
|
2021-08-18T03:54:22.000Z
|
2021-08-18T03:54:22.000Z
|
src/ShadowVolumeRender.cpp
|
Loic-Corenthy/miniGL
|
47976ea80e253e115eafae5934ec3ebdd2275d16
|
[
"MIT"
] | null | null | null |
src/ShadowVolumeRender.cpp
|
Loic-Corenthy/miniGL
|
47976ea80e253e115eafae5934ec3ebdd2275d16
|
[
"MIT"
] | null | null | null |
//===============================================================================================//
/*!
* \file ShadowVolumeRender.cpp
* \author Loïc Corenthy
* \version 1.0
*/
//===============================================================================================//
#include "ShadowVolumeRender.hpp"
#include "Shader.hpp"
#include "Exceptions.hpp"
using miniGL::ShadowVolumeRender;
using miniGL::Exceptions;
ShadowVolumeRender::~ShadowVolumeRender(void)
{
}
void ShadowVolumeRender::init(void)
{
// Create, load and compile a vertex shader
Shader lVS(Shader::ETYPE::VERTEX);
lVS.loadText("./Shaders/ShadowVolume.vert");
lVS.compile();
// Create, load and compile a geometry shader
Shader lGS(Shader::ETYPE::GEOMETRY);
lGS.loadText("./Shaders/ShadowVolume.geom");
lGS.compile();
// Create, load and compile a fragment shader
Shader lFS(Shader::ETYPE::FRAGMENT);
lFS.loadText("./Shaders/ShadowVolume.frag");
lFS.compile();
// Load the vertex and fragment shader into our program and link
attachShader(lVS);
attachShader(lGS);
attachShader(lFS);
link();
detachAndDeleteShader(lVS);
detachAndDeleteShader(lGS);
detachAndDeleteShader(lFS);
// Use our program
use();
mWVPLocation = Program::uniformLocation("uWVP");
mLightPosLocation = Program::uniformLocation("uLightPos");
// Check if we correctly initialized the uniform variables
if (!checkUniformLocations())
throw Exceptions("Not all uniform locations were updated", __FILE__, __LINE__);
}
void ShadowVolumeRender::WVP(const mat4f & pWVP)
{
glUniformMatrix4fv(mWVPLocation, 1, GL_TRUE, const_cast<mat4f &>(pWVP).data());
}
void ShadowVolumeRender::lightPosition(const vec3f & pPos)
{
glUniform3f(mLightPosLocation, pPos.x(), pPos.y(), pPos.z());
}
bool ShadowVolumeRender::checkUniformLocations(void) const
{
return (mWVPLocation != Constants::invalidUniformLocation<GLuint>() &&
mLightPosLocation != Constants::invalidUniformLocation<GLuint>());
}
| 26.74359
| 99
| 0.630393
|
Loic-Corenthy
|
b3b4c439f875d44e9c0e00a049a5a161a4f7b5d9
| 7,403
|
cpp
|
C++
|
src/postprocess/VrHooks.cpp
|
fholger/openvr_foveated
|
542768df39864386deebf260e73cf5158851fb9c
|
[
"BSD-3-Clause"
] | 76
|
2021-12-22T23:52:06.000Z
|
2022-03-30T05:52:02.000Z
|
src/postprocess/VrHooks.cpp
|
fholger/openvr_foveated
|
542768df39864386deebf260e73cf5158851fb9c
|
[
"BSD-3-Clause"
] | 10
|
2021-12-23T05:46:18.000Z
|
2022-01-15T11:43:31.000Z
|
src/postprocess/VrHooks.cpp
|
fholger/openvr_foveated
|
542768df39864386deebf260e73cf5158851fb9c
|
[
"BSD-3-Clause"
] | 3
|
2021-12-23T00:55:40.000Z
|
2022-03-02T12:08:16.000Z
|
#include "VrHooks.h"
#include "Config.h"
#include "PostProcessor.h"
#include <openvr.h>
#include <MinHook.h>
#include <unordered_map>
#include <unordered_set>
namespace {
std::unordered_map<void*, void*> hooksToOriginal;
bool ivrSystemHooked = false;
bool ivrCompositorHooked = false;
ID3D11DeviceContext *hookedContext = nullptr;
ID3D11Device *device = nullptr;
vr::PostProcessor postProcessor;
void InstallVirtualFunctionHook(void *instance, uint32_t methodPos, void *hookFunction) {
LPVOID* vtable = *((LPVOID**)instance);
LPVOID pTarget = vtable[methodPos];
LPVOID pOriginal = nullptr;
MH_CreateHook(pTarget, hookFunction, &pOriginal);
MH_EnableHook(pTarget);
hooksToOriginal[hookFunction] = pOriginal;
}
template<typename T>
T CallOriginal(T hookFunction) {
return (T)hooksToOriginal[hookFunction];
}
void IVRSystem_GetRecommendedRenderTargetSize(vr::IVRSystem *self, uint32_t *pnWidth, uint32_t *pnHeight) {
CallOriginal(IVRSystem_GetRecommendedRenderTargetSize)(self, pnWidth, pnHeight);
if (pnWidth == nullptr || pnHeight == nullptr) {
return;
}
}
vr::EVRCompositorError IVRCompositor_Submit(vr::IVRCompositor *self, vr::EVREye eEye, const vr::Texture_t *pTexture, const vr::VRTextureBounds_t *pBounds, vr::EVRSubmitFlags nSubmitFlags) {
void *origHandle = pTexture->handle;
postProcessor.Apply(eEye, pTexture, pBounds, nSubmitFlags);
vr::EVRCompositorError error = CallOriginal(IVRCompositor_Submit)(self, eEye, pTexture, pBounds, nSubmitFlags);
if (error != vr::VRCompositorError_None) {
if (Config::Instance().debugMode)
Log() << "Error when submitting for eye " << eEye << ": " << error << std::endl;
}
const_cast<vr::Texture_t*>(pTexture)->handle = origHandle;
return error;
}
vr::EVRCompositorError IVRCompositor_Submit_008(vr::IVRCompositor *self, vr::EVREye eEye, unsigned int eTextureType, void *pTexture, const vr::VRTextureBounds_t *pBounds, vr::EVRSubmitFlags nSubmitFlags) {
if (eTextureType == 0) {
// texture type is DirectX
vr::Texture_t texture;
texture.eType = vr::TextureType_DirectX;
texture.eColorSpace = vr::ColorSpace_Auto;
texture.handle = pTexture;
postProcessor.Apply(eEye, &texture, pBounds, nSubmitFlags);
pTexture = texture.handle;
}
return CallOriginal(IVRCompositor_Submit_008)(self, eEye, eTextureType, pTexture, pBounds, nSubmitFlags);
}
vr::EVRCompositorError IVRCompositor_Submit_007(vr::IVRCompositor *self, vr::EVREye eEye, unsigned int eTextureType, void *pTexture, const vr::VRTextureBounds_t *pBounds) {
if (eTextureType == 0) {
// texture type is DirectX
vr::Texture_t texture;
texture.eType = vr::TextureType_DirectX;
texture.eColorSpace = vr::ColorSpace_Auto;
texture.handle = pTexture;
postProcessor.Apply(eEye, &texture, pBounds, vr::Submit_Default);
pTexture = texture.handle;
}
return CallOriginal(IVRCompositor_Submit_007)(self, eEye, eTextureType, pTexture, pBounds);
}
using Microsoft::WRL::ComPtr;
HRESULT D3D11Context_ClearDepthStencilView(ID3D11DeviceContext *self, ID3D11DepthStencilView *pDepthStencilView, UINT ClearFlags, FLOAT Depth, UINT8 Stencil) {
HRESULT ret = CallOriginal(D3D11Context_ClearDepthStencilView)(self, pDepthStencilView, ClearFlags, Depth, Stencil);
if (ClearFlags & D3D11_CLEAR_DEPTH)
postProcessor.ApplyFixedFoveatedRendering(pDepthStencilView, Depth, Stencil);
return ret;
}
void D3D11Context_OMSetRenderTargets(
ID3D11DeviceContext *self,
UINT NumViews, ID3D11RenderTargetView * const *ppRenderTargetViews,
ID3D11DepthStencilView *pDepthStencilView) {
CallOriginal(D3D11Context_OMSetRenderTargets)(self, NumViews, ppRenderTargetViews, pDepthStencilView);
postProcessor.OnRenderTargetChange( NumViews, ppRenderTargetViews );
}
void D3D11Context_OMSetRenderTargetsAndUnorderedAccessViews(
ID3D11DeviceContext *self,
UINT NumRTVs,
ID3D11RenderTargetView * const *ppRenderTargetViews,
ID3D11DepthStencilView *pDepthStencilView,
UINT UAVStartSlot,
UINT NumUAVs,
ID3D11UnorderedAccessView * const *ppUnorderedAccessViews,
const UINT *pUAVInitialCounts) {
CallOriginal(D3D11Context_OMSetRenderTargetsAndUnorderedAccessViews)(self, NumRTVs, ppRenderTargetViews, pDepthStencilView, UAVStartSlot, NumUAVs, ppUnorderedAccessViews, pUAVInitialCounts);
postProcessor.OnRenderTargetChange( NumRTVs, ppRenderTargetViews );
}
}
void InitHooks() {
Log() << "Initializing hooks...\n";
MH_Initialize();
}
void ShutdownHooks() {
Log() << "Shutting down hooks...\n";
MH_Uninitialize();
hooksToOriginal.clear();
ivrSystemHooked = false;
ivrCompositorHooked = false;
hookedContext = nullptr;
device = nullptr;
postProcessor.Reset();
}
void HookVRInterface(const char *version, void *instance) {
// Only install hooks once, for the first interface version encountered to avoid duplicated hooks
// This is necessary because vrclient.dll may create an internal instance with a different version
// than the application to translate older versions, which with hooks installed for both would cause
// an infinite loop
Log() << "Requested interface " << version << "\n";
// -----------------------
// - Hooks for IVRSystem -
// -----------------------
unsigned int system_version = 0;
if (!ivrSystemHooked && std::sscanf(version, "IVRSystem_%u", &system_version)) {
// The 'IVRSystem::GetRecommendedRenderTargetSize' function definition has been the same since the initial
// release of OpenVR; however, in early versions there was an additional method in front of it.
uint32_t methodPos = (system_version >= 9 ? 0 : 1);
Log() << "Injecting GetRecommendedRenderTargetSize into " << version << std::endl;
InstallVirtualFunctionHook(instance, methodPos, IVRSystem_GetRecommendedRenderTargetSize);
ivrSystemHooked = true;
}
// ---------------------------
// - Hooks for IVRCompositor -
// ---------------------------
unsigned int compositor_version = 0;
if (!ivrCompositorHooked && std::sscanf(version, "IVRCompositor_%u", &compositor_version))
{
if (compositor_version >= 9) {
Log() << "Injecting Submit into " << version << std::endl;
uint32_t methodPos = compositor_version >= 12 ? 5 : 4;
InstallVirtualFunctionHook(instance, methodPos, IVRCompositor_Submit);
ivrCompositorHooked = true;
}
else if (compositor_version == 8) {
Log() << "Injecting Submit into " << version << std::endl;
InstallVirtualFunctionHook(instance, 6, IVRCompositor_Submit_008);
ivrCompositorHooked = true;
}
else if (compositor_version == 7) {
Log() << "Injecting Submit into " << version << std::endl;
InstallVirtualFunctionHook(instance, 6, IVRCompositor_Submit_007);
ivrCompositorHooked = true;
}
}
}
void HookD3D11Context( ID3D11DeviceContext *context, ID3D11Device *pDevice ) {
device = pDevice;
if (context != hookedContext) {
Log() << "Injecting ClearDepthStencilView into D3D11DeviceContext" << std::endl;
InstallVirtualFunctionHook(context, 53, D3D11Context_ClearDepthStencilView);
Log() << "Injecting OMSetRenderTargets into D3D11DeviceContext" << std::endl;
InstallVirtualFunctionHook(context, 33, D3D11Context_OMSetRenderTargets);
Log() << "Injecting OMSetRenderTargetsAndUnorderedAccessViews into D3D11DeviceContext" << std::endl;
InstallVirtualFunctionHook(context, 34, D3D11Context_OMSetRenderTargetsAndUnorderedAccessViews);
hookedContext = context;
}
}
| 38.963158
| 206
| 0.749021
|
fholger
|
b3b59670970b0825a6e0861126e8a9bc9b177aa0
| 17,708
|
cpp
|
C++
|
Minimap Source/Minimap/j1Map.cpp
|
OscarHernandezG/MinimapTestbed
|
4c06210c0e67af037232de95e02fbe44ec900cbc
|
[
"MIT"
] | null | null | null |
Minimap Source/Minimap/j1Map.cpp
|
OscarHernandezG/MinimapTestbed
|
4c06210c0e67af037232de95e02fbe44ec900cbc
|
[
"MIT"
] | null | null | null |
Minimap Source/Minimap/j1Map.cpp
|
OscarHernandezG/MinimapTestbed
|
4c06210c0e67af037232de95e02fbe44ec900cbc
|
[
"MIT"
] | null | null | null |
#include <math.h>
#include "Brofiler\Brofiler.h"
#include "Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1Collision.h"
#include "j1Scene.h"
#include "j1Audio.h"
#include "j1Map.h"
#include "j1Window.h"
j1Map::j1Map() : j1Module(), isMapLoaded(false)
{
name.assign("map");
}
// Destructor
j1Map::~j1Map()
{}
// Called before render is available
bool j1Map::Awake(pugi::xml_node& config)
{
LOG("Loading Map Parser");
bool ret = true;
folder.assign(config.child("folder").childValue());
blitOffset = config.child("general").child("blit").attribute("offset").as_int();
cameraBlit = config.child("general").child("cameraBlit").attribute("value").as_bool();
culingOffset = config.child("general").child("culing").attribute("value").as_int();
return ret;
}
void j1Map::Draw()
{
BROFILER_CATEGORY("Draw(notAbove)", Profiler::Color::Azure);
if (!isMapLoaded)
return;
// Prepare the loop to draw all tilesets + Blit
for (list<MapLayer*>::const_iterator layer = data.layers.begin(); layer != data.layers.end(); ++layer)
{
if ((*layer)->index != LAYER_TYPE_ABOVE)
{
for (int i = 0; i < (*layer)->width; ++i)
{
for (int j = 0; j < (*layer)->height; ++j)
{
int tile_id = (*layer)->Get(i, j);
if (tile_id > 0) {
TileSet* tileset = GetTilesetFromTileId(tile_id);
SDL_Rect rect = tileset->GetTileRect(tile_id);
SDL_Rect* section = ▭
iPoint world = MapToWorld(i, j);
App->render->Blit(tileset->texture, world.x, world.y, section, (*layer)->speed);
}
}//for
}//for
}
}
}
TileSet* j1Map::GetTilesetFromTileId(int id) const
{
list<TileSet*>::const_iterator item = data.tilesets.begin();
TileSet* set = *item;
while (item != data.tilesets.end())
{
if (id < (*item)->firstgid)
{
set = *(item--);
break;
}
set = *item;
item++;
}
return set;
}
iPoint j1Map::MapToWorld(int x, int y) const
{
iPoint ret;
if (data.type == MAPTYPE_ORTHOGONAL)
{
ret.x = x * data.tileWidth;
ret.y = y * data.tileHeight;
}
else if (data.type == MAPTYPE_ISOMETRIC)
{
ret.x = (x - y) * (data.tileWidth * 0.5f);
ret.y = (x + y) * (data.tileHeight * 0.5f);
}
else
{
LOG("Unknown map type");
ret.x = x; ret.y = y;
}
return ret;
}
iPoint j1Map::WorldToMap(int x, int y) const
{
iPoint ret(0, 0);
if (data.type == MAPTYPE_ORTHOGONAL)
{
ret.x = x / data.tileWidth;
ret.y = y / data.tileHeight;
}
else if (data.type == MAPTYPE_ISOMETRIC)
{
float half_width = data.tileWidth * 0.5f;
float half_height = data.tileHeight * 0.5f;
ret.x = int((x / half_width + y / half_height) / 2) - 1;
ret.y = int((y / half_height - (x / half_width)) / 2);
}
else
{
LOG("Unknown map type");
ret.x = x; ret.y = y;
}
return ret;
}
SDL_Rect TileSet::GetTileRect(int id) const
{
int relativeId = id - firstgid;
SDL_Rect rect;
rect.w = tileWidth;
rect.h = tileHeight;
rect.x = margin + ((rect.w + spacing) * (relativeId % numTilesWidth));
rect.y = margin + ((rect.h + spacing) * (relativeId / numTilesWidth));
return rect;
}
// Called before quitting
bool j1Map::CleanUp()
{
bool ret = true;
LOG("Unloading map");
// Remove all objectGroups
list<ObjectGroup*>::const_iterator objectGroup;
objectGroup = data.objectGroups.begin();
while (objectGroup != data.objectGroups.end())
{
// Remove all objects inside the objectGroup
list<Object*>::const_iterator object;
object = (*objectGroup)->objects.begin();
while (object != (*objectGroup)->objects.end())
{
delete (*object);
object++;
}
(*objectGroup)->objects.clear();
// Remove the objectGroup
delete (*objectGroup);
objectGroup++;
}
data.objectGroups.clear();
// Remove all tilesets
list<TileSet*>::const_iterator item;
item = data.tilesets.begin();
while (item != data.tilesets.end())
{
delete *item;
item++;
}
data.tilesets.clear();
// Remove all layers
list<MapLayer*>::const_iterator item1;
item1 = data.layers.begin();
while (item1 != data.layers.end())
{
delete *item1;
item1++;
}
data.layers.clear();
delete collisionLayer;
delete aboveLayer;
collisionLayer = nullptr;
aboveLayer = nullptr;
// Clean up the pugui tree
mapFile.reset();
return ret;
}
// Unload map
bool j1Map::UnLoad()
{
bool ret = true;
LOG("Unloading map");
// Remove all objectGroups
list<ObjectGroup*>::const_iterator objectGroup;
objectGroup = data.objectGroups.begin();
while (objectGroup != data.objectGroups.end())
{
// Remove all objects inside the objectGroup
list<Object*>::const_iterator object;
object = (*objectGroup)->objects.begin();
while (object != (*objectGroup)->objects.end())
{
delete (*object);
object++;
}
(*objectGroup)->objects.clear();
// Remove the objectGroup
delete (*objectGroup);
objectGroup++;
}
data.objectGroups.clear();
// Remove all tilesets
list<TileSet*>::const_iterator item;
item = data.tilesets.begin();
while (item != data.tilesets.end())
{
delete *item;
item++;
}
data.tilesets.clear();
// Remove all layers
list<MapLayer*>::const_iterator item1;
item1 = data.layers.begin();
while (item1 != data.layers.end())
{
delete *item1;
item1++;
}
data.layers.clear();
delete collisionLayer;
delete aboveLayer;
collisionLayer = nullptr;
aboveLayer = nullptr;
return ret;
}
// Load map general properties
bool j1Map::LoadMap()
{
bool ret = true;
pugi::xml_node map = mapFile.child("map");
if (map == NULL)
{
LOG("Error parsing map xml file: Cannot find 'map' tag.");
ret = false;
}
else
{
data.width = map.attribute("width").as_int();
data.height = map.attribute("height").as_int();
data.tileWidth = map.attribute("tilewidth").as_int();
data.tileHeight = map.attribute("tileheight").as_int();
string backgroundColor(map.attribute("backgroundcolor").as_string());
data.backgroundColor.r = 0;
data.backgroundColor.g = 0;
data.backgroundColor.b = 0;
data.backgroundColor.a = 0;
if (backgroundColor.size() > 0)
{
string red, green, blue;
red = backgroundColor.substr(1, 2);
green = backgroundColor.substr(3, 4);
blue = backgroundColor.substr(5, 6);
int v = 0;
sscanf_s(red.data(), "%x", &v);
if (v >= 0 && v <= 255) data.backgroundColor.r = v;
sscanf_s(green.data(), "%x", &v);
if (v >= 0 && v <= 255) data.backgroundColor.g = v;
sscanf_s(blue.data(), "%x", &v);
if (v >= 0 && v <= 255) data.backgroundColor.b = v;
}
string orientation(map.attribute("orientation").as_string());
if (orientation == "orthogonal")
{
data.type = MAPTYPE_ORTHOGONAL;
}
else if (orientation == "isometric")
{
data.type = MAPTYPE_ISOMETRIC;
}
else if (orientation == "staggered")
{
data.type = MAPTYPE_STAGGERED;
}
else
{
data.type = MAPTYPE_UNKNOWN;
}
}
return ret;
}
bool j1Map::LoadTilesetDetails(pugi::xml_node& tilesetNode, TileSet* set)
{
bool ret = true;
set->name.assign(tilesetNode.attribute("name").as_string());
set->firstgid = tilesetNode.attribute("firstgid").as_int();
set->tileWidth = tilesetNode.attribute("tilewidth").as_int();
set->tileHeight = tilesetNode.attribute("tileheight").as_int();
set->margin = tilesetNode.attribute("margin").as_int();
set->spacing = tilesetNode.attribute("spacing").as_int();
pugi::xml_node offset = tilesetNode.child("tileoffset");
if (offset != NULL)
{
set->offsetX = offset.attribute("x").as_int();
set->offsetY = offset.attribute("y").as_int();
}
else
{
set->offsetX = 0;
set->offsetY = 0;
}
return ret;
}
// Load new map
bool j1Map::Load(const char* fileName)
{
bool ret = true;
string tmp = folder.data();
tmp += fileName;
pugi::xml_parse_result result = mapFile.loadFile(tmp.data());
if (result == NULL)
{
LOG("Could not load map xml file %s. pugi error: %s", fileName, result.description());
ret = false;
}
// Load general info ----------------------------------------------
if (ret)
{
ret = LoadMap();
}
// Load all tilesets info ----------------------------------------------
pugi::xml_node tileset;
for (tileset = mapFile.child("map").child("tileset"); tileset && ret; tileset = tileset.next_sibling("tileset"))
{
TileSet* set = new TileSet();
if (ret)
{
ret = LoadTilesetDetails(tileset, set);
}
if (ret)
{
ret = LoadTilesetImage(tileset, set);
}
data.tilesets.push_back(set);
}
// Iterate all layers and load each of them
// Load layer info ----------------------------------------------
pugi::xml_node layer;
for (layer = mapFile.child("map").child("layer"); layer && ret; layer = layer.next_sibling("layer"))
{
MapLayer* set = new MapLayer();
if (ret)
{
ret = LoadLayer(layer, set);
}
data.layers.push_back(set);
}
// Load ObjectGroups and GameObjects
pugi::xml_node objectGroup;
pugi::xml_node object;
for (objectGroup = mapFile.child("map").child("objectgroup"); objectGroup && ret; objectGroup = objectGroup.next_sibling("objectgroup"))
{
ObjectGroup* set = new ObjectGroup();
if (ret)
{
ret = LoadObjectGroupDetails(objectGroup, set);
}
for (object = objectGroup.child("object"); object && ret; object = object.next_sibling("object"))
{
Object* set1 = new Object();
if (ret)
{
ret = LoadObject(object, set1);
}
set->objects.push_back(set1);
}
data.objectGroups.push_back(set);
}
if (ret)
{
LOG("Successfully parsed map XML file: %s", fileName);
LOG("width: %d height: %d", data.width, data.height);
LOG("tile_width: %d tileHeight: %d", data.tileWidth, data.tileHeight);
list<TileSet*>::const_iterator item = data.tilesets.begin();
while (item != data.tilesets.end())
{
TileSet* s = *item;
LOG("Tileset ----");
LOG("name: %s firstgid: %d", s->name.data(), s->firstgid);
LOG("tile width: %d tile height: %d", s->tileWidth, s->tileHeight);
LOG("spacing: %d margin: %d", s->spacing, s->margin);
item++;
}
// Add info here about your loaded layers
// Adapt this vcode with your own variables
list<MapLayer*>::const_iterator item_layer = data.layers.begin();
while (item_layer != data.layers.end())
{
MapLayer* l = *item_layer;
LOG("Layer ----");
LOG("name: %s", l->name.data());
LOG("tile width: %d tile height: %d", l->width, l->height);
item_layer++;
}
// Info about ObjectGroups and GameObjects
list<ObjectGroup*>::const_iterator item_group = data.objectGroups.begin();
while (item_group != data.objectGroups.end())
{
ObjectGroup* s = *item_group;
LOG("Object Group ----");
LOG("name: %s", s->name.data());
list<Object*>::const_iterator item_object = (*item_group)->objects.begin();
while (item_object != (*item_group)->objects.end())
{
Object* s = *item_object;
LOG("Object ----");
LOG("name: %s", s->name.data());
LOG("id: %d", s->id);
LOG("x: %d y: %d", s->x, s->y);
LOG("width: %d height: %d", s->width, s->height);
item_object++;
}
item_group++;
}
}
isMapLoaded = ret;
return ret;
}
bool j1Map::LoadTilesetImage(pugi::xml_node& tilesetNode, TileSet* set)
{
bool ret = true;
pugi::xml_node image = tilesetNode.child("image");
if (image == NULL)
{
LOG("Error parsing tileset xml file: Cannot find 'image' tag.");
ret = false;
}
else
{
set->texture = App->tex->Load(PATH(folder.data(), image.attribute("source").as_string()));
int w, h;
SDL_QueryTexture(set->texture, NULL, NULL, &w, &h);
set->texWidth = image.attribute("width").as_int();
if (set->texWidth <= 0)
{
set->texWidth = w;
}
set->texHeight = image.attribute("height").as_int();
if (set->texHeight <= 0)
{
set->texHeight = h;
}
set->numTilesWidth = set->texWidth / set->tileWidth;
set->numTilesHeight = set->texHeight / set->tileHeight;
}
return ret;
}
// Create the definition for a function that loads a single layer
bool j1Map::LoadLayer(pugi::xml_node& node, MapLayer* layer)
{
bool ret = true;
layer->name = node.attribute("name").as_string();
// Set layer index
if (layer->name == "Collision") {
collisionLayer = layer;
layer->index = LAYER_TYPE_COLLISION;
}
else if (layer->name == "Above") {
aboveLayer = layer;
layer->index = LAYER_TYPE_ABOVE;
}
else if (layer->name == "Parallax") {
layer->index = LAYER_TYPE_PARALLAX;
}
layer->width = node.attribute("width").as_uint();
layer->height = node.attribute("height").as_uint();
LoadProperties(node, layer->properties);
layer->data = new uint[layer->width * layer->height];
memset(layer->data, 0, layer->width * layer->height);
int i = 0;
for (pugi::xml_node tileGid = node.child("data").child("tile"); tileGid; tileGid = tileGid.next_sibling("tile")) {
layer->data[i++] = tileGid.attribute("gid").as_uint();
}
// Read layer properties
pugi::xml_node speed = node.child("properties").child("property");
if (speed != nullptr) {
string name = speed.attribute("name").as_string();
if (name == "Speed")
layer->speed = speed.attribute("value").as_float();
}
return ret;
}
inline uint MapLayer::Get(int x, int y) const
{
return data[width * y + x];
}
// Load a group of properties from a node and fill a list with it
bool j1Map::LoadProperties(pugi::xml_node& node, Properties& properties)
{
bool ret = false;
pugi::xml_node data = node.child("properties");
if (data != NULL)
{
pugi::xml_node prop;
for (prop = data.child("property"); prop; prop = prop.next_sibling("property"))
{
Properties::Property* p = new Properties::Property();
p->name = prop.attribute("name").as_string();
p->value = prop.attribute("value").as_bool();
properties.properties.push_back(p);
}
}
return ret;
}
bool j1Map::CreateWalkabilityMap(int& width, int& height, uchar** buffer) const
{
bool ret = false;
list<MapLayer*>::const_iterator item;
item = data.layers.begin();
for (item; item != data.layers.end(); ++item)
{
MapLayer* layer = *item;
if (!layer->properties.GetProperty("Navigation", false))
continue;
uchar* map = new uchar[layer->width*layer->height];
memset(map, 1, layer->width*layer->height);
for (int y = 0; y < data.height; ++y)
{
for (int x = 0; x < data.width; ++x)
{
int i = (y*layer->width) + x;
int tile_id = layer->Get(x, y);
TileSet* tileset = (tile_id > 0) ? GetTilesetFromTileId(tile_id) : NULL;
if (tileset != NULL)
{
map[i] = (tile_id - tileset->firstgid) > 0 ? 0 : 1;
/*TileType* ts = tileset->GetTileType(tile_id);
if(ts != NULL)
{
map[i] = ts->properties.Get("walkable", 1);
}*/
}
}
}
*buffer = map;
width = data.width;
height = data.height;
ret = true;
break;
}
return ret;
}
bool Properties::GetProperty(const char* value, bool default_value) const
{
list<Property*>::const_iterator item = properties.begin();
while (item != properties.end())
{
if ((*item)->name == value)
return (*item)->value;
item++;
}
return default_value;
}
bool j1Map::LoadObjectGroupDetails(pugi::xml_node& objectGroupNode, ObjectGroup* objectGroup)
{
bool ret = true;
objectGroup->name.assign(objectGroupNode.attribute("name").as_string());
return ret;
}
bool j1Map::LoadObject(pugi::xml_node& objectNode, Object* object)
{
bool ret = true;
object->name = objectNode.attribute("name").as_string();
object->id = objectNode.attribute("id").as_uint();
object->width = objectNode.attribute("width").as_uint();
object->height = objectNode.attribute("height").as_uint();
object->x = objectNode.attribute("x").as_uint();
object->y = objectNode.attribute("y").as_uint();
object->type = objectNode.attribute("type").as_uint();
return ret;
}
fPoint MapData::GetObjectPosition(string groupObject, string object)
{
fPoint pos = { 0,0 };
list<ObjectGroup*>::const_iterator item;
item = objectGroups.begin();
int ret = true;
while (item != objectGroups.end() && ret)
{
if ((*item)->name == groupObject) {
list<Object*>::const_iterator item1;
item1 = (*item)->objects.begin();
while (item1 != (*item)->objects.end() && ret)
{
if ((*item1)->name == object) {
pos.x = (*item1)->x;
pos.y = (*item1)->y;
ret = false;
}
item1++;
}
}
item++;
}
return pos;
}
fPoint MapData::GetObjectSize(string groupObject, string object)
{
fPoint size = { 0,0 };
list<ObjectGroup*>::const_iterator item;
item = objectGroups.begin();
int ret = true;
while (item != objectGroups.end() && ret)
{
if ((*item)->name == groupObject) {
list<Object*>::const_iterator item1;
item1 = (*item)->objects.begin();
while (item1 != (*item)->objects.end() && ret)
{
if ((*item1)->name == object) {
size.x = (*item1)->width;
size.y = (*item1)->height;
ret = false;
}
item1++;
}
}
item++;
}
return size;
}
Object* MapData::GetObjectByName(string groupObject, string object)
{
Object* obj = nullptr;
list<ObjectGroup*>::const_iterator item;
item = objectGroups.begin();
int ret = true;
while (item != objectGroups.end() && ret)
{
if ((*item)->name == groupObject) {
list<Object*>::const_iterator item1;
item1 = (*item)->objects.begin();
while (item1 != (*item)->objects.end() && ret)
{
if ((*item1)->name == object) {
obj = *item1;
ret = false;
}
item1++;
}
}
item++;
}
return obj;
}
bool MapData::CheckIfEnter(string groupObject, string object, fPoint position)
{
fPoint objectPos = GetObjectPosition(groupObject, object);
fPoint objectSize = GetObjectSize(groupObject, object);
return (objectPos.x < position.x + 1 && objectPos.x + objectSize.x > position.x && objectPos.y < position.y + 1 && objectSize.y + objectPos.y > position.y);
}
| 21.516403
| 157
| 0.63508
|
OscarHernandezG
|
b3b668b8797a8ff65a370f2bfaa392c52bc2462a
| 20,305
|
cpp
|
C++
|
src/CompressibleInterface.cpp
|
StephanLenz/Gas-Kinetic-Scheme
|
bb92a9640cd95ac9342adf8c31c4800414d5950a
|
[
"MIT"
] | 2
|
2018-03-05T07:51:01.000Z
|
2021-10-30T08:44:41.000Z
|
src/CompressibleInterface.cpp
|
StephanLenz/Gas-Kinetic-Scheme
|
bb92a9640cd95ac9342adf8c31c4800414d5950a
|
[
"MIT"
] | null | null | null |
src/CompressibleInterface.cpp
|
StephanLenz/Gas-Kinetic-Scheme
|
bb92a9640cd95ac9342adf8c31c4800414d5950a
|
[
"MIT"
] | 1
|
2021-03-28T12:42:15.000Z
|
2021-03-28T12:42:15.000Z
|
#include "Interface.h"
#include "CompressibleInterface.h"
#include <sstream>
CompressibleInterface::CompressibleInterface()
{
}
CompressibleInterface::CompressibleInterface(Cell* negCell, Cell* posCell, float2 center, float2 normal, FluidParameter fluidParam, InterfaceBC* BC)
: Interface(negCell, posCell, center, normal, fluidParam, BC)
{
}
CompressibleInterface::~CompressibleInterface()
{
}
void CompressibleInterface::computeTimeDerivative(double * prim, double * MomentU, double * MomentV, double * MomentXi,
double* a, double* b, double * timeGrad)
{
// ========================================================================
timeGrad[0] = a[0] * MomentU[1] * MomentV[0]
+ a[1] * MomentU[2] * MomentV[0]
+ a[2] * MomentU[1] * MomentV[1]
+ a[3] * 0.5 * ( MomentU[3] * MomentV[0] + MomentU[1] * MomentV[2] + MomentU[1] * MomentV[0] * MomentXi[2] )
+ b[0] * MomentU[0] * MomentV[1]
+ b[1] * MomentU[1] * MomentV[1]
+ b[2] * MomentU[0] * MomentV[2]
+ b[3] * 0.5 * ( MomentU[2] * MomentV[1] + MomentU[0] * MomentV[3] + MomentU[0] * MomentV[1] * MomentXi[2] )
// this part comes from the inclusion of the forcing into the flux computation
//+ 2.0 * prim[3] * ( MomentU[0]*MomentV[0] * prim[1] - MomentU[1]*MomentV[0] ) * this->fluidParam.Force.x
//+ 2.0 * prim[3] * ( MomentU[0]*MomentV[0] * prim[2] - MomentU[0]*MomentV[1] ) * this->fluidParam.Force.y
;
// ========================================================================
// ========================================================================
timeGrad[1] = a[0] * MomentU[2] * MomentV[0]
+ a[1] * MomentU[3] * MomentV[0]
+ a[2] * MomentU[2] * MomentV[1]
+ a[3] * 0.5 * ( MomentU[4] * MomentV[0] + MomentU[2] * MomentV[2] + MomentU[2] * MomentV[0] * MomentXi[2] )
+ b[0] * MomentU[1] * MomentV[1]
+ b[1] * MomentU[2] * MomentV[1]
+ b[2] * MomentU[1] * MomentV[2]
+ b[3] * 0.5 * ( MomentU[3] * MomentV[1] + MomentU[1] * MomentV[3] + MomentU[1] * MomentV[1] * MomentXi[2] )
// this part comes from the inclusion of the forcing into the flux computation
//+ 2.0 * prim[3] * ( MomentU[1]*MomentV[0] * prim[1] - MomentU[2]*MomentV[0] ) * this->fluidParam.Force.x
//+ 2.0 * prim[3] * ( MomentU[1]*MomentV[0] * prim[2] - MomentU[1]*MomentV[1] ) * this->fluidParam.Force.y
;
// ========================================================================
// ========================================================================
timeGrad[2] = a[0] * MomentU[1] * MomentV[1]
+ a[1] * MomentU[2] * MomentV[1]
+ a[2] * MomentU[1] * MomentV[2]
+ a[3] * 0.5 * ( MomentU[3] * MomentV[1] + MomentU[1] * MomentV[3] + MomentU[1] * MomentV[1] * MomentXi[2] )
+ b[0] * MomentU[0] * MomentV[2]
+ b[1] * MomentU[1] * MomentV[2]
+ b[2] * MomentU[0] * MomentV[3]
+ b[3] * 0.5 * ( MomentU[2] * MomentV[2] + MomentU[0] * MomentV[4] + MomentU[0] * MomentV[2] * MomentXi[2] )
// this part comes from the inclusion of the forcing into the flux computation
//+ 2.0 * prim[3] * ( MomentU[0]*MomentV[1] * prim[1] - MomentU[1]*MomentV[1] ) * this->fluidParam.Force.x
//+ 2.0 * prim[3] * ( MomentU[0]*MomentV[1] * prim[2] - MomentU[0]*MomentV[2] ) * this->fluidParam.Force.y
;
// ========================================================================
// ========================================================================
timeGrad[3] = a[0] * 0.50 * ( MomentU[3] * MomentV[0] + MomentU[1] * MomentV[2] + MomentU[1] * MomentV[0] * MomentXi[2] )
+ a[1] * 0.50 * ( MomentU[4] * MomentV[0] + MomentU[2] * MomentV[2] + MomentU[2] * MomentV[0] * MomentXi[2] )
+ a[2] * 0.50 * ( MomentU[3] * MomentV[1] + MomentU[1] * MomentV[3] + MomentU[1] * MomentV[1] * MomentXi[2] )
+ a[3] * 0.25 * ( MomentU[5] + MomentU[1]* ( MomentV[4] + MomentXi[4] )
+ 2.0 * MomentU[3] * MomentV[2]
+ 2.0 * MomentU[3] * MomentXi[2]
+ 2.0 * MomentU[1] * MomentV[2] * MomentXi[2]
)
+ b[0] * 0.50 * ( MomentU[2] * MomentV[1] + MomentU[0] * MomentV[3] + MomentU[0] * MomentV[1] * MomentXi[2] )
+ b[1] * 0.50 * ( MomentU[3] * MomentV[1] + MomentU[1] * MomentV[3] + MomentU[1] * MomentV[1] * MomentXi[2] )
+ b[2] * 0.50 * ( MomentU[2] * MomentV[2] + MomentU[0] * MomentV[4] + MomentU[0] * MomentV[2] * MomentXi[2] )
+ b[3] * 0.25 * ( MomentV[5] + MomentV[1] * ( MomentU[4] + MomentXi[4] )
+ 2.0 * MomentU[2] * MomentV[3]
+ 2.0 * MomentU[2] * MomentV[1] * MomentXi[2]
+ 2.0 * MomentV[3] * MomentXi[2]
)
// this part comes from the inclusion of the forcing into the flux computation
//+ prim[3] * ( ( MomentU[2] + MomentV[2] + MomentXi[2] ) * prim[1]
// - ( MomentU[3] * MomentV[0] + MomentU[1] * MomentV[2] + MomentU[1] * MomentV[0] * MomentXi[2] )
// ) * this->fluidParam.Force.x
//+ prim[3] * ( ( MomentU[2] + MomentV[2] + MomentXi[2] ) * prim[2]
// - ( MomentU[2] * MomentV[1] + MomentU[0] * MomentV[3] + MomentU[0] * MomentV[1] * MomentXi[2] )
// ) * this->fluidParam.Force.y
;
// ========================================================================
timeGrad[0] *= -1.0;
timeGrad[1] *= -1.0;
timeGrad[2] *= -1.0;
timeGrad[3] *= -1.0;
}
void CompressibleInterface::assembleFlux(double * MomentU, double * MomentV, double * MomentXi, double * a, double * b, double * A, double * timeCoefficients, double dy, double* prim, double tau)
{
double Flux_1[4];
double Flux_2[4];
double Flux_3[4];
int u = 1;
int v = 0;
// ========================================================================
Flux_1[0] = MomentU[0+u] * MomentV[0+v];
Flux_1[1] = MomentU[1+u] * MomentV[0+v];
Flux_1[2] = MomentU[0+u] * MomentV[1+v];
Flux_1[3] = 0.5 * ( MomentU[2+u] * MomentV[0+v]
+ MomentU[0+u] * MomentV[2+v]
+ MomentU[0+u] * MomentV[0+v] * MomentXi[2] );
// ========================================================================
// ================================================================================================================================================
// ================================================================================================================================================
// ================================================================================================================================================
// ========================================================================
Flux_2[0] = ( a[0] * MomentU[1+u] * MomentV[0+v]
+ a[1] * MomentU[2+u] * MomentV[0+v]
+ a[2] * MomentU[1+u] * MomentV[1+v]
+ a[3] * 0.5 * ( MomentU[3+u] * MomentV[0+v]
+ MomentU[1+u] * MomentV[2+v]
+ MomentU[1+u] * MomentV[0+v] * MomentXi[2] )
+ b[0] * MomentU[0+u] * MomentV[1+v]
+ b[1] * MomentU[1+u] * MomentV[1+v]
+ b[2] * MomentU[0+u] * MomentV[2+v]
+ b[3] * 0.5 * ( MomentU[2+u] * MomentV[1+v]
+ MomentU[0+u] * MomentV[3+v]
+ MomentU[0+u] * MomentV[1+v] * MomentXi[2] )
)
// this part comes from the inclusion of the forcing into the flux computation
//+ 2.0 * prim[3] * ( MomentU[0+u]*MomentV[0+v] * prim[1] - MomentU[1+u]*MomentV[0+v] ) * this->fluidParam.Force.x
//+ 2.0 * prim[3] * ( MomentU[0+u]*MomentV[0+v] * prim[2] - MomentU[0+u]*MomentV[1+v] ) * this->fluidParam.Force.y
;
// ========================================================================
// ========================================================================
Flux_2[1] = ( a[0] * MomentU[2+u] * MomentV[0+v]
+ a[1] * MomentU[3+u] * MomentV[0+v]
+ a[2] * MomentU[2+u] * MomentV[1+v]
+ a[3] * 0.5 * ( MomentU[4+u] * MomentV[0+v]
+ MomentU[2+u] * MomentV[2+v]
+ MomentU[2+u] * MomentV[0+v] * MomentXi[2] )
+ b[0] * MomentU[1+u] * MomentV[1+v]
+ b[1] * MomentU[2+u] * MomentV[1+v]
+ b[2] * MomentU[1+u] * MomentV[2+v]
+ b[3] * 0.5 * ( MomentU[3+u] * MomentV[1+v]
+ MomentU[1+u] * MomentV[3+v]
+ MomentU[1+u] * MomentV[1+v] * MomentXi[2] )
)
// this part comes from the inclusion of the forcing into the flux computation
//+ 2.0 * prim[3] * ( MomentU[1+u]*MomentV[0+v] * prim[1] - MomentU[2+u]*MomentV[0+v] ) * this->fluidParam.Force.x
//+ 2.0 * prim[3] * ( MomentU[1+u]*MomentV[0+v] * prim[2] - MomentU[1+u]*MomentV[1+v] ) * this->fluidParam.Force.y
;
// ========================================================================
// ========================================================================
Flux_2[2] = ( a[0] * MomentU[1+u] * MomentV[1+v]
+ a[1] * MomentU[2+u] * MomentV[1+v]
+ a[2] * MomentU[1+u] * MomentV[2+v]
+ a[3] * 0.5 * ( MomentU[3+u] * MomentV[1+v]
+ MomentU[1+u] * MomentV[3+v]
+ MomentU[1+u] * MomentV[1+v] * MomentXi[2] )
+ b[0] * MomentU[0+u] * MomentV[2+v]
+ b[1] * MomentU[1+u] * MomentV[2+v]
+ b[2] * MomentU[0+u] * MomentV[3+v]
+ b[3] * 0.5 * ( MomentU[2+u] * MomentV[2+v]
+ MomentU[0+u] * MomentV[4+v]
+ MomentU[0+u] * MomentV[2+v] * MomentXi[2] )
)
// this part comes from the inclusion of the forcing into the flux computation
//+ 2.0 * prim[3] * ( MomentU[0+u]*MomentV[1+v] * prim[1] - MomentU[1+u]*MomentV[1+v] ) * this->fluidParam.Force.x
//+ 2.0 * prim[3] * ( MomentU[0+u]*MomentV[1+v] * prim[2] - MomentU[0+u]*MomentV[2+v] ) * this->fluidParam.Force.y
;
// ========================================================================
// ========================================================================
Flux_2[3] = 0.5 * ( a[0] * ( MomentU[3+u] * MomentV[0+v]
+ MomentU[1+u] * MomentV[2+v]
+ MomentU[1+u] * MomentV[0+v] * MomentXi[2] )
+ a[1] * ( MomentU[4+u] * MomentV[0+v]
+ MomentU[2+u] * MomentV[2+v]
+ MomentU[2+u] * MomentV[0+v] * MomentXi[2] )
+ a[2] * ( MomentU[3+u] * MomentV[1+v]
+ MomentU[1+u] * MomentV[3+v]
+ MomentU[1+u] * MomentV[1+v] * MomentXi[2] )
+ a[3] * ( 0.5 * ( MomentU[5+u] * MomentV[0+v]
+ MomentU[1+u] * MomentV[4+v]
+ MomentU[1+u] * MomentV[0+v] * MomentXi[4] )
+ ( MomentU[3+u] * MomentV[2+v]
+ MomentU[3+u] * MomentV[0+v] * MomentXi[2]
+ MomentU[1+u] * MomentV[2+v] * MomentXi[2] )
)
+ b[0] * ( MomentU[2+u] * MomentV[1+v]
+ MomentU[0+u] * MomentV[3+v]
+ MomentU[0+u] * MomentV[1+v] * MomentXi[2] )
+ b[1] * ( MomentU[3+u] * MomentV[1+v]
+ MomentU[1+u] * MomentV[3+v]
+ MomentU[1+u] * MomentV[1+v] * MomentXi[2] )
+ b[2] * ( MomentU[2+u] * MomentV[2+v]
+ MomentU[0+u] * MomentV[4+v]
+ MomentU[0+u] * MomentV[2+v] * MomentXi[2] )
+ b[3] * ( 0.5 * ( MomentU[4+u] * MomentV[1+v]
+ MomentU[0+u] * MomentV[5+v]
+ MomentU[0+u] * MomentV[1+v] * MomentXi[4] )
+ ( MomentU[2+u] * MomentV[3+v]
+ MomentU[2+u] * MomentV[1+v] * MomentXi[2]
+ MomentU[0+u] * MomentV[3+v] * MomentXi[2] )
)
)
// this part comes from the inclusion of the forcing into the flux computation
//+ prim[3] * ( ( MomentU[2+u] * MomentV[0+v] + MomentU[0+u] * MomentV[2+v] + MomentU[0+u] * MomentV[0+v] * MomentXi[2] ) * prim[1]
// - ( MomentU[3+u] * MomentV[0+v] + MomentU[1+u] * MomentV[2+v] + MomentU[1+u] * MomentV[0+v] * MomentXi[2] )
// ) * this->fluidParam.Force.x
//+ prim[3] * ( ( MomentU[2+u] * MomentV[0+v] + MomentU[0+u] * MomentV[2+v] + MomentU[0+u] * MomentV[0+v] * MomentXi[2] ) * prim[2]
// - ( MomentU[2+u] * MomentV[1+v] + MomentU[0+u] * MomentV[3+v] + MomentU[0+u] * MomentV[1+v] * MomentXi[2] )
// ) * this->fluidParam.Force.y
;
// ========================================================================
// ================================================================================================================================================
// ================================================================================================================================================
// ================================================================================================================================================
// ========================================================================
Flux_3[0] = ( A[0] * MomentU[0+u] * MomentV[0+v]
+ A[1] * MomentU[1+u] * MomentV[0+v]
+ A[2] * MomentU[0+u] * MomentV[1+v]
+ A[3] * 0.5 * ( MomentU[2+u]*MomentV[0+v]
+ MomentU[0+u]*MomentV[2+v]
+ MomentU[0+u]*MomentV[0+v]*MomentXi[2] )
);
// ========================================================================
// ========================================================================
Flux_3[1] = ( A[0] * MomentU[1+u] * MomentV[0+v]
+ A[1] * MomentU[2+u] * MomentV[0+v]
+ A[2] * MomentU[1+u] * MomentV[1+v]
+ A[3] * 0.5 * ( MomentU[3+u]*MomentV[0+v]
+ MomentU[1+u]*MomentV[2+v]
+ MomentU[1+u]*MomentV[0+v]*MomentXi[2] )
);
// ========================================================================
// ========================================================================
Flux_3[2] = ( A[0] * MomentU[0+u] * MomentV[1+v]
+ A[1] * MomentU[1+u] * MomentV[1+v]
+ A[2] * MomentU[0+u] * MomentV[2+v]
+ A[3] * 0.5 * ( MomentU[2+u]*MomentV[1+v]
+ MomentU[0+u]*MomentV[3+v]
+ MomentU[0+u]*MomentV[1+v]*MomentXi[2] )
);
// ========================================================================
// ========================================================================
Flux_3[3] = 0.5 * ( A[0] * ( MomentU[2+u] * MomentV[0+v]
+ MomentU[0+u] * MomentV[2+v]
+ MomentU[0+u] * MomentV[0+v] * MomentXi[2] )
+ A[1] * ( MomentU[3+u] * MomentV[0+v]
+ MomentU[1+u] * MomentV[2+v]
+ MomentU[1+u] * MomentV[0+v] * MomentXi[2] )
+ A[2] * ( MomentU[2+u] * MomentV[1+v]
+ MomentU[0+u] * MomentV[3+v]
+ MomentU[0+u] * MomentV[1+v] * MomentXi[2] )
+ A[3] * ( 0.5 * ( MomentU[4+u] * MomentV[0+v]
+ MomentU[0+u] * MomentV[4+v]
+ MomentU[0+u] * MomentV[0+v] * MomentXi[4] )
+ ( MomentU[2+u] * MomentV[2+v]
+ MomentU[2+u] * MomentV[0+v] * MomentXi[2]
+ MomentU[0+u] * MomentV[2+v] * MomentXi[2] )
)
);
// ========================================================================
// ================================================================================================================================================
// ================================================================================================================================================
// ================================================================================================================================================
// ========================================================================
for ( int i = 0; i < 4; i++ )
{
this->timeIntegratedFlux[i] = ( timeCoefficients[0] * Flux_1[i] + timeCoefficients[1] * Flux_2[i] + timeCoefficients[2] * Flux_3[i] ) * dy * prim[0];
// The Flux density in the Flux per unit area of the interface at one instant in time
this->FluxDensity[i] = ( Flux_1[i] - tau*( Flux_2[i] + Flux_3[i] ) ) * prim[0];
}
// ========================================================================
int i = 1;
}
void CompressibleInterface::computeMicroSlope(double * prim, double * macroSlope, double * microSlope)
{
// this method computes the micro slopes from the slopes of the conservative variables
// the resulting microslopes contain the density, since they are computed from the slopes
// of the conservative variables, which are rho, rhoU, rhoV and rhoE
double A, B, C, E;
// ========================================================================
// this is 2 times the total energy density 2 E = 2 rhoE / rho
E = prim[1] * prim[1] + prim[2] * prim[2] + ( this->fluidParam.K + 2.0 ) / ( 2.0*prim[3] );
// ========================================================================
// ========================================================================
// the product rule of derivations is used here!
A = 2.0*macroSlope[3] - E * macroSlope[0]; // = 2 rho dE/dx
B = macroSlope[1] - prim[1] * macroSlope[0]; // = rho dU/dx
C = macroSlope[2] - prim[2] * macroSlope[0]; // = rho dV/dx
// ========================================================================
// compute micro slopes of primitive variables from macro slopes of conservatice variables
microSlope[3] = ( 4.0 * prim[3] * prim[3] ) / ( this->fluidParam.K + 2.0 )
* ( A - 2.0*prim[1] * B - 2.0*prim[2] * C );
microSlope[2] = 2.0 * prim[3] * C - prim[2] * microSlope[3];
microSlope[1] = 2.0 * prim[3] * B - prim[1] * microSlope[3];
microSlope[0] = macroSlope[0] - prim[1] * microSlope[1] - prim[2] * microSlope[2] - 0.5 * E* microSlope[3];
}
| 62.094801
| 195
| 0.353854
|
StephanLenz
|
b3bb7024e5e4f424c0c5d0927f92c63be9d4c0b7
| 1,274
|
hpp
|
C++
|
22_Pvector/Pvector.hpp
|
jonixis/CPP18
|
0dfe165f22a3cbef9e8cda102196d53d3e120e57
|
[
"MIT"
] | null | null | null |
22_Pvector/Pvector.hpp
|
jonixis/CPP18
|
0dfe165f22a3cbef9e8cda102196d53d3e120e57
|
[
"MIT"
] | null | null | null |
22_Pvector/Pvector.hpp
|
jonixis/CPP18
|
0dfe165f22a3cbef9e8cda102196d53d3e120e57
|
[
"MIT"
] | null | null | null |
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
#ifndef INC_41_TRAITS_PVECTOR_HPP
#define INC_41_TRAITS_PVECTOR_HPP
template<typename T>
struct persistence_traits {
static void write(ofstream &o, const T &elem) {
o << elem << endl;
}
};
template<typename T, typename P=persistence_traits<T>>
class Pvector {
string filename;
vector<T> v;
void read_vector() {
ifstream ifs(filename);
for (;;) {
T x;
ifs >> x;
if (!ifs.good()) {
break;
}
v.push_back(x);
}
}
void write_vector() {
ofstream ofs(filename);
for (const T &elem : v) {
persister::write(ofs, elem);
}
}
public:
typedef P persister;
explicit Pvector(string fname) : filename(fname) {
read_vector();
}
~Pvector() {
write_vector();
cout << "Destructor called!" << endl;
}
void push_back(const T &el) {
v.push_back(el);
}
void pop_back() {
v.pop_back();
}
long getSize() {
return v.size();
}
void printElement(int index) {
cout << v.at(index) << endl;
}
};
#endif //INC_41_TRAITS_PVECTOR_HPP
| 18.2
| 54
| 0.536892
|
jonixis
|
b3bc314b3e857569bdb88feaed3e98e849c6c9d7
| 1,442
|
cpp
|
C++
|
src/walls.cpp
|
JulianNeeleman/kattis
|
035c1113ffb397c2d8538af8ba16b7ee4160393d
|
[
"MIT"
] | null | null | null |
src/walls.cpp
|
JulianNeeleman/kattis
|
035c1113ffb397c2d8538af8ba16b7ee4160393d
|
[
"MIT"
] | 1
|
2017-05-16T15:57:29.000Z
|
2017-05-17T19:43:56.000Z
|
src/walls.cpp
|
JulianNeeleman/kattis
|
035c1113ffb397c2d8538af8ba16b7ee4160393d
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>
#include <cmath>
using namespace std;
const double epsilon = 0.0001;
struct Point {
double x, y;
};
double dist(const Point& p, const Point& q) {
return sqrt((p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y));
}
int check(const vector<Point>& ws, const vector<Point>& cs, double r) {
for(const Point &p : ws) {
bool success = false;
for(const Point &q : cs) {
if(dist(p, q) <= r + epsilon) success = true;
}
if(!success) return 5;
}
return cs.size();
}
int main() {
double l, w, n, r;
cin >> l >> w >> n >> r;
vector<Point> ws = { { -l / 2.0, 0.0 }, { l / 2.0, 0.0 },
{ 0.0, -w / 2.0 }, { 0.0, w / 2.0 } };
vector<Point> cs(n);
for(int i = 0; i < n; i++) {
cin >> cs[i].x >> cs[i].y;
}
int ans = 5;
vector<Point> cur;
for(int a = 0; a < n; a++) {
cur.push_back(cs[a]);
ans = min(ans, check(ws, cur, r));
for(int b = a + 1; b < n; b++) {
cur.push_back(cs[b]);
ans = min(ans, check(ws, cur, r));
for(int c = b + 1; c < n; c++) {
cur.push_back(cs[c]);
ans = min(ans, check(ws, cur, r));
for(int d = c + 1; d < n; d++) {
cur.push_back(cs[d]);
ans = min(ans, check(ws, cur, r));
cur.pop_back();
}
cur.pop_back();
}
cur.pop_back();
}
cur.pop_back();
}
if(ans < 5) cout << ans << endl;
else cout << "Impossible" << endl;
return 0;
}
| 20.309859
| 71
| 0.520111
|
JulianNeeleman
|
b3bcd8253059818f8721730ed9c272478c943a7e
| 23,067
|
cpp
|
C++
|
emf_core_bindings/src/emf_fs.cpp
|
GabeRealB/emf
|
a233edaed7ed99948b0a935e6378bac131fdf4c2
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
emf_core_bindings/src/emf_fs.cpp
|
GabeRealB/emf
|
a233edaed7ed99948b0a935e6378bac131fdf4c2
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
emf_core_bindings/src/emf_fs.cpp
|
GabeRealB/emf
|
a233edaed7ed99948b0a935e6378bac131fdf4c2
|
[
"Apache-2.0",
"MIT"
] | 1
|
2021-01-10T15:00:08.000Z
|
2021-01-10T15:00:08.000Z
|
#include <emf_core/emf_fs.h>
#include <emf_core_bindings/emf_core_bindings.h>
using namespace EMF::Core::C;
namespace EMF::Core::Bindings::C {
extern "C" {
emf_file_handler_t EMF_CALL_C emf_fs_register_file_handler(const emf_file_handler_interface_t* EMF_NOT_NULL file_handler,
const emf_file_type_span_t* EMF_NOT_NULL file_types) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(file_handler != nullptr, "emf_fs_register_file_handler()")
EMF_ASSERT_ERROR(file_types != nullptr, "emf_fs_register_file_handler()")
EMF_ASSERT_ERROR(file_types->data != nullptr, "emf_fs_register_file_handler()")
EMF_ASSERT_ERROR(file_types->length > 0, "emf_fs_register_file_handler()")
return emf_binding_interface->fs_register_file_handler_fn(file_handler, file_types);
}
void EMF_CALL_C emf_fs_remove_file_handler(emf_file_handler_t file_handler) EMF_NOEXCEPT
{
emf_binding_interface->fs_remove_file_handler_fn(file_handler);
}
void EMF_CALL_C emf_fs_create_file(const emf_path_t* EMF_NOT_NULL filename, const void* EMF_MAYBE_NULL options) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(filename != nullptr, "emf_fs_create_file()")
EMF_ASSERT_ERROR(emf_fs_exists(filename) == emf_bool_false, "emf_fs_create_file()")
#ifdef EMF_ENABLE_DEBUG_ASSERTIONS
auto parent { emf_fs_get_parent(filename) };
EMF_ASSERT_ERROR(emf_fs_exists(&parent) == emf_bool_true, "emf_fs_create_file()")
EMF_ASSERT_ERROR(emf_fs_is_virtual(&parent) == emf_bool_false, "emf_fs_create_file()")
EMF_ASSERT_ERROR(emf_fs_get_access_mode(&parent) == emf_file_access_mode_write, "emf_fs_create_file()")
#endif // EMF_ENABLE_DEBUG_ASSERTIONS
emf_binding_interface->fs_create_file_fn(filename, options);
}
void EMF_CALL_C emf_fs_create_link(
const emf_path_t* EMF_NOT_NULL source, const emf_path_t* EMF_NOT_NULL destination, emf_fs_link_t type) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(source != nullptr, "emf_fs_create_link()")
EMF_ASSERT_ERROR(destination != nullptr, "emf_fs_create_link()")
EMF_ASSERT_ERROR(emf_fs_exists(source) == emf_bool_true, "emf_fs_create_link()")
EMF_ASSERT_ERROR(emf_fs_exists(destination) == emf_bool_false, "emf_fs_create_link()")
EMF_ASSERT_ERROR(emf_fs_is_virtual(source) == emf_bool_false, "emf_fs_create_link()")
#ifdef EMF_ENABLE_DEBUG_ASSERTIONS
auto destination_parent { emf_fs_get_parent(destination) };
EMF_ASSERT_ERROR(emf_fs_exists(&destination_parent) == emf_bool_true, "emf_fs_create_link()")
EMF_ASSERT_ERROR(emf_fs_is_virtual(&destination_parent) == emf_bool_true, "emf_fs_create_link()")
EMF_ASSERT_ERROR(emf_fs_get_access_mode(&destination_parent) == emf_file_access_mode_write, "emf_fs_create_link()")
#endif // EMF_ENABLE_DEBUG_ASSERTIONS
emf_binding_interface->fs_create_link_fn(source, destination, type);
}
void EMF_CALL_C emf_fs_create_directory(const emf_path_t* EMF_NOT_NULL path, const void* EMF_MAYBE_NULL options) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_create_directory()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_false, "emf_fs_create_directory()")
#ifdef EMF_ENABLE_DEBUG_ASSERTIONS
auto parent { emf_fs_get_parent(path) };
EMF_ASSERT_ERROR(emf_fs_exists(&parent) == emf_bool_true, "emf_fs_create_directory()")
EMF_ASSERT_ERROR(emf_fs_get_access_mode(&parent) == emf_file_access_mode_write, "emf_fs_create_directory()")
#endif // EMF_ENABLE_DEBUG_ASSERTIONS
emf_binding_interface->fs_create_directory_fn(path, options);
}
void EMF_CALL_C emf_fs_delete(const emf_path_t* EMF_NOT_NULL path, emf_bool_t recursive) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_delete()")
EMF_ASSERT_ERROR(emf_fs_can_delete(path, recursive) == emf_bool_true, "emf_fs_delete()")
emf_binding_interface->fs_delete_fn(path, recursive);
}
emf_mount_id_t EMF_CALL_C emf_fs_mount_memory_file(emf_file_handler_t file_handler, const emf_memory_span_t* EMF_NOT_NULL file,
emf_access_mode_t access_mode, const emf_path_t* EMF_NOT_NULL mount_point, const void* EMF_MAYBE_NULL options) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(file != nullptr, "emf_fs_mount_memory_file()")
EMF_ASSERT_ERROR(mount_point != nullptr, "emf_fs_mount_memory_file()")
EMF_ASSERT_ERROR(file->data != nullptr, "emf_fs_mount_memory_file()")
EMF_ASSERT_ERROR(file->length > 0, "emf_fs_mount_memory_file()")
EMF_ASSERT_ERROR(emf_fs_exists(mount_point) == emf_bool_false, "emf_fs_mount_memory_file()")
#ifdef EMF_ENABLE_DEBUG_ASSERTIONS
auto mount_point_parent { emf_fs_get_parent(mount_point) };
EMF_ASSERT_ERROR(emf_fs_exists(&mount_point_parent) == emf_bool_true, "emf_fs_mount_memory_file()")
EMF_ASSERT_ERROR(emf_fs_is_virtual(&mount_point_parent) == emf_bool_true, "emf_fs_mount_memory_file()")
EMF_ASSERT_ERROR(emf_fs_get_access_mode(&mount_point_parent) == emf_file_access_mode_write, "emf_fs_mount_memory_file()")
#endif // EMF_ENABLE_DEBUG_ASSERTIONS
return emf_binding_interface->fs_mount_memory_file_fn(file_handler, file, access_mode, mount_point, options);
}
emf_mount_id_t EMF_CALL_C emf_fs_mount_native_path(emf_file_handler_t file_handler,
const emf_native_path_char_t* EMF_NOT_NULL path, emf_access_mode_t access_mode, const emf_path_t* EMF_NOT_NULL mount_point,
const void* EMF_MAYBE_NULL options) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_mount_native_path()")
EMF_ASSERT_ERROR(mount_point != nullptr, "emf_fs_mount_native_path()")
EMF_ASSERT_ERROR(emf_fs_can_mount_native_path(file_handler, path) == emf_bool_true, "emf_fs_mount_native_path()")
EMF_ASSERT_ERROR(emf_fs_exists(mount_point) == emf_bool_false, "emf_fs_mount_native_path()")
#ifdef EMF_ENABLE_DEBUG_ASSERTIONS
auto mount_point_parent { emf_fs_get_parent(mount_point) };
EMF_ASSERT_ERROR(emf_fs_exists(&mount_point_parent) == emf_bool_true, "emf_fs_mount_native_path()")
EMF_ASSERT_ERROR(emf_fs_is_virtual(&mount_point_parent) == emf_bool_true, "emf_fs_mount_native_path()")
EMF_ASSERT_ERROR(emf_fs_get_access_mode(&mount_point_parent) == emf_file_access_mode_write, "emf_fs_mount_native_path()")
#endif // EMF_ENABLE_DEBUG_ASSERTIONS
return emf_binding_interface->fs_mount_native_path_fn(file_handler, path, access_mode, mount_point, options);
}
EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_unmount(emf_mount_id_t mount_id) EMF_NOEXCEPT
{
return emf_binding_interface->fs_unmount_fn(mount_id);
}
void EMF_CALL_C emf_fs_set_access_mode(
const emf_path_t* EMF_NOT_NULL path, emf_access_mode_t access_mode, emf_bool_t recursive) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_set_access_mode()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_set_access_mode()")
EMF_ASSERT_ERROR(emf_fs_can_set_access_mode(path, access_mode, recursive) == emf_bool_true, "emf_fs_set_access_mode()")
emf_binding_interface->fs_set_access_mode_fn(path, access_mode, recursive);
}
EMF_NODISCARD emf_access_mode_t EMF_CALL_C emf_fs_get_access_mode(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_access_mode()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_access_mode()")
return emf_binding_interface->fs_get_access_mode_fn(path);
}
EMF_NODISCARD emf_mount_id_t EMF_CALL_C emf_fs_get_mount_id(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_mount_id()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_mount_id()")
EMF_ASSERT_ERROR(emf_fs_is_virtual(path) == emf_bool_false || emf_fs_get_entry_type(path) == emf_fs_entry_type_mount_point,
"emf_fs_get_mount_id()")
return emf_binding_interface->fs_get_mount_id_fn(path);
}
EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_can_access(
const emf_path_t* EMF_NOT_NULL path, emf_access_mode_t access_mode) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_can_access()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_can_access()")
return emf_binding_interface->fs_can_access_fn(path, access_mode);
}
EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_can_set_access_mode(
const emf_path_t* EMF_NOT_NULL path, emf_access_mode_t access_mode, emf_bool_t recursive) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_can_set_access_mode()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_can_set_access_mode()")
return emf_binding_interface->fs_can_set_access_mode_fn(path, access_mode, recursive);
}
EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_is_virtual(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_is_virtual()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_is_virtual()")
return emf_binding_interface->fs_is_virtual_fn(path);
}
EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_can_delete(const emf_path_t* EMF_NOT_NULL path, emf_bool_t recursive) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_can_delete()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_can_delete()")
return emf_binding_interface->fs_can_delete_fn(path, recursive);
}
EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_can_mount_type(
emf_file_handler_t file_handler, const emf_file_type_t* EMF_NOT_NULL type) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(type != nullptr, "emf_fs_can_mount_type()")
return emf_binding_interface->fs_can_mount_type_fn(file_handler, type);
}
EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_can_mount_native_path(
emf_file_handler_t file_handler, const emf_native_path_char_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_can_mount_native_path()")
return emf_binding_interface->fs_can_mount_native_path_fn(file_handler, path);
}
EMF_NODISCARD size_t EMF_CALL_C emf_fs_get_num_entries(const emf_path_t* EMF_NOT_NULL path, emf_bool_t recursive) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_num_entries()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_num_entries()")
return emf_binding_interface->fs_get_num_entries_fn(path, recursive);
}
size_t EMF_CALL_C emf_fs_get_entries(
const emf_path_t* EMF_NOT_NULL path, emf_bool_t recursive, emf_path_span_t* EMF_NOT_NULL buffer) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_entries()")
EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_get_entries()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_entries()")
EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_get_entries()")
EMF_ASSERT_ERROR(buffer->length >= emf_fs_get_num_entries(path, recursive), "emf_fs_get_entries()")
return emf_binding_interface->fs_get_entries_fn(path, recursive, buffer);
}
EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_exists(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_exists()")
return emf_binding_interface->fs_exists_fn(path);
}
EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_type_exists(const emf_file_type_t* EMF_NOT_NULL type) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(type != nullptr, "emf_fs_exists()")
return emf_binding_interface->fs_type_exists_fn(type);
}
EMF_NODISCARD emf_fs_entry_type_t EMF_CALL_C emf_fs_get_entry_type(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_entry_type()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_entry_type()")
return emf_binding_interface->fs_get_entry_type_fn(path);
}
EMF_NODISCARD emf_path_t EMF_CALL_C emf_fs_resolve_link(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_resolve_link()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_resolve_link()")
EMF_ASSERT_ERROR(emf_fs_get_entry_type(path) == emf_fs_entry_type_link, "emf_fs_resolve_link()")
return emf_binding_interface->fs_resolve_link_fn(path);
}
EMF_NODISCARD emf_fs_link_t EMF_CALL_C emf_fs_get_link_type(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_link_type()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_link_type()")
EMF_ASSERT_ERROR(emf_fs_get_entry_type(path) == emf_fs_entry_type_link, "emf_fs_get_link_type()")
return emf_binding_interface->fs_get_link_type_fn(path);
}
EMF_NODISCARD emf_entry_size_t EMF_CALL_C emf_fs_get_size(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_size()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_size()")
return emf_binding_interface->fs_get_size_fn(path);
}
EMF_NODISCARD size_t EMF_CALL_C emf_fs_get_native_path_length(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_native_path_length()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_native_path_length()")
EMF_ASSERT_ERROR(emf_fs_is_virtual(path) == emf_bool_false, "emf_fs_get_native_path_length()")
return emf_binding_interface->fs_get_native_path_length_fn(path);
}
size_t EMF_CALL_C emf_fs_get_native_path(
const emf_path_t* EMF_NOT_NULL path, emf_native_path_span_t* EMF_NOT_NULL buffer) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_native_path()")
EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_get_native_path()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_native_path()")
EMF_ASSERT_ERROR(emf_fs_is_virtual(path) == emf_bool_false, "emf_fs_get_native_path()")
EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_get_native_path()")
EMF_ASSERT_ERROR(buffer->length >= emf_fs_get_native_path_length(path), "emf_fs_get_native_path()")
return emf_binding_interface->fs_get_native_path_fn(path, buffer);
}
EMF_NODISCARD size_t EMF_CALL_C emf_fs_get_num_file_handlers() EMF_NOEXCEPT
{
return emf_binding_interface->fs_get_num_file_handlers_fn();
}
size_t EMF_CALL_C emf_fs_get_file_handlers(emf_file_handler_span_t* EMF_NOT_NULL buffer) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_get_file_handlers()")
EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_get_file_handlers()")
EMF_ASSERT_ERROR(buffer->length >= emf_fs_get_num_file_handlers(), "emf_fs_get_file_handlers()")
return emf_binding_interface->fs_get_file_handlers_fn(buffer);
}
EMF_NODISCARD emf_file_handler_t EMF_CALL_C emf_fs_get_file_handler_from_type(
const emf_file_type_t* EMF_NOT_NULL type) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(type != nullptr, "emf_fs_get_file_handler_from_type()")
EMF_ASSERT_ERROR(emf_fs_type_exists(type) == emf_bool_true, "emf_fs_get_file_handler_from_type()")
return emf_binding_interface->fs_get_file_handler_from_type_fn(type);
}
EMF_NODISCARD size_t EMF_CALL_C emf_fs_get_num_file_types() EMF_NOEXCEPT
{
return emf_binding_interface->fs_get_num_file_types_fn();
}
size_t EMF_CALL_C emf_fs_get_file_types(emf_file_type_span_t* EMF_NOT_NULL buffer) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_get_file_types()")
EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_get_file_types()")
EMF_ASSERT_ERROR(buffer->length >= emf_fs_get_num_file_types(), "emf_fs_get_file_types()")
return emf_binding_interface->fs_get_file_types_fn(buffer);
}
EMF_NODISCARD size_t EMF_CALL_C emf_fs_get_num_handler_file_types(emf_file_handler_t file_handler) EMF_NOEXCEPT
{
return emf_binding_interface->fs_get_num_handler_file_types_fn(file_handler);
}
size_t EMF_CALL_C emf_fs_get_handler_file_types(
emf_file_handler_t file_handler, emf_file_type_span_t* EMF_NOT_NULL buffer) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_get_file_types()")
EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_get_file_types()")
EMF_ASSERT_ERROR(buffer->length >= emf_fs_get_num_handler_file_types(file_handler), "emf_fs_get_file_types()")
return emf_binding_interface->fs_get_handler_file_types_fn(file_handler, buffer);
}
EMF_NODISCARD emf_path_t EMF_CALL_C emf_fs_normalize(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_normalize()")
return emf_binding_interface->fs_normalize_fn(path);
}
EMF_NODISCARD emf_path_t EMF_CALL_C emf_fs_get_parent(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_parent()")
return emf_binding_interface->fs_get_parent_fn(path);
}
EMF_NODISCARD emf_path_t EMF_CALL_C emf_fs_join(
const emf_path_t* EMF_NOT_NULL lhs, const emf_path_t* EMF_NOT_NULL rhs) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(lhs != nullptr, "emf_fs_join()")
EMF_ASSERT_ERROR(rhs != nullptr, "emf_fs_join()")
return emf_binding_interface->fs_join_fn(lhs, rhs);
}
EMF_NODISCARD emf_mount_id_t EMF_CALL_C emf_fs_unsafe_create_mount_id(const emf_path_t* EMF_NOT_NULL mount_point) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(mount_point != nullptr, "emf_fs_unsafe_create_mount_id()")
EMF_ASSERT_ERROR(emf_fs_exists(mount_point) == emf_bool_false, "emf_fs_unsafe_create_mount_id()")
#ifdef EMF_ENABLE_DEBUG_ASSERTIONS
auto mount_point_parent { emf_fs_get_parent(mount_point) };
EMF_ASSERT_ERROR(emf_fs_exists(&mount_point_parent) == emf_bool_true, "emf_fs_unsafe_create_mount_id()")
EMF_ASSERT_ERROR(emf_fs_get_access_mode(&mount_point_parent) == emf_file_access_mode_write, "emf_fs_unsafe_create_mount_id()")
#endif // EMF_ENABLE_DEBUG_ASSERTIONS
return emf_binding_interface->fs_unsafe_create_mount_id_fn(mount_point);
}
void EMF_CALL_C emf_fs_unsafe_remove_mount_id(emf_mount_id_t mount_id) EMF_NOEXCEPT
{
emf_binding_interface->fs_unsafe_remove_mount_id_fn(mount_id);
}
void EMF_CALL_C emf_fs_unsafe_unmount_force(emf_mount_id_t mount_id) EMF_NOEXCEPT
{
emf_binding_interface->fs_unsafe_unmount_force_fn(mount_id);
}
void EMF_CALL_C emf_fs_unsafe_link_mount_point(
emf_mount_id_t mount_id, emf_file_handler_t file_handler, emf_file_handler_mount_id_t file_handler_mount_id) EMF_NOEXCEPT
{
emf_binding_interface->fs_unsafe_link_mount_point_fn(mount_id, file_handler, file_handler_mount_id);
}
EMF_NODISCARD emf_file_stream_t EMF_CALL_C emf_fs_unsafe_create_file_stream() EMF_NOEXCEPT
{
return emf_binding_interface->fs_unsafe_create_file_stream_fn();
}
void EMF_CALL_C emf_fs_unsafe_remove_file_stream(emf_file_stream_t file_stream) EMF_NOEXCEPT
{
emf_binding_interface->fs_unsafe_remove_file_stream_fn(file_stream);
}
void EMF_CALL_C emf_fs_unsafe_link_file_stream(
emf_file_stream_t file_stream, emf_file_handler_t file_handler, emf_file_handler_stream_t file_handler_stream) EMF_NOEXCEPT
{
emf_binding_interface->fs_unsafe_link_file_stream_fn(file_stream, file_handler, file_handler_stream);
}
EMF_NODISCARD emf_file_handler_t EMF_CALL_C emf_fs_unsafe_get_file_handler_handle_from_stream(
emf_file_stream_t stream) EMF_NOEXCEPT
{
return emf_binding_interface->fs_unsafe_get_file_handler_handle_from_stream_fn(stream);
}
EMF_NODISCARD emf_file_handler_t EMF_CALL_C emf_fs_unsafe_get_file_handler_handle_from_path(
const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(path != nullptr, "emf_fs_unsafe_get_file_handler_handle_from_path()")
EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_unsafe_get_file_handler_handle_from_path()")
EMF_ASSERT_ERROR(emf_fs_is_virtual(path) == emf_bool_false || emf_fs_get_entry_type(path) == emf_fs_entry_type_mount_point,
"emf_fs_unsafe_get_file_handler_handle_from_path()")
return emf_binding_interface->fs_unsafe_get_file_handler_handle_from_path_fn(path);
}
EMF_NODISCARD emf_file_handler_stream_t EMF_CALL_C emf_fs_unsafe_get_file_handler_stream(
emf_file_stream_t file_stream) EMF_NOEXCEPT
{
return emf_binding_interface->fs_unsafe_get_file_handler_stream_fn(file_stream);
}
EMF_NODISCARD emf_file_handler_mount_id_t EMF_CALL_C emf_fs_unsafe_get_file_handler_mount_id(emf_mount_id_t mount_id) EMF_NOEXCEPT
{
return emf_binding_interface->fs_unsafe_get_file_handler_mount_id_fn(mount_id);
}
EMF_NODISCARD emf_file_handler_interface_t EMF_CALL_C emf_fs_unsafe_get_file_handler(emf_file_handler_t file_handler) EMF_NOEXCEPT
{
return emf_binding_interface->fs_unsafe_get_file_handler_fn(file_handler);
}
EMF_NODISCARD emf_file_stream_t EMF_CALL_C emf_fs_stream_open(const emf_path_t* EMF_NOT_NULL filename,
emf_file_open_mode_t open_mode, emf_access_mode_t access_mode, const void* EMF_MAYBE_NULL options) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(filename != nullptr, "emf_fs_stream_open()")
EMF_ASSERT_ERROR(emf_fs_get_entry_type(filename) == emf_fs_entry_type_file, "emf_fs_stream_open()")
EMF_ASSERT_ERROR(emf_fs_can_access(filename, access_mode) == emf_bool_true, "emf_fs_stream_open()")
return emf_binding_interface->fs_stream_open_fn(filename, open_mode, access_mode, options);
}
void EMF_CALL_C emf_fs_stream_close(emf_file_stream_t stream) EMF_NOEXCEPT { emf_binding_interface->fs_stream_close_fn(stream); }
void EMF_CALL_C emf_fs_stream_flush(emf_file_stream_t stream) EMF_NOEXCEPT { emf_binding_interface->fs_stream_flush_fn(stream); }
size_t EMF_CALL_C emf_fs_stream_read(
emf_file_stream_t stream, emf_fs_buffer_t* EMF_NOT_NULL buffer, size_t read_count) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_stream_read()")
EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_stream_read()")
EMF_ASSERT_ERROR(buffer->length >= read_count, "emf_fs_stream_read()")
return emf_binding_interface->fs_stream_read_fn(stream, buffer, read_count);
}
size_t EMF_CALL_C emf_fs_stream_write(
emf_file_stream_t stream, const emf_fs_buffer_t* EMF_NOT_NULL buffer, size_t write_count) EMF_NOEXCEPT
{
EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_stream_write()")
EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_stream_write()")
EMF_ASSERT_ERROR(buffer->length >= write_count, "emf_fs_stream_write()")
EMF_ASSERT_ERROR(emf_fs_stream_can_write(stream) == emf_bool_true, "emf_fs_stream_write()")
return emf_binding_interface->fs_stream_write_fn(stream, buffer, write_count);
}
EMF_NODISCARD emf_pos_t EMF_CALL_C emf_fs_stream_get_pos(emf_file_stream_t stream) EMF_NOEXCEPT
{
return emf_binding_interface->fs_stream_get_pos_fn(stream);
}
emf_off_t EMF_CALL_C emf_fs_stream_set_pos(emf_file_stream_t stream, emf_pos_t position) EMF_NOEXCEPT
{
return emf_binding_interface->fs_stream_set_pos_fn(stream, position);
}
emf_off_t EMF_CALL_C emf_fs_stream_move_pos(emf_file_stream_t stream, emf_off_t offset, emf_fs_direction_t direction) EMF_NOEXCEPT
{
return emf_binding_interface->fs_stream_move_pos_fn(stream, offset, direction);
}
EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_stream_can_write(emf_file_stream_t stream) EMF_NOEXCEPT
{
return emf_binding_interface->fs_stream_can_write_fn(stream);
}
EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_stream_can_grow(emf_file_stream_t stream, size_t size) EMF_NOEXCEPT
{
return emf_binding_interface->fs_stream_can_grow_fn(stream, size);
}
}
}
| 48.460084
| 130
| 0.816144
|
GabeRealB
|
b3c2be0d7c9f027f32390842006099361e76ec7d
| 135
|
cpp
|
C++
|
Cplusplus/week_four/extra/DailyTask_Mechanic/man.cpp
|
nexusstar/SoftUni
|
b97bdb08a227fd335df5b7869940c14717f760f2
|
[
"MIT"
] | 1
|
2016-12-20T19:53:03.000Z
|
2016-12-20T19:53:03.000Z
|
Cplusplus/week_four/extra/DailyTask_Mechanic/man.cpp
|
nexusstar/SoftUni
|
b97bdb08a227fd335df5b7869940c14717f760f2
|
[
"MIT"
] | null | null | null |
Cplusplus/week_four/extra/DailyTask_Mechanic/man.cpp
|
nexusstar/SoftUni
|
b97bdb08a227fd335df5b7869940c14717f760f2
|
[
"MIT"
] | null | null | null |
#include "man.h"
#include "car.h"
void Man::crashCar(Car &aCar)
{
if(aCar.needsRepair == true) return;
aCar.needsRepair = true;
}
| 15
| 38
| 0.666667
|
nexusstar
|
b3c2ef63f883c3d06f27912aa32ed1534c46e34d
| 2,814
|
cpp
|
C++
|
source/Windows/Storage/File.cpp
|
awstanley/cpp-gamefilesystem
|
fc06cf5f2b4f873846677f45fa5480a69cdd91df
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 1
|
2021-07-12T19:25:29.000Z
|
2021-07-12T19:25:29.000Z
|
source/Windows/Storage/File.cpp
|
awstanley/cpp-gamefilesystem
|
fc06cf5f2b4f873846677f45fa5480a69cdd91df
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 6
|
2017-10-16T19:30:25.000Z
|
2018-10-06T23:55:19.000Z
|
source/Windows/Storage/File.cpp
|
awstanley/cpp-gamefilesystem
|
fc06cf5f2b4f873846677f45fa5480a69cdd91df
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 3
|
2017-10-14T10:21:44.000Z
|
2021-07-12T19:25:39.000Z
|
/*
* Copyright 2017-2018 ReversingSpace. See the COPYRIGHT file at the
* top-level directory of this distribution and in the repository:
* https://github.com/ReversingSpace/cpp-gamefilesystem
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
**/
// This is the WINDOWS file code.
#if defined(_WIN32) || defined(_WIN64)
#include <ReversingSpace/Storage/File.hpp>
#include <Windows.h>
#if defined(_DEBUG)
#include <stdio.h>
#endif
namespace reversingspace {
#if REVERSINGSPACE_STORAGE_GRANULARITY == 1
namespace platform {
std::uint64_t get_granularity() {
SYSTEM_INFO SystemInfo;
GetSystemInfo(&SystemInfo);
std::uint64_t granularity = SystemInfo.dwAllocationGranularity;
return granularity;
}
}
#endif
namespace storage {
bool File::open() {
// Shared mode is *always* READ|WRITE, as we don't care
// and shouldn't care. For games, this is a non-issue,
// and it allows modders to do things. Changing this
// reflects a massive change that we probably don't want
// to have to deal with.
DWORD dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
DWORD dwDesiredAccess = GENERIC_READ;
DWORD dwCreationDisposition = OPEN_ALWAYS;
DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
switch (access) {
case FileAccess::Read:
{
dwCreationDisposition = OPEN_EXISTING;
dwFlagsAndAttributes = FILE_ATTRIBUTE_READONLY;
} break;
case FileAccess::Write: {
dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
} break;
case FileAccess::ReadWrite: {
dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
} break;
case FileAccess::ReadExecute:
case FileAccess::Execute: {
// This bodes terribly.
dwDesiredAccess = GENERIC_READ | GENERIC_EXECUTE;
} break;
case FileAccess::ReadWriteExecute: {
dwDesiredAccess = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE;
} break;
}
// This creates (or opens) the file. Naming is somewhat obvious,
// but the arguments are kind of weird to anyone used to `fopen`.
file_handle = ::CreateFileW(
path.wstring().c_str(),
dwDesiredAccess,
dwShareMode,
NULL,
dwCreationDisposition,
dwFlagsAndAttributes,
NULL
);
if (file_handle == INVALID_HANDLE_VALUE) {
#if defined(_DEBUG)
auto error = GetLastError();
fprintf(stderr, "Error in CreateFileW call: %d\n", error);
#endif
return false;
}
return true;
}
// Platform-specific terminate.
void File::close() {
::CloseHandle(file_handle);
}
}
}
#endif//defined(_WIN32) || defined(_WIN64)
| 28.714286
| 70
| 0.704691
|
awstanley
|
b3c43ce490d6003bf0804ccb623ab9ac6be650c6
| 1,094
|
hpp
|
C++
|
L7/EMail/SMTP/GpSmtpClientCurl.hpp
|
ITBear/GpNetwork
|
65b28ee8ed16e47efd8f8991cd8942c8a517c45e
|
[
"Apache-2.0"
] | null | null | null |
L7/EMail/SMTP/GpSmtpClientCurl.hpp
|
ITBear/GpNetwork
|
65b28ee8ed16e47efd8f8991cd8942c8a517c45e
|
[
"Apache-2.0"
] | null | null | null |
L7/EMail/SMTP/GpSmtpClientCurl.hpp
|
ITBear/GpNetwork
|
65b28ee8ed16e47efd8f8991cd8942c8a517c45e
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "GpSmtpClient.hpp"
typedef void CURL;
namespace GPlatform {
class GPNETWORK_API GpSmtpClientCurl final: public GpSmtpClient
{
public:
CLASS_REMOVE_CTRS_MOVE_COPY(GpSmtpClientCurl)
CLASS_DECLARE_DEFAULTS(GpSmtpClientCurl)
public:
GpSmtpClientCurl (void) noexcept;
virtual ~GpSmtpClientCurl (void) noexcept override final;
virtual std::string/*msg_id*/ Send (const GpEmail& aEmail) override final;
virtual bool IsValid (void) const noexcept override final;
private:
void CurlInit (void);
void CurlClear (void) noexcept;
void FillAddrs (void* aCurlList,
const GpEmailAddr::C::Vec::SP& aAddrList) const;
private:
CURL* iCurl = nullptr;
};
}//namespace GPlatform
| 31.257143
| 106
| 0.5
|
ITBear
|
b3c5c742b8bc852eae598eaf1b1a12f53da03a96
| 324
|
cpp
|
C++
|
src/megabreakthrough/megapawn.cpp
|
hallur/boardgame
|
374fd1366cbae785bc40ba24403d50e36b2a3637
|
[
"MIT"
] | null | null | null |
src/megabreakthrough/megapawn.cpp
|
hallur/boardgame
|
374fd1366cbae785bc40ba24403d50e36b2a3637
|
[
"MIT"
] | 1
|
2018-04-09T19:08:41.000Z
|
2018-04-09T19:08:41.000Z
|
src/megabreakthrough/megapawn.cpp
|
hallur/boardgame
|
374fd1366cbae785bc40ba24403d50e36b2a3637
|
[
"MIT"
] | null | null | null |
#include "megabreakthrough/megapawn.h"
boardgame::megabreakthrough::MegaPawn::MegaPawn(boardgame::Player* player, bool top) : boardgame::breakthrough::Pawn(player, top, 'm') {
moveRules_.push_back(MoveRule( 0, (top ? 1 : -1), true, false, false, 2 )); // up up
}
boardgame::megabreakthrough::MegaPawn::~MegaPawn() {}
| 46.285714
| 136
| 0.70679
|
hallur
|
b3d1e1203c2696aa0fdfed91592ed93edb51fb92
| 2,719
|
cpp
|
C++
|
ObjOrientedProgramming/Movie/Movie/Movie.cpp
|
jhbrian/Learning-Progress
|
de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb
|
[
"MIT"
] | null | null | null |
ObjOrientedProgramming/Movie/Movie/Movie.cpp
|
jhbrian/Learning-Progress
|
de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb
|
[
"MIT"
] | null | null | null |
ObjOrientedProgramming/Movie/Movie/Movie.cpp
|
jhbrian/Learning-Progress
|
de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb
|
[
"MIT"
] | null | null | null |
//*************************************************************************************
//Program Name: Movie
//Author: Jin Han Ho
//IDE Used: Visual Studio 2019
//Program description: read inputs from input file and output them as 4 sets of object
//*************************************************************************************
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <sstream>
using namespace std;
/*----------------------------
Movie
----------------------------
- screenWriter: string
- yearReleased : int
- title : string
----------------------------
+ getScreenWriter() : string
+ getYearReleased() : int
+ getTitle() : string
+ setScreenWriter(a : string) : void
+ setYearReleased(y : int) : void
+ setTitle(t : string) : void
----------------------------*/
class Movie {
private:
string screenWriter;
int yearReleased =0;
string title;
public:
string getScreenWriter();
int getYearReleased();
string getTitle();
void setScreenWriter(string a);
void setYearReleased(int y);
void setTitle(string t);
};
string Movie::getScreenWriter() {
return screenWriter;
}
int Movie::getYearReleased() {
return yearReleased;
}
string Movie::getTitle() {
return title;
}
void Movie::setScreenWriter(string a) {
screenWriter = a;
}
void Movie::setYearReleased(int y) {
yearReleased = y;
}
void Movie::setTitle(string t) {
title = t;
}
int main(){
ifstream fin;
string name, writer;
int i=0,year = 0;
const int SIZE = 4;
Movie Arr[SIZE];
fin.open("input.txt");
while (getline(fin, writer)) {
fin >> year;
fin.ignore();
getline(fin, name);
Arr[i].setScreenWriter(writer);
Arr[i].setYearReleased(year);
Arr[i].setTitle(name);
i++;
}
cout << "This program will create several objects depicting movies." << endl
<< "Reading input file..." << endl
<< "...done." << endl;
for (int i = 0; i < SIZE; i++) {
cout << "Movie: " << Arr[i].getTitle() << endl;
cout << setw(10) << " > " << "Year released: " << Arr[i].getYearReleased() << endl;
cout << setw(10) << " > " << "Screenwriter: " << Arr[i].getScreenWriter() << endl;
}
fin.close();
cout << endl;
cout << "I attest that this code is my original programming work, and that I received" << endl
<< "no help creating it. I attest that I did not copy this code or any portion of this" << endl
<< "code from any source." << endl;
return 0;
}
| 26.398058
| 104
| 0.513056
|
jhbrian
|
b3d743aa9520ca333b45e102bcb2087b68b4c0fe
| 4,334
|
cpp
|
C++
|
oneEngine/oneGame/source/renderer/object/shapes/RrShapePlane.cpp
|
skarik/1Engine
|
84e846544b4a89af8fd7e9236131363096538ef4
|
[
"BSD-3-Clause"
] | 8
|
2017-12-08T02:59:31.000Z
|
2022-02-02T04:30:03.000Z
|
oneEngine/oneGame/source/renderer/object/shapes/RrShapePlane.cpp
|
skarik/1Engine
|
84e846544b4a89af8fd7e9236131363096538ef4
|
[
"BSD-3-Clause"
] | 2
|
2021-04-16T03:44:42.000Z
|
2021-08-30T06:48:44.000Z
|
oneEngine/oneGame/source/renderer/object/shapes/RrShapePlane.cpp
|
skarik/1Engine
|
84e846544b4a89af8fd7e9236131363096538ef4
|
[
"BSD-3-Clause"
] | 1
|
2021-04-16T02:09:54.000Z
|
2021-04-16T02:09:54.000Z
|
#include "RrShapePlane.h"
#include "gpuw/Device.h"
#include "gpuw/GraphicsContext.h"
#include "renderer/material/Material.h"
rrMeshBuffer RrShapePlane::m_MeshBuffer;
void RrShapePlane::BuildMeshBuffer ( void )
{
if (m_MeshBuffer.m_mesh_uploaded == false)
{
const Real hxsize = 0.5F;
const Real hysize = 0.5F;
arModelData model;
model.position = new Vector3f [4];
model.normal = new Vector3f [4];
model.tangent = new Vector3f [4];
model.color = new Vector4f [4];
model.texcoord0 = new Vector3f [4];
model.vertexNum = 4;
model.indices = new uint16_t [6];
model.indexNum = 6;
// set commons
for ( uint i = 0; i < 4; i += 1 )
{
model.normal[i] = Vector3f(0, 0, 1.0F);
model.color[i] = Vector4f(1.0F, 1.0F, 1.0F, 1.0F);
model.tangent[i] = Vector3f(1.0F, 0, 0);
}
// Set UVs:
model.texcoord0[0] = Vector2f(0, 0);
model.texcoord0[1] = Vector2f(1, 0);
model.texcoord0[2] = Vector2f(0, 1);
model.texcoord0[3] = Vector2f(1, 1);
// Set triangles:
model.indices[0] = 0;
model.indices[1] = 2;
model.indices[2] = 1;
model.indices[3] = 2;
model.indices[4] = 3;
model.indices[5] = 1;
// Set new positions
model.position[0] = Vector2f(-hxsize, -hysize);
model.position[1] = Vector2f( hxsize, -hysize);
model.position[2] = Vector2f(-hxsize, hysize);
model.position[3] = Vector2f( hxsize, hysize);
// Model is created, we upload:
m_MeshBuffer.InitMeshBuffers(&model);
m_MeshBuffer.m_modeldata = NULL;
// Free the CPU model data:
delete_safe_array(model.position);
delete_safe_array(model.normal);
delete_safe_array(model.tangent);
delete_safe_array(model.color);
delete_safe_array(model.texcoord0);
delete_safe_array(model.indices);
}
}
RrShapePlane::RrShapePlane ( void )
: RrRenderObject()
{
BuildMeshBuffer();
}
bool RrShapePlane::CreateConstants ( rrCameraPass* cameraPass )
{
// Set up transformation for the mesh
PushCbufferPerObject(this->transform.world, cameraPass);
return true;
}
// Render the mesh
bool RrShapePlane::Render ( const rrRenderParams* params )
{
gpu::GraphicsContext* gfx = params->context->context_graphics;
gpu::Pipeline* pipeline = GetPipeline( params->pass );
gfx->setPipeline(pipeline);
// Set up the material helper...
renderer::Material(this, params->context, params, pipeline)
// set the depth & blend state registers
.setDepthStencilState()
.setRasterizerState()
// bind the samplers & textures
.setBlendState()
.setTextures()
// execute callback
.executePassCallback();
// bind the vertex buffers
auto passAccess = PassAccess(params->pass);
for (int i = 0; i < passAccess.getVertexSpecificationCount(); ++i)
{
int buffer_index = (int)passAccess.getVertexSpecification()[i].location;
int buffer_binding = (int)passAccess.getVertexSpecification()[i].binding;
if (m_MeshBuffer.m_bufferEnabled[buffer_index])
gfx->setVertexBuffer(buffer_binding, &m_MeshBuffer.m_buffer[buffer_index], 0);
}
// bind the index buffer
gfx->setIndexBuffer(&m_MeshBuffer.m_indexBuffer, gpu::kIndexFormatUnsigned16);
// bind the cbuffers: TODO
gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_OBJECT_MATRICES, &m_cbufPerObjectMatrices);
gfx->setShaderCBuffer(gpu::kShaderStagePs, renderer::CBUFFER_PER_OBJECT_MATRICES, &m_cbufPerObjectMatrices);
gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_OBJECT_EXTENDED, &m_cbufPerObjectSurfaces[params->pass]);
gfx->setShaderCBuffer(gpu::kShaderStagePs, renderer::CBUFFER_PER_OBJECT_EXTENDED, &m_cbufPerObjectSurfaces[params->pass]);
gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_CAMERA_INFORMATION, params->cbuf_perCamera);
gfx->setShaderCBuffer(gpu::kShaderStagePs, renderer::CBUFFER_PER_CAMERA_INFORMATION, params->cbuf_perCamera);
gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_PASS_INFORMATION, params->cbuf_perPass);
gfx->setShaderCBuffer(gpu::kShaderStagePs, renderer::CBUFFER_PER_PASS_INFORMATION, params->cbuf_perPass);
gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_FRAME_INFORMATION, params->cbuf_perFrame);
gfx->setShaderCBuffer(gpu::kShaderStagePs, renderer::CBUFFER_PER_FRAME_INFORMATION, params->cbuf_perFrame);
// draw now
//gfx->drawIndexed(m_MeshBuffer.m_modeldata->indexNum, 0, 0);
gfx->drawIndexed(6, 0, 0);
return true;
}
| 33.596899
| 123
| 0.739502
|
skarik
|
b3d91ac2b161cf618f17cb46fac3839324372ada
| 4,595
|
cpp
|
C++
|
tests/unit/test_exact_ops.cpp
|
ylatkin/tfcp
|
9db30f7fd23dfc9f56cbe9657c39dfd6ab4559cd
|
[
"Apache-2.0"
] | 2
|
2020-04-28T16:37:03.000Z
|
2021-01-07T15:52:15.000Z
|
tests/unit/test_exact_ops.cpp
|
ylatkin/tfcp
|
9db30f7fd23dfc9f56cbe9657c39dfd6ab4559cd
|
[
"Apache-2.0"
] | 1
|
2020-01-07T04:40:51.000Z
|
2020-01-07T06:48:49.000Z
|
tests/unit/test_exact_ops.cpp
|
ylatkin/tfcp
|
9db30f7fd23dfc9f56cbe9657c39dfd6ab4559cd
|
[
"Apache-2.0"
] | null | null | null |
//======================================================================
// 2019-2020 (c) Evgeny Latkin
// License: Apache 2.0 (http://www.apache.org/licenses/)
//======================================================================
#include <tfcp/test_utils.h>
#include <tfcp/exact.h>
#include <tfcp/simd.h>
#include <gtest/gtest.h>
#include <random>
#include <string>
#include <tuple>
#include <cmath>
#include <cstdio>
namespace {
using namespace tfcp;
using namespace testing;
//----------------------------------------------------------------------
//
// Reference functions (scalar types): ref_padd0, ref_psub0, ref_pmul0
//
//----------------------------------------------------------------------
template<typename T> T ref_padd0(T x, T y, T& r1)
{
if (std::fabs(x) >= std::fabs(y))
{
return fast_padd0(x, y, r1);
}
else
{
return fast_padd0(y, x, r1);
}
}
template<typename T> T ref_psub0(T x, T y, T& r1)
{
if (std::fabs(x) >= std::fabs(y))
{
return fast_psub0(x, y, r1);
}
else
{
T t0, t1;
t0 = fast_psub0(y, x, t1);
r1 = -t1;
return -t0;
}
}
template<typename T> T ref_pmul0(T x, T y, T& r1)
{
return nofma_pmul0(x, y, r1);
}
//----------------------------------------------------------------------
using TypeName = std::string;
using OpName = std::string;
using Params = typename std::tuple<TypeName, OpName>;
class TestUnitExactOps : public TestWithParam<Params> {
private:
template<typename T, typename TX, typename F, typename FX>
static void test_case(const char type[], const char op[], F f, FX fx)
{
std::mt19937 gen;
std::uniform_real_distribution<T> dis(-10, 10);
int errors = 0;
// repeat this test 1000 times
for (int n = 0; n < 1000; n++)
{
TX x, y, r0, r1;
int len = sizeof(TX) / sizeof(T);
for (int i = 0; i < len; i++)
{
getx(x, i) = dis(gen);
getx(y, i) = dis(gen);
}
r0 = fx(x, y, r1); // maybe short-vector operation
for (int i = 0; i < len; i++)
{
T xi = getx(x, i);
T yi = getx(y, i);
T r0i, r1i; // actual result
T e0i, e1i; // expected
r0i = getx(r0, i);
r1i = getx(r1, i);
e0i = f(xi, yi, e1i);
if (r0i != e0i || r1i != e1i) {
printf("ERROR: type=%s op=%s iter=%d i=%d "
"result=%g + %g expected=%g + %g\n",
type, op, n+1, i, r0i, r1i, e0i, e1i);
errors++;
if (errors > 25) {
FAIL() << "too many failures";
}
}
}
}
ASSERT_EQ(errors, 0);
}
protected:
#define TEST_CASE(OP) \
template<typename T, typename TX> \
static void test_##OP(const char type[]) \
{ \
test_case<T, TX>(type, #OP, ref_p##OP##0<T>, p##OP##0<TX>); \
}
TEST_CASE(add);
TEST_CASE(sub);
TEST_CASE(mul);
#undef TEST_CASE
};
TEST_P(TestUnitExactOps, smoke) {
auto param = GetParam();
auto type = std::get<0>(param);
auto op = std::get<1>(param);
#define OP_CASE(T, TX, OP) \
if (op == #OP) { \
test_##OP<T,TX>(#TX); \
return; \
}
#define TYPE_CASE(T, TX) \
if (type == #TX) { \
OP_CASE(T, TX, add); \
OP_CASE(T, TX, sub); \
OP_CASE(T, TX, mul); \
FAIL() << "unknown op: " << op; \
}
TYPE_CASE(float, float);
TYPE_CASE(float, floatx);
TYPE_CASE(double, double);
TYPE_CASE(double, doublex);
#undef TYPE_CASE
#undef OP_CASE
FAIL() << "unknown type: " << type;
}
//----------------------------------------------------------------------
} // namespace
INSTANTIATE_TEST_SUITE_P(types, TestUnitExactOps,
Combine(Values("float",
"double",
"floatx",
"doublex"),
Values("add",
"sub",
"mul")));
| 25.960452
| 73
| 0.395212
|
ylatkin
|
b3da909cea3b1c3a0731cc6138e902ac2390dffd
| 12,477
|
hpp
|
C++
|
mcppalloc_bitmap_allocator/mcppalloc_bitmap_allocator/include/mcppalloc/mcppalloc_bitmap_allocator/bitmap_state_impl.hpp
|
garyfurnish/mcppalloc
|
5a6dfc99bab23e7f6aba8d20919d71a6e31c38bf
|
[
"MIT"
] | null | null | null |
mcppalloc_bitmap_allocator/mcppalloc_bitmap_allocator/include/mcppalloc/mcppalloc_bitmap_allocator/bitmap_state_impl.hpp
|
garyfurnish/mcppalloc
|
5a6dfc99bab23e7f6aba8d20919d71a6e31c38bf
|
[
"MIT"
] | null | null | null |
mcppalloc_bitmap_allocator/mcppalloc_bitmap_allocator/include/mcppalloc/mcppalloc_bitmap_allocator/bitmap_state_impl.hpp
|
garyfurnish/mcppalloc
|
5a6dfc99bab23e7f6aba8d20919d71a6e31c38bf
|
[
"MIT"
] | null | null | null |
#pragma once
#include <atomic>
#include <iostream>
#include <mcppalloc/mcppalloc_slab_allocator/slab_allocator.hpp>
#include <mcpputil/mcpputil/intrinsics.hpp>
#include <mcpputil/mcpputil/security.hpp>
namespace mcppalloc::bitmap_allocator::details
{
inline bitmap_state_t *get_state(void *v)
{
uintptr_t vi = reinterpret_cast<uintptr_t>(v);
size_t mask = ::std::numeric_limits<size_t>::max() << (mcpputil::ffs(c_bitmap_block_size) - 1);
vi &= mask;
vi += ::mcppalloc::slab_allocator::details::slab_allocator_t::cs_header_sz;
bitmap_state_t *state = reinterpret_cast<bitmap_state_t *>(vi);
return state;
}
MCPPALLOC_OPT_ALWAYS_INLINE auto bitmap_state_t::declared_entry_size() const noexcept -> size_t
{
return m_internal.m_info.m_data_entry_sz;
}
MCPPALLOC_OPT_ALWAYS_INLINE auto bitmap_state_t::real_entry_size() const noexcept -> size_t
{
return cs_object_alignment > declared_entry_size() ? cs_object_alignment : declared_entry_size();
}
MCPPALLOC_OPT_ALWAYS_INLINE auto bitmap_state_t::header_size() const noexcept -> size_t
{
return m_internal.m_info.m_header_size;
}
template <typename Allocator_Policy>
void bitmap_state_t::set_bitmap_package(bitmap_package_t<Allocator_Policy> *package) noexcept
{
m_internal.m_info.m_package = package;
}
inline auto bitmap_state_t::bitmap_package() const noexcept -> void *
{
return m_internal.m_info.m_package;
}
inline void bitmap_state_t::initialize_consts() noexcept
{
m_internal.m_pre_magic_number = cs_magic_number_pre;
m_internal.m_post_magic_number = cs_magic_number_0;
}
template <typename Allocator_Policy>
inline void
bitmap_state_t::initialize(type_id_t type_id, uint8_t user_bit_fields, bitmap_package_t<Allocator_Policy> *package) noexcept
{
initialize_consts();
m_internal.m_info.m_type_id = type_id;
m_internal.m_info.m_num_user_bit_fields = user_bit_fields;
_compute_size();
free_bits_ref().fill(::std::numeric_limits<uint64_t>::max());
m_internal.m_info.m_cached_first_free = 0;
m_internal.m_info.m_package = package;
for (size_t i = 0; i < num_user_bit_fields(); ++i) {
clear_user_bits(i);
}
}
inline void bitmap_state_t::clear_mark_bits() noexcept
{
mark_bits_ref().clear();
}
inline void bitmap_state_t::clear_user_bits(size_t index) noexcept
{
user_bits_ref(index).clear();
}
inline auto bitmap_state_t::all_free() const noexcept -> bool
{
return free_bits_ref().all_set();
}
inline auto bitmap_state_t::num_bit_arrays() const noexcept -> size_t
{
return cs_bits_array_multiple + m_internal.m_info.m_num_user_bit_fields;
}
inline auto bitmap_state_t::any_free() const noexcept -> bool
{
return free_bits_ref().any_set();
}
inline auto bitmap_state_t::none_free() const noexcept -> bool
{
return free_bits_ref().none_set();
}
inline auto bitmap_state_t::first_free() const noexcept -> size_t
{
return m_internal.m_info.m_cached_first_free;
}
inline auto bitmap_state_t::_compute_first_free() noexcept -> size_t
{
auto ret = free_bits_ref().first_set();
m_internal.m_info.m_cached_first_free = ret;
return ret;
}
inline auto bitmap_state_t::any_marked() const noexcept -> bool
{
return mark_bits_ref().any_set();
}
inline auto bitmap_state_t::none_marked() const noexcept -> bool
{
return mark_bits_ref().none_set();
}
inline auto bitmap_state_t::free_popcount() const noexcept -> size_t
{
return free_bits_ref().popcount();
}
inline void bitmap_state_t::set_free(size_t i, bool val) noexcept
{
free_bits_ref().set_bit(i, val);
if (val) {
m_internal.m_info.m_cached_first_free = ::std::min(i, m_internal.m_info.m_cached_first_free);
} else if (i == m_internal.m_info.m_cached_first_free) {
// not free
if (i + 1 >= size()) {
m_internal.m_info.m_cached_first_free = ::std::numeric_limits<size_t>::max();
} else if (is_free(i + 1)) {
m_internal.m_info.m_cached_first_free++;
} else {
// could be anywhere
_compute_first_free();
}
}
}
inline void bitmap_state_t::set_marked(size_t i) noexcept
{
mark_bits_ref().set_bit_atomic(i, true, ::std::memory_order_relaxed);
}
inline auto bitmap_state_t::is_free(size_t i) const noexcept -> bool
{
return free_bits_ref().get_bit(i);
}
inline auto bitmap_state_t::is_marked(size_t i) const noexcept -> bool
{
return mark_bits_ref().get_bit(i);
}
inline auto bitmap_state_t::type_id() const noexcept -> type_id_t
{
return m_internal.m_info.m_type_id;
}
inline auto bitmap_state_t::size() const noexcept -> size_t
{
return m_internal.m_info.m_size;
}
inline void bitmap_state_t::_compute_size() noexcept
{
auto blocks = m_internal.m_info.m_num_blocks;
auto unaligned = sizeof(*this) + sizeof(bits_array_type) * blocks * num_bit_arrays();
m_internal.m_info.m_header_size = mcpputil::align(unaligned, cs_header_alignment);
auto hdr_sz = header_size();
auto data_sz = c_bitmap_block_size - slab_allocator::details::slab_allocator_t::cs_header_sz - hdr_sz;
// this needs to be min of stuff
auto num_data = data_sz / (real_entry_size());
num_data = ::std::min(num_data, m_internal.m_info.m_num_blocks * bits_array_type::size_in_bits());
m_internal.m_info.m_size = num_data;
}
inline auto bitmap_state_t::size_bytes() const noexcept -> size_t
{
return size() * real_entry_size();
}
inline auto bitmap_state_t::total_size_bytes() const noexcept -> size_t
{
return size_bytes() + header_size();
}
inline auto bitmap_state_t::begin() noexcept -> uint8_t *
{
return reinterpret_cast<uint8_t *>(this) + header_size();
}
inline auto bitmap_state_t::end() noexcept -> uint8_t *
{
return begin() + size_bytes();
}
inline auto bitmap_state_t::begin() const noexcept -> const uint8_t *
{
return reinterpret_cast<const uint8_t *>(this) + header_size();
}
inline auto bitmap_state_t::end() const noexcept -> const uint8_t *
{
return begin() + size_bytes();
}
inline void *bitmap_state_t::allocate() noexcept
{
size_t retries = 0;
RESTART:
auto i = first_free();
if (i >= size()) {
return nullptr;
}
// guarentee the memory address exists somewhere that is visible to gc
volatile auto memory_address = begin() + real_entry_size() * i;
set_free(i, false);
// this awful code is because for a conservative gc
// we could set free before memory_address is live.
// this can go wrong because we could mark while it is still free.
if (mcpputil_unlikely(is_free(i))) {
if (mcpputil_likely(retries < 15)) {
goto RESTART;
} else {
::std::cerr << "mcppalloc: bitmap_state terminating due to allocation failure 0b3fb7a6-7270-45e3-a1cf-da341de0ccfb\n";
::std::abort();
}
}
assert(memory_address);
verify_magic();
return memory_address;
}
inline bool bitmap_state_t::deallocate(void *vv) noexcept
{
auto v = reinterpret_cast<uint8_t *>(vv);
if (v < begin() || v > end()) {
return false;
}
size_t byte_diff = static_cast<size_t>(v - begin());
if (mcpputil_unlikely(byte_diff % real_entry_size())) {
return false;
}
mcpputil::secure_zero_stream(v, real_entry_size());
auto i = byte_diff / real_entry_size();
set_free(i, true);
for (size_t j = 0; j < num_user_bit_fields(); ++j) {
user_bits_ref(j).set_bit(i, false);
}
return true;
}
inline void bitmap_state_t::or_with_to_be_freed(bitmap::dynamic_bitmap_ref_t<false> to_be_freed)
{
const size_t alloca_size = block_size_in_bytes() + bitmap::dynamic_bitmap_ref_t<false>::bits_type::cs_alignment;
const auto mark_memory = alloca(alloca_size);
auto mark = bitmap::make_dynamic_bitmap_ref_from_alloca(mark_memory, num_blocks(), alloca_size);
mark.deep_copy(mark_bits_ref());
to_be_freed |= mark.negate();
}
inline void bitmap_state_t::free_unmarked()
{
or_with_to_be_freed(free_bits_ref());
_compute_first_free();
}
inline auto bitmap_state_t::num_blocks() const noexcept -> size_t
{
return m_internal.m_info.m_num_blocks;
}
inline auto bitmap_state_t::num_user_bit_fields() const noexcept -> size_t
{
return m_internal.m_info.m_num_user_bit_fields;
}
inline auto bitmap_state_t::block_size_in_bytes() const noexcept -> size_t
{
return num_blocks() * sizeof(bits_array_type);
}
inline auto bitmap_state_t::free_bits() noexcept -> bits_array_type *
{
return mcpputil::unsafe_cast<bits_array_type>(this + 1);
}
inline auto bitmap_state_t::free_bits() const noexcept -> const bits_array_type *
{
return mcpputil::unsafe_cast<bits_array_type>(this + 1);
}
inline auto bitmap_state_t::mark_bits() noexcept -> bits_array_type *
{
return free_bits() + num_blocks();
}
inline auto bitmap_state_t::mark_bits() const noexcept -> const bits_array_type *
{
return free_bits() + num_blocks();
}
inline auto bitmap_state_t::user_bits(size_t i) noexcept -> bits_array_type *
{
return mark_bits() + num_blocks() * (i + 1);
}
inline auto bitmap_state_t::user_bits(size_t i) const noexcept -> const bits_array_type *
{
return mark_bits() + num_blocks() * (i + 1);
}
inline auto bitmap_state_t::free_bits_ref() noexcept -> bitmap::dynamic_bitmap_ref_t<false>
{
return bitmap::make_dynamic_bitmap_ref(free_bits(), num_blocks());
}
inline auto bitmap_state_t::free_bits_ref() const noexcept -> bitmap::dynamic_bitmap_ref_t<true>
{
return bitmap::make_dynamic_bitmap_ref(free_bits(), num_blocks());
}
inline auto bitmap_state_t::mark_bits_ref() noexcept -> bitmap::dynamic_bitmap_ref_t<false>
{
return bitmap::make_dynamic_bitmap_ref(mark_bits(), num_blocks());
}
inline auto bitmap_state_t::mark_bits_ref() const noexcept -> bitmap::dynamic_bitmap_ref_t<true>
{
return bitmap::make_dynamic_bitmap_ref(mark_bits(), num_blocks());
}
inline auto bitmap_state_t::user_bits_ref(size_t index) noexcept -> bitmap::dynamic_bitmap_ref_t<false>
{
return bitmap::make_dynamic_bitmap_ref(user_bits(index), num_blocks());
}
inline auto bitmap_state_t::user_bits_ref(size_t index) const noexcept -> bitmap::dynamic_bitmap_ref_t<true>
{
return bitmap::make_dynamic_bitmap_ref(user_bits(index), num_blocks());
}
inline auto bitmap_state_t::user_bits_checked(size_t i) noexcept -> bits_array_type *
{
if (mcpputil_unlikely(i >= m_internal.m_info.m_num_user_bit_fields)) {
::std::cerr << "mcppalloc: User bits out of range: 224f26b3-d2e6-47f3-b6de-6a4194750242";
::std::terminate();
}
return user_bits(i);
}
inline auto bitmap_state_t::user_bits_checked(size_t i) const noexcept -> const bits_array_type *
{
if (mcpputil_unlikely(i >= m_internal.m_info.m_num_user_bit_fields)) {
::std::cerr << "mcppalloc: User bits out of range: 24a934d1-160f-4bfc-b765-e0e21ee69605";
::std::terminate();
}
return user_bits(i);
}
inline auto bitmap_state_t::get_index(void *v) const noexcept -> size_t
{
auto diff = reinterpret_cast<const uint8_t *>(v) - begin();
if (mcpputil_unlikely(diff < 0)) {
assert(false);
return ::std::numeric_limits<size_t>::max();
}
const auto index = static_cast<size_t>(diff) / real_entry_size();
if (mcpputil_unlikely(index >= size())) {
return ::std::numeric_limits<size_t>::max();
}
return index;
}
inline auto bitmap_state_t::get_object(size_t i) noexcept -> void *
{
if (mcpputil_unlikely(i >= size())) {
::std::cerr << "mcppalloc: bitmap_state get object failed";
::std::terminate();
}
return reinterpret_cast<void *>(begin() + i * real_entry_size());
}
inline auto bitmap_state_t::has_valid_magic_numbers() const noexcept -> bool
{
return m_internal.m_pre_magic_number == cs_magic_number_pre && m_internal.m_post_magic_number == cs_magic_number_0;
}
inline void bitmap_state_t::verify_magic() const
{
#ifdef _DEBUG
if (mcpputil_unlikely(!has_valid_magic_numbers())) {
::std::cerr << "mcppalloc: bitmap_state: invalid magic numbers 027e8d50-8555-4e7f-93a7-4d048b506436\n";
::std::abort();
}
#endif
}
inline auto bitmap_state_t::addr_in_header(void *v) const noexcept -> bool
{
return begin() > v;
}
}
| 34.658333
| 126
| 0.703054
|
garyfurnish
|
b3dcce1a208ebefcab89e7970a04993c5780a1f9
| 466
|
cpp
|
C++
|
examples/appearance/figure/figure_2.cpp
|
gitplcc/matplotplusplus
|
c088749434154c230ee7547c6871d65e58876dc6
|
[
"MIT"
] | 2,709
|
2020-08-29T01:25:40.000Z
|
2022-03-31T18:35:25.000Z
|
examples/appearance/figure/figure_2.cpp
|
p-ranav/matplotplusplus
|
b45015e2be88e3340b400f82637b603d733d45ce
|
[
"MIT"
] | 124
|
2020-08-29T04:48:17.000Z
|
2022-03-25T15:45:59.000Z
|
examples/appearance/figure/figure_2.cpp
|
p-ranav/matplotplusplus
|
b45015e2be88e3340b400f82637b603d733d45ce
|
[
"MIT"
] | 203
|
2020-08-29T04:16:22.000Z
|
2022-03-30T02:08:36.000Z
|
#include <matplot/matplot.h>
int main() {
using namespace matplot;
auto h = figure(true);
h->name("Measured Data");
h->number_title(false);
h->color("green");
h->position({0, 0, 600, 600});
h->size(500, 500);
h->draw();
h->font("Arial");
h->font_size(40);
h->title("My experiment");
constexpr float pi_f = 3.14f;
axis({-pi_f, pi_f, -1.5f, +1.5f});
fplot("cos(x)");
h->draw();
show();
return 0;
}
| 20.26087
| 38
| 0.534335
|
gitplcc
|
b3dd57ad425ec876ef7d19ec92a978a2c029c1d1
| 17,494
|
cpp
|
C++
|
HTWK_ChangeSpeed/ChangeSpeed.cpp
|
HTWKSmartDriving/aadc-2017
|
aff82d8b7d936cdfade6e8ad3edd548c71be8311
|
[
"BSD-3-Clause"
] | 10
|
2017-11-17T16:39:03.000Z
|
2020-10-10T08:33:43.000Z
|
HTWK_ChangeSpeed/ChangeSpeed.cpp
|
HTWKSmartDriving/aadc-2017
|
aff82d8b7d936cdfade6e8ad3edd548c71be8311
|
[
"BSD-3-Clause"
] | null | null | null |
HTWK_ChangeSpeed/ChangeSpeed.cpp
|
HTWKSmartDriving/aadc-2017
|
aff82d8b7d936cdfade6e8ad3edd548c71be8311
|
[
"BSD-3-Clause"
] | 5
|
2017-11-18T09:35:24.000Z
|
2021-01-20T07:03:46.000Z
|
#include "ChangeSpeed.h"
ADTF_FILTER_PLUGIN(FILTER_NAME, OID, ChangeSpeed);
ChangeSpeed::ChangeSpeed(const tChar *__info) : Leaf(__info) {
// speed properties
SetPropertyFloat(ROAD_SPEED_PROPERTY, SPEED_ROAD);
SetPropertyStr(ROAD_SPEED_PROPERTY NSSUBPROP_DESCRIPTION, "Speed to drive on road");
SetPropertyFloat(INTERSECTION_SPEED_PROPERTY, SPEED_INTERSECTION);
SetPropertyStr(INTERSECTION_SPEED_PROPERTY NSSUBPROP_DESCRIPTION, "Speed to drive on intersections");
SetPropertyFloat(NEARING_GIVE_WAY_SPEED_PROPERTY, SPEED_NEARING_GIVE_WAY);
SetPropertyStr(NEARING_GIVE_WAY_SPEED_PROPERTY NSSUBPROP_DESCRIPTION,
"Speed to drive when nearing give way intersection");
SetPropertyFloat(NEARING_HAVE_WAY_SPEED_PROPERTY, SPEED_NEARING_HAVE_WAY);
SetPropertyStr(NEARING_HAVE_WAY_SPEED_PROPERTY NSSUBPROP_DESCRIPTION,
"Speed to drive when nearing have way intersection");
SetPropertyFloat(NEARING_FULL_STOP_SPEED_PROPERTY, SPEED_NEARING_FULL_STOP);
SetPropertyStr(NEARING_FULL_STOP_SPEED_PROPERTY NSSUBPROP_DESCRIPTION,
"Speed to drive when nearing full stop intersection");
SetPropertyFloat(NEARING_GENERIC_SPEED_PROPERTY, SPEED_NEARING_GENERIC);
SetPropertyStr(NEARING_GENERIC_SPEED_PROPERTY NSSUBPROP_DESCRIPTION,
"Speed to drive when nearing generic intersection");
//other properties
SetPropertyFloat(DETECT_DIST_PROPERTY, DETECT_DIST_DEFAULT);
SetPropertyStr(DETECT_DIST_PROPERTY NSSUBPROP_DESCRIPTION, DETECT_DIST_DESCRIPTION);
SetPropertyFloat(SLOW_SPEED_PROPERTY, SLOW_SPEED_DEFAULT);
SetPropertyStr(SLOW_SPEED_PROPERTY NSSUBPROP_DESCRIPTION, SLOW_SPEED_DESCRIPTION);
SetPropertyFloat(STOP_AT_PERSON_PROPERTY, STOP_AT_PERSON_DEFAULT);
SetPropertyStr(STOP_AT_PERSON_PROPERTY NSSUBPROP_DESCRIPTION, STOP_AT_PERSON_DESCRIPTION);
SetPropertyFloat(LANE_WIDTH_PROPERTY, LANE_WIDTH_DEFAULT);
SetPropertyFloat(ROAD_OBTACLE_DIST_PROPERTY, ROAD_OBTACLE_DIST_DEFAULT);
SetPropertyFloat(INTERSECTION_OBTACLE_DIST_PROPERTY, INTERSECTION_OBTACLE_DIST_DEFAULT);
SetPropertyFloat(PEDESTRIAN_OBTACLE_DIST_PROPERTY, PEDESTRIAN_OBTACLE_DIST_DEFAULT);
}
ChangeSpeed::~ChangeSpeed()
= default;
tResult ChangeSpeed::Init(tInitStage eStage, __exception) {
RETURN_IF_FAILED(Leaf::Init(eStage, __exception_ptr));
if (eStage == StageNormal) {
detectDist = static_cast<tFloat32>(GetPropertyFloat(DETECT_DIST_PROPERTY, DETECT_DIST_DEFAULT));
slowSpeed = static_cast<tFloat32>(GetPropertyFloat(SLOW_SPEED_PROPERTY, SLOW_SPEED_DEFAULT));
speedOnRoad = static_cast<tFloat32>(GetPropertyFloat(ROAD_SPEED_PROPERTY));
speedNearingHaveWay = static_cast<tFloat32>(GetPropertyFloat(NEARING_HAVE_WAY_SPEED_PROPERTY));
speedNearingGiveWay = static_cast<tFloat32>(GetPropertyFloat(NEARING_GIVE_WAY_SPEED_PROPERTY));
speedNearingFullStop = static_cast<tFloat32>(GetPropertyFloat(NEARING_FULL_STOP_SPEED_PROPERTY));
speedNearingGeneric = static_cast<tFloat32>(GetPropertyFloat(NEARING_GENERIC_SPEED_PROPERTY));
speedIntersection = static_cast<tFloat32>(GetPropertyFloat(INTERSECTION_SPEED_PROPERTY));
stopPersonTime = static_cast<int>(GetPropertyFloat(STOP_AT_PERSON_PROPERTY, STOP_AT_PERSON_DEFAULT) * 1000000);
laneWidth = GetPropertyFloat(LANE_WIDTH_PROPERTY, LANE_WIDTH_DEFAULT);
distRoad = GetPropertyFloat(ROAD_OBTACLE_DIST_PROPERTY, ROAD_OBTACLE_DIST_DEFAULT);
distPedestrian = GetPropertyFloat(PEDESTRIAN_OBTACLE_DIST_PROPERTY, PEDESTRIAN_OBTACLE_DIST_DEFAULT);
distIntersection = GetPropertyFloat(INTERSECTION_OBTACLE_DIST_PROPERTY, INTERSECTION_OBTACLE_DIST_DEFAULT);
pedestrianTime = 5000000;
}
RETURN_NOERROR;
}
tResult ChangeSpeed::OnTrigger() {
std::vector<tTrackingData> allObstacles;
IntersectionState intersectionState;
if (!IS_OK(worldService->Pull(WORLD_CURRENT_POSITION, currentPos))) {
// LOG_ERROR("Current Position could not be pulled!");
TransmitStatus(BT::FAIL);
RETURN_ERROR(ERR_FAILED);
}
if (!IS_OK(worldService->Pull(WORLD_OBSTACLES, allObstacles))) {
noObstacles = true;
} else {
noObstacles = false;
}
if (!IS_OK(worldService->Pull(WORLD_CURRENT_HEADING, heading))) {
// LOG_ERROR("Heading could not be pulled!");
TransmitStatus(BT::FAIL);
RETURN_ERROR(ERR_FAILED);
}
// if (!IS_OK(worldService->Pull(WORLD_ZEBRA_STATE, zebraState))) {
// LOG_ERROR("Zebra State could not be pulled!");
// RETURN_ERROR(ERR_FAILED);
// }
if (!IS_OK(worldService->Pull(WORLD_INTERSECTION_STATE, intersectionState))) {
// LOG_ERROR("intersection state could not be pulled!");
TransmitStatus(BT::FAIL);
RETURN_ERROR(ERR_FAILED);
}
if (!IS_OK(worldService->Pull(WORLD_CURRENT_SPEED, currentSpeed))) {
#ifdef DEBUG_MAP_VIEW_LOG
LOG_ERROR("Current speed could not be pulled from WorldService");
#endif
TransmitStatus(BT::FAIL);
RETURN_ERROR(ERR_FAILED);
}
if (!IS_OK(worldService->Pull(CAR_STATE, state))) {
#ifdef DEBUG_MAP_VIEW_LOG
LOG_ERROR("State could not be pulled from WorldService");
#endif
TransmitStatus(BT::FAIL);
RETURN_ERROR(ERR_FAILED);
}
if (!IS_OK(worldService->Pull(WORLD_NEXT_TURN, nextTurn))) {
// LOG_ERROR("nextTurn could not be pulled!");
TransmitStatus(BT::FAIL);
RETURN_ERROR(ERR_FAILED);
}
if (!IS_OK(worldService->Pull(WORLD_ROAD_SIGN_EXT, nextSign))) {
// LOG_ERROR("road sign could not be pulled!");
TransmitStatus(BT::FAIL);
RETURN_ERROR(ERR_FAILED);
}
// heading = HTWKMathUtils::rad2deg(heading);
// if (!IS_OK(worldService->Pull(WORLD_LANE_LEFT, leftLaneDist))) {
leftLaneDist = laneWidth * 1.5;
// }
// if (!IS_OK(worldService->Pull(WORLD_LANE_RIGHT, rightLaneDist))) {
rightLaneDist = laneWidth / 2;
// }
return findSpeedNew(allObstacles, intersectionState);
}
// 90
// |
//180 -- -- 0
// |
// -90
//HTWKLane
//ChangeSpeed::ExtractLanesFromPositionAndHeading(HTWKPoint carPos, tFloat carHeading) {
// HTWKLane lane;
// // berechne Punkt der auf der Fahrspur liegt
// // linke Spur: berechne Vektor der 90 Grad nach links von aktueller Position aus zeigt, mit Länge der Distanz zur Spur
// // rechte Spur: Vektor zeigt 90 Grad nach rechts
// tFloat rotatedHeading = carHeading + 90;
// //rechne von Polarkoordinaten in kartesische um
// HTWKPoint vector2Lane = PolarToCartesian(rightLaneDist, rotatedHeading);
// // addiere berechneten Vektor auf die eigene Position = Spurpunkt 1
// lane.rightStart = carPos.add(vector2Lane);
// // berechne 2. Spurpunkt, durch Addition eines Vektors mit beliebiger Länge und Winkel in Richtung des Heading des Autos
// // rechne in kartesische Koordinaten um
// HTWKPoint lanePoint2 = lane.rightStart.add(PolarToCartesian(1.0, carHeading));
// // lege Gerade durch beide Punkte -> ~Spur
// lane.right = HTWKPoint(lanePoint2.x() - lane.rightStart.x(), lanePoint2.y() - lane.rightStart.y());
//
// // das gleiche für die mittlere Spur
// // Vektor auf die Spur zeigt 90 Grad nach links
// rotatedHeading = carHeading - 90;
// //dist zur Mitte = dist nach rechts
// vector2Lane = PolarToCartesian(rightLaneDist, rotatedHeading);
// lane.middleStart = carPos.add(vector2Lane);
// lanePoint2 = lane.middleStart.add(PolarToCartesian(1.0, carHeading));
// lane.middle = HTWKPoint(lanePoint2.x() - lane.middleStart.x(), lanePoint2.y() - lane.middleStart.y());
//
// vector2Lane = PolarToCartesian(leftLaneDist, rotatedHeading);
// lane.leftStart = carPos.add(vector2Lane);
// lanePoint2 = lane.leftStart.add(PolarToCartesian(1.0, carHeading));
// lane.left = HTWKPoint(lanePoint2.x() - lane.leftStart.x(), lanePoint2.y() - lane.leftStart.y());
// return lane;
//}
// x = r * cos (alpha)
// y = r * sin (alpha)
//HTWKPoint ChangeSpeed::PolarToCartesian(tFloat length, tFloat angle) {
// double x = length * std::cos(angle);
// double y = length * std::sin(angle);
// return HTWKPoint(x, y);
//}
ObstaclePos ChangeSpeed::IsPositionOnRoad(cv::Point2f obstaclePosition) {
cv::Point2f carPosition;
carPosition.x = static_cast<float>(-currentPos.x());
carPosition.y = static_cast<float>(-currentPos.y());
cv::Point2f newObstPos = htwk::translateAndRotate2DPoint(obstaclePosition,
static_cast<float>(-(heading)),
carPosition);
// std::string log = "x: " + to_string(newObstPos.x) + " y: " + to_string(newObstPos.y);
// LOG_INFO(log.c_str());
if (newObstPos.x >= 0) {
//rechte Seite
if (newObstPos.x <= rightLaneDist) {
return ObstaclePos::LANE;
} else {
return ObstaclePos::OFFROAD_R;
}
} else {
if (-newObstPos.x <= rightLaneDist) {
return ObstaclePos::LANE;
} else if (-newObstPos.x <= leftLaneDist) {
return ObstaclePos::OTHER_LANE;
} else {
return ObstaclePos::OFFROAD_L;
}
}
}
tResult ChangeSpeed::FullBrake() {
// LOG_INFO("do full brake");
//stopPersonTimer = _clock->GetStreamTime() + stopPersonTime;
SetSpeedOutput(0);
return TransmitStatus(BT::SUCCESS);
}
tResult ChangeSpeed::findUsualSpeed(const IntersectionState &interState) {
tFloat32 speed = 0;
if (state == stateCar::stateCar_RUNNING) {
switch (interState) {
case IntersectionState::ON_ROAD:
#ifdef DEBUG_MAP_VIEW_LOG
LOG_INFO("IntersectionState: ON_ROAD");
#endif
speed = speedOnRoad;
fullStopDone = false;
stopTimer = 0;
break;
case IntersectionState::NEARING_HAVE_WAY:
#ifdef DEBUG_MAP_VIEW_LOG
LOG_INFO("IntersectionState: NEARING_HAVE_WAY");
#endif
speed = speedNearingHaveWay;
fullStopDone = false;
stopTimer = 0;
break;
case IntersectionState::NEARING_GIVE_WAY:
#ifdef DEBUG_MAP_VIEW_LOG
LOG_INFO("IntersectionState: NEARING_GIVE_WAY");
#endif
speed = speedNearingGiveWay;
fullStopDone = false;
stopTimer = 0;
break;
case IntersectionState::NEARING_FULL_STOP:
#ifdef DEBUG_MAP_VIEW_LOG
LOG_INFO("IntersectionState: NEARING_FULL_STOP");
#endif
speed = speedNearingFullStop;
fullStopDone = false;
stopTimer = 0;
break;
case IntersectionState::ON_INTERSECTION:
#ifdef DEBUG_MAP_VIEW_LOG
LOG_INFO("IntersectionState: ON_INTERSECTION");
#endif
speed = speedIntersection;
break;
case IntersectionState::STOP_NOW:
#ifdef DEBUG_MAP_VIEW_LOG
LOG_INFO("IntersectionState: STOP_NOW");
#endif
if (!fullStopDone) {
if (currentSpeed > 0.1) {
speed = 0;
} else {
if (stopTimer == 0) {
stopTimer = _clock->GetStreamTime() + STOP_AT_STOP_SIGN;
} else if (_clock->GetStreamTime() > stopTimer) {
fullStopDone = tTrue;
}
}
} else {
speed = speedIntersection;
}
break;
case IntersectionState::NEARING_GENERIC:
#ifdef DEBUG_MAP_VIEW_LOG
LOG_INFO("IntersectionState: NEARING_GENERIC");
#endif
speed = speedNearingGeneric;
fullStopDone = false;
stopTimer = 0;
break;
}
} else {
speed = 0;
}
SetSpeedOutput(speed);
RETURN_NOERROR;
}
tResult ChangeSpeed::findSpeedNew(const vector<tTrackingData> &obstacles, const IntersectionState &interState) {
//pedestrian
if (pedestrianTimer != 0) {
SetSpeedOutput(0);
if (pedestrianTimer + pedestrianTime > _clock->GetStreamTime()) {
pedestrianTimer = 0;
}
return TransmitStatus(BT::SUCCESS);
}
HTWKPoint pedestrianPos1 = HTWKPoint(3.5, 0.5);
HTWKPoint pedestrianPos2 = HTWKPoint(3.5, 10.5);
if (HTWKUtils::Equals(pedestrianPos1, currentPos, distPedestrian) || HTWKUtils::Equals(pedestrianPos2, currentPos, distPedestrian)) {
SetSpeedOutput(0);
pedestrianTimer = _clock->GetStreamTime();
return TransmitStatus(BT::SUCCESS);
}
if (interState == IntersectionState::STOP_NOW) {
if (!IS_OK(findObstacleSpeedOnIntersection(obstacles))) {
findUsualSpeed(interState);
return TransmitStatus(BT::SUCCESS);
} else {
RETURN_NOERROR;
}
}
if (!IS_OK(findObstacleSpeedOnRoad(obstacles))) {
findUsualSpeed(interState);
return TransmitStatus(BT::SUCCESS);
} else {
RETURN_NOERROR;
}
}
tResult ChangeSpeed::findObstacleSpeedOnRoad(const vector<tTrackingData> &obstacles) {
if (stopPersonTimer != 0) {
SetSpeedOutput(slowSpeed);
if (stopPersonTimer + stopPersonTime < _clock->GetStreamTime()) {
stopPersonTimer = 0;
}
RETURN_ERROR(ERR_FAILED);
}
if (noObstacles) {
RETURN_ERROR(ERR_FAILED);
}
for (const tTrackingData &obstacle : obstacles) {
HTWKPoint distPoint;
distPoint.setXval(obstacle.position.x);
distPoint.setYval(obstacle.position.y);
if (obstacle.type == ObstacleType::CHILD &&
distPoint.dist(currentPos) <= distRoad) {
stopPersonTimer = _clock->GetStreamTime();
SetSpeedOutput(slowSpeed);
return TransmitStatus(BT::SUCCESS);
}
}
RETURN_ERROR(ERR_FAILED);
}
tResult
ChangeSpeed::findObstacleSpeedOnIntersection(const vector<tTrackingData> &obstacles) {
if (noObstacles) {
RETURN_ERROR(ERR_FAILED);
}
for (tTrackingData obstacle : obstacles) {
ObstaclePos obstRoad = IsPositionOnRoad(obstacle.position);
HTWKPoint distPoint;
distPoint.setXval(obstacle.position.x);
distPoint.setYval(obstacle.position.y);
if (obstacle.type == ObstacleType::CAR
&& distPoint.dist(currentPos) < distIntersection) {
switch (nextTurn) {
case Orientation::TurnDirection::STRAIGHT:
if (obstRoad == ObstaclePos::OFFROAD_R) {
return FullBrake();
} else if (obstRoad == ObstaclePos::OFFROAD_L) {
return FullBrake();
} else {
RETURN_ERROR(ERR_FAILED);
}
case Orientation::TurnDirection::LEFT: {
return FullBrake();
}
case Orientation::TurnDirection::RIGHT:
if (obstRoad == ObstaclePos::OFFROAD_L) {
return FullBrake();
} else {
RETURN_ERROR(ERR_FAILED);
}
}
}
}
RETURN_ERROR(ERR_FAILED);
}
//tResult ChangeSpeed::findObstacleSpeedOnPedestrian(const vector<tTrackingData> &obstacles) {
// if (noObstacles) {
// RETURN_ERROR(ERR_FAILED);
// }
//
// ObstaclePos obstRoad;
// HTWKPoint distPoint;
// bool slowDown = false;
//
// for (tTrackingData obstacle : obstacles) {
// obstRoad = IsPositionOnRoad(obstacle.position);
// distPoint.setXval(obstacle.position.x);
// distPoint.setYval(obstacle.position.y);
// if(distPoint.dist(currentPos) > distPedestrian){
// RETURN_ERROR(ERR_FAILED);
// }
//
// if (obstacle.type == ObstacleType::ADULT || obstacle.type == ObstacleType::CHILD) {
//
// if (firstObstacleSight) {
// firstObstacleSight = false;
// firstObstaclePos = obstRoad;
// if (currentPos.dist(distPoint) <= pedestrianDetectDist) {
// slowDown = true;
// } else {
// RETURN_ERROR(ERR_FAILED);
// }
// } else {
// if (obstRoad == ObstaclePos::LANE || obstRoad == ObstaclePos::OTHER_LANE) {
// return FullBrake();
// } else if (obstRoad == firstObstaclePos) {
// return FullBrake();
// } else {
// firstObstacleSight = true;
// RETURN_ERROR(ERR_FAILED);
// }
// }
// }
// }
// if (slowDown) {
// SetSpeedOutput(slowSpeed);
// return TransmitStatus(BT::SUCCESS);
// } else {
// RETURN_ERROR(ERR_FAILED);
// }
//}
//tFloat ChangeSpeed::VectorAngle(HTWKPoint vec1, HTWKPoint vec2) {
// tFloat prod = vec1.x() * vec2.x() + vec1.y() * vec2.y();
// tFloat length1 = std::sqrt(vec1.x() * vec1.x() + vec1.y() * vec1.y());
// tFloat length2 = std::sqrt(vec2.x() * vec2.x() + vec2.y() * vec2.y());
// return prod / (length1 * length2);
//}
| 37.460385
| 137
| 0.634732
|
HTWKSmartDriving
|
b3df21842b1f9462c97161cf890ce8cf1a5004a1
| 2,402
|
cpp
|
C++
|
simulation/algorithms/Type2/C++/Qt/Type2/MainWindow.cpp
|
motchy869/Distributed-ThompthonSampling
|
17bb11f789ccc410e12c99347decc09c836dd708
|
[
"MIT"
] | null | null | null |
simulation/algorithms/Type2/C++/Qt/Type2/MainWindow.cpp
|
motchy869/Distributed-ThompthonSampling
|
17bb11f789ccc410e12c99347decc09c836dd708
|
[
"MIT"
] | null | null | null |
simulation/algorithms/Type2/C++/Qt/Type2/MainWindow.cpp
|
motchy869/Distributed-ThompthonSampling
|
17bb11f789ccc410e12c99347decc09c836dd708
|
[
"MIT"
] | null | null | null |
#include "common.h"
#include "Simulator.h"
#include "MainWindow.h"
#include <QApplication>
#include <QDebug>
#include <QLabel>
#include <QMetaObject>
#include <QProgressBar>
#include <QThread>
#include <QVBoxLayout>
//QThreadによるマルチスレッド処理に関しては次が参考になる: https://qiita.com/hermit4/items/b1eaf6132fb06a30091f
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
//UI
setWindowTitle(tr("Type1 simulation"));
QVBoxLayout *vBoxLayout = new QVBoxLayout();
vBoxLayout->addWidget(m_label_basic_info = new QLabel(tr("basic info")));
m_label_basic_info->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding);
m_label_basic_info->setWordWrap(true);
vBoxLayout->addStretch();
vBoxLayout->addWidget(new QLabel(tr("current play progress")));
vBoxLayout->addWidget(m_pb_current_play = new QProgressBar());
vBoxLayout->addWidget(new QLabel(tr("whole progress")));
vBoxLayout->addWidget(m_pb_sim = new QProgressBar());
QWidget *centralWidget = new QWidget();
centralWidget->setLayout(vBoxLayout);
setCentralWidget(centralWidget);
setMinimumWidth(640);
//スレッド準備
m_simThread = new QThread(this);
m_simulator = new Simulator(nullptr); //moveToThread するために親を null にする必要がある!
m_simulator->moveToThread(m_simThread); //所属するイベントループを変更
connect(m_simThread, SIGNAL(started()), m_simulator, SLOT(run()));
connect(m_simThread, SIGNAL(finished()), m_simulator, SLOT(deleteLater())); //親がいないQObjectの派生クラスは自動的にdeleteされないため、お膳立てしてやる。
connect(m_simulator, SIGNAL(update_basic_info_label(QString)), this, SLOT(update_basic_info_label(QString)));
connect(m_simulator, SIGNAL(report_progress(int,int)), this, SLOT(update_progress_bar(int,int)));
//終了の流れ
connect(m_simulator, SIGNAL(sim_done()), m_simThread, SLOT(quit()));
connect(m_simThread, SIGNAL(finished()), qApp, SLOT(quit()));
m_simThread->start();
}
void MainWindow::update_basic_info_label(QString s)
{
m_label_basic_info->setText(s);
}
void MainWindow::update_progress_bar(int prog_current, int prog_whole)
{
Q_ASSERT(prog_current>=0 && prog_current<=100 && prog_whole>=0 && prog_whole<=100);
m_pb_current_play->setValue(prog_current);
m_pb_sim->setValue(prog_whole);
}
void MainWindow::closeEvent(QCloseEvent*) { //ウィンドウを閉じた時にシミュレーションスレッドを終わらせる
m_simThread->quit();
m_simThread->deleteLater();
}
MainWindow::~MainWindow()
{
m_simThread->exit();
m_simThread->wait();
qDebug() << "~MainWindow()";
}
| 34.314286
| 124
| 0.764779
|
motchy869
|
b3e2fc0a940576d593698a434dc6ea4c8eb7d035
| 4,620
|
cpp
|
C++
|
examples/example_0520.cpp
|
dyomas/pyhrol
|
6865b7de3377f9d6d3f1b282a39d5980497b703d
|
[
"BSD-3-Clause"
] | null | null | null |
examples/example_0520.cpp
|
dyomas/pyhrol
|
6865b7de3377f9d6d3f1b282a39d5980497b703d
|
[
"BSD-3-Clause"
] | null | null | null |
examples/example_0520.cpp
|
dyomas/pyhrol
|
6865b7de3377f9d6d3f1b282a39d5980497b703d
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2013, 2014, Pyhrol, pyhrol@rambler.ru
* GEO: N55.703431,E37.623324 .. N48.742359,E44.536997
*
* 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.
* 4. Neither the name of the Pyhrol 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 REGENTS 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 REGENTS 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 <pyhrol.h>
#include <pyhrol_auto_holder.h>
struct iterator
{
std::string::const_iterator iter;
const std::string::const_iterator iter_end;
iterator(const pyhrol::Ptr<const std::string> &container)
: iter(container->begin())
, iter_end(container->end())
, m_container(container)
{
Py_IncRef(m_container);
}
~iterator()
{
Py_DecRef(m_container);
}
private:
PyObject *m_container;
};
struct item: pyhrol::AutoHolder
{
const char data;
item(const pyhrol::Ptr< ::iterator> &iter)
: pyhrol::AutoHolder(iter)
, data(*iter->iter ++)
{
}
};
class Container: public pyhrol::TypeWrapper<std::string>, public pyhrol::TypeIterable<std::string, ::iterator>
{
Container()
: pyhrol::TypeBase<std::string>("MyClass", NULL)
{
m_type_object.tp_iternext = NULL;
}
virtual void constructor(std::string &res, pyhrol::Tuples &_args) const
{
const char *data;
PYHROL_PARSE_TUPLE_1(NULL, _args, data)
PYHROL_AFTER_PARSE_TUPLE(_args)
PYHROL_AFTER_BUILD_VALUE(_args)
new(&res) std::string(data);
PYHROL_AFTER_EXECUTE_DEFAULT(_args)
}
virtual void destructor(std::string &obj) const
{
using std::string;
obj.~string();
}
virtual void print(std::ostream &os, const std::string &obj) const
{
os << obj;
}
virtual void iter(const pyhrol::Ptr< ::iterator> &iter, const pyhrol::Ptr<const std::string> &container) const
{
new(&*iter) ::iterator(container);
}
static void init() __attribute__ ((constructor))
{
m_get(new Container);
}
};
class Iterator: public pyhrol::TypeWrapper< ::iterator>, public pyhrol::TypeIterable< ::iterator, item>
{
Iterator()
: pyhrol::TypeBase< ::iterator>("iter", NULL)
{
m_type_object.tp_iter = NULL;
}
virtual void constructor(::iterator &res, pyhrol::Tuples &_args) const
{
const char *data;
PYHROL_PARSE_TUPLE_1(NULL, _args, data)
PYHROL_AFTER_PARSE_TUPLE(_args)
PYHROL_AFTER_BUILD_VALUE(_args)
::Container::T_struct *obj = ::Container::allocate_static();
new(&obj->endosome) std::string(data);
new(&res) ::iterator(pyhrol::Ptr<const std::string>(&obj->endosome, *obj));
PYHROL_AFTER_EXECUTE_DEFAULT(_args)
}
virtual void destructor(::iterator &obj) const
{
obj.~iterator();
}
virtual bool next(const pyhrol::Ptr<item> &itm, const pyhrol::Ptr< ::iterator> &iter) const
{
bool retval = false;
if (iter->iter != iter->iter_end)
{
new (&*itm) item(iter);
retval = true;
}
return retval;
}
static void init() __attribute__ ((constructor))
{
m_get(new Iterator);
}
};
class Data: public pyhrol::TypeWrapper<item>
{
Data()
: pyhrol::TypeBase< ::item>("item", NULL)
{
m_add_member<const char, &item::data>("data", NULL);
}
virtual void destructor(item &itm) const
{
itm.~item();
}
static void init() __attribute__ ((constructor))
{
m_get(new Data);
}
};
| 27.017544
| 112
| 0.683117
|
dyomas
|
b3e5f4e875d2cd30505a5b6e7b464f4a323dfa52
| 8,682
|
cpp
|
C++
|
Axis.Echinopsis/application/factories/collectors/TextReportElementCollectorParser.cpp
|
renato-yuzup/axis-fem
|
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
|
[
"MIT"
] | 2
|
2021-07-23T08:49:54.000Z
|
2021-07-29T22:07:30.000Z
|
Axis.Echinopsis/application/factories/collectors/TextReportElementCollectorParser.cpp
|
renato-yuzup/axis-fem
|
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
|
[
"MIT"
] | null | null | null |
Axis.Echinopsis/application/factories/collectors/TextReportElementCollectorParser.cpp
|
renato-yuzup/axis-fem
|
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
|
[
"MIT"
] | null | null | null |
#include "TextReportElementCollectorParser.hpp"
#include "foundation/OutOfBoundsException.hpp"
#include "services/language/factories/AxisGrammar.hpp"
#include "services/language/parsing/ExpressionNode.hpp"
#include "services/language/parsing/SymbolTerminal.hpp"
#include "services/language/parsing/OperatorTerminal.hpp"
#include "services/language/parsing/ReservedWordTerminal.hpp"
#include "services/language/parsing/EnumerationExpression.hpp"
#include "services/language/parsing/NumberTerminal.hpp"
namespace aaocs = axis::application::output::collectors::summarizers;
namespace aafc = axis::application::factories::collectors;
namespace aslp = axis::services::language::parsing;
namespace aslf = axis::services::language::factories;
namespace aslpm = axis::services::language::primitives;
namespace asli = axis::services::language::iterators;
namespace {
static const int SetExpressionIdentifier = -5;
static const int ScaleExpressionIdentifier = -10;
static const int NodeExpressionIdentifier = -15;
}
aafc::TextReportElementCollectorParser::ElementCollectorParseResult::ElementCollectorParseResult(
const aslp::ParseResult& result ) :
parseResult_(result), collectorType_(kUndefined)
{
bool d[6] = {true, true, true, true, true, true};
Init(d);
}
aafc::TextReportElementCollectorParser::ElementCollectorParseResult::ElementCollectorParseResult(
const aslp::ParseResult& result,
ElementCollectorParseResult::CollectorType collectorType,
const bool *directionState,
const axis::String& targetSetName ) :
parseResult_(result), collectorType_(collectorType), targetSetName_(targetSetName)
{
Init(directionState);
}
aafc::TextReportElementCollectorParser::ElementCollectorParseResult::ElementCollectorParseResult(
const ElementCollectorParseResult& other )
{
operator =(other);
}
aafc::TextReportElementCollectorParser::ElementCollectorParseResult&
aafc::TextReportElementCollectorParser::ElementCollectorParseResult::operator=(
const ElementCollectorParseResult& other )
{
parseResult_ = other.parseResult_;
collectorType_ = other.collectorType_;
targetSetName_ = other.targetSetName_;
Init(other.directionState_);
return *this;
}
void aafc::TextReportElementCollectorParser::ElementCollectorParseResult::Init(
const bool * directionState )
{
switch (collectorType_)
{
case kStress:
case kStrain:
directionCount_ = 6;
break;
default:
directionCount_ = 3;
break;
}
for (int i = 0; i < directionCount_; ++i)
{
directionState_[i] = directionState[i];
}
}
aafc::TextReportElementCollectorParser::ElementCollectorParseResult::~ElementCollectorParseResult( void )
{
// nothing to do here
}
aslp::ParseResult aafc::TextReportElementCollectorParser::ElementCollectorParseResult::GetParseResult( void ) const
{
return parseResult_;
}
aafc::TextReportElementCollectorParser::ElementCollectorParseResult::CollectorType
aafc::TextReportElementCollectorParser::ElementCollectorParseResult::GetCollectorType( void ) const
{
return collectorType_;
}
axis::String aafc::TextReportElementCollectorParser::ElementCollectorParseResult::GetTargetSetName( void ) const
{
return targetSetName_;
}
bool aafc::TextReportElementCollectorParser::ElementCollectorParseResult::ShouldCollectDirection( int directionIndex ) const
{
switch (collectorType_)
{
case kStress:
case kStrain:
if (directionIndex < 0 || directionIndex >= 6)
{
throw axis::foundation::OutOfBoundsException();
}
break;
default:
if (directionIndex < 0 || directionIndex >= 3)
{
throw axis::foundation::OutOfBoundsException();
}
break;
}
return directionState_[directionIndex];
}
aafc::TextReportElementCollectorParser::TextReportElementCollectorParser( void )
{
InitGrammar();
}
aafc::TextReportElementCollectorParser::~TextReportElementCollectorParser( void )
{
delete direction3DEnum_;
delete direction6DEnum_;
}
aafc::TextReportElementCollectorParser::ElementCollectorParseResult
aafc::TextReportElementCollectorParser::Parse( const asli::InputIterator& begin,
const asli::InputIterator& end )
{
aslp::ParseResult result = collectorStatement_(begin, end);
if (result.IsMatch())
{
ElementCollectorParseResult ncpr = InterpretParseTree(result);
if (ncpr.GetTargetSetName().empty())
{ // prohibited situation
result.SetResult(aslp::ParseResult::FailedMatch);
}
return ncpr;
}
return ElementCollectorParseResult(result);
}
aafc::TextReportElementCollectorParser::ElementCollectorParseResult
aafc::TextReportElementCollectorParser::InterpretParseTree( const aslp::ParseResult& result ) const
{
// default values
ElementCollectorParseResult::CollectorType collectorType = ElementCollectorParseResult::kUndefined;
bool directionState[6] = {false, false, false, false, false, false};
axis::String targetSetName;
// go to starting node
const aslp::ParseTreeNode& rootNode = result.GetParseTree();
const aslp::ParseTreeNode * node = static_cast<const aslp::ExpressionNode&>(rootNode).GetFirstChild();
// get which collector type was specified
node = node->GetNextSibling()->GetNextSibling();
const aslp::ParseTreeNode *typeExprNode = static_cast<const aslp::ExpressionNode&>(*node).GetFirstChild();
const aslp::ReservedWordTerminal *typeNode = static_cast<const aslp::ReservedWordTerminal *>(typeExprNode);
collectorType = (ElementCollectorParseResult::CollectorType)typeNode->GetValue();
// check whether directions was specified
typeExprNode = typeExprNode->GetNextSibling();
if (typeExprNode != NULL)
{ // yes, it was
if (static_cast<const aslp::ExpressionNode *>(typeExprNode)->IsEnumeration())
{ // a set of various directions (or maybe a single one besides 'ALL') was specified
const aslp::EnumerationExpression *directionEnumExpr =
static_cast<const aslp::EnumerationExpression *>(typeExprNode);
const aslp::ReservedWordTerminal *directionNode = static_cast<const aslp::ReservedWordTerminal *>(
directionEnumExpr->GetFirstChild());
while (directionNode != NULL)
{
int index = directionNode->GetValue();
directionState[index] = true;
directionNode = static_cast<const aslp::ReservedWordTerminal *>(directionNode->GetNextSibling());
}
}
else
{ // 'ALL' was specified
for (int i = 0; i < 6; ++i) directionState[i] = true;
}
}
else
{ // nothing was specified; assume all directions
for (int i = 0; i < 6; ++i) directionState[i] = true;
}
node = node->GetNextSibling();
const aslp::ExpressionNode& setExprNode = static_cast<const aslp::ExpressionNode&>(*node);
const aslp::ParseTreeNode *setNode =
static_cast<const aslp::ParseTreeNode *>(setExprNode.GetFirstChild());
setNode = setNode->GetNextSibling()->GetNextSibling();
targetSetName = setNode->ToString();
return ElementCollectorParseResult(result, collectorType, directionState, targetSetName);
}
void axis::application::factories::collectors::TextReportElementCollectorParser::InitGrammar( void )
{
anyIdentifierExpression_ << aslf::AxisGrammar::CreateIdParser()
<< aslf::AxisGrammar::CreateStringParser(false);
collectorType6D_ << aslf::AxisGrammar::CreateReservedWordParser(_T("STRESS"), (int)ElementCollectorParseResult::kStress)
<< aslf::AxisGrammar::CreateReservedWordParser(_T("STRAIN"), (int)ElementCollectorParseResult::kStrain);
direction6D_ << aslf::AxisGrammar::CreateReservedWordParser(_T("XX"), 0)
<< aslf::AxisGrammar::CreateReservedWordParser(_T("YY"), 1)
<< aslf::AxisGrammar::CreateReservedWordParser(_T("ZZ"), 2)
<< aslf::AxisGrammar::CreateReservedWordParser(_T("YZ"), 3)
<< aslf::AxisGrammar::CreateReservedWordParser(_T("XZ"), 4)
<< aslf::AxisGrammar::CreateReservedWordParser(_T("XY"), 5);
direction6DEnum_ = new axis::services::language::primitives::EnumerationParser(direction6D_, true);
optionalDirection6DExpression_ << *direction6DEnum_
<< aslf::AxisGrammar::CreateReservedWordParser(_T("ALL"), -1)
<< aslf::AxisGrammar::CreateEpsilonParser();
collectorType6DExpression_ << collectorType6D_ << optionalDirection6DExpression_;
collectorTypeExpression_ << collectorType6DExpression_;
setExpression_ << aslf::AxisGrammar::CreateReservedWordParser(_T("ON"), SetExpressionIdentifier)
<< aslf::AxisGrammar::CreateReservedWordParser(_T("SET"))
<< anyIdentifierExpression_;
collectorStatement_ << aslf::AxisGrammar::CreateReservedWordParser(_T("RECORD"))
<< aslf::AxisGrammar::CreateReservedWordParser(_T("ELEMENT"), NodeExpressionIdentifier)
<< collectorTypeExpression_
<< setExpression_;
}
| 36.944681
| 124
| 0.760194
|
renato-yuzup
|
b3e6cbb6e267a886524cda9fcc411b608994070d
| 3,241
|
cpp
|
C++
|
wavebench-dag/src/algorithms/local_sequence_alignment.cpp
|
fabianmcg/wavedag
|
e975792aef4423de6cf43af6bfde44ef89a5db0d
|
[
"MIT"
] | 1
|
2021-01-10T09:04:38.000Z
|
2021-01-10T09:04:38.000Z
|
wavebench-dag/src/algorithms/local_sequence_alignment.cpp
|
fabianmcg/wavedag
|
e975792aef4423de6cf43af6bfde44ef89a5db0d
|
[
"MIT"
] | null | null | null |
wavebench-dag/src/algorithms/local_sequence_alignment.cpp
|
fabianmcg/wavedag
|
e975792aef4423de6cf43af6bfde44ef89a5db0d
|
[
"MIT"
] | null | null | null |
/*---------------------------------------------------------------------------*/
/*!
* \file local_sequence_alignment.cpp
* \author Robert Searles
* \date Tue Sep 19 15:46:00 EST 2018
* \brief Local Sequence Alignment in-gridcell algorithm
* \note
*/
/*---------------------------------------------------------------------------*/
#include "dimensions.h"
#include "local_sequence_alignment.h"
#include <stdio.h>
#include <algorithm>
#include <cstdlib>
#include <string>
/*=============================================*/
/*=== MANDATORY FUNCTIONS ===*/
/*=============================================*/
/*--- Constructor ---*/
LSA::LSA(Dimensions d) {
printf("Creating Local Sequence Alignment Simulation\n\n");
dims=d;
if(dims.ncomponents==32) {
seq1=seq1_cstr;
seq2=seq2_cstr;
}
else {
seq1=generate_sequence(dims.ncell_x,"ATCG");
seq2=generate_sequence(dims.ncell_y,"ATCG");
}
rows = seq1.size() + 1;
cols = seq2.size() + 1;
matrix_size = rows*cols;
/*--- Array Allocation ---*/
matrix = (int*)malloc_host_int(matrix_size);
}
int LSA::r(){
return rows;
}
int LSA::c(){
return cols;
}
/*--- Initialization ---*/
void LSA::init(){
for (int x = 0; x < rows; x++)
for (int y = 0; y < cols; y++)
matrix[(x * cols) + y] = 0;
}
/*--- Run ---*/
/*--- This should run your wavefront sweep component & in-gridcell computation ---*/
void LSA::run(){
create_score_matrix(rows, cols);
}
/*--- Print Output ---*/
void LSA::print(){
for (int x = 1; x < rows; x++)
for (int y = 1; y < cols; y++)
printf("matrix[%d][%d] = %d\n", x, cols-1, matrix[(x * cols) + cols-1]);
}
/*=============================================*/
/*=== ALGORITHM-SPECIFIC FUNCTIONS ===*/
/*=============================================*/
/*--- Create sequence alignment scoring matrix ---*/
void LSA::create_score_matrix(int rows, int cols)
{
int max_score = 0;
int nthreads=1,b=2;
char* bx_str=std::getenv("OMP_BLOCK_DIMX");
char* by_str=std::getenv("OMP_BLOCK_DIMY");
char* nthreads_str=std::getenv("OMP_NUM_THREADS");
if(nthreads_str!=nullptr)
if(strlen(nthreads_str)>0)
nthreads=std::stoi(std::string(nthreads_str));
b*=nthreads;
int bx=b,by=b;
if(bx_str!=nullptr)
if(strlen(bx_str)>0)
bx=std::stoi(std::string(bx_str));
if(by_str!=nullptr)
if(strlen(by_str)>0)
by=std::stoi(std::string(by_str));
#pragma omp dag coarsening(BLOCK,bx,by)
for (int x = 1; x < rows; x++)
for (int y = 1; y < cols; y++) {
#pragma omp dag task depend({(x+1)*cols+y+1,((x+1)<rows)&&((y+1)<cols)},{(x+1)*cols+y,(x+1)<rows},{x*cols+y+1,(y+1)<cols})
{
matrix[(x * cols) + y] = calc_score(x, y);
}
}
}
/*--- Calculate gridcell score ---*/
int LSA::calc_score(int x, int y)
{
int similarity;
if (seq1[x - 1] == seq2[y - 1])
similarity = match;
else
similarity = mismatch;
/*--- Calculate scores ---*/
int diag_score = matrix[(x - 1) * cols + (y - 1)] + similarity;
int up_score = matrix[(x - 1) * cols + y] + gap;
int left_score = matrix[x * cols + (y - 1)] + gap;
/*--- Take max of scores and return ---*/
int result = 0;
if (diag_score > result)
result = diag_score;
if (up_score > result)
result = up_score;
if (left_score > result)
result = left_score;
return result;
}
| 25.722222
| 122
| 0.551682
|
fabianmcg
|
b3ee6bcc5ab85f7d9652b5132b9b94a57d183632
| 118
|
hpp
|
C++
|
build/opencv_tests_config.hpp
|
Meatlf/OpenCV4
|
4a882c0b3cf10700c0cc4ac785266fa02d3f2470
|
[
"BSD-3-Clause"
] | null | null | null |
build/opencv_tests_config.hpp
|
Meatlf/OpenCV4
|
4a882c0b3cf10700c0cc4ac785266fa02d3f2470
|
[
"BSD-3-Clause"
] | null | null | null |
build/opencv_tests_config.hpp
|
Meatlf/OpenCV4
|
4a882c0b3cf10700c0cc4ac785266fa02d3f2470
|
[
"BSD-3-Clause"
] | null | null | null |
#define OPENCV_INSTALL_PREFIX "/usr/local/opencv430"
#define OPENCV_TEST_DATA_INSTALL_PATH "share/opencv4/testdata"
| 23.6
| 62
| 0.838983
|
Meatlf
|
b3f2161a3d7782a1babd2aa31e38ceb78aefe9d1
| 1,728
|
cpp
|
C++
|
src/main.cpp
|
WhitNearSpace/Whitworth-CommandModule
|
d7316fa391c58c69ef25a447df9465e36e21dddf
|
[
"MIT"
] | 1
|
2019-05-28T16:03:37.000Z
|
2019-05-28T16:03:37.000Z
|
src/main.cpp
|
WhitNearSpace/Whitworth-CommandModule
|
d7316fa391c58c69ef25a447df9465e36e21dddf
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
WhitNearSpace/Whitworth-CommandModule
|
d7316fa391c58c69ef25a447df9465e36e21dddf
|
[
"MIT"
] | null | null | null |
#include <mbed.h>
#include "RockBlock9603.h"
DigitalOut led1(LED1);
RockBlock9603 sat(p9, p10, NC);
int main() {
uint64_t imei;
ThisThread::sleep_for(1s);
imei = sat.get_IMEI();
printf("IMEI = %llu\n", imei);
int bars = sat.get_new_signal_quality();
printf("bars = %d\n", bars);
BufferStatus bs = sat.get_buffer_status();
printf("Buffer status\n");
printf("\tMOMSN: %d\n", bs.outgoingMsgNum);
printf("\tMO flag: %d\n", bs.outgoingFlag);
while (true) {
led1 = !led1;
ThisThread::sleep_for(1s);
}
}
/*********************************************************************************
* Ublox test code
********************************************************************************/
// I2C i2c(p9,p10);
// int main() {
// int latitude, longitude;
// int altitude;
// char SIV;
// int groundSpeed, verticalVelocity;
// i2c.frequency(400000);
// Ublox_GPS myGPS(&i2c);
// ThisThread::sleep_for(2s);
// led1 = myGPS.isConnected();
// myGPS.disableDebugging();
// while (true) {
// ThisThread::sleep_for(5s);
// latitude = myGPS.getLatitude();
// longitude = myGPS.getLongitude();
// altitude = myGPS.getAltitude();
// SIV = myGPS.getSIV();
// groundSpeed = myGPS.getGroundSpeed();
// verticalVelocity = myGPS.getVerticalVelocity();
// printf("Lat: %.6f", latitude*1e-7);
// printf(" Lon: %.6f", longitude*1e-7);
// printf(" Alt: %.1f m", altitude/1000.0);
// printf(" \tSatellites: %d\r\n", SIV);
// printf("Ground speed: %f m/s", groundSpeed/1000.0);
// printf(" Vertical velocity: %f m/s\r\n", verticalVelocity/1000.0);
// printf("---------------------------------------------------------------\n");
// }
// }
| 28.8
| 83
| 0.528356
|
WhitNearSpace
|
b3f89f55c1b435f645f66f2214d6eb717e3acb03
| 2,059
|
cpp
|
C++
|
PolyEngine/RenderingDevice/OpenGL/Src/Proxy/GLCubemapDeviceProxy.cpp
|
PiotrMoscicki/PolyEngine
|
573c453e9d1ae0a351ad14410595ff844e3b4620
|
[
"MIT"
] | 65
|
2017-04-04T20:33:44.000Z
|
2019-12-02T23:06:58.000Z
|
PolyEngine/RenderingDevice/OpenGL/Src/Proxy/GLCubemapDeviceProxy.cpp
|
PiotrMoscicki/PolyEngine
|
573c453e9d1ae0a351ad14410595ff844e3b4620
|
[
"MIT"
] | 46
|
2017-04-21T12:26:38.000Z
|
2019-12-15T05:31:47.000Z
|
PolyEngine/RenderingDevice/OpenGL/Src/Proxy/GLCubemapDeviceProxy.cpp
|
PiotrMoscicki/PolyEngine
|
573c453e9d1ae0a351ad14410595ff844e3b4620
|
[
"MIT"
] | 51
|
2017-04-12T10:53:32.000Z
|
2019-11-20T13:05:54.000Z
|
#include <PolyRenderingDeviceGLPCH.hpp>
#include <Proxy/GLCubemapDeviceProxy.hpp>
#include <Proxy/GLTextureDeviceProxy.hpp>
#include <Common/GLUtils.hpp>
using namespace Poly;
GLCubemapDeviceProxy::GLCubemapDeviceProxy(size_t width, size_t height)
: Width(width), Height(height)
{
InitCubemapParams();
}
GLCubemapDeviceProxy::~GLCubemapDeviceProxy()
{
if(TextureID > 0)
{
glDeleteTextures(1, &TextureID);
}
}
void GLCubemapDeviceProxy::InitCubemapParams()
{
glGenTextures(1, &TextureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, TextureID);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}
void GLCubemapDeviceProxy::SetContentHDR(const eCubemapSide side, const float* data)
{
ASSERTE(Width > 0 && Height > 0, "Invalid arguments!");
ASSERTE(TextureID > 0, "Texture is invalid!");
ASSERTE(data, "Data pointer is nullptr!");
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, TextureID);
glTexImage2D( GetEnumFromCubemapSide(side), 0, GL_RGB, (GLsizei)Width, (GLsizei)Height, 0, GL_RGB, GL_FLOAT, data);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
CHECK_GL_ERR();
}
GLenum GLCubemapDeviceProxy::GetEnumFromCubemapSide(eCubemapSide type)
{
switch (type)
{
case eCubemapSide::RIGHT: return GL_TEXTURE_CUBE_MAP_POSITIVE_X;
case eCubemapSide::LEFT: return GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
case eCubemapSide::TOP: return GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
case eCubemapSide::DOWN: return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
case eCubemapSide::BACK: return GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
case eCubemapSide::FRONT: return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
default:
ASSERTE(false, "Invalid type!");
return -1;
}
}
| 29.84058
| 116
| 0.797475
|
PiotrMoscicki
|
b3fd26f7b9288fa991e3b2c0fc65deef03a222fa
| 3,366
|
cpp
|
C++
|
Practica3/prodcons.cpp
|
JArandaIzquierdo/SistemasConcurrentesYDistribuidos
|
1d773458efecefa32b61ade42a1654679d515dc4
|
[
"Apache-2.0"
] | null | null | null |
Practica3/prodcons.cpp
|
JArandaIzquierdo/SistemasConcurrentesYDistribuidos
|
1d773458efecefa32b61ade42a1654679d515dc4
|
[
"Apache-2.0"
] | null | null | null |
Practica3/prodcons.cpp
|
JArandaIzquierdo/SistemasConcurrentesYDistribuidos
|
1d773458efecefa32b61ade42a1654679d515dc4
|
[
"Apache-2.0"
] | null | null | null |
#include <mpi.h>
#include <iostream>
#include <math.h>
#include <time.h> // incluye "time"
#include <unistd.h> // incluye "usleep"
#include <stdlib.h> // incluye "rand" y "srand"
// ---------------------------------------------------------------------
#define Productor 0
#define Buffer 1
#define Consumidor 2
#define ITERS 20
using namespace std;
// ---------------------------------------------------------------------
void productor()
{
for ( unsigned int i= 0 ; i < ITERS ; i++ )
{
cout << "Productor produce valor " << i << endl << flush;
// espera bloqueado durante un intervalo de tiempo aleatorio
// (entre una décima de segundo y un segundo)
usleep( 1000U * (100U+(rand()%900U)) );
// enviar valor
MPI_Ssend( &i, 1, MPI_INT, Buffer, 0, MPI_COMM_WORLD );
}
}
// ---------------------------------------------------------------------
void buffer()
{
int value ,
peticion ;
MPI_Status status ;
for ( unsigned int i = 0 ; i < ITERS ; i++ )
{
MPI_Recv(&value, 1, MPI_INT, Productor, 0, MPI_COMM_WORLD, &status );
MPI_Recv(&peticion, 1, MPI_INT, Consumidor, 0, MPI_COMM_WORLD, &status );
cout << "Buffer recibe valor "<< value << " de Productor " << endl << flush;
MPI_Ssend( &value, 1, MPI_INT, Consumidor, 0, MPI_COMM_WORLD);
cout << "Buffer envía valor " << value << " a Consumidor " << endl << flush;
}
}
// ---------------------------------------------------------------------
void consumidor()
{
int value,
peticion = 1 ;
float raiz ;
MPI_Status status ;
for (unsigned int i=0;i<ITERS;i++)
{
MPI_Ssend(&peticion, 1, MPI_INT, Buffer, 0, MPI_COMM_WORLD);
MPI_Recv(&value, 1, MPI_INT, Buffer, 0, MPI_COMM_WORLD,&status );
cout << "Consumidor recibe valor " << value << " de Buffer " << endl << flush ;
// espera bloqueado durante un intervalo de tiempo aleatorio
// (entre una décima de segundo y un segundo)
usleep( 1000U * (100U+(rand()%900U)) );
// calcular raíz del valor recibido
raiz = sqrt( value );
}
}
// ---------------------------------------------------------------------
int main( int argc, char *argv[] )
{
int rank , // identificador de proceso (comienza en 0)
size ; // numero de procesos
// inicializar MPI y leer identificador de proceso y número de procesos
MPI_Init( &argc, &argv );
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
MPI_Comm_size( MPI_COMM_WORLD, &size );
// inicializa la semilla aleatoria:
srand ( time(NULL) );
// comprobar el número de procesos con el que el programa
// ha sido puesto en marcha (debe ser 3)
if ( size != 3 )
{
cout << "El numero de procesos debe ser 3, pero es " << size << "." << endl << flush ;
return 0;
}
// verificar el identificador de proceso (rank), y ejecutar la
// operación apropiada a dicho identificador
if ( rank == Productor )
productor();
else if ( rank == Buffer )
buffer();
else
consumidor();
// al terminar el proceso, finalizar MPI
MPI_Finalize( );
return 0;
}
// ---------------------------------------------------------------------
| 29.787611
| 92
| 0.501485
|
JArandaIzquierdo
|
b600d5f91b170f23522494a471170d54da0dbfda
| 8,614
|
cxx
|
C++
|
PWGJE/EMCALJetTasks/AliJetShape.cxx
|
wiechula/AliPhysics
|
6c5c45a5c985747ee82328d8fd59222b34529895
|
[
"BSD-3-Clause"
] | null | null | null |
PWGJE/EMCALJetTasks/AliJetShape.cxx
|
wiechula/AliPhysics
|
6c5c45a5c985747ee82328d8fd59222b34529895
|
[
"BSD-3-Clause"
] | null | null | null |
PWGJE/EMCALJetTasks/AliJetShape.cxx
|
wiechula/AliPhysics
|
6c5c45a5c985747ee82328d8fd59222b34529895
|
[
"BSD-3-Clause"
] | null | null | null |
#include "AliJetShape.h"
#include "TMath.h"
#include "TMatrixD.h"
#include "TMatrixDSym.h"
#include "TMatrixDSymEigen.h"
#include "TVector3.h"
#include "TVector2.h"
#include "AliFJWrapper.h"
using namespace std;
#ifdef FASTJET_VERSION
//________________________________________________________________________
Double32_t AliJetShapeGRNum::result(const fastjet::PseudoJet &jet) const {
if (!jet.has_constituents())
return 0; //AliFatal("Angular structure can only be applied on jets for which the constituents are known.");
Double_t A = 0.;
std::vector<fastjet::PseudoJet> constits = jet.constituents();
for(UInt_t ic = 0; ic < constits.size(); ++ic) {
/* Int_t uid = constits[ic].user_index(); */
/* if (uid == -1) //skip ghost particle */
/* continue; */
for(UInt_t jc = ic+1; jc < constits.size(); ++jc) {
/* Int_t uid = constits[jc].user_index(); */
/* if (uid == -1) //skip ghost particle */
/* continue; */
Double_t dphi = constits[ic].phi()-constits[jc].phi();
if(dphi<-1.*TMath::Pi()) dphi+=TMath::TwoPi();
if(dphi>TMath::Pi()) dphi-=TMath::TwoPi();
Double_t dr2 = (constits[ic].eta()-constits[jc].eta())*(constits[ic].eta()-constits[jc].eta()) + dphi*dphi;
if(dr2>0.) {
Double_t dr = TMath::Sqrt(dr2);
Double_t x = fR-dr;
//noisy function
Double_t noise = TMath::Exp(-x*x/(2*fDRStep*fDRStep))/(TMath::Sqrt(2.*TMath::Pi())*fDRStep);
A += constits[ic].perp()*constits[jc].perp()*dr2*noise;
}
}
}
return A;
}
Double32_t AliJetShapeGRDen::result(const fastjet::PseudoJet &jet) const {
if (!jet.has_constituents())
return 0; //AliFatal("Angular structure can only be applied on jets for which the constituents are known.");
Double_t A = 0.;
std::vector<fastjet::PseudoJet> constits = jet.constituents();
for(UInt_t ic = 0; ic < constits.size(); ++ic) {
/* Int_t uid = constits[ic].user_index(); */
/* if (uid == -1) //skip ghost particle */
/* continue; */
for(UInt_t jc = ic+1; jc < constits.size(); ++jc) {
/* Int_t uid = constits[jc].user_index(); */
/* if (uid == -1) //skip ghost particle */
/* continue; */
Double_t dphi = constits[ic].phi()-constits[jc].phi();
if(dphi<-1.*TMath::Pi()) dphi+=TMath::TwoPi();
if(dphi>TMath::Pi()) dphi-=TMath::TwoPi();
Double_t dr2 = (constits[ic].eta()-constits[jc].eta())*(constits[ic].eta()-constits[jc].eta()) + dphi*dphi;
if(dr2>0.) {
Double_t dr = TMath::Sqrt(dr2);
Double_t x = fR-dr;
//error function
Double_t erf = 0.5*(1.+TMath::Erf(x/(TMath::Sqrt(2.)*fDRStep)));
A += constits[ic].perp()*constits[jc].perp()*dr2*erf;
}
}
}
return A;
}
Double32_t AliJetShapeAngularity::result(const fastjet::PseudoJet &jet) const {
if (!jet.has_constituents())
return 0;
Double_t den=0.;
Double_t num = 0.;
std::vector<fastjet::PseudoJet> constits = jet.constituents();
for(UInt_t ic = 0; ic < constits.size(); ++ic) {
Double_t dphi = constits[ic].phi()-jet.phi();
if(dphi<-1.*TMath::Pi()) dphi+=TMath::TwoPi();
if(dphi>TMath::Pi()) dphi-=TMath::TwoPi();
Double_t dr2 = (constits[ic].eta()-jet.eta())*(constits[ic].eta()-jet.eta()) + dphi*dphi;
Double_t dr = TMath::Sqrt(dr2);
num=num+constits[ic].perp()*dr;
den=den+constits[ic].perp();
}
return num/den;
}
Double32_t AliJetShapepTD::result(const fastjet::PseudoJet &jet) const {
if (!jet.has_constituents())
return 0;
Double_t den=0;
Double_t num = 0.;
std::vector<fastjet::PseudoJet> constits = jet.constituents();
for(UInt_t ic = 0; ic < constits.size(); ++ic) {
num=num+constits[ic].perp()*constits[ic].perp();
den=den+constits[ic].perp();
}
return TMath::Sqrt(num)/den;
}
Double32_t AliJetShapeCircularity::result(const fastjet::PseudoJet &jet) const {
if (!jet.has_constituents())
return 0;
Double_t mxx = 0.;
Double_t myy = 0.;
Double_t mxy = 0.;
int nc = 0;
Double_t sump2 = 0.;
Double_t pxjet=jet.px();
Double_t pyjet=jet.py();
Double_t pzjet=jet.pz();
//2 general normalized vectors perpendicular to the jet
TVector3 ppJ1(pxjet, pyjet, pzjet);
TVector3 ppJ3(- pxjet* pzjet, - pyjet * pzjet, pxjet * pxjet + pyjet * pyjet);
ppJ3.SetMag(1.);
TVector3 ppJ2(-pyjet, pxjet, 0);
ppJ2.SetMag(1.);
std::vector<fastjet::PseudoJet> constits = jet.constituents();
for(UInt_t ic = 0; ic < constits.size(); ++ic) {
TVector3 pp(constits[ic].px(), constits[ic].py(), constits[ic].pz());
//local frame
TVector3 pLong = pp.Dot(ppJ1) / ppJ1.Mag2() * ppJ1;
TVector3 pPerp = pp - pLong;
//projection onto the two perpendicular vectors defined above
Float_t ppjX = pPerp.Dot(ppJ2);
Float_t ppjY = pPerp.Dot(ppJ3);
Float_t ppjT = TMath::Sqrt(ppjX * ppjX + ppjY * ppjY);
if(ppjT<=0) return 0;
mxx += (ppjX * ppjX / ppjT);
myy += (ppjY * ppjY / ppjT);
mxy += (ppjX * ppjY / ppjT);
nc++;
sump2 += ppjT;
}
if(nc<2) return 0;
if(sump2==0) return 0;
// Sphericity Matrix
Double_t ele[4] = {mxx / sump2, mxy / sump2, mxy / sump2, myy / sump2};
TMatrixDSym m0(2,ele);
// Find eigenvectors
TMatrixDSymEigen m(m0);
TVectorD eval(2);
TMatrixD evecm = m.GetEigenVectors();
eval = m.GetEigenValues();
// Largest eigenvector
int jev = 0;
if (eval[0] < eval[1]) jev = 1;
TVectorD evec0(2);
// Principle axis
evec0 = TMatrixDColumn(evecm, jev);
Double_t compx=evec0[0];
Double_t compy=evec0[1];
TVector2 evec(compx, compy);
Double_t circ=0;
if(jev==1) circ=2*eval[0];
if(jev==0) circ=2*eval[1];
return circ;
}
Double32_t AliJetShapeSigma2::result(const fastjet::PseudoJet &jet) const {
if (!jet.has_constituents())
return 0;
Double_t mxx = 0.;
Double_t myy = 0.;
Double_t mxy = 0.;
int nc = 0;
Double_t sump2 = 0.;
std::vector<fastjet::PseudoJet> constits = jet.constituents();
for(UInt_t ic = 0; ic < constits.size(); ++ic) {
Double_t ppt=constits[ic].perp();
Double_t dphi = constits[ic].phi()-jet.phi();
if(dphi<-1.*TMath::Pi()) dphi+=TMath::TwoPi();
if(dphi>TMath::Pi()) dphi-=TMath::TwoPi();
Double_t deta = constits[ic].eta()-jet.eta();
mxx += ppt*ppt*deta*deta;
myy += ppt*ppt*dphi*dphi;
mxy -= ppt*ppt*deta*TMath::Abs(dphi);
nc++;
sump2 += ppt*ppt;
}
if(nc<2) return 0;
if(sump2==0) return 0;
// Sphericity Matrix
Double_t ele[4] = {mxx , mxy, mxy, myy };
TMatrixDSym m0(2,ele);
// Find eigenvectors
TMatrixDSymEigen m(m0);
TVectorD eval(2);
TMatrixD evecm = m.GetEigenVectors();
eval = m.GetEigenValues();
// Largest eigenvector
int jev = 0;
if (eval[0] < eval[1]) jev = 1;
TVectorD evec0(2);
// Principle axis
evec0 = TMatrixDColumn(evecm, jev);
Double_t compx=evec0[0];
Double_t compy=evec0[1];
TVector2 evec(compx, compy);
Double_t sigma2=0;
if(jev==1) sigma2=TMath::Sqrt(TMath::Abs(eval[0])/sump2);
if(jev==0) sigma2=TMath::Sqrt(TMath::Abs(eval[1])/sump2);
return sigma2;
}
Double32_t AliJetShape1subjettiness_kt::result(const fastjet::PseudoJet &jet) const {
if (!jet.has_constituents())
return 0;
AliFJWrapper *fFastjetWrapper = new AliFJWrapper("FJWrapper", "FJWrapper");
Double32_t Result = fFastjetWrapper->AliFJWrapper::NSubjettinessDerivativeSub(1,0,0.2,1.0,0.4,jet,0);
fFastjetWrapper->Clear();
delete fFastjetWrapper;
return Result;
}
Double32_t AliJetShape2subjettiness_kt::result(const fastjet::PseudoJet &jet) const {
if (!jet.has_constituents())
return 0;
AliFJWrapper *fFastjetWrapper = new AliFJWrapper("FJWrapper", "FJWrapper");
Double32_t Result = fFastjetWrapper->AliFJWrapper::NSubjettinessDerivativeSub(2,0,0.2,1.0,0.4,jet,0);
fFastjetWrapper->Clear();
delete fFastjetWrapper;
return Result;
}
Double32_t AliJetShape3subjettiness_kt::result(const fastjet::PseudoJet &jet) const {
if (!jet.has_constituents())
return 0;
AliFJWrapper *fFastjetWrapper = new AliFJWrapper("FJWrapper", "FJWrapper");
Double32_t Result = fFastjetWrapper->AliFJWrapper::NSubjettinessDerivativeSub(3,0,0.2,1.0,0.4,jet,0);
fFastjetWrapper->Clear();
delete fFastjetWrapper;
return Result;
}
Double32_t AliJetShapeOpeningAngle_kt::result(const fastjet::PseudoJet &jet) const {
if (!jet.has_constituents())
return 0;
AliFJWrapper *fFastjetWrapper = new AliFJWrapper("FJWrapper", "FJWrapper");
Double32_t Result = fFastjetWrapper->AliFJWrapper::NSubjettinessDerivativeSub(2,0,0.2,1.0,0.4,jet,1);
fFastjetWrapper->Clear();
delete fFastjetWrapper;
return Result;
}
#endif
| 32.752852
| 113
| 0.648015
|
wiechula
|
b60194fe3eb6c2ef2c8c9628984ac3668f1b5d58
| 1,794
|
cpp
|
C++
|
2015/day25/p1/main.cpp
|
jbaldwin/adventofcode2019
|
bdc333330dd5e36458a49f0b7cd64d462c9988c7
|
[
"MIT"
] | null | null | null |
2015/day25/p1/main.cpp
|
jbaldwin/adventofcode2019
|
bdc333330dd5e36458a49f0b7cd64d462c9988c7
|
[
"MIT"
] | null | null | null |
2015/day25/p1/main.cpp
|
jbaldwin/adventofcode2019
|
bdc333330dd5e36458a49f0b7cd64d462c9988c7
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <string>
#include <map>
int main(int argc, char* argv[])
{
constexpr int64_t row = 2978;
constexpr int64_t col = 3083;
constexpr int64_t first_code = 20151125;
constexpr int64_t multiply_by = 252533;
constexpr int64_t modulo_by = 33554393;
// Pattern for generating the grid!
// [ 1, 1, 1]
// [ 2, 2, 1]
// [ 3, 1, 2]
// [ 4, 3, 1]
// [ 5, 2, 2]
// [ 6, 1, 3]
// [ 7, 4, 1]
// [ 8, 3, 2]
// [ 9, 2, 3]
// [10, 1, 4]
// [11, 5, 1]
// [12, 4, 2]
// [13, 3, 3]
// [14, 2, 4]
// [15, 1, 5]
std::map<int64_t, std::map<int64_t, int64_t>> grid{};
// counter is the value stored at each x,y coordinate
int64_t counter{first_code};
// i is the number of items in this diagonal row
int64_t i{1};
while(true)
{
// Continue populating until the row/col pair is available.
if(auto found_row = grid.find(row); found_row != grid.end())
{
if(auto found_col = found_row->second.find(col); found_col != found_row->second.end())
{
break;
}
}
int64_t x = i;
int64_t y = 1;
// Count x down to 1 and y up to i to populate the diagonal row.
while(x >= 1)
{
grid[x][y] = counter;
x--;
y++;
auto value = counter * multiply_by;
value %= modulo_by;
counter = value;
}
++i;
}
// for(const auto& [x, row] : grid)
// {
// for(const auto& [y, value] : row)
// {
// std::cout << value << " ";
// }
// std::cout << "\n";
// }
std::cout << grid[row][col] << "\n";
return 0;
}
| 22.148148
| 98
| 0.466555
|
jbaldwin
|
b608c99031ce1661c470b10d7f08725e8fb4e8a9
| 683
|
cpp
|
C++
|
competitive_programming/programming_contests/uri/kiloman.cpp
|
LeandroTk/Algorithms
|
569ed68eba3eeff902f8078992099c28ce4d7cd6
|
[
"MIT"
] | 205
|
2018-12-01T17:49:49.000Z
|
2021-12-22T07:02:27.000Z
|
competitive_programming/programming_contests/uri/kiloman.cpp
|
LeandroTk/Algorithms
|
569ed68eba3eeff902f8078992099c28ce4d7cd6
|
[
"MIT"
] | 2
|
2020-01-01T16:34:29.000Z
|
2020-04-26T19:11:13.000Z
|
competitive_programming/programming_contests/uri/kiloman.cpp
|
LeandroTk/Algorithms
|
569ed68eba3eeff902f8078992099c28ce4d7cd6
|
[
"MIT"
] | 50
|
2018-11-28T20:51:36.000Z
|
2021-11-29T04:08:25.000Z
|
// https://www.urionlinejudge.com.br/judge/en/problems/view/1250
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool is_hit(vector<int> &v, string js, int ind) {
if (js[ind] == 'S' && (v[ind] == 1 || v[ind] == 2)) return true;
if (js[ind] == 'J' && v[ind] > 2) return true;
return false;
}
int main() {
int n, x, temp;
string js;
vector<int> v;
cin >> n;
while (n--) {
int counter = 0;
cin >> x;
for (int i = 0; i < x; i++) {
cin >> temp;
v.push_back(temp);
}
cin >> js;
for (int ind = 0; ind < x; ind++)
if (is_hit(v, js, ind)) counter++;
cout << counter << endl;
v.clear();
}
return 0;
}
| 15.522727
| 65
| 0.535871
|
LeandroTk
|
b608ee41a49d252159d0f8d61fd93b12abdbb96e
| 5,913
|
cpp
|
C++
|
src/render/ui_renderer.cpp
|
MrPepperoni/Reaping2-1
|
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
|
[
"MIT"
] | 3
|
2015-02-22T20:34:28.000Z
|
2020-03-04T08:55:25.000Z
|
src/render/ui_renderer.cpp
|
MrPepperoni/Reaping2-1
|
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
|
[
"MIT"
] | 22
|
2015-12-13T16:29:40.000Z
|
2017-03-04T15:45:44.000Z
|
src/render/ui_renderer.cpp
|
Reaping2/Reaping2
|
0d4c988c99413e50cc474f6206cf64176eeec95d
|
[
"MIT"
] | 14
|
2015-11-23T21:25:09.000Z
|
2020-07-17T17:03:23.000Z
|
#include "i_render.h"
#include "ui_renderer.h"
#include "main/window.h"
#include "engine/engine.h"
#include "uimodel_repo.h"
#include "shader_manager.h"
#include "uimodel.h"
#include "font.h"
#include "counter.h"
#include "platform/game_clock.h"
namespace {
typedef std::vector<glm::vec2> Positions_t;
typedef std::vector<glm::vec4> Colors_t;
bool getNextTextId( UiVertices_t::const_iterator& i, UiVertices_t::const_iterator e,
Positions_t& Positions, Colors_t& Colors, Positions_t& TexCoords,
render::RenderBatch& batch )
{
if( i == e )
{
return false;
}
UiVertex const& Vert = *i;
Positions.push_back( Vert.Pos );
TexCoords.push_back( Vert.TexCoord );
Colors.push_back( Vert.Color );
batch.TexId = Vert.TexId;
++i;
return true;
}
bool IsSubtreeHidden( Widget const& wdg )
{
for( Widget const* w = wdg.Parent(); NULL != w; w = w->Parent() )
{
Widget::Prop const& p = w->operator()( Widget::PT_SubtreeHidden );
if( ( p.GetType() == Widget::Prop::T_Int || p.GetType() == Widget::Prop::T_Double )
&& p.operator int32_t() )
{
return true;
}
}
return false;
}
}
void UiRenderer::Draw( Root const& UiRoot, const glm::mat4& projMatrix )
{
/* for(Widget::const_iterator i=UiRoot.begin(),e=UiRoot.end();i!=e;++i)
{
static UiModelRepo const& UiModels(UiModelRepo::Get());
Widget const& Wdg=*i;
if(!(int32_t)Wdg(Widget::PT_Visible)) continue;
UiModel const& Model=UiModels(Wdg.GetId());
Model.Draw(Wdg);
}*/
UiVertices_t Vertices;
Vertices.reserve( mPrevVertices.size() );
UiVertexInserter_t Inserter( Vertices );
for( Widget::const_iterator i = UiRoot.begin(), e = UiRoot.end(); i != e; ++i )
{
static UiModelRepo const& UiModels( UiModelRepo::Get() );
Widget const& Wdg = *i;
if( ( 0 == ( int32_t )Wdg( Widget::PT_Visible ) ) || IsSubtreeHidden( Wdg ) )
{
continue;
}
UiModel const& Model = UiModels( Wdg.GetId() );
Model.CollectVertices( Wdg, Inserter );
}
size_t const CurSize = Vertices.size();
if ( CurSize == 0 )
{
return;
}
// collect start / count values
Positions_t Positions;
Positions_t TexCoords;
Positions.reserve( CurSize );
TexCoords.reserve( CurSize );
Colors_t Colors;
Colors.reserve( CurSize );
// todo: check and track changes
UiVertices_t::const_iterator i = Vertices.begin();
render::Counts_t const& Counts = render::count(
std::bind( &getNextTextId, std::ref( i ), Vertices.end(),
std::ref( Positions ), std::ref( Colors ), std::ref( TexCoords ),
std::placeholders::_1 )
);
mVAO.Bind();
if( CurSize != mPrevVertices.size() )
{
size_t TotalSize = CurSize * ( sizeof( glm::vec4 ) + 2 * sizeof( glm::vec2 ) );
glBufferData( GL_ARRAY_BUFFER, TotalSize, NULL, GL_DYNAMIC_DRAW );
}
size_t CurrentOffset = 0;
size_t CurrentSize = CurSize * sizeof( glm::vec2 );
GLuint CurrentAttribIndex = 0;
glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &Positions[0] );
glEnableVertexAttribArray( CurrentAttribIndex );
size_t const PosIndex = CurrentOffset;
++CurrentAttribIndex;
CurrentOffset += CurrentSize;
CurrentSize = CurSize * sizeof( glm::vec2 );
glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &TexCoords[0] );
glEnableVertexAttribArray( CurrentAttribIndex );
size_t const TexIndex = CurrentOffset;
++CurrentAttribIndex;
CurrentOffset += CurrentSize;
CurrentSize = CurSize * sizeof( glm::vec4 );
glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &Colors[0] );
glEnableVertexAttribArray( CurrentAttribIndex );
size_t const ColorIndex = CurrentOffset;
ShaderManager& ShaderMgr( ShaderManager::Get() );
static int32_t def( AutoId( "ui" ) );
ShaderMgr.ActivateShader( def );
ShaderMgr.UploadData( "time", GLfloat( platform::Clock::Now() ) );
int w, h;
mWindow->GetWindowSize( w, h );
ShaderMgr.UploadData( "resolution", glm::vec2( w, h ) );
ShaderMgr.UploadData( "uiProjection", projMatrix );
glActiveTexture( GL_TEXTURE0 + 4 );
for( render::Counts_t::const_iterator i = Counts.begin(), e = Counts.end(); i != e; ++i )
{
render::CountByTexId const& Part = *i;
CurrentAttribIndex = 0;
glVertexAttribPointer( CurrentAttribIndex, 2, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( PosIndex + sizeof( glm::vec2 )*Part.Start ) );
++CurrentAttribIndex;
glVertexAttribPointer( CurrentAttribIndex, 2, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( TexIndex + sizeof( glm::vec2 )*Part.Start ) );
++CurrentAttribIndex;
glVertexAttribPointer( CurrentAttribIndex, 4, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( ColorIndex + sizeof( glm::vec4 )*Part.Start ) );
if( Part.Batch.TexId != -1 )
{
glBindTexture( GL_TEXTURE_2D, Part.Batch.TexId );
}
glDrawArrays( GL_TRIANGLES, 0, Part.Count );
}
mVAO.Unbind();
// store current match
using std::swap;
swap( mPrevVertices, Vertices );
}
void UiRenderer::Init()
{
mVAO.Init();
ShaderManager& ShaderMgr( ShaderManager::Get() );
static int32_t def( AutoId( "ui" ) );
ShaderMgr.ActivateShader( def );
glActiveTexture( GL_TEXTURE0 + 4 );
glBindTexture( GL_TEXTURE_2D, Font::Get().GetTexId() );
ShaderMgr.UploadData( "uiTexture", GLuint( 4 ) );
glActiveTexture( GL_TEXTURE0 );
mWindow = engine::Engine::Get().GetSystem<engine::WindowSystem>();
}
UiRenderer::UiRenderer()
{
Init();
}
| 34.377907
| 138
| 0.61424
|
MrPepperoni
|
b60a5042dcce244695b69aa8b1d3334bcef2896e
| 7,841
|
cpp
|
C++
|
ExploringScaleSymmetry/Chapter9/ch9_figure2.cpp
|
TGlad/ExploringScaleSymmetry
|
25b2dae0279a0ac26f6bae2277d3b76a1cda8b04
|
[
"MIT"
] | null | null | null |
ExploringScaleSymmetry/Chapter9/ch9_figure2.cpp
|
TGlad/ExploringScaleSymmetry
|
25b2dae0279a0ac26f6bae2277d3b76a1cda8b04
|
[
"MIT"
] | null | null | null |
ExploringScaleSymmetry/Chapter9/ch9_figure2.cpp
|
TGlad/ExploringScaleSymmetry
|
25b2dae0279a0ac26f6bae2277d3b76a1cda8b04
|
[
"MIT"
] | null | null | null |
// Thomas Lowe, 2020.
// Calculates the fractal content for a limit set over multiple scales, and plots it as a log-log graph, to demonstrate its oscillation.
// This also plots the limit set itself and the expanded limit set at every scale. Use a breakpoint in this look to see each expanded set.
#include "stdafx.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "imagewrite.h"
#include <sstream>
#include <fstream>
#define DRAW_LIMIT_SET
#define DRAW_EXPANDED_SET // Note: this overwrites the same image file at each expansion radius. Use a breakpoint to make copies of these images.
#define DRAW_LOGLOG_PLOT
namespace
{
struct Shape
{
Vector2d pos;
Vector2d xAxis, yAxis;
double nodeWidth;
vector<Shape, aligned_allocator<Shape> > children;
void split(int index);
void draw(ofstream &svg, const Vector2d &origin, const Vector2d &xAx, const Vector2d &yAx);
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
}
static int width = 1024;
static int height = 750;
static Vector2d offset(500.0, 600.0);
static Vector2d minVec(1e10, 1e10);
static Vector2d maxVec(-1e10, -1e10);
static vector<Vector2d> leaves;
// Note that the structure is drawn as multiple pentagons. That is because the base shape used is a pentagon.
// Of course we could just draw points for the limit set, but the original substitution rule is with pentagons so we keep that here.
void Shape::draw(ofstream &svg, const Vector2d &origin, const Vector2d &xAx, const Vector2d &yAx)
{
Vector2d minV(-1.26, 0.62);
Vector2d maxV(1.36, 1.85);
double mult = (maxV[0] - minV[0]);
Vector2d start = origin + xAx*pos[0] + yAx*pos[1];
Vector2d x = xAx*xAxis[0] + yAx*xAxis[1];
Vector2d y = xAx*yAxis[0] + yAx*yAxis[1];
double length = nodeWidth * 0.4;
if (children.empty())
{
Vector2d corners[] = { start - x*nodeWidth*0.5, start + x*nodeWidth*0.5, start + x*0.5*nodeWidth + y*length, start + y*(1.5*length), start - x*0.5*nodeWidth + y*length };
leaves.push_back(corners[2]);
minVec[0] = min(minVec[0], corners[2][0]);
minVec[1] = min(minVec[1], corners[2][1]);
maxVec[0] = max(maxVec[0], corners[2][0]);
maxVec[1] = max(maxVec[1], corners[2][1]);
for (int i = 0; i < 5; i++)
corners[i] = minV + (double)width * (corners[i] - minV) / mult;
svg << "<path d = \"M " << corners[4][0] << " " << corners[4][1];
for (int i = 0; i < 5; i++)
svg << " L " << corners[i][0] << " " << corners[i][1];
svg << "\" fill=\"black\" stroke-width = \"1\" stroke=\"black\" />\n";
}
Vector2d p = start + y*length;
for (auto &c : children)
c.draw(svg, p, x, y);
}
static void saveSVGLeaves(const string &fileName)
{
static ofstream svg;
svg.open(fileName.c_str());
svg << "<svg width = \"" << width << "\" height = \"" << height << "\" xmlns = \"http://www.w3.org/2000/svg\">" << endl;
double gscale = 0.9*(double)height;
for (auto &p : leaves)
svg << "<circle cx = \"" << gscale*(p[0] + offset[0]) << "\" cy = \"" << (double)height - gscale*(p[1] + offset[1]) << "\" r = \"2\" stroke = \"black\" stroke-width = \"1\" fill = \"black\" />" << endl;
svg << "</svg>" << endl;
svg.close();
}
static void saveSVG(const string &fileName, Shape &tree)
{
static ofstream svg;
svg.open(fileName.c_str());
svg << "<svg width = \"" << width << "\" height = \"" << height << "\" xmlns = \"http://www.w3.org/2000/svg\">" << endl;
tree.draw(svg, Vector2d(0, 0), Vector2d(1, 0), Vector2d(0, 1));
svg << "</svg>" << endl;
svg.close();
}
static void drawGraph(const string &fileName, vector<double> &graph, double yscale, double minY)
{
static ofstream svg;
svg.open(fileName.c_str());
svg << "<svg width = \"" << width << "\" height = \"" << height << "\" xmlns = \"http://www.w3.org/2000/svg\">" << endl;
double xscale = 0.9*(double)width;
svg << "<path d = \"M " << 0 << " " << (double)height - yscale*(graph[0] - minY);
for (int i = 1; i < (int)graph.size(); i++)
svg << " L " << xscale * (double)i / (double)graph.size() << " " << (double)height - yscale*(graph[i] - minY);
svg << "\" fill = \"none\" stroke-width = \"2\" stroke=\"black\" />\n";
svg << "</svg>" << endl;
svg.close();
}
// The substitution rule is applied recursively here
void Shape::split(int index)
{
if (index == 0)
{
return;
}
Shape child1, child2;
double scale = 0.5;
double ang = -0.5;
child1.pos = nodeWidth*Vector2d(-0.4, 0.5);
child1.yAxis = Vector2d(sin(ang), cos(ang));
child1.xAxis = Vector2d(cos(ang), -sin(ang));
child1.nodeWidth = nodeWidth * scale;
ang = 0.7;
child2.pos = nodeWidth*Vector2d(0.5, 0.35);
child2.yAxis = Vector2d(sin(ang), cos(ang));
child2.xAxis = Vector2d(cos(ang), -sin(ang));
child2.nodeWidth = nodeWidth * scale;
children.push_back(child1);
children.push_back(child2);
for (auto &c : children)
c.split(index - 1);
}
static void putpixel(vector<BYTE> &out, const Vector2i &pos, int shade)
{
if (pos[0] < 0 || pos[0] >= width || pos[1] < 0 || pos[1] >= height)
return;
int ind = 3 * (pos[0] + width*pos[1]);
out[ind + 0] = out[ind + 1] = out[ind + 2] = shade;
}
int chapter9Figure2()
{
Shape base;
base.xAxis = Vector2d(1, 0);
base.yAxis = Vector2d(0, 1);
base.nodeWidth = 1.0;
base.pos = Vector2d(0, 0.05);
base.split(12); // the argument is the number of iterations of the substitution
// draw the set
#if defined DRAW_LIMIT_SET
saveSVG("substitutionRuleLimitSet.svg", base);
#endif
cout << "min coordinate: " << minVec.transpose() << ", max coordinate: " << maxVec.transpose() << endl;
vector<BYTE> out(width*height * 3); // .bmp pixel buffer
vector<double> graph;
double c = 0;
for (double r = 0.25; r > 1.0 / 8.0; r /= 1.03)
{
memset(&out[0], 255, out.size() * sizeof(BYTE)); // background is grey
double w = 2e-3;
double m = 1.0 / r;
double minX = minVec[0] - r;
double minY = minVec[1] - r;
double maxX = maxVec[0] + r;
double maxY = maxVec[1] + r;
double radius2 = r*r;
double Nmink = 0;
Vector2d di(sin(22.5*pi / 180.0), cos(22.5*pi / 180.0));
for (double x = minX; x < maxX; x += w)
{
for (double y = minY; y < maxY; y += w)
{
Vector2d p(x, y);
for (auto &leaf : leaves)
{
if ((p - leaf).squaredNorm() < radius2)
{
Nmink++;
double W = 2.0*w;
putpixel(out, Vector2i(0.01 + (x - minX) / W, 0.01 + (y - minY) / W), 192);
break;
}
}
}
}
for (auto &leaf : leaves)
{
double W = 2.0*w;
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
putpixel(out, Vector2i((double)i + 0.01 + (leaf[0] - minX) / W, (double) j + 0.01 + (leaf[1] - minY) / W), 0);
}
Nmink *= w*w; // now a volume
Nmink *= m*m; // now a Minkowski number
double d = 1.0;
c = Nmink / pow(m, d);
cout << "radius: " << r << ", c: " << c << endl;
cout << "log(Nmink): " << log(Nmink) << ", log m: " << log(m) << ", ratio: " << log(Nmink) / log(m) << endl;
graph.push_back(c);
#if defined DRAW_EXPANDED_SET
stbi_write_png("substitutionRuleExpandedSet.png", width, height, 3, &out[0], 3 * width);
#endif
}
#if defined DRAW_LOGLOG_PLOT
double dif = graph.back() - graph[0];
// The content doesn't perfectly match for this approximate calculation due to insufficient processing time, so we shear slightly to correct the curve.
for (int i = 0; i < (int)graph.size(); i++)
graph[i] -= dif * (double)i / (double)(graph.size() - 1);
cout << "dif " << dif << ", " << graph[0] << ", " << graph.back() << endl;
graph.insert(graph.end(), graph.begin(), graph.end());
double yscale = 2.0*(double)height;
double minY = 9.6;
drawGraph("substitutionRuleLogLogGraph.svg", graph, yscale, minY);
#endif
return 0;
}
| 35.004464
| 206
| 0.593929
|
TGlad
|
b60a58e8480c3728b1a52904796d106364be9060
| 22,480
|
cpp
|
C++
|
src/ants.cpp
|
Segfaultt/Ant-Wars-HD
|
a913af070519e8215c8acae8c8683db28e1df046
|
[
"MIT"
] | null | null | null |
src/ants.cpp
|
Segfaultt/Ant-Wars-HD
|
a913af070519e8215c8acae8c8683db28e1df046
|
[
"MIT"
] | null | null | null |
src/ants.cpp
|
Segfaultt/Ant-Wars-HD
|
a913af070519e8215c8acae8c8683db28e1df046
|
[
"MIT"
] | null | null | null |
#include <math.h>
#include "black_hole.h"
#define PI_OVER_180 0.017453293
#define ONE_EIGHTY_OVER_PI 57.29578
#define PYTHAG(a, b) sqrt(pow(a, 2) + pow(b, 2))
#define ANT_REPEL_FORCE 1
int sign(auto x)
{
if (x < 0)
return -1;
else
return 1;
}
//=====ANT=====
ant::ant(ant_type type_, int starting_x, int starting_y)
{
x = starting_x;
y = starting_y;
type = type_;
bar_health = NULL;
bar_stamina = NULL;
reset();
//ai stuff
state = AGGRESSIVE;
srand(seed++);
inteligence = rand()%15 + 1;
srand(seed++);
right_bias = rand()%24-12;
srand(seed++);
if (x > SCREEN_WIDTH/2) {
bearing = 270;
angle = 180;
} else {
bearing = 90;
angle = 0;
}
}
ant::~ant()
{
for (auto *i : holes)
delete i;
for (auto *i : grease)
delete i;
for (auto *i : child)
delete i;
if (tesla_bolt != NULL) {
delete tesla_bolt;
tesla_bolt = NULL;
}
if (bar_health != NULL) {
delete bar_health;
bar_health = NULL;
}
if (bar_stamina != NULL) {
delete bar_stamina;
bar_stamina = NULL;
}
}
void ant::set_other_ants(std::vector<ant *> other_ants_)
{
other_ants = other_ants_;
}
void ant::move(direction dir)
{
switch (dir) {
case FORWARDS:
if (guitar > 0) {
x += grease_effect * speed * 0.3 * cos(angle * PI_OVER_180);
y -= grease_effect * speed * 0.3 * sin(angle * PI_OVER_180);
} else {
x += grease_effect * speed * cos(angle * PI_OVER_180);
y -= grease_effect * speed * sin(angle * PI_OVER_180);
}
break;
case BACKWARDS:
if (guitar > 0) {
x -= grease_effect * speed * 0.3 * cos(angle * PI_OVER_180) * 0.8;
y += grease_effect * speed * 0.3 * sin(angle * PI_OVER_180) * 0.8;
} else {
x -= grease_effect * speed * cos(angle * PI_OVER_180) * 0.8;
y += grease_effect * speed * sin(angle * PI_OVER_180) * 0.8;
}
break;
case LEFT:
if (type == MATT && angular_momentum < 10) {
angular_momentum += 1.5;
} else {
bearing -= turn_speed;
if (bearing < 0)
bearing += 360;
angle = 450 - bearing;
if (angle >= 360)
angle -= 360;
}
break;
case RIGHT:
if (type == MATT && angular_momentum > -10) {
angular_momentum -= 1.5;
} else {
bearing += turn_speed;
if (bearing >= 360)
bearing -= 360;
angle = 450 - bearing;
if (angle >= 360)
angle -= 360;
}
break;
}
}
void ant::render()
{
bar_health->render(x + 50, y - 32, health);
bar_stamina->render(x + 80, y - 20, stamina);
if (flip_timer > 0)
flip_timer--;
if (nip_out_timer > 0) {
nip_texture.render(45 * cos(angle * PI_OVER_180) + x + 25, -45 * sin(angle * PI_OVER_180) + y + 25, bearing);
}
if (nip_out_timer >= -TICKS_PER_FRAME/2)
nip_out_timer--;
if (type == LUCA) {
for (black_hole *i : holes) {
int pos = 0;
i->render();
if (!i->is_alive()) {
i->~black_hole();
holes.erase(holes.begin() + pos);
}
pos++;
}
}
if (type == YA_BOY && tesla_bolt != NULL && tesla_target != NULL) {
tesla_bolt->tick(tesla_target->get_x() + 50, tesla_target->get_y() + 50);
if (!tesla_bolt->is_alive()) {
//damage
tesla_target->damage(19);
//clean up
delete tesla_bolt;
tesla_bolt = NULL;
tesla_target = NULL;
}
}
if (laser_on > 0) {
double x_gradient = cos(angle * PI_OVER_180);
double y_gradient = sin(angle * PI_OVER_180);
thickLineRGBA(renderer, 45 * x_gradient + x + 50, -45 * y_gradient + y + 50, (SCREEN_WIDTH + SCREEN_HEIGHT) * x_gradient + x + 50, -1 *(SCREEN_WIDTH + SCREEN_HEIGHT) * y_gradient + y + 50, 9, 0x97, 0x00, 0x00, 0xff);
//check if hit
for (ant *i : other_ants) {
std::vector<int> p = {i->get_x() - x, y - i->get_y()};
double lambda = p[0]*cos(angle * PI_OVER_180) + p[1]*sin(angle * PI_OVER_180);
if (lambda >= 0 && 2500 >= pow(p[0], 2) + pow(p[1], 2) - pow(lambda, 2)) {
i->damage(5);
//push targets
double magnitude = PYTHAG(x - i->get_x(), y - i->get_y());
double x_component_unit_vector = (x - i->get_x()) / magnitude;
double y_component_unit_vector = (y - i->get_y()) / magnitude;
const double push_force = -3;
i->apply_force(push_force * x_component_unit_vector, push_force * y_component_unit_vector);
}
laser_on--;
}
}
if (type == WEEB && tenticles_out > 0) {
tenticle_texture.render(80 * cos(angle * PI_OVER_180) + x, -80 * sin(angle * PI_OVER_180) + y, bearing);
double angle_to_target, angle_difference, y_component, x_component;
for (ant *i : other_ants) {
x_component = x - i->get_x();
y_component = -1 * (y - i->get_y());
angle_to_target = atan(y_component/x_component) * ONE_EIGHTY_OVER_PI;
if (x_component < 0)
angle_to_target += 180;
if (x_component > 0 && y_component < 0)
angle_to_target += 360;
angle_difference = angle - angle_to_target + 180;
if (angle_difference > 180)
angle_difference = angle_difference - 360;
if (abs(angle_difference) < 40 && PYTHAG(x_component, y_component) < 155) {
i->damage(10);
//push targets
double magnitude = PYTHAG(x - i->get_x(), y - i->get_y());
double x_component_unit_vector = (x - i->get_x()) / magnitude;
double y_component_unit_vector = (y - i->get_y()) / magnitude;
const double push_force = -7;
i->apply_force(push_force * x_component_unit_vector, push_force * y_component_unit_vector);
}
}
tenticles_out--;
}
if (type == SQUID && squid_tenticles_out > 0) {
tenticle_texture.render(-80 * cos(angle * PI_OVER_180) + x, 80 * sin(angle * PI_OVER_180) + y, bearing + 180);
double angle_to_target, angle_difference, y_component, x_component;
for (ant *i : other_ants) {
x_component = x - i->get_x();
y_component = -1 * (y - i->get_y());
angle_to_target = atan(y_component/x_component) * ONE_EIGHTY_OVER_PI;
if (x_component < 0)
angle_to_target += 180;
if (x_component > 0 && y_component < 0)
angle_to_target += 360;
angle_difference = angle - angle_to_target;
if (angle_difference > 180)
angle_difference = angle_difference - 360;
if (abs(angle_difference) < 40 && PYTHAG(x_component, y_component) < 155) {
i->damage(10);
//push targets
double magnitude = PYTHAG(x - i->get_x(), y - i->get_y());
double x_component_unit_vector = (x - i->get_x()) / magnitude;
double y_component_unit_vector = (y - i->get_y()) / magnitude;
const double push_force = -7;
i->apply_force(push_force * x_component_unit_vector, push_force * y_component_unit_vector);
}
}
apply_force(7 * cos(angle * PI_OVER_180), -7 * sin(angle * PI_OVER_180));
}
if (squid_tenticles_out > -20)
squid_tenticles_out--;
sprite.render(x, y, bearing);
if (type == HIPSTER) {
if (guitar > 0 && stamina > 0 && health <= 100) {
guitar--;
guitar_texture.render(45 * cos(angle * PI_OVER_180) + x + 25, -45 * sin(angle * PI_OVER_180) + y + 25, bearing);
damage(-1);
stamina -= 2;
} else if (guitar > 0) {
guitar = 0;
}
}
if (type == ARC && arc_turn > 0) {
if (arc_left) {
move(LEFT);
move(LEFT);
move(LEFT);
} else {
move(RIGHT);
move(RIGHT);
move(RIGHT);
}
move(FORWARDS);
move(FORWARDS);
arc_turn--;
}
if (type == QUEEN) {
int index = 0;
for (ant *i : child) {
ant *target = NULL;
double smallest_distance = 12345;
for (ant *ants : other_ants)
if (smallest_distance > PYTHAG(ants->get_x() - x, ants->get_y() - y)) {
smallest_distance = PYTHAG(ants->get_x() - x, ants->get_y() - y);
target = ants;
}
if (smallest_distance != 12345) {
i->ai(target);
i->render();
i->apply_physics();
}
//kill dead children
if (!i->is_alive()) {
for (ant *j : other_ants) {
j->remove_other_ants(i);
}
child.erase(child.begin() + index);
}
index++;
}
}
}
void ant::apply_force(double x_component, double y_component)
{
velocity[0] += 10*x_component/mass;
velocity[1] += 10*y_component/mass;
}
void ant::apply_physics()
{
//cap velocity
/*const double velocity_cap = 50;
if (velocity[0] > velocity_cap)
velocity[0] = velocity_cap;
if (velocity[0] < -velocity_cap)
velocity[0] = -velocity_cap;
if (velocity[1] > velocity_cap)
velocity[1] = velocity_cap;
if (velocity[1] < -velocity_cap)
velocity[1] = -velocity_cap;*/
//apply velocity
x += velocity[0];
y += velocity[1];
//wrap position
const int out_of_bounds_border = -30;
/*if (x + 50 > SCREEN_WIDTH + out_of_bounds_border)
x = -out_of_bounds_border - 50;
if (x + 50 < -out_of_bounds_border)
x = SCREEN_WIDTH + out_of_bounds_border - 50;
if (y + 50 < -out_of_bounds_border)
y = SCREEN_HEIGHT + out_of_bounds_border - 50;
if (y + 50 > SCREEN_HEIGHT + out_of_bounds_border)
y = -out_of_bounds_border - 50;
//cap position
if (x + 50 > SCREEN_WIDTH + out_of_bounds_border)
x = SCREEN_WIDTH + out_of_bounds_border - 50;
if (x + 50 < -out_of_bounds_border)
x = -out_of_bounds_border - 50;
if (y + 50 < -out_of_bounds_border)
y = -out_of_bounds_border - 50;
if (y + 50 > SCREEN_HEIGHT + out_of_bounds_border)
y = SCREEN_HEIGHT + out_of_bounds_border - 50;
*/
//apply angular momentum
bearing -= angular_momentum;
if (bearing < 0)
bearing += 360;
angle = 450 - bearing;
if (angle >= 360)
angle -= 360;
//friction/air resistance
double drag = 180/(200+sqrt(mass)*PYTHAG(velocity[0], velocity[1]));
velocity[0] *= drag;
velocity[1] *= drag;
if (abs(angular_momentum) < 0.0001)
angular_momentum = 0;
else
angular_momentum += abs(angular_momentum)/angular_momentum * -0.6 / mass;
//ants repel
double distance;
for (ant *i : other_ants) {
distance = sqrt(pow(i->get_x() - x, 2) + pow(i->get_y() - y, 2));
if (distance < 50 && distance != 0) {
velocity[0] -= ANT_REPEL_FORCE * (i->get_x() - x)/distance;
velocity[1] -= ANT_REPEL_FORCE * (i->get_y() - y)/distance;
}
}
if (stamina <= 100 - stamina_regen) {//stamina regen cap
stamina += stamina_regen * grease_effect;
}
//black hole child physics
double x_component, y_component, rotation;
for (black_hole *i : holes) {
//pull other ants
for (ant *each_ant : other_ants) {
x_component = 0;//force from black hole passed by reference
y_component = 0;
i->pull_ants(each_ant->get_x(), each_ant->get_y(), each_ant->get_mass(), x_component, y_component, rotation);
each_ant->apply_force(x_component, y_component);
each_ant->apply_rotational_force(rotation);
}
}
//apply grease
if (type == GREASY_BOY) {
for (ant *target_ant : other_ants) {
bool in_grease = false;
for (grease_trap *i : grease)
if (i->tick(target_ant->get_x() + 50, target_ant->get_y() + 50))
in_grease = true;
target_ant->set_grease_effect(in_grease);
}
bool in_grease = false;
for (grease_trap *i : grease)
if (i->tick(x + 50, y + 50))
in_grease = true;
if (in_grease) {
grease_effect = 1.5;
damage(-0.2);
} else {
grease_effect = 1;
}
}
//slowly die
if (type == ANTDO) {
damage(0.1);
}
}
int ant::get_x()
{
return x;
}
int ant::get_y()
{
return y;
}
double ant::get_mass()
{
return mass;
}
double ant::damage(double damage)
{
if (damage > 0) {
if (type == YA_BOY)
damage *= 1.5;
if (type == MOONBOY)
damage *= 0.5;
if (type == WEEB)
damage *= 1.6;
}
if (damage > 0 | health - damage <= 100) {
health -= damage;
non_edge_damage += damage;
if (type != MATT && type != SQUID)
mass -= damage/150;
mass = std::max(10.0, mass);
}
if (health < 0) {
alive = false;
}
return damage;
}
bool ant::is_alive()
{
return alive;
}
void ant::check_edge()
{
if (x + 50 > SCREEN_WIDTH | x + 50< 0 | y + 50 > SCREEN_HEIGHT | y + 50 < 0) {
non_edge_damage -= damage(0.5);
}
}
void ant::ability()
{
switch (type) {
case LUCA:
if (stamina > 75 && health > 35) {
black_hole *hole = new black_hole(x, y, angle);
holes.push_back(hole);
stamina -= 75;
damage(35);
}
break;
case YA_BOY:
tesla();
break;
case CSS_BAD:
if (stamina > 60 && laser_on <= 0) {
laser_on = TICKS_PER_FRAME/2;
apply_force(-20 * cos(angle * PI_OVER_180), 20 * sin(angle * PI_OVER_180));
stamina -= 60;
}
break;
case HIPSTER:
if (stamina > 0 && guitar == 0) {
guitar = TICKS_PER_FRAME;
}
break;
case ARC:
if (stamina >= 5 && arc_turn == 0) {
stamina -= 5;
arc_turn = 180/(turn_speed*3);
srand(seed++);
arc_left = rand()%2;
}
break;
case GREASY_BOY:
if (stamina >= 70) {
stamina -= 70;
grease.push_back(new grease_trap(x + sprite.get_width()/2, y + sprite.get_height()/2));
}
break;
case WEEB:
if (stamina >= 60) {
stamina -= 60;
tenticles_out = TICKS_PER_FRAME/2;
}
break;
case ANTDO:
if (stamina >= 70) {
stamina -= 70;
srand(seed++);
ant *switcher_ant = other_ants[0];
double transfer_health = switcher_ant->get_health();
//go through the standard damage funtion for mass
switcher_ant->damage(transfer_health - health);
damage(health - transfer_health);
}
break;
case QUEEN:
if (stamina >= 53& health > 20 && child.size() < 3) {
damage(20);
stamina -= 53;
srand(seed++);
child.push_back(new ant(BOT, 45 * cos(angle * PI_OVER_180) + x + 25, -45 * sin(angle * PI_OVER_180) + y + 25));
child[child.size() - 1]->set_other_ants(other_ants);
for (ant *i : other_ants) {
i->add_other_ants(child[child.size() - 1]);
}
}
break;
case SQUID:
if (stamina >= 15 && squid_tenticles_out <= -10) {
stamina -= 15;
squid_tenticles_out = TICKS_PER_FRAME/6;
}
break;
}
}
void ant::nip()
{
const double stamina_take = 20;
if (stamina >= stamina_take && nip_out_timer < -TICKS_PER_FRAME/2) {
stamina -= stamina_take;
int nip_pos[2] = {45 * cos(angle * PI_OVER_180) + x + 25, -45 * sin(angle * PI_OVER_180) + y + 25};
double distance = 0;
nip_out_timer = TICKS_PER_FRAME/2;//0.5 seconds
for (ant *i : other_ants) {
distance = sqrt(pow(nip_pos[0] - i->get_x() - 25, 2) + pow(nip_pos[1] - i->get_y() - 25, 2));
if (distance < 50) {
i->damage(nip_damage * grease_effect);
//push targets
double magnitude = PYTHAG(x - i->get_x(), y - i->get_y());
double x_component_unit_vector = (x - i->get_x()) / magnitude;
double y_component_unit_vector = (y - i->get_y()) / magnitude;
const double push_force = (-30 - stamina);
i->apply_force(push_force * x_component_unit_vector + velocity[0], push_force * y_component_unit_vector + velocity[1]);
}
}
}
}
void ant::tesla()
{
const int cost_coefficient = 10;
tesla_target = NULL;
double shortest_distance = 999999;
for (ant *i : other_ants) {
double distance = sqrt(pow(x - i->get_x(), 2) + pow(y - i->get_y(), 2));
if (distance < shortest_distance) {
shortest_distance = distance;
tesla_target = i;
}
}
if (stamina >= shortest_distance/cost_coefficient + 10 && tesla_bolt == NULL) {
stamina -= shortest_distance/cost_coefficient + 10;
delete tesla_bolt;
tesla_bolt = new electric_bolt(x + 50, y + 50);
//apply attraction
double magnitude = PYTHAG(x - tesla_target->get_x(), y - tesla_target->get_y());
double x_component_unit_vector = (x - tesla_target->get_x()) / magnitude;
double y_component_unit_vector = (y - tesla_target->get_y()) / magnitude;
const double pull_force = 8;
tesla_target->apply_force(pull_force * x_component_unit_vector, pull_force * y_component_unit_vector);
apply_force(-pull_force * x_component_unit_vector, -pull_force * y_component_unit_vector);
}
}
double ant::get_angle()
{
return angle;
}
double ant::get_health()
{
return health;
}
double ant::get_stamina()
{
return stamina;
}
void ant::flip()
{
if (stamina >= 30 && flip_timer == 0) {
stamina -= 30;
bearing += 180;
if (bearing > 360)
bearing -= 360;
angle = 450 - bearing;
flip_timer = TICKS_PER_FRAME/2;
}
}
void ant::set_grease_effect(bool on)
{
if (type != GREASY_BOY) {
if (on) {
grease_effect = 0.5;
damage(0.2);
} else {
grease_effect = 1;
}
}
}
void ant::change_speed(double value)
{
speed += value;
}
void ant::apply_rotational_force(double angular_force)
{
angular_momentum += angular_force;
}
void ant::set_position(int new_x, int new_y)
{
x = new_x;
y = new_y;
if (x > SCREEN_WIDTH/2) {
bearing = 270;
angle = 180;
} else {
bearing = 90;
angle = 0;
}
}
void ant::add_other_ants(ant *other_ants_)
{
other_ants.push_back(other_ants_);
}
void ant::remove_other_ants(ant *other_ants_)
{
for (int i = 0; i < other_ants.size(); i++) {
if (other_ants[i] == other_ants_)
other_ants.erase(other_ants.begin() + i);
}
}
void ant::ai(ant *target)
{
//maths
double x_component = target->get_x() - get_x();
double y_component = -1 * (target->get_y() - get_y());
double angle_to_target = atan(y_component/x_component) * ONE_EIGHTY_OVER_PI;
if (x_component < 0)
angle_to_target += 180;
if (x_component > 0 && y_component < 0)
angle_to_target += 360;
double angle_difference = get_angle() - angle_to_target;
if (angle_difference > 180)
angle_difference = angle_difference - 360;
double distance = sqrt(pow(x_component, 2) + pow(y_component, 2));
double stamina_ratio = get_stamina() * 100 / target->get_stamina();
//apply behaviour
switch (state) {
case AGGRESSIVE:
//turning
if (angle_difference < -15 + right_bias)
move(LEFT);
if (angle_difference > 15 + right_bias)
move(RIGHT);
//move forwards
if (abs(angle_difference) < 30 && distance > 60)
move(FORWARDS);
srand(seed++);
if (abs(angle_difference) < 80 && distance < 70 && rand()%9 == 0)
nip();
break;
case MALFUNCTION:
{
srand(seed++);
int turn = rand()%3;
if (turn == 0)
move(LEFT);
if (turn == 1)
move(RIGHT);
srand(seed++);
if (rand()%3 != 1)
move(FORWARDS);
srand(seed++);
if (rand()%20 == 0)
nip();
srand(seed++);
if (rand()%15 == 0)
state = past_state;
break;
}
case FLEE:
if (distance < 500) {
if (angle_difference > -5)
move(LEFT);
if (angle_difference < 5)
move(RIGHT);
move(FORWARDS);
}
break;
case OFF_SCREEN:
{
//maths
double x_component = SCREEN_WIDTH/2 - get_x();
double y_component = -1 * (SCREEN_HEIGHT/2 - get_y());
double angle_to_target = atan(y_component/x_component) * ONE_EIGHTY_OVER_PI;
if (x_component < 0)
angle_to_target += 180;
if (x_component > 0 && y_component < 0)
angle_to_target += 360;
double angle_difference = get_angle() - angle_to_target;
if (angle_difference > 180)
angle_difference = angle_difference - 360;
//turning
if (angle_difference < -5)
move(LEFT);
if (angle_difference > 5)
move(RIGHT);
//move forwards
if (abs(angle_difference) < 30)
move(FORWARDS);
if (abs(get_x() - SCREEN_WIDTH/2) < SCREEN_WIDTH/2 - 100 && abs(get_y() - SCREEN_HEIGHT/2) < SCREEN_HEIGHT/2 - 100)
state = past_state;
}
}
//behaviour checks
srand(seed++);
if (get_x() - 50 < 0 | get_x() + 50 > SCREEN_WIDTH | get_y() - 50 < 0 | get_y() + 50 > SCREEN_HEIGHT) {
past_state = state;
state = OFF_SCREEN;
} else if (rand()%inteligence == 0) {
past_state = state;
state = MALFUNCTION;
} else if (stamina_ratio < 20)
state = FLEE;
else
state = AGGRESSIVE;
}
void ant::reset()
{
angular_momentum = 0;
tenticles_out = 0;
grease_effect = 1;
for (auto *i : grease)
delete i;
grease.clear();
for (auto *i : holes)
delete i;
holes.clear();
arc_turn = 0;
flip_timer = 0;
nip_out_timer = 0;
nip_damage = 40;
laser_on = 0;
guitar = 0;
alive = true;
mass = 1;
velocity[0] = 0;
velocity[1] = 0;
speed = 8;
turn_speed = 5;
health = 100;
non_edge_damage = 0;
stamina = 0;
stamina_regen = 0.22;
nip_texture.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/nip.png");
tesla_bolt = NULL;
tesla_target = NULL;
squid_tenticles_out = 0;
if (bar_health != NULL) {
delete bar_health;
bar_health = NULL;
}
if (bar_stamina != NULL) {
delete bar_stamina;
bar_stamina = NULL;
}
bar_health = new bar(90, 10);
bar_stamina = new bar(60, 7);
switch (type) {
case YA_BOY:
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/ya_boy.png");
break;
case LUCA:
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/luca.png");
break;
case CSS_BAD:
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/jeff.png");
break;
case HIPSTER:
guitar_texture.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/guitar.png");
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/hipster.png");
speed *= 1.2;
mass *= 0.5;
break;
case BOT:
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/bot.png");
speed *= 0.8;
turn_speed *= 0.8;
health *= 0.5;
nip_damage *= 0.8;
stamina_regen *= 0.5;
break;
case MOONBOY:
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/moonboy.png");
nip_damage *= 1.5;
mass *= 2;
break;
case ARC:
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/the_arc.png");
speed *= 1.5;
break;
case GREASY_BOY:
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/greasy_boy.png");
speed *= 0.7;
nip_damage *= 0.8;
mass *= 0.6;
break;
case WEEB:
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/weeb.png");
tenticle_texture.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/tenticles.png");
speed *= 1.2;
turn_speed *= 1.5;
break;
case MATT:
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/fidget_spinner.png");
speed *= 1.4;
break;
case ANTDO:
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/antdo.png");
break;
case SQUID:
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/squid.png");
tenticle_texture.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/tenticles.png");
speed = 0;
stamina_regen *= 3;
break;
case QUEEN:
sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/queen.png");
nip_damage *= 0.6;
break;
};
}
ant_type ant::get_type()
{
return type;
}
double ant::get_damaged()
{
return non_edge_damage;
}
| 24.172043
| 218
| 0.625801
|
Segfaultt
|
b60a90fd109abcc6dd7e20f9fd76e0ab74c8738d
| 904
|
cpp
|
C++
|
tests/LineFitting/LineFitting.cpp
|
argon24/robest
|
e91fe1f0ec94ae6fcf81a246ad4433b3371ddaa0
|
[
"MIT"
] | 6
|
2018-01-14T23:51:02.000Z
|
2021-12-02T08:42:20.000Z
|
tests/LineFitting/LineFitting.cpp
|
argon24/robest
|
e91fe1f0ec94ae6fcf81a246ad4433b3371ddaa0
|
[
"MIT"
] | 1
|
2018-11-10T09:56:57.000Z
|
2018-11-17T23:17:39.000Z
|
tests/LineFitting/LineFitting.cpp
|
argon24/robest
|
e91fe1f0ec94ae6fcf81a246ad4433b3371ddaa0
|
[
"MIT"
] | 5
|
2018-11-09T20:12:35.000Z
|
2021-09-24T09:41:47.000Z
|
#include "LineFitting.hpp"
LineFittingProblem::LineFittingProblem()
{
setNbParams(2);
setNbMinSamples(2);
}
LineFittingProblem::~LineFittingProblem()
{
}
void LineFittingProblem::setData(std::vector<double> & x, std::vector<double> & y)
{
points.clear();
for (int i = 0; i < x.size(); i++){
Point2d point;
point.x=x[i];
point.y=y[i];
points.push_back(point);
}
}
inline double LineFittingProblem::estimErrorForSample(int i)
{
//distance point to line
const Point2d & p = points[i];
return std::fabs(a*p.x - p.y + b) / sqrt(a*a + 1); // distance line-point
}
inline void LineFittingProblem::estimModelFromSamples(const std::vector<int> & samplesIdx)
{
//line from two points
Point2d & P = points[samplesIdx[0]];
Point2d & V = points[samplesIdx[1]];
a = (V.y-P.y)/(V.x-P.x);
b = P.y -a * P.x;
}
| 14.819672
| 90
| 0.607301
|
argon24
|
b60b7041157ce16da22f9fe08bf84a682dbfc029
| 1,830
|
cpp
|
C++
|
Days 081 - 090/Day 82/ReadNFromRead7.cpp
|
LucidSigma/Daily-Coding-Problems
|
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
|
[
"MIT"
] | null | null | null |
Days 081 - 090/Day 82/ReadNFromRead7.cpp
|
LucidSigma/Daily-Coding-Problems
|
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
|
[
"MIT"
] | null | null | null |
Days 081 - 090/Day 82/ReadNFromRead7.cpp
|
LucidSigma/Daily-Coding-Problems
|
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
|
[
"MIT"
] | null | null | null |
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
class FileReader
{
private:
mutable unsigned int offset = 0;
const std::string contents;
std::string nBuffer = "";
public:
explicit FileReader(const std::string& filename)
: contents(GetFileContents(filename))
{ }
std::string Read7() const noexcept
{
if (offset >= contents.length())
{
return "";
}
std::string sevenLetterString = contents.substr(offset, 7);
offset += 7;
return sevenLetterString;
}
std::string ReadN(unsigned int n) noexcept
{
while (nBuffer.length() < n)
{
std::string sevenLengthString = Read7();
if (sevenLengthString.empty())
{
break;
}
nBuffer += sevenLengthString;
}
std::string nLengthString = nBuffer.substr(0, n);
if (nBuffer.length() >= n)
{
nBuffer = nBuffer.substr(n);
}
else
{
nBuffer = nBuffer.substr(nBuffer.length());
}
return nLengthString;
}
private:
std::string GetFileContents(const std::string& filename) const
{
std::ifstream file(filename);
if (!file.is_open())
{
throw std::invalid_argument("File " + filename + " could not be found/opened.");
}
std::ostringstream fileReader;
fileReader << file.rdbuf();
file.close();
return fileReader.str();
}
};
int main(int argc, char* argv[])
{
FileReader readerA("input.txt");
std::cout << readerA.Read7() << "\n";
std::cout << readerA.Read7() << "\n";
std::cout << readerA.Read7() << "\n";
FileReader readerB("input.txt");
std::cout << readerB.ReadN(8) << "\n";
std::cout << readerB.ReadN(8) << "\n";
std::cout << readerB.ReadN(8) << "\n";
FileReader readerC("input.txt");
std::cout << readerC.ReadN(2) << "\n";
std::cout << readerC.ReadN(2) << "\n";
std::cout << readerC.ReadN(2) << "\n";
std::cin.get();
return 0;
}
| 18.3
| 83
| 0.631694
|
LucidSigma
|
b612d969a96841023213950ddd99d44d5f3ad978
| 343
|
cpp
|
C++
|
Samples/Win7Samples/multimedia/windowsmediaservices9/eventnotification/StdAfx.cpp
|
windows-development/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | 8
|
2017-04-30T17:38:27.000Z
|
2021-11-29T00:59:03.000Z
|
Samples/Win7Samples/multimedia/windowsmediaservices9/eventnotification/StdAfx.cpp
|
TomeSq/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | null | null | null |
Samples/Win7Samples/multimedia/windowsmediaservices9/eventnotification/StdAfx.cpp
|
TomeSq/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | 2
|
2020-08-11T13:21:49.000Z
|
2021-09-01T10:41:51.000Z
|
//+-------------------------------------------------------------------------
//
// Microsoft Windows Media Technologies
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: StdAfx.cpp
//
// Contents:
//
//--------------------------------------------------------------------------
#include "stdafx.h"
| 26.384615
| 77
| 0.335277
|
windows-development
|
b61789691f0cd73e4fd1cee7782b1361822ae577
| 1,672
|
cpp
|
C++
|
Engine/Src/SFEngine/SceneGraph/SFSceneNodeComponent.cpp
|
blue3k/StormForge
|
1557e699a673ae9adcc8f987868139f601ec0887
|
[
"Apache-2.0"
] | 1
|
2020-06-20T07:35:25.000Z
|
2020-06-20T07:35:25.000Z
|
Engine/Src/SFEngine/SceneGraph/SFSceneNodeComponent.cpp
|
blue3k/StormForge
|
1557e699a673ae9adcc8f987868139f601ec0887
|
[
"Apache-2.0"
] | null | null | null |
Engine/Src/SFEngine/SceneGraph/SFSceneNodeComponent.cpp
|
blue3k/StormForge
|
1557e699a673ae9adcc8f987868139f601ec0887
|
[
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
//
// CopyRight (c) 2018 Kyungkun Ko
//
// Author : KyungKun Ko
//
// Description : SceneNodeComponent
//
//
////////////////////////////////////////////////////////////////////////////////
#include "SFEnginePCH.h"
#include "Multithread/SFThread.h"
#include "Util/SFStrUtil.h"
#include "EngineObject/SFEngineObject.h"
#include "SceneGraph/SFSceneNodeComponent.h"
#include "SceneGraph/SFSceneNode.h"
#include "Util/SFTimeUtil.h"
#include "Service/SFEngineService.h"
namespace SF {
template class SharedPointerT<SceneNodeComponent>;
////////////////////////////////////////////////////////////////////////////////////////
//
// SceneNodeComponent class - interface for task operation
//
// Constructor
SceneNodeComponent::SceneNodeComponent(IHeap& heap, const StringCrc64& name)
: Object(&heap, name)
{
}
SceneNodeComponent::~SceneNodeComponent()
{
}
void SceneNodeComponent::Dispose()
{
Object::Dispose();
}
// Change owner
void SceneNodeComponent::ChangeOwner(SceneNode* newOwner)
{
if (m_Owner != nullptr)
m_Owner->RemoveComponent(this);
m_Owner = newOwner;
if (m_Owner != nullptr)
m_Owner->AddComponent(this);
}
Result SceneNodeComponent::CopyProperties(const SceneCloneContext& cloneFlags, SceneNodeComponent* pSrcComponent)
{
if (pSrcComponent == nullptr)
return ResultCode::INVALID_POINTER;
SetName(pSrcComponent->GetName());
m_UpdateTickMode = pSrcComponent->m_UpdateTickMode;
return ResultCode::SUCCESS;
}
}; // namespace SF
| 20.641975
| 115
| 0.584928
|
blue3k
|
b629847993fbb9a0832ede635bff792fc3f1a756
| 616
|
cpp
|
C++
|
cpp/001-010/ZigZag Conversion.cpp
|
KaiyuWei/leetcode
|
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
|
[
"MIT"
] | 150
|
2015-04-04T06:53:49.000Z
|
2022-03-21T13:32:08.000Z
|
cpp/001-010/ZigZag Conversion.cpp
|
yizhu1012/leetcode
|
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
|
[
"MIT"
] | 1
|
2015-04-13T15:15:40.000Z
|
2015-04-21T20:23:16.000Z
|
cpp/001-010/ZigZag Conversion.cpp
|
yizhu1012/leetcode
|
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
|
[
"MIT"
] | 64
|
2015-06-30T08:00:07.000Z
|
2022-01-01T16:44:14.000Z
|
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) {
return s;
}
vector<string> rows(numRows);
int row = 0;
int step = 1;
for (char ch : s) {
rows[row].push_back(ch);
if (row == (numRows - 1)) {
step = -1;
} else if (row == 0) {
step = 1;
}
row += step;
}
stringstream ss;
for (const string& row : rows) {
ss << row;
}
return ss.str();
}
};
| 21.241379
| 43
| 0.362013
|
KaiyuWei
|
b62d74bccbbca48b413e7fdbb0e2637cd73ff48a
| 394
|
hpp
|
C++
|
include/Exceptions/InputErrorException.hpp
|
Ethan13310/NanoTekSpice
|
d69550213a7607662653c52d8f34e5b565714a30
|
[
"MIT"
] | 2
|
2018-06-29T10:17:51.000Z
|
2018-07-04T13:01:53.000Z
|
include/Exceptions/InputErrorException.hpp
|
Ethan13310/NanoTekSpice
|
d69550213a7607662653c52d8f34e5b565714a30
|
[
"MIT"
] | null | null | null |
include/Exceptions/InputErrorException.hpp
|
Ethan13310/NanoTekSpice
|
d69550213a7607662653c52d8f34e5b565714a30
|
[
"MIT"
] | 3
|
2021-03-03T15:29:13.000Z
|
2022-02-22T15:44:44.000Z
|
/*
** EPITECH PROJECT, 2018
** NanoTekSpice
** File description:
** InputErrorException.hpp
*/
#pragma once
#include <string>
#include "Exceptions/BaseException.hpp"
namespace nts
{
class InputErrorException : public BaseException
{
public:
InputErrorException(char const *message);
InputErrorException(std::string const &message);
~InputErrorException() = default;
};
}
| 15.76
| 50
| 0.72335
|
Ethan13310
|
b62e7ed0d6914eecc5cdb23b532a15d7864d26fd
| 546
|
cpp
|
C++
|
heap-vs-stack/main.cpp
|
markccchiang/openmp-examples
|
5970d051e634bc2ad2cf99e84c2544bef1fa258b
|
[
"MIT"
] | 94
|
2017-04-12T13:24:10.000Z
|
2022-03-20T11:44:31.000Z
|
heap-vs-stack/main.cpp
|
markccchiang/openmp-examples
|
5970d051e634bc2ad2cf99e84c2544bef1fa258b
|
[
"MIT"
] | null | null | null |
heap-vs-stack/main.cpp
|
markccchiang/openmp-examples
|
5970d051e634bc2ad2cf99e84c2544bef1fa258b
|
[
"MIT"
] | 26
|
2019-01-31T00:33:14.000Z
|
2022-03-05T19:13:20.000Z
|
#include <iostream>
#include <omp.h>
int main() {
int heap_sum = 0;
omp_set_num_threads(3);
#pragma omp parallel
{
int stack_sum=0;
stack_sum++;
heap_sum++;
printf("stack sum is %d\n", stack_sum);
printf("heap sum is %d\n", heap_sum);
}
std::cout << "final heap sum is " << heap_sum << std::endl;
// output:
// stack sum is 1
// stack sum is 1
// stack sum is 1
// heap sum is 3
// heap sum is 3
// heap sum is 3
// final heap sum is 3
return 0;
}
| 20.222222
| 63
| 0.532967
|
markccchiang
|
ac072c254639cbe5b225437c8b0554364bffa354
| 5,372
|
cpp
|
C++
|
example/particles.cpp
|
libclsph/libclsph
|
4cdf18fba05a64826484b0db238b604c90a2e894
|
[
"MIT"
] | 39
|
2015-01-05T10:39:27.000Z
|
2022-01-25T12:21:00.000Z
|
example/particles.cpp
|
libclsph/libclsph
|
4cdf18fba05a64826484b0db238b604c90a2e894
|
[
"MIT"
] | null | null | null |
example/particles.cpp
|
libclsph/libclsph
|
4cdf18fba05a64826484b0db238b604c90a2e894
|
[
"MIT"
] | 10
|
2015-09-01T22:47:38.000Z
|
2022-01-25T12:21:04.000Z
|
#define EXIT_ON_CL_ERROR
#include <iostream>
#include <iomanip>
#include <string>
#include "sph_simulation.h"
#include "file_save_delegates/houdini_file_saver.h"
#include "util/cereal/archives/binary.hpp"
int main(int argc, char** argv) {
if(argc < 5) {
std::cout << "Too few arguments" << std::endl <<
"Usage: ./sph <fluid_name> <simulation_properties_name> <scene_name> <frames_folder_prefix>" << std::endl;
return -1;
}
sph_simulation simulation;
houdini_file_saver saver = houdini_file_saver(std::string(argv[4]));
try{
simulation.load_settings(
std::string("fluid_properties/") + argv[1] + std::string(".json"),
std::string("simulation_properties/") + argv[2] + std::string(".json"));
}
catch (const std::exception& ex) {
std::cerr << ex.what() << std::endl;
std::exit(-1);
}
int i = 0;
simulation.pre_frame = [&] (particle* particles, const simulation_parameters& params, bool full_frame) {
if(simulation.write_intermediate_frames != full_frame) {
saver.writeFrameToFile(particles, params);
}
//Lets serialize the frames if it was specified
if(simulation.serialize){
std::ofstream file_out( "last_frame.bin" );
cereal::BinaryOutputArchive archive(file_out);
archive.saveBinary(particles,sizeof(particle)*params.particles_count);
}
++i;
int num_frames =
params.simulation_time / (params.time_delta * params.simulation_scale);
int progress = i * 80 / num_frames;
std::cout << "[";
for(int j = 0; j < 80; ++j) {
if(j < progress) {
std::cout << "-";
} else {
std::cout << " ";
}
}
std::cout << "] " << i << "/" << num_frames << std::endl;
};
std::cout << std::endl <<
"Loaded parameters " << std::endl <<
"----------------- " << std::endl <<
"Simulation time: " << simulation.parameters.simulation_time << std::endl <<
"Target FPS: " << simulation.parameters.target_fps << std::endl <<
"Time delta: " << simulation.parameters.time_delta << std::endl <<
"Simulation scale: " << simulation.parameters.simulation_scale << std::endl <<
"Write intermediate frames: " << (simulation.write_intermediate_frames ? "true" : "false") << std::endl <<
"Serialize frames: " << (simulation.serialize ? "true" : "false") << std::endl <<
std::endl <<
"Particle count: " << simulation.parameters.particles_count << std::endl <<
"Particle mass: " << simulation.parameters.particle_mass << std::endl <<
"Total mass: " << simulation.parameters.total_mass << std::endl <<
"Initial volume: " << simulation.initial_volume << std::endl <<
std::endl <<
"Fluid density: " << simulation.parameters.fluid_density << std::endl <<
"Dynamic viscosity: " << simulation.parameters.dynamic_viscosity << std::endl <<
"Surface tension threshold: " << simulation.parameters.surface_tension_threshold << std::endl <<
"Surface tension: " << simulation.parameters.surface_tension << std::endl <<
"Stiffness (k): " << simulation.parameters.K << std::endl <<
"Restitution: " << simulation.parameters.restitution << std::endl <<
std::endl <<
"Kernel support radius (h): " << simulation.parameters.h << std::endl <<
std::endl <<
"Saving to folder: " << saver.frames_folder_prefix + "frames/" << std::endl;
if(!simulation.current_scene.load(argv[3])) {
std::cerr << "Unable to load scene: " << argv[3] << std::endl;
return -1;
}
//If the serialization data is not the right size, delete it
//This probably means the last simulation ran with a different number of particles or the serialization was interrupted
std::filebuf fb;
if (fb.open ("last_frame.bin",std::ios::in))
{
std::istream file_in(&fb);
file_in.seekg(0,std::ios_base::end);
size_t file_size = file_in.tellg();
//This information is important, it indicates that the behavior of the simulator is completely different, use color to draw attention of user
if(file_size == simulation.parameters.particles_count*sizeof(particle)){
std::cout << std::endl << "\033[1;32m Serialized frame found. " << " Simulation will pick up where last run left off.\033[0m";
std::cout << std::endl << "\033[1;32m To start a new simulation, delete last_frame.bin. \033[0m" << std::endl;
}
else{
std::cout << std::endl << "\033[1;31m Serialized frame of incorrect size found. Revert to last know settings or delete it, then try again. \033[0m" << std::endl;
return 0;
}
fb.close();
}
std::cout << std::endl <<
"Revise simulation parameters. Press q to quit, any other key to proceed with simulation" << std::endl;
char response;
std::cin >> response;
if(response != 'q') {
simulation.simulate();
}
return 0;
}
| 40.69697
| 173
| 0.573157
|
libclsph
|
ac0ae526c97f6b4214c6e119684ca9ac6181ecd3
| 249
|
cpp
|
C++
|
baseclass/testPattern.cpp
|
HxHexa/quang-advCG-raytracer
|
605f7dfcc9237f331d456646b7653ad0f26c0cc4
|
[
"MIT"
] | null | null | null |
baseclass/testPattern.cpp
|
HxHexa/quang-advCG-raytracer
|
605f7dfcc9237f331d456646b7653ad0f26c0cc4
|
[
"MIT"
] | null | null | null |
baseclass/testPattern.cpp
|
HxHexa/quang-advCG-raytracer
|
605f7dfcc9237f331d456646b7653ad0f26c0cc4
|
[
"MIT"
] | null | null | null |
/* it does what it says it does
* */
#include "headers/testPattern.hpp"
TestPattern::TestPattern() {
transform = Matrix::Identity();
}
Color TestPattern::patternAt(Tuple point) {
return Color(point.getx(), point.gety(), point.getz());
}
| 19.153846
| 59
| 0.674699
|
HxHexa
|
ac13a5152317f2e27bd83903b60d4f3b55b7ca2e
| 18,075
|
cpp
|
C++
|
src/legecy/stereo_calibration_example.cpp
|
behnamasadi/OpenCVProjects
|
157c8d536c78c5660b64a23300a7aaf941584756
|
[
"BSD-3-Clause"
] | null | null | null |
src/legecy/stereo_calibration_example.cpp
|
behnamasadi/OpenCVProjects
|
157c8d536c78c5660b64a23300a7aaf941584756
|
[
"BSD-3-Clause"
] | null | null | null |
src/legecy/stereo_calibration_example.cpp
|
behnamasadi/OpenCVProjects
|
157c8d536c78c5660b64a23300a7aaf941584756
|
[
"BSD-3-Clause"
] | null | null | null |
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
template<typename to, typename from>
to lexical_cast(from const &x)
{
std::stringstream os;
to ret;
os << x;
os >> ret;
return ret;
}
static bool readStringList( const std::string& filepath, std::vector<std::string>& l )
{
std::string path=filepath.substr(0,filepath.find_last_of("/"));
l.resize(0);
cv::FileStorage fs(filepath, cv::FileStorage::READ);
if( !fs.isOpened() )
return false;
cv::FileNode n = fs.getFirstTopLevelNode();
if( n.type() != cv::FileNode::SEQ )
return false;
cv::FileNodeIterator it = n.begin(), it_end = n.end();
for( ; it != it_end; ++it )
{
// std::cout<<(std::string)*it <<std::endl;
// std::cout<<filepath.substr(0,filepath.find_last_of("/") )<<std::endl;
l.push_back(path+"/"+(std::string)*it);
}
return true;
}
/***************************************calibrating pair of cameras ******************************************/
void stereo_calibartion_from_camera_pair(int argc, char** argv)
{
int numBoards = 0; //minimum 4
int numCornersHor; //usually 9
int numCornersVer; //usually 6
float square_size; //in our case it is 0.025192
/*
char file_name[256];
printf("Enter number of corners along width (usually 9): ");
scanf("%d", &numCornersHor);
printf("Enter number of corners along height (usually 6): ");
scanf("%d", &numCornersVer);
printf("Enter number of boards(number of chess boards desired for calibration, minimum 4): ");
scanf("%d", &numBoards);
printf("square size im meter (0.25192): ");
scanf("%f", &square_size);
printf("file name to save calibration data (): ");
scanf("%s", &file_name);
printf("Press n to acquire next image");
*/
numBoards = 10;
numCornersHor=9;
numCornersVer=6;
square_size= 0.025192;
std::string file_name="my_stereo";
int numSquares = numCornersHor * numCornersVer;
cv::Size board_sz = cv::Size(numCornersHor, numCornersVer);
//we set it VideoCapture(1)
cv::VideoCapture capture_left = cv::VideoCapture(0);
cv::VideoCapture capture_right = cv::VideoCapture(1);
std::vector<std::vector<cv::Point3f> > object_points;
std::vector<std::vector<cv::Point2f> > image_points_left;
std::vector<std::vector<cv::Point2f> > image_points_right;
std::vector<cv::Mat> left_images, right_images;
cv::Mat tmp_img_left,tmp_img_right;
std::vector<cv::Point2f> corners_left,corners_right;
int successes=0;
cv::Mat image_left, image_right;
cv::Mat gray_image_left,gray_image_right;
capture_left >> image_left;
capture_right >> image_right;
std::vector<cv::Point3f> obj;
for(int j=0;j<numSquares;j++)
{
obj.push_back(cv::Point3f( (j%numCornersHor) *square_size,(j/numCornersHor *square_size ) ,0.0f));
// std::cout<<(j%numCornersHor) *square_size<<std::endl;
// std::cout<<(j/numCornersHor *square_size )<<std::endl;
// std::cout<<"--------------------------------------"<<std::endl;
}
while(successes<numBoards)
{
cv::cvtColor(image_left, gray_image_left, CV_BGR2GRAY);
cv::cvtColor(image_right, gray_image_right, CV_BGR2GRAY);
bool found_left = cv::findChessboardCorners(image_left, board_sz, corners_left, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS);
bool found_right = cv::findChessboardCorners(image_right, board_sz, corners_right, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS);
if(found_left && found_right)
{
cv::cornerSubPix(gray_image_left, corners_left, cv::Size(11, 11), cv::Size(-1, -1), cv::TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1));
cv::cornerSubPix(gray_image_right, corners_right, cv::Size(11, 11), cv::Size(-1, -1), cv::TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1));
tmp_img_left=image_left.clone();
tmp_img_right=image_right.clone();
drawChessboardCorners(tmp_img_left, board_sz, corners_left, found_left);
drawChessboardCorners(tmp_img_right, board_sz, corners_right, found_right);
}
if(tmp_img_left.empty())
imshow("left", image_left);
else
imshow("left", tmp_img_left);
if(tmp_img_right.empty())
imshow("right", image_right);
else
imshow("right", tmp_img_right);
int key=cv::waitKey(1);
if((char)key==(char)27)
return ;
if((char)key==(char)110 && found_left!=0 && found_right!=0 )
{
std::cout<<"Snap stored!"<<std::endl;
left_images.push_back(image_left.clone());
right_images.push_back(image_right.clone());
image_points_left.push_back(corners_left);
image_points_right.push_back(corners_right);
object_points.push_back(obj);
successes++;
if(successes>=numBoards)
break;
}
capture_right >> image_right;
capture_left >> image_left;
tmp_img_left.release();
tmp_img_right.release();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cv::FileStorage fs(file_name+std::string(".yml"), FileStorage::WRITE);
// fs<<"imagelist";
std::string image_file_name;
for(std::size_t i=0;i<left_images.size();i++)
{
image_file_name="left_image"+lexical_cast<std::string >(i)+std::string(".jpg");
cv::imwrite(image_file_name, left_images.at(i) );
// fs<<"\n";
// fs<<"\"" +image_file_name+"\"";
image_file_name="right_image"+lexical_cast<std::string >(i)+std::string(".jpg");
cv::imwrite(image_file_name,right_images.at(i));
// fs<<image_file_name;
}
// fs<<"imagelist";
// fs.release();
std::cout << "Writing list of files Done." << std::endl;
cv::Mat cameraMatrix[2], distCoeffs[2];
cameraMatrix[0] = cv::Mat::eye(3, 3, CV_64F);
cameraMatrix[1] = cv::Mat::eye(3, 3, CV_64F);
cv::Mat R, T, E, F;
double rms = cv::stereoCalibrate(object_points, image_points_left, image_points_right,
cameraMatrix[0], distCoeffs[0],
cameraMatrix[1], distCoeffs[1],
image_left.size(), R, T, E, F,
cv::TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, 1e-5),
CV_CALIB_FIX_ASPECT_RATIO +
CV_CALIB_ZERO_TANGENT_DIST +
CV_CALIB_SAME_FOCAL_LENGTH +
CV_CALIB_RATIONAL_MODEL +
CV_CALIB_FIX_K3 + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5);
std::cout << "done with RMS error=" << rms << std::endl;
std::cout << "Translation between two cameras:" << std::endl;
std::cout << T << std::endl;
std::cout << "Rotation between two cameras:" << std::endl;
std::cout << R << std::endl;
std::cout << "Essential Matrix (maps pose of cameras together)" << std::endl;
std::cout << E << std::endl;
std::cout << "Fundemental Matrix (maps point on camera image plane to the other camera image plane )" << std::endl;
std::cout << F << std::endl;
}
/***************************************Reading image from file ******************************************/
void stereo_calibration_from_file(int argc, char ** argv)
{
std::vector<std::string> imagelist;
//std::string path_to_image_list_file="stereo_calib.xml";
std::string path_to_image_list_file=argv[1];
// std::string path_to_image_list_file="../images/stereo_calibration/stereo_calib.xml";
std::string path=path_to_image_list_file.substr(0,path_to_image_list_file.find_last_of("/"))+"/";
readStringList(path_to_image_list_file, imagelist);
float square_size;
cv::Size boardSize;
int height, width;
height=6;
width=9;
boardSize = cv::Size(width, height);
square_size=0.025;
std::vector<std::vector<cv::Point2f> > left_imagePoints, right_imagePoints;
std::vector<std::vector<cv::Point3f> > objectPoints;
cv::Size imageSize;
std::vector<std::string> good_left_imageList,good_right_imageList;
std::vector<cv::Point3f> obj;
int numSquares=width*height;
for(int j=0;j<numSquares;j++)
{
obj.push_back(cv::Point3f( (j%width) *square_size,(j/width *square_size ) ,0.0f));
// std::cout<< (j%width) <<","<<(j/width) <<std::endl;
}
bool found = false;
std::string filename;
std::vector<cv::Point2f> corners;
cv::Mat image_gray ,img;
for(std::size_t i = 0; i < imagelist.size() ; i++ )
{
corners.clear();
filename=imagelist.at(i);
img = cv::imread(imagelist.at(i));
imageSize = img.size();
found=cv::findChessboardCorners(img,boardSize,corners,CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE);
if(found)
{
cv::cvtColor(img,image_gray,cv::COLOR_RGB2GRAY);
cv::cornerSubPix(image_gray,corners, cv::Size(11, 11), cv::Size(-1, -1), cv::TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1));
if(filename.find("left")!=std::string::npos)
{
std::cout<<"L" <<std::endl;
left_imagePoints.push_back(corners);
objectPoints.push_back(obj);
}
if(filename.find("right")!=std::string::npos)
{
std::cout<<"R" <<std::endl;
right_imagePoints.push_back(corners);
}
}
cv::drawChessboardCorners(image_gray,boardSize,corners,found);
cv::imshow("corners", image_gray);
char c = (char)cv::waitKey(500);
if( c == 27 || c == 'q' || c == 'Q' ) //Allow ESC to quit
exit(-1);
}
cv::Mat left_cameraMatrix, right_cameraMatrix, left_distCoeffs,right_distCoeffs;
left_cameraMatrix = cv::Mat::eye(3, 3, CV_64F);
right_cameraMatrix = cv::Mat::eye(3, 3, CV_64F);
cv::Mat R, T, E, F;
double rms = cv::stereoCalibrate(objectPoints, left_imagePoints, right_imagePoints,
left_cameraMatrix, left_distCoeffs,
right_cameraMatrix, right_distCoeffs,
imageSize, R, T, E, F,
cv::TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, 1e-5),
CV_CALIB_FIX_ASPECT_RATIO +
CV_CALIB_ZERO_TANGENT_DIST +
CV_CALIB_SAME_FOCAL_LENGTH +
CV_CALIB_RATIONAL_MODEL +
CV_CALIB_FIX_K3 + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5);
std::cout << "done with RMS error=" << rms << std::endl;
std::cout << "Translation between two cameras:" << std::endl;
std::cout << T << std::endl;
std::cout << "Rotation between two cameras:" << std::endl;
std::cout << R << std::endl;
std::cout << "Essential Matrix:" << std::endl;
std::cout << E << std::endl;
std::cout << "Fundemental Matrix:" << std::endl;
std::cout << F << std::endl;
int number_of_left_image=left_imagePoints.size();
std::vector<cv::Vec3f> left_lines, right_lines;
double err = 0;
int npoints = 0;
for(int i=0;i<number_of_left_image;i++)
{
int number_of_corners=left_imagePoints.at(0).size();
cv::Mat left_image_cornor_points=cv::Mat(left_imagePoints.at(i));
cv::undistortPoints(left_image_cornor_points, left_image_cornor_points, left_cameraMatrix, left_distCoeffs, cv::Mat(), left_cameraMatrix);
/*
Every point in first image is a line in the second image, so here we
for every chessboard corner point we find the epipolar line in the right image
the lines are stored in right_lines in the form of ax+by+cz=0 so
for example for the first corner point
right_lines[0][0] is a
right_lines[0][1] is b
right_lines[0][2] is c
These are cordinate of third chessboard corner in the sixth left image
left_imagePoints[5][2].x
left_imagePoints[5][2].y
so this should be zero:
right_lines[0][0]*left_imagePoints[5][2].x
+
left_imagePoints[5][2].y*right_lines[0][1]
+
right_lines[0][2]
*/
cv::computeCorrespondEpilines(left_image_cornor_points, 1, F, right_lines);
cv::Mat right_image_cornor_points=cv::Mat(right_imagePoints.at(i));
cv::undistortPoints(right_image_cornor_points, right_image_cornor_points, right_cameraMatrix, right_distCoeffs, cv::Mat(), right_cameraMatrix);
cv::computeCorrespondEpilines(right_image_cornor_points, 2, F, left_lines);
for( int j = 0; j < number_of_corners; j++ )
{
double errij = fabs(left_imagePoints[i][j].x*left_lines[j][0] +
left_imagePoints[i][j].y*left_lines[j][1] + left_lines[j][2]) +
fabs(right_imagePoints[i][j].x*right_lines[j][0] +
right_imagePoints[i][j].y*right_lines[j][1] + right_lines[j][2]);
err += errij;
}
npoints += number_of_corners;
}
std::cout << "total reprojection err = " << err<< std::endl;
std::cout << "average reprojection err = " << err/npoints << std::endl;
// save intrinsic parameters
cv::FileStorage fs(path+"intrinsics.yml", CV_STORAGE_WRITE);
if( fs.isOpened() )
{
fs << "M1" << left_cameraMatrix << "D1" << left_distCoeffs <<
"M2" << right_cameraMatrix << "D2" << right_distCoeffs;
fs.release();
}
else
std::cout << "Error: can not save the intrinsic parameters\n";
cv::Mat R1, R2, P1, P2, Q;
cv::Rect validRoi[2];
cv::stereoRectify(left_cameraMatrix, left_distCoeffs,
right_cameraMatrix, right_distCoeffs,
imageSize, R, T, R1, R2, P1, P2, Q,
cv::CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[0], &validRoi[1]);
fs.open(path+"extrinsics.yml", CV_STORAGE_WRITE);
if( fs.isOpened() )
{
fs << "R" << R << "T" << T << "R1" << R1 << "R2" << R2 << "P1" << P1 << "P2" << P2 << "Q" << Q;
fs.release();
}
else
std::cout << "Error: can not save the extrinsic parameters\n";
// OpenCV can handle left-right
// or up-down camera arrangements
bool isVerticalStereo = fabs(P2.at<double>(1, 3)) > fabs(P2.at<double>(0, 3));
cv::Mat left_rmap_x,left_rmap_y, right_rmap_x, right_rmap_y;
/*
// IF BY CALIBRATED (BOUGUET'S METHOD)
if( useCalibrated )
{
// we already computed everything
}
// OR ELSE HARTLEY'S METHOD
else
// use intrinsic parameters of each camera, but
// compute the rectification transformation directly
// from the fundamental matrix
{
vector<Point2f> allimgpt[2];
for( k = 0; k < 2; k++ )
{
for( i = 0; i < nimages; i++ )
std::copy(imagePoints[k][i].begin(), imagePoints[k][i].end(), back_inserter(allimgpt[k]));
}
F = findFundamentalMat(Mat(allimgpt[0]), Mat(allimgpt[1]), FM_8POINT, 0, 0);
Mat H1, H2;
stereoRectifyUncalibrated(Mat(allimgpt[0]), Mat(allimgpt[1]), F, imageSize, H1, H2, 3);
R1 = cameraMatrix[0].inv()*H1*cameraMatrix[0];
R2 = cameraMatrix[1].inv()*H2*cameraMatrix[1];
P1 = cameraMatrix[0];
P2 = cameraMatrix[1];
}
*/
//Precompute maps for cv::remap()
cv::initUndistortRectifyMap(left_cameraMatrix, left_distCoeffs, R1, P1, imageSize, CV_16SC2, left_rmap_x, left_rmap_y);
cv::initUndistortRectifyMap(right_cameraMatrix, right_distCoeffs, R2, P2, imageSize, CV_16SC2, right_rmap_x, right_rmap_y);
//cv::stereoRectifyUncalibrated()
std::string rectified_file_path;
for(std::size_t i=0;i<imagelist.size();i++)
{
filename=imagelist.at(i);
cv::Mat img = cv::imread(filename, 0), rectified_img ;
if(filename.find("left")!=std::string::npos)
{
std::cout<<"LL" <<std::endl;
cv::remap(img, rectified_img, left_rmap_x, left_rmap_y, CV_INTER_LINEAR);
}
if(filename.find("right")!=std::string::npos)
{
std::cout<<"RR" <<std::endl;
cv::remap(img, rectified_img, right_rmap_x, right_rmap_y, CV_INTER_LINEAR);
}
rectified_file_path=filename.insert(filename.find_last_of("/")+1, std::string("rect_") );
// std::cout<< <<std::endl;
cv::imwrite(rectified_file_path,rectified_img);
}
}
//undistort -> after camera calibration we can remove the radial and tangential distortion
//rectify -> rectifing images it is the process that as if the two images taken with parallel image plane that are align
//disparity
/*
stereo rectifi cation is the process of “correcting” the individual images so that they appear as if they had been taken by
two cameras with row-aligned image planes -> stereo solution reduce to search
*/
void image_rectification_test()
{
}
/*
Stereo calibration is the process of computing the geometrical relationship between the two cameras in space.
*/
void stereo_calibration()
{
}
//http://wiki.ros.org/stereo_image_proc/Tutorials/ChoosingGoodStereoParameters
//http://wiki.ros.org/stereo_image_proc#stereo_image_proc-1
//http://wiki.ros.org/stereo_image_proc#stereo_image_proc-1
//Bouguet’s algorithm
void stereoRectify_example()
{
}
//Hartley’s algorithm
void stereoRectifyUncalibrated_example()
{
// cv::stereoRectifyUncalibrated() -> when we use chesbaord i.e
// cv::initUndistortRectifyMap() -> when we only have correspon
}
void initUndistortRectifyMap_example()
{
}
//Pollefeys calibartion
int main(int argc, char ** argv)
{
char* n_argv[] = { "stereo_calibration_example", "../images/stereo_calibration/stereo_calib.xml"};
int length = sizeof(n_argv)/sizeof(n_argv[0]);
argc=length;
argv = n_argv;
stereo_calibration_from_file( argc, argv);
}
| 31.325823
| 161
| 0.614495
|
behnamasadi
|
ac169641572830604d2fb8fe1f3781c065eaa214
| 811
|
hxx
|
C++
|
src/NodoElemento.hxx
|
taleroangel/ProyeccionesEDD
|
d246dc22776fca09b2a36c82b3db682f3af3a155
|
[
"MIT"
] | null | null | null |
src/NodoElemento.hxx
|
taleroangel/ProyeccionesEDD
|
d246dc22776fca09b2a36c82b3db682f3af3a155
|
[
"MIT"
] | null | null | null |
src/NodoElemento.hxx
|
taleroangel/ProyeccionesEDD
|
d246dc22776fca09b2a36c82b3db682f3af3a155
|
[
"MIT"
] | null | null | null |
#ifndef NODOELEMENTO_HXX
#define NODOELEMENTO_HXX
#include <vector>
#include "CodigoElemento.hxx"
#include "NodoCodificacion.hxx"
template <typename T>
struct NodoElemento : public NodoCodificacion<T> {
T dato;
NodoElemento<T>() = default;
NodoElemento<T>(T elemento, freq_t frecuencia);
std::vector<CodigoElemento<T>> codigos_elementos(
std::string codigo) override;
};
template <typename T>
inline NodoElemento<T>::NodoElemento(T elemento, freq_t frecuencia)
: NodoCodificacion<T>{frecuencia}, dato{elemento} {}
template <typename T>
inline std::vector<CodigoElemento<T>> NodoElemento<T>::codigos_elementos(
std::string codigo) {
return std::vector<CodigoElemento<T>>{
CodigoElemento<T>{this->dato, this->frecuencia, codigo}};
}
#endif // NODOELEMENTO_HXX
| 25.34375
| 73
| 0.727497
|
taleroangel
|
ac25801ccef67dcdf6a3c9db98319da2d360da8e
| 2,741
|
cpp
|
C++
|
codeforces/1515C.cpp
|
sgrade/cpptest
|
84ade6ec03ea394d4a4489c7559d12b4799c0b62
|
[
"MIT"
] | null | null | null |
codeforces/1515C.cpp
|
sgrade/cpptest
|
84ade6ec03ea394d4a4489c7559d12b4799c0b62
|
[
"MIT"
] | null | null | null |
codeforces/1515C.cpp
|
sgrade/cpptest
|
84ade6ec03ea394d4a4489c7559d12b4799c0b62
|
[
"MIT"
] | null | null | null |
// C. Phoenix and Towers
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <numeric>
#include <set>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, m, x;
cin >> n >> m >> x;
int tmp;
// <height, count_of_such_heights>
map<int, int, greater<int>> mp;
// original indexes of the heights
multimap<int, int> original_indexes;
for (int i = 0; i < n; ++i) {
cin >> tmp;
++mp[tmp];
original_indexes.insert(pair<int, int>(tmp, i));
}
bool ans = true;
vector<int> output(n);
if (m > 1) {
// pair<int, int>: first is sum, second is index in heights
multiset<pair<int, int>> sums;
for (int i = 0; i < m; ++i) {
sums.insert(pair<int, int> (0, i));
}
multiset<pair<int, int>>::iterator sums_it;
vector<vector<int>> heights(m);
map<int, int, greater<int>>::iterator it = mp.begin();
// index of related vectors
int mn_sum = 0, mn_idx = 0;
for (int i = 0; i < n; ++i) {
if (it->second == 0) {
++it;
}
mn_sum = sums.begin()->first;
mn_idx = sums.begin()->second;
mn_sum += it->first;
sums.erase(sums.begin());
sums.insert(pair<int, int>(mn_sum, mn_idx));
heights[mn_idx].push_back(it->first);
--it->second;
}
mn_sum = sums.begin()->first;
multiset<pair<int, int>>::reverse_iterator sums_rit = sums.rbegin();
int mx_sum = sums_rit->first;
if (mx_sum - mn_sum > x) {
ans = false;
}
else {
int original_idx;
map<int, int>::iterator original_idx_it;
for (int i = 0; i < m; ++i) {
for (auto &height: heights[i]) {
original_idx_it = original_indexes.find(height);
original_idx = original_idx_it->second;
output[original_idx] = i + 1;
original_indexes.erase(original_idx_it);
}
}
}
}
else {
for (int i = 0; i < n; ++i) {
output[i] = 1;
}
}
cout << (ans ? "YES" : "NO") << endl;
if (ans) {
for (auto &el: output) {
cout << el << ' ';
}
cout << endl;
}
}
return 0;
}
| 26.104762
| 80
| 0.41846
|
sgrade
|
ac26ace285bf1b9861c6eeb28f6f1d014eb74d1a
| 6,923
|
cpp
|
C++
|
src/Public/CaptureCpp/CaptureCpp.cpp
|
zpublic/cozy
|
dde5f2bcf7482e2e5042f9e51266d9fd272e1456
|
[
"WTFPL"
] | 48
|
2015-04-11T13:25:45.000Z
|
2022-03-28T08:27:40.000Z
|
src/Public/CaptureCpp/CaptureCpp.cpp
|
ToraiRei/cozy
|
c8197d9c6531f1864d6063ae149db53b669241f0
|
[
"WTFPL"
] | 4
|
2016-04-06T09:30:57.000Z
|
2022-02-26T01:21:18.000Z
|
src/Public/CaptureCpp/CaptureCpp.cpp
|
ToraiRei/cozy
|
c8197d9c6531f1864d6063ae149db53b669241f0
|
[
"WTFPL"
] | 33
|
2015-06-03T10:06:54.000Z
|
2020-12-15T00:50:28.000Z
|
// CaptureCpp.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "CaptureCpp.h"
CAPTURECPP_API CCaptureCpp CcaptureCppInstance;
CCaptureCpp::CCaptureCpp(void)
{
}
void CCaptureCpp::GetWindowSize(HWND hwnd, LPLONG x, LPLONG y)
{
RECT rect;
::GetWindowRect(hwnd, &rect);
*x = rect.right - rect.left;;
*y = rect.bottom - rect.top;
}
WORD CCaptureCpp::GetClrBits(WORD wInput)
{
WORD cClrBits = wInput;
if (cClrBits == 1)
cClrBits = 1;
else if (cClrBits <= 4)
cClrBits = 4;
else if (cClrBits <= 8)
cClrBits = 8;
else if (cClrBits <= 16)
cClrBits = 16;
else if (cClrBits <= 24)
cClrBits = 24;
else cClrBits = 32;
return cClrBits;
}
bool CCaptureCpp::GetWindowHDC(HWND *lpHwnd, HDC *lpHdc)
{
if (lpHwnd != nullptr && lpHdc != nullptr)
{
*lpHwnd = ::GetDesktopWindow();
*lpHdc = ::GetWindowDC(*lpHwnd);
return true;
}
return false;
}
DWORD CCaptureCpp::GetCaptureDataSize(HWND hwnd, HDC hdc, int x, int y, int width, int height, LPBITMAP lpBitmap)
{
POINT size;
if (width == 0 && height == 0)
{
GetWindowSize(hwnd, &(size.x), &(size.y));
}
else
{
size.x = width;
size.y = height;
}
HDC memHdc = ::CreateCompatibleDC(hdc);
HBITMAP hBmp = ::CreateCompatibleBitmap(hdc, size.x, size.y);
::SelectObject(memHdc, hBmp);
BITMAP bmp;
WORD cClrBits;
if (!::GetObject(hBmp, sizeof(BITMAP), (LPVOID)&bmp))
{
return 0;
}
cClrBits = GetClrBits((WORD)(bmp.bmPlanes * bmp.bmBitsPixel));
*lpBitmap = bmp;
return (bmp.bmWidth + 7) / 8 * bmp.bmHeight * cClrBits + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + (1 << cClrBits) *sizeof(RGBQUAD);
}
DWORD CCaptureCpp::GetCaptureData(HWND hwnd, HDC hdc, int x, int y, int width, int height, LPBYTE lpResult)
{
POINT size;
if (width == 0 && height == 0)
{
GetWindowSize(hwnd, &(size.x), &(size.y));
}
else
{
size.x = width;
size.y = height;
}
HDC memHdc = ::CreateCompatibleDC(hdc);
HBITMAP hBmp = ::CreateCompatibleBitmap(hdc, size.x, size.y);
::SelectObject(memHdc, hBmp);
::BitBlt(memHdc, 0, 0, size.x, size.y, hdc, x, y, SRCCOPY);
BITMAP bmp;
PBITMAPINFO pbmi;
WORD cClrBits;
if (!::GetObject(hBmp, sizeof(BITMAP), (LPVOID)&bmp))
{
return 0;
}
cClrBits = GetClrBits((WORD)(bmp.bmPlanes * bmp.bmBitsPixel));
if (cClrBits != 24)
{
pbmi = (PBITMAPINFO)::LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * (1 << cClrBits));
}
else
{
pbmi = (PBITMAPINFO)::LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER));
}
pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pbmi->bmiHeader.biWidth = bmp.bmWidth;
pbmi->bmiHeader.biHeight = bmp.bmHeight;
pbmi->bmiHeader.biPlanes = bmp.bmPlanes;
pbmi->bmiHeader.biBitCount = bmp.bmBitsPixel;
if (cClrBits < 24)
pbmi->bmiHeader.biClrUsed = (1 << cClrBits);
pbmi->bmiHeader.biCompression = BI_RGB;
pbmi->bmiHeader.biSizeImage = (pbmi->bmiHeader.biWidth + 7) / 8 * pbmi->bmiHeader.biHeight * cClrBits;
pbmi->bmiHeader.biClrImportant = 0;
::GetDIBits(memHdc, hBmp, 0, (WORD)(WORD)pbmi->bmiHeader.biHeight, lpResult, pbmi, DIB_RGB_COLORS);
::LocalFree(pbmi);
return 1;
}
DWORD CCaptureCpp::AppendBitmapHeader(LPBYTE lpResult, LPBITMAP lpBitmap)
{
WORD cClrBits = GetClrBits((WORD)(lpBitmap->bmPlanes * lpBitmap->bmBitsPixel));
PBITMAPINFO pbmi;
if (cClrBits != 24)
{
pbmi = (PBITMAPINFO)::LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * (1 << cClrBits));
}
else
{
pbmi = (PBITMAPINFO)::LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER));
}
pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pbmi->bmiHeader.biWidth = lpBitmap->bmWidth;
pbmi->bmiHeader.biHeight = lpBitmap->bmHeight;
pbmi->bmiHeader.biPlanes = lpBitmap->bmPlanes;
pbmi->bmiHeader.biBitCount = lpBitmap->bmBitsPixel;
if (cClrBits < 24)
pbmi->bmiHeader.biClrUsed = (1 << cClrBits);
pbmi->bmiHeader.biCompression = BI_RGB;
pbmi->bmiHeader.biSizeImage = (pbmi->bmiHeader.biWidth + 7) / 8 * pbmi->bmiHeader.biHeight * cClrBits;
pbmi->bmiHeader.biClrImportant = 0;
BITMAPFILEHEADER hdr;
PBITMAPINFOHEADER pbih;
pbih = (PBITMAPINFOHEADER)pbmi;
hdr.bfType = 0x4d42;
hdr.bfSize = (DWORD)(sizeof(BITMAPFILEHEADER) + pbih->biSize + pbih->biClrUsed * sizeof(RGBQUAD) + pbih->biSizeImage);
hdr.bfReserved1 = 0;
hdr.bfReserved2 = 0;
hdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + pbih->biSize + pbih->biClrUsed * sizeof(RGBQUAD);
DWORD offset = 0;
::CopyMemory(lpResult + offset, (LPVOID)&hdr, sizeof(BITMAPFILEHEADER));
offset += sizeof(BITMAPFILEHEADER);
::CopyMemory(lpResult + offset, (LPVOID)pbih, sizeof(BITMAPINFOHEADER) + pbih->biClrUsed * sizeof(RGBQUAD));
offset += sizeof(BITMAPINFOHEADER) + pbih->biClrUsed * sizeof(RGBQUAD);
::LocalFree(pbmi);
return offset;
}
CAPTURECPP_API int GetDesktopNum(void)
{
int dspNum = ::GetSystemMetrics(SM_CMONITORS);
return dspNum;
}
int gMonitorIndex = 0;
int gMonitorCount = 0;
RECT gMonitorSize[10];
BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
{
if (gMonitorIndex < 10)
{
gMonitorSize[gMonitorIndex] = *lprcMonitor;
gMonitorIndex++;
gMonitorCount++;
}
return TRUE;
}
CAPTURECPP_API bool GetDesktopSize(int nIndex, int* w, int* h)
{
gMonitorIndex = 0;
gMonitorCount = 0;
::EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, 0);
if (nIndex < gMonitorCount)
{
*w = gMonitorSize[nIndex].right - gMonitorSize[nIndex].left;
*h = gMonitorSize[nIndex].bottom - gMonitorSize[nIndex].top;
return true;
}
return false;
}
CAPTURECPP_API DWORD AppendBitmapHeader(LPBYTE lpData, LPBITMAP lpBitmap)
{
return CCaptureCppCppInstance.AppendBitmapHeader(lpData, lpBitmap);
}
CAPTURECPP_API bool GetWindowHDC(HWND *lpHwnd, HDC *lpHdc)
{
return CCaptureCppCppInstance.GetWindowHDC(lpHwnd, lpHdc);
}
CAPTURECPP_API DWORD GetCaptureData(HWND hwnd, HDC hdc, int x, int y, int width, int height, LPBYTE lpResult)
{
return CCaptureCppCppInstance.GetCaptureData(hwnd, hdc, x, y, width, height, lpResult);
}
CAPTURECPP_API DWORD GetCaptureDataSize(HWND hwnd, HDC hdc, int x, int y, int width, int height, LPBITMAP lpBitmap)
{
return CCaptureCppCppInstance.GetCaptureDataSize(hwnd, hdc, x, y, width, height, lpBitmap);
}
CAPTURECPP_API void GetWindowSize(HWND hwnd, LONG *x, LONG *y)
{
return CCaptureCppCppInstance.GetWindowSize(hwnd, x, y);
}
| 28.966527
| 148
| 0.648563
|
zpublic
|
ac29e77fee02fbba5e1cce28204aa9374c07145d
| 453
|
cpp
|
C++
|
Source/GCE/Game/Mover/BishopMoverComponent.cpp
|
ssapo/GCE
|
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
|
[
"MIT"
] | 2
|
2019-07-28T13:30:14.000Z
|
2019-11-22T08:14:28.000Z
|
Source/GCE/Game/Mover/BishopMoverComponent.cpp
|
ssapo/GCE
|
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
|
[
"MIT"
] | null | null | null |
Source/GCE/Game/Mover/BishopMoverComponent.cpp
|
ssapo/GCE
|
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
|
[
"MIT"
] | 1
|
2019-07-07T13:39:08.000Z
|
2019-07-07T13:39:08.000Z
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "BishopMoverComponent.h"
UBishopMoverComponent::UBishopMoverComponent()
{
MoveDirections = {
FIntPoint(1, 1),
FIntPoint(-1, 1),
FIntPoint(-1, -1),
FIntPoint(1, -1)
};
AttackDirections = {
FIntPoint(1, 1),
FIntPoint(-1, 1),
FIntPoint(-1, -1),
FIntPoint(1, -1)
};
bPercistance = true;
bHasSpecialMove = false;
bHasTeamDirection = false;
}
| 17.423077
| 78
| 0.682119
|
ssapo
|
ac34978eb29682dc1962c2d6bea27229ee9fbb64
| 602
|
cpp
|
C++
|
RealmLib/Packets/Client/EnterArena.cpp
|
SometimesRain/realmnet
|
76ead08b4a0163a05b65389e512942a620331256
|
[
"MIT"
] | 10
|
2018-11-25T21:59:43.000Z
|
2022-01-09T22:41:52.000Z
|
RealmLib/Packets/Client/EnterArena.cpp
|
SometimesRain/realmnet
|
76ead08b4a0163a05b65389e512942a620331256
|
[
"MIT"
] | 1
|
2018-11-28T12:59:59.000Z
|
2018-11-28T12:59:59.000Z
|
RealmLib/Packets/Client/EnterArena.cpp
|
SometimesRain/realmnet
|
76ead08b4a0163a05b65389e512942a620331256
|
[
"MIT"
] | 6
|
2018-12-28T22:34:13.000Z
|
2021-10-16T10:17:17.000Z
|
#include "stdafx.h"
#include <GameData/Constants.h>
#include <GameData/TypeManager.h>
#include "Packets/PacketWriter.h"
#include "Packets/PacketReader.h"
#include <Packets/EnterArena.h>
EnterArena::EnterArena(int currency)
: currency(currency)
{
}
EnterArena::EnterArena(byte* data)
{
PacketReader r(data);
r.read(currency);
}
void EnterArena::emplace(byte* buffer) const
{
PacketWriter w(buffer, size(), TypeManager::typeToId[PacketType::EnterArena]);
w.write(currency);
}
int EnterArena::size() const
{
return 9;
}
String EnterArena::toString() const
{
return String("ENTERARENA");
}
| 15.842105
| 79
| 0.734219
|
SometimesRain
|
ac3c95a1375cbc236fc8821d5baa34156e8b71cf
| 3,810
|
hpp
|
C++
|
SDE.hpp
|
jetpotion/MonteCarloOptionPricer
|
0024c9c900d1c968fca8946aa438ba07453272d8
|
[
"MIT"
] | 2
|
2020-12-13T00:07:01.000Z
|
2021-01-14T00:40:33.000Z
|
SDE.hpp
|
jetpotion/MonteCarloOptionPricer
|
0024c9c900d1c968fca8946aa438ba07453272d8
|
[
"MIT"
] | null | null | null |
SDE.hpp
|
jetpotion/MonteCarloOptionPricer
|
0024c9c900d1c968fca8946aa438ba07453272d8
|
[
"MIT"
] | null | null | null |
#ifndef SDE_HPP
#define SDE_HPP
//THE VARIOUS TYPES OF SDE
namespace MonteCarloOptionApplication
{
namespace ISde
{
class SDE
{
public:
SDE() = default;
SDE(const SDE& source) = default;
SDE& operator=(const SDE& source);
virtual ~SDE() = default; //Destructor
[[nodiscard]] virtual double Drift(double x, double t) const noexcept = 0; //Drift
[[nodiscard]] virtual double Diffusion(double x, double t) const noexcept = 0; //Diffusion term
[[nodiscard]] virtual double DriftedCorrected(double x, double t, double b) const noexcept = 0; //Drif correcte
[[nodiscard]] virtual double DiffusionDerivative(double x, double t) const noexcept= 0; //Diffusion Derivative
[[nodiscard]] virtual void Expiry(double exp) noexcept= 0; //Expiry setter
[[nodiscard]] virtual double Expiry() const noexcept= 0; //Expiry getter ;
[[nodiscard]] virtual void InitialCondition(double initial_price) noexcept = 0; //Initial condition SETTER
[[nodiscard]] virtual double InitialCondition() const noexcept = 0; //Returns the initial stock price
};
//Classical GBM SDE
class GBM : public SDE
{
private:
double mu; //The Drift
double vol; //The volatility
double d; //The dividend yield
double ic; //StockPrice
double exp; //Expiry
public:
constexpr GBM(double driftCoefficient, double diffusionCoefficient, double dividendYield, double initialCondition,
double expiry) noexcept; //Overloaded constructor
constexpr GBM(const GBM& source);
GBM& operator=(const GBM& source);
~GBM() override = default ; //Overrided destructor
[[nodiscard]] constexpr double Drift(double x, double t) const noexcept override; //Drift
[[nodiscard]] constexpr double Diffusion(double x, double t) const noexcept override; //Diffusion term
[[nodiscard]] constexpr double DriftedCorrected(double x, double t, double b) const noexcept override; //Drif correcte
[[nodiscard]] constexpr double DiffusionDerivative(double x, double t) const noexcept override; //Diffusion Derivative
[[nodiscard]] constexpr void Expiry(double exp) noexcept override; //Expiry setter
[[nodiscard]] constexpr double Expiry() const noexcept override; //Expiry getter ;
[[nodiscard]] constexpr void InitialCondition(double initial_price) noexcept override; //Initial condition SETTER
[[nodiscard]] constexpr double InitialCondition() const noexcept override; //Returns the initial stock price
};
//The elastacity variance model of the SDE
class CEV : public SDE
{
private:
double mu; //The Drift
double vol; //The volatility
double d; //The dividend yield
double ic; //StockPrice
double exp; //Expiry
double beta;
public:
constexpr CEV(double driftCoefficient, double diffusionCoefficient, double dividendYield, double initialCondition,
double expiry, double beta) noexcept; //Overloaded constructor
constexpr CEV(const CEV& source) noexcept;
CEV& operator=(const CEV& source);
~CEV() override = default; //Overrided destructor
[[nodiscard]] double Drift(double x, double t) const noexcept override; //Drift
[[nodiscard]] double Diffusion(double x, double t) const noexcept override; //Diffusion term
[[nodiscard]] double DriftedCorrected(double x, double t, double b) const noexcept override; //Drif correcte
[[nodiscard]] double DiffusionDerivative(double x, double t) const noexcept override; //Diffusion Derivative
[[nodiscard]] void Expiry(double exp) noexcept override; //Expiry setter
[[nodiscard]] double Expiry() const override; //Expiry getter ;
[[nodiscard]] void InitialCondition(double initial_price) noexcept override; //Initial condition SETTER
[[nodiscard]] double InitialCondition() const noexcept override; //Returns the initial stock price
};
}
}
#endif
| 48.227848
| 121
| 0.732021
|
jetpotion
|
ac4044985b5b2bef8e0f296ca8f4a65ec312e6b5
| 1,431
|
cpp
|
C++
|
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32746G-Discovery/Demonstrations/TouchGFX/Gui/target/GPIO.cpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | null | null | null |
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32746G-Discovery/Demonstrations/TouchGFX/Gui/target/GPIO.cpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | null | null | null |
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32746G-Discovery/Demonstrations/TouchGFX/Gui/target/GPIO.cpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | null | null | null |
/**
******************************************************************************
* This file is part of the TouchGFX 4.10.0 distribution.
*
* @attention
*
* Copyright (c) 2018 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
#include <touchgfx/hal/GPIO.hpp>
#include "stm32746g_discovery.h"
using namespace touchgfx;
static bool ledState;
// The STM32746G-Discovery board only supports a single LED.
// This GPIO utility links that LED to GPIO::RENDER_TIME.
static bool isRenderTime(GPIO::GPIO_ID id)
{
return id == GPIO::RENDER_TIME;
}
void GPIO::init()
{
BSP_LED_Init(LED_GREEN);
clear(GPIO::RENDER_TIME);
}
void GPIO::set(GPIO::GPIO_ID id)
{
if (isRenderTime(id))
{
ledState = 1;
BSP_LED_On(LED_GREEN);
}
}
void GPIO::clear(GPIO::GPIO_ID id)
{
if (isRenderTime(id))
{
ledState = 0;
BSP_LED_Off(LED_GREEN);
}
}
void GPIO::toggle(GPIO::GPIO_ID id)
{
if (isRenderTime(id))
{
BSP_LED_Toggle(LED_GREEN);
}
}
bool GPIO::get(GPIO::GPIO_ID id)
{
if (isRenderTime(id))
{
return ledState;
}
return 0;
}
| 19.337838
| 80
| 0.570929
|
ramkumarkoppu
|
ac43229a8a489dccf391abb2a9f6c2421bee788a
| 1,436
|
hpp
|
C++
|
src/api/cpp/include/OISkeleton.hpp
|
jacobnb/OpenISS
|
028b315953b27dd3acc449efd5cfb485805a14b3
|
[
"Apache-2.0"
] | null | null | null |
src/api/cpp/include/OISkeleton.hpp
|
jacobnb/OpenISS
|
028b315953b27dd3acc449efd5cfb485805a14b3
|
[
"Apache-2.0"
] | null | null | null |
src/api/cpp/include/OISkeleton.hpp
|
jacobnb/OpenISS
|
028b315953b27dd3acc449efd5cfb485805a14b3
|
[
"Apache-2.0"
] | 1
|
2018-11-17T19:33:31.000Z
|
2018-11-17T19:33:31.000Z
|
//
// OISkeleton.hpp
// Skeleton
//
// Created by Haotao Lai on 2018-08-08.
// Created by Jashanjot Singh on 2018-07-22.
//
#ifndef OPENISS_OISKELETON_H
#define OPENISS_OISKELETON_H
#include <unordered_map>
#include <memory>
#include <vector>
#include "OIEnum.hpp"
#include "OITracker.hpp"
#include "OIFrame.hpp"
using std::unordered_map;
using std::shared_ptr;
using std::vector;
namespace openiss
{
class OITracker;
/**
* Point of the skeleton joint (real world coordinate)
*/
class OISkeletonJoint {
public:
OISkeletonJoint(){};
OISkeletonJoint(float x, float y, float z, JointType type,
float row=-1.0f, float col=-1.0f);
JointType type;
float x, y, z; // real world coordinate
float row, col; // image coordinate
};
/**
* A map associates the JointType to the Joint
* JointType -> shared_ptr<SkeletonJoint>
*/
class OISkeleton
{
public:
shared_ptr<openiss::OISkeletonJoint> getJointByType(JointType type);
void addJointByType(JointType type, shared_ptr<OISkeletonJoint> jointPtr);
void drawToFrame(OIFrame *displayFrame, vector<JointType> &supportedJoints);
void mapWorld2Image(OITracker* tracker);
void setSkeletonState(bool isAvailable);
bool getSkeletonState() const;
private:
unordered_map<JointType, shared_ptr<OISkeletonJoint>, std::hash<int>> mJoints;
bool mIsSkeletonAvailable;
};
} // end of namespace
#endif //OPENISS_OISKELETON_H
| 22.793651
| 82
| 0.721448
|
jacobnb
|
ac44a7fc940a4ae2816883c6aaf7e69622258d7e
| 7,353
|
hpp
|
C++
|
artlib-cpp/include/srilakshmikanthanp/src/anixt_font.hpp
|
Thanus-MR/artlib
|
263c30701f36637ffad271c9c88e8d1aafdc2c2b
|
[
"MIT"
] | 1
|
2021-04-17T02:24:02.000Z
|
2021-04-17T02:24:02.000Z
|
artlib-cpp/include/srilakshmikanthanp/src/anixt_font.hpp
|
Thanus-MR/artlib
|
263c30701f36637ffad271c9c88e8d1aafdc2c2b
|
[
"MIT"
] | null | null | null |
artlib-cpp/include/srilakshmikanthanp/src/anixt_font.hpp
|
Thanus-MR/artlib
|
263c30701f36637ffad271c9c88e8d1aafdc2c2b
|
[
"MIT"
] | null | null | null |
///@file basic_font.hpp
/**
* Copyright (c) 2020 Sri Lakshmi Kanthan P
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#ifndef BASIC_FONT_HEADER
#define BASIC_FONT_HEADER
#include "anixt_config.hpp"
#include "filesystem"
#include "fstream"
#include "third_party/json/json.hpp"
#include "map"
/**
* @namespace srilakshmikanthanp
* @brief outer namespace
**/
namespace srilakshmikanthanp
{
/**
* @namespace art
* @brief contains art classes and functions
**/
namespace art
{
/**
* @struct basic_anixt_base_font
* @brief abstract class for font types that used
* by anixt class
* @tparam Anixtconfig type of anixt_config
**/
template <typename Anixtconfig>
struct basic_anixt_base_font
{
using anixt_config = Anixtconfig;
basic_anixt_base_font() = default;
basic_anixt_base_font( const basic_anixt_base_font & ) = default;
basic_anixt_base_font( basic_anixt_base_font && ) noexcept = default;
virtual ~basic_anixt_base_font() = default;
basic_anixt_base_font &operator=( const basic_anixt_base_font & ) = default;
basic_anixt_base_font &operator=( basic_anixt_base_font && ) noexcept = default;
/**
* @brief clears the contents
**/
virtual void clear() noexcept = 0;
/**
* @brief used to set font file, call this before
* any other operation.
* @param fp full path to font file
**/
virtual void set_font( const std::filesystem::path &fp ) = 0;
/**
* @brief used to get anixt config from font file
* @return anixt_config
**/
virtual anixt_config get_anixt_config() = 0;
/**
* @brief used to get key equivalent of anixt_letter
* from font
* @param key key letter
* @return anixt_letter
**/
virtual typename anixt_config::anixt_letter
operator()( typename anixt_config::char_type key ) = 0;
};
/**
* @class basic_anixt_json_font
* @brief This class reads font for anixt class
* from json file
* @tparam Anixtconfig type of anixt_config
**/
template <typename Anixtconfig>
class basic_anixt_json_font : public basic_anixt_base_font<Anixtconfig>
{
protected:
using base = basic_anixt_base_font<Anixtconfig>;
public:
using anixt_config = typename base::anixt_config;
private:
using char_type = typename base::anixt_config::char_type;
using size_type = typename base::anixt_config::size_type;
using traits_type = typename base::anixt_config::traits_type;
using string_type = typename base::anixt_config::string_type;
using shrink_type = typename base::anixt_config::shrink;
using anixt_letter = typename base::anixt_config::anixt_letter;
template <typename T>
using alloc_type = typename base::anixt_config::template alloc_type<T>;
using json_type = nlohmann::basic_json<std::map, std::vector,
string_type, bool, int64_t,
size_type, double, alloc_type>;
private:
/**
* @brief stores font file.
**/
json_type json_font;
/**
* @brief converts ascii character of std::string
* to anixt_config::string_type
**/
static string_type cvt( const std::string &str )
{
return string_type( str.begin(), str.end() );
}
public:
basic_anixt_json_font() = default;
basic_anixt_json_font( const basic_anixt_json_font & ) = default;
basic_anixt_json_font( basic_anixt_json_font && ) noexcept = default;
~basic_anixt_json_font() = default;
basic_anixt_json_font &operator=( const basic_anixt_json_font & ) = default;
basic_anixt_json_font &operator=( basic_anixt_json_font && ) noexcept = default;
/**
* @brief clears the contents
**/
void clear() noexcept override
{
this->json_font.clear();
}
/**
* @brief swap contents
* @param obj object to swap
**/
void swap( basic_anixt_json_font &obj )
{
using std::swap;
swap( this->json_font, obj.json_font );
}
/**
* @brief used to set font file, call this before
* any other operation.
* @param fp full path to font file
**/
void set_font( const std::filesystem::path &fp ) override
{
std::basic_ifstream<char_type, traits_type> font_file { fp };
if ( fp.extension() != ".json" )
{
throw std::runtime_error( "File should be json" );
}
if ( !font_file.is_open() )
{
throw std::runtime_error( "Unable to open file" );
}
font_file >> this->json_font;
}
/**
* @brief used to get anixt_config
* @return anixt_config
**/
anixt_config get_anixt_config() override
{
anixt_config ret;
ret.HardBlank = this->json_font[cvt( "anixt_config" )][cvt( "HardBlank" )]
.template get<size_type>();
ret.Height = this->json_font[cvt( "anixt_config" )][cvt( "Height" )]
.template get<size_type>();
ret.Shrink = this->json_font[cvt( "anixt_config" )][cvt( "Shrink" )]
.template get<shrink_type>();
return ret;
}
/**
* @brief used to get anixt_letter from font
* @param key key letter
* @return anixt_letter
**/
anixt_letter operator()( char_type key )
{
return this->json_font[cvt( "anixt_letter" )][string_type( 1, key )]
.template get<anixt_letter>();
}
};
/**
* @brief swap two anixt_config
* @param lhs object one to swap
* @param rhs object two to swap
**/
template <typename Anixtconfig>
void swap( basic_anixt_json_font<Anixtconfig> &lhs,
basic_anixt_json_font<Anixtconfig> &rhs ) noexcept
{
lhs.swap( rhs );
}
} // namespace art
} // namespace srilakshmikanthanp
#endif
| 33.884793
| 92
| 0.509452
|
Thanus-MR
|
ac45c8faca723e2e5e80e841e60b8dc687c2c893
| 4,951
|
cpp
|
C++
|
libskiwi/tail_calls_check.cpp
|
janm31415/skiwi
|
851a006c2964d527cc38b7a71f3e835b8dab52b5
|
[
"MIT"
] | 4
|
2020-10-06T14:09:13.000Z
|
2020-10-24T17:34:53.000Z
|
libskiwi/tail_calls_check.cpp
|
janm31415/skiwi
|
851a006c2964d527cc38b7a71f3e835b8dab52b5
|
[
"MIT"
] | null | null | null |
libskiwi/tail_calls_check.cpp
|
janm31415/skiwi
|
851a006c2964d527cc38b7a71f3e835b8dab52b5
|
[
"MIT"
] | null | null | null |
#include "tail_calls_check.h"
#include "visitor.h"
SKIWI_BEGIN
namespace
{
/*
A procedure call is called a tail call if it occurs in a tail position.
A tail position is defined recursively as follows:
- the body of a procedure is in tail position
- if a let expression is in tail position, then the body
of the let is in tail position
- if the condition expression (if test conseq altern) is in tail
position, then the conseq and altern branches are also in tail position.
- all other expressions are not in tail position.
*/
struct tail_calls_check : public base_visitor<tail_calls_check>
{
bool only_tails;
tail_calls_check() : only_tails(true)
{
}
virtual bool _previsit(Variable&)
{
return only_tails;
}
virtual bool _previsit(Begin&)
{
return only_tails;
}
virtual bool _previsit(FunCall& f)
{
if (!f.tail_position)
only_tails = false;
return only_tails;
}
virtual bool _previsit(If&)
{
return only_tails;
}
virtual bool _previsit(Lambda&)
{
return only_tails;
}
virtual bool _previsit(Let&)
{
return only_tails;
}
virtual bool _previsit(Literal&)
{
return only_tails;
}
virtual bool _previsit(PrimitiveCall&)
{
return only_tails;
}
virtual bool _previsit(ForeignCall&)
{
return only_tails;
}
virtual bool _previsit(Set&)
{
return only_tails;
}
};
struct tail_calls_check_helper
{
std::vector<Expression*> expressions;
bool only_tails;
tail_calls_check_helper()
{
only_tails = true;
}
void treat_expressions()
{
while (!expressions.empty())
{
Expression* p_expr = expressions.back();
expressions.pop_back();
Expression& e = *p_expr;
if (std::holds_alternative<Literal>(e))
{
}
else if (std::holds_alternative<Variable>(e))
{
}
else if (std::holds_alternative<Nop>(e))
{
}
else if (std::holds_alternative<Quote>(e))
{
}
else if (std::holds_alternative<Set>(e))
{
//Set& s = std::get<Set>(e);
expressions.push_back(&std::get<Set>(e).value.front());
}
else if (std::holds_alternative<If>(e))
{
for (auto rit = std::get<If>(e).arguments.rbegin(); rit != std::get<If>(e).arguments.rend(); ++rit)
expressions.push_back(&(*rit));
}
else if (std::holds_alternative<Begin>(e))
{
for (auto rit = std::get<Begin>(e).arguments.rbegin(); rit != std::get<Begin>(e).arguments.rend(); ++rit)
expressions.push_back(&(*rit));
}
else if (std::holds_alternative<PrimitiveCall>(e))
{
for (auto rit = std::get<PrimitiveCall>(e).arguments.rbegin(); rit != std::get<PrimitiveCall>(e).arguments.rend(); ++rit)
expressions.push_back(&(*rit));
}
else if (std::holds_alternative<ForeignCall>(e))
{
for (auto rit = std::get<ForeignCall>(e).arguments.rbegin(); rit != std::get<ForeignCall>(e).arguments.rend(); ++rit)
expressions.push_back(&(*rit));
}
else if (std::holds_alternative<Lambda>(e))
{
Lambda& l = std::get<Lambda>(e);
expressions.push_back(&l.body.front());
}
else if (std::holds_alternative<FunCall>(e))
{
FunCall& f = std::get<FunCall>(e);
if (!f.tail_position)
{
only_tails = false;
break;
}
expressions.push_back(&std::get<FunCall>(e).fun.front());
for (auto rit = std::get<FunCall>(e).arguments.rbegin(); rit != std::get<FunCall>(e).arguments.rend(); ++rit)
expressions.push_back(&(*rit));
}
else if (std::holds_alternative<Let>(e))
{
Let& l = std::get<Let>(e);
expressions.push_back(&l.body.front());
for (auto rit = l.bindings.rbegin(); rit != l.bindings.rend(); ++rit)
expressions.push_back(&(*rit).second);
}
else
throw std::runtime_error("Compiler error!: Tail calls check: not implemented");
}
}
};
}
bool only_tail_calls(Program& prog)
{
assert(prog.tail_call_analysis);
//tail_calls_check tcc;
//visitor<Program, tail_calls_check>::visit(prog, &tcc);
tail_calls_check_helper tcch;
for (auto& expr : prog.expressions)
tcch.expressions.push_back(&expr);
tcch.treat_expressions();
return tcch.only_tails;
}
bool only_tail_calls(Expression& e)
{
tail_calls_check_helper tcch;
tcch.expressions.push_back(&e);
tcch.treat_expressions();
return tcch.only_tails;
}
SKIWI_END
| 25.005051
| 131
| 0.568976
|
janm31415
|
ac49848a1882ecebb1539e54148b73293229f10c
| 3,048
|
cc
|
C++
|
leetcode/ds_hash_longest_consecutive_seq.cc
|
prashrock/C-
|
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
|
[
"MIT"
] | 1
|
2016-12-05T10:42:46.000Z
|
2016-12-05T10:42:46.000Z
|
leetcode/ds_hash_longest_consecutive_seq.cc
|
prashrock/CPP
|
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
|
[
"MIT"
] | null | null | null |
leetcode/ds_hash_longest_consecutive_seq.cc
|
prashrock/CPP
|
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
|
[
"MIT"
] | null | null | null |
//g++-5 --std=c++11 -Wall -g -o ds_hash_longest_consecutive_seq ds_hash_longest_consecutive_seq.cc
/**
* @file Longest Consecutive Sequence
* @brief Given unsorted array, find length of longest consecutive sequence
*/
// https://leetcode.com/problems/longest-consecutive-sequence/
/**
* Given an unsorted array of integers, find the length of the longest
* consecutive elements sequence.
* For example,
* Given [100, 4, 200, 1, 3, 2],
* The longest consecutive elements sequence is [1, 2, 3, 4].
* Return its length: 4.
* Note: Your algorithm should run in O(n) complexity.
*/
#include <iostream> /* std::cout */
#include <iomanip> /* std::setw */
#include <cmath> /* pow */
#include <cassert> /* assert */
#include <algorithm> /* std::max */
#include <vector> /* std:vector */
#include <string> /* std::string, */
#include <cstring> /* std::strtok */
#include <unordered_map> /* std::unordered_map */
using namespace std;
/* Use DFS to visit all consecutive numbers of a given val */
int dfs_consecutive(std::unordered_map<int, int>& mp, int val) {
int up=val+1, down=val-1;
while(mp.find(up) != mp.end() || mp.find(down) != mp.end()) {
auto uit = mp.find(up), dit = mp.find(down);
if(uit != mp.end()) {mp[val]++; mp.erase(uit); up++; }
if(dit != mp.end()) {mp[val]++; mp.erase(dit); down--;}
}
return mp[val];
}
/* Use a HashTable to find and track consecutive numbers. Use*
* DFS to traverse around every given node *
* Time_Complexity=O(n), Space_Complexity=O(n) */
int longestConsecutive(vector<int>& nums) {
int ans = 1;
std::unordered_map<int, int> mp; /* consecutive cnt */
/* Initialize unordered_map with vector */
for(auto val : nums) mp[val] = 1;
/* Pick up any random element and DFS search around it */
while( !mp.empty() ) {
auto it = mp.begin(); /* random first node from Map */
int key = it->first; /* get node's key */
/* Current max is either old or current DFS traversal */
ans = std::max(ans, dfs_consecutive(mp, key));
mp.erase(it); /* Remove current processed node */
}
return ans;
}
struct test_vector {
std::vector<int> X;
int exp;
};
const struct test_vector test[2] = {
{{9,1,-3,2,4,8,3,-1,6,-2,-4,7}, 4},
{{100, 4, 200, 1, 3, 2}, 4},
};
int main()
{
for(auto tst : test) {
auto ans = longestConsecutive(tst.X);
if(ans != tst.exp) {
cout << "Error:longestConsecutive failed for: ";
for(auto v : tst.X) cout << v << ","; cout << endl;
cout << " exp " << tst.exp << " got " << ans << endl;
return -1;
}
}
cout << "Info: All manual test-cases passed successfully" << endl;
return 0;
}
| 35.034483
| 98
| 0.543307
|
prashrock
|
ac566ec5d7bb9d1454c4a6bee2debad773b9c603
| 6,910
|
cpp
|
C++
|
ValidateEditor/SQLColsDlg.cpp
|
edwig/Kwatta
|
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
|
[
"MIT"
] | 1
|
2021-12-31T17:20:01.000Z
|
2021-12-31T17:20:01.000Z
|
ValidateEditor/SQLColsDlg.cpp
|
edwig/Kwatta
|
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
|
[
"MIT"
] | 10
|
2022-01-14T13:28:32.000Z
|
2022-02-13T12:46:34.000Z
|
ValidateEditor/SQLColsDlg.cpp
|
edwig/Kwatta
|
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
|
[
"MIT"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
// ██╗░░██╗░██╗░░░░░░░██╗░█████╗░████████╗████████╗░█████╗░
// ██║░██╔╝░██║░░██╗░░██║██╔══██╗╚══██╔══╝╚══██╔══╝██╔══██╗
// █████═╝░░╚██╗████╗██╔╝███████║░░░██║░░░░░░██║░░░███████║
// ██╔═██╗░░░████╔═████║░██╔══██║░░░██║░░░░░░██║░░░██╔══██║
// ██║░╚██╗░░╚██╔╝░╚██╔╝░██║░░██║░░░██║░░░░░░██║░░░██║░░██║
// ╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░╚═╝░░╚═╝░░░╚═╝░░░░░░╚═╝░░░╚═╝░░╚═╝
//
//
// This product: KWATTA (KWAliTy Test API) Test suite for Command-line SOAP/JSON/HTTP internet API's
// This program: ValidateEditor
// This File : SQLColsDlg.cpp
// What it does: Validation of the returned columns of an SQL database statement
// Author : ir. W.E. Huisman
// License : See license.md file in the root directory
//
///////////////////////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ValidateEditor.h"
#include "ValidateDatabaseDlg.h"
#include "SQLColsDlg.h"
#include <SearchVarDlg.h>
#include <NewVariableDlg.h>
#include <afxdialogex.h>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#define new DEBUG_NEW
#endif
// SQLColsDlg dialog
IMPLEMENT_DYNAMIC(SQLColsDlg, StyleDialog)
SQLColsDlg::SQLColsDlg(CWnd* p_parent)
:StyleDialog(IDD_SQL_COLS,p_parent)
{
}
SQLColsDlg::~SQLColsDlg()
{
}
void
SQLColsDlg::DoDataExchange(CDataExchange* pDX)
{
StyleDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_USE_RETURN, m_buttonCheck);
DDX_Control(pDX, IDC_OPERATOR, m_comboOperator);
DDX_Control(pDX, IDC_RETURN, m_editCols, m_returnedCols);
DDX_Control(pDX, IDC_BUTT_PARAM, m_buttonParm);
DDX_Control(pDX, IDC_EFF_RETURN, m_editEffective,m_effectiveReturnedCols);
DDX_Control(pDX, IDC_SUCCEED_VAR, m_comboVariable);
DDX_Control(pDX, IDC_NEWVAR, m_buttonVariable);
if(pDX->m_bSaveAndValidate == false)
{
m_comboOperator .EnableWindow(m_useCheckCols);
m_editCols .EnableWindow(m_useCheckCols);
m_editEffective .EnableWindow(m_useCheckCols);
m_comboVariable .EnableWindow(m_useCheckCols);
m_buttonVariable.EnableWindow(m_useCheckCols);
m_buttonParm .EnableWindow(m_useCheckCols);
}
}
BEGIN_MESSAGE_MAP(SQLColsDlg, StyleDialog)
ON_BN_CLICKED (IDC_USE_RETURN, &SQLColsDlg::OnBnClickedUseReturnedCols)
ON_CBN_SELCHANGE(IDC_OPERATOR, &SQLColsDlg::OnCbnSelchangeOperator)
ON_EN_KILLFOCUS (IDC_RETURN, &SQLColsDlg::OnEnChangeReturnedCols)
ON_BN_CLICKED (IDC_BUTT_PARAM, &SQLColsDlg::OnBnClickedParm)
ON_EN_CHANGE (IDC_EFF_RETURN, &SQLColsDlg::OnEnChangeEffSucceeded)
ON_CBN_SELCHANGE(IDC_SUCCEED_VAR, &SQLColsDlg::OnCbnSelchangeReturnedColsVariable)
ON_BN_CLICKED (IDC_NEWVAR, &SQLColsDlg::OnBnClickedNewvar)
END_MESSAGE_MAP()
BOOL
SQLColsDlg::OnInitDialog()
{
StyleDialog::OnInitDialog();
m_buttonVariable.SetIconImage(IDI_LIST);
m_buttonParm .SetIconImage(IDI_RETURN);
SetCanResize();
return TRUE;
}
void
SQLColsDlg::SetupDynamicLayout()
{
StyleDialog::SetupDynamicLayout();
CMFCDynamicLayout& manager = *GetDynamicLayout();
#ifdef _DEBUG
manager.AssertValid();
#endif
manager.AddItem(IDC_RETURN, CMFCDynamicLayout::MoveNone(), CMFCDynamicLayout::SizeHorizontal(100));
manager.AddItem(IDC_EFF_RETURN,CMFCDynamicLayout::MoveNone(), CMFCDynamicLayout::SizeHorizontal(100));
manager.AddItem(IDC_BUTT_PARAM,CMFCDynamicLayout::MoveHorizontal(100), CMFCDynamicLayout::SizeNone());
}
void
SQLColsDlg::InitTab(ValidateSQL* p_validate,Parameters* p_parameters)
{
m_validate = p_validate;
m_parameters = p_parameters;
LoadVariables();
FillCombos();
SetCombos();
}
void
SQLColsDlg::FillCombos()
{
m_comboOperator.ResetContent();
m_comboVariable.ResetContent();
m_comboOperator.AddString("");
m_comboOperator.AddString("= Exactly equal to");
m_comboOperator.AddString("> Greater than");
m_comboOperator.AddString(">= Greater than or equal to");
m_comboOperator.AddString("< Smaller than");
m_comboOperator.AddString("<= Smaller than or equal to");
m_comboOperator.AddString("<> Not equal to");
m_comboOperator.AddString("~~ Between two values");
m_comboOperator.AddString("[ ] In a range of values");
m_comboVariable.AddString("");
for(auto& ret : m_parameters->GetReturns())
{
m_comboVariable.AddString(ret.first);
}
}
void
SQLColsDlg::SetCombos()
{
m_comboOperator.SetCurSel((int)m_colsOperator);
int ind = m_comboVariable.FindStringExact(0, m_returnedColsVariable);
if (ind >= 0)
{
m_comboVariable.SetCurSel(ind);
}
}
void
SQLColsDlg::LoadVariables()
{
m_useCheckCols = m_validate->GetCheckCols();
m_colsOperator = m_validate->GetColsOperator();
m_returnedCols = m_validate->GetReturnedCols();
m_effectiveReturnedCols = m_validate->GetEffectiveReturnedCols();
m_returnedColsVariable = m_validate->GetReturnedColsVariable();
m_buttonCheck.SetCheck(m_useCheckCols);
m_comboOperator.SetCurSel((int)m_colsOperator - 1);
UpdateData(FALSE);
}
void
SQLColsDlg::StoreVariables()
{
m_validate->SetCheckCols(m_useCheckCols);
m_validate->SetReturnedCols(m_returnedCols);
m_validate->SetColsOperator(m_colsOperator);
m_validate->SetReturnedColsVariable(m_returnedColsVariable);
}
// SQLColsDlg message handlers
void
SQLColsDlg::OnBnClickedUseReturnedCols()
{
m_useCheckCols= m_buttonCheck.GetCheck() > 0;
if(!m_useCheckCols)
{
m_colsOperator = ReturnOperator::ROP_NOP;
m_comboOperator.SetCurSel(-1);
m_effectiveReturnedCols.Empty();
}
UpdateData(FALSE);
}
void
SQLColsDlg::OnCbnSelchangeOperator()
{
int ind = m_comboOperator.GetCurSel();
if (ind >= 0)
{
m_colsOperator = (ReturnOperator)ind;
}
}
void
SQLColsDlg::OnEnChangeReturnedCols()
{
UpdateData();
m_validate->SetSucceeded(m_returnedCols);
ValidateDatabaseDlg* parent = dynamic_cast<ValidateDatabaseDlg*>(GetParent()->GetParent());
if(parent)
{
StoreVariables();
parent->EffectiveParameters();
LoadVariables();
}
}
void
SQLColsDlg::OnBnClickedParm()
{
SearchVarDlg dlg(this,m_parameters,true,true,true,true);
if (dlg.DoModal() == IDOK || dlg.GetSaved())
{
m_returnedCols += dlg.GetVariable();
UpdateData(FALSE);
}
}
void
SQLColsDlg::OnEnChangeEffSucceeded()
{
UpdateData();
}
void
SQLColsDlg::OnCbnSelchangeReturnedColsVariable()
{
int ind = m_comboVariable.GetCurSel();
if(ind >= 0)
{
CString var;
m_comboVariable.GetLBText(ind,var);
m_returnedColsVariable = var;
}
}
void
SQLColsDlg::OnBnClickedNewvar()
{
NewVariableDlg dlg(ParType::PAR_RETURN, m_parameters->GetReturns());
if(dlg.DoModal() == IDOK)
{
CString newvar = dlg.GetNewName();
if(!newvar.IsEmpty())
{
m_returnedColsVariable = newvar;
FillCombos();
SetCombos();
}
}
}
| 26.273764
| 113
| 0.675687
|
edwig
|
ac587e3dfbebebde8bf200e83c733b6a00cfd8a5
| 27,114
|
cxx
|
C++
|
PWG/FLOW/Base/AliFlowAnalysisWithSimpleSP.cxx
|
amveen/AliPhysics
|
bef49dc8e7f8ad5f656d54430031eb67abcf3243
|
[
"BSD-3-Clause"
] | null | null | null |
PWG/FLOW/Base/AliFlowAnalysisWithSimpleSP.cxx
|
amveen/AliPhysics
|
bef49dc8e7f8ad5f656d54430031eb67abcf3243
|
[
"BSD-3-Clause"
] | null | null | null |
PWG/FLOW/Base/AliFlowAnalysisWithSimpleSP.cxx
|
amveen/AliPhysics
|
bef49dc8e7f8ad5f656d54430031eb67abcf3243
|
[
"BSD-3-Clause"
] | null | null | null |
/*************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#define ALIFLOWANALYSISWITHSIMPLESP_CXX
#include "TFile.h"
#include "TList.h"
#include "TMath.h"
#include "TString.h"
#include "TProfile.h"
#include "TVector2.h"
#include "TH1D.h"
#include "TH1F.h"
#include "TH2D.h"
#include "AliFlowCommonConstants.h"
#include "AliFlowEventSimple.h"
#include "AliFlowVector.h"
#include "AliFlowTrackSimple.h"
#include "AliFlowCommonHist.h"
#include "AliFlowCommonHistResults.h"
#include "AliFlowAnalysisWithSimpleSP.h"
using std::cout;
using std::endl;
ClassImp(AliFlowAnalysisWithSimpleSP)
//-----------------------------------------------------------------------
AliFlowAnalysisWithSimpleSP::AliFlowAnalysisWithSimpleSP():
fDebug(0),
fMinimalBook(kFALSE),
fUsePhiWeights(0),
fApplyCorrectionForNUA(0),
fHarmonic(2),
fWeights(kFALSE),
fScaling(kTRUE),
fNormalizationType(1),
fV0SanityCheck(0),
fExternalResolution(-999.),
fExternalResErr(0.),
fTotalQvector(3),
fWeightsList(NULL),
fHistList(NULL),
fHistProConfig(NULL),
fHistProQaQbNorm(NULL),
fHistSumOfWeights(NULL),
fHistProNUAq(NULL),
fCentralityWeight(1.),
fHistProQNorm(NULL),
fHistProQaQb(NULL),
fHistProQaQbM(NULL),
fHistMaMb(NULL),
fHistQNormQaQbNorm(NULL),
fHistQaNormMa(NULL),
fHistQbNormMb(NULL),
fResolution(NULL),
fHistQaQb(NULL),
fHistQaQc(NULL),
fHistQbQc(NULL),
fHistQaQbCos(NULL),
fHistNumberOfSubtractedDaughters(NULL),
fCommonHists(NULL),
fCommonHistsuQ(NULL),
fCommonHistsRes(NULL)
{
//ctor
for(int i=0; i!=2; ++i) {
fPhiWeightsSub[i] = NULL;
for(int j=0; j!=2; ++j) {
fHistProUQ[i][j] = NULL;
fHistProUQQaQb[i][j] = NULL;
fHistProNUAu[i][j][0] = NULL;
fHistProNUAu[i][j][1] = NULL;
for(int k=0; k!=3; ++k)
fHistSumOfWeightsu[i][j][k] = NULL;
}
}
}
//-----------------------------------------------------------------------
AliFlowAnalysisWithSimpleSP::~AliFlowAnalysisWithSimpleSP()
{
//destructor
delete fWeightsList;
delete fHistList;
}
//-----------------------------------------------------------------------
void AliFlowAnalysisWithSimpleSP::Init() {
//Define all histograms
//printf("---Analysis with the Scalar Product Method--- Init\n");
//printf("--- fNormalizationType %d ---\n", fNormalizationType);
//save old value and prevent histograms from being added to directory
//to avoid name clashes in case multiple analaysis objects are used
//in an analysis
Bool_t oldHistAddStatus = TH1::AddDirectoryStatus();
TH1::AddDirectory(kFALSE);
fHistList = new TList();
fHistList->SetName("cobjSP");
fHistList->SetOwner();
TList *uQRelated = new TList();
uQRelated->SetName("uQ");
uQRelated->SetOwner();
TList *nuaRelated = new TList();
nuaRelated->SetName("NUA");
nuaRelated->SetOwner();
TList *errorRelated = new TList();
errorRelated->SetName("error");
errorRelated->SetOwner();
TList *tQARelated = new TList();
tQARelated->SetName("QA");
tQARelated->SetOwner();
fCommonHists = new AliFlowCommonHist("AliFlowCommonHist_SP","AliFlowCommonHist",fMinimalBook, fHarmonic);
(fCommonHists->GetHarmonic())->Fill(0.5,fHarmonic); // store harmonic
fHistList->Add(fCommonHists);
// fCommonHistsuQ = new AliFlowCommonHist("AliFlowCommonHist_uQ");
// (fCommonHistsuQ->GetHarmonic())->Fill(0.5,fHarmonic); // store harmonic
// fHistList->Add(fCommonHistsuQ);
fCommonHistsRes = new AliFlowCommonHistResults("AliFlowCommonHistResults_SP","",fHarmonic);
fHistList->Add(fCommonHistsRes);
fHistProConfig = new TProfile("FlowPro_Flags_SP","Flow_Flags_SP",4,0.5,4.5,"s");
fHistProConfig->GetXaxis()->SetBinLabel(1,"fApplyCorrectionForNUA");
fHistProConfig->GetXaxis()->SetBinLabel(2,"fNormalizationType");
fHistProConfig->GetXaxis()->SetBinLabel(3,"fUsePhiWeights");
fHistProConfig->GetXaxis()->SetBinLabel(4,"fHarmonic");
fHistProConfig->Fill(1,fApplyCorrectionForNUA);
fHistProConfig->Fill(2,fNormalizationType);
fHistProConfig->Fill(3,fUsePhiWeights);
fHistProConfig->Fill(4,fHarmonic);
fHistList->Add(fHistProConfig);
fHistProQaQbNorm = new TProfile("FlowPro_QaQbNorm_SP","FlowPro_QaQbNorm_SP", 10000, -1000, 1000);
fHistProQaQbNorm->SetYTitle("<QaQb/Na/Nb>");
errorRelated->Add(fHistProQaQbNorm);
fHistProNUAq = new TProfile("FlowPro_NUAq_SP","FlowPro_NUAq_SP", 6, 0.5, 6.5,"s");
fHistProNUAq->GetXaxis()->SetBinLabel( 1,"<<sin(#Phi_{a})>>");
fHistProNUAq->GetXaxis()->SetBinLabel( 2,"<<cos(#Phi_{a})>>");
fHistProNUAq->GetXaxis()->SetBinLabel( 3,"<<sin(#Phi_{b})>>");
fHistProNUAq->GetXaxis()->SetBinLabel( 4,"<<cos(#Phi_{b})>>");
fHistProNUAq->GetXaxis()->SetBinLabel( 5,"<<sin(#Phi_{t})>>");
fHistProNUAq->GetXaxis()->SetBinLabel( 6,"<<cos(#Phi_{t})>>");
nuaRelated->Add(fHistProNUAq);
fHistSumOfWeights = new TH1D("Flow_SumOfWeights_SP","Flow_SumOfWeights_SP",2,0.5, 2.5);
fHistSumOfWeights->GetXaxis()->SetBinLabel( 1,"#Sigma Na*Nb");
fHistSumOfWeights->GetXaxis()->SetBinLabel( 2,"#Sigma (Na*Nb)^2");
errorRelated->Add(fHistSumOfWeights);
TString sPOI[2] = {"RP","POI"}; // backward compatibility
TString sEta[2] = {"Pt","eta"}; // backward compatibility
TString sTitle[2] = {"p_{T} [GeV]","#eta"};
TString sWeights[3] = {"uQ","uQuQ","uQQaQb"};
Int_t iNbins[2];
Double_t dMin[2], dMax[2];
iNbins[0] = AliFlowCommonConstants::GetMaster()->GetNbinsPt();
iNbins[1] = AliFlowCommonConstants::GetMaster()->GetNbinsEta();
dMin[0] = AliFlowCommonConstants::GetMaster()->GetPtMin();
dMin[1] = AliFlowCommonConstants::GetMaster()->GetEtaMin();
dMax[0] = AliFlowCommonConstants::GetMaster()->GetPtMax();
dMax[1] = AliFlowCommonConstants::GetMaster()->GetEtaMax();
for(Int_t iPOI=0; iPOI!=2; ++iPOI)
for(Int_t iSpace=0; iSpace!=2; ++iSpace) {
// uQ
fHistProUQ[iPOI][iSpace] = new TProfile( Form( "FlowPro_UQ_%s%s_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ),
Form( "FlowPro_UQ%s%s_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ),
iNbins[iSpace], dMin[iSpace], dMax[iSpace], "s");
fHistProUQ[iPOI][iSpace]->SetXTitle(sTitle[iSpace].Data());
fHistProUQ[iPOI][iSpace]->SetYTitle("<uQ>");
uQRelated->Add(fHistProUQ[iPOI][iSpace]);
// NUAu
fHistProNUAu[iPOI][iSpace][0] = new TProfile( Form("FlowPro_NUAu_%s%s_IM_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ),
Form("FlowPro_NUAu_%s%s_IM_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ),
iNbins[iSpace], dMin[iSpace], dMax[iSpace]);
fHistProNUAu[iPOI][iSpace][0]->SetXTitle(sTitle[iSpace].Data());
nuaRelated->Add(fHistProNUAu[iPOI][iSpace][0]);
fHistProNUAu[iPOI][iSpace][1] = new TProfile( Form("FlowPro_NUAu_%s%s_RE_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ),
Form("FlowPro_NUAu_%s%s_RE_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ),
iNbins[iSpace], dMin[iSpace], dMax[iSpace]);
fHistProNUAu[iPOI][iSpace][1]->SetXTitle(sTitle[iSpace].Data());
nuaRelated->Add(fHistProNUAu[iPOI][iSpace][1]);
// uQ QaQb
fHistProUQQaQb[iPOI][iSpace] = new TProfile( Form("FlowPro_UQQaQb_%s%s_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ),
Form("FlowPro_UQQaQb_%s%s_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ),
iNbins[iSpace], dMin[iSpace], dMax[iSpace]);
fHistProUQQaQb[iPOI][iSpace]->SetXTitle(sTitle[iSpace].Data());
fHistProUQQaQb[iPOI][iSpace]-> SetYTitle("<Qu QaQb>");
errorRelated->Add(fHistProUQQaQb[iPOI][iSpace]);
// uWeights
for(Int_t i=0; i!=3; ++i) {
fHistSumOfWeightsu[iPOI][iSpace][i] = new TH1D( Form("Flow_SumOfWeights_%s%s_%s_SP",sWeights[i].Data(),sPOI[iPOI].Data(),sEta[iSpace].Data()),
Form("Flow_SumOfWeights_%s%s_%s_SP",sWeights[i].Data(),sPOI[iPOI].Data(),sEta[iSpace].Data()),
iNbins[iSpace], dMin[iSpace], dMax[iSpace]);
fHistSumOfWeightsu[iPOI][iSpace][i]->SetYTitle(sWeights[i].Data());
fHistSumOfWeightsu[iPOI][iSpace][i]->SetXTitle(sTitle[iSpace].Data());
errorRelated->Add(fHistSumOfWeightsu[iPOI][iSpace][i]);
}
}
//weights
if(fUsePhiWeights) {
if(!fWeightsList) {
printf( "WARNING: fWeightsList is NULL in the Scalar Product method.\n" );
exit(0);
}
fPhiWeightsSub[0] = dynamic_cast<TH1F*>
(fWeightsList->FindObject("phi_weights_sub0"));
if(!fPhiWeightsSub[0]) {
printf( "WARNING: phi_weights_sub0 not found in the Scalar Product method.\n" );
exit(0);
}
nuaRelated->Add( fPhiWeightsSub[0] );
fPhiWeightsSub[1] = dynamic_cast<TH1F*>
(fWeightsList->FindObject("phi_weights_sub1"));
if(!fPhiWeightsSub[1]) {
printf( "WARNING: phi_weights_sub1 not found in the Scalar Product method.\n" );
exit(0);
}
nuaRelated->Add( fPhiWeightsSub[1] );
}
if(!fMinimalBook) {
fHistProQNorm = new TProfile("FlowPro_QNorm_SP","FlowPro_QNorm_SP", 1,0.5,1.5,"s");
fHistProQNorm->SetYTitle("<|Qa+Qb|>");
tQARelated->Add(fHistProQNorm);
fHistProQaQb = new TH1D("FlowPro_QaQb_SP","FlowPro_QaQb_SP", 10000,-100,100);
fHistProQaQb->SetYTitle("<QaQb>");
fHistProQaQb->StatOverflows(kTRUE);
tQARelated->Add(fHistProQaQb);
fHistProQaQbM = new TH1D("FlowPro_QaQbvsM_SP","FlowPro_QaQbvsM_SP",1000,0.0,10000);
fHistProQaQbM->SetYTitle("<QaQb>");
fHistProQaQbM->SetXTitle("M");
fHistProQaQbM->Sumw2();
tQARelated->Add(fHistProQaQbM);
fHistMaMb = new TH2D("Flow_MavsMb_SP","Flow_MavsMb_SP",100,0.,100.,100,0.,100.);
fHistMaMb->SetYTitle("Ma");
fHistMaMb->SetXTitle("Mb");
tQARelated->Add(fHistMaMb);
fHistQNormQaQbNorm = new TH2D("Flow_QNormvsQaQbNorm_SP","Flow_QNormvsQaQbNorm_SP",88,-1.1,1.1,22,0.,1.1);
fHistQNormQaQbNorm->SetYTitle("|Q/Mq|");
fHistQNormQaQbNorm->SetXTitle("QaQb/MaMb");
tQARelated->Add(fHistQNormQaQbNorm);
fHistQaNormMa = new TH2D("Flow_QaNormvsMa_SP","Flow_QaNormvsMa_SP",100,0.,100.,22,0.,1.1);
fHistQaNormMa->SetYTitle("|Qa/Ma|");
fHistQaNormMa->SetXTitle("Ma");
tQARelated->Add(fHistQaNormMa);
fHistQbNormMb = new TH2D("Flow_QbNormvsMb_SP","Flow_QbNormvsMb_SP",100,0.,100.,22,0.,1.1);
fHistQbNormMb->SetYTitle("|Qb/Mb|");
fHistQbNormMb->SetXTitle("Mb");
tQARelated->Add(fHistQbNormMb);
fResolution = new TH1D("Flow_resolution_SP","Flow_resolution_SP",100,-1.0,1.0);
fResolution->SetYTitle("dN/d(Cos2(#phi_a - #phi_b))");
fResolution->SetXTitle("Cos2(#phi_a - #phi_b)");
tQARelated->Add(fResolution);
fHistQaQb = new TH1D("Flow_QaQb_SP","Flow_QaQb_SP",20000,-1000.,1000.);
fHistQaQb->SetYTitle("dN/dQaQb");
fHistQaQb->SetXTitle("dQaQb");
fHistQaQb->StatOverflows(kTRUE);
tQARelated->Add(fHistQaQb);
fHistQaQc = new TH1D("Flow_QaQc_SP","Flow_QaQc_SP",20000,-1000.,1000.);
fHistQaQc->SetYTitle("dN/dQaQc");
fHistQaQc->SetXTitle("dQaQc");
fHistQaQc->StatOverflows(kTRUE);
tQARelated->Add(fHistQaQc);
fHistQbQc = new TH1D("Flow_QbQc_SP","Flow_QbQc_SP",20000,-1000.,1000.);
fHistQbQc->SetYTitle("dN/dQbQc");
fHistQbQc->SetXTitle("dQbQc");
fHistQbQc->StatOverflows(kTRUE);
tQARelated->Add(fHistQbQc);
fHistQaQbCos = new TH1D("Flow_QaQbCos_SP","Flow_QaQbCos_SP",63,0.,TMath::Pi());
fHistQaQbCos->SetYTitle("dN/d#phi");
fHistQaQbCos->SetXTitle("#phi");
tQARelated->Add(fHistQaQbCos);
fHistNumberOfSubtractedDaughters = new TH1I("NumberOfSubtractedDaughtersInQ",";daughters;counts;Number of daughters subtracted from Q",5,0.,5.);
tQARelated->Add(fHistNumberOfSubtractedDaughters);
}
fHistList->Add(uQRelated);
fHistList->Add(nuaRelated);
fHistList->Add(errorRelated);
fHistList->Add(tQARelated);
TH1::AddDirectory(oldHistAddStatus);
}
//-----------------------------------------------------------------------
void AliFlowAnalysisWithSimpleSP::Make(AliFlowEventSimple* anEvent) {
// Scalar Product method
if (!anEvent) return; // for coverity
fCentralityWeight = anEvent->GetPsi5();
// Get Q vectors for the subevents
AliFlowVector* vQarray = new AliFlowVector[2];
if (fUsePhiWeights)
anEvent->Get2Qsub(vQarray,fHarmonic,fWeightsList,kTRUE);
else
anEvent->Get2Qsub(vQarray,fHarmonic);
// Subevent a
AliFlowVector vQa = vQarray[0];
// Subevent b
AliFlowVector vQb = vQarray[1];
delete [] vQarray;
// multiplicity here corresponds to the V0 equalized multiplicity
Double_t dMa = vQa.GetMult();
if( dMa < 2 ) return;
Double_t dMb = vQb.GetMult();
if( dMb < 2 ) return;
//fill control histograms
fCommonHists->FillControlHistograms(anEvent);
//Normalizing: weight the Q vectors for the subevents
Double_t dNa = dMa;//fNormalizationType ? dMa: vQa.Mod(); // SP corresponds to true
Double_t dNb = dMb;//fNormalizationType ? dMb: vQb.Mod(); // SP corresponds to true
Double_t dWa = 1.;//fNormalizationType ? dMa: 1; // SP corresponds to true
Double_t dWb = 1.;//NormalizationType ? dMb: 1; // SP corresponds to true
// in the original SP method, event weights correspond to multiplicity
// for the V0 this does not necessarily make sense as the eq mult
// does not scale directly with charged track mult / centrality
// this task does not support EP style running, as this is
// ambiguous at best
//Scalar product of the two subevents vectors
Double_t dQaQb = (vQa*vQb);
// 01 10 11 <=== fTotalQVector
// Q ?= Qa or Qb or QaQb
AliFlowVector vQm;
vQm.Set(0.0,0.0);
AliFlowVector vQTPC;
vQTPC.Set(anEvent->GetPsi2(), anEvent->GetPsi3());
Double_t dNq=0;
if( (fTotalQvector%2)>0 ) { // 01 or 11
vQm += vQa;
dNq += dMa;
}
if( fTotalQvector>1 ) { // 10 or 11
vQm += vQb;
dNq += dMb;
}
Double_t dWq = 1.;//fNormalizationType ? dNq: 1; // SP corresponds to true
// if we dont normalize the q-vectors to the multiplicity, just use 1 here
if(!fScaling) {
dNa = 1.;
dNb = 1.;
}
// this profile stores the scalar product of the two
// subevent q-vectors (the denominator or 'resolution' of the
// measurement)
// fHistProQaQbNorm->Fill(1., dQaQb/dNa/dNb);
//loop over the tracks of the event
AliFlowTrackSimple* pTrack = NULL;
Int_t iNumberOfTracks = anEvent->NumberOfTracks();
Double_t dMq = 0;
for (Int_t i=0;i<iNumberOfTracks;i++) {
// so this is a track loop ...
pTrack = anEvent->GetTrack(i) ;
if (!pTrack) continue;
Double_t dPhi = pTrack->Phi();
Double_t dPt = pTrack->Pt();
Double_t dEta = pTrack->Eta();
// make sure it's not a vzero track
if(TMath::Abs(dEta) > 0.9) continue;
//calculate vU
// this is the track q-vecotr (small u)
TVector2 vU;
Double_t dUX = TMath::Cos(fHarmonic*dPhi);
Double_t dUY = TMath::Sin(fHarmonic*dPhi);
vU.Set(dUX,dUY);
// 01 10 11 <=== fTotalQVector
// Q ?= Qa or Qb or QaQb
// this will be the vector for hte scalar product itself
vQm.Set(0.0,0.0); //start the loop fresh
dMq=0;
if( (fTotalQvector%2)>0 ) { // 01 or 11
vQm += vQa;
dMq += dMa;
}
if( fTotalQvector>1 ) { // 10 or 11
vQm += vQb;
dMq += dMb;
}
dNq = dMq;//fNormalizationType ? dMq : vQm.Mod();
dWq = 1;//fNormalizationType ? dMq : 1;
// this little guy is the enumerator of the final equation
Double_t dUQ = vU*vQm;
// if we dont want scaling, disable it here
if(!fScaling) dNq = 1;
//fill the profile histograms
for(Int_t iPOI=0; iPOI!=2; ++iPOI) {
if( (iPOI==0)&&(!pTrack->InRPSelection()) )
continue;
if( (iPOI==1)&&(!pTrack->InPOISelection(fPOItype)) )
continue;
fHistProUQ[iPOI][0]->Fill(dPt ,fCentralityWeight*dUQ/dNq); //Fill (uQ/Nq') with weight (Nq')
fHistProUQ[iPOI][1]->Fill(dEta,fCentralityWeight*dUQ/dNq); //Fill (uQ/Nq') with weight (Nq')
//fHistProUQQaQb[iPOI][0]-> Fill(dPt,(dUQ*dUQ/dNq)/(dQaQb/dNa/dNb)); //Fill [Qu/Nq']*[QaQb/NaNb] with weight (Nq')NaNb
}
}//loop over tracks
//Filling QA (for compatibility with previous version)
if(!fMinimalBook) {
fHistQaQb->Fill(vQa*vQb/dNa/dNb, fCentralityWeight);
fHistQaQc->Fill(vQa*vQTPC, fCentralityWeight);
fHistQbQc->Fill(vQb*vQTPC, fCentralityWeight);
}
}
//--------------------------------------------------------------------
void AliFlowAnalysisWithSimpleSP::GetOutputHistograms(TList *outputListHistos){
//get pointers to all output histograms (called before Finish())
fHistList = outputListHistos;
fCommonHists = (AliFlowCommonHist*) fHistList->FindObject("AliFlowCommonHist_SP");
// fCommonHistsuQ = (AliFlowCommonHist*) fHistList->FindObject("AliFlowCommonHist_uQ");
fCommonHistsRes = (AliFlowCommonHistResults*) fHistList->FindObject("AliFlowCommonHistResults_SP");
fHistProConfig = (TProfile*) fHistList->FindObject("FlowPro_Flags_SP");
if(!fHistProConfig) printf("Error loading fHistProConfig\n");
TList *uQ = (TList*) fHistList->FindObject("uQ");
TList *nua = (TList*) fHistList->FindObject("NUA");
TList *error = (TList*) fHistList->FindObject("error");
TList* tQARelated = (TList*) fHistList->FindObject("QA");
fHistProQaQbNorm = (TProfile*) error->FindObject("FlowPro_QaQbNorm_SP");
if(!fHistProQaQbNorm) printf("Error loading fHistProQaQbNorm\n");
fHistProNUAq = (TProfile*) nua->FindObject("FlowPro_NUAq_SP");
if(!fHistProNUAq) printf("Error loading fHistProNUAq\n");
fHistSumOfWeights = (TH1D*) error->FindObject("Flow_SumOfWeights_SP");
if(!fHistSumOfWeights) printf("Error loading fHistSumOfWeights\n");
TString sPOI[2] = {"RP","POI"};
TString sEta[2] = {"Pt","eta"};
TString sWeights[3] = {"uQ","uQuQ","uQQaQb"};
for(Int_t iPOI=0; iPOI!=2; ++iPOI) for(Int_t iSpace=0; iSpace!=2; ++iSpace) {
fHistProUQ[iPOI][iSpace] = (TProfile*) uQ->FindObject( Form( "FlowPro_UQ_%s%s_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ) );
if(!fHistProUQ[iPOI][iSpace]) printf("Error loading fHistProUQ[%d][%d]\n",iPOI,iSpace);
fHistProNUAu[iPOI][iSpace][0] = (TProfile*) nua->FindObject( Form("FlowPro_NUAu_%s%s_IM_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ) );
if(!fHistProNUAu[iPOI][iSpace][0]) printf("Error loading fHistProNUAu[%d][%d][0]\n",iPOI,iSpace);
fHistProNUAu[iPOI][iSpace][1] = (TProfile*) nua->FindObject( Form("FlowPro_NUAu_%s%s_RE_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ) );
if(!fHistProNUAu[iPOI][iSpace][1]) printf("Error loading fHistProNUAu[%d][%d][1]\n",iPOI,iSpace);
fHistProUQQaQb[iPOI][iSpace] = (TProfile*) error->FindObject( Form("FlowPro_UQQaQb_%s%s_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ) );
for(Int_t i=0; i!=3; ++i){
fHistSumOfWeightsu[iPOI][iSpace][i] = (TH1D*) error->FindObject( Form("Flow_SumOfWeights_%s%s_%s_SP",sWeights[i].Data(),sPOI[iPOI].Data(),sEta[iSpace].Data()) );
if(!fHistSumOfWeightsu[iPOI][iSpace][i]) printf("Error loading fHistSumOfWeightsu[%d][%d][%d]\n",iPOI,iSpace,i);
}
}
if(fHistProConfig) {
fApplyCorrectionForNUA = (Int_t) fHistProConfig->GetBinContent(1);
fNormalizationType = (Int_t) fHistProConfig->GetBinContent(2);
fUsePhiWeights = (Int_t) fHistProConfig->GetBinContent(3);
fHarmonic = (Int_t) fHistProConfig->GetBinContent(4);
}
fHistQaQb = (TH1D*)tQARelated->FindObject("Flow_QaQb_SP");
fHistQaQc = (TH1D*)tQARelated->FindObject("Flow_QaQc_SP");
fHistQbQc = (TH1D*)tQARelated->FindObject("Flow_QbQc_SP");
}
//--------------------------------------------------------------------
void AliFlowAnalysisWithSimpleSP::Finish(Bool_t A) {
//calculate flow and fill the AliFlowCommonHistResults
printf("AliFlowAnalysisWithSimpleSP::Finish()\n");
// access harmonic:
fApplyCorrectionForNUA = 0;//(Int_t)(fHistProConfig->GetBinContent(1));
fNormalizationType = 1;//(Int_t)(fHistProConfig->GetBinContent(2));
fHarmonic = (Int_t)(fHistProConfig->GetBinContent(4));
printf("*************************************\n");
printf("*************************************\n");
printf(" Integrated flow from SIMPLE \n");
printf(" Scalar Product \n\n");
//Calculate reference flow
//----------------------------------
//weighted average over (QaQb/NaNb) with weight (NaNb)
if(!fHistQaQb) {
printf(" PANIC: run with full booking !");
return;
}
Double_t dEntriesQaQb = fHistQaQb->GetEntries();
if( dEntriesQaQb < 1 ) {
printf(" fHistQaQb has less than 1 entry, probably sub-events are misconfigured \n");
return;
}
//fHistQaQb->GetXaxis()->SetRangeUser(-10.,10.);
//fHistQaQC->GetXaxis()->SetRangeUser(-1000., 1000.);
//fHistQbQc->GetXaxis()->SetRangeUser(-1000., 1000.);
Double_t dQaQb = fHistQaQb->GetMean();
Double_t dQaQc = fHistQaQc->GetMean();
Double_t dQbQc = fHistQbQc->GetMean();
if(A) {
// now it's the resolution of A (which is vzero C)
dQaQb = (dQaQb*dQaQc)/dQbQc;
} else {
// else we select the resolution of B (which is V0A)
dQaQb = (dQaQb*dQbQc)/dQaQc;
}
Double_t dSpreadQaQb = fHistQaQb->GetRMS();
// this is the `resolution'
if(dQaQb <= .0 ) {
printf(" Panic! the average of QaQb <= 0! Probably you need to run on more events !\n");
printf(" \tusing dummy value 1 to avoid segfault \n");
dQaQb = 1.;
dSpreadQaQb = 1.;
}
Double_t dV = TMath::Sqrt(dQaQb);
printf("ResSub (sqrt of scalar product of sub-event qvectors) = %f\n", dV );
printf("fTotalQvector %d \n",fTotalQvector);
// we just take the spread as the uncertainty
Double_t dStatErrorQaQb = dSpreadQaQb;
Double_t dVerr = 0.;
if(dQaQb > 0.) dVerr = (1./(2.*pow(dQaQb,0.5)))*dStatErrorQaQb;
fCommonHistsRes->FillIntegratedFlow(dV,dVerr);
printf("v%d(subevents) = %f +- %f\n",fHarmonic,dV,dVerr);
Int_t iNbins[2];
iNbins[0] = AliFlowCommonConstants::GetMaster()->GetNbinsPt();
iNbins[1] = AliFlowCommonConstants::GetMaster()->GetNbinsEta();
//Calculate differential flow and integrated flow (RP, POI)
//---------------------------------------------------------
//v as a function of eta for RP selection
for(Int_t iRFPorPOI=0; iRFPorPOI != 2; ++iRFPorPOI)
for(Int_t iPTorETA=0; iPTorETA != 2; ++iPTorETA)
for(Int_t b=1; b != iNbins[iPTorETA]+1; ++b) {
Double_t duQpro = fHistProUQ[iRFPorPOI][iPTorETA]->GetBinContent(b);
Double_t dv2pro = -999.;
if( TMath::Abs(dV!=0.) && fExternalResolution < 0 ) { dv2pro = duQpro/dV; }
else if(fExternalResolution > 0) { dv2pro = duQpro / fExternalResolution; }
Double_t dv2ProErr = fHistProUQ[iRFPorPOI][iPTorETA]->GetBinError(b);
if(fHistProUQ[iRFPorPOI][iPTorETA]->GetBinEntries(b) > 1) dv2ProErr/=TMath::Sqrt(fHistProUQ[iRFPorPOI][iPTorETA]->GetBinEntries(b));
if(fExternalResErr > 0) {
// do default error propagation for a fraction where
Double_t a(0), b(0), t(0);
if(dv2ProErr > 0) a = duQpro*duQpro/(dv2ProErr*dv2ProErr); // squared relative error
if(fExternalResErr > 0) b = fExternalResolution*fExternalResolution/(fExternalResErr*fExternalResErr);
t = duQpro*fExternalResolution/(dv2ProErr*fExternalResErr);
t = dv2pro*dv2pro*(a + b -2.*t);
if(t>0) dv2ProErr = TMath::Sqrt(t);
}
if( (iRFPorPOI==0)&&(iPTorETA==0) )
fCommonHistsRes->FillDifferentialFlowPtRP( b, dv2pro, dv2ProErr);
if( (iRFPorPOI==0)&&(iPTorETA==1) )
fCommonHistsRes->FillDifferentialFlowEtaRP( b, dv2pro, dv2ProErr);
if( (iRFPorPOI==1)&&(iPTorETA==0) )
fCommonHistsRes->FillDifferentialFlowPtPOI( b, dv2pro, dv2ProErr);
if( (iRFPorPOI==1)&&(iPTorETA==1) )
fCommonHistsRes->FillDifferentialFlowEtaPOI(b, dv2pro, dv2ProErr);
}
printf("\n");
printf("*************************************\n");
printf("*************************************\n");
}
//-----------------------------------------------------------------------
void AliFlowAnalysisWithSimpleSP::WriteHistograms(TDirectoryFile *outputFileName) const {
//store the final results in output .root file
outputFileName->Add(fHistList);
outputFileName->Write(outputFileName->GetName(), TObject::kSingleKey);
}
//--------------------------------------------------------------------
| 43.244019
| 173
| 0.599174
|
amveen
|
ac5c29c36c2518fc591a949accccfd9aecb55958
| 24,233
|
cpp
|
C++
|
src/utils.cpp
|
dangerdevices/gdstk
|
bff6b2e5950b9da5b3b3f8bdb653778cf679e592
|
[
"BSL-1.0"
] | 135
|
2020-08-12T22:32:21.000Z
|
2022-03-31T04:34:56.000Z
|
src/utils.cpp
|
dangerdevices/gdstk
|
bff6b2e5950b9da5b3b3f8bdb653778cf679e592
|
[
"BSL-1.0"
] | 80
|
2020-08-12T23:03:44.000Z
|
2022-03-18T12:25:41.000Z
|
src/utils.cpp
|
dangerdevices/gdstk
|
bff6b2e5950b9da5b3b3f8bdb653778cf679e592
|
[
"BSL-1.0"
] | 35
|
2020-09-08T15:55:01.000Z
|
2022-03-29T04:52:58.000Z
|
/*
Copyright 2020 Lucas Heitzmann Gabrielli.
This file is part of gdstk, distributed under the terms of the
Boost Software License - Version 1.0. See the accompanying
LICENSE file or <http://www.boost.org/LICENSE_1_0.txt>
*/
#include "utils.h"
#include <assert.h>
#include <inttypes.h>
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include "allocator.h"
#include "vec.h"
// Qhull
#include "libqhull_r/qhull_ra.h"
namespace gdstk {
char* copy_string(const char* str, uint64_t* len) {
uint64_t size = 1 + strlen(str);
char* result = (char*)allocate(size);
memcpy(result, str, size);
if (len) *len = size;
return result;
}
bool is_multiple_of_pi_over_2(double angle, int64_t& m) {
if (angle == 0) {
m = 0;
return true;
} else if (angle == 0.5 * M_PI) {
m = 1;
return true;
} else if (angle == -0.5 * M_PI) {
m = -1;
return true;
} else if (angle == M_PI) {
m = 2;
return true;
} else if (angle == -M_PI) {
m = -2;
return true;
} else if (angle == 1.5 * M_PI) {
m = 3;
return true;
} else if (angle == -1.5 * M_PI) {
m = -3;
return true;
} else if (angle == 2 * M_PI) {
m = 4;
return true;
} else if (angle == -2 * M_PI) {
m = -4;
return true;
}
m = (int64_t)llround(angle / (M_PI / 2));
if (fabs(m * (M_PI / 2) - angle) < 1e-16) return true;
return false;
}
uint64_t arc_num_points(double angle, double radius, double tolerance) {
assert(radius > 0);
assert(tolerance > 0);
double c = 1 - tolerance / radius;
double a = c < -1 ? M_PI : acos(c);
return (uint64_t)(0.5 + 0.5 * fabs(angle) / a);
}
static double modulo(double x, double y) {
double m = fmod(x, y);
return m < 0 ? m + y : m;
}
double elliptical_angle_transform(double angle, double radius_x, double radius_y) {
if (angle == 0 || angle == M_PI || radius_x == radius_y) return angle;
double frac = angle - (modulo(angle + M_PI, 2 * M_PI) - M_PI);
double ell_angle = frac + atan2(radius_x * sin(angle), radius_y * cos(angle));
return ell_angle;
}
double distance_to_line_sq(const Vec2 p, const Vec2 p1, const Vec2 p2) {
const Vec2 v_line = p2 - p1;
const Vec2 v_point = p - p1;
const double c = v_point.cross(v_line);
return c * c / v_line.length_sq();
}
double distance_to_line(const Vec2 p, const Vec2 p1, const Vec2 p2) {
const Vec2 v_line = p2 - p1;
const Vec2 v_point = p - p1;
return fabs(v_point.cross(v_line)) / v_line.length();
}
void segments_intersection(const Vec2 p0, const Vec2 ut0, const Vec2 p1, const Vec2 ut1, double& u0,
double& u1) {
const double den = ut0.cross(ut1);
u0 = 0;
u1 = 0;
if (den >= GDSTK_PARALLEL_EPS || den <= -GDSTK_PARALLEL_EPS) {
const Vec2 delta_p = p1 - p0;
u0 = delta_p.cross(ut1) / den;
u1 = delta_p.cross(ut0) / den;
}
}
void scale_and_round_array(const Array<Vec2> points, double scaling,
Array<IntVec2>& scaled_points) {
scaled_points.ensure_slots(points.count);
scaled_points.count = points.count;
int64_t* s = (int64_t*)scaled_points.items;
double* p = (double*)points.items;
for (uint64_t i = 2 * points.count; i > 0; i--) {
*s++ = (int64_t)llround((*p++) * scaling);
}
}
void big_endian_swap16(uint16_t* buffer, uint64_t n) {
if (IS_BIG_ENDIAN) return;
for (; n > 0; n--) {
uint16_t b = *buffer;
*buffer++ = (b << 8) | (b >> 8);
}
}
void big_endian_swap32(uint32_t* buffer, uint64_t n) {
if (IS_BIG_ENDIAN) return;
for (; n > 0; n--) {
uint32_t b = *buffer;
*buffer++ = (b << 24) | ((b & 0x0000FF00) << 8) | ((b & 0x00FF0000) >> 8) | (b >> 24);
}
}
void big_endian_swap64(uint64_t* buffer, uint64_t n) {
if (IS_BIG_ENDIAN) return;
for (; n > 0; n--) {
uint64_t b = *buffer;
*buffer++ = (b << 56) | ((b & 0x000000000000FF00) << 40) |
((b & 0x0000000000FF0000) << 24) | ((b & 0x00000000FF000000) << 8) |
((b & 0x000000FF00000000) >> 8) | ((b & 0x0000FF0000000000) >> 24) |
((b & 0x00FF000000000000) >> 40) | (b >> 56);
}
}
void little_endian_swap16(uint16_t* buffer, uint64_t n) {
if (!IS_BIG_ENDIAN) return;
for (; n > 0; n--) {
uint16_t b = *buffer;
*buffer++ = (b << 8) | (b >> 8);
}
}
void little_endian_swap32(uint32_t* buffer, uint64_t n) {
if (!IS_BIG_ENDIAN) return;
for (; n > 0; n--) {
uint32_t b = *buffer;
*buffer++ = (b << 24) | ((b & 0x0000FF00) << 8) | ((b & 0x00FF0000) >> 8) | (b >> 24);
}
}
void little_endian_swap64(uint64_t* buffer, uint64_t n) {
if (!IS_BIG_ENDIAN) return;
for (; n > 0; n--) {
uint64_t b = *buffer;
*buffer++ = (b << 56) | ((b & 0x000000000000FF00) << 40) |
((b & 0x0000000000FF0000) << 24) | ((b & 0x00000000FF000000) << 8) |
((b & 0x000000FF00000000) >> 8) | ((b & 0x0000FF0000000000) >> 24) |
((b & 0x00FF000000000000) >> 40) | (b >> 56);
}
}
uint32_t checksum32(uint32_t checksum, const uint8_t* bytes, uint64_t count) {
uint64_t c = checksum;
while (count-- > 0) c = (c + *bytes++) & 0xFFFFFFFF;
return (uint32_t)c;
}
Vec2 eval_line(double t, const Vec2 p0, const Vec2 p1) { return LERP(p0, p1, t); }
Vec2 eval_bezier2(double t, const Vec2 p0, const Vec2 p1, const Vec2 p2) {
const double t2 = t * t;
const double r = 1 - t;
const double r2 = r * r;
Vec2 result = r2 * p0 + 2 * r * t * p1 + t2 * p2;
return result;
}
Vec2 eval_bezier3(double t, const Vec2 p0, const Vec2 p1, const Vec2 p2, const Vec2 p3) {
const double t2 = t * t;
const double t3 = t2 * t;
const double r = 1 - t;
const double r2 = r * r;
const double r3 = r2 * r;
Vec2 result = r3 * p0 + 3 * r2 * t * p1 + 3 * r * t2 * p2 + t3 * p3;
return result;
}
Vec2 eval_bezier(double t, const Vec2* ctrl, uint64_t count) {
Vec2 result;
Vec2* p = (Vec2*)allocate(sizeof(Vec2) * count);
memcpy(p, ctrl, sizeof(Vec2) * count);
const double r = 1 - t;
for (uint64_t j = count - 1; j > 0; j--)
for (uint64_t i = 0; i < j; i++) p[i] = r * p[i] + t * p[i + 1];
result = p[0];
free_allocation(p);
return result;
}
#ifndef NDEBUG
// NOTE: m[rows * cols] is assumed to be stored in row-major order
void print_matrix(double* m, uint64_t rows, uint64_t cols) {
for (uint64_t r = 0; r < rows; r++) {
printf("[");
for (uint64_t c = 0; c < cols; c++) {
if (c) printf("\t");
printf("%.3g", *m++);
}
printf("]\n");
}
}
#endif
// NOTE: m[rows * cols] must be stored in row-major order
// NOTE: pivots[rows] returns the pivoting order
uint64_t gauss_jordan_elimination(double* m, uint64_t* pivots, uint64_t rows, uint64_t cols) {
assert(cols >= rows);
uint64_t result = 0;
uint64_t* p = pivots;
for (uint64_t i = 0; i < rows; ++i) {
*p++ = i;
}
for (uint64_t i = 0; i < rows; ++i) {
// Select pivot: row with largest absolute value at column i
double pivot_value = fabs(m[pivots[i] * cols + i]);
uint64_t pivot_row = i;
for (uint64_t j = i + 1; j < rows; ++j) {
double candidate = fabs(m[pivots[j] * cols + i]);
if (candidate > pivot_value) {
pivot_value = candidate;
pivot_row = j;
}
}
if (pivot_value == 0) {
result += 1;
continue;
}
uint64_t row = pivots[pivot_row];
pivots[pivot_row] = pivots[i];
pivots[i] = row;
// Scale row
double* element = m + (row * cols + i);
double factor = 1.0 / *element;
for (uint64_t j = i; j < cols; ++j) {
*element++ *= factor;
}
// Zero i-th column from other rows
for (uint64_t r = 0; r < rows; ++r) {
if (r == row) continue;
element = m + row * cols;
double* other_row = m + r * cols;
factor = other_row[i];
for (uint64_t j = 0; j < cols; ++j) {
*other_row++ -= factor * *element++;
}
}
}
return result;
}
// NOTE: Matrix stored in column-major order!
void hobby_interpolation(uint64_t count, Vec2* points, double* angles, bool* angle_constraints,
Vec2* tension, double initial_curl, double final_curl, bool cycle) {
const double A = sqrt(2.0);
const double B = 1.0 / 16.0;
const double C = 0.5 * (3.0 - sqrt(5.0));
double* m = (double*)allocate(sizeof(double) * (2 * count * (2 * count + 1)));
uint64_t* pivots = (uint64_t*)allocate(sizeof(uint64_t) * (2 * count));
Vec2* pts = points;
Vec2* tens = tension;
double* ang = angles;
bool* ang_c = angle_constraints;
uint64_t points_size = count;
uint64_t rotate = 0;
if (cycle) {
while (rotate < count && !angle_constraints[rotate]) rotate++;
if (rotate == count) {
// No angle constraints
const uint64_t rows = 2 * count;
const uint64_t cols = rows + 1;
Vec2 v = points[3] - points[0];
Vec2 v_prev = points[0] - points[3 * (count - 1)];
double length_v = v.length();
double delta_prev = v_prev.angle();
memset(m, 0, sizeof(double) * rows * cols);
for (uint64_t i = 0; i < count; i++) {
const uint64_t i_1 = i == 0 ? count - 1 : i - 1;
const uint64_t i1 = i == count - 1 ? 0 : i + 1;
const uint64_t i2 = i < count - 2 ? i + 2 : (i == count - 2 ? 0 : 1);
const uint64_t j = count + i;
const uint64_t j_1 = count + i_1;
const uint64_t j1 = count + i1;
const double delta = v.angle();
const Vec2 v_next = points[3 * i2] - points[3 * i1];
const double length_v_next = v_next.length();
double psi = delta - delta_prev;
while (psi <= -M_PI) psi += 2 * M_PI;
while (psi > M_PI) psi -= 2 * M_PI;
m[i * cols + rows] = -psi;
m[i * cols + i] = 1;
m[i * cols + j_1] = 1;
// A_i
m[j * cols + i] = length_v_next * tension[i2].u * tension[i1].u * tension[i1].u;
// B_{i+1}
m[j * cols + i1] = -length_v * tension[i].v * tension[i1].v * tension[i1].v *
(1 - 3 * tension[i2].u);
// C_{i+1}
m[j * cols + j] = length_v_next * tension[i2].u * tension[i1].u * tension[i1].u *
(1 - 3 * tension[i].v);
// D_{i+2}
m[j * cols + j1] = -length_v * tension[i].v * tension[i1].v * tension[i1].v;
v_prev = v;
v = v_next;
length_v = length_v_next;
delta_prev = delta;
}
gauss_jordan_elimination(m, pivots, rows, cols);
// NOTE: re-use the first row of m to temporarily hold the angles
double* theta = m;
double* phi = theta + count;
for (uint64_t r = 0; r < count; r++) {
theta[r] = m[pivots[r] * cols + rows];
phi[r] = m[pivots[count + r] * cols + rows];
}
Vec2* cta = points + 1;
Vec2* ctb = points + 2;
v = points[3] - points[0];
Vec2 w = cplx_from_angle(theta[0] + v.angle());
for (uint64_t i = 0; i < count; i++, cta += 3, ctb += 3) {
const uint64_t i1 = i == count - 1 ? 0 : i + 1;
const uint64_t i2 = i < count - 2 ? i + 2 : (i == count - 2 ? 0 : 1);
const double st = sin(theta[i]);
const double ct = cos(theta[i]);
const double sp = sin(phi[i]);
const double cp = cos(phi[i]);
const double alpha = A * (st - B * sp) * (sp - B * st) * (ct - cp);
const Vec2 v_next = points[3 * i2] - points[3 * i1];
const double _length_v = v.length();
const double delta_next = v_next.angle();
const Vec2 w_next = cplx_from_angle(theta[i1] + delta_next);
*cta = points[3 * i] + w * _length_v * ((2 + alpha) / (1 + (1 - C) * ct + C * cp)) /
(3 * tension[i].v);
*ctb = points[3 * i1] - w_next * _length_v *
((2 - alpha) / (1 + (1 - C) * cp + C * ct)) /
(3 * tension[i1].u);
v = v_next;
w = w_next;
}
free_allocation(m);
free_allocation(pivots);
return;
}
// Cycle, but with angle constraint.
// Rotate inputs and add append last point to cycle,
// then use open curve solver.
points_size++;
pts = (Vec2*)allocate(sizeof(Vec2) * 3 * points_size);
memcpy(pts, points + 3 * rotate, sizeof(Vec2) * 3 * (count - rotate));
memcpy(pts + 3 * (count - rotate), points, sizeof(Vec2) * 3 * (rotate + 1));
tens = (Vec2*)allocate(sizeof(Vec2) * points_size);
memcpy(tens, tension + rotate, sizeof(Vec2) * (count - rotate));
memcpy(tens + count - rotate, tension, sizeof(Vec2) * (rotate + 1));
ang = (double*)allocate(sizeof(double) * points_size);
memcpy(ang, angles + rotate, sizeof(double) * (count - rotate));
memcpy(ang + count - rotate, angles, sizeof(double) * (rotate + 1));
ang_c = (bool*)allocate(sizeof(bool) * points_size);
memcpy(ang_c, angle_constraints + rotate, sizeof(bool) * (count - rotate));
memcpy(ang_c + count - rotate, angle_constraints, sizeof(bool) * (rotate + 1));
}
{
// Open curve solver
const uint64_t n = points_size - 1;
double* theta = (double*)allocate(sizeof(double) * n);
double* phi = (double*)allocate(sizeof(double) * n);
if (ang_c[0]) theta[0] = ang[0] - (pts[3] - pts[0]).angle();
uint64_t i = 0;
while (i < n) {
uint64_t j = i + 1;
while (j < n + 1 && !ang_c[j]) j++;
if (j == n + 1)
j--;
else {
phi[j - 1] = (pts[3 * j] - pts[3 * (j - 1)]).angle() - ang[j];
if (j < n) theta[j] = ang[j] - (pts[3 * (j + 1)] - pts[3 * j]).angle();
}
// Solve curve pts[i] thru pts[j]
const uint64_t range = j - i;
const uint64_t rows = 2 * range;
const uint64_t cols = rows + 1;
memset(m, 0, sizeof(double) * rows * cols);
Vec2 v_prev = pts[3 * (i + 1)] - pts[3 * i];
double delta_prev = v_prev.angle();
double length_v_prev = v_prev.length();
for (uint64_t k = 0; k < range - 1; k++) { // [0; range - 2]
const uint64_t k1 = k + 1; // [1; range - 1]
const uint64_t i0 = i + k; // [i; j - 2]
const uint64_t i1 = i0 + 1; // [i + 1; j - 1]
const uint64_t i2 = i0 + 2; // [i + 2; j]
const uint64_t l = k + range; // [range; 2 * range - 2]
const uint64_t l1 = l + 1; // [range + 1; range - 1]
Vec2 v = pts[3 * i2] - pts[3 * i1];
const double delta = v.angle();
const double length_v = v.length();
double psi = delta - delta_prev;
while (psi <= -M_PI) psi += 2 * M_PI;
while (psi > M_PI) psi -= 2 * M_PI;
m[k1 * cols + rows] = -psi;
m[k1 * cols + k1] = 1;
m[k1 * cols + l] = 1;
// A_k
m[l * cols + k] = length_v * tens[i2].u * tens[i1].u * tens[i1].u;
// B_{k+1}
m[l * cols + k1] =
-length_v_prev * tens[i0].v * tens[i1].v * tens[i1].v * (1 - 3 * tens[i2].u);
// C_{k+1}
m[l * cols + l] =
length_v * tens[i2].u * tens[i1].u * tens[i1].u * (1 - 3 * tens[i0].v);
// D_{k+2}
m[l * cols + l1] = -length_v_prev * tens[i0].v * tens[i1].v * tens[i1].v;
delta_prev = delta;
length_v_prev = length_v;
}
if (ang_c[i]) {
m[0 * cols + rows] = theta[i];
// B_0
m[0] = 1;
// D_1
// m[0 * cols + range] = 0;
} else {
const double to3 = tens[0].v * tens[0].v * tens[0].v;
const double cti3 = initial_curl * tens[1].u * tens[1].u * tens[1].u;
// B_0
m[0] = to3 * (1 - 3 * tens[1].u) - cti3;
// D_1
m[0 * cols + range] = to3 - cti3 * (1 - 3 * tens[0].v);
}
if (ang_c[j]) {
m[(rows - 1) * cols + rows] = phi[j - 1];
// A_{range-1}
// m[(rows - 1) * cols + (range - 1)] = 0;
// C_range
m[(rows - 1) * cols + (rows - 1)] = 1;
} else {
const double ti3 = tens[n].u * tens[n].u * tens[n].u;
const double cto3 = final_curl * tens[n - 1].v * tens[n - 1].v * tens[n - 1].v;
// A_{range-1}
m[(rows - 1) * cols + (range - 1)] = ti3 - cto3 * (1 - 3 * tens[n].u);
// C_range
m[(rows - 1) * cols + (rows - 1)] = ti3 * (1 - 3 * tens[n - 1].v) - cto3;
}
if (range > 1 || !ang_c[i] || !ang_c[j]) {
// printf("Solving range [%" PRIu64 ", %" PRIu64 "]\n\n", i, j);
// print_matrix(m, rows, cols);
gauss_jordan_elimination(m, pivots, rows, cols);
for (uint64_t r = 0; r < range; r++) {
theta[i + r] = m[pivots[r] * cols + rows];
phi[i + r] = m[pivots[range + r] * cols + rows];
}
// printf("\n");
// print_matrix(m, rows, cols);
// printf("\n");
}
i = j;
}
Vec2 v = pts[3] - pts[0];
Vec2 w = cplx_from_angle(theta[0] + v.angle());
for (uint64_t ii = 0; ii < n; ii++) {
const uint64_t i1 = ii + 1;
const uint64_t i2 = ii == n - 1 ? 0 : ii + 2;
const uint64_t ci = ii + rotate >= count ? ii + rotate - count : ii + rotate;
const double st = sin(theta[ii]);
const double ct = cos(theta[ii]);
const double sp = sin(phi[ii]);
const double cp = cos(phi[ii]);
const double alpha = A * (st - B * sp) * (sp - B * st) * (ct - cp);
const Vec2 v_next = pts[3 * i2] - pts[3 * i1];
const double length_v = v.length();
const Vec2 w_next = ii == n - 1 ? cplx_from_angle(v.angle() - phi[n - 1])
: cplx_from_angle(theta[i1] + v_next.angle());
points[3 * ci + 1] = pts[3 * ii] + w * length_v *
((2 + alpha) / (1 + (1 - C) * ct + C * cp)) /
(3 * tens[ii].v);
points[3 * ci + 2] = pts[3 * i1] - w_next * length_v *
((2 - alpha) / (1 + (1 - C) * cp + C * ct)) /
(3 * tens[i1].u);
v = v_next;
w = w_next;
}
if (cycle) {
free_allocation(pts);
free_allocation(tens);
free_allocation(ang);
free_allocation(ang_c);
}
free_allocation(theta);
free_allocation(phi);
}
free_allocation(m);
free_allocation(pivots);
}
void convex_hull(const Array<Vec2> points, Array<Vec2>& result) {
if (points.count < 4) {
result.extend(points);
return;
} else if (points.count > INT_MAX) {
Array<Vec2> partial;
partial.count = INT_MAX - 1;
partial.items = points.items;
Array<Vec2> temp = {0};
convex_hull(partial, temp);
partial.count = points.count - (INT_MAX - 1);
partial.items = points.items + (INT_MAX - 1);
temp.extend(partial);
convex_hull(temp, result);
temp.clear();
return;
}
qhT qh;
QHULL_LIB_CHECK;
qh_zero(&qh, stderr);
char command[256] = "qhull";
int exitcode = qh_new_qhull(&qh, 2, (int)points.count, (double*)points.items, false, command,
NULL, stderr);
if (exitcode == 0) {
result.ensure_slots(qh.num_facets);
Vec2* point = result.items + result.count;
result.count += qh.num_facets;
vertexT* qh_vertex = NULL;
facetT* qh_facet = qh_nextfacet2d(qh.facet_list, &qh_vertex);
for (int64_t i = qh.num_facets; i > 0; i--, point++) {
point->x = qh_vertex->point[0];
point->y = qh_vertex->point[1];
qh_facet = qh_nextfacet2d(qh_facet, &qh_vertex);
}
} else if (exitcode == qh_ERRsingular) {
// QHull errors for singular input (collinear points in 2D)
Vec2 min = {DBL_MAX, DBL_MAX};
Vec2 max = {-DBL_MAX, -DBL_MAX};
Vec2* p = points.items;
for (uint64_t num = points.count; num > 0; num--, p++) {
if (p->x < min.x) min.x = p->x;
if (p->x > max.x) max.x = p->x;
if (p->y < min.y) min.y = p->y;
if (p->y > max.y) max.y = p->y;
}
if (min.x < max.x) {
result.append(min);
result.append(max);
}
} else {
// The least we can do
result.extend(points);
}
#ifdef qh_NOmem
qh_freeqhull(&qh, qh_ALL);
#else
int curlong, totlong;
qh_freeqhull(&qh, !qh_ALL); /* free long memory */
qh_memfreeshort(&qh, &curlong, &totlong); /* free short memory and memory allocator */
if (curlong || totlong) {
fprintf(
stderr,
"[GDSTK] Qhull internal warning: did not free %d bytes of long memory (%d pieces)\n",
totlong, curlong);
}
#endif
}
char* double_print(double value, uint32_t precision, char* buffer, size_t buffer_size) {
uint64_t len = snprintf(buffer, buffer_size, "%.*f", precision, value);
if (precision) {
while (buffer[--len] == '0')
;
if (buffer[len] != '.') len++;
buffer[len] = 0;
}
return buffer;
}
tm* get_now(tm& result) {
time_t t = time(NULL);
#ifdef _WIN32
localtime_s(&result, &t);
#else
localtime_r(&t, &result);
#endif
return &result;
}
// Kenneth Kelly's 22 colors of maximum contrast (minus B/W: "F2F3F4", "222222")
const char* colors[] = {"F3C300", "875692", "F38400", "A1CAF1", "BE0032", "C2B280", "848482",
"008856", "E68FAC", "0067A5", "F99379", "604E97", "F6A600", "B3446C",
"DCD300", "882D17", "8DB600", "654522", "E25822", "2B3D26"};
inline static const char* default_color(Tag tag) {
return colors[(2 + get_layer(tag) + get_type(tag) * 13) % COUNT(colors)];
}
const char* default_svg_shape_style(Tag tag) {
static char buffer[] = "stroke: #XXXXXX; fill: #XXXXXX; fill-opacity: 0.5;";
const char* c = default_color(tag);
memcpy(buffer + 9, c, 6);
memcpy(buffer + 24, c, 6);
return buffer;
}
const char* default_svg_label_style(Tag tag) {
static char buffer[] = "stroke: none; fill: #XXXXXX;";
const char* c = default_color(tag);
memcpy(buffer + 21, c, 6);
return buffer;
}
} // namespace gdstk
| 36.007429
| 100
| 0.48566
|
dangerdevices
|
ac5e1706224622eb8bbd928ba02326fa6394a112
| 1,282
|
hh
|
C++
|
src/test/resources/samples/langs/Hack/HomeController.hh
|
JavascriptID/sourcerer-app
|
9ad05f7c6a18c03793c8b0295a2cb318118f6245
|
[
"MIT"
] | 8,271
|
2015-01-01T15:04:43.000Z
|
2022-03-31T06:18:14.000Z
|
src/test/resources/samples/langs/Hack/HomeController.hh
|
JavascriptID/sourcerer-app
|
9ad05f7c6a18c03793c8b0295a2cb318118f6245
|
[
"MIT"
] | 3,238
|
2015-01-01T14:25:12.000Z
|
2022-03-30T17:37:51.000Z
|
src/test/resources/samples/langs/Hack/HomeController.hh
|
JavascriptID/sourcerer-app
|
9ad05f7c6a18c03793c8b0295a2cb318118f6245
|
[
"MIT"
] | 4,070
|
2015-01-01T11:40:51.000Z
|
2022-03-31T13:45:53.000Z
|
<?hh // strict
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
require_once $_SERVER['DOCUMENT_ROOT'].'/core/controller/init.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/core/controller/standard-page/init.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/vendor/hhvm/xhp/src/init.php';
class HomeController extends GetController {
use StandardPage;
protected function getTitle(): string {
return 'Hack Cookbook';
}
protected function renderMainColumn(): :xhp {
return <div>
<h1>Cookbook</h1>
<p>
The Hack Cookbook helps you write Hack code by giving you examples of
Hack code. It is written in Hack and is open source. If you
<a href="http://github.com/facebook/hack-example-site">
head over to GitHub,
</a>
you can read the code, check out the repository, and run it
yourself. The recipes in this cookbook are small examples that
illustrate how to use Hack to solve common and interesting problems.
</p>
</div>;
}
}
| 32.871795
| 81
| 0.686427
|
JavascriptID
|
ac5fcec114a163f12d822091aba08574cff84eba
| 2,383
|
cpp
|
C++
|
Game/UI_Element_Slider.cpp
|
Chr157i4n/OpenGL_Space_Game
|
b4cd4ab65385337c37f26af641597c5fc9126f04
|
[
"MIT"
] | 3
|
2020-08-05T00:02:30.000Z
|
2021-08-23T00:41:24.000Z
|
Game/UI_Element_Slider.cpp
|
Chr157i4n/OpenGL_Space_Game
|
b4cd4ab65385337c37f26af641597c5fc9126f04
|
[
"MIT"
] | null | null | null |
Game/UI_Element_Slider.cpp
|
Chr157i4n/OpenGL_Space_Game
|
b4cd4ab65385337c37f26af641597c5fc9126f04
|
[
"MIT"
] | 2
|
2021-07-03T19:32:08.000Z
|
2021-08-19T18:48:52.000Z
|
#include "UI_Element_Slider.h"
#include "Game.h"
UI_Element_Slider::UI_Element_Slider(int x, int y, int w, int h, uint64 lifespan, std::string label, glm::vec4 foreColor, glm::vec4 backColor, bool isDebugInfo) : UI_Element(x, y, w, h, lifespan, foreColor, backColor, isDebugInfo)
{
this->label = label;
labelOffsetX = 0;
labelOffsetY = h/2;
}
void UI_Element_Slider::drawUI_Element()
{
float _x = x;
float _y = y;
float _w = w;
float _h = h;
float barThickness = 0.01;
float SliderThickness = 0.04;
float _value = (value - minValue) / (maxValue - minValue);
_x /= Game::getWindowWidth();
_y /= Game::getWindowHeight();
_w /= Game::getWindowWidth();
_h /= Game::getWindowHeight();
_x = _x * 2 - 1;
_y = _y * 2 - 1;
_w = _w * 2;
_h = _h * 2;
if (isSelected)
{
backColor.a = 1;
}
else
{
backColor.a = 0.4;
}
//background
glColor4f(backColor.r, backColor.g, backColor.b, backColor.a);
glBegin(GL_QUADS);
glVertex2f(_x , _y + 0.25*_h - barThickness);
glVertex2f(_x + _w, _y + 0.25*_h - barThickness);
glVertex2f(_x + _w, _y + 0.25*_h);
glVertex2f(_x, _y + 0.25*_h);
glEnd();
//Slider
glColor4f(foreColor.r, foreColor.g, foreColor.b, 1);
glBegin(GL_QUADS);
glVertex2f(_x + _value * _w - SliderThickness / 2, _y + 0.25 * _h - SliderThickness / 2); //left bottom
glVertex2f(_x + _value * _w + SliderThickness / 2, _y + 0.25 * _h - SliderThickness / 2); //right bottom
glVertex2f(_x + _value * _w + SliderThickness / 2, _y + 0.25 * _h + SliderThickness / 2); //right top
glVertex2f(_x + _value * _w - SliderThickness / 2, _y + 0.25 * _h + SliderThickness / 2); //left top
glEnd();
UI::drawString(x + labelOffsetX, y+labelOffsetY, label, foreColor);
}
int UI_Element_Slider::onMouseDrag(float mouseX, float mouseY, SDL_MouseButtonEvent* buttonEvent)
{
float newValue = (mouseX - this->getX()) / this->getW();
if (newValue < 0.05) newValue = 0;
if (newValue > 0.95) newValue = 1;
newValue = newValue * (maxValue - minValue) + minValue;
this->setValue(newValue);
return this->callCallBack();
}
int UI_Element_Slider::increase()
{
this->setValue(this->getValue() + 1 * (maxValue - minValue) * 0.5 * Game::getDelta()/1000);
return this->callCallBack();
}
int UI_Element_Slider::decrease()
{
this->setValue(this->getValue() - 1 * (maxValue - minValue) * 0.5 * Game::getDelta()/1000);
return this->callCallBack();
}
| 27.390805
| 230
| 0.664289
|
Chr157i4n
|
ac60947c206cb6be3969c04c3c524a5d8698d7c6
| 753
|
cpp
|
C++
|
codeforces/1392B.cpp
|
sgrade/cpptest
|
84ade6ec03ea394d4a4489c7559d12b4799c0b62
|
[
"MIT"
] | null | null | null |
codeforces/1392B.cpp
|
sgrade/cpptest
|
84ade6ec03ea394d4a4489c7559d12b4799c0b62
|
[
"MIT"
] | null | null | null |
codeforces/1392B.cpp
|
sgrade/cpptest
|
84ade6ec03ea394d4a4489c7559d12b4799c0b62
|
[
"MIT"
] | null | null | null |
// B. Omkar and Infinity Clock
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int n;
unsigned long long k;
cin >> n >> k;
vector<int> v(n);
for (int i=0; i<n; ++i){
cin >> v[i];
}
unsigned long long operations = 1;
if (k>1) {
operations = k%2 != 0 ? 3 : 2;
}
while (operations--){
int vMax = *max_element(v.begin(), v.end()) ;
for (int i = 0; i<n; ++i){
v[i] = vMax - v[i];
}
}
for (auto it: v){
cout << it << ' ';
}
cout << endl;
}
return 0;
}
| 16.733333
| 57
| 0.393094
|
sgrade
|
ac6b85c1faf5fc4c0540d0babded351d39970599
| 19,405
|
cpp
|
C++
|
src/kits/storage/NodeInfo.cpp
|
stasinek/BHAPI
|
5d9aa61665ae2cc5c6e34415957d49a769325b2b
|
[
"BSD-3-Clause",
"MIT"
] | 3
|
2018-05-21T15:32:32.000Z
|
2019-03-21T13:34:55.000Z
|
src/kits/storage/NodeInfo.cpp
|
stasinek/BHAPI
|
5d9aa61665ae2cc5c6e34415957d49a769325b2b
|
[
"BSD-3-Clause",
"MIT"
] | null | null | null |
src/kits/storage/NodeInfo.cpp
|
stasinek/BHAPI
|
5d9aa61665ae2cc5c6e34415957d49a769325b2b
|
[
"BSD-3-Clause",
"MIT"
] | null | null | null |
/*
* Copyright 2002-2010 Haiku, Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Ingo Weinhold, bonefish@users.sf.net
* Axel Dörfler, axeld@pinc-software.de
*/
//-----------------------------------------------------------------------------
#include <NodeInfo.h>
//-----------------------------------------------------------------------------
#include <MimeTypes.h>
#include <Bitmap.h>
#include <Entry.h>
#include <IconUtils.h>
#include <Node.h>
#include <Path.h>
#include <Rect.h>
//-----------------------------------------------------------------------------
#include <fs_attr.h>
#include <fs_info.h>
#include <new>
//-----------------------------------------------------------------------------
using namespace std;
using namespace bhapi;
//-----------------------------------------------------------------------------
// attribute names
#define NI_BEOS "BEOS"
static const char* kNITypeAttribute = NI_BEOS ":TYPE";
static const char* kNIPreferredAppAttribute = NI_BEOS ":PREF_APP";
static const char* kNIAppHintAttribute = NI_BEOS ":PPATH";
static const char* kNIMiniIconAttribute = NI_BEOS ":M:STD_ICON";
static const char* kNILargeIconAttribute = NI_BEOS ":L:STD_ICON";
static const char* kNIIconAttribute = NI_BEOS ":ICON";
// #pragma mark - BNodeInfo
//-----------------------------------------------------------------------------
BNodeInfo::BNodeInfo()
:
fNode(NULL),
fCStatus(B_NO_INIT)
{
}
//-----------------------------------------------------------------------------
BNodeInfo::BNodeInfo(BNode* node)
:
fNode(NULL),
fCStatus(B_NO_INIT)
{
fCStatus = SetTo(node);
}
//-----------------------------------------------------------------------------
BNodeInfo::~BNodeInfo()
{
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::SetTo(BNode* node)
{
fNode = NULL;
// check parameter
fCStatus = (node && node->InitCheck() == B_OK ? B_OK : B_BAD_VALUE);
if (fCStatus == B_OK)
fNode = node;
return fCStatus;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::InitCheck() const
{
return fCStatus;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetType(char* type) const
{
// check parameter and initialization
status_t result = (type ? B_OK : B_BAD_VALUE);
if (result == B_OK && InitCheck() != B_OK)
result = B_NO_INIT;
// get the attribute info and check type and length of the attr contents
attr_info attrInfo;
if (result == B_OK)
result = fNode->GetAttrInfo(kNITypeAttribute, &attrInfo);
if (result == B_OK && attrInfo.type != B_MIME_STRING_TYPE)
result = B_BAD_TYPE;
if (result == B_OK && attrInfo.size > B_MIME_TYPE_LENGTH)
result = B_BAD_DATA;
// read the data
if (result == B_OK) {
ssize_t read = fNode->ReadAttr(kNITypeAttribute, attrInfo.type, 0,
type, attrInfo.size);
if (read < 0)
result = read;
else if (read != attrInfo.size)
result = B_ERROR;
if (result == B_OK) {
// attribute strings doesn't have to be null terminated
type[min_c(attrInfo.size, B_MIME_TYPE_LENGTH - 1)] = '\0';
}
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::SetType(const char* type)
{
// check parameter and initialization
status_t result = B_OK;
if (result == B_OK && type && strlen(type) >= B_MIME_TYPE_LENGTH)
result = B_BAD_VALUE;
if (result == B_OK && InitCheck() != B_OK)
result = B_NO_INIT;
// write/remove the attribute
if (result == B_OK) {
if (type != NULL) {
size_t toWrite = strlen(type) + 1;
ssize_t written = fNode->WriteAttr(kNITypeAttribute,
B_MIME_STRING_TYPE, 0, type, toWrite);
if (written < 0)
result = written;
else if (written != (ssize_t)toWrite)
result = B_ERROR;
} else
result = fNode->RemoveAttr(kNITypeAttribute);
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetIcon(BBitmap* icon, icon_size which) const
{
const char* iconAttribute = kNIIconAttribute;
const char* miniIconAttribute = kNIMiniIconAttribute;
const char* largeIconAttribute = kNILargeIconAttribute;
return BIconUtils::GetIcon(fNode, iconAttribute, miniIconAttribute,
largeIconAttribute, which, icon);
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::SetIcon(const BBitmap* icon, icon_size which)
{
status_t result = B_OK;
// set some icon size related variables
const char* attribute = NULL;
BRect bounds;
uint32 attrType = 0;
size_t attrSize = 0;
switch (which) {
case B_MINI_ICON:
attribute = kNIMiniIconAttribute;
bounds.Set(0, 0, 15, 15);
attrType = B_MINI_ICON_TYPE;
attrSize = 16 * 16;
break;
case B_LARGE_ICON:
attribute = kNILargeIconAttribute;
bounds.Set(0, 0, 31, 31);
attrType = B_LARGE_ICON_TYPE;
attrSize = 32 * 32;
break;
default:
result = B_BAD_VALUE;
break;
}
// check parameter and initialization
if (result == B_OK && icon != NULL
&& (icon->InitCheck() != B_OK || icon->Bounds() != bounds)) {
result = B_BAD_VALUE;
}
if (result == B_OK && InitCheck() != B_OK)
result = B_NO_INIT;
// write/remove the attribute
if (result == B_OK) {
if (icon != NULL) {
bool otherColorSpace = (icon->ColorSpace() != B_CMAP8);
ssize_t written = 0;
if (otherColorSpace) {
BBitmap bitmap(bounds, B_BITMAP_NO_SERVER_LINK, B_CMAP8);
result = bitmap.InitCheck();
if (result == B_OK)
result = bitmap.ImportBits(icon);
if (result == B_OK) {
written = fNode->WriteAttr(attribute, attrType, 0,
bitmap.Bits(), attrSize);
}
} else {
written = fNode->WriteAttr(attribute, attrType, 0,
icon->Bits(), attrSize);
}
if (result == B_OK) {
if (written < 0)
result = written;
else if (written != (ssize_t)attrSize)
result = B_ERROR;
}
} else {
// no icon given => remove
result = fNode->RemoveAttr(attribute);
}
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetIcon(uint8** data, size_t* size, type_code* type) const
{
// check params
if (data == NULL || size == NULL || type == NULL)
return B_BAD_VALUE;
// check initialization
if (InitCheck() != B_OK)
return B_NO_INIT;
// get the attribute info and check type and size of the attr contents
attr_info attrInfo;
status_t result = fNode->GetAttrInfo(kNIIconAttribute, &attrInfo);
if (result != B_OK)
return result;
// chicken out on unrealisticly large attributes
if (attrInfo.size > 128 * 1024)
return B_ERROR;
// fill the params
*type = attrInfo.type;
*size = attrInfo.size;
*data = new (nothrow) uint8[*size];
if (*data == NULL)
return B_NO_MEMORY;
// featch the data
ssize_t read = fNode->ReadAttr(kNIIconAttribute, *type, 0, *data, *size);
if (read != attrInfo.size) {
delete[] *data;
*data = NULL;
return B_ERROR;
}
return B_OK;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::SetIcon(const uint8* data, size_t size)
{
// check initialization
if (InitCheck() != B_OK)
return B_NO_INIT;
status_t result = B_OK;
// write/remove the attribute
if (data && size > 0) {
ssize_t written = fNode->WriteAttr(kNIIconAttribute,
B_VECTOR_ICON_TYPE, 0, data, size);
if (written < 0)
result = (status_t)written;
else if (written != (ssize_t)size)
result = B_ERROR;
} else {
// no icon given => remove
result = fNode->RemoveAttr(kNIIconAttribute);
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetPreferredApp(char* signature, app_verb verb) const
{
// check parameter and initialization
status_t result = (signature && verb == B_OPEN ? B_OK : B_BAD_VALUE);
if (result == B_OK && InitCheck() != B_OK)
result = B_NO_INIT;
// get the attribute info and check type and length of the attr contents
attr_info attrInfo;
if (result == B_OK)
result = fNode->GetAttrInfo(kNIPreferredAppAttribute, &attrInfo);
if (result == B_OK && attrInfo.type != B_MIME_STRING_TYPE)
result = B_BAD_TYPE;
if (result == B_OK && attrInfo.size > B_MIME_TYPE_LENGTH)
result = B_BAD_DATA;
// read the data
if (result == B_OK) {
ssize_t read = fNode->ReadAttr(kNIPreferredAppAttribute, attrInfo.type,
0, signature, attrInfo.size);
if (read < 0)
result = read;
else if (read != attrInfo.size)
result = B_ERROR;
if (result == B_OK) {
// attribute strings doesn't have to be null terminated
signature[min_c(attrInfo.size, B_MIME_TYPE_LENGTH - 1)] = '\0';
}
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::SetPreferredApp(const char* signature, app_verb verb)
{
// check parameters and initialization
status_t result = (verb == B_OPEN ? B_OK : B_BAD_VALUE);
if (result == B_OK && signature && strlen(signature) >= B_MIME_TYPE_LENGTH)
result = B_BAD_VALUE;
if (result == B_OK && InitCheck() != B_OK)
result = B_NO_INIT;
// write/remove the attribute
if (result == B_OK) {
if (signature) {
size_t toWrite = strlen(signature) + 1;
ssize_t written = fNode->WriteAttr(kNIPreferredAppAttribute,
B_MIME_STRING_TYPE, 0, signature, toWrite);
if (written < 0)
result = written;
else if (written != (ssize_t)toWrite)
result = B_ERROR;
} else
result = fNode->RemoveAttr(kNIPreferredAppAttribute);
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetAppHint(entry_ref* ref) const
{
// check parameter and initialization
status_t result = (ref ? B_OK : B_BAD_VALUE);
if (result == B_OK && InitCheck() != B_OK)
result = B_NO_INIT;
// get the attribute info and check type and length of the attr contents
attr_info attrInfo;
if (result == B_OK)
result = fNode->GetAttrInfo(kNIAppHintAttribute, &attrInfo);
// NOTE: The attribute type should be B_STRING_TYPE, but R5 uses
// B_MIME_STRING_TYPE.
if (result == B_OK && attrInfo.type != B_MIME_STRING_TYPE)
result = B_BAD_TYPE;
if (result == B_OK && attrInfo.size > B_PATH_NAME_LENGTH)
result = B_BAD_DATA;
// read the data
if (result == B_OK) {
char path[B_PATH_NAME_LENGTH];
ssize_t read = fNode->ReadAttr(kNIAppHintAttribute, attrInfo.type, 0,
path, attrInfo.size);
if (read < 0)
result = read;
else if (read != attrInfo.size)
result = B_ERROR;
// get the entry_ref for the path
if (result == B_OK) {
// attribute strings doesn't have to be null terminated
path[min_c(attrInfo.size, B_PATH_NAME_LENGTH - 1)] = '\0';
result = get_ref_for_path(path, ref);
}
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::SetAppHint(const entry_ref* ref)
{
// check parameter and initialization
if (InitCheck() != B_OK)
return B_NO_INIT;
status_t result = B_OK;
if (ref != NULL) {
// write/remove the attribute
BPath path;
result = path.SetTo(ref);
if (result == B_OK) {
size_t toWrite = strlen(path.Path()) + 1;
ssize_t written = fNode->WriteAttr(kNIAppHintAttribute,
B_MIME_STRING_TYPE, 0, path.Path(), toWrite);
if (written < 0)
result = written;
else if (written != (ssize_t)toWrite)
result = B_ERROR;
}
} else
result = fNode->RemoveAttr(kNIAppHintAttribute);
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetTrackerIcon(BBitmap* icon, icon_size which) const
{
if (icon == NULL)
return B_BAD_VALUE;
// set some icon size related variables
BRect bounds;
switch (which) {
case B_MINI_ICON:
bounds.Set(0, 0, 15, 15);
break;
case B_LARGE_ICON:
bounds.Set(0, 0, 31, 31);
break;
default:
// result = B_BAD_VALUE;
// NOTE: added to be less strict and support scaled icons
bounds = icon->Bounds();
break;
}
// check parameters and initialization
if (icon->InitCheck() != B_OK || icon->Bounds() != bounds)
return B_BAD_VALUE;
if (InitCheck() != B_OK)
return B_NO_INIT;
// Ask GetIcon() first.
if (GetIcon(icon, which) == B_OK)
return B_OK;
// If not successful, see if the node has a type available at all.
// If no type is available, use one of the standard types.
status_t result = B_OK;
char mimeString[B_MIME_TYPE_LENGTH];
if (GetType(mimeString) != B_OK) {
// Get the icon from a mime type...
BMimeType type;
struct stat stat;
result = fNode->GetStat(&stat);
if (result == B_OK) {
// no type available -- get the icon for the appropriate type
// (file/dir/etc.)
if (S_ISREG(stat.st_mode)) {
// is it an application (executable) or just a regular file?
if ((stat.st_mode & S_IXUSR) != 0)
type.SetTo(B_APP_MIME_TYPE);
else
type.SetTo(B_FILE_MIME_TYPE);
} else if (S_ISDIR(stat.st_mode)) {
// it's either a volume or just a standard directory
fs_info info;
if (fs_stat_dev(stat.st_dev, &info) == 0
&& stat.st_ino == info.root) {
type.SetTo(B_VOLUME_MIME_TYPE);
} else
type.SetTo(B_DIRECTORY_MIME_TYPE);
} else if (S_ISLNK(stat.st_mode))
type.SetTo(B_SYMLINK_MIME_TYPE);
} else {
// GetStat() failed. Return the icon for
// "application/octet-stream" from the MIME database.
type.SetTo(B_FILE_MIME_TYPE);
}
return type.GetIcon(icon, which);
} else {
// We know the mimetype of the node.
bool success = false;
// Get the preferred application and ask the MIME database, if that
// application has a special icon for the node's file type.
char signature[B_MIME_TYPE_LENGTH];
if (GetPreferredApp(signature) == B_OK) {
BMimeType type(signature);
success = type.GetIconForType(mimeString, icon, which) == B_OK;
}
// ToDo: Confirm Tracker asks preferred app icons before asking
// mime icons.
BMimeType nodeType(mimeString);
// Ask the MIME database for the preferred application for the node's
// file type and whether this application has a special icon for the
// type.
if (!success && nodeType.GetPreferredApp(signature) == B_OK) {
BMimeType type(signature);
success = type.GetIconForType(mimeString, icon, which) == B_OK;
}
// Ask the MIME database whether there is an icon for the node's file
// type.
if (!success)
success = nodeType.GetIcon(icon, which) == B_OK;
// Get the super type if still no success.
BMimeType superType;
if (!success && nodeType.GetSupertype(&superType) == B_OK) {
// Ask the MIME database for the preferred application for the
// node's super type and whether this application has a special
// icon for the type.
if (superType.GetPreferredApp(signature) == B_OK) {
BMimeType type(signature);
success = type.GetIconForType(superType.Type(), icon,
which) == B_OK;
}
// Get the icon of the super type itself.
if (!success)
success = superType.GetIcon(icon, which) == B_OK;
}
if (success)
return B_OK;
}
return B_ERROR;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetTrackerIcon(const entry_ref* ref, BBitmap* icon, icon_size which)
{
// check ref param
status_t result = (ref ? B_OK : B_BAD_VALUE);
// init a BNode
BNode node;
if (result == B_OK)
result = node.SetTo(ref);
// init a BNodeInfo
BNodeInfo nodeInfo;
if (result == B_OK)
result = nodeInfo.SetTo(&node);
// let the non-static GetTrackerIcon() do the dirty work
if (result == B_OK)
result = nodeInfo.GetTrackerIcon(icon, which);
return result;
}
//-----------------------------------------------------------------------------
/*! This method is provided for binary compatibility purposes
(for example the program "Guido" depends on it.)
*/
extern "C" status_t GetTrackerIcon__9BNodeInfoP9entry_refP7BBitmap9icon_size(
BNodeInfo* nodeInfo, entry_ref* ref,
BBitmap* bitmap, icon_size iconSize)
{
// NOTE: nodeInfo is ignored - maybe that's wrong!
return BNodeInfo::GetTrackerIcon(ref, bitmap, iconSize);
}
//-----------------------------------------------------------------------------
void BNodeInfo::_ReservedNodeInfo1() {}
void BNodeInfo::_ReservedNodeInfo2() {}
void BNodeInfo::_ReservedNodeInfo3() {}
//-----------------------------------------------------------------------------
/*! Assignment operator is declared private to prevent it from being created
automatically by the compiler.
*/
BNodeInfo& BNodeInfo::operator=(const BNodeInfo &nodeInfo)
{
return *this;
}
//-----------------------------------------------------------------------------
/*! Copy constructor is declared private to prevent it from being created
automatically by the compiler.
*/
BNodeInfo::BNodeInfo(const BNodeInfo &)
{
}
//-----------------------------------------------------------------------------
| 31.916118
| 88
| 0.524916
|
stasinek
|
ac6c6bddc8d811b7ae25f6bbb9f8ce0e716e12c5
| 323
|
cpp
|
C++
|
maximum-difference-between-increasing-elements/maximum-difference-between-increasing-elements.cpp
|
sharmishtha2401/leetcode
|
0c7389877afb64b3ff277f075ed9c87b24cb587b
|
[
"MIT"
] | 1
|
2022-02-14T07:57:07.000Z
|
2022-02-14T07:57:07.000Z
|
maximum-difference-between-increasing-elements/maximum-difference-between-increasing-elements.cpp
|
sharmishtha2401/leetcode
|
0c7389877afb64b3ff277f075ed9c87b24cb587b
|
[
"MIT"
] | null | null | null |
maximum-difference-between-increasing-elements/maximum-difference-between-increasing-elements.cpp
|
sharmishtha2401/leetcode
|
0c7389877afb64b3ff277f075ed9c87b24cb587b
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int maximumDifference(vector<int>& nums) {
int diff=0;
int minimum=INT_MAX;
for(int n : nums)
{
if(n<minimum)
minimum=n;
if(n-minimum>diff)
diff=n-minimum;
}
return diff==0?-1:diff;
}
};
| 21.533333
| 46
| 0.458204
|
sharmishtha2401
|
ac6ecd4799d50f8520d54d5cf0337cbc916110bf
| 283
|
cpp
|
C++
|
sxaccelerate/src/io/examples/plugins/SxPluginA.cpp
|
ashtonmv/sphinx_vdw
|
5896fee0d92c06e883b72725cb859d732b8b801f
|
[
"Apache-2.0"
] | 1
|
2020-02-29T03:26:32.000Z
|
2020-02-29T03:26:32.000Z
|
sxaccelerate/src/io/examples/plugins/SxPluginA.cpp
|
ashtonmv/sphinx_vdw
|
5896fee0d92c06e883b72725cb859d732b8b801f
|
[
"Apache-2.0"
] | null | null | null |
sxaccelerate/src/io/examples/plugins/SxPluginA.cpp
|
ashtonmv/sphinx_vdw
|
5896fee0d92c06e883b72725cb859d732b8b801f
|
[
"Apache-2.0"
] | null | null | null |
#include <SxPluginA.h>
#include <stdio.h>
SxPluginA::SxPluginA (SxPluginManager *parent_, void *)
: SxDemoPluginBase (parent_)
{
//empty
}
SxPluginA::~SxPluginA ()
{
printf ("About to destroy plugin A.\n");
}
void SxPluginA::foo ()
{
printf ("This is plugin A.\n");
}
| 14.894737
| 55
| 0.650177
|
ashtonmv
|
ac6f4c0bcd49e1cd1ef543efe8fede81bd300cd0
| 2,687
|
hpp
|
C++
|
src/api/c/graphics_common.hpp
|
JuliaComputing/arrayfire
|
93427f09ff928f97df29c0e358c3fcf6b478bec6
|
[
"BSD-3-Clause"
] | 1
|
2018-06-14T23:49:18.000Z
|
2018-06-14T23:49:18.000Z
|
src/api/c/graphics_common.hpp
|
JuliaComputing/arrayfire
|
93427f09ff928f97df29c0e358c3fcf6b478bec6
|
[
"BSD-3-Clause"
] | 1
|
2015-07-02T15:53:02.000Z
|
2015-07-02T15:53:02.000Z
|
src/api/c/graphics_common.hpp
|
JuliaComputing/arrayfire
|
93427f09ff928f97df29c0e358c3fcf6b478bec6
|
[
"BSD-3-Clause"
] | 1
|
2018-02-26T17:11:03.000Z
|
2018-02-26T17:11:03.000Z
|
/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#if defined(WITH_GRAPHICS)
#include <af/graphics.h>
#include <forge.h>
#include <map>
// default to f32(float) type
template<typename T>
fg::FGType getGLType();
// Print for OpenGL errors
// Returns 1 if an OpenGL error occurred, 0 otherwise.
GLenum glErrorSkip(const char *msg, const char* file, int line);
GLenum glErrorCheck(const char *msg, const char* file, int line);
GLenum glForceErrorCheck(const char *msg, const char* file, int line);
#define CheckGL(msg) glErrorCheck (msg, __FILE__, __LINE__)
#define ForceCheckGL(msg) glForceErrorCheck(msg, __FILE__, __LINE__)
#define CheckGLSkip(msg) glErrorSkip (msg, __FILE__, __LINE__)
namespace graphics
{
enum Defaults {
WIDTH = 1280,
HEIGHT= 720
};
static const long long _16BIT = 0x000000000000FFFF;
static const long long _32BIT = 0x00000000FFFFFFFF;
static const long long _48BIT = 0x0000FFFFFFFFFFFF;
typedef std::map<long long, fg::Image*> ImageMap_t;
typedef std::map<long long, fg::Plot*> PlotMap_t;
typedef std::map<long long, fg::Histogram*> HistogramMap_t;
typedef ImageMap_t::iterator ImgMapIter;
typedef PlotMap_t::iterator PltMapIter;
typedef HistogramMap_t::iterator HstMapIter;
/**
* ForgeManager class follows a single pattern. Any user of this class, has
* to call ForgeManager::getInstance inorder to use Forge resources for rendering.
* It manages the windows, and other renderables (given below) that are drawed
* onto chosen window.
* Renderables:
* fg::Image
* fg::Plot
* fg::Histogram
* */
class ForgeManager
{
private:
ImageMap_t mImgMap;
PlotMap_t mPltMap;
HistogramMap_t mHstMap;
public:
static ForgeManager& getInstance();
~ForgeManager();
fg::Font* getFont(const bool dontCreate=false);
fg::Window* getMainWindow(const bool dontCreate=false);
fg::Image* getImage(int w, int h, fg::ColorMode mode, fg::FGType type);
fg::Plot* getPlot(int nPoints, fg::FGType type);
fg::Histogram* getHistogram(int nBins, fg::FGType type);
protected:
ForgeManager() {}
ForgeManager(ForgeManager const&);
void operator=(ForgeManager const&);
void destroyResources();
};
}
#define MAIN_WINDOW graphics::ForgeManager::getInstance().getMainWindow(true)
#endif
| 29.206522
| 82
| 0.670636
|
JuliaComputing
|
ac73d7723b986f9918a84f5b983ca76be10bff40
| 409
|
cpp
|
C++
|
tests/common/FunexTest.cpp
|
boldowa/GIEPY
|
5aa326b264ef19f71d2e0ab5513b08fac7bca941
|
[
"MIT"
] | 8
|
2018-03-15T22:01:35.000Z
|
2019-07-13T18:04:41.000Z
|
tests/common/FunexTest.cpp
|
telinc1/GIEPY
|
9c87ad1070e519637fc4b11b6bef01f998961678
|
[
"MIT"
] | 21
|
2018-02-18T06:25:40.000Z
|
2018-07-13T17:54:40.000Z
|
tests/common/FunexTest.cpp
|
telinc1/GIEPY
|
9c87ad1070e519637fc4b11b6bef01f998961678
|
[
"MIT"
] | 2
|
2018-07-25T21:04:23.000Z
|
2022-01-01T08:40:13.000Z
|
/**
* FunexTest.cpp
*/
#include <bolib.h>
#include "common/Funex.h"
#include "CppUTest/TestHarness.h"
TEST_GROUP(Funex)
{
void setup()
{
}
void teardown()
{
}
};
TEST(Funex, FunexMatch)
{
}
TEST(Funex, ishex)
{
}
TEST(Funex, atoh)
{
}
TEST(Funex, IsSpace)
{
}
TEST(Funex, CutOffTailSpaces)
{
}
TEST(Funex, SkipUntilSpaces)
{
}
TEST(Funex, SkipSpacesRev)
{
}
TEST(Funex, SkipUntilChar)
{
}
| 7.865385
| 33
| 0.640587
|
boldowa
|
ac75db0aa1c9874d955232f8b76b7cb84a7b0012
| 2,022
|
hpp
|
C++
|
src/trafficsim/RoadTile.hpp
|
lutrarutra/trafsim
|
05e87b263b48e39d63f699dcaa456f10ca61e9a4
|
[
"Apache-2.0"
] | 12
|
2019-12-28T21:45:23.000Z
|
2022-03-28T12:40:44.000Z
|
src/trafficsim/RoadTile.hpp
|
lutrarutra/trafsim
|
05e87b263b48e39d63f699dcaa456f10ca61e9a4
|
[
"Apache-2.0"
] | null | null | null |
src/trafficsim/RoadTile.hpp
|
lutrarutra/trafsim
|
05e87b263b48e39d63f699dcaa456f10ca61e9a4
|
[
"Apache-2.0"
] | 1
|
2021-05-31T10:22:41.000Z
|
2021-05-31T10:22:41.000Z
|
#pragma once
#include <array>
#include <climits> // UINT_MAX
#include <SFML/Graphics.hpp>
#include "Tile.hpp"
#include "TrafficLight.hpp"
namespace ts
{
/*
* Every Road type is derived from this class
* RoadTile is abstract class, and is derived from Tile
*
* Functions inherited from Tile:
* getNode()
* getPos()
* getTileIndex()
*
* Overrided function from Tile:
* getType()
*
* Functions to implement in derived classes:
* getType()
* connect()
* connectableFrom()
* canConnectTo()
*/
enum RoadType
{
StraightRoadType = 0,
RoadTurnType,
IntersectionType,
TrisectionType,
JunctionType,
HomeRoadType,
// Keep as last
RoadTypeCount,
};
class RoadTile : public Tile
{
public:
RoadTile(const Tile &tile);
virtual TileCategory getCategory() const { return TileCategory::RoadCategory; };
virtual RoadType getType() const = 0;
// Direction of the road
// Up: { 0, 1 }, Right { 1, 0 }, Down { 0, -1 }, Left { -1, 0 }
const sf::Vector2f &getDir() const { return dir_; }
bool isFlipped() const { return right_turn_; }
TrafficLight *getLight() { return light_.get(); }
void rotate();
virtual void flip();
void addLight(unsigned int handler_id, float green_time);
unsigned int removeLight();
// Auto rotates road if there is neighbor, only RoadTurn has own implementation
virtual void autoRotate(std::array<Tile *, 4> &neighbors);
// Pure virtual functions
virtual void connect(std::array<Tile *, 4> &neighbors) = 0;
virtual bool connectableFrom(NeighborIndex n_index) const = 0;
virtual bool canConnectTo(NeighborIndex n_index) const = 0;
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
protected:
// Up: { 0, 1 }, Right { 1, 0 }, Down { 0, -1 }, Left { -1, 0 }
sf::Vector2f dir_;
bool right_turn_ = true;
std::unique_ptr<TrafficLight> light_ = nullptr;
void connectTo(Tile *another, NeighborIndex from);
};
} // namespace ts
| 24.658537
| 84
| 0.661721
|
lutrarutra
|
ac79c816f4f43e7b2101141a3716b678589576d4
| 13,006
|
cpp
|
C++
|
frameworks/object/modules/basic/dmzObjectModuleGridBasic.cpp
|
dmzgroup/dmz
|
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
|
[
"MIT"
] | 2
|
2015-11-05T03:03:43.000Z
|
2017-05-15T12:55:39.000Z
|
frameworks/object/modules/basic/dmzObjectModuleGridBasic.cpp
|
dmzgroup/dmz
|
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
|
[
"MIT"
] | null | null | null |
frameworks/object/modules/basic/dmzObjectModuleGridBasic.cpp
|
dmzgroup/dmz
|
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
|
[
"MIT"
] | null | null | null |
#include <dmzObjectAttributeMasks.h>
#include "dmzObjectModuleGridBasic.h"
#include <dmzRuntimeConfigToTypesBase.h>
#include <dmzRuntimeConfigToVector.h>
#include <dmzRuntimePluginFactoryLinkSymbol.h>
#include <dmzRuntimePluginInfo.h>
#include <dmzTypesVolume.h>
/*!
\class dmz::ObjectModuleGridBasic
\ingroup Object
\brief Basic ObjectModuleGrid implementation.
\details This provids a basic implementation of the ObjectModuleGrid.
\code
<dmz>
<dmzObjectModuleGridBasic>
<grid>
<cell x="X cell dimension" y="Y cell dimension"/>
<min x="min x" y="min y" z="min z"/>
<max x="max x" y="max y" z="max z"/>
</grid>
</dmzObjectModuleGridBasic>
</dmz>
\endcode
*/
//! \cond
dmz::ObjectModuleGridBasic::ObjectModuleGridBasic (
const PluginInfo &Info,
Config &local) :
Plugin (Info),
ObjectModuleGrid (Info),
ObjectObserverUtil (Info, local),
_log (Info),
_primaryAxis (VectorComponentX),
_secondaryAxis (VectorComponentZ),
_xCoordMax (100),
_yCoordMax (100),
_maxGrid (100000.0, 0.0, 100000.0),
_xCellSize (0.0),
_yCellSize (0.0),
_grid (0) {
_init (local);
}
dmz::ObjectModuleGridBasic::~ObjectModuleGridBasic () {
if (_grid) { delete []_grid; _grid = 0; }
_objTable.empty ();
_obsTable.empty ();
}
// Plugin Interface
void
dmz::ObjectModuleGridBasic::update_plugin_state (
const PluginStateEnum State,
const UInt32 Level) {
if (State == PluginStateInit) {
}
else if (State == PluginStateStart) {
}
else if (State == PluginStateStop) {
}
else if (State == PluginStateShutdown) {
}
}
void
dmz::ObjectModuleGridBasic::discover_plugin (
const PluginDiscoverEnum Mode,
const Plugin *PluginPtr) {
if (Mode == PluginDiscoverAdd) {
}
else if (Mode == PluginDiscoverRemove) {
}
}
// ObjectModuleGrid Interface
dmz::Boolean
dmz::ObjectModuleGridBasic::register_object_observer_grid (ObjectObserverGrid &observer) {
Boolean result (False);
ObserverStruct *os (_obsTable.lookup (observer.get_object_observer_grid_handle ()));
if (!os) {
os = new ObserverStruct (observer);
if (!_obsTable.store (os->ObsHandle, os)) { delete os; os = 0; }
result = update_object_observer_grid (observer);
}
return result;
}
dmz::Boolean
dmz::ObjectModuleGridBasic::update_object_observer_grid (ObjectObserverGrid &observer) {
Boolean result (False);
ObserverStruct *os (_obsTable.lookup (observer.get_object_observer_grid_handle ()));
if (os) {
const Volume &SearchSpace = os->obs.get_observer_volume ();
Vector origin, min, max;
SearchSpace.get_extents (origin, min, max);
Int32 minX = 0, minY = 0, maxX = 0, maxY = 0;
_map_point_to_coord (min, minX, minY);
_map_point_to_coord (max, maxX, maxY);
Boolean updateExtents = False;
if (
(minX != os->minX) ||
(maxX != os->maxX) ||
(minY != os->minY) ||
(maxY != os->maxY)) { updateExtents = True; }
if (updateExtents && (os->minX >= 0)) {
for (Int32 ix = os->minX; ix <= os->maxX; ix++) {
for (Int32 jy = os->minY; jy <= os->maxY; jy++) {
const Int32 Place = _map_coord (ix, jy);
_grid[Place].obsTable.remove (os->ObsHandle);
HashTableHandleIterator it;
GridStruct *cell = &(_grid[Place]);
ObjectStruct *current = cell->objTable.get_first (it);
while (current) {
if (!SearchSpace.contains_point (current->pos) &&
os->objects.remove (current->Object)) {
observer.update_object_grid_state (
ObjectGridStateExit,
current->Object,
current->Type,
current->pos);
}
current = cell->objTable.get_next (it);
}
}
}
}
os->minX = minX;
os->maxX = maxX;
os->minY = minY;
os->maxY = maxX;
for (Int32 ix = os->minX; ix <= os->maxX; ix++) {
for (Int32 jy = os->minY; jy <= os->maxY; jy++) {
const Int32 Place = _map_coord (ix, jy);
GridStruct *cell = &(_grid[Place]);
if (updateExtents) { cell->obsTable.store (os->ObsHandle, os); }
HashTableHandleIterator it;
ObjectStruct *current = cell->objTable.get_first (it);
while (current) {
_update_observer (SearchSpace, *current, *os);
current = cell->objTable.get_next (it);
}
}
}
result = True;
}
return result;
}
dmz::Boolean
dmz::ObjectModuleGridBasic::release_object_observer_grid (ObjectObserverGrid &observer) {
Boolean result (False);
ObserverStruct *os (_obsTable.remove (observer.get_object_observer_grid_handle ()));
if (os) {
for (Int32 ix = os->minX; ix <= os->maxX; ix++) {
for (Int32 jy = os->minY; jy <= os->maxY; jy++) {
const Int32 Place = _map_coord (ix, jy);
_grid[Place].obsTable.remove (os->ObsHandle);
}
}
delete os; os = 0;
result = True;
}
return result;
}
void
dmz::ObjectModuleGridBasic::find_objects (
const Volume &SearchSpace,
HandleContainer &objects,
const ObjectTypeSet *IncludeTypes,
const ObjectTypeSet *ExcludeTypes) {
Vector origin, min, max;
SearchSpace.get_extents (origin, min, max);
Int32 minX = 0, minY = 0, maxX = 0, maxY = 0;
_map_point_to_coord (min, minX, minY);
_map_point_to_coord (max, maxX, maxY);
ObjectStruct *list (0);
// HandleContainer found;
for (Int32 ix = minX; ix <= maxX; ix++) {
for (Int32 jy = minY; jy <= maxY; jy++) {
HashTableHandleIterator it;
GridStruct *cell = &(_grid[_map_coord (ix, jy)]);
ObjectStruct *current = cell->objTable.get_first (it);
while (current) {
Boolean test (True);
if (IncludeTypes && !IncludeTypes->contains_type (current->Type)) {
test = False;
}
else if (ExcludeTypes && ExcludeTypes->contains_type (current->Type)) {
test = False;
}
if (test && SearchSpace.contains_point (current->pos)) {
#if 0
if (!found.add_handle (current->Object)) {
_log.error << "origin: " << origin << endl
<< "minX: " << minX << endl
<< "minY: " << minY << endl
<< "maxX: " << maxX << endl
<< "maxY: " << maxY << endl;
HandleContainer cc;
for (Int32 xx = minX; xx <= maxX; xx++) {
for (Int32 yy = minY; yy <= maxY; yy++) {
Boolean s = cc.add_handle ((Handle)_map_coord (xx, yy));
_log.error << (s ? "" : "##### NOT UNIQUE ") << xx << " " << yy << " = " << _map_coord (xx, yy) << endl;
}
}
}
#endif // 0
current->distanceSquared = (origin - current->pos).magnitude_squared ();
current->next = 0;
if (!list) { list = current; }
else {
ObjectStruct *p = 0, *c = list;
Boolean done (False);
while (!done) {
if (c->distanceSquared > current->distanceSquared) {
if (!c->next) { c->next = current; done = True; }
else {
p = c; c = c->next;
if (!c) { p->next = current; done = True; }
}
}
else {
if (p) { p->next = current; }
else { list = current; }
current->next = c;
done = True;
}
}
}
}
current = cell->objTable.get_next (it);
}
}
}
while (list) {
if (!objects.add (list->Object)) {
_log.error << "Loop detected in object list for object: " << list->Object
<< endl;
list = 0;
}
else { list = list->next; }
}
}
// Object Observer Interface
void
dmz::ObjectModuleGridBasic::create_object (
const UUID &Identity,
const Handle ObjectHandle,
const ObjectType &Type,
const ObjectLocalityEnum Locality) {
ObjectStruct *os = new ObjectStruct (ObjectHandle, Type);
if (!_objTable.store (ObjectHandle, os)) { delete os; os = 0; }
}
void
dmz::ObjectModuleGridBasic::destroy_object (
const UUID &Identity,
const Handle ObjectHandle) {
ObjectStruct *os (_objTable.remove (ObjectHandle));
if (os) {
_remove_object_from_grid (*os);
if (os->place >= 0) {
HashTableHandleIterator it;
ObserverStruct *obs = _grid[os->place].obsTable.get_first (it);
while (obs) {
obs->objects.remove (ObjectHandle);
obs = _grid[os->place].obsTable.get_next (it);
}
}
delete os; os = 0;
}
}
void
dmz::ObjectModuleGridBasic::update_object_position (
const UUID &Identity,
const Handle ObjectHandle,
const Handle AttributeHandle,
const Vector &Value,
const Vector *PreviousValue) {
ObjectStruct *current (_objTable.lookup (ObjectHandle));
if (current && _grid) {
current->pos = Value;
const Int32 OldPlace = current->place;
const Int32 Place = _map_point (Value);
if (Place != current->place) {
_remove_object_from_grid (*current);
current->place = Place;
_grid[Place].objTable.store (current->Object, current);
}
if ((Place != OldPlace) && (OldPlace >= 0)) {
HashTableHandleIterator it;
GridStruct *cell = &(_grid[OldPlace]);
ObserverStruct *os = cell->obsTable.get_first (it);
HandleContainer tested;
while (os) {
tested.add (os->ObsHandle);
_update_observer (
os->obs.get_observer_volume (),
*current,
*os);
os = cell->obsTable.get_next (it);
}
cell = &(_grid[Place]);
os = cell->obsTable.get_first (it);
while (os) {
if (!tested.contains (os->ObsHandle)) {
_update_observer (
os->obs.get_observer_volume (),
*current,
*os);
}
os = cell->obsTable.get_next (it);
}
}
else {
HashTableHandleIterator it;
GridStruct *cell = &(_grid[Place]);
ObserverStruct *os = cell->obsTable.get_first (it);
while (os) {
_update_observer (
os->obs.get_observer_volume (),
*current,
*os);
os = cell->obsTable.get_next (it);
}
}
}
}
void
dmz::ObjectModuleGridBasic::_remove_object_from_grid (ObjectStruct &obj) {
if (_grid && obj.place >= 0) {
_grid[obj.place].objTable.remove (obj.Object);
}
}
void
dmz::ObjectModuleGridBasic::_update_observer (
const Volume &SearchSpace,
const ObjectStruct &Obj,
ObserverStruct &os) {
const Boolean Contains = SearchSpace.contains_point (Obj.pos);
if (Contains && os.objects.add (Obj.Object)) {
os.obs.update_object_grid_state (
ObjectGridStateEnter,
Obj.Object,
Obj.Type,
Obj.pos);
}
else if (!Contains && os.objects.remove (Obj.Object)) {
os.obs.update_object_grid_state (
ObjectGridStateExit,
Obj.Object,
Obj.Type,
Obj.pos);
}
}
void
dmz::ObjectModuleGridBasic::_init (Config &local) {
_xCoordMax = config_to_int32 ("grid.cell.x", local, _xCoordMax);
_yCoordMax = config_to_int32 ("grid.cell.y", local, _yCoordMax);
_minGrid = config_to_vector ("grid.min", local, _minGrid);
_maxGrid = config_to_vector ("grid.max", local, _maxGrid);
_log.info << "grid: " << _xCoordMax << "x" << _yCoordMax << endl;
_log.info << "extents:" << endl
<< "\t" << _minGrid << endl
<< "\t" << _maxGrid << endl;
Vector vec (_maxGrid - _minGrid);
_xCellSize = vec.get (_primaryAxis) / (Float64)(_xCoordMax);
_yCellSize = vec.get (_secondaryAxis) / (Float64)(_yCoordMax);
_log.info << "cell count: " << _xCoordMax * _yCoordMax << endl;
if (is_zero64 (_xCellSize)) { _xCellSize = 1.0; }
if (is_zero64 (_yCellSize)) { _yCellSize = 1.0; }
_grid = new GridStruct[_xCoordMax * _yCoordMax];
activate_default_object_attribute (
ObjectCreateMask | ObjectDestroyMask | ObjectPositionMask);
}
//! \endcond
extern "C" {
DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin *
create_dmzObjectModuleGridBasic (
const dmz::PluginInfo &Info,
dmz::Config &local,
dmz::Config &global) {
return new dmz::ObjectModuleGridBasic (Info, local);
}
};
| 23.908088
| 104
| 0.559819
|
dmzgroup
|
ac7ec77ea103427b85401cf12cbcdde234ceabdd
| 15,125
|
cpp
|
C++
|
Caesar/Hack/Aimbot/Aimbot.cpp
|
danielkrupinski/caesar
|
8d84261f2b9e01c0c0d40220db301b5a0d508b3d
|
[
"MIT"
] | 27
|
2018-08-31T18:57:24.000Z
|
2022-02-13T22:58:05.000Z
|
Caesar/Hack/Aimbot/Aimbot.cpp
|
danielkrupinski/caesar
|
8d84261f2b9e01c0c0d40220db301b5a0d508b3d
|
[
"MIT"
] | 6
|
2018-09-19T21:50:38.000Z
|
2020-07-28T13:48:47.000Z
|
Caesar/Hack/Aimbot/Aimbot.cpp
|
danielkrupinski/caesar
|
8d84261f2b9e01c0c0d40220db301b5a0d508b3d
|
[
"MIT"
] | 9
|
2018-10-07T09:10:20.000Z
|
2021-04-30T16:44:43.000Z
|
#include "../../Required.h"
#include "../../Config.h"
extern Config config;
CAimBot g_AimBot;
void SmoothAimAngles(QAngle MyViewAngles, QAngle AimAngles, QAngle &OutAngles, float Smoothing, bool bSpiral, float SpiralX, float SpiralY)
{
if (Smoothing < 1)
{
OutAngles = AimAngles;
return;
}
OutAngles = AimAngles - MyViewAngles;
OutAngles.Normalize();
Vector vecViewAngleDelta = OutAngles;
if (bSpiral && SpiralX != 0 && SpiralY != 0)
vecViewAngleDelta += Vector(vecViewAngleDelta.y / SpiralX, vecViewAngleDelta.x / SpiralY, 0.0f);
if (!isnan(Smoothing))
vecViewAngleDelta /= Smoothing;
OutAngles = MyViewAngles + vecViewAngleDelta;
OutAngles.Normalize();
}
void CAimBot::Run(struct usercmd_s *cmd)
{
if (config.aimbot.enabled)
{
RageAimbot(cmd);
}
else
{
LegitAimbot(cmd);
Trigger(cmd);
}
}
void CAimBot::Trigger(struct usercmd_s *cmd)
{
if (config.trigger_key > 0 && config.trigger_key < 255)
{
static DWORD dwTemporaryBlockTimer = 0;
if (GetTickCount() - dwTemporaryBlockTimer > 200)
{
if (g_Menu.keys[config.trigger_key]) {
TriggerKeyStatus = !TriggerKeyStatus;
dwTemporaryBlockTimer = GetTickCount();
}
}
if (!TriggerKeyStatus)
return;
}
if (!IsCurWeaponGun() || !CanAttack())
return;
unsigned int m_iWeaponID = g_Local.weapon.m_iWeaponID;
if (!config.legit[m_iWeaponID].trigger)
return;
if (config.trigger_only_zoomed && IsCurWeaponSniper() && g_Local.iFOV == DEFAULT_FOV)
return;
std::deque<unsigned int> Hitboxes;
if (config.legit[m_iWeaponID].trigger_head)
{
Hitboxes.push_back(11);
}
if (config.legit[m_iWeaponID].trigger_chest)
{
Hitboxes.push_back(7);
Hitboxes.push_back(8);
Hitboxes.push_back(9);
Hitboxes.push_back(10);
Hitboxes.push_back(11);
Hitboxes.push_back(12);
Hitboxes.push_back(17);
}
if (config.legit[m_iWeaponID].trigger_stomach)
{
Hitboxes.push_back(0);
}
float flAccuracy = config.legit[m_iWeaponID].trigger_accuracy;
Vector vecSpreadDir, vecForward, vecRight, vecUp, vecRandom;
QAngle QAngles;
g_Engine.GetViewAngles(QAngles);
if (flAccuracy > 0)//Recoil
{
QAngles[0] += g_Local.vPunchangle[0];
QAngles[1] += g_Local.vPunchangle[1];
QAngles[2] = NULL;
}
QAngles.Normalize();
QAngles.AngleVectors(&vecForward, &vecRight, &vecUp);
if (flAccuracy > 1)//Recoil / Spread
{
g_NoSpread.GetSpreadXY(g_Local.weapon.random_seed, 1, vecRandom);
vecSpreadDir = vecForward + (vecRight * vecRandom[0]) + (vecUp * vecRandom[1]);
vecSpreadDir.Normalize();
}
else {//Empty or Recoil
vecSpreadDir = vecForward;
vecSpreadDir.Normalize();
}
for (int id = 1; id <= g_Engine.GetMaxClients(); ++id)
{
if (id == g_Local.iIndex)
continue;
if (!g_Player[id].bAlive)
continue;
if (!g_Player[id].bVisible)
continue;
if (g_Player[id].bFriend)
continue;
if (!config.legit_teammates && g_Player[id].iTeam == g_Local.iTeam)
continue;
for (auto &&hitbox : Hitboxes)
{
if (g_Utils.IsBoxIntersectingRay(g_PlayerExtraInfoList[id].vHitboxMin[hitbox], g_PlayerExtraInfoList[id].vHitboxMax[hitbox], g_Local.vEye, vecSpreadDir))
{
cmd->buttons |= IN_ATTACK;
break;
}
}
}
}
void CAimBot::LegitAimbot(struct usercmd_s *cmd)
{
static DWORD dwBlockAttack = 0;
static float flSpeedSpiralX = 1.3;
static float flSpeedSpiralY = 3.7;
m_flCurrentFOV = 0;
if (!IsCurWeaponGun() || g_Local.weapon.m_iInReload || g_Local.weapon.m_iClip < 1 || g_Local.weapon.m_flNextAttack > 0.0)
return;
unsigned int iWeaponID = g_Local.weapon.m_iWeaponID;
if (!config.legit[iWeaponID].aim)
return;
float flFOV = config.legit[iWeaponID].aim_fov;
if (flFOV <= 0)
return;
float flSpeed = config.legit[iWeaponID].aim_speed_in_attack;
if (config.legit[iWeaponID].aim_speed > 0 && !(cmd->buttons & IN_ATTACK))//Auto aim smooth
flSpeed = config.legit[iWeaponID].aim_speed;
if (flSpeed <= 0)
return;
std::deque<unsigned int> Hitboxes;
if (config.legit[iWeaponID].aim_head)
Hitboxes.push_back(11);
if (config.legit[iWeaponID].aim_chest)
{
Hitboxes.push_back(7);
Hitboxes.push_back(8);
Hitboxes.push_back(9);
Hitboxes.push_back(10);
Hitboxes.push_back(12);
Hitboxes.push_back(17);
}
if (config.legit[iWeaponID].aim_stomach)
Hitboxes.push_back(0);
if (Hitboxes.empty())
return;
float flReactionTime = config.legit[iWeaponID].aim_reaction_time;
if (flReactionTime > 0 && GetTickCount() - dwReactionTime < flReactionTime)
return;
float flSpeedScaleFov = config.legit[iWeaponID].aim_speed_scale_fov;
bool bSpeedSpiral = config.legit[iWeaponID].aim_humanize;
if (!g_Local.vPunchangle.IsZero2D())
bSpeedSpiral = false;
float flRecoilCompensationPitch = 0.02f * config.legit[iWeaponID].aim_recoil_compensation_pitch;
float flRecoilCompensationYaw = 0.02f * config.legit[iWeaponID].aim_recoil_compensation_yaw;
int iRecoilCompensationAfterShotsFired = static_cast<int>(config.legit[iWeaponID].aim_recoil_compensation_after_shots_fired);
if (iRecoilCompensationAfterShotsFired > 0 && g_Local.weapon.m_iShotsFired <= iRecoilCompensationAfterShotsFired)
{
flRecoilCompensationPitch = 0;
flRecoilCompensationYaw = 0;
}
float flBlockAttackAfterKill = config.block_attack_after_kill;
float flAccuracy = config.legit[iWeaponID].aim_accuracy;
float flPSilent = config.legit[iWeaponID].aim_psilent;
Vector vecFOV = {};
{
QAngle QAngles = cmd->viewangles + g_Local.vPunchangle * 2;
QAngles.Normalize();
QAngles.AngleVectors(&vecFOV, NULL, NULL);
vecFOV.Normalize();
}
m_flCurrentFOV = flFOV;
unsigned int iTarget = 0;
unsigned int iHitbox = 0;
float flBestFOV = flFOV;
for (int id = 1; id <= g_Engine.GetMaxClients(); ++id)
{
if (id == g_Local.iIndex)
continue;
if (!g_Player[id].bAlive)
continue;
if (!g_Player[id].bVisible)
continue;
if (g_Player[id].bFriend)
continue;
if (!config.legit_teammates && g_Player[id].iTeam == g_Local.iTeam)
continue;
for (auto &&hitbox : Hitboxes)
{
if (!g_PlayerExtraInfoList[id].bHitboxVisible[hitbox])
continue;
if (config.legit[iWeaponID].aim_head && (config.legit[iWeaponID].aim_chest || config.legit[iWeaponID].aim_stomach) && hitbox == 11 && (!(g_Local.weapon.m_iFlags & FL_ONGROUND) || g_Local.flVelocity > 140 || g_Local.weapon.m_iShotsFired > 5))
continue;
if (config.legit[iWeaponID].aim_chest && config.legit[iWeaponID].aim_stomach && hitbox != 0 && hitbox != 11 && (!(g_Local.weapon.m_iFlags & FL_ONGROUND) || g_Local.weapon.m_iShotsFired > 15))
continue;
float fov = vecFOV.AngleBetween(g_PlayerExtraInfoList[id].vHitbox[hitbox] - g_Local.vEye);
if (fov < flBestFOV)
{
flBestFOV = fov;
iTarget = id;
iHitbox = hitbox;
}
}
}
if (iTarget > 0)
{
bool bAttack = false;
bool bBlock = false;//Block IN_ATTACK?
if (config.legit[iWeaponID].aim_quick_stop)
{
cmd->forwardmove = 0;
cmd->sidemove = 0;
cmd->upmove = 0;
}
QAngle QMyAngles, QAimAngles, QNewAngles, QSmoothAngles;
Vector vAimOrigin = g_PlayerExtraInfoList[iTarget].vHitbox[iHitbox];
g_Engine.GetViewAngles(QMyAngles);
g_Utils.VectorAngles(vAimOrigin - g_Local.vEye, QAimAngles);
if (flPSilent > 0 && flPSilent <= 1 && CanAttack())
{
QAngle QAnglePerfectSilent = QAimAngles;
QAnglePerfectSilent += g_Local.vPunchangle;
QAnglePerfectSilent.Normalize();
g_NoSpread.GetSpreadOffset(g_Local.weapon.random_seed, 1, QAnglePerfectSilent, QAnglePerfectSilent);
Vector vecPsilentFOV;
QAnglePerfectSilent.AngleVectors(&vecPsilentFOV, NULL, NULL);
vecPsilentFOV.Normalize();
float fov = vecPsilentFOV.AngleBetween(g_PlayerExtraInfoList[iTarget].vHitbox[iHitbox] - g_Local.vEye);
if (fov <= flPSilent)
{
cmd->buttons |= IN_ATTACK;
g_Utils.MakeAngle(false, QAnglePerfectSilent, cmd);
g_Utils.bSendpacket(false);
dwBlockAttack = GetTickCount();
return;
}
}
QNewAngles[0] = QAimAngles[0] - g_Local.vPunchangle[0] * flRecoilCompensationPitch;
QNewAngles[1] = QAimAngles[1] - g_Local.vPunchangle[1] * flRecoilCompensationYaw;
QNewAngles[2] = 0;
QNewAngles.Normalize();
/*if (cmd->buttons & IN_ATTACK && CanAttack())
g_NoSpread.GetSpreadOffset(g_Local.weapon.random_seed, 1, QNewAngles, QNewAngles);*/
if (flSpeedScaleFov > 0 && flSpeedScaleFov <= 100 && g_Local.vPunchangle.IsZero() && !isnan(g_PlayerExtraInfoList[iTarget].fHitboxFOV[iHitbox]))
flSpeed = flSpeed - (((g_PlayerExtraInfoList[iTarget].fHitboxFOV[iHitbox] * (flSpeed / m_flCurrentFOV)) * flSpeedScaleFov) / 100);//speed - (((fov * (speed / 180)) * scale) / 100)
SmoothAimAngles(QMyAngles, QNewAngles, QSmoothAngles, flSpeed, bSpeedSpiral, flSpeedSpiralX, flSpeedSpiralY);
if (flAccuracy > 0)
{
bBlock = true;
QAngle QAngleAccuracy = QAimAngles;
Vector vecSpreadDir;
if (flAccuracy == 1)//Aiming
{
QSmoothAngles.AngleVectors(&vecSpreadDir, NULL, NULL);
vecSpreadDir.Normalize();
}
else if (flAccuracy == 2) //Recoil
{
Vector vecRandom, vecForward;
SmoothAimAngles(QMyAngles, QAimAngles, QAngleAccuracy, flSpeed, bSpeedSpiral, flSpeedSpiralX, flSpeedSpiralY);
QAngleAccuracy[0] += g_Local.vPunchangle[0];
QAngleAccuracy[1] += g_Local.vPunchangle[1];
QAngleAccuracy[2] = NULL;
QAngleAccuracy.Normalize();
QAngleAccuracy.AngleVectors(&vecForward, NULL, NULL);
vecSpreadDir = vecForward;
vecSpreadDir.Normalize();
}
else //Recoil / Spread
{
Vector vecRandom, vecRight, vecUp, vecForward;
SmoothAimAngles(QMyAngles, QAimAngles, QAngleAccuracy, flSpeed, bSpeedSpiral, flSpeedSpiralX, flSpeedSpiralY);
QAngleAccuracy[0] += g_Local.vPunchangle[0];
QAngleAccuracy[1] += g_Local.vPunchangle[1];
QAngleAccuracy[2] = NULL;
QAngleAccuracy.Normalize();
QAngleAccuracy.AngleVectors(&vecForward, &vecRight, &vecRight);
g_NoSpread.GetSpreadXY(g_Local.weapon.random_seed, 1, vecRandom);
vecSpreadDir = vecForward + (vecRight * vecRandom[0]) + (vecUp * vecRandom[1]);
vecSpreadDir.Normalize();
}
for (unsigned int x = 0; x < Hitboxes.size(); x++)
{
unsigned int hitbox = Hitboxes[x];
if (g_Utils.IsBoxIntersectingRay(g_PlayerExtraInfoList[iTarget].vHitboxMin[hitbox], g_PlayerExtraInfoList[iTarget].vHitboxMax[hitbox], g_Local.vEye, vecSpreadDir))
{
bBlock = false;
break;
}
}
}
if (cmd->buttons & IN_ATTACK)
bAttack = true;
else if (config.legit[iWeaponID].aim_speed > 0)//Auto aim
{
bAttack = true;
bBlock = true;
}
if (bAttack)
{
QSmoothAngles.Normalize();
g_Utils.MakeAngle(false, QSmoothAngles, cmd);
g_Engine.SetViewAngles(QSmoothAngles);
if (!bBlock)
cmd->buttons |= IN_ATTACK;
else if (cmd->buttons & IN_ATTACK)
cmd->buttons &= ~IN_ATTACK;
if (!g_Local.vPunchangle.IsZero2D())
dwBlockAttack = GetTickCount();
}
}
else if (flBlockAttackAfterKill > 0 && GetTickCount() - dwBlockAttack < flBlockAttackAfterKill)
{
cmd->buttons &= ~IN_ATTACK;
}
}
void CAimBot::RageAimbot(struct usercmd_s *cmd)
{
if (!config.aimbot.enabled && !IsCurWeaponGun() || !CanAttack())
return;
std::deque<unsigned int> Hitboxes;
if (config.aimbot.hitbox == 1)//"Head", "Neck", "Chest", "Stomach"
{
Hitboxes.push_back(11);
}
else if (config.aimbot.hitbox == 2)
{
Hitboxes.push_back(10);
}
else if (config.aimbot.hitbox == 3)
{
Hitboxes.push_back(7);
}
else if (config.aimbot.hitbox == 4)
{
Hitboxes.push_back(0);
}
else if (config.aimbot.hitbox == 5)//All
{
for (unsigned int j = 0; j <= 11; j++)
Hitboxes.push_front(j);
for (int k = 12; k < g_Local.iMaxHitboxes; k++)
Hitboxes.push_back(k);
}
else if (config.aimbot.hitbox == 6)//Vital
{
for (unsigned int j = 0; j <= 11; j++)
Hitboxes.push_front(j);
}
if (Hitboxes.empty())
return;
unsigned int m_iTarget = 0;
int m_iHitbox = -1;
int m_iPoint = -1;
float m_flBestFOV = 180;
float m_flBestDist = 8192;
for (int id = 1; id <= g_Engine.GetMaxClients(); ++id)
{
if (id == g_Local.iIndex)
continue;
if (!g_Player[id].bAlive)
continue;
if (g_Player[id].bFriend)
continue;
if (!g_Player[id].bVisible)
continue;
if (!config.aimbot.teammates && g_Player[id].iTeam == g_Local.iTeam)
continue;
if (config.aimbot.delayShot)
{
cl_entity_s *ent = g_Engine.GetEntityByIndex(id);
if (ent && ent->curstate.frame != 0)
continue;
}
for (auto &&hitbox : Hitboxes)
{
if (g_PlayerExtraInfoList[id].bHitboxVisible[hitbox])
{
m_iHitbox = hitbox;
break;
}
}
if (m_iHitbox == -1)
{
for (auto &&hitbox : Hitboxes)
{
if (config.aimbot.multiPoint > 0)
{
if (config.aimbot.multiPoint == 1 && hitbox != 11)
continue;
if (config.aimbot.multiPoint == 2 && hitbox > 11)
continue;
for (unsigned int point = 0; point <= 8; ++point)
{
if (g_PlayerExtraInfoList[id].bHitboxPointsVisible[hitbox][point] && !g_PlayerExtraInfoList[id].bHitboxVisible[hitbox])
{
m_iPoint = point;
m_iHitbox = hitbox;
break;
}
}
}
}
}
if (m_iHitbox < 0 || m_iHitbox > g_Local.iMaxHitboxes)
continue;
if (g_Player[id].bPriority)
{
m_iTarget = id;
break;
}
//"Field of view", "Distance", "Cycle"
if (config.aimbot.targetSelection == 1)
{
if (g_PlayerExtraInfoList[id].fHitboxFOV[m_iHitbox] < m_flBestFOV)
{
m_flBestFOV = g_PlayerExtraInfoList[id].fHitboxFOV[m_iHitbox];
m_iTarget = id;
}
}
else if (config.aimbot.targetSelection == 2)
{
if (g_Player[id].flDist < m_flBestDist)
{
m_flBestDist = g_Player[id].flDist;
m_iTarget = id;
}
}
else if (config.aimbot.targetSelection == 3)
{
if (g_PlayerExtraInfoList[id].fHitboxFOV[m_iHitbox] < m_flBestFOV)
{
if (g_Player[id].flDist < m_flBestDist)
{
m_flBestFOV = g_PlayerExtraInfoList[id].fHitboxFOV[m_iHitbox];
m_flBestDist = g_Player[id].flDist;
m_iTarget = id;
}
}
}
}
if (m_iTarget > 0)
{
if (config.quick_stop_duck)
{
cmd->forwardmove = 0;
cmd->sidemove = 0;
cmd->upmove = 0;
cmd->buttons |= IN_DUCK;
}
else if (config.quick_stop)
{
cmd->forwardmove = 0;
cmd->sidemove = 0;
cmd->upmove = 0;
}
if (config.aimbot.autoscope && IsCurWeaponSniper() && g_Local.iFOV == DEFAULT_FOV)
{
cmd->buttons |= IN_ATTACK2;
}
else if (CanAttack())
{
QAngle QMyAngles, QAimAngles, QSmoothAngles;
Vector vAimOrigin;
if(m_iPoint >= 0 && m_iPoint < 8)
vAimOrigin = g_PlayerExtraInfoList[m_iTarget].vHitboxPoints[m_iHitbox][m_iPoint];
else
vAimOrigin = g_PlayerExtraInfoList[m_iTarget].vHitbox[m_iHitbox];
g_Engine.GetViewAngles(QMyAngles);
g_Utils.VectorAngles(vAimOrigin - g_Local.vEye, QAimAngles);
if (config.aimbot.perfectSilent)
{
g_Utils.MakeAngle(false, QAimAngles, cmd);
g_Utils.bSendpacket(false);
}
else {
g_Utils.MakeAngle(false, QAimAngles, cmd);
if (!config.aimbot.silent)
g_Engine.SetViewAngles(QAimAngles);
}
cmd->buttons |= IN_ATTACK;
}
else {
cmd->buttons &= ~IN_ATTACK;
}
}
}
| 23.341049
| 244
| 0.686479
|
danielkrupinski
|
ac7f583280c773e6d73aa692d441c3b074a3beed
| 2,230
|
cpp
|
C++
|
src/mainwindow.cpp
|
ashleyshu/sway
|
3c89ed47773267914ba9840bc4c85714403ca137
|
[
"MIT"
] | null | null | null |
src/mainwindow.cpp
|
ashleyshu/sway
|
3c89ed47773267914ba9840bc4c85714403ca137
|
[
"MIT"
] | null | null | null |
src/mainwindow.cpp
|
ashleyshu/sway
|
3c89ed47773267914ba9840bc4c85714403ca137
|
[
"MIT"
] | null | null | null |
#include <QDebug>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "tasklistdialog.h"
#include "conslistdialog.h"
#include "taskinputdialog.h"
#include "consinputdialog.h"
#include "schedulecreator.h"
#include "googlecal.h"
//! Main Window Class
/*!
\Author: Group 33
Description: Main window from where user can select options and use program.
*/
//! Construction
/*!
\Authors: Group 33
Description: Constructor
@param controller the input controller
@param parent the parent of this widget
*/
MainWindow::MainWindow(InputController *controller, QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow),
m_controller (controller)
{
Q_ASSERT(controller != nullptr);
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
//! Opens tasks view
void MainWindow::on_bTaskView_clicked()
{
TaskListDialog tasklistdialog(m_controller);
tasklistdialog.setModal(true);
tasklistdialog.exec();
}
//! Opens constraintss view
void MainWindow::on_bConsView_clicked()
{
ConsListDialog conslistdialog(m_controller);
conslistdialog.setModal(true);
conslistdialog.exec();
}
//! Opens task input screen
void MainWindow::on_bTaskAdd_clicked()
{
TaskInputDialog taskinputdialog(m_controller);
taskinputdialog.setModal(true);
taskinputdialog.exec();
}
//! Opens constraint input view
void MainWindow::on_bConsAdd_clicked()
{
ConsInputDialog consinputdialog(m_controller);
consinputdialog.setModal(true);
consinputdialog.exec();
}
//! Generatives schedule and saves as CSV
void MainWindow::on_bSchedGen_clicked()
{
ScheduleCreator scheduleCreator(m_controller);
scheduleCreator.createSchedule();
}
//! Opens google calendar dialog
void MainWindow::on_bGoogleCal_clicked()
{
GoogleCal googleCal;
googleCal.setModal(true);
googleCal.exec();
}
//! Save task and constraint inputs
void MainWindow::on_bSchedSave_clicked() {
m_controller->saveInputs();
}
//! Load task and constraint inputs
void MainWindow::on_bSchedLoad_clicked() {
m_controller->loadInputs();
}
| 20.272727
| 81
| 0.690583
|
ashleyshu
|
ac80c716b8c45340677a672b95e9b7cdead5efcb
| 3,025
|
cpp
|
C++
|
modcode/Client.cpp
|
eezstreet/Rapture
|
1022f1013d7a7a3a84ea3ba56518420daf4733fc
|
[
"ISC"
] | 2
|
2017-10-25T03:22:34.000Z
|
2020-04-02T16:33:40.000Z
|
modcode/Client.cpp
|
eezstreet/Rapture
|
1022f1013d7a7a3a84ea3ba56518420daf4733fc
|
[
"ISC"
] | 12
|
2016-07-03T21:08:25.000Z
|
2016-07-30T06:17:26.000Z
|
modcode/Client.cpp
|
eezstreet/Rapture
|
1022f1013d7a7a3a84ea3ba56518420daf4733fc
|
[
"ISC"
] | 3
|
2016-03-02T06:56:42.000Z
|
2018-04-13T14:37:06.000Z
|
#include "Client.h"
#include "ClientDisplay.h"
#include "ClientFont.h"
namespace Client {
static bool bInitialized = false;
/*
Packet serialization/deserialization functions.
The serialization function is called when a packet is next in the queue to be written.
The deserialization function is conversely called when a packet is received.
The deserialization function is expected to call the appropriate handler for the data as well.
If a serialization function is null, the engine will throw a warning upon queueing it for send from modcode.
If a deserialization function is null, the engine will throw a warning upon receipt.
*/
packetSerializationFunc clientFuncs[PACKET_MAX] = {
nullptr, // PACKET_PING
nullptr, // PACKET_PONG
nullptr, // PACKET_DROP
nullptr, // PACKET_CLIENTATTEMPT
nullptr, // PACKET_CLIENTACCEPT
nullptr, // PACKET_CLIENTDENIED
nullptr, // PACKET_INFOREQUEST
nullptr, // PACKET_INFOREQUESTED
nullptr, // PACKET_SENDCHAT // FIXME
nullptr, // PACKET_RECVCHAT // FIXME
};
packetDeserializationFunc dclientFuncs[PACKET_MAX] = {
nullptr, // PACKET_PING
nullptr, // PACKET_PONG
nullptr, // PACKET_DROP
nullptr, // PACKET_CLIENTATTEMPT
nullptr, // PACKET_CLIENTACCEPT
nullptr, // PACKET_CLIENTDENIED
nullptr, // PACKET_INFOREQUEST
nullptr, // PACKET_INFOREQUESTED
nullptr, // PACKET_SENDCHAT // FIXME
nullptr, // PACKET_RECVCHAT // FIXME
};
/* Initialization code */
void Initialize() {
if (bInitialized) {
return;
}
ClientFont::Initialize();
ClientDisplay::Initialize();
trap->printf(PRIORITY_MESSAGE, "Waiting for additional elements to complete...\n");
ClientFont::FinishInitialization();
trap->printf(PRIORITY_MESSAGE, "Client initialized successfully.\n");
bInitialized = true;
}
/* Shutdown code */
void Shutdown() {
if (!bInitialized) {
return;
}
ClientDisplay::Shutdown();
bInitialized = false;
}
/* Code that gets run every frame */
void Frame() {
ClientDisplay::DrawDisplay();
}
/*
Packet serialization function.
This calls the appropriate function in clientFuncs (or returns false if it doesn't exist)
Called from the engine when a send packet attempt has been dequeued.
The data isn't sent across the wire in clientFuncs, it's translated to packetData.
*/
bool SerializePacket(Packet& packet, int clientNum, void* extraData) {
if (clientFuncs[packet.packetHead.type]) {
clientFuncs[packet.packetHead.type](packet, clientNum, extraData);
return true;
}
return false;
}
/*
Packet deserialization function.
This calls the appropriate function in dclientFuncs (or returns false if it doesn't exist)
Called from the engine when we have received a packet.
The data is both deserialized and used in dclientFuncs
*/
bool DeserializePacket(Packet& packet, int clientNum) {
if (dclientFuncs[packet.packetHead.type]) {
dclientFuncs[packet.packetHead.type](packet, clientNum);
return true;
}
return false;
}
}
| 30.867347
| 110
| 0.729587
|
eezstreet
|
ac8209cc98e70c57ba64947689f569a1c3d585e4
| 1,195
|
hpp
|
C++
|
experimental/Pomdog.Experimental/Gameplay2D/Animator.hpp
|
bis83/pomdog
|
133a9262958d539ae6d93664e6cb2207b5b6c7ff
|
[
"MIT"
] | null | null | null |
experimental/Pomdog.Experimental/Gameplay2D/Animator.hpp
|
bis83/pomdog
|
133a9262958d539ae6d93664e6cb2207b5b6c7ff
|
[
"MIT"
] | null | null | null |
experimental/Pomdog.Experimental/Gameplay2D/Animator.hpp
|
bis83/pomdog
|
133a9262958d539ae6d93664e6cb2207b5b6c7ff
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#ifndef POMDOG_ANIMATOR_0CFC0E37_HPP
#define POMDOG_ANIMATOR_0CFC0E37_HPP
#include "Pomdog.Experimental/Gameplay/Component.hpp"
#include "Pomdog/Application/Duration.hpp"
#include <string>
#include <memory>
namespace Pomdog {
class Skeleton;
class SkeletonTransform;
class AnimationGraph;
class Animator: public Component<Animator> {
public:
Animator(std::shared_ptr<Skeleton> const& skeleton,
std::shared_ptr<SkeletonTransform> const& skeletonTransform,
std::shared_ptr<AnimationGraph> const& animationGraph);
~Animator();
void Update(Duration const& frameDuration);
void CrossFade(std::string const& state, Duration const& transitionDuration);
void Play(std::string const& state);
float PlaybackRate() const;
void PlaybackRate(float playbackRate);
void SetFloat(std::string const& name, float value);
void SetBool(std::string const& name, bool value);
std::string GetCurrentStateName() const;
private:
class Impl;
std::unique_ptr<Impl> impl;
};
} // namespace Pomdog
#endif // POMDOG_ANIMATOR_0CFC0E37_HPP
| 24.895833
| 81
| 0.745607
|
bis83
|
ac841a98df20217c9d4e857dfdf68828aaff42cf
| 6,100
|
hpp
|
C++
|
pomdog/pomdog.hpp
|
mogemimi/pomdog
|
6dc6244d018f70d42e61c6118535cf94a9ee0618
|
[
"MIT"
] | 163
|
2015-03-16T08:42:32.000Z
|
2022-01-11T21:40:22.000Z
|
pomdog/pomdog.hpp
|
mogemimi/pomdog
|
6dc6244d018f70d42e61c6118535cf94a9ee0618
|
[
"MIT"
] | 17
|
2015-04-12T20:57:50.000Z
|
2020-10-10T10:51:45.000Z
|
pomdog/pomdog.hpp
|
mogemimi/pomdog
|
6dc6244d018f70d42e61c6118535cf94a9ee0618
|
[
"MIT"
] | 21
|
2015-04-12T20:45:11.000Z
|
2022-01-14T20:50:16.000Z
|
// Copyright mogemimi. Distributed under the MIT license.
#pragma once
/// Root namespace for the Pomdog game engine.
namespace pomdog {
} // namespace pomdog
#include "pomdog/application/game.hpp"
#include "pomdog/application/game_host.hpp"
#include "pomdog/application/game_window.hpp"
#include "pomdog/application/mouse_cursor.hpp"
#include "pomdog/chrono/duration.hpp"
#include "pomdog/chrono/game_clock.hpp"
#include "pomdog/chrono/time_point.hpp"
#include "pomdog/chrono/timer.hpp"
#include "pomdog/audio/audio_channels.hpp"
#include "pomdog/audio/audio_clip.hpp"
#include "pomdog/audio/audio_emitter.hpp"
#include "pomdog/audio/audio_engine.hpp"
#include "pomdog/audio/audio_listener.hpp"
#include "pomdog/audio/sound_effect.hpp"
#include "pomdog/audio/sound_state.hpp"
#include "pomdog/content/asset_builders/pipeline_state_builder.hpp"
#include "pomdog/content/asset_builders/shader_builder.hpp"
#include "pomdog/content/asset_manager.hpp"
#include "pomdog/filesystem/file_system.hpp"
#include "pomdog/math/bounding_box.hpp"
#include "pomdog/math/bounding_box2d.hpp"
#include "pomdog/math/bounding_circle.hpp"
#include "pomdog/math/bounding_frustum.hpp"
#include "pomdog/math/bounding_sphere.hpp"
#include "pomdog/math/color.hpp"
#include "pomdog/math/containment_type.hpp"
#include "pomdog/math/degree.hpp"
#include "pomdog/math/math.hpp"
#include "pomdog/math/matrix2x2.hpp"
#include "pomdog/math/matrix3x2.hpp"
#include "pomdog/math/matrix3x3.hpp"
#include "pomdog/math/matrix4x4.hpp"
#include "pomdog/math/plane.hpp"
#include "pomdog/math/plane_intersection_type.hpp"
#include "pomdog/math/point2d.hpp"
#include "pomdog/math/point3d.hpp"
#include "pomdog/math/quaternion.hpp"
#include "pomdog/math/radian.hpp"
#include "pomdog/math/ray.hpp"
#include "pomdog/math/rectangle.hpp"
#include "pomdog/math/vector2.hpp"
#include "pomdog/math/vector3.hpp"
#include "pomdog/math/vector4.hpp"
#include "pomdog/network/array_view.hpp"
#include "pomdog/network/http_client.hpp"
#include "pomdog/network/http_method.hpp"
#include "pomdog/network/http_request.hpp"
#include "pomdog/network/http_response.hpp"
#include "pomdog/network/io_service.hpp"
#include "pomdog/network/tcp_stream.hpp"
#include "pomdog/network/tls_stream.hpp"
#include "pomdog/network/udp_stream.hpp"
#include "pomdog/logging/log.hpp"
#include "pomdog/logging/log_channel.hpp"
#include "pomdog/logging/log_entry.hpp"
#include "pomdog/logging/log_level.hpp"
#include "pomdog/graphics/blend_description.hpp"
#include "pomdog/graphics/blend_factor.hpp"
#include "pomdog/graphics/blend_operation.hpp"
#include "pomdog/graphics/buffer_usage.hpp"
#include "pomdog/graphics/comparison_function.hpp"
#include "pomdog/graphics/constant_buffer.hpp"
#include "pomdog/graphics/cull_mode.hpp"
#include "pomdog/graphics/depth_stencil_buffer.hpp"
#include "pomdog/graphics/depth_stencil_description.hpp"
#include "pomdog/graphics/depth_stencil_operation.hpp"
#include "pomdog/graphics/effect_annotation.hpp"
#include "pomdog/graphics/effect_constant_description.hpp"
#include "pomdog/graphics/effect_reflection.hpp"
#include "pomdog/graphics/effect_variable.hpp"
#include "pomdog/graphics/effect_variable_class.hpp"
#include "pomdog/graphics/effect_variable_type.hpp"
#include "pomdog/graphics/fill_mode.hpp"
#include "pomdog/graphics/graphics_command_list.hpp"
#include "pomdog/graphics/graphics_command_queue.hpp"
#include "pomdog/graphics/graphics_device.hpp"
#include "pomdog/graphics/index_buffer.hpp"
#include "pomdog/graphics/index_element_size.hpp"
#include "pomdog/graphics/input_classification.hpp"
#include "pomdog/graphics/input_element.hpp"
#include "pomdog/graphics/input_element_format.hpp"
#include "pomdog/graphics/input_layout_description.hpp"
#include "pomdog/graphics/input_layout_helper.hpp"
#include "pomdog/graphics/pipeline_state.hpp"
#include "pomdog/graphics/pipeline_state_description.hpp"
#include "pomdog/graphics/presentation_parameters.hpp"
#include "pomdog/graphics/primitive_topology.hpp"
#include "pomdog/graphics/rasterizer_description.hpp"
#include "pomdog/graphics/render_pass.hpp"
#include "pomdog/graphics/render_target2d.hpp"
#include "pomdog/graphics/render_target_blend_description.hpp"
#include "pomdog/graphics/sampler_description.hpp"
#include "pomdog/graphics/sampler_state.hpp"
#include "pomdog/graphics/shader.hpp"
#include "pomdog/graphics/shader_language.hpp"
#include "pomdog/graphics/shader_pipeline_stage.hpp"
#include "pomdog/graphics/stencil_operation.hpp"
#include "pomdog/graphics/surface_format.hpp"
#include "pomdog/graphics/texture.hpp"
#include "pomdog/graphics/texture2d.hpp"
#include "pomdog/graphics/texture_address_mode.hpp"
#include "pomdog/graphics/texture_filter.hpp"
#include "pomdog/graphics/vertex_buffer.hpp"
#include "pomdog/graphics/viewport.hpp"
#include "pomdog/input/button_state.hpp"
#include "pomdog/input/gamepad.hpp"
#include "pomdog/input/gamepad_buttons.hpp"
#include "pomdog/input/gamepad_capabilities.hpp"
#include "pomdog/input/gamepad_dpad.hpp"
#include "pomdog/input/gamepad_state.hpp"
#include "pomdog/input/gamepad_thumbsticks.hpp"
#include "pomdog/input/gamepad_uuid.hpp"
#include "pomdog/input/key_state.hpp"
#include "pomdog/input/keyboard.hpp"
#include "pomdog/input/keyboard_state.hpp"
#include "pomdog/input/keys.hpp"
#include "pomdog/input/mouse.hpp"
#include "pomdog/input/mouse_buttons.hpp"
#include "pomdog/input/mouse_state.hpp"
#include "pomdog/input/player_index.hpp"
#include "pomdog/input/touch_location.hpp"
#include "pomdog/input/touch_location_state.hpp"
#include "pomdog/signals/connection.hpp"
#include "pomdog/signals/connection_list.hpp"
#include "pomdog/signals/delegate.hpp"
#include "pomdog/signals/event_queue.hpp"
#include "pomdog/signals/scoped_connection.hpp"
#include "pomdog/signals/signal.hpp"
#include "pomdog/signals/signal_helpers.hpp"
#include "pomdog/utility/assert.hpp"
#include "pomdog/utility/errors.hpp"
#include "pomdog/utility/path_helper.hpp"
#include "pomdog/utility/string_helper.hpp"
#include "pomdog/basic/export.hpp"
#include "pomdog/basic/platform.hpp"
#include "pomdog/basic/version.hpp"
| 38.853503
| 67
| 0.812623
|
mogemimi
|
ac848d83a6dede8aa29e7e0e403c35e2b9d7b5ce
| 879
|
hpp
|
C++
|
include/utils/platform.hpp
|
afreakana/cfs-spmv
|
cdd139c5d80b774708806298868a456ad8df1669
|
[
"BSD-3-Clause"
] | 1
|
2021-02-16T12:19:25.000Z
|
2021-02-16T12:19:25.000Z
|
include/utils/platform.hpp
|
afreakana/cfs-spmv
|
cdd139c5d80b774708806298868a456ad8df1669
|
[
"BSD-3-Clause"
] | null | null | null |
include/utils/platform.hpp
|
afreakana/cfs-spmv
|
cdd139c5d80b774708806298868a456ad8df1669
|
[
"BSD-3-Clause"
] | 1
|
2020-04-30T12:52:48.000Z
|
2020-04-30T12:52:48.000Z
|
#ifndef PLATFORM_HPP
#define PLATFORM_HPP
#include <cmath>
#include "cfs_config.hpp"
#ifdef _INTEL_COMPILER
#define PRAGMA_IVDEP _Pragma("ivdep")
#else
#define PRAGMA_IVDEP _Pragma("GCC ivdep")
//#define PRAGMA_IVDEP
#endif
namespace cfs {
namespace util {
using namespace std;
enum class Platform { cpu };
enum class Kernel { SpDMV };
enum class Tuning { None, Aggressive };
enum class Format { none, csr, sss, hyb };
inline int iceildiv(const int a, const int b) { return (a + b - 1) / b; }
inline bool isEqual(float x, float y) {
const float epsilon = 1e-4;
return abs(x - y) <= epsilon * abs(x);
// see Knuth section 4.2.2 pages 217-218
}
inline bool isEqual(double x, double y) {
const double epsilon = 1e-8;
return abs(x - y) <= epsilon * abs(x);
// see Knuth section 4.2.2 pages 217-218
}
} // end of namespace util
} // end of namespace cfs
#endif
| 20.44186
| 73
| 0.688282
|
afreakana
|
ac8574ba1f8f6017a639557901393ab589ca2519
| 918
|
cpp
|
C++
|
LuoguCodes/CF980B.cpp
|
Anguei/OI-Codes
|
0ef271e9af0619d4c236e314cd6d8708d356536a
|
[
"MIT"
] | null | null | null |
LuoguCodes/CF980B.cpp
|
Anguei/OI-Codes
|
0ef271e9af0619d4c236e314cd6d8708d356536a
|
[
"MIT"
] | null | null | null |
LuoguCodes/CF980B.cpp
|
Anguei/OI-Codes
|
0ef271e9af0619d4c236e314cd6d8708d356536a
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
const int kMaxN = 99;
char map[4 + 5][kMaxN + 5];
int main()
{
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 99 + 5; ++j)
map[i][j] = ';.';;
int n, k;
std::cin >> n >> k;
if (k == 0)
{
std::cout << "YES" << std::endl;
for (int i = 1; i <= 4; ++i)
{
for (int j = 1; j <= n; ++j)
std::cout << ".";
std::cout << std::endl;
}
return 0;
}
if (k % 2)
{
map[2][n / 2 + 1] = ';#';;
--k;
}
//int pos = 2;
for (int i = 2; i <= 4 - 1; ++i)
{
for (int j = 2; j < n / 2 + 1; ++j)
{
if (k <= 0)
goto output;
map[i][j] = map[i][n - j + 1] = ';#';;
k -= 2;
}
}
if (k == 2)
map[2][n / 2 + 1] = map[3][n / 2 + 1] = ';#';;
output:
std::cout << "YES" << std::endl;
for (int i = 1; i <= 4; ++i)
{
for (int j = 1; j <= n; ++j)
std::cout << map[i][j];
std::cout << std::endl;
}
}
| 17
| 48
| 0.400871
|
Anguei
|
ac8631435d960d1bee2d98002a8909bba8a22693
| 13,119
|
cc
|
C++
|
Digit_Example/opt_two_step/gen/opt/J_u_rightToeHeight_digit.cc
|
prem-chand/Cassie_CFROST
|
da4bd51442f86e852cbb630cc91c9a380a10b66d
|
[
"BSD-3-Clause"
] | null | null | null |
Digit_Example/opt_two_step/gen/opt/J_u_rightToeHeight_digit.cc
|
prem-chand/Cassie_CFROST
|
da4bd51442f86e852cbb630cc91c9a380a10b66d
|
[
"BSD-3-Clause"
] | null | null | null |
Digit_Example/opt_two_step/gen/opt/J_u_rightToeHeight_digit.cc
|
prem-chand/Cassie_CFROST
|
da4bd51442f86e852cbb630cc91c9a380a10b66d
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Automatically Generated from Mathematica.
* Fri 5 Nov 2021 16:30:17 GMT-04:00
*/
#ifdef MATLAB_MEX_FILE
#include <stdexcept>
#include <cmath>
#include<math.h>
/**
* Copied from Wolfram Mathematica C Definitions file mdefs.hpp
* Changed marcos to inline functions (Eric Cousineau)
*/
inline double Power(double x, double y) { return pow(x, y); }
inline double Sqrt(double x) { return sqrt(x); }
inline double Abs(double x) { return fabs(x); }
inline double Exp(double x) { return exp(x); }
inline double Log(double x) { return log(x); }
inline double Sin(double x) { return sin(x); }
inline double Cos(double x) { return cos(x); }
inline double Tan(double x) { return tan(x); }
inline double ArcSin(double x) { return asin(x); }
inline double ArcCos(double x) { return acos(x); }
inline double ArcTan(double x) { return atan(x); }
/* update ArcTan function to use atan2 instead. */
inline double ArcTan(double x, double y) { return atan2(y,x); }
inline double Sinh(double x) { return sinh(x); }
inline double Cosh(double x) { return cosh(x); }
inline double Tanh(double x) { return tanh(x); }
const double E = 2.71828182845904523536029;
const double Pi = 3.14159265358979323846264;
const double Degree = 0.01745329251994329576924;
inline double Sec(double x) { return 1/cos(x); }
inline double Csc(double x) { return 1/sin(x); }
#endif
/*
* Sub functions
*/
static void output1(double *p_output1,const double *var1)
{
double t125;
double t1504;
double t1473;
double t1481;
double t1506;
double t1560;
double t1487;
double t1508;
double t1536;
double t1432;
double t1561;
double t1574;
double t1589;
double t1611;
double t1546;
double t1593;
double t1603;
double t1407;
double t1613;
double t1645;
double t1676;
double t1720;
double t1608;
double t1678;
double t1703;
double t1325;
double t1748;
double t1763;
double t1783;
double t1903;
double t1709;
double t1851;
double t1876;
double t1324;
double t1906;
double t1909;
double t1942;
double t1960;
double t1882;
double t1946;
double t1952;
double t1308;
double t1961;
double t1966;
double t1968;
double t1982;
double t1957;
double t1973;
double t1975;
double t1295;
double t1985;
double t1996;
double t1999;
double t1244;
double t90;
double t2071;
double t2076;
double t2082;
double t2049;
double t2051;
double t2065;
double t2112;
double t2115;
double t2129;
double t2067;
double t2085;
double t2091;
double t2154;
double t2156;
double t2157;
double t2098;
double t2141;
double t2148;
double t2191;
double t2196;
double t2198;
double t2153;
double t2160;
double t2180;
double t2211;
double t2221;
double t2222;
double t2184;
double t2199;
double t2201;
double t2007;
double t2274;
double t2283;
double t2285;
double t2299;
double t2302;
double t2308;
double t2295;
double t2309;
double t2310;
double t2321;
double t2326;
double t2330;
double t2313;
double t2337;
double t2340;
double t2344;
double t2347;
double t2353;
double t2341;
double t2359;
double t2363;
double t2368;
double t2371;
double t2375;
double t2364;
double t2380;
double t2381;
double t2387;
double t2390;
double t2392;
double t2383;
double t2400;
double t2405;
double t2415;
double t2420;
double t2424;
double t2456;
double t2459;
double t2460;
double t2461;
double t2464;
double t2468;
double t2469;
double t2467;
double t2471;
double t2472;
double t2488;
double t2489;
double t2490;
double t2481;
double t2493;
double t2494;
double t2498;
double t2500;
double t2505;
double t2497;
double t2506;
double t2508;
double t2511;
double t2512;
double t2513;
double t2509;
double t2514;
double t2517;
double t2522;
double t2531;
double t2532;
double t2560;
double t2562;
double t2563;
double t2567;
double t2568;
double t2569;
double t2571;
double t2572;
double t2573;
double t2570;
double t2576;
double t2580;
double t2582;
double t2583;
double t2586;
double t2581;
double t2588;
double t2590;
double t2592;
double t2594;
double t2595;
double t2591;
double t2596;
double t2598;
double t2609;
double t2634;
double t2636;
double t2659;
double t2664;
double t2667;
double t2668;
double t2671;
double t2675;
double t2684;
double t2686;
double t2672;
double t2688;
double t2695;
double t2698;
double t2699;
double t2700;
double t2697;
double t2702;
double t2704;
double t2709;
double t2710;
double t2714;
double t2744;
double t2750;
double t2753;
double t2754;
double t2760;
double t2764;
double t2757;
double t2767;
double t2768;
double t2776;
double t2780;
double t2781;
double t2810;
double t2811;
double t2812;
double t2814;
double t2816;
double t2819;
double t2823;
double t2824;
double t2847;
double t2848;
double t2850;
double t2838;
double t2852;
double t2853;
double t2854;
t125 = Sin(var1[4]);
t1504 = Cos(var1[21]);
t1473 = Cos(var1[4]);
t1481 = Sin(var1[21]);
t1506 = Sin(var1[5]);
t1560 = Cos(var1[22]);
t1487 = t1473*t1481;
t1508 = -1.*t1504*t125*t1506;
t1536 = t1487 + t1508;
t1432 = Sin(var1[22]);
t1561 = -1.*t1504*t1473;
t1574 = -1.*t1481*t125*t1506;
t1589 = t1561 + t1574;
t1611 = Cos(var1[23]);
t1546 = t1432*t1536;
t1593 = t1560*t1589;
t1603 = t1546 + t1593;
t1407 = Sin(var1[23]);
t1613 = t1560*t1536;
t1645 = -1.*t1432*t1589;
t1676 = t1613 + t1645;
t1720 = Cos(var1[24]);
t1608 = t1407*t1603;
t1678 = t1611*t1676;
t1703 = t1608 + t1678;
t1325 = Sin(var1[24]);
t1748 = t1611*t1603;
t1763 = -1.*t1407*t1676;
t1783 = t1748 + t1763;
t1903 = Cos(var1[25]);
t1709 = t1325*t1703;
t1851 = t1720*t1783;
t1876 = t1709 + t1851;
t1324 = Sin(var1[25]);
t1906 = t1720*t1703;
t1909 = -1.*t1325*t1783;
t1942 = t1906 + t1909;
t1960 = Cos(var1[26]);
t1882 = -1.*t1324*t1876;
t1946 = t1903*t1942;
t1952 = t1882 + t1946;
t1308 = Sin(var1[26]);
t1961 = t1903*t1876;
t1966 = t1324*t1942;
t1968 = t1961 + t1966;
t1982 = Cos(var1[30]);
t1957 = t1308*t1952;
t1973 = t1960*t1968;
t1975 = t1957 + t1973;
t1295 = Sin(var1[30]);
t1985 = t1960*t1952;
t1996 = -1.*t1308*t1968;
t1999 = t1985 + t1996;
t1244 = Cos(var1[31]);
t90 = Cos(var1[5]);
t2071 = t1560*t1473*t90*t1481;
t2076 = t1504*t1473*t90*t1432;
t2082 = t2071 + t2076;
t2049 = t1504*t1560*t1473*t90;
t2051 = -1.*t1473*t90*t1481*t1432;
t2065 = t2049 + t2051;
t2112 = t1611*t2082;
t2115 = -1.*t2065*t1407;
t2129 = t2112 + t2115;
t2067 = t1611*t2065;
t2085 = t2082*t1407;
t2091 = t2067 + t2085;
t2154 = t1720*t2129;
t2156 = t2091*t1325;
t2157 = t2154 + t2156;
t2098 = t1720*t2091;
t2141 = -1.*t2129*t1325;
t2148 = t2098 + t2141;
t2191 = t1903*t2157;
t2196 = t2148*t1324;
t2198 = t2191 + t2196;
t2153 = t1903*t2148;
t2160 = -1.*t2157*t1324;
t2180 = t2153 + t2160;
t2211 = t1960*t2198;
t2221 = t2180*t1308;
t2222 = t2211 + t2221;
t2184 = t1960*t2180;
t2199 = -1.*t2198*t1308;
t2201 = t2184 + t2199;
t2007 = Sin(var1[31]);
t2274 = t1481*t125;
t2283 = t1504*t1473*t1506;
t2285 = t2274 + t2283;
t2299 = t1504*t125;
t2302 = -1.*t1473*t1481*t1506;
t2308 = t2299 + t2302;
t2295 = -1.*t1432*t2285;
t2309 = t1560*t2308;
t2310 = t2295 + t2309;
t2321 = t1560*t2285;
t2326 = t1432*t2308;
t2330 = t2321 + t2326;
t2313 = -1.*t1407*t2310;
t2337 = t1611*t2330;
t2340 = t2313 + t2337;
t2344 = t1611*t2310;
t2347 = t1407*t2330;
t2353 = t2344 + t2347;
t2341 = -1.*t1325*t2340;
t2359 = t1720*t2353;
t2363 = t2341 + t2359;
t2368 = t1720*t2340;
t2371 = t1325*t2353;
t2375 = t2368 + t2371;
t2364 = t1324*t2363;
t2380 = t1903*t2375;
t2381 = t2364 + t2380;
t2387 = t1903*t2363;
t2390 = -1.*t1324*t2375;
t2392 = t2387 + t2390;
t2383 = -1.*t1308*t2381;
t2400 = t1960*t2392;
t2405 = t2383 + t2400;
t2415 = t1960*t2381;
t2420 = t1308*t2392;
t2424 = t2415 + t2420;
t2456 = -1.*t1504*t125;
t2459 = t1473*t1481*t1506;
t2460 = t2456 + t2459;
t2461 = -1.*t1560*t2460;
t2464 = t2295 + t2461;
t2468 = -1.*t1432*t2460;
t2469 = t2321 + t2468;
t2467 = -1.*t1407*t2464;
t2471 = t1611*t2469;
t2472 = t2467 + t2471;
t2488 = t1611*t2464;
t2489 = t1407*t2469;
t2490 = t2488 + t2489;
t2481 = -1.*t1325*t2472;
t2493 = t1720*t2490;
t2494 = t2481 + t2493;
t2498 = t1720*t2472;
t2500 = t1325*t2490;
t2505 = t2498 + t2500;
t2497 = t1324*t2494;
t2506 = t1903*t2505;
t2508 = t2497 + t2506;
t2511 = t1903*t2494;
t2512 = -1.*t1324*t2505;
t2513 = t2511 + t2512;
t2509 = -1.*t1308*t2508;
t2514 = t1960*t2513;
t2517 = t2509 + t2514;
t2522 = t1960*t2508;
t2531 = t1308*t2513;
t2532 = t2522 + t2531;
t2560 = t1432*t2285;
t2562 = t1560*t2460;
t2563 = t2560 + t2562;
t2567 = -1.*t1407*t2563;
t2568 = -1.*t1611*t2469;
t2569 = t2567 + t2568;
t2571 = t1611*t2563;
t2572 = -1.*t1407*t2469;
t2573 = t2571 + t2572;
t2570 = -1.*t1325*t2569;
t2576 = t1720*t2573;
t2580 = t2570 + t2576;
t2582 = t1720*t2569;
t2583 = t1325*t2573;
t2586 = t2582 + t2583;
t2581 = t1324*t2580;
t2588 = t1903*t2586;
t2590 = t2581 + t2588;
t2592 = t1903*t2580;
t2594 = -1.*t1324*t2586;
t2595 = t2592 + t2594;
t2591 = -1.*t1308*t2590;
t2596 = t1960*t2595;
t2598 = t2591 + t2596;
t2609 = t1960*t2590;
t2634 = t1308*t2595;
t2636 = t2609 + t2634;
t2659 = t1407*t2563;
t2664 = t2659 + t2471;
t2667 = -1.*t1325*t2664;
t2668 = -1.*t1720*t2573;
t2671 = t2667 + t2668;
t2675 = t1720*t2664;
t2684 = -1.*t1325*t2573;
t2686 = t2675 + t2684;
t2672 = t1324*t2671;
t2688 = t1903*t2686;
t2695 = t2672 + t2688;
t2698 = t1903*t2671;
t2699 = -1.*t1324*t2686;
t2700 = t2698 + t2699;
t2697 = -1.*t1308*t2695;
t2702 = t1960*t2700;
t2704 = t2697 + t2702;
t2709 = t1960*t2695;
t2710 = t1308*t2700;
t2714 = t2709 + t2710;
t2744 = t1325*t2664;
t2750 = t2744 + t2576;
t2753 = -1.*t1324*t2750;
t2754 = t2753 + t2688;
t2760 = -1.*t1903*t2750;
t2764 = t2760 + t2699;
t2757 = -1.*t1308*t2754;
t2767 = t1960*t2764;
t2768 = t2757 + t2767;
t2776 = t1960*t2754;
t2780 = t1308*t2764;
t2781 = t2776 + t2780;
t2810 = t1903*t2750;
t2811 = t1324*t2686;
t2812 = t2810 + t2811;
t2814 = -1.*t1960*t2812;
t2816 = t2757 + t2814;
t2819 = -1.*t1308*t2812;
t2823 = t2776 + t2819;
t2824 = t1982*t2823;
t2847 = t1308*t2754;
t2848 = t1960*t2812;
t2850 = t2847 + t2848;
t2838 = -1.*t1295*t2823;
t2852 = -1.*t1295*t2850;
t2853 = t2852 + t2824;
t2854 = -1.*t2007*t2853;
p_output1[0]=1.;
p_output1[1]=0.05456*(t1244*(-1.*t1295*t1975 + t1982*t1999) - 1.*(t1975*t1982 + t1295*t1999)*t2007) + 0.0315*t125*t90;
p_output1[2]=0.0315*t1473*t1506 + 0.05456*(t1244*(t1982*t2201 - 1.*t1295*t2222) - 1.*t2007*(t1295*t2201 + t1982*t2222));
p_output1[3]=0.05456*(t1244*(t1982*t2405 - 1.*t1295*t2424) - 1.*t2007*(t1295*t2405 + t1982*t2424));
p_output1[4]=0.05456*(t1244*(t1982*t2517 - 1.*t1295*t2532) - 1.*t2007*(t1295*t2517 + t1982*t2532));
p_output1[5]=0.05456*(t1244*(t1982*t2598 - 1.*t1295*t2636) - 1.*t2007*(t1295*t2598 + t1982*t2636));
p_output1[6]=0.05456*(t1244*(t1982*t2704 - 1.*t1295*t2714) - 1.*t2007*(t1295*t2704 + t1982*t2714));
p_output1[7]=0.05456*(t1244*(t1982*t2768 - 1.*t1295*t2781) - 1.*t2007*(t1295*t2768 + t1982*t2781));
p_output1[8]=0.05456*(-1.*t2007*(t1295*t2816 + t2824) + t1244*(t1982*t2816 + t2838));
p_output1[9]=0.05456*(t1244*(t2838 - 1.*t1982*t2850) + t2854);
p_output1[10]=0.05456*(-1.*t1244*(t1295*t2823 + t1982*t2850) + t2854);
}
#ifdef MATLAB_MEX_FILE
#include "mex.h"
/*
* Main function
*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
size_t mrows, ncols;
double *var1;
double *p_output1;
/* Check for proper number of arguments. */
if( nrhs != 1)
{
mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "One input(s) required (var1).");
}
else if( nlhs > 1)
{
mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments.");
}
/* The input must be a noncomplex double vector or scaler. */
mrows = mxGetM(prhs[0]);
ncols = mxGetN(prhs[0]);
if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) ||
( !(mrows == 36 && ncols == 1) &&
!(mrows == 1 && ncols == 36)))
{
mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong.");
}
/* Assign pointers to each input. */
var1 = mxGetPr(prhs[0]);
/* Create matrices for return arguments. */
plhs[0] = mxCreateDoubleMatrix((mwSize) 11, (mwSize) 1, mxREAL);
p_output1 = mxGetPr(plhs[0]);
/* Call the calculation subroutine. */
output1(p_output1,var1);
}
#else // MATLAB_MEX_FILE
#include "J_u_rightToeHeight_digit.hh"
namespace LeftStance
{
void J_u_rightToeHeight_digit_raw(double *p_output1, const double *var1)
{
// Call Subroutines
output1(p_output1, var1);
}
}
#endif // MATLAB_MEX_FILE
| 22.311224
| 122
| 0.650659
|
prem-chand
|
ac87d1e1be13ef149210fbd942410e7b7c7e384f
| 2,521
|
cpp
|
C++
|
src/api/pipy.cpp
|
keveinliu/pipy
|
9a03d33631c8aa8eee2f5acf9aa4d19fcc682b9a
|
[
"BSL-1.0"
] | 1
|
2021-12-02T02:41:30.000Z
|
2021-12-02T02:41:30.000Z
|
src/api/pipy.cpp
|
keveinliu/pipy
|
9a03d33631c8aa8eee2f5acf9aa4d19fcc682b9a
|
[
"BSL-1.0"
] | null | null | null |
src/api/pipy.cpp
|
keveinliu/pipy
|
9a03d33631c8aa8eee2f5acf9aa4d19fcc682b9a
|
[
"BSL-1.0"
] | null | null | null |
/*
* Copyright (c) 2019 by flomesh.io
*
* Unless prior written consent has been obtained from the copyright
* owner, the following shall not be allowed.
*
* 1. The distribution of any source codes, header files, make files,
* or libraries of the software.
*
* 2. Disclosure of any source codes pertaining to the software to any
* additional parties.
*
* 3. Alteration or removal of any notices in or on the software or
* within the documentation included within the software.
*
* ALL SOURCE CODE AS WELL AS ALL DOCUMENTATION INCLUDED WITH THIS
* SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION, 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 "pipy.hpp"
#include "codebase.hpp"
#include "configuration.hpp"
#include "worker.hpp"
#include "utils.hpp"
namespace pipy {
void Pipy::operator()(pjs::Context &ctx, pjs::Object *obj, pjs::Value &ret) {
pjs::Value ret_obj;
pjs::Object *context_prototype = nullptr;
if (!ctx.arguments(0, &context_prototype)) return;
if (context_prototype && context_prototype->is_function()) {
auto *f = context_prototype->as<pjs::Function>();
(*f)(ctx, 0, nullptr, ret_obj);
if (!ctx.ok()) return;
if (!ret_obj.is_object()) {
ctx.error("function did not return an object");
return;
}
context_prototype = ret_obj.o();
}
try {
auto config = Configuration::make(context_prototype);
ret.set(config);
} catch (std::runtime_error &err) {
ctx.error(err);
}
}
} // namespace pipy
namespace pjs {
using namespace pipy;
template<> void ClassDef<Pipy>::init() {
super<Function>();
ctor();
method("load", [](Context &ctx, Object*, Value &ret) {
std::string filename;
if (!ctx.arguments(1, &filename)) return;
auto path = utils::path_normalize(filename);
ret.set(Codebase::current()->get(path));
});
method("restart", [](Context&, Object*, Value&) {
Worker::restart();
});
method("exit", [](Context &ctx, Object*, Value&) {
int exit_code = 0;
if (!ctx.arguments(0, &exit_code)) return;
Worker::exit(exit_code);
});
}
} // namespace pjs
| 29.658824
| 77
| 0.676716
|
keveinliu
|
12c2663764bf2f911c51e7c31ef0d53add7afc91
| 1,884
|
cpp
|
C++
|
Game/Source/Game/src/MY_Scene_MenuBase.cpp
|
SweetheartSquad/GameJam2016
|
e5787a6521add448fde8182ada0bce250ba831ea
|
[
"MIT"
] | null | null | null |
Game/Source/Game/src/MY_Scene_MenuBase.cpp
|
SweetheartSquad/GameJam2016
|
e5787a6521add448fde8182ada0bce250ba831ea
|
[
"MIT"
] | null | null | null |
Game/Source/Game/src/MY_Scene_MenuBase.cpp
|
SweetheartSquad/GameJam2016
|
e5787a6521add448fde8182ada0bce250ba831ea
|
[
"MIT"
] | null | null | null |
#pragma once
#include <MY_Scene_MenuBase.h>
#include <RenderSurface.h>
#include <StandardFrameBuffer.h>
MY_Scene_MenuBase::MY_Scene_MenuBase(Game * _game) :
MY_Scene_Base(_game),
screenSurfaceShader(new Shader("assets/RenderSurface_2", false, true)),
screenSurface(new RenderSurface(screenSurfaceShader)),
screenFBO(new StandardFrameBuffer(true))
{
}
void MY_Scene_MenuBase::update(Step * _step){
// Screen shader update
// Screen shaders are typically loaded from a file instead of built using components, so to update their uniforms
// we need to use the OpenGL API calls
screenSurfaceShader->bindShader(); // remember that we have to bind the shader before it can be updated
GLint test = glGetUniformLocation(screenSurfaceShader->getProgramId(), "time");
checkForGlError(0,__FILE__,__LINE__);
if(test != -1){
glUniform1f(test, _step->time);
checkForGlError(0,__FILE__,__LINE__);
}
if(keyboard->keyJustDown(GLFW_KEY_L)){
screenSurfaceShader->unload();
screenSurfaceShader->loadFromFile(screenSurfaceShader->vertSource, screenSurfaceShader->fragSource);
screenSurfaceShader->load();
}
MY_Scene_Base::update(_step);
}
void MY_Scene_MenuBase::render(sweet::MatrixStack * _matrixStack, RenderOptions * _renderOptions){
// keep our screen framebuffer up-to-date with the game's viewport
screenFBO->resize(game->viewPortWidth, game->viewPortHeight);
// bind our screen framebuffer
FrameBufferInterface::pushFbo(screenFBO);
// render the scene
MY_Scene_Base::render(_matrixStack, _renderOptions);
// unbind our screen framebuffer, rebinding the previously bound framebuffer
// since we didn't have one bound before, this will be the default framebuffer (i.e. the one visible to the player)
FrameBufferInterface::popFbo();
// render our screen framebuffer using the standard render surface
screenSurface->render(screenFBO->getTextureId());
}
| 34.888889
| 116
| 0.778662
|
SweetheartSquad
|
12c4d966933ab0e5976f87e85c8ebbf1f4f5303f
| 4,116
|
hpp
|
C++
|
jni/Player.hpp
|
kaitokidi/androidSpaceTongue
|
0c839dd92fe6393fa095735b08cb8966c771c36a
|
[
"MIT"
] | null | null | null |
jni/Player.hpp
|
kaitokidi/androidSpaceTongue
|
0c839dd92fe6393fa095735b08cb8966c771c36a
|
[
"MIT"
] | null | null | null |
jni/Player.hpp
|
kaitokidi/androidSpaceTongue
|
0c839dd92fe6393fa095735b08cb8966c771c36a
|
[
"MIT"
] | null | null | null |
#ifndef PLAYER_HPP
#define PLAYER_HPP
#include "utils.hpp"
class Player {
public:
sf::SoundBuffer expbuf;
sf::Texture ship;
Player() :
pos(sf::Vector2f(0,0)), speed(sf::Vector2f(0,0))
{
expbuf.loadFromFile("res/explos.ogg");
expl.setBuffer(expbuf);
expl.setVolume(100);
alive = true;
spriteTimer = 0.0;
spriteAnimation = 0.0;
timeSinceNextSprite = 0.2;
angle = speedToRad(speed);
ship.loadFromFile("res/ship.png");
sprite.setTexture(ship);
spriteHeight = ship.getSize().y;
spriteWidth = ship.getSize().x/15;
sprite.setTextureRect(sf::IntRect(spriteAnimation*spriteWidth, 0, spriteWidth, spriteHeight));
sprite.setOrigin(sprite.getGlobalBounds().width/2,sprite.getGlobalBounds().height/2);
licked = tensioning = false;
tipofuerza = 0;
}
void setPosition(sf::Vector2f newPos){
pos = newPos;
sprite.setPosition(pos);
}
void setSpeed(sf::Vector2f newSpeed){
speed = newSpeed;
}
void update(float deltaTime) {
if (!alive) return;
if (licked) timeSinceTriggered += deltaTime;
if (tipofuerza==0)
evoluciona(deltaTime);
else
evolucionabis(deltaTime);
angle = radToAngle(speedToRad(speed))+90;
sprite.setPosition(pos);
spriteTimer += deltaTime;
if(spriteTimer >= timeSinceNextSprite){
++spriteAnimation;
spriteAnimation = (int)spriteAnimation % 15;
}
}
void draw(sf::RenderWindow &window) {
if (!alive) return;
sprite.setTextureRect(sf::IntRect(spriteAnimation*spriteWidth, 0, spriteWidth, spriteHeight));
sprite.setRotation(angle);sprite.setScale(sf::Vector2f(scalePlayer,scalePlayer));
window.draw(sprite);
}
sf::Vector2f getPosition() {
return pos;
}
void setLicked(bool b, sf::Vector2f cPos, int tipofuerza) {
this->tipofuerza = tipofuerza;
camaleonPos = cPos;
licked = b;
if (!b) {
tensioning = false;
timeSinceTriggered = 0;
}
}
void setAlive(bool b) {
if (!b && alive) {
alive = b;
expl.play();
}
}
bool isAlive() {
return alive;
}
sf::Vector2f getSpeed() {
return speed;
}
sf::CircleShape getBox() {
sf::CircleShape aux(spriteWidth/2*scalePlayer*0.5);
aux.setPosition(pos);
return aux;
}
//Private functions
private:
//Player properties
sf::Sound expl;
sf::Vector2f pos;
sf::Sprite sprite;
sf::Vector2f speed;
float angle;
float spriteTimer;
float spriteWidth;
float spriteHeight;
float spriteAnimation;
float timeSinceNextSprite;
int tipofuerza;
// Camaleon related things
bool licked;
bool tensioning;
float timeSinceTriggered;
sf::Vector2f camaleonPos;
void evoluciona(float fdelta){
double delta=fdelta;
point p=vector2point(pos);
point v=vector2point(speed);
point c=vector2point(camaleonPos);
if (not licked || timeSinceTriggered < animationTime) {
p+=v*delta;
pos=point2vector(p);
return;
}
if (not tensioning) {
p+=v*delta;
pos=point2vector(p);
if (prodesc(v,p-c)>=0)
tensioning=true;
return;
}
p-=c;
double modulov=abs(v);
double desp=modulov*delta;
double r=abs(p);
double alfa=desp/r;
int signo=prodvec(p,v)>0?1:-1;
p*=std::polar(1.0,signo*alfa);
v=p*std::polar(1.0,signo*M_PI/2.0);
v=(modulov/abs(v))*v;
p+=c;
pos=point2vector(p);
speed=point2vector(v);
}
double fuerza(double distancia)
{
if (tipofuerza==1)
return sqrt(abs(distancia))*5;
if (tipofuerza==2)
return abs(distancia)/200;
//return 30;
//return 5000000/(distancia*distancia);
}
void evolucionabis(float fdelta)
{
double delta=fdelta;
point p=vector2point(pos);
point v=vector2point(speed);
if (not licked || timeSinceTriggered < animationTime) {
p+=v*delta;
pos=point2vector(p);
return;
}
point c=vector2point(camaleonPos);
int pasos=100;
delta/=pasos;
for (int paso=0;paso<pasos;paso++) {
point dir=c-p;
v=v+(fuerza(abs(dir))*delta/abs(dir))*dir;
p=p+v*delta;
}
pos=point2vector(p);
speed=point2vector(v);
}
// Comido
bool alive;
};
#endif // PLAYER_HPP
| 20.683417
| 98
| 0.654276
|
kaitokidi
|
12cc90aa410589156f8780d3316bea673f55b192
| 22,105
|
cpp
|
C++
|
cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp
|
centrallydecentralized/ufo
|
29e8f9ce4ce92635ed22f8a051c917cfe6e0313d
|
[
"BSD-3-Clause"
] | 58
|
2015-01-05T04:40:48.000Z
|
2021-12-17T06:01:28.000Z
|
cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp
|
centrallydecentralized/ufo
|
29e8f9ce4ce92635ed22f8a051c917cfe6e0313d
|
[
"BSD-3-Clause"
] | null | null | null |
cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp
|
centrallydecentralized/ufo
|
29e8f9ce4ce92635ed22f8a051c917cfe6e0313d
|
[
"BSD-3-Clause"
] | 46
|
2015-01-03T06:20:54.000Z
|
2020-04-18T13:32:52.000Z
|
#include "cocos-ext.h"
#include "../ExtensionsTest.h"
#include "SceneEditorTest.h"
#include "TriggerCode/EventDef.h"
#include "../../testResource.h"
using namespace cocos2d;
using namespace cocos2d::extension;
using namespace cocos2d::ui;
CCLayer *Next();
CCLayer *Back();
CCLayer *Restart();
static int s_nIdx = -1;
CCLayer *createTests(int index)
{
CCLayer *pLayer = NULL;
switch(index)
{
case TEST_LOADSCENEEDITORFILE:
pLayer = new LoadSceneEdtiorFileTest();
break;
case TEST_SPIRTECOMPONENT:
pLayer = new SpriteComponentTest();
break;
case TEST_ARMATURECOMPONENT:
pLayer = new ArmatureComponentTest();
break;
case TEST_UICOMPONENT:
pLayer = new UIComponentTest();
break;
case TEST_TMXMAPCOMPONENT:
pLayer = new TmxMapComponentTest();
break;
case TEST_PARTICLECOMPONENT:
pLayer = new ParticleComponentTest();
break;
case TEST_EFEECTCOMPONENT:
pLayer = new EffectComponentTest();
break;
case TEST_BACKGROUNDCOMPONENT:
pLayer = new BackgroundComponentTest();
break;
case TEST_ATTRIBUTECOMPONENT:
pLayer = new AttributeComponentTest();
break;
case TEST_TRIGGER:
pLayer = new TriggerTest();
pLayer->init();
break;
default:
break;
}
return pLayer;
}
CCLayer *Next()
{
++s_nIdx;
s_nIdx = s_nIdx % TEST_SCENEEDITOR_COUNT;
CCLayer *pLayer = createTests(s_nIdx);
pLayer->autorelease();
return pLayer;
}
CCLayer *Back()
{
--s_nIdx;
if( s_nIdx < 0 )
s_nIdx += TEST_SCENEEDITOR_COUNT;
CCLayer *pLayer = createTests(s_nIdx);
pLayer->autorelease();
return pLayer;
}
CCLayer *Restart()
{
CCLayer *pLayer = createTests(s_nIdx);
pLayer->autorelease();
return pLayer;
}
SceneEditorTestScene::SceneEditorTestScene(bool bPortrait)
{
TestScene::init();
}
void SceneEditorTestScene::runThisTest()
{
s_nIdx = -1;
addChild(Next());
CCDirector::sharedDirector()->replaceScene(this);
}
void SceneEditorTestScene::MainMenuCallback(CCObject *pSender)
{
TestScene::MainMenuCallback(pSender);
}
const char* SceneEditorTestLayer::m_loadtypeStr[2] = {"change to load \nwith binary file","change to load \nwith json file"};
void SceneEditorTestLayer::onEnter()
{
CCLayer::onEnter();
// add title and subtitle
std::string str = title();
const char *pTitle = str.c_str();
CCLabelTTF *label = CCLabelTTF::create(pTitle, "Arial", 18);
label->setColor(ccc3(255, 255, 255));
addChild(label, 100, 10000);
label->setPosition( ccp(VisibleRect::center().x, VisibleRect::top().y - 30) );
std::string strSubtitle = subtitle();
if( ! strSubtitle.empty() )
{
CCLabelTTF *l = CCLabelTTF::create(strSubtitle.c_str(), "Arial", 18);
l->setColor(ccc3(0, 0, 0));
addChild(l, 1, 10001);
l->setPosition( ccp(VisibleRect::center().x, VisibleRect::top().y - 60) );
}
// change button
m_isCsbLoad = false;
m_loadtypelb = CCLabelTTF::create(m_loadtypeStr[0], "Arial", 12);
// #endif
CCMenuItemLabel* itemlb = CCMenuItemLabel::create(m_loadtypelb, this, menu_selector(SceneEditorTestLayer::changeLoadTypeCallback));
CCMenu* loadtypemenu = CCMenu::create(itemlb, NULL);
loadtypemenu->setPosition(ccp(VisibleRect::rightTop().x -50,VisibleRect::rightTop().y -20));
addChild(loadtypemenu,100);
// add menu
backItem = CCMenuItemImage::create(s_pPathB1, s_pPathB2, this, menu_selector(SceneEditorTestLayer::backCallback) );
restartItem = CCMenuItemImage::create(s_pPathR1, s_pPathR2, this, menu_selector(SceneEditorTestLayer::restartCallback) );
nextItem = CCMenuItemImage::create(s_pPathF1, s_pPathF2, this, menu_selector(SceneEditorTestLayer::nextCallback) );
CCMenu *menu = CCMenu::create(backItem, restartItem, nextItem, NULL);
float fScale = 0.5f;
menu->setPosition(ccp(0, 0));
backItem->setPosition(ccp(VisibleRect::center().x - restartItem->getContentSize().width * 2 * fScale, VisibleRect::bottom().y + restartItem->getContentSize().height / 2));
backItem->setScale(fScale);
restartItem->setPosition(ccp(VisibleRect::center().x, VisibleRect::bottom().y + restartItem->getContentSize().height / 2));
restartItem->setScale(fScale);
nextItem->setPosition(ccp(VisibleRect::center().x + restartItem->getContentSize().width * 2 * fScale, VisibleRect::bottom().y + restartItem->getContentSize().height / 2));
nextItem->setScale(fScale);
addChild(menu, 100);
setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionTextureColor));
}
void SceneEditorTestLayer::onExit()
{
removeAllChildren();
backItem = restartItem = nextItem = NULL;
}
std::string SceneEditorTestLayer::title()
{
return "SceneReader Test LoadSceneEditorFile";
}
std::string SceneEditorTestLayer::subtitle()
{
return "";
}
void SceneEditorTestLayer::restartCallback(CCObject *pSender)
{
CCScene *s = new SceneEditorTestScene();
s->addChild(Restart());
CCDirector::sharedDirector()->replaceScene(s);
s->release();
}
void SceneEditorTestLayer::nextCallback(CCObject *pSender)
{
CCScene *s = new SceneEditorTestScene();
s->addChild(Next());
CCDirector::sharedDirector()->replaceScene(s);
s->release();
}
void SceneEditorTestLayer::backCallback(CCObject *pSender)
{
CCScene *s = new SceneEditorTestScene();
s->addChild(Back());
CCDirector::sharedDirector()->replaceScene(s);
s->release();
}
void SceneEditorTestLayer::draw()
{
CCLayer::draw();
}
void SceneEditorTestLayer::changeLoadTypeCallback( CCObject *pSender)
{
m_isCsbLoad = !m_isCsbLoad;
m_loadtypelb->setString(m_loadtypeStr[(int)m_isCsbLoad]);
loadFileChangeHelper(m_filePathName);
if(m_rootNode != NULL)
{
this->removeChild(m_rootNode);
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return ;
}
defaultPlay();
this->addChild(m_rootNode);
}
}
void SceneEditorTestLayer::loadFileChangeHelper(string& filePathName)
{
int n = filePathName.find_last_of(".");
if(-1 == n)
return;
filePathName = filePathName.substr(0,n);
if(m_isCsbLoad)
filePathName.append(".csb");
else
filePathName.append(".json");
}
LoadSceneEdtiorFileTest::LoadSceneEdtiorFileTest()
{
}
LoadSceneEdtiorFileTest::~LoadSceneEdtiorFileTest()
{
}
std::string LoadSceneEdtiorFileTest::title()
{
return "LoadSceneEdtiorFile Test";
}
void LoadSceneEdtiorFileTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void LoadSceneEdtiorFileTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* LoadSceneEdtiorFileTest::createGameScene()
{
m_filePathName = "scenetest/LoadSceneEdtiorFileTest/FishJoy2.json"; //default is json
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void LoadSceneEdtiorFileTest::defaultPlay()
{
cocos2d::extension::ActionManager::shareManager()->playActionByName("startMenu_1.json","Animation1");
}
SpriteComponentTest::SpriteComponentTest()
{
}
SpriteComponentTest::~SpriteComponentTest()
{
}
std::string SpriteComponentTest::title()
{
return "Sprite Component Test";
}
void SpriteComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void SpriteComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* SpriteComponentTest::createGameScene()
{
m_filePathName = "scenetest/SpriteComponentTest/SpriteComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void SpriteComponentTest::defaultPlay()
{
CCActionInterval* action1 = CCBlink::create(2, 10);
CCActionInterval* action2 = CCBlink::create(2, 5);
CCComRender *pSister1 = static_cast<CCComRender*>(m_rootNode->getChildByTag(10003)->getComponent("CCSprite"));
pSister1->getNode()->runAction(action1);
CCComRender *pSister2 = static_cast<CCComRender*>(m_rootNode->getChildByTag(10004)->getComponent("CCSprite"));
pSister2->getNode()->runAction(action2);
}
ArmatureComponentTest::ArmatureComponentTest()
{
}
ArmatureComponentTest::~ArmatureComponentTest()
{
}
std::string ArmatureComponentTest::title()
{
return "Armature Component Test";
}
void ArmatureComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void ArmatureComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* ArmatureComponentTest::createGameScene()
{
m_filePathName = "scenetest/ArmatureComponentTest/ArmatureComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void ArmatureComponentTest::defaultPlay()
{
CCComRender *pBlowFish = static_cast<CCComRender*>(m_rootNode->getChildByTag(10007)->getComponent("CCArmature"));
pBlowFish->getNode()->runAction(CCMoveBy::create(10.0f, ccp(-1000.0f, 0)));
CCComRender *pButterflyfish = static_cast<CCComRender*>(m_rootNode->getChildByTag(10008)->getComponent("CCArmature"));
pButterflyfish->getNode()->runAction(CCMoveBy::create(10.0f, ccp(-1000.0f, 0)));
}
UIComponentTest::UIComponentTest()
{
}
UIComponentTest::~UIComponentTest()
{
}
std::string UIComponentTest::title()
{
return "UI Component Test";
}
void UIComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void UIComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* UIComponentTest::createGameScene()
{
m_filePathName = "scenetest/UIComponentTest/UIComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void UIComponentTest::touchEvent(CCObject *pSender, TouchEventType type)
{
switch (type)
{
case TOUCH_EVENT_BEGAN:
{
CCComRender *pBlowFish = static_cast<CCComRender*>(m_rootNode->getChildByTag(10010)->getComponent("CCArmature"));
pBlowFish->getNode()->runAction(CCMoveBy::create(10.0f, ccp(-1000.0f, 0)));
CCComRender *pButterflyfish = static_cast<CCComRender*>(m_rootNode->getChildByTag(10011)->getComponent("CCArmature"));
pButterflyfish->getNode()->runAction(CCMoveBy::create(10.0f, ccp(-1000.0f, 0)));
}
break;
default:
break;
}
}
void UIComponentTest::defaultPlay()
{
CCComRender *render = static_cast<CCComRender*>(m_rootNode->getChildByTag(10025)->getComponent("GUIComponent"));
cocos2d::ui::TouchGroup* touchGroup = static_cast<cocos2d::ui::TouchGroup*>(render->getNode());
UIWidget* widget = static_cast<UIWidget*>(touchGroup->getWidgetByName("Panel_154"));
UIButton* button = static_cast<UIButton*>(widget->getChildByName("Button_156"));
button->addTouchEventListener(this, toucheventselector(UIComponentTest::touchEvent));
}
TmxMapComponentTest::TmxMapComponentTest()
{
}
TmxMapComponentTest::~TmxMapComponentTest()
{
}
std::string TmxMapComponentTest::title()
{
return "TmxMap Component Test";
}
void TmxMapComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void TmxMapComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* TmxMapComponentTest::createGameScene()
{
m_filePathName = "scenetest/TmxMapComponentTest/TmxMapComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void TmxMapComponentTest::defaultPlay()
{
CCComRender *tmxMap = static_cast<CCComRender*>(m_rootNode->getChildByTag(10015)->getComponent("CCTMXTiledMap"));
CCActionInterval *actionTo = CCSkewTo::create(2, 0.f, 2.f);
CCActionInterval *rotateTo = CCRotateTo::create(2, 61.0f);
CCActionInterval *actionScaleTo = CCScaleTo::create(2, -0.44f, 0.47f);
CCActionInterval *actionScaleToBack = CCScaleTo::create(2, 1.0f, 1.0f);
CCActionInterval *rotateToBack = CCRotateTo::create(2, 0);
CCActionInterval *actionToBack = CCSkewTo::create(2, 0, 0);
tmxMap->getNode()->runAction(CCSequence::create(actionTo, actionToBack, NULL));
tmxMap->getNode()->runAction(CCSequence::create(rotateTo, rotateToBack, NULL));
tmxMap->getNode()->runAction(CCSequence::create(actionScaleTo, actionScaleToBack, NULL));
}
ParticleComponentTest::ParticleComponentTest()
{
}
ParticleComponentTest::~ParticleComponentTest()
{
}
std::string ParticleComponentTest::title()
{
return "Particle Component Test";
}
void ParticleComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void ParticleComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* ParticleComponentTest::createGameScene()
{
m_filePathName = "scenetest/ParticleComponentTest/ParticleComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void ParticleComponentTest::defaultPlay()
{
CCComRender* Particle = static_cast<CCComRender*>(m_rootNode->getChildByTag(10020)->getComponent("CCParticleSystemQuad"));
CCActionInterval* jump = CCJumpBy::create(5, ccp(-500,0), 50, 4);
CCFiniteTimeAction* action = CCSequence::create( jump, jump->reverse(), NULL);
Particle->getNode()->runAction(action);
}
EffectComponentTest::EffectComponentTest()
{
}
EffectComponentTest::~EffectComponentTest()
{
}
std::string EffectComponentTest::title()
{
return "Effect Component Test";
}
void EffectComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void EffectComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* EffectComponentTest::createGameScene()
{
m_filePathName = "scenetest/EffectComponentTest/EffectComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void EffectComponentTest::animationEvent(cocos2d::extension::CCArmature *armature, cocos2d::extension::MovementEventType movementType, const char *movementID)
{
std::string id = movementID;
if (movementType == LOOP_COMPLETE)
{
if (id.compare("Fire") == 0)
{
CCComAudio *pAudio = static_cast<CCComAudio*>(m_rootNode->getChildByTag(10015)->getComponent("CCComAudio"));
pAudio->playEffect();
}
}
}
void EffectComponentTest::defaultPlay()
{
CCComRender *pRender = static_cast<CCComRender*>(m_rootNode->getChildByTag(10015)->getComponent("CCArmature"));
CCArmature *pAr = static_cast<CCArmature*>(pRender->getNode());
pAr->getAnimation()->setMovementEventCallFunc(this, movementEvent_selector(EffectComponentTest::animationEvent));
}
BackgroundComponentTest::BackgroundComponentTest()
{
}
BackgroundComponentTest::~BackgroundComponentTest()
{
}
std::string BackgroundComponentTest::title()
{
return "Background Component Test";
}
void BackgroundComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void BackgroundComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* BackgroundComponentTest::createGameScene()
{
m_filePathName = "scenetest/BackgroundComponentTest/BackgroundComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void BackgroundComponentTest::defaultPlay()
{
cocos2d::extension::ActionManager::shareManager()->playActionByName("startMenu_1.json","Animation1");
CCComAudio *Audio = static_cast<CCComAudio*>(m_rootNode->getComponent("CCBackgroundAudio"));
Audio->playBackgroundMusic();
}
AttributeComponentTest::AttributeComponentTest()
{
}
AttributeComponentTest::~AttributeComponentTest()
{
}
std::string AttributeComponentTest::title()
{
return "Attribute Component Test";
}
void AttributeComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
initData();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void AttributeComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
bool AttributeComponentTest::initData()
{
bool bRet = false;
do {
CC_BREAK_IF(m_rootNode == NULL);
CCComAttribute *pAttribute = static_cast<CCComAttribute*>(m_rootNode->getChildByTag(10015)->getComponent("CCComAttribute"));
CCLog("Name: %s, HP: %f, MP: %f", pAttribute->getCString("name"), pAttribute->getFloat("maxHP"), pAttribute->getFloat("maxMP"));
bRet = true;
} while (0);
return bRet;
}
cocos2d::CCNode* AttributeComponentTest::createGameScene()
{
m_filePathName = "scenetest/AttributeComponentTest/AttributeComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
return m_rootNode;
}
void AttributeComponentTest::defaultPlay()
{
initData();
}
TriggerTest::TriggerTest()
{
m_rootNode = NULL;
}
TriggerTest::~TriggerTest()
{
}
std::string TriggerTest::title()
{
return "Trigger Test";
}
bool TriggerTest::init()
{
sendEvent(TRIGGEREVENT_INITSCENE);
return true;
}
void TriggerTest::onEnter()
{
SceneEditorTestLayer::onEnter();
CCNode *root = createGameScene();
this->addChild(root, 0, 1);
}
void TriggerTest::onExit()
{
sendEvent(TRIGGEREVENT_LEAVESCENE);
this->unschedule(schedule_selector(TriggerTest::gameLogic));
this->setTouchEnabled(false);
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
bool TriggerTest::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHBEGAN);
return true;
}
void TriggerTest::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHMOVED);
}
void TriggerTest::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHENDED);
}
void TriggerTest::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHCANCELLED);
}
void TriggerTest::gameLogic(float dt)
{
sendEvent(TRIGGEREVENT_UPDATESCENE);
}
static ActionObject* actionObject = NULL;
cocos2d::CCNode* TriggerTest::createGameScene()
{
m_filePathName = "scenetest/TriggerTest/TriggerTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void TriggerTest::defaultPlay()
{
//ui action
actionObject = cocos2d::extension::ActionManager::shareManager()->playActionByName("startMenu_1.json","Animation1");
this->schedule(schedule_selector(TriggerTest::gameLogic));
this->setTouchEnabled(true);
this->setTouchMode(kCCTouchesOneByOne);
sendEvent(TRIGGEREVENT_ENTERSCENE);
}
| 24.977401
| 176
| 0.688803
|
centrallydecentralized
|
12ccb19ceb3c1569112a3e7b2c3147bd87d652aa
| 12,812
|
cpp
|
C++
|
src/windows/Undo.cpp
|
hhyyrylainen/DualViewPP
|
1fb4a1db85a8509342e16d68c75d4ec7721ced9e
|
[
"MIT"
] | null | null | null |
src/windows/Undo.cpp
|
hhyyrylainen/DualViewPP
|
1fb4a1db85a8509342e16d68c75d4ec7721ced9e
|
[
"MIT"
] | null | null | null |
src/windows/Undo.cpp
|
hhyyrylainen/DualViewPP
|
1fb4a1db85a8509342e16d68c75d4ec7721ced9e
|
[
"MIT"
] | null | null | null |
// ------------------------------------ //
#include "Undo.h"
#include "resources/DatabaseAction.h"
#include "Database.h"
#include "DualView.h"
#include "Settings.h"
using namespace DV;
// ------------------------------------ //
UndoWindow::UndoWindow() :
ClearHistory("Clear History"), HistorySizeLabel("History items to keep"),
MainContainer(Gtk::ORIENTATION_VERTICAL), ListContainer(Gtk::ORIENTATION_VERTICAL),
NothingToShow("No history items available")
{
signal_delete_event().connect(sigc::mem_fun(*this, &BaseWindow::_OnClosed));
add_events(Gdk::KEY_PRESS_MASK);
signal_key_press_event().connect(
sigc::mem_fun(*this, &UndoWindow::_StartSearchFromKeypress));
auto accelGroup = Gtk::AccelGroup::create();
set_default_size(500, 300);
property_resizable() = true;
Menu.set_image_from_icon_name("open-menu-symbolic");
// Window specific controls
ClearHistory.property_relief() = Gtk::RELIEF_NONE;
ClearHistory.signal_clicked().connect(sigc::mem_fun(*this, &UndoWindow::_ClearHistory));
MenuPopover.Container.pack_start(ClearHistory);
MenuPopover.Container.pack_start(Separator1);
MenuPopover.Container.pack_start(HistorySizeLabel);
HistorySize.property_editable() = true;
HistorySize.property_input_purpose() = Gtk::INPUT_PURPOSE_NUMBER;
HistorySize.property_snap_to_ticks() = true;
HistorySize.property_snap_to_ticks() = true;
HistorySize.set_range(1, 250);
HistorySize.set_increments(1, 10);
HistorySize.set_digits(0);
HistorySize.set_value(DualView::Get().GetSettings().GetActionHistorySize());
MenuPopover.Container.pack_start(HistorySize);
MenuPopover.show_all_children();
MenuPopover.signal_closed().connect(
sigc::mem_fun(*this, &UndoWindow::_ApplyPrimaryMenuSettings));
Menu.set_popover(MenuPopover);
SearchButton.set_image_from_icon_name("edit-find-symbolic");
SearchButton.add_accelerator("clicked", accelGroup, GDK_KEY_f,
Gdk::ModifierType::CONTROL_MASK, Gtk::AccelFlags::ACCEL_VISIBLE);
HeaderBar.property_title() = "Latest Actions";
HeaderBar.property_show_close_button() = true;
HeaderBar.pack_end(Menu);
HeaderBar.pack_end(SearchButton);
set_titlebar(HeaderBar);
//
// Content area
//
MainContainer.property_vexpand() = true;
MainContainer.property_hexpand() = true;
Search.signal_search_changed().connect(sigc::mem_fun(*this, &UndoWindow::_SearchUpdated));
SearchBar.property_search_mode_enabled() = false;
SearchActiveBinding = Glib::Binding::bind_property(SearchButton.property_active(),
SearchBar.property_search_mode_enabled(), Glib::BINDING_BIDIRECTIONAL);
SearchBar.add(Search);
MainContainer.add(SearchBar);
QueryingDatabase.property_active() = true;
MainArea.add_overlay(QueryingDatabase);
ListScroll.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_ALWAYS);
ListScroll.property_vexpand() = true;
ListScroll.property_hexpand() = true;
ListContainer.property_vexpand() = true;
ListContainer.property_hexpand() = true;
NothingToShow.property_halign() = Gtk::ALIGN_CENTER;
NothingToShow.property_hexpand() = true;
NothingToShow.property_valign() = Gtk::ALIGN_CENTER;
NothingToShow.property_vexpand() = true;
ListContainer.set_spacing(4);
ListContainer.property_margin_top() = 4;
ListContainer.property_margin_bottom() = 4;
ListContainer.property_margin_start() = 4;
ListContainer.property_margin_end() = 4;
ListContainer.add(NothingToShow);
ListScroll.add(ListContainer);
MainArea.add(ListScroll);
MainContainer.add(MainArea);
add(MainContainer);
add_accel_group(accelGroup);
show_all_children();
_SearchUpdated();
}
UndoWindow::~UndoWindow()
{
Close();
}
void UndoWindow::_OnClose() {}
// ------------------------------------ //
bool UndoWindow::_StartSearchFromKeypress(GdkEventKey* event)
{
return SearchBar.handle_event(event);
}
// ------------------------------------ //
void UndoWindow::Clear()
{
while(!FoundActions.empty()) {
ListContainer.remove(*FoundActions.back());
FoundActions.pop_back();
}
}
// ------------------------------------ //
void UndoWindow::_SearchUpdated()
{
NothingToShow.property_visible() = false;
QueryingDatabase.property_visible() = true;
const std::string search = Search.property_text().get_value();
auto isalive = GetAliveMarker();
DualView::Get().QueueDBThreadFunction([=]() {
auto actions = DualView::Get().GetDatabase().SelectLatestDatabaseActions(search);
DualView::Get().InvokeFunction([this, isalive, actions{std::move(actions)}]() {
INVOKE_CHECK_ALIVE_MARKER(isalive);
_FinishedQueryingDB(actions);
});
});
}
// ------------------------------------ //
void UndoWindow::_FinishedQueryingDB(
const std::vector<std::shared_ptr<DatabaseAction>>& actions)
{
QueryingDatabase.property_visible() = false;
Clear();
for(const auto& action : actions) {
FoundActions.push_back(std::make_shared<ActionDisplay>(action));
ListContainer.add(*FoundActions.back());
FoundActions.back()->show();
}
if(FoundActions.empty())
NothingToShow.property_visible() = true;
}
// ------------------------------------ //
void UndoWindow::_ApplyPrimaryMenuSettings()
{
// This makes sure the up to date value is available for reading
HistorySize.update();
int newSize = static_cast<int>(HistorySize.property_value());
auto& settings = DualView::Get().GetSettings();
// TODO: it isn't the cleanest thing to do all of this manipulation here
if(newSize != settings.GetActionHistorySize()) {
settings.SetActionHistorySize(newSize);
LOG_INFO("Updating setting max history size to: " +
std::to_string(settings.GetActionHistorySize()));
DualView::Get().GetDatabase().SetMaxActionHistory(settings.GetActionHistorySize());
}
}
void UndoWindow::_ClearHistory()
{
auto dialog = Gtk::MessageDialog(*this, "Clear action history?", false,
Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO, true);
dialog.set_secondary_text("It is <b>NOT</b> possible to undo this action. This will "
"permanently delete all deleted images.",
true);
int result = dialog.run();
if(result != Gtk::RESPONSE_YES) {
return;
}
set_sensitive(false);
auto isalive = GetAliveMarker();
DualView::Get().QueueDBThreadFunction([=]() {
auto& db = DualView::Get().GetDatabase();
GUARD_LOCK_OTHER(db);
db.PurgeOldActionsUntilSpecificCount(guard, 0);
DualView::Get().InvokeFunction([this, isalive]() {
INVOKE_CHECK_ALIVE_MARKER(isalive);
Clear();
set_sensitive(true);
_SearchUpdated();
});
});
}
// ------------------------------------ //
// ActionDisplay
ActionDisplay::ActionDisplay(const std::shared_ptr<DatabaseAction>& action) :
MainBox(Gtk::ORIENTATION_HORIZONTAL), LeftSide(Gtk::ORIENTATION_VERTICAL),
RightSide(Gtk::ORIENTATION_HORIZONTAL), Edit("Edit"), UndoRedo("Loading"), Action(action)
{
if(!Action)
throw InvalidState("given nullptr for action");
// The description generation accesses the database so we do that in the background
Description.property_halign() = Gtk::ALIGN_START;
Description.property_valign() = Gtk::ALIGN_START;
// Description.property_margin_start() = 8;
Description.property_margin_top() = 3;
Description.property_label() =
"Loading description for action " + std::to_string(Action->GetID());
Description.property_max_width_chars() = 80;
Description.property_wrap() = true;
LeftSide.pack_start(Description, false, false);
ResourcePreviews.property_vexpand() = true;
ResourcePreviews.set_min_content_width(140);
ResourcePreviews.set_min_content_height(80);
ResourcePreviews.SetItemSize(LIST_ITEM_SIZE::TINY);
ContainerFrame.add(ResourcePreviews);
LeftSide.pack_end(ContainerFrame, true, true);
MainBox.pack_start(LeftSide, true, true);
Edit.property_valign() = Gtk::ALIGN_CENTER;
Edit.property_halign() = Gtk::ALIGN_CENTER;
Edit.property_sensitive() = false;
Edit.property_tooltip_text() = "Edit this action and redo it";
Edit.signal_clicked().connect(sigc::mem_fun(*this, &ActionDisplay::_EditPressed));
RightSide.pack_start(Edit, false, false);
UndoRedo.property_valign() = Gtk::ALIGN_CENTER;
UndoRedo.property_halign() = Gtk::ALIGN_CENTER;
UndoRedo.property_always_show_image() = true;
UndoRedo.property_sensitive() = false;
UndoRedo.signal_clicked().connect(sigc::mem_fun(*this, &ActionDisplay::_UndoRedoPressed));
RightSide.pack_start(UndoRedo, false, false);
RightSide.set_homogeneous(true);
RightSide.set_spacing(2);
MainBox.pack_end(RightSide, false, false);
MainBox.set_spacing(3);
add(MainBox);
show_all_children();
RefreshData();
// Start listening for changes
action->ConnectToNotifiable(this);
}
ActionDisplay::~ActionDisplay()
{
GUARD_LOCK();
ReleaseParentHooks(guard);
}
// ------------------------------------ //
void ActionDisplay::RefreshData()
{
auto isalive = GetAliveMarker();
DualView::Get().QueueDBThreadFunction([action = this->Action, this, isalive]() {
auto description = action->GenerateDescription();
auto previewItems = action->LoadPreviewItems(10);
if(action->IsDeleted()) {
description = "DELETED FROM HISTORY " + description;
}
DualView::Get().InvokeFunction(
[this, isalive, description, previewItems = std::move(previewItems)]() {
INVOKE_CHECK_ALIVE_MARKER(isalive);
_OnDataRetrieved(description, previewItems);
});
});
_UpdateStatusButtons();
}
void ActionDisplay::_OnDataRetrieved(const std::string& description,
const std::vector<std::shared_ptr<ResourceWithPreview>>& previewitems)
{
// There's a small chance that this isn't always fully up to date but this is good enough
FetchingData = false;
DualView::IsOnMainThreadAssert();
Description.property_label() = description;
if(previewitems.empty()) {
ContainerFrame.property_visible() = false;
ResourcePreviews.Clear();
} else {
ContainerFrame.property_visible() = true;
ResourcePreviews.SetShownItems(previewitems.begin(), previewitems.end());
}
}
void ActionDisplay::_UpdateStatusButtons()
{
if(Action->IsDeleted()) {
UndoRedo.property_sensitive() = false;
Edit.property_sensitive() = false;
return;
}
UndoRedo.property_sensitive() = true;
if(Action->IsPerformed()) {
UndoRedo.set_image_from_icon_name("edit-undo-symbolic");
UndoRedo.property_label() = "Undo";
} else {
UndoRedo.set_image_from_icon_name("edit-redo-symbolic");
UndoRedo.property_label() = "Redo";
}
Edit.property_sensitive() = Action->SupportsEditing();
}
// ------------------------------------ //
void ActionDisplay::_UndoRedoPressed()
{
try {
if(Action->IsPerformed()) {
if(!Action->Undo())
throw Leviathan::Exception("Unknown error in action undo");
} else {
if(!Action->Redo())
throw Leviathan::Exception("Unknown error in action redo");
}
} catch(const Leviathan::Exception& e) {
Gtk::Window* parent = dynamic_cast<Gtk::Window*>(this->get_toplevel());
if(!parent)
return;
auto dialog = Gtk::MessageDialog(*parent, "Performing the action failed", false,
Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE, true);
dialog.set_secondary_text("Error: " + std::string(e.what()));
dialog.run();
}
}
void ActionDisplay::_EditPressed()
{
try {
Action->OpenEditingWindow();
} catch(const Leviathan::Exception& e) {
Gtk::Window* parent = dynamic_cast<Gtk::Window*>(this->get_toplevel());
if(!parent)
return;
auto dialog = Gtk::MessageDialog(*parent, "Can't edit this action", false,
Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE, true);
dialog.set_secondary_text("Error: " + std::string(e.what()));
dialog.run();
}
}
void ActionDisplay::OnNotified(
Lock& ownlock, Leviathan::BaseNotifierAll* parent, Lock& parentlock)
{
if(FetchingData)
return;
FetchingData = true;
auto isalive = GetAliveMarker();
DualView::Get().InvokeFunction([this, isalive]() {
INVOKE_CHECK_ALIVE_MARKER(isalive);
RefreshData();
});
}
| 29.934579
| 94
| 0.659694
|
hhyyrylainen
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.