blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
628422a594d677aaf427b7320081e3f8b12cfe81 | f3121907c593d83c8738e44ac13ccf6af87b02b2 | /jelly_bird/app/src/main/cpp/jellybird/game/core/include/JellyBirdGame.h | b09045664e5f74d29d6ea4e0e6e95e1070dfc7dd | [
"Apache-2.0"
] | permissive | xavierfebrer/jelly_bird | 044a3c982d7a4e6b54dcfddb14a42ba00d4a0591 | 2feea9007100366a76990ffd839e521acaf924fc | refs/heads/master | 2021-06-26T20:05:16.229647 | 2020-10-19T21:15:59 | 2020-10-19T21:15:59 | 168,494,217 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,359 | h | JellyBirdGame.h | #ifndef JELLY_BIRD_GAME_H
#define JELLY_BIRD_GAME_H
#include "../../../engine/core/include/Game.h"
#include "Constants.h"
#include "LogoAssets.h"
#include "MenuAssets.h"
#include "GameAssets.h"
#include "BaseScreen.h"
class JellyBirdGame : public Game<BaseScreen> {
public:
std::shared_ptr<LogoAssets> logoAssets;
std::shared_ptr<MenuAssets> menuAssets;
std::shared_ptr<GameAssets> gameAssets;
JellyBirdGame(const std::shared_ptr<LogoAssets> & logoAssets,
const std::shared_ptr<MenuAssets> & menuAssets,
const std::shared_ptr<GameAssets> & gameAssets);
virtual ~JellyBirdGame() override;
virtual bool create() override;
virtual void resume() override;
virtual void loop() override;
virtual void pause() override;
virtual void resize(double width, double height) override;
virtual void setScreen(std::unique_ptr<BaseScreen> newScreen) override;
protected:
bool initialized;
bool running;
long long currentTime = -1;
long long prevTime = -1;
std::unique_ptr<Screen<JellyBirdGame>> currentScreen;
std::unique_ptr<Screen<JellyBirdGame>> newScreen;
bool init();
bool waitForReadyState();
bool startGame();
void update(double deltaTime);
void render(double deltaTime);
void checkNewScreen();
void waitForTargetFPS();
};
#endif |
c1873c7860a232536c5064e4a322523d9e02ef99 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/cm-compiler/2019/12/CM_Topology.cpp | edeab1e7ea8652a13b2c2704ed21bedb0e686e6a | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 26,160 | cpp | CM_Topology.cpp | /*
* Copyright (c) 2017, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "stdafx.h"
#include <assert.h>
#include <iostream>
#include <limits>
#include <stdio.h>
#ifdef WIN32
#include <io.h>
//#include <cm/half.h>
#include <cm/cm.h>
#endif
#include "cmDNN.h"
/////////////////////////////////////////////////////////////////////////////
void CM_PIPELINE::Build_AlexNet(char * InputFile, int BatchSize, int UseFP16)
{
CreateInputLayer("../Data/Alexnet/Param/L0_Input.txt", InputFile, "../Data/Alexnet/Input/cnn_CnnMain_avg", BatchSize, UseFP16, true);
CreateConvolLayer("../Data/Alexnet/Param/L1_Convol.txt", "../Data/Alexnet/Input/cnn_CnnMain_conv1_w", "../Data/Alexnet/Input/cnn_CnnMain_conv1_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], NULL, true);
CreateLRNLayer("../Data/Alexnet/Param/L2_LRN.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], true);
CreateMaxPoolLayer("../Data/Alexnet/Param/L3_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], true);
CreateConvolLayer("../Data/Alexnet/Param/L4_Convol.txt", "../Data/Alexnet/Input/cnn_CnnMain_conv2_w", "../Data/Alexnet/Input/cnn_CnnMain_conv2_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], NULL, true);
CreateLRNLayer("../Data/Alexnet/Param/L5_LRN.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], true);
CreateMaxPoolLayer("../Data/Alexnet/Param/L6_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], true);
CreateConvolLayer("../Data/Alexnet/Param/L7_Convol.txt", "../Data/Alexnet/Input/cnn_CnnMain_conv3_w", "../Data/Alexnet/Input/cnn_CnnMain_conv3_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], NULL, true);
CreateConvolLayer("../Data/Alexnet/Param/L8_Convol.txt", "../Data/Alexnet/Input/cnn_CnnMain_conv4_w", "../Data/Alexnet/Input/cnn_CnnMain_conv4_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], NULL, true);
CreateConvolLayer("../Data/Alexnet/Param/L9_Convol.txt", "../Data/Alexnet/Input/cnn_CnnMain_conv5_w", "../Data/Alexnet/Input/cnn_CnnMain_conv5_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], NULL, true);
CreateMaxPoolLayer("../Data/Alexnet/Param/L10_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], true);
CreateSurfConvLayer("../Data/Alexnet/Param/L11_SurfConv.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], true);
CreateFCLayer("../Data/Alexnet/Param/L12_FC.txt", "../Data/Alexnet/Input/cnn_CnnMain_fc6_w", "../Data/Alexnet/Input/cnn_CnnMain_fc6_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], true);
CreateFCLayer("../Data/Alexnet/Param/L13_FC.txt", "../Data/Alexnet/Input/cnn_CnnMain_fc7_w", "../Data/Alexnet/Input/cnn_CnnMain_fc7_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], true);
CreateFCLayer("../Data/Alexnet/Param/L14_FC.txt", "../Data/Alexnet/Input/cnn_CnnMain_fc8_w", "../Data/Alexnet/Input/cnn_CnnMain_fc8_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], true);
CreateSoftMaxLayer("../Data/Alexnet/Param/L15_Softmax.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers-1], true);
}
///////////////////////////////////////////////////////////////////////////
void CM_PIPELINE::Build_VGG16(char * InputFile, int BatchSize, int UseFP16)
{
CreateInputLayer("../Data/VGG16/Param/L0_Input.txt", InputFile, "../Data/VGG16/Input/cnn_CnnMain_avg", BatchSize, UseFP16, true);
CreateConvolLayer("../Data/VGG16/Param/L1_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv1_1_w", "../Data/VGG16/Input/cnn_CnnMain_conv1_1_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG16/Param/L2_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv1_2_w", "../Data/VGG16/Input/cnn_CnnMain_conv1_2_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateMaxPoolLayer("../Data/VGG16/Param/L3_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateConvolLayer("../Data/VGG16/Param/L4_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv2_1_w", "../Data/VGG16/Input/cnn_CnnMain_conv2_1_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG16/Param/L5_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv2_2_w", "../Data/VGG16/Input/cnn_CnnMain_conv2_2_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateMaxPoolLayer("../Data/VGG16/Param/L6_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateConvolLayer("../Data/VGG16/Param/L7_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv3_1_w", "../Data/VGG16/Input/cnn_CnnMain_conv3_1_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG16/Param/L8_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv3_2_w", "../Data/VGG16/Input/cnn_CnnMain_conv3_2_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG16/Param/L9_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv3_3_w", "../Data/VGG16/Input/cnn_CnnMain_conv3_3_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateMaxPoolLayer("../Data/VGG16/Param/L10_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateConvolLayer("../Data/VGG16/Param/L11_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv4_1_w", "../Data/VGG16/Input/cnn_CnnMain_conv4_1_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG16/Param/L12_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv4_2_w", "../Data/VGG16/Input/cnn_CnnMain_conv4_2_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG16/Param/L13_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv4_3_w", "../Data/VGG16/Input/cnn_CnnMain_conv4_3_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateMaxPoolLayer("../Data/VGG16/Param/L14_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateConvolLayer("../Data/VGG16/Param/L15_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv5_1_w", "../Data/VGG16/Input/cnn_CnnMain_conv5_1_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG16/Param/L16_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv5_2_w", "../Data/VGG16/Input/cnn_CnnMain_conv5_2_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG16/Param/L17_Convol.txt", "../Data/VGG16/Input/cnn_CnnMain_conv5_3_w", "../Data/VGG16/Input/cnn_CnnMain_conv5_3_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateMaxPoolLayer("../Data/VGG16/Param/L18_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateSurfConvLayer("../Data/VGG16/Param/L19_SurfConv.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateFCLayer("../Data/VGG16/Param/L20_FC.txt", "../Data/VGG16/Input/cnn_CnnMain_fc6_w", "../Data/VGG16/Input/cnn_CnnMain_fc6_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateFCLayer("../Data/VGG16/Param/L21_FC.txt", "../Data/VGG16/Input/cnn_CnnMain_fc7_w", "../Data/VGG16/Input/cnn_CnnMain_fc7_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateFCLayer("../Data/VGG16/Param/L22_FC.txt", "../Data/VGG16/Input/cnn_CnnMain_fc8_w", "../Data/VGG16/Input/cnn_CnnMain_fc8_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateSoftMaxLayer("../Data/VGG16/Param/L23_Softmax.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
}
///////////////////////////////////////////////////////////////////////////
void CM_PIPELINE::Build_VGG19(char * InputFile, int BatchSize, int UseFP16)
{
CreateInputLayer("../Data/VGG19/Param/L0_Input.txt", InputFile, "../Data/VGG19/Input/cnn_CnnMain_avg", BatchSize, UseFP16, true);
CreateConvolLayer("../Data/VGG19/Param/L1_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv1_1_w", "../Data/VGG19/Input/cnn_CnnMain_conv1_1_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG19/Param/L2_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv1_2_w", "../Data/VGG19/Input/cnn_CnnMain_conv1_2_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateMaxPoolLayer("../Data/VGG19/Param/L3_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateConvolLayer("../Data/VGG19/Param/L4_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv2_1_w", "../Data/VGG19/Input/cnn_CnnMain_conv2_1_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG19/Param/L5_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv2_2_w", "../Data/VGG19/Input/cnn_CnnMain_conv2_2_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateMaxPoolLayer("../Data/VGG19/Param/L6_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateConvolLayer("../Data/VGG19/Param/L7_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv3_1_w", "../Data/VGG19/Input/cnn_CnnMain_conv3_1_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG19/Param/L8_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv3_2_w", "../Data/VGG19/Input/cnn_CnnMain_conv3_2_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG19/Param/L9_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv3_3_w", "../Data/VGG19/Input/cnn_CnnMain_conv3_3_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG19/Param/L10_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv3_4_w", "../Data/VGG19/Input/cnn_CnnMain_conv3_4_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateMaxPoolLayer("../Data/VGG19/Param/L11_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateConvolLayer("../Data/VGG19/Param/L12_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv4_1_w", "../Data/VGG19/Input/cnn_CnnMain_conv4_1_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG19/Param/L13_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv4_2_w", "../Data/VGG19/Input/cnn_CnnMain_conv4_2_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG19/Param/L14_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv4_3_w", "../Data/VGG19/Input/cnn_CnnMain_conv4_3_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG19/Param/L15_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv4_4_w", "../Data/VGG19/Input/cnn_CnnMain_conv4_4_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateMaxPoolLayer("../Data/VGG19/Param/L16_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateConvolLayer("../Data/VGG19/Param/L17_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv5_1_w", "../Data/VGG19/Input/cnn_CnnMain_conv5_1_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG19/Param/L18_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv5_2_w", "../Data/VGG19/Input/cnn_CnnMain_conv5_2_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG19/Param/L19_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv5_3_w", "../Data/VGG19/Input/cnn_CnnMain_conv5_3_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateConvolLayer("../Data/VGG19/Param/L20_Convol.txt", "../Data/VGG19/Input/cnn_CnnMain_conv5_4_w", "../Data/VGG19/Input/cnn_CnnMain_conv5_4_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], NULL, true);
CreateMaxPoolLayer("../Data/VGG19/Param/L21_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateSurfConvLayer("../Data/VGG19/Param/L22_SurfConv.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateFCLayer("../Data/VGG19/Param/L23_FC.txt", "../Data/VGG19/Input/cnn_CnnMain_fc6_w", "../Data/VGG19/Input/cnn_CnnMain_fc6_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateFCLayer("../Data/VGG19/Param/L24_FC.txt", "../Data/VGG19/Input/cnn_CnnMain_fc7_w", "../Data/VGG19/Input/cnn_CnnMain_fc7_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateFCLayer("../Data/VGG19/Param/L25_FC.txt", "../Data/VGG19/Input/cnn_CnnMain_fc8_w", "../Data/VGG19/Input/cnn_CnnMain_fc8_b", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
CreateSoftMaxLayer("../Data/VGG19/Param/L26_Softmax.txt", BatchSize, UseFP16, 1, &cmLayer[NumLayers - 1], true);
}
//////////////////////////////////////////////////////////////////////////////
void CM_PIPELINE::Build_Resnet50(char * InputFile, int BatchSize, int UseFP16)
{
// Layer 0-2
CreateInputLayer("../Data/Resnet50/Param/L0_Input.txt", InputFile, "../Data/Resnet50/Input/cnn_CnnMain_avg", BatchSize, UseFP16, true);
CreateConvolLayer("../Data/Resnet50/Param/L1_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_conv1_w", "../Data/Resnet50/Input/cnn_CnnMain_conv1_b", BatchSize, UseFP16, 1, &cmLayer[0], NULL, true);
CreateMaxPoolLayer("../Data/Resnet50/Param/L2_MaxPool.txt", BatchSize, UseFP16, 1, &cmLayer[1], true);
// Layer 3-6
CreateConvolLayer("../Data/Resnet50/Param/L3_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res2a_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res2a_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[2], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L4_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res2a_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res2a_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[3], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L5_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res2a_branch1_w", "../Data/Resnet50/Input/cnn_CnnMain_res2a_branch1_b", BatchSize, UseFP16, 1, &cmLayer[2], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L6_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res2a_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res2a_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[4], &cmLayer[5], true);
// Layer 7-9
CreateConvolLayer("../Data/Resnet50/Param/L7_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res2b_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res2b_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[6], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L8_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res2b_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res2b_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[7], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L9_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res2b_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res2b_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[8], &cmLayer[6], true);
// Layer 10-12
CreateConvolLayer("../Data/Resnet50/Param/L10_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res2c_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res2c_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[9], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L11_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res2c_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res2c_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[10], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L12_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res2c_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res2c_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[11], &cmLayer[9], true);
// Layer 13-16
CreateConvolLayer("../Data/Resnet50/Param/L13_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3a_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res3a_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[12], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L14_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3a_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res3a_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[13], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L15_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3a_branch1_w", "../Data/Resnet50/Input/cnn_CnnMain_res3a_branch1_b", BatchSize, UseFP16, 1, &cmLayer[12], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L16_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3a_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res3a_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[14], &cmLayer[15], true);
// Layer 17-19
CreateConvolLayer("../Data/Resnet50/Param/L17_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3b_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res3b_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[16], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L18_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3b_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res3b_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[17], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L19_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3b_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res3b_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[18], &cmLayer[16], true);
// Layer 20-22
CreateConvolLayer("../Data/Resnet50/Param/L20_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3c_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res3c_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[19], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L21_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3c_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res3c_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[20], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L22_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3c_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res3c_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[21], &cmLayer[19], true);
// Layer 23-25
CreateConvolLayer("../Data/Resnet50/Param/L23_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3d_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res3d_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[22], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L24_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3d_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res3d_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[23], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L25_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res3d_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res3d_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[24], &cmLayer[22], true);
// Layer 26-29
CreateConvolLayer("../Data/Resnet50/Param/L26_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4a_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res4a_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[25], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L27_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4a_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res4a_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[26], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L28_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4a_branch1_w", "../Data/Resnet50/Input/cnn_CnnMain_res4a_branch1_b", BatchSize, UseFP16, 1, &cmLayer[25], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L29_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4a_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res4a_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[27], &cmLayer[28], true);
// Layer 30-32
CreateConvolLayer("../Data/Resnet50/Param/L30_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4b_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res4b_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[29], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L31_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4b_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res4b_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[30], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L32_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4b_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res4b_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[31], &cmLayer[29], true);
// Layer 33-35
CreateConvolLayer("../Data/Resnet50/Param/L33_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4c_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res4c_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[32], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L34_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4c_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res4c_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[33], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L35_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4c_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res4c_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[34], &cmLayer[32], true);
// Layer 36-38
CreateConvolLayer("../Data/Resnet50/Param/L36_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4d_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res4d_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[35], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L37_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4d_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res4d_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[36], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L38_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4d_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res4d_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[37], &cmLayer[35], true);
// Layer 39-41
CreateConvolLayer("../Data/Resnet50/Param/L39_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4e_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res4e_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[38], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L40_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4e_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res4e_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[39], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L41_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4e_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res4e_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[40], &cmLayer[38], true);
// Layer 42-44
CreateConvolLayer("../Data/Resnet50/Param/L42_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4f_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res4f_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[41], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L43_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4f_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res4f_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[42], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L44_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res4f_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res4f_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[43], &cmLayer[41], true);
// Layer 45-48
CreateConvolLayer("../Data/Resnet50/Param/L45_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res5a_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res5a_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[44], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L46_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res5a_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res5a_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[45], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L47_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res5a_branch1_w", "../Data/Resnet50/Input/cnn_CnnMain_res5a_branch1_b", BatchSize, UseFP16, 1, &cmLayer[44], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L48_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res5a_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res5a_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[46], &cmLayer[47], true);
// Layer 49-51
CreateConvolLayer("../Data/Resnet50/Param/L49_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res5b_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res5b_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[48], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L50_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res5b_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res5b_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[49], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L51_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res5b_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res5b_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[50], &cmLayer[48], true);
// Layer 52-54
CreateConvolLayer("../Data/Resnet50/Param/L52_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res5c_branch2a_w", "../Data/Resnet50/Input/cnn_CnnMain_res5c_branch2a_b", BatchSize, UseFP16, 1, &cmLayer[51], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L53_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res5c_branch2b_w", "../Data/Resnet50/Input/cnn_CnnMain_res5c_branch2b_b", BatchSize, UseFP16, 1, &cmLayer[52], NULL, true);
CreateConvolLayer("../Data/Resnet50/Param/L54_Convol.txt", "../Data/Resnet50/Input/cnn_CnnMain_res5c_branch2c_w", "../Data/Resnet50/Input/cnn_CnnMain_res5c_branch2c_b", BatchSize, UseFP16, 2, &cmLayer[53], &cmLayer[51], true);
// Layer 55-57
CreateAvgPoolLayer("../Data/Resnet50/Param/L55_AvgPool.txt", BatchSize, UseFP16, 1, &cmLayer[54], true);
CreateFCLayer("../Data/Resnet50/Param/L56_FC.txt", "../Data/Resnet50/Input/cnn_CnnMain_fc1000_w", "../Data/Resnet50/Input/cnn_CnnMain_fc1000_b", BatchSize, UseFP16, 1, &cmLayer[55], true);
CreateSoftMaxLayer("../Data/Resnet50/Param/L57_Softmax.txt", BatchSize, UseFP16, 1, &cmLayer[56], true);
}
|
9d892243ff1758703a0e120fa35d60d3a73d8f5c | ac087020d9725e366785c3513d156a7050dcb65f | /src/BaseObj.h | 1c65920e4c12276f8a847b7fb7c439c6ac553e0e | [] | no_license | systemtwo/cellphoneescape-v2 | 9620ad40fd3300c0012133c85f445e237f4543aa | aac6d1df48d3ffccaa3bac2dca407cd19967a25f | refs/heads/master | 2021-01-25T09:59:14.556951 | 2013-06-18T05:08:09 | 2013-06-18T05:08:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 558 | h | BaseObj.h | #ifndef H_BASEOBJ
#define H_BASEOBJ
#include <SFML/Graphics.hpp>
//Move this somewhere else
class BoundingBox {
public:
BoundingBox(float, float, float, float);
float x, y, h, w;
private:
};
enum Direction {LEFT, RIGHT, UP, DOWN};
class BaseObj {
public:
bool selfDestruct;
BaseObj();
virtual void update(float dt);
virtual void draw(sf::RenderWindow*);
virtual void onCollide(BaseObj*, Direction, float);
virtual std::vector<BoundingBox> getBoundingBoxes();
virtual std::string getName();
protected:
std::string name;
};
#endif
|
39bf261019aa8211e654360454c153f86e00c740 | 6d90e332ed3e630429e959578df1181967c4bcaa | /AC-Submissions/problems/reverse_linked_list/solution.cpp | f513d2fb081cbd8d680d0734c0fe8e20cd0a0e4b | [] | no_license | amir-hosen7/LeetCode | fe27cca877b5ee8c73c00b6553b682b94351e16d | ee13b162c098276abd2f01b0ae4ea6bbe527bfa1 | refs/heads/master | 2023-02-23T04:15:52.250303 | 2023-02-13T12:57:46 | 2023-02-13T12:57:46 | 234,529,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | cpp | solution.cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* root) {
if(root==NULL){
return NULL;
}
ListNode *currNode=root;
ListNode *prevNode=NULL,*temp;
while(currNode->next!=NULL){
temp=currNode;
currNode=currNode->next;
temp->next=prevNode;
prevNode=temp;
}
currNode->next=prevNode;
return currNode;
}
}; |
0fd65a020704a3d13f9b382a36a1c2f6862c75d0 | 52dc9080af88c00222cc9b37aa08c35ff3cafe86 | /0700/30/733a.cpp | 9805f91fa8804a16e81b897f5085613369f65334 | [
"Unlicense"
] | permissive | shivral/cf | 1c1acde25fc6af775acaeeb6b5fe5aa9bbcfd4d2 | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | refs/heads/master | 2023-03-20T01:29:25.559828 | 2021-03-05T08:30:30 | 2021-03-05T08:30:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 560 | cpp | 733a.cpp | #include <iostream>
#include <string>
bool vowel(char c)
{
return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' || c == 'Y';
}
void answer(unsigned v)
{
std::cout << v << '\n';
}
void solve(const std::string& s)
{
const size_t n = s.length();
unsigned d = 0, k = 0;
for (size_t i = 0; i < n; ++i) {
++d;
if (vowel(s[i])) {
k = std::max(k, d);
d = 0;
}
}
answer(std::max(k, d+1));
}
int main()
{
std::string s;
std::cin >> s;
solve(s);
return 0;
}
|
be98f468a360db807c73437c1b97f56c25327277 | 1e63053957bfa3681b4b5c22b4aced08151e240e | /TD9/code/perceptron.hpp | f92e64db768d6defb1dc70959f81ae9d3b9913ec | [] | no_license | gostreap/INF442 | 59ca4b1ab5dacc648378d245b735df392c998fd9 | cedc9e65e96f271383b6a0a5746306a310a07f5c | refs/heads/main | 2023-05-03T09:04:00.759801 | 2021-05-25T16:49:47 | 2021-05-25T16:49:47 | 346,263,842 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,546 | hpp | perceptron.hpp | #pragma once
#include "dataset.hpp"
#include "neuron.hpp"
const int default_nb_neurons = 5;
const int default_nb_epochs = 100;
const double default_learning_rate = 0.1;
class OneLayerPerceptron
{
protected:
int dim;
int size;
std::vector<Node *> inputs;
std::vector<Neuron *> hidden;
Neuron *output;
int epoch;
double rate;
double decay;
public:
OneLayerPerceptron(int _dim, int _size, double _rate, double _decay,
std::function<double(double)> _activation,
std::function<double(double)> _activation_der);
~OneLayerPerceptron();
int getNbNeurons();
double getLearningRate();
double getDecay();
// "Using Learning Rate Schedules for Deep Learning Models
// in Python with Keras", by Jason Brownlee
// https://machinelearningmastery.com/using-learning-rate-schedules-deep-learning-models-python-keras/
void setLearningRate(double _rate);
void initLearningRate(double _rate);
void decayLearningRate();
protected:
double normalise(double val, Dataset *data, int coord);
double denormalise(double val, Dataset *data, int coord);
virtual void prepareInputs(Dataset *data, int row, int regr, bool print = false);
virtual void computeHiddenStep(bool print = false);
virtual double computeOutputStep(Dataset *data, int row, int regr, bool print = false);
virtual void propagateBackHidden(bool print = false);
public:
virtual double run(Dataset *data, int row, int regr, bool print = false);
};
|
657983fe1346511c89c2c7e804c11dfaeec282c9 | 9656ebbef39f30510919460db8369b678db7890b | /version_finale2A6_mariem/gerer_evenement.h | 3f43160f8b52b89c3f6492810f92b3fc79789f29 | [] | no_license | KhaledKhm/bus | 77cae0d700b37383bc1345ee5e9230c7642309d3 | e290b1e0fd25c62389cc6b612467f34f5a37bc2a | refs/heads/master | 2022-03-27T20:05:19.535966 | 2020-01-15T20:21:06 | 2020-01-15T20:21:06 | 221,741,893 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,405 | h | gerer_evenement.h | #ifndef GERER_EVENEMENT_H
#define GERER_EVENEMENT_H
#include "rem.h"
#include "even.h"
#include <QMainWindow>
#include<QDebug>
#include <QtCharts/QPieSlice>
#include <QtCharts/QPieSeries>
#include <QVBoxLayout>
#include <QDialog>
#include "stat2.h"
#include "stateven.h"
namespace Ui {
class gerer_evenement;
}
class gerer_evenement : public QDialog
{
Q_OBJECT
public:
explicit gerer_evenement(QWidget *parent = nullptr);
~gerer_evenement();
private slots:
void on_pb_ajouter_clicked();
void on_pb_supprimer_clicked();
void on_ajouter_clicked();
void on_Supprimer_clicked();
void on_Modifier_clicked();
//void on_tri_clicked();
//void on_tri2_clicked();
void on_xz_currentTextChanged(const QString &arg1);
void on_Modif2_clicked();
void on_xy_currentTextChanged(const QString &arg1);
void on_stat_currentchanged(int index);
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_Actualiser3_clicked();
void on_combrech_currentIndexChanged(const QString &arg1);
void on_rech_currentIndexChanged(const QString &arg1);
void on_stat2_currentchanged(int index);
private:
Ui::gerer_evenement *ui;
rem r ;
QVBoxLayout * mainLayout;
Stat2 s;
Stateven s2;
even e;
};
#endif // GERER_EVENEMENT_H
|
a43a2c2021d141c0e5912b14fc0d911ef40847fc | d8a4b84c1963974d878dc51a503f70573eea3c72 | /devel/include/easy_handeye/ComputeCalibration.h | e19cd6b97fb0adc000529760627249b32549a56c | [] | no_license | robotic-ultrasound-image-system/ur5 | 72eb8b7cbd9fbb3dbaac107ed098ac44b9da4402 | 4b0cff44fb9159a3a372a09b1abb0d5084fdf960 | refs/heads/master | 2021-01-21T10:41:50.064585 | 2018-04-08T12:08:52 | 2018-04-08T12:08:52 | 101,979,048 | 11 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,019 | h | ComputeCalibration.h | // Generated by gencpp from file easy_handeye/ComputeCalibration.msg
// DO NOT EDIT!
#ifndef EASY_HANDEYE_MESSAGE_COMPUTECALIBRATION_H
#define EASY_HANDEYE_MESSAGE_COMPUTECALIBRATION_H
#include <ros/service_traits.h>
#include <easy_handeye/ComputeCalibrationRequest.h>
#include <easy_handeye/ComputeCalibrationResponse.h>
namespace easy_handeye
{
struct ComputeCalibration
{
typedef ComputeCalibrationRequest Request;
typedef ComputeCalibrationResponse Response;
Request request;
Response response;
typedef Request RequestType;
typedef Response ResponseType;
}; // struct ComputeCalibration
} // namespace easy_handeye
namespace ros
{
namespace service_traits
{
template<>
struct MD5Sum< ::easy_handeye::ComputeCalibration > {
static const char* value()
{
return "93e3866c4ed928ecb649cca85b0b0261";
}
static const char* value(const ::easy_handeye::ComputeCalibration&) { return value(); }
};
template<>
struct DataType< ::easy_handeye::ComputeCalibration > {
static const char* value()
{
return "easy_handeye/ComputeCalibration";
}
static const char* value(const ::easy_handeye::ComputeCalibration&) { return value(); }
};
// service_traits::MD5Sum< ::easy_handeye::ComputeCalibrationRequest> should match
// service_traits::MD5Sum< ::easy_handeye::ComputeCalibration >
template<>
struct MD5Sum< ::easy_handeye::ComputeCalibrationRequest>
{
static const char* value()
{
return MD5Sum< ::easy_handeye::ComputeCalibration >::value();
}
static const char* value(const ::easy_handeye::ComputeCalibrationRequest&)
{
return value();
}
};
// service_traits::DataType< ::easy_handeye::ComputeCalibrationRequest> should match
// service_traits::DataType< ::easy_handeye::ComputeCalibration >
template<>
struct DataType< ::easy_handeye::ComputeCalibrationRequest>
{
static const char* value()
{
return DataType< ::easy_handeye::ComputeCalibration >::value();
}
static const char* value(const ::easy_handeye::ComputeCalibrationRequest&)
{
return value();
}
};
// service_traits::MD5Sum< ::easy_handeye::ComputeCalibrationResponse> should match
// service_traits::MD5Sum< ::easy_handeye::ComputeCalibration >
template<>
struct MD5Sum< ::easy_handeye::ComputeCalibrationResponse>
{
static const char* value()
{
return MD5Sum< ::easy_handeye::ComputeCalibration >::value();
}
static const char* value(const ::easy_handeye::ComputeCalibrationResponse&)
{
return value();
}
};
// service_traits::DataType< ::easy_handeye::ComputeCalibrationResponse> should match
// service_traits::DataType< ::easy_handeye::ComputeCalibration >
template<>
struct DataType< ::easy_handeye::ComputeCalibrationResponse>
{
static const char* value()
{
return DataType< ::easy_handeye::ComputeCalibration >::value();
}
static const char* value(const ::easy_handeye::ComputeCalibrationResponse&)
{
return value();
}
};
} // namespace service_traits
} // namespace ros
#endif // EASY_HANDEYE_MESSAGE_COMPUTECALIBRATION_H
|
3311f75ff00496444543103b41064cab15f0f719 | 413f6e8ba7bfc65b05ecf3327353ff901faf3508 | /src/scale.h | 44a8a6a967ad4ddf9598c4ebe91092f7fd97130d | [] | no_license | tekay/kniffs | c67589cb78d4a22a5de1920dfdde4558aefb3f53 | 8f73d109b2639bc68a53fd5feac99f4daf9907c1 | refs/heads/master | 2021-01-12T11:42:57.038074 | 2016-11-12T14:43:09 | 2016-11-12T14:43:09 | 72,273,477 | 1 | 1 | null | 2016-11-10T17:48:12 | 2016-10-29T08:23:23 | C++ | UTF-8 | C++ | false | false | 1,547 | h | scale.h | #ifndef SCALE_H__
#define SCALE_H__
#include "ltexture.h"
#include "ball.h"
#include "event.h"
#include <memory>
class Scale {
public:
Scale(SDL_Renderer *gRenderer, TTF_Font *gFont, int leftOffset, int topOffset);
~Scale();
std::shared_ptr<Ball> getBallAt(int col, int row);
std::shared_ptr<Ball> getAndRemoveBallAt(int col, int row);
std::shared_ptr<Event> dropBallAt(std::shared_ptr<Ball> ball, int col);
std::shared_ptr<Event> adjust();
void collapse();
void stack();
// graphics
void render();
private:
// constants
static const int STACK_HEIGHT = 10;
static const int COL_COUNT = 2;
static const int SCALE_TEXTURE_WIDTH = 100;
static const int SCALE_TEXTURE_HEIGHT = 110;
static const int BALL_AREA_HEIGHT = 500;
static const int SCALE_TOP_OFFSET = 450;
static const int SCALE_STATUS_COUNT = 3;
// functions
void stacking(int col);
bool relocateStacks(int oldStatus);
bool stackUp(int col, int firstElem);
void stackDown(int col, int firstElem);
int firstBallSlot(int col);
int newStatus();
std::shared_ptr<Ball> getAndRemoveBallFromTop(int col);
void setBallToPos(int row, int col);
// status: 0 = neutral, 1 = left down, 2 = right down;
int status;
int weights[COL_COUNT];
std::shared_ptr<Ball> stacks[COL_COUNT][STACK_HEIGHT];
int leftOffset;
int topOffset;
// graphics
SDL_Rect spriteClips[SCALE_STATUS_COUNT];
SDL_Renderer *renderer;
TTF_Font *font;
std::unique_ptr<LTexture> texture;
std::unique_ptr<LTexture> weightTextures[COL_COUNT];
};
#endif
|
a6465fd0998f5ec619b8c7169337f71f856d22f0 | 8d39f509abf62a0947f3e9dd11a1bc02665b609e | /TIC2/code/C10/LogFile.cpp | c548cef7c508f207f33f28316d5cee8518e37ae5 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | clcheungac/clcheungac.github.io | c77c8a0c5b2261cf37602ce644c143e266184277 | 815885f2af89ef3ac32fad607786c6e8fa47c6e0 | refs/heads/master | 2021-01-10T13:08:37.959427 | 2018-12-30T13:44:20 | 2018-12-30T13:44:20 | 48,602,655 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 137 | cpp | LogFile.cpp | //: C10:LogFile.cpp {O}
#include "LogFile.h"
std::ofstream& logfile() {
static std::ofstream log("Logfile.log");
return log;
} ///:~
|
b7e977d8b797c31c5cf4164370db2dc8b1ff1324 | ae665e498f58c76ad7f9d0430a9a92edefe0c7a6 | /generators/PerlinNoiseGenerator.h | 33baf955725f75f5b8d0aa1fddcacaf68390b0ff | [] | no_license | danseremet/371OpenWorldProject | c152ef2c7aeaf7af145f0759d42c43473b90dad0 | e6bbab791770ed1b2f3794a8d4d8c92f413d55ff | refs/heads/master | 2022-04-18T08:51:54.766677 | 2020-04-20T02:53:32 | 2020-04-20T02:53:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 863 | h | PerlinNoiseGenerator.h | //
// Created by danseremet on 2020-04-07.
//
#ifndef OPENWORLD_PERLINNOISEGENERATOR_H
#define OPENWORLD_PERLINNOISEGENERATOR_H
#include <random>
#include <iostream>
#include <math.h>
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
class PerlinNoiseGenerator {
private:
int seed;
float roughness;
int octaves;
float amplitude;
std::random_device rd;
std::mt19937 rng{rd()};
std::uniform_int_distribution<int> uni{0, 1000000000};
std::vector<int> p;
public:
PerlinNoiseGenerator(float roughness, int octaves, float amplitude);
float getAmplitude() const;
double noise(double x, double y, double z);
double fade(double t);
double grad(int hash, double x, double y, double z);
double lerp(double t, double a, double b);
};
#endif //OPENWORLD_PERLINNOISEGENERATOR_H
|
b92496aeb7e6067574e81c6062995960f1a3c43e | 8b71beed25de8e1dd3abc2f8fc4a39a29cb5e440 | /Executer/include/stats.hpp | bf596b6b5fcd1b3f459ea8fb5109f1713ff48b2a | [] | no_license | gdshukla/Executer | 38dd980637ec1b80c805eca29cd004af1a437009 | 17b6f23144ce5b7c5c0bdf75349ef46e8d431ae2 | refs/heads/main | 2023-05-14T02:49:28.866685 | 2021-06-04T18:50:59 | 2021-06-04T18:50:59 | 371,464,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,339 | hpp | stats.hpp | #pragma once
#include <atomic>
#include <iostream>
#include <condition_variable>
// singleton class to keep track of task stats
class Stats
{
std::atomic_int m_running;
std::atomic_int m_completed;
std::atomic_int m_total;
bool m_ready = false;
std::condition_variable m_cv;
std::mutex m_mutex;
Stats() : m_running{ 0 }, m_completed{ 0 }, m_total{ 0 }
{}
static std::unique_ptr<Stats> m_instance;
public:
int running()
{
return m_running;
}
void wait()
{
auto lock = std::unique_lock<std::mutex>(m_mutex);
m_cv.wait(lock, [this] { return m_ready; });
m_ready = false;
}
void started()
{
m_running++;
}
void added()
{
m_total++;
}
void completed()
{
m_completed++; m_running--;
auto lock = std::unique_lock<std::mutex>(m_mutex);
m_ready = true;
m_cv.notify_one();
}
void display()
{
std::cout << "Tasks running : " << m_running << "\n";
std::cout << "Tasks completed: " << m_completed << "\n";
std::cout << "Total Tasks : " << m_total << "\n";
}
static Stats* instance()
{
if (!m_instance)
{
m_instance.reset(new Stats);
}
return m_instance.get();
}
};
|
b18ca46cd66a4bcd5b8d99b972a367e115084c9c | 6c7d6e7d539f231318a4d89fd3d8e7ffab588885 | /BOJ10211.cpp | 0e2fd144fb861913e132b552b86507ba62246ebe | [] | no_license | muzee99/BOJ | 9c46b713624d106252d84dee78f79b72f67e1e60 | 7b88addf0480b4740dd2e8de720687a7177f7b7e | refs/heads/master | 2022-12-22T07:45:41.004499 | 2020-09-25T04:11:19 | 2020-09-25T04:11:19 | 282,138,998 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 242 | cpp | BOJ10211.cpp | // BOJ10211_Maximum Subarray
#include <iostream>
using namespace std;
int T, N;
int a[1000];
int main() {
cin >> T;
for(int i=0; i<T; i++) {
cin >> N;
for(int j=0; j<N; j++) {
cin >> a[j];
}
}
} |
2d8c67541a24d5c925f267d824d91694b7de8e91 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /iecp/include/tencentcloud/iecp/v20210914/model/ApplicationStatusInfo.h | ee5a55734ba9c57aee9f284900c12bb64f83cac1 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 14,469 | h | ApplicationStatusInfo.h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_IECP_V20210914_MODEL_APPLICATIONSTATUSINFO_H_
#define TENCENTCLOUD_IECP_V20210914_MODEL_APPLICATIONSTATUSINFO_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/iecp/v20210914/model/ApplicationDeployMode.h>
namespace TencentCloud
{
namespace Iecp
{
namespace V20210914
{
namespace Model
{
/**
* 应用状态
*/
class ApplicationStatusInfo : public AbstractModel
{
public:
ApplicationStatusInfo();
~ApplicationStatusInfo() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取应用ID
注意:此字段可能返回 null,表示取不到有效值。
* @return Id 应用ID
注意:此字段可能返回 null,表示取不到有效值。
*
*/
uint64_t GetId() const;
/**
* 设置应用ID
注意:此字段可能返回 null,表示取不到有效值。
* @param _id 应用ID
注意:此字段可能返回 null,表示取不到有效值。
*
*/
void SetId(const uint64_t& _id);
/**
* 判断参数 Id 是否已赋值
* @return Id 是否已赋值
*
*/
bool IdHasBeenSet() const;
/**
* 获取应用名称
注意:此字段可能返回 null,表示取不到有效值。
* @return Name 应用名称
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::string GetName() const;
/**
* 设置应用名称
注意:此字段可能返回 null,表示取不到有效值。
* @param _name 应用名称
注意:此字段可能返回 null,表示取不到有效值。
*
*/
void SetName(const std::string& _name);
/**
* 判断参数 Name 是否已赋值
* @return Name 是否已赋值
*
*/
bool NameHasBeenSet() const;
/**
* 获取应用版本
注意:此字段可能返回 null,表示取不到有效值。
* @return Version 应用版本
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::string GetVersion() const;
/**
* 设置应用版本
注意:此字段可能返回 null,表示取不到有效值。
* @param _version 应用版本
注意:此字段可能返回 null,表示取不到有效值。
*
*/
void SetVersion(const std::string& _version);
/**
* 判断参数 Version 是否已赋值
* @return Version 是否已赋值
*
*/
bool VersionHasBeenSet() const;
/**
* 获取应用状态(1:待部署 2:部署中 3:运行中 4:待更新 5:更新中 6:待删除 7:删除中 8:已删除
注意:此字段可能返回 null,表示取不到有效值。
* @return Status 应用状态(1:待部署 2:部署中 3:运行中 4:待更新 5:更新中 6:待删除 7:删除中 8:已删除
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::string GetStatus() const;
/**
* 设置应用状态(1:待部署 2:部署中 3:运行中 4:待更新 5:更新中 6:待删除 7:删除中 8:已删除
注意:此字段可能返回 null,表示取不到有效值。
* @param _status 应用状态(1:待部署 2:部署中 3:运行中 4:待更新 5:更新中 6:待删除 7:删除中 8:已删除
注意:此字段可能返回 null,表示取不到有效值。
*
*/
void SetStatus(const std::string& _status);
/**
* 判断参数 Status 是否已赋值
* @return Status 是否已赋值
*
*/
bool StatusHasBeenSet() const;
/**
* 获取开始时间
注意:此字段可能返回 null,表示取不到有效值。
* @return StartTime 开始时间
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::string GetStartTime() const;
/**
* 设置开始时间
注意:此字段可能返回 null,表示取不到有效值。
* @param _startTime 开始时间
注意:此字段可能返回 null,表示取不到有效值。
*
*/
void SetStartTime(const std::string& _startTime);
/**
* 判断参数 StartTime 是否已赋值
* @return StartTime 是否已赋值
*
*/
bool StartTimeHasBeenSet() const;
/**
* 获取管理地址
注意:此字段可能返回 null,表示取不到有效值。
* @return ManageUrl 管理地址
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::string GetManageUrl() const;
/**
* 设置管理地址
注意:此字段可能返回 null,表示取不到有效值。
* @param _manageUrl 管理地址
注意:此字段可能返回 null,表示取不到有效值。
*
*/
void SetManageUrl(const std::string& _manageUrl);
/**
* 判断参数 ManageUrl 是否已赋值
* @return ManageUrl 是否已赋值
*
*/
bool ManageUrlHasBeenSet() const;
/**
* 获取负载类型
注意:此字段可能返回 null,表示取不到有效值。
* @return WorkloadKind 负载类型
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::string GetWorkloadKind() const;
/**
* 设置负载类型
注意:此字段可能返回 null,表示取不到有效值。
* @param _workloadKind 负载类型
注意:此字段可能返回 null,表示取不到有效值。
*
*/
void SetWorkloadKind(const std::string& _workloadKind);
/**
* 判断参数 WorkloadKind 是否已赋值
* @return WorkloadKind 是否已赋值
*
*/
bool WorkloadKindHasBeenSet() const;
/**
* 获取应用部署模式
注意:此字段可能返回 null,表示取不到有效值。
* @return DeployMode 应用部署模式
注意:此字段可能返回 null,表示取不到有效值。
*
*/
ApplicationDeployMode GetDeployMode() const;
/**
* 设置应用部署模式
注意:此字段可能返回 null,表示取不到有效值。
* @param _deployMode 应用部署模式
注意:此字段可能返回 null,表示取不到有效值。
*
*/
void SetDeployMode(const ApplicationDeployMode& _deployMode);
/**
* 判断参数 DeployMode 是否已赋值
* @return DeployMode 是否已赋值
*
*/
bool DeployModeHasBeenSet() const;
/**
* 获取期望Pod数
注意:此字段可能返回 null,表示取不到有效值。
* @return Replicas 期望Pod数
注意:此字段可能返回 null,表示取不到有效值。
*
*/
int64_t GetReplicas() const;
/**
* 设置期望Pod数
注意:此字段可能返回 null,表示取不到有效值。
* @param _replicas 期望Pod数
注意:此字段可能返回 null,表示取不到有效值。
*
*/
void SetReplicas(const int64_t& _replicas);
/**
* 判断参数 Replicas 是否已赋值
* @return Replicas 是否已赋值
*
*/
bool ReplicasHasBeenSet() const;
/**
* 获取运行Pod数
注意:此字段可能返回 null,表示取不到有效值。
* @return AvailableReplicas 运行Pod数
注意:此字段可能返回 null,表示取不到有效值。
*
*/
int64_t GetAvailableReplicas() const;
/**
* 设置运行Pod数
注意:此字段可能返回 null,表示取不到有效值。
* @param _availableReplicas 运行Pod数
注意:此字段可能返回 null,表示取不到有效值。
*
*/
void SetAvailableReplicas(const int64_t& _availableReplicas);
/**
* 判断参数 AvailableReplicas 是否已赋值
* @return AvailableReplicas 是否已赋值
*
*/
bool AvailableReplicasHasBeenSet() const;
private:
/**
* 应用ID
注意:此字段可能返回 null,表示取不到有效值。
*/
uint64_t m_id;
bool m_idHasBeenSet;
/**
* 应用名称
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_name;
bool m_nameHasBeenSet;
/**
* 应用版本
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_version;
bool m_versionHasBeenSet;
/**
* 应用状态(1:待部署 2:部署中 3:运行中 4:待更新 5:更新中 6:待删除 7:删除中 8:已删除
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_status;
bool m_statusHasBeenSet;
/**
* 开始时间
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_startTime;
bool m_startTimeHasBeenSet;
/**
* 管理地址
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_manageUrl;
bool m_manageUrlHasBeenSet;
/**
* 负载类型
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_workloadKind;
bool m_workloadKindHasBeenSet;
/**
* 应用部署模式
注意:此字段可能返回 null,表示取不到有效值。
*/
ApplicationDeployMode m_deployMode;
bool m_deployModeHasBeenSet;
/**
* 期望Pod数
注意:此字段可能返回 null,表示取不到有效值。
*/
int64_t m_replicas;
bool m_replicasHasBeenSet;
/**
* 运行Pod数
注意:此字段可能返回 null,表示取不到有效值。
*/
int64_t m_availableReplicas;
bool m_availableReplicasHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_IECP_V20210914_MODEL_APPLICATIONSTATUSINFO_H_
|
6e11cef3e62369a19b9ae8ec2e396eaa6f3521c5 | b5109f0cb8bdf982995ac1a8ff9bcc6d28cff05e | /car.cpp | 5c3bb1072479d30c2f6201f087fd46940fb1e764 | [] | no_license | deepakpunjabi/programs | 9b0db946433f5d58234691cbb093a9299ac24b74 | 4004f9056c4806ce228c613e27e40329059a9a81 | refs/heads/master | 2021-01-18T22:14:04.614230 | 2017-06-18T06:12:30 | 2017-06-18T06:12:30 | 72,332,170 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | cpp | car.cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n,k,q;
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
scanf("%d %d %d",&n,&k,&q);
int *a=(int *)malloc(n*sizeof(int));
int *qs=(int *)malloc(q*sizeof(int));
for(int i=0;i<n;i++){
cin>>a[(i+k)%n];
}
for(int i=0;i<q;i++){
cin>>qs[i];
}
for(int i=0;i<q;i++){
cout<<a[qs[i]]<<endl;
}
return 0;
}
|
2cf88789265b17afa15b27ec44e7edc628173074 | 6d443022eae3181b4c7d6c5040c930ab27b2f1c5 | /src/native/jni/com_scriptographer_ai_Symbol.cpp | 7825909d9dd172a2117d0025ce43eed424dd90cf | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | scriptographer/scriptographer | 45397da2b56b04ca4f7a9e95efd93bc4cb57b0f7 | d896fcbf1053c5cfb623627e51e310a126907a1c | refs/heads/master | 2021-01-10T20:20:54.337812 | 2020-01-24T11:55:35 | 2020-01-24T11:55:35 | 656,874 | 88 | 15 | null | 2014-01-11T16:02:47 | 2010-05-08T20:16:22 | Java | UTF-8 | C++ | false | false | 6,235 | cpp | com_scriptographer_ai_Symbol.cpp | /*
* Scriptographer
*
* This file is part of Scriptographer, a Scripting Plugin for Adobe Illustrator
* http://scriptographer.org/
*
* Copyright (c) 2002-2010, Juerg Lehni
* http://scratchdisk.com/
*
* All rights reserved. See LICENSE file for details.
*/
#include "stdHeaders.h"
#include "ScriptographerEngine.h"
#include "aiGlobals.h"
#include "com_scriptographer_ai_Symbol.h"
/*
* com.scriptographer.ai.Symbol
*/
/*
* int nativeCreate(int artHandle)
*/
JNIEXPORT jint JNICALL Java_com_scriptographer_ai_Symbol_nativeCreate(JNIEnv *env, jclass cls, jint artHandle) {
try {
// Make sure we're switching to the right doc (gCreationDoc)
Document_activate();
AIPatternHandle symbol = NULL;
// Commit pending changes first
Item_commit(env, (AIArtHandle) artHandle);
#if kPluginInterfaceVersion >= kAI15
// TODO: Test these parameters registrationPoint, transformDefinitionArt, decide wether to pass
// them and compare with behavior in CS4...
sAISymbol->NewSymbolPattern(&symbol, (AIArtHandle) artHandle, kSymbolCenterPoint, true, false);
#else // kPluginInterfaceVersion < kAI15
sAISymbol->NewSymbolPattern(&symbol, (AIArtHandle) artHandle, false);
#endif // kPluginInterfaceVersion < kAI15
return (jint) symbol;
} EXCEPTION_CONVERT(env);
return 0;
}
/*
* java.lang.String getName()
*/
JNIEXPORT jstring JNICALL Java_com_scriptographer_ai_Symbol_getName(JNIEnv *env, jobject obj) {
try {
AIPatternHandle symbol = gEngine->getPatternHandle(env, obj);
#if kPluginInterfaceVersion >= kAI12
ai::UnicodeString name;
if (!sAISymbol->GetSymbolPatternName(symbol, name)) {
#else // kPluginInterfaceVersion < kAI12
char name[kMaxSymbolNameLength];
if (!sAISymbol->GetSymbolPatternName(symbol, name, kMaxSymbolNameLength)) {
#endif // kPluginInterfaceVersion < kAI12
return gEngine->convertString(env, name);
}
} EXCEPTION_CONVERT(env);
return NULL;
}
/*
* void setName(java.lang.String name)
*/
JNIEXPORT void JNICALL Java_com_scriptographer_ai_Symbol_setName(JNIEnv *env, jobject obj, jstring name) {
try {
AIPatternHandle symbol = gEngine->getPatternHandle(env, obj, true);
if (name != NULL) {
#if kPluginInterfaceVersion >= kAI12
ai::UnicodeString str = gEngine->convertString_UnicodeString(env, name);
sAISymbol->GetSymbolPatternDisplayName(str);
sAISymbol->SetSymbolPatternBaseName(symbol, str);
#else // kPluginInterfaceVersion < kAI12
char *str = gEngine->convertString(env, name, kMaxSymbolNameLength);
sAISymbol->GetSymbolPatternDisplayName(str);
sAISymbol->SetSymbolPatternBaseName(symbol, str);
delete str;
#endif // kPluginInterfaceVersion < kAI12
}
} EXCEPTION_CONVERT(env);
}
/*
* com.scriptographer.ai.Item getDefinition()
*/
JNIEXPORT jobject JNICALL Java_com_scriptographer_ai_Symbol_getDefinition(JNIEnv *env, jobject obj) {
try {
AIPatternHandle symbol = gEngine->getPatternHandle(env, obj);
AIArtHandle art = NULL;
sAISymbol->GetSymbolPatternArt(symbol, &art);
return gEngine->wrapArtHandle(env, art, gEngine->getDocumentHandle(env, obj));
} EXCEPTION_CONVERT(env);
return NULL;
}
/*
* void setDefinition(com.scriptographer.ai.Item item)
*/
JNIEXPORT void JNICALL Java_com_scriptographer_ai_Symbol_setDefinition(JNIEnv *env, jobject obj, jobject item) {
try {
AIPatternHandle symbol = gEngine->getPatternHandle(env, obj, true);
AIArtHandle art = gEngine->getArtHandle(env, item);
// Commit pending changes first
Item_commit(env, art);
// TODO: see what happens if symbol and art are not from the same document!
// consider adding a special case where this could work if it does not already (Using Item_copyTo?)
#if kPluginInterfaceVersion >= kAI15
// TODO: See if transformDefinationArt needs to be set to true to behave the same as CS4
sAISymbol->SetSymbolPatternArt(symbol, art, true);
#else // kPluginInterfaceVersion < kAI15
sAISymbol->SetSymbolPatternArt(symbol, art);
#endif // kPluginInterfaceVersion < kAI15
} EXCEPTION_CONVERT(env);
}
/*
* boolean isValid()
*/
JNIEXPORT jboolean JNICALL Java_com_scriptographer_ai_Symbol_isValid(JNIEnv *env, jobject obj) {
try {
AIPatternHandle symbol = gEngine->getPatternHandle(env, obj);
return sAISymbol->ValidateSymbolPattern(symbol);
} EXCEPTION_CONVERT(env);
return false;
}
/*
* boolean nativeRemove()
*/
JNIEXPORT jboolean JNICALL Java_com_scriptographer_ai_Symbol_nativeRemove(JNIEnv *env, jobject obj) {
try {
AIPatternHandle symbol = gEngine->getPatternHandle(env, obj, true);
return !sAISymbol->DeleteSymbolPattern(symbol);
} EXCEPTION_CONVERT(env);
return false;
}
/*
* boolean isListed()
*/
JNIEXPORT jboolean JNICALL Java_com_scriptographer_ai_Symbol_isListed(JNIEnv *env, jobject obj) {
try {
AIPatternHandle symbol = gEngine->getPatternHandle(env, obj);
return sAISymbol->IsSymbolPatternListed(symbol);
} EXCEPTION_CONVERT(env);
return false;
}
/*
* void setListed(boolean listed)
*/
JNIEXPORT void JNICALL Java_com_scriptographer_ai_Symbol_setListed(JNIEnv *env, jobject obj, jboolean listed) {
try {
AIPatternHandle symbol = gEngine->getPatternHandle(env, obj, true);
ASBoolean isListed = sAISymbol->IsSymbolPatternListed(symbol);
if (isListed && !listed) {
sAISymbol->UnlistSymbolPattern(symbol);
} else if (!isListed && listed) {
sAISymbol->MakeSymbolPatternListed(symbol);
}
} EXCEPTION_CONVERT(env);
}
/*
* boolean isSelected()
*/
JNIEXPORT jboolean JNICALL Java_com_scriptographer_ai_Symbol_isSelected(JNIEnv *env, jobject obj) {
try {
AIPatternHandle symbol = gEngine->getPatternHandle(env, obj);
return sAISymbolPalette->IsSymbolSelected(symbol);
} EXCEPTION_CONVERT(env);
return false;
}
/*
* void activate()
*/
JNIEXPORT void JNICALL Java_com_scriptographer_ai_Symbol_activate(JNIEnv *env, jobject obj) {
try {
AIPatternHandle symbol = gEngine->getPatternHandle(env, obj, true);
sAISymbolPalette->SetCurrentSymbol(symbol);
} EXCEPTION_CONVERT(env);
}
/*
* void setIndex(int index)
*/
JNIEXPORT void JNICALL Java_com_scriptographer_ai_Symbol_setIndex(JNIEnv *env, jobject obj, jint index) {
try {
AIPatternHandle symbol = gEngine->getPatternHandle(env, obj, true);
sAISymbol->MoveSymbolPatternInList(symbol, index);
} EXCEPTION_CONVERT(env);
}
|
e43b38ed068b2088a6f69cecf9b1de57297b837f | 4c4d4aa931c897e799efd893255be046af461b15 | /source/pawgui_dropdown.h | 7bfe493997c4170165560e7371749e5465996701 | [
"MIT"
] | permissive | pawbyte/pawgui | fe593586342051c9cde43deac3cd1ce11f430427 | 24e77f4ce40bd0e91f5f5edc27cc87ff5783d0ab | refs/heads/master | 2021-03-05T01:26:55.751739 | 2020-07-07T15:35:42 | 2020-07-07T15:35:42 | 245,880,351 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,192 | h | pawgui_dropdown.h | /*
pawgui_dropdown.h
PawByte Ambitious Working GUI(PAWGUI)
https://www.pawbyte.com/pawgui
Copyright (c) 2014-2020 Nathan Hurde, Chase Lee.
Copyright (c) 2014-2020 PawByte LLC.
Copyright (c) 2014-2020 PAWGUI contributors ( Contributors Page )
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-PAWGUI <https://www.pawbyte.com/pawgui>
*/
#ifndef PAWGUI_DROPDOWN_H
#define PAWGUI_DROPDOWN_H
#include "pawgui_base.h"
#include "pawgui_parsers.h"
#include "pawgui_context.h"
#include "../gpe/gpe_parser.h"
namespace pawgui
{
class widget_dropdown_menu: public widget_basic
{
private:
int widestOptionSpace;
int maxOptionsAllowed;
std::string dropdownName;
int opId;
bool isSelectable;
int selectedId;
std::string selectedName;
std::string selectedTag;
float selectedValue;
gpe::key_pair * selectedPair;
gpe::key_pair * dropDownParentPair;
bool isOpen;
bool justActivated;
bool showJustOptions;
public:
bool subMenuIsOpen;
gpe::color * barColor;
widget_dropdown_menu( std::string name = "", bool justOptions = false);
~widget_dropdown_menu();
std::string get_data();
void load_data(std::string dataString);
void remove_data(std::string dataString);
bool add_to_context_menu( popup_menu_option * cLevel, gpe::key_pair * cKey );
gpe::key_pair * add_menu_option(std::string optionName, std::string optionSubStr= "",float optionValue = 0, bool selectOption = false);
void clear_dropdown();
gpe::key_pair * find_option_id( int pairId );
gpe::key_pair * find_option_valie( float pairValue );
gpe::key_pair * find_selected_pair( gpe::key_pair * pairIn, std::string pairName, int pairId = -1);
gpe::key_pair * find_selected_pair_sub( gpe::key_pair * pairIn, std::string pairSubString );
std::string get_menu_option(int atNumb);
int get_menu_size();
std::string get_plain_string();
int get_selected_id();
std::string get_selected_tag();
std::string get_selected_name();
float get_selected_value();
std::string get_tag_from( std::string tagName, int tagId = -1);
bool just_activated();
void remove_option(std::string optionToRemove);
void reset_suboptions();
void set_id(int new_id);
void set_option_named( std::string newselectedOptionName );
void set_option_subvalue( std::string newselectedOptionName );
void set_option_value(float sValue);
void show_just_options(bool justOptions);
void process_self( gpe::shape_rect * view_space=NULL, gpe::shape_rect *cam=NULL);
void render_self( gpe::shape_rect * view_space=NULL, gpe::shape_rect * cam = NULL);
void set_name(std::string new_name);
};
}
#endif //PAWGUI_DROPDOWN_H
|
4dc9f526206021dccb753e82e444f91e15ed6642 | e952bf3211fd8e0c65d2733cc0b6384ea3223383 | /cbits/coin/CbcFixVariable.cpp | 30e5fbe813c772dc6dd96dd437f34ac7615c7728 | [
"MIT"
] | permissive | amosr/limp-cbc | fc63d8c8d80ec4df9bd9869296d928b03d059c26 | 3d6b9c580c529c0a7151aa7c758305bdf626f0af | refs/heads/master | 2021-01-18T20:20:10.387625 | 2020-02-01T22:02:33 | 2020-02-01T22:02:33 | 23,314,469 | 8 | 4 | MIT | 2020-02-01T21:43:26 | 2014-08-25T13:24:05 | C++ | UTF-8 | C++ | false | false | 6,039 | cpp | CbcFixVariable.cpp | // $Id: CbcFixVariable.cpp 1902 2013-04-10 16:58:16Z stefan $
// Copyright (C) 2002, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
// Edwin 11/10/2009-- carved out of CbcBranchActual
#if defined(_MSC_VER)
// Turn off compiler warning about long names
# pragma warning(disable:4786)
#endif
#include <cassert>
#include <cstdlib>
#include <cmath>
#include <cfloat>
//#define CBC_DEBUG
#include "CoinTypes.hpp"
#include "OsiSolverInterface.hpp"
#include "OsiSolverBranch.hpp"
#include "CbcModel.hpp"
#include "CbcMessage.hpp"
#include "CbcFixVariable.hpp"
#include "CbcBranchActual.hpp"
#include "CoinSort.hpp"
#include "CoinError.hpp"
//##############################################################################
// Default Constructor
CbcFixVariable::CbcFixVariable ()
: CbcConsequence(),
numberStates_(0),
states_(NULL),
startLower_(NULL),
startUpper_(NULL),
newBound_(NULL),
variable_(NULL)
{
}
// One useful Constructor
CbcFixVariable::CbcFixVariable (int numberStates, const int * states, const int * numberNewLower,
const int ** newLowerValue,
const int ** lowerColumn,
const int * numberNewUpper, const int ** newUpperValue,
const int ** upperColumn)
: CbcConsequence(),
states_(NULL),
startLower_(NULL),
startUpper_(NULL),
newBound_(NULL),
variable_(NULL)
{
// How much space
numberStates_ = numberStates;
if (numberStates_) {
states_ = new int[numberStates_];
memcpy(states_, states, numberStates_*sizeof(int));
int i;
int n = 0;
startLower_ = new int[numberStates_+1];
startUpper_ = new int[numberStates_+1];
startLower_[0] = 0;
//count
for (i = 0; i < numberStates_; i++) {
n += numberNewLower[i];
startUpper_[i] = n;
n += numberNewUpper[i];
startLower_[i+1] = n;
}
newBound_ = new double [n];
variable_ = new int [n];
n = 0;
for (i = 0; i < numberStates_; i++) {
int j;
int k;
const int * bound;
const int * variable;
k = numberNewLower[i];
bound = newLowerValue[i];
variable = lowerColumn[i];
for (j = 0; j < k; j++) {
newBound_[n] = bound[j];
variable_[n++] = variable[j];
}
k = numberNewUpper[i];
bound = newUpperValue[i];
variable = upperColumn[i];
for (j = 0; j < k; j++) {
newBound_[n] = bound[j];
variable_[n++] = variable[j];
}
}
}
}
// Copy constructor
CbcFixVariable::CbcFixVariable ( const CbcFixVariable & rhs)
: CbcConsequence(rhs)
{
numberStates_ = rhs.numberStates_;
states_ = NULL;
startLower_ = NULL;
startUpper_ = NULL;
newBound_ = NULL;
variable_ = NULL;
if (numberStates_) {
states_ = CoinCopyOfArray(rhs.states_, numberStates_);
startLower_ = CoinCopyOfArray(rhs.startLower_, numberStates_ + 1);
startUpper_ = CoinCopyOfArray(rhs.startUpper_, numberStates_ + 1);
int n = startLower_[numberStates_];
newBound_ = CoinCopyOfArray(rhs.newBound_, n);
variable_ = CoinCopyOfArray(rhs.variable_, n);
}
}
// Clone
CbcConsequence *
CbcFixVariable::clone() const
{
return new CbcFixVariable(*this);
}
// Assignment operator
CbcFixVariable &
CbcFixVariable::operator=( const CbcFixVariable & rhs)
{
if (this != &rhs) {
CbcConsequence::operator=(rhs);
delete [] states_;
delete [] startLower_;
delete [] startUpper_;
delete [] newBound_;
delete [] variable_;
states_ = NULL;
startLower_ = NULL;
startUpper_ = NULL;
newBound_ = NULL;
variable_ = NULL;
numberStates_ = rhs.numberStates_;
if (numberStates_) {
states_ = CoinCopyOfArray(rhs.states_, numberStates_);
startLower_ = CoinCopyOfArray(rhs.startLower_, numberStates_ + 1);
startUpper_ = CoinCopyOfArray(rhs.startUpper_, numberStates_ + 1);
int n = startLower_[numberStates_];
newBound_ = CoinCopyOfArray(rhs.newBound_, n);
variable_ = CoinCopyOfArray(rhs.variable_, n);
}
}
return *this;
}
// Destructor
CbcFixVariable::~CbcFixVariable ()
{
delete [] states_;
delete [] startLower_;
delete [] startUpper_;
delete [] newBound_;
delete [] variable_;
}
// Set up a startLower for a single member
void
CbcFixVariable::applyToSolver(OsiSolverInterface * solver, int state) const
{
assert (state == -9999 || state == 9999);
// Find state
int find;
for (find = 0; find < numberStates_; find++)
if (states_[find] == state)
break;
if (find == numberStates_)
return;
int i;
// Set new lower bounds
for (i = startLower_[find]; i < startUpper_[find]; i++) {
int iColumn = variable_[i];
double value = newBound_[i];
double oldValue = solver->getColLower()[iColumn];
//printf("for %d old lower bound %g, new %g",iColumn,oldValue,value);
solver->setColLower(iColumn, CoinMax(value, oldValue));
//printf(" => %g\n",solver->getColLower()[iColumn]);
}
// Set new upper bounds
for (i = startUpper_[find]; i < startLower_[find+1]; i++) {
int iColumn = variable_[i];
double value = newBound_[i];
double oldValue = solver->getColUpper()[iColumn];
//printf("for %d old upper bound %g, new %g",iColumn,oldValue,value);
solver->setColUpper(iColumn, CoinMin(value, oldValue));
//printf(" => %g\n",solver->getColUpper()[iColumn]);
}
}
|
902f2febf9bbe3897626cb6c4a1159f1165c2142 | 21ef516c20961b9a29148258552cf1072c93715c | /lib/Galois/lonestar/experimental/betweennesscentrality/HybridBFS.h | b5978ac228ecf9fdd5e6f9b4f1d5c3c5cb3cd672 | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | rovinski/LSOracle | b6426c3e45129faa4c41e0f569c323d9d78a9643 | 0a3f08fb9925e45fa912799d0ee96513c02005e1 | refs/heads/master | 2023-06-08T05:35:28.164760 | 2021-07-02T00:46:41 | 2021-07-02T00:46:41 | 382,189,413 | 0 | 0 | MIT | 2021-07-02T00:33:59 | 2021-07-02T00:33:59 | null | UTF-8 | C++ | false | false | 9,332 | h | HybridBFS.h | /*
* This file belongs to the Galois project, a C++ library for exploiting parallelism.
* The code is being released under the terms of the 3-Clause BSD License (a
* copy is located in LICENSE.txt at the top-level directory).
*
* Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
* SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
* PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
* DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
* RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
* shall University be liable for incidental, special, indirect, direct or
* consequential damages or loss of profits, interruption of business, or
* related expenses which may arise from use of Software or Documentation,
* including but not limited to those resulting from defects in Software and/or
* Documentation, or loss or inaccuracy of data of any kind.
*/
#ifndef APPS_BFS_HYBRIDBFS_H
#define APPS_BFS_HYBRIDBFS_H
#include "galois/Galois.h"
#include "galois/graphs/LCGraph.h"
template <typename NodeData, typename DistType>
struct HybridBFS {
using InnerGraph = typename galois::graphs::LC_CSR_Graph<NodeData, void>::
template with_no_lockable<true>::type ::template with_numa_alloc<
true>::type;
using Graph = typename galois::graphs::LC_InOut_Graph<InnerGraph>;
using GNode = typename Graph::GraphNode;
using WorkItem = std::pair<GNode, DistType>;
using NodeBag = galois::InsertBag<GNode>;
using WorkItemBag = galois::InsertBag<WorkItem>;
// used to track how much work was done in a round to determine if you do a
// push or a pull
galois::GAccumulator<size_t> count;
// 2 bags; a "current" bag and a "new" bag to flip between BSP phases
NodeBag bags[2];
/**
* Push operator. Takes an edge and does the update to the destination
* if the distance on the dest is higher than the distance we are using
* to update.
*
* @tparam I type of an Edge
*
* @param outEdge edge to consider/push out of
* @param graph graph object
* @param nextBag Nodes that are updated are added to this bag
* @param newDist Distance to push along edge
*/
template <typename I>
void bfsPushBulkSyncOperator(I outEdge, Graph& graph, NodeBag* nextBag,
DistType newDist) {
GNode dst = graph.getEdgeDst(outEdge);
NodeData& ddata = graph.getData(dst, galois::MethodFlag::UNPROTECTED);
DistType oldDist;
while (true) {
oldDist = ddata.dist;
if (oldDist <= newDist)
return;
if (__sync_bool_compare_and_swap(&ddata.dist, oldDist, newDist)) {
nextBag->push(dst);
this->count +=
1 + std::distance(
graph.edge_begin(dst, galois::MethodFlag::UNPROTECTED),
graph.edge_end(dst, galois::MethodFlag::UNPROTECTED));
break;
}
}
}
/**
* Does BFS push, asynchronous, using a worklist. Finishes the rest of BFS
* (i.e. not round by round).
*
* @param graph graph object to do BFS on
* @param asyncBag Bag of nodes that need to be processed
*/
void bfsPushAsync(Graph& graph, WorkItemBag& asyncBag) {
using namespace galois::worklists;
using BSWL = BulkSynchronous<PerSocketChunkLIFO<256>>;
// each thread processes one node + does pushes along its edges
galois::for_each(
galois::iterate(asyncBag),
[&](const WorkItem& item, auto& ctx) {
GNode n = item.first;
const DistType& newDist = item.second;
for (auto ii = graph.edge_begin(n, galois::MethodFlag::UNPROTECTED),
ei = graph.edge_end(n, galois::MethodFlag::UNPROTECTED);
ii != ei; ++ii) {
GNode dst = graph.getEdgeDst(ii);
NodeData& ddata =
graph.getData(dst, galois::MethodFlag::UNPROTECTED);
DistType oldDist;
while (true) {
oldDist = ddata.dist;
if (oldDist <= newDist)
return;
if (__sync_bool_compare_and_swap(&ddata.dist, oldDist, newDist)) {
ctx.push(WorkItem(dst, newDist + 1));
break;
}
}
}
},
galois::no_conflicts(), galois::loopname("bfsPushAsync"),
galois::steal(), galois::wl<BSWL>());
}
/**
* Pull style BFS. Nodes update themselves if distance to that node is
* equal to newDist
*
* @param graph Graph object
* @param nextBag object that will contain all nodes that updated themselves
* in this call
* @param newDist a node updates itself to this if it has an incoming edge
* from a source with newDist - 1 as its distance
*/
void bfsPullTopo(Graph& graph, NodeBag* nextBag, const DistType& newDist) {
galois::do_all(
galois::iterate(graph),
// Loop over in-edges: if the source node's dist + 1 is equivalent
// to the the current new dist, "pull" and update self with new dist
// (i.e. an edge exists to this node)
[&, outer = this](const GNode& n) {
NodeData& sdata = graph.getData(n, galois::MethodFlag::UNPROTECTED);
if (sdata.dist <= newDist)
return;
for (auto
ii = graph.in_edge_begin(n, galois::MethodFlag::UNPROTECTED),
ei = graph.in_edge_end(n, galois::MethodFlag::UNPROTECTED);
ii != ei; ++ii) {
GNode dst = graph.getInEdgeDst(ii);
NodeData& ddata =
graph.getData(dst, galois::MethodFlag::UNPROTECTED);
if (ddata.dist + 1 == newDist) {
sdata.dist = newDist;
nextBag->push(n);
outer->count +=
1 + std::distance(
graph.edge_begin(n, galois::MethodFlag::UNPROTECTED),
graph.edge_end(n, galois::MethodFlag::UNPROTECTED));
break;
}
}
},
galois::steal(), galois::loopname("bfsPullTopo"));
}
void operator()(Graph& graph, const GNode& source) {
int next = 0; // next node bag to process; flips between 0 and 1
DistType newDist = 1;
int numForward = 0; // number of push phases done
int numBackward = 0; // number of pull phases done
graph.getData(source).dist = 0;
// First round of BFS, i.e. only the original source
// Chooses between a push style call or a pull style call depending
// on number of edges on the source
// If number of out-edges is great, do a pull.
// Else do a push
if (std::distance(graph.edge_begin(source), graph.edge_end(source)) + 1 >
(long)graph.sizeEdges() / 20) {
bfsPullTopo(graph, &bags[next], newDist);
numBackward += 1;
} else {
galois::do_all(
galois::iterate(
graph.out_edges(source, galois::MethodFlag::UNPROTECTED).begin(),
graph.out_edges(source, galois::MethodFlag::UNPROTECTED).end()),
[&, outer = this](auto ii) {
outer->bfsPushBulkSyncOperator(ii, graph, &outer->bags[next],
newDist);
},
galois::steal(), galois::loopname("bfsPushBulkSync"));
numForward += 1;
}
// Handle the rest of the BFS propagation by processing updated nodes
// pushed to bags
while (!bags[next].empty()) {
// flip "old" and "new" node bags
int cur = next;
next = (cur + 1) & 1; // if 0, become 1, if 1, become 0
size_t nextSize = count.reduce();
count.reset();
newDist++;
if (nextSize > graph.sizeEdges() / 20) {
// Dense number of updates = do a pull
bfsPullTopo(graph, &bags[next], newDist);
numBackward += 1;
} else if (numForward < 10 && numBackward == 0) {
// if haven't done many push phases and backward phase count is 0,
// do push
galois::do_all(
galois::iterate(bags[cur]),
[&, outer = this](const GNode& n) {
for (auto ii = graph.edge_begin(n,
galois::MethodFlag::UNPROTECTED),
ei = graph.edge_end(n, galois::MethodFlag::UNPROTECTED);
ii != ei; ++ii) {
outer->bfsPushBulkSyncOperator(ii, graph, &outer->bags[next],
newDist);
}
},
galois::steal(), galois::loopname("bfsPushBulkSync"));
numForward += 1;
} else {
// ASYNC BFS
// create a work item bag based on what was updated last round
WorkItemBag asyncBag;
galois::do_all(galois::iterate(bags[cur]), [&](const GNode& n) {
asyncBag.push(WorkItem(n, newDist));
});
// do a push, asynchronous version (i.e. finish off the rest of
// BFS)
bfsPushAsync(graph, asyncBag);
break;
}
// bags[cur] becomes bags[next] next round
bags[cur].clear();
}
}
};
#endif
|
4a86e154bf20bd6b76de3c76061f6af73a708ea6 | 19662dc31e0320f5ee3df9dde467be9966c4c469 | /renderer3d.cpp | d6bc86c04dc4da4d3dad809776ed2667d45d760c | [] | no_license | steve9164/Assignment3 | 3763c9d05687699f356e16670f37a6455926b99a | 5ec5e319df971e24d92cbb2ad629a88b9827f4b9 | refs/heads/master | 2021-06-03T21:22:41.041984 | 2016-06-11T13:25:08 | 2016-06-11T13:25:08 | 59,877,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,488 | cpp | renderer3d.cpp | #include "renderer3d.h"
#include "config.h"
#include "renderer3deventhandlers.h"
#include <QGradient>
#include <QWidget>
#include <QDebug>
#include <algorithm>
#include <array>
#include <QDebug>
#include <QSurfaceFormat>
#include <QOpenGLFunctions_3_3_Core>
#include <QQuaternion>
// Use C++11 raw string literals for GLSL shader source code
static const char *vertexShaderSourceCore = R"(
#version 330
in vec4 vertex;
in vec3 position;
in float scale;
in vec4 vertexColor;
out vec4 fragmentColor;
uniform mat4 projMatrix;
uniform mat4 viewMatrix;
void main() {
gl_Position = projMatrix * viewMatrix * vec4(scale*vertex.xyz + position, 1);
fragmentColor = vertexColor;
}
)";
static const char *fragmentShaderSourceCore = R"(
#version 330
in vec4 fragmentColor;
out vec4 color;
void main() {
color = fragmentColor;
}
)";
struct Renderer3D::BodyRenderDetails
{
QVector3D position;
float scale;
QVector4D color;
};
Renderer3D::Renderer3D(QOpenGLWidget* widget)
: m_view(),
m_cameraVelocity(),
m_program(),
m_cubeIndices(QOpenGLBuffer::IndexBuffer),
m_widget(widget)
{
qDebug() << "Test";
qDebug() << initializeOpenGLFunctions();
m_program = new QOpenGLShaderProgram();
m_view.setToIdentity();
//m_view.translate(0.0f, 0.0f, -3.0f);
m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSourceCore);
m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSourceCore);
m_program->bindAttributeLocation("vertex", 0);
m_program->link();
m_program->bind();
m_vao.create();
QOpenGLVertexArrayObject::Binder vaoBinder(&m_vao);
std::array<QVector3D, 8> vertices{{{-1.0f,-1.0f,-1.0f}, {-1.0f,-1.0f,1.0f}, {-1.0f,1.0f,-1.0f}, {-1.0f,1.0f,1.0f}, {1.0f,-1.0f,-1.0f}, {1.0f,-1.0f,1.0f}, {1.0f,1.0f,-1.0f}, {1.0f,1.0f,1.0f}}};
std::array<GLushort, 16> vertexIndices{{2,0,6,4,5,0,1,2,3,6,7,5,3,1}};
// Setup our vertex buffer object.
m_cubeVertices.create();
m_cubeVertices.bind();
m_cubeVertices.allocate(vertices.data(), vertices.size() * sizeof(QVector3D));
m_cubeIndices.create();
m_cubeIndices.bind();
m_cubeIndices.allocate(vertexIndices.data(), vertexIndices.size() * sizeof(GLushort));
// Tell OpenGL programmable pipeline how to locate vertex position data
m_program->enableAttributeArray("vertex");
m_program->setAttributeBuffer("vertex", GL_FLOAT, 0, 3, sizeof(QVector3D));
// std::array<QVector3D, 4> locations{{{2.0f, 2.0f, 0.0f}, {2.0f, -2.0f, 0.0f}, {-2.0f, 2.0f, 0.0f}, {-2.0f, -2.0f, 0.0f}}};
m_cubeInstanceData.create();
m_cubeInstanceData.bind(); // All of the attributes below are in this vbo
// Compile time assertion that struct BodyRenderDetails is laid out as assumed
static_assert(sizeof(struct BodyRenderDetails) == 8*sizeof(float), "Renderer3D::BodyRenderDetails layout is not correct. Should be 3 floats | 1 float | 4 floats = 8 floats overall");
m_program->enableAttributeArray("position");
m_program->setAttributeBuffer("position", GL_FLOAT, 0, 3, sizeof(struct BodyRenderDetails));
glVertexAttribDivisor(m_program->attributeLocation("position"), 1);
m_program->enableAttributeArray("scale");
m_program->setAttributeBuffer("scale", GL_FLOAT, 3*sizeof(float), 1, sizeof(struct BodyRenderDetails));
glVertexAttribDivisor(m_program->attributeLocation("scale"), 1);
m_program->enableAttributeArray("vertexColor");
m_program->setAttributeBuffer("vertexColor", GL_FLOAT, 4*sizeof(float), 4, sizeof(struct BodyRenderDetails));
glVertexAttribDivisor(m_program->attributeLocation("vertexColor"), 1);
m_program->release();
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
}
Renderer3D::~Renderer3D()
{
m_cubeVertices.destroy();
m_cubeIndices.destroy();
}
std::shared_ptr<EventHandler> Renderer3D::buildEventChain()
{
std::shared_ptr<EventHandler> handler(new KeyEventHandler(*this));
handler->chain(std::shared_ptr<EventHandler>(new MouseWheelEventHandler(*this)));
return handler;
}
void Renderer3D::autoAdjustCamera(std::pair<QVector3D, QVector3D> boundingBox)
{
m_view.setToIdentity();
}
void Renderer3D::startRender(QWidget* widget)
{
// Clear previous frame's Body details
m_bodyRenderDetailsAccumulator.clear();
}
void Renderer3D::drawBody(const UniverseBody& body)
{
Config* config = Config::getInstance();
//get scaled position and radius
QVector3D pos = body.getPosition() / config->getDistanceScale();
double radius = body.getRadius() / config->getRadiusScale();
if(config->getUseLogRadius())
{
radius = std::log(body.getRadius() / config->getLogPointRadius());
}
double r,g,b,a;
body.getColor().getRgbF(&r,&g,&b,&a);
// qDebug() << pos << radius << QVector4D(r,g,b,a);
// qDebug() << "Radius:" << body.getRadius() << config->getRadiusScale() << config->getUseLogRadius();
m_bodyRenderDetailsAccumulator.push_back({pos, static_cast<float>(radius), QVector4D(r,g,b,a)});
}
void Renderer3D::drawZodiac(const Zodiac& zodiac)
{
}
void Renderer3D::drawLabel(const UniverseBody& body)
{
}
void Renderer3D::finishRender()
{
// m_view.translate(-m_cameraVelocity);
// V[n+1] = Rotation[inv] * V[n]
// Qt can't invert a matrix, so invert a quaternion
QMatrix4x4 rot;
rot.rotate(1.0f, QVector3D(-m_cameraVelocity.y(), m_cameraVelocity.x(), 0.0f));
m_view = rot * m_view;
m_proj.setToIdentity();
m_proj.perspective(45.0f, (GLfloat)m_widget->width() / m_widget->height(), 0.01f, 1000.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Bind m_vao and release when vaoBinder goes out of scope
QOpenGLVertexArrayObject::Binder vaoBinder(&m_vao);
// Test m_bodyRenderDetailsAccumulator.data():
m_cubeInstanceData.bind();
m_cubeInstanceData.allocate(m_bodyRenderDetailsAccumulator.data(), m_bodyRenderDetailsAccumulator.size() * sizeof(struct BodyRenderDetails));
m_program->bind();
m_program->setUniformValue("projMatrix", m_proj);
m_program->setUniformValue("viewMatrix", m_view);
static unsigned int counter = 0;
//qDebug() << "Rendering scene:" << counter++;
// Draw cube geometry using indices from VBO 1
glDrawElementsInstanced(GL_TRIANGLE_STRIP, 16, GL_UNSIGNED_SHORT, 0, m_bodyRenderDetailsAccumulator.size());
m_program->release();
}
|
b3b8001690363976aa4ec05fd4d4f955f7eba943 | 06ede1e41a43795046c354c3a5f86f7abfd0a2ee | /old_src/common/cso.cpp | a13cc3452f356fa9119c62ded2304e60d9bb7838 | [] | no_license | elkebir-group/CSO | 2b5455ebf9e6c86ceedfc5a4060dc79230f18e1f | 79e6777d421dfce942b62870e7bdc8ad4aebcb15 | refs/heads/master | 2020-03-23T01:08:24.968573 | 2014-06-15T20:17:56 | 2014-06-15T20:17:56 | 140,902,458 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,533 | cpp | cso.cpp | /*
* cso.cpp
*
* Created on: 18-feb-2009
* Author: M. El-Kebir
*/
#include "cso.h"
const Gamete g_InvalidGamete = {INVALID_GAMETE, 0};
void toBitstring(int val, int n, char* buf)
{
/*
* Example:
* '1000' = 8
* '0001' = 1
*/
for (int i = 0; i < n; i++)
{
buf[n - i - 1] = (val & 1) ? '1' : '0';
val >>= 1;
}
buf[n] = '\0';
}
int fromBitstring(int n, const char* buf)
{
/*
* Example:
* '1000' = 8
* '0001' = 1
*/
int val = 0;
for (int i = 0; i < n; i++)
{
if (buf[n - i - 1] == '1')
{
val |= (1 << i);
}
}
return val;
}
int numberOfDifferences(int n, int val1, int val2)
{
int res = 0;
for (int i = 0; i < n; i++)
{
if ((val1 & 1) != (val2 & 1)) res++;
val1 >>= 1;
val2 >>= 1;
}
return res;
}
/*
* Index 0 = LSB
*/
int chromosomeCompare(int n, int val1, int val2,
std::vector<int>& homyzygousLoci, std::vector<int>& heterozygousLoci)
{
homyzygousLoci.clear();
heterozygousLoci.clear();
int base = 0;
for (int i = 0; i < n; i++)
{
if (GET_BIT(n, val1, i) == GET_BIT(n, val2, i)) // homozygous
{
base |= GET_BIT(n, val1, i) << (n - i - 1);
homyzygousLoci.push_back(i);
}
else // heterozygous
{
heterozygousLoci.push_back(i);
}
}
// base is the case where all bits at heterozygous loci are set to 0
return base;
}
int randInt(int n)
{
return (int) (n * (rand() / ((double)RAND_MAX + 1)));
}
int randChromosome(int nLoci)
{
int res = 0;
for (int i = 0; i < nLoci; i++)
{
if (randDouble() < 0.5)
res |= 1 << i;
}
return res;
}
double randDouble()
{
return rand() / ((double)RAND_MAX + 1);
}
unsigned long probToPop(double p, double gamma)
{
if ((1 - p) <= (2 * DBL_EPSILON)) return 1;
return (unsigned long) ceil(log(1 - gamma) / log(1 - p));
}
int largestSubGroupSize(int nLoci, int val, int target)
{
int largestGroupSize = 0;
int currentGroupSize = 0;
for (int i = 0; i < nLoci; i++)
{
if (GET_BIT(nLoci, val, i) == GET_BIT(nLoci, target, i))
{
currentGroupSize++;
if (currentGroupSize > largestGroupSize)
{
largestGroupSize = currentGroupSize;
}
}
else
{
currentGroupSize = 0;
}
}
return largestGroupSize;
}
bool gamete_eq(const Gamete& gamete1, const Gamete& gamete2)
{
return gamete1._c == gamete2._c;
}
bool gamete_lt(const Gamete& gamete1, const Gamete& gamete2)
{
return gamete1._c < gamete2._c;
}
|
f204ce9bddb025ed2860942775a8357cc7956784 | ca0e7bcfed6672931e5d0ff549de3e4f525142f8 | /shared/OpenglCodecCommon/astc-codec.h | e15fe47d977463c5bbffedc1d05b961a63da37eb | [
"Apache-2.0"
] | permissive | xiaohua2018/goldfishOpengl | 070686de9ab178cf2e37325245a8eca0497a0f65 | 03aafeef950afd4375d8158dab6fd4fa7206169c | refs/heads/master | 2023-06-28T15:55:34.567184 | 2021-08-04T20:23:55 | 2021-08-04T20:23:55 | 392,877,526 | 0 | 0 | NOASSERTION | 2021-08-05T02:37:17 | 2021-08-05T02:19:43 | C++ | UTF-8 | C++ | false | false | 1,060 | h | astc-codec.h | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ASTC_CODEC_ASTC_CODEC_H_
#define ASTC_CODEC_ASTC_CODEC_H_
namespace astc_codec {
// These are the valid ASTC footprints according to the specification in
// Section C.2.7.
enum FootprintType {
k4x4,
k5x4,
k5x5,
k6x5,
k6x6,
k8x5,
k8x6,
k10x5,
k10x6,
k8x8,
k10x8,
k10x10,
k12x10,
k12x12,
kCount
};
struct AstcFootprint {
AstcFootprint(int width, int height);
};
} // namespace astc_codec
#endif // ASTC_CODEC_ASTC_CODEC_H_
|
68668477c088b1c8f6335fa5f51c12688ae2a63a | 2eaf198cab76506045fcc4d312abd12afc9fc713 | /src/ripple/app/tx/impl/applySteps.cpp | fdb84c271a05935bd6eb03b60f419511a3c76cde | [
"LicenseRef-scancode-free-unknown",
"ISC"
] | permissive | XRPLF/rippled | 26c378a72f65dde2ee9427a8a106505a60a3303d | 300b7e078a4bc511f30b74509d416e5081ec3650 | refs/heads/develop | 2023-08-31T00:07:03.935167 | 2023-08-21T23:22:59 | 2023-08-21T23:23:06 | 2,724,167 | 267 | 126 | ISC | 2023-09-14T21:57:05 | 2011-11-07T04:40:15 | C++ | UTF-8 | C++ | false | false | 20,942 | cpp | applySteps.cpp | //------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <ripple/app/tx/applySteps.h>
#include <ripple/app/tx/impl/AMMBid.h>
#include <ripple/app/tx/impl/AMMCreate.h>
#include <ripple/app/tx/impl/AMMDelete.h>
#include <ripple/app/tx/impl/AMMDeposit.h>
#include <ripple/app/tx/impl/AMMVote.h>
#include <ripple/app/tx/impl/AMMWithdraw.h>
#include <ripple/app/tx/impl/ApplyContext.h>
#include <ripple/app/tx/impl/CancelCheck.h>
#include <ripple/app/tx/impl/CancelOffer.h>
#include <ripple/app/tx/impl/CashCheck.h>
#include <ripple/app/tx/impl/Change.h>
#include <ripple/app/tx/impl/Clawback.h>
#include <ripple/app/tx/impl/CreateCheck.h>
#include <ripple/app/tx/impl/CreateOffer.h>
#include <ripple/app/tx/impl/CreateTicket.h>
#include <ripple/app/tx/impl/DeleteAccount.h>
#include <ripple/app/tx/impl/DepositPreauth.h>
#include <ripple/app/tx/impl/Escrow.h>
#include <ripple/app/tx/impl/NFTokenAcceptOffer.h>
#include <ripple/app/tx/impl/NFTokenBurn.h>
#include <ripple/app/tx/impl/NFTokenCancelOffer.h>
#include <ripple/app/tx/impl/NFTokenCreateOffer.h>
#include <ripple/app/tx/impl/NFTokenMint.h>
#include <ripple/app/tx/impl/PayChan.h>
#include <ripple/app/tx/impl/Payment.h>
#include <ripple/app/tx/impl/SetAccount.h>
#include <ripple/app/tx/impl/SetRegularKey.h>
#include <ripple/app/tx/impl/SetSignerList.h>
#include <ripple/app/tx/impl/SetTrust.h>
namespace ripple {
// Templates so preflight does the right thing with T::ConsequencesFactory.
//
// This could be done more easily using if constexpr, but Visual Studio
// 2017 doesn't handle if constexpr correctly. So once we're no longer
// building with Visual Studio 2017 we can consider replacing the four
// templates with a single template function that uses if constexpr.
//
// For Transactor::Normal
template <
class T,
std::enable_if_t<T::ConsequencesFactory == Transactor::Normal, int> = 0>
TxConsequences
consequences_helper(PreflightContext const& ctx)
{
return TxConsequences(ctx.tx);
};
// For Transactor::Blocker
template <
class T,
std::enable_if_t<T::ConsequencesFactory == Transactor::Blocker, int> = 0>
TxConsequences
consequences_helper(PreflightContext const& ctx)
{
return TxConsequences(ctx.tx, TxConsequences::blocker);
};
// For Transactor::Custom
template <
class T,
std::enable_if_t<T::ConsequencesFactory == Transactor::Custom, int> = 0>
TxConsequences
consequences_helper(PreflightContext const& ctx)
{
return T::makeTxConsequences(ctx);
};
template <class T>
std::pair<NotTEC, TxConsequences>
invoke_preflight_helper(PreflightContext const& ctx)
{
auto const tec = T::preflight(ctx);
return {
tec,
isTesSuccess(tec) ? consequences_helper<T>(ctx) : TxConsequences{tec}};
}
static std::pair<NotTEC, TxConsequences>
invoke_preflight(PreflightContext const& ctx)
{
switch (ctx.tx.getTxnType())
{
case ttACCOUNT_DELETE:
return invoke_preflight_helper<DeleteAccount>(ctx);
case ttACCOUNT_SET:
return invoke_preflight_helper<SetAccount>(ctx);
case ttCHECK_CANCEL:
return invoke_preflight_helper<CancelCheck>(ctx);
case ttCHECK_CASH:
return invoke_preflight_helper<CashCheck>(ctx);
case ttCHECK_CREATE:
return invoke_preflight_helper<CreateCheck>(ctx);
case ttDEPOSIT_PREAUTH:
return invoke_preflight_helper<DepositPreauth>(ctx);
case ttOFFER_CANCEL:
return invoke_preflight_helper<CancelOffer>(ctx);
case ttOFFER_CREATE:
return invoke_preflight_helper<CreateOffer>(ctx);
case ttESCROW_CREATE:
return invoke_preflight_helper<EscrowCreate>(ctx);
case ttESCROW_FINISH:
return invoke_preflight_helper<EscrowFinish>(ctx);
case ttESCROW_CANCEL:
return invoke_preflight_helper<EscrowCancel>(ctx);
case ttPAYCHAN_CLAIM:
return invoke_preflight_helper<PayChanClaim>(ctx);
case ttPAYCHAN_CREATE:
return invoke_preflight_helper<PayChanCreate>(ctx);
case ttPAYCHAN_FUND:
return invoke_preflight_helper<PayChanFund>(ctx);
case ttPAYMENT:
return invoke_preflight_helper<Payment>(ctx);
case ttREGULAR_KEY_SET:
return invoke_preflight_helper<SetRegularKey>(ctx);
case ttSIGNER_LIST_SET:
return invoke_preflight_helper<SetSignerList>(ctx);
case ttTICKET_CREATE:
return invoke_preflight_helper<CreateTicket>(ctx);
case ttTRUST_SET:
return invoke_preflight_helper<SetTrust>(ctx);
case ttAMENDMENT:
case ttFEE:
case ttUNL_MODIFY:
return invoke_preflight_helper<Change>(ctx);
case ttNFTOKEN_MINT:
return invoke_preflight_helper<NFTokenMint>(ctx);
case ttNFTOKEN_BURN:
return invoke_preflight_helper<NFTokenBurn>(ctx);
case ttNFTOKEN_CREATE_OFFER:
return invoke_preflight_helper<NFTokenCreateOffer>(ctx);
case ttNFTOKEN_CANCEL_OFFER:
return invoke_preflight_helper<NFTokenCancelOffer>(ctx);
case ttNFTOKEN_ACCEPT_OFFER:
return invoke_preflight_helper<NFTokenAcceptOffer>(ctx);
case ttCLAWBACK:
return invoke_preflight_helper<Clawback>(ctx);
case ttAMM_CREATE:
return invoke_preflight_helper<AMMCreate>(ctx);
case ttAMM_DEPOSIT:
return invoke_preflight_helper<AMMDeposit>(ctx);
case ttAMM_WITHDRAW:
return invoke_preflight_helper<AMMWithdraw>(ctx);
case ttAMM_VOTE:
return invoke_preflight_helper<AMMVote>(ctx);
case ttAMM_BID:
return invoke_preflight_helper<AMMBid>(ctx);
case ttAMM_DELETE:
return invoke_preflight_helper<AMMDelete>(ctx);
default:
assert(false);
return {temUNKNOWN, TxConsequences{temUNKNOWN}};
}
}
/* invoke_preclaim<T> uses name hiding to accomplish
compile-time polymorphism of (presumably) static
class functions for Transactor and derived classes.
*/
template <class T>
static TER
invoke_preclaim(PreclaimContext const& ctx)
{
// If the transactor requires a valid account and the transaction doesn't
// list one, preflight will have already a flagged a failure.
auto const id = ctx.tx.getAccountID(sfAccount);
if (id != beast::zero)
{
TER result = T::checkSeqProxy(ctx.view, ctx.tx, ctx.j);
if (result != tesSUCCESS)
return result;
result = T::checkPriorTxAndLastLedger(ctx);
if (result != tesSUCCESS)
return result;
result = T::checkFee(ctx, calculateBaseFee(ctx.view, ctx.tx));
if (result != tesSUCCESS)
return result;
result = T::checkSign(ctx);
if (result != tesSUCCESS)
return result;
}
return T::preclaim(ctx);
}
static TER
invoke_preclaim(PreclaimContext const& ctx)
{
switch (ctx.tx.getTxnType())
{
case ttACCOUNT_DELETE:
return invoke_preclaim<DeleteAccount>(ctx);
case ttACCOUNT_SET:
return invoke_preclaim<SetAccount>(ctx);
case ttCHECK_CANCEL:
return invoke_preclaim<CancelCheck>(ctx);
case ttCHECK_CASH:
return invoke_preclaim<CashCheck>(ctx);
case ttCHECK_CREATE:
return invoke_preclaim<CreateCheck>(ctx);
case ttDEPOSIT_PREAUTH:
return invoke_preclaim<DepositPreauth>(ctx);
case ttOFFER_CANCEL:
return invoke_preclaim<CancelOffer>(ctx);
case ttOFFER_CREATE:
return invoke_preclaim<CreateOffer>(ctx);
case ttESCROW_CREATE:
return invoke_preclaim<EscrowCreate>(ctx);
case ttESCROW_FINISH:
return invoke_preclaim<EscrowFinish>(ctx);
case ttESCROW_CANCEL:
return invoke_preclaim<EscrowCancel>(ctx);
case ttPAYCHAN_CLAIM:
return invoke_preclaim<PayChanClaim>(ctx);
case ttPAYCHAN_CREATE:
return invoke_preclaim<PayChanCreate>(ctx);
case ttPAYCHAN_FUND:
return invoke_preclaim<PayChanFund>(ctx);
case ttPAYMENT:
return invoke_preclaim<Payment>(ctx);
case ttREGULAR_KEY_SET:
return invoke_preclaim<SetRegularKey>(ctx);
case ttSIGNER_LIST_SET:
return invoke_preclaim<SetSignerList>(ctx);
case ttTICKET_CREATE:
return invoke_preclaim<CreateTicket>(ctx);
case ttTRUST_SET:
return invoke_preclaim<SetTrust>(ctx);
case ttAMENDMENT:
case ttFEE:
case ttUNL_MODIFY:
return invoke_preclaim<Change>(ctx);
case ttNFTOKEN_MINT:
return invoke_preclaim<NFTokenMint>(ctx);
case ttNFTOKEN_BURN:
return invoke_preclaim<NFTokenBurn>(ctx);
case ttNFTOKEN_CREATE_OFFER:
return invoke_preclaim<NFTokenCreateOffer>(ctx);
case ttNFTOKEN_CANCEL_OFFER:
return invoke_preclaim<NFTokenCancelOffer>(ctx);
case ttNFTOKEN_ACCEPT_OFFER:
return invoke_preclaim<NFTokenAcceptOffer>(ctx);
case ttCLAWBACK:
return invoke_preclaim<Clawback>(ctx);
case ttAMM_CREATE:
return invoke_preclaim<AMMCreate>(ctx);
case ttAMM_DEPOSIT:
return invoke_preclaim<AMMDeposit>(ctx);
case ttAMM_WITHDRAW:
return invoke_preclaim<AMMWithdraw>(ctx);
case ttAMM_VOTE:
return invoke_preclaim<AMMVote>(ctx);
case ttAMM_BID:
return invoke_preclaim<AMMBid>(ctx);
case ttAMM_DELETE:
return invoke_preclaim<AMMDelete>(ctx);
default:
assert(false);
return temUNKNOWN;
}
}
static XRPAmount
invoke_calculateBaseFee(ReadView const& view, STTx const& tx)
{
switch (tx.getTxnType())
{
case ttACCOUNT_DELETE:
return DeleteAccount::calculateBaseFee(view, tx);
case ttACCOUNT_SET:
return SetAccount::calculateBaseFee(view, tx);
case ttCHECK_CANCEL:
return CancelCheck::calculateBaseFee(view, tx);
case ttCHECK_CASH:
return CashCheck::calculateBaseFee(view, tx);
case ttCHECK_CREATE:
return CreateCheck::calculateBaseFee(view, tx);
case ttDEPOSIT_PREAUTH:
return DepositPreauth::calculateBaseFee(view, tx);
case ttOFFER_CANCEL:
return CancelOffer::calculateBaseFee(view, tx);
case ttOFFER_CREATE:
return CreateOffer::calculateBaseFee(view, tx);
case ttESCROW_CREATE:
return EscrowCreate::calculateBaseFee(view, tx);
case ttESCROW_FINISH:
return EscrowFinish::calculateBaseFee(view, tx);
case ttESCROW_CANCEL:
return EscrowCancel::calculateBaseFee(view, tx);
case ttPAYCHAN_CLAIM:
return PayChanClaim::calculateBaseFee(view, tx);
case ttPAYCHAN_CREATE:
return PayChanCreate::calculateBaseFee(view, tx);
case ttPAYCHAN_FUND:
return PayChanFund::calculateBaseFee(view, tx);
case ttPAYMENT:
return Payment::calculateBaseFee(view, tx);
case ttREGULAR_KEY_SET:
return SetRegularKey::calculateBaseFee(view, tx);
case ttSIGNER_LIST_SET:
return SetSignerList::calculateBaseFee(view, tx);
case ttTICKET_CREATE:
return CreateTicket::calculateBaseFee(view, tx);
case ttTRUST_SET:
return SetTrust::calculateBaseFee(view, tx);
case ttAMENDMENT:
case ttFEE:
case ttUNL_MODIFY:
return Change::calculateBaseFee(view, tx);
case ttNFTOKEN_MINT:
return NFTokenMint::calculateBaseFee(view, tx);
case ttNFTOKEN_BURN:
return NFTokenBurn::calculateBaseFee(view, tx);
case ttNFTOKEN_CREATE_OFFER:
return NFTokenCreateOffer::calculateBaseFee(view, tx);
case ttNFTOKEN_CANCEL_OFFER:
return NFTokenCancelOffer::calculateBaseFee(view, tx);
case ttNFTOKEN_ACCEPT_OFFER:
return NFTokenAcceptOffer::calculateBaseFee(view, tx);
case ttCLAWBACK:
return Clawback::calculateBaseFee(view, tx);
case ttAMM_CREATE:
return AMMCreate::calculateBaseFee(view, tx);
case ttAMM_DEPOSIT:
return AMMDeposit::calculateBaseFee(view, tx);
case ttAMM_WITHDRAW:
return AMMWithdraw::calculateBaseFee(view, tx);
case ttAMM_VOTE:
return AMMVote::calculateBaseFee(view, tx);
case ttAMM_BID:
return AMMBid::calculateBaseFee(view, tx);
case ttAMM_DELETE:
return AMMDelete::calculateBaseFee(view, tx);
default:
assert(false);
return XRPAmount{0};
}
}
TxConsequences::TxConsequences(NotTEC pfresult)
: isBlocker_(false)
, fee_(beast::zero)
, potentialSpend_(beast::zero)
, seqProx_(SeqProxy::sequence(0))
, sequencesConsumed_(0)
{
assert(!isTesSuccess(pfresult));
}
TxConsequences::TxConsequences(STTx const& tx)
: isBlocker_(false)
, fee_(
tx[sfFee].native() && !tx[sfFee].negative() ? tx[sfFee].xrp()
: beast::zero)
, potentialSpend_(beast::zero)
, seqProx_(tx.getSeqProxy())
, sequencesConsumed_(tx.getSeqProxy().isSeq() ? 1 : 0)
{
}
TxConsequences::TxConsequences(STTx const& tx, Category category)
: TxConsequences(tx)
{
isBlocker_ = (category == blocker);
}
TxConsequences::TxConsequences(STTx const& tx, XRPAmount potentialSpend)
: TxConsequences(tx)
{
potentialSpend_ = potentialSpend;
}
TxConsequences::TxConsequences(STTx const& tx, std::uint32_t sequencesConsumed)
: TxConsequences(tx)
{
sequencesConsumed_ = sequencesConsumed;
}
static std::pair<TER, bool>
invoke_apply(ApplyContext& ctx)
{
switch (ctx.tx.getTxnType())
{
case ttACCOUNT_DELETE: {
DeleteAccount p(ctx);
return p();
}
case ttACCOUNT_SET: {
SetAccount p(ctx);
return p();
}
case ttCHECK_CANCEL: {
CancelCheck p(ctx);
return p();
}
case ttCHECK_CASH: {
CashCheck p(ctx);
return p();
}
case ttCHECK_CREATE: {
CreateCheck p(ctx);
return p();
}
case ttDEPOSIT_PREAUTH: {
DepositPreauth p(ctx);
return p();
}
case ttOFFER_CANCEL: {
CancelOffer p(ctx);
return p();
}
case ttOFFER_CREATE: {
CreateOffer p(ctx);
return p();
}
case ttESCROW_CREATE: {
EscrowCreate p(ctx);
return p();
}
case ttESCROW_FINISH: {
EscrowFinish p(ctx);
return p();
}
case ttESCROW_CANCEL: {
EscrowCancel p(ctx);
return p();
}
case ttPAYCHAN_CLAIM: {
PayChanClaim p(ctx);
return p();
}
case ttPAYCHAN_CREATE: {
PayChanCreate p(ctx);
return p();
}
case ttPAYCHAN_FUND: {
PayChanFund p(ctx);
return p();
}
case ttPAYMENT: {
Payment p(ctx);
return p();
}
case ttREGULAR_KEY_SET: {
SetRegularKey p(ctx);
return p();
}
case ttSIGNER_LIST_SET: {
SetSignerList p(ctx);
return p();
}
case ttTICKET_CREATE: {
CreateTicket p(ctx);
return p();
}
case ttTRUST_SET: {
SetTrust p(ctx);
return p();
}
case ttAMENDMENT:
case ttFEE:
case ttUNL_MODIFY: {
Change p(ctx);
return p();
}
case ttNFTOKEN_MINT: {
NFTokenMint p(ctx);
return p();
}
case ttNFTOKEN_BURN: {
NFTokenBurn p(ctx);
return p();
}
case ttNFTOKEN_CREATE_OFFER: {
NFTokenCreateOffer p(ctx);
return p();
}
case ttNFTOKEN_CANCEL_OFFER: {
NFTokenCancelOffer p(ctx);
return p();
}
case ttNFTOKEN_ACCEPT_OFFER: {
NFTokenAcceptOffer p(ctx);
return p();
}
case ttCLAWBACK: {
Clawback p(ctx);
return p();
}
case ttAMM_CREATE: {
AMMCreate p(ctx);
return p();
}
case ttAMM_DEPOSIT: {
AMMDeposit p(ctx);
return p();
}
case ttAMM_WITHDRAW: {
AMMWithdraw p(ctx);
return p();
}
case ttAMM_VOTE: {
AMMVote p(ctx);
return p();
}
case ttAMM_BID: {
AMMBid p(ctx);
return p();
}
case ttAMM_DELETE: {
AMMDelete p(ctx);
return p();
}
default:
assert(false);
return {temUNKNOWN, false};
}
}
PreflightResult
preflight(
Application& app,
Rules const& rules,
STTx const& tx,
ApplyFlags flags,
beast::Journal j)
{
PreflightContext const pfctx(app, tx, rules, flags, j);
try
{
return {pfctx, invoke_preflight(pfctx)};
}
catch (std::exception const& e)
{
JLOG(j.fatal()) << "apply: " << e.what();
return {pfctx, {tefEXCEPTION, TxConsequences{tx}}};
}
}
PreclaimResult
preclaim(
PreflightResult const& preflightResult,
Application& app,
OpenView const& view)
{
std::optional<PreclaimContext const> ctx;
if (preflightResult.rules != view.rules())
{
auto secondFlight = preflight(
app,
view.rules(),
preflightResult.tx,
preflightResult.flags,
preflightResult.j);
ctx.emplace(
app,
view,
secondFlight.ter,
secondFlight.tx,
secondFlight.flags,
secondFlight.j);
}
else
{
ctx.emplace(
app,
view,
preflightResult.ter,
preflightResult.tx,
preflightResult.flags,
preflightResult.j);
}
try
{
if (ctx->preflightResult != tesSUCCESS)
return {*ctx, ctx->preflightResult};
return {*ctx, invoke_preclaim(*ctx)};
}
catch (std::exception const& e)
{
JLOG(ctx->j.fatal()) << "apply: " << e.what();
return {*ctx, tefEXCEPTION};
}
}
XRPAmount
calculateBaseFee(ReadView const& view, STTx const& tx)
{
return invoke_calculateBaseFee(view, tx);
}
XRPAmount
calculateDefaultBaseFee(ReadView const& view, STTx const& tx)
{
return Transactor::calculateBaseFee(view, tx);
}
std::pair<TER, bool>
doApply(PreclaimResult const& preclaimResult, Application& app, OpenView& view)
{
if (preclaimResult.view.seq() != view.seq())
{
// Logic error from the caller. Don't have enough
// info to recover.
return {tefEXCEPTION, false};
}
try
{
if (!preclaimResult.likelyToClaimFee)
return {preclaimResult.ter, false};
ApplyContext ctx(
app,
view,
preclaimResult.tx,
preclaimResult.ter,
calculateBaseFee(view, preclaimResult.tx),
preclaimResult.flags,
preclaimResult.j);
return invoke_apply(ctx);
}
catch (std::exception const& e)
{
JLOG(preclaimResult.j.fatal()) << "apply: " << e.what();
return {tefEXCEPTION, false};
}
}
} // namespace ripple
|
255fa09540a2764fe20360b04022e02b8cf3c835 | 63f3f110472c457db862d625b20512eb6dfc10fe | /example/async_client_example/async_client_example.cpp | ebd1b648886eafb2321e7e1f68a11c73d059882f | [] | no_license | eagle518/rest_rpc | 00fbf04367530b706d53812e2742abbeb31e2058 | 0645ae4bdc7f87e5a9d35994a81d3424e301b918 | refs/heads/master | 2021-01-18T00:00:50.168516 | 2016-09-10T03:07:50 | 2016-09-10T03:07:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 932 | cpp | async_client_example.cpp | #include <rest_rpc/rpc.hpp>
namespace client
{
TIMAX_DEFINE_PROTOCOL(add, int(int, int));
TIMAX_DEFINE_PROTOCOL(sub_add, int(int, int));
TIMAX_DEFINE_PROTOCOL(foo, void(std::string, double));
}
int main()
{
using client_type = timax::rpc::async_client<timax::rpc::msgpack_codec>;
// create the client
auto client = std::make_shared<client_type>();
// get the server endpoint
auto endpoint = timax::rpc::get_tcp_endpoint("127.0.0.1", 8000);
// call an rpc
client->call(endpoint, client::add, 100, 200.0).when_ok([](int r)
{
// process success
std::cout << r << std::endl;
}).when_error([](timax::rpc::client_error const& error)
{
// process error
if (error.get_code() == timax::rpc::error_code::FAIL)
std::cout << error.get_message() << std::endl;
});
// call in synchronize style
auto task = client->call(endpoint, client::add, 400.0, 2);
auto result = task.get();
std::getchar();
return 0;
} |
f4d31642968eec387ed4447c2f2eb4f50e604256 | c5875b818ed25d9ef1c8c52559111da4eeb03f18 | /roboime-firmware-NewBoard/inc/network/ip_stack.h | 0c568026e5c87507e97bd7235b68792fc15acaf8 | [] | no_license | joaogocm/RoboIME-Firmware-LARC2018 | f61e1e77ae0c35689d50c4d104e24dc2b0e2c5ac | 0ef0005173d9dda51dee17c2e6c64a8c364ba1f6 | refs/heads/master | 2020-04-28T01:28:37.132758 | 2019-10-26T05:17:40 | 2019-10-26T05:17:40 | 174,858,686 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 406 | h | ip_stack.h | #pragma once
#include <inttypes.h>
#include <lwip/ip_addr.h>
#include <network/rndisif.h>
class IP_STACK{
public:
IP_STACK();
void Timer(uint32_t LocalTime);
uint16_t InputBuffer(uint8_t *buffer, uint16_t len);
uint16_t GetData(uint8_t *buffer, uint16_t len);
protected:
struct netif rndisif;
struct netif netairif;
ip_addr_t ip_client;
ip_addr_t ip_radio;
ip_addr_t ip_msk;
ip_addr_t ip_gw;
};
|
d02c2b43cec2e772c11050196508d1fe2437f197 | e1461fb6193246a63517af943f6dcd592cd31e21 | /core-tests/src/core/log.cpp | 40ef7ecaeab799d098d5dde4055ed71b56d33d1a | [
"Apache-2.0"
] | permissive | zyh94946/swoole-src | ec6092f113391d2d488f62771f9fd3214d05c85a | 327b20eb83c2113ec835cb154517dc4ec0deb539 | refs/heads/master | 2022-07-22T09:12:29.577205 | 2020-05-09T03:16:03 | 2020-05-09T03:16:03 | 262,814,172 | 0 | 0 | Apache-2.0 | 2020-05-10T15:13:20 | 2020-05-10T15:13:19 | null | UTF-8 | C++ | false | false | 1,705 | cpp | log.cpp | #include "tests.h"
#include <regex>
const char* file = "/tmp/swoole_log_test.log";
TEST(log, level)
{
swLog_reset();
swLog_set_level(SW_LOG_NOTICE);
swLog_open(file);
swLog_put(SW_LOG_INFO, SW_STRL("hello info"));
swLog_put(SW_LOG_NOTICE, SW_STRL("hello notice"));
swLog_put(SW_LOG_WARNING, SW_STRL("hello warning"));
swoole::String content(swoole_file_get_contents(file));
swLog_close();
unlink(file);
ASSERT_FALSE(swString_contains(content.get(), SW_STRL("hello info")));
ASSERT_TRUE(swString_contains(content.get(), SW_STRL("hello notice")));
ASSERT_TRUE(swString_contains(content.get(), SW_STRL("hello warning")));
}
TEST(log, date_format)
{
swLog_reset();
swLog_set_date_format("day %d of %B in the year %Y. Time: %I:%S %p");
swLog_open(file);
swLog_put(SW_LOG_WARNING, SW_STRL("hello world"));
swoole::String content(swoole_file_get_contents(file));
swLog_close();
unlink(file);
int data[16];
char *month = nullptr;
char *am = nullptr;
int n = std::sscanf(content.value(), "[day %d of %s in the year %d. Time: %d:%d %s @%d.%d]\tWARNING\thello world", data,
month, data + 1, data + 2, data + 3, am, data + 4, data + 5);
ASSERT_TRUE(n);
}
TEST(log, date_with_microseconds)
{
swLog_reset();
swLog_set_date_with_microseconds(true);
swLog_open(file);
swLog_put(SW_LOG_WARNING, SW_STRL("hello world"));
swoole::String content(swoole_file_get_contents(file));
swLog_close();
unlink(file);
std::regex e("\\[\\S+\\s\\d{2}:\\d{2}:\\d{2}\\<\\.(\\d+)\\>\\s@\\d+\\.\\d+\\]\tWARNING\thello world");
ASSERT_TRUE(std::regex_search(content.value(), e));
}
|
8ec8003a6b5e91ac6cdb193dc3dcf155b2193f6c | b0ae45be462527e82dbf2a46187b466acd0d92a5 | /ugt3d/Files/Source Examples (C++)/Chapter 14/ex58.cpp | 2d078ef9d65e26f6f780d07d703c7640a6f85528 | [] | no_license | Torque-Dump/TorqueResourcesDump | 1c97e03da503c2667012dfeb097dae12eb4b90d3 | 5e0b50d1b6c5938d7132475ca9837331a1867b8f | refs/heads/master | 2022-05-18T02:10:47.835191 | 2019-12-09T21:22:23 | 2019-12-09T21:32:34 | 226,960,161 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 421 | cpp | ex58.cpp | /**
The Ultimate Guide To Torque 3D
Chapter 14
By: Robert C Fritzen
ex58.cpp
**/
#include <iostream>
using namespace std;
int divideIt(int num, int den) {
if(den == 0) {
throw "Divide By Zero";
}
return num / den;
}
void main() {
try {
int result = divideIt(10, 0);
cout << "The division is: " << result << endl;
}
catch(char *exception) {
cout << "The above operation failed: " << exception << endl;
}
} |
09afe5eb2ea8441603cbade74e9cfa74df7504ea | f3bb5d77a20d91081364941cfc9dde9658cccfc3 | /code/TestDesignPatterns/TestDesignPatterns/15_composite.cpp | a382640cc15fa2ab8a9ab041dd450cc281a52b5a | [] | no_license | phat64/designpattern | 704da2ec3865477b379d02e895b603910610986f | 30fe6ccc30a40776be086e256b3eb25dc72e8b0e | refs/heads/master | 2021-01-17T10:00:27.615167 | 2019-05-12T22:19:34 | 2019-05-12T22:19:34 | 84,000,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,726 | cpp | 15_composite.cpp | #include <iostream>
#include <list>
#include <algorithm>
#include <assert.h>
using namespace std;
typedef std::string String;
class Employee {
private:
String name;
String dept;
int salary;
list<Employee*> subordinates;
public:
// constructor
Employee(const String& name, const String& dept, int sal) {
this->name = name;
this->dept = dept;
this->salary = sal;
}
virtual ~Employee()
{
cout << "delete :" << name.c_str() << endl;
for (Employee* e : subordinates)
{
delete e;
}
subordinates.clear();
}
void add(Employee* e) {
subordinates.push_back(e);
}
void remove(Employee* e) {
subordinates.remove(e);
}
const list<Employee*>& getSubordinates() {
return subordinates;
}
void printEmployees() {
cout << "Employee :[ Name : " << name.c_str() << ", dept : " << dept.c_str() << ", salary :" << salary << " ]" << endl;
for (Employee* e : subordinates)
{
e->printEmployees();
}
}
};
void main15(int argc, char ** argv) {
Employee* CEO = new Employee("John", "CEO", 30000);
Employee* headSales = new Employee("Robert", "Head Sales", 20000);
Employee* headMarketing = new Employee("Michel", "Head Marketing", 20000);
Employee* clerk1 = new Employee("Laura", "Marketing", 10000);
Employee* clerk2 = new Employee("Bob", "Marketing", 10000);
Employee* salesExecutive1 = new Employee("Richard", "Sales", 10000);
Employee* salesExecutive2 = new Employee("Rob", "Sales", 10000);
CEO->add(headSales);
CEO->add(headMarketing);
headSales->add(salesExecutive1);
headSales->add(salesExecutive2);
headMarketing->add(clerk1);
headMarketing->add(clerk2);
//print all employees of the organization
CEO->printEmployees();
// recursive deletion
delete CEO;
} |
44aac36ce60d64fd6558c8c072363f50d78843bd | cb80a8562d90eb969272a7ff2cf52c1fa7aeb084 | /inletTest3/0.119/yPlus | b3ad08bd38cad1692dded1594eb0a72cc1add974 | [] | no_license | mahoep/inletCFD | eb516145fad17408f018f51e32aa0604871eaa95 | 0df91e3fbfa60d5db9d52739e212ca6d3f0a28b2 | refs/heads/main | 2023-08-30T22:07:41.314690 | 2021-10-14T19:23:51 | 2021-10-14T19:23:51 | 314,657,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,877 | yPlus | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v2006 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.119";
object yPlus;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 0;
boundaryField
{
bottomEmptyFaces
{
type empty;
}
topEmptyFaces
{
type empty;
}
inlet
{
type calculated;
value uniform 0;
}
outlet
{
type calculated;
value uniform 0;
}
walls
{
type calculated;
value nonuniform List<scalar>
1055
(
30.3947
29.6571
28.978
28.3507
27.7841
27.2749
26.8237
26.4177
26.053
25.7237
25.4319
25.1741
24.9513
24.7581
24.5942
24.4531
24.3348
24.2335
24.1504
24.0803
24.024
23.9766
23.9395
23.9085
23.8845
23.865
23.8518
23.842
23.8364
23.8323
23.8324
23.832
23.8338
23.8362
23.8393
23.8435
23.8472
23.8516
23.8544
23.8579
23.8592
23.8616
23.8612
23.8624
23.8606
23.8606
23.8572
23.8558
23.8509
23.8483
23.8419
23.8378
23.8306
23.8255
23.8176
23.8117
23.8037
23.7976
23.7893
23.7829
23.7746
23.7682
23.7598
23.7533
23.7451
23.7387
23.7303
23.724
23.7157
23.7094
23.7013
23.6951
23.6871
23.6812
23.6736
23.668
23.6607
23.6556
23.6487
23.6442
23.6378
23.6339
23.628
23.6249
23.6196
23.6174
23.6128
23.6113
23.6075
23.6066
23.6038
23.6034
23.6016
23.6017
23.601
23.6016
23.6019
23.6031
23.6046
23.6063
23.6086
23.611
23.6138
23.6171
23.6203
23.6244
23.6281
23.6329
23.637
23.6424
23.6471
23.6529
23.658
23.6643
23.6698
23.6765
23.6824
23.6894
23.6956
23.703
23.7095
23.7171
23.7238
23.7317
23.7386
23.7468
23.7539
23.7622
23.7696
23.778
23.7856
23.7942
23.8019
23.8107
23.8185
23.8273
23.8353
23.8442
23.8522
23.8612
23.8693
23.8783
23.8865
23.8955
23.9036
23.9127
23.9209
23.9299
23.9381
23.9471
23.9553
23.9642
23.9724
23.9813
23.9895
23.9983
24.0065
24.0153
24.0234
24.0323
24.0404
24.0493
24.0573
24.0663
24.0743
24.0833
24.0913
24.1003
24.1083
24.1173
24.1253
24.1344
24.1424
24.1514
24.1593
24.1682
24.1759
24.1848
24.1923
24.2011
24.2082
24.2252
24.2241
24.2247
24.2392
24.2485
24.254
24.2801
24.2891
24.3168
24.2763
24.2163
23.9997
24.1586
24.5681
8.48694
7.19204
6.55538
11.3922
10.6002
9.68062
7.98222
18.2619
13.3597
11.5844
11.4901
12.7087
9.40242
8.08216
12.4951
11.3846
13.657
13.6328
10.7286
9.21001
9.77326
9.65179
8.53466
7.37066
10.1101
9.93062
8.85342
7.4805
9.13563
7.62023
8.61217
7.39406
9.57902
10.1061
8.55261
7.38978
8.3685
7.29616
8.36199
7.27574
6.55771
10.4443
10.9358
9.73448
10.6133
9.48441
10.4009
9.21348
9.96792
9.25071
10.1189
10.1261
10.5465
9.32586
10.2178
11.5774
8.49464
8.89507
8.98604
9.73999
10.3258
10.7736
11.8946
8.66121
9.10383
9.58787
10.3847
8.35112
9.0142
10.0234
7.36953
7.68144
8.80272
9.0658
10.1845
7.48362
7.82584
8.01801
8.49579
9.16525
9.53374
8.1559
8.70522
8.42107
9.13941
8.67011
9.39326
8.33438
8.91429
10.7737
9.39633
9.77564
7.82033
8.2304
10.5656
7.71787
8.1228
10.4285
9.10248
9.4071
8.296
9.01113
7.96445
8.54791
7.5072
7.85594
9.88301
10.2912
11.405
8.32791
8.75991
8.85157
9.73083
11.0489
8.03545
8.45258
8.66763
9.29337
9.13195
9.94844
9.64289
10.1022
8.9754
9.7402
8.65235
9.54314
8.53074
9.19288
9.4604
9.83268
10.8648
7.93138
8.23917
8.66442
9.4012
9.13379
9.97821
8.81778
9.5919
8.67077
9.1106
7.88088
7.71545
7.32469
7.0419
9.5722
7.42889
7.85091
8.34786
8.52739
9.45852
6.95825
7.14307
8.38636
8.59249
9.73094
7.13739
7.45091
7.59711
8.02863
8.15698
8.26012
7.03222
7.25437
7.97965
7.98045
7.8197
7.80816
9.16681
6.84891
7.01007
9.20551
7.87731
7.94165
6.78632
6.98806
9.0713
7.34225
7.02585
8.98835
7.77525
7.72686
8.68927
6.6381
6.66958
7.83903
7.76791
6.71639
6.76285
6.71854
6.84529
9.25183
7.97445
8.05088
9.29718
6.94913
7.13173
6.8099
7.02537
8.98774
8.79535
7.39888
6.95178
8.32819
7.02143
6.57305
8.3734
7.106
6.53209
8.4485
7.16553
6.5894
8.35056
6.9877
6.46034
8.07691
6.49201
6.30797
8.28164
6.83497
6.46718
7.79615
7.43276
8.41139
7.73445
7.52828
6.56439
6.52762
8.75207
8.64642
7.27025
6.88461
7.38877
6.92912
7.11356
6.80103
8.95
7.20026
6.90299
8.56079
6.68435
6.72676
8.73176
8.95548
10.0766
7.41413
7.71072
9.8992
7.17135
7.48349
8.58585
8.82806
7.77442
8.28034
7.86586
8.34161
8.7167
9.03654
8.04603
8.57481
13.2263
11.3563
8.65267
11.2564
8.33559
11.6902
9.73049
7.00231
10.6693
10.352
7.15564
12.2501
9.98439
26.1658
24.6434
8.23778
8.80969
6.17039
25.2783
21.2069
21.2092
20.3961
10.3679
20.1416
8.85699
25.4016
7.73166
20.6633
8.94602
6.16369
20.1037
21.4347
20.8997
10.7113
9.5751
8.44008
7.44321
8.31291
6.01244
28.063
26.5035
21.8411
21.3833
22.1129
21.5611
25.103
22.0636
20.9347
27.1904
23.2969
22.3946
9.99478
9.00764
8.46655
7.98565
7.34021
8.51483
6.06293
10.5196
9.68317
9.11522
8.61643
8.20682
7.67589
6.96293
7.83933
5.77556
9.68968
8.94143
8.49962
8.12564
7.82415
7.51813
7.26357
7.0346
6.91477
6.77692
6.4122
7.78281
5.39579
9.82466
9.28829
8.9814
8.81016
8.60729
13.9751
8.38154
8.20513
8.06677
7.91587
7.8214
10.9714
12.0127
7.67875
12.0593
12.5064
10.3923
11.2246
13.4757
11.6653
12.1885
9.73395
10.2895
10.6773
11.7115
7.58758
7.54775
7.42929
7.30552
7.21094
7.13047
7.0578
7.00087
14.7458
10.6261
11.2211
12.6124
13.1801
11.6029
12.7145
6.94948
6.91057
6.87851
6.85783
6.83495
6.819
6.80766
6.7971
13.5616
14.1675
12.3883
13.4787
6.78938
6.77824
6.77392
6.77213
6.76707
6.76164
6.76175
6.7603
13.8201
14.2686
13.2385
14.3704
12.5841
13.5875
16.1235
11.6989
12.3679
6.75381
15.8062
6.74678
6.74451
11.3972
12.036
6.73971
6.73733
12.2987
13.1845
6.72763
6.72436
6.71845
15.2308
11.8173
12.9098
13.0663
13.5861
11.8299
12.8022
11.0187
11.6196
11.3992
12.3099
11.2933
12.3129
12.185
12.6647
11.0794
12.1934
14.1378
10.2476
10.7881
10.901
11.7759
14.4257
11.151
12.0611
10.3828
10.9836
12.3977
12.9283
10.7966
11.6698
10.1813
10.7018
19.2122
14.3594
14.9381
6.71396
6.70352
6.69838
6.69399
20.693
6.68363
6.67438
6.66806
20.0104
6.66346
14.5386
15.4421
17.3359
17.4145
19.8444
16.8767
17.2535
14.6388
15.3514
16.7138
16.985
6.65325
6.64388
6.63773
6.63232
6.62164
6.61158
6.60485
6.59931
6.58841
6.57868
6.57213
6.56701
6.5567
6.54729
6.54114
15.4349
6.53565
15.7274
16.2542
16.7834
14.4234
15.405
18.2127
13.1211
13.9298
6.52518
6.51547
6.50953
6.50413
6.49465
6.48465
6.47972
6.47207
17.4735
13.997
14.9641
12.9075
13.646
13.3455
14.2738
17.11
14.6415
15.1997
12.2403
13.0346
14.8175
15.4466
18.397
15.7162
16.2085
13.3042
14.0629
19.2434
19.0509
13.9827
14.6271
16.2906
16.5056
16.1442
16.6206
6.46662
14.1372
6.45504
14.8854
6.44988
6.44251
6.43778
6.42646
6.42202
6.41502
21.3928
6.41029
6.39916
15.9165
16.6056
6.39469
6.38807
6.38377
6.37347
6.3689
22.1986
6.36534
21.9052
18.1215
17.8912
18.7234
18.918
19.828
19.9328
23.5285
6.35643
18.8549
6.35048
18.6875
6.34207
6.34038
6.33252
22.7581
6.32735
6.32246
18.7521
18.4225
6.31531
22.9418
17.8623
18.4069
16.8152
17.3951
18.0728
18.3367
15.4963
16.1637
6.31371
6.30801
6.31131
6.37337
6.4147
6.51328
6.78074
7.13175
29.2696
25.9545
30.2352
23.7619
22.1045
30.0135
27.236
26.9518
23.3986
22.3201
9.90804
10.7673
33.234
32.0369
30.821
33.1365
25.6306
23.5395
30.6445
27.0572
25.2363
22.7348
12.5362
30.3957
9.97653
10.9128
10.8509
11.2677
28.9174
35.3452
27.3551
25.4116
10.2501
11.2113
10.0399
11.0068
35.5676
12.8173
11.1223
11.5915
9.32336
9.79569
36.1793
9.7903
10.5711
9.11005
9.57115
36.6874
36.7256
36.8629
36.5587
35.7928
13.1553
34.8601
10.7556
11.7131
10.4484
11.4944
10.2457
11.0559
9.49682
10.0166
10.4161
11.3897
11.3349
11.7778
10.217
11.1362
33.9187
32.9802
32.0634
31.1968
9.59732
10.5397
12.0154
8.79523
9.21398
9.31917
10.0887
9.78462
10.7268
25.0507
7.57638
36.4709
33.1928
31.0011
29.5309
28.4213
27.3887
26.6569
25.9466
25.5499
25.0744
24.7908
24.4221
24.2085
23.9079
23.7398
23.4853
23.3472
23.1238
23.0057
22.8044
22.7008
22.5154
22.4219
22.2482
22.162
21.9971
21.9162
21.7582
21.6813
21.5286
21.4547
21.3063
21.2346
21.0897
21.0196
20.8774
20.8086
20.6687
20.6008
20.4626
20.3953
20.2584
20.1915
20.0554
19.9885
19.8529
19.7858
19.6501
19.5825
19.4464
19.3781
19.2412
19.1719
19.0339
18.9633
18.8238
18.7518
18.6104
18.5369
18.3934
18.318
18.1722
18.095
17.9466
17.8675
17.7164
17.6355
17.4816
17.3989
17.2423
17.158
16.9988
16.9132
16.7517
16.6652
16.5017
16.415
16.2502
16.1639
15.9987
15.9141
15.7497
15.6681
15.5061
15.4291
15.2713
15.2012
15.0498
14.9891
14.8465
14.7989
14.6689
14.6359
14.5253
14.5069
14.4189
14.4164
14.3585
14.3687
14.3438
14.3665
14.3591
14.4107
14.4188
14.4977
14.5217
14.6234
14.659
14.7763
14.8204
14.9481
14.9985
15.1337
15.1881
15.3275
15.3834
15.523
15.5785
15.7153
15.7687
15.8997
15.9497
16.0725
16.1179
16.2308
16.2711
16.3724
16.4066
16.4951
16.5229
16.5983
16.6197
16.6824
16.6977
16.7485
16.7581
16.7982
16.8029
16.8338
16.8343
16.8566
16.8545
16.8702
16.8659
16.8758
16.8697
16.8761
16.8672
16.8714
16.8583
16.8616
16.846
16.8485
16.8307
16.8328
16.8133
16.8151
16.7941
16.7954
16.7733
16.7743
16.7513
16.752
16.7282
16.729
16.702
16.7085
16.6758
16.6853
16.6403
16.7147
16.7441
16.946
17.2278
18.2726
20.9117
18.9403
39.9395
)
;
}
rightWall
{
type calculated;
value uniform 0;
}
symmetryLine
{
type symmetryPlane;
}
}
// ************************************************************************* //
| |
cab8fc97367a5388777743ffa931005d969b4f75 | b7713ff4d4d102ae181190ee6350d793d25d5a0b | /engine/src/managers/EntityManager.cpp | c4f1229a2d8331373d8f3d0bcf0d44efb7cd0c4a | [] | no_license | rokkiPeruna/SummerEngine | dfa750c0dd4eb94cb14e65976276c0995db9d9b2 | ec60ee58516142576caf5446d91891a24381a68a | refs/heads/master | 2021-05-09T23:33:07.218529 | 2017-08-23T11:36:14 | 2017-08-23T11:36:14 | 118,786,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,261 | cpp | EntityManager.cpp | #include <managers/EntityManager.h>
#include <managers/ComponentManager.h>
#include <systems/TransformSystem.h>
namespace se
{
namespace priv
{
EntityManager::EntityManager(Engine& engine_ref)
: Manager(engine_ref)
, m_currentScene(nullptr)
, m_currentEntity(nullptr)
, m_rel_path_to_json_scenes("")
, m_rel_path_to_user_files("")
, m_templ_number(0)
, ffd()
, sf_struct()
, snaf_struct()
, eobj_struct()
, cobj_struct()
, m_entities{}
, m_entities_names_map{}
, m_entity_templs_map{}
, m_clock()
, m_start_time()
, m_end_time()
, m_posb_gap_in_free_entity_ids(true)
, m_curr_free_entity_id(-1)
, m_free_entity_ids{}
{
}
void EntityManager::Initialize(std::string relativePathToEntitiesJson)
{
m_rel_path_to_user_files = relativePathToEntitiesJson;
m_rel_path_to_json_scenes = relativePathToEntitiesJson + ffd.scene_folder_name;
m_entities.clear();
m_entities_names_map.clear();
while (!m_free_entity_ids.empty())
m_free_entity_ids.pop();
///Register events
m_event_handler.RegisterEvent(SE_Event_SceneChanged(nullptr));
m_event_handler.RegisterEvent(SE_Event_CreateBasicEntity(""));
m_event_handler.RegisterEvent(SE_Cmd_SaveEntityAsTemplate(nullptr));
m_event_handler.RegisterEvent(SE_Cmd_SetEntityAsCurrent(nullptr));
m_event_handler.RegisterEvent(SE_Cmd_DeleteEntityByName(""));
}
void EntityManager::Uninitialize()
{
}
void EntityManager::Update()
{
//Check events
SE_Event se_event;
while (m_event_handler.PollEvents(se_event))
{
switch (se_event.type)
{
case EventType::SceneChanged:
{
InitWithNewScene(static_cast<Scene*>(se_event.data.void_ptr));
break;
}
case EventType::CreateBasicEntity:
{
CreateEntityOnEditor(se_event.data.char_arr);
break;
}
case EventType::SaveEntityAsTemplate:
{
SaveEntityAsTemplate(static_cast<Entity*>(se_event.data.void_ptr));
break;
}
case EventType::SetEntityAsCurrent:
{
m_currentEntity = static_cast<Entity*>(se_event.data.void_ptr);
if (m_currentEntity)
{
auto new_cam_pos = TransformSystem::TransformableComponents.at(m_currentEntity->id).position;
new_cam_pos.z = 40.0f;
m_event_handler.SendEvent(SE_Cmd_ChangeCameraPos(new_cam_pos));
}
break;
}
case EventType::DeleteEntityByName:
{
DeleteEntityOnEditor(se_event.data.char_arr);
break;
}
default:
break;
}
}
}
void EntityManager::InitWithNewScene(Scene* scene)
{
m_entities.clear();
m_entities_names_map.clear();
m_currentEntity = nullptr;
m_currentScene = scene;
SEint largest_id_found = _loadSceneEntities();
_res_space_CTransfComponents(largest_id_found);
std::cout << "largest_id " << largest_id_found << "TRsize " << TransformSystem::TransformableComponents.size() << std::endl;
//Find free ids
while (!m_free_entity_ids.empty())
m_free_entity_ids.pop();
m_curr_free_entity_id = _findFreeEntityID();
}
void EntityManager::CreateEntityOnEditor(std::string name)
{
//Get json object holding entities
auto json = m_currentScene->GetData();
auto& entities_obj = json->find(sf_struct.prim_obj_name);
entities_obj.value().push_back({ name,
nlohmann::json({{eobj_struct.id_obj_name, m_curr_free_entity_id }}),
});
m_entities.emplace(m_curr_free_entity_id, Entity(name, m_curr_free_entity_id));
m_entities_names_map.emplace(name, m_curr_free_entity_id);
m_currentEntity = &m_entities.at(m_curr_free_entity_id);
m_curr_free_entity_id = _findFreeEntityID();
m_event_handler.SendEvent(SE_Event_EntityCreatedOnEditor(m_currentEntity->id));
auto new_cam_pos{ TransformSystem::TransformableComponents.at(m_currentEntity->id).position };
new_cam_pos.z = 10.0f;
m_event_handler.SendEvent(SE_Cmd_ChangeCameraPos(new_cam_pos));
}
void EntityManager::CreateEntityOnEditor(Entity&, std::string)
{
}
Entity* EntityManager::CreateEntityFromTemplate(std::string templateName)
{
//If this entity template has already been used in scene, it it added to run-time container
if (m_entity_templs_map.count(templateName + "_template"))
{
std::string tmp = templateName + std::to_string(m_templ_number++);
SEint freeid = _findFreeEntityID();
m_entities.emplace(freeid, Entity(tmp, freeid));
m_entities_names_map.emplace(tmp, freeid);
//Add component types
auto& entity = m_entities.at(freeid);
auto& itr = m_entity_templs_map.at(templateName + "_template").find(templateName + "_template");
for (auto c : (*itr))
{
if (c.count(cobj_struct.type_obj_name))
{
SEint type_as_int = c.at(cobj_struct.type_obj_name);
entity.components.emplace(static_cast<COMPONENT_TYPE>(type_as_int), -1);
}
}
for (auto s : m_engine.GetSystemsContainer())
{
s->OnEntityAdded(m_entities.at(freeid), itr);
}
//Clean up, one method to take care of all this entityAdded stuff!
auto rend = m_engine.GetCurrentRenderer();
for (auto e : m_entities)
{
rend->OnEntityAdded(e.second);
}
return &m_entities.at(freeid);
}
//Otherwise we create and add it to run-time container for further use
else
{
//Open file for reading and loop all components
nlohmann::json entity;
util::ReadFileToJson(entity, m_rel_path_to_user_files + ffd.entity_tmpl_fold_name + templateName + "_template" + ffd.scene_file_suffix, EntityMgr_id);
//Store json object
m_entity_templs_map.emplace(templateName + "_template", entity);
SEint freeid = _findFreeEntityID();
m_entities.emplace(freeid, Entity(templateName + "_template", freeid));
m_entities_names_map.emplace(templateName + "_template", freeid);
auto& e = m_entities.at(freeid);
for (auto j = entity[templateName + "_template"].begin(); j != entity[templateName + "_template"].end(); j++)
{
if (j.key() != "id")
{
SEint type_as_int = j.value().at(cobj_struct.type_obj_name);
e.components.emplace(static_cast<COMPONENT_TYPE>(type_as_int), -1);
}
}
auto& itr = entity.find(templateName + "_template");
for (auto s : m_engine.GetSystemsContainer())
{
s->OnEntityAdded(m_entities.at(freeid), itr);
}
return &m_entities.at(freeid);
}
}
void EntityManager::SaveEntityAsTemplate(Entity* entity)
{
assert(entity);
try
{
auto& file = m_rel_path_to_user_files + ffd.entity_tmpl_fold_name + entity->name + "_template" + ffd.scene_file_suffix;
auto& tmpl_name = entity->name + "_template";
//Write base json object manually
std::ofstream entity_tmpl(file, std::ios::trunc);
if (!entity_tmpl.is_open())
{
MessageError(EntityMgr_id) << "Failed to create and open " + file + " in SaveEntityAsTemplate()";
return;
}
entity_tmpl << "{\n\"" + entity->name + "_template\": \n{\n}" + "\n}";
entity_tmpl.close();
//Find json object from which the template is made
auto json = m_currentScene->GetData();
auto& entities_obj = json->find(sf_struct.prim_obj_name);
auto components = entities_obj.value().find(entity->name);
nlohmann::json templateEntity;
util::ReadFileToJson(templateEntity, file, EntityMgr_id);
templateEntity[tmpl_name] = (*components);
templateEntity.at(tmpl_name).at(eobj_struct.id_obj_name) = -1;
for (auto& itr : templateEntity.at(tmpl_name))
{
if (itr.count(cobj_struct.ownerID_obj_name))
{
itr.at(cobj_struct.ownerID_obj_name) = -1;
}
}
util::RewriteFileWithJson(templateEntity, file, EntityMgr_id);
}
catch (const std::exception& exc)
{
//e_templ.close();
std::string tmp = exc.what();
MessageError(EntityMgr_id) << "Json exception in SaveEntityAsTemplate(),\njson exception message: " + tmp;
}
}
void EntityManager::DeleteEntityOnEditor(std::string entity_name)
{
auto json = m_currentScene->GetData();
auto& entities_obj = json->find(sf_struct.prim_obj_name);
entities_obj.value().erase(entity_name);
SEint entity_id = m_entities_names_map.at(entity_name);
for (auto s : m_engine.GetSystemsContainer())
{
s->OnEntityRemoved(m_entities.at(entity_id));
}
//SE_TODO: Should this be event based?
m_engine.GetCurrentRenderer()->OnEntityRemoved(m_entities.at(entity_id));
m_free_entity_ids.push(m_entities.at(entity_id).id);
if (m_currentEntity == &m_entities.at(entity_id))
{
m_currentEntity = nullptr;
}
m_event_handler.SendEvent(SE_Event_EntityDeletedOnEditor(m_currentEntity, entity_id));
m_entities.erase(entity_id);
m_entities_names_map.erase(entity_name);
}
std::unordered_map<std::string, SEint>& EntityManager::GetEntityNameToID()
{
return m_entities_names_map;
}
Scene* EntityManager::GetCurrentScene()
{
return m_currentScene;
}
Entity* EntityManager::GetCurrentEntity()
{
return m_currentEntity;
}
void EntityManager::SetCurrentEntity(Entity* e)
{
m_currentEntity = e;
}
SEint EntityManager::_loadSceneEntities()
{
auto json = m_currentScene->GetData();
auto& entities_obj = json->find(sf_struct.prim_obj_name);
if (entities_obj == json->end())
{
MessageError(EntityMgr_id) << "Could not open json object [" + sf_struct.prim_obj_name + "] in _loadSceneEntities()\nscene's entities not loaded!";
return -1;
}
SEint largestID = 0;
for (auto& itr = entities_obj.value().begin(); itr != entities_obj.value().end(); itr++)
{
SEint id = itr.value().at(eobj_struct.id_obj_name);
m_entities.emplace(id, Entity(itr.key(), id));
m_entities_names_map.emplace(itr.key(), id);
if (id > largestID)
largestID = id;
}
return largestID;
}
void EntityManager::_res_space_CTransfComponents(SEint largest_id)
{
SEint safetyFactor = 2;
SEint rsz_val = (largest_id > 10) ? largest_id : 50;
TransformSystem::TransformableComponents.resize(rsz_val * safetyFactor);
}
SEint EntityManager::_findFreeEntityID()
{
//If we have values in free entity ids, just return top of the stack and pop it
if (!m_free_entity_ids.empty())
{
SEint ret = m_free_entity_ids.top();
m_free_entity_ids.pop();
return ret;
}
//Else we have to loop through all entities, and push possible gap values to stack
auto json = m_currentScene->GetData();
auto& entities_obj = json->find(sf_struct.prim_obj_name);
if (entities_obj == json->end())
{
MessageError(EntityMgr_id) << "Could not open json object [" + sf_struct.prim_obj_name + "] in _findFreeEntityID()\nscene's entities not loaded!";
return 0;
}
//Find current largest id
//For nlohmann::json (lack of know-how/bug?) we have to push values to temporary container
std::vector<SEint> tmp;
for (auto& itr = entities_obj.value().begin(); itr != entities_obj.value().end(); ++itr)
{
tmp.emplace_back(static_cast<SEint>(itr.value().at(eobj_struct.id_obj_name)));
}
//Sort vector
std::sort(tmp.begin(), tmp.end(), [&tmp](SEint a, SEint b) {return a < b; });
//Check for possible empty scene
if (!tmp.empty())
{
//Push indices larger than current largest index with proper marginal
SEint curr_larg_id = tmp.back();
for (SEint i = 200; i > 0; --i)
{
m_free_entity_ids.push(curr_larg_id + i);
}
//Find and fill (possible) gaps
for (SEint i = 0; i < tmp.size() - 1; ++i)
{
if (tmp.at(i) + 1 != tmp.at(i + 1))
m_free_entity_ids.push(tmp.at(i) + 1);
}
SEint id = m_free_entity_ids.top();
m_free_entity_ids.pop();
return id;
}
//If scene is really empty of entities, push proper amount of values to free ids and return first id
else
{
for (SEint i = 200; i > 0; --i)
{
m_free_entity_ids.push(i);
}
return 0;
}
}
}//namespace priv
}//namespace se |
757b519fecf5af0a9605040c815785e035315dbe | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/sqlite/src/ext/lsm1/lsm-test/lsmtest_tdb2.cc | 86ebb49583ffb0dcfe7e60121906e7dbba8a9a01 | [
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"blessing",
"LicenseRef-scancode-public-domain"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 7,681 | cc | lsmtest_tdb2.cc |
#include "lsmtest.h"
#include <stdlib.h>
#ifdef HAVE_KYOTOCABINET
#include "kcpolydb.h"
extern "C" {
struct KcDb {
TestDb base;
kyotocabinet::TreeDB* db;
char *pVal;
};
}
int test_kc_open(const char *zFilename, int bClear, TestDb **ppDb){
KcDb *pKcDb;
int ok;
int rc = 0;
if( bClear ){
char *zCmd = sqlite3_mprintf("rm -rf %s\n", zFilename);
system(zCmd);
sqlite3_free(zCmd);
}
pKcDb = (KcDb *)malloc(sizeof(KcDb));
memset(pKcDb, 0, sizeof(KcDb));
pKcDb->db = new kyotocabinet::TreeDB();
pKcDb->db->tune_page(TESTDB_DEFAULT_PAGE_SIZE);
pKcDb->db->tune_page_cache(
TESTDB_DEFAULT_PAGE_SIZE * TESTDB_DEFAULT_CACHE_SIZE
);
ok = pKcDb->db->open(zFilename,
kyotocabinet::PolyDB::OWRITER | kyotocabinet::PolyDB::OCREATE
);
if( ok==0 ){
free(pKcDb);
pKcDb = 0;
rc = 1;
}
*ppDb = (TestDb *)pKcDb;
return rc;
}
int test_kc_close(TestDb *pDb){
KcDb *pKcDb = (KcDb *)pDb;
if( pKcDb->pVal ){
delete [] pKcDb->pVal;
}
pKcDb->db->close();
delete pKcDb->db;
free(pKcDb);
return 0;
}
int test_kc_write(TestDb *pDb, void *pKey, int nKey, void *pVal, int nVal){
KcDb *pKcDb = (KcDb *)pDb;
int ok;
ok = pKcDb->db->set((const char *)pKey, nKey, (const char *)pVal, nVal);
return (ok ? 0 : 1);
}
int test_kc_delete(TestDb *pDb, void *pKey, int nKey){
KcDb *pKcDb = (KcDb *)pDb;
int ok;
ok = pKcDb->db->remove((const char *)pKey, nKey);
return (ok ? 0 : 1);
}
int test_kc_delete_range(
TestDb *pDb,
void *pKey1, int nKey1,
void *pKey2, int nKey2
){
int res;
KcDb *pKcDb = (KcDb *)pDb;
kyotocabinet::DB::Cursor* pCur = pKcDb->db->cursor();
if( pKey1 ){
res = pCur->jump((const char *)pKey1, nKey1);
}else{
res = pCur->jump();
}
while( 1 ){
const char *pKey; size_t nKey;
const char *pVal; size_t nVal;
pKey = pCur->get(&nKey, &pVal, &nVal);
if( pKey==0 ) break;
#ifndef NDEBUG
if( pKey1 ){
res = memcmp(pKey, pKey1, MIN((size_t)nKey1, nKey));
assert( res>0 || (res==0 && nKey>nKey1) );
}
#endif
if( pKey2 ){
res = memcmp(pKey, pKey2, MIN((size_t)nKey2, nKey));
if( res>0 || (res==0 && (size_t)nKey2<nKey) ){
delete [] pKey;
break;
}
}
pCur->remove();
delete [] pKey;
}
delete pCur;
return 0;
}
int test_kc_fetch(
TestDb *pDb,
void *pKey,
int nKey,
void **ppVal,
int *pnVal
){
KcDb *pKcDb = (KcDb *)pDb;
size_t nVal;
if( pKcDb->pVal ){
delete [] pKcDb->pVal;
pKcDb->pVal = 0;
}
pKcDb->pVal = pKcDb->db->get((const char *)pKey, nKey, &nVal);
if( pKcDb->pVal ){
*ppVal = pKcDb->pVal;
*pnVal = nVal;
}else{
*ppVal = 0;
*pnVal = -1;
}
return 0;
}
int test_kc_scan(
TestDb *pDb, /* Database handle */
void *pCtx, /* Context pointer to pass to xCallback */
int bReverse, /* True for a reverse order scan */
void *pKey1, int nKey1, /* Start of search */
void *pKey2, int nKey2, /* End of search */
void (*xCallback)(void *pCtx, void *pKey, int nKey, void *pVal, int nVal)
){
KcDb *pKcDb = (KcDb *)pDb;
kyotocabinet::DB::Cursor* pCur = pKcDb->db->cursor();
int res;
if( bReverse==0 ){
if( pKey1 ){
res = pCur->jump((const char *)pKey1, nKey1);
}else{
res = pCur->jump();
}
}else{
if( pKey2 ){
res = pCur->jump_back((const char *)pKey2, nKey2);
}else{
res = pCur->jump_back();
}
}
while( res ){
const char *pKey; size_t nKey;
const char *pVal; size_t nVal;
pKey = pCur->get(&nKey, &pVal, &nVal);
if( bReverse==0 && pKey2 ){
res = memcmp(pKey, pKey2, MIN((size_t)nKey2, nKey));
if( res>0 || (res==0 && (size_t)nKey2<nKey) ){
delete [] pKey;
break;
}
}else if( bReverse!=0 && pKey1 ){
res = memcmp(pKey, pKey1, MIN((size_t)nKey1, nKey));
if( res<0 || (res==0 && (size_t)nKey1>nKey) ){
delete [] pKey;
break;
}
}
xCallback(pCtx, (void *)pKey, (int)nKey, (void *)pVal, (int)nVal);
delete [] pKey;
if( bReverse ){
res = pCur->step_back();
}else{
res = pCur->step();
}
}
delete pCur;
return 0;
}
#endif /* HAVE_KYOTOCABINET */
#ifdef HAVE_MDB
#include "lmdb.h"
extern "C" {
struct MdbDb {
TestDb base;
MDB_env *env;
MDB_dbi dbi;
};
}
int test_mdb_open(
const char *zSpec,
const char *zFilename,
int bClear,
TestDb **ppDb
){
MDB_txn *txn;
MdbDb *pMdb;
int rc;
if( bClear ){
char *zCmd = sqlite3_mprintf("rm -rf %s\n", zFilename);
system(zCmd);
sqlite3_free(zCmd);
}
pMdb = (MdbDb *)malloc(sizeof(MdbDb));
memset(pMdb, 0, sizeof(MdbDb));
rc = mdb_env_create(&pMdb->env);
if( rc==0 ) rc = mdb_env_set_mapsize(pMdb->env, 1*1024*1024*1024);
if( rc==0 ) rc = mdb_env_open(pMdb->env, zFilename, MDB_NOSYNC|MDB_NOSUBDIR, 0600);
if( rc==0 ) rc = mdb_txn_begin(pMdb->env, NULL, 0, &txn);
if( rc==0 ){
rc = mdb_open(txn, NULL, 0, &pMdb->dbi);
mdb_txn_commit(txn);
}
*ppDb = (TestDb *)pMdb;
return rc;
}
int test_mdb_close(TestDb *pDb){
MdbDb *pMdb = (MdbDb *)pDb;
mdb_close(pMdb->env, pMdb->dbi);
mdb_env_close(pMdb->env);
free(pMdb);
return 0;
}
int test_mdb_write(TestDb *pDb, void *pKey, int nKey, void *pVal, int nVal){
int rc;
MdbDb *pMdb = (MdbDb *)pDb;
MDB_val val;
MDB_val key;
MDB_txn *txn;
val.mv_size = nVal;
val.mv_data = pVal;
key.mv_size = nKey;
key.mv_data = pKey;
rc = mdb_txn_begin(pMdb->env, NULL, 0, &txn);
if( rc==0 ){
rc = mdb_put(txn, pMdb->dbi, &key, &val, 0);
if( rc==0 ){
rc = mdb_txn_commit(txn);
}else{
mdb_txn_abort(txn);
}
}
return rc;
}
int test_mdb_delete(TestDb *pDb, void *pKey, int nKey){
int rc;
MdbDb *pMdb = (MdbDb *)pDb;
MDB_val key;
MDB_txn *txn;
key.mv_size = nKey;
key.mv_data = pKey;
rc = mdb_txn_begin(pMdb->env, NULL, 0, &txn);
if( rc==0 ){
rc = mdb_del(txn, pMdb->dbi, &key, 0);
if( rc==0 ){
rc = mdb_txn_commit(txn);
}else{
mdb_txn_abort(txn);
}
}
return rc;
}
int test_mdb_fetch(
TestDb *pDb,
void *pKey,
int nKey,
void **ppVal,
int *pnVal
){
int rc;
MdbDb *pMdb = (MdbDb *)pDb;
MDB_val key;
MDB_txn *txn;
key.mv_size = nKey;
key.mv_data = pKey;
rc = mdb_txn_begin(pMdb->env, NULL, MDB_RDONLY, &txn);
if( rc==0 ){
MDB_val val = {0, 0};
rc = mdb_get(txn, pMdb->dbi, &key, &val);
if( rc==MDB_NOTFOUND ){
rc = 0;
*ppVal = 0;
*pnVal = -1;
}else{
*ppVal = val.mv_data;
*pnVal = val.mv_size;
}
mdb_txn_commit(txn);
}
return rc;
}
int test_mdb_scan(
TestDb *pDb, /* Database handle */
void *pCtx, /* Context pointer to pass to xCallback */
int bReverse, /* True for a reverse order scan */
void *pKey1, int nKey1, /* Start of search */
void *pKey2, int nKey2, /* End of search */
void (*xCallback)(void *pCtx, void *pKey, int nKey, void *pVal, int nVal)
){
MdbDb *pMdb = (MdbDb *)pDb;
int rc;
MDB_cursor_op op = bReverse ? MDB_PREV : MDB_NEXT;
MDB_txn *txn;
rc = mdb_txn_begin(pMdb->env, NULL, MDB_RDONLY, &txn);
if( rc==0 ){
MDB_cursor *csr;
MDB_val key = {0, 0};
MDB_val val = {0, 0};
rc = mdb_cursor_open(txn, pMdb->dbi, &csr);
if( rc==0 ){
while( mdb_cursor_get(csr, &key, &val, op)==0 ){
xCallback(pCtx, key.mv_data, key.mv_size, val.mv_data, val.mv_size);
}
mdb_cursor_close(csr);
}
}
return rc;
}
#endif /* HAVE_MDB */
|
b8e525531b50fe2ece3dc898a0b89355c00a4042 | 5c64bf47c299f32a7b5dd27cbb3a270f87bfb21e | /Lab3/Part2.cpp | ef8daf9410cc44feabc71ec168893365ab988650 | [] | no_license | alanngo/Prog-Fund-3 | cfb1847ed64deb8a77d6e6668a8e08972fe68345 | 24e76afd64466799a5a9799b307d188afeca7891 | refs/heads/master | 2021-07-02T10:53:56.442962 | 2020-04-21T17:29:14 | 2020-04-21T17:29:14 | 99,513,355 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,144 | cpp | Part2.cpp | /******************************************************************
// Template Program
// Programmer: Alan Ngo
// Completed : Febuary 13 2017
// Status : Complete
//
// This program will be used to test the factorial function using both
iterative and recursive functions
******************************************************************/
#include <iostream> // for cin, cout, endl
#include <cmath>
#include <iomanip>
#include <fstream>
#include <string>
#include <string.h>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <ctime>
using namespace std;
//prototypes
int recursiveFactorial(int);
int iterativeFactorial(int);
void input(int&, long long int&);
void output(int&, long long int&, double, double);
void determineEfficiency(double, double);
int main()
{
cout << fixed << showpoint << setprecision (2);
long int test = 0;
long long int trialRuns=0;
int x=0;
clock_t start;
double recursiveTime=0;
double iterativeTime=0;
char again='y';
while(again=='y')
{
input(x, trialRuns);
start=clock();
for (int n = 0; n <trialRuns; n++)
{
test=recursiveFactorial(x);
//cout<<test<<endl;
}
recursiveTime=(clock()-double(start))/CLOCKS_PER_SEC;
/*______________________________________________________*/
start=clock();
for (int n=0; n<trialRuns; n++)
{
test=iterativeFactorial(x);
//cout<<test<<endl;
}
iterativeTime=(clock()-double(start))/CLOCKS_PER_SEC;
output(x, trialRuns, recursiveTime, iterativeTime);
determineEfficiency(recursiveTime, iterativeTime);
/*______________________________________________________*/
cout<<"Do you want to run it again? ";
cin>>again;
}
return 0;
} // end of main function
int recursiveFactorial(int x)
{
if (x==0)//base case x=0
{
return 1;
}
else//recursive case OTHERWISE
{
return x* recursiveFactorial(x-1);
}
}//end of recursive factorial
int iterativeFactorial(int x)
{
int product=1;
for (int i=1; i<=x; i++)
{
product*=i;
}
return product;
}//end of iterativeFactorial
void determineEfficiency(double recur, double iter)
{
double diff=0;
diff=abs(recur-iter);
if (recur<iter)
{
cout<<"Recursion is more effective by "<<diff<<" sec"<<endl;
}
else if (recur>iter)
{
cout<<"Iteration is more effective by "<<diff<<" sec"<<endl;
}
else
{
cout<<"Neither one is more effective than the other"<<endl;
}
}//end of determineEfficiency
void input(int &x, long long int &trialRuns)
{
cout<<"Enter the number of trial runs ";
cin>>trialRuns;
cout<<"Enter the number to take factorial ";
cin>>x;
cout<<"Processing..."<<endl;
}//end of input
void output(int&x, long long int& trialRuns, double recur, double iter)
{
cout<<"*********************************************"<<endl;
cout<<"Trial Runs: "<<trialRuns<<endl;
cout<<"Number used: "<<x<<endl;
cout<<"Recursive version: "<<recur<<endl;
cout<<"Iterative version: "<<iter<<endl;
cout<<"*********************************************"<<endl;
}//end of output
|
6da71274b93a2358c25635efe3eb7e192e22a7f7 | c82a8cb017fa54b6027d66083884cb08b87f11b4 | /src/updateMeans.cpp | f9d2cbe3e13fdc1d21252cbb69a1871dc6a79f4c | [] | no_license | cran/bayesSurv | c2c2a04aa4ebf6b5b6beda2dbf9dd8c0ffb89aad | b8d092f388e2d110961c3951d167d7d76d3f3c7f | refs/heads/master | 2022-12-10T10:47:32.887146 | 2022-12-05T15:00:05 | 2022-12-05T15:00:05 | 17,694,605 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,302 | cpp | updateMeans.cpp | // Function to update the mixture means
// The components are updated using a Metropolis-Hastings step
// which is almost equal to the Gibbs move.
// The mixture means are sampled from their full conditionals (apart the factorial)
// and accepted provided the ordering is unchanged.
// 26/11/2003: start woking on it
// 14/03/2004: general mean of the random intercept allowed
// Assumption: input means (muM) are sorted in increasing order
// Remarks: * with mean of random intercept being a mean of the mixture, this mean must
// be recalculated after each mixture mean is updated
// * moreover, the full conditional distribution is somewhat more complex
// since also distribution of random effects must be taken into account
#include "updateMeans.h"
using namespace std;
// =======================================
//
// mixMomentM ..... mean and standard deviation of the error distribution
//
// INPUT PARAMETERS:
//
// regresResM ..... regression residuals (y - x'beta - z'b) (nP x 1)
// kP ............. current number of mixture components
// mixtureNM ...... numbers of observations belonging to each mixture component (at least kP x 1)
// invsigma2M ..... current mixture inverse variances (at least kP x 1)
// rM ............. current component pertinences (nP x 1)
// xiInvkappaP .... prior hyperparameter (mean * inverse variance)
// invkappaP ...... prior hyperparameter (inverse variance)
// nP ............. number of observations
//
void
updateMeans(double* muM, double* mixMomentM,
const double* regresResM, const double* betaM, const double* bM,
const covMatrix* Dcm,
const int* kP, const int* mixtureNM,
const double* wM, const double* invsigma2M, const List<int>* invrM,
const double* xiInvkappaP, const double* invkappaP,
const int* Eb0dependMix, const int* randomIntP,
const int* nP, const int* nclusterP, const int* nrandomP,
const int* indbinXA)
{
int i, j, obs;
double proposalMean, proposalSD, proposalmu;
double intcptadd = 0.0; // alpha[j] in my notes
double sumb0 = 0.0; // sum(b[i,0])
double sumW = 0.0; // sum(V[0,1]*(b[i] - gamma))
bool accept;
if ((*Eb0dependMix) && (*randomIntP)){
double* sumbmingamma = new double[*nrandomP - 1]; // sum(b[i] - gamma)
for (j = 1; j < *nrandomP; j++){
sumbmingamma[j] = -(*nclusterP)*betaM[indbinXA[j]];
}
for (i = 0; i < *nclusterP; i++){
sumb0 += bM[(*nrandomP)*i];
for (j = 1; j < *nrandomP; j++){
sumbmingamma[j] += bM[(*nrandomP)*i + j];
}
}
for (j = 1; j < *nrandomP; j++){ // sum(V[0,1] * (b[i] - gamma))
sumW += Dcm->icovm[j] * sumbmingamma[j - 1];
}
delete [] sumbmingamma;
}
for (j = 0; j < *kP; j++){
accept = false;
// Compute the mean and variance of the proposal distributions
proposalMean = 0.0;
if ((*Eb0dependMix) && (*randomIntP)) intcptadd = mixMomentM[0] - wM[j]*muM[j];
for (i = 0; i < invrM[j].length(); i++){
obs = invrM[j][i];
proposalMean += regresResM[obs] + intcptadd;
}
if ((*Eb0dependMix) && (*randomIntP)){
proposalSD = 1 / ((*invkappaP) + mixtureNM[j]*invsigma2M[j]*(1 - wM[j])*(1 - wM[j]) +
(*nclusterP)*wM[j]*wM[j]*Dcm->icovm[0]);
proposalMean *= (1 - wM[j])*invsigma2M[j];
proposalMean += (*xiInvkappaP) + wM[j]*Dcm->icovm[0]*(sumb0 - (*nclusterP)*intcptadd) +
wM[j]*sumW;
}
else{
proposalSD = 1 / ((*invkappaP) + mixtureNM[j] * invsigma2M[j]);
proposalMean *= invsigma2M[j];
proposalMean += (*xiInvkappaP);
}
proposalMean *= proposalSD;
proposalSD = sqrt(proposalSD);
// Sample and check the adjacency condition
// *kP == 1
// =========
if (*kP == 1){
proposalmu = rnorm(proposalMean, proposalSD);
muM[0] = proposalmu;
mixMoments(mixMomentM, kP, wM, muM, invsigma2M, false);
return;
}
// *kP >= 2
// =========
// j = 0 (only one neighbour on the right)
if (j == 0){
proposalmu = rnorm(proposalMean, proposalSD);
if (proposalmu < muM[1]) accept = true;
}
else{
// j = 1, ..., *kP - 2 (neighbours from both sides)
if (j < *kP - 1){
proposalmu = rnorm(proposalMean, proposalSD);
if (proposalmu > muM[j - 1] && proposalmu < muM[j + 1]) accept = true;
}
// j = *kP - 1 (only one neighbour on the left)
else{
proposalmu = rnorm(proposalMean, proposalSD);
if (proposalmu > muM[*kP - 2]) accept = true;
}
}
// Recalculate mean of the error if necessary
if (accept){
mixMomentM[0] += wM[j]*(proposalmu - muM[j]);
muM[j] = proposalmu;
}
} // end of the loop over mixture components
// Recalculate SD of the error
mixMoments(mixMomentM, kP, wM, muM, invsigma2M, true);
return;
} // end of function updateMeans
|
e159b79b71e22e745c94644677018509abb3db01 | 74359a77bc2ee4f4730d1bd9716fd3cea13fa54c | /src/execution/core/Finalize.h | 32449894af0d788b69a8bf3cbc4c1cc703f84c8f | [
"Apache-2.0"
] | permissive | Anewczs/nebula | 32c0d82e982a41886d3ea0d8d3d331b7e5c5a473 | f9bcd3c6df47c459712c1c30c5183873970182ae | refs/heads/master | 2022-04-23T00:01:30.514432 | 2020-04-18T00:46:56 | 2020-04-20T22:27:54 | 257,549,610 | 1 | 0 | null | 2020-04-21T09:47:01 | 2020-04-21T09:47:00 | null | UTF-8 | C++ | false | false | 1,063 | h | Finalize.h | /*
* Copyright 2017-present Shawn Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "execution/ExecutionPlan.h"
#include "surface/DataSurface.h"
/**
* A logic wrapper to return top sort cursors when sorting and limiting are present
*/
namespace nebula {
namespace execution {
namespace core {
// global phase will need to finalize some columns when fetching data
nebula::surface::RowCursorPtr finalize(nebula::surface::RowCursorPtr, const FinalPhase&);
} // namespace core
} // namespace execution
} // namespace nebula |
48e48d43e9652007f2438bd08058c8ea512313e9 | affa6e61c2b198c85857eac7fd6940dcb11cbf58 | /Source/PbrRenderer/RenderingPipeline.cpp | ea368843bbec0eddff9fa2187c689882937761cd | [] | no_license | acaly/PbrRenderer | 6b5cbb25c5854fa0aabca72efb33b8883d6ef459 | 0d8b49b732069c3754dbda1ba9b7b6be3a3e27fa | refs/heads/master | 2020-08-04T05:00:17.638673 | 2019-10-03T08:18:47 | 2019-10-03T08:18:47 | 212,015,560 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,233 | cpp | RenderingPipeline.cpp | #include "RenderingPipeline.h"
#include "RenderingSystem.h"
#include <d3dcompiler.h>
void PbrRenderer::RenderingPipeline::SetDefaultViewport()
{
D3D11_VIEWPORT vp[1] = { { 0.0f, 0.0f, float(renderingSystem->window_width), float(renderingSystem->window_height), 0, 1 } };
SetViewport(vp);
}
void PbrRenderer::RenderingPipeline::SetShaderFromFile(ShaderType shader, LPCWSTR filename)
{
ComPtr<ID3DBlob> buffer;
CheckComError(D3DReadFileToBlob(filename, buffer.GetAddressOf()));
switch (shader)
{
case ShaderType::Vertex:
CheckComError(renderingSystem->device->CreateVertexShader(buffer->GetBufferPointer(), buffer->GetBufferSize(), 0,
vertexShader.ReleaseAndGetAddressOf()));
CheckComError(renderingSystem->device->CreateInputLayout(inputLayoutDesc.data(), inputLayoutDesc.size(),
buffer->GetBufferPointer(), buffer->GetBufferSize(), inputLayout.ReleaseAndGetAddressOf()));
break;
case ShaderType::Geometry:
CheckComError(renderingSystem->device->CreateGeometryShader(buffer->GetBufferPointer(), buffer->GetBufferSize(), 0,
geometryShader.ReleaseAndGetAddressOf()));
break;
case ShaderType::Pixel:
CheckComError(renderingSystem->device->CreatePixelShader(buffer->GetBufferPointer(), buffer->GetBufferSize(), 0,
pixelShader.ReleaseAndGetAddressOf()));
break;
}
}
void PbrRenderer::RenderingPipeline::SetConstantBuffer(ShaderType shader, int i, ID3D11Buffer* buffer)
{
constantBuffers.push_back({ shader, i, buffer });
}
void PbrRenderer::RenderingPipeline::SetRasterizer(const D3D11_RASTERIZER_DESC& desc)
{
CheckComError(renderingSystem->device->CreateRasterizerState(&desc, rasterizer.ReleaseAndGetAddressOf()));
}
void PbrRenderer::RenderingPipeline::SetViewportInternal(const D3D11_VIEWPORT* vp, int count)
{
viewports.clear();
viewports.insert(viewports.end(), vp, vp + count);
}
void PbrRenderer::RenderingPipeline::SetInputLayoutInternal(const D3D11_INPUT_ELEMENT_DESC* desc, int count)
{
inputLayoutDesc.clear();
inputLayoutDesc.insert(inputLayoutDesc.end(), desc, desc + count);
}
void PbrRenderer::RenderingPipeline::Attach(ID3D11DeviceContext* dc)
{
dc->RSSetState(rasterizer.Get());
dc->RSSetViewports(viewports.size(), viewports.data());
dc->IASetInputLayout(inputLayout.Get());
dc->IASetPrimitiveTopology(topology);
dc->VSSetShader(vertexShader.Get(), 0, 0);
dc->GSSetShader(geometryShader.Get(), 0, 0);
dc->PSSetShader(pixelShader.Get(), 0, 0);
for (auto& k : constantBuffers)
{
switch (k.Shader)
{
case ShaderType::Vertex:
dc->VSSetConstantBuffers(k.Index, 1, k.Buffer.GetAddressOf());
break;
case ShaderType::Geometry:
dc->GSSetConstantBuffers(k.Index, 1, k.Buffer.GetAddressOf());
break;
case ShaderType::Pixel:
dc->PSSetConstantBuffers(k.Index, 1, k.Buffer.GetAddressOf());
break;
}
}
}
void PbrRenderer::RenderingPipeline::Detach(ID3D11DeviceContext* dc)
{
ID3D11Buffer* buffer = nullptr;
for (auto& k : constantBuffers)
{
switch (k.Shader)
{
case ShaderType::Vertex:
dc->VSSetConstantBuffers(k.Index, 1, &buffer);
break;
case ShaderType::Geometry:
dc->GSSetConstantBuffers(k.Index, 1, &buffer);
break;
case ShaderType::Pixel:
dc->PSSetConstantBuffers(k.Index, 1, &buffer);
break;
}
}
}
|
12e64f0ed24df5471a14f1b46a23c28894ac0b93 | 518c1ea218366df02c9d04c08a9944742a94339a | /codeforces/Codeforces Beta Round #11/A.cpp | cf732b6641cd717612e165362a4eff227901bcaa | [] | no_license | jhonber/Programming-Contest | 5b670d0e96263926e5d467c7b7c2434328c53c83 | c2aa60acd3ac55f9e58a610ac037b31f52236ad4 | refs/heads/master | 2021-01-24T12:52:39.569485 | 2020-03-13T01:24:32 | 2020-03-13T01:24:32 | 16,530,134 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,232 | cpp | A.cpp | // http://codeforces.com/contest/11/problem/A
using namespace std;
#include<algorithm>
#include<iostream>
#include<sstream>
#include<string>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<climits>
#include<cstring>
#include<cstdio>
#include<cmath>
#define PI acos(-1)
#define fr(i,j,n) for(int i=j;i<n;++i)
#define FR(i,n) fr(i,0,n)
#define foreach(x,v) for(typeof (v).begin() x = (v).begin(); x!= (v).end(); x++)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define D(x) cout<< #x " = "<<(x)<<endl
#define Dd(x) printf("#x = %lf\n", x)
#define Dbg if(1)
#define PB push_back
#define MAXN 1000
typedef long long int ll;
typedef vector<ll> vl;
typedef vector< string > vs;
typedef vector<int> vi;
typedef vector<int,int> vii;
typedef vector<vi> vvi;
typedef pair <int,int> pii;
typedef pair <string,string> pss;
typedef vector<pss> vpss;
typedef pair <double,double> pdd;
int main(){
int n,d,a,b;
cin >> n >> d;
cin >> a;
int ans = 0;
FR(i,n-1){
cin >> b;
if(a>b){
double x = ceil(((double)a - (double)b) / (double)d);
b += d*x;
ans += x;
}
if(a==b) {
b += d;
ans++;
}
a = b;
}
cout << ans << endl;
return 0;
} |
dce8c378804d72b6895fc0b8f34c53d7de041abc | c2c8846fcd657fcca735646792ec194ec1a8216a | /Space Invaders/Structs/Signal.h | 795d9678f90bd164a6c6f8703f6651cd319023db | [] | no_license | AlexeiKislinskii/SpaceInvaders | 96bc7331ea16deb6ead3621a33805727a48bd7cb | df67fa2bc3a02edbd805b2afbd2dfa0da3522c65 | refs/heads/master | 2021-08-29T08:43:47.626643 | 2017-12-13T15:57:25 | 2017-12-13T15:57:25 | 103,810,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,152 | h | Signal.h | #pragma once
#include <functional>
#include <map>
#include <vector>
//rework to https://stackoverflow.com/questions/7582546/using-generic-stdfunction-objects-with-member-functions-in-one-class
template <typename... Args>
class CSignal
{
public:
CSignal() : current_id(0), isEmitted(false) {}
// connects a member function to this Signal return index for further deleting
template <typename T>
int Connect(T *inst, void (T::*func)(Args...))
{
m_slots.insert(std::make_pair(++current_id, [=](Args... args) { (inst->*func)(args...); }));
return current_id;
}
void Disconnect(const int index)
{
m_IdForErase.push_back(index);
if (isEmitted)
return;
DisconnectInternal();
}
// calls all connected functions
void Emit(Args... p)
{
isEmitted = true;
for (auto it : m_slots) it.second(p...);
isEmitted = false;
DisconnectInternal();
}
private:
void DisconnectInternal()
{
for (auto i : m_IdForErase) m_slots.erase(i);
m_IdForErase.clear();
}
int current_id;
std::map<int, std::function<void(Args...)>> m_slots;
bool isEmitted;
std::vector<int> m_IdForErase;
}; |
b4c05d94c9f250ca994982bcdf96d7dacaafbce3 | ad18b25ebb1353112569449b96d45f0665319022 | /FFTTest.ino | 76498675c1c5d4fcddaa5a480c241dd7e562a3d3 | [] | no_license | OwenPi22/MASK_PROJECT | 3412375688e07ae198cf9c6dc5404e87a04705ec | c4dc3e4dc895af1b50147687ab4a49abb7b8e99e | refs/heads/master | 2022-12-16T02:41:17.654791 | 2020-09-18T03:48:44 | 2020-09-18T03:48:44 | 295,575,242 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,473 | ino | FFTTest.ino | #include "LedControl.h" // Library for controlling the led panel
LedControl lc=LedControl(12,11,10,2); // Setting up the led panel
#include "arduinoFFT.h" // Library for processing the input sound
#define SAMPLES 64 //Must be a power of 2
#define SAMPLING_FREQUENCY 800 //Hz, must be less than 10000 due to ADC
#define PIN 7 // Digital input pin for the sound sensor
int Analog_Pin = A0;
arduinoFFT FFT = arduinoFFT();
unsigned int sampling_period_us;
unsigned long microseconds;
double vReal[SAMPLES];
double vImag[SAMPLES];
void setup()
{
lc.shutdown(0,false);// turn off power saving, enables display
lc.setIntensity(0,15);// sets brightness (0~15 possible values)
lc.clearDisplay(0);// clear screen
lc.shutdown(1,false);// turn off power saving, enables display
lc.setIntensity(1,15);// sets brightness (0~15 possible values)
lc.clearDisplay(1);// clear screen
Serial.begin(115200);
sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));
}
void loop()
{
/*SAMPLING*/
for(int i=0; i<SAMPLES; i++)
{
microseconds = micros(); //Overflows after around 70 minutes!
vReal[i] = analogRead(0);
vImag[i] = 0;
while(micros() < (microseconds + sampling_period_us)){}
}
/*FFT*/
FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);
int count = 0;
for(int i=0; i<(SAMPLES/2); i++)
{
/*View all these three lines in serial terminal to see which frequencies has which amplitudes*/
if((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES >= 150 && (i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES < 350)
{
colorCol(count, (vReal[i]-20) / 50);
count++;
}
}
}
void colorCol(int col, int n)
{
if(col < 8) // Control for the first 8x8 panel
{
for(int i = 0; i < 8; i++)
{
if(i >= 4 - n && i <= 3 + n) // Lighting for middle +/- n
{
lc.setLed(1, i, col, true);
}
else
{
lc.setLed(1, i, col, false);
}
}
}
else // Control for second panel
{
for(int i = 0; i < 8; i++)
{
if(i >= 4 - n && i <= 3 + n)
{
lc.setLed(0, i, col - 8, true);
}
else
{
lc.setLed(0, i, col - 8, false);
}
}
}
}
|
ee945d22638c50db28d11cc21fe7c354d16ed6f0 | 1cb93ce35651d1352587b50f9f3be94d6053d94a | /services/audiopolicy/engineconfigurable/src/EngineInstance.cpp | b127796c339bc791234c080bb8ddad496dd1d9c2 | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | LineageOS/android_frameworks_av | 7a685135784cd7dfad88c524acb7044cab188db5 | be311717b151597a000cf3435812c56f915f2f4c | refs/heads/lineage-19.1 | 2023-07-25T06:37:24.324351 | 2023-05-11T00:26:30 | 2023-07-07T12:58:22 | 75,639,894 | 26 | 628 | NOASSERTION | 2022-10-02T20:13:57 | 2016-12-05T15:41:27 | C++ | UTF-8 | C++ | false | false | 1,676 | cpp | EngineInstance.cpp | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <EngineInterface.h>
#include <AudioPolicyPluginInterface.h>
#include "AudioPolicyEngineInstance.h"
#include "Engine.h"
using std::string;
namespace android {
namespace audio_policy {
EngineInstance::EngineInstance()
{
}
EngineInstance *EngineInstance::getInstance()
{
static EngineInstance instance;
return &instance;
}
EngineInstance::~EngineInstance()
{
}
Engine *EngineInstance::getEngine() const
{
static Engine engine;
return &engine;
}
template <>
EngineInterface *EngineInstance::queryInterface() const
{
return getEngine()->queryInterface<EngineInterface>();
}
template <>
AudioPolicyPluginInterface *EngineInstance::queryInterface() const
{
return getEngine()->queryInterface<AudioPolicyPluginInterface>();
}
} // namespace audio_policy
extern "C" EngineInterface* createEngineInstance()
{
return audio_policy::EngineInstance::getInstance()->queryInterface<EngineInterface>();
}
extern "C" void destroyEngineInstance(EngineInterface*)
{
// The engine is a singleton.
}
} // namespace android
|
d161e5a87e149470aca2d87d8d47457ee26ee828 | d334ee8ac9e7b4b54f268b9f7e9facc0bb2efafe | /DesktopLiveStreaming/RingCacheBuffer.h | 638e6f6df61ce19f97d7f394e86e00a2082dff84 | [] | no_license | daveamato/DesktopLiveStreaming | ee26cac5d97e9863a87f98b8b0c62dedff989468 | b845e5312aea043e5dd086011743a40eb378abee | refs/heads/master | 2022-11-17T05:41:23.733904 | 2020-07-14T00:39:03 | 2020-07-14T00:39:03 | 279,435,189 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,445 | h | RingCacheBuffer.h | #pragma once
#include "AppContext.h"
#include "FLVhelp.h"
#define DefaultItemSize (4*1024)
#define rcb_lock_value (4)
enum TagType {
VideoTag,
AudioTag,
ScriptTag,
OtherTag
};
typedef struct _RCBItem {
TagType tagType;
bool isKeyFrame;
char tag_body_default[DefaultItemSize];//4kb默认
char *tag_body_big;//
bool tag_body_isbig;
size_t tag_body_length;
char flv_tag_header[20];// size 11+9固定大小 11是tag头 9是视频头 音频也用这个字段
char *flv_tag_real;//主要是h264的偏移量,真正的数据地址,比如跳过了h264nal的 00 00 00 01
size_t flv_tag_real_length;//跳过之后的数据长度
QWORD compositionTime;
QWORD timems;
_RCBItem* next;
volatile int index;
}RCBItem;
typedef struct FlvTagHeader
{
char data[12];// size 11固定大小
WSABUF wsabuf;
};
class RingCacheBuffer
{
public:
//
RingCacheBuffer(int ringLength);
~RingCacheBuffer();
void overlay_video(bool isKeyFrame, char *data, int length, DWORD timems, int compositionTime);
void overlay_audio(char *data, int length, DWORD timems);
friend class FlvLiveStream;
friend class HLS_Server;
private:
HANDLE new_event;
int RingLength;
volatile RCBItem* LastWrite;//用于实际选择写入
volatile RCBItem* ReadLastWrite;//用于读取上次写入
RCBItem* items;
RCBItem* lastKeyFrame;//上个关键帧
CRITICAL_SECTION overlay_cs;
app_atomic_lock_t lock_t;
volatile unsigned int tag_index;
}; |
4c3ca6ed6b4b12fce89c889ef95df8c139df028b | 2e0a6fd5767ee4551d370f682910702be9095d73 | /Base/Numerics/tubeSplineApproximation1D.cxx | 0bc3169c983be51bfe420c8dad9b99a23ef574d1 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | LucasGandel/TubeTK | ee0ce6a378aab732a3ee051ecd2ea36332d4943a | 50682d4d8b30b0392575685e11e16a1086790bc8 | refs/heads/master | 2021-01-18T09:29:06.802793 | 2016-01-30T04:11:39 | 2016-01-30T04:11:39 | 40,605,754 | 1 | 1 | null | 2015-08-12T14:39:59 | 2015-08-12T14:39:59 | null | UTF-8 | C++ | false | false | 5,145 | cxx | tubeSplineApproximation1D.cxx | /*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "tubeSplineApproximation1D.h"
namespace tube
{
SplineApproximation1D
::SplineApproximation1D( void )
: Spline1D()
{
m_SplineApproximation1DMatrixConst = (double)(1.0/6.0);
m_SplineApproximation1DMatrix(0, 0) = 1;
m_SplineApproximation1DMatrix(0, 1) = 0;
m_SplineApproximation1DMatrix(0, 2) = 0;
m_SplineApproximation1DMatrix(0, 3) = 0;
m_SplineApproximation1DMatrix(1, 0) = -3;
m_SplineApproximation1DMatrix(1, 1) = 3;
m_SplineApproximation1DMatrix(1, 2) = 3;
m_SplineApproximation1DMatrix(1, 3) = 1;
m_SplineApproximation1DMatrix(2, 0) = 3;
m_SplineApproximation1DMatrix(2, 1) = -6;
m_SplineApproximation1DMatrix(2, 2) = 0;
m_SplineApproximation1DMatrix(2, 3) = 4;
m_SplineApproximation1DMatrix(3, 0) = -1;
m_SplineApproximation1DMatrix(3, 1) = 3;
m_SplineApproximation1DMatrix(3, 2) = -3;
m_SplineApproximation1DMatrix(3, 3) = 1;
}
SplineApproximation1D
::SplineApproximation1D( ValueFunctionType::Pointer funcVal,
Optimizer1D::Pointer optimizer1D )
: Spline1D(funcVal, optimizer1D)
{
m_SplineApproximation1DMatrixConst = (double)(1.0/6.0);
m_SplineApproximation1DMatrix(0, 0) = 1;
m_SplineApproximation1DMatrix(0, 1) = 0;
m_SplineApproximation1DMatrix(0, 2) = 0;
m_SplineApproximation1DMatrix(0, 3) = 0;
m_SplineApproximation1DMatrix(1, 0) = -3;
m_SplineApproximation1DMatrix(1, 1) = 3;
m_SplineApproximation1DMatrix(1, 2) = 3;
m_SplineApproximation1DMatrix(1, 3) = 1;
m_SplineApproximation1DMatrix(2, 0) = 3;
m_SplineApproximation1DMatrix(2, 1) = -6;
m_SplineApproximation1DMatrix(2, 2) = 0;
m_SplineApproximation1DMatrix(2, 3) = 4;
m_SplineApproximation1DMatrix(3, 0) = -1;
m_SplineApproximation1DMatrix(3, 1) = 3;
m_SplineApproximation1DMatrix(3, 2) = -3;
m_SplineApproximation1DMatrix(3, 3) = 1;
}
SplineApproximation1D
::~SplineApproximation1D( void )
{
}
double
SplineApproximation1D
::DataValue( const VectorType & y, double x )
{
double u[4];
u[3] = 1.0;
u[2] = x-(int)x;
u[1] = u[2]*u[2];
u[0] = u[1]*u[2];
double s = 0;
for(unsigned int i=0; i<4; i++)
{
double b = 0;
for(unsigned int p=0; p<4; p++)
{
b += m_SplineApproximation1DMatrix(i, p) * u[p];
}
s += y(3-i) * b * m_SplineApproximation1DMatrixConst;
}
return s;
}
double
SplineApproximation1D
::DataValueD( const VectorType & y, double x )
{
double u[3];
u[2] = 1.0;
u[1] = x-(int)x;
u[0] = u[1]*u[1];
double s = 0;
for(unsigned int i=0; i<4; i++)
{
double b = 0;
for(unsigned int p=0; p<3; p++)
{
b += (3-p)*m_SplineApproximation1DMatrix(i, p) * u[p];
}
s += y(3-i) * b * m_SplineApproximation1DMatrixConst;
}
return s;
}
double
SplineApproximation1D
::DataValueD2( const VectorType & y, double x )
{
double u[2];
u[1] = 1.0;
u[0] = x-(int)x;
double s = 0;
for(unsigned int i=0; i<4; i++)
{
double b = 0;
for(unsigned int p=0; p<2; p++)
{
b += (2-p) * m_SplineApproximation1DMatrix(i, p) * u[p];
}
s += y(3-i) * b * m_SplineApproximation1DMatrixConst;
}
return s;
}
double
SplineApproximation1D
::DataValueJet( const VectorType & y, double x, double * d, double * d2 )
{
double u[4];
u[3] = 1.0;
u[2] = x-(int)x;
u[1] = u[2]*u[2];
u[0] = u[1]*u[2];
double s = 0;
*d = 0;
*d2 = 0;
for(unsigned int i=0; i<4; i++)
{
double b = 0;
double bD = 0;
double bD2 = 0;
for(unsigned int p=0; p<4; p++)
{
b += m_SplineApproximation1DMatrix(i, p) * u[p];
}
for(unsigned int p=0; p<3; p++)
{
bD += (3-p) * m_SplineApproximation1DMatrix(i, p) * u[p+1];
}
for(unsigned int p=0; p<2; p++)
{
bD2 += (2-p) * m_SplineApproximation1DMatrix(i, p) * u[p+2];
}
s += y(3-i) * b * m_SplineApproximation1DMatrixConst;
*d += y(3-i) * bD * m_SplineApproximation1DMatrixConst;
*d2 += y(3-i) * bD2 * m_SplineApproximation1DMatrixConst;
}
return s;
}
void
SplineApproximation1D
::PrintSelf( std::ostream & os, Indent indent ) const
{
this->Superclass::PrintSelf( os, indent );
os << indent << "SplineApproximation1DMatrixConst: "
<< m_SplineApproximation1DMatrixConst << std::endl;
os << indent << "SplineApproximation1DMatrix: "
<< m_SplineApproximation1DMatrix << std::endl;
}
} // End namespace tube
|
2accb820c8be00b5f330b8f1e0a838ab10c7a5b5 | 97661a4740b6e33148df5aa0a5bd2abd2cac5a8d | /Matrix.h | d7c0e8ad2fc96769189bb70035b411ebf4742682 | [] | no_license | ycHepth/MatrixCalculate | a208edca6c8d91267a4df018dd196b800a64b198 | 8984685bbbb95b7bd528def2daa84609d146cdbc | refs/heads/master | 2022-12-10T12:02:41.494679 | 2020-09-18T08:16:55 | 2020-09-18T08:16:55 | 294,955,992 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,112 | h | Matrix.h | //
// Created by azurec on 2020/9/12.
//
#ifndef MATRIXCALCULATE_MATRIX_H
#define MATRIXCALCULATE_MATRIX_H
#include "Array.h"
/**
* generate identical matrix (eye in MATLAB)
* @param n
* @param m
* @return
*/
Matrix<double> EyeMatrix(const unsigned int n, const unsigned int m);
/**
* generate zero matrix
* @param n
* @param m
* @return
*/
Matrix<double> ZeroMatrix(const unsigned int n, const unsigned int m);
/**
* transfer column vector to row vector
* @param v
* @return
*/
Matrix<double> transposeVector(const Vector<double> &v);
/**
* get power of square matrix
* @param m
* @param n
* @return
*/
Matrix<double> exp(const Matrix<double>&m, unsigned int n);
/**
* get power sequence of specified square matrix
* @param a
* @param n
* @return
*/
std::vector<Matrix<double>> get_powers(const Matrix<double> a, int n);
/**
* extend matrix with large dimensions. the inner function declared in Matrix class
* @param m : operated matrix
* @param r : extended rows
* @param c : extended cols
*/
void extend_matrix(Matrix<double> &m, unsigned int r, unsigned int c);
/**
* set
* @param a : Target Vector
* @param b : Origin Vector
* @param pos : the start position of overwriting.
*/
void set_subvector(Vector<double> &a, const Vector<double> &b, unsigned int pos);
/**
* set submatrix
* @param dst : Target Matrix
* @param src : Origin Matrix
* @param row : start point of rows
* @param col : start point of cols
*/
void set_submatrix(Matrix<double> &dst, const Matrix<double> &src, int row,
int col);
/**
* extend vector with large dimensions.
* @param v
* @param n
*/
void extend_vector(Vector<double> &v, int n);
/**
* bind compatible matrices in rows
* @param a : matrix one
* @param b : matrix two
* @return : bind matrix
*/
Matrix<double> bind_matrices(const Matrix<double> &a, const Matrix<double> &b);
/**
* bind vector in rows
* @param a : matrix one
* @param b : matrix two
* @return : bind vector
*/
Vector<double> bind_vectors(const Vector<double> &a, const Vector<double> &b);
#endif //MATRIXCALCULATE_MATRIX_H
|
67dc248a01bc376ab7a95c4fb1fcef7e6b9bcb9b | 8aa9a970895b0b2cf639f75738e33b0a4487208e | /Utils/print.cpp | 16460b0ff2f579bdcbc08cf9a1a545174e080941 | [] | no_license | VladAdGad/leetcode-solutions | 09d24c3cdd1f95ea45746a67a71ebfb944933152 | 0431f983ab86a53b5a22dc9deca62746c877e7e7 | refs/heads/master | 2023-01-30T16:14:37.235018 | 2020-12-11T19:24:45 | 2020-12-11T19:24:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 779 | cpp | print.cpp | #include <vector>
#include <string>
#include <iterator>
#include <sstream>
#include "print.h"
std::string print(const std::vector<int> &cont) {
std::stringstream result;
std::copy(cont.begin(), cont.end(), std::ostream_iterator<int>(result, " "));
return result.str();
}
std::string print(const std::vector<char> &cont) {
std::string result;
for (char c : cont) {
result.push_back(c);
result.push_back(' ');
}
return result;
}
std::string print(const std::vector<std::vector<int>> &cont) {
std::string result;
std::string separator = " ";
for (const auto &i: cont) {
for (const auto j : i) {
result += std::to_string(j) + separator;
}
result += "\n";
}
return result;
}
|
cd7be5a82bae26e723a8ce044b6b82bd140a4fe5 | 0daf0d997653db5759d5bd98308bad08a994b220 | /src/rpc/util.h | 073a520ef130e1daba8f5b306a87211df3cf5e03 | [
"MIT"
] | permissive | dim4egster/btcu_coderev | 5e5dbdbc4434f23b92d6322348e88af6c49f931d | 75daa1a8ab6010c93939f8bdd6d71101fbc58c48 | refs/heads/main | 2023-02-28T08:40:27.318343 | 2021-02-03T14:47:31 | 2021-02-03T15:02:09 | 322,042,518 | 0 | 0 | MIT | 2021-02-02T22:31:39 | 2020-12-16T16:39:35 | C++ | UTF-8 | C++ | false | false | 1,141 | h | util.h | // Copyright (c) 2017-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_RPC_UTIL_H
#define BITCOIN_RPC_UTIL_H
//#include <node/transaction.h>
//#include <outputtype.h>
#include <univalue.h>
#include <string>
#include <vector>
#include <boost/variant.hpp>
/** Wrapper for UniValue::VType, which includes typeAny:
* Used to denote don't care type. */
struct UniValueType {
UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
UniValueType() : typeAny(true) {}
bool typeAny;
UniValue::VType type;
};
/**
* Utilities: convert hex-encoded Values
* (throws error if not hex).
*/
extern uint256 ParseHashV(const UniValue& v, std::string strName);
extern uint256 ParseHashO(const UniValue& o, std::string strKey);
extern std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName);
extern std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey);
extern CAmount AmountFromValue(const UniValue& value);
#endif // BITCOIN_RPC_UTIL_H
|
ddd40693611ae4bd22de168019300b2a6c6fd016 | a7ec24767a4b9224a9f8fa69c71f90686a7c5bc0 | /TestProject/TestProject.cpp | f4bf8220c3b890fac18bda57a2a2eb679a34f7a1 | [] | no_license | LastStranger0/Huffman | e6e5c143344ad9008f4b1cb6a6284a6a8538229c | e557fa13b14fbdba8f3062d04caf38d02e9c67c1 | refs/heads/master | 2022-09-04T07:16:34.725370 | 2020-05-25T14:35:04 | 2020-05-25T14:35:04 | 265,379,777 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 137 | cpp | TestProject.cpp | #include <iostream>
#include <string>
#include "Huffman.h"
using namespace std;
int main()
{
string m;
cin >> m;
Huffman t(m);
}
|
7024002e67b1fe15acb518a1de34777f04f10df7 | 0283d03497e279266d48ff4deccc50379b0d2636 | /submission/lut.h | 74dcddc18e895bed36831aeb759d6df085de4b6f | [] | no_license | rainzhao2000/image-processing | 7e259c6f351870bcc669af4c3130d63b470d92bf | 1fe8efdd06e41662013716cc1a1ac82b1a8ed042 | refs/heads/master | 2020-12-21T21:37:53.241451 | 2020-01-27T23:41:04 | 2020-01-27T23:41:04 | 236,570,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 218 | h | lut.h | #ifndef _LUT_H_
#define _LUT_H_
#include "image.h"
#include "decorator.h"
#include "ppm.h"
class LutImage final: public Decorator {
public:
LutImage(Image *image);
void render(PPM &ppm) override;
};
#endif
|
16c5f59ef66c13cc0ef57f4df64d87d32f3c9a65 | 442927f3e6417b5a6e658c5d580d4ce317d978b4 | /NESulator/APU.h | 84397ed8cc8285b345a26451e157220c8a261871 | [] | no_license | miniragnarok/NESulator | b91dfd5bfc2dbef7e4872e487c74a5a55694c8c3 | f07850d4f11d22f58691d563960ea7a8dba8cf48 | refs/heads/master | 2020-07-16T00:29:59.481312 | 2019-09-05T01:36:00 | 2019-09-05T01:36:00 | 205,681,103 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29 | h | APU.h | #pragma once
class APU
{
};
|
f769b5745fdcfb1345a407ba6f24ba2c9d959ea5 | a0fd12ceeedc38266bb04d64dc2f3124f2b2ab0a | /string/charstring.cpp | 945f7e84f48cce8cb0d8747596cb154ad8004b53 | [] | no_license | LukianovVS/rinex_change_meas | 08c4b90800347432ecaa79fe0a4790017e0aeffe | b16cef0bdd3e23dfa46e932bf4f2b67025a95f3d | refs/heads/master | 2020-04-29T12:26:52.530114 | 2019-05-08T12:26:53 | 2019-05-08T12:26:53 | 176,137,953 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 751 | cpp | charstring.cpp | #include "charstring.h"
#include <cmath>
double str2float(char str[], int N, int *flag_empty)
{
double x = 0;
double sign = 1;
int j = 0;
int fp = 0;
int counter_space = 0;
for (int k = 0; k < N; k++)
{
if (fp)
j++;
if (str[k] == ' ')
counter_space ++;
else if (str[k] == '-')
sign = -1;
else if( str[k] == '.')
fp = 1;
else
x = x*10 + (str[k] - '0');
}
if (flag_empty && counter_space == N)
*flag_empty = 1;
return sign * x / pow(10, j);
}
int str2int(char str[], int N)
{
int x = 0;
for (int k = 0; k < N; k++)
{
if (str[k] == ' ')
continue;
else
x = x * 10 + (str[k] - '0');
}
return x;
}
|
687596347c79cbd08edd20395159c1a6ec4cb41d | b9a095298633b4e838e5ed500652f85d7ce35c63 | /MFCPixel/PointLight.h | 4a76db4841751efa23905b61ba4b71dac75ff8c6 | [] | no_license | elephant1334/raytracer | 746754853520f04f36722c63006678ba3b48c362 | f24d56f62d9ca50bcf67b78f82a740285d6e8a15 | refs/heads/master | 2021-01-17T12:09:08.346600 | 2014-12-22T01:16:21 | 2014-12-22T01:16:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,296 | h | PointLight.h | #ifndef __POINT_LIGHT__
#define __POINT_LIGHT__
#include "Light.h"
#include "Vector3D.h"
#include "RGBColor.h"
#include "World.h"
#include "ShadeRec.h"
class PointLight:public Light{
public:
PointLight();
PointLight(const PointLight& pl);
virtual Light* clone() const;
PointLight& operator=(const PointLight& rhs);
virtual ~PointLight();
void scale_radiance(const float b);
void set_color(const float c);
void set_color(const RGBColor& c);
void set_color(const float r,const float g,const float b);
void set_location(Vector3D d);
void set_location(float dx,float dy,float dz);
virtual Vector3D get_direction(ShadeRec& sr);
virtual RGBColor L(ShadeRec& sr);
bool in_shadow(const Ray& ray,const ShadeRec& sr)const;
private:
float ls;
RGBColor color;
Vector3D location;
};
inline void PointLight::scale_radiance(const float b){
ls=b;
}
inline void PointLight::set_color(const float c){
color.r=c;color.g=c;color.b=c;
}
inline void PointLight::set_color(const RGBColor& c){
color=c;
}
inline void PointLight::set_color(const float r,const float g,const float b){
color.r=r;color.g=g;color.b=b;
}
inline void PointLight::set_location(Vector3D d){
location = d;
}
inline void PointLight::set_location(float dx,float dy,float dz){
location.x=dx;location.y=dy;location.z=dz;
}
#endif |
892f16646e1e5ba0ee6032c5480fcda355ef7938 | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-clouddirectory/source/model/GetObjectInformationRequest.cpp | af42ef4c02e81e469f40ffd68736b5ab1dd59c59 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 1,396 | cpp | GetObjectInformationRequest.cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/clouddirectory/model/GetObjectInformationRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::CloudDirectory::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
GetObjectInformationRequest::GetObjectInformationRequest() :
m_directoryArnHasBeenSet(false),
m_objectReferenceHasBeenSet(false),
m_consistencyLevel(ConsistencyLevel::NOT_SET),
m_consistencyLevelHasBeenSet(false)
{
}
Aws::String GetObjectInformationRequest::SerializePayload() const
{
JsonValue payload;
if(m_objectReferenceHasBeenSet)
{
payload.WithObject("ObjectReference", m_objectReference.Jsonize());
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection GetObjectInformationRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
Aws::StringStream ss;
if(m_directoryArnHasBeenSet)
{
ss << m_directoryArn;
headers.emplace("x-amz-data-partition", ss.str());
ss.str("");
}
if(m_consistencyLevelHasBeenSet)
{
headers.emplace("x-amz-consistency-level", ConsistencyLevelMapper::GetNameForConsistencyLevel(m_consistencyLevel));
}
return headers;
}
|
28cf7442870f1175793dd3d2e25fc015ad4010cd | 0304b94fb4bc4682c4d5e25bb65dab2c7e9f324f | /Code/Source/sv/Geometry/sv_sys_geom.cxx | 2d9cc5d230f0d046d1452eda6d8d81b9d4e46669 | [
"MIT"
] | permissive | SimVascular/SimVascular | 205126a3483079a9744d74bbef05112da0dbcc24 | edd1fc7c26cf9550594a7362d66bb5d0fadda4d9 | refs/heads/master | 2023-08-04T10:48:30.886728 | 2023-08-03T02:40:08 | 2023-08-03T02:40:08 | 41,169,947 | 228 | 140 | NOASSERTION | 2023-08-03T02:40:10 | 2015-08-21T18:01:19 | C++ | UTF-8 | C++ | false | false | 119,769 | cxx | sv_sys_geom.cxx | /* Copyright (c) Stanford University, The Regents of the University of
* California, and others.
*
* All Rights Reserved.
*
* See Copyright-SimVascular.txt for additional details.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "SimVascular.h"
#include <stdio.h>
#include <assert.h>
#include <map>
#include <math.h>
#include "sv_sys_geom.h"
#include "sv_VTK.h"
#include "sv_vtk_utils.h"
#include "sv_misc_utils.h"
#include "sv_ggems.h"
#include "sv_Math.h"
#include "sv_SolidModel.h"
#include "vtkSmartPointer.h"
#include "vtkSortDataArray.h"
#include "vtkPolygon.h"
#include "vtkThreshold.h"
#include "vtkConnectivityFilter.h"
#include "vtkDataSetSurfaceFilter.h"
#include "vtkAppendPolyData.h"
#include "vtkOBBTree.h"
#include "vtkSVFindSeparateRegions.h"
#include "vtkSVGetSphereRegions.h"
#include "vtkSVLoftSplineSurface.h"
#include "vtkSVConstrainedSmoothing.h"
#include "vtkSVConstrainedBlend.h"
#include "vtkSVLocalButterflySubdivisionFilter.h"
#include "vtkSVLocalLinearSubdivisionFilter.h"
#include "vtkSVLocalLoopSubdivisionFilter.h"
#include "vtkSVLocalSmoothPolyDataFilter.h"
#include "vtkSVLocalQuadricDecimation.h"
#include "vtkSVLoopBooleanPolyDataFilter.h"
#include "vtkSVLoopIntersectionPolyDataFilter.h"
#include "vtkSVLoftNURBSSurface.h"
#include "vtkSVMultiplePolyDataIntersectionFilter.h"
#include "vtkSVNURBSSurface.h"
#include "sv_polydatasolid_utils.h"
#define vtkNew(type,name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
/* ----------------- */
/* sys_geom_DeepCopy */
/* ----------------- */
cvPolyData *sys_geom_DeepCopy( cvPolyData *src )
{
cvPolyData *dst;
vtkPolyData *srcPd = src->GetVtkPolyData();
vtkPolyData *pd;
vtkPoints *pts;
vtkCellArray *verts, *lines, *polys, *strips;
pts = VtkUtils_DeepCopyPoints( srcPd->GetPoints() );
if ( pts == NULL ) {
return NULL;
}
verts = VtkUtils_DeepCopyCells( srcPd->GetVerts() );
lines = VtkUtils_DeepCopyCells( srcPd->GetLines() );
polys = VtkUtils_DeepCopyCells( srcPd->GetPolys() );
strips = VtkUtils_DeepCopyCells( srcPd->GetStrips() );
pd = vtkPolyData::New();
pd->SetPoints( pts );
pd->SetVerts( verts );
pd->SetLines( lines );
pd->SetPolys( polys );
pd->SetStrips( strips );
pts->Delete();
verts->Delete();
lines->Delete();
polys->Delete();
strips->Delete();
pd->GetPointData()->DeepCopy( srcPd->GetPointData() );
pd->GetCellData()->DeepCopy( srcPd->GetCellData() );
dst = new cvPolyData( pd );
pd->Delete();
return dst;
}
/* ----------------- */
/* sys_geom_MergePts */
/* ----------------- */
cvPolyData *sys_geom_MergePts( cvPolyData *src )
{
double tol = 1e10 * FindMachineEpsilon();
return sys_geom_MergePts_tol( src, tol );
}
/* --------------------- */
/* sys_geom_MergePts_tol */
/* --------------------- */
cvPolyData *sys_geom_MergePts_tol( cvPolyData *src, double tol )
{
cvPolyData *dst;
vtkCleanPolyData *merge = vtkCleanPolyData::New();
merge->SetTolerance( tol );
// merge->ConvertLinesToPointsOn(); // new method as of vtk 3.2.0
merge->SetInputDataObject( src->GetVtkPolyData() );
merge->Update();
dst = new cvPolyData( merge->GetOutput() );
merge->Delete();
return dst;
}
/* ----------------------------- */
/* sys_geom_NumClosedLineRegions */
/* ----------------------------- */
int sys_geom_NumClosedLineRegions( cvPolyData *src, int *num )
{
cvPolyData *merged_pd;
vtkPolyData *pd;
int numPts;
double *pts;
vtkIdType *lines;
int numLines;
int *startIxs;
int numRegions;
merged_pd = sys_geom_MergePts( src );
if ( merged_pd == NULL ) {
return SV_ERROR;
}
pd = merged_pd->GetVtkPolyData();
if ( VtkUtils_GetPoints( pd, &pts, &numPts ) != SV_OK ) {
printf("ERR: VtkUtils_GetPoints failed\n");
delete merged_pd;
return SV_ERROR;
}
if ( VtkUtils_GetLines( pd, &lines, &numLines ) != SV_OK ) {
printf("ERR: VtkUtils_GetLines failed\n");
delete merged_pd;
delete [] pts;
return SV_ERROR;
}
if ( VtkUtils_FindClosedLineRegions( lines, numLines, numPts,
&startIxs, &numRegions ) != SV_OK ) {
printf("ERR: VtkUtils_FindClosedLineRegions failed\n");
delete merged_pd;
delete [] pts;
delete [] lines;
return SV_ERROR;
}
*num = numRegions;
delete merged_pd;
delete [] pts;
delete [] lines;
return SV_OK;
}
/* ---------------------------- */
/* sys_geom_GetClosedLineRegion */
/* ---------------------------- */
int sys_geom_GetClosedLineRegion( cvPolyData *src, int id, cvPolyData **dst )
{
cvPolyData *merged_pd;
vtkPolyData *pd;
vtkPolyData *tmp = NULL;
int numPts;
double *pts;
vtkIdType *lines;
int numLines;
int *startIxs;
int numRegions;
int *regionLines;
int numRegionLines;
int status = SV_ERROR;
merged_pd = sys_geom_MergePts( src );
if ( merged_pd == NULL ) {
return SV_ERROR;
}
pd = merged_pd->GetVtkPolyData();
if ( VtkUtils_GetPoints( pd, &pts, &numPts ) != SV_OK ) {
printf("ERR: VtkUtils_GetPoints failed\n");
return SV_ERROR;
}
if ( VtkUtils_GetLines( pd, &lines, &numLines ) != SV_OK ) {
printf("ERR: VtkUtils_GetLines failed\n");
delete [] pts;
return SV_ERROR;
}
if ( VtkUtils_FindClosedLineRegions( lines, numLines, numPts,
&startIxs, &numRegions ) != SV_OK ) {
printf("ERR: VtkUtils_FindClosedLineRegions failed\n");
delete [] pts;
delete [] lines;
return SV_ERROR;
}
if ( ( id < 0 ) || ( id >= numRegions ) ) {
printf("ERR: region id [%d] out of range\n", id);
delete [] pts;
delete [] lines;
delete [] startIxs;
return SV_ERROR;
}
if ( VtkUtils_GetClosedLineRegion( lines, numLines, startIxs[id],
®ionLines, &numRegionLines )
!= SV_OK ) {
printf("ERR: VtkUtils_GetClosedLineRegion failed\n");
delete [] pts;
delete [] lines;
delete [] startIxs;
return SV_ERROR;
}
if ( VtkUtils_MakePolyDataFromLineIds( pts, numPts, lines, regionLines,
numRegionLines, &tmp ) != SV_OK ) {
printf("ERR: VtkUtils_MakePolyDataFromLineIds failed\n");
delete [] pts;
delete [] lines;
delete [] startIxs;
delete [] regionLines;
return SV_ERROR;
}
(*dst) = new cvPolyData( tmp );
delete [] pts;
delete [] lines;
delete [] startIxs;
delete [] regionLines;
tmp->Delete();
return SV_OK;
}
/* ------------- */
/* sys_geom_Pick */
/* ------------- */
int sys_geom_Pick( cvPolyData *src, double pos[], cvPolyData **dst )
{
cvPolyData *merged_pd = NULL;
vtkPolyData *pd = NULL;
vtkPolyData *tmp = NULL;
cvPolyData *tmpPd = NULL;
int numPts;
double *pts = NULL;
vtkIdType *lines = NULL;
int numLines;
int *startIxs = NULL;
int numRegions;
int *regionLines = NULL;
int numRegionLines;
int i, classification;
int status = SV_ERROR;
cvSolidModel *solid = NULL;
int foundOne = 0;
solid = cvSolidModel::DefaultInstantiateSolidModel();
if ( solid == NULL ) {
printf("ERR: default instantiate solid model failed\n");
return SV_ERROR;
}
merged_pd = sys_geom_MergePts( src );
if ( merged_pd == NULL ) {
printf("ERR: merge points failed failed\n");
return SV_ERROR;
}
pd = merged_pd->GetVtkPolyData();
if ( VtkUtils_GetPoints( pd, &pts, &numPts ) != SV_OK ) {
printf("ERR: VtkUtils_GetPoints failed\n");
return SV_ERROR;
}
if ( VtkUtils_GetLines( pd, &lines, &numLines ) != SV_OK ) {
printf("ERR: VtkUtils_GetLines failed\n");
delete [] pts;
return SV_ERROR;
}
if ( VtkUtils_FindClosedLineRegions( lines, numLines, numPts,
&startIxs, &numRegions ) != SV_OK ) {
printf("ERR: VtkUtils_FindClosedLineRegions failed\n");
delete [] pts;
delete [] lines;
return SV_ERROR;
}
// Now, foreach closed region, get an ordered list of segments,
// create the corresponding solid, and check for point
// classification of the given pos.
printf(" ------ sys_geom_Pick ------\n");
printf(" >>>>>> num closed regions [%d]\n", numRegions);
for (i = 0; i < numRegions; i++) {
if ( VtkUtils_GetClosedLineRegion( lines, numLines, startIxs[i],
®ionLines, &numRegionLines )
!= SV_OK ) {
printf("ERR: VtkUtils_GetClosedLineRegion failed\n");
delete [] pts;
delete [] lines;
delete [] startIxs;
return SV_ERROR;
}
if ( tmp != NULL ) {
tmp->Delete();
tmp = NULL;
}
if ( VtkUtils_MakePolyDataFromLineIds( pts, numPts, lines, regionLines,
numRegionLines, &tmp ) != SV_OK ) {
printf("ERR: VtkUtils_MakePolyDataFromLineIds failed\n");
delete [] pts;
delete [] lines;
delete [] startIxs;
delete [] regionLines;
return SV_ERROR;
} else {
solid->Clear();
tmpPd = new cvPolyData( tmp );
if ( solid->MakePoly2d( tmpPd ) == SV_OK ) {
if ( solid->ClassifyPt( pos[0], pos[1], 0, &classification )
== SV_OK ) {
if ( classification >= 0 ) {
*dst = tmpPd;
status = SV_OK;
printf(" >>>>>> picked region lines [%d]\n", numRegionLines);
foundOne = 1;
break;
}
} else {
printf("ERR: cvSolidModel::ClassifyPt failed\n");
}
} else {
printf("ERR: cvSolidModel::MakePoly2d failed\n");
}
delete tmpPd;
}
}
if ( ! foundOne ) {
printf(" >>>>>> no closed region selected\n");
}
delete [] pts;
delete [] lines;
delete [] startIxs;
// be careful here since these objects will not exist if numRegions == 0
if (numRegions != NULL) delete [] regionLines;
if ( tmp != NULL ) tmp->Delete();
return status;
}
/* --------------- */
/* sys_geom_Reduce */
/* --------------- */
/* Caller is responsible for cleaning up the result. */
int sys_geom_Reduce( cvPolyData *src, double tol, cvPolyData **dst )
{
cvPolyData *merged_pd;
vtkPolyData *pd;
int status;
merged_pd = sys_geom_MergePts( src );
if ( merged_pd == NULL ) {
return SV_ERROR;
}
pd = merged_pd->GetVtkPolyData();
status = VtkUtils_FixTopology( pd, tol );
if ( status != SV_OK ) {
delete merged_pd;
return SV_ERROR;
}
*dst = new cvPolyData( pd );
delete merged_pd; // virtual destructor calls Delete on vtk data obj
return SV_OK;
}
/* ---------------------------- */
/* sys_geom_MakePolysConsistent */
/* ---------------------------- */
/* Caller is responsible for cleaning up the result. */
int sys_geom_MakePolysConsistent( cvPolyData *src, cvPolyData **dst )
{
vtkPolyData *pdIn = src->GetVtkPolyData();
vtkPolyData *pdCopy = vtkPolyData::New();
vtkPoints *ptsCopy = VtkUtils_DeepCopyPoints( pdIn->GetPoints() );
vtkCellArray *polysCopy = VtkUtils_DeepCopyCells( pdIn->GetPolys() );
cvPolyData *result;
int status;
pdCopy->SetPoints( ptsCopy );
pdCopy->SetPolys( polysCopy );
ptsCopy->Delete();
polysCopy->Delete();
result = new cvPolyData( pdCopy );
status = VtkUtils_MakePolysConsistent( result->GetVtkPolyData() );
if ( status != SV_OK ) {
delete result;
return SV_ERROR;
}
*dst = result;
return SV_OK;
}
/* -------------- */
/* sys_geom_union */
/* -------------- */
int sys_geom_union( cvPolyData *srcA, cvPolyData *srcB, double tolerance, cvPolyData **dst )
{
vtkPolyData *a = srcA->GetVtkPolyData();
vtkPolyData *b = srcB->GetVtkPolyData();
cvPolyData *result = NULL;
*dst = NULL;
try {
vtkNew(vtkSVLoopBooleanPolyDataFilter,booleanOperator);
booleanOperator->SetInputData(0,a);
booleanOperator->SetInputData(1,b);
booleanOperator->SetOperationToUnion();
booleanOperator->SetTolerance(tolerance);
booleanOperator->Update();
result = new cvPolyData( booleanOperator->GetOutput() );
*dst = result;
}
catch (...) {
fprintf(stderr,"ERROR in boolean operation.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
/* -------------- */
/* sys_geom_all_union */
/* -------------- */
int sys_geom_all_union( cvPolyData **srcs,int numSrcs,int nointerbool,double tolerance,cvPolyData **dst )
{
cvPolyData *result = NULL;
*dst = NULL;
vtkNew(vtkSVMultiplePolyDataIntersectionFilter,vesselInter);
for (int i=0;i<numSrcs;i++)
{
vtkPolyData *newPd = srcs[i]->GetVtkPolyData();
vesselInter->AddInputData(newPd);
}
vesselInter->SetPassInfoAsGlobal(1);
vesselInter->SetAssignSurfaceIds(1);
vesselInter->SetNoIntersectionOutput(nointerbool);
vesselInter->SetTolerance(tolerance);
try {
vesselInter->Update();
result = new cvPolyData(vesselInter->GetOutput());
*dst = result;
}
catch (...) {
fprintf(stderr,"ERROR in boolean operation.\n");
fflush(stderr);
return SV_ERROR;
}
if (vesselInter->GetStatus() == 0)
{
return SV_ERROR;
}
return SV_OK;
}
/* -------------- */
/* sys_geom_assign_ids_based_on_faces */
/* -------------- */
int sys_geom_assign_ids_based_on_faces( cvPolyData *model, cvPolyData **faces,int numFaces,int *ids,cvPolyData **dst )
{
cvPolyData *result = NULL;
*dst = NULL;
vtkIdType cellId = 0;
vtkIdType closestCell;
vtkIdType npts;
vtkIdType *pts;
int subId = 0;
double distance;
double centroid[3];
double closestPt[3];
vtkNew(vtkGenericCell,genericCell);
vtkPolyData *fullPd = model->GetVtkPolyData();
fullPd->BuildLinks();
vtkNew(vtkAppendPolyData,appender);
vtkNew(vtkPolyData,facePd);
for (int i=0;i<numFaces;i++)
{
vtkPolyData *newPd = faces[i]->GetVtkPolyData();
vtkNew(vtkIntArray,scalarArray);
scalarArray->SetName("ModelFaceID");
for (vtkIdType cellId=0;cellId<newPd->GetNumberOfCells();cellId++)
scalarArray->InsertNextValue(ids[i]);
newPd->GetCellData()->AddArray(scalarArray);
appender->AddInputData(newPd);
}
appender->Update();
facePd->DeepCopy(appender->GetOutput());
vtkNew(vtkCellLocator,cellLocator);
cellLocator->SetDataSet(facePd);
cellLocator->BuildLocator();
vtkNew(vtkIntArray,newIdArray);
newIdArray->SetName("ModelFaceID");
vtkNew(vtkIntArray,oldIdArray);
oldIdArray = vtkIntArray::SafeDownCast(facePd->GetCellData()->GetArray("ModelFaceID"));
for (vtkIdType cellId=0;cellId<fullPd->GetNumberOfCells();cellId++)
{
fullPd->GetCellPoints(cellId,npts,pts);
vtkNew(vtkPoints,polyPts);
vtkNew(vtkIdTypeArray,polyPtIds);
for (int i=0;i<npts;i++)
{
polyPtIds->InsertValue(i,i);
polyPts->InsertNextPoint(fullPd->GetPoint(pts[i]));
}
vtkPolygon::ComputeCentroid(polyPtIds,polyPts,centroid);
cellLocator->FindClosestPoint(centroid,closestPt,genericCell,closestCell,
subId,distance);
vtkIdType faceValue = oldIdArray->GetValue(closestCell);
newIdArray->InsertValue(cellId,faceValue);
}
fullPd->GetCellData()->AddArray(newIdArray);
result = new cvPolyData( fullPd);
*dst = result;
return SV_OK;
}
/* ------------------ */
/* sys_geom_intersect */
/* ------------------ */
int sys_geom_intersect( cvPolyData *srcA, cvPolyData *srcB,double tolerance, cvPolyData **dst )
{
vtkPolyData *a = srcA->GetVtkPolyData();
vtkPolyData *b = srcB->GetVtkPolyData();
cvPolyData *result = NULL;
*dst = NULL;
try {
vtkNew(vtkSVLoopBooleanPolyDataFilter,booleanOperator);
booleanOperator->SetInputData(0,a);
booleanOperator->SetInputData(1,b);
booleanOperator->SetOperationToIntersection();
booleanOperator->SetTolerance(tolerance);
booleanOperator->Update();
result = new cvPolyData( booleanOperator->GetOutput() );
*dst = result;
}
catch (...) {
fprintf(stderr,"ERROR in boolean operation.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
/* ----------------- */
/* sys_geom_subtract */
/* ----------------- */
int sys_geom_subtract( cvPolyData *srcA, cvPolyData *srcB, double tolerance,cvPolyData **dst )
{
vtkPolyData *a = srcA->GetVtkPolyData();
vtkPolyData *b = srcB->GetVtkPolyData();
cvPolyData *result = NULL;
*dst = NULL;
try {
vtkNew(vtkSVLoopBooleanPolyDataFilter,booleanOperator);
booleanOperator->SetInputData(0,a);
booleanOperator->SetInputData(1,b);
booleanOperator->SetOperationToDifference();
booleanOperator->SetTolerance(tolerance);
booleanOperator->Update();
result = new cvPolyData( booleanOperator->GetOutput() );
*dst = result;
}
catch (...) {
fprintf(stderr,"ERROR in boolean operation.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
int sys_geom_checksurface( cvPolyData *src, int stats[],double tolerance)
{
vtkPolyData *pd = src->GetVtkPolyData();
try {
double surfstats[2];
vtkSVLoopIntersectionPolyDataFilter::CleanAndCheckSurface(pd,surfstats,tolerance);
stats[0] = surfstats[0];
stats[1] = surfstats[1];
//double fe[2];double bc[2];
//pd->GetCellData()->GetArray("FreeEdge")->GetRange(fe,0);
//pd->GetCellData()->GetArray("BadTri")->GetRange(bc,0);
//stats[0] = fe[0];
//stats[1] = fe[1];
//stats[2] = bc[0];
//stats[3] = bc[1];
}
catch (...) {
fprintf(stderr,"ERROR in checking of surface.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
/* ----------------- */
/* sys_geom_Clean */
/* ----------------- */
cvPolyData *sys_geom_Clean( cvPolyData *src )
{
cvPolyData *dst;
vtkPolyData *srcPd = src->GetVtkPolyData();
vtkPolyData *pd;
vtkNew(vtkCleanPolyData, cleaner);
cleaner->SetInputData(srcPd);
cleaner->Update();
pd = vtkPolyData::New();
pd->DeepCopy(cleaner->GetOutput());
dst = new cvPolyData( pd );
pd->Delete();
return dst;
}
/* ------------------------ */
/* sys_geom_ReverseAllCells */
/* ------------------------ */
/* Caller is responsible for cleaning up the result. */
int sys_geom_ReverseAllCells( cvPolyData *src, cvPolyData **dst )
{
vtkPolyData *pdIn = src->GetVtkPolyData();
vtkPolyData *pdCopy = vtkPolyData::New();
vtkPoints *ptsCopy = VtkUtils_DeepCopyPoints( pdIn->GetPoints() );
vtkCellArray *vertsCopy = VtkUtils_DeepCopyCells( pdIn->GetVerts() );
vtkCellArray *linesCopy = VtkUtils_DeepCopyCells( pdIn->GetLines() );
vtkCellArray *polysCopy = VtkUtils_DeepCopyCells( pdIn->GetPolys() );
vtkCellArray *stripsCopy = VtkUtils_DeepCopyCells( pdIn->GetStrips() );
cvPolyData *result;
int status;
pdCopy->SetPoints( ptsCopy );
pdCopy->SetVerts( vertsCopy );
pdCopy->SetLines( linesCopy );
pdCopy->SetPolys( polysCopy );
pdCopy->SetStrips( stripsCopy );
pdCopy->GetPointData()->DeepCopy( pdIn->GetPointData() );
ptsCopy->Delete();
vertsCopy->Delete();
linesCopy->Delete();
polysCopy->Delete();
stripsCopy->Delete();
result = new cvPolyData( pdCopy );
status = VtkUtils_ReverseAllCells( result->GetVtkPolyData() );
if ( status != SV_OK ) {
delete result;
return SV_ERROR;
}
*dst = result;
return SV_OK;
}
/* ---------------------- */
/* sys_geom_GetOrderedPts */
/* ---------------------- */
int sys_geom_GetOrderedPts( cvPolyData *src, double **ord_pts, int *num )
{
cvPolyData *merged_pd;
vtkPolyData *pd;
double *pts;
int numPts;
vtkIdType *lines;
int numLines;
int *linkedLineIxs;
int numLinkedLineIxs;
int *lineVisited;
int targetIx;
int i, lineA, lineB, a, b, c, d;
int status = SV_ERROR;
double x, y, z;
int startIx;
merged_pd = sys_geom_MergePts( src );
if ( merged_pd == NULL ) {
return SV_ERROR;
}
pd = merged_pd->GetVtkPolyData();
if ( VtkUtils_GetPoints( pd, &pts, &numPts ) != SV_OK ) {
return SV_ERROR;
}
if ( VtkUtils_GetLines( pd, &lines, &numLines ) != SV_OK ) {
delete [] pts;
return SV_ERROR;
}
/*
printf("\n--- sys_geom_GetOrderedPts ---\n\n");
printf(" num pts [%d]\n", numPts);
printf(" num lines [%d]\n\n", numLines);
*/
if (numPts == 0 || numLines == 0) {
fprintf(stderr,"ERROR: no points or lines in polydata object!\n");
// don't know if I should free pts & lines here or not, but to be
// safe I wont
return SV_ERROR;
} else if (numPts < 3 || numLines < 3) {
// assume we need at least 3 pts and 3 lines to define a contour.
fprintf(stderr,"ERROR: not enough pts (%i) or lines (%i)\n", numPts, numLines);
return SV_ERROR;
}
lineVisited = new int [numLines];
for (i = 0; i < numLines; i++) {
lineVisited[i] = 0;
}
*ord_pts = new double [numPts * 3];
*num = 0;
targetIx = lines[0];
startIx = lines[0];
x = pts[targetIx*3];
y = pts[targetIx*3 + 1];
z = pts[targetIx*3 + 2];
(*ord_pts)[(*num)*3] = x;
(*ord_pts)[(*num)*3 + 1] = y;
(*ord_pts)[(*num)*3 + 2] = z;
(*num)++;
targetIx = lines[1];
x = pts[targetIx*3];
y = pts[targetIx*3 + 1];
z = pts[targetIx*3 + 2];
(*ord_pts)[(*num)*3] = x;
(*ord_pts)[(*num)*3 + 1] = y;
(*ord_pts)[(*num)*3 + 2] = z;
(*num)++;
lineVisited[0] = 1;
// Things which are allocated which we need to delete:
// - pts (VtkUtils_GetPoints) <--
// - lines (VtkUtils_GetLines) <--
// - lineVisited [numLines] <--
// - linkedLineIxs (VtkUtils_GetLinkedLines)
// - *ord_pts [numPts * 3] (delete if error)
while ( VtkUtils_GetLinkedLines( lines, numLines, targetIx,
&linkedLineIxs, &numLinkedLineIxs ) ) {
// Open contour:
if ( numLinkedLineIxs == 1 ) {
delete [] linkedLineIxs;
delete [] (*ord_pts);
break;
}
// Weird connection:
else if ( numLinkedLineIxs != 2 ) {
delete [] linkedLineIxs;
delete [] (*ord_pts);
break;
}
// Normal:
lineA = linkedLineIxs[0];
lineB = linkedLineIxs[1];
delete [] linkedLineIxs;
a = lines[ lineA * 2 ];
b = lines[ (lineA * 2) + 1 ];
c = lines[ lineB * 2 ];
d = lines[ (lineB * 2) + 1 ];
if ( ( ! lineVisited[ lineA ] ) && ( ! lineVisited[ lineB ] ) ) {
printf("ERR: line traversal error\n");
delete [] (*ord_pts);
break;
}
if ( lineVisited[ lineA ] ) {
lineVisited[ lineB ] = 1;
if ( ( a == c ) || ( b == c ) ) {
targetIx = d;
} else {
targetIx = c;
}
} else {
lineVisited[ lineA ] = 1;
if ( ( c == a ) || ( d == a ) ) {
targetIx = b;
} else {
targetIx = a;
}
}
if ( targetIx == startIx ) {
status = SV_OK;
break;
}
x = pts[targetIx*3];
y = pts[targetIx*3 + 1];
z = pts[targetIx*3 + 2];
(*ord_pts)[(*num)*3] = x;
(*ord_pts)[(*num)*3 + 1] = y;
(*ord_pts)[(*num)*3 + 2] = z;
(*num)++;
if ( (*num) > numPts ) {
printf("ERR: ordered pt list overflow\n");
delete [] (*ord_pts);
break;
}
}
delete [] pts;
delete [] lines;
delete [] lineVisited;
return status;
}
// ------------------
// sys_geom_Get2DPgon
// ------------------
int sys_geom_Get2DPgon( cvPolyData *src, double **pgon, int *num )
{
double bbox[6];
double tol = 1e10 * FindMachineEpsilon(); // looser than in other places
double *ord_pts;
double *rev_pts = NULL;
double *pts;
int i;
int wnum;
sys_geom_BBox( src, bbox );
if ( ( fabs(bbox[4]) > tol ) || ( fabs(bbox[5]) > tol ) ) {
printf("ERR: sys_geom_Get2DPgon called with non-planar input cvPolyData\n");
return SV_ERROR;
}
if ( sys_geom_GetOrderedPts( src, &ord_pts, num ) != SV_OK ) {
return SV_ERROR;
}
// We want pgon to have points in CCW order:
wnum = sys_geom_2DWindingNum( src );
if ( wnum < 0 ) {
sys_geom_ReversePtList( *num, ord_pts, &rev_pts );
pts = rev_pts;
} else {
pts = ord_pts;
}
// Transfer (x,y)'s to output:
*pgon = new double [(*num)*2];
for ( i = 0; i < (*num); i++ ) {
(*pgon)[i*2] = pts[i*3];
(*pgon)[i*2+1] = pts[i*3+1];
}
// Clean up stuff:
delete [] ord_pts;
if ( rev_pts != NULL ) {
delete [] rev_pts;
}
return SV_OK;
}
// ----------------------
// sys_geom_ReversePtList
// ----------------------
int sys_geom_ReversePtList( int num, double ptsIn[], double *ptsOut[] )
{
int i;
int rev;
*ptsOut = new double [3*num];
for ( i = 0; i < num; i++ ) {
rev = num - i - 1;
(*ptsOut)[3*i] = ptsIn[3*rev];
(*ptsOut)[3*i+1] = ptsIn[3*rev+1];
(*ptsOut)[3*i+2] = ptsIn[3*rev+2];
}
return SV_OK;
}
/* ------------------------ */
/* sys_geom_WriteOrderedPts */
/* ------------------------ */
int sys_geom_WriteOrderedPts( cvPolyData *src, char *fn )
{
double *pts;
int num_pts;
int i;
FILE *fp;
if ( sys_geom_GetOrderedPts( src, &pts, &num_pts ) != SV_OK ) {
return SV_ERROR;
}
fp = fopen( fn, "w" );
if ( fp == NULL ) {
delete [] pts;
return SV_ERROR;
}
for ( i = 0; i < num_pts; i++ ) {
fprintf( fp, "%f %f %f\n", pts[3*i], pts[3*i+1], pts[3*i+2] );
}
fclose( fp );
delete [] pts;
return SV_OK;
/*
vtkPolyData *pd;
double *pts;
int numPts;
int *lines;
int numLines;
int *linkedLineIxs;
int numLinkedLineIxs;
int *lineVisited;
int targetIx;
int i, lineA, lineB, a, b, c, d;
int status = SV_ERROR;
FILE *fp;
double x, y;
pd = src->GetVtkPolyData();
fp = fopen( fn, "w" );
if ( fp == NULL ) {
return SV_ERROR;
}
if ( VtkUtils_GetPoints( pd, &pts, &numPts ) != SV_OK ) {
fclose( fp );
return SV_ERROR;
}
if ( VtkUtils_GetLines( pd, &lines, &numLines ) != SV_OK ) {
delete [] pts;
fclose( fp );
return SV_ERROR;
}
lineVisited = new int [numLines];
for (i = 0; i < numLines; i++) {
lineVisited[i] = 0;
}
targetIx = lines[0];
x = pts[targetIx*3];
y = pts[targetIx*3 + 1];
fprintf( fp, "%f %f 0.0 0.0 0.0 0.0\n", x, y );
while ( VtkUtils_GetLinkedLines( lines, numLines, targetIx,
&linkedLineIxs, &numLinkedLineIxs ) ) {
// Open contour:
if ( numLinkedLineIxs == 1 ) {
delete [] linkedLineIxs;
break;
}
// Weird connection:
else if ( numLinkedLineIxs != 2 ) {
delete [] linkedLineIxs;
break;
}
// Normal:
else {
lineA = linkedLineIxs[0];
lineB = linkedLineIxs[1];
a = lines[ lineA * 2 ];
b = lines[ (lineA * 2) + 1 ];
c = lines[ lineB * 2 ];
d = lines[ (lineB * 2) + 1 ];
if ( ( lineVisited[ lineA ] ) && ( lineVisited[ lineB ] ) ) {
status = SV_OK;
break;
}
if ( lineVisited[ lineA ] ) {
lineVisited[ lineB ] = 1;
if ( a == c ) {
targetIx = d;
} else {
targetIx = c;
}
} else {
lineVisited[ lineA ] = 1;
if ( c == a ) {
targetIx = b;
} else {
targetIx = a;
}
}
x = pts[targetIx*3];
y = pts[targetIx*3 + 1];
fprintf( fp, "%f %f 0.0 0.0 0.0 0.0\n", x, y );
delete [] linkedLineIxs;
}
}
delete [] lineVisited;
delete [] pts;
delete [] lines;
fclose( fp );
return status;
*/
}
/* ------------------- */
/* sys_geom_WriteLines */
/* ------------------- */
int sys_geom_WriteLines( cvPolyData *src, char *fn )
{
vtkPolyData *pd;
double *pts;
int numPts;
vtkIdType *lines;
int numLines;
int i, ptAIx, ptBIx;
FILE *fp;
pd = src->GetVtkPolyData();
fp = fopen( fn, "w" );
if ( fp == NULL ) {
return SV_ERROR;
}
if ( VtkUtils_GetPoints( pd, &pts, &numPts ) != SV_OK ) {
fclose( fp );
return SV_ERROR;
}
if ( VtkUtils_GetLines( pd, &lines, &numLines ) != SV_OK ) {
delete [] pts;
fclose( fp );
return SV_ERROR;
}
for (i = 0; i < numLines; i++) {
ptAIx = lines[2*i];
ptBIx = lines[2*i + 1];
fprintf( fp, "%f %f %f %f %f %f\n",
pts[3*ptAIx], pts[3*ptAIx + 1], pts[3*ptAIx + 2],
pts[3*ptBIx], pts[3*ptBIx + 1], pts[3*ptBIx + 2] );
}
fclose( fp );
delete [] pts;
delete [] lines;
return SV_OK;
}
// --------------------
// sys_geom_PolysClosed
// --------------------
int sys_geom_PolysClosed( cvPolyData *src, int *closed )
{
vtkPolyData *pd;
int numPts, numPolys;
vtkFloatingPointType *pts;
vtkIdType *polys;
pd = src->GetVtkPolyData();
if ( VtkUtils_GetPointsFloat( pd, &pts, &numPts ) != SV_OK ) {
printf("ERR: VtkUtils_GetPoints failed\n");
return SV_ERROR;
}
if ( VtkUtils_GetAllPolys( pd, &numPolys, &polys ) != SV_OK ) {
printf("ERR: VtkUtils_GetAllPolys failed\n");
return SV_ERROR;
}
cgeom_PolysClosed( numPts, pts, numPolys, polys, closed );
return SV_OK;
}
// -----------------
// sys_geom_SurfArea
// -----------------
int sys_geom_SurfArea( cvPolyData *src, double *area )
{
vtkPolyData *pd;
int numPts, numPolys;
vtkFloatingPointType *pts;
vtkIdType *polys;
vtkFloatingPointType fArea;
// since cgeom_CompArea requires triangles, we will
// create triangles before we call that routine
vtkTriangleFilter *tri = vtkTriangleFilter::New();
tri->SetInputData(src->GetVtkPolyData());
tri->Update();
pd = tri->GetOutput();
if ( VtkUtils_GetPointsFloat( pd, &pts, &numPts ) != SV_OK ) {
printf("ERR: VtkUtils_GetPoints failed\n");
tri->Delete();
return SV_ERROR;
}
if ( VtkUtils_GetAllPolys( pd, &numPolys, &polys ) != SV_OK ) {
printf("ERR: VtkUtils_GetAllPolys failed\n");
tri->Delete();
return SV_ERROR;
}
cgeom_CompArea( numPts, pts, numPolys, polys, &fArea );
*area = fArea;
tri->Delete();
return SV_OK;
}
// ------------------------
// sys_geom_getPolyCentroid
// ------------------------
// Interface from VtkPolyData to use cgeom_GetPolyCentroid routine
// centroid must be an array of at least THREE elements.
int sys_geom_getPolyCentroid( cvPolyData *src, double centroid[])
{
vtkPolyData *pd;
int numPts, numPolys;
vtkFloatingPointType *pts;
vtkIdType *polys;
// since cgeom_CalcPolyCentroid requires triangles, we will
// create triangles before we call that routine
vtkTriangleFilter *tri = vtkTriangleFilter::New();
tri->SetInputData(src->GetVtkPolyData());
tri->Update();
pd = tri->GetOutput();
if ( VtkUtils_GetPointsFloat( pd, &pts, &numPts ) != SV_OK ) {
printf("ERR: VtkUtils_GetPoints failed\n");
tri->Delete();
return SV_ERROR;
}
if ( VtkUtils_GetAllPolys( pd, &numPolys, &polys ) != SV_OK ) {
printf("ERR: VtkUtils_GetAllPolys failed\n");
tri->Delete();
return SV_ERROR;
}
cgeom_GetPolyCentroid ( numPts, pts, numPolys, polys, centroid);
tri->Delete();
return SV_OK;
}
// ----------------------
// sys_geom_PrintTriStats
// ----------------------
int sys_geom_PrintTriStats( cvPolyData *surf )
{
vtkPolyData *pd;
int numPts, numPolys;
double *pts;
vtkIdType *polys;
int i, pos;
int numTri = 0;
int numOther = 0;
int a, b, c;
double minEdge, currMinEdge, currMaxEdge;
double minArea, currArea;
double ab[3];
double ac[3];
double cp[3];
double minHeight, currMinHeight;
double len_ab, len_ac, len_bc;
int min_e_id, min_a_id, min_h_id;
double tol = 1e6 * FindMachineEpsilon();
pd = surf->GetVtkPolyData();
if ( VtkUtils_GetPoints( pd, &pts, &numPts ) != SV_OK ) {
printf("ERR: VtkUtils_GetPoints failed\n");
return SV_ERROR;
}
if ( VtkUtils_GetAllPolys( pd, &numPolys, &polys ) != SV_OK ) {
printf("ERR: VtkUtils_GetAllPolys failed\n");
delete [] pts;
return SV_ERROR;
}
printf( "\n\n ------ sys_geom_PrintTriStats ------\n" );
pos = 0;
minEdge = 0.0; // these are needed
minArea = 0.0; // only to prevent
minHeight = 0.0; // compiler warnings
min_e_id = -1;
min_a_id = -1;
min_h_id = -1;
for ( i = 0; i < numPolys; i++ ) {
if ( polys[pos] == 3 ) {
numTri++;
a = polys[pos+1];
b = polys[pos+2];
c = polys[pos+3];
// Find the shortest edge of the triangle:
len_ab = Distance( pts[3*a], pts[3*a+1], pts[3*a+2],
pts[3*b], pts[3*b+1], pts[3*b+2] );
len_ac = Distance( pts[3*a], pts[3*a+1], pts[3*a+2],
pts[3*c], pts[3*c+1], pts[3*c+2] );
len_bc = Distance( pts[3*b], pts[3*b+1], pts[3*b+2],
pts[3*c], pts[3*c+1], pts[3*c+2] );
currMinEdge = svminimum( len_ab, len_ac );
currMinEdge = svminimum( currMinEdge, len_bc );
if ( ( i == 0 ) || ( currMinEdge < minEdge ) ) {
minEdge = currMinEdge;
min_e_id = i;
}
// Find triangle area:
ab[0] = pts[3*b] - pts[3*a];
ab[1] = pts[3*b+1] - pts[3*a+1];
ab[2] = pts[3*b+2] - pts[3*a+2];
ac[0] = pts[3*c] - pts[3*a];
ac[1] = pts[3*c+1] - pts[3*a+1];
ac[2] = pts[3*c+2] - pts[3*a+2];
Cross( ab[0], ab[1], ab[2], ac[0], ac[1], ac[2],
&(cp[0]), &(cp[1]), &(cp[2]) );
currArea = Magnitude( cp[0], cp[1], cp[2] ) / 2.0;
if ( ( i == 0 ) || ( currArea < minArea ) ) {
minArea = currArea;
min_a_id = i;
}
// Find the smallest triangle height:
// A(tri) = 1/2 (base) (height)
currMaxEdge = svmaximum( len_ab, len_ac );
currMaxEdge = svmaximum( currMaxEdge, len_bc );
currMinHeight = 2 * currArea / currMaxEdge;
if ( ( i == 0 ) || ( currMinHeight < minHeight ) ) {
minHeight = currMinHeight;
min_h_id = i;
}
} else {
numOther++;
}
pos += polys[pos] + 1;
}
printf( " >>>>>> num tri [%d]\n", numTri );
printf( " >>>>>> num non-tri [%d]\n", numOther );
printf( " >>>>>> tot polys [%d]\n", numPolys );
printf( " >>>>>> min edge [%f]\n", minEdge );
printf( " >>>>>> min edge id [%d]\n", min_e_id );
printf( " >>>>>> min area [%f]\n", minArea );
printf( " >>>>>> min area id [%d]\n", min_a_id );
printf( " >>>>>> min height [%f]\n", minHeight );
printf( " >>>>>> min height id [%d]\n", min_h_id );
printf( "\n\n" );
return SV_OK;
}
// ------------------------
// sys_geom_PrintSmallPolys
// ------------------------
int sys_geom_PrintSmallPolys( cvPolyData *src, double sideTol )
{
vtkPolyData *pd;
int numPts, numPolys;
int numFound, minPolyId;
vtkFloatingPointType *pts;
vtkIdType *polys;
pd = src->GetVtkPolyData();
if ( VtkUtils_GetPointsFloat( pd, &pts, &numPts ) != SV_OK ) {
printf("ERR: VtkUtils_GetPoints failed\n");
return SV_ERROR;
}
if ( VtkUtils_GetAllPolys( pd, &numPolys, &polys ) != SV_OK ) {
printf("ERR: VtkUtils_GetAllPolys failed\n");
delete [] pts;
return SV_ERROR;
}
printf ( "\n\n ------ sys_geom_PrintSmallPolys ------\n" );
cgeom_FindDegen( numPts, pts, numPolys, polys, sideTol, &numFound,
&minPolyId );
printf ( " >>>>>> num degen polys [%d]. \n", numFound );
printf ( " >>>>>> min poly id [%d]. \n", minPolyId );
printf ( "\n\n");
delete [] pts;
delete [] polys;
return SV_OK;
}
// ---------------------
// sys_geom_RmSmallPolys
// ---------------------
int sys_geom_RmSmallPolys( cvPolyData *src, double sideTol, cvPolyData **dst )
{
vtkPolyData *pd;
int numPts, numPolys;
vtkFloatingPointType *pts;
vtkIdType *polys;
int numRemoved, minPolyId;
int numNewPts, numNewPolys;
vtkFloatingPointType *newPts;
vtkIdType *newPolys;
vtkPolyData *result;
pd = src->GetVtkPolyData();
if ( VtkUtils_GetPointsFloat( pd, &pts, &numPts ) != SV_OK ) {
printf("ERR: VtkUtils_GetPoints failed\n");
return SV_ERROR;
}
if ( VtkUtils_GetAllPolys( pd, &numPolys, &polys ) != SV_OK ) {
printf("ERR: VtkUtils_GetAllPolys failed\n");
delete [] pts;
return SV_ERROR;
}
printf ( "\n\n ------ sys_geom_RmSmallPolys ------\n" );
cgeom_FindDegen( numPts, pts, numPolys, polys, sideTol,
&numRemoved, &minPolyId );
printf ( " >>>>>> num degen polys [%d]. \n", numRemoved );
printf ( " >>>>>> min poly id [%d]. \n", minPolyId );
printf ( "\n\n");
cgeom_FixDegen( numPts, pts, numPolys, polys, sideTol,
&numNewPts, &newPts, &numNewPolys, &newPolys );
printf ( " >>>>>> num new pts [%d]. \n", numNewPts );
printf ( " >>>>>> num new polys [%d]. \n", numNewPolys );
printf ( "\n\n" );
if ( VtkUtils_NewVtkPolyData( &result, numNewPts, newPts, numNewPolys,
newPolys ) != SV_OK ) {
printf("ERR: VtkUtils_NewVtkPolyData failed\n");
delete [] pts;
delete [] polys;
delete [] newPts;
delete [] newPolys;
return SV_ERROR;
}
(*dst) = new cvPolyData( result );
result->Delete();
delete [] pts;
delete [] polys;
delete [] newPts;
delete [] newPolys;
return SV_OK;
}
/* ------------- */
/* sys_geom_BBox */
/* ------------- */
// bbox MUST be a caller-allocated array of 6 doubles. bbox is filled
// as follows:
// bbox[0] min x
// bbox[1] max x
// bbox[2] min y
// bbox[3] max y
// bbox[4] min z
// bbox[5] max z
int sys_geom_BBox( cvPolyData *obj, double bbox[] )
{
vtkPolyData *pd;
double *pts;
int numPts;
int i;
pd = obj->GetVtkPolyData();
if ( VtkUtils_GetPoints( pd, &pts, &numPts ) != SV_OK ) {
printf("ERR: VtkUtils_GetPoints failed\n");
return SV_ERROR;
}
for ( i = 0; i < numPts; i++ ) {
if ( i == 0 ) {
bbox[0] = bbox[1] = pts[3*i];
bbox[2] = bbox[3] = pts[3*i+1];
bbox[4] = bbox[5] = pts[3*i+2];
}
bbox[0] = svminimum( bbox[0], pts[3*i] );
bbox[1] = svmaximum( bbox[1], pts[3*i] );
bbox[2] = svminimum( bbox[2], pts[3*i+1] );
bbox[3] = svmaximum( bbox[3], pts[3*i+1] );
bbox[4] = svminimum( bbox[4], pts[3*i+2] );
bbox[5] = svmaximum( bbox[5], pts[3*i+2] );
}
delete [] pts;
return SV_OK;
}
/* ---------------------- */
/* sys_geom_OrientProfile */
/* ---------------------- */
int sys_geom_OrientProfile( cvPolyData *src, double ppt[], double ptan[],
double xhat[], cvPolyData **dst )
{
double yhat[3];
vtkCellArray *lines;
vtkPoints *pts = vtkPoints::New();
vtkPolyData *srcPd = src->GetVtkPolyData();
vtkPolyData *pd = vtkPolyData::New();
int i, numPts;
vtkFloatingPointType origpt[3];
vtkFloatingPointType newpt[3];
vtkFloatingPointType trans[2];
cvPolyData *result;
NormVector( &(ptan[0]), &(ptan[1]), &(ptan[2]) );
NormVector( &(xhat[0]), &(xhat[1]), &(xhat[2]) );
Cross( ptan[0], ptan[1], ptan[2], xhat[0], xhat[1], xhat[2],
&(yhat[0]), &(yhat[1]), &(yhat[2]) );
NormVector( &(yhat[0]), &(yhat[1]), &(yhat[2]) );
lines = VtkUtils_DeepCopyCells( srcPd->GetLines() );
numPts = srcPd->GetNumberOfPoints();
for ( i = 0; i < numPts; i++ ) {
srcPd->GetPoint( i, origpt );
trans[0] = origpt[0];
trans[1] = origpt[1];
newpt[0] = ppt[0] + trans[0] * xhat[0] + trans[1] * yhat[0];
newpt[1] = ppt[1] + trans[0] * xhat[1] + trans[1] * yhat[1];
newpt[2] = ppt[2] + trans[0] * xhat[2] + trans[1] * yhat[2];
pts->InsertNextPoint( newpt );
}
pd->SetPoints( pts );
pd->SetLines( lines );
pts->Delete();
lines->Delete();
result = new cvPolyData( pd );
pd->Delete();
*dst = result;
return SV_OK;
}
/* ------------------------- */
/* sys_geom_DisorientProfile */
/* ------------------------- */
int sys_geom_DisorientProfile( cvPolyData *src, double ppt[], double ptan[],
double xhat[], cvPolyData **dst )
{
double yhat[3];
double S[9], detS;
double A[9];
double B[9];
vtkCellArray *lines;
vtkPoints *pts = vtkPoints::New();
vtkPolyData *srcPd = src->GetVtkPolyData();
vtkPolyData *pd = vtkPolyData::New();
int i, numPts;
vtkFloatingPointType srcpt[3];
vtkFloatingPointType dstpt[3];
cvPolyData *result;
double ep = 1e6 * FindMachineEpsilon();
NormVector( &(ptan[0]), &(ptan[1]), &(ptan[2]) );
NormVector( &(xhat[0]), &(xhat[1]), &(xhat[2]) );
Cross( ptan[0], ptan[1], ptan[2], xhat[0], xhat[1], xhat[2],
&(yhat[0]), &(yhat[1]), &(yhat[2]) );
NormVector( &(yhat[0]), &(yhat[1]), &(yhat[2]) );
// Set up S, A and B for use with Cramer's Rule to find dstpt[0] and
// dstpt[1], respectively:
S[0] = xhat[0];
S[1] = xhat[1];
S[2] = xhat[2];
S[3] = yhat[0];
S[4] = yhat[1];
S[5] = yhat[2];
S[6] = ptan[0];
S[7] = ptan[1];
S[8] = ptan[2];
detS = misc_Det3x3(S);
A[3] = yhat[0];
A[4] = yhat[1];
A[5] = yhat[2];
A[6] = ptan[0];
A[7] = ptan[1];
A[8] = ptan[2];
B[0] = xhat[0];
B[1] = xhat[1];
B[2] = xhat[2];
B[6] = ptan[0];
B[7] = ptan[1];
B[8] = ptan[2];
/*
a = xhat[0];
b = yhat[0];
c = xhat[1];
d = yhat[1];
if ( fabs(a*d - b*c) < ep ) {
printf("ERR: singular disorientation matrix\n");
pts->Delete();
pd->Delete();
*dst = NULL;
return SV_ERROR;
}
coeff = 1.0 / ( a*d - b*c );
lines = VtkUtils_DeepCopyCells( srcPd->GetLines() );
numPts = srcPd->GetNumberOfPoints();
for ( i = 0; i < numPts; i++ ) {
srcPd->GetPoint( i, srcpt );
dstpt[0] = coeff * ( d*(srcpt[0] - ppt[0]) - b*(srcpt[1] - ppt[1]) );
dstpt[1] = coeff * ( -c*(srcpt[0] - ppt[0]) + a*(srcpt[1] - ppt[1]) );
dstpt[2] = 0.0;
pts->InsertNextPoint( dstpt );
}
*/
lines = VtkUtils_DeepCopyCells( srcPd->GetLines() );
numPts = srcPd->GetNumberOfPoints();
for ( i = 0; i < numPts; i++ ) {
srcPd->GetPoint( i, srcpt );
A[0] = srcpt[0] - ppt[0];
A[1] = srcpt[1] - ppt[1];
A[2] = srcpt[2] - ppt[2];
B[3] = srcpt[0] - ppt[0];
B[4] = srcpt[1] - ppt[1];
B[5] = srcpt[2] - ppt[2];
dstpt[0] = (1.0 / detS) * ( misc_Det3x3(A) );
dstpt[1] = (1.0 / detS) * ( misc_Det3x3(B) );
dstpt[2] = 0.0;
pts->InsertNextPoint( dstpt );
}
pd->SetPoints( pts );
pd->SetLines( lines );
pts->Delete();
lines->Delete();
result = new cvPolyData( pd );
pd->Delete();
*dst = result;
return SV_OK;
}
/* ------------------ */
/* sys_geom_Translate */
/* ------------------ */
/* Caller is responsible for cleaning up the result. */
int sys_geom_Translate( cvPolyData *src, double translate[], cvPolyData **dst )
{
// cvPolyData *result = new cvPolyData( src );
cvPolyData *result = sys_geom_DeepCopy( src );
int i, numPts;
vtkFloatingPointType pt[3];
vtkPoints *pts = result->GetVtkPolyData()->GetPoints();
numPts = pts->GetNumberOfPoints();
for ( i = 0; i < numPts; i++ ) {
pts->GetPoint( i, pt );
pt[0] += translate[0];
pt[1] += translate[1];
pt[2] += translate[2];
pts->SetPoint( i, pt );
}
*dst = result;
return SV_OK;
}
// -----------------
// sys_geom_ScaleAvg
// -----------------
int sys_geom_ScaleAvg( cvPolyData *src, double factor, cvPolyData **dst )
{
cvPolyData *result = sys_geom_DeepCopy( src );
int i, numPts;
double avgPt[3];
vtkFloatingPointType pt[3];
vtkFloatingPointType vec[3];
sys_geom_AvgPt( src, avgPt );
vtkPoints *pts = result->GetVtkPolyData()->GetPoints();
numPts = pts->GetNumberOfPoints();
for ( i = 0; i < numPts; i++ ) {
pts->GetPoint( i, pt );
vec[0] = factor * (pt[0] - avgPt[0]);
vec[1] = factor * (pt[1] - avgPt[1]);
vec[2] = factor * (pt[2] - avgPt[2]);
pt[0] = avgPt[0] + vec[0];
pt[1] = avgPt[1] + vec[1];
pt[2] = avgPt[2] + vec[2];
pts->SetPoint( i, pt );
}
*dst = result;
return SV_OK;
}
// --------------
// sys_geom_Align
// --------------
cvPolyData *sys_geom_Align( cvPolyData *ref, cvPolyData *src )
{
double refNrm[3];
double srcNrm[3];
double *refPts, *srcPts;
int numRefPts, numSrcPts;
double refAvg[3];
double srcAvg[3];
double refStart[3];
double radial[3];
double refCross[3];
double currCross[3];
cvPolyData *dst;
double currScore, maxScore;
int posId;
if ( sys_geom_PolygonNormal( ref, refNrm ) != SV_OK ) {
printf( "ERR: normal calculation for reference polygon failed\n" );
return NULL;
}
if ( sys_geom_GetOrderedPts( ref, &refPts, &numRefPts ) != SV_OK ) {
printf( "ERR: get ref ordered points failed\n" );
return NULL;
}
refStart[0] = refPts[0];
refStart[1] = refPts[1];
refStart[2] = refPts[2];
delete [] refPts;
// Compute the target vector ref norm cross ref radial vec at start
// pos:
sys_geom_AvgPt( ref, refAvg );
radial[0] = refStart[0] - refAvg[0];
radial[1] = refStart[1] - refAvg[1];
radial[2] = refStart[2] - refAvg[2];
Cross( refNrm[0], refNrm[1], refNrm[2],
radial[0], radial[1], radial[2],
&(refCross[0]), &(refCross[1]), &(refCross[2]) );
NormVector( &(refCross[0]), &(refCross[1]), &(refCross[2]) );
if ( sys_geom_PolygonNormal( src, srcNrm ) != SV_OK ) {
printf( "ERR: normal calculation for source polygon failed\n" );
return NULL;
}
// If src normal opposes ref normal, then invert src. This is
// reasonable because this alignment function is only meant for use
// with neighboring curves which are changing direction gradually.
if ( Dot( refNrm[0], refNrm[1], refNrm[2], srcNrm[0], srcNrm[1],
srcNrm[2] ) < 0.0 ) {
VtkUtils_ReverseAllCells( src->GetVtkPolyData() );
}
if ( sys_geom_GetOrderedPts( src, &srcPts, &numSrcPts ) != SV_OK ) {
printf( "ERR: get src ordered points failed\n" );
return NULL;
}
sys_geom_AvgPt( src, srcAvg );
// Foreach pos p in the src polygon, compute src norm cross radial
// vec at p. A score can then be computed as the dot between the
// reference direction (i.e. refCross) and the current direction
// (i.e. currCross). Note that this strategy breaks down as refNrm
// cross srcNrm --> refCross. However, if we assume that adjacent
// profiles won't change direction too abruptly, this is OK. Note
// also that this implies that we should apply sys_geom_Align in a
// cascading fashion (i.e. align b to a, c to b, d to c, etc.) as
// opposed to using a single base profile (i.e. align b to a, c to
// a, d to a, etc.).
for ( int i = 0; i < numSrcPts; i++ ) {
radial[0] = srcPts[3*i] - srcAvg[0];
radial[1] = srcPts[3*i+1] - srcAvg[1];
radial[2] = srcPts[3*i+2] - srcAvg[2];
Cross( srcNrm[0], srcNrm[1], srcNrm[2],
radial[0], radial[1], radial[2],
&(currCross[0]), &(currCross[1]), &(currCross[2]) );
NormVector( &(currCross[0]), &(currCross[1]), &(currCross[2]) );
currScore = Dot( refCross[0], refCross[1], refCross[2],
currCross[0], currCross[1], currCross[2] );
if ( i == 0 ) {
maxScore = currScore;
posId = i;
} else {
if ( currScore > maxScore ) {
posId = i;
}
maxScore = svmaximum( maxScore, currScore );
}
}
delete [] srcPts;
// No re-alignment:
if ( posId == 0 ) {
printf( "NOTE: no adjustment to alignment [%s]\n", src->GetName() );
dst = new cvPolyData( src );
return dst;
}
dst = sys_geom_ReorderPolygon( src, posId );
return dst;
}
// -----------------------
// sys_geom_ReorderPolygon
// -----------------------
cvPolyData *sys_geom_ReorderPolygon( cvPolyData *src, int startIx )
{
double *srcPts;
int numSrcPts;
vtkFloatingPointType *alignedPts;
vtkIdType *cells;
vtkPolyData *pd;
cvPolyData *dst;
int i, j;
if ( sys_geom_GetOrderedPts( src, &srcPts, &numSrcPts ) != SV_OK ) {
printf( "ERR: get src ordered points failed\n" );
return NULL;
}
if ( ( startIx < 0 ) || ( startIx >= numSrcPts ) ) {
printf("ERR: index %d out of range\n", startIx);
delete [] srcPts;
return NULL;
}
alignedPts = new vtkFloatingPointType [3 * numSrcPts];
for ( i = 0; i < numSrcPts; i++ ) {
j = (startIx + i) % numSrcPts;
alignedPts[3*i] = srcPts[3*j];
alignedPts[3*i+1] = srcPts[3*j+1];
alignedPts[3*i+2] = srcPts[3*j+2];
}
cells = new vtkIdType [3 * numSrcPts];
for ( i = 0; i < numSrcPts; i++ ) {
cells[3*i] = 2;
cells[3*i+1] = i;
cells[3*i+2] = (i + 1) % numSrcPts;
}
delete [] srcPts;
if ( VtkUtils_NewVtkPolyDataLines( &pd, numSrcPts, alignedPts, numSrcPts,
cells ) != SV_OK ) {
printf( "ERR: poly data creation failed\n" );
delete [] alignedPts;
delete [] cells;
return NULL;
}
dst = new cvPolyData( pd );
pd->Delete();
delete [] alignedPts;
delete [] cells;
return dst;
}
// --------------------
// sys_geom_AlignByDist
// --------------------
cvPolyData *sys_geom_AlignByDist( cvPolyData *ref, cvPolyData *src )
{
double refNrm[3], srcNrm[3];
double *refPts;
int numRefPts;
double *srcPts;
int numSrcPts;
int ix;
cvPolyData *dst;
// not sure this normal stuff makes sense? nw.
if ( sys_geom_PolygonNormal( ref, refNrm ) != SV_OK ) {
printf( "ERR: normal calculation for reference polygon failed\n" );
return NULL;
}
if ( sys_geom_PolygonNormal( src, srcNrm ) != SV_OK ) {
printf( "ERR: normal calculation for source polygon failed\n" );
return NULL;
}
// printf( "Aligning profile [%s]\n", src->GetName() );
// If src normal opposes ref normal, then invert src. This is
// reasonable because this alignment function is only meant for use
// with neighboring curves which are changing direction gradually.
if ( Dot( refNrm[0], refNrm[1], refNrm[2], srcNrm[0], srcNrm[1],
srcNrm[2] ) < 0.0 ) {
//fprintf(stdout," Reversing src.\n");
VtkUtils_ReverseAllCells( src->GetVtkPolyData() );
}
// Get ref and src points:
if ( sys_geom_GetOrderedPts( ref, &refPts, &numRefPts ) != SV_OK ) {
printf( "ERROR: get ref ordered points failed\n" );
return NULL;
}
if ( sys_geom_GetOrderedPts( src, &srcPts, &numSrcPts ) != SV_OK ) {
delete [] refPts;
printf( "ERROR: get src ordered points failed\n" );
return NULL;
}
// find the closest two points in 3-space between the two
// profiles. Note that it is possible two pts are the same
// distance from a corresponding pt on another curve and the
// one picked by this code is nearly random. But this should
// be okay.
if (numRefPts != numSrcPts) {
fprintf(stderr,"ERROR: must have equal number of pts to align curves by distance~\n");
delete [] srcPts;
delete [] refPts;
return SV_ERROR;
}
double d2 = 0;
double d2min = 9999999999.99;
int refPtId = -1;
int dstPtId = -1;
for (int ki = 0; ki < numRefPts; ki++) {
for (int kj = 0; kj < numSrcPts; kj++) {
d2 = 0;
int pt1ix = ki;
int pt2ix = kj;
for (int i = 0; i < numRefPts; i++) {
d2 += ((refPts[3*pt1ix+0]-srcPts[3*pt2ix+0]) * (refPts[3*pt1ix+0]-srcPts[3*pt2ix+0])) +
((refPts[3*pt1ix+1]-srcPts[3*pt2ix+1]) * (refPts[3*pt1ix+1]-srcPts[3*pt2ix+1])) +
((refPts[3*pt1ix+2]-srcPts[3*pt2ix+2]) * (refPts[3*pt1ix+2]-srcPts[3*pt2ix+2]));
pt2ix++;
if (pt2ix == numSrcPts) pt2ix = 0;
pt1ix++;
if (pt1ix == numRefPts) pt1ix = 0;
}
if (d2 < d2min) {
refPtId = ki;
dstPtId = kj;
d2min = d2;
}
}
}
//fprintf(stdout," refPtId: %i dstPtId: %i d2min: %lf\n",refPtId,dstPtId,d2min);
delete [] srcPts;
delete [] refPts;
// check for error condition
if (refPtId < 0) {
fprintf(stderr,"ERROR: could not find min distance between curves?!\n");
return SV_ERROR;
}
// No re-alignment:
if ( refPtId == dstPtId ) {
//printf( " NOTE: no adjustment to alignment [%s]\n", src->GetName() );
dst = new cvPolyData( src );
return dst;
}
if ( dstPtId > refPtId ) {
ix = dstPtId - refPtId;
} else {
ix = dstPtId + (numRefPts -refPtId);
}
//fprintf(stdout," ix: %i\n",ix);
dst = sys_geom_ReorderPolygon(src, ix);
return dst;
}
/* ----------------- */
/* sys_geom_Classify */
/* ----------------- */
/* Note that there is no deep copy of data here like there is
* sys_geom_PtInPoly. So hopefully we can get away without adding the
* static object pointers we used in sys_geom_PtInPoly.
*/
int sys_geom_Classify( cvPolyData *obj, double pt[], int *result )
{
vtkPolyData *pd;
vtkCellArray *polys;
int numPolys;
vtkFloatingPointType tmp[3];
vtkIdType *ptIds;
vtkIdType npts;
ggemsGeoPoint *verts;
int maxVerts = 0;
ggemsGeoPoint p;
Rdouble Area = 0.0;
pd = obj->GetVtkPolyData();
polys = pd->GetPolys();
numPolys = pd->GetNumberOfPolys();
maxVerts = polys->GetMaxCellSize();
verts = new ggemsGeoPoint [maxVerts];
if ( verts == NULL ) {
return SV_ERROR;
}
p.x = pt[0];
p.y = pt[1];
p.z = pt[2];
// Foreach poly:
polys->InitTraversal();
while ( polys->GetNextCell( npts, ptIds ) ) {
// Foreach pt in poly, set up verts array:
for (int j = 0; j < npts; j++) {
pd->GetPoint( ptIds[j], tmp );
verts[j].x = tmp[0];
verts[j].y = tmp[1];
verts[j].z = tmp[2];
}
// Compute solid angle for this poly:
Area += ggemsgeo_solid_angle ( npts, verts, &p );
}
// inside <--> 1
// outside <--> -1
if ((Area > 2*PI) || (Area < -2*PI)) {
*result = 1;
} else {
*result = -1;
}
delete [] verts;
return SV_OK;
}
/* ----------------- */
/* sys_geom_PtInPoly */
/* ----------------- */
/* Input cvPolyData should be planar and lie in the xy plane. Only the
* x and y components of the given test point will be examined. 1 is
* returned for points in the polygon, -1 for points outside.
*/
static double *g_sys_geom_PtInPoly_pgon = NULL;
static int g_sys_geom_PtInPoly_num = 0;
int sys_geom_PtInPoly( cvPolyData *obj, double pt[], int usePrevPoly, int *result )
{
// to speed access, let the user use the previous polygon. It is up
// to the user to ensure this makes sense!
if (usePrevPoly != 0) {
if ( ggems_CrossingsMultiplyTest(g_sys_geom_PtInPoly_pgon ,
g_sys_geom_PtInPoly_num, pt ) ) {
*result = 1;
return SV_OK;
} else {
*result = -1;
return SV_OK;
}
}
// lazy free of the previous polygon
if (g_sys_geom_PtInPoly_pgon != NULL) {
delete [] g_sys_geom_PtInPoly_pgon;
g_sys_geom_PtInPoly_pgon = NULL;
}
double *pgon = NULL;
int num = 0;
int havePolygon = 0;
vtkFeatureEdges *edgeFilter;
cvPolyData *tmppd;
// check if we have a polygon in the cvPolyData. If we do,
// this obj is used to create line segments to be passed
// to Ken's code which counts on line segments.
vtkPolyData *pd = obj->GetVtkPolyData();
if (pd->GetPolys()->GetNumberOfCells() > 0) {
edgeFilter = vtkFeatureEdges::New();
edgeFilter->BoundaryEdgesOn();
edgeFilter->FeatureEdgesOff();
edgeFilter->ManifoldEdgesOff();
edgeFilter->NonManifoldEdgesOff();
edgeFilter->SetInputData(pd);
edgeFilter->Update();
tmppd = new cvPolyData(edgeFilter->GetOutput());
int status = sys_geom_Get2DPgon( tmppd, &pgon, &num );
delete tmppd;
edgeFilter->Delete();
if (status != SV_OK ) {
return SV_ERROR;
}
} else {
if ( sys_geom_Get2DPgon( obj, &pgon, &num ) != SV_OK ) {
return SV_ERROR;
}
}
if (num == 0 || pgon == NULL) {
return SV_ERROR;
}
if ( ggems_CrossingsMultiplyTest( pgon, num, pt ) ) {
*result = 1;
} else {
*result = -1;
}
// delete on next call to function
//delete [] pgon;
g_sys_geom_PtInPoly_pgon = pgon;
g_sys_geom_PtInPoly_num = num;
return SV_OK;
}
// -------------------
// sys_geom_sampleLoop
// -------------------
cvPolyData *sys_geom_sampleLoop( cvPolyData *src, int targetNumPts )
{
cvPolyData *merged_pd;
vtkPolyData *pd;
double *pts;
int numPts;
vtkIdType *lines;
int numLines;
int *startIxs;
int numRegions;
int i, j;
vtkFloatingPointType *ptsOut;
vtkIdType *linesOut;
vtkPolyData *pdOut;
cvPolyData *result;
double tol = 1e10 * FindMachineEpsilon();
if ( targetNumPts < 3 ) {
printf("ERR: target # pts must be >= 3\n");
return NULL;
}
merged_pd = sys_geom_MergePts( src );
if ( merged_pd == NULL ) {
return SV_ERROR;
}
pd = merged_pd->GetVtkPolyData();
// First, we just want to count the number of closed loops:
if ( VtkUtils_GetPoints( pd, &pts, &numPts ) != SV_OK ) {
delete merged_pd;
return NULL;
}
if ( VtkUtils_GetLines( pd, &lines, &numLines ) != SV_OK ) {
delete merged_pd;
delete [] pts;
return NULL;
}
delete merged_pd;
if ( VtkUtils_FindClosedLineRegions( lines, numLines, numPts,
&startIxs, &numRegions ) != SV_OK ) {
delete [] pts;
delete [] lines;
return NULL;
}
delete [] startIxs;
delete [] pts;
delete [] lines;
if ( numRegions != 1 ) {
printf("ERR: sys_geom_sampleLoop requires input to contain exactly "
"1 closed loop\n");
return NULL;
}
// Now get an ordered point list:
if ( sys_geom_GetOrderedPts( src, &pts, &numPts ) != SV_OK ) {
return NULL;
}
ptsOut = new vtkFloatingPointType [3*targetNumPts];
linesOut = new vtkIdType [3*targetNumPts];
// unfortunately I wrote my math code expecting 2-dimensional arrays
// instead of flat structures, so I need to convert here.
cvMath *mathobj = new cvMath();
double **nwpts = mathobj->createArray(numPts,3);
for (i = 0; i < numPts; i++) {
nwpts[i][0]=pts[3*i+0];
nwpts[i][1]=pts[3*i+1];
nwpts[i][2]=pts[3*i+2];
}
double **outPts = NULL;
int closed = 1;
if ((mathobj->linearInterpolateCurve(nwpts, numPts, closed, targetNumPts, &outPts)) == SV_ERROR) {
mathobj->deleteArray(nwpts,numPts,3);
delete mathobj;
fprintf(stderr,"ERROR: problems sampling curve.\n");
delete [] ptsOut;
delete [] linesOut;
return NULL;
}
for (i = 0; i < targetNumPts; i++) {
ptsOut[3*i+0] = outPts[i][0];
ptsOut[3*i+1] = outPts[i][1];
ptsOut[3*i+2] = outPts[i][2];
}
mathobj->deleteArray(nwpts,numPts,3);
mathobj->deleteArray(outPts,targetNumPts,3);
delete mathobj;
for ( i = 0; i < targetNumPts; i++ ) {
if ( i == (targetNumPts-1) ) {
j = 0;
} else {
j = i+1;
}
linesOut[3*i] = 2;
linesOut[3*i+1] = i;
linesOut[3*i+2] = j;
}
if ( VtkUtils_NewVtkPolyDataLines( &pdOut, targetNumPts, ptsOut,
targetNumPts, linesOut ) != SV_OK ) {
delete [] ptsOut;
delete [] linesOut;
return NULL;
}
result = new cvPolyData( pdOut );
pdOut->Delete();
delete [] ptsOut;
delete [] linesOut;
return result;
}
/* -------------- */
/* sys_geom_loft_solid */
/* -------------- */
int sys_geom_loft_solid( cvPolyData **srcs,int numSrcs,int useLinearSampleAlongLength,
int useFFT,int numOutPtsAlongLength, int numOutPtsInSegs,
int numLinearPtsAlongLength,int numModes,int splineType,double bias, double tension,double continuity, cvPolyData **dst )
{
cvPolyData *result = NULL;
*dst = NULL;
vtkNew(vtkSVLoftSplineSurface,lofter);
for (int i=0;i<numSrcs;i++)
{
vtkPolyData *newPd = srcs[i]->GetVtkPolyData();
lofter->AddInputData(newPd);
}
lofter->SetUseLinearSampleAlongLength(useLinearSampleAlongLength);
lofter->SetUseFFT(useFFT);
lofter->SetNumOutPtsAlongLength(numOutPtsAlongLength);
lofter->SetNumOutPtsInSegs(numOutPtsInSegs);
lofter->SetNumLinearPtsAlongLength(numLinearPtsAlongLength);
lofter->SetNumModes(numModes);
lofter->SetSplineType(splineType);
lofter->SetBias(bias);
lofter->SetTension(tension);
lofter->SetContinuity(continuity);
try {
lofter->Update();
result = new cvPolyData(lofter->GetOutput());
*dst = result;
}
catch (...) {
fprintf(stderr,"ERROR in boolean operation.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
/* -------------- */
/* sys_geom_loft_solid_with_nurbs */
/* -------------- */
int sys_geom_loft_solid_with_nurbs(cvPolyData **srcs, int numSrcs, int uDegree,
int vDegree, double uSpacing, double vSpacing,
const char *uKnotSpanType, const char *vKnotSpanType,
const char *uParametricSpanType, const char *vParametricSpanType,
vtkSVNURBSSurface *surface,
cvPolyData **dst )
{
cvPolyData *result = NULL;
*dst = NULL;
vtkNew(vtkSVLoftNURBSSurface,lofter);
// Set up the structured grid
int dim[3]; dim[0] = numSrcs; dim[1] = srcs[0]->GetVtkPolyData()->GetNumberOfPoints() + 1; dim[2] = 1;
vtkNew(vtkPoints, inputGridPoints);
inputGridPoints->SetNumberOfPoints(dim[0] * dim[1]);
vtkNew(vtkStructuredGrid, inputGrid);
inputGrid->SetPoints(inputGridPoints);
inputGrid->SetDimensions(dim);
// Loop through to set points on structured grid
int ptId;
int pos[3];
double pt[3];
for (int i=0;i<numSrcs;i++)
{
for (int j=0; j<srcs[i]->GetVtkPolyData()->GetNumberOfPoints(); j++)
{
srcs[i]->GetVtkPolyData()->GetPoint(j, pt);
pos[0] = i; pos[1] = j; pos[2] = 0;
ptId = vtkStructuredData::ComputePointId(dim, pos);
inputGrid->GetPoints()->SetPoint(ptId, pt);
}
// Get 1st point and copy to the end. For watertight surface, we need
// to provide first point at the beginning and end.
srcs[i]->GetVtkPolyData()->GetPoint(0, pt);
pos[0] = i; pos[1] = srcs[i]->GetVtkPolyData()->GetNumberOfPoints(); pos[2] = 0;
ptId = vtkStructuredData::ComputePointId(dim, pos);
inputGrid->GetPoints()->SetPoint(ptId, pt);
}
// Set up lofter
lofter->SetInputData(inputGrid);
lofter->SetUDegree(uDegree);
lofter->SetVDegree(vDegree);
lofter->SetPolyDataUSpacing(uSpacing);
lofter->SetPolyDataVSpacing(vSpacing);
lofter->SetUKnotSpanType(uKnotSpanType);
lofter->SetVKnotSpanType(vKnotSpanType);
lofter->SetUParametricSpanType(uParametricSpanType);
lofter->SetVParametricSpanType(vParametricSpanType);
try {
lofter->Update();
if (lofter->GetOutput() == NULL)
return SV_ERROR;
if (lofter->GetOutput()->GetNumberOfPoints() == 0)
return SV_ERROR;
surface->DeepCopy(lofter->GetSurface());
// The NURBS is a vtkPolyDataAlgorithm and thus, returns a PolyData
// representation. To get the NURBS surface use GetSurface()
// Triangulate the surface
vtkNew(vtkTriangleFilter, triangulator);
triangulator->SetInputData(lofter->GetOutput());
triangulator->Update();
result = new cvPolyData(triangulator->GetOutput());
*dst = result;
}
catch (...) {
fprintf(stderr,"ERROR in creating solid with nurbs lofting.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
// ---------------------
// sys_geom_2DWindingNum
// ---------------------
// Assumes src is a 2D polygon in the xy plane.
int sys_geom_2DWindingNum( cvPolyData *pgn )
{
cvPolyData *tmp;
vtkPolyData *pd;
vtkIdType *lines;
int numLines;
double *pts;
int numPts;
int *lineIds;
int numLineIds;
int lineId;
int curr, next;
int currI, currJ;
int nextI, nextJ;
double currVec[3], nextVec[3];
double sign;
double dtheta;
double tot_theta = 0.0;
int wnum;
tmp = sys_geom_MergePts( pgn );
pd = tmp->GetVtkPolyData();
VtkUtils_GetLines( pd, &lines, &numLines );
VtkUtils_GetPoints( pd, &pts, &numPts );
if ( VtkUtils_GetClosedLineRegion( lines, numLines, 0,
&lineIds, &numLineIds ) != SV_OK ) {
delete tmp;
delete [] lines;
delete [] pts;
printf( "ERR: get closed line region failed\n" );
return 0;
}
for ( curr = 0; curr < numLineIds; curr++ ) {
lineId = lineIds[curr];
currI = lines[2*lineId];
currJ = lines[2*lineId+1];
if ( curr == (numLineIds-1) ) {
next = 0;
} else {
next = curr + 1;
}
lineId = lineIds[next];
nextI = lines[2*lineId];
nextJ = lines[2*lineId+1];
currVec[0] = pts[3*currJ] - pts[3*currI];
currVec[1] = pts[3*currJ+1] - pts[3*currI+1];
currVec[2] = 0.0;
NormVector( &(currVec[0]), &(currVec[1]), &(currVec[2]) );
nextVec[0] = pts[3*nextJ] - pts[3*nextI];
nextVec[1] = pts[3*nextJ+1] - pts[3*nextI+1];
nextVec[2] = 0.0;
NormVector( &(nextVec[0]), &(nextVec[1]), &(nextVec[2]) );
// This is nothing more than the z-component of curr x next:
sign = currVec[0] * nextVec[1] - currVec[1] * nextVec[0];
if ( sign < 0.0 ) {
dtheta = - acos( currVec[0] * nextVec[0] + currVec[1] * nextVec[1] );
} else {
dtheta = acos( currVec[0] * nextVec[0] + currVec[1] * nextVec[1] );
}
tot_theta += dtheta;
}
wnum = svRound( tot_theta / (2 * CV_PI) );
delete tmp;
delete [] lines;
delete [] pts;
delete [] lineIds;
return wnum;
}
// ----------------------
// sys_geom_PolygonNormal
// ----------------------
int sys_geom_PolygonNormal( cvPolyData *pgn, double n[] )
{
double *pts;
int numPts;
int i, j;
double v0[3], v1[3], v2[3];
double ax, ay, az, bx, by, bz;
if ( sys_geom_GetOrderedPts( pgn, &pts, &numPts ) != SV_OK ) {
printf( "ERR: get ordered points failed\n" );
return SV_ERROR;
}
// Adapted from vtk-3.1-beta/common/vtkPolygon.cxx:
// Because polygon may be concave, need to accumulate cross products to
// determine true normal.
v1[0] = pts[0];
v1[1] = pts[1];
v1[2] = pts[2];
v2[0] = pts[3];
v2[1] = pts[4];
v2[2] = pts[5];
n[0] = 0.0;
n[1] = 0.0;
n[2] = 0.0;
for ( i = 0; i < numPts; i++ ) {
v0[0] = v1[0];
v0[1] = v1[1];
v0[2] = v1[2];
v1[0] = v2[0];
v1[1] = v2[1];
v1[2] = v2[2];
j = (i + 2) % numPts;
v2[0] = pts[3*j];
v2[1] = pts[3*j+1];
v2[2] = pts[3*j+2];
// order is important!!! to maintain consistency with polygon vertex order
ax = v2[0] - v1[0];
ay = v2[1] - v1[1];
az = v2[2] - v1[2];
bx = v0[0] - v1[0];
by = v0[1] - v1[1];
bz = v0[2] - v1[2];
n[0] += (ay * bz - az * by);
n[1] += (az * bx - ax * bz);
n[2] += (ax * by - ay * bx);
}
NormVector( &(n[0]), &(n[1]), &(n[2]) );
delete [] pts;
return SV_OK;
}
// --------------
// sys_geom_AvgPt
// --------------
// This does NOT produce a centroid.
int sys_geom_AvgPt( cvPolyData *src, double pt[] )
{
cvPolyData *tmp;
vtkPolyData *pd;
double *pts;
int numPts;
int i;
tmp = sys_geom_MergePts( src );
pd = tmp->GetVtkPolyData();
if ( VtkUtils_GetPoints( pd, &pts, &numPts ) != SV_OK ) {
printf( "ERR: get points failed\n" );
delete tmp;
return SV_ERROR;
}
pt[0] = pt[1] = pt[2] = 0.0;
for ( i = 0; i < numPts; i++ ) {
pt[0] += pts[3*i];
pt[1] += pts[3*i+1];
pt[2] += pts[3*i+2];
}
pt[0] /= numPts;
pt[1] /= numPts;
pt[2] /= numPts;
delete tmp;
delete [] pts;
return SV_OK;
}
// --------------------------
// sys_geom_interpolateScalar
// --------------------------
int sys_geom_InterpolateScalar( cvPolyData *src, double pt[], double *scalar )
{
// return value
double s = 0.0;
*scalar = s;
vtkFloatingPointType x[3];
vtkFloatingPointType closestPoint[3];
vtkIdType cellId = 0;
int subId = 0;
vtkFloatingPointType dist2 = 0;
vtkFloatingPointType pcoords[3];
vtkFloatingPointType weights[10];
vtkFloatingPointType *weightsPtr;
vtkFloatingPointType *closestPointPtr;
vtkPolyData *pd;
pd = src->GetVtkPolyData();
x[0]=pt[0];x[1]=pt[1];x[2]=pt[2];
vtkCellLocator *locator = vtkCellLocator::New();
vtkGenericCell *cell = vtkGenericCell::New();
locator->SetDataSet(pd);
locator->BuildLocator();
locator->FindClosestPoint(x, closestPoint, cell, cellId, subId, dist2);
closestPointPtr = closestPoint;
weightsPtr = weights;
if (cell->EvaluatePosition (x,closestPointPtr,subId,pcoords,dist2,weightsPtr) == 0) {
fprintf(stderr,"ERROR: Point is not inside of generic cell!\n");
locator->Delete();
cell->Delete();
return SV_ERROR;
}
//fprintf(stdout,"pcoords: %f %f %f cellId: %i subId; %i dist: %f\n",
// pcoords[0],pcoords[1],pcoords[2],cellId,subId,sqrt(dist2));
vtkIdList *ids = vtkIdList::New();
ids->Allocate(10,10);
ids->Initialize();
pd->GetCellPoints(cellId,ids);
if (ids->GetNumberOfIds() == 0) {
fprintf(stderr,"ERROR: No id's found for cell %i.\n",cellId);
ids->Delete();
locator->Delete();
cell->Delete();
return SV_ERROR;
}
vtkDataArray *vScalars = pd->GetPointData()->GetScalars();
vtkFloatingPointType nodeScalar = 0.0;
int numIds = ids->GetNumberOfIds();
for (int i = 0; i < numIds; i++) {
nodeScalar = vScalars->GetTuple1(ids->GetId(i));
s += weights[i]*nodeScalar;
//fprintf(stdout,"%i: weight: %f value: %f\n", i,weights[i],nodeScalar);
}
ids->Delete();
locator->Delete();
cell->Delete();
*scalar = s;
return SV_OK;
}
// --------------------------
// sys_geom_InterpolateVector
// --------------------------
int sys_geom_InterpolateVector( cvPolyData *src, double pt[], double vect[] )
{
// return value
double vx = 0.0;
double vy = 0.0;
double vz = 0.0;
vect[0] = vx;
vect[1] = vy;
vect[2] = vz;
vtkFloatingPointType x[3];
vtkFloatingPointType closestPoint[3];
vtkIdType cellId = 0;
int subId = 0;
vtkFloatingPointType dist2 = 0;
vtkFloatingPointType pcoords[3];
vtkFloatingPointType weights[10];
vtkFloatingPointType *weightsPtr;
vtkFloatingPointType *closestPointPtr;
vtkPolyData *pd;
pd = src->GetVtkPolyData();
x[0]=pt[0];x[1]=pt[1];x[2]=pt[2];
vtkCellLocator *locator = vtkCellLocator::New();
vtkGenericCell *cell = vtkGenericCell::New();
locator->SetDataSet(pd);
locator->BuildLocator();
locator->FindClosestPoint(x, closestPoint, cell, cellId, subId, dist2);
closestPointPtr = closestPoint;
weightsPtr = weights;
if (cell->EvaluatePosition (x,closestPointPtr,subId,pcoords,dist2,weightsPtr) == 0) {
fprintf(stderr,"ERROR: Point is not inside of generic cell!\n");
locator->Delete();
cell->Delete();
return SV_ERROR;
}
// fprintf(stdout,"pcoords: %f %f %f cellId: %i subId; %i dist: %f\n",
// pcoords[0],pcoords[1],pcoords[2],cellId,subId,sqrt(dist2));
vtkIdList *ids = vtkIdList::New();
ids->Allocate(10,10);
ids->Initialize();
pd->GetCellPoints(cellId,ids);
if (ids->GetNumberOfIds() == 0) {
fprintf(stderr,"ERROR: No id's found for cell %i.\n",cellId);
ids->Delete();
locator->Delete();
cell->Delete();
return SV_ERROR;
}
vtkDataArray *vVectors= pd->GetPointData()->GetVectors();
vtkFloatingPointType *nodeVector;
int numIds = ids->GetNumberOfIds();
for (int i = 0; i < numIds; i++) {
nodeVector = vVectors->GetTuple(ids->GetId(i));
vx += weights[i]*nodeVector[0];
vy += weights[i]*nodeVector[1];
vz += weights[i]*nodeVector[2];
// fprintf(stdout,"%i: weight: %f value: %f %f %f\n", i,weights[i],nodeVector[0], nodeVector[1], nodeVector[2]);
}
ids->Delete();
locator->Delete();
cell->Delete();
vect[0] = vx;
vect[1] = vy;
vect[2] = vz;
return SV_OK;
}
// --------------------------
// sys_geom_IntersectWithLine
// --------------------------
int sys_geom_IntersectWithLine( cvPolyData *src, double p0[], double p1[], double intersect[] )
{
// return value
intersect[0] = 0.0;
intersect[1] = 0.0;
intersect[2] = 0.0;
vtkFloatingPointType a0[3];
vtkFloatingPointType a1[3];
vtkFloatingPointType tol = 0.001;
vtkFloatingPointType t = 0.0;
vtkFloatingPointType x[3];
vtkFloatingPointType pcoords[3];
int subId = 0;
vtkIdType cellId = 0;
vtkPolyData *pd;
pd = src->GetVtkPolyData();
for (int i=0; i < 3; i++) {
a0[i]=p0[i];
a1[i]=p1[i];
}
vtkOBBTree *locator = vtkOBBTree::New();
//vtkCellLocator *locator = vtkCellLocator::New();
vtkGenericCell *cell = vtkGenericCell::New();
locator->SetDataSet(pd);
locator->BuildLocator();
//fprintf(stdout,"a0: %f %f %f\n",a0[0],a0[1],a0[2]);
//fprintf(stdout,"a1: %f %f %f\n",a1[0],a1[1],a1[2]);
//fprintf(stdout,"tol: %f\n",tol);
vtkSmartPointer<vtkPoints> intersectionPoints =
vtkSmartPointer<vtkPoints>::New();
x[0]=0;x[1]=0;x[2]=0;
locator->IntersectWithLine(a0, a1, intersectionPoints,NULL);
if (intersectionPoints->GetNumberOfPoints() == 0) {
//if (locator->IntersectWithLine(a0,a1,tol,t,x,pcoords,subId,cellId,cell) == 0) {
fprintf(stderr,"ERROR: Line does not intersect vtkPolyData!\n");
locator->Delete();
cell->Delete();
return SV_ERROR;
}
intersectionPoints->GetPoint(0,x);
locator->Delete();
cell->Delete();
intersect[0]=x[0];intersect[1]=x[1];intersect[2]=x[2];
return SV_OK;
}
// -----------------
// geom_warp3dPts
// -----------------
cvPolyData *sys_geom_warp3dPts(cvPolyData *src, double scale) {
vtkPolyData *orgpd = src->GetVtkPolyData();
int numPts = orgpd->GetNumberOfPoints();
fprintf(stdout,"numPts: %i\n",numPts);
// get the normals and vectors
vtkDataArray* normals = orgpd->GetPointData()->GetNormals();
vtkDataArray* vectors = orgpd->GetPointData()->GetVectors();
vtkPoints* orgpts = orgpd->GetPoints();
// create return vtk vector
vtkPoints *newpts = vtkPoints::New();
//newpts->SetNumberOfComponents(3);
newpts->Allocate(numPts,10000);
newpts->Initialize();
vtkFloatArray *mags = vtkFloatArray::New();
mags->SetNumberOfComponents(1);
mags->Allocate(numPts,10000);
mags->Initialize();
vtkFloatingPointType nrm[3];
vtkFloatingPointType v[3];
vtkFloatingPointType newpt[3];
vtkFloatingPointType pt[3];
vtkFloatingPointType v_dot_n = 0.0;
for (int i = 0; i < numPts; i++) {
// get outward normal
normals->GetTuple(i,nrm);
vectors->GetTuple(i,v);
orgpts->GetPoint(i,pt);
// calculate normal component
v_dot_n = v[0]*nrm[0]+v[1]*nrm[1]+v[2]*nrm[2];
mags->InsertNextTuple1(v_dot_n);
// scale by factor and add along normal vector
newpt[0] = pt[0]+v_dot_n*scale*nrm[0];
newpt[1] = pt[1]+v_dot_n*scale*nrm[1];
newpt[2] = pt[2]+v_dot_n*scale*nrm[2];
newpts->InsertNextPoint(newpt[0],newpt[1],newpt[2]);
}
// create cvPolyData object to return
vtkPolyData* pd = vtkPolyData::New();
pd->CopyStructure(orgpd);
pd->SetPoints(newpts);
pd->GetPointData()->SetScalars(mags);
cvPolyData* reposobj = new cvPolyData(pd);
return reposobj;
}
// ----------------------
// geom_mathPointData
// ----------------------
int sys_geom_mathPointData( cvPolyData *srcA, cvPolyData *srcB, sys_geom_math_scalar scflag,
sys_geom_math_vector vflag, cvPolyData **dst ) {
int i = 0;
int j = 0;
vtkFloatingPointType myvec[3];
vtkFloatingPointType s=0;
vtkFloatingPointType tmpvec[3];
vtkFloatingPointType tmps=0;
vtkFloatingPointArrayType *scalar = NULL;
vtkFloatingPointArrayType *vec = NULL;
// all of the pds must have the same num pts
int numPtsA = srcA->GetVtkPolyData()->GetNumberOfPoints();
int numPtsB = srcB->GetVtkPolyData()->GetNumberOfPoints();
int numPts = numPtsA;
if (numPtsA != numPtsB) {
return SV_ERROR;
}
if (scflag == SYS_GEOM_NO_SCALAR && vflag == SYS_GEOM_NO_VECTOR) {
return SV_ERROR;
}
// get pointers to data
if (scflag != SYS_GEOM_NO_SCALAR) {
vtkDataArray *scalarsA=srcA->GetVtkPolyData()->GetPointData()->GetScalars();
vtkDataArray *scalarsB=srcB->GetVtkPolyData()->GetPointData()->GetScalars();
// create return vtk scalar array
scalar = vtkFloatingPointArrayType::New();
scalar->SetNumberOfComponents(1);
scalar->Allocate(numPts,1000);
scalar->Initialize();
for (i = 0; i < numPts; i++) {
s = scalarsA->GetTuple1(i);
tmps = scalarsB->GetTuple1(i);
if (scflag == SYS_GEOM_ADD_SCALAR) {
s = s + tmps;
} else if (scflag == SYS_GEOM_SUBTRACT_SCALAR) {
s = s - tmps;
} else if (scflag == SYS_GEOM_MULTIPLY_SCALAR) {
s = s * tmps;
} else if (scflag == SYS_GEOM_DIVIDE_SCALAR) {
s = s / tmps;
} else {
fprintf(stdout,"invalid flag!\n");
return SV_ERROR;
}
scalar->InsertNextTuple1(s);
}
}
if (vflag != SYS_GEOM_NO_VECTOR) {
vtkDataArray *vectorsA=srcA->GetVtkPolyData()->GetPointData()->GetVectors();
vtkDataArray *vectorsB=srcB->GetVtkPolyData()->GetPointData()->GetVectors();
// create return vtk vector array
vec = vtkFloatingPointArrayType::New();
vec->SetNumberOfComponents(3);
vec->Allocate(numPts,1000);
vec->Initialize();
for (i = 0; i < numPts; i++) {
vectorsA->GetTuple(i,myvec);
vectorsB->GetTuple(i,tmpvec);
if (vflag == SYS_GEOM_ADD_VECTOR) {
myvec[0] = myvec[0]+tmpvec[0];
myvec[1] = myvec[1]+tmpvec[1];
myvec[2] = myvec[2]+tmpvec[2];
} else if (vflag == SYS_GEOM_SUBTRACT_VECTOR) {
myvec[0] = myvec[0]-tmpvec[0];
myvec[1] = myvec[1]-tmpvec[1];
myvec[2] = myvec[2]-tmpvec[2];
} else if (vflag == SYS_GEOM_MULTIPLY_VECTOR) {
myvec[0] = myvec[0]*tmpvec[0];
myvec[1] = myvec[1]*tmpvec[1];
myvec[2] = myvec[2]*tmpvec[2];
} else if (vflag == SYS_GEOM_DIVIDE_VECTOR) {
myvec[0] = myvec[0]/tmpvec[0];
myvec[1] = myvec[1]/tmpvec[1];
myvec[2] = myvec[2]/tmpvec[2];
} else {
fprintf(stdout,"invalid flag!\n");
return SV_ERROR;
}
vec->InsertNextTuple3(myvec[0],myvec[1],myvec[2]);
}
}
// create cvPolyData object to return
vtkPolyData* pd = vtkPolyData::New();
pd->CopyStructure(srcA->GetVtkPolyData());
if (scflag != SYS_GEOM_NO_SCALAR) {
pd->GetPointData()->SetScalars(scalar);
}
if (vflag != SYS_GEOM_NO_VECTOR) {
pd->GetPointData()->SetVectors(vec);
}
cvPolyData* reposobj = new cvPolyData(pd);
*dst = reposobj;
pd->Delete();
return SV_OK;
}
// ----------------------
// geom_Project
// ----------------------
int sys_geom_Project( cvPolyData *srcA, cvPolyData *srcB, sys_geom_math_scalar scflag,
sys_geom_math_vector vflag, cvPolyData **dst ) {
int i = 0;
int j = 0;
vtkFloatingPointType s=0;
vtkFloatingPointArrayType *scalar = NULL;
vtkFloatingPointArrayType *vec = NULL;
double vx = 0.0;
double vy = 0.0;
double vz = 0.0;
vtkFloatingPointType x[3];
vtkFloatingPointType closestPoint[3];
vtkIdType cellId = 0;
int subId = 0;
vtkFloatingPointType dist2 = 0;
vtkFloatingPointType pcoords[3];
vtkFloatingPointType weights[10];
vtkFloatingPointType *weightsPtr;
vtkFloatingPointType *closestPointPtr;
vtkPolyData *pdA = srcA->GetVtkPolyData();
vtkPolyData *pdB = srcB->GetVtkPolyData();
// all of the pds must have the same num pts
int numPtsA = pdA->GetNumberOfPoints();
int numPtsB = pdB->GetNumberOfPoints();
if (scflag == SYS_GEOM_NO_SCALAR && vflag == SYS_GEOM_NO_VECTOR) {
return SV_ERROR;
}
// build a locator to find closest points in A
vtkCellLocator *locator = vtkCellLocator::New();
vtkGenericCell *cell = vtkGenericCell::New();
locator->SetDataSet(pdA);
locator->BuildLocator();
vtkDataArray *scalarsA;
vtkDataArray *vectorsA;
// get pointers to data and create return objects
if (scflag != SYS_GEOM_NO_SCALAR) {
scalarsA=srcA->GetVtkPolyData()->GetPointData()->GetScalars();
// create return vtk scalar array
scalar = vtkFloatingPointArrayType::New();
scalar->SetNumberOfComponents(1);
scalar->Allocate(numPtsB,1000);
scalar->Initialize();
}
if (vflag != SYS_GEOM_NO_VECTOR) {
vectorsA=srcA->GetVtkPolyData()->GetPointData()->GetVectors();
// create return vtk vector array
vec = vtkFloatingPointArrayType::New();
vec->SetNumberOfComponents(3);
vec->Allocate(numPtsB,1000);
vec->Initialize();
}
vtkIdList *ids = vtkIdList::New();
ids->Allocate(10,10);
ids->Initialize();
for (i = 0; i < numPtsB; i++) {
pdB->GetPoint(i,x);
locator->FindClosestPoint(x, closestPoint, cell, cellId, subId, dist2);
closestPointPtr = closestPoint;
weightsPtr = weights;
if (cell->EvaluatePosition (x,closestPointPtr,subId,pcoords,dist2,weightsPtr) == 0) {
fprintf(stderr,"Warning: Point is not inside of generic cell!\n");
fprintf(stderr," using average value for cell.\n");
weights[0]=1.0/3.0;
weights[1]=1.0/3.0;
weights[2]=1.0/3.0;
}
pdA->GetCellPoints(cellId,ids);
if (ids->GetNumberOfIds() == 0) {
fprintf(stderr,"ERROR: No id's found for cell %i.\n",cellId);
ids->Delete();
locator->Delete();
cell->Delete();
if (scalar != NULL) {
scalar->Delete();
}
if (vec != NULL) {
vec->Delete();
}
return SV_ERROR;
}
vtkFloatingPointType *nodeVector;
vtkFloatingPointType nodeScalar;
int numIds = ids->GetNumberOfIds();
vx = 0.0; vy = 0.0; vz = 0.0; s = 0.0;
for (int i = 0; i < numIds; i++) {
if (scflag != SYS_GEOM_NO_SCALAR) {
nodeScalar = scalarsA->GetTuple1(ids->GetId(i));
s += weights[i]*nodeScalar;
}
if (vflag != SYS_GEOM_NO_VECTOR) {
nodeVector = vectorsA->GetTuple(ids->GetId(i));
vx += weights[i]*nodeVector[0];
vy += weights[i]*nodeVector[1];
vz += weights[i]*nodeVector[2];
// fprintf(stdout,"%i: weight: %f value: %f %f %f\n", i,weights[i],nodeVector[0], nodeVector[1], nodeVector[2]);
}
}
if (scflag != SYS_GEOM_NO_SCALAR) scalar->InsertNextTuple1(s);
if (vflag != SYS_GEOM_NO_VECTOR) vec->InsertNextTuple3(vx,vy,vz);
}
// create cvPolyData object to return
vtkPolyData* pd = vtkPolyData::New();
pd->CopyStructure(srcB->GetVtkPolyData());
if (scflag != SYS_GEOM_NO_SCALAR) {
pd->GetPointData()->SetScalars(scalar);
}
if (vflag != SYS_GEOM_NO_VECTOR) {
pd->GetPointData()->SetVectors(vec);
}
cvPolyData* reposobj = new cvPolyData(pd);
*dst = reposobj;
pd->Delete();
// clean up
ids->Delete();
locator->Delete();
cell->Delete();
if (scalar != NULL) scalar->Delete();
if (vec != NULL) vec->Delete();
return SV_OK;
}
// -------------------------
// geom_ReplacePointData
// -------------------------
int sys_geom_ReplacePointData( cvPolyData *srcA, cvPolyData *srcB, sys_geom_math_scalar scflag,
sys_geom_math_vector vflag, cvPolyData **dst ) {
int i = 0;
int j = 0;
vtkFloatingPointType s=0;
vtkFloatingPointArrayType *scalar = NULL;
vtkFloatingPointArrayType *vec = NULL;
double vx = 0.0;
double vy = 0.0;
double vz = 0.0;
vtkPolyData *pdA = srcA->GetVtkPolyData();
vtkPolyData *pdB = srcB->GetVtkPolyData();
// all of the pds must have the same num pts
int numPtsA = pdA->GetNumberOfPoints();
int numPtsB = pdB->GetNumberOfPoints();
if (scflag == SYS_GEOM_NO_SCALAR && vflag == SYS_GEOM_NO_VECTOR) {
return SV_ERROR;
}
// must have scalars on srcB
vtkDataArray *scalarsB = NULL;
scalarsB=srcB->GetVtkPolyData()->GetPointData()->GetScalars();
if (scalarsB == NULL) {
fprintf(stderr,"ERROR: no scalars on srcB!\n");
return SV_ERROR;
}
vtkDataArray *scalarsA;
vtkDataArray *vectorsA;
// get pointers to data and create return objects
if (scflag != SYS_GEOM_NO_SCALAR) {
scalarsA=srcA->GetVtkPolyData()->GetPointData()->GetScalars();
// create return vtk scalar array
scalar = vtkFloatingPointArrayType::New();
scalar->SetNumberOfComponents(1);
scalar->Allocate(numPtsB,1000);
scalar->Initialize();
}
if (vflag != SYS_GEOM_NO_VECTOR) {
vectorsA=srcA->GetVtkPolyData()->GetPointData()->GetVectors();
// create return vtk vector array
vec = vtkFloatingPointArrayType::New();
vec->SetNumberOfComponents(3);
vec->Allocate(numPtsB,1000);
vec->Initialize();
}
for (i = 0; i < numPtsB; i++) {
double sB = scalarsB->GetTuple1(i);
int iB = (int)sB;
//fprintf(stdout,"sB: %lf iB: %i\n",sB,iB);
vtkFloatingPointType *nodeVector;
vtkFloatingPointType nodeScalar;
s =0.0;
vx = 0.0; vy = 0.0; vz = 0.0; s = 0.0;
// need to offset by -1 here since node
// numbers start at 1 but vtk starts refs
// at 0
iB = iB - 1;
if (scflag != SYS_GEOM_NO_SCALAR) {
nodeScalar = scalarsA->GetTuple1(iB);
s = nodeScalar;
}
if (vflag != SYS_GEOM_NO_VECTOR) {
nodeVector = vectorsA->GetTuple(iB);
vx = nodeVector[0];
vy = nodeVector[1];
vz = nodeVector[2];
}
if (scflag != SYS_GEOM_NO_SCALAR) scalar->InsertNextTuple1(s);
if (vflag != SYS_GEOM_NO_VECTOR) vec->InsertNextTuple3(vx,vy,vz);
}
// create cvPolyData object to return
vtkPolyData* pd = vtkPolyData::New();
pd->CopyStructure(srcB->GetVtkPolyData());
if (scflag != SYS_GEOM_NO_SCALAR) {
pd->GetPointData()->SetScalars(scalar);
}
if (vflag != SYS_GEOM_NO_VECTOR) {
pd->GetPointData()->SetVectors(vec);
}
cvPolyData* reposobj = new cvPolyData(pd);
*dst = reposobj;
pd->Delete();
// clean up
if (scalar != NULL) scalar->Delete();
if (vec != NULL) vec->Delete();
return SV_OK;
}
/* -------------- */
/* sys_geom_set_array_for_local_op_sphere */
/* -------------- */
/** @author Adam Updegrove
* @author updega2@gmail.com
* @author UC Berkeley
* @author shaddenlab.berkeley.edu
*
* @brief Function to set a boolean array on the surface for local mesh operations.
* Points are set based on cells or points in spherical region. If based on cells,
* cell is determine to be in sphere if the centroid of the cell is within the sphere.
* @param *pd The input polydata on which to set an array
* @param **outpd polydata that contains the output surface with new array
* @param radius radius of the sphere
* @param *center center of the sphere
* @param *outarray This contains the arrayname holding the boolean array
* @param datatype This indicates whether the input array is point data (0)
* or cell data (1)
* @return SV_OK if the function executes properly
*/
int sys_geom_set_array_for_local_op_sphere( cvPolyData *pd,cvPolyData **outpd,double radius,double *center,char *outarrayname,int datatype)
{
vtkPolyData *geom = pd->GetVtkPolyData();
cvPolyData *result = NULL;
/*
fprintf(stdout,"Adding array in sphere\n");
fprintf(stdout,"Out Array Name: %s\n",outarrayname);
fprintf(stdout,"Radius: %.3f\n",radius);
fprintf(stdout,"Center: %.3f %.3f %.3f\n",center[0],center[1],center[2]);
fprintf(stdout,"Datatype: %d\n",datatype);
*/
vtkNew(vtkPolyData,tmp);
tmp->DeepCopy(geom);
tmp->BuildLinks();
vtkNew(vtkIntArray,newArray);
newArray->SetName(outarrayname);
if (datatype == 0)
{
double pt[3];
int numPoints = tmp->GetNumberOfPoints();
if (VtkUtils_PDCheckArrayName(tmp,0,outarrayname) != SV_OK)
{
newArray->SetNumberOfTuples(numPoints);
for (vtkIdType id=0;id < numPoints;id++)
newArray->InsertValue(id,0);
}
else
newArray = vtkIntArray::SafeDownCast(tmp->GetPointData()->GetArray(outarrayname));
for (vtkIdType id=0; id < numPoints;id++)
{
tmp->GetPoint(id,pt);
double dist = sqrt(pow(pt[0] - center[0],2) +
pow(pt[1] - center[1],2) +
pow(pt[2] - center[2],2));
if (dist <= radius)
newArray->InsertValue(id,1);
}
if (VtkUtils_PDCheckArrayName(tmp,0,outarrayname) == SV_OK)
tmp->GetPointData()->RemoveArray(outarrayname);
tmp->GetPointData()->AddArray(newArray);
}
else
{
double centroid[3];
vtkIdType npts,*pts;
int numCells = tmp->GetNumberOfCells();
if (VtkUtils_PDCheckArrayName(tmp,1,outarrayname) != SV_OK)
{
newArray->SetNumberOfTuples(numCells);
for (vtkIdType id=0;id < numCells;id++)
newArray->InsertValue(id,0);
}
else
newArray = vtkIntArray::SafeDownCast(tmp->GetCellData()->GetArray(outarrayname));
for (vtkIdType id=0; id < numCells;id++)
{
tmp->GetCellPoints(id,npts,pts);
vtkSmartPointer<vtkPoints> polyPts = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkIdTypeArray> polyPtIds = vtkSmartPointer<vtkIdTypeArray>::New();
for (int i=0;i<npts;i++)
{
polyPtIds->InsertValue(i,i);
polyPts->InsertNextPoint(tmp->GetPoint(pts[i]));
}
vtkPolygon::ComputeCentroid(polyPtIds,polyPts,centroid);
double dist = sqrt(pow(centroid[0] - center[0],2) +
pow(centroid[1] - center[1],2) +
pow(centroid[2] - center[2],2));
if (dist <= radius)
newArray->InsertValue(id,1);
}
if (VtkUtils_PDCheckArrayName(tmp,1,outarrayname) == SV_OK)
tmp->GetCellData()->RemoveArray(outarrayname);
tmp->GetCellData()->AddArray(newArray);
}
result = new cvPolyData(tmp);
*outpd = result;
return SV_OK;
}
/* -------------- */
/* sys_geom_set_array_for_local_op_face */
/* -------------- */
/** @author Adam Updegrove
* @author updega2@gmail.com
* @author UC Berkeley
* @author shaddenlab.berkeley.edu
*
* @brief Function to set a boolean array on the surface for local mesh operations.
* Points are set based on an id of a given array
* @param *pd The input polydata on which to set an array
* @param **outpd polydata that contains the output surface with new array
* @param *arrayname array on which to look for the given values
* @param *values ids to looks for in the given array name. Cells with this
* id are given a value of 1
* @param *outarray This contains the arrayname holding the boolean array
* @param datatype This indicates whether the input array is point data (0)
* or cell data (1)
* values indication with cells to decimate
* @return SV_OK if the function executes properly
*/
int sys_geom_set_array_for_local_op_face( cvPolyData *pd,cvPolyData **outpd,char *inarrayname,int *vals,int nvals,char *outarrayname,int datatype)
{
vtkPolyData *geom = pd->GetVtkPolyData();
cvPolyData *result = NULL;
/*
fprintf(stdout,"Adding array on face\n");
fprintf(stdout,"Given Array Name: %s\n",inarrayname);
fprintf(stdout,"Target Array Name: %s\n",outarrayname);
fprintf(stdout,"Array Type: %d\n",datatype);
fprintf(stdout,"Number of Ids: %d\n",nvals);
*/
double range[2];
int max;
int value=0;
int *wantval;
vtkNew(vtkPolyData,tmp);
tmp->DeepCopy(geom);
vtkNew(vtkIntArray,newArray);
newArray->SetName(outarrayname);
if (datatype == 0)
{
if (VtkUtils_PDCheckArrayName(tmp,0,inarrayname) != SV_OK)
{
fprintf(stderr,"%s Array is not on the surface\n",inarrayname);
return SV_ERROR;
}
int numPoints = tmp->GetNumberOfPoints();
if (VtkUtils_PDCheckArrayName(tmp,0,outarrayname) != SV_OK)
{
newArray->SetNumberOfTuples(numPoints);
for (vtkIdType id=0;id< numPoints;id++)
newArray->InsertValue(id,0);
}
else
newArray = vtkIntArray::SafeDownCast(tmp->GetPointData()->GetArray(outarrayname));
tmp->GetPointData()->GetArray(inarrayname)->GetRange(range);
max = range[1];
wantval = new int[max];
for (int i=0; i< max; i++)
wantval[i] = 0;
for (int i=0; i< nvals; i++)
wantval[vals[i]-1] = 1;
for (vtkIdType id=0;id < numPoints; id++)
{
value = (int)tmp->GetPointData()->GetArray(inarrayname)->GetTuple1(id);
if (wantval[value-1])
newArray->InsertValue(id,1);
}
if (VtkUtils_PDCheckArrayName(tmp,0,outarrayname) == SV_OK)
tmp->GetPointData()->RemoveArray(outarrayname);
tmp->GetPointData()->AddArray(newArray);
delete [] wantval;
}
else
{
if (VtkUtils_PDCheckArrayName(tmp,1,inarrayname) != SV_OK)
{
fprintf(stderr,"%s Array is not on the surface\n",inarrayname);
return SV_ERROR;
}
int numCells = tmp->GetNumberOfCells();
if (VtkUtils_PDCheckArrayName(tmp,1,outarrayname) != SV_OK)
{
newArray->SetNumberOfTuples(numCells);
for (vtkIdType id=0;id< numCells;id++)
newArray->InsertValue(id,0);
}
else
newArray = vtkIntArray::SafeDownCast(tmp->GetCellData()->GetArray(outarrayname));
tmp->GetCellData()->GetArray(inarrayname)->GetRange(range);
max = range[1];
wantval = new int[max];
for (int i=0; i< max; i++)
wantval[i] = 0;
for (int i=0; i< nvals; i++)
wantval[vals[i]-1] = 1;
for (int id=0;id < numCells; id++)
{
value = (int)tmp->GetCellData()->GetArray(inarrayname)->GetTuple1(id);
if (wantval[value-1])
newArray->InsertValue(id,1);
}
if (VtkUtils_PDCheckArrayName(tmp,1,outarrayname) == SV_OK)
tmp->GetCellData()->RemoveArray(outarrayname);
tmp->GetCellData()->AddArray(newArray);
delete [] wantval;
}
result = new cvPolyData(tmp);
*outpd = result;
return SV_OK;
}
/* -------------- */
/* sys_geom_set_array_for_local_op_cells */
/* -------------- */
/** @author Adam Updegrove
* @author updega2@gmail.com
* @author UC Berkeley
* @author shaddenlab.berkeley.edu
*
* @brief Function to set a boolean array on the surface for local mesh operations.
* Points are set based on an id of a given array
* @param *pd The input polydata on which to set an array
* @param **outpd polydata that contains the output surface with new array
* @param *values ids of cells to change on PolyData1
* @param *outarray This contains the arrayname holding the boolean array
* @param datatype This indicates whether the input array is point data (0)
* or cell data (1)
* values indication with cells to decimate
* @return SV_OK if the function executes properly
*/
int sys_geom_set_array_for_local_op_cells( cvPolyData *pd,cvPolyData **outpd,int *vals,int nvals,char *outarrayname,int datatype)
{
vtkPolyData *geom = pd->GetVtkPolyData();
cvPolyData *result = NULL;
fprintf(stdout,"Adding array on cells\n");
fprintf(stdout,"Target Array Name: %s\n",outarrayname);
fprintf(stdout,"Array Type: %d\n",datatype);
fprintf(stdout,"Number of Ids: %d\n",nvals);
int *wantval;
vtkNew(vtkPolyData,tmp);
tmp->DeepCopy(geom);
vtkNew(vtkIntArray,newArray);
newArray->SetName(outarrayname);
if (datatype == 0)
{
int numPoints = tmp->GetNumberOfPoints();
if (VtkUtils_PDCheckArrayName(tmp,0,outarrayname) != SV_OK)
{
newArray->SetNumberOfTuples(numPoints);
for (vtkIdType id=0;id< numPoints;id++)
newArray->InsertValue(id,0);
}
else
newArray = vtkIntArray::SafeDownCast(tmp->GetPointData()->GetArray(outarrayname));
wantval = new int[numPoints];
for (int i=0; i< numPoints; i++)
wantval[i] = 0;
for (int i=0; i< nvals; i++)
wantval[vals[i]-1] = 1;
for (vtkIdType id=0;id < numPoints; id++)
{
if (wantval[id-1])
newArray->InsertValue(id,1);
}
if (VtkUtils_PDCheckArrayName(tmp,0,outarrayname) == SV_OK)
tmp->GetPointData()->RemoveArray(outarrayname);
tmp->GetPointData()->AddArray(newArray);
delete [] wantval;
}
else
{
int numCells = tmp->GetNumberOfCells();
if (VtkUtils_PDCheckArrayName(tmp,1,outarrayname) != SV_OK)
{
newArray->SetNumberOfTuples(numCells);
for (vtkIdType id=0;id< numCells;id++)
newArray->InsertValue(id,0);
}
else
newArray = vtkIntArray::SafeDownCast(tmp->GetCellData()->GetArray(outarrayname));
wantval = new int[numCells];
for (int i=0; i< numCells; i++)
wantval[i] = 0;
for (int i=0; i< nvals; i++)
wantval[vals[i]-1] = 1;
for (int id=0;id < numCells; id++)
{
if (wantval[id-1])
newArray->InsertValue(id,1);
}
if (VtkUtils_PDCheckArrayName(tmp,1,outarrayname) == SV_OK)
tmp->GetCellData()->RemoveArray(outarrayname);
tmp->GetCellData()->AddArray(newArray);
delete [] wantval;
}
result = new cvPolyData(tmp);
*outpd = result;
return SV_OK;
}
/* -------------- */
/* sys_geom_set_array_for_local_op_face_blend */
/* -------------- */
/** @author Adam Updegrove
* @author updega2@gmail.com
* @author UC Berkeley
* @author shaddenlab.berkeley.edu
*
* @brief Function to set a boolean array on the surface for local mesh operations.
* Points are set based on an id of a given array
* @param *pd The input polydata on which to set an array
* @param **outpd polydata that contains the output surface with new array
* @param *arrayname array on which to look for the given values
* @param *values ids to looks for in the given array name. Cells with this
* id are given a value of 1
* @param *outarray This contains the arrayname holding the boolean array
* @param datatype This indicates whether the input array is point data (0)
* or cell data (1)
* values indication with cells to decimate
* @return SV_OK if the function executes properly
*/
int sys_geom_set_array_for_local_op_face_blend( cvPolyData *pd,cvPolyData **outpd,char *inarrayname,int *vals,int nvals,double radius,char *outarrayname,int datatype)
{
vtkPolyData *geom = pd->GetVtkPolyData();
cvPolyData *result = NULL;
/*
fprintf(stdout,"Adding face blend\n");
fprintf(stdout,"Given Array Name: %s\n",inarrayname);
fprintf(stdout,"Target Array Name: %s\n",outarrayname);
fprintf(stdout,"Array Type: %d\n",datatype);
fprintf(stdout,"Number of Ids: %d\n",nvals);
fprintf(stdout,"Radius: %.4f\n",radius);
*/
double range[2];
int max;
int value=0;
vtkNew(vtkPolyData,tmp);
tmp->DeepCopy(geom);
vtkNew(vtkIntArray,newArray);
newArray->SetName(outarrayname);
if (datatype == 0)
{
fprintf(stderr,"Sorry, this functionality is not currently available");
}
else
{
if (VtkUtils_PDCheckArrayName(tmp,1,inarrayname) != SV_OK)
{
fprintf(stderr,"%s Array is not on the surface\n",inarrayname);
return SV_ERROR;
}
vtkNew(vtkIdList,targetCells);
for (int i=0; i< nvals; i++)
targetCells->InsertNextId((vals[i]));
vtkNew(vtkSVFindSeparateRegions,separator);
separator->SetInputData(tmp);
separator->SetOutPointArrayName("BoundaryPoints");
separator->SetCellArrayName(inarrayname);
separator->SetTargetCellIds(targetCells);
separator->Update();
vtkNew(vtkSVGetSphereRegions,sphereSetter);
sphereSetter->SetInputData(separator->GetOutput());
sphereSetter->SetOutCellArrayName(outarrayname);
sphereSetter->SetCellArrayName(inarrayname);
sphereSetter->SetPointArrayName("BoundaryPoints");
sphereSetter->SetSphereRadius(radius);
sphereSetter->Update();
result = new cvPolyData(sphereSetter->GetOutput());
*outpd = result;
}
return SV_OK;
}
/* -------------- */
/* sys_geom_local_decimation */
/* -------------- */
/** @author Adam Updegrove
* @author updega2@gmail.com
* @author UC Berkeley
* @author shaddenlab.berkeley.edu
*
* @brief Function to perform a decimation operation on only a portion
* of a polydata
* @param *pd The input polydata on which to perform decimation
* @param **outpd The output polydata surface
* @param *pointarrayname This contains the arrayname holding the boolean
* values indication with points to decimate
* @param *cellarrayname This contains the arrayname holding the boolean
* values indication with cells to decimate
* @return SV_OK if the function executes properly
*/
int sys_geom_local_quadric_decimation( cvPolyData *pd,cvPolyData **outpd, double target,
char *pointarrayname, char *cellarrayname)
{
vtkPolyData *geom = pd->GetVtkPolyData();
cvPolyData *result = NULL;
/*
fprintf(stdout,"Running local decimation\n");
fprintf(stdout,"Target Decimation: %.4f\n",target);
fprintf(stdout,"Point Array Name: %s\n",pointarrayname);
fprintf(stdout,"Cell Array Name: %s\n",cellarrayname);
*/
try {
vtkNew(vtkSVLocalQuadricDecimation,decimator);
decimator->SetInputData(geom);
if (pointarrayname != 0)
{
decimator->SetDecimatePointArrayName(pointarrayname);
decimator->UsePointArrayOn();
}
if (cellarrayname != 0)
{
decimator->SetDecimateCellArrayName(cellarrayname);
decimator->UseCellArrayOn();
}
decimator->SetTargetReduction(target);
decimator->Update();
result = new cvPolyData( decimator->GetOutput());
*outpd = result;
}
catch (...) {
fprintf(stderr,"ERROR in local decimation.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
/* -------------- */
/* sys_geom_local_laplacian_smooth */
/* -------------- */
/** @author Adam Updegrove
* @author updega2@gmail.com
* @author UC Berkeley
* @author shaddenlab.berkeley.edu
*
* @brief Function to perform a smoothing operation on only a portion
* of a polydata
* @param *pd The input polydata on which to perform decimation
* @param **outpd The output polydata surface
* @param numiters number of iterations of smoothing to perform
* @param relax relaxation factor for smoothing
* @param *pointarrayname This contains the arrayname holding the boolean
* values indication with points to smooth
* @param *cellarrayname This contains the arrayname holding the boolean
* values indication with cells to smooth
* @return SV_OK if the function executes properly
*/
int sys_geom_local_laplacian_smooth( cvPolyData *pd,cvPolyData **outpd, int numiters,
double relax,char *pointarrayname, char *cellarrayname)
{
vtkPolyData *geom = pd->GetVtkPolyData();
cvPolyData *result = NULL;
/*
fprintf(stdout,"Running local smoothing\n");
fprintf(stdout,"Num Iters: %d\n",numiters);
fprintf(stdout,"Relax: %.4f\n",relax);
fprintf(stdout,"Point Array Name: %s\n",pointarrayname);
fprintf(stdout,"Cell Array Name: %s\n",cellarrayname);
*/
try {
vtkNew(vtkSVLocalSmoothPolyDataFilter,smoother);
smoother->SetInputData(geom);
if (pointarrayname != 0)
{
smoother->SetSmoothPointArrayName(pointarrayname);
smoother->UsePointArrayOn();
}
if (cellarrayname != 0)
{
smoother->SetSmoothCellArrayName(cellarrayname);
smoother->UseCellArrayOn();
}
smoother->SetNumberOfIterations(numiters);
smoother->SetRelaxationFactor(relax);
smoother->Update();
vtkNew(vtkPolyDataNormals,normaler);
normaler->SetInputData(smoother->GetOutput());
normaler->ComputePointNormalsOff();
normaler->ComputeCellNormalsOn();
normaler->SplittingOff();
normaler->Update();
result = new cvPolyData( normaler->GetOutput());
*outpd = result;
}
catch (...) {
fprintf(stderr,"ERROR in local smoothing.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
/* -------------- */
/* sys_geom_local_constrain_smooth */
/* -------------- */
/** @author Adam Updegrove
* @author updega2@gmail.com
* @author UC Berkeley
* @author shaddenlab.berkeley.edu
*
* @brief Function to perform a smoothing operation on only a portion
* of a polydata
* @param *pd The input polydata on which to perform decimation
* @param **outpd The output polydata surface
* @param numiters number of iterations of smoothing to perform
* @param constrainfactor Extent to which operation attempts to push surface
* back to original surface. 1.0 attempts to push it back 100%, 0.0
* attempts to push it back 0%.
* @param *pointarrayname This contains the arrayname holding the boolean
* values indication with points to smooth
* @param *cellarrayname This contains the arrayname holding the boolean
* values indication with cells to smooth
* @return SV_OK if the function executes properly
*/
int sys_geom_local_constrain_smooth( cvPolyData *pd,cvPolyData **outpd, int numiters,
double constrainfactor,int numcgsolves, char *pointarrayname, char *cellarrayname)
{
vtkPolyData *geom = pd->GetVtkPolyData();
cvPolyData *result = NULL;
/*
fprintf(stdout,"Running local smoothing\n");
fprintf(stdout,"Num Iters: %d\n",numiters);
fprintf(stdout,"Constrain: %.4f\n",constrainfactor);
fprintf(stdout,"Point Array Name: %s\n",pointarrayname);
fprintf(stdout,"Cell Array Name: %s\n",cellarrayname);
*/
try {
vtkNew(vtkSVConstrainedSmoothing,smoother);
smoother->SetInputData(geom);
if (pointarrayname != 0)
{
smoother->SetPointArrayName(pointarrayname);
smoother->UsePointArrayOn();
}
if (cellarrayname != 0)
{
smoother->SetCellArrayName(cellarrayname);
smoother->UseCellArrayOn();
}
smoother->SetNumGradientSolves(numcgsolves);
smoother->SetNumSmoothOperations(numiters);
smoother->SetWeight(constrainfactor);
smoother->Update();
vtkNew(vtkPolyDataNormals,normaler);
normaler->SetInputData(smoother->GetOutput());
normaler->ComputePointNormalsOff();
normaler->ComputeCellNormalsOn();
normaler->SplittingOff();
normaler->Update();
result = new cvPolyData( normaler->GetOutput());
*outpd = result;
}
catch (...) {
fprintf(stderr,"ERROR in local smoothing.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
/* -------------- */
/* sys_geom_local_linear_subdivision */
/* -------------- */
/** @author Adam Updegrove
* @author updega2@gmail.com
* @author UC Berkeley
* @author shaddenlab.berkeley.edu
*
* @brief Function to perform a subdivision operation on only a portion
* of a polydata
* @param *pd The input polydata on which to perform decimation
* @param **outpd The output polydata surface
* @param numiters number of iterations of subdivision to perform
* @param *pointarrayname This contains the arrayname holding the boolean
* values indication with points to subdivide
* @param *cellarrayname This contains the arrayname holding the boolean
* values indication with cells to subdivide
* @return SV_OK if the function executes properly
*/
int sys_geom_local_linear_subdivision( cvPolyData *pd,cvPolyData **outpd, int numiters,
char *pointarrayname, char *cellarrayname)
{
vtkPolyData *geom = pd->GetVtkPolyData();
cvPolyData *result = NULL;
/*
fprintf(stdout,"Running local subdivision\n");
fprintf(stdout,"Num Iters: %d\n",numiters);
fprintf(stdout,"Point Array Name: %s\n",pointarrayname);
fprintf(stdout,"Cell Array Name: %s\n",cellarrayname);
*/
try {
vtkNew(vtkSVLocalLinearSubdivisionFilter,subdivider);
subdivider->SetInputData(geom);
if (pointarrayname != 0)
{
subdivider->SetSubdividePointArrayName(pointarrayname);
subdivider->UsePointArrayOn();
}
if (cellarrayname != 0)
{
subdivider->SetSubdivideCellArrayName(cellarrayname);
subdivider->UseCellArrayOn();
}
subdivider->SetNumberOfSubdivisions(numiters);
subdivider->Update();
result = new cvPolyData( subdivider->GetOutput());
*outpd = result;
}
catch (...) {
fprintf(stderr,"ERROR in local subdivision.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
/* -------------- */
/* sys_geom_local_butterfly_subdivision */
/* -------------- */
/** @author Adam Updegrove
* @author updega2@gmail.com
* @author UC Berkeley
* @author shaddenlab.berkeley.edu
*
* @brief Function to perform a subdivision operation on only a portion
* of a polydata
* @param *pd The input polydata on which to perform decimation
* @param **outpd The output polydata surface
* @param numiters number of iterations of subdivision to perform
* @param *pointarrayname This contains the arrayname holding the boolean
* values indication with points to subdivide
* @param *cellarrayname This contains the arrayname holding the boolean
* values indication with cells to subdivide
* @return SV_OK if the function executes properly
*/
int sys_geom_local_butterfly_subdivision( cvPolyData *pd,cvPolyData **outpd, int numiters,
char *pointarrayname, char *cellarrayname)
{
vtkPolyData *geom = pd->GetVtkPolyData();
cvPolyData *result = NULL;
/*
fprintf(stdout,"Running local subdivision\n");
fprintf(stdout,"Num Iters: %d\n",numiters);
fprintf(stdout,"Point Array Name: %s\n",pointarrayname);
fprintf(stdout,"Cell Array Name: %s\n",cellarrayname);
*/
try {
vtkNew(vtkSVLocalButterflySubdivisionFilter,subdivider);
subdivider->SetInputData(geom);
if (pointarrayname != 0)
{
subdivider->SetSubdividePointArrayName(pointarrayname);
subdivider->UsePointArrayOn();
}
if (cellarrayname != 0)
{
subdivider->SetSubdivideCellArrayName(cellarrayname);
subdivider->UseCellArrayOn();
}
subdivider->SetNumberOfSubdivisions(numiters);
subdivider->Update();
result = new cvPolyData( subdivider->GetOutput());
*outpd = result;
}
catch (...) {
fprintf(stderr,"ERROR in local subdivision.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
/* -------------- */
/* sys_geom_local_loop_subdivision */
/* -------------- */
/** @author Adam Updegrove
* @author updega2@gmail.com
* @author UC Berkeley
* @author shaddenlab.berkeley.edu
*
* @brief Function to perform a subdivision operation on only a portion
* of a polydata
* @param *pd The input polydata on which to perform decimation
* @param **outpd The output polydata surface
* @param numiters number of iterations of subdivision to perform
* @param *pointarrayname This contains the arrayname holding the boolean
* values indication with points to subdivide
* @param *cellarrayname This contains the arrayname holding the boolean
* values indication with cells to subdivide
* @return SV_OK if the function executes properly
*/
int sys_geom_local_loop_subdivision( cvPolyData *pd,cvPolyData **outpd, int numiters,
char *pointarrayname, char *cellarrayname)
{
vtkPolyData *geom = pd->GetVtkPolyData();
cvPolyData *result = NULL;
/*
fprintf(stdout,"Running local subdivision\n");
fprintf(stdout,"Num Iters: %d\n",numiters);
fprintf(stdout,"Point Array Name: %s\n",pointarrayname);
fprintf(stdout,"Cell Array Name: %s\n",cellarrayname);
*/
try {
vtkNew(vtkSVLocalLoopSubdivisionFilter,subdivider);
subdivider->SetInputData(geom);
if (pointarrayname != 0)
{
subdivider->SetSubdividePointArrayName(pointarrayname);
subdivider->UsePointArrayOn();
}
if (cellarrayname != 0)
{
subdivider->SetSubdivideCellArrayName(cellarrayname);
subdivider->UseCellArrayOn();
}
subdivider->SetNumberOfSubdivisions(numiters);
subdivider->Update();
result = new cvPolyData( subdivider->GetOutput());
*outpd = result;
}
catch (...) {
fprintf(stderr,"ERROR in local subdivision.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
/* -------------- */
/* sys_geom_local_blend */
/* -------------- */
/** @author Adam Updegrove
* @author updega2@gmail.com
* @author UC Berkeley
* @author shaddenlab.berkeley.edu
*
* @brief Function to perform a blend operation on only a portion
* of a polydata
* @param *pd The input polydata on which to perform decimation
* @param **outpd The output polydata surface
* @param numiters number of iterations of blending to perform
* @param *pointarrayname This contains the arrayname holding the boolean
* values indication with points to do blend on
* @param *cellarrayname This contains the arrayname holding the boolean
* values indication with cells to do blend on
* @return SV_OK if the function executes properly
*/
int sys_geom_local_blend( cvPolyData *pd,cvPolyData **outpd, int numblenditers,
int numsubblenditers, int numsubdivisioniters,
int numcgsmoothiters, int numlapsmoothiters,
double targetdecimation,
char *pointarrayname, char *cellarrayname)
{
vtkPolyData *geom = pd->GetVtkPolyData();
cvPolyData *result = NULL;
/*
fprintf(stdout,"Running local subdivision\n");
fprintf(stdout,"Num Iters: %d\n",numblenditers);
fprintf(stdout,"Point Array Name: %s\n",pointarrayname);
fprintf(stdout,"Cell Array Name: %s\n",cellarrayname);
*/
try {
vtkNew(vtkSVConstrainedBlend,blender);
blender->SetInputData(geom);
if (pointarrayname != 0)
{
blender->SetPointArrayName(pointarrayname);
blender->UsePointArrayOn();
}
if (cellarrayname != 0)
{
blender->SetCellArrayName(cellarrayname);
blender->UseCellArrayOn();
}
blender->SetNumBlendOperations(numblenditers);
blender->SetNumSubBlendOperations(numsubblenditers);
blender->SetNumSubdivisionIterations(numsubdivisioniters);
blender->SetNumConstrainedSmoothOperations(numcgsmoothiters);
blender->SetNumLapSmoothOperations(numlapsmoothiters);
blender->SetDecimationTargetReduction(targetdecimation);
blender->Update();
vtkNew(vtkPolyDataNormals,normaler);
normaler->SetInputData(blender->GetOutput());
normaler->SplittingOff();
normaler->Update();
result = new cvPolyData( normaler->GetOutput());
*outpd = result;
}
catch (...) {
fprintf(stderr,"ERROR in local subdivision.\n");
fflush(stderr);
return SV_ERROR;
}
return SV_OK;
}
/* -------------- */
/* sys_geom_set_ids_for_caps */
/* -------------- */
/** @author Adam Updegrove
* @author updega2@gmail.com
* @author UC Berkeley
* @author shaddenlab.berkeley.edu
*
* @brief Function to set ids in order to retain face names from Boolean
* operation. Lots of sneaky tricks here
* @param *pd The polydata to set the ids on
* @param **outpd The polydata with the full ModelFaceIDs on it
* @param **doublecaps This returns the faces that have two caps on it
* @param *numfaces This is the number of total faces on the object
* @return SV_OK if the VTMK function executes properly
*/
int sys_geom_set_ids_for_caps( cvPolyData *pd,cvPolyData **outpd,int **doublecaps,
int *numfaces)
{
vtkPolyData *geom = pd->GetVtkPolyData();
cvPolyData *result = NULL;
*outpd = NULL;
int *capone;
int *captwo;
int facemax=0,capmax=0;
double facerange[2],caprange[2];
vtkNew(vtkIntArray,capids);
vtkNew(vtkIntArray,faceids);
if (VtkUtils_PDCheckArrayName(geom,1,"CapID") != SV_OK)
{
fprintf(stderr,"CapID Array is not on the surface\n");
return SV_ERROR;
}
if (VtkUtils_PDCheckArrayName(geom,1,"ModelFaceID") != SV_OK)
{
fprintf(stderr,"ModelFaceID Array is not on the surface\n");
return SV_ERROR;
}
capids = vtkIntArray::SafeDownCast(geom->GetCellData()->
GetArray("CapID"));
faceids = vtkIntArray::SafeDownCast(geom->GetCellData()->
GetArray("ModelFaceID"));
faceids->GetRange(facerange,0);
facemax = facerange[1];
capids->GetRange(caprange,0);
capmax = caprange[1];
capone = new int[facemax];
captwo = new int[facemax];
*doublecaps = new int[facemax];
*numfaces = facemax;
int numtwocaps=0;
for (int i = 0; i < facemax; i++)
{
double facecaprange[2];
vtkNew(vtkThreshold,threshold1);
threshold1->SetInputData(geom);
threshold1->SetInputArrayToProcess(0,0,0,1,"ModelFaceID");
threshold1->ThresholdBetween(i+1,i+1);
threshold1->Update();
vtkNew(vtkDataSetSurfaceFilter,surfacer);
surfacer->SetInputData(threshold1->GetOutput());
surfacer->Update();
vtkNew(vtkIntArray,modelfacecaps);
if (VtkUtils_PDCheckArrayName(surfacer->GetOutput(),1,"CapID") != SV_OK)
{
fprintf(stderr,"Second\n");
fprintf(stderr,"CapID Array is not on the surface\n");
delete [] capone;
delete [] captwo;
return SV_ERROR;
}
modelfacecaps = vtkIntArray::SafeDownCast(surfacer->GetOutput()->
GetCellData()->GetArray("CapID"));
capone[i] = 0;
captwo[i] = 0;
(*doublecaps)[i] = 0;
for (int j = 0; j < surfacer->GetOutput()->GetNumberOfCells();j++)
{
if (modelfacecaps->GetValue(j) == 1)
capone[i] = 1;
if (modelfacecaps->GetValue(j) == 2)
captwo[i] = 1;
}
if (capone[i] && captwo[i])
{
numtwocaps++;
(*doublecaps)[i] = numtwocaps;
}
}
//New face ids are a function of the ModelFaceID, the CapID, whether or
//not the face has two caps assigned to it and total number of faces
for (int i = 0; i < geom->GetNumberOfCells(); i++)
{
if (capids->GetValue(i) != -1)
{
int capval = capids->GetValue(i);
int faceval = faceids->GetValue(i);
if ((*doublecaps)[faceval-1] != 0)
{
if (capval == 1)
faceids->SetValue(i,faceval+capval+facemax-1);
else
faceids->SetValue(i,facemax*2+(*doublecaps)[faceval-1]);
}
else
faceids->SetValue(i,faceval+capval+facemax-captwo[faceval-1]-1);
}
}
geom->GetCellData()->RemoveArray("ModelFaceID");
geom->GetCellData()->AddArray(faceids);
geom->GetCellData()->SetActiveScalars("ModelFaceID");
result = new cvPolyData(geom);
*outpd = result;
delete [] capone;
delete [] captwo;
return SV_OK;
}
//-----------------------------------
// sys_geom_check_lines_connectivity
//-----------------------------------
// Check that the connectivity of the lines from a vtkPolyData
// object satisfy
//
// 1) Define a single closed region
// 2) Are manifold; two lines connected to a vertex
//
// Lines connectivity is given in 'lineConn' as pairs of point IDs.
// The (startID,endID) pairs are first stored in an std::map as
//
// connMap[startID] = endID
//
// The map is then traversed using the startID of the first pair
// to check if it reaches the original startID. The check fails if
//
// 1) The last ID in the map != original startID: not closed
// 2) The number of lines != the number of lines traversed: more than one region
// 3) There is more than one ID per end ID: non-manifold
//
// Arguments:
// numLines: The number of lines (i.e. pairs of IDs).
// lineConn: The array storing line pair IDs.
//
// Note: No check for an overlapping curve is performed.
//
// Returns:
// nonManifold: If true then the lines are non-manifold.
// multipleRegions: If true then the lines form multiple disjoint regions.
// notClosed: If true then the lines donot form a closed curve.
//
void sys_geom_check_lines_connectivity(int numLines, vtkIdType *lineConn, bool& nonManifold,
bool& multipleRegions, bool& notClosed)
{
nonManifold = false;
multipleRegions = false;
notClosed = false;
std::map<int,std::vector<int>> connMap;
for (int i = 0; i < numLines; i++) {
int id1 = lineConn[2*i];
int id2 = lineConn[2*i+1];
connMap[id1].push_back(id2);
if (connMap[id1].size() > 1) {
nonManifold = true;
return;
}
}
int startID = lineConn[0];
int numLoopLines = 0;
int id = startID;
bool foundLoop = false;
while (true) {
if (connMap.count(id) == 0) {
break;
}
numLoopLines += 1;
int nextID = connMap[id][0];
connMap[id][0] = -1;
if (nextID == startID) {
foundLoop = true;
break;
}
id = nextID;
}
if (!foundLoop) {
notClosed = true;
return;
}
if (numLoopLines != numLines) {
multipleRegions = true;
}
}
|
4a3f0f37eebca6a3b06fe305409df73e4cd8a1ca | 9de3a50f836e84fa02e293188d72585832d636dc | /Arduino/alarme/alarme.ino | 43fcbf6f45f3f288ca1974aa227cde175a05b7c5 | [] | no_license | wesleiferreira98/controle | a64cea414faacbcaac94cd997986c315db4a7ba6 | 7416fbedb6acc1c458946116e28eb702af7f0aa5 | refs/heads/master | 2021-01-04T15:12:29.470857 | 2020-06-18T21:46:01 | 2020-06-18T21:46:01 | 240,606,329 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | ino | alarme.ino | #include<TimerOne.h>
#define led_alarme 7
#define led_armado 13
#define btn 2
int led_al=LOW;
int led_ar=LOW;
bool armado=false;
void setup() {
pinMode(led_alarme,OUTPUT);
pinMode(led_armado,INPUT);
attachInterrupt(digitalPinToInterrupt(btn),toogle_alarme,FALLING);
}
void loop() {
//O loop que se foda nesse programa do caralho.
}
void alarme(){
digitalWrite(led_alarme,!digitalRead(led_alarme));
}
void toogle_alarme(){
if(armado){
digitalWrite(led_armado,LOW);
armado=false;
Timer1.detachInterrupt();
digitalWrite(led_armado,LOW);
}else{
digitalWrite(led_armado,HIGH);
armado=true;
Timer1.initialize(1000000);
Timer1.attachInterrupt(alarme);
}
}
|
12a8d5a43fc2f74440fc1acd078e7cbf698833a8 | 48f5cc4d7359ca07b67722a67d2a183a52ac83ac | /dataProvider/dmProviderHost.cpp | f33c253748d7fa78e7fd21be43eaf497172b52ef | [
"Apache-2.0"
] | permissive | PeterDeHerdt/rdk-rtmessage | 34582e8e3666996eb86ffe0d6b22c02cac88cdfa | 1bde4752b1da384d35d9a81e9e4ad47850bbad51 | refs/heads/rdk-next | 2023-08-14T06:33:38.149693 | 2021-09-02T18:02:42 | 2021-09-22T19:35:57 | 387,007,707 | 0 | 0 | NOASSERTION | 2021-07-17T18:04:25 | 2021-07-17T18:04:25 | null | UTF-8 | C++ | false | false | 11,975 | cpp | dmProviderHost.cpp | /*
##########################################################################
# If not stated otherwise in this file or this component's LICENSE
# file the following copyright and licenses apply:
#
# Copyright 2019 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##########################################################################
*/
#include "dmProviderHost.h"
#include "dmProvider.h"
#include "dmProviderOperation.h"
#include <sstream>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <unistd.h>
#include <rtConnection.h>
#include <rtError.h>
#include <rtLog.h>
#include "dmUtility.h"
namespace
{
dmNamedValue
makeNamedValue(dmPropertyInfo const& propInfo, char const* valueAsString)
{
// TODO conver to propert type from string
return dmNamedValue(propInfo, dmValue(valueAsString));
}
}
class dmProviderHostImpl : public dmProviderHost
{
public:
dmProviderHostImpl()
{
}
virtual ~dmProviderHostImpl()
{
if (m_con)
{
rtLog_Info("closing rtMessage connection");
rtConnection_Destroy(m_con);
m_con = nullptr;
}
}
private:
virtual bool providerRegistered(std::string const& name)
{
std::stringstream topic;
topic << "RDK.MODEL.";
topic << name;
std::string s = topic.str();
rtLog_Debug("register provider with topic:%s", s.c_str());
rtError e = rtConnection_AddListener(m_con, s.c_str(), &dmProviderHostImpl::requestHandler, this);
if (e != RT_OK)
{
rtLog_Warn("failed to register provider listener. %s", rtStrError(e));
return false;
}
return true;
}
void start()
{
rtConnection_Create(&m_con, "USE_UNIQUE_NAME_HERE", "tcp://127.0.0.1:10001");
std::unique_lock<std::mutex> lock(m_mutex);
m_thread.reset(new std::thread(&dmProviderHostImpl::run, this));
}
void stop()
{
rtConnection_Destroy(m_con);
std::unique_lock<std::mutex> lock(m_mutex);
if (m_thread)
{
// TODO
}
}
void run()
{
pause();
}
static void requestHandler(rtMessageHeader const* hdr, uint8_t const* buff, uint32_t n,
void* closure)
{
if (!rtMessageHeader_IsRequest(hdr))
{
rtLog_Error("got message that wasn't request in datamodel callback");
return;
}
rtMessage req;
rtError e = rtMessage_FromBytes(&req, buff, n);
rtLog_Debug("req: %s", buff);
if (e != RT_OK)
{
rtLog_Warn("failed to decode datamodel request");
// TODO: return error
}
dmProviderHostImpl* host = reinterpret_cast<dmProviderHostImpl *>(closure);
if (!host)
{
rtLog_Error("dmProviderHost is null");
// TODO: return error
}
dmQueryResult result;
dmProviderOperation op = host->decodeOperation(req);
if (op == dmProviderOperation_Get)
{
std::string providerName;
std::vector<dmPropertyInfo> params;
host->decodeGetRequest(req, providerName, params);
host->doGet(providerName, params, result);
}
else if (op == dmProviderOperation_Set)
{
std::string providerName;
std::vector<dmNamedValue> params;
host->decodeSetRequest(req, providerName, params);
host->doSet(providerName, params, result);
}
rtMessage_Release(req);
rtMessage res;
rtMessage_Create(&res);
host->encodeResult(res, result);
rtConnection_SendResponse(m_con, hdr, res, 1000);
rtMessage_Release(res);
}
dmProviderOperation decodeOperation(rtMessage req)
{
char const* operation = nullptr;
rtMessage_GetString(req, "method", &operation);
if ((strcmp(operation, "set") == 0))
return dmProviderOperation_Set;
else
return dmProviderOperation_Get;
}
void decodeGetRequest(rtMessage req, std::string& name, std::vector<dmPropertyInfo>& params)
{
char const* providerName = nullptr;
dmPropertyInfo propertyInfo;
rtMessage_GetString(req, "provider", &providerName);
if (providerName)
name = providerName;
rtMessage item;
rtMessage_GetMessage(req, "params", &item);
char const* propertyName = nullptr;
rtMessage_GetString(item, "name", &propertyName);
bool isWildcard = dmUtility::isWildcard(propertyName);
std::string objectName = isWildcard ? dmUtility::trimWildcard(propertyName) : dmUtility::trimProperty(propertyName);
rtLog_Debug("decodeGetRequest property=%s\n", (propertyName != nullptr ? propertyName : ""));
if(name != objectName)
rtLog_Warn("provider/property name missmatch %s, %s", name.c_str(), objectName.c_str());
std::shared_ptr<dmProviderInfo> objectInfo = db->getProviderByObjectName(objectName);
if (objectInfo)
{
rtLog_Debug("decodeGetRequest object found %s", providerName);
if (isWildcard)
params = objectInfo->properties();
else
{
dmPropertyInfo info = objectInfo->getPropertyInfo(propertyName);
//if property not found then set its fullName so that it gets passed up in the error
if(info.fullName().empty())
info.setFullName(propertyName);
params.push_back(info);
}
}
else
{
rtLog_Debug("decodeGetRequest object not found %s", propertyName);
}
rtMessage_Release(item);
}
void decodeSetRequest(rtMessage req, std::string& name, std::vector<dmNamedValue>& params)
{
char const* providerName = nullptr;
rtMessage_GetString(req, "provider", &providerName);
if (providerName)
name = providerName;
rtMessage item;
rtMessage_GetMessage(req, "params", &item);
char const* targetName = nullptr;
rtMessage_GetString(item, "name", &targetName);
char const* value = nullptr;
rtMessage_GetString(item, "value", &value);
if(!value)
{
rtLog_Debug("decodeSetRequest value is null");
return;
}
size_t len = strlen(value);
if(len == 0)
{
rtLog_Debug("decodeSetRequest value is empty");
return;
}
rtLog_Debug("decoderSetRequest name=%s value=%s\n", (targetName != nullptr ? targetName : ""), (value != nullptr ? value : ""));
std::vector< std::pair<std::string,std::string> > nameVals;
std::shared_ptr<dmProviderInfo> objectInfo;
//determine if value is a single value or multi-set value, like object={prop1=val1,prop2=val2...}
if(dmUtility::parseMultisetValue(value, nameVals))
{
objectInfo = db->getProviderByObjectName(targetName);//for multi-set the targetName is the object name
}
else
{
objectInfo = db->getProviderByPropertyName(targetName);
nameVals.push_back(std::make_pair(dmUtility::trimPropertyName(targetName), value));
}
if(objectInfo)
{
rtLog_Debug("decodeSetRequest object found %s", targetName);
std::vector<dmPropertyInfo> props = objectInfo->properties();
for (auto const& nameVal : nameVals)
{
std::string propertyName = nameVal.first;
auto itr = std::find_if(
props.begin(),
props.end(),
[propertyName](dmPropertyInfo const& info) {
rtLog_Debug("decodeSetRequest find_if %s compare to %s = %d\n", info.name().c_str(), propertyName.c_str(), (int)(info.name() == propertyName));
return info.name() == propertyName;
});
if (itr != props.end())
{
params.push_back(makeNamedValue(*itr, nameVal.second.c_str()));
}
else
{
//if property not found then create one with a fullName so that it gets passed up in the error
dmPropertyInfo info;
info.setFullName(targetName);
info.setIsWritable(true);
params.push_back(makeNamedValue(info, nameVal.second.c_str()));
}
}
}
else
{
rtLog_Debug("decodeSetRequest object not found %s", targetName);
}
rtMessage_Release(item);
}
void encodeResult(rtMessage& res, dmQueryResult const& result)
{
rtMessage msg;
rtMessage_Create(&msg);
int statusCode = result.status();
std::string statusMessage = result.statusMsg();
for (dmQueryResult::Param const& param : result.values())
{
rtMessage p;
rtMessage_Create(&p);
rtMessage_SetString(p, "name", param.Info.fullName().c_str());
rtMessage_SetString(p, "value", param.Value.toString().c_str());
rtMessage_SetInt32(p, "status", param.StatusCode);
rtMessage_SetString(p, "status_msg", param.StatusMessage.c_str());
rtMessage_AddMessage(msg, "params", p);
rtMessage_Release(p);
// I don't like how we do this. This is trying to set the overall status of the
// request to the first error it sees. For example, if we query two params, and
// one is ok and the other is an error, the statuscode is set to the second error
// code. If there are two errors it'll set it to the first. We should introduce an
// top-level error code in the response message. possibly something that indicates
// that there's partial failure.
//if (param.StatusCode != 0 && statusCode == 0)
//statusCode = param.StatusCode;
//if (statusMessage.empty() && !param.StatusMessage.empty())
//statusMessage = param.StatusMessage;
// rtMessage_SetString(msg, "name", param.Info.fullName().c_str());
// rtMessage_SetString(msg, "value", param.Value.toString().c_str());
}
rtMessage_SetInt32(msg, "status", statusCode);
rtMessage_SetString(msg, "status_msg", statusMessage.c_str());
rtMessage_AddMessage(res, "result", msg);
rtMessage_Release(msg);
}
private:
std::unique_ptr<std::thread> m_thread;
std::mutex m_mutex;
static rtConnection m_con;
};
rtConnection dmProviderHostImpl::m_con = nullptr;
dmProviderHost*
dmProviderHost::create()
{
return new dmProviderHostImpl();
}
bool
dmProviderHost::registerProvider(char const* object, std::unique_ptr<dmProvider> provider)
{
bool b = false;
std::shared_ptr<dmProviderInfo> objectInfo = db->getProviderByObjectName(std::string(object));
if (objectInfo)
{
rtLog_Debug("registerProvider fullName=%s instanceName=%s", objectInfo->objectName().c_str(), object);
b = providerRegistered(object);
if (b)
{
m_providers.insert(std::make_pair(object, std::move(provider)));
if(objectInfo->isList())
{
std::string listName = dmUtility::trimProperty(object);
rtLog_Debug("adding list item %s to list %s", object, listName.c_str());
m_lists[listName].push_back(object);
}
}
}
else
{
rtLog_Error("failed to find provider info in database for object:%s", object);
}
return b;
}
void
dmProviderHost::doGet(std::string const& providerName, std::vector<dmPropertyInfo> const& params, dmQueryResult& result)
{
auto itr = m_providers.find(providerName);
if (itr != m_providers.end())
{
rtLog_Debug("dmProviderHost::doGet %s found", providerName.c_str());
itr->second->doGet(params, result);
}
else
{
rtLog_Debug("dmProviderHost::doGet %s not found", providerName.c_str());
}
}
void
dmProviderHost::doSet(std::string const& providerName, std::vector<dmNamedValue> const& params, dmQueryResult& result)
{
auto itr = m_providers.find(providerName);
if (itr != m_providers.end())
{
rtLog_Debug("dmProviderHost::doSet %s found", providerName.c_str());
itr->second->doSet(params, result);
}
else
{
rtLog_Debug("dmProviderHost::doSet %s not found", providerName.c_str());
}
}
|
4bdf50c9d846e589b352657c9f90a94470646494 | 5e4e2ae5c863dee1003c064ef70d74c9165fc65e | /traversal/move-zeroes.cpp | 13561f38495e3210f75691a4f4047fc44f2d69fd | [] | no_license | rootid/fft | 3ec6f0e6ae1be96d531119b2571610646a7256e9 | af187df0eafee37f69d6be95dc22685a96b96742 | refs/heads/master | 2020-12-14T09:24:18.915482 | 2019-07-25T23:52:21 | 2019-07-25T23:52:21 | 46,454,112 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,090 | cpp | move-zeroes.cpp | //Move Zeroes
//Given an array nums, write a function to move all 0's to the end of it while
//maintaining the relative order of the non-zero elements.
//For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums
//should be [1, 3, 12, 0, 0].
//Note:
//You must do this in-place without making a copy of the array.
//Minimize the total number of operations.
#include<iostream>
using namespace std;
//######################################### Trick #########################################
public void moveZeroes(int[] nums) {
int m = nums.length;
int idx = 0;
for(int i=0;i<m;i++) {
if(nums[i] != 0) swap(nums,i,idx++);
}
}
private void swap(int[] nums, int i,int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
//######################################### Trick #########################################
void moveZeroes(vector<int>& nums) {
int len = nums.size();
int idx = 0;
for(int i=0;i<len;i++) {
if(nums[i] != 0) {
swap(nums[idx],nums[i]);
idx += 1;
}
}
}
int main() {
}
|
59c51d5454c714f55e57f7a9f045a1f85875b31a | 08e37252304e8a691305f8453c16c2ff8b850d3e | /examples/SEN-36004_TMD3700_RGB_ALS_Proximity/SEN-36004_TMD3700_RGB_ALS_Proximity.ino | 9869a7372257bbbdcba091b3ce0573f8ce631792 | [
"MIT"
] | permissive | PlayingWithFusion/PWFusion_TMD3700 | 24d82b5fcd33fbddc35345631bd4d04f804ad824 | c1e7ef72ab1ff52603077582fb59e4bd3a82e493 | refs/heads/master | 2020-03-11T07:00:50.066395 | 2018-04-17T04:46:04 | 2018-04-17T04:46:04 | 129,846,447 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,287 | ino | SEN-36004_TMD3700_RGB_ALS_Proximity.ino | /***************************************************************************
* File Name: SEN-36004_TMD3700_RGB_ALS_Proximity.ino
* Processor/Platform: Arduino Uno R3 (tested)
* Development Environment: Arduino 1.8.3
*
* Designed for use with with Playing With Fusion TMD3700 RGB Color, Proximity
* and Ambient Light Sensor Breakout: SEN-36004
*
* SEN-36004 (universal applications)
* ---> http://www.playingwithfusion.com/productview.php?pdid=85
*
* Copyright © 2016-2018, Playing With Fusion, Inc.
* SOFTWARE LICENSE AGREEMENT: This code is released under the MIT License.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
* **************************************************************************
* REVISION HISTORY:
* Author Date Comments
* J. Steinlage 2016Sep Original version
*
* Playing With Fusion, Inc. invests time and resources developing open-source
* code. Please support Playing With Fusion and continued open-source
* development by buying products from Playing With Fusion!
**************************************************************************/
/*
* Circuit:
* Arduino Uno Arduino Mega --> SEN-36004: TMD3700 Breakout
* SDA: SDA SDA --> SDA
* SCL: SCL SCL --> SCL
* GND: GND '' --> GND
* 5V: 5V '' --> VDD
* 3V: 3V '' --> LED
* GPIO0/1 are not used in this example. They could be used for interrupts
* (note: VDD should match voltage of IO, and can be between 3.3 and 5V)
**************************************************************************/
// The TMD3700 communicates via I2C.
// This example uses the I2C interface via Wire library
#include "Wire.h"
// include Playing With Fusion TMD3700 libraries
#include <PWFusion_TMD3700.h>
#include <PWFusion_TMD3700_STRUCT.h>
// declare sensor object (see PWFusion_TMD3700.h file for definitions)
PWFusion_TMD3700 tmd3700_snsr0(0x39);
// declare sensor structure
struct var_tmd3700 tmd3700_str_ch0;
void setup()
{
struct var_tmd3700 *tmd3700_ptr;
tmd3700_ptr = &tmd3700_str_ch0;
Serial.begin(115200);
Serial.println("Playing With Fusion: TMD3700 RGB, ALS and Proximity Sensor, SEN-36004");
delay(500);
// need to start I2C comms
Wire.begin();
pinMode(9,OUTPUT);
digitalWrite(9,LOW);
// give the Arduino time to start up
delay(100);
// setup for the proximity sensor
// see PWFusion_TMD3700.h file for definitions
while(0 == tmd3700_snsr0.Init(tmd3700_ptr));
}
uint8_t state = 0;
void loop()
{
delay(500);
struct var_tmd3700 *tmd3700_ptr;
tmd3700_ptr = &tmd3700_str_ch0;
tmd3700_snsr0.update_all(tmd3700_ptr);
if(state == 0){
digitalWrite(9,HIGH);
state = 1;
}
else{
digitalWrite(9,LOW);
state = 0;
}
Serial.println("Cdata Rdata Gdata Bdata Pdata Poffst Status");
Serial.print(tmd3700_ptr->Cdata);
Serial.print(" ");
Serial.print(tmd3700_ptr->Rdata);
Serial.print(" ");
Serial.print(tmd3700_ptr->Gdata);
Serial.print(" ");
Serial.print(tmd3700_ptr->Bdata);
Serial.print(" ");
Serial.print(tmd3700_ptr->Pdata);
Serial.print(" ");
Serial.print(tmd3700_ptr->Poffset);
Serial.print(" ");
Serial.print(tmd3700_ptr->status, BIN);
Serial.println(" ");
}
|
211709493ac72f638dace01c82c8dee62dd83f56 | d8cb8c90eb6ad16b494e93d8e1da20b90956b568 | /MyClientHandler.cpp | 6ea74bc49719084601d8679f801134d8359ef95d | [] | no_license | gal95elkayam/ex4 | f7eb8452a39e5e3f861effd885fc60ad1b421e59 | 9f60f1deb612b36b62988c000bc6672811018c68 | refs/heads/master | 2020-12-11T11:42:07.588632 | 2020-01-22T23:55:42 | 2020-01-22T23:55:42 | 233,839,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,511 | cpp | MyClientHandler.cpp | //
// Created by gal on 15/01/2020.
//
#include <algorithm>
#include <cstring>
#include <zconf.h>
#include <regex>
#include <iostream>
#include "MyClientHandler.h"
vector<vector<string>> MyClientHandler::lexer(string input) {
vector<vector<string >> after_lex;
vector<string> vec_lex;
string temp;
regex number("[0-9.]*");
smatch match_results;
while (input.size() > 0) {
if (input[0] == '\n') {
input = input.substr(1, input.size());
after_lex.push_back(vec_lex);
temp = ""; // clear to list
vec_lex.clear();
} else if ((input[0] >= 48 && input[0] < 58)) {
// if valid number or minus
regex_search(input, match_results, number);
for (unsigned i = 0; i < match_results.size(); ++i) {
// TODO check the +=
temp += temp + match_results.str(i);
}
vec_lex.push_back(temp);
input = input.substr(temp.size(), input.size());
temp = ""; // clear to list
} else if ((input[0] >= 65 && input[0] <= 90) || (input[0] >= 97 && input[0] <= 122)) {
// if a char- "end" - return and finish
return after_lex;
} else if (input[0] == 45) {
temp = "-1";
vec_lex.push_back(temp);
input = input.substr(temp.size(), input.size());
temp = "";
} else {
temp = ""; // clear to list
input = input.substr(1, input.size());
}
}
return after_lex;
}
//check if we have the problem in cache if not solved and save
void MyClientHandler::handleClient(int sock_id) {
string solution;
string problem;
vector<vector<string>> data;
cout<<"enter function handleclient "<<sock_id<<endl;
problem = getData(sock_id);
cout<<"recive data from "<<sock_id<<endl;
///////////////////////////////
// string problem_to_lexer = problem;
// arrange the string problem
// replace(problem.begin(), problem.end(), '\n', '%');
// if (problem.back() == '%') {
// problem.pop_back();
// }
////////////////////////////////////
// have problem
if (this->cache_Manager->containsSolution(&problem)) {
// write the solution and return
solution = this->cache_Manager->getSolution(&problem);
writeToServer(solution, sock_id);
return;
}
// else - find solution
/////////////////////////////////
data = this->lexer(problem);
///////////////////////////////////
solution = solver->solve(&data);
// the solution isn't saved already- save, write and return
this->cache_Manager->saveSolution(&problem, &solution);
writeToServer(solution, sock_id);
}
void MyClientHandler::writeToServer(string sol, int sock_id) {
const char *solution = sol.c_str();
int n = write(sock_id, solution, strlen(solution));
if (n < 0) {
perror("ERROR writing to socket");
exit(1);
}
}
bool MyClientHandler::getOut(const string &line) {
if (line.substr(0).find("end") < line.size()) {
this->toStop = false;
return true;
} else {
return false;
}
}
string MyClientHandler::getData(int sock_id) {
string curr_line;
string problem;
while (true) { // condition to stop- inside
curr_line = getLineFromSocket(sock_id);
problem += curr_line;
if (curr_line.find("end") != std::string::npos) {
break;
}
}
return problem;
}
string MyClientHandler::getLineFromSocket(int sock_id) {
char buf[CHARS_TO_BUFFER];
ssize_t readen_bytes;
readen_bytes = read(sock_id, buf, CHARS_TO_BUFFER - 1);
if (readen_bytes < 0) {
__throw_bad_exception();
} else if (readen_bytes == 0) {
//connection closed
} else {
buf[readen_bytes] = NULL;
}
return buf;
}
////read from file
//string MyClientHandler::getData(int socketId) {
// vector<string> v;
// std::string lineData;
// std::stringstream ss;
// char buffer[1024];
// string line;
// string problem;
// while (true) {
// bzero(buffer, 1024);
// read(socketId, buffer, 1023);
// ss << buffer;
// if (this->getOut(ss.str())) {
// break;
// }
// }
// while (std::getline(ss,lineData)) {
// lineData.erase(std::remove(lineData.begin(),lineData.end(),' '),lineData.end());
// problem += lineData;
// }
// return problem;
//}
|
9d0e30e365d7f6a5c229a85ea953bf7b46830945 | 5a6ccde5f37cc86b6fc0812b2bf40f42eab23906 | /F-set/1144F. Graph Without Long Directed Paths.cpp | e9addbe96d2f20b22fb111397a3b76d846ebbdd9 | [] | no_license | Waqar-107/Codeforces | 23f2b1edffb85f6f020107f03e09a455d3e6e792 | f0d2f25aa6a09c06083b82c39cdf3288ec2eecba | refs/heads/master | 2023-03-09T07:55:46.583363 | 2023-03-04T09:57:44 | 2023-03-04T09:57:44 | 82,915,896 | 196 | 138 | null | 2023-02-11T22:06:20 | 2017-02-23T10:29:34 | C++ | UTF-8 | C++ | false | false | 1,387 | cpp | 1144F. Graph Without Long Directed Paths.cpp | /***from dust i have come, dust i will be***/
#include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define dbg printf("in\n")
#define nl printf("\n")
#define N 200100
#define inf 1e18
#define sf(n) scanf("%d", &n)
#define sff(n,m) scanf("%d%d",&n,&m)
#define sfl(n) scanf("%I64d", &n)
#define sffl(n,m) scanf("%I64d%I64d",&n,&m)
#define pf(n) printf("%d",n)
#define pff(n,m) printf("%d %d",n,m)
#define pffl(n,m) printf("%I64d %I64d",n,m)
#define pfl(n) printf("%I64d",n)
#define pfs(s) printf("%s",s)
#define pb push_back
#define pp pair<int, int>
using namespace std;
int color[N];
vector<int> adj[N];
void bipartite(int s, int col)
{
color[s] = col;
for(int e : adj[s])
{
if(color[e] == -1)
bipartite(e, 1 - col);
else
{
if(color[e] == color[s])
{
pfs("NO\n");
exit(0);
}
}
}
}
int main()
{
freopen("in.txt", "r", stdin);
int i, j, k;
int n, m;
int u, v;
sff(n, m);
vector<pp> vec;
for(i = 0; i < m; i++)
{
sff(u, v);
adj[u].pb(v);
adj[v].pb(u);
vec.pb({u, v});
}
fill(color, color + N, -1);
bipartite(1, 0);
pfs("YES\n");
for(i = 0; i < m; i++)
pf(color[vec[i].first] < color[vec[i].second]);
return 0;
}
|
0a86e78cccda7ff520ed5e93aebae74cbd4be612 | dd4b37726b9c84aa4e34a35655a6a0fac7204df7 | /SkinMesh.h | 5ce36173eeb5fa68b3f354bc1ae56e5e0683cd24 | [] | no_license | ym1124/sic-meiro | 1145cfa7b11d77b1f907145927add54746dab1a6 | 1f801d031f64ed64f8cdbcc7d8e256d533a2c4cf | refs/heads/master | 2020-07-18T23:49:41.976318 | 2019-09-04T19:25:29 | 2019-09-04T19:25:29 | 206,336,606 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 6,222 | h | SkinMesh.h | #pragma once
#include <d3d11.h>
#include <DirectXMath.h>
#include <sstream>
#include <vector>
#include "..\Header\Light.h"
#define MAX_BONE_INFLUENCES 4 //1つの頂点が影響を受けるボーンの最大数
#define MAX_BONES 128
#define LIGHT_MAX 16
extern DirectX::XMINT4 light_exist[6];
class SkinMesh
{
public:
struct bone
{
DirectX::XMFLOAT4X4 transform;
};
typedef std::vector<bone> skeletal;
struct skeletal_animation :public std::vector<skeletal>
{
float sampling_time = 1 / 24.0f; float animation_tick = 0.0f;//経過時間
};
protected:
struct vertex
{
DirectX::XMFLOAT3 position;
DirectX::XMFLOAT3 normal;
DirectX::XMFLOAT2 uv;
FLOAT bone_weights[MAX_BONE_INFLUENCES] = { 1, 0, 0, 0 };
INT bone_indices[MAX_BONE_INFLUENCES] = {};
};
struct cbuffer
{
DirectX::XMFLOAT4X4 world_view_projection; //ワールド・ビュー・プロジェクション合成行列
DirectX::XMFLOAT4X4 world; //ワールド変換行列
DirectX::XMFLOAT4 material_color; //材質色
DirectX::XMFLOAT4 light_direction; //ライト進行方向
DirectX::XMFLOAT4X4 bone_transforms[MAX_BONES];
};
struct cbuffer_light
{
DirectX::XMFLOAT4X4 world_view_projection; //ワールド・ビュー・プロジェクション合成行列
DirectX::XMFLOAT4X4 world; //ワールド変換行列
DirectX::XMFLOAT4X4 view;
DirectX::XMFLOAT4X4 projection;
DirectX::XMFLOAT4 light_point[LIGHT_MAX]; //ライトの位置
DirectX::XMFLOAT4 attenution[LIGHT_MAX]; //明りの減衰の調整
DirectX::XMFLOAT4 light_color[LIGHT_MAX]; //ライトの色
DirectX::XMFLOAT4 obj_color; //objの色
DirectX::XMFLOAT4 light_directional;
DirectX::XMINT4 light_exist[LIGHT_MAX];
};
struct material
{
DirectX::XMFLOAT4 color = { 0.8f, 0.8f, 0.8f, 1.0f };
ID3D11ShaderResourceView *shader_resource_view;
D3D11_TEXTURE2D_DESC *tex2d_desc;
};
//material diffuse;
struct subset
{
u_int index_start = 0; // start number of index buffer
u_int index_count = 0; // number of vertices (indices)
material diffuse;
};
struct mesh
{
ID3D11Buffer *vertex_buffer;
ID3D11Buffer *index_buffer;
std::vector<subset> subsets;
DirectX::XMFLOAT4X4 global_transform = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
//std::vector<SkinMesh::bone> skeletal;
skeletal_animation skeletal_animation;
};
std::vector<mesh> meshes;
ID3D11VertexShader *vertex_shader;
ID3D11VertexShader *no_bone_vertex_shader;
ID3D11VertexShader *test_vs;
ID3D11VertexShader *energized_vs;
ID3D11VertexShader *load_vs;
ID3D11PixelShader *pixel_shader;
ID3D11PixelShader *no_texture_pixel_shader;
ID3D11PixelShader *test_ps;
ID3D11PixelShader *energized_ps;
ID3D11PixelShader *load_ps;
ID3D11InputLayout *input_layout;
ID3D11InputLayout *no_bone_input_layout;
ID3D11InputLayout *test_layout;
ID3D11InputLayout *energized_layout;
ID3D11InputLayout *load_layout;
ID3D11Buffer *const_buffer;
ID3D11RasterizerState *wire_rasterizer_state;
ID3D11RasterizerState *solid_rasterizer_state;
ID3D11DepthStencilState *depth_stencil;
ID3D11SamplerState *sampler_state;
public:
bool is_bone;
bool culling_clockwise;
DirectX::XMFLOAT4X4 coordinate_conversion =
{
1, 0, 0, 0,
0, 0, 1, 0,
0, 1, 0, 0,
0, 0, 0, 1
};
SkinMesh(ID3D11Device*, const std::string& fbx_filename);
~SkinMesh() { Release(); }
void Render(
ID3D11DeviceContext *device_context, //デバイスコンテキスト
const DirectX::XMFLOAT4X4 & world_view_projection, //ワールド・ビュー・プロジェクション合成行列
const DirectX::XMFLOAT4X4 & world, //ワールド変換行列
const DirectX::XMFLOAT4 & light_direction, //ライト進行方向
const DirectX::XMFLOAT4 & material_color, //材質色
float elapsed_time,
bool mode //線・塗りつぶし描画フラグ
);
void Render(
ID3D11DeviceContext *device_context, //デバイスコンテキスト
const DirectX::XMFLOAT4X4 & world_view_projection, //ワールド・ビュー・プロジェクション合成行列
const DirectX::XMFLOAT4X4 & world, //ワールド変換行列
const DirectX::XMFLOAT4X4 & view,
const DirectX::XMFLOAT4X4 & projection,
const DirectX::XMFLOAT4 & light_direction, //ライト進行方向
const DirectX::XMFLOAT4 & material_color, //材質色
float elapsed_time,
bool mode, //線・塗りつぶし描画フラグ
const DirectX::XMFLOAT3 &pos,
const int &light_num,
const Light &_light
);
void EnergizedRender(
ID3D11DeviceContext *device_context, //デバイスコンテキスト
const DirectX::XMFLOAT4X4 & world_view_projection, //ワールド・ビュー・プロジェクション合成行列
const DirectX::XMFLOAT4X4 & world, //ワールド変換行列
const DirectX::XMFLOAT4X4 & view,
const DirectX::XMFLOAT4X4 & projection,
const DirectX::XMFLOAT4 & light_direction, //ライト進行方向
const DirectX::XMFLOAT4 & material_color, //材質色
float elapsed_time,
bool mode, //線・塗りつぶし描画フラグ
const DirectX::XMFLOAT3 &pos,
const int &light_num,
const Light &_light
);
void LoadRender(
ID3D11DeviceContext *device_context, //デバイスコンテキスト
const DirectX::XMFLOAT4X4 & world_view_projection, //ワールド・ビュー・プロジェクション合成行列
const DirectX::XMFLOAT4X4 & world, //ワールド変換行列
const DirectX::XMFLOAT4X4 & view,
const DirectX::XMFLOAT4X4 & projection,
const DirectX::XMFLOAT4 & light_direction, //ライト進行方向
const DirectX::XMFLOAT4 & material_color, //材質色
float elapsed_time,
bool mode, //線・塗りつぶし描画フラグ
const DirectX::XMFLOAT3 &pos,
const int &light_num,
const Light &_light
);
void Release();
//void CreateBuffers(ID3D11Device *device, vertex *vertices, int num_vertices, u_int *indices, int num_indices);
void CreateBuffers(ID3D11Device *device, vertex *vertices, int num_vertices, u_int *indices, int num_indices, mesh &mesh);
void LoadFBX(ID3D11Device*, const std::string& fbx_filename);
}; |
ea13224adff4d7a193a3962ee937edda48fbcaf1 | 215750938b1dd4354eab9b8581eec76881502afb | /src/mfx/dsp/iir/Lpf1p.h | c029de483a65d1eb25b5bbbd79fbae7d836ebf06 | [
"WTFPL"
] | permissive | EleonoreMizo/pedalevite | c28fd19578506bce127b4f451c709914ff374189 | 3e324801e3a1c5f19a4f764176cc89e724055a2b | refs/heads/master | 2023-05-30T12:13:26.159826 | 2023-05-01T06:53:31 | 2023-05-01T06:53:31 | 77,694,808 | 103 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 2,208 | h | Lpf1p.h | /*****************************************************************************
Lpf1p.h
Author: Laurent de Soras, 2020
Simple smoothing low-pass filter with one pole and no zero.
Equation:
y += c * (x - y)
Template parameters:
- T: processed data type, floating point
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://www.wtfpl.net/ for more details.
*Tab=3***********************************************************************/
#pragma once
#if ! defined (mfx_dsp_iir_Lpf1p_HEADER_INCLUDED)
#define mfx_dsp_iir_Lpf1p_HEADER_INCLUDED
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "fstb/def.h"
namespace mfx
{
namespace dsp
{
namespace iir
{
template <typename T>
class Lpf1p
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
public:
typedef T DataType;
fstb_FORCEINLINE void
set_coef (T c) noexcept;
fstb_FORCEINLINE T
process_sample (T x) noexcept;
fstb_FORCEINLINE T
constant_block (T x, int nbr_spl) noexcept;
fstb_FORCEINLINE T &
use_state () noexcept;
fstb_FORCEINLINE const T &
use_state () const noexcept;
void clear_buffers () noexcept;
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
protected:
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
T _coef { 1.f };
T _mem_y {};
/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
bool operator == (const Lpf1p &other) const = delete;
bool operator != (const Lpf1p &other) const = delete;
}; // class Lpf1p
} // namespace iir
} // namespace dsp
} // namespace mfx
#include "mfx/dsp/iir/Lpf1p.hpp"
#endif // mfx_dsp_iir_Lpf1p_HEADER_INCLUDED
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
|
373051233ab4fa2d692631de981f1910d973942c | a5f3b0001cdb692aeffc444a16f79a0c4422b9d0 | /main/slideshow/source/engine/transitions/checkerboardwipe.cxx | be55971ced599f3f26f9c892b3975bccf02e914d | [
"Apache-2.0",
"CPL-1.0",
"bzip2-1.0.6",
"LicenseRef-scancode-other-permissive",
"Zlib",
"LZMA-exception",
"LGPL-2.0-or-later",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-philippe-de-muyter",
"OFL-1.1",
"LGPL-2.1-only",
"MPL-1.1",
"X11",
"LGPL-2.1-or-later",
"GPL-2.0-only",
... | permissive | apache/openoffice | b9518e36d784898c6c2ea3ebd44458a5e47825bb | 681286523c50f34f13f05f7b87ce0c70e28295de | refs/heads/trunk | 2023-08-30T15:25:48.357535 | 2023-08-28T19:50:26 | 2023-08-28T19:50:26 | 14,357,669 | 907 | 379 | Apache-2.0 | 2023-08-16T20:49:37 | 2013-11-13T08:00:13 | C++ | UTF-8 | C++ | false | false | 2,054 | cxx | checkerboardwipe.cxx | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
#include <canvas/debug.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include "checkerboardwipe.hxx"
namespace slideshow {
namespace internal {
::basegfx::B2DPolyPolygon CheckerBoardWipe::operator () ( double t )
{
const double d = (1.0 / m_unitsPerEdge);
::basegfx::B2DHomMatrix aTransform;
aTransform.scale( ::basegfx::pruneScaleValue( d * 2.0 * t ),
::basegfx::pruneScaleValue( d ) );
::basegfx::B2DPolyPolygon res;
for ( sal_Int32 i = m_unitsPerEdge; i--; )
{
::basegfx::B2DHomMatrix transform( aTransform );
if ((i % 2) == 1) // odd line
transform.translate( -d, 0.0 );
for ( sal_Int32 j = (m_unitsPerEdge / 2) + 1; j--; )
{
::basegfx::B2DPolyPolygon poly( m_unitRect );
poly.transform( transform );
res.append( poly );
transform.translate( d * 2.0, 0.0 );
}
aTransform.translate( 0.0, d ); // next line
}
return res;
}
}
}
|
e2d855e9229ac61a44a05b933e60ed73fc82f3f0 | 578e1eb0209a237c5bc7a48960015e62c7c0b9ec | /unitTest/PrimeTest/primeTest.cc | f1837357edc5e830c95f95fe657b9db71179c5e2 | [] | no_license | javicuriel/CalidadPruebasSoftware | 1b763ba4beb098b31924bd821905f5e1424873a4 | ae44a5bce3a6474722df50e77889c3fe8ce7ef23 | refs/heads/master | 2021-01-22T14:56:18.101201 | 2017-12-05T01:44:36 | 2017-12-05T01:44:36 | 100,720,149 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | cc | primeTest.cc | #include "gtest/gtest.h"
#include "../../PrimosCirculares/circularPrime.h"
TEST(TestCaseName,TestNameUno){
int array[19] = {2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933};
int i = 0;
while(i < 19){
ASSERT_TRUE(girar(array[i]));
i++;
}
}
|
25b7b18e7fb789a4f524710c59477ee5b3086090 | e1b5cef539451dd3a62003b80510464228e1d880 | /Color.cpp | 0a1b5300eab8f3561aad22f9bbaaf52a9a597168 | [] | no_license | Mont3iro68/VC1718 | 99e105140b3e1058d815849eecd0694e3ef17aa8 | c9bf43c888f9d40e302e30fb0fb4a8bccd6ce74c | refs/heads/master | 2020-04-07T10:12:57.109451 | 2019-01-08T20:35:25 | 2019-01-08T20:35:25 | 158,279,027 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 908 | cpp | Color.cpp |
#include "Color.h"
Color::Color(){
setColor("Color");
}
Color::Color(string color){
if (color == "green"){
setColor(color);
setHSVlow(Scalar(45,90,50));
setHSVhigh(Scalar(100,255,255));
}
if(color == "blue"){
setColor(color);
setHSVlow(Scalar(90,120,120));
setHSVhigh(Scalar(130,255,255));
}
if(color == "red"){
setColor(color);
setHSVlow(Scalar(0,160,0));
setHSVhigh(Scalar(179,255,255));
}
if(color == "yellow"){
setColor(color);
setHSVlow(Scalar(15,130,50));
setHSVhigh(Scalar(35,255,255));
}
}
Color::~Color()
{
}
string Color::getColor(){
return Color::color;
}
void Color::setColor(string c){
Color::color = c;
}
Scalar Color::getHSVhigh(){
return Color::HSVhigh;
}
void Color::setHSVhigh(Scalar high){
Color::HSVhigh = high;
}
Scalar Color::getHSVlow(){
return Color::HSVlow;
}
void Color::setHSVlow(Scalar low){
Color::HSVlow = low;
}
|
e1f9509efa52659c45a5495c9ba5c315944f9daf | 190d37ec5fddea760caa846cbc71e5f0043174cc | /src/commands/creation/CreationCommandList.h | 6ab7d287b7a1733cf701592978169ab7965533bb | [] | no_license | urho3d-archive/artofwar | d7348862386a89ff5852e1cb1f5fc556d4d33659 | 476e01d0f99e3237df83aabdbce17d60ecf16a6a | refs/heads/master | 2020-03-21T06:29:48.519966 | 2018-06-20T21:24:38 | 2018-06-20T21:24:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 638 | h | CreationCommandList.h | #pragma once
#include "commands/CommandList.h"
namespace Urho3D {
class Vector2;
}
class SimulationObjectManager;
class CreationCommandList : public CommandList
{
public:
CreationCommandList();
virtual ~CreationCommandList();
bool addUnits(int _number, int id, Urho3D::Vector2& _position, int _player, int level);
bool addBuilding(int id, Urho3D::Vector2& _position, int _player, int level);
bool addResource(int id, Urho3D::Vector2& _position, int level);
SimulationObjectManager* getManager();
protected:
void setParemeters(AbstractCommand* command) override;
private:
SimulationObjectManager* simulationObjectManager;
};
|
3bb1e774b1d13a2b4d74a95f6cc42a7dc46f542b | bf4a7f2638a3cf3b99bea8bc08189c7a334493b4 | /Pattern_Command/Game.h | 36dae243c8babedb6abada339323094ce18b45f4 | [] | no_license | sybek96/Y4-GamesEngineering | 2e80a8b1a82db5e9d16acb228900526e7413aec2 | 39b0d14908dbf2b118e1b348c607c0d885f4c122 | refs/heads/master | 2020-03-28T22:37:13.068023 | 2019-03-28T09:47:42 | 2019-03-28T09:47:42 | 149,245,307 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,071 | h | Game.h | #pragma once
#include <SDL.h>
#include <stdio.h>
#include <functional>
#include <SDL_image.h>
#include "InputHandler.h"
#include "Player.h"
#include <vector>
class Game
{
public:
Game();
~Game();
//Starts up SDL and creates window
bool init();
//Loads media
bool loadMedia();
//method to load a texture
SDL_Texture* loadTexture(std::string path);
//Frees media and shuts down SDL
void close();
//draw method
void draw();
private:
//Screen dimension constants
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
//The window we'll be rendering to
SDL_Window* gWindow = NULL;
//The surface contained by the window
SDL_Surface* gScreenSurface = NULL;
//The image we will load and show on the screen
SDL_Surface* gXOut = NULL;
//The window renderer
SDL_Renderer* gRenderer = NULL;
//Current displayed texture
SDL_Texture* gTexture = NULL;
SDL_Texture* gTexture2 = NULL;
std::vector<SDL_Texture*> m_wallTextures;
std::unique_ptr<InputHandler> m_inputHandler;
std::unique_ptr<Player> m_player;
Command* m_playerCommand;
};
|
c2e828001ef5367524e1ef1891eb6fe354d7ac06 | 78e0a01db4afa3fdd428aedcab96c86b0e79aed6 | /Algorithms/Polygon Cover/main.cpp | f1d30ba68b4782bcbc13d464842cc7385901d46e | [] | no_license | VladGeana/Vlad-s-Projects | edea9c2387bc8174b032293beb0df2d00ce356c0 | 1cbc05bfbee93487e08635c7c04c26a9a8040be1 | refs/heads/master | 2020-07-20T00:29:21.608271 | 2020-05-23T13:55:39 | 2020-05-23T13:55:39 | 206,539,819 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | cpp | main.cpp | #include <iostream>
#include<fstream>
#include<math.h>
#define PI 3.14159265
using namespace std;
ifstream f("infasuratoare.in");
ofstream g("infasuratoare.out");
struct coord
{
double x,y;
};
coord c[121000];
int n,i,pct,nxt,j,cur;
double panta_max,x,y,mn=10000000,x1,y1;
double panta(double x1,double y1,double x2,double y2)
{
double m = ( (y1-y2)/(x1-x2) );
double cos=sqrt(1/(m*m+1));
return (acos(cos) *180/PI);
}
int main()
{
f>>n;
for(i=1;i<=n;i++)
{
f>>c[i].x>>c[i].y;
if(c[i].x<mn)
{
mn=c[i].x;
pct=i;
x1=mn;
y1=c[i].y;
}
}
while(nxt!=pct)
{
cout<<x1<<' '<<y1<<'\n';
panta_max=-10000000;
for(i=1;i<=n;i++)
if( x1!=c[i].x && panta(x1,y1,c[i].x,c[i].y)>panta_max)
{
panta_max=panta(x1,y1,c[i].x,c[i].y);
nxt=i;
}
x1=c[nxt].x;
y1=c[nxt].y;
}
}
|
a0c01965f9892c051a3fac0b2dacc512c2ce3ad1 | 49ffdd7ea31a341d5dbe0918a0c0c1d3b0429722 | /Sol-Hmn/main.cpp | d98a4340b7fba2bca83e8f912bcd8b0d4179adf6 | [] | no_license | humanova/Sol-Hmn | 4da461e9c6a3bc2ab72844389e6102b89f994c3c | 673355857b8023feb76c0f2e2cb6ae766a820018 | refs/heads/master | 2022-01-26T19:47:53.577291 | 2019-04-28T21:20:31 | 2019-04-28T21:20:31 | 162,185,977 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,863 | cpp | main.cpp | /*Emir Erbasan (humanova) 2018
*============*
Sol-Hmn is a fun project that I'm working on to gain some knowledge on reverse engineering and game hacking.
And I worked on reversing a 2D shooter game called "Soldat" to improve myself on reverse engineering.
I don't know open sourcing this project will cause a problem with the devs(because they currently work an a
huge update on this month (December 2018) and the game will get released to the Steam) If a problem occurs
I can delete/set private this repository.
Before diving into the code you need to know that this project is only for 'Soldat 1.7.1'.
Memory addresses, structures, functions can differ version to version.
Even a small change on the game's source code may cause this project to not to work.
*============*
== Notes about some methods and structures on this file ==
Line : SolHook::Settings settings; :
SolHook::Settings is a structure to store launch settings of the hack.
All settings are set to 'true' by default. If a setting is
set to 'false', even if you toggled that cheat(or something else)
it won't run/call any function(related to that cheat)
Line : settings.stabilizer = 0; :
Creating an instance of SolHook using the constructor that takes
launch settings. Default constructor doesn't take any arguments
and uses default settings.
Use 'SolHook::SetSettings()' to change settings manually (after construction ofc).
Method : SolHook::RefreshVal() :
Refreshes 'val' which is a gameVal structure that contains all necessary game values
Method : SolHook::CheckEvents() :
Checks events, such as toggling and activated cheats (to call functions)
*/
#include "SolHook.h"
int main()
{
SolHook::Settings settings;
settings.stabilizer = 0;
SolHook Sol(settings);
while (1)
{
Sol.RefreshVal();
Sol.CheckEvents();
Sleep(1);
}
return 0;
} |
27053a68b2988f5ef9257bb7dc74980071887f62 | 013196acdac02f62a1259619fce44df75a39158e | /pc/oriented_obj/productthread.h | ca03cd801b0c0fccfcaae0c96b22bc528fc63d4d | [] | no_license | iversongit/20160318 | 82078561d3c83d04ba067e1c14b2e7b7a6d30adb | 5fffb6f41c5b1ec0bf215e4467c6b68928e16dd3 | refs/heads/master | 2021-01-10T10:27:24.855323 | 2016-03-21T16:10:36 | 2016-03-21T16:10:36 | 54,197,991 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | h | productthread.h | ///
/// @file productthread.h
/// @iverson (1564329410@qq.com)
/// @date 2016-03-19 02:41:20
///
#ifndef __PRODUCTTHREAD_H__
#define __PRODUCTTHREAD_H__
#include "thread.h"
namespace yy{
class Buffer;
class ProductThread : public Thread
{
public:
ProductThread(Buffer & buffer);
void run();
private:
Buffer & _buffer;
};
}
#endif
|
8b6ab39308399009c52c2dee23cc87898ad36e32 | 4f4ea854df57269628ef8b68a6e445560af4a449 | /src/mainwindow.cpp | 580cb8f0ad086251a60257a6cb4f0975b0194ec1 | [] | no_license | arduinoNube/AutonomousPatchClamp | 33d6993fc358881dd887ab28802051cbd85b3376 | 3dea8f03598747d647149376d144cab85065aa9c | refs/heads/master | 2022-07-13T09:54:49.200114 | 2020-05-13T21:44:23 | 2020-05-13T21:44:23 | 263,674,412 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 87,390 | cpp | mainwindow.cpp | // Sublime text line count search
// ^(.*)$
// C:\Users\gholst3\Dropbox\Research\Autoswapper\C++\Qt 5.4\Autopatch_5.0\src,*.cpp,*.h,-*/daqmx_libs/*,-*/libssh2-1.4.3/*,-*/qcustomplot/*,-*/qcustomplot_old/*
// VERSION 4.0 - 17268 lines
//
// VERSION 5.0
// 07/10/2015 - 9108 lines
// 07/13/2015 - 9216 lines
// 12/17/2015 - 13340 lines
// 02/10/2016 - 14109 lines
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "daqmx_libs/NIDAQmx.h"
#include <qcustomplot/qcustomplot.h>
#include <QDebug>
#include <QVector>
#include <vector>
#include <fstream>
#include <string>
#include <ui/breakinsettingszap.h>
#include <ui/breakinsettingssuction.h>
#include <ui/breakinsettingsramp.h>
#include <cmath>
#include <QStringList>
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
//fix the data save directory and preferences path
// GUI Busy Symbol
busy.setParent(this);
busy.setInterval(200);
connect(&busy,SIGNAL(timeout()),this,SLOT(busyTimeout()));
// GUI Setup
guiInit(); // loading bitmaps, instantiating ui classes (settings windows), setting gui defaults, etc.
// Hardware Threads
// Assigning parent so the cleanup happens when the window is closed
daqThread.setParent(this);
multiclampThread.setParent(this);
tMotorThread.setParent(this);
autopatcherThread.setParent(this);
scaraThread.setParent(this);
fillerThread.setParent(this);
headstageClampThread.setParent(this);
lengthThread.setParent(this);
// Initializings state variables
stateRunning = 0;
currentState = NULL;
initTimer.setSingleShot(true); // Timer used to give the GUI a chance to refresh before initializing everything else.
connect(&initTimer,SIGNAL(timeout()),this,SLOT(init()),Qt::QueuedConnection);
initTimer.start(1000); // this will call init();
}
MainWindow::~MainWindow()
{
// emit stopVstim();
if(stateRunning && currentState != NULL) AP_Data = currentState->getData();
if(AP_Data.trialSaved == 0)
{
AP_Data.saveSettings();
AP_Data.saveLog();
}
savePreferences();
connect(this,SIGNAL(daq_stopTask()),daq,SLOT(stopTask()),Qt::QueuedConnection);
emit daq_stopTask();
connect(this,SIGNAL(scara_powerDown()),scara,SLOT(powerDown()),Qt::QueuedConnection);
emit scara_powerDown();
// connect(this,SIGNAL(autopatcher_stop()),autopatcher,SLOT(stop()),Qt::QueuedConnection);
// emit autopatcher_stop();
// connect(this,SIGNAL(filler_stop()),filler,SLOT(stop()),Qt::QueuedConnection);
// emit filler_stop();
// connect(this,SIGNAL(headstageClamp_stop()),headstageClamp,SLOT(stop()),Qt::QueuedConnection);
// emit headstageClamp_stop();
// connect(this,SIGNAL(scara_stop()),scara,SLOT(stop()),Qt::QueuedConnection);
// emit scara_stop();
QThread::msleep(500);
connect(this,SIGNAL(closeWorkers()),autopatcher,SLOT(aboutToClose()),Qt::QueuedConnection);
connect(this,SIGNAL(closeWorkers()),headstageClamp,SLOT(aboutToClose()),Qt::QueuedConnection);
connect(this,SIGNAL(closeWorkers()),filler,SLOT(aboutToClose()),Qt::QueuedConnection);
connect(this,SIGNAL(closeWorkers()),scara,SLOT(aboutToClose()),Qt::QueuedConnection);
connect(this,SIGNAL(closeWorkers()),multiclamp,SLOT(aboutToClose()),Qt::QueuedConnection);
connect(this,SIGNAL(closeWorkers()),tMotor,SLOT(aboutToClose()),Qt::QueuedConnection);
connect(this,SIGNAL(closeWorkers()),length,SLOT(aboutToClose()),Qt::QueuedConnection);
emit closeWorkers();
autopatcherThread.quit();
headstageClampThread.quit();
fillerThread.quit();
scaraThread.quit();
daqThread.quit();
multiclampThread.quit();
tMotorThread.quit();
lengthThread.quit();
autopatcherThread.wait(3000);
headstageClampThread.wait(3000);
fillerThread.wait(3000);
scaraThread.wait(3000);
daqThread.wait(3000);
multiclampThread.wait(3000);
tMotorThread.wait(3000);
lengthThread.wait(3000);
qWarning() << autopatcherThread.isFinished();
qWarning() << headstageClampThread.isFinished();
qWarning() << fillerThread.isFinished();
qWarning() << scaraThread.isFinished();
qWarning() << daqThread.isFinished();
qWarning() << multiclampThread.isFinished();
qWarning() << tMotorThread.isFinished();
qWarning() << lengthThread.isFinished();
// Deleting the hardware workers (this should close the serial
// ports etc. when their destructors are called)
delete autopatcher;
delete headstageClamp;
delete scara;
delete filler;
delete tMotor;
delete multiclamp;
delete daq;
delete length;
delete ui;
ap_win->close();
brkRampSettings->close();
brkSuckSettings->close();
brkZapSettings->close();
hw_win->close();
pref_win->close();
delete brkZapSettings;
delete brkSuckSettings;
delete brkRampSettings;
delete ap_win;
}
void MainWindow::init()
{
// ###########################################################################################
// STEP 1 Setup
// ###########################################################################################
AP_Data.clearLogValues();
// Hardware Workers (don't assign parents so that they can be moved to another thread)
autopatcher = new AutopatcherWorker();
headstageClamp = new HeadstageClampWorker();
scara = new SCARAWorker();
filler = new FillerWorker();
multiclamp = new MulticlampWorker();
daq = new DAQWorker();
tMotor = new ThorWorker(); // ActiveX Controls are slow to initialize
// (that's why we let the GUI loop run first)
visualStim = new VisualStimuliWorker();
length = new LengthMeasurementCameraWorker();
allWorkers.push_back(autopatcher);
allWorkers.push_back(headstageClamp);
allWorkers.push_back(scara);
allWorkers.push_back(filler);
allWorkers.push_back(tMotor);
allWorkers.push_back(multiclamp);
allWorkers.push_back(daq);
allWorkers.push_back(visualStim);
allWorkers.push_back(length);
autopatcher-> moveToThread(&autopatcherThread);
headstageClamp->moveToThread(&headstageClampThread);
scara-> moveToThread(&scaraThread);
filler-> moveToThread(&fillerThread);
tMotor-> moveToThread(&tMotorThread);
multiclamp-> moveToThread(&multiclampThread);
daq-> moveToThread(&daqThread);
length-> moveToThread(&lengthThread);
// Setting up threads
autopatcherThread.start(QThread::TimeCriticalPriority);
daqThread.start(QThread::TimeCriticalPriority);
scaraThread.start();
fillerThread.start();
headstageClampThread.start();
multiclampThread.start(QThread::TimeCriticalPriority);
tMotorThread.start();
lengthThread.start();
// ************************************
// ********* Setup Hardware ***********
// ************************************
connect(this,SIGNAL(initDAQInThread()),daq,SLOT(initInThread()),Qt::QueuedConnection);
emit initDAQInThread();
daq->setAmplifierScaleVC(multiclamp->getCommandScale()); // is this necessary?
connect(this,SIGNAL(initAutopatcherInThread()),autopatcher,SLOT(initInThread()),Qt::QueuedConnection);
emit initAutopatcherInThread();
// ************************************
// ************ Setup Plots ***********
// ************************************
plotInit();
ui->pages->setEnabled(true);
busy_stop("You may edit the settings in drop down menu or click GO to initialize the hardware connections.");
}
void MainWindow::initializeStates()
{
/* Initializing State Flow/Logic Variables
* Each state should return an integer when it reaches an exit point.
* The following cases describe the significance of the integer
* 0= Error. This means the state finished without reaching a decision like if it was interrupted during execution
* 1 = Go to the state listed at position "1" index nextStates vector in State. (GO TO NEXT STATE, OPTION 1)
* 2 = Go to the state listed at position "2" index nextStates vector in State. (GO TO NEXT STATE, OPTION 2)
* etc.
*
* I should probably write a GUI selector for this so that people can pick and choose which states to use
* and when to switch between them live. It will make debugging a lot harder depending on which route
* the user makes the state machine go so reproducing errors will be tricky since the flow of the code
* is changing live as the user uses it. It should probably have a log file to trace the code flow and
* help with debugging.
*
* Each state will need to declare how many decision options there are within it's code and also define
* what logic it is using to decide betwen each state. That way, the GUI can show the user what the state
* is thinking when it chooses decision 1, 2, etc.
*
* Don't forget to add any new states to the allStates vector (see below)
*
*
* The following cases are different examples of how the states are arranged and linked. They don't all work
* and many contain errors. They are mainly used for debugging and hardware readjustment. If you create a new
* state flow case, don't forget to add a description to the comboBoxModeSelect in guiInit. The combo box is what
* chooses which state flow case will be used at runtime states between
*
* Another point, it's generally better to create new states than edit old ones when making changes to the code.
* That way, the state flows can remain the same for old versions of the code (old experimental protocols)
* and new ones can rely on the new states. When editing old states, make sure it won't break the old functionality.
* To make this easier, try to write very simple and very general states that are indepdenent from the others.
* This is difficult especially when reusing states that change which output state is selected based on what happend
* in another state. One solution is to insert little states in the sequence that change which state follows another
* state. That way, the complex state code can be reused, but the state flow can be modified using these small custom
* states that do nothing except set a flag or set the decision variable of the next state. The fact that they show
* up in the state flow below highlights their importance in the execution and will make it eaiser for people to find
* out where the decision is being made to go to a particular state.
*
*
* _____________ _____________ ________ _____________ _____________
* | | | | | | | | | |
* | State 1 | -> | State 2 | -> | Little | -> | State 1 | -> | State 3 |
* |_____________| |_____________| |_State__| |_____________| |_____________|
*
* ^
* |
* This little state changes a flag that
* State 1 uses to decide to go to State 3
* instead of back to State 2 again like
* it did the first time State 1 was
* executed. This could be
* encapsulated inside State 2 but if
* you're reusing State 2 for something
* else somewhere else, then it wouldn't
* be a "general" state. Using the flag
* helps keep State 2 reusable and is more
* readable in the state flow vectors
* (see below).
*
*
*
* I have not always follwed my own advice so watch out inside some of my states where I'm setting flags that should be
* more visible. Here are a couple of those important flags that shouldn't be hidden in these states, but are:
*
* in "BreakIn", I'm setting the "data.restingVoltageStateDecision", "data.quickAPDetectStateDecision", and
* "data.visualStimulationCounter" flags to control the decisions of the "ic_quickAPDetectState" and
* "ic_restingVoltageState" states.
*
* I am, however using the "waitAndSetVars" state as one of these little states to control flow flags. Frankly, I think
* it's more readable but it's still a little confusing.
*
*
*
* Another confusing thing is to have a state behave differently based on the number of times it's run. That doesn't seem
* very intuitive from the state machine perspective where states are supposed to be able to be inserted and moved around. Especially
* for a state like quickAPDetectState where all it's supposed to do is check to see if there are action potentials and give
* a yes or no answer. For example, when I check for APs after the second visual stimulation, even if there are APs, I
* still want to retract because I'm done with that cell. Therefore, the state is doing a little trickery where it's based
* on whether there are APs or not, but also on how many times the visual stimulation has been run. Not very intuitive so
* I guess I'll have to add something to the description of the state. It's amazing how fast these things change and how
* documentation like this and in the state description go out of date almost immediately. It's tough to keep track of
* documentation that references changing files.
*
*/
qWarning() << "State machine was set up with the \"" << ui->comboBoxModeSelect->currentIndex() << "\" case.";
switch (ui->comboBoxModeSelect->currentIndex())
{
case 0: // Actual state order
hardwareInitState .setNextStates(QVector<State*>() << &errorState << &loadPipettesState);
loadPipettesState .setNextStates(QVector<State*>() << &errorState << &hardwareCalibState);
hardwareCalibState .setNextStates(QVector<State*>() << &errorState << &getPipetteState);
getPipetteState .setNextStates(QVector<State*>() << &errorState << &trialInitState);
trialInitState .setNextStates(QVector<State*>() << &errorState << &setBrainHeightState << &pipetteQCState);
setBrainHeightState .setNextStates(QVector<State*>() << &errorState << &pipetteQCState);
pipetteQCState .setNextStates(QVector<State*>() << &errorState << &clogCheckState << &retractState);
clogCheckState .setNextStates(QVector<State*>() << &errorState << &neuronHuntState << &retractState << &gigasealState);
neuronHuntState .setNextStates(QVector<State*>() << &errorState << &gigasealState << &retractState);
gigasealState .setNextStates(QVector<State*>() << &errorState << &breakInState << &neuronHuntState << &retractState << &vc_membraneTestState);
breakInState .setNextStates(QVector<State*>() << &errorState << &vc_membraneTestState << &retractState); // This sets a couple of decision flags for ic_restingVoltageState and ic_quickAPDetectState
vc_membraneTestState .setNextStates(QVector<State*>() << &errorState << &breakInState << &ic_bridgeBalanceAdjustState); // << &retractState);
ic_bridgeBalanceAdjustState .setNextStates(QVector<State*>() << &errorState << &ic_restingVoltageState);
ic_restingVoltageState .setNextStates(QVector<State*>() << &errorState << &ic_quickAPDetectState << &ic_measureRheobaseState << &retractState); // << &retractState);
ic_quickAPDetectState .setNextStates(QVector<State*>() << &errorState << &waitAndSetVarsState << &ic_recordVisualStimulationState << &retractState);
waitAndSetVarsState .setNextStates(QVector<State*>() << &errorState << &vc_membraneTestState); // This sets a flag used by the ic_restingVoltageState state decision
ic_measureRheobaseState .setNextStates(QVector<State*>() << &errorState << &ic_currentStepsState << &retractState);
ic_currentStepsState .setNextStates(QVector<State*>() << &errorState << &ic_BACFiringState);
ic_BACFiringState .setNextStates(QVector<State*>() << &errorState << &ic_recordVisualStimulationState);
ic_recordVisualStimulationState .setNextStates(QVector<State*>() << &errorState << &vc_membraneTestState);
retractState .setNextStates(QVector<State*>() << &errorState << &removePipetteState); // uncomment this line when actually running the code, (and commend out the next one)
retractSlowlyState .setNextStates(QVector<State*>() << &errorState << &removePipetteState);
removePipetteState .setNextStates(QVector<State*>() << &errorState << &getPipetteState);
break;
case 1: // Just loads a single pipette and finishes
hardwareInitState .setNextStates(QVector<State*>() << &errorState << &loadPipettesState);
loadPipettesState .setNextStates(QVector<State*>() << &errorState << &hardwareCalibState);
hardwareCalibState .setNextStates(QVector<State*>() << &errorState << &getPipetteState);
getPipetteState .setNextStates(QVector<State*>() << &errorState << &errorState);
break;
case 2: // Cycles through pipettes for the video
hardwareInitState .setNextStates(QVector<State*>() << &errorState << &loadPipettesState);
loadPipettesState .setNextStates(QVector<State*>() << &errorState << &hardwareCalibState);
hardwareCalibState .setNextStates(QVector<State*>() << &errorState << &getPipetteState);
getPipetteState .setNextStates(QVector<State*>() << &errorState << &trialInitState);
trialInitState .setNextStates(QVector<State*>() << &errorState << &setBrainHeightState << &retractState);
setBrainHeightState .setNextStates(QVector<State*>() << &errorState << &retractState);
retractState .setNextStates(QVector<State*>() << &errorState << &removePipetteState);
removePipetteState .setNextStates(QVector<State*>() << &errorState << &getPipetteState);
break;
case 3: // Testing resistance check code (skipping load pipettes, calib, get pipettes, retract etc.
// This case leaves the pipette in the holder and just does resistance checks, neuron hunt, etc.
// I should probably inclulde the option to switch to the spare headstage to make this easier to
// debug. The THOR motor needs to be homed using the APT User software before running this
hardwareInitState .setNextStates(QVector<State*>() << &errorState << &loadPipettesState);
loadPipettesState .setNextStates(QVector<State*>() << &errorState << &hardwareCalibState);
hardwareCalibState .setNextStates(QVector<State*>() << &errorState << &getPipetteState);
getPipetteState .setNextStates(QVector<State*>() << &errorState << &trialInitState);
trialInitState .setNextStates(QVector<State*>() << &errorState << &setBrainHeightState << &pipetteQCState);
setBrainHeightState .setNextStates(QVector<State*>() << &errorState << &pipetteQCState);
pipetteQCState .setNextStates(QVector<State*>() << &errorState << &retractState << &retractState);
retractState .setNextStates(QVector<State*>() << &errorState << &removePipetteState);
removePipetteState .setNextStates(QVector<State*>() << &errorState << &getPipetteState);
break;
case 4:
// Before using this state, you need to edit hardware calibrate so it doesn't take so long. That's the point of using this state anyway.
hardwareInitState .setNextStates(QVector<State*>() << &errorState << &hardwareCalibState);
hardwareCalibState .setNextStates(QVector<State*>() << &errorState << &trialInitState);
trialInitState .setNextStates(QVector<State*>() << &errorState << &pipetteQCState << &pipetteQCState);
pipetteQCState .setNextStates(QVector<State*>() << &errorState << &clogCheckState << &retractState);
clogCheckState .setNextStates(QVector<State*>() << &errorState << &neuronHuntState << &retractState << &gigasealState);
neuronHuntState .setNextStates(QVector<State*>() << &errorState << &gigasealState << &retractState);
gigasealState .setNextStates(QVector<State*>() << &errorState << &breakInState << &neuronHuntState << &retractState << &vc_membraneTestState);
breakInState .setNextStates(QVector<State*>() << &errorState << &vc_membraneTestState << &retractState); // This sets a couple of decision flags for ic_restingVoltageState and ic_quickAPDetectState
vc_membraneTestState .setNextStates(QVector<State*>() << &errorState << &breakInState << &ic_restingVoltageState); // << &retractState);
ic_restingVoltageState .setNextStates(QVector<State*>() << &errorState << &ic_quickAPDetectState << &ic_measureRheobaseState << &retractState);
ic_quickAPDetectState .setNextStates(QVector<State*>() << &errorState << &waitAndSetVarsState << &ic_recordVisualStimulationState << &retractState);
waitAndSetVarsState .setNextStates(QVector<State*>() << &errorState << &vc_membraneTestState); // This sets a flag used by the ic_restingVoltageState state decision
ic_measureRheobaseState .setNextStates(QVector<State*>() << &errorState << &ic_currentStepsState << &retractState);
ic_currentStepsState .setNextStates(QVector<State*>() << &errorState << &ic_BACFiringState);
ic_BACFiringState .setNextStates(QVector<State*>() << &errorState << &ic_recordVisualStimulationState);
ic_recordVisualStimulationState .setNextStates(QVector<State*>() << &errorState << &vc_membraneTestState);
retractState .setNextStates(QVector<State*>() << &errorState << &trialInitState);
case 5:
hardwareInitState .setNextStates(QVector<State*>() << &errorState << &hardwareCalibState);
hardwareCalibState .setNextStates(QVector<State*>() << &errorState << &trialInitState);
trialInitState .setNextStates(QVector<State*>() << &errorState << &ic_bridgeBalanceAdjustState << &ic_bridgeBalanceAdjustState);
ic_bridgeBalanceAdjustState .setNextStates(QVector<State*>() << &errorState << &trialInitState); // << &retractState);
break;
/* GOOD SEQUENCE BACKUP FROM DECEMBER/JANUARY RECORDINGS
hardwareInitState .setNextStates(QVector<State*>() << &errorState << &loadPipettesState);
loadPipettesState .setNextStates(QVector<State*>() << &errorState << &hardwareCalibState);
hardwareCalibState .setNextStates(QVector<State*>() << &errorState << &getPipetteState);
getPipetteState .setNextStates(QVector<State*>() << &errorState << &trialInitState);
trialInitState .setNextStates(QVector<State*>() << &errorState << &setBrainHeightState << &pipetteQCState);
setBrainHeightState .setNextStates(QVector<State*>() << &errorState << &pipetteQCState);
pipetteQCState .setNextStates(QVector<State*>() << &errorState << &clogCheckState << &retractState);
clogCheckState .setNextStates(QVector<State*>() << &errorState << &neuronHuntState << &retractState << &gigasealState);
neuronHuntState .setNextStates(QVector<State*>() << &errorState << &gigasealState << &retractState);
gigasealState .setNextStates(QVector<State*>() << &errorState << &breakInState << &neuronHuntState << &retractState << &vc_membraneTestState);
breakInState .setNextStates(QVector<State*>() << &errorState << &vc_membraneTestState << &retractState); // This sets a couple of decision flags for ic_restingVoltageState and ic_quickAPDetectState
vc_membraneTestState .setNextStates(QVector<State*>() << &errorState << &breakInState << &ic_restingVoltageState); // << &retractState);
ic_restingVoltageState .setNextStates(QVector<State*>() << &errorState << &ic_quickAPDetectState << &ic_measureRheobaseState << &retractState); // << &retractState);
ic_quickAPDetectState .setNextStates(QVector<State*>() << &errorState << &waitAndSetVarsState << &ic_recordVisualStimulationState << &retractState);
waitAndSetVarsState .setNextStates(QVector<State*>() << &errorState << &vc_membraneTestState); // This sets a flag used by the ic_restingVoltageState state decision
ic_measureRheobaseState .setNextStates(QVector<State*>() << &errorState << &ic_currentStepsState << &retractState);
ic_currentStepsState .setNextStates(QVector<State*>() << &errorState << &ic_BACFiringState);
ic_BACFiringState .setNextStates(QVector<State*>() << &errorState << &ic_recordVisualStimulationState);
ic_recordVisualStimulationState .setNextStates(QVector<State*>() << &errorState << &vc_membraneTestState);
retractState .setNextStates(QVector<State*>() << &errorState << &removePipetteState);
retractSlowlyState .setNextStates(QVector<State*>() << &errorState << &removePipetteState);
removePipetteState .setNextStates(QVector<State*>() << &errorState << &getPipetteState);
*/
}
// Just a list of all states in no particular order (this is used by setHardwareVals())
allStates = QVector<State*>() << &hardwareInitState
<< &loadPipettesState
<< &hardwareCalibState
<< &getPipetteState
<< &setBrainHeightState
<< &trialInitState
<< &pipetteQCState
<< &clogCheckState
<< &neuronHuntState
<< &gigasealState
<< &breakInState
<< &vc_membraneTestState
<< &vc_pipetteCapCompState
<< &ic_bridgeBalanceAdjustState
<< &ic_restingVoltageState
<< &ic_quickAPDetectState
<< &ic_measureRheobaseState
<< &ic_currentStepsState
<< &ic_BACFiringState
<< &ic_recordVisualStimulationState
<< &waitAndSetVarsState
<< &retractState
<< &retractSlowlyState
<< &removePipetteState;
hwSettingsChanged(); // Initializing the states with the default hardware settings in the hardware window
// If these values change with each time the state is run, add them to the "connectState" function
updateStateValues();
}
void MainWindow::startStateMachine()
{
// On program startup
stateRunning = 1;
currentState = &hardwareInitState;
connectState(currentState);
currentState->setData(AP_Data);
ap_win->setVals(AP_Data);
//updateStateValues();
qWarning() << "State starting: " << currentState->getName();
currentState->firstRun();
}
void MainWindow::stateFinished()
{
ui->pages->setEnabled(false);
disconnectState(currentState);
stateRunning = 0;
qWarning() << "State finished: " << currentState->getName();
if(currentState->decision != -1)
{
if((currentState->getNextStates()[currentState->decision] != NULL) &&
(currentState->getNextStates()[currentState->decision] != &errorState) &&
(currentState->decision < currentState->getNextStates().size()))
{
stateRunning = 1;
AP_Data = currentState->getData();
ap_win->setVals(AP_Data);
currentState = currentState->getNextStates()[currentState->decision];
connectState(currentState);
currentState->setData(AP_Data);
qWarning() << "State starting: " << currentState->getName();
currentState->firstRun();
}
else
{
qWarning() << "State machine stopped. NULL state, error state, or bad decision value from a state." << currentState->decision << currentState->getNextStates()[currentState->decision];
}
ui->pages->setEnabled(true);
}
else
{
qWarning() << "ERROR!!! STATE FINISHED WITH A CODE -1. Something is wrong with the state code.";
// WHAT TO DO WITH THE DATA?
}
}
void MainWindow::updateStateValues()
{
// Call this function whenever the values in AP_Data change
// to propagates them down into the states
pipetteQCState.setHeadstageNum(AP_Data.headstageNum);
pipetteQCState.setNumAve(AP_Data.numAve);
}
void MainWindow::updateWorkerValues()
{
daq->setNPeriods(AP_Data.nPeriods);
}
void MainWindow::connectState(State * state)
{
qRegisterMetaType< QVector<double> >("QVector<double>");
// GUI Signals
connect(state,SIGNAL(stateFinished()) ,this,SLOT(stateFinished()) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_busy_start(QString)) ,this,SLOT(busy_start(QString)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_busy_stop(QString)) ,this,SLOT(busy_stop(QString)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_busy_stop_error(QString)) ,this,SLOT(busy_stop_error(QString)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_setCurrentPageIndex(int)) ,this,SLOT(setCurrentPageIndex(int)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_setCurrentPageIndex(QString)) ,this,SLOT(setCurrentPageIndex(QString)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enablePages(bool)) ,this,SLOT(enablePages(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_setTextStatus(QString)) ,this,SLOT(setTextStatus(QString)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_clearResistancePlot()) ,this,SLOT(clearResistancePlot()) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_clearRawDataPlot()) ,this,SLOT(clearRawDataPlot()) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_clearMemTestPlot()) ,this,SLOT(clearMemTestPlot()) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enableActions(bool)) ,ui->actionFill_Pipette,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enableActions(bool)) ,ui->actionReset_Carousel,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enableActions(bool)) ,ui->actionLoad_microfil_20uL,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enableActions(bool)) ,ui->actionOpen_Headstage_Clamp,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enableActions(bool)) ,ui->actionClose_Headstage_Clamp,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enableActions(bool)) ,ui->actionRetract_Headstage_Wire,SLOT(setEnabled(bool)),Qt::QueuedConnection);
connect(state,SIGNAL(gui_enableActions(bool)) ,ui->actionInsert_Headstage_Wire,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enableActions(bool)) ,ui->actionHome_Thorlabs_Motor,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enableActions(bool)) ,ui->actionFinish_Visual_Stimuli,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enableActions(bool)) ,ui->actionReset_Brain_Height_On_New_Pipette,SLOT(setEnabled(bool)),Qt::QueuedConnection);
connect(state,SIGNAL(gui_checkedBrainHeightReset(bool)) ,ui->actionReset_Brain_Height_On_New_Pipette,SLOT(setChecked(bool)),Qt::QueuedConnection);
connect(state,SIGNAL(gui_enableActions(bool)) ,ui->actionFiller_Valve_On,SLOT(setEnabled(bool)),Qt::QueuedConnection);
connect(state,SIGNAL(gui_enableActions(bool)) ,ui->actionFiller_Valve_Off,SLOT(setEnabled(bool)),Qt::QueuedConnection);
connect(state,SIGNAL(gui_pauseButtonEnable(bool)) ,ui->pushButtonPause,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_pauseButtonVisible(bool)) ,ui->pushButtonPause,SLOT(setVisible(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_plotResData(double)) ,this,SLOT(plotResData(double)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_updateCurrentPosition()) ,this,SLOT(updateCurrentPosition()) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_updateCurrentBrainPosition(double)) ,this,SLOT(updateCurrentBrainPosition(double)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_incrementTrialNumber()) ,this,SLOT(incrementTrialNumber()) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_updateMembraneTestValues(QVector<double>)),this,SLOT(updateMemTestVals(QVector<double>)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enablePushButtonUpAdjust(bool)) ,ui->pushButtonUpAdjust,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enablePushButtonDownAdjust(bool)) ,ui->pushButtonDownAdjust,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enablePushButtonGO1(bool)) ,ui->pushButtonGo1,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enablePushButtonGO3(bool)) ,ui->pushButtonGo3,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(gui_enablePushButtonCalibrate(bool)) ,ui->pushButtonSCARACalibrate,SLOT(setEnabled(bool)) ,Qt::QueuedConnection);
// Autopatcher Signals
connect(state,SIGNAL(autopatcher_init(QString)) ,autopatcher,SLOT(init(QString)) ,Qt::QueuedConnection);
connect(state,SIGNAL(autopatcher_switchBNC(bool, bool)) ,autopatcher,SLOT(switchBNC(bool,bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(autopatcher_softwarePressure(bool,bool)) ,autopatcher,SLOT(softwarePressure(bool,bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(autopatcher_switchPressure(int,bool)) ,autopatcher,SLOT(switchPressure(int,bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(autopatcher_setPressure(int, double, bool)) ,autopatcher,SLOT(setPressure(int, double, bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(autopatcher_breakIn(int,int,int)) ,autopatcher,SLOT(breakIn(int,int,int)) ,Qt::QueuedConnection);
connect(state,SIGNAL(autopatcher_breakInRamp(int, int)) ,autopatcher,SLOT(breakInRamp(int, int)) ,Qt::QueuedConnection);
connect(state,SIGNAL(autopatcher_breakInRampFeedback(int)) ,autopatcher,SLOT(breakInRampFeedback(int)) ,Qt::QueuedConnection);
connect(state,SIGNAL(autopatcher_stopRamp()) ,autopatcher,SLOT(stopRamp()) ,Qt::QueuedConnection);
// Headstage Clamp Signals
connect(state,SIGNAL(headstageClamp_init(QString)) ,headstageClamp,SLOT(init(QString)) ,Qt::QueuedConnection);
connect(state,SIGNAL(headstageClamp_openClamp(bool)) ,headstageClamp,SLOT(openClamp(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(headstageClamp_halfClamp(bool)) ,headstageClamp,SLOT(halfClamp(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(headstageClamp_closeClamp(bool)) ,headstageClamp,SLOT(closeClamp(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(headstageClamp_threadWire(bool)) ,headstageClamp,SLOT(threadWire(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(headstageClamp_retractWire(bool)),headstageClamp,SLOT(retractWire(bool)) ,Qt::QueuedConnection);
// SCARA Signals
connect(state,SIGNAL(scara_init(QString)) ,scara,SLOT(init(QString)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_rotateCarouselNext(bool)) ,scara,SLOT(carouselNextPipette(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_calibrate()) ,scara,SLOT(calibrate()) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_calibrateCarousel(bool)) ,scara,SLOT(calibrateCarousel(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_rotateArm(int,bool,int)) ,scara,SLOT(rotateArm(int,bool,int)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_enableEndEffector(bool,bool)) ,scara,SLOT(enableEndEffector(bool,bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_openEndEffector(bool)) ,scara,SLOT(openEndEffector(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_partialCloseEndEffector(bool)) ,scara,SLOT(partialCloseEndEffector(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_closeEndEffector(bool)) ,scara,SLOT(closeEndEffector(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_moveNext(bool)) ,scara,SLOT(moveNext(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_fill1(bool)) ,scara,SLOT(fill1(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_fill2(bool)) ,scara,SLOT(fill2(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_fill3(bool)) ,scara,SLOT(fill3(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_dispenseHighPressure(int,bool)) ,scara,SLOT(dispenseHighPressure(int,bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_powerDown()) ,scara,SLOT(powerDown()) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_powerUp()) ,scara,SLOT(powerUp()) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_peltier(bool)) ,scara,SLOT(peltier(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(scara_fan(bool)) ,scara,SLOT(fan(bool)) ,Qt::QueuedConnection);
// Filler Signals
connect(state,SIGNAL(filler_init(QString)) ,filler,SLOT(init(QString)) ,Qt::QueuedConnection);
connect(state,SIGNAL(filler_aspirateVolume(float,bool)) ,filler,SLOT(aspirateVolume(float,bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(filler_dispenseVolume(float,bool)) ,filler,SLOT(dispenseVolume(float,bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(filler_enablePressureControl(bool,bool)),filler,SLOT(enablePressureControl(bool,bool)),Qt::QueuedConnection);
// Thor Labs Motor Signals
connect(state,SIGNAL(thorLabsMotor_init(int)) ,tMotor,SLOT(init(int)) ,Qt::DirectConnection);
connect(state,SIGNAL(thorLabsMotor_calibrate()) ,tMotor,SLOT(calibrate()) ,Qt::QueuedConnection);
connect(state,SIGNAL(thorLabsMotor_moveToAbsolute(float,float)) ,tMotor,SLOT(moveMotorAbsolute(float,float)),Qt::QueuedConnection);
connect(state,SIGNAL(thorLabsMotor_moveByRelative(float,float)) ,tMotor,SLOT(moveMotorRelative(float,float)),Qt::QueuedConnection);
connect(state,SIGNAL(thorLabsMotor_getPosition(bool)) ,tMotor,SLOT(getPosition(bool)) ,Qt::QueuedConnection);
// Multiclamp Signals
connect(state,SIGNAL(multiclamp_init(int, QString)) ,multiclamp,SLOT(init(int, QString)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_selectChannel(int)) ,multiclamp,SLOT(selectChannel(int)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_setMode(int)) ,multiclamp,SLOT(setMode(int)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_setHoldingVSafe(double,bool)) ,multiclamp,SLOT(setHoldingVoltageSafe(double,bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_setHoldingVRaw(double)) ,multiclamp,SLOT(setHoldingVoltageRaw(double)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_setHoldingISafe(double,bool)) ,multiclamp,SLOT(setHoldingCurrentSafe(double,bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_setHoldingIRaw(double)) ,multiclamp,SLOT(setHoldingCurrentRaw(double)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_setHoldingVChecked(bool)) ,multiclamp,SLOT(setHoldingVoltageChecked(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_setHoldingIChecked(bool,bool)) ,multiclamp,SLOT(setHoldingCurrentChecked(bool,bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_autoPipetteOffset()) ,multiclamp,SLOT(autoCorrectOffset()) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_autoFastCapacitance()) ,multiclamp,SLOT(autoFastCapacitance()) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_autoSlowCapacitance()) ,multiclamp,SLOT(autoSlowCapacitance()) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_getFastCapacitanceValue()) ,multiclamp,SLOT(getFastCapacitanceValue()) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_enablePipetteCapacitanceCompensation(bool)) ,multiclamp,SLOT(enablePipetteCapacitanceCompensation(bool)),Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_setPipetteCapacitanceCompensation(double)) ,multiclamp,SLOT(setPipetteCapacitanceCompensation(double)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_getPipetteCapacitanceCompensation()) ,multiclamp,SLOT(getPipetteCapacitanceCompensation()) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_setFastCapacitanceValue(double)) ,multiclamp,SLOT(setFastCapacitanceValue(double)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_setWholeCellChecked(bool)) ,multiclamp,SLOT(setWholeCellChecked(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_autoBridgeBalance()) ,multiclamp,SLOT(autoBridgeBalance()) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_getBridgeBalance()) ,multiclamp,SLOT(getBridgeBalance()) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_setBridgeBalance(double,bool)) ,multiclamp,SLOT(setBridgeBalance(double,bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_injectSlowCurrentEnable(bool)) ,multiclamp,SLOT(injectSlowCurrentEnable(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_injectSlowCurrentSetTimeConstant(double)) ,multiclamp,SLOT(injectSlowCurrentSetTimeConstant(double)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_injectSlowCurrentSetVoltage(double)) ,multiclamp,SLOT(injectSlowCurrentSetVoltage(double)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_leakSubtractionChecked(bool)) ,multiclamp,SLOT(leakSubtractionChecked(bool)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_zap(double)) ,multiclamp,SLOT(zap(double)) ,Qt::QueuedConnection);
connect(state,SIGNAL(multiclamp_zapWithDelay(double,int)) ,multiclamp,SLOT(zapWithDelay(double,int)) ,Qt::QueuedConnection);
// DAQ Signals
connect(state,SIGNAL(daq_init(QString)) ,daq,SLOT(init(QString)) ,Qt::QueuedConnection);
connect(state,SIGNAL(daq_initTask(int)) ,daq,SLOT(initTask(int)) ,Qt::QueuedConnection);
connect(state,SIGNAL(daq_startTask()) ,daq,SLOT(startTask()) ,Qt::QueuedConnection);
connect(state,SIGNAL(daq_stopTask()) ,daq,SLOT(stopTask()) ,Qt::QueuedConnection);
connect(state,SIGNAL(daq_getTaskRunning()) ,daq,SLOT(getTaskRunning()) ,Qt::QueuedConnection);
connect(state,SIGNAL(daq_trigger()) ,daq,SLOT(trigger()) ,Qt::QueuedConnection);
connect(state,SIGNAL(daq_setCurrentInjAmplitude(double)) ,daq,SLOT(setCurrInjAmplitude(double)) ,Qt::QueuedConnection);
connect(state,SIGNAL(daq_setBACCurrentInjAmplitude(double)) ,daq,SLOT(setBACCurrInjAmplitude(double)) ,Qt::QueuedConnection);
connect(state,SIGNAL(daq_setBACCurrentInjFrequency(double)) ,daq,SLOT(setBACCurrInjFrequency(double)) ,Qt::QueuedConnection);
// Visual Signals
connect(state,SIGNAL(visual_init(QString,QString)) ,visualStim,SLOT(init(QString,QString)) ,Qt::QueuedConnection);
connect(state,SIGNAL(visual_start(int)) ,visualStim,SLOT(start(int)) ,Qt::QueuedConnection);
connect(state,SIGNAL(visual_stop()) ,visualStim,SLOT(stop()) ,Qt::QueuedConnection);
connect(state,SIGNAL(visual_pause()) ,visualStim,SLOT(pause()) ,Qt::QueuedConnection);
connect(state,SIGNAL(visual_continue()) ,visualStim,SLOT(continue_()) ,Qt::QueuedConnection);
// Length Signals
connect(state,SIGNAL(length_init()) ,length,SLOT(init()) ,Qt::QueuedConnection);
connect(state,SIGNAL(length_measure()) ,length,SLOT(measureLength()) ,Qt::QueuedConnection);
connect(state,SIGNAL(length_aboutToClose()) ,length,SLOT(aboutToClose()) ,Qt::QueuedConnection);
// SLOTS
connect(ui->pushButtonPause,SIGNAL(toggled(bool)) ,state,SLOT(pauseState(bool)) ,Qt::QueuedConnection);
// Autopatcher Slots
connect(autopatcher,SIGNAL(initReady()) ,state,SLOT(autopatcher_initReady()) ,Qt::QueuedConnection);
connect(autopatcher,SIGNAL(initError()) ,state,SLOT(autopatcher_initError()) ,Qt::QueuedConnection);
connect(autopatcher,SIGNAL(breakInFinished()) ,state,SLOT(autopatcher_breakInComplete()) ,Qt::QueuedConnection);
connect(autopatcher,SIGNAL(breakInRampFinished()) ,state,SLOT(autopatcher_breakInRampFinished()) ,Qt::QueuedConnection);
// Headstage Clamp Slots
connect(headstageClamp,SIGNAL(initReady()) ,state,SLOT(headstageClamp_initReady()) ,Qt::QueuedConnection);
connect(headstageClamp,SIGNAL(initError()) ,state,SLOT(headstageClamp_initError()) ,Qt::QueuedConnection);
connect(headstageClamp,SIGNAL(commandFinished()) ,state,SLOT(headstageClamp_commandFinished()) ,Qt::QueuedConnection);
// SCARA Slots
connect(scara,SIGNAL(initReady()) ,state,SLOT(scara_initReady()) ,Qt::QueuedConnection);
connect(scara,SIGNAL(initError()) ,state,SLOT(scara_initError()) ,Qt::QueuedConnection);
connect(scara,SIGNAL(calibFinished()) ,state,SLOT(scara_calibrateFinished()) ,Qt::QueuedConnection);
connect(scara,SIGNAL(commandFinished()) ,state,SLOT(scara_commandFinished()) ,Qt::QueuedConnection);
// Filler Slots
connect(filler,SIGNAL(initReady()) ,state,SLOT(filler_initReady()) ,Qt::QueuedConnection);
connect(filler,SIGNAL(initError()) ,state,SLOT(filler_initError()) ,Qt::QueuedConnection);
connect(filler,SIGNAL(commandFinished()),state,SLOT(filler_commandFinished()) ,Qt::QueuedConnection);
// Thor Labs Motor Slots
connect(tMotor,SIGNAL(initReady()) ,state,SLOT(thorLabsMotor_initReady()) ,Qt::QueuedConnection);
connect(tMotor,SIGNAL(initError()) ,state,SLOT(thorLabsMotor_initError()) ,Qt::QueuedConnection);
connect(tMotor,SIGNAL(calibFinished()) ,state,SLOT(thorLabsMotor_calibrateFinished()) ,Qt::QueuedConnection);
connect(tMotor,SIGNAL(moveMotorFinished()) ,state,SLOT(thorLabsMotor_moveComplete()) ,Qt::QueuedConnection);
connect(tMotor,SIGNAL(currentMotorPosition(float)) ,state,SLOT(thorLabsMotor_currentMotorPosition(float)) ,Qt::QueuedConnection);
// Multiclamp Slots
connect(multiclamp,SIGNAL(initReady()) ,state,SLOT(multiclamp_initReady()) ,Qt::QueuedConnection);
connect(multiclamp,SIGNAL(initError()) ,state,SLOT(multiclamp_initError()) ,Qt::QueuedConnection);
connect(multiclamp,SIGNAL(autoOffsetComplete()) ,state,SLOT(multiclamp_autoPipetteOffsetComplete()) ,Qt::QueuedConnection);
connect(multiclamp,SIGNAL(autoFastCapacitanceComplete()) ,state,SLOT(multiclamp_autoFastCapacitanceComplete()) ,Qt::QueuedConnection);
connect(multiclamp,SIGNAL(setHoldingVoltageSafeComplete()) ,state,SLOT(multiclamp_setHoldingVoltageSafeComplete()) ,Qt::QueuedConnection);
connect(multiclamp,SIGNAL(setHoldingCurrentSafeComplete()) ,state,SLOT(multiclamp_setHoldingCurrentSafeComplete()) ,Qt::QueuedConnection);
connect(multiclamp,SIGNAL(pipetteCapacitanceCompensationValue(double)),state,SLOT(multiclamp_pipetteCapacitanceCompensationValue(double)) ,Qt::QueuedConnection);
connect(multiclamp,SIGNAL(holdingCurrentCheckedComplete()) ,state,SLOT(multiclamp_holdingCurrentCheckedComplete()) ,Qt::QueuedConnection);
connect(multiclamp,SIGNAL(setBridgeBalanceComplete()) ,state,SLOT(multiclamp_setBridgeBalanceComplete()) ,Qt::QueuedConnection);
connect(multiclamp,SIGNAL(getBridgeBalanceComplete(double)) ,state,SLOT(multiclamp_getBridgeBalanceComplete(double)),Qt::QueuedConnection);
// DAQ Slots
connect(daq,SIGNAL(initReady()) ,state,SLOT(daq_initReady()) ,Qt::QueuedConnection);
connect(daq,SIGNAL(initError()) ,state,SLOT(daq_initError()) ,Qt::QueuedConnection);
connect(daq,SIGNAL(initTaskReady()) ,state,SLOT(daq_initTaskReady()) ,Qt::QueuedConnection);
connect(daq,SIGNAL(initTaskError()) ,state,SLOT(daq_initTaskError()) ,Qt::QueuedConnection);
connect(daq,SIGNAL(memTestValsReady(QVector<double>)) ,state,SLOT(daq_memTestValsReady(QVector<double>)) ,Qt::QueuedConnection);
connect(daq,SIGNAL(resDataReady(double)) ,state,SLOT(daq_resDataReady(double)) ,Qt::QueuedConnection);
connect(daq,SIGNAL(taskIsRunning(int)) ,state,SLOT(daq_taskRunning(int)) ,Qt::QueuedConnection);
connect(daq,SIGNAL(rawDataReady(QVector<double>)) ,state,SLOT(daq_rawDataReady(QVector<double>)) ,Qt::QueuedConnection);
connect(daq,SIGNAL(currInjDataReady(QVector<double>)) ,state,SLOT(daq_currInjDataReady(QVector<double>)) ,Qt::QueuedConnection);
connect(daq,SIGNAL(bacCurrInjDataReady(QVector<double>)),state,SLOT(daq_bacCurrInjDataReady(QVector<double>)) ,Qt::QueuedConnection);
// Visual Stim
connect(visualStim,SIGNAL(initReady()) ,state,SLOT(visual_initReady()) ,Qt::QueuedConnection);
connect(visualStim,SIGNAL(initError()) ,state,SLOT(visual_initError()) ,Qt::QueuedConnection);
connect(visualStim,SIGNAL(started()) ,state,SLOT(visual_started()) ,Qt::QueuedConnection);
connect(visualStim,SIGNAL(paused()) ,state,SLOT(visual_paused()) ,Qt::QueuedConnection);
connect(visualStim,SIGNAL(finished()) ,state,SLOT(visual_finished()) ,Qt::QueuedConnection);
connect(visualStim,SIGNAL(stopped()) ,state,SLOT(visual_stopped()) ,Qt::QueuedConnection);
// Length Measurement
connect(length,SIGNAL(initReady()) ,state,SLOT(length_initReady()) ,Qt::QueuedConnection);
connect(length,SIGNAL(initError()) ,state,SLOT(length_initError()) ,Qt::QueuedConnection);
connect(length,SIGNAL(imagesAquired()) ,state,SLOT(length_imagesAquired()) ,Qt::QueuedConnection);
connect(length,SIGNAL(measurementReady(float)) ,state,SLOT(length_measurementReady(float)) ,Qt::QueuedConnection);
// OTHER SIGNALS THAT HAVE TO BE REESTABLISHED BECAUSE EVERYTHING GETS DISCONNECTED IN THE "disconnectState" function
// ADD ANY OTHER SIGNALS TO THAT FUNCTION THAT DON'T GO THROUGH State.h AND CONNECT BETWEEEN ANYTHING ELSE AND THE WORKERS.
}
void MainWindow::disconnectState(State *state)
{
// All the objects referenced in connectState need to be listed here or
// things will get connected and not disconnected whenever the state changes.
ui->pushButtonPause->disconnect();
state->disconnect();
autopatcher->disconnect();
headstageClamp->disconnect();
scara->disconnect();
filler->disconnect();
tMotor->disconnect();
multiclamp->disconnect();
daq->disconnect();
visualStim->disconnect();
length->disconnect();
// This is not a state connection but to use the "disconnect" function, I have to restablish the connection with every other signal.
connect(daq,SIGNAL(rawDataReady()),this,SLOT(rawDataReadySlot()),Qt::QueuedConnection);
}
void MainWindow::addStates(vector< vector<State*> > &table, State** states)
{
table.push_back(vector<State*>(states,states+sizeof(states)/sizeof(State*)));
}
void MainWindow::pauseState(State *)
{
}
void MainWindow::resumeState(State *)
{
}
void MainWindow::busy_start(QString msg)
{
if(!busy.isActive())
{
busy.start();
}
ui->textStatus->setText(msg);
}
void MainWindow::busy_stop(QString msg)
{
busy.stop();
ui->textBusy->setText("✔");
ui->textStatus->setText(msg);
}
void MainWindow::busy_stop_error(QString msg)
{
busy.stop();
ui->textBusy->setText("X");
ui->textStatus->setText(msg);
}
void MainWindow::setCurrentPageIndex(int i)
{
ui->pages->setCurrentIndex(i);
}
void MainWindow::setCurrentPageIndex(QString pgObjName)
{
for(int i=0; i<ui->pages->count(); i++)
{
if(ui->pages->widget(i)->objectName() == pgObjName)
{
ui->pages->setCurrentIndex(i);
break;
}
}
}
void MainWindow::enablePages(bool flag)
{
ui->pages->setEnabled(flag);
}
void MainWindow::setTextStatus(QString msg)
{
ui->textStatus->setText(msg);
}
void MainWindow::clearResistancePlot()
{
ui->resistancePlot->graph(0)->clearData();;
resPlotData.clear();
ui->resistancePlot->replot();
}
void MainWindow::clearRawDataPlot()
{
ui->rawPlot->graph(0)->clearData();
rawPlotData.clear();
ui->rawPlot->replot();
}
void MainWindow::clearMemTestPlot()
{
ui->membraneTestPlot->graph(0)->clearData();
ui->membraneTestPlot->replot();
}
void MainWindow::enableActionFillPipette(bool flag)
{
ui->actionFill_Pipette->setEnabled(flag);
}
void MainWindow::enableActionResetCarousel(bool flag)
{
ui->actionReset_Carousel->setEnabled(flag);
}
void MainWindow::enableActionLoadMicrofil(bool flag)
{
ui->actionLoad_microfil_20uL->setEnabled(flag);
}
void MainWindow::updateCurrentPosition()
{
ui->label_CurrentPosition->setText(QString::number(tMotor->getPosition()*1000));
}
void MainWindow::updateCurrentBrainPosition(double depth)
{
ui->label_BrainPosition->setText(QString::number(depth));
}
void MainWindow::guiInit()
{
ui->setupUi(this);
QThread::currentThread()->setPriority(QThread::TimeCriticalPriority);
busy_start("Initializing...");
ui->pages->setCurrentIndex(0);
ui->pages->setEnabled(false);
ui->pushButtonGo1->setEnabled(true);
ui->pushButtonHALT->setVisible(false);
ui->actionFill_Pipette->setEnabled(false);
ui->actionReset_Carousel->setEnabled(false);
ui->actionLoad_microfil_20uL->setEnabled(false);
ui->actionHome_Thorlabs_Motor->setEnabled(false);
ui->actionRetract_Headstage_Wire->setEnabled(false);
ui->actionInsert_Headstage_Wire->setEnabled(false);
ui->actionOpen_Headstage_Clamp->setEnabled(false);
ui->actionClose_Headstage_Clamp->setEnabled(false);
ui->actionFinish_Visual_Stimuli->setEnabled(false);
ui->actionReset_Brain_Height_On_New_Pipette->setEnabled(false);
ui->actionFiller_Valve_On->setEnabled(false);
ui->actionFiller_Valve_Off->setEnabled(false);
ui->checkBoxPauseOnRemoval->setVisible(false);
ui->pushButtonPause->setVisible(false);
imgLEDon = QPixmap("../img/LED_on.png");
imgLEDoff = QPixmap("../img/LED_off.png");
// imgScara = QPixmap("../img/scara_adjust_view.png");
// ui->LED->setPixmap(imgLEDoff);
// ui->label_scara_adjust_view->setPixmap(imgScara);
// ui->label_scara_adjust_view->setScaledContents(true);
ap_win = new AutopatcherSettingsWindow();
connect(ap_win,SIGNAL(windowClosed()),this,SLOT(apSettingsChanged()),Qt::QueuedConnection);
AP_Data = ap_win->getVals();
AP_Data.setWindowTitle(this->windowTitle());
AP_Data.LOG_experimentDateTime.setDate(QDate::currentDate());
brkZapSettings = new BreakInSettingsZap();
connect(brkZapSettings,SIGNAL(windowClosed()),this,SLOT(breakInSettingsChangedZap()),Qt::QueuedConnection);
brkSuckSettings = new BreakInSettingsSuction();
connect(brkSuckSettings,SIGNAL(windowClosed()),this,SLOT(breakInSettingsChangedSuction()),Qt::QueuedConnection);
brkRampSettings = new BreakInSettingsRamp();
connect(brkRampSettings,SIGNAL(windowClosed()),this,SLOT(breakInSettingsChangedRamp()),Qt::QueuedConnection);
hw_win = new HardwareSettingsWindow();
connect(hw_win,SIGNAL(windowClosed()),this,SLOT(hwSettingsChanged()),Qt::QueuedConnection);
pref_win = new Preferences();
connect(pref_win,SIGNAL(windowClosed()),this,SLOT(preferencesWindowClosed()),Qt::QueuedConnection);
loadPreferences();
// GUI VARIABLES
if(ui->radioButton->isChecked()) numStepsScaraAdjust = ui->radioButton->text().split(QRegExp("([^0-9])+"))[0].toInt();
if(ui->radioButton_2->isChecked()) numStepsScaraAdjust = ui->radioButton_2->text().split(QRegExp("([^0-9])+"))[0].toInt();
if(ui->radioButton_3->isChecked()) numStepsScaraAdjust = ui->radioButton_3->text().split(QRegExp("([^0-9])+"))[0].toInt();
if(ui->radioButton_4->isChecked()) microfilFillVolumeAdjust = ui->radioButton_4->text().split(QRegExp("([^0-9])+"))[0].toInt();
if(ui->radioButton_5->isChecked()) microfilFillVolumeAdjust = ui->radioButton_5->text().split(QRegExp("([^0-9])+"))[0].toInt();
if(ui->radioButton_6->isChecked()) microfilFillVolumeAdjust = ui->radioButton_6->text().split(QRegExp("([^0-9])+"))[0].toInt();
if(ui->radioButton_7->isChecked()) pipetteAdjustDistance = ui->radioButton_7->text().split(QRegExp("([^0-9])+"))[0].toInt();
if(ui->radioButton_8->isChecked()) pipetteAdjustDistance = ui->radioButton_8->text().split(QRegExp("([^0-9])+"))[0].toInt();
if(ui->radioButton_9->isChecked()) pipetteAdjustDistance = ui->radioButton_9->text().split(QRegExp("([^0-9])+"))[0].toInt();
if(ui->radioButton_10->isChecked()) pipetteAdjustDistance = ui->radioButton_10->text().split(QRegExp("([^0-9])+"))[0].toInt();
// This selects the state execution mode (see initializeStates)
ui->comboBoxModeSelect->addItem("Autopatch");
ui->comboBoxModeSelect->addItem("Load 1 Pipette");
ui->comboBoxModeSelect->addItem("Continuous Pipette Cycle");
ui->comboBoxModeSelect->addItem("Continuous Resistance Checks");
ui->comboBoxModeSelect->addItem("Test the new algorithms");
ui->comboBoxModeSelect->addItem("Test");
}
void MainWindow::loadPreferences()
{
// Name value pairs
QStringList names;
names << "data directory" << "experiment date" << "trial number" << "output file format";
QVector<bool> flags(names.size(),false);
QString trialNum;
qWarning() << "Loading preferences file";
ifstream fin;
QDir path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0) + "/" + this->windowTitle() + "/";
QString fullPath = path.path() + "/preferences.txt";
fin.open(fullPath.toStdString().c_str());
if(fin.is_open())
{
string str;
QString tmp;
int i(0);
while(getline(fin,str))
{
i++;
tmp = QString::fromStdString(str);
QString name = tmp.split(QRegExp("(=)+"))[0];
QString value = tmp.split(QRegExp("(=)+"))[1];
int flag(0);
if (name.contains(names[0],Qt::CaseInsensitive)){ flag = 1;}
else if(name.contains(names[1],Qt::CaseInsensitive)){ flag = 2;}
else if(name.contains(names[2],Qt::CaseInsensitive)){ flag = 3;}
else if(name.contains(names[3],Qt::CaseInsensitive)){ flag = 4;}
else flag = 0;
switch (flag)
{
case 1: // Data Directory
{
QDir tmp2(value);
if(tmp2.exists())
{
pref_win->setDataDir(QDir(value));
flags[1] = true;
}
else
{
tmp2.mkpath(tmp2.path());
pref_win->setDataDir(QDir(value));
flags[1] = true;
}
break;
}
case 2: // experiment date (but this should be based on the clock, not the file
{
// QStringList tmp3 = value.split(QRegExp("(-)+"));
// AP_Data.LOG_experimentDateTime.setDate(QDate(tmp3[0].toInt(),tmp3[1].toInt(),tmp3[2].toInt()));
// if(AP_Data.LOG_experimentDateTime.date().isValid()) flags[2] = true;
// else
// if(AP_Data.LOG_experimentDateTime != QDateTime::currentDateTime())
AP_Data.LOG_experimentDateTime = QDateTime::currentDateTime();
break;
}
case 3: // trial number
// waiting to process the trial number until all the lines have been read. this is done in the error checking
// section next
trialNum = value;
break;
case 4: // Output file format
{
bool ok(0);
AP_Data.fileFormat = value.toInt(&ok);
pref_win->setFileFormat(value.toInt(&ok));
if(!ok) flags[4] = false;
else flags[4] = true;
break;
}
case 0:
{
qWarning() << "Bad line in preferences file: " << QString::number(i);
}
}
}
fin.close();
}
else // If file wasn't opened
{
qWarning() << "Preferences file not opened.";
}
// Error checking
for(int i=0; i<flags.size(); i++)
{
if(!flags[i])
{
switch(i)
{
case 1:
{
qWarning() << "data directory error in preferences file. Using default.";
QDir dataDir = QStandardPaths::standardLocations(QStandardPaths::HomeLocation).at(0) + "/" + this->windowTitle() + "/data/";
pref_win->setDataDir(dataDir);
if(!dataDir.exists()) dataDir.mkpath(dataDir.path());
}
break;
case 2:
{
qWarning() << "experiment date error in preferences file. Using default.";
AP_Data.LOG_experimentDateTime.setDate(QDate::currentDate());
break;
}
case 3:
{
if(AP_Data.LOG_experimentDateTime.date() == QDate::currentDate())
{
bool ok(0);
AP_Data.trialNum = trialNum.toInt(&ok);
if(!ok)
{
AP_Data.trialNum = 0;
}
}
else // new day, start the trial number from zero
{
AP_Data.trialNum = 0;
}
break;
}
case 4:
AP_Data.fileFormat = 2;
pref_win->setFileFormat(AP_Data.fileFormat);
break;
}
}
}
}
void MainWindow::savePreferences()
{
QDir path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0) + "/" + this->windowTitle() + "/";
if(!path.exists()){path.mkpath(path.path());}
QString fullPath = path.path() + "/preferences.txt";
qWarning() << "Saving preferences file." << fullPath;
ofstream fout;
fout.open(fullPath.toStdString().c_str());
if(fout.is_open())
{
fout << "data directory = " << AP_Data.dataDir.path().toStdString() << "\n";
fout << "experiment date = " << QDate::currentDate().toString("yyyy-MM-dd").toStdString() << "\n";
fout << "output file format = " << AP_Data.fileFormat << "\n";
fout << "trial number = " << QString::number(AP_Data.trialNum).toStdString() << "\n";;
fout.close();
}
else
{
qWarning() << "Preferences file could not be saved.";
}
}
void MainWindow::plotInit()
{
rawPlotBuffSize = 5*daq->getSamplingRate();
ui->rawPlot->addGraph();
QPen my_pen = QPen(Qt::blue);
my_pen.setWidthF(0.5);
ui->rawPlot->graph(0)->setPen(my_pen);
ui->rawPlot->xAxis->setRange(0,rawPlotBuffSize);
ui->rawPlot->xAxis->setVisible(false);
ui->rawPlot->graph(0)->setAntialiased(false);
ui->rawPlot->setNoAntialiasingOnDrag(true);
ui->rawPlot->graph(0)->setAdaptiveSampling(true);
ui->resistancePlot->addGraph();
ui->resistancePlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, Qt::white, 4));
ui->resistancePlot->graph(0)->setAntialiased(false);
ui->resistancePlot->graph(0)->setLineStyle(QCPGraph::lsNone);
ui->resistancePlot->replot();
ui->resistancePlot->xAxis->setVisible(false);
ui->resistancePlot->setNoAntialiasingOnDrag(true);
ui->resistancePlot->graph(0)->setAdaptiveSampling(true);
ui->membraneTestPlot->addGraph();
ui->membraneTestPlot->graph(0)->setPen(my_pen);
ui->membraneTestPlot->xAxis->setRange(0,200);
ui->membraneTestPlot->xAxis->setVisible(false);
ui->membraneTestPlot->graph(0)->setAntialiased(0);
ui->membraneTestPlot->setNoAntialiasingOnDrag(true);
ui->membraneTestPlot->graph(0)->setAdaptiveSampling(true);
}
// DAQ slots
void MainWindow::rawDataReadySlot()
{
daq->getRawData(&raw);
if(ui->pages->currentWidget()->objectName() == "page_autopatching") plotRawData(); // this will plot "raw"
if(ui->pages->currentWidget()->objectName() == "page_cell_qc") rawMemTestDataReady(raw);
}
void MainWindow::rawMemTestDataReady(QVector<double> buffer)
{
QVector<double> keys(buffer.size());
for(int i=0; i<buffer.size(); i++)
{
keys[i] = i;
}
ui->membraneTestPlot->graph(0)->setData(keys,buffer);
ui->membraneTestPlot->yAxis->rescale();
ui->membraneTestPlot->replot();
}
void MainWindow::updateMemTestVals(QVector<double> vals)
{
ofstream cout;
cout << "Trial Number: " << AP_Data.trialNum << "Cell parameters: ";
for(int i=0; i<vals.size(); i++)
{
cout << vals[i] << " " ;
}
cout << endl;
ui->lineEditCm->setText(QString::number(vals[0],'g',3)); // Cm Membrane Capacitance
ui->lineEditRm->setText(QString::number(vals[1],'g',3)); // Rm Membrane Resistance
ui->lineEditRa->setText(QString::number(vals[2],'g',3)); // Ra Access Resistance
ui->lineEditTau->setText(QString::number(vals[3],'g',3)); // Tau RC time constant
ui->lineEditHold->setText(QString::number(vals[4],'g',4));// Holding holding current
}
void MainWindow::busyTimeout()
{
static int num(0);
switch(num)
{
case 0:
ui->textBusy->setText("--");
num = 1;
break;
case 1:
ui->textBusy->setText("\\");
num = 2;
break;
case 2:
ui->textBusy->setText("|");
num = 3;
break;
case 3:
ui->textBusy->setText("/");
num = 0;
break;
}
}
// *********************
// Page 0 CBs
// *********************
void MainWindow::on_pushButtonGo1_released()
{
ui->pushButtonGo1->setEnabled(false);
ui->pages->setEnabled(false);
initializeStates();
if(!stateRunning)
{
currentState = &hardwareInitState;
startStateMachine();
}
}
// *********************
// Page 1 CBs
// *********************
void MainWindow::on_pushButtonGo3_released()
{
// This is simpler than using the signals and slots
setBrainHeightState.gui_pushbuttonGO3Released(tMotor);
ui->label_CurrentPosition->setText(QString::number(tMotor->getPosition()*1000));
}
// *********************
// Page 2 CBs
// *********************
void MainWindow::plotRawData()
{
QTime profile;
profile = profile.currentTime();
// Loading the QCPData structure with new data
static int indexMarker(0); // Marks the key where the last data point was added to the plot
int length = rawPlotData.size();
// Filling the buffer if it isn't full. Once it' wraps around the end of the buffer, it sets the indexMarker and all
// subsequent data is handled in the wrapping buffer fashion.
if(rawPlotData.size() < rawPlotBuffSize)
{
if(length+raw.size() < rawPlotBuffSize)
{
int j=0;
for(int i=length; i<raw.size()+length; i++)
{
rawPlotData.insert(i,QCPData(i,raw.at(j)));
j++;
}
}
else
{
int j=0;
for(int i=length; i<rawPlotBuffSize; i++)
{
rawPlotData.insert(i,QCPData(i,raw.at(j)));
j++;
}
int tmp = j;
for(int i=0; i<raw.size()-tmp; i++)
{
rawPlotData.insert(i,QCPData(i,raw.at(j)));
j++;
indexMarker = j-tmp;
}
}
}
// If the data has wrapped around the buffer once already, this gives it the o-scope behavior
else if(length == rawPlotBuffSize)
{
// If the new data won't wrap around the end of the buffer
if(indexMarker+raw.size()<rawPlotBuffSize)
{
int j=0;
for(int i=indexMarker; i<raw.size()+indexMarker; i++)
{
rawPlotData.insert(i,QCPData(i,raw.at(j)));
j++;
}
indexMarker = raw.size() + indexMarker;
}
// If the new data will wrap around
else if(indexMarker+raw.size() >= rawPlotBuffSize)
{
int j=0;
for(int i=indexMarker; i<rawPlotBuffSize; i++)
{
rawPlotData.insert(i,QCPData(i,raw.at(j)));
j++;
}
int tmp = j;
for(int i=0; i<raw.size()-tmp; i++)
{
rawPlotData.insert(i,QCPData(i,raw.at(j)));
j++;
}
indexMarker = j-tmp;
}
}
// Plotting
ui->rawPlot->graph(0)->setData(&rawPlotData,true);
ui->rawPlot->yAxis->rescale();
ui->rawPlot->replot();
//qWarning() << "Raw Plot data size: " << ui->rawPlot->graph(0)->data()->size();
//qWarning() << "Raw plot profiler" << profile.msec() << profile.currentTime().msec() - profile.msec() << profile.currentTime().msec();
}
void MainWindow::plotResData(double res)
{
// This function adds the resistance value to the resistance plot
// and overwrites the raw current traces with the new data
if(resPlotData.size()<70)
{
// qWarning() << resPlotData.size() << " " << resPlotData.keys().value(resPlotData.size()-1);
resPlotData.insert(resPlotData.size(),QCPData(resPlotData.size(),res));
ui->resistancePlot->graph(0)->clearData();
ui->resistancePlot->graph(0)->addData(resPlotData);
}
else
{
// qWarning() << "Removing... " << resPlotData.keys().value(0);
// qWarning() << "Adding..... " << resPlotData.keys().value(resPlotData.size()-1)+1;
resPlotData.remove(resPlotData.keys().value(0));
resPlotData.insert(resPlotData.keys().value(resPlotData.size()-1)+1,QCPData(resPlotData.keys().value(resPlotData.size()-1)+1,res));
ui->resistancePlot->graph(0)->clearData();
ui->resistancePlot->graph(0)->addData(resPlotData);
}
// There usually aren't very many resistance values (<200) so code optimization here is unnecessary.
QList<QCPData> vals = resPlotData.values();
double resMax = vals.at(0).value;
double resMin = vals.at(0).value;
for(int i=0; i<vals.size()-1; i++)
{
if(vals.at(i+1).value>resMax)
{
resMax = vals.at(i+1).value;
}
if(vals.at(i+1).value<resMin)
{
resMin = vals.at(i+1).value;
}
}
ui->resistancePlot->yAxis->setRange(resMin-resMax*0.05,resMax+0.05*resMax);
double start = resPlotData.keys()[0]-1;
double end = resPlotData.keys()[resPlotData.keys().size()-1]+1;
ui->resistancePlot->xAxis->setRange(start,end);
ui->resistancePlot->replot();
}
// *********************
// General CBs
// *********************
void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
if(event->isAccepted())
{
switch(event->key())
{
case Qt::Key_Down:
event->accept();
if(ui->pages->widget(ui->pages->currentIndex())->objectName() == "page_brain_height_adjustment") ui->pushButtonDownAdjust->animateClick(500);
break;
case Qt::Key_Up:
event->accept();
if(ui->pages->widget(ui->pages->currentIndex())->objectName() == "page_brain_height_adjustment") ui->pushButtonUpAdjust->animateClick(500);
break;
case Qt::Key_Enter:
event->accept();
if(ui->pages->widget(ui->pages->currentIndex())->objectName() == "page_hardware_init") ui->pushButtonGo1->animateClick(100);
else if(ui->pages->widget(ui->pages->currentIndex())->objectName() == "page_hardware_init") ui->pushButtonGo3->animateClick(100);
break;
case Qt::Key_Return:
event->accept();
if(ui->pages->widget(ui->pages->currentIndex())->objectName() == "page_hardware_init") ui->pushButtonGo1->animateClick(100);
else if(ui->pages->widget(ui->pages->currentIndex())->objectName() == "page_brain_height_adjustment") ui->pushButtonGo3->animateClick(100);
break;
default:
event->ignore();
break;
}
}
}
void MainWindow::on_pushButtonHALT_clicked()
{
qWarning() << "Halt clicked. ADD CODE FOR INTERRUPTING STATES";
}
void MainWindow::savePlot(QString fname, QCustomPlot *plot)
{
QString desktopDir = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation).at(0);
QString ffname = "trial " + QString::number(AP_Data.trialNum) + " " +fname+ ".png";
QString date = QDate::currentDate().toString("M-d");
QString fullpath = desktopDir + "/" + date + "/trial " + ffname;
plot->savePng(fullpath,800,600);
}
void MainWindow::incrementTrialNumber()
{
if(stateRunning && currentState != NULL) AP_Data = currentState->getData();
savePreferences();
ui->label_trialNumber->setText("Trial Number: " + QString::number(AP_Data.trialNum));
}
void MainWindow::apSettingsChanged()
{
qWarning() << "Autopatcher settings window closed. Any data changed during this state up to this point will be lost.";
AP_Data = ap_win->getVals();
if(currentState != NULL) currentState->setData(AP_Data);
AP_Data.saveSettings();
}
void MainWindow::breakInSettingsChangedZap()
{
qWarning() << "Break in settings changed ";
AP_Data.breakInTableZap = brkZapSettings->getTable();
if(currentState != NULL) currentState->setData(AP_Data);
}
void MainWindow::breakInSettingsChangedSuction()
{
qWarning() << "Break in settings changed Suction";
AP_Data.breakInTableSuction = brkSuckSettings->getTable();
if(currentState != NULL) currentState->setData(AP_Data);
}
void MainWindow::breakInSettingsChangedRamp()
{
qWarning() << "Break in settings changed Ramp";
AP_Data.breakInTableRamp = brkRampSettings->getTable();
if(currentState != NULL) currentState->setData(AP_Data);
}
void MainWindow::hwSettingsChanged()
{
qWarning() << "Hardware settings window closed, values updated";
for(int i=0; i<allStates.size(); i++)
{
allStates[i]->setHardwareVals(hw_win);
}
for(int i=0; i<allWorkers.size(); i++)
{
allWorkers[i]->setHardwareVals(hw_win);
}
}
void MainWindow::preferencesWindowClosed()
{
AP_Data.dataDir = pref_win->getDataDir();
AP_Data.fileFormat = pref_win->getFileFormat();
qWarning() << "FileFormat: " << AP_Data.fileFormat;
savePreferences();
}
void MainWindow::on_actionBreakInSuctionWindow_triggered()
{
brkSuckSettings->setTableData(AP_Data.breakInTableSuction);
brkSuckSettings->show();
}
void MainWindow::on_actionBreakInZapWindow_triggered()
{
brkZapSettings->setTableData(AP_Data.breakInTableZap);
brkZapSettings->show();
}
void MainWindow::on_actionBreakInRampWindow_triggered()
{
brkRampSettings->setTableData(AP_Data.breakInTableRamp);
brkRampSettings->show();
}
void MainWindow::on_actionAutopatcher_Settings_triggered()
{
if(stateRunning && currentState != NULL) AP_Data = currentState->getData();
ap_win->setVals(AP_Data);
ap_win->show();
qWarning() << "AP settings window launched";
}
void MainWindow::on_actionHardware_Settings_triggered()
{
hw_win->show();
qWarning() << "HW settings window launched.";
}
void MainWindow::closeEvent(QCloseEvent *e)
{
QMainWindow::closeEvent(e);
if(ap_win->isVisible()) ap_win->close();
if(brkRampSettings->isVisible()) brkRampSettings->close();
if(brkSuckSettings->isVisible()) brkSuckSettings->close();
if(brkZapSettings->isVisible()) brkZapSettings->close();
}
void MainWindow::on_checkBoxPauseOnRemoval_stateChanged(int)
{
}
void MainWindow::on_pushButtonSCARACalibrate_released()
{
hardwareCalibState.gui_calibrateSCARA();
}
void MainWindow::on_pushButtonArm1Clockwise_released()
{
currentState->gui_rotateSCARA(1,1,numStepsScaraAdjust);
}
void MainWindow::on_pushButtonArm1Counterclockwise_released()
{
currentState->gui_rotateSCARA(1,0,numStepsScaraAdjust);
}
void MainWindow::on_pushButtonArm2Counterclockwise_released()
{
currentState->gui_rotateSCARA(2,0,numStepsScaraAdjust);
}
void MainWindow::on_pushButtonArm2Clockwise_released()
{
currentState->gui_rotateSCARA(2,1,numStepsScaraAdjust);
}
void MainWindow::on_radioButton_toggled(bool checked)
{
if(checked)
{
numStepsScaraAdjust = ui->radioButton->text().split(QRegExp("([^0-9])+"))[0].toInt();
}
}
void MainWindow::on_radioButton_2_toggled(bool checked)
{
if(checked)
{
numStepsScaraAdjust = ui->radioButton_2->text().split(QRegExp("([^0-9])+"))[0].toInt();
}
}
void MainWindow::on_radioButton_3_toggled(bool checked)
{
if(checked)
{
numStepsScaraAdjust = ui->radioButton_3->text().split(QRegExp("([^0-9])+"))[0].toInt();
}
}
void MainWindow::on_radioButton_4_toggled(bool checked)
{
if(checked)
{
microfilFillVolumeAdjust = ui->radioButton_4->text().split(QRegExp("([^0-9])+"))[0].toInt();
}
}
void MainWindow::on_radioButton_5_toggled(bool checked)
{
if(checked)
{
microfilFillVolumeAdjust = ui->radioButton_5->text().split(QRegExp("([^0-9])+"))[0].toInt();
}
}
void MainWindow::on_radioButton_6_toggled(bool checked)
{
if(checked)
{
microfilFillVolumeAdjust = ui->radioButton_6->text().split(QRegExp("([^0-9])+"))[0].toInt();
}
}
void MainWindow::on_pushButtonDispenseLoadPipettes_released()
{
if(currentState != NULL)
currentState->gui_dispenseVolumeFiller(microfilFillVolumeAdjust,false);
}
void MainWindow::on_pushButtonAspirateLoadPipettes_released()
{
if(currentState != NULL)
currentState->gui_aspirateVolumeFiller(microfilFillVolumeAdjust,false);
}
void MainWindow::on_pushButtonNextLoadPipettes_released()
{
if(currentState != NULL)
currentState->gui_pushbuttonNextLoadPipettesReleased();
}
void MainWindow::on_actionReset_Carousel_triggered()
{
scara->resetCarousel();
}
void MainWindow::on_actionFill_Pipette_triggered()
{
disconnectState(currentState);
QMetaObject::invokeMethod(scara,"fill1",Qt::QueuedConnection,Q_ARG(bool,false));
QMetaObject::invokeMethod(filler,"enablePressureControl",Qt::QueuedConnection,Q_ARG(bool,true),Q_ARG(bool,false));
QMetaObject::invokeMethod(scara,"fill2",Qt::QueuedConnection,Q_ARG(bool,false));
QThread::sleep(2);
QMetaObject::invokeMethod(scara,"dispenseHighPressure",Qt::QueuedConnection,Q_ARG(int,100),Q_ARG(bool,false));
QThread::sleep(1);
QMetaObject::invokeMethod(filler,"enablePressureControl",Qt::QueuedConnection,Q_ARG(bool,false));
QMetaObject::invokeMethod(scara,"fill3",Qt::QueuedConnection,Q_ARG(bool,false));
connectState(currentState);
}
void MainWindow::on_radioButton_7_toggled(bool checked)
{
if(checked)
{
pipetteAdjustDistance = ui->radioButton_7->text().split(QRegExp("([^0-9])+"))[0].toInt();
}
}
void MainWindow::on_radioButton_8_toggled(bool checked)
{
if(checked)
{
pipetteAdjustDistance = ui->radioButton_8->text().split(QRegExp("([^0-9])+"))[0].toInt();
qWarning() << pipetteAdjustDistance << ui->radioButton_8->text().split(QRegExp("([^0-9])+"))[0] ;
}
}
void MainWindow::on_radioButton_9_toggled(bool checked)
{
if(checked)
{
pipetteAdjustDistance = ui->radioButton_9->text().split(QRegExp("([^0-9])+"))[0].toInt();
}
}
void MainWindow::on_radioButton_10_toggled(bool checked)
{
if(checked)
{
pipetteAdjustDistance = ui->radioButton_10->text().split(QRegExp("([^0-9])+"))[0].toInt();
}
}
void MainWindow::on_pushButtonUpAdjust_released()
{
if(currentState != NULL)
currentState->gui_upAdjustBtn(pipetteAdjustDistance);
}
void MainWindow::on_pushButtonDownAdjust_released()
{
if(currentState != NULL)
currentState->gui_downAdjustBtn(pipetteAdjustDistance);
}
void MainWindow::on_actionLoad_microfil_20uL_triggered()
{
if(currentState != NULL)
currentState->gui_Load20uLInMicrofil(false);
}
void MainWindow::on_actionHome_Thorlabs_Motor_triggered()
{
tMotor->calibrate();
}
void MainWindow::on_actionOpen_Headstage_Clamp_triggered()
{
headstageClamp->openClamp(false);
}
void MainWindow::on_actionRetract_Headstage_Wire_triggered()
{
headstageClamp->retractWire(false);
}
void MainWindow::on_pushButtonPause_toggled(bool checked)
{
if(checked)
{
ui->pushButtonPause->setText("Resume");
}
else
{
ui->pushButtonPause->setText("Pause");
}
}
void MainWindow::on_actionPreferences_triggered()
{
pref_win->setFileFormat(AP_Data.fileFormat);
pref_win->setDataDir(AP_Data.dataDir);
pref_win->show();
}
void MainWindow::on_actionClose_Headstage_Clamp_triggered()
{
headstageClamp->closeClamp(false);
}
void MainWindow::on_actionInsert_Headstage_Wire_triggered()
{
headstageClamp->threadWire(false);
}
void MainWindow::on_actionFinish_Visual_Stimuli_triggered()
{
if(currentState != NULL)
{
currentState->visual_finished();
}
}
void MainWindow::on_actionReset_Brain_Height_On_New_Pipette_triggered()
{
}
void MainWindow::on_actionReset_Brain_Height_On_New_Pipette_toggled(bool toggled)
{
if(toggled)
{
qWarning() << "Brain height will be readjusted the next time a trial is started";
busy_start("Brain height will be readjusted when a new trial starts.");
if(currentState !=NULL)
{
AutopatcherSettings tmp = currentState->getData();
tmp.brainHeightSet = 0;
currentState->setData(tmp);
}
}
else
{
AutopatcherSettings tmp = currentState->getData();
if(tmp.brainHeightSet == 0)
{
if(currentState !=NULL && tmp.brainHeight != 0)
{
tmp.brainHeightSet = 1;
currentState->setData(tmp);
}
}
}
}
void MainWindow::on_actionFiller_Valve_On_triggered()
{
QMetaObject::invokeMethod(filler,"enablePressureControl",Qt::QueuedConnection,Q_ARG(bool,true),Q_ARG(bool,false));
}
void MainWindow::on_actionFiller_Valve_Off_triggered()
{
QMetaObject::invokeMethod(filler,"enablePressureControl",Qt::QueuedConnection,Q_ARG(bool,false),Q_ARG(bool,false));
}
|
404f6385cd6a496531ca73ee7b78c1e61ae7eedb | 0fa1152e1e434ce9fe9e2db95f43f25675bf7d27 | /src/modules/fw_att_control/ecl_controller.h | 0e58cfec5be103dca9c3d43d63db554e25c60425 | [
"BSD-3-Clause"
] | permissive | PX4/PX4-Autopilot | 4cc90dccc9285ca4db7f595ac5a7547df02ca92e | 3d61ab84c42ff8623bd48ff0ba74f9cf26bb402b | refs/heads/main | 2023-08-30T23:58:35.398450 | 2022-03-26T01:29:03 | 2023-08-30T15:40:01 | 5,298,790 | 3,146 | 3,798 | BSD-3-Clause | 2023-09-14T17:22:04 | 2012-08-04T21:19:36 | C++ | UTF-8 | C++ | false | false | 3,547 | h | ecl_controller.h | /****************************************************************************
*
* Copyright (c) 2020-2022 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file ecl_controller.h
* Definition of base class for other controllers
*
* @author Lorenz Meier <lm@inf.ethz.ch>
* @author Thomas Gubler <thomasgubler@gmail.com>
*
* Acknowledgements:
*
* The control design is based on a design
* by Paul Riseborough and Andrew Tridgell, 2013,
* which in turn is based on initial work of
* Jonathan Challinger, 2012.
*/
#pragma once
#include <drivers/drv_hrt.h>
#include <px4_log.h>
struct ECL_ControlData {
float roll;
float pitch;
float yaw;
float body_z_rate;
float roll_setpoint;
float pitch_setpoint;
float yaw_setpoint;
float euler_pitch_rate_setpoint;
float euler_yaw_rate_setpoint;
float airspeed_constrained;
float groundspeed;
float groundspeed_scaler;
};
class ECL_Controller
{
public:
ECL_Controller();
virtual ~ECL_Controller() = default;
/**
* @brief Calculates both euler and body rate setpoints. Has different implementations for all body axes.
*
* @param dt Time step [s]
* @param ctrl_data Various control inputs (attitude, body rates, attitdue stepoints, euler rate setpoints, current speeed)
* @return Body rate setpoint [rad/s]
*/
virtual float control_attitude(const float dt, const ECL_ControlData &ctl_data) = 0;
/* Setters */
void set_time_constant(float time_constant);
void set_k_p(float k_p);
void set_k_i(float k_i);
void set_k_ff(float k_ff);
void set_integrator_max(float max);
void set_max_rate(float max_rate);
/* Getters */
float get_euler_rate_setpoint();
float get_body_rate_setpoint();
float get_integrator();
void reset_integrator();
protected:
uint64_t _last_run;
float _tc;
float _k_p;
float _k_i;
float _k_ff;
float _integrator_max;
float _max_rate;
float _last_output;
float _integrator;
float _euler_rate_setpoint;
float _body_rate_setpoint;
};
|
5c27508efb08ac50fcce5abe7a3be8a6e01ce35c | 139791527ccaca55f532c3c20929d4c7ef9ac52f | /FractalCreator.cpp | e44365927f2b3b16363fe5f7f4f206225ff0da12 | [] | no_license | thomi137/mandelbrot | b523686c3e9a76b99217012bcd33dac29e24cd6f | 662793ddf9383c21ded6d1a3d81e1f803d201395 | refs/heads/master | 2020-09-13T04:09:11.605959 | 2019-11-19T20:24:21 | 2019-11-19T20:24:21 | 222,650,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,415 | cpp | FractalCreator.cpp | //
// Created by Thomas Prosser on 19.11.19.
//
#include <math.h>
#include "FractalCreator.h"
#include "Mandelbrot.h"
namespace thomit {
FractalCreator::FractalCreator(int width, int height):
m_width(width),
m_height(height),
m_histogram(new int[Mandelbrot::MAX_ITERATIONS]{0}),
m_fractal(new int[m_width * m_height]{0}),
m_bitmap(m_width, m_height),
m_zoomList(m_width, m_height){
addZoom(Zoom(m_width / 2, m_height / 2, 4.0 / m_width));
}
void FractalCreator::calculateIteration() {
for(int y = 0; y < m_height; y++) {
for(int x = 0; x < m_width; x++){
pair<double, double> coords = m_zoomList.doZoom(x, y);
int iterations = Mandelbrot::getIterations(coords.first, coords.second);
m_fractal[y * m_width + x] = iterations;
if (iterations != Mandelbrot::MAX_ITERATIONS) {
m_histogram[iterations]++;
}
}
}
}
void FractalCreator::drawFractal() {
for(int y = 0; y < m_height; y++){
for(int x = 0; x < m_width; x++) {
uint8_t red = 0;
uint8_t green = 0;
uint8_t blue = 0;
int iterations = m_fractal[y * m_width + x];
if (iterations != Mandelbrot::MAX_ITERATIONS){
double hue = 0.0;
for(int i = 0; i<=iterations; i++){
hue += ((double)m_histogram[i]) / m_total;
}
green = pow(255, hue);
}
m_bitmap.setPixel(x, y, red, green, blue);
}
}
}
void FractalCreator::addZoom(const Zoom &zoom) {
m_zoomList.add(zoom);
}
void FractalCreator::writeBitmap(string fileName) {
m_bitmap.write(fileName);
}
FractalCreator::~FractalCreator() {
}
void FractalCreator::calculateTotalIterations() {
int total = 0;
for(int i = 0; i < Mandelbrot::MAX_ITERATIONS; i++){
m_total += m_histogram[i];
}
}
void FractalCreator::run(string fileName) {
addZoom(Zoom(295, m_height - 202, 0.1));
addZoom(Zoom(312, m_height - 304, 0.1));
calculateIteration();
calculateTotalIterations();
drawFractal();
writeBitmap(fileName);
}
}
|
536385150f47c49e4e464906e3e2faad35eacc2a | 35cbf0f7f26ce1d06c429a01c1d006ff201ce02f | /core/qcframe.cpp | 5f99d05f183ef749d9afc742af60e3404b83ef6b | [] | no_license | walterqin/weighbridge | 384da46dd03c3787c30fa253a745674b900adcc7 | 0afe406e7394fcc529dddd82af66158ce5b8a9b1 | refs/heads/master | 2021-01-18T13:59:39.966713 | 2016-01-19T09:48:37 | 2016-01-19T09:48:37 | 42,099,107 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,783 | cpp | qcframe.cpp | /**
* @file qcframe.cpp
* @brief 质控界面实现
* @ingroup core
* @author walterqin(walterqin@hotmail.com)
* @date 2015-11-24
*/
#include <QDebug>
#include "qcwidget.h"
#include "qcframe.h"
#include "workbench.h"
#include "wbaction.h"
#include "profile.h"
#include "wbapp.h"
QcFrame::QcFrame(Workbench *wb, QWidget *parent)
: MainWindowBase(parent)
, m_workbench(wb)
{
actions = workbench()->actionManager();
toolbar = createFixedToolbar();
toolbar->addActions(actions->qcActions->actions());
toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly);
toolbar->setToolButtonStyle(actions->qcSelectGroupAction, Qt::ToolButtonTextBesideIcon);
toolbar->setToolButtonStyle(actions->qcChangeScaleAction, Qt::ToolButtonTextBesideIcon);
toolbar->setToolButtonStyle(actions->qcDisplayNewAction, Qt::ToolButtonTextBesideIcon);
toolbar->setToolButtonAutoRepeat(actions->qcPrevDataAction);
toolbar->setToolButtonAutoRepeat(actions->qcNextDataAction);
toolbar->setToolButtonAutoRepeat(actions->qcPrevPageAction);
toolbar->setToolButtonAutoRepeat(actions->qcNextPageAction);
connect(actions->qcPrevDataAction, SIGNAL(triggered()), this, SLOT(prevData()));
connect(actions->qcNextDataAction, SIGNAL(triggered()), this, SLOT(nextData()));
connect(actions->qcPrevPageAction, SIGNAL(triggered()), this, SLOT(prevPage()));
connect(actions->qcNextPageAction, SIGNAL(triggered()), this, SLOT(nextPage()));
connect(actions->qcPrintAction, SIGNAL(triggered()), this, SLOT(print()));
}
QcFrame::~QcFrame()
{
}
void QcFrame::selectFile()
{
}
void QcFrame::print()
{
}
void QcFrame::prevPage()
{
}
void QcFrame::nextPage()
{
}
void QcFrame::prevData()
{
}
void QcFrame::nextData()
{
}
|
168eb0b4ada3c67159c35ed41f8fa6a066f78c90 | 913fa3978fff3fcc51f63e6dfe02fae46afab614 | /gapid_tests/traits_query_tests/vkEnumeratePhysicalDevices/main.cpp | fad75967874b9490799bdfc1ecf7fdd3f1226556 | [
"Apache-2.0"
] | permissive | bjoeris/vulkan_test_applications | b48c0cd3a40a49879ccb2f3984cb0e915fb641db | ec83d20e524cb95c295e483b8f8078db8c79955a | refs/heads/master | 2022-04-29T10:58:44.742560 | 2020-08-18T13:42:47 | 2022-03-28T19:14:40 | 143,206,321 | 1 | 0 | Apache-2.0 | 2022-03-31T20:03:55 | 2018-08-01T20:38:07 | C++ | UTF-8 | C++ | false | false | 2,370 | cpp | main.cpp | /* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "support/containers/vector.h"
#include "support/entry/entry.h"
#include "support/log/log.h"
#include "vulkan_helpers/helper_functions.h"
#include "vulkan_wrapper/instance_wrapper.h"
#include "vulkan_wrapper/library_wrapper.h"
int main_entry(const entry::EntryData* data) {
data->logger()->LogInfo("Application Startup");
vulkan::LibraryWrapper wrapper(data->allocator(), data->logger());
vulkan::VkInstance instance(
vulkan::CreateEmptyInstance(data->allocator(), &wrapper));
uint32_t device_count = 0;
LOG_EXPECT(
==, data->logger(),
instance->vkEnumeratePhysicalDevices(instance, &device_count, nullptr),
VK_SUCCESS);
LOG_ASSERT(>, data->logger(), device_count, 0u);
data->logger()->LogInfo("Device Count is ", device_count);
containers::vector<VkPhysicalDevice> physical_devices(data->allocator());
physical_devices.resize(device_count);
LOG_ASSERT(==, data->logger(),
instance->vkEnumeratePhysicalDevices(instance, &device_count,
physical_devices.data()),
VK_SUCCESS);
for (size_t i = 0; i < device_count; ++i) {
LOG_ASSERT(!=, data->logger(), physical_devices[i], VkPhysicalDevice(nullptr));
}
device_count -= 1;
LOG_EXPECT(==, data->logger(),
instance->vkEnumeratePhysicalDevices(instance, &device_count,
physical_devices.data()),
VK_INCOMPLETE);
device_count = 0;
LOG_EXPECT(==, data->logger(),
instance->vkEnumeratePhysicalDevices(instance, &device_count,
physical_devices.data()),
VK_INCOMPLETE);
data->logger()->LogInfo("Application Shutdown");
return 0;
}
|
fa38914f4af6951303bb7ccb972a5a96ee18250d | a9448c49f6a3e1e1a56610b0725b7e5b89bf06fa | /cses/dynamic-programming/coinCombinations2.cpp | 83045abcc928e9eb8ce226ad6f8dd0a9638974bb | [] | no_license | manvendra-rajpoot/competitive-programming | aa50ccb340aea9dfa551e70209eec2ed8b117972 | 7f6431d167f716c34a192b6ab30465242e269095 | refs/heads/main | 2023-06-12T01:24:47.260691 | 2021-06-24T03:34:19 | 2021-06-24T03:34:19 | 318,832,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,445 | cpp | coinCombinations2.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
#define fr first
#define sc second
#define pb push_back
#define mp make_pair
#define sz(c) c.size()
#define all(v) (v).begin(), (v).end()
#define rep(i, a, n) for (int i = a; i < n; ++i)
#define IOS \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
/*
- dp(i,j) = no.of valid ways of making sum==j using first ith coins.
- Ans = dp(n,x).
- dp(i,j) = dp(i-1,j) + dp(i,j-c[i]); we exclude that coin with no effect on sum, we include that coin with reduced sum
- dp(i,0) = 1
- T(n) = O(n.X); X= (v1+v2+v3+...+vn)/n
- S(n) = O(n)
*/
int find(int i, int x, const vector<int>& c, int** dp) {
if(dp[i][x]>-1) return dp[i][x];
int option1 = (i<=1)? 0 : ( (dp[i-1][x]>-1) ? dp[i-1][x] : find(i-1,x,c,dp) ); //excluding that coin
int option2 = (c[i]>x)? 0 : ( (dp[i][x-c[i]]>-1) ? dp[i][x-c[i]] : find(i,x-c[i],c,dp) ); //including that coin
if(option1>0) dp[i-1][x] = option1;
if(option2>0) dp[i][x-c[i]] = option2;
int ans = (option1 + option2)%MOD;
dp[i][x] = ans;
return ans;
}
//top to bottom approach
void method1(int n, int x, vector<int> c) {
int** dp = new int*[n+1];
rep(i,0,n+1) {
dp[i] = new int[x+1];
rep(j,0,x+1) {
dp[i][j] = -1;
}
}
//if sum==0, there is 1 way by selecting no coin
rep(i,1,n+1){
dp[i][0] = 1;
}
// no coins left
rep(i,0,x+1){
dp[0][i] = 0;
}
cout<<find(n,x,c,dp)<<'\n';
rep(i,0,n) delete [] dp[i];
delete [] dp;
}
//bottom to top approach
void method2(int n, int x, vector<int> c) {
int dp[n+1][x+1];
rep(i,1,n+1){
for(int sum=0;sum<=x;++sum){
if(sum==0) dp[i][sum]=1;
else {
int option1 = (i==1) ? 0 : dp[i-1][sum]; //excluding that coin & if one one coin is left we have to take it
int option2 = (c[i]>sum) ? 0 : dp[i][sum-c[i]]; //including that coin & checking if sum<=c[i]
dp[i][sum] = (option1 + option2)%MOD;
}
}
}
cout<<dp[n][x]<<'\n';
}
int main() {
IOS;
int T = 1;
//cin >> T;
rep(i, 1, T + 1) {
int n,x;
cin>>n>>x;
vector<int> c(n+1);
rep(i,1,n+1) cin>>c[i];
//method1(n,x,c);
method2(n,x,c);
}
return 0;
}
|
3f155b9cd8db3e7625ef3979ec725412d9169be9 | c4effa0484709ef3c77478e7f7318f4bef5d6f8f | /modules/bookmarks/operaspeeddial.h | 3c66924e3ab67b0e3045627f3e901333885cbad9 | [] | no_license | SlipperyPete/opera-presto | 199915a603e7844cbe27fcd20215e19545baf91c | 1e23e4f167942aa27eb417374236455a6f163b59 | refs/heads/master | 2020-07-14T17:09:27.639098 | 2018-08-05T16:05:20 | 2018-08-05T16:05:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,922 | h | operaspeeddial.h | /* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 2008 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef BOOKMARKS_OPERASPEEDDIAL_H
#define BOOKMARKS_OPERASPEEDDIAL_H
#ifdef OPERASPEEDDIAL_URL
#include "modules/about/opgenerateddocument.h"
#include "modules/bookmarks/speeddial_listener.h"
#include "modules/url/url_lop_api.h"
/** URL hook */
class OperaSpeedDialURLGenerator
: public OperaURL_Generator
{
public:
virtual OperaURL_Generator::GeneratorMode GetMode() const { return OperaURL_Generator::KQuickGenerate; }
virtual OP_STATUS QuickGenerate(URL &url, OpWindowCommander*);
};
/** opera:speeddial generator */
class OperaSpeedDial
: public OpGeneratedDocument
{
public:
OperaSpeedDial(URL url);
virtual ~OperaSpeedDial();
virtual OP_STATUS GenerateData();
};
class ES_AsyncInterface;
class ES_Object;
/**
* Keeps track of the callback to one opera:speeddial page.
*/
class OperaSpeedDialCallback
: public OpSpeedDialListener
{
public:
OperaSpeedDialCallback(ES_AsyncInterface *ai, ES_Object *callback)
: m_ai(ai), m_callback(callback)
{ }
/** Destructor the also removes the object from the callback list */
~OperaSpeedDialCallback();
/** Call during GCTrace. Will prevent the callback from being GC'ed. */
void GCTrace(ES_Runtime *runtime);
// From OpSpeedDialListener
OP_STATUS OnSpeedDialChanged(SpeedDial* speed_dial);
OP_STATUS OnSpeedDialRemoved(SpeedDial* speed_dial);
private:
OP_STATUS Call(int index, const uni_char* title, const uni_char* url, const uni_char* thumbnail_url, BOOL is_loading);
ES_AsyncInterface *m_ai;
ES_Object *m_callback;
};
#endif // OPERASPEEDDIAL_URL
#endif // BOOKMARKS_OPERASPEEDDIAL_H
|
b00a78783880a553d36ca2218bc63ea2c1115ebd | b6607ecc11e389cc56ee4966293de9e2e0aca491 | /NSUTS/2013/Onsite tour/1-st nomination/work/Documentation/production.cpp | 929455696e9bf14b1eadfbf3e08aabf7d3cd9976 | [] | no_license | BekzhanKassenov/olymp | ec31cefee36d2afe40eeead5c2c516f9bf92e66d | e3013095a4f88fb614abb8ac9ba532c5e955a32e | refs/heads/master | 2022-09-21T10:07:10.232514 | 2021-11-01T16:40:24 | 2021-11-01T16:40:24 | 39,900,971 | 5 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 4,405 | cpp | production.cpp | #include "Solution.h"
#include <sstream>
#include <fstream>
#include <vector>
#include <cmath>
#include <cstring>
#include <time.h>
using namespace std;
char buff[1024];
int otherFactoryNum = 0;
int factories[7] = {};
std::map<int, int> Strategy() {
std::map<int, int> answer;
int k = 0;
for (int i = 0; i < MAX_FACTORY_COUNT; i++) {
const Factory &f = pWorld->factories[i];
if (f.id < 0) continue; //пропускаем "мёртвые" заводы
if (f.owner != playerIndex) continue; //пропускаем чужие заводы
answer[f.id] = 0; //говорим, что на нашем заводе надо строить!
}
return answer;
}
void goToRandomFactory(char buff[]) {
int num = 0;
num = rand() % 7;
const Factory &f = pWorld->factories[num];
double delta = rand() % 50;
delta -= 25;
sprintf(buff, "gofact = {x = %lf, y = %lf}", f.position.x + delta, f.position.y + delta);
}
double get_dist(double x, double y) {
return sqrt(x * x + y * y);
}
void goToClosestFactory(char buff[], int robotIndex) {
if (otherFactoryNum == 0) {
goToRandomFactory(buff);
}
else {
//int num = rand() % otherFactoryNum;
double dist = 10000;
int bi = 0;
double cx = 0, cy = 0;
const Robot &r = pWorld -> robots[robotIndex];
cx = r.position.x;
cy = r.position.y;
for (int i = 0; i < otherFactoryNum; i++) {
double ox = 0, oy = 0;
const Factory &of = pWorld->factories[factories[i]];
ox = of.position.x;
oy = of.position.y;
if (get_dist(cx - ox, cy - oy) < dist) {
dist = get_dist(cx - ox, cy - oy);
bi = i;
}
}
double delta = rand() % 70;
delta -= 35;
const Factory &f = pWorld->factories[factories[bi]];
//пишем инициализирующий скрипт: бежать в центр этого завода
sprintf(buff, "gofact = {x = %lf, y = %lf}", f.position.x + delta, f.position.y + delta);
}
}
void goToNotOwnFactory(char buff[]) {
if (otherFactoryNum == 0) {
goToRandomFactory(buff);
}
else {
int num = rand() % otherFactoryNum;
const Factory &f = pWorld->factories[factories[num]];
double delta = rand() % 70;
delta -= 35;
sprintf(buff, "gofact = {x = %lf, y = %lf}", f.position.x + delta, f.position.y + delta);
}
}
void goToFactory(char buff[], int x) {
const Factory &f = pWorld->factories[factories[x]];
double delta = rand() % 70;
delta -= 35;
sprintf(buff, "gofact = {x = %lf, y = %lf}", f.position.x + delta, f.position.y + delta);
}
void captureFactory(int robotIndex) {
if (rand() % 10 < 5)
goToClosestFactory(buff, robotIndex);
else
goToNotOwnFactory(buff);
}
void beKiller() {
sprintf(buff, "isKiller = true\n");
}
void bePatrol(int robotIndex) {
double rat = 0.1 * (robotIndex % 5);
//пишем в строку инициализирующий скрипт на LUA (задаём путь для патруля)
sprintf(buff, "path = {}\n \
path[0] = {x = %lf, y = %lf}\n \
path[1] = {x = %lf, y = %lf}\n \
path[2] = {x = %lf, y = %lf}\n \
path[3] = {x = %lf, y = %lf}\n",
FIELD_SIZE*rat, FIELD_SIZE*rat,
FIELD_SIZE*(1-rat), FIELD_SIZE*rat,
FIELD_SIZE*(1-rat), FIELD_SIZE*(1-rat),
FIELD_SIZE*rat, FIELD_SIZE*(1-rat));
}
std::pair<std::string, std::string> Program(int robotIndex) {
srand(time(NULL));
otherFactoryNum = 0;
for (int i = 0; i < MAX_FACTORY_COUNT; i++) {
const Factory &f = pWorld->factories[i];
if (f.id < 0) continue; //пропускаем "мёртвые" заводы
if (f.owner == playerIndex) continue; //пропускаем свои заводы
factories[otherFactoryNum] = i;
otherFactoryNum++;
}
int firstLimit = 60;
if (robotIndex < 60) {
int go = robotIndex % 7;
double cx = 0, cy = 0;
const Robot &r = pWorld -> robots[robotIndex];
cx = r.position.x;
cy = r.position.y;
double ox = 0, oy = 0;
const Factory &of = pWorld->factories[factories[go]];
ox = of.position.x;
oy = of.position.y;
if (get_dist(cx - ox, cy - oy) < 50) {
go = (go + 1) % 7;
}
goToFactory(buff, go);
}
else
if (otherFactoryNum == 0) {
if (rand() & 1)
bePatrol(robotIndex);
else
beKiller();
}
else {
captureFactory(robotIndex);
}
return make_pair("", std::string(buff));
}
|
14cccf03b5ccf03a295b4e7f6c89613540c82bf1 | 9fc4193859fa66b828db6ce1f051a1ab81c6d02d | /Classes/MenuBackground.cpp | a4038ffb7429689eed488f8bb0af8871d2abdd22 | [] | no_license | hitlolo/AngryCoder | 0ab1b2249bd810f1ffc2bc3bf8f98c4ab669f4d3 | a071b79c0f55ad8d358dc58f177f1053a9c4fbc3 | refs/heads/master | 2020-06-03T18:05:49.618322 | 2015-04-23T16:51:34 | 2015-04-23T16:51:34 | 34,254,143 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,025 | cpp | MenuBackground.cpp | #include "MenuBackground.h"
bool MenuBackground::init()
{
if (!Layer::init())
{
return false;
}
this->initBackGroundFromTMX();
return true;
}
void MenuBackground::initBackGroundFromTMX()
{
m_tmxMap = TMXTiledMap::create("menu.tmx");
auto floors = m_tmxMap->getObjectGroup("Floors");
auto items = m_tmxMap->getObjectGroup("Items");
this->initFloor(floors);
this->initItems(items);
this->addChild(m_tmxMap);
Node *rootNode = CSLoader::createNode("Node.csb");//传入Studio2.x的资源路径
//m_tmxMap->addChild(rootNode,2);//假设this是即将显示的scene
auto sp = Sprite::create();
sp->addChild(rootNode);
//加载动画:
ActionTimeline *action = CSLoader::createTimeline("Node.csb");
rootNode->runAction(action);
//sp->runAction(action);
action->gotoFrameAndPlay(0, 20, true);
m_tmxMap->addChild(sp, 2);
}
void MenuBackground::initFloor(TMXObjectGroup* floors)
{
ValueVector objectsVector = floors->getObjects();
for (auto def : objectsVector)
{
auto floorDef = def.asValueMap();
std::string filename = floorDef["png"].asString();
float positionX = floorDef["x"].asFloat();
float positionY = floorDef["y"].asFloat();
int z = floorDef["zOrder"].asInt();
Sprite* floor = Sprite::createWithSpriteFrameName(filename.c_str());
floor->setPosition(positionX, positionY);
floor->setZOrder(z);
floor->setAnchorPoint(Vec2(0, 0));
m_tmxMap->addChild(floor);
}
}
void MenuBackground::initItems(TMXObjectGroup* items)
{
ValueVector objectsVector = items->getObjects();
for (auto def : objectsVector)
{
auto itemDef = def.asValueMap();
std::string filename = itemDef["png"].asString();
float positionX = itemDef["x"].asFloat();
float positionY = itemDef["y"].asFloat();
int z = itemDef["zOrder"].asInt();
Sprite* item = Sprite::createWithSpriteFrameName(filename.c_str());
item->setPosition(positionX, positionY);
item->setZOrder(z);
item->setAnchorPoint(Vec2(0, 0));
m_tmxMap->addChild(item);
}
} |
3f909540c33cef09b5103f6f0a8c65357e5c7428 | b812db5d69f1ddc38596149460a0cbdf5248e0a7 | /AtCoder/abc145/D.cpp | 0dbc61551bfaf6575f32b2f05ac88047587cb5f6 | [] | no_license | mnaveenkumar2009/Competitive-Programming | f15536906f8a6015654baf73fec3b94f334c998a | 9bd02ae15d132468e97bc86a95e924910fe5692a | refs/heads/master | 2021-06-06T12:22:59.879873 | 2020-07-12T11:41:44 | 2020-07-12T11:41:44 | 99,432,530 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 875 | cpp | D.cpp | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
#define mod 1000000007
ll pr(ll x, ll y)
{
ll res = 1;
x = x % mod;
while (y > 0){
if (y & 1)
res = (res*x) % mod;
y >>= 1;
x = (x*x) % mod;
}
return res;
}
signed main(){
vector <int> fact(3000006), invfact(3000006);
fact[0] = 1;
invfact[0] = 1;
for(int i = 0; i < 3000003; i++){
fact[i+1] = (fact[i] * (i+1))%mod;
invfact[i+1] = pr(fact[i+1], mod - 2);
}
int x, y;
cin >> x >> y;
if(x > y)
swap(x, y);
int Y = y - x;
int X = (x - Y)/3;
if((x - Y)%3 || X < 0 || Y < 0){
cout << "0\n";
return 0;
}
// cout << X <<' ' << Y << '\n';
int no_of_steps = 2 * X + Y;
int ans = 1;
ans *= fact[2*X + Y];
ans %= mod;
ans *= invfact[X + Y];
ans %= mod;
ans *= invfact[X];
ans %= mod;
cout << ans << '\n';
} |
6bb5f13ed00a655dc3d64cc84f50d7034087cbf7 | ee42363ad592ec44af3c5e650a8b377ac60e11a2 | /cores/dos/src/hardware/serialport/serialdummy.cpp | ccbdc3f3adc553d832c1340bd9900599ff6cd943 | [
"MIT",
"LGPL-2.1-only",
"MPL-1.1",
"LicenseRef-scancode-mame",
"GPL-1.0-or-later",
"Zlib",
"GPL-2.0-only",
"LGPL-2.1-or-later",
"MPL-2.0",
"CC-PDDC",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-brian-gladman-3-clause",
"BSD-3-Clause"... | permissive | dchichkov/retro | be6952bce70bd837eadadc87233cb068617ae837 | 4b628e9873d00228984e1060a366b221f5ed575b | refs/heads/master | 2020-07-02T14:08:37.532302 | 2019-08-23T06:09:29 | 2019-10-16T05:59:44 | 201,550,968 | 0 | 0 | MIT | 2019-08-09T22:56:47 | 2019-08-09T22:56:46 | null | UTF-8 | C++ | false | false | 3,070 | cpp | serialdummy.cpp | /*
* Copyright (C) 2002-2013 The DOSBox Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "dosbox.h"
#include "setup.h"
#include "serialdummy.h"
#include "serialport.h"
CSerialDummy::CSerialDummy(Bitu id, CommandLine* cmd):CSerial(id, cmd) {
CSerial::Init_Registers();
setRI(false);
setDSR(false);
setCD(false);
setCTS(false);
InstallationSuccessful=true;
}
CSerialDummy::~CSerialDummy() {
// clear events
removeEvent(SERIAL_TX_EVENT);
}
void CSerialDummy::handleUpperEvent(Bit16u type) {
if(type==SERIAL_TX_EVENT) {
//LOG_MSG("SERIAL_TX_EVENT");
#ifdef CHECKIT_TESTPLUG
receiveByte(loopbackdata);
#endif
ByteTransmitted(); // tx timeout
}
else if(type==SERIAL_THR_EVENT){
//LOG_MSG("SERIAL_THR_EVENT");
ByteTransmitting();
setEvent(SERIAL_TX_EVENT,bytetime);
}
}
/*****************************************************************************/
/* updatePortConfig is called when emulated app changes the serial port **/
/* parameters baudrate, stopbits, number of databits, parity. **/
/*****************************************************************************/
void CSerialDummy::updatePortConfig(Bit16u divider, Bit8u lcr) {
//LOG_MSG("Serial port at 0x%x: Port params changed: %d Baud", base,dcb.BaudRate);
}
void CSerialDummy::updateMSR() {
}
void CSerialDummy::transmitByte(Bit8u val, bool first) {
if(first) setEvent(SERIAL_THR_EVENT, bytetime/10);
else setEvent(SERIAL_TX_EVENT, bytetime);
#ifdef CHECKIT_TESTPLUG
loopbackdata=val;
#endif
}
/*****************************************************************************/
/* setBreak(val) switches break on or off **/
/*****************************************************************************/
void CSerialDummy::setBreak(bool value) {
//LOG_MSG("UART 0x%x: Break toggeled: %d", base, value);
}
/*****************************************************************************/
/* setRTSDTR sets the modem control lines **/
/*****************************************************************************/
void CSerialDummy::setRTSDTR(bool rts, bool dtr) {
setRTS(rts);
setDTR(dtr);
}
void CSerialDummy::setRTS(bool val) {
#ifdef CHECKIT_TESTPLUG
setCTS(val);
#endif
}
void CSerialDummy::setDTR(bool val) {
#ifdef CHECKIT_TESTPLUG
setDSR(val);
setRI(val);
setCD(val);
#endif
}
|
831b7c1104973188507f30ea94fda63147383e74 | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/PhysicsAnalysis/SUSYPhys/LongLivedParticleDPDMaker/src/components/LongLivedParticleDPDMaker_load.cxx | f8829249b4dac1e5d24105931151565c6d115543 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 92 | cxx | LongLivedParticleDPDMaker_load.cxx | #include "GaudiKernel/LoadFactoryEntries.h"
LOAD_FACTORY_ENTRIES(LongLivedParticleDPDMaker)
|
2dff7e006c1e4273e808c0e8c2362fac80f3aee9 | bad056ec24d2660dc3bcd0eadfc7d987cba4ca93 | /Client_Example/DeepHandClient_Example/Client_Example.cpp | 2a2188bdcf9710f6ccc4569d6c788046669a80bb | [] | no_license | webstorage119/DeepHandPoseRecognizer | 100dd3610e680e3fa0b1e36d7d23c8d19eee3feb | f2e4e5db796b2597776af29e5fcd3efd9d89b911 | refs/heads/master | 2021-07-22T23:30:04.954310 | 2017-11-01T10:05:40 | 2017-11-01T10:05:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | Client_Example.cpp | #include <stdio.h>
#include "DeepHandClient.h"
int main(){
DeepHandClient client;
client.Init(NULL, DEFAULT_PORT);
cv::Mat img = cv::imread("1_f_177.jpg");
int gestIdx = client.SendAndRecognition(img);
printf("idx : %d\n", gestIdx);
img = cv::imread("1_f_211.jpg");
gestIdx = client.SendAndRecognition(img);
printf("idx : %d\n", gestIdx);
client.DeInit();
return 0;
} |
04953623643a8d0a37db934395b003dc2a225e60 | 579db4e83746d4c8c2f64fe3e1e37acc60acb37b | /server/GameStats.cpp | 47dcb81e47c35e7ed7b7439234d7e209de52c649 | [] | no_license | seanzaretzky23/AdvancedProgServer | 49c38a6953c2e26e1415b218e93bfa8d4beb5423 | 7d6863d142670adb74894e06b7a5007b863cad55 | refs/heads/master | 2021-09-02T20:10:25.240761 | 2018-01-03T21:08:06 | 2018-01-03T21:08:06 | 115,423,593 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,408 | cpp | GameStats.cpp | /****************************************************************
* Student name: sean zaretzky(209164086), yaniv zimmer (318849908)
* Course Exercise Group: 03, 05
*****************************************************************/
#include "GameStats.h"
using namespace std;
GameStats::GameStats(string gameName, int firstClientSocket): gameName(gameName), firstClientSocket(firstClientSocket),
secondClientSocket(-1){
}
GameStats::GameStats(std::string gameName): gameName(gameName), firstClientSocket(-1), secondClientSocket(-1) {}
GameStats::GameStats(const GameStats &gameStatsToCopy) {
this->gameName = gameStatsToCopy.gameName;
this->firstClientSocket = gameStatsToCopy.firstClientSocket;
this->secondClientSocket = gameStatsToCopy.secondClientSocket;
}
GameStats::GameStats(): gameName(""), firstClientSocket(-1), secondClientSocket(-1) {}
string GameStats::getGameName() const {
return string(this->gameName);
}
int GameStats::getFirstClientSocket() const {
return this->firstClientSocket;
}
int GameStats::getSecondClientSocket() const {
return this->secondClientSocket;
}
void GameStats::setSecondClientSocket(int secondClientSocket) {
this->secondClientSocket = secondClientSocket;
}
bool GameStats::operator==(GameStats gameStats) const {
return this->gameName == gameStats.getGameName();
}
|
e0d4a7ebc04e27ccae75ba7d189aa8e34ea0b427 | 6678444259b32ffebc96020699ac91c31c14daf2 | /LAB_6/header/StackArr.h | fce7835dadc6d6ee2bb8e88da7069d9a7a0e350a | [] | no_license | AlexandrovaAnastasia/OOPSZI_lab | a9736a133a9c3aa78e44b2093a03bfd8904612c9 | 6980818fadbfc39ad4f701084f957170de920c5c | refs/heads/master | 2020-05-21T12:12:43.984907 | 2019-05-22T18:38:32 | 2019-05-22T18:38:32 | 186,048,988 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,718 | h | StackArr.h | #pragma once
#include <iostream>
#include "AbstractStack.h"
using namespace std;
template<typename T>
class StackArr: public AbstractStack<T>
{
T *arr;
int count;
int end = 0, start = 0, size = 0;
public:
StackArr(int count)
: count(count)
{
this->count = count;
arr = new T[count];
}
StackArr(const StackArr &other)
{
arr = new T[other.count];
count = other.count;
end = other.end;
start = other.start;
size = other.size;
for (int i = 0; i < count; ++i)
{
arr[i] = other.arr[i];
}
}
StackArr(StackArr &&other)
{
arr = other.arr;
count = other.count;
other.arr = nullptr;
}
~StackArr()
{
delete[] arr;
}
StackArr&operator=(const StackArr &other)
{
if (this == &other)
{
return *this;
}
delete[] arr;
arr = new T[other.count];
count = other.count;
for (int i = 0; i < count; ++i)
{
arr[i] = other.arr[i];
}
}
StackArr&operator=(StackArr &&other)
{
if (this == &other)
{
return *this;
}
delete[] arr;
arr = other.arr;
count = other.count;
other.arr = nullptr;
}
int GetSize()
{
return this->size;
}
void Push(T element)
{
if (size <= count)
{
arr[end] = element;
end = (end + 1);
size++;
}
}
T Pop()
{
if (size > 0)
{
T element = arr[start];
start = (start + 1) % count;
size--;
return element;
}
return 0;
}
T Peek()
{
return arr[start];
}
bool CheckNoEmptyStack()
{
return (size > 0);
}
friend ostream& operator<<(ostream& stream, StackArr& a)
{
for (int i = 0; i <= a.count; ++i)
cout << a.arr[i] << " ";
return stream;
}
}; |
c24f01b8deef7035440c8065f4060f16a3df8006 | 7ca05f627496b97e6a40b9e7b7c065c35fc04784 | /SOURCE/LDPC_dec_engine.h | aaa2a0f06558906724e195ef4075eaf653a9d736 | [] | no_license | eovs/WiFi | a630f5fea17c3b790b5f6e11f827958cc664cf45 | 2c6dbbf7c743da082d6fd75892af15a490a97d0c | refs/heads/master | 2020-03-25T00:28:31.626368 | 2019-04-26T12:34:37 | 2019-04-26T12:34:37 | 143,187,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 844 | h | LDPC_dec_engine.h | #ifndef LDPC_DEC_ENGINE_H
#define LDPC_DEC_ENGINE_H
#include <vector>
#include <memory>
struct box_plus_cfg_t;
class ldpc_dec_engine_t {
public:
enum class ret_status { ERROR = 0, OK = 1, ET = 2 };
ldpc_dec_engine_t();
void init(const std::vector<std::vector<int>> &check_matrix, int z);
void reset();
void push(const std::vector<int> &in);
ret_status iterate();
const std::vector<bool> &pull();
bool calc_parity_check();
ldpc_dec_engine_t(ldpc_dec_engine_t &&);
ldpc_dec_engine_t &operator=(ldpc_dec_engine_t &&);
~ldpc_dec_engine_t();
std::shared_ptr<box_plus_cfg_t> cfg;
private:
bool is_init = false;
class impl;
std::unique_ptr<impl> p_impl_;
};
#endif /*LDPC_DEC_ENGINE_H*/
|
7dcfb610a0f8e6cfa0ac6557c97d458e52a3f59b | 2465fdef459e5654b57d0cbaec14e9bfdf45b57d | /兩顆星/UVA113.cpp | 76639baf63396c6aedae8aa86eeb26a5f35120ee | [] | no_license | a84959947mp45/UVA-ProgramSolvingSet | 3479c25d5d938da3583250806f8a7848458f18dd | 4efecfa3f165f875f86f1e3aa1a44aec1b923e96 | refs/heads/master | 2020-04-29T21:31:58.643725 | 2019-03-21T15:52:47 | 2019-03-21T15:52:47 | 176,415,954 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 223 | cpp | UVA113.cpp | #include <iostream>
#include <cmath>
using namespace std;
int main(){
double a,b;
while(cin>>a>>b){
double k;
double re;
re = log(b)/log(2) / a ;
k = pow(2,re);
cout<<k<<endl;
}
}
|
a506866da4c354cef508027670025f9de17d4fc9 | f92d10305f44b5db68653e65345cf78d3953fff2 | /Game_Captain_America/BulletBegin.h | a3752e63bdcff500f3c1d2bc0f3919c5c623c9ca | [] | no_license | conghauto/Game-DPSG | e7179298567e822208cdb9a716c8af526025c12d | 3f3e8be73f380264d10d77105aff32ead2a4b230 | refs/heads/master | 2023-02-05T01:48:08.628462 | 2019-10-28T05:38:33 | 2019-10-28T05:38:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 427 | h | BulletBegin.h | #pragma once
#include "GameObject.h"
class BulletBegin : public CGameObject
{
public:
BulletBegin()
{
this->time_start_shoot = GetTickCount();
}
int countCol;
float time_start_shoot;
float time_end_start;
virtual void SetState(int state);
virtual void GetBoundingBox(float &left, float &top, float &right, float &bottom);
virtual void Update(DWORD dt, vector<LPGAMEOBJECT> *coObjects);
virtual void Render();
}; |
006eb1861e94ee19bc8d806f4ad8b8dd61d8b926 | 8ccd4dab524c12df2ae3492df80097209a064d0f | /LeptTest/LeptTest/ccutil/mfcpch.cpp | 38b714bc1b14b5e8e111a49e3357d98e547692f9 | [] | no_license | Dlng/Van-s-pet | e6abcbbb877e6c4df7ac38e48bfdd1d668d3c940 | 7b43cf2d581619955ad63375dc50ed4619208b61 | refs/heads/master | 2020-12-07T02:22:15.129156 | 2016-01-10T14:44:14 | 2016-01-10T14:44:14 | 48,267,027 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | mfcpch.cpp | // mfcpch.cpp : source file that includes just the standard includes
// elist.pch will be the pre-compiled header
// mfcpch.obj will contain the pre-compiled type information
#include "mfcpch.h" //precompiled headers
#include "stdafx.h" //precompiled headers
|
dc446194da9f5595379b7064fbd1c5eb11a107c2 | db6e9064356d49c694f666f30b3b8d78c11387e8 | /ebc2urikai/main.cpp | 1864ac393b5b4864eeee449b29378d9e8b37a932 | [] | no_license | aki323buri2/atd | 617f5bc9aa43d55c25751c422132a7bb69be8aad | eb642b6adf7eb056959e3942175fd0a51c26661b | refs/heads/master | 2016-09-10T04:39:47.527891 | 2015-04-10T05:05:24 | 2015-04-10T05:05:24 | 30,438,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,582 | cpp | main.cpp | //main.cpp
#include "common.h"
int main(int argc, char **argv)
{
int r = 0;
try
{
r = frame(argc, argv);
}
catch (std::exception &e)
{
notifyf("!!!! %s error (%s) : %s"
, app.basename.c_str()
, app::now().c_str()
, e.what()
);
notify("");
}
return r;
}
int frame(int argc, char **argv)
{
notifyf(">>>> %s start (%s) >>>>", app.filename.c_str(), app::now().c_str());
int r = run(argc, argv);
notifyf(">>>> %s e n d (%s) >>>>", app.filename.c_str(), app::now().c_str());
notify ("");
return r;
}
int run(int argc, char **argv)
{
properties args;
struct { string &path; } ebc =
{
args.value_of("ebc.path"),
};
struct { string &path1, &path2, &path3; } fdg =
{
args.value_of("fdg.path1"),
args.value_of("fdg.path2"),
args.value_of("fdg.path3"),
};
ebc.path = "D:\\data2\\saikensaimu\\債権債務サンプルデータ\\債権債務サンプルデータ(2015.02.09)\\TDBK1D1.D0209";//売掛(関西)
ebc.path = "D:\\data2\\saikensaimu\\債権債務サンプルデータ\\債権債務サンプルデータ(2015.02.09)\\TDBK2D1.D0209";//買掛(関西)
fdg.path1 = "D:\\data2\\saikensaimu\\債権債務サンプルデータ\\データ退避COPYメンバ\\TUF010.TXT";//売掛HEAD
fdg.path2 = "D:\\data2\\saikensaimu\\債権債務サンプルデータ\\データ退避COPYメンバ\\TUF020.TXT";//売掛BODY
fdg.path3 = "D:\\data2\\saikensaimu\\債権債務サンプルデータ\\データ退避COPYメンバ\\TUF090.TXT";//売掛NYU
fdg.path1 = "D:\\data2\\saikensaimu\\債権債務サンプルデータ\\データ退避COPYメンバ\\TCF040.TXT";//買掛BODY※
fdg.path2 = "D:\\data2\\saikensaimu\\債権債務サンプルデータ\\データ退避COPYメンバ\\TCF010.TXT";//買掛BODY
fdg.path3 = "D:\\data2\\saikensaimu\\債権債務サンプルデータ\\データ退避COPYメンバ\\TCF040.TXT";//買掛KES
//コマンドライン引数でオーバーライド
args.commandline(argc, argv);
bool check = true;
//絶対パスと存在チェック
{
string *ss[] =
{
&ebc.path,
&fdg.path1,
&fdg.path2,
&fdg.path3,
0,
};
check = abspath_and_existscheck(ss);
}
args.demo(notify);
if (!check) throw generic::exception("args file exists check error !!");
//invokers
invokers invokers;
invokers.entry(new invoker(fdg.path1));
invokers.entry(new invoker(fdg.path2));
invokers.entry(new invoker(fdg.path3));
if (!invokers.size())
{
throw generic::exception("invokers is empty!!");
}
if (!invokers[0]->navigater.size())
{
throw generic::exception("invokers has empty navigater!!");
}
if (!invokers.even())
{
throw generic::exception("record size is uneven!!");
}
//レコード長
int rsize = invokers[0]->navigater.rsize;
//変換元ファイルを分割
string fname = path::basename(ebc.path.sjis()).utf8();
int64 fsize = path::filesize(ebc.path.sjis());
int64 lines = fsize / (int64)rsize;
notify ("**********************************");
notify ("* EBCDIC file >> *");
notifyf("* file name : %-16s *", fname.c_str());
notify ("*---------------------------------");
notifyf("* record size : %10lld bytes *", rsize);
notifyf("* file size : %10lld bytes *", fsize);
notifyf("* lines count: %10lld lines *", lines);
notify ("**********************************");
//読み取りファイルオープン
std::ifstream ifs(ebc.path.sjis().c_str()
, std::ios::binary
| std::ios::in
);
//出力フォルダ作成
struct { string d; } out;
out.d = path::make_sure_directory(path::app_path("out.d").sjis()).utf8();
notifyf(">> 出力フォルダ : %s", out.d.c_str());
//EBCDICファイル振り分け用ファイルオープン
string basename = path::basename(ebc.path.sjis()).utf8();
for (invokers::iterator i = invokers.begin(), e = invokers.end()
; i != e; ++i)
{
invoker &invoker = **i;
std::ofstream &ofs = invoker.ofs;
string &name = invoker.name;
string &ebc = invoker.ebc;
string &json = invoker.json;
ebc = path::combine(out.d, basename + "." + name);
json = path::combine(out.d, basename + "." + name + ".json");
//クリア
ofs.open(ebc.sjis().c_str()
, std::ios::binary
| std::ios::out
);
ofs.close();
//追記
ofs.open(ebc.sjis().c_str()
, std::ios::binary
| std::ios::app
);
}
//カウンタ変数
struct { int64 bytes, lines; } done = {0};
//進捗バー用変数
struct { int steps; int64 step; } prog = {0};
prog.steps = 50;
prog.step = lines / (int64)prog.steps;
notifyf(">> %s input start: ", fname.c_str());
cout << ">> loading... ";
string line(rsize, 0);
while (ifs.read(&line[0], line.size()))
{
//末尾1バイトで判定
uchar judge = *(line.rbegin());
//EBCDIC変換
judge = ebcdic::tosjis(judge);
//'1' or '2' or ....
size_t offset = judge - '1';
//invokersのイテレータ取得
invokers::iterator i = invokers.invoker_of(offset);
if (i == invokers.end())
{
notifyf("!!!! '%c' is unknown judgement flag !!!!", judge);
throw generic::exception("invalid judgement flag !");
}
//振り分けファイルへの追記処理
invoker &invoker = **i;
std::ofstream &ofs = invoker.ofs;
ofs.write(&line[0], line.size());
//振り分け行数インクリメント
invoker.judge = judge;
invoker.lines.total++;
//進捗バー
done.lines += 1;
done.bytes += line.size();
if (done.lines % prog.step == 0)
{
cout << "#";
}
}
cout << endl;
//ファイルクローズ
ifs.close();
invokers.ofclose();
notifyf(">> done.lines = %10lld", done.lines);
notifyf(">> done.bytes = %10lld", done.bytes);
//振り分け結果表示
for (invokers::iterator i = invokers.begin(), e = invokers.end()
; i != e; ++i)
{
invoker &invoker = **i;
uchar judge = invoker.judge;
int64 lines = invoker.lines.total;
int64 bytes = path::filesize(invoker.ebc.sjis());
string basename = path::basename(invoker.ebc.sjis()).utf8();
notifyf("-- '%c' : %10s %10lld lines / %10lld bytes"
, judge
, basename.c_str()
, lines
, bytes
);
}
//並列処理進捗通知ボードを初期化
boards.init(invokers);
//並列処理スタート&全スレッド完了待ち
cout << "...";
invokers.start();
invokers.wait();
cout << endl;
//変換JSONファイルのサイズを表示
for (invokers::iterator i = invokers.begin(), e = invokers.end()
; i != e; ++i)
{
invoker &invoker = **i;
uchar judge = invoker.judge;
int64 bytes = path::filesize(invoker.json.sjis());
string basename = path::basename(invoker.json.sjis()).utf8();
notifyf("-- '%c' : %10s %10lld bytes"
, judge
, basename.c_str()
, bytes
);
}
return 0;
}
//====================================================
//= 並列処理の内容
//====================================================
void invoker::run()
{
//ゼロディバイド対応
int64 total = lines.total;
int64 &done = lines.done;
if (!total) return;
ifs.open(ebc.sjis().c_str()
, std::ios::binary
| std::ios::in
);
ofs.open(json.sjis().c_str()
, std::ios::binary
| std::ios::out
);
ofs << "[\n";
//通知ボード取得
board::page &board = boards.find(judge)->second;
//パーセント進捗
struct { int pre, now, step; } percent = {0};
int &pre = percent.pre;
int &now = percent.now;
int &step = percent.step;
step = 1;
string line(navigater.rsize, 0);
string buf(0x100, 0);
string sjis, utf8;
while (ifs.read(&line[0], line.size()))
{
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
ofs << (done ? ", " : " ");
ofs << "{\n";
int offset = 0;
for (fdg::navigater::iterator
b = navigater.begin()
, i = b
, e = navigater.end()
; i != e
; ++i
)
{
// ofs << "\t";
ofs << (i - b ? ", " : " ");
fdg::field &field = *i;
int real = field.real;
const string &name = field.name;
buf.resize(real, 0);
::memcpy(&buf[0], &line[offset], real);
sjis = field.translate(buf);
utf8 = sjis.utf8();
ofs << translator::json_escape(name).double_quote();
ofs << ": ";
ofs << translator::json_escape(utf8).double_quote();
ofs << "\n";
offset += real;
}
ofs << "}\n";
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
done++;
now = (done * (int64)100) / total;
if ((now - pre) < step) continue;
pre = now;
board.percent = percent.now;
boards.update();//通知★
}
//ラスト
now = (done * (int64)100) / total;
boards.update();
ofs << "]";
ifs.close();
ofs.close();
} |
a0b2d5f29e26d7ff528ee16d3ffd979999d848e4 | a602ae221f2af4d3847c3addf58c9a3efcdee22e | /models/src/Finder.cpp | b7a02552742d96a36fd78b6be53fc908b586f5e3 | [] | no_license | TalPat/Bomberman | 1b85a137666a9f5adf7ad551184dc2f27d33b251 | 0dcae9b989d69c62701a6fa75e513d5068c8947a | refs/heads/master | 2020-06-22T17:09:11.451515 | 2019-10-29T09:34:19 | 2019-10-29T09:34:19 | 197,751,472 | 2 | 9 | null | 2019-10-29T09:34:20 | 2019-07-19T10:13:20 | C | UTF-8 | C++ | false | false | 3,446 | cpp | Finder.cpp | #include "../include/Finder.hpp"
#include <RNG.hpp>
const int NUM_MOVEMENT_STATES = 4;
const float AGGROTIME = 4;
const float DEFAULT_SPEED = 2.5;
const float AUTOSWITCH = 1;
const bool DEFAULT_WALLPASS = true;
const int SIGHT_RANGE = 8;
const sf::Vector2f DEFAULT_START(9.5, 9.5);
Finder::Finder()
{
_position = (DEFAULT_START);
_enemySpeed = (DEFAULT_SPEED);
moveState = (EnemyMoveState::north);
_switchTime = (AUTOSWITCH);
type = (EnemyType::EFinder);
_wallPass = (DEFAULT_WALLPASS);
changeMoveState();
}
Finder::Finder(sf::Vector2f start)
{
_position = (start);
_enemySpeed = (DEFAULT_SPEED);
moveState = (EnemyMoveState::north);
_switchTime = (AUTOSWITCH);
type = (EnemyType::EFinder);
_wallPass = (DEFAULT_WALLPASS);
changeMoveState();
}
Finder::~Finder()
{
return;
}
void Finder::changeMoveState()
{
this->moveState =(EnemyMoveState)(RNG::getRandomNumber(0, NUM_MOVEMENT_STATES - 1));
}
void Finder::changeMoveState(const Map &map, const Player &player)
{
this->moveState = findpath(map, sf::Vector2i(this->position()), sf::Vector2i(player.position()));
}
void Finder::update(float deltaTime, const Map &map, const Player &player)
{
_switchTime -= deltaTime;
double mf, xdec, ydec;
xdec = modf(this->position().x, &mf);
ydec = modf(this->position().y, &mf);
sf::Vector2i dist = distance(sf::Vector2i(this->position()), sf::Vector2i(player.position()));
if(abs(dist.y) < SIGHT_RANGE && abs(dist.x) < SIGHT_RANGE){
if((xdec <0.55 && xdec > 0.4) && (ydec <0.55 && ydec > 0.4) && ((int)(this->position().x) % 2 || (int)(this->position().y) % 2))
this->changeMoveState(map, player);
}else{
if(_switchTime <= 0)
{
this->changeMoveState();
_switchTime = (RNG::getRandomNumber(0, (int)(AUTOSWITCH))) + 1;
}
}
this->move(deltaTime, map);
}
void Finder::changeAggression()
{
if(_aggression == 3 && type == EnemyType::EBallom)
{
_enemySpeed = DEFAULT_SPEED + 1.5;
type = EnemyType::EAggroBallom;
}
else
{
_enemySpeed = DEFAULT_SPEED;
type = EnemyType::EBallom;
}
_aggression = AGGROTIME;
}
sf::Vector2i Finder::distance(sf::Vector2i start, sf::Vector2i end)
{
int dy = start.y - end.y;
int dx = start.x - end.x;
return (sf::Vector2i(dx, dy));
}
EnemyMoveState Finder::calculatedirection(sf::Vector2i start, sf::Vector2i end)
{
sf::Vector2i dist = distance(start, end);
if(start.x % 2 == 0)
dist.y = 0;
else if(start.y % 2 == 0)
dist.x = 0;
if(!dist.y)
return (dist.x > 0 ? EnemyMoveState::west : EnemyMoveState::east);
else if (!dist.x)
return (dist.y > 0 ? EnemyMoveState::north : EnemyMoveState::south);
else if(abs(dist.y) >= abs(dist.x))
return (dist.y >= 0 ? EnemyMoveState::north : EnemyMoveState::south);
else
return (dist.x >= 0 ? EnemyMoveState::west : EnemyMoveState::east);
}
EnemyMoveState Finder::findpath(Map map, sf::Vector2i start, sf::Vector2i end)
{
EnemyMoveState estDir = calculatedirection(start, end);
sf::Vector2i path(start.x,start.y);
switch (estDir)
{
case EnemyMoveState::north:
path.y -= 1;
break;
case EnemyMoveState::south:
path.y += 1;
break;
case EnemyMoveState::west:
path.x -= 1;
break;
case EnemyMoveState::east:
path.x += 1;
break;
default:
break;
}
if(map.tileAt(path) == Tile::Solid || (!_wallPass && map.tileAt(path) == Tile::Destructible) || (!_wallPass && map.tileAt(path) == Tile::Bomb))
return (EnemyMoveState)(RNG::getRandomNumber(0, (NUM_MOVEMENT_STATES - 1)));
return estDir;
}
|
7b670dcff8f5eccce1f78a1d68bfdbb909cb27b0 | c1d3e3d6436c7c4b95b6df3e79b22309b5f06c46 | /src/view/src/page/SingerPage/AlbumPage.cpp | 4ebd49967d36f98447f4d61c5ce9c4a7aaebe8e8 | [] | no_license | 1028417/XMusic | 5fe5fbc0bcd58754a324c819aac8f21525c5b055 | f01603e427613c1cb8ed2a7ecb04d446ba78641c | refs/heads/master | 2021-06-13T22:31:28.861017 | 2021-05-13T12:06:59 | 2021-05-13T12:06:59 | 198,460,051 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 38,272 | cpp | AlbumPage.cpp |
#include "StdAfx.h"
#include "AlbumPage.h"
#include "SingerPage.h"
enum E_AlbumItemColumn
{
__Column_Name = 0
, __Column_Info
, __Column_Playlist
, __Column_Path
, __Column_AddTime
};
#define __BrowseTop (UINT(m_view.m_globalSize.m_uAlbumDockWidth * 3 / 4))
#define __PlaySingerImageElapse 8000
#define __SingerImgRect CRect(m_cx - m_view.m_globalSize.m_uAlbumDockWidth, 0, m_cx, __BrowseTop)
static const RECT g_rcSingerImgMargin{ 3,0,0,0 };
CAlbumPage::CAlbumPage(__view& view)
: CBasePage(view, IDD_PAGE_ALBUM, L"", IDR_MENU_ALBUMITEM, true)
, m_AlbumMenuGuard(view.m_ResModule, IDR_MENU_ALBUM, __MenuWidth)
, m_wndMediaResPanel(view, *this)
{
}
BEGIN_MESSAGE_MAP(CAlbumPage, CBasePage)
ON_WM_SIZE()
ON_WM_PAINT()
ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST_BROWSE, &CAlbumPage::OnLvnItemchangedListBrowse)
ON_NOTIFY(LVN_ENDLABELEDIT, IDC_LIST_BROWSE, &CAlbumPage::OnLvnEndlabeleditListBrowse)
ON_NOTIFY(LVN_BEGINLABELEDIT, IDC_LIST_BROWSE, &CAlbumPage::OnLvnBeginlabeleditListBrowse)
ON_NOTIFY(NM_RCLICK, IDC_LIST_BROWSE, &CAlbumPage::OnNMRclickListBrowse)
ON_NOTIFY(NM_DBLCLK, IDC_LIST_BROWSE, &CAlbumPage::OnNMDblclkListBrowse)
ON_NOTIFY(NM_SETFOCUS, IDC_LIST_BROWSE, &CAlbumPage::OnNMSetFocusListBrowse)
ON_NOTIFY(NM_SETFOCUS, IDC_LIST_EXPLORE, &CAlbumPage::OnNMSetFocusListExplore)
ON_NOTIFY(NM_RCLICK, IDC_LIST_EXPLORE, &CAlbumPage::OnNMRclickListExplore)
ON_NOTIFY(NM_DBLCLK, IDC_LIST_EXPLORE, &CAlbumPage::OnNMDblclkListExplore)
ON_NOTIFY(NM_CLICK, IDC_LIST_EXPLORE, &CAlbumPage::OnNMClickListExplore)
END_MESSAGE_MAP()
void CAlbumPage::DoDataExchange(CDataExchange* pDX)
{
DDX_Control(pDX, IDC_LIST_BROWSE, m_wndAlbumList);
DDX_Control(pDX, IDC_LIST_EXPLORE, m_wndAlbumItemList);
CPage::DoDataExchange(pDX);
}
BOOL CAlbumPage::OnInitDialog()
{
(void)CPage::OnInitDialog();
cauto strSingerImg = m_view.m_ImgMgr.getImgPath(L"singerdefault");
__AssertReturn(m_imgSingerDefault.Load(strSingerImg), FALSE);
auto& globalSize = m_view.m_globalSize;
m_wndAlbumList.SetImageList(NULL, &m_view.m_ImgMgr.bigImglst());
(void)m_wndAlbumList.ModifyStyle(0, LVS_NOCOLUMNHEADER | LVS_SINGLESEL | LVS_EDITLABELS);
CObjectList::tagListPara ListPara(globalSize.m_uAlbumDockWidth);
ListPara.fFontSize = m_view.m_globalSize.m_fMidFontSize;
ListPara.crText = __Color_Text;
__AssertReturn(m_wndAlbumList.InitCtrl(ListPara), FALSE);
m_wndAlbumList.SetCustomDraw([&](tagLVDrawSubItem& lvcd) {
CAlbum *pAlbum = (CAlbum*)lvcd.pObject;
if (pAlbum)
{
if (pAlbum->property().isDisableDemand() && pAlbum->property().isDisableExport())
{
lvcd.setTextAlpha(200);
}
else if (pAlbum->property().isDisableDemand() || pAlbum->property().isDisableExport())
{
lvcd.setTextAlpha(128);
}
}
}, [=](tagLVDrawSubItem& lvcd){
__Ensure(m_pSinger);
auto eImage = E_GlobalImage::GI_Album;
CAlbum *pAlbum = (CAlbum*)lvcd.pObject;
if (pAlbum)
{
if (pAlbum->albumType() == E_AlbumType::AT_Dir)
{
eImage = E_GlobalImage::GI_AttachDir;
}
}
else
{
eImage = E_GlobalImage::GI_Dir;
}
auto& rc = lvcd.rc;
auto offset = (rc.bottom - rc.top - (int)m_view.m_globalSize.m_uBigIconSize) / 2;
CDC& dc = lvcd.dc;
m_view.m_ImgMgr.bigImglst().Draw(&dc, (int)eImage, { offset, rc.top + offset }, 0);
if (NULL == pAlbum)
{
rc.left = rc.bottom - 20;
dc.SetTextColor(lvcd.crText);
dc.DrawText(m_pSinger->m_strName.c_str(), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
}
});
(void)m_wndAlbumItemList.ModifyStyle(WS_VISIBLE | LVS_ALIGNLEFT
, LVS_AUTOARRANGE | LVS_EDITLABELS | LVS_NOCOLUMNHEADER);
m_wndAlbumItemList.SetImageList(&m_view.m_ImgMgr.bigImglst()
, &m_view.m_ImgMgr.smallImglst());
CRect rcClient;
m_view.m_MainWnd.GetClientRect(rcClient);
UINT width = rcClient.Width() - globalSize.m_uLeftDockWidth - globalSize.m_uAlbumDockWidth - globalSize.m_uScrollbarWidth;
CListColumnGuard ColumnGuard(width + globalSize.m_ColWidth_AddTime);
ColumnGuard.addDynamic(_T("专辑曲目"), 0.63)
.addFix(_T("类型/大小/时长"), globalSize.m_ColWidth_Type + globalSize.m_ColWidth_FileSize, true)
.addFix(_T("关联歌单"), globalSize.m_ColWidth_RelatedPlaylist, true)
.addDynamic(_T("目录"), 0.37)
.addFix(_T("加入时间"), globalSize.m_ColWidth_AddTime, true);
ListPara = CObjectList::tagListPara(ColumnGuard, 0);
ListPara.fFontSize = globalSize.m_fSmallFontSize;
ListPara.crText = __Color_Text;
width -= m_view.m_globalSize.m_uScrollbarWidth;
ListPara.uTileWidth = width/4-1;
ListPara.uTileHeight = globalSize.m_uTileHeight;
__AssertReturn(m_wndAlbumItemList.InitCtrl(ListPara), FALSE);
m_wndAlbumItemList.SetCustomDraw([&](tagLVDrawSubItem& lvcd) {
switch (lvcd.nSubItem)
{
case __Column_Name:
{
CAlbumItem *pAlbumItem = (CAlbumItem *)lvcd.pObject;
__EnsureBreak(pAlbumItem);
if (pAlbumItem->notExist())
{
lvcd.setTextAlpha(128);
}
}
break;
case __Column_Info:
{
CAlbumItem *pAlbumItem = (CAlbumItem *)lvcd.pObject;
__EnsureBreak(pAlbumItem);
CDC& dc = lvcd.dc;
//dc.FillSolidRect(&rc, lvcd.crBkg);
m_wndAlbumItemList.SetCustomFont(dc, -.2f, false);
BYTE uAlpha = m_view.genByteRateAlpha(*pAlbumItem);
dc.SetTextColor(lvcd.getTextColor(uAlpha));
cauto rc = lvcd.rc;
RECT rcText = rc;
rcText.right = rcText.left + globalSize.m_ColWidth_Type;
dc.DrawText(pAlbumItem->GetExtName().c_str(), &rcText, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
dc.SetTextColor(lvcd.crText);
rcText.left = rcText.right;
rcText.right = rc.right;
rcText.bottom = (rcText.bottom + rcText.top)/2 +6;
dc.DrawText(pAlbumItem->displayFileSizeString(true).c_str(), &rcText, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
rcText.top = rcText.bottom -9;
rcText.bottom = rc.bottom;
dc.DrawText(pAlbumItem->displayDurationString().c_str(), &rcText, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
}
lvcd.bSkipDefault = true;
break;
case __Column_Playlist:
lvcd.bSetUnderline = true;
lvcd.fFontSizeOffset = -.15f;
break;
case __Column_Path:
lvcd.bSetUnderline = true;
lvcd.fFontSizeOffset = -.2f;
break;
case __Column_AddTime:
lvcd.fFontSizeOffset = -.2f;
lvcd.setTextAlpha(128);
break;
default:
break;
};
}, [&](tagLVDrawSubItem& lvcd) {
auto eViewType = m_wndAlbumItemList.GetView();
if (E_ListViewType::LVT_Report == eViewType || E_ListViewType::LVT_List == eViewType)
{
CAlbumItem *pAlbumItem = (CAlbumItem *)lvcd.pObject;
__Ensure(pAlbumItem);
auto iImage = pAlbumItem->cueFile() ? (int)E_GlobalImage::GI_WholeTrack : (int)E_GlobalImage::GI_AlbumItem;
POINT pt;
if (E_ListViewType::LVT_Report == eViewType)
{
m_wndAlbumItemList.GetItemPosition(lvcd.uItem, &pt);
}
else
{
pt.x = lvcd.rc.left;
pt.y = lvcd.rc.top;
}
m_view.m_ImgMgr.smallImglst().Draw(&lvcd.dc, iImage, pt, 0);
}
});
m_wndAlbumItemList.SetViewAutoChange([&](E_ListViewType eViewType) {
m_wndAlbumItemList.UpdateItems();
_asyncTask();
});
m_wndAlbumItemList.SetIconSpacing(width / 5-1, m_view.m_globalSize.m_uBigIconSize + m_view.m_globalSize.m_uIconSpace);
__AssertReturn(m_wndMediaResPanel.Create(*this), FALSE);
(void)__super::RegDragDropCtrl(m_wndAlbumList, [&](tagDragData& DragData) {
CAlbum *pAlbum = (CAlbum*)m_wndAlbumList.GetSelObject();
__EnsureReturn(pAlbum, false);
__EnsureReturn(pAlbum->albumType() == E_AlbumType::AT_Normal, false);
DragData.pMediaSet = pAlbum;
DragData.iImage = (int)E_GlobalImage::GI_Album;
return true;
});
(void)__super::RegDragDropCtrl(m_wndAlbumItemList, [&](tagDragData& DragData) {
__EnsureReturn(m_pAlbum && m_pAlbum->albumType() == E_AlbumType::AT_Normal, false);
TD_ListObjectList lstObjects;
m_wndAlbumItemList.GetSelObjects(lstObjects);
__EnsureReturn(lstObjects, false);
DragData.lstMedias.add(lstObjects);
DragData.iImage = (int)E_GlobalImage::GI_AlbumItem;
return true;
});
__super::RegMenuHotkey(m_wndAlbumList, VK_RETURN, ID_PLAY_ALBUM);
__super::RegMenuHotkey(m_wndAlbumList, VK_F2, ID_RENAME_ALBUM);
__super::RegMenuHotkey(m_wndAlbumList, VK_DELETE, ID_REMOVE_ALBUM);
__super::RegMenuHotkey(m_wndAlbumItemList, VK_RETURN, ID_PLAY_ALBUMITEM);
__super::RegMenuHotkey(m_wndAlbumItemList, VK_F2, ID_RENAME_ALBUMITEM);
__super::RegMenuHotkey(m_wndAlbumItemList, VK_DELETE, ID_REMOVE_ALBUMITEM);
return TRUE;
}
void CAlbumPage::OnPaint()
{
if (NULL == m_pSinger)
{
__super::OnPaint();
return;
}
CPaintDC dc(this);
CRect rcSingerImg(__SingerImgRect);
dc.FillSolidRect(rcSingerImg, __crWhite);
rcSingerImg.left += g_rcSingerImgMargin.left;
rcSingerImg.top += g_rcSingerImgMargin.top;
rcSingerImg.right -= g_rcSingerImgMargin.right;
rcSingerImg.bottom -= g_rcSingerImgMargin.bottom;
auto& img = m_imgSinger.IsNull()?m_imgSingerDefault:m_imgSinger;
img.StretchBltEx(dc, rcSingerImg, E_ImgFixMode::IFM_Outer);
}
#define __XOffset 6
void CAlbumPage::OnSize(UINT nType, int cx, int cy)
{
m_cx = cx;
int x = cx - m_view.m_globalSize.m_uAlbumDockWidth;
CRect rcPos(0, 0, x, cy);
if (m_wndMediaResPanel)
{
m_wndMediaResPanel.MoveWindow(rcPos);
}
if (m_wndAlbumItemList)
{
rcPos.left = __XOffset;
m_wndAlbumItemList.MoveWindow(rcPos);
m_wndAlbumList.MoveWindow(x-1, __BrowseTop, m_view.m_globalSize.m_uAlbumDockWidth
, cy - __BrowseTop + m_view.m_globalSize.m_uScrollbarWidth);
CRect rcSingerImg(__SingerImgRect);
rcSingerImg.left -= 50;
this->RedrawWindow(rcSingerImg, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
}
}
void CAlbumPage::ShowSinger(CSinger *pSinger, CMedia *pAlbumItem, IMedia *pIMedia)
{
if (!m_hWnd)
{
if (!pSinger)
{
return;
}
m_view.m_ResModule.ActivateResource();
__Assert(m_view.m_MainWnd.AddPage(*this, E_DockViewType::DVT_DockCenter));
this->Active();
}
m_pAlbum = NULL;
bool bSingerChanged = (pSinger != m_pSinger);
m_pSinger = pSinger;
if (NULL == m_pSinger)
{
UpdateTitle();
(void)m_wndAlbumList.ShowWindow(SW_HIDE);
(void)m_wndAlbumList.DeleteAllItems();
(void)m_wndAlbumItemList.ShowWindow(SW_HIDE);
(void)m_wndAlbumItemList.DeleteAllItems();
m_wndMediaResPanel.ShowDir();
(void)m_wndMediaResPanel.ShowWindow(SW_SHOW);
// TODO this->DestryWindow(); m_view.m_MainWnd.RemvePage(*this);
this->Invalidate();
return;
}
(void)m_wndAlbumList.ShowWindow(SW_SHOW);
if (bSingerChanged)
{
UpdateSingerImage();
(void)m_wndAlbumList.SetObjects(TD_ListObjectList((list<CAlbum>&)m_pSinger->albums()));
(void)m_wndAlbumList.InsertItem(0, L"", -1);// , (int)E_GlobalImage::GI_Dir);
m_wndMediaResPanel.SetSinger(*m_pSinger); //SetDir(m_pSinger->dir());
}
if (pAlbumItem)
{
auto pAlbum = (CAlbum*)pAlbumItem->m_pParent;
m_wndAlbumList.SelectObject(pAlbum);
m_pAlbum = pAlbum;
m_wndAlbumItemList.DeselectAll();
m_wndAlbumItemList.SelectObject(pAlbumItem);
(void)m_wndAlbumItemList.SetFocus();
}
else
{
_showAlbum(NULL);
(void)m_wndAlbumList.SelectFirstItem();
if (pIMedia)
{
m_wndMediaResPanel.HittestMedia(*pIMedia, *this);
(void)m_wndMediaResPanel.SetFocus();
}
}
}
bool CAlbumPage::_playSingerImage(bool bReset)
{
__AssertReturn(m_pSinger, false);
static UINT uSingerImgIdx = 0;
if (bReset)
{
uSingerImgIdx = 0;
}
auto hBitmap = m_view.getSingerImgMgr().getSingerImg(m_pSinger->m_strName, uSingerImgIdx);
if (hBitmap)
{
m_imgSinger.Destroy();
m_imgSinger.Attach(hBitmap);
this->InvalidateRect(__SingerImgRect);
uSingerImgIdx++;
return true;
}
if (uSingerImgIdx > 1)
{
return _playSingerImage(true);
}
return false;
}
void CAlbumPage::UpdateSingerImage()
{
static CWinTimer s_timer;
if (_playSingerImage(true))
{
s_timer.set(__PlaySingerImageElapse, [&]{
_playSingerImage(false);
return true;
});
}
else
{
s_timer.kill();
m_imgSinger.Destroy();
this->InvalidateRect(__SingerImgRect);
}
}
void CAlbumPage::UpdateTitle()
{
m_strBaseTitle = L" ";
wstring strTitle;
if (m_pSinger)
{
if (m_pAlbum)
{
strTitle = __CNDot + m_pAlbum->m_strName;
m_strBaseTitle.append(m_pSinger->m_strName);
}
else
{
strTitle = m_wndMediaResPanel.GetTitle();
if (strTitle.empty())
{
m_strBaseTitle.append(m_pSinger->m_pParent->m_strName + __CNDot + m_pSinger->m_strName);
}
else
{
m_strBaseTitle.append(m_pSinger->m_strName);
}
}
}
else
{
m_strBaseTitle.append(L"歌手");
}
strTitle.push_back(' ');
SetTitle(strTitle);
}
void CAlbumPage::UpdateSingerName()
{
m_wndAlbumList.Update(0);
//if (m_pSinger) m_wndAlbumList.SetItemText(0, 0, (L" " + m_pSinger->m_strName).c_str());
UpdateTitle();
}
int CAlbumPage::GetTabImage()
{
UINT uImgPos = (UINT)E_GlobalImage::GI_SingerDefault;
if (NULL != m_pSinger)
{
uImgPos = m_view.m_ImgMgr.getSingerImgPos(m_pSinger->m_uID);
}
return uImgPos;
}
void CAlbumPage::OnNMRclickListBrowse(NMHDR *pNMHDR, LRESULT *pResult)
{
__Ensure(m_pSinger);
*pResult = 0;
LPNMLISTVIEW lpNM = (LPNMLISTVIEW)pNMHDR;
BOOL bEnable = (lpNM->iItem > 0);
m_AlbumMenuGuard.EnableItem(ID_RENAME_ALBUM, bEnable);
m_AlbumMenuGuard.EnableItem(ID_REMOVE_ALBUM, bEnable);
m_AlbumMenuGuard.EnableItem(ID_CNLanguage, bEnable);
m_AlbumMenuGuard.EnableItem(ID_HKLanguage, bEnable);
m_AlbumMenuGuard.EnableItem(ID_KRLanguage, bEnable);
m_AlbumMenuGuard.EnableItem(ID_JPLanguage, bEnable);
m_AlbumMenuGuard.EnableItem(ID_ENLanguage, bEnable);
m_AlbumMenuGuard.EnableItem(ID_OtherLanguage, bEnable);
m_AlbumMenuGuard.EnableItem(ID_TlLanguage, bEnable);
m_AlbumMenuGuard.EnableItem(ID_RsLanguage, bEnable);
m_AlbumMenuGuard.EnableItem(ID_FrLanguage, bEnable);
bool bPlayable = false;
bool bNormalAlbum = false;
if (bEnable)
{
CAlbum *pAlbum = (CAlbum*)m_wndAlbumList.GetItemObject(lpNM->iItem);
__Assert(pAlbum);
const CMediasetProperty& property = pAlbum->property();
m_AlbumMenuGuard.CheckItem(ID_DisableDemand, property.isDisableDemand());
m_AlbumMenuGuard.CheckItem(ID_DisableExport, property.isDisableExport());
m_AlbumMenuGuard.CheckItem(ID_CNLanguage, property.isCnLanguage());
m_AlbumMenuGuard.CheckItem(ID_HKLanguage, property.isHkLanguage());
m_AlbumMenuGuard.CheckItem(ID_KRLanguage, property.isKrLanguage());
m_AlbumMenuGuard.CheckItem(ID_JPLanguage, property.isJpLanguage());
m_AlbumMenuGuard.CheckItem(ID_ENLanguage, property.isEnLanguage());
m_AlbumMenuGuard.CheckItem(ID_OtherLanguage, property.isOtherLanguage());
if (property.isTlLanguage() || property.isRsLanguage() || property.isFrLanguage())
{
m_AlbumMenuGuard.EnableItem(ID_OtherLanguage, false);
}
m_AlbumMenuGuard.CheckItem(ID_TlLanguage, property.isTlLanguage());
m_AlbumMenuGuard.CheckItem(ID_RsLanguage, property.isRsLanguage());
m_AlbumMenuGuard.CheckItem(ID_FrLanguage, property.isFrLanguage());
bPlayable = pAlbum->albumItems();
bNormalAlbum = E_AlbumType::AT_Normal == pAlbum->albumType();
}
m_AlbumMenuGuard.EnableItem(ID_PLAY_ALBUM, bPlayable);
m_AlbumMenuGuard.EnableItem(ID_VERIFY_ALBUM, bPlayable && bNormalAlbum);
m_AlbumMenuGuard.EnableItem(ID_EXPORT_ALBUM, bPlayable && bNormalAlbum);
m_AlbumMenuGuard.EnableItem(ID_ADD_ALBUMITEM, bNormalAlbum);
m_AlbumMenuGuard.EnableItem(ID_DisableDemand, bNormalAlbum);
m_AlbumMenuGuard.EnableItem(ID_DisableExport, bNormalAlbum);
(void)m_AlbumMenuGuard.EnableItem(ID_ADD_ALBUM, true);
(void)m_AlbumMenuGuard.EnableItem(ID_ATTACH_DIR, true);
(void)m_AlbumMenuGuard.EnableItem(ID_ATTACH_WHOLETRACK, true);
(void)m_AlbumMenuGuard.Popup(this, m_view.m_globalSize.m_uMenuItemHeight, m_view.m_globalSize.m_fMidFontSize);
}
void CAlbumPage::OnMenuCommand_Album(UINT uID)
{
int nItem = m_wndAlbumList.GetSelItem();
CAlbum *pAlbum = (CAlbum*)m_wndAlbumList.GetSelObject();
switch (uID)
{
case ID_VERIFY_ALBUM:
__Assert(pAlbum);
m_view.verifyMedia(*pAlbum);
break;
case ID_EXPORT_ALBUM:
__Assert(pAlbum);
m_view.exportMediaSet(*pAlbum);
break;
case ID_PLAY_ALBUM:
__Ensure(pAlbum);
m_view.m_PlayCtrl.addPlayingItem(*pAlbum);
break;
case ID_ADD_ALBUMITEM:
{
__Ensure(pAlbum);
cauto strSingerDir = __xmedialib.toAbsPath(m_pSinger->dir(), true);
if (!fsutil::existDir(strSingerDir))
{
msgBox(L"歌手目录不存在!");
return;
}
tagFileDlgOpt FileDlgOpt;
FileDlgOpt.strTitle = L"添加专辑曲目";
FileDlgOpt.strFilter = __MediaFilter;
FileDlgOpt.strInitialDir = strSingerDir;
CFileDlgEx fileDlg(FileDlgOpt);
list<wstring> lstFiles;
fileDlg.ShowOpenMulti(lstFiles);
__Ensure(!lstFiles.empty());
int nRet = m_view.getController().AddAlbumItems(lstFiles, *pAlbum);
__Ensure(nRet > 0);
this->_showAlbum(pAlbum);
UINT uSelectCount = (UINT)nRet;
m_wndAlbumItemList.SelectItems(m_wndAlbumItemList.GetItemCount() - uSelectCount, uSelectCount);
}
break;
//case ID_ATTACH_WHOLETRACK:
case ID_ATTACH_DIR:
{
__AssertBreak(m_pSinger);
CMediaDir *pDir = m_view.showChooseDirDlg(L"选择附加目录", false);
__EnsureBreak(pDir);
if (pDir->files())
{
auto pAlbum = m_view.getSingerMgr().AddAlbum(*m_pSinger, pDir->fileName(), NULL, E_AlbumType::AT_Dir, pDir->GetPath());
__EnsureBreak(pAlbum);
m_wndAlbumList.InsertObject(*pAlbum);
}
pDir->dirs()([&](CPath& dir){
if (dir.files())
{
auto pAlbum = m_view.getSingerMgr().AddAlbum(*m_pSinger, ((CMediaDir&)dir).fileName()
, NULL, E_AlbumType::AT_Dir, ((CMediaDir&)dir).GetPath());
if (pAlbum)
{
m_wndAlbumList.InsertObject(*pAlbum);
}
}
});
}
break;
case ID_ADD_ALBUM:
{
auto pAlbum = m_view.getSingerMgr().AddAlbum(*m_pSinger, L"");
__EnsureBreak(pAlbum);
auto nItem = m_wndAlbumList.InsertObject(*pAlbum);
(void)m_wndAlbumList.EditLabel(nItem);
}
break;
case ID_RENAME_ALBUM:
__EnsureBreak(nItem > 0);
(void)m_wndAlbumList.EditLabel(nItem);
break;
case ID_REMOVE_ALBUM:
__AssertBreak(pAlbum);
__EnsureBreak(confirmBox(L"确认删除所选专辑?"));
(void)m_wndAlbumList.DeleteItem(nItem);
(void)m_wndAlbumList.SetItemState(0, LVIS_SELECTED, LVIS_SELECTED);
__EnsureBreak(m_view.getController().removeMediaSet(*pAlbum));
break;
case ID_DisableDemand:
case ID_DisableExport:
case ID_CNLanguage:
case ID_HKLanguage:
case ID_KRLanguage:
case ID_JPLanguage:
case ID_ENLanguage:
case ID_OtherLanguage:
case ID_TlLanguage:
case ID_RsLanguage:
case ID_FrLanguage:
{
__AssertBreak(pAlbum);
CMediasetProperty property = pAlbum->property();
if (ID_DisableDemand == uID)
{
bool bDisableDemand = !property.isDisableDemand();
property.setDisableDemand(bDisableDemand);
property.setDisableExport(bDisableDemand);
m_wndAlbumList.UpdateItem(nItem);
}
else if (ID_DisableExport == uID)
{
property.setDisableExport(!property.isDisableExport());
m_wndAlbumList.UpdateItem(nItem);
}
else
{
E_LanguageType eLanguage = E_LanguageType::LT_None;
switch (uID)
{
case ID_CNLanguage:
eLanguage = E_LanguageType::LT_CN;
break;
case ID_HKLanguage:
eLanguage = E_LanguageType::LT_HK;
break;
case ID_KRLanguage:
eLanguage = E_LanguageType::LT_KR;
break;
case ID_JPLanguage:
eLanguage = E_LanguageType::LT_JP;
break;
case ID_ENLanguage:
eLanguage = E_LanguageType::LT_EN;
break;
case ID_OtherLanguage:
eLanguage = E_LanguageType::LT_Other;
break;
case ID_TlLanguage:
eLanguage = E_LanguageType::LT_TL;
break;
case ID_RsLanguage:
eLanguage = E_LanguageType::LT_RS;
break;
case ID_FrLanguage:
eLanguage = E_LanguageType::LT_FR;
break;
default:
return;
};
if ((property.language() & (UINT)eLanguage) == (UINT)eLanguage)
{
property.unsetLanguage(eLanguage);
}
else
{
property.setLanguage(eLanguage);
}
};
(void)m_view.getDataMgr().updateMediaSetProperty(*pAlbum, property);
}
break;
}
}
void CAlbumPage::OnMenuCommand_AlbumItem(UINT uID, UINT uVkKey)
{
TD_ListObjectList lstObjects;
m_wndAlbumItemList.GetSelObjects(lstObjects);
TD_MediaList lstAlbumItems(lstObjects);
switch (uID)
{
case ID_ADD_ALBUMITEM:
OnMenuCommand_Album(ID_ADD_ALBUMITEM);
break;
case ID_PLAY_ALBUMITEM:
if (lstAlbumItems)
{
m_view.m_PlayCtrl.addPlayingItem(TD_IMediaList(lstAlbumItems));
}
else
{
if (0 == uVkKey)
{
__AssertBreak(m_pAlbum);
m_view.m_PlayCtrl.addPlayingItem(*m_pAlbum);
}
}
break;
case ID_FIND_ALBUMITEM:
__AssertBreak(1 == lstAlbumItems.size());
lstAlbumItems.front([&](auto& media) {
m_view.showFindDlg(media.GetTitle(), false);
});
break;
case ID_HITTEST_ALBUMITEM:
__AssertBreak(1 == lstAlbumItems.size());
lstAlbumItems.front([&](auto& media) {
if (m_pAlbum->albumType() == E_AlbumType::AT_Normal)
{
(void)m_wndMediaResPanel.HittestMedia(media, *this);
}
else
{
m_view.m_MediaResPage.HittestMedia(media, *this);
}
});
break;
case ID_SETALARMCLOCK:
{
__AssertBreak(lstAlbumItems);
TD_IMediaList lstMedias(lstAlbumItems);
m_view.getDataMgr().addAlarmmedia(lstMedias);
}
break;
case ID_CopyTitle:
lstAlbumItems.front([&](auto& media) {
(void)m_view.copyMediaTitle(media);
});
break;
case ID_EXPLORE_ALBUMITEM:
if (lstAlbumItems.size() == 1)
{
lstAlbumItems.front([&](CMedia& media) {
m_view.exploreMedia(media);
});
}
break;
case ID_EXPORT_ALBUMITEM:
if (lstAlbumItems)
{
m_view.exportMedia(TD_MediaList(lstAlbumItems));
}
else
{
TD_MediaList paMedias((ArrList<CAlbumItem>&)m_pAlbum->albumItems());
m_view.exportMedia(paMedias);
}
break;
case ID_REMOVE_ALBUMITEM:
__EnsureBreak(lstAlbumItems);
__EnsureBreak(confirmBox(L"确认移除选中的曲目?"));
__EnsureBreak(m_view.getModel().removeMedia(lstAlbumItems));
break;
case ID_RENAME_ALBUMITEM:
__EnsureBreak(1 == lstObjects.size());
lstObjects.front([&](CListObject& ListObject) {
(void)m_wndAlbumItemList.EditLabel(m_wndAlbumItemList.GetObjectItem(&ListObject));
});
}
}
/*void CAlbumPage::OnActive(BOOL bActive)
{
if (bActive)
{
if (m_pAlbum)
{
_asyncTask();
}
else
{
m_wndMediaResPanel.OnActive(true);
}
}
}*/
void CAlbumPage::OnMenuCommand(UINT uID, UINT uVkKey)
{
CWnd *pWndFocus = CWnd::GetFocus();
if (&m_wndAlbumList == pWndFocus)
{
this->OnMenuCommand_Album(uID);
}
else if (&m_wndAlbumItemList == pWndFocus)
{
this->OnMenuCommand_AlbumItem(uID, uVkKey);
}
}
void CAlbumPage::OnLvnItemchangedListBrowse(NMHDR *pNMHDR, LRESULT *pResult)
{
*pResult = 0;
LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
__Ensure(pNMLV->uChanged & LVIF_STATE)
__Ensure(pNMLV->uNewState & LVIS_SELECTED);
auto pAlbum = (CAlbum*)m_wndAlbumList.GetItemObject(pNMLV->iItem);
if (pAlbum != m_pAlbum)
{
_showAlbum(pAlbum);
}
}
void CAlbumPage::_showAlbum(CAlbum *pAlbum)
{
__Ensure(m_hWnd);
if (NULL == pAlbum)
{
m_pAlbum = NULL;
this->UpdateTitle();
m_wndMediaResPanel.Refresh();
(void)m_wndMediaResPanel.ShowWindow(SW_SHOW);
(void)m_wndAlbumItemList.ShowWindow(SW_HIDE);
(void)m_wndAlbumItemList.DeleteAllItems();
return;
}
bool bChanged = pAlbum != m_pAlbum;
m_pAlbum = pAlbum;
this->UpdateTitle();
if (E_AlbumType::AT_Normal == m_pAlbum->albumType())
{
m_pAlbum->albumItems()([&](cauto AlbumItem) {
((CAlbumItem&)AlbumItem).findRelatedMedia();
});
}
(void)m_wndAlbumItemList.SetObjects(TD_ListObjectList((ArrList<CAlbumItem>&)m_pAlbum->albumItems()));
if (bChanged)
{
m_wndAlbumItemList.EnsureVisible(0, FALSE);
}
(void)m_wndAlbumItemList.ShowWindow(SW_SHOW);
(void)m_wndMediaResPanel.ShowWindow(SW_HIDE);
_asyncTask();
}
void CAlbumPage::RefreshAlbum()
{
if (m_pAlbum)
{
_showAlbum(m_pAlbum);
}
}
void CAlbumPage::OnLvnBeginlabeleditListBrowse(NMHDR *pNMHDR, LRESULT *pResult)
{
*pResult = 0;
NMLVDISPINFO *pLVDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
if (0 == pLVDispInfo->item.iItem)
{
*pResult = TRUE;
}
}
void CAlbumPage::OnLvnEndlabeleditListBrowse(NMHDR *pNMHDR, LRESULT *pResult)
{
*pResult = 0;
NMLVDISPINFO *pLVDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
CAlbum *pAlbum = (CAlbum*)m_wndAlbumList.GetItemObject(pLVDispInfo->item.iItem);
__Ensure(pAlbum);
CString cstrNewName(pLVDispInfo->item.pszText);
(void)cstrNewName.Trim();
__Ensure(!cstrNewName.IsEmpty());
wstring strNewName = cstrNewName;
__Ensure(strNewName != pAlbum->m_strName);
auto eRetCode = m_view.getController().renameMediaSet(*pAlbum, strNewName);
if (E_RenameRetCode::RRC_Success != eRetCode)
{
if (E_RenameRetCode::RRC_InvalidName == eRetCode)
{
msgBox(L"名称含特殊字符!");
}
else if (E_RenameRetCode::RRC_NameExists == eRetCode)
{
msgBox(L"重命名失败,存在同名专辑!");
}
return;
}
(void)m_wndAlbumList.SetItemText(pLVDispInfo->item.iItem, 0, cstrNewName);
this->UpdateTitle();
}
DROPEFFECT CAlbumPage::OnMediasDragOverExploreList(const TD_IMediaList& lstMedias, CDragContext& DragContext)
{
//__EnsureReturn(_checkMediasDropable(lstMedias), DROPEFFECT_NONE);
DROPEFFECT dwRet = 0;
lstMedias.front([&](IMedia& media) {
if (media.mediaSet() == m_pAlbum)
{
dwRet = DROPEFFECT_MOVE;
}
else
{
dwRet = DROPEFFECT_COPY;
}
});
auto eViewType = m_wndAlbumItemList.GetView();
if (E_ListViewType::LVT_Report == eViewType)
{
handleDragOver(m_wndAlbumItemList, DragContext);
return dwRet;
}
int nItem = 0;
CRect rcItem;
(void)m_wndAlbumItemList.GetItemRect(m_wndAlbumItemList.GetItemCount() - 1, &rcItem, LVIR_BOUNDS);
bool bOutofRange = false;
if (E_ListViewType::LVT_List == eViewType)
{
if (DragContext.x > rcItem.right || (DragContext.x >= rcItem.left && DragContext.y >= rcItem.bottom))
{
bOutofRange = true;
}
}
else if (DragContext.y > rcItem.bottom || (DragContext.y >= rcItem.top && DragContext.x >= rcItem.right))
{
bOutofRange = true;
}
if (bOutofRange)
{
nItem = m_wndAlbumItemList.GetItemCount()-1;
DragContext.x = rcItem.right;
DragContext.y = rcItem.bottom;
}
else
{
#define __Margin 10
tagPOINT lpPoint[4] {
{DragContext.x - __Margin, DragContext.y - __Margin}
, {DragContext.x + __Margin, DragContext.y - __Margin}
, {DragContext.x - __Margin, DragContext.y + __Margin}
, {DragContext.x + __Margin, DragContext.y + __Margin}
};
map<int, CRect> mapItems;
for (UINT uIndex = 0; uIndex < sizeof(lpPoint)/sizeof(tagPOINT); ++uIndex)
{
nItem = m_wndAlbumItemList.HitTest(lpPoint[uIndex]);
if (nItem >= 0 && mapItems.find(nItem) == mapItems.end())
{
(void)m_wndAlbumItemList.GetItemRect(nItem, &mapItems[nItem], LVIR_BOUNDS);
}
}
__EnsureReturn(!mapItems.empty(), DROPEFFECT_NONE);
UINT uMinDistance = 0;
for (map<int, CRect>::iterator itItem = mapItems.begin()
; itItem != mapItems.end(); ++itItem)
{
int nDx = itItem->second.CenterPoint().x - DragContext.x;
int nDy = itItem->second.CenterPoint().y - DragContext.y;
UINT uDistance = nDx * nDx + nDy * nDy;
if (0 == uMinDistance || uDistance < uMinDistance)
{
uMinDistance = uDistance;
nItem = itItem->first;
rcItem = itItem->second;
}
}
}
DragContext.uTargetPos = nItem;
if (DragContext.x < rcItem.CenterPoint().x)
{
DragContext.x = rcItem.left;
}
else
{
DragContext.x = rcItem.right+4;
DragContext.uTargetPos++;
}
if (DragContext.x < 1)
{
DragContext.x = 1;
}
DragContext.DrawDragOverVLine(DragContext.x, rcItem.top, rcItem.bottom);
return dwRet;
}
BOOL CAlbumPage::OnMediasDropExploreList(const TD_IMediaList& lstMedias, UINT uTargetPos, DROPEFFECT nDropEffect)
{
__EnsureReturn(lstMedias, FALSE);
__EnsureReturn(m_pAlbum, FALSE);
int nNewPos = 0;
CMediaSet *pSrcMediaSet = NULL;
lstMedias.front([&](IMedia& media) {
pSrcMediaSet = media.mediaSet();
});
UINT uCount = 0;
if (pSrcMediaSet != m_pAlbum)
{
int nRet = m_view.getController().AddAlbumItems(lstMedias, *m_pAlbum, uTargetPos);
__EnsureReturn(nRet > 0, FALSE);
uCount = (UINT)nRet;
nNewPos = uTargetPos;
}
else
{
list<UINT> lstSelectedItems;
m_wndAlbumItemList.GetSelItems(lstSelectedItems);
__AssertReturn(!lstSelectedItems.empty(), FALSE);
if (uTargetPos >= lstSelectedItems.front() && uTargetPos <= lstSelectedItems.back() + 1)
{
if (lstSelectedItems.back() - lstSelectedItems.front() + 1 == lstSelectedItems.size())
{
return FALSE;
}
}
nNewPos = m_view.getSingerMgr().RepositAlbumItem(*m_pAlbum, lstMedias, uTargetPos);
__EnsureReturn(nNewPos >= 0, FALSE);
uCount = lstMedias.size();
}
_showAlbum(m_pAlbum);
m_wndAlbumItemList.SelectItems(nNewPos, uCount);
return TRUE;
}
BOOL CAlbumPage::_checkMediasDropable(const TD_IMediaList& lstMedias)
{
__EnsureReturn(m_pSinger, FALSE);
cauto strSingerDir = m_pSinger->dir();
BOOL bRet = TRUE;
lstMedias.front([&](IMedia& media) {
if (media.type() != E_MediaType::MT_AlbumItem)
{
lstMedias([&](IMedia& media) {
if (!fsutil::CheckSubPath(strSingerDir, media.GetPath()))
{
bRet = FALSE;
return false;
}
return true;
});
}
});
return bRet;
}
DROPEFFECT CAlbumPage::OnMediasDragOverBrowseList(const TD_IMediaList& lstMedias, CDragContext& DragContext)
{
bool bScroll = DragScroll(m_wndAlbumList, DragContext.x, DragContext.y);
//__EnsureReturn(_checkMediasDropable(lstMedias), DROPEFFECT_NONE);
int nItem = m_wndAlbumList.HitTest(CPoint(5, DragContext.y));
__EnsureReturn(1 <= nItem, DROPEFFECT_NONE);
CAlbum *pDropHilightAlbum = (CAlbum*)m_wndAlbumList.GetItemObject(nItem);
__AssertReturn(pDropHilightAlbum, DROPEFFECT_NONE);
CMediaSet *pSrcMediaSet = NULL;
lstMedias.front([&](IMedia& media) {
pSrcMediaSet = media.mediaSet();
});
__EnsureReturn(pSrcMediaSet != pDropHilightAlbum, DROPEFFECT_NONE);
DragContext.pTargetObj = pDropHilightAlbum;
if (!bScroll)
{
CRect rcItem;
(void)m_wndAlbumList.GetItemRect(nItem, &rcItem, LVIR_BOUNDS);
DragContext.DrawDragOverRect(rcItem.top, rcItem.bottom);
}
if (pSrcMediaSet && E_MediaSetType::MST_Album==pSrcMediaSet->type())
{
if (0 == (DragContext.dwKeyState & MK_CONTROL))
{
return DROPEFFECT_MOVE;
}
}
return DROPEFFECT_COPY;
}
BOOL CAlbumPage::OnMediasDropBrowseList(const TD_IMediaList& lstMedias, CAlbum *pTargetAlbum, DROPEFFECT nDropEffect)
{
__EnsureReturn(lstMedias, FALSE);
__AssertReturn(pTargetAlbum, FALSE);
CMediaSet *pSrcMediaSet = NULL;
lstMedias.front([&](IMedia& media) {
pSrcMediaSet = media.mediaSet();
});
UINT uCount = 0;
if (pSrcMediaSet && E_MediaSetType::MST_Album == pSrcMediaSet->type())
{
__EnsureReturn(pTargetAlbum != pSrcMediaSet, FALSE);
auto len = pTargetAlbum->GetSinger().dir().size();
TD_AlbumItemList lstAlbumItems(lstMedias);
cauto lstOppPath = lstAlbumItems.map([&](const CAlbumItem& AlbumItem) {
auto strPath = AlbumItem.GetPath();
strPath.erase(0, len);
return strPath;
});
__EnsureReturn(m_view.getSingerMgr().AddAlbumItems(lstOppPath, *pTargetAlbum), FALSE);
uCount = lstAlbumItems.size();
if (DROPEFFECT_MOVE == nDropEffect)
{
__EnsureReturn(m_view.getSingerMgr().RemoveAlbumItems(lstAlbumItems), FALSE);
}
}
else
{
int nRet = m_view.getController().AddAlbumItems(lstMedias, *pTargetAlbum);
__EnsureReturn(nRet > 0, FALSE);
uCount = (UINT)nRet;
}
m_wndAlbumList.SelectObject(pTargetAlbum);
_showAlbum(pTargetAlbum);
m_wndAlbumItemList.SelectItems((UINT)m_wndAlbumItemList.GetItemCount()-uCount, uCount);
(void)m_wndAlbumItemList.SetFocus();
return TRUE;
}
DROPEFFECT CAlbumPage::OnMediaSetDragOver(CWnd *pwndCtrl, CMediaSet *pMediaSet, CDragContext& DragContext)
{
__EnsureReturn(pwndCtrl == &m_wndAlbumList, DROPEFFECT_NONE);
__EnsureReturn(pMediaSet && E_MediaSetType::MST_Album == pMediaSet->type(), DROPEFFECT_NONE);
int nDragingItem = m_wndAlbumList.GetObjectItem(pMediaSet);
__AssertReturn(nDragingItem >= 0, DROPEFFECT_NONE);
DROPEFFECT dwRet = DROPEFFECT_MOVE;
handleDragOver(m_wndAlbumList, DragContext, [&](UINT& uTargetPos) {
if (uTargetPos < 1)
{
uTargetPos = 1;
}
});
return dwRet;
}
BOOL CAlbumPage::OnMediaSetDrop(CWnd *pwndCtrl, CMediaSet *pMediaSet, CDragContext& DragContext)
{
__AssertReturn(pwndCtrl == &m_wndAlbumList && pMediaSet && E_MediaSetType::MST_Album == pMediaSet->type(), DROPEFFECT_NONE);
int nDragingItem = m_wndAlbumList.GetObjectItem(pMediaSet);
__AssertReturn(nDragingItem >= 0, FALSE);
int nTargetPos = DragContext.uTargetPos;
if (nTargetPos > nDragingItem)
{
nTargetPos--;
}
__EnsureReturn(nTargetPos != nDragingItem, FALSE);
CRedrawLock RedrawLock(*this);
_showAlbum(NULL);
int nNewPos = nTargetPos - 1;
if (nNewPos < 0)
{
nNewPos = 0;
}
CAlbum *pAlbum = m_view.getSingerMgr().RepositAlbum(*(CAlbum*)pMediaSet, (UINT)nNewPos);
__EnsureReturn(pAlbum, FALSE);
(void)m_wndAlbumList.DeleteItem(nDragingItem);
(void)m_wndAlbumList.InsertObject(*pAlbum, nTargetPos);
m_wndAlbumList.SelectItem(nTargetPos);
return TRUE;
}
DROPEFFECT CAlbumPage::OnMediasDragOver(CWnd *pwndCtrl, const TD_IMediaList& lstMedias, CDragContext& DragContext)
{
if (pwndCtrl == &m_wndAlbumList)
{
return OnMediasDragOverBrowseList(lstMedias, DragContext);
}
else if (pwndCtrl == &m_wndAlbumItemList)
{
return OnMediasDragOverExploreList(lstMedias, DragContext);
}
return DROPEFFECT_NONE;
}
BOOL CAlbumPage::OnMediasDrop(CWnd *pwndCtrl, const TD_IMediaList& lstMedias, CDragContext& DragContext)
{
if (pwndCtrl == &m_wndAlbumList)
{
return OnMediasDropBrowseList(lstMedias, (CAlbum*)DragContext.pTargetObj, DragContext.nDropEffect);
}
else if (pwndCtrl == &m_wndAlbumItemList)
{
return OnMediasDropExploreList(lstMedias, DragContext.uTargetPos, DragContext.nDropEffect);
}
return FALSE;
}
void CAlbumPage::OnNMRclickListExplore(NMHDR *pNMHDR, LRESULT *pResult)
{
__Ensure(m_pAlbum);
bool bNormalAlbum = E_AlbumType::AT_Normal == m_pAlbum->albumType();
m_MenuGuard.EnableItem(ID_ADD_ALBUMITEM, bNormalAlbum);
m_MenuGuard.EnableItem(ID_PLAY_ALBUMITEM, m_pAlbum->albumItems());
int nSelCount = m_wndAlbumItemList.GetSelectedCount();
m_MenuGuard.EnableItem(ID_FIND_ALBUMITEM, (1 == nSelCount) && bNormalAlbum);
m_MenuGuard.EnableItem(ID_HITTEST_ALBUMITEM, (1 == nSelCount));
m_MenuGuard.EnableItem(ID_SETALARMCLOCK, (nSelCount > 0));
m_MenuGuard.EnableItem(ID_CopyTitle, (1 == nSelCount));
m_MenuGuard.EnableItem(ID_EXPLORE_ALBUMITEM, (1 == nSelCount));
m_MenuGuard.EnableItem(ID_EXPORT_ALBUMITEM, (m_wndAlbumItemList.GetItemCount() > 0) && bNormalAlbum);
m_MenuGuard.EnableItem(ID_RENAME_ALBUMITEM, (1 == nSelCount) && bNormalAlbum);
m_MenuGuard.EnableItem(ID_REMOVE_ALBUMITEM, (nSelCount > 0) && bNormalAlbum);
(void)m_MenuGuard.Popup(this, m_view.m_globalSize.m_uMenuItemHeight, m_view.m_globalSize.m_fMidFontSize);
}
void CAlbumPage::OnNMDblclkListBrowse(NMHDR *pNMHDR, LRESULT *pResult)
{
*pResult = 0;
this->OnMenuCommand(ID_PLAY_ALBUM);
}
void CAlbumPage::OnNMDblclkListExplore(NMHDR *pNMHDR, LRESULT *pResult)
{
*pResult = 0;
LPNMLISTVIEW lpNMList = (LPNMLISTVIEW)pNMHDR;
__Ensure(lpNMList->iItem >= 0);
m_wndAlbumItemList.DeselectAll();
m_wndAlbumItemList.SelectItem(lpNMList->iItem);
this->OnMenuCommand(ID_PLAY_ALBUMITEM);
}
void CAlbumPage::OnNMClickListExplore(NMHDR *pNMHDR, LRESULT *pResult)
{
*pResult = 0;
LPNMITEMACTIVATE lpNMList = (LPNMITEMACTIVATE)pNMHDR;
int iSubItem = lpNMList->iSubItem;
if (__Column_Playlist == iSubItem || __Column_Path == iSubItem)
{
__Ensure(m_wndAlbumItemList.GetSelectedCount()<=1 && !CMainApp::getKeyState(VK_SHIFT) && !CMainApp::getKeyState(VK_CONTROL));
int iItem = lpNMList->iItem;
m_wndAlbumItemList.AsyncLButtondown([=]{
auto pAlbumItem = (CAlbumItem*)m_wndAlbumItemList.GetItemObject(iItem);
__Ensure(pAlbumItem);
(void)pAlbumItem->findRelatedMedia();
m_wndAlbumItemList.UpdateItem(iItem, pAlbumItem);
if (__Column_Playlist == iSubItem)
{
m_view.hittestRelatedPlaylist(*pAlbumItem);
}
else
{
this->OnMenuCommand_AlbumItem(ID_HITTEST_ALBUMITEM);
}
});
}
}
void CAlbumPage::UpdateRelated(E_RelatedMediaSet eRmsType, const tagMediaSetChanged& MediaSetChanged)
{
if (NULL != m_pSinger)
{
m_wndMediaResPanel.UpdateRelated(eRmsType, MediaSetChanged);
if (m_pAlbum)
{
m_pAlbum->albumItems()([&](cauto t_AlbumItem, size_t uIdx) {
auto& AlbumItem = (CAlbumItem&)t_AlbumItem;
if (AlbumItem.UpdateRelatedMediaSet(eRmsType, MediaSetChanged))
{
m_wndAlbumItemList.UpdateItem(uIdx, &AlbumItem);
}
uIdx++;
});
}
}
}
void CAlbumPage::_asyncTask()
{
__async(10, [&]{
if (m_pAlbum)
{
m_wndAlbumItemList.AsyncTask(__AsyncTaskElapse + m_pAlbum->albumItems().size() / 10, [](CListObject& object) {
__checkMedia((CMedia&)object);
return false;
});
}
});
}
|
a97519f3f0edbe9489174cff6f9ceca5cbdd9322 | 403e84740ece164893f522556c2f4d8bd622e08d | /demo/demo.cpp | e992fbdd991a9690aa1911adcbda89b198cf46a1 | [] | no_license | marekzajac92/cjs | 1f6353d44b29a33ca903266ba54f886a69e1c8b4 | daa2aaa34e985a7b361dff4dff997d700851458c | refs/heads/master | 2021-03-19T07:15:34.361819 | 2013-06-05T12:52:03 | 2013-06-05T12:52:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,521 | cpp | demo.cpp |
//The headers
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include <string>
#include <iostream>
//Screen attributes
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
//The frame rate
const int FRAMES_PER_SECOND = 20;
//The dot dimensions
const int DOT_WIDTH = 20;
const int DOT_HEIGHT = 20;
//The surfaces
SDL_Surface *dot = NULL;
SDL_Surface *screen = NULL;
//The event structure
SDL_Event event;
//The joystick that will be used
SDL_Joystick *stick = NULL;
//The dot
class Dot {
private:
//The offsets of the dot
int x, y;
//The velocity of the dot
int xVel, yVel;
public:
//Initializes
Dot();
//Handles joystick
void handle_input();
//Moves the dot
void move();
//Shows the dot
void show();
};
//The timer
class Timer {
private:
//The clock time when the timer started
int startTicks;
//The ticks stored when the timer was paused
int pausedTicks;
//The timer status
bool paused;
bool started;
public:
//Initializes variables
Timer();
//The various clock actions
void start();
void stop();
void pause();
void unpause();
//Gets the timer's time
int get_ticks();
//Checks the status of the timer
bool is_started();
bool is_paused();
};
SDL_Surface *load_image(std::string filename) {
//The image that's loaded
SDL_Surface* loadedImage = NULL;
//The optimized surface that will be used
SDL_Surface* optimizedImage = NULL;
//Load the image
loadedImage = IMG_Load(filename.c_str());
//If the image loaded
if (loadedImage != NULL) {
//Create an optimized surface
optimizedImage = SDL_DisplayFormat(loadedImage);
//Free the old surface
SDL_FreeSurface(loadedImage);
//If the surface was optimized
if (optimizedImage != NULL) {
//Color key surface
SDL_SetColorKey(optimizedImage, SDL_SRCCOLORKEY,
SDL_MapRGB(optimizedImage->format, 0, 0xFF, 0xFF));
}
}
//Return the optimized surface
return optimizedImage;
}
void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination,
SDL_Rect* clip = NULL) {
//Holds offsets
SDL_Rect offset;
//Get offsets
offset.x = x;
offset.y = y;
//Blit
SDL_BlitSurface(source, clip, destination, &offset);
}
bool init() {
//Initialize all SDL subsystems
if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
std::cout << "SDL_Init error" << std::endl;
return false;
}
//Set up the screen
screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP,
SDL_SWSURFACE);
//If there was an error in setting up the screen
if (screen == NULL) {
return false;
}
//Check if there's any joysticks
if (SDL_NumJoysticks() < 1) {
std::cout << "Joystick not found." << std::endl;
return false;
}
//Open the joystick
stick = SDL_JoystickOpen(0);
//If there's a problem opening the joystick
if (stick == NULL) {
std::cout << "Joystick not open." << std::endl;
return false;
}
//Set the window caption
SDL_WM_SetCaption("Move the Dot", NULL);
//If everything initialized fine
return true;
}
bool load_files() {
//Load the dot image
dot = load_image("dot.bmp");
//If there was a problem in loading the dot
if (dot == NULL) {
return false;
}
//If everything loaded fine
return true;
}
void clean_up() {
//Free the surface
SDL_FreeSurface(dot);
//Close the joystick
SDL_JoystickClose(stick);
//Quit SDL
SDL_Quit();
}
Dot::Dot() {
//Initialize the offsets
x = 0;
y = 0;
//Initialize the velocity
xVel = 0;
yVel = 0;
}
void Dot::handle_input() {
//If a axis was changed
if (event.type == SDL_JOYAXISMOTION) {
//If joystick 0 has moved
if (event.jaxis.which == 0) {
std::cout << "Joystick 0 has moved" << std::endl;
//If the X axis changed
if (event.jaxis.axis == 0) {
//If the X axis is neutral
if ((event.jaxis.value > -8000) && (event.jaxis.value < 8000)) {
std::cout << "The X axis is neutral" << std::endl;
xVel = 0;
}
//If not
else {
std::cout << "The dot X move!: " << event.jaxis.value << std::endl;
//Adjust the velocity
if (event.jaxis.value < 0) {
xVel = -DOT_WIDTH / 2;
} else {
xVel = DOT_WIDTH / 2;
}
}
}
//If the Y axis changed
else if (event.jaxis.axis == 1) {
//If the Y axis is neutral
if ((event.jaxis.value > -8000) && (event.jaxis.value < 8000)) {
std::cout << "The Y axis is neutral" << event.jaxis.value << std::endl;
yVel = 0;
}
//If not
else {
std::cout << "The dot Y move!" << std::endl;
//Adjust the velocity
if (event.jaxis.value < 0) {
yVel = -DOT_HEIGHT / 2;
} else {
yVel = DOT_HEIGHT / 2;
}
}
}
}
}
}
void Dot::move() {
//Move the dot left or right
x += xVel;
//If the dot went too far to the left or right
if ((x < 0) || (x + DOT_WIDTH > SCREEN_WIDTH)) {
//move back
x -= xVel;
}
//Move the dot up or down
y += yVel;
//If the dot went too far up or down
if ((y < 0) || (y + DOT_HEIGHT > SCREEN_HEIGHT)) {
//move back
y -= yVel;
}
//std::cout << "X: " << x << std::endl;
//std::cout << "Y: " << y << std::endl;
}
void Dot::show() {
//Show the dot
apply_surface(x, y, dot, screen);
}
Timer::Timer() {
//Initialize the variables
startTicks = 0;
pausedTicks = 0;
paused = false;
started = false;
}
void Timer::start() {
//Start the timer
started = true;
//Unpause the timer
paused = false;
//Get the current clock time
startTicks = SDL_GetTicks();
}
void Timer::stop() {
//Stop the timer
started = false;
//Unpause the timer
paused = false;
}
void Timer::pause() {
//If the timer is running and isn't already paused
if ((started == true) && (paused == false)) {
//Pause the timer
paused = true;
//Calculate the paused ticks
pausedTicks = SDL_GetTicks() - startTicks;
}
}
void Timer::unpause() {
//If the timer is paused
if (paused == true) {
//Unpause the timer
paused = false;
//Reset the starting ticks
startTicks = SDL_GetTicks() - pausedTicks;
//Reset the paused ticks
pausedTicks = 0;
}
}
int Timer::get_ticks() {
//If the timer is running
if (started == true) {
//If the timer is paused
if (paused == true) {
//Return the number of ticks when the timer was paused
return pausedTicks;
} else {
//Return the current time minus the start time
return SDL_GetTicks() - startTicks;
}
}
//If the timer isn't running
return 0;
}
bool Timer::is_started() {
return started;
}
bool Timer::is_paused() {
return paused;
}
int main(int argc, char* args[]) {
//Quit flag
bool quit = false;
//Make the dot
Dot myDot;
//The frame rate regulator
Timer fps;
//Initialize
if (init() == false) {
return 1;
}
//Load the files
if (load_files() == false) {
return 1;
}
//While the user hasn't quit
while (quit == false) {
//Start the frame timer
fps.start();
//While there's events to handle
while (SDL_PollEvent(&event)) {
//Handle events for the dot
myDot.handle_input();
//If the user has Xed out the window
if (event.type == SDL_QUIT) {
//Quit the program
quit = true;
}
}
//Move the dot
myDot.move();
//Fill the screen white
SDL_FillRect(screen, &screen->clip_rect,
SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF));
//Show the dot on the screen
myDot.show();
//Update the screen
if (SDL_Flip(screen) == -1) {
return 1;
}
//Cap the frame rate
if (fps.get_ticks() < 1000 / FRAMES_PER_SECOND) {
SDL_Delay((1000 / FRAMES_PER_SECOND) - fps.get_ticks());
}
}
//Clean up
clean_up();
return 0;
}
|
fe7e350e7bbbc9ca0516b0deb5aa56e5aca8840c | 3f1e226f1d440b06cbfa2da9b98a81e803143957 | /segundo-parcial/hw2/main.cpp | 345685b8d224c3d3efded7ce6117585a1a040d1f | [] | no_license | margotduek/Progra-avanzada | 27a527d20446480b80ad200b90d28a5ddffb1432 | 2ee02cbab730a9554e7a6c2cce998c18a85d333f | refs/heads/master | 2021-01-11T21:17:29.572928 | 2017-05-11T19:29:13 | 2017-05-11T19:29:13 | 78,757,634 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,055 | cpp | main.cpp |
#include <SFML/Graphics.hpp>
#include <iostream>
#include <unistd.h>
#include <signal.h>
void direction(int x);
void stop(int y);
void continue_(int y);
bool dir = true;
bool status = true;
int main()
{
//Rendering a 800 * 800 window
sf::RenderWindow window(sf::VideoMode(800, 800), "SFML works!");
//creating a circle to put a texture to put jacos' image
sf::CircleShape shape(50);
sf::Texture texture;
if (!texture.loadFromFile("jaco.png")){
printf("No se cargó la imagen");
}
//puting the jacos texture into a sprite
sf::Sprite sprite;
sprite.setTexture(texture);
//Center jaco in the middle of the window
sprite.setPosition(sf::Vector2f(400, 400));
int i = 0;
//Call handlers
signal(SIGINT, stop);
signal(SIGTSTP, continue_);
signal(SIGALRM, direction);
alarm(5);
//Ignore Signals
signal(SIGABRT,SIG_IGN);
signal(SIGFPE,SIG_IGN);
signal(SIGILL,SIG_IGN);
signal(SIGSEGV,SIG_IGN);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
//clear the window each time of the while
window.clear();
// draw the sprite again
window.draw(sprite);
// display jacos' sprite again
window.display();
sprite.setPosition(sf::Vector2f(i, i*2));
// if status is false, then the program is in pause, check function stop and continue_
if(status){
//if the image goes out of the window start again
if(i > 400){
i = 0;
}
if(i < -400){
i = 400;
}
// change direction, check function direction()
if(dir){
i++;
}
else if(!dir){
i--;
}
}
}
return 0;
}
//direction handler
void direction(int x){
alarm(5);
signal(SIGALRM, direction);
if(dir == true){
dir = false;
}else{
dir = true;
}
}
//pause handler
void stop(int y){
status = false;
}
//continue handler
void continue_(int y){
status = true;
}
|
f07eb79fd3f99ed23c689268b868a690e2fbceac | a2e420076860c2834e7a8291e766a0d11a61612a | /CloudDDS/include/dds_dcps/sub/datareaderimpl.h | 38a0e91a671f97829289943424e8cb7f4231db4e | [] | no_license | MAPSWorks/QAR | 84934ed08d6c0e6365efd50df72f6cbbc71e7656 | ecc2757de2e96ca8f780a1c3857f62e058ae1abe | refs/heads/master | 2020-04-09T09:20:54.008960 | 2018-05-10T06:41:24 | 2018-05-10T06:41:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 921 | h | datareaderimpl.h | #ifndef _CLOUD_BUS_DATA_READER_IMPL_H_
#define _CLOUD_BUS_DATA_READER_IMPL_H_
#include "../core/types.h"
#if (HERMES_OS == HERMES_OS_WINDOWS_NT)
#include <objbase.h>
#endif
namespace DDS
{
class DataReaderImpl
{
public:
DataReaderImpl(Subscriber_ptr pSub, Topic_ptr pTopic, const DataReaderQos& qos, DataReaderListener_ptr a_listener, StatusMask mask);
virtual ~DataReaderImpl();
virtual ReturnCode_t set_listener(DataReaderListener_ptr a_listener, StatusMask mask);
virtual DataReaderListener_ptr get_listener();
virtual Subscriber_ptr get_subscriber();
private:
DataReaderListener_ptr m_pListener;
Subscriber_ptr m_pSubscriber;
Topic_ptr m_pTopic;
DomainParticipant_ptr m_pDp;
GUID m_nodeId;
};
}
#endif |
a8bd5ce591cc5e2986849deca3153558a84b269b | 682797727dd61ecc784983e343318223e59b0342 | /Konto.HPP | bfbd5da8184da2220a58f7b2df2a2554ad6ca730 | [] | no_license | BielskiGrzegorz/Projekt | 1c31f9dfb211e0d6a2d3f6ed04a9f71de511ddba | 6db3a747ace386b326235b40f126bcec907bc85b | refs/heads/master | 2021-09-04T03:43:43.743010 | 2018-01-15T12:31:06 | 2018-01-15T12:31:06 | 113,041,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 473 | hpp | Konto.HPP | #ifndef Konto_HPP
#define Konto_HPP
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
class Konto
{
std::vector<Konto> dane;
public:
std::string login, haslo;
Konto();
Konto(std::string login1,std::string haslo1);
int iloscKont();
void wczytKont(std::string s);
void zapisKont(Konto& daneKonta, std::string nazwaPliku);
void noweKonto(std::string nazwaPliku);
bool logowanie();
};
#endif // Konto_HPP
|
959ba3afd375cbbfc31c9d3b2d4b63386b3393fb | e8d41e6c547e5fa00400539c1514f0d6ecc7a0fe | /Source/Towers/Public/LevelController.h | 7dddda00b3308b321b3944eafe7001cc3671654f | [] | no_license | Fjool/Nightlands | 63e9c73dd4035828606aaa4fb892f750b0e22d40 | 0f21c3675f026a7438e140212495615c63ed53eb | refs/heads/master | 2020-12-24T10:53:43.948089 | 2016-11-19T14:42:57 | 2016-11-19T14:42:57 | 73,125,187 | 0 | 0 | null | 2016-11-13T23:58:11 | 2016-11-07T22:05:51 | C++ | UTF-8 | C++ | false | false | 1,138 | h | LevelController.h | // (C) 2016 Mesomorphic Ltd
#pragma once
#include "GameFramework/Actor.h"
#include "LevelController.generated.h"
class AMonsterActor;
class ATowerActor;
UCLASS()
class TOWERS_API ALevelController : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ALevelController();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
void RegisterMonster(AMonsterActor* Monster); // called by generators when they spawn a new monster, so things are kept track of centrally
void ReachedTarget( AMonsterActor* Monster); // called by monsters when they reach their target
void Died( AMonsterActor* Monster); // called by monsters when they die
bool IsTarget( AMonsterActor* Monster);
private:
TArray<AMonsterActor*> Monsters;
TArray< ATowerActor*> Towers;
// Activate tower spawning for level
void SpawnTowers();
void RemoveMonsterFromGame(AMonsterActor* Monster);
UPROPERTY(EditDefaultsOnly, Category = Setup) TSubclassOf<ATowerActor> TowerBlueprint = nullptr;
};
|
6cbae727781039ff040dc195fbfb9f8b2db765a4 | f5079cc796501fd933d833f2f5e24dee994eded0 | /3年時/チョコの逆襲/ソース/title.cpp | 894a08cf6e6e4b14816b35fb3e91636116119533 | [] | no_license | thurapro/tensyoku | 0bbcea59bf0b7d9a70b8997af3ccdc138771b35f | 68432cae647fe77af87b0bd7f22b43f7b90b35bd | refs/heads/master | 2023-08-23T05:11:53.656699 | 2021-10-19T15:20:11 | 2021-10-19T15:20:11 | 418,956,503 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 7,248 | cpp | title.cpp | //=============================================================================
//
// title処理 [title.cpp] 松尾 雄太
//
//=============================================================================
//=============================================================================
// ヘッダー読み込み
//=============================================================================
#include "../hedder/title.h"
//=============================================================================
// マクロ定義
//=============================================================================
#define FVF_VERTEX_2D_TEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1) // 2Dテクスチャー設定
#define TEX_INIT_X (0.25f)
#define TEX_MAX (1.0f)
#define ANIMECNT_MAX (40)
#define TEX_SPEED_X (0.25f)
#define TITLE_SOUND (0)
//=============================================================================
// グローバル変数
//=============================================================================
static Title g_Title; // タイトル変数
static LPDIRECT3DVERTEXBUFFER9 g_pD3DVBXYZBuffer; // 頂点バッファー
static LPDIRECT3DTEXTURE9 g_pD3DTex; // タイトル画像
static int g_nAnimeCnt = 0;
static LPDIRECTSOUNDBUFFER g_soundTitle;
//=============================================================================
// 構造体
//=============================================================================
typedef struct
{
D3DVECTOR vtx; // 頂点座標
float rhw; // 同次座標の逆数
D3DCOLOR diffuse; // 色情報
D3DXVECTOR2 tex; // テクスチャー座標
}VERTEX_2D;
//=============================================================================
// プロトタイプ宣言
//=============================================================================
static HRESULT MakeVertexTitle(LPDIRECT3DDEVICE9 pDevice); // 頂点バッファー作成
//=============================================================================
// タイトル初期化
//=============================================================================
HRESULT InitTitle(LPDIRECT3DDEVICE9 pDevice)
{
HRESULT hr;
g_Title.fPosX = 0.0f; // 画像のX軸位置
g_Title.fPosY = 0.0f; // 画像のY軸位置
g_Title.fWidth = (float)SCREEN_WIDTH; // 画像の幅設定
g_Title.fHeight = (float)SCREEN_HEIGHT; // 画像の高さ設定
g_Title.fTexX0 = 0.0f; // 画像頂点
g_Title.fTexY0 = 0.0f; // 画像頂点
g_Title.fTexX1 = TEX_INIT_X; // 画像頂点
g_Title.fTexY1 = 1.0f; // 画像頂点
g_Title.fMoveX = TEX_SPEED_X; // 画像の動く速度
g_Title.fMoveY = 0.0f; // 画像の動く速度
g_nAnimeCnt = 0;
SoundFileLoad( "DATA/Sound/Title.wav" , TITLE_SOUND );
CreateSoundBuffer(&g_soundTitle, TITLE_SOUND);
//------------------------
// テクスチャーのロード
hr = D3DXCreateTextureFromFile(pDevice, "DATA/Texture/Title.png" , &g_pD3DTex);
//---------------------------------------
// テクスチャーがロードできなかった場合
if( FAILED(hr) )
{
return hr;
}
//----------------------------------------
// 頂点作成
hr = MakeVertexTitle(pDevice);
//----------------------------------------
// 頂点バッファーが作成できなかったら
if( FAILED(hr) )
{
return hr;
}
g_soundTitle->Play(0,0,0);
return hr;
}
//=============================================================================
// タイトル破棄
//=============================================================================
void UninitTitle(void)
{
if(g_pD3DVBXYZBuffer != NULL)
{
g_pD3DVBXYZBuffer->Release();
g_pD3DVBXYZBuffer = NULL;
}
if(g_pD3DTex != NULL)
{
g_pD3DTex->Release();
g_pD3DTex = NULL;
}
if(g_soundTitle != NULL)
{
g_soundTitle->Release();
g_soundTitle = NULL;
}
}
//=============================================================================
// タイトル更新
//=============================================================================
void UpdateTitle(void)
{
VERTEX_2D *pVtx;
// 更新
if( KeyPush(DIK_RETURN) )
{
GameSelectSet(GAME);
}
else
{
if( g_nAnimeCnt > ANIMECNT_MAX )
{
if( g_Title.fTexX1 < TEX_MAX )
{
g_Title.fTexX0 += g_Title.fMoveX;
g_Title.fTexX1 += g_Title.fMoveX;
}
else
{
g_Title.fTexX0 += g_Title.fMoveX;
g_Title.fTexX1 += g_Title.fMoveX;
}
g_nAnimeCnt = 0;
}
else
{
g_nAnimeCnt++;
}
g_pD3DVBXYZBuffer->Lock(0, 0, (void **)&pVtx, 0);
pVtx[0].tex = D3DXVECTOR2(g_Title.fTexX0, g_Title.fTexY0);
pVtx[1].tex = D3DXVECTOR2(g_Title.fTexX1, g_Title.fTexY0);
pVtx[2].tex = D3DXVECTOR2(g_Title.fTexX0, g_Title.fTexY1);
pVtx[3].tex = D3DXVECTOR2(g_Title.fTexX1, g_Title.fTexY1);
g_pD3DVBXYZBuffer->Unlock();
}
}
//=============================================================================
// タイトル描画
//=============================================================================
void DrawTitle(LPDIRECT3DDEVICE9 pDevice)
{
// 頂点フォーマットをセット
pDevice->SetFVF(FVF_VERTEX_2D_TEX);
// 頂点バッファーのセット
pDevice->SetStreamSource(0, g_pD3DVBXYZBuffer, 0, sizeof(VERTEX_2D));
// テクスチャーセット
pDevice->SetTexture(0, g_pD3DTex);
// プリミティブ
pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
}
//=============================================================================
// タイトルの頂点バッファー作成
//=============================================================================
HRESULT MakeVertexTitle(LPDIRECT3DDEVICE9 pDevice)
{
HRESULT hr;
VERTEX_2D *pVtx;
// 頂点バッファー作成
hr = pDevice->CreateVertexBuffer( sizeof(VERTEX_2D) * 4 ,
D3DUSAGE_WRITEONLY,
FVF_VERTEX_2D_TEX,
D3DPOOL_MANAGED,
&g_pD3DVBXYZBuffer,
NULL);
//-----------------------
// 作成できなかったら
if(FAILED(hr))
{
return hr;
}
// 頂点バッファーロック
hr = g_pD3DVBXYZBuffer->Lock(0, 0, (void **)&pVtx, 0);
//-----------------------
// ロックできなかったら
if(FAILED(hr))
{
return hr;
}
// 頂点バッファー位置セット
pVtx[0].vtx = D3DXVECTOR3(g_Title.fPosX, g_Title.fPosY, 0);
pVtx[1].vtx = D3DXVECTOR3(g_Title.fWidth, g_Title.fPosY, 0);
pVtx[2].vtx = D3DXVECTOR3(g_Title.fPosX,g_Title.fHeight, 0);
pVtx[3].vtx = D3DXVECTOR3(g_Title.fWidth, g_Title.fHeight, 0);
// rhwの設定
pVtx[0].rhw = 1.0f;
pVtx[1].rhw = 1.0f;
pVtx[2].rhw = 1.0f;
pVtx[3].rhw = 1.0f;
// 色情報
pVtx[0].diffuse = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[1].diffuse = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[2].diffuse = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[3].diffuse = D3DCOLOR_RGBA(255, 255, 255, 255);
// テクスチャー座標設定
pVtx[0].tex = D3DXVECTOR2(g_Title.fTexX0, g_Title.fTexY0);
pVtx[1].tex = D3DXVECTOR2(g_Title.fTexX1, g_Title.fTexY0);
pVtx[2].tex = D3DXVECTOR2(g_Title.fTexX0, g_Title.fTexY1);
pVtx[3].tex = D3DXVECTOR2(g_Title.fTexX1, g_Title.fTexY1);
// ロック解除
hr = g_pD3DVBXYZBuffer->Unlock();
//-----------------------
// ロック解除できなかったら
if(FAILED(hr))
{
return hr;
}
return hr;
}
|
82014db81a2bed5bb7614a974d53e981df2a6038 | 0a4541e219bbfe9296cc659618dd4a91c81e0d56 | /KR3/parser/csvparser.cpp | fc88816183c4e1b37a835100a93e976417fd7240 | [] | no_license | karikera/ken | e07b8858f63d839ac1cc9b69c648897644d5bfe2 | c41bee5f2da2b8e99d0b9284a53404218c4a6869 | refs/heads/master | 2023-04-27T17:48:03.681745 | 2023-04-17T09:20:50 | 2023-04-17T09:20:50 | 182,513,850 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,032 | cpp | csvparser.cpp | #include "stdafx.h"
#include "csvparser.h"
#include <KR3/meta/text.h>
kr::CSVParser::CSVParser(nullptr_t) noexcept
:m_stream(nullptr)
{
m_nLast = ',';
m_line = 1;
}
kr::CSVParser::CSVParser(io::VIStream<char> stream)
:m_stream(_new io::VIStream<char>(stream))
{
m_nLast = ',';
m_line = 1;
m_stream.hasBom();
}
kr::CSVParser& kr::CSVParser::operator = (nullptr_t)
{
m_stream = nullptr;
return *this;
}
kr::CSVParser& kr::CSVParser::operator = (io::VIStream<char> stream)
{
m_stream.close();
m_stream.resetIStream(_new io::VIStream<char>(stream));
return *this;
}
kr::io::VIStream<char>* kr::CSVParser::operator &() const
{
return m_stream.base();
}
size_t kr::CSVParser::nextLength() noexcept
{
size_t len = 0;
try
{
char chr = m_stream.peek();
size_t start = 0;
if (chr == '\"')
{
start++;
size_t pos = start;
for (;;)
{
try
{
pos = m_stream.pos('\"', pos);
if (m_stream.peekAt(pos + 1) != '\"')
{
len += pos - start;
start = pos + 1;
break;
}
else
{
pos++;
len += pos - start;
pos++;
start = pos;
}
}
catch (EofException&)
{
return len;
}
}
}
size_t pos = m_stream.pos_y(",\n", start);
return pos - start + len;
}
catch (EofException&)
{
return eof;
}
}
void kr::CSVParser::mustLine() throws(EofException, NoLineException)
{
switch (m_nLast)
{
case '\n': m_nLast = ','; break;
case eof: throw EofException();
default: throw NoLineException();
}
m_line++;
}
bool kr::CSVParser::nextLine() noexcept
{
if (m_nLast == '\n')
{
m_nLast = ',';
m_line++;
return true;
}
try
{
char finded;
do
{
char chr = m_stream.peek();
if (chr == '\"')
{
m_stream.skip(1);
size_t pos = 0;
for (;;)
{
try
{
pos = m_stream.pos('\"', pos);
pos++;
if (m_stream.peekAt(pos) != '\"')
{
m_stream.skip(pos);
break;
}
else
{
m_stream.skip(pos + 1);
pos = 0;
}
}
catch (TooBigException&)
{
m_stream.clearBuffer();
}
}
}
m_stream.readwith_y(",\n", &finded);
} while (finded == ',');
m_nLast = ',';
m_line++;
return true;
}
catch (EofException&)
{
m_stream.clearBuffer();
m_nLast = eof;
return false;
}
}
int kr::CSVParser::getLine() noexcept
{
return m_line;
}
bool kr::CSVParser::hasNext() noexcept
{
switch (m_nLast)
{
case eof: return false;
case '\n': return false;
case ',': break;
}
return true;
}
void kr::CSVParser::skip() throws(EofException, NoLineException, NextLineException)
{
switch (m_nLast)
{
case eof: throw EofException();
case '\n':
m_nLast = ',';
m_line++;
throw NextLineException();
case ',': break;
}
int finded = 0;
try
{
while (m_stream.peek() == '\"')
{
m_stream.skip(1);
m_stream.skipwith('\"');
}
finded = m_stream.skipwith_y(",\n");
}
catch (EofException&)
{
m_stream.clearBuffer();
finded = eof;
}
m_nLast = finded;
}
kr::TmpArray<char> kr::CSVParser::next() throws(EofException, NoLineException, NextLineException)
{
TText tx;
tx.reserve(1024);
next(&tx);
return tx;
}
kr::Array<char> kr::CSVParser::nextAlloc() throws(EofException, NoLineException, NextLineException)
{
AText tx;
next(&tx);
tx.shrink();
return tx;
}
kr::CSVWriter::CSVWriter(nullptr_t) noexcept
{
m_prev = false;
}
kr::CSVWriter::CSVWriter(io::VOStream<char> stream) noexcept
: m_stream(stream)
{
m_prev = false;
}
kr::CSVWriter& kr::CSVWriter::operator = (nullptr_t) noexcept
{
m_stream.reset();
return *this;
}
kr::CSVWriter& kr::CSVWriter::operator = (io::VOStream<char> stream) noexcept
{
m_stream = stream;
return *this;
}
kr::io::VOStream<char>* kr::CSVWriter::operator &() noexcept
{
return &m_stream;
}
void kr::CSVWriter::write(View<char> str) throws(NotEnoughSpaceException)
{
write<View<char>, char>(str);
}
void kr::CSVWriter::nextLine() throws(NotEnoughSpaceException)
{
m_stream.write('\n');
m_prev = false;
}
|
c7694c139544ac1826f443807fe00cb79c410bf4 | 00dbe4fd5f00fab51f959fdf32ddb185daa8de30 | /P161.cpp | 9515c22766a2b0cc8c99265ab7638e17c5c641f9 | [] | no_license | LasseD/uva | c02b21c37700bd6f43ec91e788b2787152bfb09b | 14b62742d3dfd8fb55948b2682458aae676e7c14 | refs/heads/master | 2023-01-29T14:51:42.426459 | 2023-01-15T09:29:47 | 2023-01-15T09:29:47 | 17,707,082 | 3 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,269 | cpp | P161.cpp | #include <iostream>
#include <stdio.h>
int main() {
int signals[100];
while(true) {
// read signals:
int numSignals = 0;
int minSignal = 9000;
while(true) {
int signal;
std::cin >> signal;
if(signal == 0)
break;
signals[numSignals] = signal;
++numSignals;
if(signal < minSignal)
minSignal = signal;
}
if(numSignals == 0)
return 0;
// simulate:
int okk = false;
for(int time = 2*minSignal; time <= 5*60*60;) {
//Check if all green:
bool ok = true;
for(int i = 0; i < numSignals; ++i) {
int in = time % (2*signals[i]);
if(in >= signals[i]-5) {
//std::cerr << i << " not green at time " << time << std::endl;
ok = false;
break;
}
}
if(ok) {
//std::cerr << "All green at time " << time << std::endl;
printf("%02i:%02i:%02i\n", time / 3600, (time / 60) % 60, time % 60);
okk = true;
break;
}
// Find next green:
int toNextGreen = 90;
for(int i = 0; i < numSignals; ++i) {
int in = (2*signals[i]) - time % (2*signals[i]);
if(in < toNextGreen) {
toNextGreen = in;
}
}
time += toNextGreen;
}
if(!okk) {
std::cout << "Signals fail to synchronise in 5 hours" << std::endl;
}
}
}
|
587491c04f3d51bb7550e7e129ef8168db729014 | 0e4d92e0da4abf3fe8e5d8ab97f6ca033a6ac8f0 | /Utils/FE_ana/evtbuilder.cxx | 8b37881dcd6c9791b6acdbe38f70bab0501deebf | [] | no_license | luigicalligaris/HL_LHC | a141e0b342438aa786e4f9bbf386dcdc5962499d | e36d801b1cc5fb69e20134d52f0adb10bc8bb17b | refs/heads/master | 2020-03-07T06:59:06.178117 | 2016-01-07T14:50:18 | 2016-01-07T14:50:18 | 127,336,933 | 0 | 0 | null | 2018-03-29T19:24:38 | 2018-03-29T19:17:00 | C++ | UTF-8 | C++ | false | false | 52,065 | cxx | evtbuilder.cxx | // Base class for Phase II tracker FrontEnd tests
// Main constructor
// Constructor for the concentrator
// Meaning of the parameters
//
//
// filenameRAW : the input data files for L1 block generation
// filenameTRG : the input data files for trigger block generation
// outfile : name of the output root file
// npatt : how many BXs should be produced (will be fitted correctly afterwards)
// rate : input L1A rate (for the L1 raw block writing
// layer : restrict info to a given layer, or not (give -1 in this case)
// sector : the input file defining the modules
// RAW : write the L1 block or not
// TRIG : write the Trigger block or not
// npblock : How many bits do we reserve to L1 in the concentrator block (between 8 and 320, should be a multiple of 8)
// BMPA : How many bits are used to code the stub bend on MPA concentrator level (0 to 5)
// BCBC : How many bits are used to code the stub bend on CBC concentrator level (0 to 5)
// conc : Are we building concentrator (true) or FE (false) data sequences
// L1prop : The proportion of PU4T events you want in the TRG flow (in %)
// CICsize : The size of the concentrator block, in BX
#include "evtbuilder.h"
evtbuilder::evtbuilder(std::string filenameRAW, std::string filenameTRG, std::string outfile,
int npatt, int rate, int layer, std::string sector,
bool RAW, bool TRIG, int npblock, int BMPA, int BCBC,
bool conc,int L1prop, int CICsize)
{
m_rate = rate;
m_lay = layer;
m_npblock = npblock;
m_tri_data = new std::vector<int>;
m_raw_data = new std::vector<int>;
m_raw_chip_bx= new std::vector<int>;;
m_raw_chip_fifo= new std::vector<int>;;
m_L1prop = L1prop;
m_CICsize = CICsize;
m_write_raw = RAW;
m_write_trg = TRIG;
bend_bit_MPA = BMPA;
bend_bit_CBC = BCBC;
m_write_out = false;
int m_tower = -1;
evtbuilder::initVars(); // Initialize everything
evtbuilder::convert(sector,m_tower); // Get the trigger tower module info
evtbuilder::initTuple(filenameRAW,filenameTRG,outfile); // Initialize ROOT stuff
evtbuilder::get_stores(npatt-conc*npatt%8,conc); // Prepare the data store where to pickup info
}
/////////////////////////////////////////////////////////
//
//
// get_stores() is the core of the event builder
//
// This method is divided into 3 steps. In the first step we build a data store by picking events
// in CMSSW samples, then we generate random sequences of events (L1 and TRIG). Finally, depending on the
// type of data requested, we produce a root file with the output and a text file with the corresponding sequence
//
/////////////////////////////////////////////////////////
void evtbuilder::get_stores(int nevts, bool conc)
{
int B_id; // The detector module IDs (defined in the header)
int layer,ladder,module,strip,chip,seg,pt;
int n_entries_TRG = L1TT->GetEntries();
int n_entries_RAW = PIX->GetEntries();
bool isPS = false;
int goodstub = -1;
float pTgen = 0.;
float d0gen = 0.;
// Then loop over events
std::vector<int> m_stub_list;
std::vector<int> m_digi_list;
m_data_trig.clear();
m_data_raw.clear();
//
// We make a first loop over all entries available
// in order to build data stores, using the digis (L1raw block)
// and the stubs (trigger block)
//
// 2 data samples are defined for that, one with m_L1prop % physics events,
// for the trigger words, and one with pure physics events, for L1 data transmission
//
// You can choose the proportion of complex events you want in the TRG block, in %
//
int mixpar = 0;
int store_size;
if (m_write_raw) store_size = n_entries_RAW;
if (m_write_trg) store_size = n_entries_TRG;
cout << "--> Entering loop 1, producing the big data stores for "
<< store_size << " events..." << endl;
//for (int j=0;j<100;++j)
for (int j=0;j<store_size;++j)
{
if (j%20==0)
cout << "Processing event " << j << "/" << store_size << endl;
m_chip_trig.clear();
m_chip_raw.clear();
if (m_write_trg)
{
if (rand()%100>m_L1prop) // Mbias event in the trigger block
{
mixpar=rand()%(n_entries_TRG-m_PHYsize);
L1TT->GetEntry(m_PHYsize+mixpar);
}
else // Phys event (stored in the s2nd half of the TRG sample)
{
mixpar=rand()%m_PHYsize;
L1TT->GetEntry(mixpar);
}
}
if (m_write_raw) PIX->GetEntry(rand()%n_entries_RAW); // For the L1 it's much more simple
// Initialize the map with dummy values for all referenced modules
//
// Please keep in mind that this map is 8 times larger in the FE output case
// Maps are quite heavy, so don't produce a lot of FE events
if (!conc)
{
for (unsigned int i=0;i<m_chips.size();++i) // All the chips if one asks the FE output
{
m_digi_list.clear();
m_digi_list.push_back(-1);
m_chip_raw.insert(std::make_pair(m_chips.at(i),m_digi_list));
m_chip_trig.insert(std::make_pair(m_chips.at(i),m_digi_list));
}
}
else
{
for (unsigned int i=0;i<m_concs.size();++i) // All the concentrators if one asks the CONC output (8 times less)
{
m_digi_list.clear();
m_digi_list.push_back(-1);
m_chip_raw.insert(std::make_pair(m_concs.at(i),m_digi_list));
m_chip_trig.insert(std::make_pair(m_concs.at(i),m_digi_list));
}
}
// First loop over the digis (raw block)
if (m_write_raw)
{
for (int i=0;i<m_pix;++i) // Loop over pixels
{
isPS = false;
layer = m_pix_layer[i];
if (layer<5) continue;
if (layer!=m_lay && m_lay!=-1) continue; // By default we loop over all layers (-1)
ladder= m_pix_ladder[i]-1;
if (layer<8 || (layer>10 && ladder<9)) isPS = true;
module= static_cast<int>((m_pix_module[i]-1)/2);
seg = m_pix_col[i];
strip = m_pix_row[i];
if (isPS && m_pix_module[i]%2==1) // Ger the chip number for the PS
{
chip = static_cast<int>(strip/127)+(seg/16)*8;
}
else // For the 2S
{
chip = static_cast<int>(strip/127)+seg*8;
}
strip = strip%128+((m_pix_module[i]-1)%2)*128;
B_id = layer*1000000 + ladder*10000 + module*100 + chip; // Finally get the module ID corresponding to the map
if (conc) B_id = B_id - chip%8; // Here we get the concentrator ID
// Look if this chip has already been touched in this event
m_iter = m_chip_raw.find(B_id);
if (m_iter == m_chip_raw.end()) // Unknown chip, this can happen because csv file is only considering chips involved in TRG
{
// continue; // We don't consider them for the moment...
m_digi_list.clear();
(conc)
? m_concs.push_back(B_id)
: m_chips.push_back(B_id);
m_digi_list.push_back(-1);
m_chip_raw.insert(std::make_pair(B_id,m_digi_list));
m_chip_trig.insert(std::make_pair(B_id,m_digi_list));
m_iter = m_chip_raw.find(B_id);
}
m_digi_list.clear();
m_digi_list = m_iter->second;
m_digi_list.push_back(chip%8);
m_digi_list.push_back(strip);
(isPS)
? m_digi_list.push_back(seg%16)
: m_digi_list.push_back(-1);
m_chip_raw.erase(m_iter->first);
m_chip_raw.insert(std::make_pair(B_id,m_digi_list));
} // End of digi collection
} // End of raw event collection
// Start the trigger store building
if (m_write_trg)
{
for (int i=0;i<m_stub;++i) // Loop over stubs
{
// First of all we compute the ID of the stub's module
isPS = false;
goodstub =-1;
layer = m_stub_layer[i];
if (layer!=m_lay && m_lay!=-1) continue;
ladder= m_stub_ladder[i];
if (layer<8 || (layer>10 && ladder<9)) isPS = true;
module= m_stub_module[i];
seg = m_stub_seg[i];
if (isPS)
{
chip = m_stub_chip[i]+(seg/16)*8;
}
else
{
chip = m_stub_chip[i]+seg*8;
}
if (isPS)
{
strip = int(2*m_stub_strip[i])%256; // Bet 0 and 255
}
else
{
strip = int(2*m_stub_strip[i])%254+1; // Code between 1 and 254 to avoid 00000000 position
}
pTgen = sqrt(m_stub_pxGEN[i]*m_stub_pxGEN[i]+m_stub_pyGEN[i]*m_stub_pyGEN[i]);
d0gen = sqrt(m_stub_X0[i]*m_stub_X0[i]+m_stub_Y0[i]*m_stub_Y0[i]);
if (pTgen>2 && d0gen<0.5) goodstub=1; // Good stubs are the ones looked at by L1 tracking
pt = static_cast<int>(abs(2*m_stub_deltas[i]));
B_id = layer*1000000 + ladder*10000 + module*100 + chip;
if (conc) B_id = B_id - chip%8; // Here we get the concentrator ID
// Look if this chip has already been touched in this event
m_iter = m_chip_trig.find(B_id);
if (m_iter == m_chip_trig.end()) // Unknown chip???
{
continue;
cout << "Wow, this should not happen, the chip ref " << B_id << " is unknown!!!" << endl;
}
else // Otherwise complement
{
m_stub_list.clear();
m_stub_list = m_iter->second;
m_stub_list.push_back(chip%8);
m_stub_list.push_back(strip);
(isPS)
? m_stub_list.push_back(seg%16)
: m_stub_list.push_back(-1);
m_stub_list.push_back(pt);
m_stub_list.push_back(goodstub);
m_chip_trig.erase(m_iter->first);
m_chip_trig.insert(std::make_pair(B_id,m_stub_list));
}
} // End of stub collection
} // End of trigger event collection
// Finally we add both collection to the stores
m_data_trig.push_back(m_chip_trig);
m_data_raw.push_back(m_chip_raw);
} // End of storage loop
// Now we have two collections one containing the raw data, and one the trigger data for all event at the concentrator level
// Trigger data is sent at every BX
// Raw data is sent every n BX, where n depends on the L1 rate
// If the L1 rate is given in kHz, we have n=40000/rate
//
// For the moment we produce it only for a concentrator chip
cout << "--> Entering loop 2, producing the random Trig/L1 sequence..." << endl;
int delta = static_cast<int>(40000/m_rate);
int n_trig = m_data_trig.size();
int n_raw = m_data_raw.size();
std::default_random_engine generator(time(NULL));
std::normal_distribution<double> L1s(delta,delta/3);
std::cout << "Average L1A period will be " << delta << " BXs with a sigma of " << delta/3 << " BXs" << std::endl;
srand(time(NULL));
int trg_evnum;
std::vector<int> trig_seq;
std::vector<int> raw_seq;
trig_seq.clear();
raw_seq.clear();
// First we create random sequence for L1 satisfying the trigger rules
// The first L1 is always sent at BX=0
raw_seq.push_back(rand()%n_raw);
int rank_r1 = 0;
int rank_r2 = 0;
int rank_r3 = 0;
int lim_r1 = 3;
int lim_r2 = 25;
int lim_r3 = 100;
bool L1_rule = true;
cout << "... Generate the sequence of " << nevts << " by picking up events in the store..." << std::endl;
while (rank_r1<nevts)
{
L1_rule = false;
// First we need to generate a space which is not enforcing the trigger rules
//
// Then check that the rules are not enforced
// L1T rules are taken from:
//
// http://www.hephy.at/project/cms/trigger/globalTrigger/trans/GT_status_dec03.pdf
//
while (!L1_rule)
{
delta = L1s(generator); // Compute a L1 space
if (delta < lim_r1) continue; // Rule 1 enforced
if ((delta+rank_r1-rank_r2) < lim_r2 && rank_r2!=0) continue; // Rule 2 enforced
if ((delta+rank_r1-rank_r3) < lim_r3 && rank_r3!=0) continue; // Rule 3 enforced
L1_rule=true;
}
// Event satisfying the trigger rules update the ranks
rank_r3 = rank_r2;
rank_r2 = rank_r1;
rank_r1 = rank_r2+delta;
for (int i=0;i<delta-1;++i)
{
raw_seq.push_back(-1);
}
raw_seq.push_back(rand()%n_raw);
}
int n_l1 = 0;
for (int i=0;i<nevts;++i)
{
trg_evnum = rand()%n_trig;
trig_seq.push_back(trg_evnum);
if (raw_seq.at(i)!=-1) ++n_l1;
}
float av_rate = 1000./((float(nevts)/float(n_l1)*0.025));
cout << "Got " << n_l1 << " L1A over " << nevts << " BXs" << endl;
cout << "This corresponds to av. L1A freq of " << av_rate << " kHz" << endl;
cout << "Sequence of L1 events is (BX,evt_ID) :" << endl;
for (unsigned int i=0;i<raw_seq.size();++i)
{
if (raw_seq.at(i)==-1) continue;
cout << "(" << i << "," << raw_seq.at(i) << "),";
}
cout << endl;
// Now we have a sequence of nevts, with L1A distributed randomly
// following the trigger rules
// Next stage consists in creating a ROOT/txt file containing this sequence
// of events, with the correspondind data for each Concentrator chip
cout << "--> Entering loop 3, producing the final root file..." << endl;
// Create the sequences, and write them on the fly
int L1_id = 0;
std::vector<int> FIFO,FIFO_new;
int last_rank;
int last_BX;
m_raw_FIFO.clear();
m_chip_FIFOs.clear();
if (conc)
{
cout << "Coding the bend over " << bend_bit_MPA
<< " bit(s) in the MPA and " << bend_bit_CBC
<< " bit(s) in the CBC in the concentrator output..." << endl;
for (unsigned int i=0;i<m_concs.size();++i)
{
m_digi_list.clear();
m_digi_list.push_back(-1);
m_raw_FIFO.insert(std::make_pair(m_concs.at(i),m_digi_list));
m_digi_list.clear();
m_digi_list.push_back(0);
m_digi_list.push_back(0);
m_chip_FIFOs.insert(std::make_pair(m_concs.at(i),m_digi_list));
}
}
else
{
for (unsigned int i=0;i<m_chips.size();++i)
{
m_digi_list.clear();
m_digi_list.push_back(-1);
m_raw_FIFO.insert(std::make_pair(m_chips.at(i),m_digi_list));
m_digi_list.clear();
m_digi_list.push_back(0);
m_digi_list.push_back(0);
m_chip_FIFOs.insert(std::make_pair(m_chips.at(i),m_digi_list));
}
}
//
// First of all one writes the L1 word, either at the FE of the concentrator level
//
//
//
if (m_write_raw)
{
for (int i=0;i<nevts;++i)
{
if (i%100==0)
cout << i << endl;
if (i%3564==0) L1_id=0; // BCR, L1ID get back to 0
evtbuilder::initVars();
if (raw_seq.at(i)!=-1) // Chip has received received a L1 A, we write the raw block
{
++L1_id;
m_chip_raw = m_data_raw.at(raw_seq.at(i)); // Pick up the event in the store
for ( m_iter = m_chip_raw.begin(); m_iter != m_chip_raw.end();++m_iter )
{
// First, look at the main info
isPS = false;
m_raw_bx = i;
m_raw_FIFO_FULL = 0;
m_raw_FIFO_SIZE = 0;
m_raw_chip = m_iter->first;
m_raw_lay = m_raw_chip/1000000;
m_raw_lad = (m_raw_chip-1000000*m_raw_lay)/10000;
m_raw_mod = (m_raw_chip-1000000*m_raw_lay-10000*m_raw_lad)/100;
m_raw_np = 0;
m_raw_ns = 0;
if (m_raw_lay<8 || (m_raw_lay>10 && m_raw_lad<9)) isPS = true;
// Now, we get the digis contained in the event, and fill the block
m_digi_list = m_iter->second;
// We have the info, we now write the word, making a difference bet. CIC and FE chip words
(conc)
? evtbuilder::fill_CONC_RAW_block(m_digi_list,isPS,L1_id)
: evtbuilder::fill_RAW_block(m_digi_list,isPS,L1_id);
// The word is written, we now emulate the FIFO behavior for the CIC
m_raw_size = m_raw_data->size();
// Concentrator FIFO size is 266*8*16 = 34048 bits
int FIFO_size = 0.;
int extracted_bit_per_BX = (m_npblock/m_CICsize);
if (!conc) extracted_bit_per_BX = 16/2;
if (conc || isPS) // It's only for the CIC and MPA chips
{
// Find the chip FIFO footprint
// defined as follows:
// < CHIP_ID, <-1,BXin(1),BXout(1),BXin(2),BXout(2),... > >
m_iter2 = m_raw_FIFO.find(m_raw_chip); // Find the chip
FIFO_new.clear();
FIFO=m_iter2->second;
FIFO_size=(FIFO.size()-1)/2; // How many L1 events are in the FIFO?
FIFO_new.push_back(-1);
if (FIFO_size==0) // Empty FIFO, initialize it!
{
FIFO_new.push_back(i); // BXin is the current BX, the L1 event enters the CIC
FIFO_new.push_back(i+m_raw_size/(extracted_bit_per_BX)+1); // BXout = BXin + numb of BXs to extract the event (if FIFO is empty it's simple)
m_raw_FIFO_FULL = (FIFO_new.size()-1)/2; // Number of events in the FIFO (1)
FIFO_size=m_raw_size;
m_raw_FIFO_SIZE=m_raw_size;
last_BX=i+m_raw_size/(extracted_bit_per_BX)+1;
}
else // FIFO not empty, one need to increment
{
last_BX=i;
for (unsigned int j=0;j<(FIFO.size()-1)/2;++j)
{
if (FIFO.at(2*j+2)<i) continue; // Time to go out for this event (BXo(j)<i)
FIFO_new.push_back(FIFO.at(2*j+1)); // Otherwise event stays there
FIFO_new.push_back(FIFO.at(2*j+2));
last_BX=FIFO.at(2*j+2); // The last BXo fixes the time where we can start to extract the next event
}
// Here we compute the size of the current FIFO
last_rank=0;
if (FIFO_new.size()>1) last_rank = (last_BX-i)*(extracted_bit_per_BX);
FIFO_size=m_raw_size+last_rank;
m_raw_FIFO_SIZE=m_raw_size+last_rank;
//if (last_rank+m_raw_size>34048) // The new event cannot fit in, we raise an error...
if (last_rank+m_raw_size>100000000) // ...or not, as here, as we want to study the FIFO divergence
{
m_raw_FIFO_FULL = -1;
}
else // OK, come in!
{
FIFO_new.push_back(i); // BXin is the current BX, the L1 event enters the CIC
FIFO_new.push_back(last_BX+m_raw_size/(extracted_bit_per_BX)+1); // BXout tells us when the event really goes out
m_raw_FIFO_FULL = (FIFO_new.size()-1)/2;
last_BX=last_BX+m_raw_size/(extracted_bit_per_BX)+1;
}
}
m_raw_FIFO.erase(m_iter2->first);
m_raw_FIFO.insert(std::make_pair(m_raw_chip,FIFO_new)); // Update the FIFO
// Then update the chip FIFO list
m_iter2 = m_chip_FIFOs.find(m_raw_chip);
FIFO=m_iter2->second;
FIFO.push_back(i);
FIFO.push_back(last_BX-i);
m_chip_FIFOs.erase(m_iter2->first);
m_chip_FIFOs.insert(std::make_pair(m_raw_chip,FIFO)); // Update the FIFO list
} // End of the FIFO emulator
m_raw_tree->Fill();
}
}
} // End of the loop on raw events
} // End of the RAW block definition
// Then write the trigger data
if (m_write_trg)
{
if (conc) // For the concentrator we work on a m_CICsize BXs basis (default is 8)
{
for (int i=0;i<nevts/m_CICsize;++i) // Loop over the number of sequences
{
if (i%100==0) cout << m_CICsize*i << endl;
m_chip_trig = m_data_trig.at(trig_seq.at(m_CICsize*i)); // Pick up the event in the store
for ( m_iter = m_chip_trig.begin(); m_iter != m_chip_trig.end();++m_iter )
{
trig_sequence.clear();
// The main info
isPS = false;
m_tri_bx = m_CICsize*i;
m_tri_nstubs = 0;
m_tri_nstubs_g = 0;
m_tri_nstubs_s = 0;
m_tri_nstubs_gs = 0;
m_tri_chip = m_iter->first;
m_tri_lay = m_tri_chip/1000000;
m_tri_lad = (m_tri_chip-1000000*m_tri_lay)/10000;
m_tri_mod = (m_tri_chip-1000000*m_tri_lay-10000*m_tri_lad)/100;
if (m_tri_lay<8 || (m_tri_lay>10 && m_tri_lad<9)) isPS = true;
// Then we get all the stubs of the corresponding chip
// in trig_sequence
trig_sequence.push_back(m_iter->second);
for (int j=1;j<m_CICsize;++j)
{
trig_sequence.push_back((m_data_trig.at(trig_seq.at(m_CICsize*i+j)).find(m_tri_chip))->second);
}
// And we write the word
if (m_write_out) std::cout << i << " / " << m_tri_bx << " / " << m_tri_chip << " -> ";
evtbuilder::fill_TRG_block(trig_sequence,isPS,conc,m_CICsize*i);
}
}
}
else // For the front end chips, we write on a 2BX basis
{
for (int i=0;i<nevts/2;++i)
{
if (i%100==0) cout << i << endl;
m_chip_trig = m_data_trig.at(trig_seq.at(2*i));
for ( m_iter = m_chip_trig.begin(); m_iter != m_chip_trig.end();++m_iter )
{
trig_sequence.clear();
isPS = false;
m_tri_bx = 2*i;
m_tri_nstubs= 0;
m_tri_nstubs_g=0;
m_tri_nstubs_s=0;
m_tri_nstubs_gs=0;
m_tri_chip = m_iter->first;
m_tri_lay = m_tri_chip/1000000;
m_tri_lad = (m_tri_chip-1000000*m_tri_lay)/10000;
m_tri_mod = (m_tri_chip-1000000*m_tri_lay-10000*m_tri_lad)/100;
trig_sequence.push_back(m_iter->second);
if (m_tri_lay<8 || (m_tri_lay>10 && m_tri_lad<9)) isPS = true;
if (isPS) // MPA case, data is sent over 2BXs
{
m_tri_nstubs= 0;
m_tri_nstubs_g=0;
m_tri_nstubs_s=0;
m_tri_nstubs_gs=0;
trig_sequence.push_back((m_data_trig.at(trig_seq.at(2*i+1)).find(m_tri_chip))->second);
std::cout << m_tri_bx << " / " << m_tri_chip << " -> ";
evtbuilder::fill_TRG_block(trig_sequence,isPS,conc,2*i);
}
else // CBC case, one BX basis
{
m_tri_nstubs= 0;
m_tri_nstubs_g=0;
m_tri_nstubs_s=0;
m_tri_nstubs_gs=0;
std::cout << m_tri_bx << " / " << m_tri_chip << " -> ";
evtbuilder::fill_TRG_block(trig_sequence,isPS,conc,2*i);
trig_sequence.clear();
m_tri_bx = 2*i+1;
m_tri_nstubs= 0;
m_tri_nstubs_g=0;
m_tri_nstubs_s=0;
m_tri_nstubs_gs=0;
trig_sequence.push_back((m_data_trig.at(trig_seq.at(2*i+1)).find(m_tri_chip))->second);
std::cout << m_tri_bx << " / " << m_tri_chip << " -> ";
evtbuilder::fill_TRG_block(trig_sequence,isPS,conc,2*i+1);
}
}
}
}
} // End of the trigger writing block
// We evaluate the drift function : BX_out-BX_in = a*BX + b
// X = a*Z + b
//
// The idea here is quite simple, we look if the time to extract
// an event from the CIC is drifting or not. If it's drifting, it means that
// the FIFO is filling up slowly, which is bad, definitely...
//
// Along with the error on these params
std::vector<int> FIFO_cnt;
double parZX[2][2];
double resZX[2];
double invZX[2][2];
double detZX = 0;
float a,b;
float da,db;
float x,z;
if (m_write_raw)
{
for ( m_iter = m_chip_FIFOs.begin(); m_iter != m_chip_FIFOs.end();++m_iter )
{
a = 0;
b = 0;
da = 0;
db = 0;
for (int i=0;i<2;++i)
{
resZX[i] = 0.;
for (int j=0;j<2;++j) parZX[i][j] = 0.;
for (int j=0;j<2;++j) invZX[i][j] = 0.;
}
detZX = 0;
m_raw_chip_bx->clear();
m_raw_chip_fifo->clear();
m_raw_chip_slope=0.;
m_raw_chip_slope_err=0.;
m_raw_chip_int=0.;
m_raw_chip_int_err=0.;
FIFO_cnt.clear();
m_raw_chip = m_iter->first;
FIFO_cnt = m_iter->second;
// Chip FIFO footprint
// defined as follows:
// < m_raw_chip , FIFO >
// FIFO.push_back(i); // BX where the L1 event enters the FIFO
// FIFO.push_back(last_BX-i); // Time spent by L1 in the FIFO
for (unsigned int j=1;j<(FIFO_cnt.size())/2;++j)
{
// cout << j << "/" << FIFO_cnt.at(2*j) << "/" << FIFO_cnt.at(2*j+1) << endl;
m_raw_chip_bx->push_back(FIFO_cnt.at(2*j));
m_raw_chip_fifo->push_back(FIFO_cnt.at(2*j+1));
x = FIFO_cnt.at(2*j+1); // BXout-BXin
z = FIFO_cnt.at(2*j); // BXin
parZX[0][0] += z*z; // S_ZZ
parZX[1][1] += 1; // S
parZX[1][0] += z; // S_Z
resZX[0] += x*z; // S_XZ
resZX[1] += x; // S_X
// cout << m_raw_chip << " / " << z << " / " << x << endl;
}
detZX = parZX[0][0]*parZX[1][1]-parZX[1][0]*parZX[1][0];
invZX[1][1] = parZX[1][1]/detZX;
invZX[1][0] = parZX[1][0]/detZX;
invZX[0][0] = parZX[0][0]/detZX;
b = invZX[0][0]*resZX[1] - invZX[1][0]*resZX[0];
a = invZX[1][1]*resZX[0] - invZX[1][0]*resZX[1];
// cout << m_raw_chip << " / Fifo_cnt = " << a << "*BX+" << b<< endl;
db = sqrt(invZX[0][0]);
da = sqrt(invZX[1][1]);
// cout <<" a = " << a << "+/-" << da << endl;
// cout <<" b = " << b << "+/-" << db << endl;
m_raw_chip_slope = a;
m_raw_chip_slope_err = da;
m_raw_chip_int = b;
m_raw_chip_int_err = db;
m_raw_summary->Fill();
}
}
m_outfile->Write();
delete L1TT;
delete PIX;
delete m_outfile;
}
/////////////////////////////////////////////////////////////
//
// Basic methods, initializations,...
//
/////////////////////////////////////////////////////////////
void evtbuilder::initVars()
{
m_tri_bx=0;
m_raw_bx=0;
m_tri_chip=0;
m_raw_chip=0;
m_tri_size=0;
m_tri_size_anders=0;
m_raw_size=0;
m_raw_mbits=0;
m_raw_np=0;
m_raw_ns=0;
m_tri_lay=0;
m_tri_lad=0;
m_tri_mod=0;
m_tri_nstubs=0;
m_tri_nstubs_s=0;
m_tri_nstubs_g=0;
m_tri_nstubs_gs=0;
m_raw_lay=0;
m_raw_lad=0;
m_raw_mod=0;
m_raw_FIFO_FULL=0;
m_tri_data->clear();
m_raw_data->clear();
m_raw_chip=0;
m_raw_chip_bx->clear();
m_raw_chip_fifo->clear();
m_raw_chip_slope=0.;
m_raw_chip_slope_err=0.;
m_raw_chip_int=0.;
m_raw_chip_int_err=0.;
}
void evtbuilder::initTuple(std::string inRAW,std::string inTRG,std::string out)
{
m_outfile = new TFile(out.c_str(),"recreate");
m_tri_tree = new TTree("Trigger_FE","L1Trigger words after FE");
m_raw_tree = new TTree("Raw_FE","Raw data words after FE");
m_raw_summary = new TTree("Raw_SUM","Raw data summary info");
m_tri_tree->Branch("TRI_BX", &m_tri_bx, "TRI_BX/I");
m_tri_tree->Branch("TRI_CHP", &m_tri_chip, "TRI_CHP/I");
m_tri_tree->Branch("TRI_LAY", &m_tri_lay, "TRI_LAY/I");
m_tri_tree->Branch("TRI_LAD", &m_tri_lad, "TRI_LAD/I");
m_tri_tree->Branch("TRI_MOD", &m_tri_mod, "TRI_MOD/I");
m_tri_tree->Branch("TRI_WORD", &m_tri_data);
m_tri_tree->Branch("TRI_SIZE", &m_tri_size, "TRI_SIZE/I");
m_tri_tree->Branch("TRI_SIZE_A", &m_tri_size_anders, "TRI_SIZE_A/I");
m_tri_tree->Branch("TRI_NSTUBS", &m_tri_nstubs);
m_tri_tree->Branch("TRI_NSTUBS_S", &m_tri_nstubs_s);
m_tri_tree->Branch("TRI_NSTUBS_G", &m_tri_nstubs_g);
m_tri_tree->Branch("TRI_NSTUBS_GS", &m_tri_nstubs_gs);
m_raw_tree->Branch("RAW_BX", &m_raw_bx, "RAW_BX/I");
m_raw_tree->Branch("RAW_CHP", &m_raw_chip, "RAW_CHP/I");
m_raw_tree->Branch("RAW_LAY", &m_raw_lay, "RAW_LAY/I");
m_raw_tree->Branch("RAW_LAD", &m_raw_lad, "RAW_LAD/I");
m_raw_tree->Branch("RAW_MOD", &m_raw_mod, "RAW_MOD/I");
m_raw_tree->Branch("RAW_WORD", &m_raw_data);
m_raw_tree->Branch("RAW_SIZE", &m_raw_size, "RAW_SIZE/I");
m_raw_tree->Branch("RAW_MBITS", &m_raw_mbits, "RAW_MBITS/I");
m_raw_tree->Branch("RAW_FIFULL", &m_raw_FIFO_FULL,"RAW_FIFULL/I");
m_raw_tree->Branch("RAW_FISIZE", &m_raw_FIFO_SIZE,"RAW_FISIZE/I");
m_raw_tree->Branch("RAW_NPCLUS", &m_raw_np);
m_raw_tree->Branch("RAW_NSCLUS", &m_raw_ns);
m_raw_summary->Branch("RAW_CHP", &m_raw_chip, "RAW_CHP/I");
m_raw_summary->Branch("RAW_CHP_BX", &m_raw_chip_bx);
m_raw_summary->Branch("RAW_CHP_FIFO", &m_raw_chip_fifo);
m_raw_summary->Branch("RAW_CHP_SLOPE", &m_raw_chip_slope);
m_raw_summary->Branch("RAW_CHP_SLOPE_ERR", &m_raw_chip_slope_err);
m_raw_summary->Branch("RAW_CHP_INT", &m_raw_chip_int);
m_raw_summary->Branch("RAW_CHP_INT_ERR", &m_raw_chip_int_err);
L1TT = new TChain("TkStubs");
PIX = new TChain("Pixels");
// Input RAW data file
if (m_write_raw)
{
std::size_t found = inRAW.find(".root");
// Case 1, it's a root file
if (found!=std::string::npos)
{
PIX->Add(inRAW.c_str());
}
else // This is a list provided into a text file
{
std::string STRING;
std::ifstream in2(inRAW.c_str());
if (!in2)
{
std::cout << "Please provide a valid RAW data filename list" << std::endl;
return;
}
while (!in2.eof())
{
getline(in2,STRING);
found = STRING.find(".root");
if (found!=std::string::npos) PIX->Add(STRING.c_str());
}
in2.close();
}
}
// Input TRG data file
if (m_write_trg)
{
std::size_t found = inRAW.find(".root");
// Case 1, it's a root file
if (found!=std::string::npos)
{
L1TT->Add(inRAW.c_str());
}
else // This is a list provided into a text file
{
std::string STRING;
std::ifstream in2(inRAW.c_str());
if (!in2)
{
std::cout << "Please provide a valid RAW data filename list" << std::endl;
return;
}
while (!in2.eof())
{
getline(in2,STRING);
found = STRING.find(".root");
if (found!=std::string::npos) L1TT->Add(STRING.c_str());
}
in2.close();
}
m_PHYsize = L1TT->GetEntries();
found = inTRG.find(".root");
// Case 1, it's a root file
if (found!=std::string::npos)
{
L1TT->Add(inTRG.c_str());
}
else // This is a list provided into a text file
{
std::string STRING;
std::ifstream in2(inTRG.c_str());
if (!in2)
{
std::cout << "Please provide a valid TRG data filename list" << std::endl;
return;
}
while (!in2.eof())
{
getline(in2,STRING);
found = STRING.find(".root");
if (found!=std::string::npos) L1TT->Add(STRING.c_str());
}
in2.close();
}
}
if (m_write_raw)
{
pm_pix_layer=&m_pix_layer;
pm_pix_ladder=&m_pix_ladder;
pm_pix_module=&m_pix_module;
pm_pix_row=&m_pix_row;
pm_pix_col=&m_pix_col;
PIX->SetBranchAddress("PIX_n", &m_pix);
PIX->SetBranchAddress("PIX_nPU", &m_npu);
PIX->SetBranchAddress("PIX_layer", &pm_pix_layer);
PIX->SetBranchAddress("PIX_ladder", &pm_pix_ladder);
PIX->SetBranchAddress("PIX_module", &pm_pix_module);
PIX->SetBranchAddress("PIX_row", &pm_pix_row);
PIX->SetBranchAddress("PIX_column", &pm_pix_col);
}
if (m_write_trg)
{
pm_stub_layer=&m_stub_layer;
pm_stub_ladder=&m_stub_ladder;
pm_stub_module=&m_stub_module;
pm_stub_pt=&m_stub_pt;
pm_stub_deltas=&m_stub_deltas;
pm_stub_strip=&m_stub_strip;
pm_stub_seg=&m_stub_seg;
pm_stub_chip=&m_stub_chip;
pm_stub_X0=&m_stub_X0;
pm_stub_Y0=&m_stub_Y0;
pm_stub_pxGEN=&m_stub_pxGEN;
pm_stub_pyGEN=&m_stub_pyGEN;
L1TT->SetBranchAddress("L1TkSTUB_n", &m_stub);
L1TT->SetBranchAddress("L1TkSTUB_layer", &pm_stub_layer);
L1TT->SetBranchAddress("L1TkSTUB_ladder", &pm_stub_ladder);
L1TT->SetBranchAddress("L1TkSTUB_module", &pm_stub_module);
L1TT->SetBranchAddress("L1TkSTUB_pt", &pm_stub_pt);
L1TT->SetBranchAddress("L1TkSTUB_deltas", &pm_stub_deltas);
L1TT->SetBranchAddress("L1TkSTUB_strip", &pm_stub_strip);
L1TT->SetBranchAddress("L1TkSTUB_seg", &pm_stub_seg);
L1TT->SetBranchAddress("L1TkSTUB_chip", &pm_stub_chip);
L1TT->SetBranchAddress("L1TkSTUB_pxGEN", &pm_stub_pxGEN);
L1TT->SetBranchAddress("L1TkSTUB_pyGEN", &pm_stub_pyGEN);
L1TT->SetBranchAddress("L1TkSTUB_X0", &pm_stub_X0);
L1TT->SetBranchAddress("L1TkSTUB_Y0", &pm_stub_Y0);
}
}
/////////////////////////////////////////////////////////////////////////////////
//
// ==> convert(std::string sectorfilename)
//
// Here we retrieve info from the TKLayout CSV file containing the sector definition
//
// This file contains, for each sector, the ids of the modules and chips contained in the sector sec_num
//
// The role of this method is to create the opposite, ie a vector containing, for every module the list of sectors belonging to it
//
/////////////////////////////////////////////////////////////////////////////////
bool evtbuilder::convert(std::string sectorfilename, int sec_num)
{
std::vector<int> module;
std::cout << "Convert in" << std::endl;
m_modules.clear();
m_chips.clear();
m_concs.clear();
for (int i=0;i<230000;++i)
{
module.clear();
module.push_back(-1);
m_modules.push_back(module);
}
std::string STRING;
std::ifstream in(sectorfilename.c_str());
if (!in)
{
std::cout << "Please provide a valid csv sector filename" << std::endl;
return false;
}
int m_sec_mult = 0;
int npar = 0;
while (!in.eof())
{
++m_sec_mult;
getline(in,STRING);
if (m_sec_mult<2) continue;
if (m_sec_mult-2!=sec_num && sec_num!=-1) continue;
std::istringstream ss(STRING);
npar = 0;
while (ss)
{
std::string s;
if (!getline( ss, s, ',' )) break;
++npar;
if (npar<=2) continue;
if (int(atoi(s.c_str())/10000)!=m_lay && m_lay!=-1) continue;
m_modules.at(atoi(s.c_str())).push_back(m_sec_mult-2);
}
}
in.close();
std::cout << "Convert out" << std::endl;
for (int i=0;i<230000;++i)
{
if (m_modules.at(i).size()<=1) continue;
for (int j=0;j<16;++j) m_chips.push_back(100*i+j);
m_concs.push_back(100*i);
m_concs.push_back(100*i+8);
}
return true;
}
//
// List of method writing the data blocks, according to the format defined in
// the following document:
//
// https://espace.cern.ch/Tracker-Upgrade/Electronics/CIC/Shared%20Documents/Data%20formats/CIC_IO_Formats_v2.pdf
//
//
// 1: L1 raw block at the MPA/CBC level
//
void evtbuilder::fill_RAW_block(std::vector<int> digis,bool spars,int BXid)
{
m_raw_data->clear();
// First write the headers
(spars)
? evtbuilder::fill_RAW_header_MPA(BXid)
: evtbuilder::fill_RAW_header_CBC(BXid);
// Then go for the data
int ndata=(digis.size()-1)/3; // Default first item is -1
int hsize=m_raw_data->size();
if (!spars) // CBC (unsparsified), slide 9 of the presentation cited
{
for (int j=0;j<256;++j) m_raw_data->push_back(0);
for (int j=0;j<ndata;++j)
{
m_raw_data->at(digis.at(3*j+2)+hsize) = 1;
}
}
else // MPA
{
int data_MPA[128][17];
int row,col;
// The sparsification is done at the MPA level
// Strips 0 to 120 belong to the pixel layer
// 121 to 239 belong to the strip layer
for (int j=0;j<128;++j)
{
for (int i=0;i<17;++i) data_MPA[j][i] = 0;
}
for (int j=0;j<ndata;++j)
{
row = digis.at(3*j+2);
col = digis.at(3*j+3);
(row<120)
? data_MPA[row][col] = 1
: data_MPA[row%120][16] = 1;
}
int np = 0;
int ns = 0;
int compt=0;
int start_r = -1;
std::vector<int> clus_p;
std::vector<int> clus_s;
clus_p.clear();
clus_s.clear();
for (int j=0;j<17;++j)
{
start_r = -1;
compt = 0;
// cout << j << " / " << clus_p.size()/3 << " / " << clus_s.size()/2 << endl;
for (int i=0;i<128;++i)
{
if (data_MPA[i][j] == 1)
{
if (start_r==-1) // new clus
{
start_r=i+1; // 0000000 forbiden
compt=0;
}
else
{
++compt;
if (compt==7) // Max width reached
{
if (j<16)
{
clus_p.push_back(start_r);
clus_p.push_back(j);
clus_p.push_back(compt);
}
else
{
clus_s.push_back(start_r);
clus_s.push_back(compt);
}
start_r=-1;
compt=0;
}
}
}
else
{
if (start_r!=-1)
{
if (j<16)
{
clus_p.push_back(start_r);
clus_p.push_back(j);
clus_p.push_back(compt);
}
else
{
clus_s.push_back(start_r);
clus_s.push_back(compt);
}
start_r=-1;
compt=0;
}
}
}
if (start_r!=-1) // Just handle the case where rows ends up with 1
{
if (j<16)
{
clus_p.push_back(start_r);
clus_p.push_back(j);
clus_p.push_back(compt);
}
else
{
clus_s.push_back(start_r);
clus_s.push_back(compt);
}
}
}
// Now encode them
np = clus_p.size()/3 ;
ns = clus_s.size()/2;
m_raw_np = np;
m_raw_ns = ns;
np = std::min(31,np); // One cannot pass more than
ns = std::min(31,ns); // 31 clusters out of the MPA
std::bitset<5> N_S = ns;
std::bitset<5> N_P = np;
for (int j=0;j<5;++j) m_raw_data->push_back(N_S[4-j]);
for (int j=0;j<5;++j) m_raw_data->push_back(N_P[4-j]);
m_raw_data->push_back(0);
for (int j=0;j<ns;++j)
{
std::bitset<7> row = clus_s.at(2*j);
std::bitset<3> wdt = clus_s.at(2*j+1);
for (int k=0;k<7;++k) m_raw_data->push_back(row[6-k]);
for (int k=0;k<3;++k) m_raw_data->push_back(wdt[2-k]);
}
for (int j=0;j<np;++j)
{
std::bitset<7> row = clus_p.at(3*j);
std::bitset<4> col = clus_p.at(3*j+1);
std::bitset<3> wdt = clus_p.at(3*j+2);
for (int k=0;k<7;++k) m_raw_data->push_back(row[6-k]);
for (int k=0;k<3;++k) m_raw_data->push_back(wdt[2-k]);
for (int k=0;k<4;++k) m_raw_data->push_back(col[3-k]);
}
m_raw_data->push_back(0); // Trailer
}
// Here we put a common trailer (if needed)
// std::cout << "Size of the L1 raw word / " << spars << " / " << m_raw_data->size() << std::endl;
// for (int j=0;j<m_raw_data->size();++j)
// {
// std::cout << m_raw_data->at(j);
// }
// std::cout << std::endl;
// Here we just count the maximum number of consecutive bits at 1
int max_bits = 0;
int nbits = 0;
for (unsigned int j=hsize;j<m_raw_data->size();++j)
{
if (m_raw_data->at(j)==1) ++nbits;
if (m_raw_data->at(j)==0) nbits=0;
if (nbits>=max_bits) max_bits=nbits;
}
m_raw_mbits = max_bits;
}
//
// 2: L1 raw block at the concentrator level
//
void evtbuilder::fill_CONC_RAW_block(std::vector<int> digis,bool spars,int BXid)
{
m_raw_data->clear();
// First write the header
evtbuilder::fill_CONC_RAW_header(BXid);
// Then go for the data
int np,ns;
int ndata=(digis.size()-1)/3; // Default first item is -1
int hsize=m_raw_data->size();
// %%%%%%%%%%%%%%%%
// !! Still to clarify (SV 26/08/14), number of bits in the CBC word (252 or 256)
// %%%%%%%%%%%%%%%%
if (!spars) // CBC case
{
int data_CBC[8][256];
int row,chip;
for (int j=0;j<256;++j)
{
for (int i=0;i<8;++i) data_CBC[i][j] = 0;
}
for (int j=0;j<ndata;++j)
{
chip = digis.at(3*j+1);
row = digis.at(3*j+2);
// std::cout << row << "," << chip << " / ";
data_CBC[chip][row] = 1;
}
// if (ndata!=0) std::cout << std::endl;
ns = 0;
int compt = 0;
int start_r = -1;
std::vector<int> clus_s;
clus_s.clear();
for (int j=0;j<8;++j)
{
start_r = -1;
compt = 0;
// cout << j << " / " << clus_s.size()/3 << endl;
for (int i=0;i<256;++i)
{
if (data_CBC[j][i] == 1)
{
if (start_r==-1) // new clus
{
start_r=i+1;
compt=0;
}
else
{
++compt;
if (compt==7) // Max width reached
{
clus_s.push_back(start_r);
clus_s.push_back(compt);
clus_s.push_back(j);
start_r=-1;
compt=0;
}
}
}
else
{
if (start_r!=-1)
{
clus_s.push_back(start_r);
clus_s.push_back(compt);
clus_s.push_back(j);
start_r=-1;
compt=0;
}
}
}
if (start_r!=-1) // Just handle the case where rows ends up with 1
{
clus_s.push_back(start_r);
clus_s.push_back(compt);
clus_s.push_back(j);
}
}
// std::cout << "This CBC conc chip contains " << clus_s.size()/3 << " strip clusters" << std::endl;
// Now encode them
ns = clus_s.size()/3;
m_raw_ns = ns;
ns = std::min(31,ns);
std::bitset<5> N_S = ns;
for (int j=0;j<5;++j) m_raw_data->push_back(N_S[4-j]);
for (int j=0;j<ns;++j)
{
std::bitset<3> chp = clus_s.at(3*j+2);
std::bitset<8> row = clus_s.at(3*j);
std::bitset<3> wdt = clus_s.at(3*j+1);
for (int k=0;k<3;++k) m_raw_data->push_back(chp[2-k]);
for (int k=0;k<8;++k) m_raw_data->push_back(row[7-k]);
for (int k=0;k<3;++k) m_raw_data->push_back(wdt[2-k]);
}
}
else // MPA case
{
int data_MPA[8][128][17];
int row,col,chip;
// The sparsification is done at the MPA level
// Strips 0 to 120 belong to the pixel layer
// 120 to 239 belong to the strip layer
for (int k=0;k<8;++k)
{
for (int j=0;j<128;++j)
{
for (int i=0;i<17;++i) data_MPA[k][j][i] = 0;
}
}
for (int j=0;j<ndata;++j)
{
chip = digis.at(3*j+1);
row = digis.at(3*j+2);
col = digis.at(3*j+3);
// std::cout << chip << "," << row << "," << col << " / ";
(row<120)
? data_MPA[chip][row][col] = 1
: data_MPA[chip][row%120][16] = 1;
}
// if (ndata!=0) std::cout << std::endl;
np = 0;
ns = 0;
int compt=0;
int start_r = -1;
std::vector<int> clus_p;
std::vector<int> clus_s;
clus_p.clear();
clus_s.clear();
for (int k=0;k<8;++k)
{
for (int j=0;j<17;++j)
{
start_r = -1;
compt = 0;
// cout << j << " / " << clus_p.size()/3 << " / " << clus_s.size()/2 << endl;
for (int i=0;i<128;++i)
{
if (data_MPA[k][i][j] == 1)
{
if (start_r==-1) // new clus
{
start_r=i+1;
compt=0;
}
else
{
++compt;
if (compt==7) // Max width reached
{
if (j<16)
{
clus_p.push_back(start_r);
clus_p.push_back(j);
clus_p.push_back(compt);
clus_p.push_back(k);
}
else
{
clus_s.push_back(start_r);
clus_s.push_back(compt);
clus_s.push_back(k);
}
start_r=-1;
compt=0;
}
}
}
else
{
if (start_r!=-1)
{
if (j<16)
{
clus_p.push_back(start_r);
clus_p.push_back(j);
clus_p.push_back(compt);
clus_p.push_back(k);
}
else
{
clus_s.push_back(start_r);
clus_s.push_back(compt);
clus_s.push_back(k);
}
start_r=-1;
compt=0;
}
}
}
if (start_r!=-1) // Just handle the case where rows ends up with 1
{
if (j<16)
{
clus_p.push_back(start_r);
clus_p.push_back(j);
clus_p.push_back(compt);
clus_p.push_back(k);
}
else
{
clus_s.push_back(start_r);
clus_s.push_back(compt);
clus_s.push_back(k);
}
}
}
}
// std::cout << "This MPA chip contains " << clus_p.size()/4 << " pixels clusters and "
// << clus_s.size()/3 << " strip clusters" << std::endl;
// Now encode them
np = clus_p.size()/4 ;
ns = clus_s.size()/3;
m_raw_np = np;
m_raw_ns = ns;
np = std::min(63,np);
ns = std::min(63,ns);
std::bitset<6> N_S = ns;
std::bitset<6> N_P = np;
// std::cout << "This MPA chip contains
for (int j=0;j<6;++j) m_raw_data->push_back(N_S[5-j]);
for (int j=0;j<6;++j) m_raw_data->push_back(N_P[5-j]);
for (int j=0;j<ns;++j)
{
std::bitset<7> row = clus_s.at(3*j);
std::bitset<3> wdt = clus_s.at(3*j+1);
std::bitset<3> chp = clus_s.at(3*j+2);
for (int k=0;k<3;++k) m_raw_data->push_back(chp[2-k]);
for (int k=0;k<7;++k) m_raw_data->push_back(row[6-k]);
for (int k=0;k<3;++k) m_raw_data->push_back(wdt[2-k]);
}
for (int j=0;j<np;++j)
{
std::bitset<7> row = clus_p.at(4*j);
std::bitset<4> col = clus_p.at(4*j+1);
std::bitset<3> wdt = clus_p.at(4*j+2);
std::bitset<3> chp = clus_p.at(4*j+3);
for (int k=0;k<3;++k) m_raw_data->push_back(chp[2-k]);
for (int k=0;k<7;++k) m_raw_data->push_back(row[6-k]);
for (int k=0;k<3;++k) m_raw_data->push_back(wdt[2-k]);
for (int k=0;k<4;++k) m_raw_data->push_back(col[3-k]);
}
}
// Here we put a common trailer
m_raw_data->push_back(0);
int max_bits = 0;
int nbits = 0;
for (unsigned int j=hsize;j<m_raw_data->size();++j)
{
if (m_raw_data->at(j)==1) ++nbits;
if (m_raw_data->at(j)==0) nbits=0;
if (nbits>=max_bits) max_bits=nbits;
}
m_raw_mbits = max_bits;
if (m_raw_mbits>17)
{
std::cout << "This chip contains " << np << " pixels clusters and "
<< ns << " strip clusters" << std::endl;
std::cout << "Size of the L1 raw word / " << spars << " / " << m_raw_data->size() << std::endl;
for (unsigned int j=0;j<m_raw_data->size();++j)
{
std::cout << m_raw_data->at(j);
}
std::cout << std::endl;
}
}
//
// 3: Trigger block
//
void evtbuilder::fill_TRG_block(std::vector< std::vector<int> > stubs, bool spars, bool conc, int BXid)
{
m_tri_data->clear();
// Then go for the data
int nstubs[8]; // Number of stubs stored in each chip
int seqsize = static_cast<int>(stubs.size());
int lim_CBC=3; // Max number of stubs passed by the CBC is 3/BX
int lim_MPA=4; // Max number of stubs passed by the MPA is 4/2BXs
if (bend_bit_MPA<4) lim_MPA=5;
int gstub;
m_tri_nstubs = 0;
m_tri_nstubs_s = 0;
m_tri_nstubs_g = 0;
m_tri_nstubs_gs = 0;
std::vector<int> stublist;
if (conc)
{
(spars)
? evtbuilder::fill_CONC_TRG_header(BXid%3564,1)
: evtbuilder::fill_CONC_TRG_header(BXid%3564,0);
}
if (!conc) // Put a specific header for FE words
{
m_tri_data->push_back(1); // Always start with synchro bit 1
if (spars) // For the PS one puts the number of stubs in the first BX
{ // will be completed at the end
for (int j=0;j<3;++j) m_tri_data->push_back(0);
}
}
//std::cout << "Writing trigger block for " << seqsize << " BXs" << std::endl;
//
// (conc)
// ? std::cout << "Concentrator" << std::endl
// : std::cout << "FE" << std::endl;
int bit_bx = 3; // Number of bits necessary to precise the offset number in the CIC word
if (m_CICsize>8) bit_bx=4;
std::vector<int> sequence;
sequence.clear();
for (int i=0;i<seqsize;++i) // Loop over the block of events
{
sequence.push_back(0);
}
for (int i=0;i<seqsize;++i) // Loop over the block of events
{
std::bitset<4> bx = i;
stublist = stubs.at(i); // Get the stubs for event i
// Here we initialize the stub per chip counters
if (spars && i%2==0) // For the MPA, it's every 2BXs
{
for (int j=0;j<8;++j) nstubs[j]=0;
}
if (spars && i%2==1 && !conc) // Here we have the number of stubs in the first BX for the MPA
{
std::bitset<3> cnt= m_tri_nstubs_s;
for (int j=0;j<3;++j) m_tri_data->at(j+1)=cnt[2-j];
}
if (!spars) // For the CBC, it's every BX
{
for (int j=0;j<8;++j) nstubs[j]=0;
}
//std::cout << i << "/" << nstubs << "/" << bend_bit_MPA << "/" << bend_bit_CBC << "/" ;
// Then loop over the stubs contained in the event
for (unsigned int kk=0;kk<(stublist.size()-1)/5;++kk)
{
gstub=stublist.at(5*kk+5); // Is the stub interesting or not
++m_tri_nstubs;
if (gstub>0) ++m_tri_nstubs_g;
// Here we apply the chip limits
if (nstubs[stublist.at(5*kk+1)]>=lim_CBC && !spars) continue; // No CHIP sorting for the moment
if (nstubs[stublist.at(5*kk+1)]>=lim_MPA && spars) continue; // No CHIP sorting for the moment
++nstubs[stublist.at(5*kk+1)];
++m_tri_nstubs_s;
if (gstub>0) ++m_tri_nstubs_gs;
++sequence.at(i);
std::bitset<3> chp = stublist.at(5*kk+1); // Chip number
std::bitset<8> pos = stublist.at(5*kk+2); // Stub position
std::bitset<4> col = stublist.at(5*kk+3); // Z position (for PS module)
std::bitset<5> off = abs(2*stublist.at(5*kk+4)); // Bend
//std::cout << stublist.at(4*kk+1)<< ","
// << stublist.at(4*kk+2)<< ","
// << stublist.at(4*kk+3) << ","
// << stublist.at(4*kk+4) << "/" ;
// For the CIC, start with the offset and chip number
if (conc)
{
for (int j=0;j<3;++j) m_tri_data->push_back(bx[bit_bx-1-j]);
for (int j=0;j<3;++j) m_tri_data->push_back(chp[2-j]);
}
// Then the position
for (int j=0;j<8;++j)
{
if (!conc && m_tri_data->size()==40 && spars) m_tri_data->push_back(0); // Second synchro bit
m_tri_data->push_back(pos[7-j]);
}
// The column for MPA side
if (spars) for (int j=0;j<4;++j)
{
if (!conc && m_tri_data->size()==40 && spars) m_tri_data->push_back(0); // Second synchro bit
m_tri_data->push_back(col[3-j]);
}
// Finally the bend
if (conc)
{
if (spars)
{
for (int j=0;j<bend_bit_MPA;++j) m_tri_data->push_back(off[4-j]);
}
else
{
for (int j=0;j<bend_bit_CBC;++j) m_tri_data->push_back(off[4-j]);
}
}
else
{
for (int j=0;j<5;++j)
{
if (!conc && m_tri_data->size()==40 && spars) m_tri_data->push_back(0); // Second synchro bit
m_tri_data->push_back(off[4-j]);
}
}
}
}
// std::cout << std::endl;
// Potentially put a trailer here, only for the FE chips
if (!conc)
{
if (!spars)
{
for (int j=m_tri_data->size();j<40;++j) m_tri_data->push_back(0);
}
else
{
for (int j=m_tri_data->size();j<80;++j) m_tri_data->push_back(0);
}
}
int nzeros=0;
for (int i=0;i<seqsize;++i) // Loop over the block of events
{
if (sequence.at(i)==0) ++nzeros;
}
if (conc)
{
if (m_tri_nstubs_s>15)
{
m_tri_data->at(9) = 1; // Raise the CIC error bit if the number of stubs is in overflow
for (int j=0;j<4;++j) m_tri_data->at(22+j) = 1;
}
else
{
std::bitset<4> nst = m_tri_nstubs_s;
for (int j=0;j<4;++j) m_tri_data->at(22+j) = nst[3-j];
}
}
m_tri_size=m_tri_data->size();
m_tri_size_anders=m_tri_data->size()-2*m_tri_nstubs_s+nzeros;
m_tri_tree->Fill();
// std::cout << "Size of the trigger word / " << spars << " / " << conc << " / " << m_tri_size << std::endl;
if (m_write_out)
{
for (unsigned int j=0;j<m_tri_data->size();++j)
{
std::cout << m_tri_data->at(j);
}
std::cout << std::endl;
}
}
void evtbuilder::fill_RAW_header_CBC(int L1id)
{
// Format of the CBC L1 word header
//
// HHEEPPPPPPPPPLLLLLLLLL : HHEE (header + error) LL..LL (L1 ID bet 0 and 512)
// PP..PP CBC pipeline address
for (int j=0;j<4;++j) m_raw_data->push_back(1); // HHEE
if (L1id>512)
{
std::cout << "Too many L1ids, problem!!!" << std::endl;
}
std::bitset<9> L1_ID = L1id;
for (int j=0;j<9;++j) m_raw_data->push_back(L1_ID[8-j]); // PP..PP
for (int j=0;j<9;++j) m_raw_data->push_back(L1_ID[8-j]); // CC..CC
}
void evtbuilder::fill_RAW_header_MPA(int L1id)
{
// Format of the CBC L1 word header
//
// 1111111111111111110EECCCCCCCCC0 : EE (error) CC..CC (L1 ID bet 0 and 512)
//
for (int j=0;j<18;++j) m_raw_data->push_back(1);
m_raw_data->push_back(0);
m_raw_data->push_back(1);
m_raw_data->push_back(1);
if (L1id>512)
{
std::cout << "Too many L1ids, problem!!!" << std::endl;
}
std::bitset<9> L1_ID = L1id;
for (int j=0;j<9;++j) m_raw_data->push_back(L1_ID[8-j]); // CC..CC
m_raw_data->push_back(0);
}
void evtbuilder::fill_CONC_RAW_header(int L1id)
{
// Format of the CONC L1 word header
//
// 1111111111111110EEEEEEEEECCCCCCCCC : E..E (error) CC..CC (L1 ID bet 0 and 512)
//
for (int j=0;j<15;++j) m_raw_data->push_back(1);
m_raw_data->push_back(0);
for (int j=0;j<9;++j) m_raw_data->push_back(0);
if (L1id>512)
{
std::cout << "Too many L1ids, problem!!!" << std::endl;
}
std::bitset<9> L1_ID = L1id;
for (int j=0;j<9;++j) m_raw_data->push_back(L1_ID[8-j]); // CC..CC
m_raw_data->push_back(0);
}
void evtbuilder::fill_CONC_TRG_header(int BXid,int MPA)
{
// Format of the CONC TRIGGER word header
//
// CSSSSSSSSSCCCCCCCCCCCC : SS..SS (status) CC..CC (BX ID bet 0 and 3564)
//
m_tri_data->push_back(MPA);
for (int j=0;j<9;++j) m_tri_data->push_back(0); // Status bits
std::bitset<12> BX_ID = BXid;
for (int j=0;j<12;++j) m_tri_data->push_back(BX_ID[11-j]); // CC..CC
for (int j=0;j<4;++j) m_tri_data->push_back(0); // Let room for the number of stubs
}
|
879acc71d6186a678baaf629d9c0eabcb1f78890 | 3cd2e95528a5b02fd308c2eca1b82a1deff3d6f0 | /Project/SmartLed_IoT.ino | 739299b66bf8d962c42f0c60547a78c51be04453 | [] | no_license | VitorCV/Projeto_SmartLamp | 38b017cebf12bb4e036d8dbef83071ae754a617b | d78efffffa4e376601a3b7aafe0248e545d9fa47 | refs/heads/master | 2020-03-18T14:26:55.280697 | 2018-06-05T11:11:08 | 2018-06-05T11:11:08 | 134,848,602 | 0 | 0 | null | 2018-05-25T11:41:27 | 2018-05-25T11:41:27 | null | UTF-8 | C++ | false | false | 1,780 | ino | SmartLed_IoT.ino | /*************************************************************
Download desse projeto no GitHub
https://github.com/gabrielkenji12/Projeto_SmartLamp
Biblioteca utilizada BLynk- IFTTT
Blynk is a platform with iOS and Android apps to control
Arduino, Raspberry Pi and the likes over the Internet.
You can easily build graphic interfaces for all your
projects by simply dragging and dropping widgets.
Downloads, docs, tutorials: http://www.blynk.cc
Sketch generator: http://examples.blynk.cc
Blynk community: http://community.blynk.cc
Follow us: http://www.fb.com/blynkapp
http://twitter.com/blynk_app
Blynk library is licensed under MIT license
This example code is in public domain.
*/
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
//Define o LDR
const int LDRPin = A0;
//define o pino do LED
#define ledPin D1
//define a variavel para do LDR
int sensorValue = 0;
//define um contador
int count=0;
// Utilize Api Key gerada pelo blynk.
char auth[] = "54fdc59952b541b286382a20289fd95a";
// Insira seu Wifi.
char ssid[] = "iPhone";
// Coloque a senha do Wifi
char pass[] = "nawf1997";
void setup()
{
// Debugg do console
//debugging serial communcation
Serial.begin(9600);
pinMode( ledPin, OUTPUT );
Blynk.begin(auth, ssid, pass);
}
void loop(){
Blynk.run();
//Ler o valor do LDR
sensorValue=analogRead(A0);
// Valor do LDR para o Monitor
Serial.println(sensorValue);
Blynk.virtualWrite(ledPin,HIGH);
if(sensorValue<100){
if(count==0){
Blynk.notify("Está escuro");
count = 1;
}
} else {
count = 0;
}
}
|
e717a2cb1a73c1a5754372faaf8cdf7784433b11 | ca977582e0d7818c4aeec001c57f0041f8f0c2ff | /SpaceInvaders/Bullet.h | c14f250c53cfd5329952e12c099e22fd6eee31ca | [] | no_license | vzhang97/INFO3220-Assignments | 96b3e446aea99d9dd6909ea156d824a4d83895e0 | 081f93efbb8e99892009b99e42a15a7fc966d5a1 | refs/heads/master | 2021-06-14T10:15:31.774969 | 2017-04-08T03:45:39 | 2017-04-08T03:45:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | h | Bullet.h | #ifndef BULLET_H
#define BULLET_H
#include <QPixmap>
#include <iostream>
namespace si {
/*
* Superclass for Bullets.
* Subclasses will inherit from it and be specific type of bullet
*
*/
class Bullet : public QPixmap
{
public:
Bullet(int x, int y); //X and Y Coordinate for the bullet
virtual ~Bullet();
virtual void shoot() = 0; //Abstract Method
protected:
int bulletX; //X coordinate of Bullet
int bulletY; //Y coordinate of Bullet
int bulletSpeed; //Speed of Bullet
int bulletHeight; //Height of Bullet
int bulletWidth; //Width of Bullet
};
}
#endif // BULLET_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.